Allow "" to be a match in property searches for empty and undefined value.
[org-mode.git] / org.el
blobbdd8b2ef91265b93422d93c33e4574133cbc7d4c
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 is added to `org-stored-links' and can later be inserted
11899 into an org-buffer with \\[org-insert-link].
11901 For some link types, a prefix arg is interpreted:
11902 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11903 For file links, arg negates `org-context-in-file-links'."
11904 (interactive "P")
11905 (setq org-store-link-plist nil) ; reset
11906 (let (link cpltxt desc description search txt)
11907 (cond
11909 ((run-hook-with-args-until-success 'org-store-link-functions)
11910 (setq link (plist-get org-store-link-plist :link)
11911 desc (or (plist-get org-store-link-plist :description) link)))
11913 ((eq major-mode 'bbdb-mode)
11914 (let ((name (bbdb-record-name (bbdb-current-record)))
11915 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11916 (setq cpltxt (concat "bbdb:" (or name company))
11917 link (org-make-link cpltxt))
11918 (org-store-link-props :type "bbdb" :name name :company company)))
11920 ((eq major-mode 'Info-mode)
11921 (setq link (org-make-link "info:"
11922 (file-name-nondirectory Info-current-file)
11923 ":" Info-current-node))
11924 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11925 ":" Info-current-node))
11926 (org-store-link-props :type "info" :file Info-current-file
11927 :node Info-current-node))
11929 ((eq major-mode 'calendar-mode)
11930 (let ((cd (calendar-cursor-to-date)))
11931 (setq link
11932 (format-time-string
11933 (car org-time-stamp-formats)
11934 (apply 'encode-time
11935 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11936 nil nil nil))))
11937 (org-store-link-props :type "calendar" :date cd)))
11939 ((or (eq major-mode 'vm-summary-mode)
11940 (eq major-mode 'vm-presentation-mode))
11941 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11942 (vm-follow-summary-cursor)
11943 (save-excursion
11944 (vm-select-folder-buffer)
11945 (let* ((message (car vm-message-pointer))
11946 (folder buffer-file-name)
11947 (subject (vm-su-subject message))
11948 (to (vm-get-header-contents message "To"))
11949 (from (vm-get-header-contents message "From"))
11950 (message-id (vm-su-message-id message)))
11951 (org-store-link-props :type "vm" :from from :to to :subject subject
11952 :message-id message-id)
11953 (setq message-id (org-remove-angle-brackets message-id))
11954 (setq folder (abbreviate-file-name folder))
11955 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11956 folder)
11957 (setq folder (replace-match "" t t folder)))
11958 (setq cpltxt (org-email-link-description))
11959 (setq link (org-make-link "vm:" folder "#" message-id)))))
11961 ((eq major-mode 'wl-summary-mode)
11962 (let* ((msgnum (wl-summary-message-number))
11963 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11964 msgnum 'message-id))
11965 (wl-message-entity
11966 (if (fboundp 'elmo-message-entity)
11967 (elmo-message-entity
11968 wl-summary-buffer-elmo-folder msgnum)
11969 (elmo-msgdb-overview-get-entity
11970 msgnum (wl-summary-buffer-msgdb))))
11971 (from (wl-summary-line-from))
11972 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11973 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11974 (wl-summary-line-subject))))
11975 (org-store-link-props :type "wl" :from from :to to
11976 :subject subject :message-id message-id)
11977 (setq message-id (org-remove-angle-brackets message-id))
11978 (setq cpltxt (org-email-link-description))
11979 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11980 "#" message-id))))
11982 ((or (equal major-mode 'mh-folder-mode)
11983 (equal major-mode 'mh-show-mode))
11984 (let ((from (org-mhe-get-header "From:"))
11985 (to (org-mhe-get-header "To:"))
11986 (message-id (org-mhe-get-header "Message-Id:"))
11987 (subject (org-mhe-get-header "Subject:")))
11988 (org-store-link-props :type "mh" :from from :to to
11989 :subject subject :message-id message-id)
11990 (setq cpltxt (org-email-link-description))
11991 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11992 (org-remove-angle-brackets message-id)))))
11994 ((or (eq major-mode 'rmail-mode)
11995 (eq major-mode 'rmail-summary-mode))
11996 (save-window-excursion
11997 (save-restriction
11998 (when (eq major-mode 'rmail-summary-mode)
11999 (rmail-show-message rmail-current-message))
12000 (rmail-narrow-to-non-pruned-header)
12001 (let ((folder buffer-file-name)
12002 (message-id (mail-fetch-field "message-id"))
12003 (from (mail-fetch-field "from"))
12004 (to (mail-fetch-field "to"))
12005 (subject (mail-fetch-field "subject")))
12006 (org-store-link-props
12007 :type "rmail" :from from :to to
12008 :subject subject :message-id message-id)
12009 (setq message-id (org-remove-angle-brackets message-id))
12010 (setq cpltxt (org-email-link-description))
12011 (setq link (org-make-link "rmail:" folder "#" message-id)))
12012 (rmail-show-message rmail-current-message))))
12014 ((eq major-mode 'gnus-group-mode)
12015 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12016 (gnus-group-group-name)) ; version
12017 ((fboundp 'gnus-group-name)
12018 (gnus-group-name))
12019 (t "???"))))
12020 (unless group (error "Not on a group"))
12021 (org-store-link-props :type "gnus" :group group)
12022 (setq cpltxt (concat
12023 (if (org-xor arg org-usenet-links-prefer-google)
12024 "http://groups.google.com/groups?group="
12025 "gnus:")
12026 group)
12027 link (org-make-link cpltxt))))
12029 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12030 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12031 (let* ((group gnus-newsgroup-name)
12032 (article (gnus-summary-article-number))
12033 (header (gnus-summary-article-header article))
12034 (from (mail-header-from header))
12035 (message-id (mail-header-id header))
12036 (date (mail-header-date header))
12037 (subject (gnus-summary-subject-string)))
12038 (org-store-link-props :type "gnus" :from from :subject subject
12039 :message-id message-id :group group)
12040 (setq cpltxt (org-email-link-description))
12041 (if (org-xor arg org-usenet-links-prefer-google)
12042 (setq link
12043 (concat
12044 cpltxt "\n "
12045 (format "http://groups.google.com/groups?as_umsgid=%s"
12046 (org-fixup-message-id-for-http message-id))))
12047 (setq link (org-make-link "gnus:" group
12048 "#" (number-to-string article))))))
12050 ((eq major-mode 'w3-mode)
12051 (setq cpltxt (url-view-url t)
12052 link (org-make-link cpltxt))
12053 (org-store-link-props :type "w3" :url (url-view-url t)))
12055 ((eq major-mode 'w3m-mode)
12056 (setq cpltxt (or w3m-current-title w3m-current-url)
12057 link (org-make-link w3m-current-url))
12058 (org-store-link-props :type "w3m" :url (url-view-url t)))
12060 ((setq search (run-hook-with-args-until-success
12061 'org-create-file-search-functions))
12062 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12063 "::" search))
12064 (setq cpltxt (or description link)))
12066 ((eq major-mode 'image-mode)
12067 (setq cpltxt (concat "file:"
12068 (abbreviate-file-name buffer-file-name))
12069 link (org-make-link cpltxt))
12070 (org-store-link-props :type "image" :file buffer-file-name))
12072 ((eq major-mode 'dired-mode)
12073 ;; link to the file in the current line
12074 (setq cpltxt (concat "file:"
12075 (abbreviate-file-name
12076 (expand-file-name
12077 (dired-get-filename nil t))))
12078 link (org-make-link cpltxt)))
12080 ((and buffer-file-name (org-mode-p))
12081 ;; Just link to current headline
12082 (setq cpltxt (concat "file:"
12083 (abbreviate-file-name buffer-file-name)))
12084 ;; Add a context search string
12085 (when (org-xor org-context-in-file-links arg)
12086 ;; Check if we are on a target
12087 (if (org-in-regexp "<<\\(.*?\\)>>")
12088 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12089 (setq txt (cond
12090 ((org-on-heading-p) nil)
12091 ((org-region-active-p)
12092 (buffer-substring (region-beginning) (region-end)))
12093 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12094 (when (or (null txt) (string-match "\\S-" txt))
12095 (setq cpltxt
12096 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12097 desc "NONE"))))
12098 (if (string-match "::\\'" cpltxt)
12099 (setq cpltxt (substring cpltxt 0 -2)))
12100 (setq link (org-make-link cpltxt)))
12102 ((buffer-file-name (buffer-base-buffer))
12103 ;; Just link to this file here.
12104 (setq cpltxt (concat "file:"
12105 (abbreviate-file-name
12106 (buffer-file-name (buffer-base-buffer)))))
12107 ;; Add a context string
12108 (when (org-xor org-context-in-file-links arg)
12109 (setq txt (if (org-region-active-p)
12110 (buffer-substring (region-beginning) (region-end))
12111 (buffer-substring (point-at-bol) (point-at-eol))))
12112 ;; Only use search option if there is some text.
12113 (when (string-match "\\S-" txt)
12114 (setq cpltxt
12115 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12116 desc "NONE")))
12117 (setq link (org-make-link cpltxt)))
12119 ((interactive-p)
12120 (error "Cannot link to a buffer which is not visiting a file"))
12122 (t (setq link nil)))
12124 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12125 (setq link (or link cpltxt)
12126 desc (or desc cpltxt))
12127 (if (equal desc "NONE") (setq desc nil))
12129 (if (and (interactive-p) link)
12130 (progn
12131 (setq org-stored-links
12132 (cons (list link desc) org-stored-links))
12133 (message "Stored: %s" (or desc link)))
12134 (and link (org-make-link-string link desc)))))
12136 (defun org-store-link-props (&rest plist)
12137 "Store link properties, extract names and addresses."
12138 (let (x adr)
12139 (when (setq x (plist-get plist :from))
12140 (setq adr (mail-extract-address-components x))
12141 (plist-put plist :fromname (car adr))
12142 (plist-put plist :fromaddress (nth 1 adr)))
12143 (when (setq x (plist-get plist :to))
12144 (setq adr (mail-extract-address-components x))
12145 (plist-put plist :toname (car adr))
12146 (plist-put plist :toaddress (nth 1 adr))))
12147 (let ((from (plist-get plist :from))
12148 (to (plist-get plist :to)))
12149 (when (and from to org-from-is-user-regexp)
12150 (plist-put plist :fromto
12151 (if (string-match org-from-is-user-regexp from)
12152 (concat "to %t")
12153 (concat "from %f")))))
12154 (setq org-store-link-plist plist))
12156 (defun org-email-link-description (&optional fmt)
12157 "Return the description part of an email link.
12158 This takes information from `org-store-link-plist' and formats it
12159 according to FMT (default from `org-email-link-description-format')."
12160 (setq fmt (or fmt org-email-link-description-format))
12161 (let* ((p org-store-link-plist)
12162 (to (plist-get p :toaddress))
12163 (from (plist-get p :fromaddress))
12164 (table
12165 (list
12166 (cons "%c" (plist-get p :fromto))
12167 (cons "%F" (plist-get p :from))
12168 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12169 (cons "%T" (plist-get p :to))
12170 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12171 (cons "%s" (plist-get p :subject))
12172 (cons "%m" (plist-get p :message-id)))))
12173 (when (string-match "%c" fmt)
12174 ;; Check if the user wrote this message
12175 (if (and org-from-is-user-regexp from to
12176 (save-match-data (string-match org-from-is-user-regexp from)))
12177 (setq fmt (replace-match "to %t" t t fmt))
12178 (setq fmt (replace-match "from %f" t t fmt))))
12179 (org-replace-escapes fmt table)))
12181 (defun org-make-org-heading-search-string (&optional string heading)
12182 "Make search string for STRING or current headline."
12183 (interactive)
12184 (let ((s (or string (org-get-heading))))
12185 (unless (and string (not heading))
12186 ;; We are using a headline, clean up garbage in there.
12187 (if (string-match org-todo-regexp s)
12188 (setq s (replace-match "" t t s)))
12189 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12190 (setq s (replace-match "" t t s)))
12191 (setq s (org-trim s))
12192 (if (string-match (concat "^\\(" org-quote-string "\\|"
12193 org-comment-string "\\)") s)
12194 (setq s (replace-match "" t t s)))
12195 (while (string-match org-ts-regexp s)
12196 (setq s (replace-match "" t t s))))
12197 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12198 (setq s (replace-match " " t t s)))
12199 (or string (setq s (concat "*" s))) ; Add * for headlines
12200 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12202 (defun org-make-link (&rest strings)
12203 "Concatenate STRINGS."
12204 (apply 'concat strings))
12206 (defun org-make-link-string (link &optional description)
12207 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12208 (unless (string-match "\\S-" link)
12209 (error "Empty link"))
12210 (when (stringp description)
12211 ;; Remove brackets from the description, they are fatal.
12212 (while (string-match "\\[" description)
12213 (setq description (replace-match "{" t t description)))
12214 (while (string-match "\\]" description)
12215 (setq description (replace-match "}" t t description))))
12216 (when (equal (org-link-escape link) description)
12217 ;; No description needed, it is identical
12218 (setq description nil))
12219 (when (and (not description)
12220 (not (equal link (org-link-escape link))))
12221 (setq description link))
12222 (concat "[[" (org-link-escape link) "]"
12223 (if description (concat "[" description "]") "")
12224 "]"))
12226 (defconst org-link-escape-chars
12227 '((?\ . "%20")
12228 (?\[ . "%5B")
12229 (?\] . "%5D")
12230 (?\340 . "%E0") ; `a
12231 (?\342 . "%E2") ; ^a
12232 (?\347 . "%E7") ; ,c
12233 (?\350 . "%E8") ; `e
12234 (?\351 . "%E9") ; 'e
12235 (?\352 . "%EA") ; ^e
12236 (?\356 . "%EE") ; ^i
12237 (?\364 . "%F4") ; ^o
12238 (?\371 . "%F9") ; `u
12239 (?\373 . "%FB") ; ^u
12240 (?\; . "%3B")
12241 (?? . "%3F")
12242 (?= . "%3D")
12243 (?+ . "%2B")
12245 "Association list of escapes for some characters problematic in links.
12246 This is the list that is used for internal purposes.")
12248 (defconst org-link-escape-chars-browser
12249 '((?\ . "%20")) ; 32 for the SPC char
12250 "Association list of escapes for some characters problematic in links.
12251 This is the list that is used before handing over to the browser.")
12253 (defun org-link-escape (text &optional table)
12254 "Escape charaters in TEXT that are problematic for links."
12255 (setq table (or table org-link-escape-chars))
12256 (when text
12257 (let ((re (mapconcat (lambda (x) (regexp-quote
12258 (char-to-string (car x))))
12259 table "\\|")))
12260 (while (string-match re text)
12261 (setq text
12262 (replace-match
12263 (cdr (assoc (string-to-char (match-string 0 text))
12264 table))
12265 t t text)))
12266 text)))
12268 (defun org-link-unescape (text &optional table)
12269 "Reverse the action of `org-link-escape'."
12270 (setq table (or table org-link-escape-chars))
12271 (when text
12272 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12273 table "\\|")))
12274 (while (string-match re text)
12275 (setq text
12276 (replace-match
12277 (char-to-string (car (rassoc (match-string 0 text) table)))
12278 t t text)))
12279 text)))
12281 (defun org-xor (a b)
12282 "Exclusive or."
12283 (if a (not b) b))
12285 (defun org-get-header (header)
12286 "Find a header field in the current buffer."
12287 (save-excursion
12288 (goto-char (point-min))
12289 (let ((case-fold-search t) s)
12290 (cond
12291 ((eq header 'from)
12292 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12293 (setq s (match-string 1)))
12294 (while (string-match "\"" s)
12295 (setq s (replace-match "" t t s)))
12296 (if (string-match "[<(].*" s)
12297 (setq s (replace-match "" t t s))))
12298 ((eq header 'message-id)
12299 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12300 (setq s (match-string 1))))
12301 ((eq header 'subject)
12302 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12303 (setq s (match-string 1)))))
12304 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12305 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12306 s)))
12309 (defun org-fixup-message-id-for-http (s)
12310 "Replace special characters in a message id, so it can be used in an http query."
12311 (while (string-match "<" s)
12312 (setq s (replace-match "%3C" t t s)))
12313 (while (string-match ">" s)
12314 (setq s (replace-match "%3E" t t s)))
12315 (while (string-match "@" s)
12316 (setq s (replace-match "%40" t t s)))
12319 ;;;###autoload
12320 (defun org-insert-link-global ()
12321 "Insert a link like Org-mode does.
12322 This command can be called in any mode to insert a link in Org-mode syntax."
12323 (interactive)
12324 (org-run-like-in-org-mode 'org-insert-link))
12326 (defun org-insert-link (&optional complete-file)
12327 "Insert a link. At the prompt, enter the link.
12329 Completion can be used to select a link previously stored with
12330 `org-store-link'. When the empty string is entered (i.e. if you just
12331 press RET at the prompt), the link defaults to the most recently
12332 stored link. As SPC triggers completion in the minibuffer, you need to
12333 use M-SPC or C-q SPC to force the insertion of a space character.
12335 You will also be prompted for a description, and if one is given, it will
12336 be displayed in the buffer instead of the link.
12338 If there is already a link at point, this command will allow you to edit link
12339 and description parts.
12341 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12342 selected using completion. The path to the file will be relative to
12343 the current directory if the file is in the current directory or a
12344 subdirectory. Otherwise, the link will be the absolute path as
12345 completed in the minibuffer (i.e. normally ~/path/to/file).
12347 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12348 is in the current directory or below.
12349 With three \\[universal-argument] prefixes, negate the meaning of
12350 `org-keep-stored-link-after-insertion'."
12351 (interactive "P")
12352 (let* ((wcf (current-window-configuration))
12353 (region (if (org-region-active-p)
12354 (buffer-substring (region-beginning) (region-end))))
12355 (remove (and region (list (region-beginning) (region-end))))
12356 (desc region)
12357 tmphist ; byte-compile incorrectly complains about this
12358 link entry file)
12359 (cond
12360 ((org-in-regexp org-bracket-link-regexp 1)
12361 ;; We do have a link at point, and we are going to edit it.
12362 (setq remove (list (match-beginning 0) (match-end 0)))
12363 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12364 (setq link (read-string "Link: "
12365 (org-link-unescape
12366 (org-match-string-no-properties 1)))))
12367 ((or (org-in-regexp org-angle-link-re)
12368 (org-in-regexp org-plain-link-re))
12369 ;; Convert to bracket link
12370 (setq remove (list (match-beginning 0) (match-end 0))
12371 link (read-string "Link: "
12372 (org-remove-angle-brackets (match-string 0)))))
12373 ((equal complete-file '(4))
12374 ;; Completing read for file names.
12375 (setq file (read-file-name "File: "))
12376 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12377 (pwd1 (file-name-as-directory (abbreviate-file-name
12378 (expand-file-name ".")))))
12379 (cond
12380 ((equal complete-file '(16))
12381 (setq link (org-make-link
12382 "file:"
12383 (abbreviate-file-name (expand-file-name file)))))
12384 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12385 (setq link (org-make-link "file:" (match-string 1 file))))
12386 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12387 (expand-file-name file))
12388 (setq link (org-make-link
12389 "file:" (match-string 1 (expand-file-name file)))))
12390 (t (setq link (org-make-link "file:" file))))))
12392 ;; Read link, with completion for stored links.
12393 (with-output-to-temp-buffer "*Org Links*"
12394 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12395 (when org-stored-links
12396 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12397 (princ (mapconcat
12398 (lambda (x)
12399 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12400 (reverse org-stored-links) "\n"))))
12401 (let ((cw (selected-window)))
12402 (select-window (get-buffer-window "*Org Links*"))
12403 (shrink-window-if-larger-than-buffer)
12404 (setq truncate-lines t)
12405 (select-window cw))
12406 ;; Fake a link history, containing the stored links.
12407 (setq tmphist (append (mapcar 'car org-stored-links)
12408 org-insert-link-history))
12409 (unwind-protect
12410 (setq link (org-completing-read
12411 "Link: "
12412 (append
12413 (mapcar (lambda (x) (list (concat (car x) ":")))
12414 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12415 (mapcar (lambda (x) (list (concat x ":")))
12416 org-link-types))
12417 nil nil nil
12418 'tmphist
12419 (or (car (car org-stored-links)))))
12420 (set-window-configuration wcf)
12421 (kill-buffer "*Org Links*"))
12422 (setq entry (assoc link org-stored-links))
12423 (or entry (push link org-insert-link-history))
12424 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12425 (not org-keep-stored-link-after-insertion))
12426 (setq org-stored-links (delq (assoc link org-stored-links)
12427 org-stored-links)))
12428 (setq desc (or desc (nth 1 entry)))))
12430 (if (string-match org-plain-link-re link)
12431 ;; URL-like link, normalize the use of angular brackets.
12432 (setq link (org-make-link (org-remove-angle-brackets link))))
12434 ;; Check if we are linking to the current file with a search option
12435 ;; If yes, simplify the link by using only the search option.
12436 (when (and buffer-file-name
12437 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12438 (let* ((path (match-string 1 link))
12439 (case-fold-search nil)
12440 (search (match-string 2 link)))
12441 (save-match-data
12442 (if (equal (file-truename buffer-file-name) (file-truename path))
12443 ;; We are linking to this same file, with a search option
12444 (setq link search)))))
12446 ;; Check if we can/should use a relative path. If yes, simplify the link
12447 (when (string-match "\\<file:\\(.*\\)" link)
12448 (let* ((path (match-string 1 link))
12449 (origpath path)
12450 (desc-is-link (equal link desc))
12451 (case-fold-search nil))
12452 (cond
12453 ((eq org-link-file-path-type 'absolute)
12454 (setq path (abbreviate-file-name (expand-file-name path))))
12455 ((eq org-link-file-path-type 'noabbrev)
12456 (setq path (expand-file-name path)))
12457 ((eq org-link-file-path-type 'relative)
12458 (setq path (file-relative-name path)))
12460 (save-match-data
12461 (if (string-match (concat "^" (regexp-quote
12462 (file-name-as-directory
12463 (expand-file-name "."))))
12464 (expand-file-name path))
12465 ;; We are linking a file with relative path name.
12466 (setq path (substring (expand-file-name path)
12467 (match-end 0)))))))
12468 (setq link (concat "file:" path))
12469 (if (equal desc origpath)
12470 (setq desc path))))
12472 (setq desc (read-string "Description: " desc))
12473 (unless (string-match "\\S-" desc) (setq desc nil))
12474 (if remove (apply 'delete-region remove))
12475 (insert (org-make-link-string link desc))))
12477 (defun org-completing-read (&rest args)
12478 (let ((minibuffer-local-completion-map
12479 (copy-keymap minibuffer-local-completion-map)))
12480 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12481 (apply 'completing-read args)))
12483 ;;; Opening/following a link
12484 (defvar org-link-search-failed nil)
12486 (defun org-next-link ()
12487 "Move forward to the next link.
12488 If the link is in hidden text, expose it."
12489 (interactive)
12490 (when (and org-link-search-failed (eq this-command last-command))
12491 (goto-char (point-min))
12492 (message "Link search wrapped back to beginning of buffer"))
12493 (setq org-link-search-failed nil)
12494 (let* ((pos (point))
12495 (ct (org-context))
12496 (a (assoc :link ct)))
12497 (if a (goto-char (nth 2 a)))
12498 (if (re-search-forward org-any-link-re nil t)
12499 (progn
12500 (goto-char (match-beginning 0))
12501 (if (org-invisible-p) (org-show-context)))
12502 (goto-char pos)
12503 (setq org-link-search-failed t)
12504 (error "No further link found"))))
12506 (defun org-previous-link ()
12507 "Move backward to the previous link.
12508 If the link is in hidden text, expose it."
12509 (interactive)
12510 (when (and org-link-search-failed (eq this-command last-command))
12511 (goto-char (point-max))
12512 (message "Link search wrapped back to end of buffer"))
12513 (setq org-link-search-failed nil)
12514 (let* ((pos (point))
12515 (ct (org-context))
12516 (a (assoc :link ct)))
12517 (if a (goto-char (nth 1 a)))
12518 (if (re-search-backward org-any-link-re nil t)
12519 (progn
12520 (goto-char (match-beginning 0))
12521 (if (org-invisible-p) (org-show-context)))
12522 (goto-char pos)
12523 (setq org-link-search-failed t)
12524 (error "No further link found"))))
12526 (defun org-find-file-at-mouse (ev)
12527 "Open file link or URL at mouse."
12528 (interactive "e")
12529 (mouse-set-point ev)
12530 (org-open-at-point 'in-emacs))
12532 (defun org-open-at-mouse (ev)
12533 "Open file link or URL at mouse."
12534 (interactive "e")
12535 (mouse-set-point ev)
12536 (org-open-at-point))
12538 (defvar org-window-config-before-follow-link nil
12539 "The window configuration before following a link.
12540 This is saved in case the need arises to restore it.")
12542 (defvar org-open-link-marker (make-marker)
12543 "Marker pointing to the location where `org-open-at-point; was called.")
12545 ;;;###autoload
12546 (defun org-open-at-point-global ()
12547 "Follow a link like Org-mode does.
12548 This command can be called in any mode to follow a link that has
12549 Org-mode syntax."
12550 (interactive)
12551 (org-run-like-in-org-mode 'org-open-at-point))
12553 (defun org-open-at-point (&optional in-emacs)
12554 "Open link at or after point.
12555 If there is no link at point, this function will search forward up to
12556 the end of the current subtree.
12557 Normally, files will be opened by an appropriate application. If the
12558 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12559 (interactive "P")
12560 (catch 'abort
12561 (move-marker org-open-link-marker (point))
12562 (setq org-window-config-before-follow-link (current-window-configuration))
12563 (org-remove-occur-highlights nil nil t)
12564 (if (org-at-timestamp-p t)
12565 (org-follow-timestamp-link)
12566 (let (type path link line search (pos (point)))
12567 (catch 'match
12568 (save-excursion
12569 (skip-chars-forward "^]\n\r")
12570 (when (org-in-regexp org-bracket-link-regexp)
12571 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12572 (while (string-match " *\n *" link)
12573 (setq link (replace-match " " t t link)))
12574 (setq link (org-link-expand-abbrev link))
12575 (if (string-match org-link-re-with-space2 link)
12576 (setq type (match-string 1 link) path (match-string 2 link))
12577 (setq type "thisfile" path link))
12578 (throw 'match t)))
12580 (when (get-text-property (point) 'org-linked-text)
12581 (setq type "thisfile"
12582 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12583 (1+ (point)) (point))
12584 path (buffer-substring
12585 (previous-single-property-change pos 'org-linked-text)
12586 (next-single-property-change pos 'org-linked-text)))
12587 (throw 'match t))
12589 (save-excursion
12590 (when (or (org-in-regexp org-angle-link-re)
12591 (org-in-regexp org-plain-link-re))
12592 (setq type (match-string 1) path (match-string 2))
12593 (throw 'match t)))
12594 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12595 (setq type "tree-match"
12596 path (match-string 1))
12597 (throw 'match t))
12598 (save-excursion
12599 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12600 (setq type "tags"
12601 path (match-string 1))
12602 (while (string-match ":" path)
12603 (setq path (replace-match "+" t t path)))
12604 (throw 'match t))))
12605 (unless path
12606 (error "No link found"))
12607 ;; Remove any trailing spaces in path
12608 (if (string-match " +\\'" path)
12609 (setq path (replace-match "" t t path)))
12611 (cond
12613 ((assoc type org-link-protocols)
12614 (funcall (nth 1 (assoc type org-link-protocols)) path))
12616 ((equal type "mailto")
12617 (let ((cmd (car org-link-mailto-program))
12618 (args (cdr org-link-mailto-program)) args1
12619 (address path) (subject "") a)
12620 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12621 (setq address (match-string 1 path)
12622 subject (org-link-escape (match-string 2 path))))
12623 (while args
12624 (cond
12625 ((not (stringp (car args))) (push (pop args) args1))
12626 (t (setq a (pop args))
12627 (if (string-match "%a" a)
12628 (setq a (replace-match address t t a)))
12629 (if (string-match "%s" a)
12630 (setq a (replace-match subject t t a)))
12631 (push a args1))))
12632 (apply cmd (nreverse args1))))
12634 ((member type '("http" "https" "ftp" "news"))
12635 (browse-url (concat type ":" (org-link-escape
12636 path org-link-escape-chars-browser))))
12638 ((member type '("message"))
12639 (browse-url (concat type ":" path)))
12641 ((string= type "tags")
12642 (org-tags-view in-emacs path))
12643 ((string= type "thisfile")
12644 (if in-emacs
12645 (switch-to-buffer-other-window
12646 (org-get-buffer-for-internal-link (current-buffer)))
12647 (org-mark-ring-push))
12648 (let ((cmd `(org-link-search
12649 ,path
12650 ,(cond ((equal in-emacs '(4)) 'occur)
12651 ((equal in-emacs '(16)) 'org-occur)
12652 (t nil))
12653 ,pos)))
12654 (condition-case nil (eval cmd)
12655 (error (progn (widen) (eval cmd))))))
12657 ((string= type "tree-match")
12658 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12660 ((string= type "file")
12661 (if (string-match "::\\([0-9]+\\)\\'" path)
12662 (setq line (string-to-number (match-string 1 path))
12663 path (substring path 0 (match-beginning 0)))
12664 (if (string-match "::\\(.+\\)\\'" path)
12665 (setq search (match-string 1 path)
12666 path (substring path 0 (match-beginning 0)))))
12667 (if (string-match "[*?{]" (file-name-nondirectory path))
12668 (dired path)
12669 (org-open-file path in-emacs line search)))
12671 ((string= type "news")
12672 (org-follow-gnus-link path))
12674 ((string= type "bbdb")
12675 (org-follow-bbdb-link path))
12677 ((string= type "info")
12678 (org-follow-info-link path))
12680 ((string= type "gnus")
12681 (let (group article)
12682 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12683 (error "Error in Gnus link"))
12684 (setq group (match-string 1 path)
12685 article (match-string 3 path))
12686 (org-follow-gnus-link group article)))
12688 ((string= type "vm")
12689 (let (folder article)
12690 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12691 (error "Error in VM link"))
12692 (setq folder (match-string 1 path)
12693 article (match-string 3 path))
12694 ;; in-emacs is the prefix arg, will be interpreted as read-only
12695 (org-follow-vm-link folder article in-emacs)))
12697 ((string= type "wl")
12698 (let (folder article)
12699 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12700 (error "Error in Wanderlust link"))
12701 (setq folder (match-string 1 path)
12702 article (match-string 3 path))
12703 (org-follow-wl-link folder article)))
12705 ((string= type "mhe")
12706 (let (folder article)
12707 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12708 (error "Error in MHE link"))
12709 (setq folder (match-string 1 path)
12710 article (match-string 3 path))
12711 (org-follow-mhe-link folder article)))
12713 ((string= type "rmail")
12714 (let (folder article)
12715 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12716 (error "Error in RMAIL link"))
12717 (setq folder (match-string 1 path)
12718 article (match-string 3 path))
12719 (org-follow-rmail-link folder article)))
12721 ((string= type "shell")
12722 (let ((cmd path))
12723 (if (or (not org-confirm-shell-link-function)
12724 (funcall org-confirm-shell-link-function
12725 (format "Execute \"%s\" in shell? "
12726 (org-add-props cmd nil
12727 'face 'org-warning))))
12728 (progn
12729 (message "Executing %s" cmd)
12730 (shell-command cmd))
12731 (error "Abort"))))
12733 ((string= type "elisp")
12734 (let ((cmd path))
12735 (if (or (not org-confirm-elisp-link-function)
12736 (funcall org-confirm-elisp-link-function
12737 (format "Execute \"%s\" as elisp? "
12738 (org-add-props cmd nil
12739 'face 'org-warning))))
12740 (message "%s => %s" cmd (eval (read cmd)))
12741 (error "Abort"))))
12744 (browse-url-at-point)))))
12745 (move-marker org-open-link-marker nil)))
12747 ;;; File search
12749 (defvar org-create-file-search-functions nil
12750 "List of functions to construct the right search string for a file link.
12751 These functions are called in turn with point at the location to
12752 which the link should point.
12754 A function in the hook should first test if it would like to
12755 handle this file type, for example by checking the major-mode or
12756 the file extension. If it decides not to handle this file, it
12757 should just return nil to give other functions a chance. If it
12758 does handle the file, it must return the search string to be used
12759 when following the link. The search string will be part of the
12760 file link, given after a double colon, and `org-open-at-point'
12761 will automatically search for it. If special measures must be
12762 taken to make the search successful, another function should be
12763 added to the companion hook `org-execute-file-search-functions',
12764 which see.
12766 A function in this hook may also use `setq' to set the variable
12767 `description' to provide a suggestion for the descriptive text to
12768 be used for this link when it gets inserted into an Org-mode
12769 buffer with \\[org-insert-link].")
12771 (defvar org-execute-file-search-functions nil
12772 "List of functions to execute a file search triggered by a link.
12774 Functions added to this hook must accept a single argument, the
12775 search string that was part of the file link, the part after the
12776 double colon. The function must first check if it would like to
12777 handle this search, for example by checking the major-mode or the
12778 file extension. If it decides not to handle this search, it
12779 should just return nil to give other functions a chance. If it
12780 does handle the search, it must return a non-nil value to keep
12781 other functions from trying.
12783 Each function can access the current prefix argument through the
12784 variable `current-prefix-argument'. Note that a single prefix is
12785 used to force opening a link in Emacs, so it may be good to only
12786 use a numeric or double prefix to guide the search function.
12788 In case this is needed, a function in this hook can also restore
12789 the window configuration before `org-open-at-point' was called using:
12791 (set-window-configuration org-window-config-before-follow-link)")
12793 (defun org-link-search (s &optional type avoid-pos)
12794 "Search for a link search option.
12795 If S is surrounded by forward slashes, it is interpreted as a
12796 regular expression. In org-mode files, this will create an `org-occur'
12797 sparse tree. In ordinary files, `occur' will be used to list matches.
12798 If the current buffer is in `dired-mode', grep will be used to search
12799 in all files. If AVOID-POS is given, ignore matches near that position."
12800 (let ((case-fold-search t)
12801 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12802 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12803 (append '(("") (" ") ("\t") ("\n"))
12804 org-emphasis-alist)
12805 "\\|") "\\)"))
12806 (pos (point))
12807 (pre "") (post "")
12808 words re0 re1 re2 re3 re4 re5 re2a reall)
12809 (cond
12810 ;; First check if there are any special
12811 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12812 ;; Now try the builtin stuff
12813 ((save-excursion
12814 (goto-char (point-min))
12815 (and
12816 (re-search-forward
12817 (concat "<<" (regexp-quote s0) ">>") nil t)
12818 (setq pos (match-beginning 0))))
12819 ;; There is an exact target for this
12820 (goto-char pos))
12821 ((string-match "^/\\(.*\\)/$" s)
12822 ;; A regular expression
12823 (cond
12824 ((org-mode-p)
12825 (org-occur (match-string 1 s)))
12826 ;;((eq major-mode 'dired-mode)
12827 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12828 (t (org-do-occur (match-string 1 s)))))
12830 ;; A normal search strings
12831 (when (equal (string-to-char s) ?*)
12832 ;; Anchor on headlines, post may include tags.
12833 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12834 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12835 s (substring s 1)))
12836 (remove-text-properties
12837 0 (length s)
12838 '(face nil mouse-face nil keymap nil fontified nil) s)
12839 ;; Make a series of regular expressions to find a match
12840 (setq words (org-split-string s "[ \n\r\t]+")
12841 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12842 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12843 "\\)" markers)
12844 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12845 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12846 re1 (concat pre re2 post)
12847 re3 (concat pre re4 post)
12848 re5 (concat pre ".*" re4)
12849 re2 (concat pre re2)
12850 re2a (concat pre re2a)
12851 re4 (concat pre re4)
12852 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12853 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12854 re5 "\\)"
12856 (cond
12857 ((eq type 'org-occur) (org-occur reall))
12858 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12859 (t (goto-char (point-min))
12860 (if (or (org-search-not-self 1 re0 nil t)
12861 (org-search-not-self 1 re1 nil t)
12862 (org-search-not-self 1 re2 nil t)
12863 (org-search-not-self 1 re2a nil t)
12864 (org-search-not-self 1 re3 nil t)
12865 (org-search-not-self 1 re4 nil t)
12866 (org-search-not-self 1 re5 nil t)
12868 (goto-char (match-beginning 1))
12869 (goto-char pos)
12870 (error "No match")))))
12872 ;; Normal string-search
12873 (goto-char (point-min))
12874 (if (search-forward s nil t)
12875 (goto-char (match-beginning 0))
12876 (error "No match"))))
12877 (and (org-mode-p) (org-show-context 'link-search))))
12879 (defun org-search-not-self (group &rest args)
12880 "Execute `re-search-forward', but only accept matches that do not
12881 enclose the position of `org-open-link-marker'."
12882 (let ((m org-open-link-marker))
12883 (catch 'exit
12884 (while (apply 're-search-forward args)
12885 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12886 (goto-char (match-end group))
12887 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12888 (> (match-beginning 0) (marker-position m))
12889 (< (match-end 0) (marker-position m)))
12890 (save-match-data
12891 (or (not (org-in-regexp
12892 org-bracket-link-analytic-regexp 1))
12893 (not (match-end 4)) ; no description
12894 (and (<= (match-beginning 4) (point))
12895 (>= (match-end 4) (point))))))
12896 (throw 'exit (point))))))))
12898 (defun org-get-buffer-for-internal-link (buffer)
12899 "Return a buffer to be used for displaying the link target of internal links."
12900 (cond
12901 ((not org-display-internal-link-with-indirect-buffer)
12902 buffer)
12903 ((string-match "(Clone)$" (buffer-name buffer))
12904 (message "Buffer is already a clone, not making another one")
12905 ;; we also do not modify visibility in this case
12906 buffer)
12907 (t ; make a new indirect buffer for displaying the link
12908 (let* ((bn (buffer-name buffer))
12909 (ibn (concat bn "(Clone)"))
12910 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12911 (with-current-buffer ib (org-overview))
12912 ib))))
12914 (defun org-do-occur (regexp &optional cleanup)
12915 "Call the Emacs command `occur'.
12916 If CLEANUP is non-nil, remove the printout of the regular expression
12917 in the *Occur* buffer. This is useful if the regex is long and not useful
12918 to read."
12919 (occur regexp)
12920 (when cleanup
12921 (let ((cwin (selected-window)) win beg end)
12922 (when (setq win (get-buffer-window "*Occur*"))
12923 (select-window win))
12924 (goto-char (point-min))
12925 (when (re-search-forward "match[a-z]+" nil t)
12926 (setq beg (match-end 0))
12927 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12928 (setq end (1- (match-beginning 0)))))
12929 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12930 (goto-char (point-min))
12931 (select-window cwin))))
12933 ;;; The mark ring for links jumps
12935 (defvar org-mark-ring nil
12936 "Mark ring for positions before jumps in Org-mode.")
12937 (defvar org-mark-ring-last-goto nil
12938 "Last position in the mark ring used to go back.")
12939 ;; Fill and close the ring
12940 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12941 (loop for i from 1 to org-mark-ring-length do
12942 (push (make-marker) org-mark-ring))
12943 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12944 org-mark-ring)
12946 (defun org-mark-ring-push (&optional pos buffer)
12947 "Put the current position or POS into the mark ring and rotate it."
12948 (interactive)
12949 (setq pos (or pos (point)))
12950 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12951 (move-marker (car org-mark-ring)
12952 (or pos (point))
12953 (or buffer (current-buffer)))
12954 (message "%s"
12955 (substitute-command-keys
12956 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12958 (defun org-mark-ring-goto (&optional n)
12959 "Jump to the previous position in the mark ring.
12960 With prefix arg N, jump back that many stored positions. When
12961 called several times in succession, walk through the entire ring.
12962 Org-mode commands jumping to a different position in the current file,
12963 or to another Org-mode file, automatically push the old position
12964 onto the ring."
12965 (interactive "p")
12966 (let (p m)
12967 (if (eq last-command this-command)
12968 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12969 (setq p org-mark-ring))
12970 (setq org-mark-ring-last-goto p)
12971 (setq m (car p))
12972 (switch-to-buffer (marker-buffer m))
12973 (goto-char m)
12974 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12976 (defun org-remove-angle-brackets (s)
12977 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12978 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12980 (defun org-add-angle-brackets (s)
12981 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12982 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12985 ;;; Following specific links
12987 (defun org-follow-timestamp-link ()
12988 (cond
12989 ((org-at-date-range-p t)
12990 (let ((org-agenda-start-on-weekday)
12991 (t1 (match-string 1))
12992 (t2 (match-string 2)))
12993 (setq t1 (time-to-days (org-time-string-to-time t1))
12994 t2 (time-to-days (org-time-string-to-time t2)))
12995 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12996 ((org-at-timestamp-p t)
12997 (org-agenda-list nil (time-to-days (org-time-string-to-time
12998 (substring (match-string 1) 0 10)))
13000 (t (error "This should not happen"))))
13003 (defun org-follow-bbdb-link (name)
13004 "Follow a BBDB link to NAME."
13005 (require 'bbdb)
13006 (let ((inhibit-redisplay (not debug-on-error))
13007 (bbdb-electric-p nil))
13008 (catch 'exit
13009 ;; Exact match on name
13010 (bbdb-name (concat "\\`" name "\\'") nil)
13011 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13012 ;; Exact match on name
13013 (bbdb-company (concat "\\`" name "\\'") nil)
13014 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13015 ;; Partial match on name
13016 (bbdb-name name nil)
13017 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13018 ;; Partial match on company
13019 (bbdb-company name nil)
13020 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13021 ;; General match including network address and notes
13022 (bbdb name nil)
13023 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13024 (delete-window (get-buffer-window "*BBDB*"))
13025 (error "No matching BBDB record")))))
13027 (defun org-follow-info-link (name)
13028 "Follow an info file & node link to NAME."
13029 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13030 (string-match "\\(.*\\)" name))
13031 (progn
13032 (require 'info)
13033 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13034 (Info-find-node (match-string 1 name) (match-string 2 name))
13035 (Info-find-node (match-string 1 name) "Top")))
13036 (message "Could not open: %s" name)))
13038 (defun org-follow-gnus-link (&optional group article)
13039 "Follow a Gnus link to GROUP and ARTICLE."
13040 (require 'gnus)
13041 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13042 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13043 (cond ((and group article)
13044 (gnus-group-read-group 1 nil group)
13045 (gnus-summary-goto-article (string-to-number article) nil t))
13046 (group (gnus-group-jump-to-group group))))
13048 (defun org-follow-vm-link (&optional folder article readonly)
13049 "Follow a VM link to FOLDER and ARTICLE."
13050 (require 'vm)
13051 (setq article (org-add-angle-brackets article))
13052 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13053 ;; ange-ftp or efs or tramp access
13054 (let ((user (or (match-string 1 folder) (user-login-name)))
13055 (host (match-string 2 folder))
13056 (file (match-string 3 folder)))
13057 (cond
13058 ((featurep 'tramp)
13059 ;; use tramp to access the file
13060 (if (featurep 'xemacs)
13061 (setq folder (format "[%s@%s]%s" user host file))
13062 (setq folder (format "/%s@%s:%s" user host file))))
13064 ;; use ange-ftp or efs
13065 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13066 (setq folder (format "/%s@%s:%s" user host file))))))
13067 (when folder
13068 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13069 (sit-for 0.1)
13070 (when article
13071 (vm-select-folder-buffer)
13072 (widen)
13073 (let ((case-fold-search t))
13074 (goto-char (point-min))
13075 (if (not (re-search-forward
13076 (concat "^" "message-id: *" (regexp-quote article))))
13077 (error "Could not find the specified message in this folder"))
13078 (vm-isearch-update)
13079 (vm-isearch-narrow)
13080 (vm-beginning-of-message)
13081 (vm-summarize)))))
13083 (defun org-follow-wl-link (folder article)
13084 "Follow a Wanderlust link to FOLDER and ARTICLE."
13085 (if (and (string= folder "%")
13086 article
13087 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13088 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13089 ;; Thus, we recompose folder and article ids.
13090 (setq folder (format "%s#%s" folder (match-string 1 article))
13091 article (match-string 3 article)))
13092 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13093 (error "No such folder: %s" folder))
13094 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13095 (and article
13096 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13097 (wl-summary-redisplay)))
13099 (defun org-follow-rmail-link (folder article)
13100 "Follow an RMAIL link to FOLDER and ARTICLE."
13101 (setq article (org-add-angle-brackets article))
13102 (let (message-number)
13103 (save-excursion
13104 (save-window-excursion
13105 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13106 (setq message-number
13107 (save-restriction
13108 (widen)
13109 (goto-char (point-max))
13110 (if (re-search-backward
13111 (concat "^Message-ID:\\s-+" (regexp-quote
13112 (or article "")))
13113 nil t)
13114 (rmail-what-message))))))
13115 (if message-number
13116 (progn
13117 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13118 (rmail-show-message message-number)
13119 message-number)
13120 (error "Message not found"))))
13122 ;;; mh-e integration based on planner-mode
13123 (defun org-mhe-get-message-real-folder ()
13124 "Return the name of the current message real folder, so if you use
13125 sequences, it will now work."
13126 (save-excursion
13127 (let* ((folder
13128 (if (equal major-mode 'mh-folder-mode)
13129 mh-current-folder
13130 ;; Refer to the show buffer
13131 mh-show-folder-buffer))
13132 (end-index
13133 (if (boundp 'mh-index-folder)
13134 (min (length mh-index-folder) (length folder))))
13136 ;; a simple test on mh-index-data does not work, because
13137 ;; mh-index-data is always nil in a show buffer.
13138 (if (and (boundp 'mh-index-folder)
13139 (string= mh-index-folder (substring folder 0 end-index)))
13140 (if (equal major-mode 'mh-show-mode)
13141 (save-window-excursion
13142 (let (pop-up-frames)
13143 (when (buffer-live-p (get-buffer folder))
13144 (progn
13145 (pop-to-buffer folder)
13146 (org-mhe-get-message-folder-from-index)
13149 (org-mhe-get-message-folder-from-index)
13151 folder
13155 (defun org-mhe-get-message-folder-from-index ()
13156 "Returns the name of the message folder in a index folder buffer."
13157 (save-excursion
13158 (mh-index-previous-folder)
13159 (re-search-forward "^\\(+.*\\)$" nil t)
13160 (message "%s" (match-string 1))))
13162 (defun org-mhe-get-message-folder ()
13163 "Return the name of the current message folder. Be careful if you
13164 use sequences."
13165 (save-excursion
13166 (if (equal major-mode 'mh-folder-mode)
13167 mh-current-folder
13168 ;; Refer to the show buffer
13169 mh-show-folder-buffer)))
13171 (defun org-mhe-get-message-num ()
13172 "Return the number of the current message. Be careful if you
13173 use sequences."
13174 (save-excursion
13175 (if (equal major-mode 'mh-folder-mode)
13176 (mh-get-msg-num nil)
13177 ;; Refer to the show buffer
13178 (mh-show-buffer-message-number))))
13180 (defun org-mhe-get-header (header)
13181 "Return a header of the message in folder mode. This will create a
13182 show buffer for the corresponding message. If you have a more clever
13183 idea..."
13184 (let* ((folder (org-mhe-get-message-folder))
13185 (num (org-mhe-get-message-num))
13186 (buffer (get-buffer-create (concat "show-" folder)))
13187 (header-field))
13188 (with-current-buffer buffer
13189 (mh-display-msg num folder)
13190 (if (equal major-mode 'mh-folder-mode)
13191 (mh-header-display)
13192 (mh-show-header-display))
13193 (set-buffer buffer)
13194 (setq header-field (mh-get-header-field header))
13195 (if (equal major-mode 'mh-folder-mode)
13196 (mh-show)
13197 (mh-show-show))
13198 header-field)))
13200 (defun org-follow-mhe-link (folder article)
13201 "Follow an MHE link to FOLDER and ARTICLE.
13202 If ARTICLE is nil FOLDER is shown. If the configuration variable
13203 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13204 ARTICLE is searched in all folders. Indexed searches (swish++,
13205 namazu, and others supported by MH-E) will always search in all
13206 folders."
13207 (require 'mh-e)
13208 (require 'mh-search)
13209 (require 'mh-utils)
13210 (mh-find-path)
13211 (if (not article)
13212 (mh-visit-folder (mh-normalize-folder-name folder))
13213 (setq article (org-add-angle-brackets article))
13214 (mh-search-choose)
13215 (if (equal mh-searcher 'pick)
13216 (progn
13217 (mh-search folder (list "--message-id" article))
13218 (when (and org-mhe-search-all-folders
13219 (not (org-mhe-get-message-real-folder)))
13220 (kill-this-buffer)
13221 (mh-search "+" (list "--message-id" article))))
13222 (mh-search "+" article))
13223 (if (org-mhe-get-message-real-folder)
13224 (mh-show-msg 1)
13225 (kill-this-buffer)
13226 (error "Message not found"))))
13228 ;;; BibTeX links
13230 ;; Use the custom search meachnism to construct and use search strings for
13231 ;; file links to BibTeX database entries.
13233 (defun org-create-file-search-in-bibtex ()
13234 "Create the search string and description for a BibTeX database entry."
13235 (when (eq major-mode 'bibtex-mode)
13236 ;; yes, we want to construct this search string.
13237 ;; Make a good description for this entry, using names, year and the title
13238 ;; Put it into the `description' variable which is dynamically scoped.
13239 (let ((bibtex-autokey-names 1)
13240 (bibtex-autokey-names-stretch 1)
13241 (bibtex-autokey-name-case-convert-function 'identity)
13242 (bibtex-autokey-name-separator " & ")
13243 (bibtex-autokey-additional-names " et al.")
13244 (bibtex-autokey-year-length 4)
13245 (bibtex-autokey-name-year-separator " ")
13246 (bibtex-autokey-titlewords 3)
13247 (bibtex-autokey-titleword-separator " ")
13248 (bibtex-autokey-titleword-case-convert-function 'identity)
13249 (bibtex-autokey-titleword-length 'infty)
13250 (bibtex-autokey-year-title-separator ": "))
13251 (setq description (bibtex-generate-autokey)))
13252 ;; Now parse the entry, get the key and return it.
13253 (save-excursion
13254 (bibtex-beginning-of-entry)
13255 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13257 (defun org-execute-file-search-in-bibtex (s)
13258 "Find the link search string S as a key for a database entry."
13259 (when (eq major-mode 'bibtex-mode)
13260 ;; Yes, we want to do the search in this file.
13261 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13262 (goto-char (point-min))
13263 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13264 (regexp-quote s) "[ \t\n]*,") nil t)
13265 (goto-char (match-beginning 0)))
13266 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13267 ;; Use double prefix to indicate that any web link should be browsed
13268 (let ((b (current-buffer)) (p (point)))
13269 ;; Restore the window configuration because we just use the web link
13270 (set-window-configuration org-window-config-before-follow-link)
13271 (save-excursion (set-buffer b) (goto-char p)
13272 (bibtex-url)))
13273 (recenter 0)) ; Move entry start to beginning of window
13274 ;; return t to indicate that the search is done.
13277 ;; Finally add the functions to the right hooks.
13278 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13279 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13281 ;; end of Bibtex link setup
13283 ;;; Following file links
13285 (defun org-open-file (path &optional in-emacs line search)
13286 "Open the file at PATH.
13287 First, this expands any special file name abbreviations. Then the
13288 configuration variable `org-file-apps' is checked if it contains an
13289 entry for this file type, and if yes, the corresponding command is launched.
13290 If no application is found, Emacs simply visits the file.
13291 With optional argument IN-EMACS, Emacs will visit the file.
13292 Optional LINE specifies a line to go to, optional SEARCH a string to
13293 search for. If LINE or SEARCH is given, the file will always be
13294 opened in Emacs.
13295 If the file does not exist, an error is thrown."
13296 (setq in-emacs (or in-emacs line search))
13297 (let* ((file (if (equal path "")
13298 buffer-file-name
13299 (substitute-in-file-name (expand-file-name path))))
13300 (apps (append org-file-apps (org-default-apps)))
13301 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13302 (dirp (if remp nil (file-directory-p file)))
13303 (dfile (downcase file))
13304 (old-buffer (current-buffer))
13305 (old-pos (point))
13306 (old-mode major-mode)
13307 ext cmd)
13308 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13309 (setq ext (match-string 1 dfile))
13310 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13311 (setq ext (match-string 1 dfile))))
13312 (if in-emacs
13313 (setq cmd 'emacs)
13314 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13315 (and dirp (cdr (assoc 'directory apps)))
13316 (cdr (assoc ext apps))
13317 (cdr (assoc t apps)))))
13318 (when (eq cmd 'mailcap)
13319 (require 'mailcap)
13320 (mailcap-parse-mailcaps)
13321 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13322 (command (mailcap-mime-info mime-type)))
13323 (if (stringp command)
13324 (setq cmd command)
13325 (setq cmd 'emacs))))
13326 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13327 (not (file-exists-p file))
13328 (not org-open-non-existing-files))
13329 (error "No such file: %s" file))
13330 (cond
13331 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13332 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13333 (while (string-match "['\"]%s['\"]" cmd)
13334 (setq cmd (replace-match "%s" t t cmd)))
13335 (while (string-match "%s" cmd)
13336 (setq cmd (replace-match
13337 (save-match-data (shell-quote-argument file))
13338 t t cmd)))
13339 (save-window-excursion
13340 (start-process-shell-command cmd nil cmd)))
13341 ((or (stringp cmd)
13342 (eq cmd 'emacs))
13343 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13344 (widen)
13345 (if line (goto-line line)
13346 (if search (org-link-search search))))
13347 ((consp cmd)
13348 (eval cmd))
13349 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13350 (and (org-mode-p) (eq old-mode 'org-mode)
13351 (or (not (equal old-buffer (current-buffer)))
13352 (not (equal old-pos (point))))
13353 (org-mark-ring-push old-pos old-buffer))))
13355 (defun org-default-apps ()
13356 "Return the default applications for this operating system."
13357 (cond
13358 ((eq system-type 'darwin)
13359 org-file-apps-defaults-macosx)
13360 ((eq system-type 'windows-nt)
13361 org-file-apps-defaults-windowsnt)
13362 (t org-file-apps-defaults-gnu)))
13364 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13365 (defun org-file-remote-p (file)
13366 "Test whether FILE specifies a location on a remote system.
13367 Return non-nil if the location is indeed remote.
13369 For example, the filename \"/user@host:/foo\" specifies a location
13370 on the system \"/user@host:\"."
13371 (cond ((fboundp 'file-remote-p)
13372 (file-remote-p file))
13373 ((fboundp 'tramp-handle-file-remote-p)
13374 (tramp-handle-file-remote-p file))
13375 ((and (boundp 'ange-ftp-name-format)
13376 (string-match (car ange-ftp-name-format) file))
13378 (t nil)))
13381 ;;;; Hooks for remember.el, and refiling
13383 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13384 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13386 ;;;###autoload
13387 (defun org-remember-insinuate ()
13388 "Setup remember.el for use wiht Org-mode."
13389 (require 'remember)
13390 (setq remember-annotation-functions '(org-remember-annotation))
13391 (setq remember-handler-functions '(org-remember-handler))
13392 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13394 ;;;###autoload
13395 (defun org-remember-annotation ()
13396 "Return a link to the current location as an annotation for remember.el.
13397 If you are using Org-mode files as target for data storage with
13398 remember.el, then the annotations should include a link compatible with the
13399 conventions in Org-mode. This function returns such a link."
13400 (org-store-link nil))
13402 (defconst org-remember-help
13403 "Select a destination location for the note.
13404 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13405 RET on headline -> Store as sublevel entry to current headline
13406 RET at beg-of-buf -> Append to file as level 2 headline
13407 <left>/<right> -> before/after current headline, same headings level")
13409 (defvar org-remember-previous-location nil)
13410 (defvar org-force-remember-template-char) ;; dynamically scoped
13412 (defun org-select-remember-template (&optional use-char)
13413 (when org-remember-templates
13414 (let* ((templates (mapcar (lambda (x)
13415 (if (stringp (car x))
13416 (append (list (nth 1 x) (car x)) (cddr x))
13417 (append (list (car x) "") (cdr x))))
13418 org-remember-templates))
13419 (char (or use-char
13420 (cond
13421 ((= (length templates) 1)
13422 (caar templates))
13423 ((and (boundp 'org-force-remember-template-char)
13424 org-force-remember-template-char)
13425 (if (stringp org-force-remember-template-char)
13426 (string-to-char org-force-remember-template-char)
13427 org-force-remember-template-char))
13429 (message "Select template: %s"
13430 (mapconcat
13431 (lambda (x)
13432 (cond
13433 ((not (string-match "\\S-" (nth 1 x)))
13434 (format "[%c]" (car x)))
13435 ((equal (downcase (car x))
13436 (downcase (aref (nth 1 x) 0)))
13437 (format "[%c]%s" (car x)
13438 (substring (nth 1 x) 1)))
13439 (t (format "[%c]%s" (car x) (nth 1 x)))))
13440 templates " "))
13441 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13442 (when (equal char0 ?\C-g)
13443 (jump-to-register remember-register)
13444 (kill-buffer remember-buffer))
13445 char0))))))
13446 (cddr (assoc char templates)))))
13448 (defvar x-last-selected-text)
13449 (defvar x-last-selected-text-primary)
13451 ;;;###autoload
13452 (defun org-remember-apply-template (&optional use-char skip-interactive)
13453 "Initialize *remember* buffer with template, invoke `org-mode'.
13454 This function should be placed into `remember-mode-hook' and in fact requires
13455 to be run from that hook to function properly."
13456 (if org-remember-templates
13457 (let* ((entry (org-select-remember-template use-char))
13458 (tpl (car entry))
13459 (plist-p (if org-store-link-plist t nil))
13460 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13461 (string-match "\\S-" (nth 1 entry)))
13462 (nth 1 entry)
13463 org-default-notes-file))
13464 (headline (nth 2 entry))
13465 (v-c (or (and (eq window-system 'x)
13466 (fboundp 'x-cut-buffer-or-selection-value)
13467 (x-cut-buffer-or-selection-value))
13468 (org-bound-and-true-p x-last-selected-text)
13469 (org-bound-and-true-p x-last-selected-text-primary)
13470 (and (> (length kill-ring) 0) (current-kill 0))))
13471 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13472 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13473 (v-u (concat "[" (substring v-t 1 -1) "]"))
13474 (v-U (concat "[" (substring v-T 1 -1) "]"))
13475 ;; `initial' and `annotation' are bound in `remember'
13476 (v-i (if (boundp 'initial) initial))
13477 (v-a (if (and (boundp 'annotation) annotation)
13478 (if (equal annotation "[[]]") "" annotation)
13479 ""))
13480 (v-A (if (and v-a
13481 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13482 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13483 v-a))
13484 (v-n user-full-name)
13485 (org-startup-folded nil)
13486 org-time-was-given org-end-time-was-given x
13487 prompt completions char time pos default histvar)
13488 (setq org-store-link-plist
13489 (append (list :annotation v-a :initial v-i)
13490 org-store-link-plist))
13491 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13492 (erase-buffer)
13493 (insert (substitute-command-keys
13494 (format
13495 "## Filing location: Select interactively, default, or last used:
13496 ## %s to select file and header location interactively.
13497 ## %s \"%s\" -> \"* %s\"
13498 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13499 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13500 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13501 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13502 (abbreviate-file-name (or file org-default-notes-file))
13503 (or headline "")
13504 (or (car org-remember-previous-location) "???")
13505 (or (cdr org-remember-previous-location) "???"))))
13506 (insert tpl) (goto-char (point-min))
13507 ;; Simple %-escapes
13508 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13509 (when (and initial (equal (match-string 0) "%i"))
13510 (save-match-data
13511 (let* ((lead (buffer-substring
13512 (point-at-bol) (match-beginning 0))))
13513 (setq v-i (mapconcat 'identity
13514 (org-split-string initial "\n")
13515 (concat "\n" lead))))))
13516 (replace-match
13517 (or (eval (intern (concat "v-" (match-string 1)))) "")
13518 t t))
13520 ;; %[] Insert contents of a file.
13521 (goto-char (point-min))
13522 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13523 (let ((start (match-beginning 0))
13524 (end (match-end 0))
13525 (filename (expand-file-name (match-string 1))))
13526 (goto-char start)
13527 (delete-region start end)
13528 (condition-case error
13529 (insert-file-contents filename)
13530 (error (insert (format "%%![Couldn't insert %s: %s]"
13531 filename error))))))
13532 ;; %() embedded elisp
13533 (goto-char (point-min))
13534 (while (re-search-forward "%\\((.+)\\)" nil t)
13535 (goto-char (match-beginning 0))
13536 (let ((template-start (point)))
13537 (forward-char 1)
13538 (let ((result
13539 (condition-case error
13540 (eval (read (current-buffer)))
13541 (error (format "%%![Error: %s]" error)))))
13542 (delete-region template-start (point))
13543 (insert result))))
13545 ;; From the property list
13546 (when plist-p
13547 (goto-char (point-min))
13548 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13549 (and (setq x (or (plist-get org-store-link-plist
13550 (intern (match-string 1))) ""))
13551 (replace-match x t t))))
13553 ;; Turn on org-mode in the remember buffer, set local variables
13554 (org-mode)
13555 (org-set-local 'org-finish-function 'org-remember-finalize)
13556 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13557 (org-set-local 'org-default-notes-file file))
13558 (if (and headline (stringp headline) (string-match "\\S-" headline))
13559 (org-set-local 'org-remember-default-headline headline))
13560 ;; Interactive template entries
13561 (goto-char (point-min))
13562 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13563 (setq char (if (match-end 3) (match-string 3))
13564 prompt (if (match-end 2) (match-string 2)))
13565 (goto-char (match-beginning 0))
13566 (replace-match "")
13567 (setq completions nil default nil)
13568 (when prompt
13569 (setq completions (org-split-string prompt "|")
13570 prompt (pop completions)
13571 default (car completions)
13572 histvar (intern (concat
13573 "org-remember-template-prompt-history::"
13574 (or prompt "")))
13575 completions (mapcar 'list completions)))
13576 (cond
13577 ((member char '("G" "g"))
13578 (let* ((org-last-tags-completion-table
13579 (org-global-tags-completion-table
13580 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13581 (org-add-colon-after-tag-completion t)
13582 (ins (completing-read
13583 (if prompt (concat prompt ": ") "Tags: ")
13584 'org-tags-completion-function nil nil nil
13585 'org-tags-history)))
13586 (setq ins (mapconcat 'identity
13587 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13588 ":"))
13589 (when (string-match "\\S-" ins)
13590 (or (equal (char-before) ?:) (insert ":"))
13591 (insert ins)
13592 (or (equal (char-after) ?:) (insert ":")))))
13593 (char
13594 (setq org-time-was-given (equal (upcase char) char))
13595 (setq time (org-read-date (equal (upcase char) "U") t nil
13596 prompt))
13597 (org-insert-time-stamp time org-time-was-given
13598 (member char '("u" "U"))
13599 nil nil (list org-end-time-was-given)))
13601 (insert (org-completing-read
13602 (concat (if prompt prompt "Enter string")
13603 (if default (concat " [" default "]"))
13604 ": ")
13605 completions nil nil nil histvar default)))))
13606 (goto-char (point-min))
13607 (if (re-search-forward "%\\?" nil t)
13608 (replace-match "")
13609 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13610 (org-mode)
13611 (org-set-local 'org-finish-function 'org-remember-finalize))
13612 (when (save-excursion
13613 (goto-char (point-min))
13614 (re-search-forward "%!" nil t))
13615 (replace-match "")
13616 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13618 (defun org-remember-finish-immediately ()
13619 "File remember note immediately.
13620 This should be run in `post-command-hook' and will remove itself
13621 from that hook."
13622 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13623 (when org-finish-function
13624 (funcall org-finish-function)))
13626 (defvar org-clock-marker) ; Defined below
13627 (defun org-remember-finalize ()
13628 "Finalize the remember process."
13629 (unless (fboundp 'remember-finalize)
13630 (defalias 'remember-finalize 'remember-buffer))
13631 (when (and org-clock-marker
13632 (equal (marker-buffer org-clock-marker) (current-buffer)))
13633 ;; FIXME: test this, this is w/o notetaking!
13634 (let (org-log-done) (org-clock-out)))
13635 (when buffer-file-name
13636 (save-buffer)
13637 (setq buffer-file-name nil))
13638 (remember-finalize))
13640 ;;;###autoload
13641 (defun org-remember (&optional goto org-force-remember-template-char)
13642 "Call `remember'. If this is already a remember buffer, re-apply template.
13643 If there is an active region, make sure remember uses it as initial content
13644 of the remember buffer.
13646 When called interactively with a `C-u' prefix argument GOTO, don't remember
13647 anything, just go to the file/headline where the selected template usually
13648 stores its notes. With a double prefix arg `C-u C-u', go to the last
13649 note stored by remember.
13651 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13652 associated with a template in `org-remember-templates'."
13653 (interactive "P")
13654 (cond
13655 ((equal goto '(4)) (org-go-to-remember-target))
13656 ((equal goto '(16)) (org-remember-goto-last-stored))
13658 (if (memq org-finish-function '(remember-buffer remember-finalize))
13659 (progn
13660 (when (< (length org-remember-templates) 2)
13661 (error "No other template available"))
13662 (erase-buffer)
13663 (let ((annotation (plist-get org-store-link-plist :annotation))
13664 (initial (plist-get org-store-link-plist :initial)))
13665 (org-remember-apply-template))
13666 (message "Press C-c C-c to remember data"))
13667 (if (org-region-active-p)
13668 (remember (buffer-substring (point) (mark)))
13669 (call-interactively 'remember))))))
13671 (defun org-remember-goto-last-stored ()
13672 "Go to the location where the last remember note was stored."
13673 (interactive)
13674 (bookmark-jump "org-remember-last-stored")
13675 (message "This is the last note stored by remember"))
13677 (defun org-go-to-remember-target (&optional template-key)
13678 "Go to the target location of a remember template.
13679 The user is queried for the template."
13680 (interactive)
13681 (let* ((entry (org-select-remember-template template-key))
13682 (file (nth 1 entry))
13683 (heading (nth 2 entry))
13684 visiting)
13685 (unless (and file (stringp file) (string-match "\\S-" file))
13686 (setq file org-default-notes-file))
13687 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13688 (setq heading org-remember-default-headline))
13689 (setq visiting (org-find-base-buffer-visiting file))
13690 (if (not visiting) (find-file-noselect file))
13691 (switch-to-buffer (or visiting (get-file-buffer file)))
13692 (widen)
13693 (goto-char (point-min))
13694 (if (re-search-forward
13695 (concat "^\\*+[ \t]+" (regexp-quote heading)
13696 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13697 nil t)
13698 (goto-char (match-beginning 0))
13699 (error "Target headline not found: %s" heading))))
13701 (defvar org-note-abort nil) ; dynamically scoped
13703 ;;;###autoload
13704 (defun org-remember-handler ()
13705 "Store stuff from remember.el into an org file.
13706 First prompts for an org file. If the user just presses return, the value
13707 of `org-default-notes-file' is used.
13708 Then the command offers the headings tree of the selected file in order to
13709 file the text at a specific location.
13710 You can either immediately press RET to get the note appended to the
13711 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13712 find a better place. Then press RET or <left> or <right> in insert the note.
13714 Key Cursor position Note gets inserted
13715 -----------------------------------------------------------------------------
13716 RET buffer-start as level 1 heading at end of file
13717 RET on headline as sublevel of the heading at cursor
13718 RET no heading at cursor position, level taken from context.
13719 Or use prefix arg to specify level manually.
13720 <left> on headline as same level, before current heading
13721 <right> on headline as same level, after current heading
13723 So the fastest way to store the note is to press RET RET to append it to
13724 the default file. This way your current train of thought is not
13725 interrupted, in accordance with the principles of remember.el.
13726 You can also get the fast execution without prompting by using
13727 C-u C-c C-c to exit the remember buffer. See also the variable
13728 `org-remember-store-without-prompt'.
13730 Before being stored away, the function ensures that the text has a
13731 headline, i.e. a first line that starts with a \"*\". If not, a headline
13732 is constructed from the current date and some additional data.
13734 If the variable `org-adapt-indentation' is non-nil, the entire text is
13735 also indented so that it starts in the same column as the headline
13736 \(i.e. after the stars).
13738 See also the variable `org-reverse-note-order'."
13739 (goto-char (point-min))
13740 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13741 (replace-match ""))
13742 (goto-char (point-max))
13743 (beginning-of-line 1)
13744 (while (looking-at "[ \t]*$\\|##.*")
13745 (delete-region (1- (point)) (point-max))
13746 (beginning-of-line 1))
13747 (catch 'quit
13748 (if org-note-abort (throw 'quit nil))
13749 (let* ((txt (buffer-substring (point-min) (point-max)))
13750 (fastp (org-xor (equal current-prefix-arg '(4))
13751 org-remember-store-without-prompt))
13752 (file (cond
13753 (fastp org-default-notes-file)
13754 ((and (eq org-remember-interactive-interface 'refile)
13755 org-refile-targets)
13756 org-default-notes-file)
13757 ((not (and (equal current-prefix-arg '(16))
13758 org-remember-previous-location))
13759 (org-get-org-file))))
13760 (heading org-remember-default-headline)
13761 (visiting (and file (org-find-base-buffer-visiting file)))
13762 (org-startup-folded nil)
13763 (org-startup-align-all-tables nil)
13764 (org-goto-start-pos 1)
13765 spos exitcmd level indent reversed)
13766 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13767 (setq file (car org-remember-previous-location)
13768 heading (cdr org-remember-previous-location)
13769 fastp t))
13770 (setq current-prefix-arg nil)
13771 (if (string-match "[ \t\n]+\\'" txt)
13772 (setq txt (replace-match "" t t txt)))
13773 ;; Modify text so that it becomes a nice subtree which can be inserted
13774 ;; into an org tree.
13775 (let* ((lines (split-string txt "\n"))
13776 first)
13777 (setq first (car lines) lines (cdr lines))
13778 (if (string-match "^\\*+ " first)
13779 ;; Is already a headline
13780 (setq indent nil)
13781 ;; We need to add a headline: Use time and first buffer line
13782 (setq lines (cons first lines)
13783 first (concat "* " (current-time-string)
13784 " (" (remember-buffer-desc) ")")
13785 indent " "))
13786 (if (and org-adapt-indentation indent)
13787 (setq lines (mapcar
13788 (lambda (x)
13789 (if (string-match "\\S-" x)
13790 (concat indent x) x))
13791 lines)))
13792 (setq txt (concat first "\n"
13793 (mapconcat 'identity lines "\n"))))
13794 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13795 (setq txt (replace-match "\n\n" t t txt))
13796 (if (string-match "[ \t\n]*\\'" txt)
13797 (setq txt (replace-match "\n" t t txt))))
13798 ;; Put the modified text back into the remember buffer, for refile.
13799 (erase-buffer)
13800 (insert txt)
13801 (goto-char (point-min))
13802 (when (and (eq org-remember-interactive-interface 'refile)
13803 (not fastp))
13804 (org-refile nil (or visiting (find-file-noselect file)))
13805 (throw 'quit t))
13806 ;; Find the file
13807 (if (not visiting) (find-file-noselect file))
13808 (with-current-buffer (or visiting (get-file-buffer file))
13809 (unless (org-mode-p)
13810 (error "Target files for remember notes must be in Org-mode"))
13811 (save-excursion
13812 (save-restriction
13813 (widen)
13814 (and (goto-char (point-min))
13815 (not (re-search-forward "^\\* " nil t))
13816 (insert "\n* " (or heading "Notes") "\n"))
13817 (setq reversed (org-notes-order-reversed-p))
13819 ;; Find the default location
13820 (when (and heading (stringp heading) (string-match "\\S-" heading))
13821 (goto-char (point-min))
13822 (if (re-search-forward
13823 (concat "^\\*+[ \t]+" (regexp-quote heading)
13824 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13825 nil t)
13826 (setq org-goto-start-pos (match-beginning 0))
13827 (when fastp
13828 (goto-char (point-max))
13829 (unless (bolp) (newline))
13830 (insert "* " heading "\n")
13831 (setq org-goto-start-pos (point-at-bol 0)))))
13833 ;; Ask the User for a location, using the appropriate interface
13834 (cond
13835 (fastp (setq spos org-goto-start-pos
13836 exitcmd 'return))
13837 ((eq org-remember-interactive-interface 'outline)
13838 (setq spos (org-get-location (current-buffer)
13839 org-remember-help)
13840 exitcmd (cdr spos)
13841 spos (car spos)))
13842 ((eq org-remember-interactive-interface 'outline-path-completion)
13843 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13844 (org-refile-use-outline-path t))
13845 (setq spos (org-refile-get-location "Heading: ")
13846 exitcmd 'return
13847 spos (nth 3 spos))))
13848 (t (error "this should not hapen")))
13849 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13850 ; not handle this note
13851 (goto-char spos)
13852 (cond ((org-on-heading-p t)
13853 (org-back-to-heading t)
13854 (setq level (funcall outline-level))
13855 (cond
13856 ((eq exitcmd 'return)
13857 ;; sublevel of current
13858 (setq org-remember-previous-location
13859 (cons (abbreviate-file-name file)
13860 (org-get-heading 'notags)))
13861 (if reversed
13862 (outline-next-heading)
13863 (org-end-of-subtree t)
13864 (if (not (bolp))
13865 (if (looking-at "[ \t]*\n")
13866 (beginning-of-line 2)
13867 (end-of-line 1)
13868 (insert "\n"))))
13869 (bookmark-set "org-remember-last-stored")
13870 (org-paste-subtree (org-get-legal-level level 1) txt))
13871 ((eq exitcmd 'left)
13872 ;; before current
13873 (bookmark-set "org-remember-last-stored")
13874 (org-paste-subtree level txt))
13875 ((eq exitcmd 'right)
13876 ;; after current
13877 (org-end-of-subtree t)
13878 (bookmark-set "org-remember-last-stored")
13879 (org-paste-subtree level txt))
13880 (t (error "This should not happen"))))
13882 ((and (bobp) (not reversed))
13883 ;; Put it at the end, one level below level 1
13884 (save-restriction
13885 (widen)
13886 (goto-char (point-max))
13887 (if (not (bolp)) (newline))
13888 (bookmark-set "org-remember-last-stored")
13889 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13891 ((and (bobp) reversed)
13892 ;; Put it at the start, as level 1
13893 (save-restriction
13894 (widen)
13895 (goto-char (point-min))
13896 (re-search-forward "^\\*+ " nil t)
13897 (beginning-of-line 1)
13898 (bookmark-set "org-remember-last-stored")
13899 (org-paste-subtree 1 txt)))
13901 ;; Put it right there, with automatic level determined by
13902 ;; org-paste-subtree or from prefix arg
13903 (bookmark-set "org-remember-last-stored")
13904 (org-paste-subtree
13905 (if (numberp current-prefix-arg) current-prefix-arg)
13906 txt)))
13907 (when remember-save-after-remembering
13908 (save-buffer)
13909 (if (not visiting) (kill-buffer (current-buffer)))))))))
13911 t) ;; return t to indicate that we took care of this note.
13913 (defun org-get-org-file ()
13914 "Read a filename, with default directory `org-directory'."
13915 (let ((default (or org-default-notes-file remember-data-file)))
13916 (read-file-name (format "File name [%s]: " default)
13917 (file-name-as-directory org-directory)
13918 default)))
13920 (defun org-notes-order-reversed-p ()
13921 "Check if the current file should receive notes in reversed order."
13922 (cond
13923 ((not org-reverse-note-order) nil)
13924 ((eq t org-reverse-note-order) t)
13925 ((not (listp org-reverse-note-order)) nil)
13926 (t (catch 'exit
13927 (let ((all org-reverse-note-order)
13928 entry)
13929 (while (setq entry (pop all))
13930 (if (string-match (car entry) buffer-file-name)
13931 (throw 'exit (cdr entry))))
13932 nil)))))
13934 ;;; Refiling
13936 (defvar org-refile-target-table nil
13937 "The list of refile targets, created by `org-refile'.")
13939 (defvar org-agenda-new-buffers nil
13940 "Buffers created to visit agenda files.")
13942 (defun org-get-refile-targets (&optional default-buffer)
13943 "Produce a table with refile targets."
13944 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13945 targets txt re files f desc descre)
13946 (with-current-buffer (or default-buffer (current-buffer))
13947 (while (setq entry (pop entries))
13948 (setq files (car entry) desc (cdr entry))
13949 (cond
13950 ((null files) (setq files (list (current-buffer))))
13951 ((eq files 'org-agenda-files)
13952 (setq files (org-agenda-files 'unrestricted)))
13953 ((and (symbolp files) (fboundp files))
13954 (setq files (funcall files)))
13955 ((and (symbolp files) (boundp files))
13956 (setq files (symbol-value files))))
13957 (if (stringp files) (setq files (list files)))
13958 (cond
13959 ((eq (car desc) :tag)
13960 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13961 ((eq (car desc) :todo)
13962 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13963 ((eq (car desc) :regexp)
13964 (setq descre (cdr desc)))
13965 ((eq (car desc) :level)
13966 (setq descre (concat "^\\*\\{" (number-to-string
13967 (if org-odd-levels-only
13968 (1- (* 2 (cdr desc)))
13969 (cdr desc)))
13970 "\\}[ \t]")))
13971 ((eq (car desc) :maxlevel)
13972 (setq descre (concat "^\\*\\{1," (number-to-string
13973 (if org-odd-levels-only
13974 (1- (* 2 (cdr desc)))
13975 (cdr desc)))
13976 "\\}[ \t]")))
13977 (t (error "Bad refiling target description %s" desc)))
13978 (while (setq f (pop files))
13979 (save-excursion
13980 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13981 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13982 (save-excursion
13983 (save-restriction
13984 (widen)
13985 (goto-char (point-min))
13986 (while (re-search-forward descre nil t)
13987 (goto-char (point-at-bol))
13988 (when (looking-at org-complex-heading-regexp)
13989 (setq txt (match-string 4)
13990 re (concat "^" (regexp-quote
13991 (buffer-substring (match-beginning 1)
13992 (match-end 4)))))
13993 (if (match-end 5) (setq re (concat re "[ \t]+"
13994 (regexp-quote
13995 (match-string 5)))))
13996 (setq re (concat re "[ \t]*$"))
13997 (when org-refile-use-outline-path
13998 (setq txt (mapconcat 'identity
13999 (append
14000 (if (eq org-refile-use-outline-path 'file)
14001 (list (file-name-nondirectory
14002 (buffer-file-name (buffer-base-buffer))))
14003 (if (eq org-refile-use-outline-path 'full-file-path)
14004 (list (buffer-file-name (buffer-base-buffer)))))
14005 (org-get-outline-path)
14006 (list txt))
14007 "/")))
14008 (push (list txt f re (point)) targets))
14009 (goto-char (point-at-eol))))))))
14010 (nreverse targets))))
14012 (defun org-get-outline-path ()
14013 "Return the outline path to the current entry, as a list."
14014 (let (rtn)
14015 (save-excursion
14016 (while (org-up-heading-safe)
14017 (when (looking-at org-complex-heading-regexp)
14018 (push (org-match-string-no-properties 4) rtn)))
14019 rtn)))
14021 (defvar org-refile-history nil
14022 "History for refiling operations.")
14024 (defun org-refile (&optional goto default-buffer)
14025 "Move the entry at point to another heading.
14026 The list of target headings is compiled using the information in
14027 `org-refile-targets', which see. This list is created upon first use, and
14028 you can update it by calling this command with a double prefix (`C-u C-u').
14029 FIXME: Can we find a better way of updating?
14031 At the target location, the entry is filed as a subitem of the target heading.
14032 Depending on `org-reverse-note-order', the new subitem will either be the
14033 first of the last subitem.
14035 With prefix arg GOTO, the command will only visit the target location,
14036 not actually move anything.
14037 With a double prefix `C-c C-c', go to the location where the last refiling
14038 operation has put the subtree.
14040 With a double prefix argument, the command can be used to jump to any
14041 heading in the current buffer."
14042 (interactive "P")
14043 (let* ((cbuf (current-buffer))
14044 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14045 (fname (and filename (file-truename filename)))
14046 pos it nbuf file re level reversed)
14047 (if (equal goto '(16))
14048 (org-refile-goto-last-stored)
14049 (when (setq it (org-refile-get-location
14050 (if goto "Goto: " "Refile to: ") default-buffer))
14051 (setq file (nth 1 it)
14052 re (nth 2 it)
14053 pos (nth 3 it))
14054 (setq nbuf (or (find-buffer-visiting file)
14055 (find-file-noselect file)))
14056 (if goto
14057 (progn
14058 (switch-to-buffer nbuf)
14059 (goto-char pos)
14060 (org-show-context 'org-goto))
14061 (org-copy-special)
14062 (save-excursion
14063 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14064 (find-file-noselect file))))
14065 (setq reversed (org-notes-order-reversed-p))
14066 (save-excursion
14067 (save-restriction
14068 (widen)
14069 (goto-char pos)
14070 (looking-at outline-regexp)
14071 (setq level (org-get-legal-level (funcall outline-level) 1))
14072 (goto-char
14073 (if reversed
14074 (outline-next-heading)
14075 (or (save-excursion (outline-get-next-sibling))
14076 (org-end-of-subtree t t)
14077 (point-max))))
14078 (bookmark-set "org-refile-last-stored")
14079 (org-paste-subtree level))))
14080 (org-cut-special)
14081 (message "Entry refiled to \"%s\"" (car it)))))))
14083 (defun org-refile-goto-last-stored ()
14084 "Go to the location where the last refile was stored."
14085 (interactive)
14086 (bookmark-jump "org-refile-last-stored")
14087 (message "This is the location of the last refile"))
14089 (defun org-refile-get-location (&optional prompt default-buffer)
14090 "Prompt the user for a refile location, using PROMPT."
14091 (let ((org-refile-targets org-refile-targets)
14092 (org-refile-use-outline-path org-refile-use-outline-path))
14093 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14094 (unless org-refile-target-table
14095 (error "No refile targets"))
14096 (let* ((cbuf (current-buffer))
14097 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14098 (fname (and filename (file-truename filename)))
14099 (tbl (mapcar
14100 (lambda (x)
14101 (if (not (equal fname (file-truename (nth 1 x))))
14102 (cons (concat (car x) " (" (file-name-nondirectory
14103 (nth 1 x)) ")")
14104 (cdr x))
14106 org-refile-target-table))
14107 (completion-ignore-case t)
14108 pos it nbuf file re level reversed)
14109 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14110 tbl)))
14112 ;;;; Dynamic blocks
14114 (defun org-find-dblock (name)
14115 "Find the first dynamic block with name NAME in the buffer.
14116 If not found, stay at current position and return nil."
14117 (let (pos)
14118 (save-excursion
14119 (goto-char (point-min))
14120 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14121 nil t)
14122 (match-beginning 0))))
14123 (if pos (goto-char pos))
14124 pos))
14126 (defconst org-dblock-start-re
14127 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14128 "Matches the startline of a dynamic block, with parameters.")
14130 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14131 "Matches the end of a dyhamic block.")
14133 (defun org-create-dblock (plist)
14134 "Create a dynamic block section, with parameters taken from PLIST.
14135 PLIST must containe a :name entry which is used as name of the block."
14136 (unless (bolp) (newline))
14137 (let ((name (plist-get plist :name)))
14138 (insert "#+BEGIN: " name)
14139 (while plist
14140 (if (eq (car plist) :name)
14141 (setq plist (cddr plist))
14142 (insert " " (prin1-to-string (pop plist)))))
14143 (insert "\n\n#+END:\n")
14144 (beginning-of-line -2)))
14146 (defun org-prepare-dblock ()
14147 "Prepare dynamic block for refresh.
14148 This empties the block, puts the cursor at the insert position and returns
14149 the property list including an extra property :name with the block name."
14150 (unless (looking-at org-dblock-start-re)
14151 (error "Not at a dynamic block"))
14152 (let* ((begdel (1+ (match-end 0)))
14153 (name (org-no-properties (match-string 1)))
14154 (params (append (list :name name)
14155 (read (concat "(" (match-string 3) ")")))))
14156 (unless (re-search-forward org-dblock-end-re nil t)
14157 (error "Dynamic block not terminated"))
14158 (delete-region begdel (match-beginning 0))
14159 (goto-char begdel)
14160 (open-line 1)
14161 params))
14163 (defun org-map-dblocks (&optional command)
14164 "Apply COMMAND to all dynamic blocks in the current buffer.
14165 If COMMAND is not given, use `org-update-dblock'."
14166 (let ((cmd (or command 'org-update-dblock))
14167 pos)
14168 (save-excursion
14169 (goto-char (point-min))
14170 (while (re-search-forward org-dblock-start-re nil t)
14171 (goto-char (setq pos (match-beginning 0)))
14172 (condition-case nil
14173 (funcall cmd)
14174 (error (message "Error during update of dynamic block")))
14175 (goto-char pos)
14176 (unless (re-search-forward org-dblock-end-re nil t)
14177 (error "Dynamic block not terminated"))))))
14179 (defun org-dblock-update (&optional arg)
14180 "User command for updating dynamic blocks.
14181 Update the dynamic block at point. With prefix ARG, update all dynamic
14182 blocks in the buffer."
14183 (interactive "P")
14184 (if arg
14185 (org-update-all-dblocks)
14186 (or (looking-at org-dblock-start-re)
14187 (org-beginning-of-dblock))
14188 (org-update-dblock)))
14190 (defun org-update-dblock ()
14191 "Update the dynamic block at point
14192 This means to empty the block, parse for parameters and then call
14193 the correct writing function."
14194 (save-window-excursion
14195 (let* ((pos (point))
14196 (line (org-current-line))
14197 (params (org-prepare-dblock))
14198 (name (plist-get params :name))
14199 (cmd (intern (concat "org-dblock-write:" name))))
14200 (message "Updating dynamic block `%s' at line %d..." name line)
14201 (funcall cmd params)
14202 (message "Updating dynamic block `%s' at line %d...done" name line)
14203 (goto-char pos))))
14205 (defun org-beginning-of-dblock ()
14206 "Find the beginning of the dynamic block at point.
14207 Error if there is no scuh block at point."
14208 (let ((pos (point))
14209 beg)
14210 (end-of-line 1)
14211 (if (and (re-search-backward org-dblock-start-re nil t)
14212 (setq beg (match-beginning 0))
14213 (re-search-forward org-dblock-end-re nil t)
14214 (> (match-end 0) pos))
14215 (goto-char beg)
14216 (goto-char pos)
14217 (error "Not in a dynamic block"))))
14219 (defun org-update-all-dblocks ()
14220 "Update all dynamic blocks in the buffer.
14221 This function can be used in a hook."
14222 (when (org-mode-p)
14223 (org-map-dblocks 'org-update-dblock)))
14226 ;;;; Completion
14228 (defconst org-additional-option-like-keywords
14229 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14230 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14231 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14233 (defun org-complete (&optional arg)
14234 "Perform completion on word at point.
14235 At the beginning of a headline, this completes TODO keywords as given in
14236 `org-todo-keywords'.
14237 If the current word is preceded by a backslash, completes the TeX symbols
14238 that are supported for HTML support.
14239 If the current word is preceded by \"#+\", completes special words for
14240 setting file options.
14241 In the line after \"#+STARTUP:, complete valid keywords.\"
14242 At all other locations, this simply calls the value of
14243 `org-completion-fallback-command'."
14244 (interactive "P")
14245 (org-without-partial-completion
14246 (catch 'exit
14247 (let* ((end (point))
14248 (beg1 (save-excursion
14249 (skip-chars-backward (org-re "[:alnum:]_@"))
14250 (point)))
14251 (beg (save-excursion
14252 (skip-chars-backward "a-zA-Z0-9_:$")
14253 (point)))
14254 (confirm (lambda (x) (stringp (car x))))
14255 (searchhead (equal (char-before beg) ?*))
14256 (tag (and (equal (char-before beg1) ?:)
14257 (equal (char-after (point-at-bol)) ?*)))
14258 (prop (and (equal (char-before beg1) ?:)
14259 (not (equal (char-after (point-at-bol)) ?*))))
14260 (texp (equal (char-before beg) ?\\))
14261 (link (equal (char-before beg) ?\[))
14262 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14263 beg)
14264 "#+"))
14265 (startup (string-match "^#\\+STARTUP:.*"
14266 (buffer-substring (point-at-bol) (point))))
14267 (completion-ignore-case opt)
14268 (type nil)
14269 (tbl nil)
14270 (table (cond
14271 (opt
14272 (setq type :opt)
14273 (append
14274 (mapcar
14275 (lambda (x)
14276 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14277 (cons (match-string 2 x) (match-string 1 x)))
14278 (org-split-string (org-get-current-options) "\n"))
14279 (mapcar 'list org-additional-option-like-keywords)))
14280 (startup
14281 (setq type :startup)
14282 org-startup-options)
14283 (link (append org-link-abbrev-alist-local
14284 org-link-abbrev-alist))
14285 (texp
14286 (setq type :tex)
14287 org-html-entities)
14288 ((string-match "\\`\\*+[ \t]+\\'"
14289 (buffer-substring (point-at-bol) beg))
14290 (setq type :todo)
14291 (mapcar 'list org-todo-keywords-1))
14292 (searchhead
14293 (setq type :searchhead)
14294 (save-excursion
14295 (goto-char (point-min))
14296 (while (re-search-forward org-todo-line-regexp nil t)
14297 (push (list
14298 (org-make-org-heading-search-string
14299 (match-string 3) t))
14300 tbl)))
14301 tbl)
14302 (tag (setq type :tag beg beg1)
14303 (or org-tag-alist (org-get-buffer-tags)))
14304 (prop (setq type :prop beg beg1)
14305 (mapcar 'list (org-buffer-property-keys nil t t)))
14306 (t (progn
14307 (call-interactively org-completion-fallback-command)
14308 (throw 'exit nil)))))
14309 (pattern (buffer-substring-no-properties beg end))
14310 (completion (try-completion pattern table confirm)))
14311 (cond ((eq completion t)
14312 (if (not (assoc (upcase pattern) table))
14313 (message "Already complete")
14314 (if (equal type :opt)
14315 (insert (substring (cdr (assoc (upcase pattern) table))
14316 (length pattern)))
14317 (if (memq type '(:tag :prop)) (insert ":")))))
14318 ((null completion)
14319 (message "Can't find completion for \"%s\"" pattern)
14320 (ding))
14321 ((not (string= pattern completion))
14322 (delete-region beg end)
14323 (if (string-match " +$" completion)
14324 (setq completion (replace-match "" t t completion)))
14325 (insert completion)
14326 (if (get-buffer-window "*Completions*")
14327 (delete-window (get-buffer-window "*Completions*")))
14328 (if (assoc completion table)
14329 (if (eq type :todo) (insert " ")
14330 (if (memq type '(:tag :prop)) (insert ":"))))
14331 (if (and (equal type :opt) (assoc completion table))
14332 (message "%s" (substitute-command-keys
14333 "Press \\[org-complete] again to insert example settings"))))
14335 (message "Making completion list...")
14336 (let ((list (sort (all-completions pattern table confirm)
14337 'string<)))
14338 (with-output-to-temp-buffer "*Completions*"
14339 (condition-case nil
14340 ;; Protection needed for XEmacs and emacs 21
14341 (display-completion-list list pattern)
14342 (error (display-completion-list list)))))
14343 (message "Making completion list...%s" "done")))))))
14345 ;;;; TODO, DEADLINE, Comments
14347 (defun org-toggle-comment ()
14348 "Change the COMMENT state of an entry."
14349 (interactive)
14350 (save-excursion
14351 (org-back-to-heading)
14352 (let (case-fold-search)
14353 (if (looking-at (concat outline-regexp
14354 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14355 (replace-match "" t t nil 1)
14356 (if (looking-at outline-regexp)
14357 (progn
14358 (goto-char (match-end 0))
14359 (insert org-comment-string " ")))))))
14361 (defvar org-last-todo-state-is-todo nil
14362 "This is non-nil when the last TODO state change led to a TODO state.
14363 If the last change removed the TODO tag or switched to DONE, then
14364 this is nil.")
14366 (defvar org-setting-tags nil) ; dynamically skiped
14368 ;; FIXME: better place
14369 (defun org-property-or-variable-value (var &optional inherit)
14370 "Check if there is a property fixing the value of VAR.
14371 If yes, return this value. If not, return the current value of the variable."
14372 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14373 (if (and prop (stringp prop) (string-match "\\S-" prop))
14374 (read prop)
14375 (symbol-value var))))
14377 (defun org-parse-local-options (string var)
14378 "Parse STRING for startup setting relevant for variable VAR."
14379 (let ((rtn (symbol-value var))
14380 e opts)
14381 (save-match-data
14382 (if (or (not string) (not (string-match "\\S-" string)))
14384 (setq opts (delq nil (mapcar (lambda (x)
14385 (setq e (assoc x org-startup-options))
14386 (if (eq (nth 1 e) var) e nil))
14387 (org-split-string string "[ \t]+"))))
14388 (if (not opts)
14390 (setq rtn nil)
14391 (while (setq e (pop opts))
14392 (if (not (nth 3 e))
14393 (setq rtn (nth 2 e))
14394 (if (not (listp rtn)) (setq rtn nil))
14395 (push (nth 2 e) rtn)))
14396 rtn)))))
14398 (defvar org-blocker-hook nil
14399 "Hook for functions that are allowed to block a state change.
14401 Each function gets as its single argument a property list, see
14402 `org-trigger-hook' for more information about this list.
14404 If any of the functions in this hook returns nil, the state change
14405 is blocked.")
14407 (defvar org-trigger-hook nil
14408 "Hook for functions that are triggered by a state change.
14410 Each function gets as its single argument a property list with at least
14411 the following elements:
14413 (:type type-of-change :position pos-at-entry-start
14414 :from old-state :to new-state)
14416 Depending on the type, more properties may be present.
14418 This mechanism is currently implemented for:
14420 TODO state changes
14421 ------------------
14422 :type todo-state-change
14423 :from previous state (keyword as a string), or nil
14424 :to new state (keyword as a string), or nil")
14427 (defun org-todo (&optional arg)
14428 "Change the TODO state of an item.
14429 The state of an item is given by a keyword at the start of the heading,
14430 like
14431 *** TODO Write paper
14432 *** DONE Call mom
14434 The different keywords are specified in the variable `org-todo-keywords'.
14435 By default the available states are \"TODO\" and \"DONE\".
14436 So for this example: when the item starts with TODO, it is changed to DONE.
14437 When it starts with DONE, the DONE is removed. And when neither TODO nor
14438 DONE are present, add TODO at the beginning of the heading.
14440 With C-u prefix arg, use completion to determine the new state.
14441 With numeric prefix arg, switch to that state.
14443 For calling through lisp, arg is also interpreted in the following way:
14444 'none -> empty state
14445 \"\"(empty string) -> switch to empty state
14446 'done -> switch to DONE
14447 'nextset -> switch to the next set of keywords
14448 'previousset -> switch to the previous set of keywords
14449 \"WAITING\" -> switch to the specified keyword, but only if it
14450 really is a member of `org-todo-keywords'."
14451 (interactive "P")
14452 (save-excursion
14453 (catch 'exit
14454 (org-back-to-heading)
14455 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14456 (or (looking-at (concat " +" org-todo-regexp " *"))
14457 (looking-at " *"))
14458 (let* ((match-data (match-data))
14459 (startpos (point-at-bol))
14460 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14461 (org-log-done (org-parse-local-options logging 'org-log-done))
14462 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
14463 (this (match-string 1))
14464 (hl-pos (match-beginning 0))
14465 (head (org-get-todo-sequence-head this))
14466 (ass (assoc head org-todo-kwd-alist))
14467 (interpret (nth 1 ass))
14468 (done-word (nth 3 ass))
14469 (final-done-word (nth 4 ass))
14470 (last-state (or this ""))
14471 (completion-ignore-case t)
14472 (member (member this org-todo-keywords-1))
14473 (tail (cdr member))
14474 (state (cond
14475 ((and org-todo-key-trigger
14476 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14477 (and (not arg) org-use-fast-todo-selection
14478 (not (eq org-use-fast-todo-selection 'prefix)))))
14479 ;; Use fast selection
14480 (org-fast-todo-selection))
14481 ((and (equal arg '(4))
14482 (or (not org-use-fast-todo-selection)
14483 (not org-todo-key-trigger)))
14484 ;; Read a state with completion
14485 (completing-read "State: " (mapcar (lambda(x) (list x))
14486 org-todo-keywords-1)
14487 nil t))
14488 ((eq arg 'right)
14489 (if this
14490 (if tail (car tail) nil)
14491 (car org-todo-keywords-1)))
14492 ((eq arg 'left)
14493 (if (equal member org-todo-keywords-1)
14495 (if this
14496 (nth (- (length org-todo-keywords-1) (length tail) 2)
14497 org-todo-keywords-1)
14498 (org-last org-todo-keywords-1))))
14499 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14500 (setq arg nil))) ; hack to fall back to cycling
14501 (arg
14502 ;; user or caller requests a specific state
14503 (cond
14504 ((equal arg "") nil)
14505 ((eq arg 'none) nil)
14506 ((eq arg 'done) (or done-word (car org-done-keywords)))
14507 ((eq arg 'nextset)
14508 (or (car (cdr (member head org-todo-heads)))
14509 (car org-todo-heads)))
14510 ((eq arg 'previousset)
14511 (let ((org-todo-heads (reverse org-todo-heads)))
14512 (or (car (cdr (member head org-todo-heads)))
14513 (car org-todo-heads))))
14514 ((car (member arg org-todo-keywords-1)))
14515 ((nth (1- (prefix-numeric-value arg))
14516 org-todo-keywords-1))))
14517 ((null member) (or head (car org-todo-keywords-1)))
14518 ((equal this final-done-word) nil) ;; -> make empty
14519 ((null tail) nil) ;; -> first entry
14520 ((eq interpret 'sequence)
14521 (car tail))
14522 ((memq interpret '(type priority))
14523 (if (eq this-command last-command)
14524 (car tail)
14525 (if (> (length tail) 0)
14526 (or done-word (car org-done-keywords))
14527 nil)))
14528 (t nil)))
14529 (next (if state (concat " " state " ") " "))
14530 (change-plist (list :type 'todo-state-change :from this :to state
14531 :position startpos))
14532 dostates)
14533 (when org-blocker-hook
14534 (unless (save-excursion
14535 (save-match-data
14536 (run-hook-with-args-until-failure
14537 'org-blocker-hook change-plist)))
14538 (if (interactive-p)
14539 (error "TODO state change from %s to %s blocked" this state)
14540 ;; fail silently
14541 (message "TODO state change from %s to %s blocked" this state)
14542 (throw 'exit nil))))
14543 (store-match-data match-data)
14544 (replace-match next t t)
14545 (unless (pos-visible-in-window-p hl-pos)
14546 (message "TODO state changed to %s" (org-trim next)))
14547 (unless head
14548 (setq head (org-get-todo-sequence-head state)
14549 ass (assoc head org-todo-kwd-alist)
14550 interpret (nth 1 ass)
14551 done-word (nth 3 ass)
14552 final-done-word (nth 4 ass)))
14553 (when (memq arg '(nextset previousset))
14554 (message "Keyword-Set %d/%d: %s"
14555 (- (length org-todo-sets) -1
14556 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14557 (length org-todo-sets)
14558 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14559 (setq org-last-todo-state-is-todo
14560 (not (member state org-done-keywords)))
14561 (when (and org-log-done (not (memq arg '(nextset previousset))))
14562 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
14563 (or (not org-todo-log-states)
14564 (member state org-todo-log-states))))
14566 (cond
14567 ((and state (member state org-not-done-keywords)
14568 (not (member this org-not-done-keywords)))
14569 ;; This is now a todo state and was not one before
14570 ;; Remove any CLOSED timestamp, and possibly log the state change
14571 (org-add-planning-info nil nil 'closed)
14572 (and dostates (org-add-log-maybe 'state state 'findpos)))
14573 ((and state dostates)
14574 ;; This is a non-nil state, and we need to log it
14575 (org-add-log-maybe 'state state 'findpos))
14576 ((and (member state org-done-keywords)
14577 (not (member this org-done-keywords)))
14578 ;; It is now done, and it was not done before
14579 (org-add-planning-info 'closed (org-current-time))
14580 (org-add-log-maybe 'done state 'findpos))))
14581 ;; Fixup tag positioning
14582 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14583 (run-hooks 'org-after-todo-state-change-hook)
14584 (and (member state org-done-keywords) (org-auto-repeat-maybe))
14585 (if (and arg (not (member state org-done-keywords)))
14586 (setq head (org-get-todo-sequence-head state)))
14587 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14588 ;; Fixup cursor location if close to the keyword
14589 (if (and (outline-on-heading-p)
14590 (not (bolp))
14591 (save-excursion (beginning-of-line 1)
14592 (looking-at org-todo-line-regexp))
14593 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14594 (progn
14595 (goto-char (or (match-end 2) (match-end 1)))
14596 (just-one-space)))
14597 (when org-trigger-hook
14598 (save-excursion
14599 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14601 (defun org-get-todo-sequence-head (kwd)
14602 "Return the head of the TODO sequence to which KWD belongs.
14603 If KWD is not set, check if there is a text property remembering the
14604 right sequence."
14605 (let (p)
14606 (cond
14607 ((not kwd)
14608 (or (get-text-property (point-at-bol) 'org-todo-head)
14609 (progn
14610 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14611 nil (point-at-eol)))
14612 (get-text-property p 'org-todo-head))))
14613 ((not (member kwd org-todo-keywords-1))
14614 (car org-todo-keywords-1))
14615 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14617 (defun org-fast-todo-selection ()
14618 "Fast TODO keyword selection with single keys.
14619 Returns the new TODO keyword, or nil if no state change should occur."
14620 (let* ((fulltable org-todo-key-alist)
14621 (done-keywords org-done-keywords) ;; needed for the faces.
14622 (maxlen (apply 'max (mapcar
14623 (lambda (x)
14624 (if (stringp (car x)) (string-width (car x)) 0))
14625 fulltable)))
14626 (expert nil)
14627 (fwidth (+ maxlen 3 1 3))
14628 (ncol (/ (- (window-width) 4) fwidth))
14629 tg cnt e c tbl
14630 groups ingroup)
14631 (save-window-excursion
14632 (if expert
14633 (set-buffer (get-buffer-create " *Org todo*"))
14634 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14635 (erase-buffer)
14636 (org-set-local 'org-done-keywords done-keywords)
14637 (setq tbl fulltable cnt 0)
14638 (while (setq e (pop tbl))
14639 (cond
14640 ((equal e '(:startgroup))
14641 (push '() groups) (setq ingroup t)
14642 (when (not (= cnt 0))
14643 (setq cnt 0)
14644 (insert "\n"))
14645 (insert "{ "))
14646 ((equal e '(:endgroup))
14647 (setq ingroup nil cnt 0)
14648 (insert "}\n"))
14650 (setq tg (car e) c (cdr e))
14651 (if ingroup (push tg (car groups)))
14652 (setq tg (org-add-props tg nil 'face
14653 (org-get-todo-face tg)))
14654 (if (and (= cnt 0) (not ingroup)) (insert " "))
14655 (insert "[" c "] " tg (make-string
14656 (- fwidth 4 (length tg)) ?\ ))
14657 (when (= (setq cnt (1+ cnt)) ncol)
14658 (insert "\n")
14659 (if ingroup (insert " "))
14660 (setq cnt 0)))))
14661 (insert "\n")
14662 (goto-char (point-min))
14663 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14664 (fit-window-to-buffer))
14665 (message "[a-z..]:Set [SPC]:clear")
14666 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14667 (cond
14668 ((or (= c ?\C-g)
14669 (and (= c ?q) (not (rassoc c fulltable))))
14670 (setq quit-flag t))
14671 ((= c ?\ ) nil)
14672 ((setq e (rassoc c fulltable) tg (car e))
14674 (t (setq quit-flag t))))))
14676 (defun org-get-repeat ()
14677 "Check if tere is a deadline/schedule with repeater in this entry."
14678 (save-match-data
14679 (save-excursion
14680 (org-back-to-heading t)
14681 (if (re-search-forward
14682 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14683 (match-string 1)))))
14685 (defvar org-last-changed-timestamp)
14686 (defvar org-log-post-message)
14687 (defun org-auto-repeat-maybe ()
14688 "Check if the current headline contains a repeated deadline/schedule.
14689 If yes, set TODO state back to what it was and change the base date
14690 of repeating deadline/scheduled time stamps to new date.
14691 This function should be run in the `org-after-todo-state-change-hook'."
14692 ;; last-state is dynamically scoped into this function
14693 (let* ((repeat (org-get-repeat))
14694 (aa (assoc last-state org-todo-kwd-alist))
14695 (interpret (nth 1 aa))
14696 (head (nth 2 aa))
14697 (done-word (nth 3 aa))
14698 (whata '(("d" . day) ("m" . month) ("y" . year)))
14699 (msg "Entry repeats: ")
14700 (org-log-done)
14701 re type n what ts)
14702 (when repeat
14703 (org-todo (if (eq interpret 'type) last-state head))
14704 (when (and org-log-repeat
14705 (not (memq 'org-add-log-note
14706 (default-value 'post-command-hook))))
14707 ;; Make sure a note is taken
14708 (let ((org-log-done '(done)))
14709 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
14710 'findpos)))
14711 (org-back-to-heading t)
14712 (org-add-planning-info nil nil 'closed)
14713 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14714 org-deadline-time-regexp "\\)\\|\\("
14715 org-ts-regexp "\\)"))
14716 (while (re-search-forward
14717 re (save-excursion (outline-next-heading) (point)) t)
14718 (setq type (if (match-end 1) org-scheduled-string
14719 (if (match-end 3) org-deadline-string "Plain:"))
14720 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14721 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14722 (setq n (string-to-number (match-string 1 ts))
14723 what (match-string 2 ts))
14724 (if (equal what "w") (setq n (* n 7) what "d"))
14725 (org-timestamp-change n (cdr (assoc what whata)))
14726 (setq msg (concat msg type org-last-changed-timestamp " "))))
14727 (setq org-log-post-message msg)
14728 (message "%s" msg))))
14730 (defun org-show-todo-tree (arg)
14731 "Make a compact tree which shows all headlines marked with TODO.
14732 The tree will show the lines where the regexp matches, and all higher
14733 headlines above the match.
14734 With \\[universal-argument] prefix, also show the DONE entries.
14735 With a numeric prefix N, construct a sparse tree for the Nth element
14736 of `org-todo-keywords-1'."
14737 (interactive "P")
14738 (let ((case-fold-search nil)
14739 (kwd-re
14740 (cond ((null arg) org-not-done-regexp)
14741 ((equal arg '(4))
14742 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14743 (mapcar 'list org-todo-keywords-1))))
14744 (concat "\\("
14745 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14746 "\\)\\>")))
14747 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14748 (regexp-quote (nth (1- (prefix-numeric-value arg))
14749 org-todo-keywords-1)))
14750 (t (error "Invalid prefix argument: %s" arg)))))
14751 (message "%d TODO entries found"
14752 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14754 (defun org-deadline (&optional remove)
14755 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14756 With argument REMOVE, remove any deadline from the item."
14757 (interactive "P")
14758 (if remove
14759 (progn
14760 (org-remove-timestamp-with-keyword org-deadline-string)
14761 (message "Item no longer has a deadline."))
14762 (org-add-planning-info 'deadline nil 'closed)))
14764 (defun org-schedule (&optional remove)
14765 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14766 With argument REMOVE, remove any scheduling date from the item."
14767 (interactive "P")
14768 (if remove
14769 (progn
14770 (org-remove-timestamp-with-keyword org-scheduled-string)
14771 (message "Item is no longer scheduled."))
14772 (org-add-planning-info 'scheduled nil 'closed)))
14774 (defun org-remove-timestamp-with-keyword (keyword)
14775 "Remove all time stamps with KEYWORD in the current entry."
14776 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14777 beg)
14778 (save-excursion
14779 (org-back-to-heading t)
14780 (setq beg (point))
14781 (org-end-of-subtree t t)
14782 (while (re-search-backward re beg t)
14783 (replace-match "")
14784 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14785 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14787 (defun org-add-planning-info (what &optional time &rest remove)
14788 "Insert new timestamp with keyword in the line directly after the headline.
14789 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14790 If non is given, the user is prompted for a date.
14791 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14792 be removed."
14793 (interactive)
14794 (let (org-time-was-given org-end-time-was-given)
14795 (when what (setq time (or time (org-read-date nil 'to-time))))
14796 (when (and org-insert-labeled-timestamps-at-point
14797 (member what '(scheduled deadline)))
14798 (insert
14799 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14800 (org-insert-time-stamp time org-time-was-given
14801 nil nil nil (list org-end-time-was-given))
14802 (setq what nil))
14803 (save-excursion
14804 (save-restriction
14805 (let (col list elt ts buffer-invisibility-spec)
14806 (org-back-to-heading t)
14807 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14808 (goto-char (match-end 1))
14809 (setq col (current-column))
14810 (goto-char (match-end 0))
14811 (if (eobp) (insert "\n") (forward-char 1))
14812 (if (and (not (looking-at outline-regexp))
14813 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14814 "[^\r\n]*"))
14815 (not (equal (match-string 1) org-clock-string)))
14816 (narrow-to-region (match-beginning 0) (match-end 0))
14817 (insert-before-markers "\n")
14818 (backward-char 1)
14819 (narrow-to-region (point) (point))
14820 (indent-to-column col))
14821 ;; Check if we have to remove something.
14822 (setq list (cons what remove))
14823 (while list
14824 (setq elt (pop list))
14825 (goto-char (point-min))
14826 (when (or (and (eq elt 'scheduled)
14827 (re-search-forward org-scheduled-time-regexp nil t))
14828 (and (eq elt 'deadline)
14829 (re-search-forward org-deadline-time-regexp nil t))
14830 (and (eq elt 'closed)
14831 (re-search-forward org-closed-time-regexp nil t)))
14832 (replace-match "")
14833 (if (looking-at "--+<[^>]+>") (replace-match ""))
14834 (if (looking-at " +") (replace-match ""))))
14835 (goto-char (point-max))
14836 (when what
14837 (insert
14838 (if (not (equal (char-before) ?\ )) " " "")
14839 (cond ((eq what 'scheduled) org-scheduled-string)
14840 ((eq what 'deadline) org-deadline-string)
14841 ((eq what 'closed) org-closed-string))
14842 " ")
14843 (setq ts (org-insert-time-stamp
14844 time
14845 (or org-time-was-given
14846 (and (eq what 'closed) org-log-done-with-time))
14847 (eq what 'closed)
14848 nil nil (list org-end-time-was-given)))
14849 (end-of-line 1))
14850 (goto-char (point-min))
14851 (widen)
14852 (if (looking-at "[ \t]+\r?\n")
14853 (replace-match ""))
14854 ts)))))
14856 (defvar org-log-note-marker (make-marker))
14857 (defvar org-log-note-purpose nil)
14858 (defvar org-log-note-state nil)
14859 (defvar org-log-note-window-configuration nil)
14860 (defvar org-log-note-return-to (make-marker))
14861 (defvar org-log-post-message nil
14862 "Message to be displayed after a log note has been stored.
14863 The auto-repeater uses this.")
14865 (defun org-add-log-maybe (&optional purpose state findpos)
14866 "Set up the post command hook to take a note."
14867 (save-excursion
14868 (when (and (listp org-log-done)
14869 (memq purpose org-log-done))
14870 (when findpos
14871 (org-back-to-heading t)
14872 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14873 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14874 "[^\r\n]*\\)?"))
14875 (goto-char (match-end 0))
14876 (unless org-log-states-order-reversed
14877 (and (= (char-after) ?\n) (forward-char 1))
14878 (org-skip-over-state-notes)
14879 (skip-chars-backward " \t\n\r")))
14880 (move-marker org-log-note-marker (point))
14881 (setq org-log-note-purpose purpose)
14882 (setq org-log-note-state state)
14883 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14885 (defun org-skip-over-state-notes ()
14886 "Skip past the list of State notes in an entry."
14887 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14888 (while (looking-at "[ \t]*- State")
14889 (condition-case nil
14890 (org-next-item)
14891 (error (org-end-of-item)))))
14893 (defun org-add-log-note (&optional purpose)
14894 "Pop up a window for taking a note, and add this note later at point."
14895 (remove-hook 'post-command-hook 'org-add-log-note)
14896 (setq org-log-note-window-configuration (current-window-configuration))
14897 (delete-other-windows)
14898 (move-marker org-log-note-return-to (point))
14899 (switch-to-buffer (marker-buffer org-log-note-marker))
14900 (goto-char org-log-note-marker)
14901 (org-switch-to-buffer-other-window "*Org Note*")
14902 (erase-buffer)
14903 (let ((org-inhibit-startup t)) (org-mode))
14904 (insert (format "# Insert note for %s.
14905 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14906 (cond
14907 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14908 ((eq org-log-note-purpose 'done) "closed todo item")
14909 ((eq org-log-note-purpose 'state)
14910 (format "state change to \"%s\"" org-log-note-state))
14911 (t (error "This should not happen")))))
14912 (org-set-local 'org-finish-function 'org-store-log-note))
14914 (defun org-store-log-note ()
14915 "Finish taking a log note, and insert it to where it belongs."
14916 (let ((txt (buffer-string))
14917 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14918 lines ind)
14919 (kill-buffer (current-buffer))
14920 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14921 (setq txt (replace-match "" t t txt)))
14922 (if (string-match "\\s-+\\'" txt)
14923 (setq txt (replace-match "" t t txt)))
14924 (setq lines (org-split-string txt "\n"))
14925 (when (and note (string-match "\\S-" note))
14926 (setq note
14927 (org-replace-escapes
14928 note
14929 (list (cons "%u" (user-login-name))
14930 (cons "%U" user-full-name)
14931 (cons "%t" (format-time-string
14932 (org-time-stamp-format 'long 'inactive)
14933 (current-time)))
14934 (cons "%s" (if org-log-note-state
14935 (concat "\"" org-log-note-state "\"")
14936 "")))))
14937 (if lines (setq note (concat note " \\\\")))
14938 (push note lines))
14939 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14940 (when lines
14941 (save-excursion
14942 (set-buffer (marker-buffer org-log-note-marker))
14943 (save-excursion
14944 (goto-char org-log-note-marker)
14945 (move-marker org-log-note-marker nil)
14946 (end-of-line 1)
14947 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14948 (indent-relative nil)
14949 (insert "- " (pop lines))
14950 (org-indent-line-function)
14951 (beginning-of-line 1)
14952 (looking-at "[ \t]*")
14953 (setq ind (concat (match-string 0) " "))
14954 (end-of-line 1)
14955 (while lines (insert "\n" ind (pop lines)))))))
14956 (set-window-configuration org-log-note-window-configuration)
14957 (with-current-buffer (marker-buffer org-log-note-return-to)
14958 (goto-char org-log-note-return-to))
14959 (move-marker org-log-note-return-to nil)
14960 (and org-log-post-message (message "%s" org-log-post-message)))
14962 ;; FIXME: what else would be useful?
14963 ;; - priority
14964 ;; - date
14966 (defun org-sparse-tree (&optional arg)
14967 "Create a sparse tree, prompt for the details.
14968 This command can create sparse trees. You first need to select the type
14969 of match used to create the tree:
14971 t Show entries with a specific TODO keyword.
14972 T Show entries selected by a tags match.
14973 p Enter a property name and its value (both with completion on existing
14974 names/values) and show entries with that property.
14975 r Show entries matching a regular expression
14976 d Show deadlines due within `org-deadline-warning-days'."
14977 (interactive "P")
14978 (let (ans kwd value)
14979 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14980 (setq ans (read-char-exclusive))
14981 (cond
14982 ((equal ans ?d)
14983 (call-interactively 'org-check-deadlines))
14984 ((equal ans ?b)
14985 (call-interactively 'org-check-before-date))
14986 ((equal ans ?t)
14987 (org-show-todo-tree '(4)))
14988 ((equal ans ?T)
14989 (call-interactively 'org-tags-sparse-tree))
14990 ((member ans '(?p ?P))
14991 (setq kwd (completing-read "Property: "
14992 (mapcar 'list (org-buffer-property-keys))))
14993 (setq value (completing-read "Value: "
14994 (mapcar 'list (org-property-values kwd))))
14995 (unless (string-match "\\`{.*}\\'" value)
14996 (setq value (concat "\"" value "\"")))
14997 (org-tags-sparse-tree arg (concat kwd "=" value)))
14998 ((member ans '(?r ?R ?/))
14999 (call-interactively 'org-occur))
15000 (t (error "No such sparse tree command \"%c\"" ans)))))
15002 (defvar org-occur-highlights nil)
15003 (make-variable-buffer-local 'org-occur-highlights)
15005 (defun org-occur (regexp &optional keep-previous callback)
15006 "Make a compact tree which shows all matches of REGEXP.
15007 The tree will show the lines where the regexp matches, and all higher
15008 headlines above the match. It will also show the heading after the match,
15009 to make sure editing the matching entry is easy.
15010 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15011 call to `org-occur' will be kept, to allow stacking of calls to this
15012 command.
15013 If CALLBACK is non-nil, it is a function which is called to confirm
15014 that the match should indeed be shown."
15015 (interactive "sRegexp: \nP")
15016 (or keep-previous (org-remove-occur-highlights nil nil t))
15017 (let ((cnt 0))
15018 (save-excursion
15019 (goto-char (point-min))
15020 (if (or (not keep-previous) ; do not want to keep
15021 (not org-occur-highlights)) ; no previous matches
15022 ;; hide everything
15023 (org-overview))
15024 (while (re-search-forward regexp nil t)
15025 (when (or (not callback)
15026 (save-match-data (funcall callback)))
15027 (setq cnt (1+ cnt))
15028 (when org-highlight-sparse-tree-matches
15029 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15030 (org-show-context 'occur-tree))))
15031 (when org-remove-highlights-with-change
15032 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15033 nil 'local))
15034 (unless org-sparse-tree-open-archived-trees
15035 (org-hide-archived-subtrees (point-min) (point-max)))
15036 (run-hooks 'org-occur-hook)
15037 (if (interactive-p)
15038 (message "%d match(es) for regexp %s" cnt regexp))
15039 cnt))
15041 (defun org-show-context (&optional key)
15042 "Make sure point and context and visible.
15043 How much context is shown depends upon the variables
15044 `org-show-hierarchy-above', `org-show-following-heading'. and
15045 `org-show-siblings'."
15046 (let ((heading-p (org-on-heading-p t))
15047 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15048 (following-p (org-get-alist-option org-show-following-heading key))
15049 (entry-p (org-get-alist-option org-show-entry-below key))
15050 (siblings-p (org-get-alist-option org-show-siblings key)))
15051 (catch 'exit
15052 ;; Show heading or entry text
15053 (if (and heading-p (not entry-p))
15054 (org-flag-heading nil) ; only show the heading
15055 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15056 (org-show-hidden-entry))) ; show entire entry
15057 (when following-p
15058 ;; Show next sibling, or heading below text
15059 (save-excursion
15060 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15061 (org-flag-heading nil))))
15062 (when siblings-p (org-show-siblings))
15063 (when hierarchy-p
15064 ;; show all higher headings, possibly with siblings
15065 (save-excursion
15066 (while (and (condition-case nil
15067 (progn (org-up-heading-all 1) t)
15068 (error nil))
15069 (not (bobp)))
15070 (org-flag-heading nil)
15071 (when siblings-p (org-show-siblings))))))))
15073 (defun org-reveal (&optional siblings)
15074 "Show current entry, hierarchy above it, and the following headline.
15075 This can be used to show a consistent set of context around locations
15076 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15077 not t for the search context.
15079 With optional argument SIBLINGS, on each level of the hierarchy all
15080 siblings are shown. This repairs the tree structure to what it would
15081 look like when opened with hierarchical calls to `org-cycle'."
15082 (interactive "P")
15083 (let ((org-show-hierarchy-above t)
15084 (org-show-following-heading t)
15085 (org-show-siblings (if siblings t org-show-siblings)))
15086 (org-show-context nil)))
15088 (defun org-highlight-new-match (beg end)
15089 "Highlight from BEG to END and mark the highlight is an occur headline."
15090 (let ((ov (org-make-overlay beg end)))
15091 (org-overlay-put ov 'face 'secondary-selection)
15092 (push ov org-occur-highlights)))
15094 (defun org-remove-occur-highlights (&optional beg end noremove)
15095 "Remove the occur highlights from the buffer.
15096 BEG and END are ignored. If NOREMOVE is nil, remove this function
15097 from the `before-change-functions' in the current buffer."
15098 (interactive)
15099 (unless org-inhibit-highlight-removal
15100 (mapc 'org-delete-overlay org-occur-highlights)
15101 (setq org-occur-highlights nil)
15102 (unless noremove
15103 (remove-hook 'before-change-functions
15104 'org-remove-occur-highlights 'local))))
15106 ;;;; Priorities
15108 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15109 "Regular expression matching the priority indicator.")
15111 (defvar org-remove-priority-next-time nil)
15113 (defun org-priority-up ()
15114 "Increase the priority of the current item."
15115 (interactive)
15116 (org-priority 'up))
15118 (defun org-priority-down ()
15119 "Decrease the priority of the current item."
15120 (interactive)
15121 (org-priority 'down))
15123 (defun org-priority (&optional action)
15124 "Change the priority of an item by ARG.
15125 ACTION can be `set', `up', `down', or a character."
15126 (interactive)
15127 (setq action (or action 'set))
15128 (let (current new news have remove)
15129 (save-excursion
15130 (org-back-to-heading)
15131 (if (looking-at org-priority-regexp)
15132 (setq current (string-to-char (match-string 2))
15133 have t)
15134 (setq current org-default-priority))
15135 (cond
15136 ((or (eq action 'set) (integerp action))
15137 (if (integerp action)
15138 (setq new action)
15139 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15140 (setq new (read-char-exclusive)))
15141 (if (and (= (upcase org-highest-priority) org-highest-priority)
15142 (= (upcase org-lowest-priority) org-lowest-priority))
15143 (setq new (upcase new)))
15144 (cond ((equal new ?\ ) (setq remove t))
15145 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15146 (error "Priority must be between `%c' and `%c'"
15147 org-highest-priority org-lowest-priority))))
15148 ((eq action 'up)
15149 (if (and (not have) (eq last-command this-command))
15150 (setq new org-lowest-priority)
15151 (setq new (if (and org-priority-start-cycle-with-default (not have))
15152 org-default-priority (1- current)))))
15153 ((eq action 'down)
15154 (if (and (not have) (eq last-command this-command))
15155 (setq new org-highest-priority)
15156 (setq new (if (and org-priority-start-cycle-with-default (not have))
15157 org-default-priority (1+ current)))))
15158 (t (error "Invalid action")))
15159 (if (or (< (upcase new) org-highest-priority)
15160 (> (upcase new) org-lowest-priority))
15161 (setq remove t))
15162 (setq news (format "%c" new))
15163 (if have
15164 (if remove
15165 (replace-match "" t t nil 1)
15166 (replace-match news t t nil 2))
15167 (if remove
15168 (error "No priority cookie found in line")
15169 (looking-at org-todo-line-regexp)
15170 (if (match-end 2)
15171 (progn
15172 (goto-char (match-end 2))
15173 (insert " [#" news "]"))
15174 (goto-char (match-beginning 3))
15175 (insert "[#" news "] ")))))
15176 (org-preserve-lc (org-set-tags nil 'align))
15177 (if remove
15178 (message "Priority removed")
15179 (message "Priority of current item set to %s" news))))
15182 (defun org-get-priority (s)
15183 "Find priority cookie and return priority."
15184 (save-match-data
15185 (if (not (string-match org-priority-regexp s))
15186 (* 1000 (- org-lowest-priority org-default-priority))
15187 (* 1000 (- org-lowest-priority
15188 (string-to-char (match-string 2 s)))))))
15190 ;;;; Tags
15192 (defun org-scan-tags (action matcher &optional todo-only)
15193 "Scan headline tags with inheritance and produce output ACTION.
15194 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15195 evaluated, testing if a given set of tags qualifies a headline for
15196 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15197 are included in the output."
15198 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15199 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15200 (org-re
15201 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15202 (props (list 'face nil
15203 'done-face 'org-done
15204 'undone-face nil
15205 'mouse-face 'highlight
15206 'org-not-done-regexp org-not-done-regexp
15207 'org-todo-regexp org-todo-regexp
15208 'keymap org-agenda-keymap
15209 'help-echo
15210 (format "mouse-2 or RET jump to org file %s"
15211 (abbreviate-file-name
15212 (or (buffer-file-name (buffer-base-buffer))
15213 (buffer-name (buffer-base-buffer)))))))
15214 (case-fold-search nil)
15215 lspos
15216 tags tags-list tags-alist (llast 0) rtn level category i txt
15217 todo marker entry priority)
15218 (save-excursion
15219 (goto-char (point-min))
15220 (when (eq action 'sparse-tree)
15221 (org-overview)
15222 (org-remove-occur-highlights))
15223 (while (re-search-forward re nil t)
15224 (catch :skip
15225 (setq todo (if (match-end 1) (match-string 2))
15226 tags (if (match-end 4) (match-string 4)))
15227 (goto-char (setq lspos (1+ (match-beginning 0))))
15228 (setq level (org-reduced-level (funcall outline-level))
15229 category (org-get-category))
15230 (setq i llast llast level)
15231 ;; remove tag lists from same and sublevels
15232 (while (>= i level)
15233 (when (setq entry (assoc i tags-alist))
15234 (setq tags-alist (delete entry tags-alist)))
15235 (setq i (1- i)))
15236 ;; add the nex tags
15237 (when tags
15238 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15239 tags-alist
15240 (cons (cons level tags) tags-alist)))
15241 ;; compile tags for current headline
15242 (setq tags-list
15243 (if org-use-tag-inheritance
15244 (apply 'append (mapcar 'cdr tags-alist))
15245 tags))
15246 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15247 (eval matcher)
15248 (or (not org-agenda-skip-archived-trees)
15249 (not (member org-archive-tag tags-list))))
15250 (and (eq action 'agenda) (org-agenda-skip))
15251 ;; list this headline
15253 (if (eq action 'sparse-tree)
15254 (progn
15255 (and org-highlight-sparse-tree-matches
15256 (org-get-heading) (match-end 0)
15257 (org-highlight-new-match
15258 (match-beginning 0) (match-beginning 1)))
15259 (org-show-context 'tags-tree))
15260 (setq txt (org-format-agenda-item
15262 (concat
15263 (if org-tags-match-list-sublevels
15264 (make-string (1- level) ?.) "")
15265 (org-get-heading))
15266 category tags-list)
15267 priority (org-get-priority txt))
15268 (goto-char lspos)
15269 (setq marker (org-agenda-new-marker))
15270 (org-add-props txt props
15271 'org-marker marker 'org-hd-marker marker 'org-category category
15272 'priority priority 'type "tagsmatch")
15273 (push txt rtn))
15274 ;; if we are to skip sublevels, jump to end of subtree
15275 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15276 (when (and (eq action 'sparse-tree)
15277 (not org-sparse-tree-open-archived-trees))
15278 (org-hide-archived-subtrees (point-min) (point-max)))
15279 (nreverse rtn)))
15281 (defvar todo-only) ;; dynamically scoped
15283 (defun org-tags-sparse-tree (&optional todo-only match)
15284 "Create a sparse tree according to tags string MATCH.
15285 MATCH can contain positive and negative selection of tags, like
15286 \"+WORK+URGENT-WITHBOSS\".
15287 If optional argument TODO_ONLY is non-nil, only select lines that are
15288 also TODO lines."
15289 (interactive "P")
15290 (org-prepare-agenda-buffers (list (current-buffer)))
15291 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15293 (defvar org-cached-props nil)
15294 (defun org-cached-entry-get (pom property)
15295 (if (or (eq t org-use-property-inheritance)
15296 (member property org-use-property-inheritance))
15297 ;; Caching is not possible, check it directly
15298 (org-entry-get pom property 'inherit)
15299 ;; Get all properties, so that we can do complicated checks easily
15300 (cdr (assoc property (or org-cached-props
15301 (setq org-cached-props
15302 (org-entry-properties pom)))))))
15304 (defun org-global-tags-completion-table (&optional files)
15305 "Return the list of all tags in all agenda buffer/files."
15306 (save-excursion
15307 (org-uniquify
15308 (delq nil
15309 (apply 'append
15310 (mapcar
15311 (lambda (file)
15312 (set-buffer (find-file-noselect file))
15313 (append (org-get-buffer-tags)
15314 (mapcar (lambda (x) (if (stringp (car-safe x))
15315 (list (car-safe x)) nil))
15316 org-tag-alist)))
15317 (if (and files (car files))
15318 files
15319 (org-agenda-files))))))))
15321 (defun org-make-tags-matcher (match)
15322 "Create the TAGS//TODO matcher form for the selection string MATCH."
15323 ;; todo-only is scoped dynamically into this function, and the function
15324 ;; may change it it the matcher asksk for it.
15325 (unless match
15326 ;; Get a new match request, with completion
15327 (let ((org-last-tags-completion-table
15328 (org-global-tags-completion-table)))
15329 (setq match (completing-read
15330 "Match: " 'org-tags-completion-function nil nil nil
15331 'org-tags-history))))
15333 ;; Parse the string and create a lisp form
15334 (let ((match0 match)
15335 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15336 minus tag mm
15337 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15338 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15339 (if (string-match "/+" match)
15340 ;; match contains also a todo-matching request
15341 (progn
15342 (setq tagsmatch (substring match 0 (match-beginning 0))
15343 todomatch (substring match (match-end 0)))
15344 (if (string-match "^!" todomatch)
15345 (setq todo-only t todomatch (substring todomatch 1)))
15346 (if (string-match "^\\s-*$" todomatch)
15347 (setq todomatch nil)))
15348 ;; only matching tags
15349 (setq tagsmatch match todomatch nil))
15351 ;; Make the tags matcher
15352 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15353 (setq tagsmatcher t)
15354 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15355 (while (setq term (pop orterms))
15356 (while (and (equal (substring term -1) "\\") orterms)
15357 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15358 (while (string-match re term)
15359 (setq minus (and (match-end 1)
15360 (equal (match-string 1 term) "-"))
15361 tag (match-string 2 term)
15362 re-p (equal (string-to-char tag) ?{)
15363 level-p (match-end 3)
15364 prop-p (match-end 4)
15365 mm (cond
15366 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15367 (level-p `(= level ,(string-to-number
15368 (match-string 3 term))))
15369 (prop-p
15370 (setq pn (match-string 4 term)
15371 pv (match-string 5 term)
15372 cat-p (equal pn "CATEGORY")
15373 re-p (equal (string-to-char pv) ?{)
15374 pv (substring pv 1 -1))
15375 (if (equal pn "CATEGORY")
15376 (setq gv '(get-text-property (point) 'org-category))
15377 (setq gv `(org-cached-entry-get nil ,pn)))
15378 (if re-p
15379 `(string-match ,pv (or ,gv ""))
15380 `(equal ,pv (or ,gv ""))))
15381 (t `(member ,(downcase tag) tags-list)))
15382 mm (if minus (list 'not mm) mm)
15383 term (substring term (match-end 0)))
15384 (push mm tagsmatcher))
15385 (push (if (> (length tagsmatcher) 1)
15386 (cons 'and tagsmatcher)
15387 (car tagsmatcher))
15388 orlist)
15389 (setq tagsmatcher nil))
15390 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15391 (setq tagsmatcher
15392 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15394 ;; Make the todo matcher
15395 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15396 (setq todomatcher t)
15397 (setq orterms (org-split-string todomatch "|") orlist nil)
15398 (while (setq term (pop orterms))
15399 (while (string-match re term)
15400 (setq minus (and (match-end 1)
15401 (equal (match-string 1 term) "-"))
15402 kwd (match-string 2 term)
15403 re-p (equal (string-to-char kwd) ?{)
15404 term (substring term (match-end 0))
15405 mm (if re-p
15406 `(string-match ,(substring kwd 1 -1) todo)
15407 (list 'equal 'todo kwd))
15408 mm (if minus (list 'not mm) mm))
15409 (push mm todomatcher))
15410 (push (if (> (length todomatcher) 1)
15411 (cons 'and todomatcher)
15412 (car todomatcher))
15413 orlist)
15414 (setq todomatcher nil))
15415 (setq todomatcher (if (> (length orlist) 1)
15416 (cons 'or orlist) (car orlist))))
15418 ;; Return the string and lisp forms of the matcher
15419 (setq matcher (if todomatcher
15420 (list 'and tagsmatcher todomatcher)
15421 tagsmatcher))
15422 (cons match0 matcher)))
15424 (defun org-match-any-p (re list)
15425 "Does re match any element of list?"
15426 (setq list (mapcar (lambda (x) (string-match re x)) list))
15427 (delq nil list))
15429 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15430 (defvar org-tags-overlay (org-make-overlay 1 1))
15431 (org-detach-overlay org-tags-overlay)
15433 (defun org-align-tags-here (to-col)
15434 ;; Assumes that this is a headline
15435 (let ((pos (point)) (col (current-column)) tags)
15436 (beginning-of-line 1)
15437 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15438 (< pos (match-beginning 2)))
15439 (progn
15440 (setq tags (match-string 2))
15441 (goto-char (match-beginning 1))
15442 (insert " ")
15443 (delete-region (point) (1+ (match-end 0)))
15444 (backward-char 1)
15445 (move-to-column
15446 (max (1+ (current-column))
15447 (1+ col)
15448 (if (> to-col 0)
15449 to-col
15450 (- (abs to-col) (length tags))))
15452 (insert tags)
15453 (move-to-column (min (current-column) col) t))
15454 (goto-char pos))))
15456 (defun org-set-tags (&optional arg just-align)
15457 "Set the tags for the current headline.
15458 With prefix ARG, realign all tags in headings in the current buffer."
15459 (interactive "P")
15460 (let* ((re (concat "^" outline-regexp))
15461 (current (org-get-tags-string))
15462 (col (current-column))
15463 (org-setting-tags t)
15464 table current-tags inherited-tags ; computed below when needed
15465 tags p0 c0 c1 rpl)
15466 (if arg
15467 (save-excursion
15468 (goto-char (point-min))
15469 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15470 (while (re-search-forward re nil t)
15471 (org-set-tags nil t)
15472 (end-of-line 1)))
15473 (message "All tags realigned to column %d" org-tags-column))
15474 (if just-align
15475 (setq tags current)
15476 ;; Get a new set of tags from the user
15477 (save-excursion
15478 (setq table (or org-tag-alist (org-get-buffer-tags))
15479 org-last-tags-completion-table table
15480 current-tags (org-split-string current ":")
15481 inherited-tags (nreverse
15482 (nthcdr (length current-tags)
15483 (nreverse (org-get-tags-at))))
15484 tags
15485 (if (or (eq t org-use-fast-tag-selection)
15486 (and org-use-fast-tag-selection
15487 (delq nil (mapcar 'cdr table))))
15488 (org-fast-tag-selection
15489 current-tags inherited-tags table
15490 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15491 (let ((org-add-colon-after-tag-completion t))
15492 (org-trim
15493 (org-without-partial-completion
15494 (completing-read "Tags: " 'org-tags-completion-function
15495 nil nil current 'org-tags-history)))))))
15496 (while (string-match "[-+&]+" tags)
15497 ;; No boolean logic, just a list
15498 (setq tags (replace-match ":" t t tags))))
15500 (if (string-match "\\`[\t ]*\\'" tags)
15501 (setq tags "")
15502 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15503 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15505 ;; Insert new tags at the correct column
15506 (beginning-of-line 1)
15507 (cond
15508 ((and (equal current "") (equal tags "")))
15509 ((re-search-forward
15510 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15511 (point-at-eol) t)
15512 (if (equal tags "")
15513 (setq rpl "")
15514 (goto-char (match-beginning 0))
15515 (setq c0 (current-column) p0 (point)
15516 c1 (max (1+ c0) (if (> org-tags-column 0)
15517 org-tags-column
15518 (- (- org-tags-column) (length tags))))
15519 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15520 (replace-match rpl t t)
15521 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15522 tags)
15523 (t (error "Tags alignment failed")))
15524 (move-to-column col)
15525 (unless just-align
15526 (run-hooks 'org-after-tags-change-hook)))))
15528 (defun org-change-tag-in-region (beg end tag off)
15529 "Add or remove TAG for each entry in the region.
15530 This works in the agenda, and also in an org-mode buffer."
15531 (interactive
15532 (list (region-beginning) (region-end)
15533 (let ((org-last-tags-completion-table
15534 (if (org-mode-p)
15535 (org-get-buffer-tags)
15536 (org-global-tags-completion-table))))
15537 (completing-read
15538 "Tag: " 'org-tags-completion-function nil nil nil
15539 'org-tags-history))
15540 (progn
15541 (message "[s]et or [r]emove? ")
15542 (equal (read-char-exclusive) ?r))))
15543 (if (fboundp 'deactivate-mark) (deactivate-mark))
15544 (let ((agendap (equal major-mode 'org-agenda-mode))
15545 l1 l2 m buf pos newhead (cnt 0))
15546 (goto-char end)
15547 (setq l2 (1- (org-current-line)))
15548 (goto-char beg)
15549 (setq l1 (org-current-line))
15550 (loop for l from l1 to l2 do
15551 (goto-line l)
15552 (setq m (get-text-property (point) 'org-hd-marker))
15553 (when (or (and (org-mode-p) (org-on-heading-p))
15554 (and agendap m))
15555 (setq buf (if agendap (marker-buffer m) (current-buffer))
15556 pos (if agendap m (point)))
15557 (with-current-buffer buf
15558 (save-excursion
15559 (save-restriction
15560 (goto-char pos)
15561 (setq cnt (1+ cnt))
15562 (org-toggle-tag tag (if off 'off 'on))
15563 (setq newhead (org-get-heading)))))
15564 (and agendap (org-agenda-change-all-lines newhead m))))
15565 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15567 (defun org-tags-completion-function (string predicate &optional flag)
15568 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15569 (confirm (lambda (x) (stringp (car x)))))
15570 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15571 (setq s1 (match-string 1 string)
15572 s2 (match-string 2 string))
15573 (setq s1 "" s2 string))
15574 (cond
15575 ((eq flag nil)
15576 ;; try completion
15577 (setq rtn (try-completion s2 ctable confirm))
15578 (if (stringp rtn)
15579 (setq rtn
15580 (concat s1 s2 (substring rtn (length s2))
15581 (if (and org-add-colon-after-tag-completion
15582 (assoc rtn ctable))
15583 ":" ""))))
15584 rtn)
15585 ((eq flag t)
15586 ;; all-completions
15587 (all-completions s2 ctable confirm)
15589 ((eq flag 'lambda)
15590 ;; exact match?
15591 (assoc s2 ctable)))
15594 (defun org-fast-tag-insert (kwd tags face &optional end)
15595 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15596 (insert (format "%-12s" (concat kwd ":"))
15597 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15598 (or end "")))
15600 (defun org-fast-tag-show-exit (flag)
15601 (save-excursion
15602 (goto-line 3)
15603 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15604 (replace-match ""))
15605 (when flag
15606 (end-of-line 1)
15607 (move-to-column (- (window-width) 19) t)
15608 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15610 (defun org-set-current-tags-overlay (current prefix)
15611 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15612 (if (featurep 'xemacs)
15613 (org-overlay-display org-tags-overlay (concat prefix s)
15614 'secondary-selection)
15615 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15616 (org-overlay-display org-tags-overlay (concat prefix s)))))
15618 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15619 "Fast tag selection with single keys.
15620 CURRENT is the current list of tags in the headline, INHERITED is the
15621 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15622 possibly with grouping information. TODO-TABLE is a similar table with
15623 TODO keywords, should these have keys assigned to them.
15624 If the keys are nil, a-z are automatically assigned.
15625 Returns the new tags string, or nil to not change the current settings."
15626 (let* ((fulltable (append table todo-table))
15627 (maxlen (apply 'max (mapcar
15628 (lambda (x)
15629 (if (stringp (car x)) (string-width (car x)) 0))
15630 fulltable)))
15631 (buf (current-buffer))
15632 (expert (eq org-fast-tag-selection-single-key 'expert))
15633 (buffer-tags nil)
15634 (fwidth (+ maxlen 3 1 3))
15635 (ncol (/ (- (window-width) 4) fwidth))
15636 (i-face 'org-done)
15637 (c-face 'org-todo)
15638 tg cnt e c char c1 c2 ntable tbl rtn
15639 ov-start ov-end ov-prefix
15640 (exit-after-next org-fast-tag-selection-single-key)
15641 (done-keywords org-done-keywords)
15642 groups ingroup)
15643 (save-excursion
15644 (beginning-of-line 1)
15645 (if (looking-at
15646 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15647 (setq ov-start (match-beginning 1)
15648 ov-end (match-end 1)
15649 ov-prefix "")
15650 (setq ov-start (1- (point-at-eol))
15651 ov-end (1+ ov-start))
15652 (skip-chars-forward "^\n\r")
15653 (setq ov-prefix
15654 (concat
15655 (buffer-substring (1- (point)) (point))
15656 (if (> (current-column) org-tags-column)
15658 (make-string (- org-tags-column (current-column)) ?\ ))))))
15659 (org-move-overlay org-tags-overlay ov-start ov-end)
15660 (save-window-excursion
15661 (if expert
15662 (set-buffer (get-buffer-create " *Org tags*"))
15663 (delete-other-windows)
15664 (split-window-vertically)
15665 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15666 (erase-buffer)
15667 (org-set-local 'org-done-keywords done-keywords)
15668 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15669 (org-fast-tag-insert "Current" current c-face "\n\n")
15670 (org-fast-tag-show-exit exit-after-next)
15671 (org-set-current-tags-overlay current ov-prefix)
15672 (setq tbl fulltable char ?a cnt 0)
15673 (while (setq e (pop tbl))
15674 (cond
15675 ((equal e '(:startgroup))
15676 (push '() groups) (setq ingroup t)
15677 (when (not (= cnt 0))
15678 (setq cnt 0)
15679 (insert "\n"))
15680 (insert "{ "))
15681 ((equal e '(:endgroup))
15682 (setq ingroup nil cnt 0)
15683 (insert "}\n"))
15685 (setq tg (car e) c2 nil)
15686 (if (cdr e)
15687 (setq c (cdr e))
15688 ;; automatically assign a character.
15689 (setq c1 (string-to-char
15690 (downcase (substring
15691 tg (if (= (string-to-char tg) ?@) 1 0)))))
15692 (if (or (rassoc c1 ntable) (rassoc c1 table))
15693 (while (or (rassoc char ntable) (rassoc char table))
15694 (setq char (1+ char)))
15695 (setq c2 c1))
15696 (setq c (or c2 char)))
15697 (if ingroup (push tg (car groups)))
15698 (setq tg (org-add-props tg nil 'face
15699 (cond
15700 ((not (assoc tg table))
15701 (org-get-todo-face tg))
15702 ((member tg current) c-face)
15703 ((member tg inherited) i-face)
15704 (t nil))))
15705 (if (and (= cnt 0) (not ingroup)) (insert " "))
15706 (insert "[" c "] " tg (make-string
15707 (- fwidth 4 (length tg)) ?\ ))
15708 (push (cons tg c) ntable)
15709 (when (= (setq cnt (1+ cnt)) ncol)
15710 (insert "\n")
15711 (if ingroup (insert " "))
15712 (setq cnt 0)))))
15713 (setq ntable (nreverse ntable))
15714 (insert "\n")
15715 (goto-char (point-min))
15716 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15717 (fit-window-to-buffer))
15718 (setq rtn
15719 (catch 'exit
15720 (while t
15721 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15722 (if groups " [!] no groups" " [!]groups")
15723 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15724 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15725 (cond
15726 ((= c ?\r) (throw 'exit t))
15727 ((= c ?!)
15728 (setq groups (not groups))
15729 (goto-char (point-min))
15730 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15731 ((= c ?\C-c)
15732 (if (not expert)
15733 (org-fast-tag-show-exit
15734 (setq exit-after-next (not exit-after-next)))
15735 (setq expert nil)
15736 (delete-other-windows)
15737 (split-window-vertically)
15738 (org-switch-to-buffer-other-window " *Org tags*")
15739 (and (fboundp 'fit-window-to-buffer)
15740 (fit-window-to-buffer))))
15741 ((or (= c ?\C-g)
15742 (and (= c ?q) (not (rassoc c ntable))))
15743 (org-detach-overlay org-tags-overlay)
15744 (setq quit-flag t))
15745 ((= c ?\ )
15746 (setq current nil)
15747 (if exit-after-next (setq exit-after-next 'now)))
15748 ((= c ?\t)
15749 (condition-case nil
15750 (setq tg (completing-read
15751 "Tag: "
15752 (or buffer-tags
15753 (with-current-buffer buf
15754 (org-get-buffer-tags)))))
15755 (quit (setq tg "")))
15756 (when (string-match "\\S-" tg)
15757 (add-to-list 'buffer-tags (list tg))
15758 (if (member tg current)
15759 (setq current (delete tg current))
15760 (push tg current)))
15761 (if exit-after-next (setq exit-after-next 'now)))
15762 ((setq e (rassoc c todo-table) tg (car e))
15763 (with-current-buffer buf
15764 (save-excursion (org-todo tg)))
15765 (if exit-after-next (setq exit-after-next 'now)))
15766 ((setq e (rassoc c ntable) tg (car e))
15767 (if (member tg current)
15768 (setq current (delete tg current))
15769 (loop for g in groups do
15770 (if (member tg g)
15771 (mapc (lambda (x)
15772 (setq current (delete x current)))
15773 g)))
15774 (push tg current))
15775 (if exit-after-next (setq exit-after-next 'now))))
15777 ;; Create a sorted list
15778 (setq current
15779 (sort current
15780 (lambda (a b)
15781 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15782 (if (eq exit-after-next 'now) (throw 'exit t))
15783 (goto-char (point-min))
15784 (beginning-of-line 2)
15785 (delete-region (point) (point-at-eol))
15786 (org-fast-tag-insert "Current" current c-face)
15787 (org-set-current-tags-overlay current ov-prefix)
15788 (while (re-search-forward
15789 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15790 (setq tg (match-string 1))
15791 (add-text-properties
15792 (match-beginning 1) (match-end 1)
15793 (list 'face
15794 (cond
15795 ((member tg current) c-face)
15796 ((member tg inherited) i-face)
15797 (t (get-text-property (match-beginning 1) 'face))))))
15798 (goto-char (point-min)))))
15799 (org-detach-overlay org-tags-overlay)
15800 (if rtn
15801 (mapconcat 'identity current ":")
15802 nil))))
15804 (defun org-get-tags-string ()
15805 "Get the TAGS string in the current headline."
15806 (unless (org-on-heading-p t)
15807 (error "Not on a heading"))
15808 (save-excursion
15809 (beginning-of-line 1)
15810 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15811 (org-match-string-no-properties 1)
15812 "")))
15814 (defun org-get-tags ()
15815 "Get the list of tags specified in the current headline."
15816 (org-split-string (org-get-tags-string) ":"))
15818 (defun org-get-buffer-tags ()
15819 "Get a table of all tags used in the buffer, for completion."
15820 (let (tags)
15821 (save-excursion
15822 (goto-char (point-min))
15823 (while (re-search-forward
15824 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15825 (when (equal (char-after (point-at-bol 0)) ?*)
15826 (mapc (lambda (x) (add-to-list 'tags x))
15827 (org-split-string (org-match-string-no-properties 1) ":")))))
15828 (mapcar 'list tags)))
15831 ;;;; Properties
15833 ;;; Setting and retrieving properties
15835 (defconst org-special-properties
15836 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15837 "TIMESTAMP" "TIMESTAMP_IA")
15838 "The special properties valid in Org-mode.
15840 These are properties that are not defined in the property drawer,
15841 but in some other way.")
15843 (defconst org-default-properties
15844 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15845 "LOCATION" "LOGGING" "COLUMNS")
15846 "Some properties that are used by Org-mode for various purposes.
15847 Being in this list makes sure that they are offered for completion.")
15849 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15850 "Regular expression matching the first line of a property drawer.")
15852 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15853 "Regular expression matching the first line of a property drawer.")
15855 (defun org-property-action ()
15856 "Do an action on properties."
15857 (interactive)
15858 (let (c)
15859 (org-at-property-p)
15860 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15861 (setq c (read-char-exclusive))
15862 (cond
15863 ((equal c ?s)
15864 (call-interactively 'org-set-property))
15865 ((equal c ?d)
15866 (call-interactively 'org-delete-property))
15867 ((equal c ?D)
15868 (call-interactively 'org-delete-property-globally))
15869 ((equal c ?c)
15870 (call-interactively 'org-compute-property-at-point))
15871 (t (error "No such property action %c" c)))))
15873 (defun org-at-property-p ()
15874 "Is the cursor in a property line?"
15875 ;; FIXME: Does not check if we are actually in the drawer.
15876 ;; FIXME: also returns true on any drawers.....
15877 ;; This is used by C-c C-c for property action.
15878 (save-excursion
15879 (beginning-of-line 1)
15880 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15882 (defmacro org-with-point-at (pom &rest body)
15883 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15884 (declare (indent 1) (debug t))
15885 `(save-excursion
15886 (if (markerp pom) (set-buffer (marker-buffer pom)))
15887 (save-excursion
15888 (goto-char (or pom (point)))
15889 ,@body)))
15891 (defun org-get-property-block (&optional beg end force)
15892 "Return the (beg . end) range of the body of the property drawer.
15893 BEG and END can be beginning and end of subtree, if not given
15894 they will be found.
15895 If the drawer does not exist and FORCE is non-nil, create the drawer."
15896 (catch 'exit
15897 (save-excursion
15898 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15899 (end (or end (progn (outline-next-heading) (point)))))
15900 (goto-char beg)
15901 (if (re-search-forward org-property-start-re end t)
15902 (setq beg (1+ (match-end 0)))
15903 (if force
15904 (save-excursion
15905 (org-insert-property-drawer)
15906 (setq end (progn (outline-next-heading) (point))))
15907 (throw 'exit nil))
15908 (goto-char beg)
15909 (if (re-search-forward org-property-start-re end t)
15910 (setq beg (1+ (match-end 0)))))
15911 (if (re-search-forward org-property-end-re end t)
15912 (setq end (match-beginning 0))
15913 (or force (throw 'exit nil))
15914 (goto-char beg)
15915 (setq end beg)
15916 (org-indent-line-function)
15917 (insert ":END:\n"))
15918 (cons beg end)))))
15920 (defun org-entry-properties (&optional pom which)
15921 "Get all properties of the entry at point-or-marker POM.
15922 This includes the TODO keyword, the tags, time strings for deadline,
15923 scheduled, and clocking, and any additional properties defined in the
15924 entry. The return value is an alist, keys may occur multiple times
15925 if the property key was used several times.
15926 POM may also be nil, in which case the current entry is used.
15927 If WHICH is nil or `all', get all properties. If WHICH is
15928 `special' or `standard', only get that subclass."
15929 (setq which (or which 'all))
15930 (org-with-point-at pom
15931 (let ((clockstr (substring org-clock-string 0 -1))
15932 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15933 beg end range props sum-props key value string clocksum)
15934 (save-excursion
15935 (when (condition-case nil (org-back-to-heading t) (error nil))
15936 (setq beg (point))
15937 (setq sum-props (get-text-property (point) 'org-summaries))
15938 (setq clocksum (get-text-property (point) :org-clock-minutes))
15939 (outline-next-heading)
15940 (setq end (point))
15941 (when (memq which '(all special))
15942 ;; Get the special properties, like TODO and tags
15943 (goto-char beg)
15944 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15945 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15946 (when (looking-at org-priority-regexp)
15947 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15948 (when (and (setq value (org-get-tags-string))
15949 (string-match "\\S-" value))
15950 (push (cons "TAGS" value) props))
15951 (when (setq value (org-get-tags-at))
15952 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15953 props))
15954 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15955 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15956 string (if (equal key clockstr)
15957 (org-no-properties
15958 (org-trim
15959 (buffer-substring
15960 (match-beginning 3) (goto-char (point-at-eol)))))
15961 (substring (org-match-string-no-properties 3) 1 -1)))
15962 (unless key
15963 (if (= (char-after (match-beginning 3)) ?\[)
15964 (setq key "TIMESTAMP_IA")
15965 (setq key "TIMESTAMP")))
15966 (when (or (equal key clockstr) (not (assoc key props)))
15967 (push (cons key string) props)))
15971 (when (memq which '(all standard))
15972 ;; Get the standard properties, like :PORP: ...
15973 (setq range (org-get-property-block beg end))
15974 (when range
15975 (goto-char (car range))
15976 (while (re-search-forward
15977 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15978 (cdr range) t)
15979 (setq key (org-match-string-no-properties 1)
15980 value (org-trim (or (org-match-string-no-properties 2) "")))
15981 (unless (member key excluded)
15982 (push (cons key (or value "")) props)))))
15983 (if clocksum
15984 (push (cons "CLOCKSUM"
15985 (org-column-number-to-string (/ (float clocksum) 60.)
15986 'add_times))
15987 props))
15988 (append sum-props (nreverse props)))))))
15990 (defun org-entry-get (pom property &optional inherit)
15991 "Get value of PROPERTY for entry at point-or-marker POM.
15992 If INHERIT is non-nil and the entry does not have the property,
15993 then also check higher levels of the hierarchy.
15994 If the property is present but empty, the return value is the empty string.
15995 If the property is not present at all, nil is returned."
15996 (org-with-point-at pom
15997 (if inherit
15998 (org-entry-get-with-inheritance property)
15999 (if (member property org-special-properties)
16000 ;; We need a special property. Use brute force, get all properties.
16001 (cdr (assoc property (org-entry-properties nil 'special)))
16002 (let ((range (org-get-property-block)))
16003 (if (and range
16004 (goto-char (car range))
16005 (re-search-forward
16006 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16007 (cdr range) t))
16008 ;; Found the property, return it.
16009 (if (match-end 1)
16010 (org-match-string-no-properties 1)
16011 "")))))))
16013 (defun org-entry-delete (pom property)
16014 "Delete the property PROPERTY from entry at point-or-marker POM."
16015 (org-with-point-at pom
16016 (if (member property org-special-properties)
16017 nil ; cannot delete these properties.
16018 (let ((range (org-get-property-block)))
16019 (if (and range
16020 (goto-char (car range))
16021 (re-search-forward
16022 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16023 (cdr range) t))
16024 (progn
16025 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16027 nil)))))
16029 ;; Multi-values properties are properties that contain multiple values
16030 ;; These values are assumed to be single words, separated by whitespace.
16031 (defun org-entry-add-to-multivalued-property (pom property value)
16032 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16033 (let* ((old (org-entry-get pom property))
16034 (values (and old (org-split-string old "[ \t]"))))
16035 (unless (member value values)
16036 (setq values (cons value values))
16037 (org-entry-put pom property
16038 (mapconcat 'identity values " ")))))
16040 (defun org-entry-remove-from-multivalued-property (pom property value)
16041 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16042 (let* ((old (org-entry-get pom property))
16043 (values (and old (org-split-string old "[ \t]"))))
16044 (when (member value values)
16045 (setq values (delete value values))
16046 (org-entry-put pom property
16047 (mapconcat 'identity values " ")))))
16049 (defun org-entry-member-in-multivalued-property (pom property value)
16050 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16051 (let* ((old (org-entry-get pom property))
16052 (values (and old (org-split-string old "[ \t]"))))
16053 (member value values)))
16055 (defvar org-entry-property-inherited-from (make-marker))
16057 (defun org-entry-get-with-inheritance (property)
16058 "Get entry property, and search higher levels if not present."
16059 (let (tmp)
16060 (save-excursion
16061 (save-restriction
16062 (widen)
16063 (catch 'ex
16064 (while t
16065 (when (setq tmp (org-entry-get nil property))
16066 (org-back-to-heading t)
16067 (move-marker org-entry-property-inherited-from (point))
16068 (throw 'ex tmp))
16069 (or (org-up-heading-safe) (throw 'ex nil)))))
16070 (or tmp (cdr (assoc property org-local-properties))
16071 (cdr (assoc property org-global-properties))))))
16073 (defun org-entry-put (pom property value)
16074 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16075 (org-with-point-at pom
16076 (org-back-to-heading t)
16077 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16078 range)
16079 (cond
16080 ((equal property "TODO")
16081 (when (and (stringp value) (string-match "\\S-" value)
16082 (not (member value org-todo-keywords-1)))
16083 (error "\"%s\" is not a valid TODO state" value))
16084 (if (or (not value)
16085 (not (string-match "\\S-" value)))
16086 (setq value 'none))
16087 (org-todo value)
16088 (org-set-tags nil 'align))
16089 ((equal property "PRIORITY")
16090 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16091 (string-to-char value) ?\ ))
16092 (org-set-tags nil 'align))
16093 ((equal property "SCHEDULED")
16094 (if (re-search-forward org-scheduled-time-regexp end t)
16095 (cond
16096 ((eq value 'earlier) (org-timestamp-change -1 'day))
16097 ((eq value 'later) (org-timestamp-change 1 'day))
16098 (t (call-interactively 'org-schedule)))
16099 (call-interactively 'org-schedule)))
16100 ((equal property "DEADLINE")
16101 (if (re-search-forward org-deadline-time-regexp end t)
16102 (cond
16103 ((eq value 'earlier) (org-timestamp-change -1 'day))
16104 ((eq value 'later) (org-timestamp-change 1 'day))
16105 (t (call-interactively 'org-deadline)))
16106 (call-interactively 'org-deadline)))
16107 ((member property org-special-properties)
16108 (error "The %s property can not yet be set with `org-entry-put'"
16109 property))
16110 (t ; a non-special property
16111 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16112 (setq range (org-get-property-block beg end 'force))
16113 (goto-char (car range))
16114 (if (re-search-forward
16115 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16116 (progn
16117 (delete-region (match-beginning 1) (match-end 1))
16118 (goto-char (match-beginning 1)))
16119 (goto-char (cdr range))
16120 (insert "\n")
16121 (backward-char 1)
16122 (org-indent-line-function)
16123 (insert ":" property ":"))
16124 (and value (insert " " value))
16125 (org-indent-line-function)))))))
16127 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16128 "Get all property keys in the current buffer.
16129 With INCLUDE-SPECIALS, also list the special properties that relect things
16130 like tags and TODO state.
16131 With INCLUDE-DEFAULTS, also include properties that has special meaning
16132 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16133 With INCLUDE-COLUMNS, also include property names given in COLUMN
16134 formats in the current buffer."
16135 (let (rtn range cfmt cols)
16136 (save-excursion
16137 (save-restriction
16138 (widen)
16139 (goto-char (point-min))
16140 (while (re-search-forward org-property-start-re nil t)
16141 (setq range (org-get-property-block))
16142 (goto-char (car range))
16143 (while (re-search-forward
16144 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16145 (cdr range) t)
16146 (add-to-list 'rtn (org-match-string-no-properties 1)))
16147 (outline-next-heading))))
16149 (when include-specials
16150 (setq rtn (append org-special-properties rtn)))
16152 (when include-defaults
16153 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16155 (when include-columns
16156 (save-excursion
16157 (save-restriction
16158 (widen)
16159 (goto-char (point-min))
16160 (while (re-search-forward
16161 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16162 nil t)
16163 (setq cfmt (match-string 2) s 0)
16164 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16165 cfmt s)
16166 (setq s (match-end 0)
16167 p (match-string 1 cfmt))
16168 (unless (or (equal p "ITEM")
16169 (member p org-special-properties))
16170 (add-to-list 'rtn (match-string 1 cfmt))))))))
16172 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16174 (defun org-property-values (key)
16175 "Return a list of all values of property KEY."
16176 (save-excursion
16177 (save-restriction
16178 (widen)
16179 (goto-char (point-min))
16180 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16181 values)
16182 (while (re-search-forward re nil t)
16183 (add-to-list 'values (org-trim (match-string 1))))
16184 (delete "" values)))))
16186 (defun org-insert-property-drawer ()
16187 "Insert a property drawer into the current entry."
16188 (interactive)
16189 (org-back-to-heading t)
16190 (looking-at outline-regexp)
16191 (let ((indent (- (match-end 0)(match-beginning 0)))
16192 (beg (point))
16193 (re (concat "^[ \t]*" org-keyword-time-regexp))
16194 end hiddenp)
16195 (outline-next-heading)
16196 (setq end (point))
16197 (goto-char beg)
16198 (while (re-search-forward re end t))
16199 (setq hiddenp (org-invisible-p))
16200 (end-of-line 1)
16201 (and (equal (char-after) ?\n) (forward-char 1))
16202 (org-skip-over-state-notes)
16203 (skip-chars-backward " \t\n\r")
16204 (if (eq (char-before) ?*) (forward-char 1))
16205 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16206 (beginning-of-line 0)
16207 (indent-to-column indent)
16208 (beginning-of-line 2)
16209 (indent-to-column indent)
16210 (beginning-of-line 0)
16211 (if hiddenp
16212 (save-excursion
16213 (org-back-to-heading t)
16214 (hide-entry))
16215 (org-flag-drawer t))))
16217 (defun org-set-property (property value)
16218 "In the current entry, set PROPERTY to VALUE.
16219 When called interactively, this will prompt for a property name, offering
16220 completion on existing and default properties. And then it will prompt
16221 for a value, offering competion either on allowed values (via an inherited
16222 xxx_ALL property) or on existing values in other instances of this property
16223 in the current file."
16224 (interactive
16225 (let* ((prop (completing-read
16226 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16227 (cur (org-entry-get nil prop))
16228 (allowed (org-property-get-allowed-values nil prop 'table))
16229 (existing (mapcar 'list (org-property-values prop)))
16230 (val (if allowed
16231 (completing-read "Value: " allowed nil 'req-match)
16232 (completing-read
16233 (concat "Value" (if (and cur (string-match "\\S-" cur))
16234 (concat "[" cur "]") "")
16235 ": ")
16236 existing nil nil "" nil cur))))
16237 (list prop (if (equal val "") cur val))))
16238 (unless (equal (org-entry-get nil property) value)
16239 (org-entry-put nil property value)))
16241 (defun org-delete-property (property)
16242 "In the current entry, delete PROPERTY."
16243 (interactive
16244 (let* ((prop (completing-read
16245 "Property: " (org-entry-properties nil 'standard))))
16246 (list prop)))
16247 (message "Property %s %s" property
16248 (if (org-entry-delete nil property)
16249 "deleted"
16250 "was not present in the entry")))
16252 (defun org-delete-property-globally (property)
16253 "Remove PROPERTY globally, from all entries."
16254 (interactive
16255 (let* ((prop (completing-read
16256 "Globally remove property: "
16257 (mapcar 'list (org-buffer-property-keys)))))
16258 (list prop)))
16259 (save-excursion
16260 (save-restriction
16261 (widen)
16262 (goto-char (point-min))
16263 (let ((cnt 0))
16264 (while (re-search-forward
16265 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16266 nil t)
16267 (setq cnt (1+ cnt))
16268 (replace-match ""))
16269 (message "Property \"%s\" removed from %d entries" property cnt)))))
16271 (defvar org-columns-current-fmt-compiled) ; defined below
16273 (defun org-compute-property-at-point ()
16274 "Compute the property at point.
16275 This looks for an enclosing column format, extracts the operator and
16276 then applies it to the proerty in the column format's scope."
16277 (interactive)
16278 (unless (org-at-property-p)
16279 (error "Not at a property"))
16280 (let ((prop (org-match-string-no-properties 2)))
16281 (org-columns-get-format-and-top-level)
16282 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16283 (error "No operator defined for property %s" prop))
16284 (org-columns-compute prop)))
16286 (defun org-property-get-allowed-values (pom property &optional table)
16287 "Get allowed values for the property PROPERTY.
16288 When TABLE is non-nil, return an alist that can directly be used for
16289 completion."
16290 (let (vals)
16291 (cond
16292 ((equal property "TODO")
16293 (setq vals (org-with-point-at pom
16294 (append org-todo-keywords-1 '("")))))
16295 ((equal property "PRIORITY")
16296 (let ((n org-lowest-priority))
16297 (while (>= n org-highest-priority)
16298 (push (char-to-string n) vals)
16299 (setq n (1- n)))))
16300 ((member property org-special-properties))
16302 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16304 (when (and vals (string-match "\\S-" vals))
16305 (setq vals (car (read-from-string (concat "(" vals ")"))))
16306 (setq vals (mapcar (lambda (x)
16307 (cond ((stringp x) x)
16308 ((numberp x) (number-to-string x))
16309 ((symbolp x) (symbol-name x))
16310 (t "???")))
16311 vals)))))
16312 (if table (mapcar 'list vals) vals)))
16314 (defun org-property-previous-allowed-value (&optional previous)
16315 "Switch to the next allowed value for this property."
16316 (interactive)
16317 (org-property-next-allowed-value t))
16319 (defun org-property-next-allowed-value (&optional previous)
16320 "Switch to the next allowed value for this property."
16321 (interactive)
16322 (unless (org-at-property-p)
16323 (error "Not at a property"))
16324 (let* ((key (match-string 2))
16325 (value (match-string 3))
16326 (allowed (or (org-property-get-allowed-values (point) key)
16327 (and (member value '("[ ]" "[-]" "[X]"))
16328 '("[ ]" "[X]"))))
16329 nval)
16330 (unless allowed
16331 (error "Allowed values for this property have not been defined"))
16332 (if previous (setq allowed (reverse allowed)))
16333 (if (member value allowed)
16334 (setq nval (car (cdr (member value allowed)))))
16335 (setq nval (or nval (car allowed)))
16336 (if (equal nval value)
16337 (error "Only one allowed value for this property"))
16338 (org-at-property-p)
16339 (replace-match (concat " :" key ": " nval) t t)
16340 (org-indent-line-function)
16341 (beginning-of-line 1)
16342 (skip-chars-forward " \t")))
16344 (defun org-find-entry-with-id (ident)
16345 "Locate the entry that contains the ID property with exact value IDENT.
16346 IDENT can be a string, a symbol or a number, this function will search for
16347 the string representation of it.
16348 Return the position where this entry starts, or nil if there is no such entry."
16349 (let ((id (cond
16350 ((stringp ident) ident)
16351 ((symbol-name ident) (symbol-name ident))
16352 ((numberp ident) (number-to-string ident))
16353 (t (error "IDENT %s must be a string, symbol or number" ident))))
16354 (case-fold-search nil))
16355 (save-excursion
16356 (save-restriction
16357 (goto-char (point-min))
16358 (when (re-search-forward
16359 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16360 nil t)
16361 (org-back-to-heading)
16362 (point))))))
16364 ;;; Column View
16366 (defvar org-columns-overlays nil
16367 "Holds the list of current column overlays.")
16369 (defvar org-columns-current-fmt nil
16370 "Local variable, holds the currently active column format.")
16371 (defvar org-columns-current-fmt-compiled nil
16372 "Local variable, holds the currently active column format.
16373 This is the compiled version of the format.")
16374 (defvar org-columns-current-widths nil
16375 "Loval variable, holds the currently widths of fields.")
16376 (defvar org-columns-current-maxwidths nil
16377 "Loval variable, holds the currently active maximum column widths.")
16378 (defvar org-columns-begin-marker (make-marker)
16379 "Points to the position where last a column creation command was called.")
16380 (defvar org-columns-top-level-marker (make-marker)
16381 "Points to the position where current columns region starts.")
16383 (defvar org-columns-map (make-sparse-keymap)
16384 "The keymap valid in column display.")
16386 (defun org-columns-content ()
16387 "Switch to contents view while in columns view."
16388 (interactive)
16389 (org-overview)
16390 (org-content))
16392 (org-defkey org-columns-map "c" 'org-columns-content)
16393 (org-defkey org-columns-map "o" 'org-overview)
16394 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16395 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16396 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16397 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16398 (org-defkey org-columns-map "v" 'org-columns-show-value)
16399 (org-defkey org-columns-map "q" 'org-columns-quit)
16400 (org-defkey org-columns-map "r" 'org-columns-redo)
16401 (org-defkey org-columns-map "g" 'org-columns-redo)
16402 (org-defkey org-columns-map [left] 'backward-char)
16403 (org-defkey org-columns-map "\M-b" 'backward-char)
16404 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16405 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16406 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16407 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16408 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16409 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16410 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16411 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16412 (org-defkey org-columns-map "<" 'org-columns-narrow)
16413 (org-defkey org-columns-map ">" 'org-columns-widen)
16414 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16415 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16416 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16417 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16419 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16420 '("Column"
16421 ["Edit property" org-columns-edit-value t]
16422 ["Next allowed value" org-columns-next-allowed-value t]
16423 ["Previous allowed value" org-columns-previous-allowed-value t]
16424 ["Show full value" org-columns-show-value t]
16425 ["Edit allowed values" org-columns-edit-allowed t]
16426 "--"
16427 ["Edit column attributes" org-columns-edit-attributes t]
16428 ["Increase column width" org-columns-widen t]
16429 ["Decrease column width" org-columns-narrow t]
16430 "--"
16431 ["Move column right" org-columns-move-right t]
16432 ["Move column left" org-columns-move-left t]
16433 ["Add column" org-columns-new t]
16434 ["Delete column" org-columns-delete t]
16435 "--"
16436 ["CONTENTS" org-columns-content t]
16437 ["OVERVIEW" org-overview t]
16438 ["Refresh columns display" org-columns-redo t]
16439 "--"
16440 ["Open link" org-columns-open-link t]
16441 "--"
16442 ["Quit" org-columns-quit t]))
16444 (defun org-columns-new-overlay (beg end &optional string face)
16445 "Create a new column overlay and add it to the list."
16446 (let ((ov (org-make-overlay beg end)))
16447 (org-overlay-put ov 'face (or face 'secondary-selection))
16448 (org-overlay-display ov string face)
16449 (push ov org-columns-overlays)
16450 ov))
16452 (defun org-columns-display-here (&optional props)
16453 "Overlay the current line with column display."
16454 (interactive)
16455 (let* ((fmt org-columns-current-fmt-compiled)
16456 (beg (point-at-bol))
16457 (level-face (save-excursion
16458 (beginning-of-line 1)
16459 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16460 (org-get-level-face 2))))
16461 (color (list :foreground
16462 (face-attribute (or level-face 'default) :foreground)))
16463 props pom property ass width f string ov column val modval)
16464 ;; Check if the entry is in another buffer.
16465 (unless props
16466 (if (eq major-mode 'org-agenda-mode)
16467 (setq pom (or (get-text-property (point) 'org-hd-marker)
16468 (get-text-property (point) 'org-marker))
16469 props (if pom (org-entry-properties pom) nil))
16470 (setq props (org-entry-properties nil))))
16471 ;; Walk the format
16472 (while (setq column (pop fmt))
16473 (setq property (car column)
16474 ass (if (equal property "ITEM")
16475 (cons "ITEM"
16476 (save-match-data
16477 (org-no-properties
16478 (org-remove-tabs
16479 (buffer-substring-no-properties
16480 (point-at-bol) (point-at-eol))))))
16481 (assoc property props))
16482 width (or (cdr (assoc property org-columns-current-maxwidths))
16483 (nth 2 column)
16484 (length property))
16485 f (format "%%-%d.%ds | " width width)
16486 val (or (cdr ass) "")
16487 modval (if (equal property "ITEM")
16488 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16489 string (format f (or modval val)))
16490 ;; Create the overlay
16491 (org-unmodified
16492 (setq ov (org-columns-new-overlay
16493 beg (setq beg (1+ beg)) string
16494 (list color 'org-column)))
16495 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16496 (org-overlay-put ov 'keymap org-columns-map)
16497 (org-overlay-put ov 'org-columns-key property)
16498 (org-overlay-put ov 'org-columns-value (cdr ass))
16499 (org-overlay-put ov 'org-columns-value-modified modval)
16500 (org-overlay-put ov 'org-columns-pom pom)
16501 (org-overlay-put ov 'org-columns-format f))
16502 (if (or (not (char-after beg))
16503 (equal (char-after beg) ?\n))
16504 (let ((inhibit-read-only t))
16505 (save-excursion
16506 (goto-char beg)
16507 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16508 ;; Make the rest of the line disappear.
16509 (org-unmodified
16510 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16511 (org-overlay-put ov 'invisible t)
16512 (org-overlay-put ov 'keymap org-columns-map)
16513 (org-overlay-put ov 'intangible t)
16514 (push ov org-columns-overlays)
16515 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16516 (org-overlay-put ov 'keymap org-columns-map)
16517 (push ov org-columns-overlays)
16518 (let ((inhibit-read-only t))
16519 (put-text-property (max (point-min) (1- (point-at-bol)))
16520 (min (point-max) (1+ (point-at-eol)))
16521 'read-only "Type `e' to edit property")))))
16523 (defvar org-previous-header-line-format nil
16524 "The header line format before column view was turned on.")
16525 (defvar org-columns-inhibit-recalculation nil
16526 "Inhibit recomputing of columns on column view startup.")
16529 (defvar header-line-format)
16530 (defun org-columns-display-here-title ()
16531 "Overlay the newline before the current line with the table title."
16532 (interactive)
16533 (let ((fmt org-columns-current-fmt-compiled)
16534 string (title "")
16535 property width f column str widths)
16536 (while (setq column (pop fmt))
16537 (setq property (car column)
16538 str (or (nth 1 column) property)
16539 width (or (cdr (assoc property org-columns-current-maxwidths))
16540 (nth 2 column)
16541 (length str))
16542 widths (push width widths)
16543 f (format "%%-%d.%ds | " width width)
16544 string (format f str)
16545 title (concat title string)))
16546 (setq title (concat
16547 (org-add-props " " nil 'display '(space :align-to 0))
16548 (org-add-props title nil 'face '(:weight bold :underline t))))
16549 (org-set-local 'org-previous-header-line-format header-line-format)
16550 (org-set-local 'org-columns-current-widths (nreverse widths))
16551 (setq header-line-format title)))
16553 (defun org-columns-remove-overlays ()
16554 "Remove all currently active column overlays."
16555 (interactive)
16556 (when (marker-buffer org-columns-begin-marker)
16557 (with-current-buffer (marker-buffer org-columns-begin-marker)
16558 (when (local-variable-p 'org-previous-header-line-format)
16559 (setq header-line-format org-previous-header-line-format)
16560 (kill-local-variable 'org-previous-header-line-format))
16561 (move-marker org-columns-begin-marker nil)
16562 (move-marker org-columns-top-level-marker nil)
16563 (org-unmodified
16564 (mapc 'org-delete-overlay org-columns-overlays)
16565 (setq org-columns-overlays nil)
16566 (let ((inhibit-read-only t))
16567 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16569 (defun org-columns-cleanup-item (item fmt)
16570 "Remove from ITEM what is a column in the format FMT."
16571 (if (not org-complex-heading-regexp)
16572 item
16573 (when (string-match org-complex-heading-regexp item)
16574 (concat
16575 (org-add-props (concat (match-string 1 item) " ") nil
16576 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16577 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16578 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16579 " " (match-string 4 item)
16580 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16582 (defun org-columns-show-value ()
16583 "Show the full value of the property."
16584 (interactive)
16585 (let ((value (get-char-property (point) 'org-columns-value)))
16586 (message "Value is: %s" (or value ""))))
16588 (defun org-columns-quit ()
16589 "Remove the column overlays and in this way exit column editing."
16590 (interactive)
16591 (org-unmodified
16592 (org-columns-remove-overlays)
16593 (let ((inhibit-read-only t))
16594 (remove-text-properties (point-min) (point-max) '(read-only t))))
16595 (when (eq major-mode 'org-agenda-mode)
16596 (message
16597 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16599 (defun org-columns-check-computed ()
16600 "Check if this column value is computed.
16601 If yes, throw an error indicating that changing it does not make sense."
16602 (let ((val (get-char-property (point) 'org-columns-value)))
16603 (when (and (stringp val)
16604 (get-char-property 0 'org-computed val))
16605 (error "This value is computed from the entry's children"))))
16607 (defun org-columns-todo (&optional arg)
16608 "Change the TODO state during column view."
16609 (interactive "P")
16610 (org-columns-edit-value "TODO"))
16612 (defun org-columns-set-tags-or-toggle (&optional arg)
16613 "Toggle checkbox at point, or set tags for current headline."
16614 (interactive "P")
16615 (if (string-match "\\`\\[[ xX-]\\]\\'"
16616 (get-char-property (point) 'org-columns-value))
16617 (org-columns-next-allowed-value)
16618 (org-columns-edit-value "TAGS")))
16620 (defun org-columns-edit-value (&optional key)
16621 "Edit the value of the property at point in column view.
16622 Where possible, use the standard interface for changing this line."
16623 (interactive)
16624 (org-columns-check-computed)
16625 (let* ((external-key key)
16626 (col (current-column))
16627 (key (or key (get-char-property (point) 'org-columns-key)))
16628 (value (get-char-property (point) 'org-columns-value))
16629 (bol (point-at-bol)) (eol (point-at-eol))
16630 (pom (or (get-text-property bol 'org-hd-marker)
16631 (point))) ; keep despite of compiler waring
16632 (line-overlays
16633 (delq nil (mapcar (lambda (x)
16634 (and (eq (overlay-buffer x) (current-buffer))
16635 (>= (overlay-start x) bol)
16636 (<= (overlay-start x) eol)
16638 org-columns-overlays)))
16639 nval eval allowed)
16640 (cond
16641 ((equal key "CLOCKSUM")
16642 (error "This special column cannot be edited"))
16643 ((equal key "ITEM")
16644 (setq eval '(org-with-point-at pom
16645 (org-edit-headline))))
16646 ((equal key "TODO")
16647 (setq eval '(org-with-point-at pom
16648 (let ((current-prefix-arg
16649 (if external-key current-prefix-arg '(4))))
16650 (call-interactively 'org-todo)))))
16651 ((equal key "PRIORITY")
16652 (setq eval '(org-with-point-at pom
16653 (call-interactively 'org-priority))))
16654 ((equal key "TAGS")
16655 (setq eval '(org-with-point-at pom
16656 (let ((org-fast-tag-selection-single-key
16657 (if (eq org-fast-tag-selection-single-key 'expert)
16658 t org-fast-tag-selection-single-key)))
16659 (call-interactively 'org-set-tags)))))
16660 ((equal key "DEADLINE")
16661 (setq eval '(org-with-point-at pom
16662 (call-interactively 'org-deadline))))
16663 ((equal key "SCHEDULED")
16664 (setq eval '(org-with-point-at pom
16665 (call-interactively 'org-schedule))))
16667 (setq allowed (org-property-get-allowed-values pom key 'table))
16668 (if allowed
16669 (setq nval (completing-read "Value: " allowed nil t))
16670 (setq nval (read-string "Edit: " value)))
16671 (setq nval (org-trim nval))
16672 (when (not (equal nval value))
16673 (setq eval '(org-entry-put pom key nval)))))
16674 (when eval
16675 (let ((inhibit-read-only t))
16676 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16677 (unwind-protect
16678 (progn
16679 (setq org-columns-overlays
16680 (org-delete-all line-overlays org-columns-overlays))
16681 (mapc 'org-delete-overlay line-overlays)
16682 (org-columns-eval eval))
16683 (org-columns-display-here))))
16684 (move-to-column col)
16685 (if (and (org-mode-p)
16686 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16687 (org-columns-update key))))
16689 (defun org-edit-headline () ; FIXME: this is not columns specific
16690 "Edit the current headline, the part without TODO keyword, TAGS."
16691 (org-back-to-heading)
16692 (when (looking-at org-todo-line-regexp)
16693 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16694 (txt (match-string 3))
16695 (post "")
16696 txt2)
16697 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16698 (setq post (match-string 0 txt)
16699 txt (substring txt 0 (match-beginning 0))))
16700 (setq txt2 (read-string "Edit: " txt))
16701 (when (not (equal txt txt2))
16702 (beginning-of-line 1)
16703 (insert pre txt2 post)
16704 (delete-region (point) (point-at-eol))
16705 (org-set-tags nil t)))))
16707 (defun org-columns-edit-allowed ()
16708 "Edit the list of allowed values for the current property."
16709 (interactive)
16710 (let* ((key (get-char-property (point) 'org-columns-key))
16711 (key1 (concat key "_ALL"))
16712 (allowed (org-entry-get (point) key1 t))
16713 nval)
16714 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16715 (setq nval (read-string "Allowed: " allowed))
16716 (org-entry-put
16717 (cond ((marker-position org-entry-property-inherited-from)
16718 org-entry-property-inherited-from)
16719 ((marker-position org-columns-top-level-marker)
16720 org-columns-top-level-marker))
16721 key1 nval)))
16723 (defmacro org-no-warnings (&rest body)
16724 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16726 (defun org-columns-eval (form)
16727 (let (hidep)
16728 (save-excursion
16729 (beginning-of-line 1)
16730 ;; `next-line' is needed here, because it skips invisible line.
16731 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16732 (setq hidep (org-on-heading-p 1)))
16733 (eval form)
16734 (and hidep (hide-entry))))
16736 (defun org-columns-previous-allowed-value ()
16737 "Switch to the previous allowed value for this column."
16738 (interactive)
16739 (org-columns-next-allowed-value t))
16741 (defun org-columns-next-allowed-value (&optional previous)
16742 "Switch to the next allowed value for this column."
16743 (interactive)
16744 (org-columns-check-computed)
16745 (let* ((col (current-column))
16746 (key (get-char-property (point) 'org-columns-key))
16747 (value (get-char-property (point) 'org-columns-value))
16748 (bol (point-at-bol)) (eol (point-at-eol))
16749 (pom (or (get-text-property bol 'org-hd-marker)
16750 (point))) ; keep despite of compiler waring
16751 (line-overlays
16752 (delq nil (mapcar (lambda (x)
16753 (and (eq (overlay-buffer x) (current-buffer))
16754 (>= (overlay-start x) bol)
16755 (<= (overlay-start x) eol)
16757 org-columns-overlays)))
16758 (allowed (or (org-property-get-allowed-values pom key)
16759 (and (equal
16760 (nth 4 (assoc key org-columns-current-fmt-compiled))
16761 'checkbox) '("[ ]" "[X]"))))
16762 nval)
16763 (when (equal key "ITEM")
16764 (error "Cannot edit item headline from here"))
16765 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16766 (error "Allowed values for this property have not been defined"))
16767 (if (member key '("SCHEDULED" "DEADLINE"))
16768 (setq nval (if previous 'earlier 'later))
16769 (if previous (setq allowed (reverse allowed)))
16770 (if (member value allowed)
16771 (setq nval (car (cdr (member value allowed)))))
16772 (setq nval (or nval (car allowed)))
16773 (if (equal nval value)
16774 (error "Only one allowed value for this property")))
16775 (let ((inhibit-read-only t))
16776 (remove-text-properties (1- bol) eol '(read-only t))
16777 (unwind-protect
16778 (progn
16779 (setq org-columns-overlays
16780 (org-delete-all line-overlays org-columns-overlays))
16781 (mapc 'org-delete-overlay line-overlays)
16782 (org-columns-eval '(org-entry-put pom key nval)))
16783 (org-columns-display-here)))
16784 (move-to-column col)
16785 (if (and (org-mode-p)
16786 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16787 (org-columns-update key))))
16789 (defun org-verify-version (task)
16790 (cond
16791 ((eq task 'columns)
16792 (if (or (featurep 'xemacs)
16793 (< emacs-major-version 22))
16794 (error "Emacs 22 is required for the columns feature")))))
16796 (defun org-columns-open-link (&optional arg)
16797 (interactive "P")
16798 (let ((key (get-char-property (point) 'org-columns-key))
16799 (value (get-char-property (point) 'org-columns-value)))
16800 (org-open-link-from-string arg)))
16802 (defun org-open-link-from-string (s &optional arg)
16803 "Open a link in the string S, as if it was in Org-mode."
16804 (interactive)
16805 (with-temp-buffer
16806 (let ((org-inhibit-startup t))
16807 (org-mode)
16808 (insert s)
16809 (goto-char (point-min))
16810 (org-open-at-point arg))))
16812 (defun org-columns-get-format-and-top-level ()
16813 (let (fmt)
16814 (when (condition-case nil (org-back-to-heading) (error nil))
16815 (move-marker org-entry-property-inherited-from nil)
16816 (setq fmt (org-entry-get nil "COLUMNS" t)))
16817 (setq fmt (or fmt org-columns-default-format))
16818 (org-set-local 'org-columns-current-fmt fmt)
16819 (org-columns-compile-format fmt)
16820 (if (marker-position org-entry-property-inherited-from)
16821 (move-marker org-columns-top-level-marker
16822 org-entry-property-inherited-from)
16823 (move-marker org-columns-top-level-marker (point)))
16824 fmt))
16826 (defun org-columns ()
16827 "Turn on column view on an org-mode file."
16828 (interactive)
16829 (org-verify-version 'columns)
16830 (org-columns-remove-overlays)
16831 (move-marker org-columns-begin-marker (point))
16832 (let (beg end fmt cache maxwidths clocksump)
16833 (setq fmt (org-columns-get-format-and-top-level))
16834 (save-excursion
16835 (goto-char org-columns-top-level-marker)
16836 (setq beg (point))
16837 (unless org-columns-inhibit-recalculation
16838 (org-columns-compute-all))
16839 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16840 (point-max)))
16841 ;; Get and cache the properties
16842 (goto-char beg)
16843 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16844 (setq clocksump t)
16845 (save-excursion
16846 (save-restriction
16847 (narrow-to-region beg end)
16848 (org-clock-sum))))
16849 (while (re-search-forward (concat "^" outline-regexp) end t)
16850 (push (cons (org-current-line) (org-entry-properties)) cache))
16851 (when cache
16852 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16853 (org-set-local 'org-columns-current-maxwidths maxwidths)
16854 (org-columns-display-here-title)
16855 (mapc (lambda (x)
16856 (goto-line (car x))
16857 (org-columns-display-here (cdr x)))
16858 cache)))))
16860 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16861 "Insert a new column, to the leeft o the current column."
16862 (interactive)
16863 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16864 cell)
16865 (setq prop (completing-read
16866 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
16867 nil nil prop))
16868 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16869 (setq width (read-string "Column width: " (if width (number-to-string width))))
16870 (if (string-match "\\S-" width)
16871 (setq width (string-to-number width))
16872 (setq width nil))
16873 (setq fmt (completing-read "Summary [none]: "
16874 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16875 nil t))
16876 (if (string-match "\\S-" fmt)
16877 (setq fmt (intern fmt))
16878 (setq fmt nil))
16879 (if (eq fmt 'none) (setq fmt nil))
16880 (if editp
16881 (progn
16882 (setcar editp prop)
16883 (setcdr editp (list title width nil fmt)))
16884 (setq cell (nthcdr (1- (current-column))
16885 org-columns-current-fmt-compiled))
16886 (setcdr cell (cons (list prop title width nil fmt)
16887 (cdr cell))))
16888 (org-columns-store-format)
16889 (org-columns-redo)))
16891 (defun org-columns-delete ()
16892 "Delete the column at point from columns view."
16893 (interactive)
16894 (let* ((n (current-column))
16895 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16896 (when (y-or-n-p
16897 (format "Are you sure you want to remove column \"%s\"? " title))
16898 (setq org-columns-current-fmt-compiled
16899 (delq (nth n org-columns-current-fmt-compiled)
16900 org-columns-current-fmt-compiled))
16901 (org-columns-store-format)
16902 (org-columns-redo)
16903 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16904 (backward-char 1)))))
16906 (defun org-columns-edit-attributes ()
16907 "Edit the attributes of the current column."
16908 (interactive)
16909 (let* ((n (current-column))
16910 (info (nth n org-columns-current-fmt-compiled)))
16911 (apply 'org-columns-new info)))
16913 (defun org-columns-widen (arg)
16914 "Make the column wider by ARG characters."
16915 (interactive "p")
16916 (let* ((n (current-column))
16917 (entry (nth n org-columns-current-fmt-compiled))
16918 (width (or (nth 2 entry)
16919 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16920 (setq width (max 1 (+ width arg)))
16921 (setcar (nthcdr 2 entry) width)
16922 (org-columns-store-format)
16923 (org-columns-redo)))
16925 (defun org-columns-narrow (arg)
16926 "Make the column nrrower by ARG characters."
16927 (interactive "p")
16928 (org-columns-widen (- arg)))
16930 (defun org-columns-move-right ()
16931 "Swap this column with the one to the right."
16932 (interactive)
16933 (let* ((n (current-column))
16934 (cell (nthcdr n org-columns-current-fmt-compiled))
16936 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16937 (error "Cannot shift this column further to the right"))
16938 (setq e (car cell))
16939 (setcar cell (car (cdr cell)))
16940 (setcdr cell (cons e (cdr (cdr cell))))
16941 (org-columns-store-format)
16942 (org-columns-redo)
16943 (forward-char 1)))
16945 (defun org-columns-move-left ()
16946 "Swap this column with the one to the left."
16947 (interactive)
16948 (let* ((n (current-column)))
16949 (when (= n 0)
16950 (error "Cannot shift this column further to the left"))
16951 (backward-char 1)
16952 (org-columns-move-right)
16953 (backward-char 1)))
16955 (defun org-columns-store-format ()
16956 "Store the text version of the current columns format in appropriate place.
16957 This is either in the COLUMNS property of the node starting the current column
16958 display, or in the #+COLUMNS line of the current buffer."
16959 (let (fmt (cnt 0))
16960 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16961 (org-set-local 'org-columns-current-fmt fmt)
16962 (if (marker-position org-columns-top-level-marker)
16963 (save-excursion
16964 (goto-char org-columns-top-level-marker)
16965 (if (and (org-at-heading-p)
16966 (org-entry-get nil "COLUMNS"))
16967 (org-entry-put nil "COLUMNS" fmt)
16968 (goto-char (point-min))
16969 ;; Overwrite all #+COLUMNS lines....
16970 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16971 (setq cnt (1+ cnt))
16972 (replace-match (concat "#+COLUMNS: " fmt) t t))
16973 (unless (> cnt 0)
16974 (goto-char (point-min))
16975 (or (org-on-heading-p t) (outline-next-heading))
16976 (let ((inhibit-read-only t))
16977 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16978 (org-set-local 'org-columns-default-format fmt))))))
16980 (defvar org-overriding-columns-format nil
16981 "When set, overrides any other definition.")
16982 (defvar org-agenda-view-columns-initially nil
16983 "When set, switch to columns view immediately after creating the agenda.")
16985 (defun org-agenda-columns ()
16986 "Turn on column view in the agenda."
16987 (interactive)
16988 (org-verify-version 'columns)
16989 (org-columns-remove-overlays)
16990 (move-marker org-columns-begin-marker (point))
16991 (let (fmt cache maxwidths m)
16992 (cond
16993 ((and (local-variable-p 'org-overriding-columns-format)
16994 org-overriding-columns-format)
16995 (setq fmt org-overriding-columns-format))
16996 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16997 (setq fmt (org-entry-get m "COLUMNS" t)))
16998 ((and (boundp 'org-columns-current-fmt)
16999 (local-variable-p 'org-columns-current-fmt)
17000 org-columns-current-fmt)
17001 (setq fmt org-columns-current-fmt))
17002 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17003 (setq m (get-text-property m 'org-hd-marker))
17004 (setq fmt (org-entry-get m "COLUMNS" t))))
17005 (setq fmt (or fmt org-columns-default-format))
17006 (org-set-local 'org-columns-current-fmt fmt)
17007 (org-columns-compile-format fmt)
17008 (save-excursion
17009 ;; Get and cache the properties
17010 (goto-char (point-min))
17011 (while (not (eobp))
17012 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17013 (get-text-property (point) 'org-marker)))
17014 (push (cons (org-current-line) (org-entry-properties m)) cache))
17015 (beginning-of-line 2))
17016 (when cache
17017 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17018 (org-set-local 'org-columns-current-maxwidths maxwidths)
17019 (org-columns-display-here-title)
17020 (mapc (lambda (x)
17021 (goto-line (car x))
17022 (org-columns-display-here (cdr x)))
17023 cache)))))
17025 (defun org-columns-get-autowidth-alist (s cache)
17026 "Derive the maximum column widths from the format and the cache."
17027 (let ((start 0) rtn)
17028 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
17029 (push (cons (match-string 1 s) 1) rtn)
17030 (setq start (match-end 0)))
17031 (mapc (lambda (x)
17032 (setcdr x (apply 'max
17033 (mapcar
17034 (lambda (y)
17035 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17036 cache))))
17037 rtn)
17038 rtn))
17040 (defun org-columns-compute-all ()
17041 "Compute all columns that have operators defined."
17042 (org-unmodified
17043 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17044 (let ((columns org-columns-current-fmt-compiled) col)
17045 (while (setq col (pop columns))
17046 (when (nth 3 col)
17047 (save-excursion
17048 (org-columns-compute (car col)))))))
17050 (defun org-columns-update (property)
17051 "Recompute PROPERTY, and update the columns display for it."
17052 (org-columns-compute property)
17053 (let (fmt val pos)
17054 (save-excursion
17055 (mapc (lambda (ov)
17056 (when (equal (org-overlay-get ov 'org-columns-key) property)
17057 (setq pos (org-overlay-start ov))
17058 (goto-char pos)
17059 (when (setq val (cdr (assoc property
17060 (get-text-property
17061 (point-at-bol) 'org-summaries))))
17062 (setq fmt (org-overlay-get ov 'org-columns-format))
17063 (org-overlay-put ov 'org-columns-value val)
17064 (org-overlay-put ov 'display (format fmt val)))))
17065 org-columns-overlays))))
17067 (defun org-columns-compute (property)
17068 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17069 (interactive)
17070 (let* ((re (concat "^" outline-regexp))
17071 (lmax 30) ; Does anyone use deeper levels???
17072 (lsum (make-vector lmax 0))
17073 (lflag (make-vector lmax nil))
17074 (level 0)
17075 (ass (assoc property org-columns-current-fmt-compiled))
17076 (format (nth 4 ass))
17077 (printf (nth 5 ass))
17078 (beg org-columns-top-level-marker)
17079 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17080 (save-excursion
17081 ;; Find the region to compute
17082 (goto-char beg)
17083 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17084 (goto-char end)
17085 ;; Walk the tree from the back and do the computations
17086 (while (re-search-backward re beg t)
17087 (setq sumpos (match-beginning 0)
17088 last-level level
17089 level (org-outline-level)
17090 val (org-entry-get nil property)
17091 valflag (and val (string-match "\\S-" val)))
17092 (cond
17093 ((< level last-level)
17094 ;; put the sum of lower levels here as a property
17095 (setq sum (aref lsum last-level) ; current sum
17096 flag (aref lflag last-level) ; any valid entries from children?
17097 str (org-column-number-to-string sum format printf)
17098 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17099 useval (if flag str1 (if valflag val ""))
17100 sum-alist (get-text-property sumpos 'org-summaries))
17101 (if (assoc property sum-alist)
17102 (setcdr (assoc property sum-alist) useval)
17103 (push (cons property useval) sum-alist)
17104 (org-unmodified
17105 (add-text-properties sumpos (1+ sumpos)
17106 (list 'org-summaries sum-alist))))
17107 (when val
17108 (org-entry-put nil property (if flag str val)))
17109 ;; add current to current level accumulator
17110 (when (or flag valflag)
17111 (aset lsum level (+ (aref lsum level)
17112 (if flag sum (org-column-string-to-number
17113 (if flag str val) format))))
17114 (aset lflag level t))
17115 ;; clear accumulators for deeper levels
17116 (loop for l from (1+ level) to (1- lmax) do
17117 (aset lsum l 0)
17118 (aset lflag l nil)))
17119 ((>= level last-level)
17120 ;; add what we have here to the accumulator for this level
17121 (aset lsum level (+ (aref lsum level)
17122 (org-column-string-to-number (or val "0") format)))
17123 (and valflag (aset lflag level t)))
17124 (t (error "This should not happen")))))))
17126 (defun org-columns-redo ()
17127 "Construct the column display again."
17128 (interactive)
17129 (message "Recomputing columns...")
17130 (save-excursion
17131 (if (marker-position org-columns-begin-marker)
17132 (goto-char org-columns-begin-marker))
17133 (org-columns-remove-overlays)
17134 (if (org-mode-p)
17135 (call-interactively 'org-columns)
17136 (call-interactively 'org-agenda-columns)))
17137 (message "Recomputing columns...done"))
17139 (defun org-columns-not-in-agenda ()
17140 (if (eq major-mode 'org-agenda-mode)
17141 (error "This command is only allowed in Org-mode buffers")))
17144 (defun org-string-to-number (s)
17145 "Convert string to number, and interpret hh:mm:ss."
17146 (if (not (string-match ":" s))
17147 (string-to-number s)
17148 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17149 (while l
17150 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17151 sum)))
17153 (defun org-column-number-to-string (n fmt &optional printf)
17154 "Convert a computed column number to a string value, according to FMT."
17155 (cond
17156 ((eq fmt 'add_times)
17157 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17158 (format "%d:%02d" h m)))
17159 ((eq fmt 'checkbox)
17160 (cond ((= n (floor n)) "[X]")
17161 ((> n 1.) "[-]")
17162 (t "[ ]")))
17163 (printf (format printf n))
17164 ((eq fmt 'currency)
17165 (format "%.2f" n))
17166 (t (number-to-string n))))
17168 (defun org-column-string-to-number (s fmt)
17169 "Convert a column value to a number that can be used for column computing."
17170 (cond
17171 ((string-match ":" s)
17172 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17173 (while l
17174 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17175 sum))
17176 ((eq fmt 'checkbox)
17177 (if (equal s "[X]") 1. 0.000001))
17178 (t (string-to-number s))))
17180 (defun org-columns-uncompile-format (cfmt)
17181 "Turn the compiled columns format back into a string representation."
17182 (let ((rtn "") e s prop title op width fmt printf)
17183 (while (setq e (pop cfmt))
17184 (setq prop (car e)
17185 title (nth 1 e)
17186 width (nth 2 e)
17187 op (nth 3 e)
17188 fmt (nth 4 e)
17189 printf (nth 5 e))
17190 (cond
17191 ((eq fmt 'add_times) (setq op ":"))
17192 ((eq fmt 'checkbox) (setq op "X"))
17193 ((eq fmt 'add_numbers) (setq op "+"))
17194 ((eq fmt 'currency) (setq op "$")))
17195 (if (and op printf) (setq op (concat op ";" printf)))
17196 (if (equal title prop) (setq title nil))
17197 (setq s (concat "%" (if width (number-to-string width))
17198 prop
17199 (if title (concat "(" title ")"))
17200 (if op (concat "{" op "}"))))
17201 (setq rtn (concat rtn " " s)))
17202 (org-trim rtn)))
17204 (defun org-columns-compile-format (fmt)
17205 "Turn a column format string into an alist of specifications.
17206 The alist has one entry for each column in the format. The elements of
17207 that list are:
17208 property the property
17209 title the title field for the columns
17210 width the column width in characters, can be nil for automatic
17211 operator the operator if any
17212 format the output format for computed results, derived from operator
17213 printf a printf format for computed values"
17214 (let ((start 0) width prop title op f printf)
17215 (setq org-columns-current-fmt-compiled nil)
17216 (while (string-match
17217 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17218 fmt start)
17219 (setq start (match-end 0)
17220 width (match-string 1 fmt)
17221 prop (match-string 2 fmt)
17222 title (or (match-string 3 fmt) prop)
17223 op (match-string 4 fmt)
17224 f nil
17225 printf nil)
17226 (if width (setq width (string-to-number width)))
17227 (when (and op (string-match ";" op))
17228 (setq printf (substring op (match-end 0))
17229 op (substring op 0 (match-beginning 0))))
17230 (cond
17231 ((equal op "+") (setq f 'add_numbers))
17232 ((equal op "$") (setq f 'currency))
17233 ((equal op ":") (setq f 'add_times))
17234 ((equal op "X") (setq f 'checkbox)))
17235 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17236 (setq org-columns-current-fmt-compiled
17237 (nreverse org-columns-current-fmt-compiled))))
17240 ;;; Dynamic block for Column view
17242 (defun org-columns-capture-view ()
17243 "Get the column view of the current buffer and return it as a list.
17244 The list will contains the title row and all other rows. Each row is
17245 a list of fields."
17246 (save-excursion
17247 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17248 (n (length title)) row tbl)
17249 (goto-char (point-min))
17250 (while (re-search-forward "^\\*+ " nil t)
17251 (when (get-char-property (match-beginning 0) 'org-columns-key)
17252 (setq row nil)
17253 (loop for i from 0 to (1- n) do
17254 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17255 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17257 row))
17258 (setq row (nreverse row))
17259 (push row tbl)))
17260 (append (list title 'hline) (nreverse tbl)))))
17262 (defun org-dblock-write:columnview (params)
17263 "Write the column view table.
17264 PARAMS is a property list of parameters:
17266 :width enforce same column widths with <N> specifiers.
17267 :id the :ID: property of the entry where the columns view
17268 should be built, as a string. When `local', call locally.
17269 When `global' call column view with the cursor at the beginning
17270 of the buffer (usually this means that the whole buffer switches
17271 to column view).
17272 :hlines When t, insert a hline before each item. When a number, insert
17273 a hline before each level <= that number.
17274 :vlines When t, make each column a colgroup to enforce vertical lines."
17275 (let ((pos (move-marker (make-marker) (point)))
17276 (hlines (plist-get params :hlines))
17277 (vlines (plist-get params :vlines))
17278 tbl id idpos nfields tmp)
17279 (save-excursion
17280 (save-restriction
17281 (when (setq id (plist-get params :id))
17282 (cond ((not id) nil)
17283 ((eq id 'global) (goto-char (point-min)))
17284 ((eq id 'local) nil)
17285 ((setq idpos (org-find-entry-with-id id))
17286 (goto-char idpos))
17287 (t (error "Cannot find entry with :ID: %s" id))))
17288 (org-columns)
17289 (setq tbl (org-columns-capture-view))
17290 (setq nfields (length (car tbl)))
17291 (org-columns-quit)))
17292 (goto-char pos)
17293 (move-marker pos nil)
17294 (when tbl
17295 (when (plist-get params :hlines)
17296 (setq tmp nil)
17297 (while tbl
17298 (if (eq (car tbl) 'hline)
17299 (push (pop tbl) tmp)
17300 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17301 (if (and (not (eq (car tmp) 'hline))
17302 (or (eq hlines t)
17303 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17304 (push 'hline tmp)))
17305 (push (pop tbl) tmp)))
17306 (setq tbl (nreverse tmp)))
17307 (when vlines
17308 (setq tbl (mapcar (lambda (x)
17309 (if (eq 'hline x) x (cons "" x)))
17310 tbl))
17311 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17312 (setq pos (point))
17313 (insert (org-listtable-to-string tbl))
17314 (when (plist-get params :width)
17315 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17316 org-columns-current-widths "|")))
17317 (goto-char pos)
17318 (org-table-align))))
17320 (defun org-listtable-to-string (tbl)
17321 "Convert a listtable TBL to a string that contains the Org-mode table.
17322 The table still need to be alligned. The resulting string has no leading
17323 and tailing newline characters."
17324 (mapconcat
17325 (lambda (x)
17326 (cond
17327 ((listp x)
17328 (concat "|" (mapconcat 'identity x "|") "|"))
17329 ((eq x 'hline) "|-|")
17330 (t (error "Garbage in listtable: %s" x))))
17331 tbl "\n"))
17333 (defun org-insert-columns-dblock ()
17334 "Create a dynamic block capturing a column view table."
17335 (interactive)
17336 (let ((defaults '(:name "columnview" :hlines 1))
17337 (id (completing-read
17338 "Capture columns (local, global, entry with :ID: property) [local]: "
17339 (append '(("global") ("local"))
17340 (mapcar 'list (org-property-values "ID"))))))
17341 (if (equal id "") (setq id 'local))
17342 (if (equal id "global") (setq id 'global))
17343 (setq defaults (append defaults (list :id id)))
17344 (org-create-dblock defaults)
17345 (org-update-dblock)))
17347 ;;;; Timestamps
17349 (defvar org-last-changed-timestamp nil)
17350 (defvar org-time-was-given) ; dynamically scoped parameter
17351 (defvar org-end-time-was-given) ; dynamically scoped parameter
17352 (defvar org-ts-what) ; dynamically scoped parameter
17354 (defun org-time-stamp (arg)
17355 "Prompt for a date/time and insert a time stamp.
17356 If the user specifies a time like HH:MM, or if this command is called
17357 with a prefix argument, the time stamp will contain date and time.
17358 Otherwise, only the date will be included. All parts of a date not
17359 specified by the user will be filled in from the current date/time.
17360 So if you press just return without typing anything, the time stamp
17361 will represent the current date/time. If there is already a timestamp
17362 at the cursor, it will be modified."
17363 (interactive "P")
17364 (let* ((ts nil)
17365 (default-time
17366 ;; Default time is either today, or, when entering a range,
17367 ;; the range start.
17368 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17369 (save-excursion
17370 (re-search-backward
17371 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17372 (- (point) 20) t)))
17373 (apply 'encode-time (org-parse-time-string (match-string 1)))
17374 (current-time)))
17375 (default-input (and ts (org-get-compact-tod ts)))
17376 org-time-was-given org-end-time-was-given time)
17377 (cond
17378 ((and (org-at-timestamp-p)
17379 (eq last-command 'org-time-stamp)
17380 (eq this-command 'org-time-stamp))
17381 (insert "--")
17382 (setq time (let ((this-command this-command))
17383 (org-read-date arg 'totime nil nil default-time default-input)))
17384 (org-insert-time-stamp time (or org-time-was-given arg)))
17385 ((org-at-timestamp-p)
17386 (setq time (let ((this-command this-command))
17387 (org-read-date arg 'totime nil nil default-time default-input)))
17388 (when (org-at-timestamp-p) ; just to get the match data
17389 (replace-match "")
17390 (setq org-last-changed-timestamp
17391 (org-insert-time-stamp
17392 time (or org-time-was-given arg)
17393 nil nil nil (list org-end-time-was-given))))
17394 (message "Timestamp updated"))
17396 (setq time (let ((this-command this-command))
17397 (org-read-date arg 'totime nil nil default-time default-input)))
17398 (org-insert-time-stamp time (or org-time-was-given arg)
17399 nil nil nil (list org-end-time-was-given))))))
17401 ;; FIXME: can we use this for something else????
17402 ;; like computing time differences?????
17403 (defun org-get-compact-tod (s)
17404 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17405 (let* ((t1 (match-string 1 s))
17406 (h1 (string-to-number (match-string 2 s)))
17407 (m1 (string-to-number (match-string 3 s)))
17408 (t2 (and (match-end 4) (match-string 5 s)))
17409 (h2 (and t2 (string-to-number (match-string 6 s))))
17410 (m2 (and t2 (string-to-number (match-string 7 s))))
17411 dh dm)
17412 (if (not t2)
17414 (setq dh (- h2 h1) dm (- m2 m1))
17415 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17416 (concat t1 "+" (number-to-string dh)
17417 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17419 (defun org-time-stamp-inactive (&optional arg)
17420 "Insert an inactive time stamp.
17421 An inactive time stamp is enclosed in square brackets instead of angle
17422 brackets. It is inactive in the sense that it does not trigger agenda entries,
17423 does not link to the calendar and cannot be changed with the S-cursor keys.
17424 So these are more for recording a certain time/date."
17425 (interactive "P")
17426 (let (org-time-was-given org-end-time-was-given time)
17427 (setq time (org-read-date arg 'totime))
17428 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17429 nil nil (list org-end-time-was-given))))
17431 (defvar org-date-ovl (org-make-overlay 1 1))
17432 (org-overlay-put org-date-ovl 'face 'org-warning)
17433 (org-detach-overlay org-date-ovl)
17435 (defvar org-ans1) ; dynamically scoped parameter
17436 (defvar org-ans2) ; dynamically scoped parameter
17438 (defvar org-plain-time-of-day-regexp) ; defined below
17440 (defvar org-read-date-overlay nil)
17441 (defvar org-dcst nil) ; dynamically scoped
17443 (defun org-read-date (&optional with-time to-time from-string prompt
17444 default-time default-input)
17445 "Read a date, possibly a time, and make things smooth for the user.
17446 The prompt will suggest to enter an ISO date, but you can also enter anything
17447 which will at least partially be understood by `parse-time-string'.
17448 Unrecognized parts of the date will default to the current day, month, year,
17449 hour and minute. If this command is called to replace a timestamp at point,
17450 of to enter the second timestamp of a range, the default time is taken from the
17451 existing stamp. For example,
17452 3-2-5 --> 2003-02-05
17453 feb 15 --> currentyear-02-15
17454 sep 12 9 --> 2009-09-12
17455 12:45 --> today 12:45
17456 22 sept 0:34 --> currentyear-09-22 0:34
17457 12 --> currentyear-currentmonth-12
17458 Fri --> nearest Friday (today or later)
17459 etc.
17461 Furthermore you can specify a relative date by giving, as the *first* thing
17462 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17463 change in days weeks, months, years.
17464 With a single plus or minus, the date is relative to today. With a double
17465 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17466 +4d --> four days from today
17467 +4 --> same as above
17468 +2w --> two weeks from today
17469 ++5 --> five days from default date
17471 The function understands only English month and weekday abbreviations,
17472 but this can be configured with the variables `parse-time-months' and
17473 `parse-time-weekdays'.
17475 While prompting, a calendar is popped up - you can also select the
17476 date with the mouse (button 1). The calendar shows a period of three
17477 months. To scroll it to other months, use the keys `>' and `<'.
17478 If you don't like the calendar, turn it off with
17479 \(setq org-read-date-popup-calendar nil)
17481 With optional argument TO-TIME, the date will immediately be converted
17482 to an internal time.
17483 With an optional argument WITH-TIME, the prompt will suggest to also
17484 insert a time. Note that when WITH-TIME is not set, you can still
17485 enter a time, and this function will inform the calling routine about
17486 this change. The calling routine may then choose to change the format
17487 used to insert the time stamp into the buffer to include the time.
17488 With optional argument FROM-STRING, read from this string instead from
17489 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17490 the time/date that is used for everything that is not specified by the
17491 user."
17492 (require 'parse-time)
17493 (let* ((org-time-stamp-rounding-minutes
17494 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17495 (org-dcst org-display-custom-times)
17496 (ct (org-current-time))
17497 (def (or default-time ct))
17498 (defdecode (decode-time def))
17499 (dummy (progn
17500 (when (< (nth 2 defdecode) org-extend-today-until)
17501 (setcar (nthcdr 2 defdecode) -1)
17502 (setcar (nthcdr 1 defdecode) 59)
17503 (setq def (apply 'encode-time defdecode)
17504 defdecode (decode-time def)))))
17505 (calendar-move-hook nil)
17506 (view-diary-entries-initially nil)
17507 (view-calendar-holidays-initially nil)
17508 (timestr (format-time-string
17509 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17510 (prompt (concat (if prompt (concat prompt " ") "")
17511 (format "Date+time [%s]: " timestr)))
17512 ans (org-ans0 "") org-ans1 org-ans2 final)
17514 (cond
17515 (from-string (setq ans from-string))
17516 (org-read-date-popup-calendar
17517 (save-excursion
17518 (save-window-excursion
17519 (calendar)
17520 (calendar-forward-day (- (time-to-days def)
17521 (calendar-absolute-from-gregorian
17522 (calendar-current-date))))
17523 (org-eval-in-calendar nil t)
17524 (let* ((old-map (current-local-map))
17525 (map (copy-keymap calendar-mode-map))
17526 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17527 (org-defkey map (kbd "RET") 'org-calendar-select)
17528 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17529 'org-calendar-select-mouse)
17530 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17531 'org-calendar-select-mouse)
17532 (org-defkey minibuffer-local-map [(meta shift left)]
17533 (lambda () (interactive)
17534 (org-eval-in-calendar '(calendar-backward-month 1))))
17535 (org-defkey minibuffer-local-map [(meta shift right)]
17536 (lambda () (interactive)
17537 (org-eval-in-calendar '(calendar-forward-month 1))))
17538 (org-defkey minibuffer-local-map [(meta shift up)]
17539 (lambda () (interactive)
17540 (org-eval-in-calendar '(calendar-backward-year 1))))
17541 (org-defkey minibuffer-local-map [(meta shift down)]
17542 (lambda () (interactive)
17543 (org-eval-in-calendar '(calendar-forward-year 1))))
17544 (org-defkey minibuffer-local-map [(shift up)]
17545 (lambda () (interactive)
17546 (org-eval-in-calendar '(calendar-backward-week 1))))
17547 (org-defkey minibuffer-local-map [(shift down)]
17548 (lambda () (interactive)
17549 (org-eval-in-calendar '(calendar-forward-week 1))))
17550 (org-defkey minibuffer-local-map [(shift left)]
17551 (lambda () (interactive)
17552 (org-eval-in-calendar '(calendar-backward-day 1))))
17553 (org-defkey minibuffer-local-map [(shift right)]
17554 (lambda () (interactive)
17555 (org-eval-in-calendar '(calendar-forward-day 1))))
17556 (org-defkey minibuffer-local-map ">"
17557 (lambda () (interactive)
17558 (org-eval-in-calendar '(scroll-calendar-left 1))))
17559 (org-defkey minibuffer-local-map "<"
17560 (lambda () (interactive)
17561 (org-eval-in-calendar '(scroll-calendar-right 1))))
17562 (unwind-protect
17563 (progn
17564 (use-local-map map)
17565 (add-hook 'post-command-hook 'org-read-date-display)
17566 (setq org-ans0 (read-string prompt default-input nil nil))
17567 ;; org-ans0: from prompt
17568 ;; org-ans1: from mouse click
17569 ;; org-ans2: from calendar motion
17570 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17571 (remove-hook 'post-command-hook 'org-read-date-display)
17572 (use-local-map old-map)
17573 (when org-read-date-overlay
17574 (org-delete-overlay org-read-date-overlay)
17575 (setq org-read-date-overlay nil)))))))
17577 (t ; Naked prompt only
17578 (unwind-protect
17579 (setq ans (read-string prompt default-input nil timestr))
17580 (when org-read-date-overlay
17581 (org-delete-overlay org-read-date-overlay)
17582 (setq org-read-date-overlay nil)))))
17584 (setq final (org-read-date-analyze ans def defdecode))
17586 (if to-time
17587 (apply 'encode-time final)
17588 (if (and (boundp 'org-time-was-given) org-time-was-given)
17589 (format "%04d-%02d-%02d %02d:%02d"
17590 (nth 5 final) (nth 4 final) (nth 3 final)
17591 (nth 2 final) (nth 1 final))
17592 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17593 (defvar def)
17594 (defvar defdecode)
17595 (defvar with-time)
17596 (defun org-read-date-display ()
17597 "Display the currrent date prompt interpretation in the minibuffer."
17598 (when org-read-date-display-live
17599 (when org-read-date-overlay
17600 (org-delete-overlay org-read-date-overlay))
17601 (let ((p (point)))
17602 (end-of-line 1)
17603 (while (not (equal (buffer-substring
17604 (max (point-min) (- (point) 4)) (point))
17605 " "))
17606 (insert " "))
17607 (goto-char p))
17608 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17609 " " (or org-ans1 org-ans2)))
17610 (org-end-time-was-given nil)
17611 (f (org-read-date-analyze ans def defdecode))
17612 (fmts (if org-dcst
17613 org-time-stamp-custom-formats
17614 org-time-stamp-formats))
17615 (fmt (if (or with-time
17616 (and (boundp 'org-time-was-given) org-time-was-given))
17617 (cdr fmts)
17618 (car fmts)))
17619 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17620 (when (and org-end-time-was-given
17621 (string-match org-plain-time-of-day-regexp txt))
17622 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17623 org-end-time-was-given
17624 (substring txt (match-end 0)))))
17625 (setq org-read-date-overlay
17626 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17627 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17629 (defun org-read-date-analyze (ans def defdecode)
17630 "Analyze the combined answer of the date prompt."
17631 ;; FIXME: cleanup and comment
17632 (let (delta deltan deltaw deltadef year month day
17633 hour minute second wday pm h2 m2 tl wday1)
17635 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17636 (setq ans (replace-match "" t t ans)
17637 deltan (car delta)
17638 deltaw (nth 1 delta)
17639 deltadef (nth 2 delta)))
17641 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17642 (when (string-match
17643 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17644 (setq year (if (match-end 2)
17645 (string-to-number (match-string 2 ans))
17646 (string-to-number (format-time-string "%Y")))
17647 month (string-to-number (match-string 3 ans))
17648 day (string-to-number (match-string 4 ans)))
17649 (if (< year 100) (setq year (+ 2000 year)))
17650 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17651 t nil ans)))
17652 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17653 ;; If there is a time with am/pm, and *no* time without it, we convert
17654 ;; so that matching will be successful.
17655 (loop for i from 1 to 2 do ; twice, for end time as well
17656 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17657 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17658 (setq hour (string-to-number (match-string 1 ans))
17659 minute (if (match-end 3)
17660 (string-to-number (match-string 3 ans))
17662 pm (equal ?p
17663 (string-to-char (downcase (match-string 4 ans)))))
17664 (if (and (= hour 12) (not pm))
17665 (setq hour 0)
17666 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17667 (setq ans (replace-match (format "%02d:%02d" hour minute)
17668 t t ans))))
17670 ;; Check if a time range is given as a duration
17671 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17672 (setq hour (string-to-number (match-string 1 ans))
17673 h2 (+ hour (string-to-number (match-string 3 ans)))
17674 minute (string-to-number (match-string 2 ans))
17675 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17676 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17677 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17679 ;; Check if there is a time range
17680 (when (boundp 'org-end-time-was-given)
17681 (setq org-time-was-given nil)
17682 (when (and (string-match org-plain-time-of-day-regexp ans)
17683 (match-end 8))
17684 (setq org-end-time-was-given (match-string 8 ans))
17685 (setq ans (concat (substring ans 0 (match-beginning 7))
17686 (substring ans (match-end 7))))))
17688 (setq tl (parse-time-string ans)
17689 day (or (nth 3 tl) (nth 3 defdecode))
17690 month (or (nth 4 tl)
17691 (if (and org-read-date-prefer-future
17692 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17693 (1+ (nth 4 defdecode))
17694 (nth 4 defdecode)))
17695 year (or (nth 5 tl)
17696 (if (and org-read-date-prefer-future
17697 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17698 (1+ (nth 5 defdecode))
17699 (nth 5 defdecode)))
17700 hour (or (nth 2 tl) (nth 2 defdecode))
17701 minute (or (nth 1 tl) (nth 1 defdecode))
17702 second (or (nth 0 tl) 0)
17703 wday (nth 6 tl))
17704 (when deltan
17705 (unless deltadef
17706 (let ((now (decode-time (current-time))))
17707 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17708 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17709 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17710 ((equal deltaw "m") (setq month (+ month deltan)))
17711 ((equal deltaw "y") (setq year (+ year deltan)))))
17712 (when (and wday (not (nth 3 tl)))
17713 ;; Weekday was given, but no day, so pick that day in the week
17714 ;; on or after the derived date.
17715 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17716 (unless (equal wday wday1)
17717 (setq day (+ day (% (- wday wday1 -7) 7)))))
17718 (if (and (boundp 'org-time-was-given)
17719 (nth 2 tl))
17720 (setq org-time-was-given t))
17721 (if (< year 100) (setq year (+ 2000 year)))
17722 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17723 (list second minute hour day month year)))
17725 (defvar parse-time-weekdays)
17727 (defun org-read-date-get-relative (s today default)
17728 "Check string S for special relative date string.
17729 TODAY and DEFAULT are internal times, for today and for a default.
17730 Return shift list (N what def-flag)
17731 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17732 N is the number of WHATs to shift.
17733 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17734 the DEFAULT date rather than TODAY."
17735 (when (string-match
17736 (concat
17737 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17738 "\\([0-9]+\\)?"
17739 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17740 "\\([ \t]\\|$\\)") s)
17741 (let* ((dir (if (match-end 1)
17742 (string-to-char (substring (match-string 1 s) -1))
17743 ?+))
17744 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17745 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17746 (what (if (match-end 3) (match-string 3 s) "d"))
17747 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17748 (date (if rel default today))
17749 (wday (nth 6 (decode-time date)))
17750 delta)
17751 (if wday1
17752 (progn
17753 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17754 (if (= dir ?-) (setq delta (- delta 7)))
17755 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17756 (list delta "d" rel))
17757 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17759 (defun org-eval-in-calendar (form &optional keepdate)
17760 "Eval FORM in the calendar window and return to current window.
17761 Also, store the cursor date in variable org-ans2."
17762 (let ((sw (selected-window)))
17763 (select-window (get-buffer-window "*Calendar*"))
17764 (eval form)
17765 (when (and (not keepdate) (calendar-cursor-to-date))
17766 (let* ((date (calendar-cursor-to-date))
17767 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17768 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17769 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17770 (select-window sw)))
17772 ; ;; Update the prompt to show new default date
17773 ; (save-excursion
17774 ; (goto-char (point-min))
17775 ; (when (and org-ans2
17776 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17777 ; (get-text-property (match-end 0) 'field))
17778 ; (let ((inhibit-read-only t))
17779 ; (replace-match (concat "[" org-ans2 "]") t t)
17780 ; (add-text-properties (point-min) (1+ (match-end 0))
17781 ; (text-properties-at (1+ (point-min)))))))))
17783 (defun org-calendar-select ()
17784 "Return to `org-read-date' with the date currently selected.
17785 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17786 (interactive)
17787 (when (calendar-cursor-to-date)
17788 (let* ((date (calendar-cursor-to-date))
17789 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17790 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17791 (if (active-minibuffer-window) (exit-minibuffer))))
17793 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17794 "Insert a date stamp for the date given by the internal TIME.
17795 WITH-HM means, use the stamp format that includes the time of the day.
17796 INACTIVE means use square brackets instead of angular ones, so that the
17797 stamp will not contribute to the agenda.
17798 PRE and POST are optional strings to be inserted before and after the
17799 stamp.
17800 The command returns the inserted time stamp."
17801 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17802 stamp)
17803 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17804 (insert-before-markers (or pre ""))
17805 (insert-before-markers (setq stamp (format-time-string fmt time)))
17806 (when (listp extra)
17807 (setq extra (car extra))
17808 (if (and (stringp extra)
17809 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17810 (setq extra (format "-%02d:%02d"
17811 (string-to-number (match-string 1 extra))
17812 (string-to-number (match-string 2 extra))))
17813 (setq extra nil)))
17814 (when extra
17815 (backward-char 1)
17816 (insert-before-markers extra)
17817 (forward-char 1))
17818 (insert-before-markers (or post ""))
17819 stamp))
17821 (defun org-toggle-time-stamp-overlays ()
17822 "Toggle the use of custom time stamp formats."
17823 (interactive)
17824 (setq org-display-custom-times (not org-display-custom-times))
17825 (unless org-display-custom-times
17826 (let ((p (point-min)) (bmp (buffer-modified-p)))
17827 (while (setq p (next-single-property-change p 'display))
17828 (if (and (get-text-property p 'display)
17829 (eq (get-text-property p 'face) 'org-date))
17830 (remove-text-properties
17831 p (setq p (next-single-property-change p 'display))
17832 '(display t))))
17833 (set-buffer-modified-p bmp)))
17834 (if (featurep 'xemacs)
17835 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17836 (org-restart-font-lock)
17837 (setq org-table-may-need-update t)
17838 (if org-display-custom-times
17839 (message "Time stamps are overlayed with custom format")
17840 (message "Time stamp overlays removed")))
17842 (defun org-display-custom-time (beg end)
17843 "Overlay modified time stamp format over timestamp between BED and END."
17844 (let* ((ts (buffer-substring beg end))
17845 t1 w1 with-hm tf time str w2 (off 0))
17846 (save-match-data
17847 (setq t1 (org-parse-time-string ts t))
17848 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17849 (setq off (- (match-end 0) (match-beginning 0)))))
17850 (setq end (- end off))
17851 (setq w1 (- end beg)
17852 with-hm (and (nth 1 t1) (nth 2 t1))
17853 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17854 time (org-fix-decoded-time t1)
17855 str (org-add-props
17856 (format-time-string
17857 (substring tf 1 -1) (apply 'encode-time time))
17858 nil 'mouse-face 'highlight)
17859 w2 (length str))
17860 (if (not (= w2 w1))
17861 (add-text-properties (1+ beg) (+ 2 beg)
17862 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17863 (if (featurep 'xemacs)
17864 (progn
17865 (put-text-property beg end 'invisible t)
17866 (put-text-property beg end 'end-glyph (make-glyph str)))
17867 (put-text-property beg end 'display str))))
17869 (defun org-translate-time (string)
17870 "Translate all timestamps in STRING to custom format.
17871 But do this only if the variable `org-display-custom-times' is set."
17872 (when org-display-custom-times
17873 (save-match-data
17874 (let* ((start 0)
17875 (re org-ts-regexp-both)
17876 t1 with-hm inactive tf time str beg end)
17877 (while (setq start (string-match re string start))
17878 (setq beg (match-beginning 0)
17879 end (match-end 0)
17880 t1 (save-match-data
17881 (org-parse-time-string (substring string beg end) t))
17882 with-hm (and (nth 1 t1) (nth 2 t1))
17883 inactive (equal (substring string beg (1+ beg)) "[")
17884 tf (funcall (if with-hm 'cdr 'car)
17885 org-time-stamp-custom-formats)
17886 time (org-fix-decoded-time t1)
17887 str (format-time-string
17888 (concat
17889 (if inactive "[" "<") (substring tf 1 -1)
17890 (if inactive "]" ">"))
17891 (apply 'encode-time time))
17892 string (replace-match str t t string)
17893 start (+ start (length str)))))))
17894 string)
17896 (defun org-fix-decoded-time (time)
17897 "Set 0 instead of nil for the first 6 elements of time.
17898 Don't touch the rest."
17899 (let ((n 0))
17900 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17902 (defun org-days-to-time (timestamp-string)
17903 "Difference between TIMESTAMP-STRING and now in days."
17904 (- (time-to-days (org-time-string-to-time timestamp-string))
17905 (time-to-days (current-time))))
17907 (defun org-deadline-close (timestamp-string &optional ndays)
17908 "Is the time in TIMESTAMP-STRING close to the current date?"
17909 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17910 (and (< (org-days-to-time timestamp-string) ndays)
17911 (not (org-entry-is-done-p))))
17913 (defun org-get-wdays (ts)
17914 "Get the deadline lead time appropriate for timestring TS."
17915 (cond
17916 ((<= org-deadline-warning-days 0)
17917 ;; 0 or negative, enforce this value no matter what
17918 (- org-deadline-warning-days))
17919 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17920 ;; lead time is specified.
17921 (floor (* (string-to-number (match-string 1 ts))
17922 (cdr (assoc (match-string 2 ts)
17923 '(("d" . 1) ("w" . 7)
17924 ("m" . 30.4) ("y" . 365.25)))))))
17925 ;; go for the default.
17926 (t org-deadline-warning-days)))
17928 (defun org-calendar-select-mouse (ev)
17929 "Return to `org-read-date' with the date currently selected.
17930 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17931 (interactive "e")
17932 (mouse-set-point ev)
17933 (when (calendar-cursor-to-date)
17934 (let* ((date (calendar-cursor-to-date))
17935 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17936 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17937 (if (active-minibuffer-window) (exit-minibuffer))))
17939 (defun org-check-deadlines (ndays)
17940 "Check if there are any deadlines due or past due.
17941 A deadline is considered due if it happens within `org-deadline-warning-days'
17942 days from today's date. If the deadline appears in an entry marked DONE,
17943 it is not shown. The prefix arg NDAYS can be used to test that many
17944 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17945 (interactive "P")
17946 (let* ((org-warn-days
17947 (cond
17948 ((equal ndays '(4)) 100000)
17949 (ndays (prefix-numeric-value ndays))
17950 (t (abs org-deadline-warning-days))))
17951 (case-fold-search nil)
17952 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17953 (callback
17954 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17956 (message "%d deadlines past-due or due within %d days"
17957 (org-occur regexp nil callback)
17958 org-warn-days)))
17960 (defun org-check-before-date (date)
17961 "Check if there are deadlines or scheduled entries before DATE."
17962 (interactive (list (org-read-date)))
17963 (let ((case-fold-search nil)
17964 (regexp (concat "\\<\\(" org-deadline-string
17965 "\\|" org-scheduled-string
17966 "\\) *<\\([^>]+\\)>"))
17967 (callback
17968 (lambda () (time-less-p
17969 (org-time-string-to-time (match-string 2))
17970 (org-time-string-to-time date)))))
17971 (message "%d entries before %s"
17972 (org-occur regexp nil callback) date)))
17974 (defun org-evaluate-time-range (&optional to-buffer)
17975 "Evaluate a time range by computing the difference between start and end.
17976 Normally the result is just printed in the echo area, but with prefix arg
17977 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17978 If the time range is actually in a table, the result is inserted into the
17979 next column.
17980 For time difference computation, a year is assumed to be exactly 365
17981 days in order to avoid rounding problems."
17982 (interactive "P")
17984 (org-clock-update-time-maybe)
17985 (save-excursion
17986 (unless (org-at-date-range-p t)
17987 (goto-char (point-at-bol))
17988 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17989 (if (not (org-at-date-range-p t))
17990 (error "Not at a time-stamp range, and none found in current line")))
17991 (let* ((ts1 (match-string 1))
17992 (ts2 (match-string 2))
17993 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17994 (match-end (match-end 0))
17995 (time1 (org-time-string-to-time ts1))
17996 (time2 (org-time-string-to-time ts2))
17997 (t1 (time-to-seconds time1))
17998 (t2 (time-to-seconds time2))
17999 (diff (abs (- t2 t1)))
18000 (negative (< (- t2 t1) 0))
18001 ;; (ys (floor (* 365 24 60 60)))
18002 (ds (* 24 60 60))
18003 (hs (* 60 60))
18004 (fy "%dy %dd %02d:%02d")
18005 (fy1 "%dy %dd")
18006 (fd "%dd %02d:%02d")
18007 (fd1 "%dd")
18008 (fh "%02d:%02d")
18009 y d h m align)
18010 (if havetime
18011 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18013 d (floor (/ diff ds)) diff (mod diff ds)
18014 h (floor (/ diff hs)) diff (mod diff hs)
18015 m (floor (/ diff 60)))
18016 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18018 d (floor (+ (/ diff ds) 0.5))
18019 h 0 m 0))
18020 (if (not to-buffer)
18021 (message "%s" (org-make-tdiff-string y d h m))
18022 (if (org-at-table-p)
18023 (progn
18024 (goto-char match-end)
18025 (setq align t)
18026 (and (looking-at " *|") (goto-char (match-end 0))))
18027 (goto-char match-end))
18028 (if (looking-at
18029 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18030 (replace-match ""))
18031 (if negative (insert " -"))
18032 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18033 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18034 (insert " " (format fh h m))))
18035 (if align (org-table-align))
18036 (message "Time difference inserted")))))
18038 (defun org-make-tdiff-string (y d h m)
18039 (let ((fmt "")
18040 (l nil))
18041 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18042 l (push y l)))
18043 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18044 l (push d l)))
18045 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18046 l (push h l)))
18047 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18048 l (push m l)))
18049 (apply 'format fmt (nreverse l))))
18051 (defun org-time-string-to-time (s)
18052 (apply 'encode-time (org-parse-time-string s)))
18054 (defun org-time-string-to-absolute (s &optional daynr prefer)
18055 "Convert a time stamp to an absolute day number.
18056 If there is a specifyer for a cyclic time stamp, get the closest date to
18057 DAYNR."
18058 (cond
18059 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18060 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18061 daynr
18062 (+ daynr 1000)))
18063 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18064 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18065 (time-to-days (current-time))) (match-string 0 s)
18066 prefer))
18067 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18069 (defun org-time-from-absolute (d)
18070 "Return the time corresponding to date D.
18071 D may be an absolute day number, or a calendar-type list (month day year)."
18072 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18073 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18075 (defun org-calendar-holiday ()
18076 "List of holidays, for Diary display in Org-mode."
18077 (require 'holidays)
18078 (let ((hl (funcall
18079 (if (fboundp 'calendar-check-holidays)
18080 'calendar-check-holidays 'check-calendar-holidays) date)))
18081 (if hl (mapconcat 'identity hl "; "))))
18083 (defun org-diary-sexp-entry (sexp entry date)
18084 "Process a SEXP diary ENTRY for DATE."
18085 (require 'diary-lib)
18086 (let ((result (if calendar-debug-sexp
18087 (let ((stack-trace-on-error t))
18088 (eval (car (read-from-string sexp))))
18089 (condition-case nil
18090 (eval (car (read-from-string sexp)))
18091 (error
18092 (beep)
18093 (message "Bad sexp at line %d in %s: %s"
18094 (org-current-line)
18095 (buffer-file-name) sexp)
18096 (sleep-for 2))))))
18097 (cond ((stringp result) result)
18098 ((and (consp result)
18099 (stringp (cdr result))) (cdr result))
18100 (result entry)
18101 (t nil))))
18103 (defun org-diary-to-ical-string (frombuf)
18104 "Get iCalendar entries from diary entries in buffer FROMBUF.
18105 This uses the icalendar.el library."
18106 (let* ((tmpdir (if (featurep 'xemacs)
18107 (temp-directory)
18108 temporary-file-directory))
18109 (tmpfile (make-temp-name
18110 (expand-file-name "orgics" tmpdir)))
18111 buf rtn b e)
18112 (save-excursion
18113 (set-buffer frombuf)
18114 (icalendar-export-region (point-min) (point-max) tmpfile)
18115 (setq buf (find-buffer-visiting tmpfile))
18116 (set-buffer buf)
18117 (goto-char (point-min))
18118 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18119 (setq b (match-beginning 0)))
18120 (goto-char (point-max))
18121 (if (re-search-backward "^END:VEVENT" nil t)
18122 (setq e (match-end 0)))
18123 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18124 (kill-buffer buf)
18125 (kill-buffer frombuf)
18126 (delete-file tmpfile)
18127 rtn))
18129 (defun org-closest-date (start current change prefer)
18130 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18131 When PREFER is `past' return a date that is either CURRENT or past.
18132 When PREFER is `future', return a date that is either CURRENT or future."
18133 ;; Make the proper lists from the dates
18134 (catch 'exit
18135 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18136 dn dw sday cday n1 n2
18137 d m y y1 y2 date1 date2 nmonths nm ny m2)
18139 (setq start (org-date-to-gregorian start)
18140 current (org-date-to-gregorian
18141 (if org-agenda-repeating-timestamp-show-all
18142 current
18143 (time-to-days (current-time))))
18144 sday (calendar-absolute-from-gregorian start)
18145 cday (calendar-absolute-from-gregorian current))
18147 (if (<= cday sday) (throw 'exit sday))
18149 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18150 (setq dn (string-to-number (match-string 1 change))
18151 dw (cdr (assoc (match-string 2 change) a1)))
18152 (error "Invalid change specifyer: %s" change))
18153 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18154 (cond
18155 ((eq dw 'day)
18156 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18157 n2 (+ n1 dn)))
18158 ((eq dw 'year)
18159 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18160 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18161 (setq date1 (list m d y1)
18162 n1 (calendar-absolute-from-gregorian date1)
18163 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18164 n2 (calendar-absolute-from-gregorian date2)))
18165 ((eq dw 'month)
18166 ;; approx number of month between the tow dates
18167 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18168 ;; How often does dn fit in there?
18169 (setq d (nth 1 start) m (car start) y (nth 2 start)
18170 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18171 m (+ m nm)
18172 ny (floor (/ m 12))
18173 y (+ y ny)
18174 m (- m (* ny 12)))
18175 (while (> m 12) (setq m (- m 12) y (1+ y)))
18176 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
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)))
18180 (while (< n2 cday)
18181 (setq n1 n2 m m2 y y2)
18182 (setq m2 (+ m dn) y2 y)
18183 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18184 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18186 (if org-agenda-repeating-timestamp-show-all
18187 (cond
18188 ((eq prefer 'past) n1)
18189 ((eq prefer 'future) (if (= cday n1) n1 n2))
18190 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18191 (cond
18192 ((eq prefer 'past) n1)
18193 ((eq prefer 'future) (if (= cday n1) n1 n2))
18194 (t (if (= cday n1) n1 n2)))))))
18196 (defun org-date-to-gregorian (date)
18197 "Turn any specification of DATE into a gregorian date for the calendar."
18198 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18199 ((and (listp date) (= (length date) 3)) date)
18200 ((stringp date)
18201 (setq date (org-parse-time-string date))
18202 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18203 ((listp date)
18204 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18206 (defun org-parse-time-string (s &optional nodefault)
18207 "Parse the standard Org-mode time string.
18208 This should be a lot faster than the normal `parse-time-string'.
18209 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18210 hour and minute fields will be nil if not given."
18211 (if (string-match org-ts-regexp0 s)
18212 (list 0
18213 (if (or (match-beginning 8) (not nodefault))
18214 (string-to-number (or (match-string 8 s) "0")))
18215 (if (or (match-beginning 7) (not nodefault))
18216 (string-to-number (or (match-string 7 s) "0")))
18217 (string-to-number (match-string 4 s))
18218 (string-to-number (match-string 3 s))
18219 (string-to-number (match-string 2 s))
18220 nil nil nil)
18221 (make-list 9 0)))
18223 (defun org-timestamp-up (&optional arg)
18224 "Increase the date item at the cursor by one.
18225 If the cursor is on the year, change the year. If it is on the month or
18226 the day, change that.
18227 With prefix ARG, change by that many units."
18228 (interactive "p")
18229 (org-timestamp-change (prefix-numeric-value arg)))
18231 (defun org-timestamp-down (&optional arg)
18232 "Decrease the date item at the cursor by one.
18233 If the cursor is on the year, change the year. If it is on the month or
18234 the day, change that.
18235 With prefix ARG, change by that many units."
18236 (interactive "p")
18237 (org-timestamp-change (- (prefix-numeric-value arg))))
18239 (defun org-timestamp-up-day (&optional arg)
18240 "Increase the date in the time stamp by one day.
18241 With prefix ARG, change that many days."
18242 (interactive "p")
18243 (if (and (not (org-at-timestamp-p t))
18244 (org-on-heading-p))
18245 (org-todo 'up)
18246 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18248 (defun org-timestamp-down-day (&optional arg)
18249 "Decrease the date in the time stamp by one day.
18250 With prefix ARG, change that many days."
18251 (interactive "p")
18252 (if (and (not (org-at-timestamp-p t))
18253 (org-on-heading-p))
18254 (org-todo 'down)
18255 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18257 (defsubst org-pos-in-match-range (pos n)
18258 (and (match-beginning n)
18259 (<= (match-beginning n) pos)
18260 (>= (match-end n) pos)))
18262 (defun org-at-timestamp-p (&optional inactive-ok)
18263 "Determine if the cursor is in or at a timestamp."
18264 (interactive)
18265 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18266 (pos (point))
18267 (ans (or (looking-at tsr)
18268 (save-excursion
18269 (skip-chars-backward "^[<\n\r\t")
18270 (if (> (point) (point-min)) (backward-char 1))
18271 (and (looking-at tsr)
18272 (> (- (match-end 0) pos) -1))))))
18273 (and ans
18274 (boundp 'org-ts-what)
18275 (setq org-ts-what
18276 (cond
18277 ((= pos (match-beginning 0)) 'bracket)
18278 ((= pos (1- (match-end 0))) 'bracket)
18279 ((org-pos-in-match-range pos 2) 'year)
18280 ((org-pos-in-match-range pos 3) 'month)
18281 ((org-pos-in-match-range pos 7) 'hour)
18282 ((org-pos-in-match-range pos 8) 'minute)
18283 ((or (org-pos-in-match-range pos 4)
18284 (org-pos-in-match-range pos 5)) 'day)
18285 ((and (> pos (or (match-end 8) (match-end 5)))
18286 (< pos (match-end 0)))
18287 (- pos (or (match-end 8) (match-end 5))))
18288 (t 'day))))
18289 ans))
18291 (defun org-toggle-timestamp-type ()
18293 (interactive)
18294 (when (org-at-timestamp-p t)
18295 (save-excursion
18296 (goto-char (match-beginning 0))
18297 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18298 (goto-char (1- (match-end 0)))
18299 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18300 (message "Timestamp is now %sactive"
18301 (if (equal (char-before) ?>) "in" ""))))
18303 (defun org-timestamp-change (n &optional what)
18304 "Change the date in the time stamp at point.
18305 The date will be changed by N times WHAT. WHAT can be `day', `month',
18306 `year', `minute', `second'. If WHAT is not given, the cursor position
18307 in the timestamp determines what will be changed."
18308 (let ((pos (point))
18309 with-hm inactive
18310 org-ts-what
18311 extra
18312 ts time time0)
18313 (if (not (org-at-timestamp-p t))
18314 (error "Not at a timestamp"))
18315 (if (and (not what) (eq org-ts-what 'bracket))
18316 (org-toggle-timestamp-type)
18317 (if (and (not what) (not (eq org-ts-what 'day))
18318 org-display-custom-times
18319 (get-text-property (point) 'display)
18320 (not (get-text-property (1- (point)) 'display)))
18321 (setq org-ts-what 'day))
18322 (setq org-ts-what (or what org-ts-what)
18323 inactive (= (char-after (match-beginning 0)) ?\[)
18324 ts (match-string 0))
18325 (replace-match "")
18326 (if (string-match
18327 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18329 (setq extra (match-string 1 ts)))
18330 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18331 (setq with-hm t))
18332 (setq time0 (org-parse-time-string ts))
18333 (setq time
18334 (encode-time (or (car time0) 0)
18335 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18336 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18337 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18338 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18339 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18340 (nthcdr 6 time0)))
18341 (when (integerp org-ts-what)
18342 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18343 (if (eq what 'calendar)
18344 (let ((cal-date (org-get-date-from-calendar)))
18345 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18346 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18347 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18348 (setcar time0 (or (car time0) 0))
18349 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18350 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18351 (setq time (apply 'encode-time time0))))
18352 (setq org-last-changed-timestamp
18353 (org-insert-time-stamp time with-hm inactive nil nil extra))
18354 (org-clock-update-time-maybe)
18355 (goto-char pos)
18356 ;; Try to recenter the calendar window, if any
18357 (if (and org-calendar-follow-timestamp-change
18358 (get-buffer-window "*Calendar*" t)
18359 (memq org-ts-what '(day month year)))
18360 (org-recenter-calendar (time-to-days time))))))
18362 ;; FIXME: does not yet work for lead times
18363 (defun org-modify-ts-extra (s pos n)
18364 "Change the different parts of the lead-time and repeat fields in timestamp."
18365 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18366 ng h m new)
18367 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18368 (cond
18369 ((or (org-pos-in-match-range pos 2)
18370 (org-pos-in-match-range pos 3))
18371 (setq m (string-to-number (match-string 3 s))
18372 h (string-to-number (match-string 2 s)))
18373 (if (org-pos-in-match-range pos 2)
18374 (setq h (+ h n))
18375 (setq m (+ m n)))
18376 (if (< m 0) (setq m (+ m 60) h (1- h)))
18377 (if (> m 59) (setq m (- m 60) h (1+ h)))
18378 (setq h (min 24 (max 0 h)))
18379 (setq ng 1 new (format "-%02d:%02d" h m)))
18380 ((org-pos-in-match-range pos 6)
18381 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18382 ((org-pos-in-match-range pos 5)
18383 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18385 (when ng
18386 (setq s (concat
18387 (substring s 0 (match-beginning ng))
18389 (substring s (match-end ng))))))
18392 (defun org-recenter-calendar (date)
18393 "If the calendar is visible, recenter it to DATE."
18394 (let* ((win (selected-window))
18395 (cwin (get-buffer-window "*Calendar*" t))
18396 (calendar-move-hook nil))
18397 (when cwin
18398 (select-window cwin)
18399 (calendar-goto-date (if (listp date) date
18400 (calendar-gregorian-from-absolute date)))
18401 (select-window win))))
18403 (defun org-goto-calendar (&optional arg)
18404 "Go to the Emacs calendar at the current date.
18405 If there is a time stamp in the current line, go to that date.
18406 A prefix ARG can be used to force the current date."
18407 (interactive "P")
18408 (let ((tsr org-ts-regexp) diff
18409 (calendar-move-hook nil)
18410 (view-calendar-holidays-initially nil)
18411 (view-diary-entries-initially nil))
18412 (if (or (org-at-timestamp-p)
18413 (save-excursion
18414 (beginning-of-line 1)
18415 (looking-at (concat ".*" tsr))))
18416 (let ((d1 (time-to-days (current-time)))
18417 (d2 (time-to-days
18418 (org-time-string-to-time (match-string 1)))))
18419 (setq diff (- d2 d1))))
18420 (calendar)
18421 (calendar-goto-today)
18422 (if (and diff (not arg)) (calendar-forward-day diff))))
18424 (defun org-get-date-from-calendar ()
18425 "Return a list (month day year) of date at point in calendar."
18426 (with-current-buffer "*Calendar*"
18427 (save-match-data
18428 (calendar-cursor-to-date))))
18430 (defun org-date-from-calendar ()
18431 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18432 If there is already a time stamp at the cursor position, update it."
18433 (interactive)
18434 (if (org-at-timestamp-p t)
18435 (org-timestamp-change 0 'calendar)
18436 (let ((cal-date (org-get-date-from-calendar)))
18437 (org-insert-time-stamp
18438 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18440 ;; Make appt aware of appointments from the agenda
18441 ;;;###autoload
18442 (defun org-agenda-to-appt (&optional filter)
18443 "Activate appointments found in `org-agenda-files'.
18444 When prefixed, prompt for a regular expression and use it as a
18445 filter: only add entries if they match this regular expression.
18447 FILTER can be a string. In this case, use this string as a
18448 regular expression to filter results.
18450 FILTER can also be an alist, with the car of each cell being
18451 either 'headline or 'category. For example:
18453 '((headline \"IMPORTANT\")
18454 (category \"Work\"))
18456 will only add headlines containing IMPORTANT or headlines
18457 belonging to the category \"Work\"."
18458 (interactive "P")
18459 (require 'calendar)
18460 (if (equal filter '(4))
18461 (setq filter (read-from-minibuffer "Regexp filter: ")))
18462 (let* ((cnt 0) ; count added events
18463 (org-agenda-new-buffers nil)
18464 (today (org-date-to-gregorian
18465 (time-to-days (current-time))))
18466 (files (org-agenda-files)) entries file)
18467 ;; Get all entries which may contain an appt
18468 (while (setq file (pop files))
18469 (setq entries
18470 (append entries
18471 (org-agenda-get-day-entries
18472 file today
18473 :timestamp :scheduled :deadline))))
18474 (setq entries (delq nil entries))
18475 ;; Map thru entries and find if they pass thru the filter
18476 (mapc
18477 (lambda(x)
18478 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18479 (cat (get-text-property 1 'org-category x))
18480 (tod (get-text-property 1 'time-of-day x))
18481 (ok (or (null filter)
18482 (and (stringp filter) (string-match filter evt))
18483 (and (listp filter)
18484 (or (string-match
18485 (cadr (assoc 'category filter)) cat)
18486 (string-match
18487 (cadr (assoc 'headline filter)) evt))))))
18488 ;; FIXME: Shall we remove text-properties for the appt text?
18489 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18490 (when (and ok tod)
18491 (setq tod (number-to-string tod)
18492 tod (when (string-match
18493 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18494 (concat (match-string 1 tod) ":"
18495 (match-string 2 tod))))
18496 (appt-add tod evt)
18497 (setq cnt (1+ cnt))))) entries)
18498 (org-release-buffers org-agenda-new-buffers)
18499 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18501 ;;; The clock for measuring work time.
18503 (defvar org-mode-line-string "")
18504 (put 'org-mode-line-string 'risky-local-variable t)
18506 (defvar org-mode-line-timer nil)
18507 (defvar org-clock-heading "")
18508 (defvar org-clock-start-time "")
18510 (defun org-update-mode-line ()
18511 (let* ((delta (- (time-to-seconds (current-time))
18512 (time-to-seconds org-clock-start-time)))
18513 (h (floor delta 3600))
18514 (m (floor (- delta (* 3600 h)) 60)))
18515 (setq org-mode-line-string
18516 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18517 'help-echo "Org-mode clock is running"))
18518 (force-mode-line-update)))
18520 (defvar org-clock-marker (make-marker)
18521 "Marker recording the last clock-in.")
18522 (defvar org-clock-mode-line-entry nil
18523 "Information for the modeline about the running clock.")
18525 (defun org-clock-in ()
18526 "Start the clock on the current item.
18527 If necessary, clock-out of the currently active clock."
18528 (interactive)
18529 (org-clock-out t)
18530 (let (ts)
18531 (save-excursion
18532 (org-back-to-heading t)
18533 (when (and org-clock-in-switch-to-state
18534 (not (looking-at (concat outline-regexp "[ \t]*"
18535 org-clock-in-switch-to-state
18536 "\\>"))))
18537 (org-todo org-clock-in-switch-to-state))
18538 (if (and org-clock-heading-function
18539 (functionp org-clock-heading-function))
18540 (setq org-clock-heading (funcall org-clock-heading-function))
18541 (if (looking-at org-complex-heading-regexp)
18542 (setq org-clock-heading (match-string 4))
18543 (setq org-clock-heading "???")))
18544 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18545 (org-clock-find-position)
18547 (insert "\n") (backward-char 1)
18548 (indent-relative)
18549 (insert org-clock-string " ")
18550 (setq org-clock-start-time (current-time))
18551 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18552 (move-marker org-clock-marker (point) (buffer-base-buffer))
18553 (or global-mode-string (setq global-mode-string '("")))
18554 (or (memq 'org-mode-line-string global-mode-string)
18555 (setq global-mode-string
18556 (append global-mode-string '(org-mode-line-string))))
18557 (org-update-mode-line)
18558 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18559 (message "Clock started at %s" ts))))
18561 (defun org-clock-find-position ()
18562 "Find the location where the next clock line should be inserted."
18563 (org-back-to-heading t)
18564 (catch 'exit
18565 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18566 (re (concat "^[ \t]*" org-clock-string))
18567 (cnt 0)
18568 first last)
18569 (goto-char beg)
18570 (when (eobp) (newline) (setq end (max (point) end)))
18571 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18572 ;; we seem to have a CLOCK drawer, so go there.
18573 (beginning-of-line 2)
18574 (throw 'exit t))
18575 ;; Lets count the CLOCK lines
18576 (goto-char beg)
18577 (while (re-search-forward re end t)
18578 (setq first (or first (match-beginning 0))
18579 last (match-beginning 0)
18580 cnt (1+ cnt)))
18581 (when (and (integerp org-clock-into-drawer)
18582 (>= (1+ cnt) org-clock-into-drawer))
18583 ;; Wrap current entries into a new drawer
18584 (goto-char last)
18585 (beginning-of-line 2)
18586 (if (org-at-item-p) (org-end-of-item))
18587 (insert ":END:\n")
18588 (beginning-of-line 0)
18589 (org-indent-line-function)
18590 (goto-char first)
18591 (insert ":CLOCK:\n")
18592 (beginning-of-line 0)
18593 (org-indent-line-function)
18594 (org-flag-drawer t)
18595 (beginning-of-line 2)
18596 (throw 'exit nil))
18598 (goto-char beg)
18599 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18600 (not (equal (match-string 1) org-clock-string)))
18601 ;; Planning info, skip to after it
18602 (beginning-of-line 2)
18603 (or (bolp) (newline)))
18604 (when (eq t org-clock-into-drawer)
18605 (insert ":CLOCK:\n:END:\n")
18606 (beginning-of-line -1)
18607 (org-indent-line-function)
18608 (org-flag-drawer t)
18609 (beginning-of-line 2)
18610 (org-indent-line-function)))))
18612 (defun org-clock-out (&optional fail-quietly)
18613 "Stop the currently running clock.
18614 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18615 (interactive)
18616 (catch 'exit
18617 (if (not (marker-buffer org-clock-marker))
18618 (if fail-quietly (throw 'exit t) (error "No active clock")))
18619 (let (ts te s h m)
18620 (save-excursion
18621 (set-buffer (marker-buffer org-clock-marker))
18622 (goto-char org-clock-marker)
18623 (beginning-of-line 1)
18624 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18625 (equal (match-string 1) org-clock-string))
18626 (setq ts (match-string 2))
18627 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18628 (goto-char (match-end 0))
18629 (delete-region (point) (point-at-eol))
18630 (insert "--")
18631 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18632 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18633 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18634 h (floor (/ s 3600))
18635 s (- s (* 3600 h))
18636 m (floor (/ s 60))
18637 s (- s (* 60 s)))
18638 (insert " => " (format "%2d:%02d" h m))
18639 (move-marker org-clock-marker nil)
18640 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
18641 (org-log-done (org-parse-local-options logging 'org-log-done))
18642 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
18643 (org-add-log-maybe 'clock-out))
18644 (when org-mode-line-timer
18645 (cancel-timer org-mode-line-timer)
18646 (setq org-mode-line-timer nil))
18647 (setq global-mode-string
18648 (delq 'org-mode-line-string global-mode-string))
18649 (force-mode-line-update)
18650 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18652 (defun org-clock-cancel ()
18653 "Cancel the running clock be removing the start timestamp."
18654 (interactive)
18655 (if (not (marker-buffer org-clock-marker))
18656 (error "No active clock"))
18657 (save-excursion
18658 (set-buffer (marker-buffer org-clock-marker))
18659 (goto-char org-clock-marker)
18660 (delete-region (1- (point-at-bol)) (point-at-eol)))
18661 (setq global-mode-string
18662 (delq 'org-mode-line-string global-mode-string))
18663 (force-mode-line-update)
18664 (message "Clock canceled"))
18666 (defun org-clock-goto (&optional delete-windows)
18667 "Go to the currently clocked-in entry."
18668 (interactive "P")
18669 (if (not (marker-buffer org-clock-marker))
18670 (error "No active clock"))
18671 (switch-to-buffer-other-window
18672 (marker-buffer org-clock-marker))
18673 (if delete-windows (delete-other-windows))
18674 (goto-char org-clock-marker)
18675 (org-show-entry)
18676 (org-back-to-heading)
18677 (recenter))
18679 (defvar org-clock-file-total-minutes nil
18680 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18681 (make-variable-buffer-local 'org-clock-file-total-minutes)
18683 (defun org-clock-sum (&optional tstart tend)
18684 "Sum the times for each subtree.
18685 Puts the resulting times in minutes as a text property on each headline."
18686 (interactive)
18687 (let* ((bmp (buffer-modified-p))
18688 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18689 org-clock-string
18690 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18691 (lmax 30)
18692 (ltimes (make-vector lmax 0))
18693 (t1 0)
18694 (level 0)
18695 ts te dt
18696 time)
18697 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18698 (save-excursion
18699 (goto-char (point-max))
18700 (while (re-search-backward re nil t)
18701 (cond
18702 ((match-end 2)
18703 ;; Two time stamps
18704 (setq ts (match-string 2)
18705 te (match-string 3)
18706 ts (time-to-seconds
18707 (apply 'encode-time (org-parse-time-string ts)))
18708 te (time-to-seconds
18709 (apply 'encode-time (org-parse-time-string te)))
18710 ts (if tstart (max ts tstart) ts)
18711 te (if tend (min te tend) te)
18712 dt (- te ts)
18713 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18714 ((match-end 4)
18715 ;; A naket time
18716 (setq t1 (+ t1 (string-to-number (match-string 5))
18717 (* 60 (string-to-number (match-string 4))))))
18718 (t ;; A headline
18719 (setq level (- (match-end 1) (match-beginning 1)))
18720 (when (or (> t1 0) (> (aref ltimes level) 0))
18721 (loop for l from 0 to level do
18722 (aset ltimes l (+ (aref ltimes l) t1)))
18723 (setq t1 0 time (aref ltimes level))
18724 (loop for l from level to (1- lmax) do
18725 (aset ltimes l 0))
18726 (goto-char (match-beginning 0))
18727 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18728 (setq org-clock-file-total-minutes (aref ltimes 0)))
18729 (set-buffer-modified-p bmp)))
18731 (defun org-clock-display (&optional total-only)
18732 "Show subtree times in the entire buffer.
18733 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18734 in the echo area."
18735 (interactive)
18736 (org-remove-clock-overlays)
18737 (let (time h m p)
18738 (org-clock-sum)
18739 (unless total-only
18740 (save-excursion
18741 (goto-char (point-min))
18742 (while (or (and (equal (setq p (point)) (point-min))
18743 (get-text-property p :org-clock-minutes))
18744 (setq p (next-single-property-change
18745 (point) :org-clock-minutes)))
18746 (goto-char p)
18747 (when (setq time (get-text-property p :org-clock-minutes))
18748 (org-put-clock-overlay time (funcall outline-level))))
18749 (setq h (/ org-clock-file-total-minutes 60)
18750 m (- org-clock-file-total-minutes (* 60 h)))
18751 ;; Arrange to remove the overlays upon next change.
18752 (when org-remove-highlights-with-change
18753 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18754 nil 'local))))
18755 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18757 (defvar org-clock-overlays nil)
18758 (make-variable-buffer-local 'org-clock-overlays)
18760 (defun org-put-clock-overlay (time &optional level)
18761 "Put an overlays on the current line, displaying TIME.
18762 If LEVEL is given, prefix time with a corresponding number of stars.
18763 This creates a new overlay and stores it in `org-clock-overlays', so that it
18764 will be easy to remove."
18765 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18766 (l (if level (org-get-legal-level level 0) 0))
18767 (off 0)
18768 ov tx)
18769 (move-to-column c)
18770 (unless (eolp) (skip-chars-backward "^ \t"))
18771 (skip-chars-backward " \t")
18772 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18773 tx (concat (buffer-substring (1- (point)) (point))
18774 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18775 (org-add-props (format "%s %2d:%02d%s"
18776 (make-string l ?*) h m
18777 (make-string (- 10 l) ?\ ))
18778 '(face secondary-selection))
18779 ""))
18780 (if (not (featurep 'xemacs))
18781 (org-overlay-put ov 'display tx)
18782 (org-overlay-put ov 'invisible t)
18783 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18784 (push ov org-clock-overlays)))
18786 (defun org-remove-clock-overlays (&optional beg end noremove)
18787 "Remove the occur highlights from the buffer.
18788 BEG and END are ignored. If NOREMOVE is nil, remove this function
18789 from the `before-change-functions' in the current buffer."
18790 (interactive)
18791 (unless org-inhibit-highlight-removal
18792 (mapc 'org-delete-overlay org-clock-overlays)
18793 (setq org-clock-overlays nil)
18794 (unless noremove
18795 (remove-hook 'before-change-functions
18796 'org-remove-clock-overlays 'local))))
18798 (defun org-clock-out-if-current ()
18799 "Clock out if the current entry contains the running clock.
18800 This is used to stop the clock after a TODO entry is marked DONE,
18801 and is only done if the variable `org-clock-out-when-done' is not nil."
18802 (when (and org-clock-out-when-done
18803 (member state org-done-keywords)
18804 (equal (marker-buffer org-clock-marker) (current-buffer))
18805 (< (point) org-clock-marker)
18806 (> (save-excursion (outline-next-heading) (point))
18807 org-clock-marker))
18808 ;; Clock out, but don't accept a logging message for this.
18809 (let ((org-log-done (if (and (listp org-log-done)
18810 (member 'clock-out org-log-done))
18811 '(done)
18812 org-log-done)))
18813 (org-clock-out))))
18815 (add-hook 'org-after-todo-state-change-hook
18816 'org-clock-out-if-current)
18818 (defun org-check-running-clock ()
18819 "Check if the current buffer contains the running clock.
18820 If yes, offer to stop it and to save the buffer with the changes."
18821 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18822 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18823 (buffer-name))))
18824 (org-clock-out)
18825 (when (y-or-n-p "Save changed buffer?")
18826 (save-buffer))))
18828 (defun org-clock-report (&optional arg)
18829 "Create a table containing a report about clocked time.
18830 If the cursor is inside an existing clocktable block, then the table
18831 will be updated. If not, a new clocktable will be inserted.
18832 When called with a prefix argument, move to the first clock table in the
18833 buffer and update it."
18834 (interactive "P")
18835 (org-remove-clock-overlays)
18836 (when arg
18837 (org-find-dblock "clocktable")
18838 (org-show-entry))
18839 (if (org-in-clocktable-p)
18840 (goto-char (org-in-clocktable-p))
18841 (org-create-dblock (list :name "clocktable"
18842 :maxlevel 2 :scope 'file)))
18843 (org-update-dblock))
18845 (defun org-in-clocktable-p ()
18846 "Check if the cursor is in a clocktable."
18847 (let ((pos (point)) start)
18848 (save-excursion
18849 (end-of-line 1)
18850 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18851 (setq start (match-beginning 0))
18852 (re-search-forward "^#\\+END:.*" nil t)
18853 (>= (match-end 0) pos)
18854 start))))
18856 (defun org-clock-update-time-maybe ()
18857 "If this is a CLOCK line, update it and return t.
18858 Otherwise, return nil."
18859 (interactive)
18860 (save-excursion
18861 (beginning-of-line 1)
18862 (skip-chars-forward " \t")
18863 (when (looking-at org-clock-string)
18864 (let ((re (concat "[ \t]*" org-clock-string
18865 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18866 "\\([ \t]*=>.*\\)?"))
18867 ts te h m s)
18868 (if (not (looking-at re))
18870 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18871 (end-of-line 1)
18872 (setq ts (match-string 1)
18873 te (match-string 2))
18874 (setq s (- (time-to-seconds
18875 (apply 'encode-time (org-parse-time-string te)))
18876 (time-to-seconds
18877 (apply 'encode-time (org-parse-time-string ts))))
18878 h (floor (/ s 3600))
18879 s (- s (* 3600 h))
18880 m (floor (/ s 60))
18881 s (- s (* 60 s)))
18882 (insert " => " (format "%2d:%02d" h m))
18883 t)))))
18885 (defun org-clock-special-range (key &optional time as-strings)
18886 "Return two times bordering a special time range.
18887 Key is a symbol specifying the range and can be one of `today', `yesterday',
18888 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18889 A week starts Monday 0:00 and ends Sunday 24:00.
18890 The range is determined relative to TIME. TIME defaults to the current time.
18891 The return value is a cons cell with two internal times like the ones
18892 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18893 the returned times will be formatted strings."
18894 (let* ((tm (decode-time (or time (current-time))))
18895 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18896 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18897 (dow (nth 6 tm))
18898 s1 m1 h1 d1 month1 y1 diff ts te fm)
18899 (cond
18900 ((eq key 'today)
18901 (setq h 0 m 0 h1 24 m1 0))
18902 ((eq key 'yesterday)
18903 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18904 ((eq key 'thisweek)
18905 (setq diff (if (= dow 0) 6 (1- dow))
18906 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18907 ((eq key 'lastweek)
18908 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18909 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18910 ((eq key 'thismonth)
18911 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18912 ((eq key 'lastmonth)
18913 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18914 ((eq key 'thisyear)
18915 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18916 ((eq key 'lastyear)
18917 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18918 (t (error "No such time block %s" key)))
18919 (setq ts (encode-time s m h d month y)
18920 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18921 (or d1 d) (or month1 month) (or y1 y)))
18922 (setq fm (cdr org-time-stamp-formats))
18923 (if as-strings
18924 (cons (format-time-string fm ts) (format-time-string fm te))
18925 (cons ts te))))
18927 (defun org-dblock-write:clocktable (params)
18928 "Write the standard clocktable."
18929 (catch 'exit
18930 (let* ((hlchars '((1 . "*") (2 . "/")))
18931 (ins (make-marker))
18932 (total-time nil)
18933 (scope (plist-get params :scope))
18934 (tostring (plist-get params :tostring))
18935 (multifile (plist-get params :multifile))
18936 (header (plist-get params :header))
18937 (maxlevel (or (plist-get params :maxlevel) 3))
18938 (step (plist-get params :step))
18939 (emph (plist-get params :emphasize))
18940 (ts (plist-get params :tstart))
18941 (te (plist-get params :tend))
18942 (block (plist-get params :block))
18943 ipos time h m p level hlc hdl
18944 cc beg end pos tbl)
18945 (when step
18946 (org-clocktable-steps params)
18947 (throw 'exit nil))
18948 (when block
18949 (setq cc (org-clock-special-range block nil t)
18950 ts (car cc) te (cdr cc)))
18951 (if ts (setq ts (time-to-seconds
18952 (apply 'encode-time (org-parse-time-string ts)))))
18953 (if te (setq te (time-to-seconds
18954 (apply 'encode-time (org-parse-time-string te)))))
18955 (move-marker ins (point))
18956 (setq ipos (point))
18958 ;; Get the right scope
18959 (setq pos (point))
18960 (save-restriction
18961 (cond
18962 ((not scope))
18963 ((eq scope 'file) (widen))
18964 ((eq scope 'subtree) (org-narrow-to-subtree))
18965 ((eq scope 'tree)
18966 (while (org-up-heading-safe))
18967 (org-narrow-to-subtree))
18968 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18969 (symbol-name scope)))
18970 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18971 (catch 'exit
18972 (while (org-up-heading-safe)
18973 (looking-at outline-regexp)
18974 (if (<= (org-reduced-level (funcall outline-level)) level)
18975 (throw 'exit nil))))
18976 (org-narrow-to-subtree))
18977 ((or (listp scope) (eq scope 'agenda))
18978 (let* ((files (if (listp scope) scope (org-agenda-files)))
18979 (scope 'agenda)
18980 (p1 (copy-sequence params))
18981 file)
18982 (plist-put p1 :tostring t)
18983 (plist-put p1 :multifile t)
18984 (plist-put p1 :scope 'file)
18985 (org-prepare-agenda-buffers files)
18986 (while (setq file (pop files))
18987 (with-current-buffer (find-buffer-visiting file)
18988 (push (org-clocktable-add-file
18989 file (org-dblock-write:clocktable p1)) tbl)
18990 (setq total-time (+ (or total-time 0)
18991 org-clock-file-total-minutes)))))))
18992 (goto-char pos)
18994 (unless (eq scope 'agenda)
18995 (org-clock-sum ts te)
18996 (goto-char (point-min))
18997 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18998 (goto-char p)
18999 (when (setq time (get-text-property p :org-clock-minutes))
19000 (save-excursion
19001 (beginning-of-line 1)
19002 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19003 (setq level (org-reduced-level
19004 (- (match-end 1) (match-beginning 1))))
19005 (<= level maxlevel))
19006 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19007 hdl (match-string 2)
19008 h (/ time 60)
19009 m (- time (* 60 h)))
19010 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19011 (push (concat
19012 "| " (int-to-string level) "|" hlc hdl hlc " |"
19013 (make-string (1- level) ?|)
19014 hlc (format "%d:%02d" h m) hlc
19015 " |") tbl))))))
19016 (setq tbl (nreverse tbl))
19017 (if tostring
19018 (if tbl (mapconcat 'identity tbl "\n") nil)
19019 (goto-char ins)
19020 (insert-before-markers
19021 (or header
19022 (concat
19023 "Clock summary at ["
19024 (substring
19025 (format-time-string (cdr org-time-stamp-formats))
19026 1 -1)
19027 "]."
19028 (if block
19029 (format " Considered range is /%s/." block)
19031 "\n\n"))
19032 (if (eq scope 'agenda) "|File" "")
19033 "|L|Headline|Time|\n")
19034 (setq total-time (or total-time org-clock-file-total-minutes)
19035 h (/ total-time 60)
19036 m (- total-time (* 60 h)))
19037 (insert-before-markers
19038 "|-\n|"
19039 (if (eq scope 'agenda) "|" "")
19041 "*Total time*| "
19042 (format "*%d:%02d*" h m)
19043 "|\n|-\n")
19044 (setq tbl (delq nil tbl))
19045 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19046 (equal (substring (car tbl) 0 2) "|-"))
19047 (pop tbl))
19048 (insert-before-markers (mapconcat
19049 'identity (delq nil tbl)
19050 (if (eq scope 'agenda) "\n|-\n" "\n")))
19051 (backward-delete-char 1)
19052 (goto-char ipos)
19053 (skip-chars-forward "^|")
19054 (org-table-align))))))
19056 (defun org-clocktable-steps (params)
19057 (let* ((p1 (copy-sequence params))
19058 (ts (plist-get p1 :tstart))
19059 (te (plist-get p1 :tend))
19060 (step0 (plist-get p1 :step))
19061 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19062 (block (plist-get p1 :block))
19064 (when block
19065 (setq cc (org-clock-special-range block nil t)
19066 ts (car cc) te (cdr cc)))
19067 (if ts (setq ts (time-to-seconds
19068 (apply 'encode-time (org-parse-time-string ts)))))
19069 (if te (setq te (time-to-seconds
19070 (apply 'encode-time (org-parse-time-string te)))))
19071 (plist-put p1 :header "")
19072 (plist-put p1 :step nil)
19073 (plist-put p1 :block nil)
19074 (while (< ts te)
19075 (or (bolp) (insert "\n"))
19076 (plist-put p1 :tstart (format-time-string
19077 (car org-time-stamp-formats)
19078 (seconds-to-time ts)))
19079 (plist-put p1 :tend (format-time-string
19080 (car org-time-stamp-formats)
19081 (seconds-to-time (setq ts (+ ts step)))))
19082 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19083 (plist-get p1 :tstart) "\n")
19084 (org-dblock-write:clocktable p1)
19085 (re-search-forward "#\\+END:")
19086 (end-of-line 0))))
19089 (defun org-clocktable-add-file (file table)
19090 (if table
19091 (let ((lines (org-split-string table "\n"))
19092 (ff (file-name-nondirectory file)))
19093 (mapconcat 'identity
19094 (mapcar (lambda (x)
19095 (if (string-match org-table-dataline-regexp x)
19096 (concat "|" ff x)
19098 lines)
19099 "\n"))))
19101 ;; FIXME: I don't think anybody uses this, ask David
19102 (defun org-collect-clock-time-entries ()
19103 "Return an internal list with clocking information.
19104 This list has one entry for each CLOCK interval.
19105 FIXME: describe the elements."
19106 (interactive)
19107 (let ((re (concat "^[ \t]*" org-clock-string
19108 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19109 rtn beg end next cont level title total closedp leafp
19110 clockpos titlepos h m donep)
19111 (save-excursion
19112 (org-clock-sum)
19113 (goto-char (point-min))
19114 (while (re-search-forward re nil t)
19115 (setq clockpos (match-beginning 0)
19116 beg (match-string 1) end (match-string 2)
19117 cont (match-end 0))
19118 (setq beg (apply 'encode-time (org-parse-time-string beg))
19119 end (apply 'encode-time (org-parse-time-string end)))
19120 (org-back-to-heading t)
19121 (setq donep (org-entry-is-done-p))
19122 (setq titlepos (point)
19123 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19124 h (/ total 60) m (- total (* 60 h))
19125 total (cons h m))
19126 (looking-at "\\(\\*+\\) +\\(.*\\)")
19127 (setq level (- (match-end 1) (match-beginning 1))
19128 title (org-match-string-no-properties 2))
19129 (save-excursion (outline-next-heading) (setq next (point)))
19130 (setq closedp (re-search-forward org-closed-time-regexp next t))
19131 (goto-char next)
19132 (setq leafp (and (looking-at "^\\*+ ")
19133 (<= (- (match-end 0) (point)) level)))
19134 (push (list beg end clockpos closedp donep
19135 total title titlepos level leafp)
19136 rtn)
19137 (goto-char cont)))
19138 (nreverse rtn)))
19140 ;;;; Agenda, and Diary Integration
19142 ;;; Define the Org-agenda-mode
19144 (defvar org-agenda-mode-map (make-sparse-keymap)
19145 "Keymap for `org-agenda-mode'.")
19147 (defvar org-agenda-menu) ; defined later in this file.
19148 (defvar org-agenda-follow-mode nil)
19149 (defvar org-agenda-show-log nil)
19150 (defvar org-agenda-redo-command nil)
19151 (defvar org-agenda-mode-hook nil)
19152 (defvar org-agenda-type nil)
19153 (defvar org-agenda-force-single-file nil)
19155 (defun org-agenda-mode ()
19156 "Mode for time-sorted view on action items in Org-mode files.
19158 The following commands are available:
19160 \\{org-agenda-mode-map}"
19161 (interactive)
19162 (kill-all-local-variables)
19163 (setq org-agenda-undo-list nil
19164 org-agenda-pending-undo-list nil)
19165 (setq major-mode 'org-agenda-mode)
19166 ;; Keep global-font-lock-mode from turning on font-lock-mode
19167 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19168 (setq mode-name "Org-Agenda")
19169 (use-local-map org-agenda-mode-map)
19170 (easy-menu-add org-agenda-menu)
19171 (if org-startup-truncated (setq truncate-lines t))
19172 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19173 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19174 ;; Make sure properties are removed when copying text
19175 (when (boundp 'buffer-substring-filters)
19176 (org-set-local 'buffer-substring-filters
19177 (cons (lambda (x)
19178 (set-text-properties 0 (length x) nil x) x)
19179 buffer-substring-filters)))
19180 (unless org-agenda-keep-modes
19181 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19182 org-agenda-show-log nil))
19183 (easy-menu-change
19184 '("Agenda") "Agenda Files"
19185 (append
19186 (list
19187 (vector
19188 (if (get 'org-agenda-files 'org-restrict)
19189 "Restricted to single file"
19190 "Edit File List")
19191 '(org-edit-agenda-file-list)
19192 (not (get 'org-agenda-files 'org-restrict)))
19193 "--")
19194 (mapcar 'org-file-menu-entry (org-agenda-files))))
19195 (org-agenda-set-mode-name)
19196 (apply
19197 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19198 (list 'org-agenda-mode-hook)))
19200 (substitute-key-definition 'undo 'org-agenda-undo
19201 org-agenda-mode-map global-map)
19202 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19203 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19204 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19205 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19206 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19207 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19208 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19209 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19210 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19211 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19212 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19213 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19214 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19215 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19216 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19217 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19218 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19219 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19220 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19221 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19222 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19223 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19224 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19225 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19226 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19227 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19228 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19229 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19230 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19232 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19233 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19234 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19235 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19236 (while l (org-defkey org-agenda-mode-map
19237 (int-to-string (pop l)) 'digit-argument)))
19239 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19240 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19241 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19242 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19243 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19244 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19245 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19246 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19247 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19248 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19249 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19250 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19251 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19252 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19253 (org-defkey org-agenda-mode-map "n" 'next-line)
19254 (org-defkey org-agenda-mode-map "p" 'previous-line)
19255 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19256 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19257 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19258 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19259 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19260 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19261 (eval-after-load "calendar"
19262 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19263 'org-calendar-goto-agenda))
19264 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19265 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19266 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19267 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19268 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19269 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19270 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19271 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19272 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19273 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19274 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19275 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19276 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19277 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19278 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19279 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19280 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19281 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19282 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19283 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19284 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19285 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19287 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19288 "Local keymap for agenda entries from Org-mode.")
19290 (org-defkey org-agenda-keymap
19291 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19292 (org-defkey org-agenda-keymap
19293 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19294 (when org-agenda-mouse-1-follows-link
19295 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19296 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19297 '("Agenda"
19298 ("Agenda Files")
19299 "--"
19300 ["Show" org-agenda-show t]
19301 ["Go To (other window)" org-agenda-goto t]
19302 ["Go To (this window)" org-agenda-switch-to t]
19303 ["Follow Mode" org-agenda-follow-mode
19304 :style toggle :selected org-agenda-follow-mode :active t]
19305 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19306 "--"
19307 ["Cycle TODO" org-agenda-todo t]
19308 ["Archive subtree" org-agenda-archive t]
19309 ["Delete subtree" org-agenda-kill t]
19310 "--"
19311 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19312 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19313 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19314 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19315 "--"
19316 ("Tags and Properties"
19317 ["Show all Tags" org-agenda-show-tags t]
19318 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19319 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19320 "--"
19321 ["Column View" org-columns t])
19322 ("Date/Schedule"
19323 ["Schedule" org-agenda-schedule t]
19324 ["Set Deadline" org-agenda-deadline t]
19325 "--"
19326 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19327 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19328 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19329 ("Clock"
19330 ["Clock in" org-agenda-clock-in t]
19331 ["Clock out" org-agenda-clock-out t]
19332 ["Clock cancel" org-agenda-clock-cancel t]
19333 ["Goto running clock" org-clock-goto t])
19334 ("Priority"
19335 ["Set Priority" org-agenda-priority t]
19336 ["Increase Priority" org-agenda-priority-up t]
19337 ["Decrease Priority" org-agenda-priority-down t]
19338 ["Show Priority" org-agenda-show-priority t])
19339 ("Calendar/Diary"
19340 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19341 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19342 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19343 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19344 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19345 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19346 "--"
19347 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19348 "--"
19349 ("View"
19350 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19351 :style radio :selected (equal org-agenda-ndays 1)]
19352 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19353 :style radio :selected (equal org-agenda-ndays 7)]
19354 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19355 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19356 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19357 :style radio :selected (member org-agenda-ndays '(365 366))]
19358 "--"
19359 ["Show Logbook entries" org-agenda-log-mode
19360 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19361 ["Include Diary" org-agenda-toggle-diary
19362 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19363 ["Use Time Grid" org-agenda-toggle-time-grid
19364 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19365 ["Write view to file" org-write-agenda t]
19366 ["Rebuild buffer" org-agenda-redo t]
19367 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19368 "--"
19369 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19370 "--"
19371 ["Quit" org-agenda-quit t]
19372 ["Exit and Release Buffers" org-agenda-exit t]
19375 ;;; Agenda undo
19377 (defvar org-agenda-allow-remote-undo t
19378 "Non-nil means, allow remote undo from the agenda buffer.")
19379 (defvar org-agenda-undo-list nil
19380 "List of undoable operations in the agenda since last refresh.")
19381 (defvar org-agenda-undo-has-started-in nil
19382 "Buffers that have already seen `undo-start' in the current undo sequence.")
19383 (defvar org-agenda-pending-undo-list nil
19384 "In a series of undo commands, this is the list of remaning undo items.")
19386 (defmacro org-if-unprotected (&rest body)
19387 "Execute BODY if there is no `org-protected' text property at point."
19388 (declare (debug t))
19389 `(unless (get-text-property (point) 'org-protected)
19390 ,@body))
19392 (defmacro org-with-remote-undo (_buffer &rest _body)
19393 "Execute BODY while recording undo information in two buffers."
19394 (declare (indent 1) (debug t))
19395 `(let ((_cline (org-current-line))
19396 (_cmd this-command)
19397 (_buf1 (current-buffer))
19398 (_buf2 ,_buffer)
19399 (_undo1 buffer-undo-list)
19400 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19401 _c1 _c2)
19402 ,@_body
19403 (when org-agenda-allow-remote-undo
19404 (setq _c1 (org-verify-change-for-undo
19405 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19406 _c2 (org-verify-change-for-undo
19407 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19408 (when (or _c1 _c2)
19409 ;; make sure there are undo boundaries
19410 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19411 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19412 ;; remember which buffer to undo
19413 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19414 org-agenda-undo-list)))))
19416 (defun org-agenda-undo ()
19417 "Undo a remote editing step in the agenda.
19418 This undoes changes both in the agenda buffer and in the remote buffer
19419 that have been changed along."
19420 (interactive)
19421 (or org-agenda-allow-remote-undo
19422 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19423 (if (not (eq this-command last-command))
19424 (setq org-agenda-undo-has-started-in nil
19425 org-agenda-pending-undo-list org-agenda-undo-list))
19426 (if (not org-agenda-pending-undo-list)
19427 (error "No further undo information"))
19428 (let* ((entry (pop org-agenda-pending-undo-list))
19429 buf line cmd rembuf)
19430 (setq cmd (pop entry) line (pop entry))
19431 (setq rembuf (nth 2 entry))
19432 (org-with-remote-undo rembuf
19433 (while (bufferp (setq buf (pop entry)))
19434 (if (pop entry)
19435 (with-current-buffer buf
19436 (let ((last-undo-buffer buf)
19437 (inhibit-read-only t))
19438 (unless (memq buf org-agenda-undo-has-started-in)
19439 (push buf org-agenda-undo-has-started-in)
19440 (make-local-variable 'pending-undo-list)
19441 (undo-start))
19442 (while (and pending-undo-list
19443 (listp pending-undo-list)
19444 (not (car pending-undo-list)))
19445 (pop pending-undo-list))
19446 (undo-more 1))))))
19447 (goto-line line)
19448 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19450 (defun org-verify-change-for-undo (l1 l2)
19451 "Verify that a real change occurred between the undo lists L1 and L2."
19452 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19453 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19454 (not (eq l1 l2)))
19456 ;;; Agenda dispatch
19458 (defvar org-agenda-restrict nil)
19459 (defvar org-agenda-restrict-begin (make-marker))
19460 (defvar org-agenda-restrict-end (make-marker))
19461 (defvar org-agenda-last-dispatch-buffer nil)
19462 (defvar org-agenda-overriding-restriction nil)
19464 ;;;###autoload
19465 (defun org-agenda (arg &optional keys restriction)
19466 "Dispatch agenda commands to collect entries to the agenda buffer.
19467 Prompts for a command to execute. Any prefix arg will be passed
19468 on to the selected command. The default selections are:
19470 a Call `org-agenda-list' to display the agenda for current day or week.
19471 t Call `org-todo-list' to display the global todo list.
19472 T Call `org-todo-list' to display the global todo list, select only
19473 entries with a specific TODO keyword (the user gets a prompt).
19474 m Call `org-tags-view' to display headlines with tags matching
19475 a condition (the user is prompted for the condition).
19476 M Like `m', but select only TODO entries, no ordinary headlines.
19477 L Create a timeline for the current buffer.
19478 e Export views to associated files.
19480 More commands can be added by configuring the variable
19481 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19482 searches can be pre-defined in this way.
19484 If the current buffer is in Org-mode and visiting a file, you can also
19485 first press `<' once to indicate that the agenda should be temporarily
19486 \(until the next use of \\[org-agenda]) restricted to the current file.
19487 Pressing `<' twice means to restrict to the current subtree or region
19488 \(if active)."
19489 (interactive "P")
19490 (catch 'exit
19491 (let* ((prefix-descriptions nil)
19492 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19493 (org-agenda-custom-commands
19494 ;; normalize different versions
19495 (delq nil
19496 (mapcar
19497 (lambda (x)
19498 (cond ((stringp (cdr x))
19499 (push x prefix-descriptions)
19500 nil)
19501 ((stringp (nth 1 x)) x)
19502 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19503 (t (cons (car x) (cons "" (cdr x))))))
19504 org-agenda-custom-commands)))
19505 (buf (current-buffer))
19506 (bfn (buffer-file-name (buffer-base-buffer)))
19507 entry key type match lprops ans)
19508 ;; Turn off restriction unless there is an overriding one
19509 (unless org-agenda-overriding-restriction
19510 (put 'org-agenda-files 'org-restrict nil)
19511 (setq org-agenda-restrict nil)
19512 (move-marker org-agenda-restrict-begin nil)
19513 (move-marker org-agenda-restrict-end nil))
19514 ;; Delete old local properties
19515 (put 'org-agenda-redo-command 'org-lprops nil)
19516 ;; Remember where this call originated
19517 (setq org-agenda-last-dispatch-buffer (current-buffer))
19518 (unless keys
19519 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19520 keys (car ans)
19521 restriction (cdr ans)))
19522 ;; Estabish the restriction, if any
19523 (when (and (not org-agenda-overriding-restriction) restriction)
19524 (put 'org-agenda-files 'org-restrict (list bfn))
19525 (cond
19526 ((eq restriction 'region)
19527 (setq org-agenda-restrict t)
19528 (move-marker org-agenda-restrict-begin (region-beginning))
19529 (move-marker org-agenda-restrict-end (region-end)))
19530 ((eq restriction 'subtree)
19531 (save-excursion
19532 (setq org-agenda-restrict t)
19533 (org-back-to-heading t)
19534 (move-marker org-agenda-restrict-begin (point))
19535 (move-marker org-agenda-restrict-end
19536 (progn (org-end-of-subtree t)))))))
19538 (require 'calendar) ; FIXME: can we avoid this for some commands?
19539 ;; For example the todo list should not need it (but does...)
19540 (cond
19541 ((setq entry (assoc keys org-agenda-custom-commands))
19542 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19543 (progn
19544 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19545 (put 'org-agenda-redo-command 'org-lprops lprops)
19546 (cond
19547 ((eq type 'agenda)
19548 (org-let lprops '(org-agenda-list current-prefix-arg)))
19549 ((eq type 'alltodo)
19550 (org-let lprops '(org-todo-list current-prefix-arg)))
19551 ((eq type 'stuck)
19552 (org-let lprops '(org-agenda-list-stuck-projects
19553 current-prefix-arg)))
19554 ((eq type 'tags)
19555 (org-let lprops '(org-tags-view current-prefix-arg match)))
19556 ((eq type 'tags-todo)
19557 (org-let lprops '(org-tags-view '(4) match)))
19558 ((eq type 'todo)
19559 (org-let lprops '(org-todo-list match)))
19560 ((eq type 'tags-tree)
19561 (org-check-for-org-mode)
19562 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19563 ((eq type 'todo-tree)
19564 (org-check-for-org-mode)
19565 (org-let lprops
19566 '(org-occur (concat "^" outline-regexp "[ \t]*"
19567 (regexp-quote match) "\\>"))))
19568 ((eq type 'occur-tree)
19569 (org-check-for-org-mode)
19570 (org-let lprops '(org-occur match)))
19571 ((functionp type)
19572 (org-let lprops '(funcall type match)))
19573 ((fboundp type)
19574 (org-let lprops '(funcall type match)))
19575 (t (error "Invalid custom agenda command type %s" type))))
19576 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19577 ((equal keys "C")
19578 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19579 (customize-variable 'org-agenda-custom-commands))
19580 ((equal keys "a") (call-interactively 'org-agenda-list))
19581 ((equal keys "t") (call-interactively 'org-todo-list))
19582 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19583 ((equal keys "m") (call-interactively 'org-tags-view))
19584 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19585 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19586 ((equal keys "L")
19587 (unless (org-mode-p)
19588 (error "This is not an Org-mode file"))
19589 (unless restriction
19590 (put 'org-agenda-files 'org-restrict (list bfn))
19591 (org-call-with-arg 'org-timeline arg)))
19592 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19593 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19594 ((equal keys "!") (customize-variable 'org-stuck-projects))
19595 (t (error "Invalid agenda key"))))))
19597 (defun org-agenda-normalize-custom-commands (cmds)
19598 (delq nil
19599 (mapcar
19600 (lambda (x)
19601 (cond ((stringp (cdr x)) nil)
19602 ((stringp (nth 1 x)) x)
19603 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19604 (t (cons (car x) (cons "" (cdr x))))))
19605 cmds)))
19607 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19608 "The user interface for selecting an agenda command."
19609 (catch 'exit
19610 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19611 (restrict-ok (and bfn (org-mode-p)))
19612 (region-p (org-region-active-p))
19613 (custom org-agenda-custom-commands)
19614 (selstring "")
19615 restriction second-time
19616 c entry key type match prefixes rmheader header-end custom1 desc)
19617 (save-window-excursion
19618 (delete-other-windows)
19619 (org-switch-to-buffer-other-window " *Agenda Commands*")
19620 (erase-buffer)
19621 (insert (eval-when-compile
19622 (let ((header
19624 Press key for an agenda command: < Buffer,subtree/region restriction
19625 -------------------------------- > Remove restriction
19626 a Agenda for current week or day e Export agenda views
19627 t List of all TODO entries T Entries with special TODO kwd
19628 m Match a TAGS query M Like m, but only TODO entries
19629 L Timeline for current buffer # List stuck projects (!=configure)
19630 / Multi-occur C Configure custom agenda commands
19632 (start 0))
19633 (while (string-match
19634 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19635 header start)
19636 (setq start (match-end 0))
19637 (add-text-properties (match-beginning 2) (match-end 2)
19638 '(face bold) header))
19639 header)))
19640 (setq header-end (move-marker (make-marker) (point)))
19641 (while t
19642 (setq custom1 custom)
19643 (when (eq rmheader t)
19644 (goto-line 1)
19645 (re-search-forward ":" nil t)
19646 (delete-region (match-end 0) (point-at-eol))
19647 (forward-char 1)
19648 (looking-at "-+")
19649 (delete-region (match-end 0) (point-at-eol))
19650 (move-marker header-end (match-end 0)))
19651 (goto-char header-end)
19652 (delete-region (point) (point-max))
19653 (while (setq entry (pop custom1))
19654 (setq key (car entry) desc (nth 1 entry)
19655 type (nth 2 entry) match (nth 3 entry))
19656 (if (> (length key) 1)
19657 (add-to-list 'prefixes (string-to-char key))
19658 (insert
19659 (format
19660 "\n%-4s%-14s: %s"
19661 (org-add-props (copy-sequence key)
19662 '(face bold))
19663 (cond
19664 ((string-match "\\S-" desc) desc)
19665 ((eq type 'agenda) "Agenda for current week or day")
19666 ((eq type 'alltodo) "List of all TODO entries")
19667 ((eq type 'stuck) "List of stuck projects")
19668 ((eq type 'todo) "TODO keyword")
19669 ((eq type 'tags) "Tags query")
19670 ((eq type 'tags-todo) "Tags (TODO)")
19671 ((eq type 'tags-tree) "Tags tree")
19672 ((eq type 'todo-tree) "TODO kwd tree")
19673 ((eq type 'occur-tree) "Occur tree")
19674 ((functionp type) (if (symbolp type)
19675 (symbol-name type)
19676 "Lambda expression"))
19677 (t "???"))
19678 (cond
19679 ((stringp match)
19680 (org-add-props match nil 'face 'org-warning))
19681 (match
19682 (format "set of %d commands" (length match)))
19683 (t ""))))))
19684 (when prefixes
19685 (mapc (lambda (x)
19686 (insert
19687 (format "\n%s %s"
19688 (org-add-props (char-to-string x)
19689 nil 'face 'bold)
19690 (or (cdr (assoc (concat selstring (char-to-string x))
19691 prefix-descriptions))
19692 "Prefix key"))))
19693 prefixes))
19694 (goto-char (point-min))
19695 (when (fboundp 'fit-window-to-buffer)
19696 (if second-time
19697 (if (not (pos-visible-in-window-p (point-max)))
19698 (fit-window-to-buffer))
19699 (setq second-time t)
19700 (fit-window-to-buffer)))
19701 (message "Press key for agenda command%s:"
19702 (if (or restrict-ok org-agenda-overriding-restriction)
19703 (if org-agenda-overriding-restriction
19704 " (restriction lock active)"
19705 (if restriction
19706 (format " (restricted to %s)" restriction)
19707 " (unrestricted)"))
19708 ""))
19709 (setq c (read-char-exclusive))
19710 (message "")
19711 (cond
19712 ((assoc (char-to-string c) custom)
19713 (setq selstring (concat selstring (char-to-string c)))
19714 (throw 'exit (cons selstring restriction)))
19715 ((memq c prefixes)
19716 (setq selstring (concat selstring (char-to-string c))
19717 prefixes nil
19718 rmheader (or rmheader t)
19719 custom (delq nil (mapcar
19720 (lambda (x)
19721 (if (or (= (length (car x)) 1)
19722 (/= (string-to-char (car x)) c))
19724 (cons (substring (car x) 1) (cdr x))))
19725 custom))))
19726 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19727 (message "Restriction is only possible in Org-mode buffers")
19728 (ding) (sit-for 1))
19729 ((eq c ?1)
19730 (org-agenda-remove-restriction-lock 'noupdate)
19731 (setq restriction 'buffer))
19732 ((eq c ?0)
19733 (org-agenda-remove-restriction-lock 'noupdate)
19734 (setq restriction (if region-p 'region 'subtree)))
19735 ((eq c ?<)
19736 (org-agenda-remove-restriction-lock 'noupdate)
19737 (setq restriction
19738 (cond
19739 ((eq restriction 'buffer)
19740 (if region-p 'region 'subtree))
19741 ((memq restriction '(subtree region))
19742 nil)
19743 (t 'buffer))))
19744 ((eq c ?>)
19745 (org-agenda-remove-restriction-lock 'noupdate)
19746 (setq restriction nil))
19747 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19748 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19749 ((and (> (length selstring) 0) (eq c ?\d))
19750 (delete-window)
19751 (org-agenda-get-restriction-and-command prefix-descriptions))
19753 ((equal c ?q) (error "Abort"))
19754 (t (error "Invalid key %c" c))))))))
19756 (defun org-run-agenda-series (name series)
19757 (org-prepare-agenda name)
19758 (let* ((org-agenda-multi t)
19759 (redo (list 'org-run-agenda-series name (list 'quote series)))
19760 (cmds (car series))
19761 (gprops (nth 1 series))
19762 match ;; The byte compiler incorrectly complains about this. Keep it!
19763 cmd type lprops)
19764 (while (setq cmd (pop cmds))
19765 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19766 (cond
19767 ((eq type 'agenda)
19768 (org-let2 gprops lprops
19769 '(call-interactively 'org-agenda-list)))
19770 ((eq type 'alltodo)
19771 (org-let2 gprops lprops
19772 '(call-interactively 'org-todo-list)))
19773 ((eq type 'stuck)
19774 (org-let2 gprops lprops
19775 '(call-interactively 'org-agenda-list-stuck-projects)))
19776 ((eq type 'tags)
19777 (org-let2 gprops lprops
19778 '(org-tags-view current-prefix-arg match)))
19779 ((eq type 'tags-todo)
19780 (org-let2 gprops lprops
19781 '(org-tags-view '(4) match)))
19782 ((eq type 'todo)
19783 (org-let2 gprops lprops
19784 '(org-todo-list match)))
19785 ((fboundp type)
19786 (org-let2 gprops lprops
19787 '(funcall type match)))
19788 (t (error "Invalid type in command series"))))
19789 (widen)
19790 (setq org-agenda-redo-command redo)
19791 (goto-char (point-min)))
19792 (org-finalize-agenda))
19794 ;;;###autoload
19795 (defmacro org-batch-agenda (cmd-key &rest parameters)
19796 "Run an agenda command in batch mode and send the result to STDOUT.
19797 If CMD-KEY is a string of length 1, it is used as a key in
19798 `org-agenda-custom-commands' and triggers this command. If it is a
19799 longer string it is used as a tags/todo match string.
19800 Paramters are alternating variable names and values that will be bound
19801 before running the agenda command."
19802 (let (pars)
19803 (while parameters
19804 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19805 (if (> (length cmd-key) 2)
19806 (eval (list 'let (nreverse pars)
19807 (list 'org-tags-view nil cmd-key)))
19808 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19809 (set-buffer org-agenda-buffer-name)
19810 (princ (org-encode-for-stdout (buffer-string)))))
19812 (defun org-encode-for-stdout (string)
19813 (if (fboundp 'encode-coding-string)
19814 (encode-coding-string string buffer-file-coding-system)
19815 string))
19817 (defvar org-agenda-info nil)
19819 ;;;###autoload
19820 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19821 "Run an agenda command in batch mode and send the result to STDOUT.
19822 If CMD-KEY is a string of length 1, it is used as a key in
19823 `org-agenda-custom-commands' and triggers this command. If it is a
19824 longer string it is used as a tags/todo match string.
19825 Paramters are alternating variable names and values that will be bound
19826 before running the agenda command.
19828 The output gives a line for each selected agenda item. Each
19829 item is a list of comma-separated values, like this:
19831 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19833 category The category of the item
19834 head The headline, without TODO kwd, TAGS and PRIORITY
19835 type The type of the agenda entry, can be
19836 todo selected in TODO match
19837 tagsmatch selected in tags match
19838 diary imported from diary
19839 deadline a deadline on given date
19840 scheduled scheduled on given date
19841 timestamp entry has timestamp on given date
19842 closed entry was closed on given date
19843 upcoming-deadline warning about deadline
19844 past-scheduled forwarded scheduled item
19845 block entry has date block including g. date
19846 todo The todo keyword, if any
19847 tags All tags including inherited ones, separated by colons
19848 date The relevant date, like 2007-2-14
19849 time The time, like 15:00-16:50
19850 extra Sting with extra planning info
19851 priority-l The priority letter if any was given
19852 priority-n The computed numerical priority
19853 agenda-day The day in the agenda where this is listed"
19855 (let (pars)
19856 (while parameters
19857 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19858 (push (list 'org-agenda-remove-tags t) pars)
19859 (if (> (length cmd-key) 2)
19860 (eval (list 'let (nreverse pars)
19861 (list 'org-tags-view nil cmd-key)))
19862 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19863 (set-buffer org-agenda-buffer-name)
19864 (let* ((lines (org-split-string (buffer-string) "\n"))
19865 line)
19866 (while (setq line (pop lines))
19867 (catch 'next
19868 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19869 (setq org-agenda-info
19870 (org-fix-agenda-info (text-properties-at 0 line)))
19871 (princ
19872 (org-encode-for-stdout
19873 (mapconcat 'org-agenda-export-csv-mapper
19874 '(org-category txt type todo tags date time-of-day extra
19875 priority-letter priority agenda-day)
19876 ",")))
19877 (princ "\n"))))))
19879 (defun org-fix-agenda-info (props)
19880 "Make sure all properties on an agenda item have a canonical form,
19881 so the export commands can easily use it."
19882 (let (tmp re)
19883 (when (setq tmp (plist-get props 'tags))
19884 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19885 (when (setq tmp (plist-get props 'date))
19886 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19887 (let ((calendar-date-display-form '(year "-" month "-" day)))
19888 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19890 (setq tmp (calendar-date-string tmp)))
19891 (setq props (plist-put props 'date tmp)))
19892 (when (setq tmp (plist-get props 'day))
19893 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19894 (let ((calendar-date-display-form '(year "-" month "-" day)))
19895 (setq tmp (calendar-date-string tmp)))
19896 (setq props (plist-put props 'day tmp))
19897 (setq props (plist-put props 'agenda-day tmp)))
19898 (when (setq tmp (plist-get props 'txt))
19899 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19900 (plist-put props 'priority-letter (match-string 1 tmp))
19901 (setq tmp (replace-match "" t t tmp)))
19902 (when (and (setq re (plist-get props 'org-todo-regexp))
19903 (setq re (concat "\\`\\.*" re " ?"))
19904 (string-match re tmp))
19905 (plist-put props 'todo (match-string 1 tmp))
19906 (setq tmp (replace-match "" t t tmp)))
19907 (plist-put props 'txt tmp)))
19908 props)
19910 (defun org-agenda-export-csv-mapper (prop)
19911 (let ((res (plist-get org-agenda-info prop)))
19912 (setq res
19913 (cond
19914 ((not res) "")
19915 ((stringp res) res)
19916 (t (prin1-to-string res))))
19917 (while (string-match "," res)
19918 (setq res (replace-match ";" t t res)))
19919 (org-trim res)))
19922 ;;;###autoload
19923 (defun org-store-agenda-views (&rest parameters)
19924 (interactive)
19925 (eval (list 'org-batch-store-agenda-views)))
19927 ;; FIXME, why is this a macro?????
19928 ;;;###autoload
19929 (defmacro org-batch-store-agenda-views (&rest parameters)
19930 "Run all custom agenda commands that have a file argument."
19931 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19932 (pop-up-frames nil)
19933 (dir default-directory)
19934 pars cmd thiscmdkey files opts)
19935 (while parameters
19936 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19937 (setq pars (reverse pars))
19938 (save-window-excursion
19939 (while cmds
19940 (setq cmd (pop cmds)
19941 thiscmdkey (car cmd)
19942 opts (nth 4 cmd)
19943 files (nth 5 cmd))
19944 (if (stringp files) (setq files (list files)))
19945 (when files
19946 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19947 (list 'org-agenda nil thiscmdkey)))
19948 (set-buffer org-agenda-buffer-name)
19949 (while files
19950 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19951 (list 'org-write-agenda
19952 (expand-file-name (pop files) dir) t))))
19953 (and (get-buffer org-agenda-buffer-name)
19954 (kill-buffer org-agenda-buffer-name)))))))
19956 (defun org-write-agenda (file &optional nosettings)
19957 "Write the current buffer (an agenda view) as a file.
19958 Depending on the extension of the file name, plain text (.txt),
19959 HTML (.html or .htm) or Postscript (.ps) is produced.
19960 If NOSETTINGS is given, do not scope the settings of
19961 `org-agenda-exporter-settings' into the export commands. This is used when
19962 the settings have already been scoped and we do not wish to overrule other,
19963 higher priority settings."
19964 (interactive "FWrite agenda to file: ")
19965 (if (not (file-writable-p file))
19966 (error "Cannot write agenda to file %s" file))
19967 (cond
19968 ((string-match "\\.html?\\'" file) (require 'htmlize))
19969 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19970 (org-let (if nosettings nil org-agenda-exporter-settings)
19971 '(save-excursion
19972 (save-window-excursion
19973 (cond
19974 ((string-match "\\.html?\\'" file)
19975 (set-buffer (htmlize-buffer (current-buffer)))
19977 (when (and org-agenda-export-html-style
19978 (string-match "<style>" org-agenda-export-html-style))
19979 ;; replace <style> section with org-agenda-export-html-style
19980 (goto-char (point-min))
19981 (kill-region (- (search-forward "<style") 6)
19982 (search-forward "</style>"))
19983 (insert org-agenda-export-html-style))
19984 (write-file file)
19985 (kill-buffer (current-buffer))
19986 (message "HTML written to %s" file))
19987 ((string-match "\\.ps\\'" file)
19988 (ps-print-buffer-with-faces file)
19989 (message "Postscript written to %s" file))
19991 (let ((bs (buffer-string)))
19992 (find-file file)
19993 (insert bs)
19994 (save-buffer 0)
19995 (kill-buffer (current-buffer))
19996 (message "Plain text written to %s" file))))))
19997 (set-buffer org-agenda-buffer-name)))
19999 (defmacro org-no-read-only (&rest body)
20000 "Inhibit read-only for BODY."
20001 `(let ((inhibit-read-only t)) ,@body))
20003 (defun org-check-for-org-mode ()
20004 "Make sure current buffer is in org-mode. Error if not."
20005 (or (org-mode-p)
20006 (error "Cannot execute org-mode agenda command on buffer in %s."
20007 major-mode)))
20009 (defun org-fit-agenda-window ()
20010 "Fit the window to the buffer size."
20011 (and (memq org-agenda-window-setup '(reorganize-frame))
20012 (fboundp 'fit-window-to-buffer)
20013 (fit-window-to-buffer
20015 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20016 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20018 ;;; Agenda file list
20020 (defun org-agenda-files (&optional unrestricted)
20021 "Get the list of agenda files.
20022 Optional UNRESTRICTED means return the full list even if a restriction
20023 is currently in place."
20024 (let ((files
20025 (cond
20026 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20027 ((stringp org-agenda-files) (org-read-agenda-file-list))
20028 ((listp org-agenda-files) org-agenda-files)
20029 (t (error "Invalid value of `org-agenda-files'")))))
20030 (setq files (apply 'append
20031 (mapcar (lambda (f)
20032 (if (file-directory-p f)
20033 (directory-files f t
20034 org-agenda-file-regexp)
20035 (list f)))
20036 files)))
20037 (if org-agenda-skip-unavailable-files
20038 (delq nil
20039 (mapcar (function
20040 (lambda (file)
20041 (and (file-readable-p file) file)))
20042 files))
20043 files))) ; `org-check-agenda-file' will remove them from the list
20045 (defun org-edit-agenda-file-list ()
20046 "Edit the list of agenda files.
20047 Depending on setup, this either uses customize to edit the variable
20048 `org-agenda-files', or it visits the file that is holding the list. In the
20049 latter case, the buffer is set up in a way that saving it automatically kills
20050 the buffer and restores the previous window configuration."
20051 (interactive)
20052 (if (stringp org-agenda-files)
20053 (let ((cw (current-window-configuration)))
20054 (find-file org-agenda-files)
20055 (org-set-local 'org-window-configuration cw)
20056 (org-add-hook 'after-save-hook
20057 (lambda ()
20058 (set-window-configuration
20059 (prog1 org-window-configuration
20060 (kill-buffer (current-buffer))))
20061 (org-install-agenda-files-menu)
20062 (message "New agenda file list installed"))
20063 nil 'local)
20064 (message "%s" (substitute-command-keys
20065 "Edit list and finish with \\[save-buffer]")))
20066 (customize-variable 'org-agenda-files)))
20068 (defun org-store-new-agenda-file-list (list)
20069 "Set new value for the agenda file list and save it correcly."
20070 (if (stringp org-agenda-files)
20071 (let ((f org-agenda-files) b)
20072 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20073 (with-temp-file f
20074 (insert (mapconcat 'identity list "\n") "\n")))
20075 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20076 (setq org-agenda-files list)
20077 (customize-save-variable 'org-agenda-files org-agenda-files))))
20079 (defun org-read-agenda-file-list ()
20080 "Read the list of agenda files from a file."
20081 (when (stringp org-agenda-files)
20082 (with-temp-buffer
20083 (insert-file-contents org-agenda-files)
20084 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20087 ;;;###autoload
20088 (defun org-cycle-agenda-files ()
20089 "Cycle through the files in `org-agenda-files'.
20090 If the current buffer visits an agenda file, find the next one in the list.
20091 If the current buffer does not, find the first agenda file."
20092 (interactive)
20093 (let* ((fs (org-agenda-files t))
20094 (files (append fs (list (car fs))))
20095 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20096 file)
20097 (unless files (error "No agenda files"))
20098 (catch 'exit
20099 (while (setq file (pop files))
20100 (if (equal (file-truename file) tcf)
20101 (when (car files)
20102 (find-file (car files))
20103 (throw 'exit t))))
20104 (find-file (car fs)))
20105 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20107 (defun org-agenda-file-to-front (&optional to-end)
20108 "Move/add the current file to the top of the agenda file list.
20109 If the file is not present in the list, it is added to the front. If it is
20110 present, it is moved there. With optional argument TO-END, add/move to the
20111 end of the list."
20112 (interactive "P")
20113 (let ((org-agenda-skip-unavailable-files nil)
20114 (file-alist (mapcar (lambda (x)
20115 (cons (file-truename x) x))
20116 (org-agenda-files t)))
20117 (ctf (file-truename buffer-file-name))
20118 x had)
20119 (setq x (assoc ctf file-alist) had x)
20121 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20122 (if to-end
20123 (setq file-alist (append (delq x file-alist) (list x)))
20124 (setq file-alist (cons x (delq x file-alist))))
20125 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20126 (org-install-agenda-files-menu)
20127 (message "File %s to %s of agenda file list"
20128 (if had "moved" "added") (if to-end "end" "front"))))
20130 (defun org-remove-file (&optional file)
20131 "Remove current file from the list of files in variable `org-agenda-files'.
20132 These are the files which are being checked for agenda entries.
20133 Optional argument FILE means, use this file instead of the current."
20134 (interactive)
20135 (let* ((org-agenda-skip-unavailable-files nil)
20136 (file (or file buffer-file-name))
20137 (true-file (file-truename file))
20138 (afile (abbreviate-file-name file))
20139 (files (delq nil (mapcar
20140 (lambda (x)
20141 (if (equal true-file
20142 (file-truename x))
20143 nil x))
20144 (org-agenda-files t)))))
20145 (if (not (= (length files) (length (org-agenda-files t))))
20146 (progn
20147 (org-store-new-agenda-file-list files)
20148 (org-install-agenda-files-menu)
20149 (message "Removed file: %s" afile))
20150 (message "File was not in list: %s (not removed)" afile))))
20152 (defun org-file-menu-entry (file)
20153 (vector file (list 'find-file file) t))
20155 (defun org-check-agenda-file (file)
20156 "Make sure FILE exists. If not, ask user what to do."
20157 (when (not (file-exists-p file))
20158 (message "non-existent file %s. [R]emove from list or [A]bort?"
20159 (abbreviate-file-name file))
20160 (let ((r (downcase (read-char-exclusive))))
20161 (cond
20162 ((equal r ?r)
20163 (org-remove-file file)
20164 (throw 'nextfile t))
20165 (t (error "Abort"))))))
20167 ;;; Agenda prepare and finalize
20169 (defvar org-agenda-multi nil) ; dynammically scoped
20170 (defvar org-agenda-buffer-name "*Org Agenda*")
20171 (defvar org-pre-agenda-window-conf nil)
20172 (defvar org-agenda-name nil)
20173 (defun org-prepare-agenda (&optional name)
20174 (setq org-todo-keywords-for-agenda nil)
20175 (setq org-done-keywords-for-agenda nil)
20176 (if org-agenda-multi
20177 (progn
20178 (setq buffer-read-only nil)
20179 (goto-char (point-max))
20180 (unless (or (bobp) org-agenda-compact-blocks)
20181 (insert "\n" (make-string (window-width) ?=) "\n"))
20182 (narrow-to-region (point) (point-max)))
20183 (org-agenda-maybe-reset-markers 'force)
20184 (org-prepare-agenda-buffers (org-agenda-files))
20185 (setq org-todo-keywords-for-agenda
20186 (org-uniquify org-todo-keywords-for-agenda))
20187 (setq org-done-keywords-for-agenda
20188 (org-uniquify org-done-keywords-for-agenda))
20189 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20190 (awin (get-buffer-window abuf)))
20191 (cond
20192 ((equal (current-buffer) abuf) nil)
20193 (awin (select-window awin))
20194 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20195 ((equal org-agenda-window-setup 'current-window)
20196 (switch-to-buffer abuf))
20197 ((equal org-agenda-window-setup 'other-window)
20198 (org-switch-to-buffer-other-window abuf))
20199 ((equal org-agenda-window-setup 'other-frame)
20200 (switch-to-buffer-other-frame abuf))
20201 ((equal org-agenda-window-setup 'reorganize-frame)
20202 (delete-other-windows)
20203 (org-switch-to-buffer-other-window abuf))))
20204 (setq buffer-read-only nil)
20205 (erase-buffer)
20206 (org-agenda-mode)
20207 (and name (not org-agenda-name)
20208 (org-set-local 'org-agenda-name name)))
20209 (setq buffer-read-only nil))
20211 (defun org-finalize-agenda ()
20212 "Finishing touch for the agenda buffer, called just before displaying it."
20213 (unless org-agenda-multi
20214 (save-excursion
20215 (let ((inhibit-read-only t))
20216 (goto-char (point-min))
20217 (while (org-activate-bracket-links (point-max))
20218 (add-text-properties (match-beginning 0) (match-end 0)
20219 '(face org-link)))
20220 (org-agenda-align-tags)
20221 (unless org-agenda-with-colors
20222 (remove-text-properties (point-min) (point-max) '(face nil))))
20223 (if (and (boundp 'org-overriding-columns-format)
20224 org-overriding-columns-format)
20225 (org-set-local 'org-overriding-columns-format
20226 org-overriding-columns-format))
20227 (if (and (boundp 'org-agenda-view-columns-initially)
20228 org-agenda-view-columns-initially)
20229 (org-agenda-columns))
20230 (when org-agenda-fontify-priorities
20231 (org-fontify-priorities))
20232 (run-hooks 'org-finalize-agenda-hook)
20233 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20236 (defun org-fontify-priorities ()
20237 "Make highest priority lines bold, and lowest italic."
20238 (interactive)
20239 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20240 (org-delete-overlay o)))
20241 (org-overlays-in (point-min) (point-max)))
20242 (save-excursion
20243 (let ((inhibit-read-only t)
20244 b e p ov h l)
20245 (goto-char (point-min))
20246 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20247 (setq h (or (get-char-property (point) 'org-highest-priority)
20248 org-highest-priority)
20249 l (or (get-char-property (point) 'org-lowest-priority)
20250 org-lowest-priority)
20251 p (string-to-char (match-string 1))
20252 b (match-beginning 0) e (point-at-eol)
20253 ov (org-make-overlay b e))
20254 (org-overlay-put
20255 ov 'face
20256 (cond ((listp org-agenda-fontify-priorities)
20257 (cdr (assoc p org-agenda-fontify-priorities)))
20258 ((equal p l) 'italic)
20259 ((equal p h) 'bold)))
20260 (org-overlay-put ov 'org-type 'org-priority)))))
20262 (defun org-prepare-agenda-buffers (files)
20263 "Create buffers for all agenda files, protect archived trees and comments."
20264 (interactive)
20265 (let ((pa '(:org-archived t))
20266 (pc '(:org-comment t))
20267 (pall '(:org-archived t :org-comment t))
20268 (inhibit-read-only t)
20269 (rea (concat ":" org-archive-tag ":"))
20270 bmp file re)
20271 (save-excursion
20272 (save-restriction
20273 (while (setq file (pop files))
20274 (if (bufferp file)
20275 (set-buffer file)
20276 (org-check-agenda-file file)
20277 (set-buffer (org-get-agenda-file-buffer file)))
20278 (widen)
20279 (setq bmp (buffer-modified-p))
20280 (org-refresh-category-properties)
20281 (setq org-todo-keywords-for-agenda
20282 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20283 (setq org-done-keywords-for-agenda
20284 (append org-done-keywords-for-agenda org-done-keywords))
20285 (save-excursion
20286 (remove-text-properties (point-min) (point-max) pall)
20287 (when org-agenda-skip-archived-trees
20288 (goto-char (point-min))
20289 (while (re-search-forward rea nil t)
20290 (if (org-on-heading-p t)
20291 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20292 (goto-char (point-min))
20293 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20294 (while (re-search-forward re nil t)
20295 (add-text-properties
20296 (match-beginning 0) (org-end-of-subtree t) pc)))
20297 (set-buffer-modified-p bmp))))))
20299 (defvar org-agenda-skip-function nil
20300 "Function to be called at each match during agenda construction.
20301 If this function returns nil, the current match should not be skipped.
20302 Otherwise, the function must return a position from where the search
20303 should be continued.
20304 This may also be a Lisp form, it will be evaluated.
20305 Never set this variable using `setq' or so, because then it will apply
20306 to all future agenda commands. Instead, bind it with `let' to scope
20307 it dynamically into the agenda-constructing command. A good way to set
20308 it is through options in org-agenda-custom-commands.")
20310 (defun org-agenda-skip ()
20311 "Throw to `:skip' in places that should be skipped.
20312 Also moves point to the end of the skipped region, so that search can
20313 continue from there."
20314 (let ((p (point-at-bol)) to fp)
20315 (and org-agenda-skip-archived-trees
20316 (get-text-property p :org-archived)
20317 (org-end-of-subtree t)
20318 (throw :skip t))
20319 (and (get-text-property p :org-comment)
20320 (org-end-of-subtree t)
20321 (throw :skip t))
20322 (if (equal (char-after p) ?#) (throw :skip t))
20323 (when (and (or (setq fp (functionp org-agenda-skip-function))
20324 (consp org-agenda-skip-function))
20325 (setq to (save-excursion
20326 (save-match-data
20327 (if fp
20328 (funcall org-agenda-skip-function)
20329 (eval org-agenda-skip-function))))))
20330 (goto-char to)
20331 (throw :skip t))))
20333 (defvar org-agenda-markers nil
20334 "List of all currently active markers created by `org-agenda'.")
20335 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20336 "Creation time of the last agenda marker.")
20338 (defun org-agenda-new-marker (&optional pos)
20339 "Return a new agenda marker.
20340 Org-mode keeps a list of these markers and resets them when they are
20341 no longer in use."
20342 (let ((m (copy-marker (or pos (point)))))
20343 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20344 (push m org-agenda-markers)
20347 (defun org-agenda-maybe-reset-markers (&optional force)
20348 "Reset markers created by `org-agenda'. But only if they are old enough."
20349 (if (or (and force (not org-agenda-multi))
20350 (> (- (time-to-seconds (current-time))
20351 org-agenda-last-marker-time)
20353 (while org-agenda-markers
20354 (move-marker (pop org-agenda-markers) nil))))
20356 (defun org-get-agenda-file-buffer (file)
20357 "Get a buffer visiting FILE. If the buffer needs to be created, add
20358 it to the list of buffers which might be released later."
20359 (let ((buf (org-find-base-buffer-visiting file)))
20360 (if buf
20361 buf ; just return it
20362 ;; Make a new buffer and remember it
20363 (setq buf (find-file-noselect file))
20364 (if buf (push buf org-agenda-new-buffers))
20365 buf)))
20367 (defun org-release-buffers (blist)
20368 "Release all buffers in list, asking the user for confirmation when needed.
20369 When a buffer is unmodified, it is just killed. When modified, it is saved
20370 \(if the user agrees) and then killed."
20371 (let (buf file)
20372 (while (setq buf (pop blist))
20373 (setq file (buffer-file-name buf))
20374 (when (and (buffer-modified-p buf)
20375 file
20376 (y-or-n-p (format "Save file %s? " file)))
20377 (with-current-buffer buf (save-buffer)))
20378 (kill-buffer buf))))
20380 (defun org-get-category (&optional pos)
20381 "Get the category applying to position POS."
20382 (get-text-property (or pos (point)) 'org-category))
20384 ;;; Agenda timeline
20386 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20388 (defun org-timeline (&optional include-all)
20389 "Show a time-sorted view of the entries in the current org file.
20390 Only entries with a time stamp of today or later will be listed. With
20391 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20392 under the current date.
20393 If the buffer contains an active region, only check the region for
20394 dates."
20395 (interactive "P")
20396 (require 'calendar)
20397 (org-compile-prefix-format 'timeline)
20398 (org-set-sorting-strategy 'timeline)
20399 (let* ((dopast t)
20400 (dotodo include-all)
20401 (doclosed org-agenda-show-log)
20402 (entry buffer-file-name)
20403 (date (calendar-current-date))
20404 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20405 (end (if (org-region-active-p) (region-end) (point-max)))
20406 (day-numbers (org-get-all-dates beg end 'no-ranges
20407 t doclosed ; always include today
20408 org-timeline-show-empty-dates))
20409 (org-deadline-warning-days 0)
20410 (org-agenda-only-exact-dates t)
20411 (today (time-to-days (current-time)))
20412 (past t)
20413 args
20414 s e rtn d emptyp)
20415 (setq org-agenda-redo-command
20416 (list 'progn
20417 (list 'org-switch-to-buffer-other-window (current-buffer))
20418 (list 'org-timeline (list 'quote include-all))))
20419 (if (not dopast)
20420 ;; Remove past dates from the list of dates.
20421 (setq day-numbers (delq nil (mapcar (lambda(x)
20422 (if (>= x today) x nil))
20423 day-numbers))))
20424 (org-prepare-agenda (concat "Timeline "
20425 (file-name-nondirectory buffer-file-name)))
20426 (if doclosed (push :closed args))
20427 (push :timestamp args)
20428 (push :deadline args)
20429 (push :scheduled args)
20430 (push :sexp args)
20431 (if dotodo (push :todo args))
20432 (while (setq d (pop day-numbers))
20433 (if (and (listp d) (eq (car d) :omitted))
20434 (progn
20435 (setq s (point))
20436 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20437 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20438 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20439 (if (and (>= d today)
20440 dopast
20441 past)
20442 (progn
20443 (setq past nil)
20444 (insert (make-string 79 ?-) "\n")))
20445 (setq date (calendar-gregorian-from-absolute d))
20446 (setq s (point))
20447 (setq rtn (and (not emptyp)
20448 (apply 'org-agenda-get-day-entries entry
20449 date args)))
20450 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20451 (progn
20452 (insert
20453 (if (stringp org-agenda-format-date)
20454 (format-time-string org-agenda-format-date
20455 (org-time-from-absolute date))
20456 (funcall org-agenda-format-date date))
20457 "\n")
20458 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20459 (put-text-property s (1- (point)) 'org-date-line t)
20460 (if (equal d today)
20461 (put-text-property s (1- (point)) 'org-today t))
20462 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20463 (put-text-property s (1- (point)) 'day d)))))
20464 (goto-char (point-min))
20465 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20466 (point-min)))
20467 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20468 (org-finalize-agenda)
20469 (setq buffer-read-only t)))
20471 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20472 "Return a list of all relevant day numbers from BEG to END buffer positions.
20473 If NO-RANGES is non-nil, include only the start and end dates of a range,
20474 not every single day in the range. If FORCE-TODAY is non-nil, make
20475 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20476 inactive time stamps (those in square brackets) are included.
20477 When EMPTY is non-nil, also include days without any entries."
20478 (let ((re (concat
20479 (if pre-re pre-re "")
20480 (if inactive org-ts-regexp-both org-ts-regexp)))
20481 dates dates1 date day day1 day2 ts1 ts2)
20482 (if force-today
20483 (setq dates (list (time-to-days (current-time)))))
20484 (save-excursion
20485 (goto-char beg)
20486 (while (re-search-forward re end t)
20487 (setq day (time-to-days (org-time-string-to-time
20488 (substring (match-string 1) 0 10))))
20489 (or (memq day dates) (push day dates)))
20490 (unless no-ranges
20491 (goto-char beg)
20492 (while (re-search-forward org-tr-regexp end t)
20493 (setq ts1 (substring (match-string 1) 0 10)
20494 ts2 (substring (match-string 2) 0 10)
20495 day1 (time-to-days (org-time-string-to-time ts1))
20496 day2 (time-to-days (org-time-string-to-time ts2)))
20497 (while (< (setq day1 (1+ day1)) day2)
20498 (or (memq day1 dates) (push day1 dates)))))
20499 (setq dates (sort dates '<))
20500 (when empty
20501 (while (setq day (pop dates))
20502 (setq day2 (car dates))
20503 (push day dates1)
20504 (when (and day2 empty)
20505 (if (or (eq empty t)
20506 (and (numberp empty) (<= (- day2 day) empty)))
20507 (while (< (setq day (1+ day)) day2)
20508 (push (list day) dates1))
20509 (push (cons :omitted (- day2 day)) dates1))))
20510 (setq dates (nreverse dates1)))
20511 dates)))
20513 ;;; Agenda Daily/Weekly
20515 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20516 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20517 (defvar org-agenda-last-arguments nil
20518 "The arguments of the previous call to org-agenda")
20519 (defvar org-starting-day nil) ; local variable in the agenda buffer
20520 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20521 (defvar org-include-all-loc nil) ; local variable
20522 (defvar org-agenda-remove-date nil) ; dynamically scoped
20524 ;;;###autoload
20525 (defun org-agenda-list (&optional include-all start-day ndays)
20526 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20527 The view will be for the current day or week, but from the overview buffer
20528 you will be able to go to other days/weeks.
20530 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20531 all unfinished TODO items will also be shown, before the agenda.
20532 This feature is considered obsolete, please use the TODO list or a block
20533 agenda instead.
20535 With a numeric prefix argument in an interactive call, the agenda will
20536 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20537 the number of days. NDAYS defaults to `org-agenda-ndays'.
20539 START-DAY defaults to TODAY, or to the most recent match for the weekday
20540 given in `org-agenda-start-on-weekday'."
20541 (interactive "P")
20542 (if (and (integerp include-all) (> include-all 0))
20543 (setq ndays include-all include-all nil))
20544 (setq ndays (or ndays org-agenda-ndays)
20545 start-day (or start-day org-agenda-start-day))
20546 (if org-agenda-overriding-arguments
20547 (setq include-all (car org-agenda-overriding-arguments)
20548 start-day (nth 1 org-agenda-overriding-arguments)
20549 ndays (nth 2 org-agenda-overriding-arguments)))
20550 (if (stringp start-day)
20551 ;; Convert to an absolute day number
20552 (setq start-day (time-to-days (org-read-date nil t start-day))))
20553 (setq org-agenda-last-arguments (list include-all start-day ndays))
20554 (org-compile-prefix-format 'agenda)
20555 (org-set-sorting-strategy 'agenda)
20556 (require 'calendar)
20557 (let* ((org-agenda-start-on-weekday
20558 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20559 org-agenda-start-on-weekday nil))
20560 (thefiles (org-agenda-files))
20561 (files thefiles)
20562 (today (time-to-days
20563 (time-subtract (current-time)
20564 (list 0 (* 3600 org-extend-today-until) 0))))
20565 (sd (or start-day today))
20566 (start (if (or (null org-agenda-start-on-weekday)
20567 (< org-agenda-ndays 7))
20569 (let* ((nt (calendar-day-of-week
20570 (calendar-gregorian-from-absolute sd)))
20571 (n1 org-agenda-start-on-weekday)
20572 (d (- nt n1)))
20573 (- sd (+ (if (< d 0) 7 0) d)))))
20574 (day-numbers (list start))
20575 (day-cnt 0)
20576 (inhibit-redisplay (not debug-on-error))
20577 s e rtn rtnall file date d start-pos end-pos todayp nd)
20578 (setq org-agenda-redo-command
20579 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20580 ;; Make the list of days
20581 (setq ndays (or ndays org-agenda-ndays)
20582 nd ndays)
20583 (while (> ndays 1)
20584 (push (1+ (car day-numbers)) day-numbers)
20585 (setq ndays (1- ndays)))
20586 (setq day-numbers (nreverse day-numbers))
20587 (org-prepare-agenda "Day/Week")
20588 (org-set-local 'org-starting-day (car day-numbers))
20589 (org-set-local 'org-include-all-loc include-all)
20590 (org-set-local 'org-agenda-span
20591 (org-agenda-ndays-to-span nd))
20592 (when (and (or include-all org-agenda-include-all-todo)
20593 (member today day-numbers))
20594 (setq files thefiles
20595 rtnall nil)
20596 (while (setq file (pop files))
20597 (catch 'nextfile
20598 (org-check-agenda-file file)
20599 (setq date (calendar-gregorian-from-absolute today)
20600 rtn (org-agenda-get-day-entries
20601 file date :todo))
20602 (setq rtnall (append rtnall rtn))))
20603 (when rtnall
20604 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20605 (add-text-properties (point-min) (1- (point))
20606 (list 'face 'org-agenda-structure))
20607 (insert (org-finalize-agenda-entries rtnall) "\n")))
20608 (unless org-agenda-compact-blocks
20609 (setq s (point))
20610 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20611 "-agenda:\n")
20612 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20613 'org-date-line t)))
20614 (while (setq d (pop day-numbers))
20615 (setq date (calendar-gregorian-from-absolute d)
20616 s (point))
20617 (if (or (setq todayp (= d today))
20618 (and (not start-pos) (= d sd)))
20619 (setq start-pos (point))
20620 (if (and start-pos (not end-pos))
20621 (setq end-pos (point))))
20622 (setq files thefiles
20623 rtnall nil)
20624 (while (setq file (pop files))
20625 (catch 'nextfile
20626 (org-check-agenda-file file)
20627 (if org-agenda-show-log
20628 (setq rtn (org-agenda-get-day-entries
20629 file date
20630 :deadline :scheduled :timestamp :sexp :closed))
20631 (setq rtn (org-agenda-get-day-entries
20632 file date
20633 :deadline :scheduled :sexp :timestamp)))
20634 (setq rtnall (append rtnall rtn))))
20635 (if org-agenda-include-diary
20636 (progn
20637 (require 'diary-lib)
20638 (setq rtn (org-get-entries-from-diary date))
20639 (setq rtnall (append rtnall rtn))))
20640 (if (or rtnall org-agenda-show-all-dates)
20641 (progn
20642 (setq day-cnt (1+ day-cnt))
20643 (insert
20644 (if (stringp org-agenda-format-date)
20645 (format-time-string org-agenda-format-date
20646 (org-time-from-absolute date))
20647 (funcall org-agenda-format-date date))
20648 "\n")
20649 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20650 (put-text-property s (1- (point)) 'org-date-line t)
20651 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20652 (if todayp (put-text-property s (1- (point)) 'org-today t))
20653 (if rtnall (insert
20654 (org-finalize-agenda-entries
20655 (org-agenda-add-time-grid-maybe
20656 rtnall nd todayp))
20657 "\n"))
20658 (put-text-property s (1- (point)) 'day d)
20659 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20660 (goto-char (point-min))
20661 (org-fit-agenda-window)
20662 (unless (and (pos-visible-in-window-p (point-min))
20663 (pos-visible-in-window-p (point-max)))
20664 (goto-char (1- (point-max)))
20665 (recenter -1)
20666 (if (not (pos-visible-in-window-p (or start-pos 1)))
20667 (progn
20668 (goto-char (or start-pos 1))
20669 (recenter 1))))
20670 (goto-char (or start-pos 1))
20671 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20672 (org-finalize-agenda)
20673 (setq buffer-read-only t)
20674 (message "")))
20676 (defun org-agenda-ndays-to-span (n)
20677 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20679 ;;; Agenda TODO list
20681 (defvar org-select-this-todo-keyword nil)
20682 (defvar org-last-arg nil)
20684 ;;;###autoload
20685 (defun org-todo-list (arg)
20686 "Show all TODO entries from all agenda file in a single list.
20687 The prefix arg can be used to select a specific TODO keyword and limit
20688 the list to these. When using \\[universal-argument], you will be prompted
20689 for a keyword. A numeric prefix directly selects the Nth keyword in
20690 `org-todo-keywords-1'."
20691 (interactive "P")
20692 (require 'calendar)
20693 (org-compile-prefix-format 'todo)
20694 (org-set-sorting-strategy 'todo)
20695 (org-prepare-agenda "TODO")
20696 (let* ((today (time-to-days (current-time)))
20697 (date (calendar-gregorian-from-absolute today))
20698 (kwds org-todo-keywords-for-agenda)
20699 (completion-ignore-case t)
20700 (org-select-this-todo-keyword
20701 (if (stringp arg) arg
20702 (and arg (integerp arg) (> arg 0)
20703 (nth (1- arg) kwds))))
20704 rtn rtnall files file pos)
20705 (when (equal arg '(4))
20706 (setq org-select-this-todo-keyword
20707 (completing-read "Keyword (or KWD1|K2D2|...): "
20708 (mapcar 'list kwds) nil nil)))
20709 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20710 (org-set-local 'org-last-arg arg)
20711 (setq org-agenda-redo-command
20712 '(org-todo-list (or current-prefix-arg org-last-arg)))
20713 (setq files (org-agenda-files)
20714 rtnall nil)
20715 (while (setq file (pop files))
20716 (catch 'nextfile
20717 (org-check-agenda-file file)
20718 (setq rtn (org-agenda-get-day-entries file date :todo))
20719 (setq rtnall (append rtnall rtn))))
20720 (if org-agenda-overriding-header
20721 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20722 nil 'face 'org-agenda-structure) "\n")
20723 (insert "Global list of TODO items of type: ")
20724 (add-text-properties (point-min) (1- (point))
20725 (list 'face 'org-agenda-structure))
20726 (setq pos (point))
20727 (insert (or org-select-this-todo-keyword "ALL") "\n")
20728 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20729 (setq pos (point))
20730 (unless org-agenda-multi
20731 (insert "Available with `N r': (0)ALL")
20732 (let ((n 0) s)
20733 (mapc (lambda (x)
20734 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20735 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20736 (insert "\n "))
20737 (insert " " s))
20738 kwds))
20739 (insert "\n"))
20740 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20741 (when rtnall
20742 (insert (org-finalize-agenda-entries rtnall) "\n"))
20743 (goto-char (point-min))
20744 (org-fit-agenda-window)
20745 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20746 (org-finalize-agenda)
20747 (setq buffer-read-only t)))
20749 ;;; Agenda tags match
20751 ;;;###autoload
20752 (defun org-tags-view (&optional todo-only match)
20753 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20754 The prefix arg TODO-ONLY limits the search to TODO entries."
20755 (interactive "P")
20756 (org-compile-prefix-format 'tags)
20757 (org-set-sorting-strategy 'tags)
20758 (let* ((org-tags-match-list-sublevels
20759 (if todo-only t org-tags-match-list-sublevels))
20760 (completion-ignore-case t)
20761 rtn rtnall files file pos matcher
20762 buffer)
20763 (setq matcher (org-make-tags-matcher match)
20764 match (car matcher) matcher (cdr matcher))
20765 (org-prepare-agenda (concat "TAGS " match))
20766 (setq org-agenda-redo-command
20767 (list 'org-tags-view (list 'quote todo-only)
20768 (list 'if 'current-prefix-arg nil match)))
20769 (setq files (org-agenda-files)
20770 rtnall nil)
20771 (while (setq file (pop files))
20772 (catch 'nextfile
20773 (org-check-agenda-file file)
20774 (setq buffer (if (file-exists-p file)
20775 (org-get-agenda-file-buffer file)
20776 (error "No such file %s" file)))
20777 (if (not buffer)
20778 ;; If file does not exist, merror message to agenda
20779 (setq rtn (list
20780 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20781 rtnall (append rtnall rtn))
20782 (with-current-buffer buffer
20783 (unless (org-mode-p)
20784 (error "Agenda file %s is not in `org-mode'" file))
20785 (save-excursion
20786 (save-restriction
20787 (if org-agenda-restrict
20788 (narrow-to-region org-agenda-restrict-begin
20789 org-agenda-restrict-end)
20790 (widen))
20791 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20792 (setq rtnall (append rtnall rtn))))))))
20793 (if org-agenda-overriding-header
20794 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20795 nil 'face 'org-agenda-structure) "\n")
20796 (insert "Headlines with TAGS match: ")
20797 (add-text-properties (point-min) (1- (point))
20798 (list 'face 'org-agenda-structure))
20799 (setq pos (point))
20800 (insert match "\n")
20801 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20802 (setq pos (point))
20803 (unless org-agenda-multi
20804 (insert "Press `C-u r' to search again with new search string\n"))
20805 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20806 (when rtnall
20807 (insert (org-finalize-agenda-entries rtnall) "\n"))
20808 (goto-char (point-min))
20809 (org-fit-agenda-window)
20810 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20811 (org-finalize-agenda)
20812 (setq buffer-read-only t)))
20814 ;;; Agenda Finding stuck projects
20816 (defvar org-agenda-skip-regexp nil
20817 "Regular expression used in skipping subtrees for the agenda.
20818 This is basically a temporary global variable that can be set and then
20819 used by user-defined selections using `org-agenda-skip-function'.")
20821 (defvar org-agenda-overriding-header nil
20822 "When this is set during todo and tags searches, will replace header.")
20824 (defun org-agenda-skip-subtree-when-regexp-matches ()
20825 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20826 If yes, it returns the end position of this tree, causing agenda commands
20827 to skip this subtree. This is a function that can be put into
20828 `org-agenda-skip-function' for the duration of a command."
20829 (let ((end (save-excursion (org-end-of-subtree t)))
20830 skip)
20831 (save-excursion
20832 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20833 (and skip end)))
20835 (defun org-agenda-skip-entry-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 nil conditions))
20840 (defun org-agenda-skip-subtree-if (&rest conditions)
20841 "Skip entry if any of CONDITIONS is true.
20842 See `org-agenda-skip-if' for details."
20843 (org-agenda-skip-if t conditions))
20845 (defun org-agenda-skip-if (subtree conditions)
20846 "Checks current entity for CONDITIONS.
20847 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20848 the entry, i.e. the text before the next heading is checked.
20850 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20851 from different tests. Valid conditions are:
20853 scheduled Check if there is a scheduled cookie
20854 notscheduled Check if there is no scheduled cookie
20855 deadline Check if there is a deadline
20856 notdeadline Check if there is no deadline
20857 regexp Check if regexp matches
20858 notregexp Check if regexp does not match.
20860 The regexp is taken from the conditions list, it must come right after
20861 the `regexp' or `notregexp' element.
20863 If any of these conditions is met, this function returns the end point of
20864 the entity, causing the search to continue from there. This is a function
20865 that can be put into `org-agenda-skip-function' for the duration of a command."
20866 (let (beg end m)
20867 (org-back-to-heading t)
20868 (setq beg (point)
20869 end (if subtree
20870 (progn (org-end-of-subtree t) (point))
20871 (progn (outline-next-heading) (1- (point)))))
20872 (goto-char beg)
20873 (and
20875 (and (memq 'scheduled conditions)
20876 (re-search-forward org-scheduled-time-regexp end t))
20877 (and (memq 'notscheduled conditions)
20878 (not (re-search-forward org-scheduled-time-regexp end t)))
20879 (and (memq 'deadline conditions)
20880 (re-search-forward org-deadline-time-regexp end t))
20881 (and (memq 'notdeadline conditions)
20882 (not (re-search-forward org-deadline-time-regexp end t)))
20883 (and (setq m (memq 'regexp conditions))
20884 (stringp (nth 1 m))
20885 (re-search-forward (nth 1 m) end t))
20886 (and (setq m (memq 'notregexp conditions))
20887 (stringp (nth 1 m))
20888 (not (re-search-forward (nth 1 m) end t))))
20889 end)))
20891 ;;;###autoload
20892 (defun org-agenda-list-stuck-projects (&rest ignore)
20893 "Create agenda view for projects that are stuck.
20894 Stuck projects are project that have no next actions. For the definitions
20895 of what a project is and how to check if it stuck, customize the variable
20896 `org-stuck-projects'.
20897 MATCH is being ignored."
20898 (interactive)
20899 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20900 ;; FIXME: we could have used org-agenda-skip-if here.
20901 (org-agenda-overriding-header "List of stuck projects: ")
20902 (matcher (nth 0 org-stuck-projects))
20903 (todo (nth 1 org-stuck-projects))
20904 (todo-wds (if (member "*" todo)
20905 (progn
20906 (org-prepare-agenda-buffers (org-agenda-files))
20907 (org-delete-all
20908 org-done-keywords-for-agenda
20909 (copy-sequence org-todo-keywords-for-agenda)))
20910 todo))
20911 (todo-re (concat "^\\*+[ \t]+\\("
20912 (mapconcat 'identity todo-wds "\\|")
20913 "\\)\\>"))
20914 (tags (nth 2 org-stuck-projects))
20915 (tags-re (if (member "*" tags)
20916 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20917 (concat "^\\*+ .*:\\("
20918 (mapconcat 'identity tags "\\|")
20919 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20920 (gen-re (nth 3 org-stuck-projects))
20921 (re-list
20922 (delq nil
20923 (list
20924 (if todo todo-re)
20925 (if tags tags-re)
20926 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20927 gen-re)))))
20928 (setq org-agenda-skip-regexp
20929 (if re-list
20930 (mapconcat 'identity re-list "\\|")
20931 (error "No information how to identify unstuck projects")))
20932 (org-tags-view nil matcher)
20933 (with-current-buffer org-agenda-buffer-name
20934 (setq org-agenda-redo-command
20935 '(org-agenda-list-stuck-projects
20936 (or current-prefix-arg org-last-arg))))))
20938 ;;; Diary integration
20940 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20942 (defun org-get-entries-from-diary (date)
20943 "Get the (Emacs Calendar) diary entries for DATE."
20944 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20945 (diary-display-hook '(fancy-diary-display))
20946 (pop-up-frames nil)
20947 (list-diary-entries-hook
20948 (cons 'org-diary-default-entry list-diary-entries-hook))
20949 (diary-file-name-prefix-function nil) ; turn this feature off
20950 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20951 entries
20952 (org-disable-agenda-to-diary t))
20953 (save-excursion
20954 (save-window-excursion
20955 (funcall (if (fboundp 'diary-list-entries)
20956 'diary-list-entries 'list-diary-entries)
20957 date 1)))
20958 (if (not (get-buffer fancy-diary-buffer))
20959 (setq entries nil)
20960 (with-current-buffer fancy-diary-buffer
20961 (setq buffer-read-only nil)
20962 (if (zerop (buffer-size))
20963 ;; No entries
20964 (setq entries nil)
20965 ;; Omit the date and other unnecessary stuff
20966 (org-agenda-cleanup-fancy-diary)
20967 ;; Add prefix to each line and extend the text properties
20968 (if (zerop (buffer-size))
20969 (setq entries nil)
20970 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20971 (set-buffer-modified-p nil)
20972 (kill-buffer fancy-diary-buffer)))
20973 (when entries
20974 (setq entries (org-split-string entries "\n"))
20975 (setq entries
20976 (mapcar
20977 (lambda (x)
20978 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20979 ;; Extend the text properties to the beginning of the line
20980 (org-add-props x (text-properties-at (1- (length x)) x)
20981 'type "diary" 'date date))
20982 entries)))))
20984 (defun org-agenda-cleanup-fancy-diary ()
20985 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20986 This gets rid of the date, the underline under the date, and
20987 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20988 date. It also removes lines that contain only whitespace."
20989 (goto-char (point-min))
20990 (if (looking-at ".*?:[ \t]*")
20991 (progn
20992 (replace-match "")
20993 (re-search-forward "\n=+$" nil t)
20994 (replace-match "")
20995 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20996 (re-search-forward "\n=+$" nil t)
20997 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20998 (goto-char (point-min))
20999 (while (re-search-forward "^ +\n" nil t)
21000 (replace-match ""))
21001 (goto-char (point-min))
21002 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21003 (replace-match "")))
21005 ;; Make sure entries from the diary have the right text properties.
21006 (eval-after-load "diary-lib"
21007 '(if (boundp 'diary-modify-entry-list-string-function)
21008 ;; We can rely on the hook, nothing to do
21010 ;; Hook not avaiable, must use advice to make this work
21011 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21012 "Make the position visible."
21013 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21014 (stringp string)
21015 buffer-file-name)
21016 (setq string (org-modify-diary-entry-string string))))))
21018 (defun org-modify-diary-entry-string (string)
21019 "Add text properties to string, allowing org-mode to act on it."
21020 (org-add-props string nil
21021 'mouse-face 'highlight
21022 'keymap org-agenda-keymap
21023 'help-echo (if buffer-file-name
21024 (format "mouse-2 or RET jump to diary file %s"
21025 (abbreviate-file-name buffer-file-name))
21027 'org-agenda-diary-link t
21028 'org-marker (org-agenda-new-marker (point-at-bol))))
21030 (defun org-diary-default-entry ()
21031 "Add a dummy entry to the diary.
21032 Needed to avoid empty dates which mess up holiday display."
21033 ;; Catch the error if dealing with the new add-to-diary-alist
21034 (when org-disable-agenda-to-diary
21035 (condition-case nil
21036 (add-to-diary-list original-date "Org-mode dummy" "")
21037 (error
21038 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21040 ;;;###autoload
21041 (defun org-diary (&rest args)
21042 "Return diary information from org-files.
21043 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21044 It accesses org files and extracts information from those files to be
21045 listed in the diary. The function accepts arguments specifying what
21046 items should be listed. The following arguments are allowed:
21048 :timestamp List the headlines of items containing a date stamp or
21049 date range matching the selected date. Deadlines will
21050 also be listed, on the expiration day.
21052 :sexp List entries resulting from diary-like sexps.
21054 :deadline List any deadlines past due, or due within
21055 `org-deadline-warning-days'. The listing occurs only
21056 in the diary for *today*, not at any other date. If
21057 an entry is marked DONE, it is no longer listed.
21059 :scheduled List all items which are scheduled for the given date.
21060 The diary for *today* also contains items which were
21061 scheduled earlier and are not yet marked DONE.
21063 :todo List all TODO items from the org-file. This may be a
21064 long list - so this is not turned on by default.
21065 Like deadlines, these entries only show up in the
21066 diary for *today*, not at any other date.
21068 The call in the diary file should look like this:
21070 &%%(org-diary) ~/path/to/some/orgfile.org
21072 Use a separate line for each org file to check. Or, if you omit the file name,
21073 all files listed in `org-agenda-files' will be checked automatically:
21075 &%%(org-diary)
21077 If you don't give any arguments (as in the example above), the default
21078 arguments (:deadline :scheduled :timestamp :sexp) are used.
21079 So the example above may also be written as
21081 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21083 The function expects the lisp variables `entry' and `date' to be provided
21084 by the caller, because this is how the calendar works. Don't use this
21085 function from a program - use `org-agenda-get-day-entries' instead."
21086 (org-agenda-maybe-reset-markers)
21087 (org-compile-prefix-format 'agenda)
21088 (org-set-sorting-strategy 'agenda)
21089 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21090 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21091 (list entry)
21092 (org-agenda-files t)))
21093 file rtn results)
21094 (org-prepare-agenda-buffers files)
21095 ;; If this is called during org-agenda, don't return any entries to
21096 ;; the calendar. Org Agenda will list these entries itself.
21097 (if org-disable-agenda-to-diary (setq files nil))
21098 (while (setq file (pop files))
21099 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21100 (setq results (append results rtn)))
21101 (if results
21102 (concat (org-finalize-agenda-entries results) "\n"))))
21104 ;;; Agenda entry finders
21106 (defun org-agenda-get-day-entries (file date &rest args)
21107 "Does the work for `org-diary' and `org-agenda'.
21108 FILE is the path to a file to be checked for entries. DATE is date like
21109 the one returned by `calendar-current-date'. ARGS are symbols indicating
21110 which kind of entries should be extracted. For details about these, see
21111 the documentation of `org-diary'."
21112 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21113 (let* ((org-startup-folded nil)
21114 (org-startup-align-all-tables nil)
21115 (buffer (if (file-exists-p file)
21116 (org-get-agenda-file-buffer file)
21117 (error "No such file %s" file)))
21118 arg results rtn)
21119 (if (not buffer)
21120 ;; If file does not exist, make sure an error message ends up in diary
21121 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21122 (with-current-buffer buffer
21123 (unless (org-mode-p)
21124 (error "Agenda file %s is not in `org-mode'" file))
21125 (let ((case-fold-search nil))
21126 (save-excursion
21127 (save-restriction
21128 (if org-agenda-restrict
21129 (narrow-to-region org-agenda-restrict-begin
21130 org-agenda-restrict-end)
21131 (widen))
21132 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21133 (while (setq arg (pop args))
21134 (cond
21135 ((and (eq arg :todo)
21136 (equal date (calendar-current-date)))
21137 (setq rtn (org-agenda-get-todos))
21138 (setq results (append results rtn)))
21139 ((eq arg :timestamp)
21140 (setq rtn (org-agenda-get-blocks))
21141 (setq results (append results rtn))
21142 (setq rtn (org-agenda-get-timestamps))
21143 (setq results (append results rtn)))
21144 ((eq arg :sexp)
21145 (setq rtn (org-agenda-get-sexps))
21146 (setq results (append results rtn)))
21147 ((eq arg :scheduled)
21148 (setq rtn (org-agenda-get-scheduled))
21149 (setq results (append results rtn)))
21150 ((eq arg :closed)
21151 (setq rtn (org-agenda-get-closed))
21152 (setq results (append results rtn)))
21153 ((eq arg :deadline)
21154 (setq rtn (org-agenda-get-deadlines))
21155 (setq results (append results rtn))))))))
21156 results))))
21158 (defun org-entry-is-todo-p ()
21159 (member (org-get-todo-state) org-not-done-keywords))
21161 (defun org-entry-is-done-p ()
21162 (member (org-get-todo-state) org-done-keywords))
21164 (defun org-get-todo-state ()
21165 (save-excursion
21166 (org-back-to-heading t)
21167 (and (looking-at org-todo-line-regexp)
21168 (match-end 2)
21169 (match-string 2))))
21171 (defun org-at-date-range-p (&optional inactive-ok)
21172 "Is the cursor inside a date range?"
21173 (interactive)
21174 (save-excursion
21175 (catch 'exit
21176 (let ((pos (point)))
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 (skip-chars-backward "^<[\r\n")
21183 (skip-chars-backward "<[")
21184 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21185 (>= (match-end 0) pos)
21186 (throw 'exit t)))
21187 nil)))
21189 (defun org-agenda-get-todos ()
21190 "Return the TODO information for agenda display."
21191 (let* ((props (list 'face nil
21192 'done-face 'org-done
21193 'org-not-done-regexp org-not-done-regexp
21194 'org-todo-regexp org-todo-regexp
21195 'mouse-face 'highlight
21196 'keymap org-agenda-keymap
21197 'help-echo
21198 (format "mouse-2 or RET jump to org file %s"
21199 (abbreviate-file-name buffer-file-name))))
21200 ;; FIXME: get rid of the \n at some point but watch out
21201 (regexp (concat "^\\*+[ \t]+\\("
21202 (if org-select-this-todo-keyword
21203 (if (equal org-select-this-todo-keyword "*")
21204 org-todo-regexp
21205 (concat "\\<\\("
21206 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21207 "\\)\\>"))
21208 org-not-done-regexp)
21209 "[^\n\r]*\\)"))
21210 marker priority category tags
21211 ee txt beg end)
21212 (goto-char (point-min))
21213 (while (re-search-forward regexp nil t)
21214 (catch :skip
21215 (save-match-data
21216 (beginning-of-line)
21217 (setq beg (point) end (progn (outline-next-heading) (point)))
21218 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21219 (re-search-forward org-ts-regexp end t))
21220 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21221 (re-search-forward org-scheduled-time-regexp end t))
21222 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21223 (re-search-forward org-deadline-time-regexp end t)
21224 (org-deadline-close (match-string 1))))
21225 (goto-char (1+ beg))
21226 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21227 (throw :skip nil)))
21228 (goto-char beg)
21229 (org-agenda-skip)
21230 (goto-char (match-beginning 1))
21231 (setq marker (org-agenda-new-marker (match-beginning 0))
21232 category (org-get-category)
21233 tags (org-get-tags-at (point))
21234 txt (org-format-agenda-item "" (match-string 1) category tags)
21235 priority (1+ (org-get-priority txt)))
21236 (org-add-props txt props
21237 'org-marker marker 'org-hd-marker marker
21238 'priority priority 'org-category category
21239 'type "todo")
21240 (push txt ee)
21241 (if org-agenda-todo-list-sublevels
21242 (goto-char (match-end 1))
21243 (org-end-of-subtree 'invisible))))
21244 (nreverse ee)))
21246 (defconst org-agenda-no-heading-message
21247 "No heading for this item in buffer or region.")
21249 (defun org-agenda-get-timestamps ()
21250 "Return the date stamp information for agenda display."
21251 (let* ((props (list 'face nil
21252 'org-not-done-regexp org-not-done-regexp
21253 'org-todo-regexp org-todo-regexp
21254 'mouse-face 'highlight
21255 'keymap org-agenda-keymap
21256 'help-echo
21257 (format "mouse-2 or RET jump to org file %s"
21258 (abbreviate-file-name buffer-file-name))))
21259 (d1 (calendar-absolute-from-gregorian date))
21260 (remove-re
21261 (concat
21262 (regexp-quote
21263 (format-time-string
21264 "<%Y-%m-%d"
21265 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21266 ".*?>"))
21267 (regexp
21268 (concat
21269 (regexp-quote
21270 (substring
21271 (format-time-string
21272 (car org-time-stamp-formats)
21273 (apply 'encode-time ; DATE bound by calendar
21274 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21275 0 11))
21276 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21277 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21278 marker hdmarker deadlinep scheduledp donep tmp priority category
21279 ee txt timestr tags b0 b3 e3 head)
21280 (goto-char (point-min))
21281 (while (re-search-forward regexp nil t)
21282 (setq b0 (match-beginning 0)
21283 b3 (match-beginning 3) e3 (match-end 3))
21284 (catch :skip
21285 (and (org-at-date-range-p) (throw :skip nil))
21286 (org-agenda-skip)
21287 (if (and (match-end 1)
21288 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21289 (throw :skip nil))
21290 (if (and e3
21291 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21292 (throw :skip nil))
21293 (setq marker (org-agenda-new-marker b0)
21294 category (org-get-category b0)
21295 tmp (buffer-substring (max (point-min)
21296 (- b0 org-ds-keyword-length))
21298 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21299 deadlinep (string-match org-deadline-regexp tmp)
21300 scheduledp (string-match org-scheduled-regexp tmp)
21301 donep (org-entry-is-done-p))
21302 (if (or scheduledp deadlinep) (throw :skip t))
21303 (if (string-match ">" timestr)
21304 ;; substring should only run to end of time stamp
21305 (setq timestr (substring timestr 0 (match-end 0))))
21306 (save-excursion
21307 (if (re-search-backward "^\\*+ " nil t)
21308 (progn
21309 (goto-char (match-beginning 0))
21310 (setq hdmarker (org-agenda-new-marker)
21311 tags (org-get-tags-at))
21312 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21313 (setq head (match-string 1))
21314 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21315 (setq txt (org-format-agenda-item
21316 nil head category tags timestr nil
21317 remove-re)))
21318 (setq txt org-agenda-no-heading-message))
21319 (setq priority (org-get-priority txt))
21320 (org-add-props txt props
21321 'org-marker marker 'org-hd-marker hdmarker)
21322 (org-add-props txt nil 'priority priority
21323 'org-category category 'date date
21324 'type "timestamp")
21325 (push txt ee))
21326 (outline-next-heading)))
21327 (nreverse ee)))
21329 (defun org-agenda-get-sexps ()
21330 "Return the sexp information for agenda display."
21331 (require 'diary-lib)
21332 (let* ((props (list 'face nil
21333 'mouse-face 'highlight
21334 'keymap org-agenda-keymap
21335 'help-echo
21336 (format "mouse-2 or RET jump to org file %s"
21337 (abbreviate-file-name buffer-file-name))))
21338 (regexp "^&?%%(")
21339 marker category ee txt tags entry result beg b sexp sexp-entry)
21340 (goto-char (point-min))
21341 (while (re-search-forward regexp nil t)
21342 (catch :skip
21343 (org-agenda-skip)
21344 (setq beg (match-beginning 0))
21345 (goto-char (1- (match-end 0)))
21346 (setq b (point))
21347 (forward-sexp 1)
21348 (setq sexp (buffer-substring b (point)))
21349 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21350 (org-trim (match-string 1))
21351 ""))
21352 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21353 (when result
21354 (setq marker (org-agenda-new-marker beg)
21355 category (org-get-category beg))
21357 (if (string-match "\\S-" result)
21358 (setq txt result)
21359 (setq txt "SEXP entry returned empty string"))
21361 (setq txt (org-format-agenda-item
21362 "" txt category tags 'time))
21363 (org-add-props txt props 'org-marker marker)
21364 (org-add-props txt nil
21365 'org-category category 'date date
21366 'type "sexp")
21367 (push txt ee))))
21368 (nreverse ee)))
21370 (defun org-agenda-get-closed ()
21371 "Return the logged TODO entries for agenda display."
21372 (let* ((props (list 'mouse-face 'highlight
21373 'org-not-done-regexp org-not-done-regexp
21374 'org-todo-regexp org-todo-regexp
21375 'keymap org-agenda-keymap
21376 'help-echo
21377 (format "mouse-2 or RET jump to org file %s"
21378 (abbreviate-file-name buffer-file-name))))
21379 (regexp (concat
21380 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21381 (regexp-quote
21382 (substring
21383 (format-time-string
21384 (car org-time-stamp-formats)
21385 (apply 'encode-time ; DATE bound by calendar
21386 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21387 1 11))))
21388 marker hdmarker priority category tags closedp
21389 ee txt timestr)
21390 (goto-char (point-min))
21391 (while (re-search-forward regexp nil t)
21392 (catch :skip
21393 (org-agenda-skip)
21394 (setq marker (org-agenda-new-marker (match-beginning 0))
21395 closedp (equal (match-string 1) org-closed-string)
21396 category (org-get-category (match-beginning 0))
21397 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21398 ;; donep (org-entry-is-done-p)
21400 (if (string-match "\\]" timestr)
21401 ;; substring should only run to end of time stamp
21402 (setq timestr (substring timestr 0 (match-end 0))))
21403 (save-excursion
21404 (if (re-search-backward "^\\*+ " nil t)
21405 (progn
21406 (goto-char (match-beginning 0))
21407 (setq hdmarker (org-agenda-new-marker)
21408 tags (org-get-tags-at))
21409 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21410 (setq txt (org-format-agenda-item
21411 (if closedp "Closed: " "Clocked: ")
21412 (match-string 1) category tags timestr)))
21413 (setq txt org-agenda-no-heading-message))
21414 (setq priority 100000)
21415 (org-add-props txt props
21416 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21417 'priority priority 'org-category category
21418 'type "closed" 'date date
21419 'undone-face 'org-warning 'done-face 'org-done)
21420 (push txt ee))
21421 (goto-char (point-at-eol))))
21422 (nreverse ee)))
21424 (defun org-agenda-get-deadlines ()
21425 "Return the deadline information for agenda display."
21426 (let* ((props (list 'mouse-face 'highlight
21427 'org-not-done-regexp org-not-done-regexp
21428 'org-todo-regexp org-todo-regexp
21429 'keymap org-agenda-keymap
21430 'help-echo
21431 (format "mouse-2 or RET jump to org file %s"
21432 (abbreviate-file-name buffer-file-name))))
21433 (regexp org-deadline-time-regexp)
21434 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21435 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21436 d2 diff dfrac wdays pos pos1 category tags
21437 ee txt head face s upcomingp donep timestr)
21438 (goto-char (point-min))
21439 (while (re-search-forward regexp nil t)
21440 (catch :skip
21441 (org-agenda-skip)
21442 (setq s (match-string 1)
21443 pos (1- (match-beginning 1))
21444 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21445 diff (- d2 d1)
21446 wdays (org-get-wdays s)
21447 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21448 upcomingp (and todayp (> diff 0)))
21449 ;; When to show a deadline in the calendar:
21450 ;; If the expiration is within wdays warning time.
21451 ;; Past-due deadlines are only shown on the current date
21452 (if (or (and (<= diff wdays)
21453 (and todayp (not org-agenda-only-exact-dates)))
21454 (= diff 0))
21455 (save-excursion
21456 (setq category (org-get-category))
21457 (if (re-search-backward "^\\*+[ \t]+" nil t)
21458 (progn
21459 (goto-char (match-end 0))
21460 (setq pos1 (match-beginning 0))
21461 (setq tags (org-get-tags-at pos1))
21462 (setq head (buffer-substring-no-properties
21463 (point)
21464 (progn (skip-chars-forward "^\r\n")
21465 (point))))
21466 (setq donep (string-match org-looking-at-done-regexp head))
21467 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21468 (setq timestr
21469 (concat (substring s (match-beginning 1)) " "))
21470 (setq timestr 'time))
21471 (if (and donep
21472 (or org-agenda-skip-deadline-if-done
21473 (not (= diff 0))))
21474 (setq txt nil)
21475 (setq txt (org-format-agenda-item
21476 (if (= diff 0)
21477 (car org-agenda-deadline-leaders)
21478 (format (nth 1 org-agenda-deadline-leaders)
21479 diff))
21480 head category tags timestr))))
21481 (setq txt org-agenda-no-heading-message))
21482 (when txt
21483 (setq face (org-agenda-deadline-face dfrac))
21484 (org-add-props txt props
21485 'org-marker (org-agenda-new-marker pos)
21486 'org-hd-marker (org-agenda-new-marker pos1)
21487 'priority (+ (- diff)
21488 (org-get-priority txt))
21489 'org-category category
21490 'type (if upcomingp "upcoming-deadline" "deadline")
21491 'date (if upcomingp date d2)
21492 'face (if donep 'org-done face)
21493 'undone-face face 'done-face 'org-done)
21494 (push txt ee))))))
21495 (nreverse ee)))
21497 (defun org-agenda-deadline-face (fraction)
21498 "Return the face to displaying a deadline item.
21499 FRACTION is what fraction of the head-warning time has passed."
21500 (let ((faces org-agenda-deadline-faces) f)
21501 (catch 'exit
21502 (while (setq f (pop faces))
21503 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21505 (defun org-agenda-get-scheduled ()
21506 "Return the scheduled information for agenda display."
21507 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21508 'org-todo-regexp org-todo-regexp
21509 'done-face 'org-done
21510 'mouse-face 'highlight
21511 'keymap org-agenda-keymap
21512 'help-echo
21513 (format "mouse-2 or RET jump to org file %s"
21514 (abbreviate-file-name buffer-file-name))))
21515 (regexp org-scheduled-time-regexp)
21516 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21517 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21518 d2 diff pos pos1 category tags
21519 ee txt head pastschedp donep face timestr s)
21520 (goto-char (point-min))
21521 (while (re-search-forward regexp nil t)
21522 (catch :skip
21523 (org-agenda-skip)
21524 (setq s (match-string 1)
21525 pos (1- (match-beginning 1))
21526 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21527 ;;; is this right?
21528 ;;; do we need to do this for deadleine too????
21529 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21530 diff (- d2 d1))
21531 (setq pastschedp (and todayp (< diff 0)))
21532 ;; When to show a scheduled item in the calendar:
21533 ;; If it is on or past the date.
21534 (if (or (and (< diff 0)
21535 (and todayp (not org-agenda-only-exact-dates)))
21536 (= diff 0))
21537 (save-excursion
21538 (setq category (org-get-category))
21539 (if (re-search-backward "^\\*+[ \t]+" nil t)
21540 (progn
21541 (goto-char (match-end 0))
21542 (setq pos1 (match-beginning 0))
21543 (setq tags (org-get-tags-at))
21544 (setq head (buffer-substring-no-properties
21545 (point)
21546 (progn (skip-chars-forward "^\r\n") (point))))
21547 (setq donep (string-match org-looking-at-done-regexp head))
21548 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21549 (setq timestr
21550 (concat (substring s (match-beginning 1)) " "))
21551 (setq timestr 'time))
21552 (if (and donep
21553 (or org-agenda-skip-scheduled-if-done
21554 (not (= diff 0))))
21555 (setq txt nil)
21556 (setq txt (org-format-agenda-item
21557 (if (= diff 0)
21558 (car org-agenda-scheduled-leaders)
21559 (format (nth 1 org-agenda-scheduled-leaders)
21560 (- 1 diff)))
21561 head category tags timestr))))
21562 (setq txt org-agenda-no-heading-message))
21563 (when txt
21564 (setq face (if pastschedp
21565 'org-scheduled-previously
21566 'org-scheduled-today))
21567 (org-add-props txt props
21568 'undone-face face
21569 'face (if donep 'org-done face)
21570 'org-marker (org-agenda-new-marker pos)
21571 'org-hd-marker (org-agenda-new-marker pos1)
21572 'type (if pastschedp "past-scheduled" "scheduled")
21573 'date (if pastschedp d2 date)
21574 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21575 'org-category category)
21576 (push txt ee))))))
21577 (nreverse ee)))
21579 (defun org-agenda-get-blocks ()
21580 "Return the date-range information for agenda display."
21581 (let* ((props (list 'face nil
21582 'org-not-done-regexp org-not-done-regexp
21583 'org-todo-regexp org-todo-regexp
21584 'mouse-face 'highlight
21585 'keymap org-agenda-keymap
21586 'help-echo
21587 (format "mouse-2 or RET jump to org file %s"
21588 (abbreviate-file-name buffer-file-name))))
21589 (regexp org-tr-regexp)
21590 (d0 (calendar-absolute-from-gregorian date))
21591 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21592 donep head)
21593 (goto-char (point-min))
21594 (while (re-search-forward regexp nil t)
21595 (catch :skip
21596 (org-agenda-skip)
21597 (setq pos (point))
21598 (setq timestr (match-string 0)
21599 s1 (match-string 1)
21600 s2 (match-string 2)
21601 d1 (time-to-days (org-time-string-to-time s1))
21602 d2 (time-to-days (org-time-string-to-time s2)))
21603 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21604 ;; Only allow days between the limits, because the normal
21605 ;; date stamps will catch the limits.
21606 (save-excursion
21607 (setq marker (org-agenda-new-marker (point)))
21608 (setq category (org-get-category))
21609 (if (re-search-backward "^\\*+ " nil t)
21610 (progn
21611 (goto-char (match-beginning 0))
21612 (setq hdmarker (org-agenda-new-marker (point)))
21613 (setq tags (org-get-tags-at))
21614 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21615 (setq head (match-string 1))
21616 (and org-agenda-skip-timestamp-if-done
21617 (org-entry-is-done-p)
21618 (throw :skip t))
21619 (setq txt (org-format-agenda-item
21620 (format (if (= d1 d2) "" "(%d/%d): ")
21621 (1+ (- d0 d1)) (1+ (- d2 d1)))
21622 head category tags
21623 (if (= d0 d1) timestr))))
21624 (setq txt org-agenda-no-heading-message))
21625 (org-add-props txt props
21626 'org-marker marker 'org-hd-marker hdmarker
21627 'type "block" 'date date
21628 'priority (org-get-priority txt) 'org-category category)
21629 (push txt ee)))
21630 (goto-char pos)))
21631 ;; Sort the entries by expiration date.
21632 (nreverse ee)))
21634 ;;; Agenda presentation and sorting
21636 (defconst org-plain-time-of-day-regexp
21637 (concat
21638 "\\(\\<[012]?[0-9]"
21639 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21640 "\\(--?"
21641 "\\(\\<[012]?[0-9]"
21642 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21643 "\\)?")
21644 "Regular expression to match a plain time or time range.
21645 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21646 groups carry important information:
21647 0 the full match
21648 1 the first time, range or not
21649 8 the second time, if it is a range.")
21651 (defconst org-plain-time-extension-regexp
21652 (concat
21653 "\\(\\<[012]?[0-9]"
21654 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21655 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21656 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21657 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21658 groups carry important information:
21659 0 the full match
21660 7 hours of duration
21661 9 minutes of duration")
21663 (defconst org-stamp-time-of-day-regexp
21664 (concat
21665 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21666 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21667 "\\(--?"
21668 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21669 "Regular expression to match a timestamp time or time range.
21670 After a match, the following groups carry important information:
21671 0 the full match
21672 1 date plus weekday, for backreferencing to make sure both times on same day
21673 2 the first time, range or not
21674 4 the second time, if it is a range.")
21676 (defvar org-prefix-has-time nil
21677 "A flag, set by `org-compile-prefix-format'.
21678 The flag is set if the currently compiled format contains a `%t'.")
21679 (defvar org-prefix-has-tag nil
21680 "A flag, set by `org-compile-prefix-format'.
21681 The flag is set if the currently compiled format contains a `%T'.")
21683 (defun org-format-agenda-item (extra txt &optional category tags dotime
21684 noprefix remove-re)
21685 "Format TXT to be inserted into the agenda buffer.
21686 In particular, it adds the prefix and corresponding text properties. EXTRA
21687 must be a string and replaces the `%s' specifier in the prefix format.
21688 CATEGORY (string, symbol or nil) may be used to overrule the default
21689 category taken from local variable or file name. It will replace the `%c'
21690 specifier in the format. DOTIME, when non-nil, indicates that a
21691 time-of-day should be extracted from TXT for sorting of this entry, and for
21692 the `%t' specifier in the format. When DOTIME is a string, this string is
21693 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21694 only the correctly processes TXT should be returned - this is used by
21695 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21696 Any match of REMOVE-RE will be removed from TXT."
21697 (save-match-data
21698 ;; Diary entries sometimes have extra whitespace at the beginning
21699 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21700 (let* ((category (or category
21701 org-category
21702 (if buffer-file-name
21703 (file-name-sans-extension
21704 (file-name-nondirectory buffer-file-name))
21705 "")))
21706 (tag (if tags (nth (1- (length tags)) tags) ""))
21707 time ; time and tag are needed for the eval of the prefix format
21708 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21709 (time-of-day (and dotime (org-get-time-of-day ts)))
21710 stamp plain s0 s1 s2 rtn srp)
21711 (when (and dotime time-of-day org-prefix-has-time)
21712 ;; Extract starting and ending time and move them to prefix
21713 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21714 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21715 (setq s0 (match-string 0 ts)
21716 srp (and stamp (match-end 3))
21717 s1 (match-string (if plain 1 2) ts)
21718 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21720 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21721 ;; them, we might want to remove them there to avoid duplication.
21722 ;; The user can turn this off with a variable.
21723 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21724 (string-match (concat (regexp-quote s0) " *") txt)
21725 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21726 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21727 (= (match-beginning 0) 0)
21729 (setq txt (replace-match "" nil nil txt))))
21730 ;; Normalize the time(s) to 24 hour
21731 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21732 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21734 (when (and s1 (not s2) org-agenda-default-appointment-duration
21735 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21736 (let ((m (+ (string-to-number (match-string 2 s1))
21737 (* 60 (string-to-number (match-string 1 s1)))
21738 org-agenda-default-appointment-duration))
21740 (setq h (/ m 60) m (- m (* h 60)))
21741 (setq s2 (format "%02d:%02d" h m))))
21743 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21744 txt)
21745 ;; Tags are in the string
21746 (if (or (eq org-agenda-remove-tags t)
21747 (and org-agenda-remove-tags
21748 org-prefix-has-tag))
21749 (setq txt (replace-match "" t t txt))
21750 (setq txt (replace-match
21751 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21752 (match-string 2 txt))
21753 t t txt))))
21755 (when remove-re
21756 (while (string-match remove-re txt)
21757 (setq txt (replace-match "" t t txt))))
21759 ;; Create the final string
21760 (if noprefix
21761 (setq rtn txt)
21762 ;; Prepare the variables needed in the eval of the compiled format
21763 (setq time (cond (s2 (concat s1 "-" s2))
21764 (s1 (concat s1 "......"))
21765 (t ""))
21766 extra (or extra "")
21767 category (if (symbolp category) (symbol-name category) category))
21768 ;; Evaluate the compiled format
21769 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21771 ;; And finally add the text properties
21772 (org-add-props rtn nil
21773 'org-category (downcase category) 'tags tags
21774 'org-highest-priority org-highest-priority
21775 'org-lowest-priority org-lowest-priority
21776 'prefix-length (- (length rtn) (length txt))
21777 'time-of-day time-of-day
21778 'txt txt
21779 'time time
21780 'extra extra
21781 'dotime dotime))))
21783 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21784 (defvar org-agenda-sorting-strategy-selected nil)
21786 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21787 (catch 'exit
21788 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21789 ((and todayp (member 'today (car org-agenda-time-grid))))
21790 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21791 ((member 'weekly (car org-agenda-time-grid)))
21792 (t (throw 'exit list)))
21793 (let* ((have (delq nil (mapcar
21794 (lambda (x) (get-text-property 1 'time-of-day x))
21795 list)))
21796 (string (nth 1 org-agenda-time-grid))
21797 (gridtimes (nth 2 org-agenda-time-grid))
21798 (req (car org-agenda-time-grid))
21799 (remove (member 'remove-match req))
21800 new time)
21801 (if (and (member 'require-timed req) (not have))
21802 ;; don't show empty grid
21803 (throw 'exit list))
21804 (while (setq time (pop gridtimes))
21805 (unless (and remove (member time have))
21806 (setq time (int-to-string time))
21807 (push (org-format-agenda-item
21808 nil string "" nil
21809 (concat (substring time 0 -2) ":" (substring time -2)))
21810 new)
21811 (put-text-property
21812 1 (length (car new)) 'face 'org-time-grid (car new))))
21813 (if (member 'time-up org-agenda-sorting-strategy-selected)
21814 (append new list)
21815 (append list new)))))
21817 (defun org-compile-prefix-format (key)
21818 "Compile the prefix format into a Lisp form that can be evaluated.
21819 The resulting form is returned and stored in the variable
21820 `org-prefix-format-compiled'."
21821 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21822 (let ((s (cond
21823 ((stringp org-agenda-prefix-format)
21824 org-agenda-prefix-format)
21825 ((assq key org-agenda-prefix-format)
21826 (cdr (assq key org-agenda-prefix-format)))
21827 (t " %-12:c%?-12t% s")))
21828 (start 0)
21829 varform vars var e c f opt)
21830 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21831 s start)
21832 (setq var (cdr (assoc (match-string 4 s)
21833 '(("c" . category) ("t" . time) ("s" . extra)
21834 ("T" . tag))))
21835 c (or (match-string 3 s) "")
21836 opt (match-beginning 1)
21837 start (1+ (match-beginning 0)))
21838 (if (equal var 'time) (setq org-prefix-has-time t))
21839 (if (equal var 'tag) (setq org-prefix-has-tag t))
21840 (setq f (concat "%" (match-string 2 s) "s"))
21841 (if opt
21842 (setq varform
21843 `(if (equal "" ,var)
21845 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21846 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21847 (setq s (replace-match "%s" t nil s))
21848 (push varform vars))
21849 (setq vars (nreverse vars))
21850 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21852 (defun org-set-sorting-strategy (key)
21853 (if (symbolp (car org-agenda-sorting-strategy))
21854 ;; the old format
21855 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21856 (setq org-agenda-sorting-strategy-selected
21857 (or (cdr (assq key org-agenda-sorting-strategy))
21858 (cdr (assq 'agenda org-agenda-sorting-strategy))
21859 '(time-up category-keep priority-down)))))
21861 (defun org-get-time-of-day (s &optional string mod24)
21862 "Check string S for a time of day.
21863 If found, return it as a military time number between 0 and 2400.
21864 If not found, return nil.
21865 The optional STRING argument forces conversion into a 5 character wide string
21866 HH:MM."
21867 (save-match-data
21868 (when
21869 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21870 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21871 (let* ((h (string-to-number (match-string 1 s)))
21872 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21873 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21874 (am-p (equal ampm "am"))
21875 (h1 (cond ((not ampm) h)
21876 ((= h 12) (if am-p 0 12))
21877 (t (+ h (if am-p 0 12)))))
21878 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21879 (mod h1 24) h1))
21880 (t0 (+ (* 100 h2) m))
21881 (t1 (concat (if (>= h1 24) "+" " ")
21882 (if (< t0 100) "0" "")
21883 (if (< t0 10) "0" "")
21884 (int-to-string t0))))
21885 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21887 (defun org-finalize-agenda-entries (list &optional nosort)
21888 "Sort and concatenate the agenda items."
21889 (setq list (mapcar 'org-agenda-highlight-todo list))
21890 (if nosort
21891 list
21892 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21894 (defun org-agenda-highlight-todo (x)
21895 (let (re pl)
21896 (if (eq x 'line)
21897 (save-excursion
21898 (beginning-of-line 1)
21899 (setq re (get-text-property (point) 'org-todo-regexp))
21900 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21901 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21902 (add-text-properties (match-beginning 0) (match-end 0)
21903 (list 'face (org-get-todo-face 0)))
21904 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21905 (delete-region (match-beginning 1) (1- (match-end 0)))
21906 (goto-char (match-beginning 1))
21907 (insert (format org-agenda-todo-keyword-format s)))))
21908 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21909 pl (get-text-property 0 'prefix-length x))
21910 ; (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
21911 ; (add-text-properties
21912 ; (or (match-end 1) (match-end 0)) (match-end 0)
21913 ; (list 'face (org-get-todo-face (match-string 2 x)))
21914 ; x))
21915 (when (and re
21916 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21917 x (or pl 0)) pl))
21918 (add-text-properties
21919 (or (match-end 1) (match-end 0)) (match-end 0)
21920 (list 'face (org-get-todo-face (match-string 2 x)))
21922 (setq x (concat (substring x 0 (match-end 1))
21923 (format org-agenda-todo-keyword-format
21924 (match-string 2 x))
21926 (substring x (match-end 3)))))
21927 x)))
21929 (defsubst org-cmp-priority (a b)
21930 "Compare the priorities of string A and B."
21931 (let ((pa (or (get-text-property 1 'priority a) 0))
21932 (pb (or (get-text-property 1 'priority b) 0)))
21933 (cond ((> pa pb) +1)
21934 ((< pa pb) -1)
21935 (t nil))))
21937 (defsubst org-cmp-category (a b)
21938 "Compare the string values of categories of strings A and B."
21939 (let ((ca (or (get-text-property 1 'org-category a) ""))
21940 (cb (or (get-text-property 1 'org-category b) "")))
21941 (cond ((string-lessp ca cb) -1)
21942 ((string-lessp cb ca) +1)
21943 (t nil))))
21945 (defsubst org-cmp-tag (a b)
21946 "Compare the string values of categories of strings A and B."
21947 (let ((ta (car (last (get-text-property 1 'tags a))))
21948 (tb (car (last (get-text-property 1 'tags b)))))
21949 (cond ((not ta) +1)
21950 ((not tb) -1)
21951 ((string-lessp ta tb) -1)
21952 ((string-lessp tb ta) +1)
21953 (t nil))))
21955 (defsubst org-cmp-time (a b)
21956 "Compare the time-of-day values of strings A and B."
21957 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21958 (ta (or (get-text-property 1 'time-of-day a) def))
21959 (tb (or (get-text-property 1 'time-of-day b) def)))
21960 (cond ((< ta tb) -1)
21961 ((< tb ta) +1)
21962 (t nil))))
21964 (defun org-entries-lessp (a b)
21965 "Predicate for sorting agenda entries."
21966 ;; The following variables will be used when the form is evaluated.
21967 ;; So even though the compiler complains, keep them.
21968 (let* ((time-up (org-cmp-time a b))
21969 (time-down (if time-up (- time-up) nil))
21970 (priority-up (org-cmp-priority a b))
21971 (priority-down (if priority-up (- priority-up) nil))
21972 (category-up (org-cmp-category a b))
21973 (category-down (if category-up (- category-up) nil))
21974 (category-keep (if category-up +1 nil))
21975 (tag-up (org-cmp-tag a b))
21976 (tag-down (if tag-up (- tag-up) nil)))
21977 (cdr (assoc
21978 (eval (cons 'or org-agenda-sorting-strategy-selected))
21979 '((-1 . t) (1 . nil) (nil . nil))))))
21981 ;;; Agenda restriction lock
21983 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
21984 "Overlay to mark the headline to which arenda commands are restricted.")
21985 (org-overlay-put org-agenda-restriction-lock-overlay
21986 'face 'org-agenda-restriction-lock)
21987 (org-overlay-put org-agenda-restriction-lock-overlay
21988 'help-echo "Agendas are currently limited to this subtree.")
21989 (org-detach-overlay org-agenda-restriction-lock-overlay)
21990 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
21991 "Overlay marking the agenda restriction line in speedbar.")
21992 (org-overlay-put org-speedbar-restriction-lock-overlay
21993 'face 'org-agenda-restriction-lock)
21994 (org-overlay-put org-speedbar-restriction-lock-overlay
21995 'help-echo "Agendas are currently limited to this item.")
21996 (org-detach-overlay org-speedbar-restriction-lock-overlay)
21998 (defun org-agenda-set-restriction-lock (&optional type)
21999 "Set restriction lock for agenda, to current subtree or file.
22000 Restriction will be the file if TYPE is `file', or if type is the
22001 universal prefix '(4), or if the cursor is before the first headline
22002 in the file. Otherwise, restriction will be to the current subtree."
22003 (interactive "P")
22004 (and (equal type '(4)) (setq type 'file))
22005 (setq type (cond
22006 (type type)
22007 ((org-at-heading-p) 'subtree)
22008 ((condition-case nil (org-back-to-heading t) (error nil))
22009 'subtree)
22010 (t 'file)))
22011 (if (eq type 'subtree)
22012 (progn
22013 (setq org-agenda-restrict t)
22014 (setq org-agenda-overriding-restriction 'subtree)
22015 (put 'org-agenda-files 'org-restrict
22016 (list (buffer-file-name (buffer-base-buffer))))
22017 (org-back-to-heading t)
22018 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22019 (move-marker org-agenda-restrict-begin (point))
22020 (move-marker org-agenda-restrict-end
22021 (save-excursion (org-end-of-subtree t)))
22022 (message "Locking agenda restriction to subtree"))
22023 (put 'org-agenda-files 'org-restrict
22024 (list (buffer-file-name (buffer-base-buffer))))
22025 (setq org-agenda-restrict nil)
22026 (setq org-agenda-overriding-restriction 'file)
22027 (move-marker org-agenda-restrict-begin nil)
22028 (move-marker org-agenda-restrict-end nil)
22029 (message "Locking agenda restriction to file"))
22030 (setq current-prefix-arg nil)
22031 (org-agenda-maybe-redo))
22033 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22034 "Remove the agenda restriction lock."
22035 (interactive "P")
22036 (org-detach-overlay org-agenda-restriction-lock-overlay)
22037 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22038 (setq org-agenda-overriding-restriction nil)
22039 (setq org-agenda-restrict nil)
22040 (put 'org-agenda-files 'org-restrict nil)
22041 (move-marker org-agenda-restrict-begin nil)
22042 (move-marker org-agenda-restrict-end nil)
22043 (setq current-prefix-arg nil)
22044 (message "Agenda restriction lock removed")
22045 (or noupdate (org-agenda-maybe-redo)))
22047 (defun org-agenda-maybe-redo ()
22048 "If there is any window showing the agenda view, update it."
22049 (let ((w (get-buffer-window org-agenda-buffer-name t))
22050 (w0 (selected-window)))
22051 (when w
22052 (select-window w)
22053 (org-agenda-redo)
22054 (select-window w0)
22055 (if org-agenda-overriding-restriction
22056 (message "Agenda view shifted to new %s restriction"
22057 org-agenda-overriding-restriction)
22058 (message "Agenda restriction lock removed")))))
22060 ;;; Agenda commands
22062 (defun org-agenda-check-type (error &rest types)
22063 "Check if agenda buffer is of allowed type.
22064 If ERROR is non-nil, throw an error, otherwise just return nil."
22065 (if (memq org-agenda-type types)
22067 (if error
22068 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22069 nil)))
22071 (defun org-agenda-quit ()
22072 "Exit agenda by removing the window or the buffer."
22073 (interactive)
22074 (let ((buf (current-buffer)))
22075 (if (not (one-window-p)) (delete-window))
22076 (kill-buffer buf)
22077 (org-agenda-maybe-reset-markers 'force)
22078 (org-columns-remove-overlays))
22079 ;; Maybe restore the pre-agenda window configuration.
22080 (and org-agenda-restore-windows-after-quit
22081 (not (eq org-agenda-window-setup 'other-frame))
22082 org-pre-agenda-window-conf
22083 (set-window-configuration org-pre-agenda-window-conf)))
22085 (defun org-agenda-exit ()
22086 "Exit agenda by removing the window or the buffer.
22087 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22088 Org-mode buffers visited directly by the user will not be touched."
22089 (interactive)
22090 (org-release-buffers org-agenda-new-buffers)
22091 (setq org-agenda-new-buffers nil)
22092 (org-agenda-quit))
22094 (defun org-agenda-execute (arg)
22095 "Execute another agenda command, keeping same window.\\<global-map>
22096 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22097 (interactive "P")
22098 (let ((org-agenda-window-setup 'current-window))
22099 (org-agenda arg)))
22101 (defun org-save-all-org-buffers ()
22102 "Save all Org-mode buffers without user confirmation."
22103 (interactive)
22104 (message "Saving all Org-mode buffers...")
22105 (save-some-buffers t 'org-mode-p)
22106 (message "Saving all Org-mode buffers... done"))
22108 (defun org-agenda-redo ()
22109 "Rebuild Agenda.
22110 When this is the global TODO list, a prefix argument will be interpreted."
22111 (interactive)
22112 (let* ((org-agenda-keep-modes t)
22113 (line (org-current-line))
22114 (window-line (- line (org-current-line (window-start))))
22115 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22116 (message "Rebuilding agenda buffer...")
22117 (org-let lprops '(eval org-agenda-redo-command))
22118 (setq org-agenda-undo-list nil
22119 org-agenda-pending-undo-list nil)
22120 (message "Rebuilding agenda buffer...done")
22121 (goto-line line)
22122 (recenter window-line)))
22124 (defun org-agenda-goto-date (date)
22125 "Jump to DATE in agenda."
22126 (interactive (list (org-read-date)))
22127 (org-agenda-list nil date))
22129 (defun org-agenda-goto-today ()
22130 "Go to today."
22131 (interactive)
22132 (org-agenda-check-type t 'timeline 'agenda)
22133 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22134 (cond
22135 (tdpos (goto-char tdpos))
22136 ((eq org-agenda-type 'agenda)
22137 (let* ((sd (time-to-days
22138 (time-subtract (current-time)
22139 (list 0 (* 3600 org-extend-today-until) 0))))
22140 (comp (org-agenda-compute-time-span sd org-agenda-span))
22141 (org-agenda-overriding-arguments org-agenda-last-arguments))
22142 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22143 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22144 (org-agenda-redo)
22145 (org-agenda-find-same-or-today-or-agenda)))
22146 (t (error "Cannot find today")))))
22148 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22149 (goto-char
22150 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22151 (text-property-any (point-min) (point-max) 'org-today t)
22152 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22153 (point-min))))
22155 (defun org-agenda-later (arg)
22156 "Go forward in time by thee current span.
22157 With prefix ARG, go forward that many times the current span."
22158 (interactive "p")
22159 (org-agenda-check-type t 'agenda)
22160 (let* ((span org-agenda-span)
22161 (sd org-starting-day)
22162 (greg (calendar-gregorian-from-absolute sd))
22163 (cnt (get-text-property (point) 'org-day-cnt))
22164 greg2 nd)
22165 (cond
22166 ((eq span 'day)
22167 (setq sd (+ arg sd) nd 1))
22168 ((eq span 'week)
22169 (setq sd (+ (* 7 arg) sd) nd 7))
22170 ((eq span 'month)
22171 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22172 sd (calendar-absolute-from-gregorian greg2))
22173 (setcar greg2 (1+ (car greg2)))
22174 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22175 ((eq span 'year)
22176 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22177 sd (calendar-absolute-from-gregorian greg2))
22178 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22179 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22180 (let ((org-agenda-overriding-arguments
22181 (list (car org-agenda-last-arguments) sd nd t)))
22182 (org-agenda-redo)
22183 (org-agenda-find-same-or-today-or-agenda cnt))))
22185 (defun org-agenda-earlier (arg)
22186 "Go backward in time by the current span.
22187 With prefix ARG, go backward that many times the current span."
22188 (interactive "p")
22189 (org-agenda-later (- arg)))
22191 (defun org-agenda-day-view ()
22192 "Switch to daily view for agenda."
22193 (interactive)
22194 (setq org-agenda-ndays 1)
22195 (org-agenda-change-time-span 'day))
22196 (defun org-agenda-week-view ()
22197 "Switch to daily view for agenda."
22198 (interactive)
22199 (setq org-agenda-ndays 7)
22200 (org-agenda-change-time-span 'week))
22201 (defun org-agenda-month-view ()
22202 "Switch to daily view for agenda."
22203 (interactive)
22204 (org-agenda-change-time-span 'month))
22205 (defun org-agenda-year-view ()
22206 "Switch to daily view for agenda."
22207 (interactive)
22208 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22209 (org-agenda-change-time-span 'year)
22210 (error "Abort")))
22212 (defun org-agenda-change-time-span (span)
22213 "Change the agenda view to SPAN.
22214 SPAN may be `day', `week', `month', `year'."
22215 (org-agenda-check-type t 'agenda)
22216 (if (equal org-agenda-span span)
22217 (error "Viewing span is already \"%s\"" span))
22218 (let* ((sd (or (get-text-property (point) 'day)
22219 org-starting-day))
22220 (computed (org-agenda-compute-time-span sd span))
22221 (org-agenda-overriding-arguments
22222 (list (car org-agenda-last-arguments)
22223 (car computed) (cdr computed) t)))
22224 (org-agenda-redo)
22225 (org-agenda-find-same-or-today-or-agenda))
22226 (org-agenda-set-mode-name)
22227 (message "Switched to %s view" span))
22229 (defun org-agenda-compute-time-span (sd span)
22230 "Compute starting date and number of days for agenda.
22231 SPAN may be `day', `week', `month', `year'. The return value
22232 is a cons cell with the starting date and the number of days,
22233 so that the date SD will be in that range."
22234 (let* ((greg (calendar-gregorian-from-absolute sd))
22236 (cond
22237 ((eq span 'day)
22238 (setq nd 1))
22239 ((eq span 'week)
22240 (let* ((nt (calendar-day-of-week
22241 (calendar-gregorian-from-absolute sd)))
22242 (d (if org-agenda-start-on-weekday
22243 (- nt org-agenda-start-on-weekday)
22244 0)))
22245 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22246 (setq nd 7)))
22247 ((eq span 'month)
22248 (setq sd (calendar-absolute-from-gregorian
22249 (list (car greg) 1 (nth 2 greg)))
22250 nd (- (calendar-absolute-from-gregorian
22251 (list (1+ (car greg)) 1 (nth 2 greg)))
22252 sd)))
22253 ((eq span 'year)
22254 (setq sd (calendar-absolute-from-gregorian
22255 (list 1 1 (nth 2 greg)))
22256 nd (- (calendar-absolute-from-gregorian
22257 (list 1 1 (1+ (nth 2 greg))))
22258 sd))))
22259 (cons sd nd)))
22261 ;; FIXME: does not work if user makes date format that starts with a blank
22262 (defun org-agenda-next-date-line (&optional arg)
22263 "Jump to the next line indicating a date in agenda buffer."
22264 (interactive "p")
22265 (org-agenda-check-type t 'agenda 'timeline)
22266 (beginning-of-line 1)
22267 (if (looking-at "^\\S-") (forward-char 1))
22268 (if (not (re-search-forward "^\\S-" nil t arg))
22269 (progn
22270 (backward-char 1)
22271 (error "No next date after this line in this buffer")))
22272 (goto-char (match-beginning 0)))
22274 (defun org-agenda-previous-date-line (&optional arg)
22275 "Jump to the previous line indicating a date in agenda buffer."
22276 (interactive "p")
22277 (org-agenda-check-type t 'agenda 'timeline)
22278 (beginning-of-line 1)
22279 (if (not (re-search-backward "^\\S-" nil t arg))
22280 (error "No previous date before this line in this buffer")))
22282 ;; Initialize the highlight
22283 (defvar org-hl (org-make-overlay 1 1))
22284 (org-overlay-put org-hl 'face 'highlight)
22286 (defun org-highlight (begin end &optional buffer)
22287 "Highlight a region with overlay."
22288 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22289 org-hl begin end (or buffer (current-buffer))))
22291 (defun org-unhighlight ()
22292 "Detach overlay INDEX."
22293 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22295 ;; FIXME this is currently not used.
22296 (defun org-highlight-until-next-command (beg end &optional buffer)
22297 (org-highlight beg end buffer)
22298 (add-hook 'pre-command-hook 'org-unhighlight-once))
22299 (defun org-unhighlight-once ()
22300 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22301 (org-unhighlight))
22303 (defun org-agenda-follow-mode ()
22304 "Toggle follow mode in an agenda buffer."
22305 (interactive)
22306 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22307 (org-agenda-set-mode-name)
22308 (message "Follow mode is %s"
22309 (if org-agenda-follow-mode "on" "off")))
22311 (defun org-agenda-log-mode ()
22312 "Toggle log mode in an agenda buffer."
22313 (interactive)
22314 (org-agenda-check-type t 'agenda 'timeline)
22315 (setq org-agenda-show-log (not org-agenda-show-log))
22316 (org-agenda-set-mode-name)
22317 (org-agenda-redo)
22318 (message "Log mode is %s"
22319 (if org-agenda-show-log "on" "off")))
22321 (defun org-agenda-toggle-diary ()
22322 "Toggle diary inclusion in an agenda buffer."
22323 (interactive)
22324 (org-agenda-check-type t 'agenda)
22325 (setq org-agenda-include-diary (not org-agenda-include-diary))
22326 (org-agenda-redo)
22327 (org-agenda-set-mode-name)
22328 (message "Diary inclusion turned %s"
22329 (if org-agenda-include-diary "on" "off")))
22331 (defun org-agenda-toggle-time-grid ()
22332 "Toggle time grid in an agenda buffer."
22333 (interactive)
22334 (org-agenda-check-type t 'agenda)
22335 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22336 (org-agenda-redo)
22337 (org-agenda-set-mode-name)
22338 (message "Time-grid turned %s"
22339 (if org-agenda-use-time-grid "on" "off")))
22341 (defun org-agenda-set-mode-name ()
22342 "Set the mode name to indicate all the small mode settings."
22343 (setq mode-name
22344 (concat "Org-Agenda"
22345 (if (equal org-agenda-ndays 1) " Day" "")
22346 (if (equal org-agenda-ndays 7) " Week" "")
22347 (if org-agenda-follow-mode " Follow" "")
22348 (if org-agenda-include-diary " Diary" "")
22349 (if org-agenda-use-time-grid " Grid" "")
22350 (if org-agenda-show-log " Log" "")))
22351 (force-mode-line-update))
22353 (defun org-agenda-post-command-hook ()
22354 (and (eolp) (not (bolp)) (backward-char 1))
22355 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22356 (if (and org-agenda-follow-mode
22357 (get-text-property (point) 'org-marker))
22358 (org-agenda-show)))
22360 (defun org-agenda-show-priority ()
22361 "Show the priority of the current item.
22362 This priority is composed of the main priority given with the [#A] cookies,
22363 and by additional input from the age of a schedules or deadline entry."
22364 (interactive)
22365 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22366 (message "Priority is %d" (if pri pri -1000))))
22368 (defun org-agenda-show-tags ()
22369 "Show the tags applicable to the current item."
22370 (interactive)
22371 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22372 (if tags
22373 (message "Tags are :%s:"
22374 (org-no-properties (mapconcat 'identity tags ":")))
22375 (message "No tags associated with this line"))))
22377 (defun org-agenda-goto (&optional highlight)
22378 "Go to the Org-mode file which contains the item at point."
22379 (interactive)
22380 (let* ((marker (or (get-text-property (point) 'org-marker)
22381 (org-agenda-error)))
22382 (buffer (marker-buffer marker))
22383 (pos (marker-position marker)))
22384 (switch-to-buffer-other-window buffer)
22385 (widen)
22386 (goto-char pos)
22387 (when (org-mode-p)
22388 (org-show-context 'agenda)
22389 (save-excursion
22390 (and (outline-next-heading)
22391 (org-flag-heading nil)))) ; show the next heading
22392 (recenter (/ (window-height) 2))
22393 (run-hooks 'org-agenda-after-show-hook)
22394 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22396 (defvar org-agenda-after-show-hook nil
22397 "Normal hook run after an item has been shown from the agenda.
22398 Point is in the buffer where the item originated.")
22400 (defun org-agenda-kill ()
22401 "Kill the entry or subtree belonging to the current agenda entry."
22402 (interactive)
22403 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22404 (let* ((marker (or (get-text-property (point) 'org-marker)
22405 (org-agenda-error)))
22406 (buffer (marker-buffer marker))
22407 (pos (marker-position marker))
22408 (type (get-text-property (point) 'type))
22409 dbeg dend (n 0) conf)
22410 (org-with-remote-undo buffer
22411 (with-current-buffer buffer
22412 (save-excursion
22413 (goto-char pos)
22414 (if (and (org-mode-p) (not (member type '("sexp"))))
22415 (setq dbeg (progn (org-back-to-heading t) (point))
22416 dend (org-end-of-subtree t t))
22417 (setq dbeg (point-at-bol)
22418 dend (min (point-max) (1+ (point-at-eol)))))
22419 (goto-char dbeg)
22420 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22421 (setq conf (or (eq t org-agenda-confirm-kill)
22422 (and (numberp org-agenda-confirm-kill)
22423 (> n org-agenda-confirm-kill))))
22424 (and conf
22425 (not (y-or-n-p
22426 (format "Delete entry with %d lines in buffer \"%s\"? "
22427 n (buffer-name buffer))))
22428 (error "Abort"))
22429 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22430 (with-current-buffer buffer (delete-region dbeg dend))
22431 (message "Agenda item and source killed"))))
22433 (defun org-agenda-archive ()
22434 "Kill the entry or subtree belonging to the current agenda entry."
22435 (interactive)
22436 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22437 (let* ((marker (or (get-text-property (point) 'org-marker)
22438 (org-agenda-error)))
22439 (buffer (marker-buffer marker))
22440 (pos (marker-position marker)))
22441 (org-with-remote-undo buffer
22442 (with-current-buffer buffer
22443 (if (org-mode-p)
22444 (save-excursion
22445 (goto-char pos)
22446 (org-remove-subtree-entries-from-agenda)
22447 (org-back-to-heading t)
22448 (org-archive-subtree))
22449 (error "Archiving works only in Org-mode files"))))))
22451 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22452 "Remove all lines in the agenda that correspond to a given subtree.
22453 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22454 If this information is not given, the function uses the tree at point."
22455 (let ((buf (or buf (current-buffer))) m p)
22456 (save-excursion
22457 (unless (and beg end)
22458 (org-back-to-heading t)
22459 (setq beg (point))
22460 (org-end-of-subtree t)
22461 (setq end (point)))
22462 (set-buffer (get-buffer org-agenda-buffer-name))
22463 (save-excursion
22464 (goto-char (point-max))
22465 (beginning-of-line 1)
22466 (while (not (bobp))
22467 (when (and (setq m (get-text-property (point) 'org-marker))
22468 (equal buf (marker-buffer m))
22469 (setq p (marker-position m))
22470 (>= p beg)
22471 (<= p end))
22472 (let ((inhibit-read-only t))
22473 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22474 (beginning-of-line 0))))))
22476 (defun org-agenda-open-link ()
22477 "Follow the link in the current line, if any."
22478 (interactive)
22479 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22480 (save-excursion
22481 (save-restriction
22482 (narrow-to-region (point-at-bol) (point-at-eol))
22483 (org-open-at-point))))
22485 (defun org-agenda-copy-local-variable (var)
22486 "Get a variable from a referenced buffer and install it here."
22487 (let ((m (get-text-property (point) 'org-marker)))
22488 (when (and m (buffer-live-p (marker-buffer m)))
22489 (org-set-local var (with-current-buffer (marker-buffer m)
22490 (symbol-value var))))))
22492 (defun org-agenda-switch-to (&optional delete-other-windows)
22493 "Go to the Org-mode file which contains the item at point."
22494 (interactive)
22495 (let* ((marker (or (get-text-property (point) 'org-marker)
22496 (org-agenda-error)))
22497 (buffer (marker-buffer marker))
22498 (pos (marker-position marker)))
22499 (switch-to-buffer buffer)
22500 (and delete-other-windows (delete-other-windows))
22501 (widen)
22502 (goto-char pos)
22503 (when (org-mode-p)
22504 (org-show-context 'agenda)
22505 (save-excursion
22506 (and (outline-next-heading)
22507 (org-flag-heading nil)))))) ; show the next heading
22509 (defun org-agenda-goto-mouse (ev)
22510 "Go to the Org-mode file which contains the item at the mouse click."
22511 (interactive "e")
22512 (mouse-set-point ev)
22513 (org-agenda-goto))
22515 (defun org-agenda-show ()
22516 "Display the Org-mode file which contains the item at point."
22517 (interactive)
22518 (let ((win (selected-window)))
22519 (org-agenda-goto t)
22520 (select-window win)))
22522 (defun org-agenda-recenter (arg)
22523 "Display the Org-mode file which contains the item at point and recenter."
22524 (interactive "P")
22525 (let ((win (selected-window)))
22526 (org-agenda-goto t)
22527 (recenter arg)
22528 (select-window win)))
22530 (defun org-agenda-show-mouse (ev)
22531 "Display the Org-mode file which contains the item at the mouse click."
22532 (interactive "e")
22533 (mouse-set-point ev)
22534 (org-agenda-show))
22536 (defun org-agenda-check-no-diary ()
22537 "Check if the entry is a diary link and abort if yes."
22538 (if (get-text-property (point) 'org-agenda-diary-link)
22539 (org-agenda-error)))
22541 (defun org-agenda-error ()
22542 (error "Command not allowed in this line"))
22544 (defun org-agenda-tree-to-indirect-buffer ()
22545 "Show the subtree corresponding to the current entry in an indirect buffer.
22546 This calls the command `org-tree-to-indirect-buffer' from the original
22547 Org-mode buffer.
22548 With numerical prefix arg ARG, go up to this level and then take that tree.
22549 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22550 dedicated frame)."
22551 (interactive)
22552 (org-agenda-check-no-diary)
22553 (let* ((marker (or (get-text-property (point) 'org-marker)
22554 (org-agenda-error)))
22555 (buffer (marker-buffer marker))
22556 (pos (marker-position marker)))
22557 (with-current-buffer buffer
22558 (save-excursion
22559 (goto-char pos)
22560 (call-interactively 'org-tree-to-indirect-buffer)))))
22562 (defvar org-last-heading-marker (make-marker)
22563 "Marker pointing to the headline that last changed its TODO state
22564 by a remote command from the agenda.")
22566 (defun org-agenda-todo-nextset ()
22567 "Switch TODO entry to next sequence."
22568 (interactive)
22569 (org-agenda-todo 'nextset))
22571 (defun org-agenda-todo-previousset ()
22572 "Switch TODO entry to previous sequence."
22573 (interactive)
22574 (org-agenda-todo 'previousset))
22576 (defun org-agenda-todo (&optional arg)
22577 "Cycle TODO state of line at point, also in Org-mode file.
22578 This changes the line at point, all other lines in the agenda referring to
22579 the same tree node, and the headline of the tree node in the Org-mode file."
22580 (interactive "P")
22581 (org-agenda-check-no-diary)
22582 (let* ((col (current-column))
22583 (marker (or (get-text-property (point) 'org-marker)
22584 (org-agenda-error)))
22585 (buffer (marker-buffer marker))
22586 (pos (marker-position marker))
22587 (hdmarker (get-text-property (point) 'org-hd-marker))
22588 (inhibit-read-only t)
22589 newhead)
22590 (org-with-remote-undo buffer
22591 (with-current-buffer buffer
22592 (widen)
22593 (goto-char pos)
22594 (org-show-context 'agenda)
22595 (save-excursion
22596 (and (outline-next-heading)
22597 (org-flag-heading nil))) ; show the next heading
22598 (org-todo arg)
22599 (and (bolp) (forward-char 1))
22600 (setq newhead (org-get-heading))
22601 (save-excursion
22602 (org-back-to-heading)
22603 (move-marker org-last-heading-marker (point))))
22604 (beginning-of-line 1)
22605 (save-excursion
22606 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22607 (move-to-column col))))
22609 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22610 "Change all lines in the agenda buffer which match HDMARKER.
22611 The new content of the line will be NEWHEAD (as modified by
22612 `org-format-agenda-item'). HDMARKER is checked with
22613 `equal' against all `org-hd-marker' text properties in the file.
22614 If FIXFACE is non-nil, the face of each item is modified acording to
22615 the new TODO state."
22616 (let* ((inhibit-read-only t)
22617 props m pl undone-face done-face finish new dotime cat tags)
22618 (save-excursion
22619 (goto-char (point-max))
22620 (beginning-of-line 1)
22621 (while (not finish)
22622 (setq finish (bobp))
22623 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22624 (equal m hdmarker))
22625 (setq props (text-properties-at (point))
22626 dotime (get-text-property (point) 'dotime)
22627 cat (get-text-property (point) 'org-category)
22628 tags (get-text-property (point) 'tags)
22629 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22630 pl (get-text-property (point) 'prefix-length)
22631 undone-face (get-text-property (point) 'undone-face)
22632 done-face (get-text-property (point) 'done-face))
22633 (move-to-column pl)
22634 (cond
22635 ((equal new "")
22636 (beginning-of-line 1)
22637 (and (looking-at ".*\n?") (replace-match "")))
22638 ((looking-at ".*")
22639 (replace-match new t t)
22640 (beginning-of-line 1)
22641 (add-text-properties (point-at-bol) (point-at-eol) props)
22642 (when fixface
22643 (add-text-properties
22644 (point-at-bol) (point-at-eol)
22645 (list 'face
22646 (if org-last-todo-state-is-todo
22647 undone-face done-face))))
22648 (org-agenda-highlight-todo 'line)
22649 (beginning-of-line 1))
22650 (t (error "Line update did not work"))))
22651 (beginning-of-line 0)))
22652 (org-finalize-agenda)))
22654 (defun org-agenda-align-tags (&optional line)
22655 "Align all tags in agenda items to `org-agenda-tags-column'."
22656 (let ((inhibit-read-only t) l c)
22657 (save-excursion
22658 (goto-char (if line (point-at-bol) (point-min)))
22659 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22660 (if line (point-at-eol) nil) t)
22661 (add-text-properties
22662 (match-beginning 2) (match-end 2)
22663 (list 'face (list 'org-tag (get-text-property
22664 (match-beginning 2) 'face))))
22665 (setq l (- (match-end 2) (match-beginning 2))
22666 c (if (< org-agenda-tags-column 0)
22667 (- (abs org-agenda-tags-column) l)
22668 org-agenda-tags-column))
22669 (delete-region (match-beginning 1) (match-end 1))
22670 (goto-char (match-beginning 1))
22671 (insert (org-add-props
22672 (make-string (max 1 (- c (current-column))) ?\ )
22673 (text-properties-at (point))))))))
22675 (defun org-agenda-priority-up ()
22676 "Increase the priority of line at point, also in Org-mode file."
22677 (interactive)
22678 (org-agenda-priority 'up))
22680 (defun org-agenda-priority-down ()
22681 "Decrease the priority of line at point, also in Org-mode file."
22682 (interactive)
22683 (org-agenda-priority 'down))
22685 (defun org-agenda-priority (&optional force-direction)
22686 "Set the priority of line at point, also in Org-mode file.
22687 This changes the line at point, all other lines in the agenda referring to
22688 the same tree node, and the headline of the tree node in the Org-mode file."
22689 (interactive)
22690 (org-agenda-check-no-diary)
22691 (let* ((marker (or (get-text-property (point) 'org-marker)
22692 (org-agenda-error)))
22693 (hdmarker (get-text-property (point) 'org-hd-marker))
22694 (buffer (marker-buffer hdmarker))
22695 (pos (marker-position hdmarker))
22696 (inhibit-read-only t)
22697 newhead)
22698 (org-with-remote-undo buffer
22699 (with-current-buffer buffer
22700 (widen)
22701 (goto-char pos)
22702 (org-show-context 'agenda)
22703 (save-excursion
22704 (and (outline-next-heading)
22705 (org-flag-heading nil))) ; show the next heading
22706 (funcall 'org-priority force-direction)
22707 (end-of-line 1)
22708 (setq newhead (org-get-heading)))
22709 (org-agenda-change-all-lines newhead hdmarker)
22710 (beginning-of-line 1))))
22712 (defun org-get-tags-at (&optional pos)
22713 "Get a list of all headline tags applicable at POS.
22714 POS defaults to point. If tags are inherited, the list contains
22715 the targets in the same sequence as the headlines appear, i.e.
22716 the tags of the current headline come last."
22717 (interactive)
22718 (let (tags lastpos)
22719 (save-excursion
22720 (save-restriction
22721 (widen)
22722 (goto-char (or pos (point)))
22723 (save-match-data
22724 (org-back-to-heading t)
22725 (condition-case nil
22726 (while (not (equal lastpos (point)))
22727 (setq lastpos (point))
22728 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22729 (setq tags (append (org-split-string
22730 (org-match-string-no-properties 1) ":")
22731 tags)))
22732 (or org-use-tag-inheritance (error ""))
22733 (org-up-heading-all 1))
22734 (error nil))))
22735 tags)))
22737 ;; FIXME: should fix the tags property of the agenda line.
22738 (defun org-agenda-set-tags ()
22739 "Set tags for the current headline."
22740 (interactive)
22741 (org-agenda-check-no-diary)
22742 (if (and (org-region-active-p) (interactive-p))
22743 (call-interactively 'org-change-tag-in-region)
22744 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22745 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22746 (org-agenda-error)))
22747 (buffer (marker-buffer hdmarker))
22748 (pos (marker-position hdmarker))
22749 (inhibit-read-only t)
22750 newhead)
22751 (org-with-remote-undo buffer
22752 (with-current-buffer buffer
22753 (widen)
22754 (goto-char pos)
22755 (save-excursion
22756 (org-show-context 'agenda))
22757 (save-excursion
22758 (and (outline-next-heading)
22759 (org-flag-heading nil))) ; show the next heading
22760 (goto-char pos)
22761 (call-interactively 'org-set-tags)
22762 (end-of-line 1)
22763 (setq newhead (org-get-heading)))
22764 (org-agenda-change-all-lines newhead hdmarker)
22765 (beginning-of-line 1)))))
22767 (defun org-agenda-toggle-archive-tag ()
22768 "Toggle the archive tag for the current entry."
22769 (interactive)
22770 (org-agenda-check-no-diary)
22771 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22772 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22773 (org-agenda-error)))
22774 (buffer (marker-buffer hdmarker))
22775 (pos (marker-position hdmarker))
22776 (inhibit-read-only t)
22777 newhead)
22778 (org-with-remote-undo buffer
22779 (with-current-buffer buffer
22780 (widen)
22781 (goto-char pos)
22782 (org-show-context 'agenda)
22783 (save-excursion
22784 (and (outline-next-heading)
22785 (org-flag-heading nil))) ; show the next heading
22786 (call-interactively 'org-toggle-archive-tag)
22787 (end-of-line 1)
22788 (setq newhead (org-get-heading)))
22789 (org-agenda-change-all-lines newhead hdmarker)
22790 (beginning-of-line 1))))
22792 (defun org-agenda-date-later (arg &optional what)
22793 "Change the date of this item to one day later."
22794 (interactive "p")
22795 (org-agenda-check-type t 'agenda 'timeline)
22796 (org-agenda-check-no-diary)
22797 (let* ((marker (or (get-text-property (point) 'org-marker)
22798 (org-agenda-error)))
22799 (buffer (marker-buffer marker))
22800 (pos (marker-position marker)))
22801 (org-with-remote-undo buffer
22802 (with-current-buffer buffer
22803 (widen)
22804 (goto-char pos)
22805 (if (not (org-at-timestamp-p))
22806 (error "Cannot find time stamp"))
22807 (org-timestamp-change arg (or what 'day)))
22808 (org-agenda-show-new-time marker org-last-changed-timestamp))
22809 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22811 (defun org-agenda-date-earlier (arg &optional what)
22812 "Change the date of this item to one day earlier."
22813 (interactive "p")
22814 (org-agenda-date-later (- arg) what))
22816 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22817 "Show new date stamp via text properties."
22818 ;; We use text properties to make this undoable
22819 (let ((inhibit-read-only t))
22820 (setq stamp (concat " " prefix " => " stamp))
22821 (save-excursion
22822 (goto-char (point-max))
22823 (while (not (bobp))
22824 (when (equal marker (get-text-property (point) 'org-marker))
22825 (move-to-column (- (window-width) (length stamp)) t)
22826 (if (featurep 'xemacs)
22827 ;; Use `duplicable' property to trigger undo recording
22828 (let ((ex (make-extent nil nil))
22829 (gl (make-glyph stamp)))
22830 (set-glyph-face gl 'secondary-selection)
22831 (set-extent-properties
22832 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22833 (insert-extent ex (1- (point)) (point-at-eol)))
22834 (add-text-properties
22835 (1- (point)) (point-at-eol)
22836 (list 'display (org-add-props stamp nil
22837 'face 'secondary-selection))))
22838 (beginning-of-line 1))
22839 (beginning-of-line 0)))))
22841 (defun org-agenda-date-prompt (arg)
22842 "Change the date of this item. Date is prompted for, with default today.
22843 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22844 be used to request time specification in the time stamp."
22845 (interactive "P")
22846 (org-agenda-check-type t 'agenda 'timeline)
22847 (org-agenda-check-no-diary)
22848 (let* ((marker (or (get-text-property (point) 'org-marker)
22849 (org-agenda-error)))
22850 (buffer (marker-buffer marker))
22851 (pos (marker-position marker)))
22852 (org-with-remote-undo buffer
22853 (with-current-buffer buffer
22854 (widen)
22855 (goto-char pos)
22856 (if (not (org-at-timestamp-p))
22857 (error "Cannot find time stamp"))
22858 (org-time-stamp arg)
22859 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22861 (defun org-agenda-schedule (arg)
22862 "Schedule the item at point."
22863 (interactive "P")
22864 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22865 (org-agenda-check-no-diary)
22866 (let* ((marker (or (get-text-property (point) 'org-marker)
22867 (org-agenda-error)))
22868 (buffer (marker-buffer marker))
22869 (pos (marker-position marker))
22870 (org-insert-labeled-timestamps-at-point nil)
22872 (org-with-remote-undo buffer
22873 (with-current-buffer buffer
22874 (widen)
22875 (goto-char pos)
22876 (setq ts (org-schedule arg)))
22877 (org-agenda-show-new-time marker ts "S"))
22878 (message "Item scheduled for %s" ts)))
22880 (defun org-agenda-deadline (arg)
22881 "Schedule the item at point."
22882 (interactive "P")
22883 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22884 (org-agenda-check-no-diary)
22885 (let* ((marker (or (get-text-property (point) 'org-marker)
22886 (org-agenda-error)))
22887 (buffer (marker-buffer marker))
22888 (pos (marker-position marker))
22889 (org-insert-labeled-timestamps-at-point nil)
22891 (org-with-remote-undo buffer
22892 (with-current-buffer buffer
22893 (widen)
22894 (goto-char pos)
22895 (setq ts (org-deadline arg)))
22896 (org-agenda-show-new-time marker ts "S"))
22897 (message "Deadline for this item set to %s" ts)))
22899 (defun org-get-heading (&optional no-tags)
22900 "Return the heading of the current entry, without the stars."
22901 (save-excursion
22902 (org-back-to-heading t)
22903 (if (looking-at
22904 (if no-tags
22905 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22906 "\\*+[ \t]+\\([^\r\n]*\\)"))
22907 (match-string 1) "")))
22909 (defun org-agenda-clock-in (&optional arg)
22910 "Start the clock on the currently selected item."
22911 (interactive "P")
22912 (org-agenda-check-no-diary)
22913 (let* ((marker (or (get-text-property (point) 'org-marker)
22914 (org-agenda-error)))
22915 (pos (marker-position marker)))
22916 (org-with-remote-undo (marker-buffer marker)
22917 (with-current-buffer (marker-buffer marker)
22918 (widen)
22919 (goto-char pos)
22920 (org-clock-in)))))
22922 (defun org-agenda-clock-out (&optional arg)
22923 "Stop the currently running clock."
22924 (interactive "P")
22925 (unless (marker-buffer org-clock-marker)
22926 (error "No running clock"))
22927 (org-with-remote-undo (marker-buffer org-clock-marker)
22928 (org-clock-out)))
22930 (defun org-agenda-clock-cancel (&optional arg)
22931 "Cancel the currently running clock."
22932 (interactive "P")
22933 (unless (marker-buffer org-clock-marker)
22934 (error "No running clock"))
22935 (org-with-remote-undo (marker-buffer org-clock-marker)
22936 (org-clock-cancel)))
22938 (defun org-agenda-diary-entry ()
22939 "Make a diary entry, like the `i' command from the calendar.
22940 All the standard commands work: block, weekly etc."
22941 (interactive)
22942 (org-agenda-check-type t 'agenda 'timeline)
22943 (require 'diary-lib)
22944 (let* ((char (progn
22945 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
22946 (read-char-exclusive)))
22947 (cmd (cdr (assoc char
22948 '((?d . insert-diary-entry)
22949 (?w . insert-weekly-diary-entry)
22950 (?m . insert-monthly-diary-entry)
22951 (?y . insert-yearly-diary-entry)
22952 (?a . insert-anniversary-diary-entry)
22953 (?b . insert-block-diary-entry)
22954 (?c . insert-cyclic-diary-entry)))))
22955 (oldf (symbol-function 'calendar-cursor-to-date))
22956 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
22957 (point (point))
22958 (mark (or (mark t) (point))))
22959 (unless cmd
22960 (error "No command associated with <%c>" char))
22961 (unless (and (get-text-property point 'day)
22962 (or (not (equal ?b char))
22963 (get-text-property mark 'day)))
22964 (error "Don't know which date to use for diary entry"))
22965 ;; We implement this by hacking the `calendar-cursor-to-date' function
22966 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
22967 (let ((calendar-mark-ring
22968 (list (calendar-gregorian-from-absolute
22969 (or (get-text-property mark 'day)
22970 (get-text-property point 'day))))))
22971 (unwind-protect
22972 (progn
22973 (fset 'calendar-cursor-to-date
22974 (lambda (&optional error)
22975 (calendar-gregorian-from-absolute
22976 (get-text-property point 'day))))
22977 (call-interactively cmd))
22978 (fset 'calendar-cursor-to-date oldf)))))
22981 (defun org-agenda-execute-calendar-command (cmd)
22982 "Execute a calendar command from the agenda, with the date associated to
22983 the cursor position."
22984 (org-agenda-check-type t 'agenda 'timeline)
22985 (require 'diary-lib)
22986 (unless (get-text-property (point) 'day)
22987 (error "Don't know which date to use for calendar command"))
22988 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
22989 (point (point))
22990 (date (calendar-gregorian-from-absolute
22991 (get-text-property point 'day)))
22992 ;; the following 3 vars are needed in the calendar
22993 (displayed-day (extract-calendar-day date))
22994 (displayed-month (extract-calendar-month date))
22995 (displayed-year (extract-calendar-year date)))
22996 (unwind-protect
22997 (progn
22998 (fset 'calendar-cursor-to-date
22999 (lambda (&optional error)
23000 (calendar-gregorian-from-absolute
23001 (get-text-property point 'day))))
23002 (call-interactively cmd))
23003 (fset 'calendar-cursor-to-date oldf))))
23005 (defun org-agenda-phases-of-moon ()
23006 "Display the phases of the moon for the 3 months around the cursor date."
23007 (interactive)
23008 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23010 (defun org-agenda-holidays ()
23011 "Display the holidays for the 3 months around the cursor date."
23012 (interactive)
23013 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23015 (defun org-agenda-sunrise-sunset (arg)
23016 "Display sunrise and sunset for the cursor date.
23017 Latitude and longitude can be specified with the variables
23018 `calendar-latitude' and `calendar-longitude'. When called with prefix
23019 argument, latitude and longitude will be prompted for."
23020 (interactive "P")
23021 (let ((calendar-longitude (if arg nil calendar-longitude))
23022 (calendar-latitude (if arg nil calendar-latitude))
23023 (calendar-location-name
23024 (if arg "the given coordinates" calendar-location-name)))
23025 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23027 (defun org-agenda-goto-calendar ()
23028 "Open the Emacs calendar with the date at the cursor."
23029 (interactive)
23030 (org-agenda-check-type t 'agenda 'timeline)
23031 (let* ((day (or (get-text-property (point) 'day)
23032 (error "Don't know which date to open in calendar")))
23033 (date (calendar-gregorian-from-absolute day))
23034 (calendar-move-hook nil)
23035 (view-calendar-holidays-initially nil)
23036 (view-diary-entries-initially nil))
23037 (calendar)
23038 (calendar-goto-date date)))
23040 (defun org-calendar-goto-agenda ()
23041 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23042 This is a command that has to be installed in `calendar-mode-map'."
23043 (interactive)
23044 (org-agenda-list nil (calendar-absolute-from-gregorian
23045 (calendar-cursor-to-date))
23046 nil))
23048 (defun org-agenda-convert-date ()
23049 (interactive)
23050 (org-agenda-check-type t 'agenda 'timeline)
23051 (let ((day (get-text-property (point) 'day))
23052 date s)
23053 (unless day
23054 (error "Don't know which date to convert"))
23055 (setq date (calendar-gregorian-from-absolute day))
23056 (setq s (concat
23057 "Gregorian: " (calendar-date-string date) "\n"
23058 "ISO: " (calendar-iso-date-string date) "\n"
23059 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23060 "Julian: " (calendar-julian-date-string date) "\n"
23061 "Astron. JD: " (calendar-astro-date-string date)
23062 " (Julian date number at noon UTC)\n"
23063 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23064 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23065 "French: " (calendar-french-date-string date) "\n"
23066 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23067 "Mayan: " (calendar-mayan-date-string date) "\n"
23068 "Coptic: " (calendar-coptic-date-string date) "\n"
23069 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23070 "Persian: " (calendar-persian-date-string date) "\n"
23071 "Chinese: " (calendar-chinese-date-string date) "\n"))
23072 (with-output-to-temp-buffer "*Dates*"
23073 (princ s))
23074 (if (fboundp 'fit-window-to-buffer)
23075 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23078 ;;;; Embedded LaTeX
23080 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23081 "Keymap for the minor `org-cdlatex-mode'.")
23083 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23084 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23085 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23086 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23087 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23089 (defvar org-cdlatex-texmathp-advice-is-done nil
23090 "Flag remembering if we have applied the advice to texmathp already.")
23092 (define-minor-mode org-cdlatex-mode
23093 "Toggle the minor `org-cdlatex-mode'.
23094 This mode supports entering LaTeX environment and math in LaTeX fragments
23095 in Org-mode.
23096 \\{org-cdlatex-mode-map}"
23097 nil " OCDL" nil
23098 (when org-cdlatex-mode (require 'cdlatex))
23099 (unless org-cdlatex-texmathp-advice-is-done
23100 (setq org-cdlatex-texmathp-advice-is-done t)
23101 (defadvice texmathp (around org-math-always-on activate)
23102 "Always return t in org-mode buffers.
23103 This is because we want to insert math symbols without dollars even outside
23104 the LaTeX math segments. If Orgmode thinks that point is actually inside
23105 en embedded LaTeX fragement, let texmathp do its job.
23106 \\[org-cdlatex-mode-map]"
23107 (interactive)
23108 (let (p)
23109 (cond
23110 ((not (org-mode-p)) ad-do-it)
23111 ((eq this-command 'cdlatex-math-symbol)
23112 (setq ad-return-value t
23113 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23115 (let ((p (org-inside-LaTeX-fragment-p)))
23116 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23117 (setq ad-return-value t
23118 texmathp-why '("Org-mode embedded math" . 0))
23119 (if p ad-do-it)))))))))
23121 (defun turn-on-org-cdlatex ()
23122 "Unconditionally turn on `org-cdlatex-mode'."
23123 (org-cdlatex-mode 1))
23125 (defun org-inside-LaTeX-fragment-p ()
23126 "Test if point is inside a LaTeX fragment.
23127 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23128 sequence appearing also before point.
23129 Even though the matchers for math are configurable, this function assumes
23130 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23131 delimiters are skipped when they have been removed by customization.
23132 The return value is nil, or a cons cell with the delimiter and
23133 and the position of this delimiter.
23135 This function does a reasonably good job, but can locally be fooled by
23136 for example currency specifications. For example it will assume being in
23137 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23138 fragments that are properly closed, but during editing, we have to live
23139 with the uncertainty caused by missing closing delimiters. This function
23140 looks only before point, not after."
23141 (catch 'exit
23142 (let ((pos (point))
23143 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23144 (lim (progn
23145 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23146 (point)))
23147 dd-on str (start 0) m re)
23148 (goto-char pos)
23149 (when dodollar
23150 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23151 re (nth 1 (assoc "$" org-latex-regexps)))
23152 (while (string-match re str start)
23153 (cond
23154 ((= (match-end 0) (length str))
23155 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23156 ((= (match-end 0) (- (length str) 5))
23157 (throw 'exit nil))
23158 (t (setq start (match-end 0))))))
23159 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23160 (goto-char pos)
23161 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23162 (and (match-beginning 2) (throw 'exit nil))
23163 ;; count $$
23164 (while (re-search-backward "\\$\\$" lim t)
23165 (setq dd-on (not dd-on)))
23166 (goto-char pos)
23167 (if dd-on (cons "$$" m))))))
23170 (defun org-try-cdlatex-tab ()
23171 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23172 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23173 - inside a LaTeX fragment, or
23174 - after the first word in a line, where an abbreviation expansion could
23175 insert a LaTeX environment."
23176 (when org-cdlatex-mode
23177 (cond
23178 ((save-excursion
23179 (skip-chars-backward "a-zA-Z0-9*")
23180 (skip-chars-backward " \t")
23181 (bolp))
23182 (cdlatex-tab) t)
23183 ((org-inside-LaTeX-fragment-p)
23184 (cdlatex-tab) t)
23185 (t nil))))
23187 (defun org-cdlatex-underscore-caret (&optional arg)
23188 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23189 Revert to the normal definition outside of these fragments."
23190 (interactive "P")
23191 (if (org-inside-LaTeX-fragment-p)
23192 (call-interactively 'cdlatex-sub-superscript)
23193 (let (org-cdlatex-mode)
23194 (call-interactively (key-binding (vector last-input-event))))))
23196 (defun org-cdlatex-math-modify (&optional arg)
23197 "Execute `cdlatex-math-modify' in LaTeX fragments.
23198 Revert to the normal definition outside of these fragments."
23199 (interactive "P")
23200 (if (org-inside-LaTeX-fragment-p)
23201 (call-interactively 'cdlatex-math-modify)
23202 (let (org-cdlatex-mode)
23203 (call-interactively (key-binding (vector last-input-event))))))
23205 (defvar org-latex-fragment-image-overlays nil
23206 "List of overlays carrying the images of latex fragments.")
23207 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23209 (defun org-remove-latex-fragment-image-overlays ()
23210 "Remove all overlays with LaTeX fragment images in current buffer."
23211 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23212 (setq org-latex-fragment-image-overlays nil))
23214 (defun org-preview-latex-fragment (&optional subtree)
23215 "Preview the LaTeX fragment at point, or all locally or globally.
23216 If the cursor is in a LaTeX fragment, create the image and overlay
23217 it over the source code. If there is no fragment at point, display
23218 all fragments in the current text, from one headline to the next. With
23219 prefix SUBTREE, display all fragments in the current subtree. With a
23220 double prefix `C-u C-u', or when the cursor is before the first headline,
23221 display all fragments in the buffer.
23222 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23223 (interactive "P")
23224 (org-remove-latex-fragment-image-overlays)
23225 (save-excursion
23226 (save-restriction
23227 (let (beg end at msg)
23228 (cond
23229 ((or (equal subtree '(16))
23230 (not (save-excursion
23231 (re-search-backward (concat "^" outline-regexp) nil t))))
23232 (setq beg (point-min) end (point-max)
23233 msg "Creating images for buffer...%s"))
23234 ((equal subtree '(4))
23235 (org-back-to-heading)
23236 (setq beg (point) end (org-end-of-subtree t)
23237 msg "Creating images for subtree...%s"))
23239 (if (setq at (org-inside-LaTeX-fragment-p))
23240 (goto-char (max (point-min) (- (cdr at) 2)))
23241 (org-back-to-heading))
23242 (setq beg (point) end (progn (outline-next-heading) (point))
23243 msg (if at "Creating image...%s"
23244 "Creating images for entry...%s"))))
23245 (message msg "")
23246 (narrow-to-region beg end)
23247 (goto-char beg)
23248 (org-format-latex
23249 (concat "ltxpng/" (file-name-sans-extension
23250 (file-name-nondirectory
23251 buffer-file-name)))
23252 default-directory 'overlays msg at 'forbuffer)
23253 (message msg "done. Use `C-c C-c' to remove images.")))))
23255 (defvar org-latex-regexps
23256 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23257 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23258 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23259 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23260 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23261 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23262 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23263 "Regular expressions for matching embedded LaTeX.")
23265 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23266 "Replace LaTeX fragments with links to an image, and produce images."
23267 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23268 (let* ((prefixnodir (file-name-nondirectory prefix))
23269 (absprefix (expand-file-name prefix dir))
23270 (todir (file-name-directory absprefix))
23271 (opt org-format-latex-options)
23272 (matchers (plist-get opt :matchers))
23273 (re-list org-latex-regexps)
23274 (cnt 0) txt link beg end re e checkdir
23275 m n block linkfile movefile ov)
23276 ;; Check if there are old images files with this prefix, and remove them
23277 (when (file-directory-p todir)
23278 (mapc 'delete-file
23279 (directory-files
23280 todir 'full
23281 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23282 ;; Check the different regular expressions
23283 (while (setq e (pop re-list))
23284 (setq m (car e) re (nth 1 e) n (nth 2 e)
23285 block (if (nth 3 e) "\n\n" ""))
23286 (when (member m matchers)
23287 (goto-char (point-min))
23288 (while (re-search-forward re nil t)
23289 (when (or (not at) (equal (cdr at) (match-beginning n)))
23290 (setq txt (match-string n)
23291 beg (match-beginning n) end (match-end n)
23292 cnt (1+ cnt)
23293 linkfile (format "%s_%04d.png" prefix cnt)
23294 movefile (format "%s_%04d.png" absprefix cnt)
23295 link (concat block "[[file:" linkfile "]]" block))
23296 (if msg (message msg cnt))
23297 (goto-char beg)
23298 (unless checkdir ; make sure the directory exists
23299 (setq checkdir t)
23300 (or (file-directory-p todir) (make-directory todir)))
23301 (org-create-formula-image
23302 txt movefile opt forbuffer)
23303 (if overlays
23304 (progn
23305 (setq ov (org-make-overlay beg end))
23306 (if (featurep 'xemacs)
23307 (progn
23308 (org-overlay-put ov 'invisible t)
23309 (org-overlay-put
23310 ov 'end-glyph
23311 (make-glyph (vector 'png :file movefile))))
23312 (org-overlay-put
23313 ov 'display
23314 (list 'image :type 'png :file movefile :ascent 'center)))
23315 (push ov org-latex-fragment-image-overlays)
23316 (goto-char end))
23317 (delete-region beg end)
23318 (insert link))))))))
23320 ;; This function borrows from Ganesh Swami's latex2png.el
23321 (defun org-create-formula-image (string tofile options buffer)
23322 (let* ((tmpdir (if (featurep 'xemacs)
23323 (temp-directory)
23324 temporary-file-directory))
23325 (texfilebase (make-temp-name
23326 (expand-file-name "orgtex" tmpdir)))
23327 (texfile (concat texfilebase ".tex"))
23328 (dvifile (concat texfilebase ".dvi"))
23329 (pngfile (concat texfilebase ".png"))
23330 (fnh (face-attribute 'default :height nil))
23331 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23332 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23333 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23334 "Black"))
23335 (bg (or (plist-get options (if buffer :background :html-background))
23336 "Transparent")))
23337 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23338 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23339 (with-temp-file texfile
23340 (insert org-format-latex-header
23341 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23342 (let ((dir default-directory))
23343 (condition-case nil
23344 (progn
23345 (cd tmpdir)
23346 (call-process "latex" nil nil nil texfile))
23347 (error nil))
23348 (cd dir))
23349 (if (not (file-exists-p dvifile))
23350 (progn (message "Failed to create dvi file from %s" texfile) nil)
23351 (call-process "dvipng" nil nil nil
23352 "-E" "-fg" fg "-bg" bg
23353 "-D" dpi
23354 ;;"-x" scale "-y" scale
23355 "-T" "tight"
23356 "-o" pngfile
23357 dvifile)
23358 (if (not (file-exists-p pngfile))
23359 (progn (message "Failed to create png file from %s" texfile) nil)
23360 ;; Use the requested file name and clean up
23361 (copy-file pngfile tofile 'replace)
23362 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23363 (delete-file (concat texfilebase e)))
23364 pngfile))))
23366 (defun org-dvipng-color (attr)
23367 "Return an rgb color specification for dvipng."
23368 (apply 'format "rgb %s %s %s"
23369 (mapcar 'org-normalize-color
23370 (color-values (face-attribute 'default attr nil)))))
23372 (defun org-normalize-color (value)
23373 "Return string to be used as color value for an RGB component."
23374 (format "%g" (/ value 65535.0)))
23376 ;;;; Exporting
23378 ;;; Variables, constants, and parameter plists
23380 (defconst org-level-max 20)
23382 (defvar org-export-html-preamble nil
23383 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23384 (defvar org-export-html-postamble nil
23385 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23386 (defvar org-export-html-auto-preamble t
23387 "Should default preamble be inserted? Set by publishing functions.")
23388 (defvar org-export-html-auto-postamble t
23389 "Should default postamble be inserted? Set by publishing functions.")
23390 (defvar org-current-export-file nil) ; dynamically scoped parameter
23391 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23394 (defconst org-export-plist-vars
23395 '((:language . org-export-default-language)
23396 (:customtime . org-display-custom-times)
23397 (:headline-levels . org-export-headline-levels)
23398 (:section-numbers . org-export-with-section-numbers)
23399 (:table-of-contents . org-export-with-toc)
23400 (:preserve-breaks . org-export-preserve-breaks)
23401 (:archived-trees . org-export-with-archived-trees)
23402 (:emphasize . org-export-with-emphasize)
23403 (:sub-superscript . org-export-with-sub-superscripts)
23404 (:special-strings . org-export-with-special-strings)
23405 (:footnotes . org-export-with-footnotes)
23406 (:drawers . org-export-with-drawers)
23407 (:tags . org-export-with-tags)
23408 (:TeX-macros . org-export-with-TeX-macros)
23409 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23410 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23411 (:fixed-width . org-export-with-fixed-width)
23412 (:timestamps . org-export-with-timestamps)
23413 (:author-info . org-export-author-info)
23414 (:time-stamp-file . org-export-time-stamp-file)
23415 (:tables . org-export-with-tables)
23416 (:table-auto-headline . org-export-highlight-first-table-line)
23417 (:style . org-export-html-style)
23418 (:agenda-style . org-agenda-export-html-style)
23419 (:convert-org-links . org-export-html-link-org-files-as-html)
23420 (:inline-images . org-export-html-inline-images)
23421 (:html-extension . org-export-html-extension)
23422 (:html-table-tag . org-export-html-table-tag)
23423 (:expand-quoted-html . org-export-html-expand)
23424 (:timestamp . org-export-html-with-timestamp)
23425 (:publishing-directory . org-export-publishing-directory)
23426 (:preamble . org-export-html-preamble)
23427 (:postamble . org-export-html-postamble)
23428 (:auto-preamble . org-export-html-auto-preamble)
23429 (:auto-postamble . org-export-html-auto-postamble)
23430 (:author . user-full-name)
23431 (:email . user-mail-address)))
23433 (defun org-default-export-plist ()
23434 "Return the property list with default settings for the export variables."
23435 (let ((l org-export-plist-vars) rtn e)
23436 (while (setq e (pop l))
23437 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23438 rtn))
23440 (defun org-infile-export-plist ()
23441 "Return the property list with file-local settings for export."
23442 (save-excursion
23443 (save-restriction
23444 (widen)
23445 (goto-char 0)
23446 (let ((re (org-make-options-regexp
23447 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23448 p key val text options)
23449 (while (re-search-forward re nil t)
23450 (setq key (org-match-string-no-properties 1)
23451 val (org-match-string-no-properties 2))
23452 (cond
23453 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23454 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23455 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23456 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23457 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23458 ((string-equal key "TEXT")
23459 (setq text (if text (concat text "\n" val) val)))
23460 ((string-equal key "OPTIONS") (setq options val))))
23461 (setq p (plist-put p :text text))
23462 (when options
23463 (let ((op '(("H" . :headline-levels)
23464 ("num" . :section-numbers)
23465 ("toc" . :table-of-contents)
23466 ("\\n" . :preserve-breaks)
23467 ("@" . :expand-quoted-html)
23468 (":" . :fixed-width)
23469 ("|" . :tables)
23470 ("^" . :sub-superscript)
23471 ("-" . :special-strings)
23472 ("f" . :footnotes)
23473 ("d" . :drawers)
23474 ("tags" . :tags)
23475 ("*" . :emphasize)
23476 ("TeX" . :TeX-macros)
23477 ("LaTeX" . :LaTeX-fragments)
23478 ("skip" . :skip-before-1st-heading)
23479 ("author" . :author-info)
23480 ("timestamp" . :time-stamp-file)))
23482 (while (setq o (pop op))
23483 (if (string-match (concat (regexp-quote (car o))
23484 ":\\([^ \t\n\r;,.]*\\)")
23485 options)
23486 (setq p (plist-put p (cdr o)
23487 (car (read-from-string
23488 (match-string 1 options)))))))))
23489 p))))
23491 (defun org-export-directory (type plist)
23492 (let* ((val (plist-get plist :publishing-directory))
23493 (dir (if (listp val)
23494 (or (cdr (assoc type val)) ".")
23495 val)))
23496 dir))
23498 (defun org-skip-comments (lines)
23499 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23500 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23501 (re2 "^\\(\\*+\\)[ \t\n\r]")
23502 (case-fold-search nil)
23503 rtn line level)
23504 (while (setq line (pop lines))
23505 (cond
23506 ((and (string-match re1 line)
23507 (setq level (- (match-end 1) (match-beginning 1))))
23508 ;; Beginning of a COMMENT subtree. Skip it.
23509 (while (and (setq line (pop lines))
23510 (or (not (string-match re2 line))
23511 (> (- (match-end 1) (match-beginning 1)) level))))
23512 (setq lines (cons line lines)))
23513 ((string-match "^#" line)
23514 ;; an ordinary comment line
23516 ((and org-export-table-remove-special-lines
23517 (string-match "^[ \t]*|" line)
23518 (or (string-match "^[ \t]*| *[!_^] *|" line)
23519 (and (string-match "| *<[0-9]+> *|" line)
23520 (not (string-match "| *[^ <|]" line)))))
23521 ;; a special table line that should be removed
23523 (t (setq rtn (cons line rtn)))))
23524 (nreverse rtn)))
23526 (defun org-export (&optional arg)
23527 (interactive)
23528 (let ((help "[t] insert the export option template
23529 \[v] limit export to visible part of outline tree
23531 \[a] export as ASCII
23533 \[h] export as HTML
23534 \[H] export as HTML to temporary buffer
23535 \[R] export region as HTML
23536 \[b] export as HTML and browse immediately
23537 \[x] export as XOXO
23539 \[l] export as LaTeX
23540 \[L] export as LaTeX to temporary buffer
23542 \[i] export current file as iCalendar file
23543 \[I] export all agenda files as iCalendar files
23544 \[c] export agenda files into combined iCalendar file
23546 \[F] publish current file
23547 \[P] publish current project
23548 \[X] publish... (project will be prompted for)
23549 \[A] publish all projects")
23550 (cmds
23551 '((?t . org-insert-export-options-template)
23552 (?v . org-export-visible)
23553 (?a . org-export-as-ascii)
23554 (?h . org-export-as-html)
23555 (?b . org-export-as-html-and-open)
23556 (?H . org-export-as-html-to-buffer)
23557 (?R . org-export-region-as-html)
23558 (?x . org-export-as-xoxo)
23559 (?l . org-export-as-latex)
23560 (?L . org-export-as-latex-to-buffer)
23561 (?i . org-export-icalendar-this-file)
23562 (?I . org-export-icalendar-all-agenda-files)
23563 (?c . org-export-icalendar-combine-agenda-files)
23564 (?F . org-publish-current-file)
23565 (?P . org-publish-current-project)
23566 (?X . org-publish)
23567 (?A . org-publish-all)))
23568 r1 r2 ass)
23569 (save-window-excursion
23570 (delete-other-windows)
23571 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23572 (princ help))
23573 (message "Select command: ")
23574 (setq r1 (read-char-exclusive)))
23575 (setq r2 (if (< r1 27) (+ r1 96) r1))
23576 (if (setq ass (assq r2 cmds))
23577 (call-interactively (cdr ass))
23578 (error "No command associated with key %c" r1))))
23580 (defconst org-html-entities
23581 '(("nbsp")
23582 ("iexcl")
23583 ("cent")
23584 ("pound")
23585 ("curren")
23586 ("yen")
23587 ("brvbar")
23588 ("vert" . "&#124;")
23589 ("sect")
23590 ("uml")
23591 ("copy")
23592 ("ordf")
23593 ("laquo")
23594 ("not")
23595 ("shy")
23596 ("reg")
23597 ("macr")
23598 ("deg")
23599 ("plusmn")
23600 ("sup2")
23601 ("sup3")
23602 ("acute")
23603 ("micro")
23604 ("para")
23605 ("middot")
23606 ("odot"."o")
23607 ("star"."*")
23608 ("cedil")
23609 ("sup1")
23610 ("ordm")
23611 ("raquo")
23612 ("frac14")
23613 ("frac12")
23614 ("frac34")
23615 ("iquest")
23616 ("Agrave")
23617 ("Aacute")
23618 ("Acirc")
23619 ("Atilde")
23620 ("Auml")
23621 ("Aring") ("AA"."&Aring;")
23622 ("AElig")
23623 ("Ccedil")
23624 ("Egrave")
23625 ("Eacute")
23626 ("Ecirc")
23627 ("Euml")
23628 ("Igrave")
23629 ("Iacute")
23630 ("Icirc")
23631 ("Iuml")
23632 ("ETH")
23633 ("Ntilde")
23634 ("Ograve")
23635 ("Oacute")
23636 ("Ocirc")
23637 ("Otilde")
23638 ("Ouml")
23639 ("times")
23640 ("Oslash")
23641 ("Ugrave")
23642 ("Uacute")
23643 ("Ucirc")
23644 ("Uuml")
23645 ("Yacute")
23646 ("THORN")
23647 ("szlig")
23648 ("agrave")
23649 ("aacute")
23650 ("acirc")
23651 ("atilde")
23652 ("auml")
23653 ("aring")
23654 ("aelig")
23655 ("ccedil")
23656 ("egrave")
23657 ("eacute")
23658 ("ecirc")
23659 ("euml")
23660 ("igrave")
23661 ("iacute")
23662 ("icirc")
23663 ("iuml")
23664 ("eth")
23665 ("ntilde")
23666 ("ograve")
23667 ("oacute")
23668 ("ocirc")
23669 ("otilde")
23670 ("ouml")
23671 ("divide")
23672 ("oslash")
23673 ("ugrave")
23674 ("uacute")
23675 ("ucirc")
23676 ("uuml")
23677 ("yacute")
23678 ("thorn")
23679 ("yuml")
23680 ("fnof")
23681 ("Alpha")
23682 ("Beta")
23683 ("Gamma")
23684 ("Delta")
23685 ("Epsilon")
23686 ("Zeta")
23687 ("Eta")
23688 ("Theta")
23689 ("Iota")
23690 ("Kappa")
23691 ("Lambda")
23692 ("Mu")
23693 ("Nu")
23694 ("Xi")
23695 ("Omicron")
23696 ("Pi")
23697 ("Rho")
23698 ("Sigma")
23699 ("Tau")
23700 ("Upsilon")
23701 ("Phi")
23702 ("Chi")
23703 ("Psi")
23704 ("Omega")
23705 ("alpha")
23706 ("beta")
23707 ("gamma")
23708 ("delta")
23709 ("epsilon")
23710 ("varepsilon"."&epsilon;")
23711 ("zeta")
23712 ("eta")
23713 ("theta")
23714 ("iota")
23715 ("kappa")
23716 ("lambda")
23717 ("mu")
23718 ("nu")
23719 ("xi")
23720 ("omicron")
23721 ("pi")
23722 ("rho")
23723 ("sigmaf") ("varsigma"."&sigmaf;")
23724 ("sigma")
23725 ("tau")
23726 ("upsilon")
23727 ("phi")
23728 ("chi")
23729 ("psi")
23730 ("omega")
23731 ("thetasym") ("vartheta"."&thetasym;")
23732 ("upsih")
23733 ("piv")
23734 ("bull") ("bullet"."&bull;")
23735 ("hellip") ("dots"."&hellip;")
23736 ("prime")
23737 ("Prime")
23738 ("oline")
23739 ("frasl")
23740 ("weierp")
23741 ("image")
23742 ("real")
23743 ("trade")
23744 ("alefsym")
23745 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23746 ("uarr") ("uparrow"."&uarr;")
23747 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23748 ("darr")("downarrow"."&darr;")
23749 ("harr") ("leftrightarrow"."&harr;")
23750 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23751 ("lArr") ("Leftarrow"."&lArr;")
23752 ("uArr") ("Uparrow"."&uArr;")
23753 ("rArr") ("Rightarrow"."&rArr;")
23754 ("dArr") ("Downarrow"."&dArr;")
23755 ("hArr") ("Leftrightarrow"."&hArr;")
23756 ("forall")
23757 ("part") ("partial"."&part;")
23758 ("exist") ("exists"."&exist;")
23759 ("empty") ("emptyset"."&empty;")
23760 ("nabla")
23761 ("isin") ("in"."&isin;")
23762 ("notin")
23763 ("ni")
23764 ("prod")
23765 ("sum")
23766 ("minus")
23767 ("lowast") ("ast"."&lowast;")
23768 ("radic")
23769 ("prop") ("proptp"."&prop;")
23770 ("infin") ("infty"."&infin;")
23771 ("ang") ("angle"."&ang;")
23772 ("and") ("wedge"."&and;")
23773 ("or") ("vee"."&or;")
23774 ("cap")
23775 ("cup")
23776 ("int")
23777 ("there4")
23778 ("sim")
23779 ("cong") ("simeq"."&cong;")
23780 ("asymp")("approx"."&asymp;")
23781 ("ne") ("neq"."&ne;")
23782 ("equiv")
23783 ("le")
23784 ("ge")
23785 ("sub") ("subset"."&sub;")
23786 ("sup") ("supset"."&sup;")
23787 ("nsub")
23788 ("sube")
23789 ("supe")
23790 ("oplus")
23791 ("otimes")
23792 ("perp")
23793 ("sdot") ("cdot"."&sdot;")
23794 ("lceil")
23795 ("rceil")
23796 ("lfloor")
23797 ("rfloor")
23798 ("lang")
23799 ("rang")
23800 ("loz") ("Diamond"."&loz;")
23801 ("spades") ("spadesuit"."&spades;")
23802 ("clubs") ("clubsuit"."&clubs;")
23803 ("hearts") ("diamondsuit"."&hearts;")
23804 ("diams") ("diamondsuit"."&diams;")
23805 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23806 ("quot")
23807 ("amp")
23808 ("lt")
23809 ("gt")
23810 ("OElig")
23811 ("oelig")
23812 ("Scaron")
23813 ("scaron")
23814 ("Yuml")
23815 ("circ")
23816 ("tilde")
23817 ("ensp")
23818 ("emsp")
23819 ("thinsp")
23820 ("zwnj")
23821 ("zwj")
23822 ("lrm")
23823 ("rlm")
23824 ("ndash")
23825 ("mdash")
23826 ("lsquo")
23827 ("rsquo")
23828 ("sbquo")
23829 ("ldquo")
23830 ("rdquo")
23831 ("bdquo")
23832 ("dagger")
23833 ("Dagger")
23834 ("permil")
23835 ("lsaquo")
23836 ("rsaquo")
23837 ("euro")
23839 ("arccos"."arccos")
23840 ("arcsin"."arcsin")
23841 ("arctan"."arctan")
23842 ("arg"."arg")
23843 ("cos"."cos")
23844 ("cosh"."cosh")
23845 ("cot"."cot")
23846 ("coth"."coth")
23847 ("csc"."csc")
23848 ("deg"."deg")
23849 ("det"."det")
23850 ("dim"."dim")
23851 ("exp"."exp")
23852 ("gcd"."gcd")
23853 ("hom"."hom")
23854 ("inf"."inf")
23855 ("ker"."ker")
23856 ("lg"."lg")
23857 ("lim"."lim")
23858 ("liminf"."liminf")
23859 ("limsup"."limsup")
23860 ("ln"."ln")
23861 ("log"."log")
23862 ("max"."max")
23863 ("min"."min")
23864 ("Pr"."Pr")
23865 ("sec"."sec")
23866 ("sin"."sin")
23867 ("sinh"."sinh")
23868 ("sup"."sup")
23869 ("tan"."tan")
23870 ("tanh"."tanh")
23872 "Entities for TeX->HTML translation.
23873 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23874 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23875 In that case, \"\\ent\" will be translated to \"&other;\".
23876 The list contains HTML entities for Latin-1, Greek and other symbols.
23877 It is supplemented by a number of commonly used TeX macros with appropriate
23878 translations. There is currently no way for users to extend this.")
23880 ;;; General functions for all backends
23882 (defun org-cleaned-string-for-export (string &rest parameters)
23883 "Cleanup a buffer STRING so that links can be created safely."
23884 (interactive)
23885 (let* ((re-radio (and org-target-link-regexp
23886 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23887 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23888 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23889 (re-archive (concat ":" org-archive-tag ":"))
23890 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23891 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23892 (htmlp (plist-get parameters :for-html))
23893 (asciip (plist-get parameters :for-ascii))
23894 (latexp (plist-get parameters :for-LaTeX))
23895 (commentsp (plist-get parameters :comments))
23896 (archived-trees (plist-get parameters :archived-trees))
23897 (inhibit-read-only t)
23898 (drawers org-drawers)
23899 (exp-drawers (plist-get parameters :drawers))
23900 (outline-regexp "\\*+ ")
23901 a b xx
23902 rtn p)
23903 (with-current-buffer (get-buffer-create " org-mode-tmp")
23904 (erase-buffer)
23905 (insert string)
23906 ;; Remove license-to-kill stuff
23907 (while (setq p (text-property-any (point-min) (point-max)
23908 :org-license-to-kill t))
23909 (delete-region p (next-single-property-change p :org-license-to-kill)))
23911 (let ((org-inhibit-startup t)) (org-mode))
23912 (untabify (point-min) (point-max))
23914 ;; Get rid of drawers
23915 (unless (eq t exp-drawers)
23916 (goto-char (point-min))
23917 (let ((re (concat "^[ \t]*:\\("
23918 (mapconcat
23919 'identity
23920 (org-delete-all exp-drawers
23921 (copy-sequence drawers))
23922 "\\|")
23923 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23924 (while (re-search-forward re nil t)
23925 (replace-match ""))))
23927 ;; Get the correct stuff before the first headline
23928 (when (plist-get parameters :skip-before-1st-heading)
23929 (goto-char (point-min))
23930 (when (re-search-forward "^\\*+[ \t]" nil t)
23931 (delete-region (point-min) (match-beginning 0))
23932 (goto-char (point-min))
23933 (insert "\n")))
23934 (when (plist-get parameters :add-text)
23935 (goto-char (point-min))
23936 (insert (plist-get parameters :add-text) "\n"))
23938 ;; Get rid of archived trees
23939 (when (not (eq archived-trees t))
23940 (goto-char (point-min))
23941 (while (re-search-forward re-archive nil t)
23942 (if (not (org-on-heading-p t))
23943 (org-end-of-subtree t)
23944 (beginning-of-line 1)
23945 (setq a (if archived-trees
23946 (1+ (point-at-eol)) (point))
23947 b (org-end-of-subtree t))
23948 (if (> b a) (delete-region a b)))))
23950 ;; Find targets in comments and move them out of comments,
23951 ;; but mark them as targets that should be invisible
23952 (goto-char (point-min))
23953 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
23954 (replace-match "\\1(INVISIBLE)"))
23956 ;; Protect backend specific stuff, throw away the others.
23957 (let ((formatters
23958 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
23959 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
23960 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
23961 fmt)
23962 (goto-char (point-min))
23963 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
23964 (goto-char (match-end 0))
23965 (while (not (looking-at "#\\+END_EXAMPLE"))
23966 (insert ": ")
23967 (beginning-of-line 2)))
23968 (goto-char (point-min))
23969 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
23970 (add-text-properties (match-beginning 0) (match-end 0)
23971 '(org-protected t)))
23972 (while formatters
23973 (setq fmt (pop formatters))
23974 (when (car fmt)
23975 (goto-char (point-min))
23976 (while (re-search-forward (concat "^#\\+" (cadr fmt)
23977 ":[ \t]*\\(.*\\)") nil t)
23978 (replace-match "\\1" t)
23979 (add-text-properties
23980 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
23981 '(org-protected t))))
23982 (goto-char (point-min))
23983 (while (re-search-forward
23984 (concat "^#\\+"
23985 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
23986 (cadddr fmt) "\\>.*\n?") nil t)
23987 (if (car fmt)
23988 (add-text-properties (match-beginning 1) (1+ (match-end 1))
23989 '(org-protected t))
23990 (delete-region (match-beginning 0) (match-end 0))))))
23992 ;; Protect quoted subtrees
23993 (goto-char (point-min))
23994 (while (re-search-forward re-quote nil t)
23995 (goto-char (match-beginning 0))
23996 (end-of-line 1)
23997 (add-text-properties (point) (org-end-of-subtree t)
23998 '(org-protected t)))
24000 ;; Protect verbatim elements
24001 (goto-char (point-min))
24002 (while (re-search-forward org-verbatim-re nil t)
24003 (add-text-properties (match-beginning 4) (match-end 4)
24004 '(org-protected t))
24005 (goto-char (1+ (match-end 4))))
24007 ;; Remove subtrees that are commented
24008 (goto-char (point-min))
24009 (while (re-search-forward re-commented nil t)
24010 (goto-char (match-beginning 0))
24011 (delete-region (point) (org-end-of-subtree t)))
24013 ;; Remove special table lines
24014 (when org-export-table-remove-special-lines
24015 (goto-char (point-min))
24016 (while (re-search-forward "^[ \t]*|" nil t)
24017 (beginning-of-line 1)
24018 (if (or (looking-at "[ \t]*| *[!_^] *|")
24019 (and (looking-at ".*?| *<[0-9]+> *|")
24020 (not (looking-at ".*?| *[^ <|]"))))
24021 (delete-region (max (point-min) (1- (point-at-bol)))
24022 (point-at-eol))
24023 (end-of-line 1))))
24025 ;; Specific LaTeX stuff
24026 (when latexp
24027 (require 'org-export-latex nil)
24028 (org-export-latex-cleaned-string))
24030 (when asciip
24031 (org-export-ascii-clean-string))
24033 ;; Specific HTML stuff
24034 (when htmlp
24035 ;; Convert LaTeX fragments to images
24036 (when (plist-get parameters :LaTeX-fragments)
24037 (org-format-latex
24038 (concat "ltxpng/" (file-name-sans-extension
24039 (file-name-nondirectory
24040 org-current-export-file)))
24041 org-current-export-dir nil "Creating LaTeX image %s"))
24042 (message "Exporting..."))
24044 ;; Remove or replace comments
24045 (goto-char (point-min))
24046 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24047 (if commentsp
24048 (progn (add-text-properties
24049 (match-beginning 0) (match-end 0) '(org-protected t))
24050 (replace-match (format commentsp (match-string 1)) t t))
24051 (replace-match "")))
24053 ;; Find matches for radio targets and turn them into internal links
24054 (goto-char (point-min))
24055 (when re-radio
24056 (while (re-search-forward re-radio nil t)
24057 (org-if-unprotected
24058 (replace-match "\\1[[\\2]]"))))
24060 ;; Find all links that contain a newline and put them into a single line
24061 (goto-char (point-min))
24062 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24063 (org-if-unprotected
24064 (replace-match "\\1 \\3")
24065 (goto-char (match-beginning 0))))
24068 ;; Normalize links: Convert angle and plain links into bracket links
24069 ;; Expand link abbreviations
24070 (goto-char (point-min))
24071 (while (re-search-forward re-plain-link nil t)
24072 (goto-char (1- (match-end 0)))
24073 (org-if-unprotected
24074 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24075 ":" (match-string 3) "]]")))
24076 ;; added 'org-link face to links
24077 (put-text-property 0 (length s) 'face 'org-link s)
24078 (replace-match s t t))))
24079 (goto-char (point-min))
24080 (while (re-search-forward re-angle-link nil t)
24081 (goto-char (1- (match-end 0)))
24082 (org-if-unprotected
24083 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24084 ":" (match-string 3) "]]")))
24085 (put-text-property 0 (length s) 'face 'org-link s)
24086 (replace-match s t t))))
24087 (goto-char (point-min))
24088 (while (re-search-forward org-bracket-link-regexp nil t)
24089 (org-if-unprotected
24090 (let* ((s (concat "[[" (setq xx (save-match-data
24091 (org-link-expand-abbrev (match-string 1))))
24093 (if (match-end 3)
24094 (match-string 2)
24095 (concat "[" xx "]"))
24096 "]")))
24097 (put-text-property 0 (length s) 'face 'org-link s)
24098 (replace-match s t t))))
24100 ;; Find multiline emphasis and put them into single line
24101 (when (plist-get parameters :emph-multiline)
24102 (goto-char (point-min))
24103 (while (re-search-forward org-emph-re nil t)
24104 (if (not (= (char-after (match-beginning 3))
24105 (char-after (match-beginning 4))))
24106 (org-if-unprotected
24107 (subst-char-in-region (match-beginning 0) (match-end 0)
24108 ?\n ?\ t)
24109 (goto-char (1- (match-end 0))))
24110 (goto-char (1+ (match-beginning 0))))))
24112 (setq rtn (buffer-string)))
24113 (kill-buffer " org-mode-tmp")
24114 rtn))
24116 (defun org-export-grab-title-from-buffer ()
24117 "Get a title for the current document, from looking at the buffer."
24118 (let ((inhibit-read-only t))
24119 (save-excursion
24120 (goto-char (point-min))
24121 (let ((end (save-excursion (outline-next-heading) (point))))
24122 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24123 ;; Mark the line so that it will not be exported as normal text.
24124 (org-unmodified
24125 (add-text-properties (match-beginning 0) (match-end 0)
24126 (list :org-license-to-kill t)))
24127 ;; Return the title string
24128 (org-trim (match-string 0)))))))
24130 (defun org-export-get-title-from-subtree ()
24131 "Return subtree title and exclude it from export."
24132 (let (title (m (mark)))
24133 (save-excursion
24134 (goto-char (region-beginning))
24135 (when (and (org-at-heading-p)
24136 (>= (org-end-of-subtree t t) (region-end)))
24137 ;; This is a subtree, we take the title from the first heading
24138 (goto-char (region-beginning))
24139 (looking-at org-todo-line-regexp)
24140 (setq title (match-string 3))
24141 (org-unmodified
24142 (add-text-properties (point) (1+ (point-at-eol))
24143 (list :org-license-to-kill t)))))
24144 title))
24146 (defun org-solidify-link-text (s &optional alist)
24147 "Take link text and make a safe target out of it."
24148 (save-match-data
24149 (let* ((rtn
24150 (mapconcat
24151 'identity
24152 (org-split-string s "[ \t\r\n]+") "--"))
24153 (a (assoc rtn alist)))
24154 (or (cdr a) rtn))))
24156 (defun org-get-min-level (lines)
24157 "Get the minimum level in LINES."
24158 (let ((re "^\\(\\*+\\) ") l min)
24159 (catch 'exit
24160 (while (setq l (pop lines))
24161 (if (string-match re l)
24162 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24163 1)))
24165 ;; Variable holding the vector with section numbers
24166 (defvar org-section-numbers (make-vector org-level-max 0))
24168 (defun org-init-section-numbers ()
24169 "Initialize the vector for the section numbers."
24170 (let* ((level -1)
24171 (numbers (nreverse (org-split-string "" "\\.")))
24172 (depth (1- (length org-section-numbers)))
24173 (i depth) number-string)
24174 (while (>= i 0)
24175 (if (> i level)
24176 (aset org-section-numbers i 0)
24177 (setq number-string (or (car numbers) "0"))
24178 (if (string-match "\\`[A-Z]\\'" number-string)
24179 (aset org-section-numbers i
24180 (- (string-to-char number-string) ?A -1))
24181 (aset org-section-numbers i (string-to-number number-string)))
24182 (pop numbers))
24183 (setq i (1- i)))))
24185 (defun org-section-number (&optional level)
24186 "Return a string with the current section number.
24187 When LEVEL is non-nil, increase section numbers on that level."
24188 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24189 (when level
24190 (when (> level -1)
24191 (aset org-section-numbers
24192 level (1+ (aref org-section-numbers level))))
24193 (setq idx (1+ level))
24194 (while (<= idx depth)
24195 (if (not (= idx 1))
24196 (aset org-section-numbers idx 0))
24197 (setq idx (1+ idx))))
24198 (setq idx 0)
24199 (while (<= idx depth)
24200 (setq n (aref org-section-numbers idx))
24201 (setq string (concat string (if (not (string= string "")) "." "")
24202 (int-to-string n)))
24203 (setq idx (1+ idx)))
24204 (save-match-data
24205 (if (string-match "\\`\\([@0]\\.\\)+" string)
24206 (setq string (replace-match "" t nil string)))
24207 (if (string-match "\\(\\.0\\)+\\'" string)
24208 (setq string (replace-match "" t nil string))))
24209 string))
24211 ;;; ASCII export
24213 (defvar org-last-level nil) ; dynamically scoped variable
24214 (defvar org-min-level nil) ; dynamically scoped variable
24215 (defvar org-levels-open nil) ; dynamically scoped parameter
24216 (defvar org-ascii-current-indentation nil) ; For communication
24218 (defun org-export-as-ascii (arg)
24219 "Export the outline as a pretty ASCII file.
24220 If there is an active region, export only the region.
24221 The prefix ARG specifies how many levels of the outline should become
24222 underlined headlines. The default is 3."
24223 (interactive "P")
24224 (setq-default org-todo-line-regexp org-todo-line-regexp)
24225 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24226 (org-infile-export-plist)))
24227 (region-p (org-region-active-p))
24228 (subtree-p
24229 (when region-p
24230 (save-excursion
24231 (goto-char (region-beginning))
24232 (and (org-at-heading-p)
24233 (>= (org-end-of-subtree t t) (region-end))))))
24234 (custom-times org-display-custom-times)
24235 (org-ascii-current-indentation '(0 . 0))
24236 (level 0) line txt
24237 (umax nil)
24238 (umax-toc nil)
24239 (case-fold-search nil)
24240 (filename (concat (file-name-as-directory
24241 (org-export-directory :ascii opt-plist))
24242 (file-name-sans-extension
24243 (or (and subtree-p
24244 (org-entry-get (region-beginning)
24245 "EXPORT_FILE_NAME" t))
24246 (file-name-nondirectory buffer-file-name)))
24247 ".txt"))
24248 (filename (if (equal (file-truename filename)
24249 (file-truename buffer-file-name))
24250 (concat filename ".txt")
24251 filename))
24252 (buffer (find-file-noselect filename))
24253 (org-levels-open (make-vector org-level-max nil))
24254 (odd org-odd-levels-only)
24255 (date (plist-get opt-plist :date))
24256 (author (plist-get opt-plist :author))
24257 (title (or (and subtree-p (org-export-get-title-from-subtree))
24258 (plist-get opt-plist :title)
24259 (and (not
24260 (plist-get opt-plist :skip-before-1st-heading))
24261 (org-export-grab-title-from-buffer))
24262 (file-name-sans-extension
24263 (file-name-nondirectory buffer-file-name))))
24264 (email (plist-get opt-plist :email))
24265 (language (plist-get opt-plist :language))
24266 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24267 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24268 (todo nil)
24269 (lang-words nil)
24270 (region
24271 (buffer-substring
24272 (if (org-region-active-p) (region-beginning) (point-min))
24273 (if (org-region-active-p) (region-end) (point-max))))
24274 (lines (org-split-string
24275 (org-cleaned-string-for-export
24276 region
24277 :for-ascii t
24278 :skip-before-1st-heading
24279 (plist-get opt-plist :skip-before-1st-heading)
24280 :drawers (plist-get opt-plist :drawers)
24281 :verbatim-multiline t
24282 :archived-trees
24283 (plist-get opt-plist :archived-trees)
24284 :add-text (plist-get opt-plist :text))
24285 "\n"))
24286 thetoc have-headings first-heading-pos
24287 table-open table-buffer)
24289 (let ((inhibit-read-only t))
24290 (org-unmodified
24291 (remove-text-properties (point-min) (point-max)
24292 '(:org-license-to-kill t))))
24294 (setq org-min-level (org-get-min-level lines))
24295 (setq org-last-level org-min-level)
24296 (org-init-section-numbers)
24298 (find-file-noselect filename)
24300 (setq lang-words (or (assoc language org-export-language-setup)
24301 (assoc "en" org-export-language-setup)))
24302 (switch-to-buffer-other-window buffer)
24303 (erase-buffer)
24304 (fundamental-mode)
24305 ;; create local variables for all options, to make sure all called
24306 ;; functions get the correct information
24307 (mapc (lambda (x)
24308 (set (make-local-variable (cdr x))
24309 (plist-get opt-plist (car x))))
24310 org-export-plist-vars)
24311 (org-set-local 'org-odd-levels-only odd)
24312 (setq umax (if arg (prefix-numeric-value arg)
24313 org-export-headline-levels))
24314 (setq umax-toc (if (integerp org-export-with-toc)
24315 (min org-export-with-toc umax)
24316 umax))
24318 ;; File header
24319 (if title (org-insert-centered title ?=))
24320 (insert "\n")
24321 (if (and (or author email)
24322 org-export-author-info)
24323 (insert (concat (nth 1 lang-words) ": " (or author "")
24324 (if email (concat " <" email ">") "")
24325 "\n")))
24327 (cond
24328 ((and date (string-match "%" date))
24329 (setq date (format-time-string date (current-time))))
24330 (date)
24331 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24333 (if (and date org-export-time-stamp-file)
24334 (insert (concat (nth 2 lang-words) ": " date"\n")))
24336 (insert "\n\n")
24338 (if org-export-with-toc
24339 (progn
24340 (push (concat (nth 3 lang-words) "\n") thetoc)
24341 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24342 (mapc '(lambda (line)
24343 (if (string-match org-todo-line-regexp
24344 line)
24345 ;; This is a headline
24346 (progn
24347 (setq have-headings t)
24348 (setq level (- (match-end 1) (match-beginning 1))
24349 level (org-tr-level level)
24350 txt (match-string 3 line)
24351 todo
24352 (or (and org-export-mark-todo-in-toc
24353 (match-beginning 2)
24354 (not (member (match-string 2 line)
24355 org-done-keywords)))
24356 ; TODO, not DONE
24357 (and org-export-mark-todo-in-toc
24358 (= level umax-toc)
24359 (org-search-todo-below
24360 line lines level))))
24361 (setq txt (org-html-expand-for-ascii txt))
24363 (while (string-match org-bracket-link-regexp txt)
24364 (setq txt
24365 (replace-match
24366 (match-string (if (match-end 2) 3 1) txt)
24367 t t txt)))
24369 (if (and (memq org-export-with-tags '(not-in-toc nil))
24370 (string-match
24371 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24372 txt))
24373 (setq txt (replace-match "" t t txt)))
24374 (if (string-match quote-re0 txt)
24375 (setq txt (replace-match "" t t txt)))
24377 (if org-export-with-section-numbers
24378 (setq txt (concat (org-section-number level)
24379 " " txt)))
24380 (if (<= level umax-toc)
24381 (progn
24382 (push
24383 (concat
24384 (make-string
24385 (* (max 0 (- level org-min-level)) 4) ?\ )
24386 (format (if todo "%s (*)\n" "%s\n") txt))
24387 thetoc)
24388 (setq org-last-level level))
24389 ))))
24390 lines)
24391 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24393 (org-init-section-numbers)
24394 (while (setq line (pop lines))
24395 ;; Remove the quoted HTML tags.
24396 (setq line (org-html-expand-for-ascii line))
24397 ;; Remove targets
24398 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24399 (setq line (replace-match "" t t line)))
24400 ;; Replace internal links
24401 (while (string-match org-bracket-link-regexp line)
24402 (setq line (replace-match
24403 (if (match-end 3) "[\\3]" "[\\1]")
24404 t nil line)))
24405 (when custom-times
24406 (setq line (org-translate-time line)))
24407 (cond
24408 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24409 ;; a Headline
24410 (setq first-heading-pos (or first-heading-pos (point)))
24411 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24412 txt (match-string 2 line))
24413 (org-ascii-level-start level txt umax lines))
24415 ((and org-export-with-tables
24416 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24417 (if (not table-open)
24418 ;; New table starts
24419 (setq table-open t table-buffer nil))
24420 ;; Accumulate lines
24421 (setq table-buffer (cons line table-buffer))
24422 (when (or (not lines)
24423 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24424 (car lines))))
24425 (setq table-open nil
24426 table-buffer (nreverse table-buffer))
24427 (insert (mapconcat
24428 (lambda (x)
24429 (org-fix-indentation x org-ascii-current-indentation))
24430 (org-format-table-ascii table-buffer)
24431 "\n") "\n")))
24433 (setq line (org-fix-indentation line org-ascii-current-indentation))
24434 (if (and org-export-with-fixed-width
24435 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24436 (setq line (replace-match "\\1" nil nil line)))
24437 (insert line "\n"))))
24439 (normal-mode)
24441 ;; insert the table of contents
24442 (when thetoc
24443 (goto-char (point-min))
24444 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24445 (progn
24446 (goto-char (match-beginning 0))
24447 (replace-match ""))
24448 (goto-char first-heading-pos))
24449 (mapc 'insert thetoc)
24450 (or (looking-at "[ \t]*\n[ \t]*\n")
24451 (insert "\n\n")))
24453 ;; Convert whitespace place holders
24454 (goto-char (point-min))
24455 (let (beg end)
24456 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24457 (setq end (next-single-property-change beg 'org-whitespace))
24458 (goto-char beg)
24459 (delete-region beg end)
24460 (insert (make-string (- end beg) ?\ ))))
24462 (save-buffer)
24463 ;; remove display and invisible chars
24464 (let (beg end)
24465 (goto-char (point-min))
24466 (while (setq beg (next-single-property-change (point) 'display))
24467 (setq end (next-single-property-change beg 'display))
24468 (delete-region beg end)
24469 (goto-char beg)
24470 (insert "=>"))
24471 (goto-char (point-min))
24472 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24473 (setq end (next-single-property-change beg 'org-cwidth))
24474 (delete-region beg end)
24475 (goto-char beg)))
24476 (goto-char (point-min))))
24478 (defun org-export-ascii-clean-string ()
24479 "Do extra work for ASCII export"
24480 (goto-char (point-min))
24481 (while (re-search-forward org-verbatim-re nil t)
24482 (goto-char (match-end 2))
24483 (backward-delete-char 1) (insert "'")
24484 (goto-char (match-beginning 2))
24485 (delete-char 1) (insert "`")
24486 (goto-char (match-end 2))))
24488 (defun org-search-todo-below (line lines level)
24489 "Search the subtree below LINE for any TODO entries."
24490 (let ((rest (cdr (memq line lines)))
24491 (re org-todo-line-regexp)
24492 line lv todo)
24493 (catch 'exit
24494 (while (setq line (pop rest))
24495 (if (string-match re line)
24496 (progn
24497 (setq lv (- (match-end 1) (match-beginning 1))
24498 todo (and (match-beginning 2)
24499 (not (member (match-string 2 line)
24500 org-done-keywords))))
24501 ; TODO, not DONE
24502 (if (<= lv level) (throw 'exit nil))
24503 (if todo (throw 'exit t))))))))
24505 (defun org-html-expand-for-ascii (line)
24506 "Handle quoted HTML for ASCII export."
24507 (if org-export-html-expand
24508 (while (string-match "@<[^<>\n]*>" line)
24509 ;; We just remove the tags for now.
24510 (setq line (replace-match "" nil nil line))))
24511 line)
24513 (defun org-insert-centered (s &optional underline)
24514 "Insert the string S centered and underline it with character UNDERLINE."
24515 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24516 (insert (make-string ind ?\ ) s "\n")
24517 (if underline
24518 (insert (make-string ind ?\ )
24519 (make-string (string-width s) underline)
24520 "\n"))))
24522 (defun org-ascii-level-start (level title umax &optional lines)
24523 "Insert a new level in ASCII export."
24524 (let (char (n (- level umax 1)) (ind 0))
24525 (if (> level umax)
24526 (progn
24527 (insert (make-string (* 2 n) ?\ )
24528 (char-to-string (nth (% n (length org-export-ascii-bullets))
24529 org-export-ascii-bullets))
24530 " " title "\n")
24531 ;; find the indentation of the next non-empty line
24532 (catch 'stop
24533 (while lines
24534 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24535 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24536 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24537 (pop lines)))
24538 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24539 (if (or (not (equal (char-before) ?\n))
24540 (not (equal (char-before (1- (point))) ?\n)))
24541 (insert "\n"))
24542 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24543 (unless org-export-with-tags
24544 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24545 (setq title (replace-match "" t t title))))
24546 (if org-export-with-section-numbers
24547 (setq title (concat (org-section-number level) " " title)))
24548 (insert title "\n" (make-string (string-width title) char) "\n")
24549 (setq org-ascii-current-indentation '(0 . 0)))))
24551 (defun org-export-visible (type arg)
24552 "Create a copy of the visible part of the current buffer, and export it.
24553 The copy is created in a temporary buffer and removed after use.
24554 TYPE is the final key (as a string) that also select the export command in
24555 the `C-c C-e' export dispatcher.
24556 As a special case, if the you type SPC at the prompt, the temporary
24557 org-mode file will not be removed but presented to you so that you can
24558 continue to use it. The prefix arg ARG is passed through to the exporting
24559 command."
24560 (interactive
24561 (list (progn
24562 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24563 (read-char-exclusive))
24564 current-prefix-arg))
24565 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24566 (error "Invalid export key"))
24567 (let* ((binding (cdr (assoc type
24568 '((?a . org-export-as-ascii)
24569 (?\C-a . org-export-as-ascii)
24570 (?b . org-export-as-html-and-open)
24571 (?\C-b . org-export-as-html-and-open)
24572 (?h . org-export-as-html)
24573 (?H . org-export-as-html-to-buffer)
24574 (?R . org-export-region-as-html)
24575 (?x . org-export-as-xoxo)))))
24576 (keepp (equal type ?\ ))
24577 (file buffer-file-name)
24578 (buffer (get-buffer-create "*Org Export Visible*"))
24579 s e)
24580 ;; Need to hack the drawers here.
24581 (save-excursion
24582 (goto-char (point-min))
24583 (while (re-search-forward org-drawer-regexp nil t)
24584 (goto-char (match-beginning 1))
24585 (or (org-invisible-p) (org-flag-drawer nil))))
24586 (with-current-buffer buffer (erase-buffer))
24587 (save-excursion
24588 (setq s (goto-char (point-min)))
24589 (while (not (= (point) (point-max)))
24590 (goto-char (org-find-invisible))
24591 (append-to-buffer buffer s (point))
24592 (setq s (goto-char (org-find-visible))))
24593 (org-cycle-hide-drawers 'all)
24594 (goto-char (point-min))
24595 (unless keepp
24596 ;; Copy all comment lines to the end, to make sure #+ settings are
24597 ;; still available for the second export step. Kind of a hack, but
24598 ;; does do the trick.
24599 (if (looking-at "#[^\r\n]*")
24600 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24601 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24602 (append-to-buffer buffer (1+ (match-beginning 0))
24603 (min (point-max) (1+ (match-end 0))))))
24604 (set-buffer buffer)
24605 (let ((buffer-file-name file)
24606 (org-inhibit-startup t))
24607 (org-mode)
24608 (show-all)
24609 (unless keepp (funcall binding arg))))
24610 (if (not keepp)
24611 (kill-buffer buffer)
24612 (switch-to-buffer-other-window buffer)
24613 (goto-char (point-min)))))
24615 (defun org-find-visible ()
24616 (let ((s (point)))
24617 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24618 (get-char-property s 'invisible)))
24620 (defun org-find-invisible ()
24621 (let ((s (point)))
24622 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24623 (not (get-char-property s 'invisible))))
24626 ;;; HTML export
24628 (defun org-get-current-options ()
24629 "Return a string with current options as keyword options.
24630 Does include HTML export options as well as TODO and CATEGORY stuff."
24631 (format
24632 "#+TITLE: %s
24633 #+AUTHOR: %s
24634 #+EMAIL: %s
24635 #+LANGUAGE: %s
24636 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24637 #+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
24638 #+CATEGORY: %s
24639 #+SEQ_TODO: %s
24640 #+TYP_TODO: %s
24641 #+PRIORITIES: %c %c %c
24642 #+DRAWERS: %s
24643 #+STARTUP: %s %s %s %s %s
24644 #+TAGS: %s
24645 #+ARCHIVE: %s
24646 #+LINK: %s
24648 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24649 org-export-headline-levels
24650 org-export-with-section-numbers
24651 org-export-with-toc
24652 org-export-preserve-breaks
24653 org-export-html-expand
24654 org-export-with-fixed-width
24655 org-export-with-tables
24656 org-export-with-sub-superscripts
24657 org-export-with-special-strings
24658 org-export-with-footnotes
24659 org-export-with-emphasize
24660 org-export-with-TeX-macros
24661 org-export-with-LaTeX-fragments
24662 org-export-skip-text-before-1st-heading
24663 org-export-with-drawers
24664 org-export-with-tags
24665 (file-name-nondirectory buffer-file-name)
24666 "TODO FEEDBACK VERIFY DONE"
24667 "Me Jason Marie DONE"
24668 org-highest-priority org-lowest-priority org-default-priority
24669 (mapconcat 'identity org-drawers " ")
24670 (cdr (assoc org-startup-folded
24671 '((nil . "showall") (t . "overview") (content . "content"))))
24672 (if org-odd-levels-only "odd" "oddeven")
24673 (if org-hide-leading-stars "hidestars" "showstars")
24674 (if org-startup-align-all-tables "align" "noalign")
24675 (cond ((eq t org-log-done) "logdone")
24676 ((not org-log-done) "nologging")
24677 ((listp org-log-done)
24678 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
24679 org-log-done " ")))
24680 (or (mapconcat (lambda (x)
24681 (cond
24682 ((equal '(:startgroup) x) "{")
24683 ((equal '(:endgroup) x) "}")
24684 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24685 (t (car x))))
24686 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24687 org-archive-location
24688 "org file:~/org/%s.org"
24691 (defun org-insert-export-options-template ()
24692 "Insert into the buffer a template with information for exporting."
24693 (interactive)
24694 (if (not (bolp)) (newline))
24695 (let ((s (org-get-current-options)))
24696 (and (string-match "#\\+CATEGORY" s)
24697 (setq s (substring s 0 (match-beginning 0))))
24698 (insert s)))
24700 (defun org-toggle-fixed-width-section (arg)
24701 "Toggle the fixed-width export.
24702 If there is no active region, the QUOTE keyword at the current headline is
24703 inserted or removed. When present, it causes the text between this headline
24704 and the next to be exported as fixed-width text, and unmodified.
24705 If there is an active region, this command adds or removes a colon as the
24706 first character of this line. If the first character of a line is a colon,
24707 this line is also exported in fixed-width font."
24708 (interactive "P")
24709 (let* ((cc 0)
24710 (regionp (org-region-active-p))
24711 (beg (if regionp (region-beginning) (point)))
24712 (end (if regionp (region-end)))
24713 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24714 (case-fold-search nil)
24715 (re "[ \t]*\\(:\\)")
24716 off)
24717 (if regionp
24718 (save-excursion
24719 (goto-char beg)
24720 (setq cc (current-column))
24721 (beginning-of-line 1)
24722 (setq off (looking-at re))
24723 (while (> nlines 0)
24724 (setq nlines (1- nlines))
24725 (beginning-of-line 1)
24726 (cond
24727 (arg
24728 (move-to-column cc t)
24729 (insert ":\n")
24730 (forward-line -1))
24731 ((and off (looking-at re))
24732 (replace-match "" t t nil 1))
24733 ((not off) (move-to-column cc t) (insert ":")))
24734 (forward-line 1)))
24735 (save-excursion
24736 (org-back-to-heading)
24737 (if (looking-at (concat outline-regexp
24738 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24739 (replace-match "" t t nil 1)
24740 (if (looking-at outline-regexp)
24741 (progn
24742 (goto-char (match-end 0))
24743 (insert org-quote-string " "))))))))
24745 (defun org-export-as-html-and-open (arg)
24746 "Export the outline as HTML and immediately open it with a browser.
24747 If there is an active region, export only the region.
24748 The prefix ARG specifies how many levels of the outline should become
24749 headlines. The default is 3. Lower levels will become bulleted lists."
24750 (interactive "P")
24751 (org-export-as-html arg 'hidden)
24752 (org-open-file buffer-file-name))
24754 (defun org-export-as-html-batch ()
24755 "Call `org-export-as-html', may be used in batch processing as
24756 emacs --batch
24757 --load=$HOME/lib/emacs/org.el
24758 --eval \"(setq org-export-headline-levels 2)\"
24759 --visit=MyFile --funcall org-export-as-html-batch"
24760 (org-export-as-html org-export-headline-levels 'hidden))
24762 (defun org-export-as-html-to-buffer (arg)
24763 "Call `org-exort-as-html` with output to a temporary buffer.
24764 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24765 (interactive "P")
24766 (org-export-as-html arg nil nil "*Org HTML Export*")
24767 (switch-to-buffer-other-window "*Org HTML Export*"))
24769 (defun org-replace-region-by-html (beg end)
24770 "Assume the current region has org-mode syntax, and convert it to HTML.
24771 This can be used in any buffer. For example, you could write an
24772 itemized list in org-mode syntax in an HTML buffer and then use this
24773 command to convert it."
24774 (interactive "r")
24775 (let (reg html buf pop-up-frames)
24776 (save-window-excursion
24777 (if (org-mode-p)
24778 (setq html (org-export-region-as-html
24779 beg end t 'string))
24780 (setq reg (buffer-substring beg end)
24781 buf (get-buffer-create "*Org tmp*"))
24782 (with-current-buffer buf
24783 (erase-buffer)
24784 (insert reg)
24785 (org-mode)
24786 (setq html (org-export-region-as-html
24787 (point-min) (point-max) t 'string)))
24788 (kill-buffer buf)))
24789 (delete-region beg end)
24790 (insert html)))
24792 (defun org-export-region-as-html (beg end &optional body-only buffer)
24793 "Convert region from BEG to END in org-mode buffer to HTML.
24794 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24795 contents, and only produce the region of converted text, useful for
24796 cut-and-paste operations.
24797 If BUFFER is a buffer or a string, use/create that buffer as a target
24798 of the converted HTML. If BUFFER is the symbol `string', return the
24799 produced HTML as a string and leave not buffer behind. For example,
24800 a Lisp program could call this function in the following way:
24802 (setq html (org-export-region-as-html beg end t 'string))
24804 When called interactively, the output buffer is selected, and shown
24805 in a window. A non-interactive call will only retunr the buffer."
24806 (interactive "r\nP")
24807 (when (interactive-p)
24808 (setq buffer "*Org HTML Export*"))
24809 (let ((transient-mark-mode t) (zmacs-regions t)
24810 rtn)
24811 (goto-char end)
24812 (set-mark (point)) ;; to activate the region
24813 (goto-char beg)
24814 (setq rtn (org-export-as-html
24815 nil nil nil
24816 buffer body-only))
24817 (if (fboundp 'deactivate-mark) (deactivate-mark))
24818 (if (and (interactive-p) (bufferp rtn))
24819 (switch-to-buffer-other-window rtn)
24820 rtn)))
24822 (defvar html-table-tag nil) ; dynamically scoped into this.
24823 (defun org-export-as-html (arg &optional hidden ext-plist
24824 to-buffer body-only)
24825 "Export the outline as a pretty HTML file.
24826 If there is an active region, export only the region. The prefix
24827 ARG specifies how many levels of the outline should become
24828 headlines. The default is 3. Lower levels will become bulleted
24829 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24830 EXT-PLIST is a property list with external parameters overriding
24831 org-mode's default settings, but still inferior to file-local
24832 settings. When TO-BUFFER is non-nil, create a buffer with that
24833 name and export to that buffer. If TO-BUFFER is the symbol `string',
24834 don't leave any buffer behind but just return the resulting HTML as
24835 a string. When BODY-ONLY is set, don't produce the file header and footer,
24836 simply return the content of <body>...</body>, without even
24837 the body tags themselves."
24838 (interactive "P")
24840 ;; Make sure we have a file name when we need it.
24841 (when (and (not (or to-buffer body-only))
24842 (not buffer-file-name))
24843 (if (buffer-base-buffer)
24844 (org-set-local 'buffer-file-name
24845 (with-current-buffer (buffer-base-buffer)
24846 buffer-file-name))
24847 (error "Need a file name to be able to export.")))
24849 (message "Exporting...")
24850 (setq-default org-todo-line-regexp org-todo-line-regexp)
24851 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24852 (setq-default org-done-keywords org-done-keywords)
24853 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24854 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24855 ext-plist
24856 (org-infile-export-plist)))
24858 (style (plist-get opt-plist :style))
24859 (html-extension (plist-get opt-plist :html-extension))
24860 (link-validate (plist-get opt-plist :link-validation-function))
24861 valid thetoc have-headings first-heading-pos
24862 (odd org-odd-levels-only)
24863 (region-p (org-region-active-p))
24864 (subtree-p
24865 (when region-p
24866 (save-excursion
24867 (goto-char (region-beginning))
24868 (and (org-at-heading-p)
24869 (>= (org-end-of-subtree t t) (region-end))))))
24870 ;; The following two are dynamically scoped into other
24871 ;; routines below.
24872 (org-current-export-dir (org-export-directory :html opt-plist))
24873 (org-current-export-file buffer-file-name)
24874 (level 0) (line "") (origline "") txt todo
24875 (umax nil)
24876 (umax-toc nil)
24877 (filename (if to-buffer nil
24878 (expand-file-name
24879 (concat
24880 (file-name-sans-extension
24881 (or (and subtree-p
24882 (org-entry-get (region-beginning)
24883 "EXPORT_FILE_NAME" t))
24884 (file-name-nondirectory buffer-file-name)))
24885 "." html-extension)
24886 (file-name-as-directory
24887 (org-export-directory :html opt-plist)))))
24888 (current-dir (if buffer-file-name
24889 (file-name-directory buffer-file-name)
24890 default-directory))
24891 (buffer (if to-buffer
24892 (cond
24893 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24894 (t (get-buffer-create to-buffer)))
24895 (find-file-noselect filename)))
24896 (org-levels-open (make-vector org-level-max nil))
24897 (date (plist-get opt-plist :date))
24898 (author (plist-get opt-plist :author))
24899 (title (or (and subtree-p (org-export-get-title-from-subtree))
24900 (plist-get opt-plist :title)
24901 (and (not
24902 (plist-get opt-plist :skip-before-1st-heading))
24903 (org-export-grab-title-from-buffer))
24904 (and buffer-file-name
24905 (file-name-sans-extension
24906 (file-name-nondirectory buffer-file-name)))
24907 "UNTITLED"))
24908 (html-table-tag (plist-get opt-plist :html-table-tag))
24909 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24910 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24911 (inquote nil)
24912 (infixed nil)
24913 (in-local-list nil)
24914 (local-list-num nil)
24915 (local-list-indent nil)
24916 (llt org-plain-list-ordered-item-terminator)
24917 (email (plist-get opt-plist :email))
24918 (language (plist-get opt-plist :language))
24919 (lang-words nil)
24920 (target-alist nil) tg
24921 (head-count 0) cnt
24922 (start 0)
24923 (coding-system (and (boundp 'buffer-file-coding-system)
24924 buffer-file-coding-system))
24925 (coding-system-for-write (or org-export-html-coding-system
24926 coding-system))
24927 (save-buffer-coding-system (or org-export-html-coding-system
24928 coding-system))
24929 (charset (and coding-system-for-write
24930 (fboundp 'coding-system-get)
24931 (coding-system-get coding-system-for-write
24932 'mime-charset)))
24933 (region
24934 (buffer-substring
24935 (if region-p (region-beginning) (point-min))
24936 (if region-p (region-end) (point-max))))
24937 (lines
24938 (org-split-string
24939 (org-cleaned-string-for-export
24940 region
24941 :emph-multiline t
24942 :for-html t
24943 :skip-before-1st-heading
24944 (plist-get opt-plist :skip-before-1st-heading)
24945 :drawers (plist-get opt-plist :drawers)
24946 :archived-trees
24947 (plist-get opt-plist :archived-trees)
24948 :add-text
24949 (plist-get opt-plist :text)
24950 :LaTeX-fragments
24951 (plist-get opt-plist :LaTeX-fragments))
24952 "[\r\n]"))
24953 table-open type
24954 table-buffer table-orig-buffer
24955 ind start-is-num starter didclose
24956 rpl path desc descp desc1 desc2 link
24959 (let ((inhibit-read-only t))
24960 (org-unmodified
24961 (remove-text-properties (point-min) (point-max)
24962 '(:org-license-to-kill t))))
24964 (message "Exporting...")
24966 (setq org-min-level (org-get-min-level lines))
24967 (setq org-last-level org-min-level)
24968 (org-init-section-numbers)
24970 (cond
24971 ((and date (string-match "%" date))
24972 (setq date (format-time-string date (current-time))))
24973 (date)
24974 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24976 ;; Get the language-dependent settings
24977 (setq lang-words (or (assoc language org-export-language-setup)
24978 (assoc "en" org-export-language-setup)))
24980 ;; Switch to the output buffer
24981 (set-buffer buffer)
24982 (let ((inhibit-read-only t)) (erase-buffer))
24983 (fundamental-mode)
24985 (and (fboundp 'set-buffer-file-coding-system)
24986 (set-buffer-file-coding-system coding-system-for-write))
24988 (let ((case-fold-search nil)
24989 (org-odd-levels-only odd))
24990 ;; create local variables for all options, to make sure all called
24991 ;; functions get the correct information
24992 (mapc (lambda (x)
24993 (set (make-local-variable (cdr x))
24994 (plist-get opt-plist (car x))))
24995 org-export-plist-vars)
24996 (setq umax (if arg (prefix-numeric-value arg)
24997 org-export-headline-levels))
24998 (setq umax-toc (if (integerp org-export-with-toc)
24999 (min org-export-with-toc umax)
25000 umax))
25001 (unless body-only
25002 ;; File header
25003 (insert (format
25004 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25005 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25006 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25007 lang=\"%s\" xml:lang=\"%s\">
25008 <head>
25009 <title>%s</title>
25010 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25011 <meta name=\"generator\" content=\"Org-mode\"/>
25012 <meta name=\"generated\" content=\"%s\"/>
25013 <meta name=\"author\" content=\"%s\"/>
25015 </head><body>
25017 language language (org-html-expand title)
25018 (or charset "iso-8859-1") date author style))
25020 (insert (or (plist-get opt-plist :preamble) ""))
25022 (when (plist-get opt-plist :auto-preamble)
25023 (if title (insert (format org-export-html-title-format
25024 (org-html-expand title))))))
25026 (if (and org-export-with-toc (not body-only))
25027 (progn
25028 (push (format "<h%d>%s</h%d>\n"
25029 org-export-html-toplevel-hlevel
25030 (nth 3 lang-words)
25031 org-export-html-toplevel-hlevel)
25032 thetoc)
25033 (push "<ul>\n<li>" thetoc)
25034 (setq lines
25035 (mapcar '(lambda (line)
25036 (if (string-match org-todo-line-regexp line)
25037 ;; This is a headline
25038 (progn
25039 (setq have-headings t)
25040 (setq level (- (match-end 1) (match-beginning 1))
25041 level (org-tr-level level)
25042 txt (save-match-data
25043 (org-html-expand
25044 (org-export-cleanup-toc-line
25045 (match-string 3 line))))
25046 todo
25047 (or (and org-export-mark-todo-in-toc
25048 (match-beginning 2)
25049 (not (member (match-string 2 line)
25050 org-done-keywords)))
25051 ; TODO, not DONE
25052 (and org-export-mark-todo-in-toc
25053 (= level umax-toc)
25054 (org-search-todo-below
25055 line lines level))))
25056 (if (string-match
25057 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25058 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25059 (if (string-match quote-re0 txt)
25060 (setq txt (replace-match "" t t txt)))
25061 (if org-export-with-section-numbers
25062 (setq txt (concat (org-section-number level)
25063 " " txt)))
25064 (if (<= level (max umax umax-toc))
25065 (setq head-count (+ head-count 1)))
25066 (if (<= level umax-toc)
25067 (progn
25068 (if (> level org-last-level)
25069 (progn
25070 (setq cnt (- level org-last-level))
25071 (while (>= (setq cnt (1- cnt)) 0)
25072 (push "\n<ul>\n<li>" thetoc))
25073 (push "\n" thetoc)))
25074 (if (< level org-last-level)
25075 (progn
25076 (setq cnt (- org-last-level level))
25077 (while (>= (setq cnt (1- cnt)) 0)
25078 (push "</li>\n</ul>" thetoc))
25079 (push "\n" thetoc)))
25080 ;; Check for targets
25081 (while (string-match org-target-regexp line)
25082 (setq tg (match-string 1 line)
25083 line (replace-match
25084 (concat "@<span class=\"target\">" tg "@</span> ")
25085 t t line))
25086 (push (cons (org-solidify-link-text tg)
25087 (format "sec-%d" head-count))
25088 target-alist))
25089 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25090 (setq txt (replace-match "" t t txt)))
25091 (push
25092 (format
25093 (if todo
25094 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25095 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25096 head-count txt) thetoc)
25098 (setq org-last-level level))
25100 line)
25101 lines))
25102 (while (> org-last-level (1- org-min-level))
25103 (setq org-last-level (1- org-last-level))
25104 (push "</li>\n</ul>\n" thetoc))
25105 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25107 (setq head-count 0)
25108 (org-init-section-numbers)
25110 (while (setq line (pop lines) origline line)
25111 (catch 'nextline
25113 ;; end of quote section?
25114 (when (and inquote (string-match "^\\*+ " line))
25115 (insert "</pre>\n")
25116 (setq inquote nil))
25117 ;; inside a quote section?
25118 (when inquote
25119 (insert (org-html-protect line) "\n")
25120 (throw 'nextline nil))
25122 ;; verbatim lines
25123 (when (and org-export-with-fixed-width
25124 (string-match "^[ \t]*:\\(.*\\)" line))
25125 (when (not infixed)
25126 (setq infixed t)
25127 (insert "<pre>\n"))
25128 (insert (org-html-protect (match-string 1 line)) "\n")
25129 (when (and lines
25130 (not (string-match "^[ \t]*\\(:.*\\)"
25131 (car lines))))
25132 (setq infixed nil)
25133 (insert "</pre>\n"))
25134 (throw 'nextline nil))
25136 ;; Protected HTML
25137 (when (get-text-property 0 'org-protected line)
25138 (let (par)
25139 (when (re-search-backward
25140 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25141 (setq par (match-string 1))
25142 (replace-match "\\2\n"))
25143 (insert line "\n")
25144 (while (and lines
25145 (or (= (length (car lines)) 0)
25146 (get-text-property 0 'org-protected (car lines))))
25147 (insert (pop lines) "\n"))
25148 (and par (insert "<p>\n")))
25149 (throw 'nextline nil))
25151 ;; Horizontal line
25152 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25153 (insert "\n<hr/>\n")
25154 (throw 'nextline nil))
25156 ;; make targets to anchors
25157 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25158 (cond
25159 ((match-end 2)
25160 (setq line (replace-match
25161 (concat "@<a name=\""
25162 (org-solidify-link-text (match-string 1 line))
25163 "\">\\nbsp@</a>")
25164 t t line)))
25165 ((and org-export-with-toc (equal (string-to-char line) ?*))
25166 (setq line (replace-match
25167 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25168 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25169 t t line)))
25171 (setq line (replace-match
25172 (concat "@<a name=\""
25173 (org-solidify-link-text (match-string 1 line))
25174 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25175 t t line)))))
25177 (setq line (org-html-handle-time-stamps line))
25179 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25180 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25181 ;; Also handle sub_superscripts and checkboxes
25182 (or (string-match org-table-hline-regexp line)
25183 (setq line (org-html-expand line)))
25185 ;; Format the links
25186 (setq start 0)
25187 (while (string-match org-bracket-link-analytic-regexp line start)
25188 (setq start (match-beginning 0))
25189 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25190 (setq path (match-string 3 line))
25191 (setq desc1 (if (match-end 5) (match-string 5 line))
25192 desc2 (if (match-end 2) (concat type ":" path) path)
25193 descp (and desc1 (not (equal desc1 desc2)))
25194 desc (or desc1 desc2))
25195 ;; Make an image out of the description if that is so wanted
25196 (when (and descp (org-file-image-p desc))
25197 (save-match-data
25198 (if (string-match "^file:" desc)
25199 (setq desc (substring desc (match-end 0)))))
25200 (setq desc (concat "<img src=\"" desc "\"/>")))
25201 ;; FIXME: do we need to unescape here somewhere?
25202 (cond
25203 ((equal type "internal")
25204 (setq rpl
25205 (concat
25206 "<a href=\"#"
25207 (org-solidify-link-text
25208 (save-match-data (org-link-unescape path)) target-alist)
25209 "\">" desc "</a>")))
25210 ((member type '("http" "https"))
25211 ;; standard URL, just check if we need to inline an image
25212 (if (and (or (eq t org-export-html-inline-images)
25213 (and org-export-html-inline-images (not descp)))
25214 (org-file-image-p path))
25215 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25216 (setq link (concat type ":" path))
25217 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25218 ((member type '("ftp" "mailto" "news"))
25219 ;; standard URL
25220 (setq link (concat type ":" path))
25221 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25222 ((string= type "file")
25223 ;; FILE link
25224 (let* ((filename path)
25225 (abs-p (file-name-absolute-p filename))
25226 thefile file-is-image-p search)
25227 (save-match-data
25228 (if (string-match "::\\(.*\\)" filename)
25229 (setq search (match-string 1 filename)
25230 filename (replace-match "" t nil filename)))
25231 (setq valid
25232 (if (functionp link-validate)
25233 (funcall link-validate filename current-dir)
25235 (setq file-is-image-p (org-file-image-p filename))
25236 (setq thefile (if abs-p (expand-file-name filename) filename))
25237 (when (and org-export-html-link-org-files-as-html
25238 (string-match "\\.org$" thefile))
25239 (setq thefile (concat (substring thefile 0
25240 (match-beginning 0))
25241 "." html-extension))
25242 (if (and search
25243 ;; make sure this is can be used as target search
25244 (not (string-match "^[0-9]*$" search))
25245 (not (string-match "^\\*" search))
25246 (not (string-match "^/.*/$" search)))
25247 (setq thefile (concat thefile "#"
25248 (org-solidify-link-text
25249 (org-link-unescape search)))))
25250 (when (string-match "^file:" desc)
25251 (setq desc (replace-match "" t t desc))
25252 (if (string-match "\\.org$" desc)
25253 (setq desc (replace-match "" t t desc))))))
25254 (setq rpl (if (and file-is-image-p
25255 (or (eq t org-export-html-inline-images)
25256 (and org-export-html-inline-images
25257 (not descp))))
25258 (concat "<img src=\"" thefile "\"/>")
25259 (concat "<a href=\"" thefile "\">" desc "</a>")))
25260 (if (not valid) (setq rpl desc))))
25261 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25262 (setq rpl (concat "<i>&lt;" type ":"
25263 (save-match-data (org-link-unescape path))
25264 "&gt;</i>"))))
25265 (setq line (replace-match rpl t t line)
25266 start (+ start (length rpl))))
25268 ;; TODO items
25269 (if (and (string-match org-todo-line-regexp line)
25270 (match-beginning 2))
25272 (setq line
25273 (concat (substring line 0 (match-beginning 2))
25274 "<span class=\""
25275 (if (member (match-string 2 line)
25276 org-done-keywords)
25277 "done" "todo")
25278 "\">" (match-string 2 line)
25279 "</span>" (substring line (match-end 2)))))
25281 ;; Does this contain a reference to a footnote?
25282 (when org-export-with-footnotes
25283 (setq start 0)
25284 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25285 (if (get-text-property (match-beginning 2) 'org-protected line)
25286 (setq start (match-end 2))
25287 (let ((n (match-string 2 line)))
25288 (setq line
25289 (replace-match
25290 (format
25291 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25292 (match-string 1 line) n n n)
25293 t t line))))))
25295 (cond
25296 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25297 ;; This is a headline
25298 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25299 txt (match-string 2 line))
25300 (if (string-match quote-re0 txt)
25301 (setq txt (replace-match "" t t txt)))
25302 (if (<= level (max umax umax-toc))
25303 (setq head-count (+ head-count 1)))
25304 (when in-local-list
25305 ;; Close any local lists before inserting a new header line
25306 (while local-list-num
25307 (org-close-li)
25308 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25309 (pop local-list-num))
25310 (setq local-list-indent nil
25311 in-local-list nil))
25312 (setq first-heading-pos (or first-heading-pos (point)))
25313 (org-html-level-start level txt umax
25314 (and org-export-with-toc (<= level umax))
25315 head-count)
25316 ;; QUOTES
25317 (when (string-match quote-re line)
25318 (insert "<pre>")
25319 (setq inquote t)))
25321 ((and org-export-with-tables
25322 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25323 (if (not table-open)
25324 ;; New table starts
25325 (setq table-open t table-buffer nil table-orig-buffer nil))
25326 ;; Accumulate lines
25327 (setq table-buffer (cons line table-buffer)
25328 table-orig-buffer (cons origline table-orig-buffer))
25329 (when (or (not lines)
25330 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25331 (car lines))))
25332 (setq table-open nil
25333 table-buffer (nreverse table-buffer)
25334 table-orig-buffer (nreverse table-orig-buffer))
25335 (org-close-par-maybe)
25336 (insert (org-format-table-html table-buffer table-orig-buffer))))
25338 ;; Normal lines
25339 (when (string-match
25340 (cond
25341 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25342 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25343 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25344 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25345 line)
25346 (setq ind (org-get-string-indentation line)
25347 start-is-num (match-beginning 4)
25348 starter (if (match-beginning 2)
25349 (substring (match-string 2 line) 0 -1))
25350 line (substring line (match-beginning 5)))
25351 (unless (string-match "[^ \t]" line)
25352 ;; empty line. Pretend indentation is large.
25353 (setq ind (if org-empty-line-terminates-plain-lists
25355 (1+ (or (car local-list-indent) 1)))))
25356 (setq didclose nil)
25357 (while (and in-local-list
25358 (or (and (= ind (car local-list-indent))
25359 (not starter))
25360 (< ind (car local-list-indent))))
25361 (setq didclose t)
25362 (org-close-li)
25363 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25364 (pop local-list-num) (pop local-list-indent)
25365 (setq in-local-list local-list-indent))
25366 (cond
25367 ((and starter
25368 (or (not in-local-list)
25369 (> ind (car local-list-indent))))
25370 ;; Start new (level of) list
25371 (org-close-par-maybe)
25372 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25373 (push start-is-num local-list-num)
25374 (push ind local-list-indent)
25375 (setq in-local-list t))
25376 (starter
25377 ;; continue current list
25378 (org-close-li)
25379 (insert "<li>\n"))
25380 (didclose
25381 ;; we did close a list, normal text follows: need <p>
25382 (org-open-par)))
25383 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25384 (setq line
25385 (replace-match
25386 (if (equal (match-string 1 line) "X")
25387 "<b>[X]</b>"
25388 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25389 t t line))))
25391 ;; Empty lines start a new paragraph. If hand-formatted lists
25392 ;; are not fully interpreted, lines starting with "-", "+", "*"
25393 ;; also start a new paragraph.
25394 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25396 ;; Is this the start of a footnote?
25397 (when org-export-with-footnotes
25398 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25399 (org-close-par-maybe)
25400 (let ((n (match-string 1 line)))
25401 (setq line (replace-match
25402 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25404 ;; Check if the line break needs to be conserved
25405 (cond
25406 ((string-match "\\\\\\\\[ \t]*$" line)
25407 (setq line (replace-match "<br/>" t t line)))
25408 (org-export-preserve-breaks
25409 (setq line (concat line "<br/>"))))
25411 (insert line "\n")))))
25413 ;; Properly close all local lists and other lists
25414 (when inquote (insert "</pre>\n"))
25415 (when in-local-list
25416 ;; Close any local lists before inserting a new header line
25417 (while local-list-num
25418 (org-close-li)
25419 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25420 (pop local-list-num))
25421 (setq local-list-indent nil
25422 in-local-list nil))
25423 (org-html-level-start 1 nil umax
25424 (and org-export-with-toc (<= level umax))
25425 head-count)
25427 (unless body-only
25428 (when (plist-get opt-plist :auto-postamble)
25429 (insert "<div id=\"postamble\">")
25430 (when (and org-export-author-info author)
25431 (insert "<p class=\"author\"> "
25432 (nth 1 lang-words) ": " author "\n")
25433 (when email
25434 (if (listp (split-string email ",+ *"))
25435 (mapc (lambda(e)
25436 (insert "<a href=\"mailto:" e "\">&lt;"
25437 e "&gt;</a>\n"))
25438 (split-string email ",+ *"))
25439 (insert "<a href=\"mailto:" email "\">&lt;"
25440 email "&gt;</a>\n")))
25441 (insert "</p>\n"))
25442 (when (and date org-export-time-stamp-file)
25443 (insert "<p class=\"date\"> "
25444 (nth 2 lang-words) ": "
25445 date "</p>\n"))
25446 (insert "</div>"))
25448 (if org-export-html-with-timestamp
25449 (insert org-export-html-html-helper-timestamp))
25450 (insert (or (plist-get opt-plist :postamble) ""))
25451 (insert "</body>\n</html>\n"))
25453 (normal-mode)
25454 (if (eq major-mode default-major-mode) (html-mode))
25456 ;; insert the table of contents
25457 (goto-char (point-min))
25458 (when thetoc
25459 (if (or (re-search-forward
25460 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25461 (re-search-forward
25462 "\\[TABLE-OF-CONTENTS\\]" nil t))
25463 (progn
25464 (goto-char (match-beginning 0))
25465 (replace-match ""))
25466 (goto-char first-heading-pos)
25467 (when (looking-at "\\s-*</p>")
25468 (goto-char (match-end 0))
25469 (insert "\n")))
25470 (insert "<div id=\"table-of-contents\">\n")
25471 (mapc 'insert thetoc)
25472 (insert "</div>\n"))
25473 ;; remove empty paragraphs and lists
25474 (goto-char (point-min))
25475 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25476 (replace-match ""))
25477 (goto-char (point-min))
25478 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25479 (replace-match ""))
25480 ;; Convert whitespace place holders
25481 (goto-char (point-min))
25482 (let (beg end n)
25483 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25484 (setq n (get-text-property beg 'org-whitespace)
25485 end (next-single-property-change beg 'org-whitespace))
25486 (goto-char beg)
25487 (delete-region beg end)
25488 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25489 (make-string n ?x)))))
25491 (or to-buffer (save-buffer))
25492 (goto-char (point-min))
25493 (message "Exporting... done")
25494 (if (eq to-buffer 'string)
25495 (prog1 (buffer-substring (point-min) (point-max))
25496 (kill-buffer (current-buffer)))
25497 (current-buffer)))))
25499 (defvar org-table-colgroup-info nil)
25500 (defun org-format-table-ascii (lines)
25501 "Format a table for ascii export."
25502 (if (stringp lines)
25503 (setq lines (org-split-string lines "\n")))
25504 (if (not (string-match "^[ \t]*|" (car lines)))
25505 ;; Table made by table.el - test for spanning
25506 lines
25508 ;; A normal org table
25509 ;; Get rid of hlines at beginning and end
25510 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25511 (setq lines (nreverse lines))
25512 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25513 (setq lines (nreverse lines))
25514 (when org-export-table-remove-special-lines
25515 ;; Check if the table has a marking column. If yes remove the
25516 ;; column and the special lines
25517 (setq lines (org-table-clean-before-export lines)))
25518 ;; Get rid of the vertical lines except for grouping
25519 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25520 rtn line vl1 start)
25521 (while (setq line (pop lines))
25522 (if (string-match org-table-hline-regexp line)
25523 (and (string-match "|\\(.*\\)|" line)
25524 (setq line (replace-match " \\1" t nil line)))
25525 (setq start 0 vl1 vl)
25526 (while (string-match "|" line start)
25527 (setq start (match-end 0))
25528 (or (pop vl1) (setq line (replace-match " " t t line)))))
25529 (push line rtn))
25530 (nreverse rtn))))
25532 (defun org-colgroup-info-to-vline-list (info)
25533 (let (vl new last)
25534 (while info
25535 (setq last new new (pop info))
25536 (if (or (memq last '(:end :startend))
25537 (memq new '(:start :startend)))
25538 (push t vl)
25539 (push nil vl)))
25540 (setq vl (nreverse vl))
25541 (and vl (setcar vl nil))
25542 vl))
25544 (defun org-format-table-html (lines olines)
25545 "Find out which HTML converter to use and return the HTML code."
25546 (if (stringp lines)
25547 (setq lines (org-split-string lines "\n")))
25548 (if (string-match "^[ \t]*|" (car lines))
25549 ;; A normal org table
25550 (org-format-org-table-html lines)
25551 ;; Table made by table.el - test for spanning
25552 (let* ((hlines (delq nil (mapcar
25553 (lambda (x)
25554 (if (string-match "^[ \t]*\\+-" x) x
25555 nil))
25556 lines)))
25557 (first (car hlines))
25558 (ll (and (string-match "\\S-+" first)
25559 (match-string 0 first)))
25560 (re (concat "^[ \t]*" (regexp-quote ll)))
25561 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25562 hlines))))
25563 (if (and (not spanning)
25564 (not org-export-prefer-native-exporter-for-tables))
25565 ;; We can use my own converter with HTML conversions
25566 (org-format-table-table-html lines)
25567 ;; Need to use the code generator in table.el, with the original text.
25568 (org-format-table-table-html-using-table-generate-source olines)))))
25570 (defun org-format-org-table-html (lines &optional splice)
25571 "Format a table into HTML."
25572 ;; Get rid of hlines at beginning and end
25573 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25574 (setq lines (nreverse lines))
25575 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25576 (setq lines (nreverse lines))
25577 (when org-export-table-remove-special-lines
25578 ;; Check if the table has a marking column. If yes remove the
25579 ;; column and the special lines
25580 (setq lines (org-table-clean-before-export lines)))
25582 (let ((head (and org-export-highlight-first-table-line
25583 (delq nil (mapcar
25584 (lambda (x) (string-match "^[ \t]*|-" x))
25585 (cdr lines)))))
25586 (nlines 0) fnum i
25587 tbopen line fields html gr colgropen)
25588 (if splice (setq head nil))
25589 (unless splice (push (if head "<thead>" "<tbody>") html))
25590 (setq tbopen t)
25591 (while (setq line (pop lines))
25592 (catch 'next-line
25593 (if (string-match "^[ \t]*|-" line)
25594 (progn
25595 (unless splice
25596 (push (if head "</thead>" "</tbody>") html)
25597 (if lines (push "<tbody>" html) (setq tbopen nil)))
25598 (setq head nil) ;; head ends here, first time around
25599 ;; ignore this line
25600 (throw 'next-line t)))
25601 ;; Break the line into fields
25602 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25603 (unless fnum (setq fnum (make-vector (length fields) 0)))
25604 (setq nlines (1+ nlines) i -1)
25605 (push (concat "<tr>"
25606 (mapconcat
25607 (lambda (x)
25608 (setq i (1+ i))
25609 (if (and (< i nlines)
25610 (string-match org-table-number-regexp x))
25611 (incf (aref fnum i)))
25612 (if head
25613 (concat (car org-export-table-header-tags) x
25614 (cdr org-export-table-header-tags))
25615 (concat (car org-export-table-data-tags) x
25616 (cdr org-export-table-data-tags))))
25617 fields "")
25618 "</tr>")
25619 html)))
25620 (unless splice (if tbopen (push "</tbody>" html)))
25621 (unless splice (push "</table>\n" html))
25622 (setq html (nreverse html))
25623 (unless splice
25624 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25625 (push (mapconcat
25626 (lambda (x)
25627 (setq gr (pop org-table-colgroup-info))
25628 (format "%s<col align=\"%s\"></col>%s"
25629 (if (memq gr '(:start :startend))
25630 (prog1
25631 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25632 (setq colgropen t))
25634 (if (> (/ (float x) nlines) org-table-number-fraction)
25635 "right" "left")
25636 (if (memq gr '(:end :startend))
25637 (progn (setq colgropen nil) "</colgroup>")
25638 "")))
25639 fnum "")
25640 html)
25641 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25642 (push html-table-tag html))
25643 (concat (mapconcat 'identity html "\n") "\n")))
25645 (defun org-table-clean-before-export (lines)
25646 "Check if the table has a marking column.
25647 If yes remove the column and the special lines."
25648 (setq org-table-colgroup-info nil)
25649 (if (memq nil
25650 (mapcar
25651 (lambda (x) (or (string-match "^[ \t]*|-" x)
25652 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25653 lines))
25654 (progn
25655 (setq org-table-clean-did-remove-column nil)
25656 (delq nil
25657 (mapcar
25658 (lambda (x)
25659 (cond
25660 ((string-match "^[ \t]*| */ *|" x)
25661 (setq org-table-colgroup-info
25662 (mapcar (lambda (x)
25663 (cond ((member x '("<" "&lt;")) :start)
25664 ((member x '(">" "&gt;")) :end)
25665 ((member x '("<>" "&lt;&gt;")) :startend)
25666 (t nil)))
25667 (org-split-string x "[ \t]*|[ \t]*")))
25668 nil)
25669 (t x)))
25670 lines)))
25671 (setq org-table-clean-did-remove-column t)
25672 (delq nil
25673 (mapcar
25674 (lambda (x)
25675 (cond
25676 ((string-match "^[ \t]*| */ *|" x)
25677 (setq org-table-colgroup-info
25678 (mapcar (lambda (x)
25679 (cond ((member x '("<" "&lt;")) :start)
25680 ((member x '(">" "&gt;")) :end)
25681 ((member x '("<>" "&lt;&gt;")) :startend)
25682 (t nil)))
25683 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25684 nil)
25685 ((string-match "^[ \t]*| *[!_^/] *|" x)
25686 nil) ; ignore this line
25687 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25688 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25689 ;; remove the first column
25690 (replace-match "\\1|" t nil x))))
25691 lines))))
25693 (defun org-format-table-table-html (lines)
25694 "Format a table generated by table.el into HTML.
25695 This conversion does *not* use `table-generate-source' from table.el.
25696 This has the advantage that Org-mode's HTML conversions can be used.
25697 But it has the disadvantage, that no cell- or row-spanning is allowed."
25698 (let (line field-buffer
25699 (head org-export-highlight-first-table-line)
25700 fields html empty)
25701 (setq html (concat html-table-tag "\n"))
25702 (while (setq line (pop lines))
25703 (setq empty "&nbsp;")
25704 (catch 'next-line
25705 (if (string-match "^[ \t]*\\+-" line)
25706 (progn
25707 (if field-buffer
25708 (progn
25709 (setq
25710 html
25711 (concat
25712 html
25713 "<tr>"
25714 (mapconcat
25715 (lambda (x)
25716 (if (equal x "") (setq x empty))
25717 (if head
25718 (concat (car org-export-table-header-tags) x
25719 (cdr org-export-table-header-tags))
25720 (concat (car org-export-table-data-tags) x
25721 (cdr org-export-table-data-tags))))
25722 field-buffer "\n")
25723 "</tr>\n"))
25724 (setq head nil)
25725 (setq field-buffer nil)))
25726 ;; Ignore this line
25727 (throw 'next-line t)))
25728 ;; Break the line into fields and store the fields
25729 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25730 (if field-buffer
25731 (setq field-buffer (mapcar
25732 (lambda (x)
25733 (concat x "<br/>" (pop fields)))
25734 field-buffer))
25735 (setq field-buffer fields))))
25736 (setq html (concat html "</table>\n"))
25737 html))
25739 (defun org-format-table-table-html-using-table-generate-source (lines)
25740 "Format a table into html, using `table-generate-source' from table.el.
25741 This has the advantage that cell- or row-spanning is allowed.
25742 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25743 (require 'table)
25744 (with-current-buffer (get-buffer-create " org-tmp1 ")
25745 (erase-buffer)
25746 (insert (mapconcat 'identity lines "\n"))
25747 (goto-char (point-min))
25748 (if (not (re-search-forward "|[^+]" nil t))
25749 (error "Error processing table"))
25750 (table-recognize-table)
25751 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25752 (table-generate-source 'html " org-tmp2 ")
25753 (set-buffer " org-tmp2 ")
25754 (buffer-substring (point-min) (point-max))))
25756 (defun org-html-handle-time-stamps (s)
25757 "Format time stamps in string S, or remove them."
25758 (catch 'exit
25759 (let (r b)
25760 (while (string-match org-maybe-keyword-time-regexp s)
25761 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25762 ;; never export CLOCK
25763 (throw 'exit ""))
25764 (or b (setq b (substring s 0 (match-beginning 0))))
25765 (if (not org-export-with-timestamps)
25766 (setq r (concat r (substring s 0 (match-beginning 0)))
25767 s (substring s (match-end 0)))
25768 (setq r (concat
25769 r (substring s 0 (match-beginning 0))
25770 (if (match-end 1)
25771 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25772 (match-string 1 s)))
25773 (format " @<span class=\"timestamp\">%s@</span>"
25774 (substring
25775 (org-translate-time (match-string 3 s)) 1 -1)))
25776 s (substring s (match-end 0)))))
25777 ;; Line break if line started and ended with time stamp stuff
25778 (if (not r)
25780 (setq r (concat r s))
25781 (unless (string-match "\\S-" (concat b s))
25782 (setq r (concat r "@<br/>")))
25783 r))))
25785 (defun org-html-protect (s)
25786 ;; convert & to &amp;, < to &lt; and > to &gt;
25787 (let ((start 0))
25788 (while (string-match "&" s start)
25789 (setq s (replace-match "&amp;" t t s)
25790 start (1+ (match-beginning 0))))
25791 (while (string-match "<" s)
25792 (setq s (replace-match "&lt;" t t s)))
25793 (while (string-match ">" s)
25794 (setq s (replace-match "&gt;" t t s))))
25797 (defun org-export-cleanup-toc-line (s)
25798 "Remove tags and time staps from lines going into the toc."
25799 (when (memq org-export-with-tags '(not-in-toc nil))
25800 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25801 (setq s (replace-match "" t t s))))
25802 (when org-export-remove-timestamps-from-toc
25803 (while (string-match org-maybe-keyword-time-regexp s)
25804 (setq s (replace-match "" t t s))))
25805 (while (string-match org-bracket-link-regexp s)
25806 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25807 t t s)))
25810 (defun org-html-expand (string)
25811 "Prepare STRING for HTML export. Applies all active conversions.
25812 If there are links in the string, don't modify these."
25813 (let* ((re (concat org-bracket-link-regexp "\\|"
25814 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25815 m s l res)
25816 (while (setq m (string-match re string))
25817 (setq s (substring string 0 m)
25818 l (match-string 0 string)
25819 string (substring string (match-end 0)))
25820 (push (org-html-do-expand s) res)
25821 (push l res))
25822 (push (org-html-do-expand string) res)
25823 (apply 'concat (nreverse res))))
25825 (defun org-html-do-expand (s)
25826 "Apply all active conversions to translate special ASCII to HTML."
25827 (setq s (org-html-protect s))
25828 (if org-export-html-expand
25829 (let ((start 0))
25830 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25831 (setq s (replace-match "<\\1>" t nil s)))))
25832 (if org-export-with-emphasize
25833 (setq s (org-export-html-convert-emphasize s)))
25834 (if org-export-with-special-strings
25835 (setq s (org-export-html-convert-special-strings s)))
25836 (if org-export-with-sub-superscripts
25837 (setq s (org-export-html-convert-sub-super s)))
25838 (if org-export-with-TeX-macros
25839 (let ((start 0) wd ass)
25840 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25841 (if (get-text-property (match-beginning 0) 'org-protected s)
25842 (setq start (match-end 0))
25843 (setq wd (match-string 1 s))
25844 (if (setq ass (assoc wd org-html-entities))
25845 (setq s (replace-match (or (cdr ass)
25846 (concat "&" (car ass) ";"))
25847 t t s))
25848 (setq start (+ start (length wd))))))))
25851 (defun org-create-multibrace-regexp (left right n)
25852 "Create a regular expression which will match a balanced sexp.
25853 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25854 as single character strings.
25855 The regexp returned will match the entire expression including the
25856 delimiters. It will also define a single group which contains the
25857 match except for the outermost delimiters. The maximum depth of
25858 stacked delimiters is N. Escaping delimiters is not possible."
25859 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25860 (or "\\|")
25861 (re nothing)
25862 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25863 (while (> n 1)
25864 (setq n (1- n)
25865 re (concat re or next)
25866 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25867 (concat left "\\(" re "\\)" right)))
25869 (defvar org-match-substring-regexp
25870 (concat
25871 "\\([^\\]\\)\\([_^]\\)\\("
25872 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25873 "\\|"
25874 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25875 "\\|"
25876 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25877 "The regular expression matching a sub- or superscript.")
25879 (defvar org-match-substring-with-braces-regexp
25880 (concat
25881 "\\([^\\]\\)\\([_^]\\)\\("
25882 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25883 "\\)")
25884 "The regular expression matching a sub- or superscript, forcing braces.")
25886 (defconst org-export-html-special-string-regexps
25887 '(("\\\\-" . "&shy;")
25888 ("---\\([^-]\\)" . "&mdash;\\1")
25889 ("--\\([^-]\\)" . "&ndash;\\1")
25890 ("\\.\\.\\." . "&hellip;"))
25891 "Regular expressions for special string conversion.")
25893 (defun org-export-html-convert-special-strings (string)
25894 "Convert special characters in STRING to HTML."
25895 (let ((all org-export-html-special-string-regexps)
25896 e a re rpl start)
25897 (while (setq a (pop all))
25898 (setq re (car a) rpl (cdr a) start 0)
25899 (while (string-match re string start)
25900 (if (get-text-property (match-beginning 0) 'org-protected string)
25901 (setq start (match-end 0))
25902 (setq string (replace-match rpl t nil string)))))
25903 string))
25905 (defun org-export-html-convert-sub-super (string)
25906 "Convert sub- and superscripts in STRING to HTML."
25907 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25908 (while (string-match org-match-substring-regexp string s)
25909 (cond
25910 ((and requireb (match-end 8)) (setq s (match-end 2)))
25911 ((get-text-property (match-beginning 2) 'org-protected string)
25912 (setq s (match-end 2)))
25914 (setq s (match-end 1)
25915 key (if (string= (match-string 2 string) "_") "sub" "sup")
25916 c (or (match-string 8 string)
25917 (match-string 6 string)
25918 (match-string 5 string))
25919 string (replace-match
25920 (concat (match-string 1 string)
25921 "<" key ">" c "</" key ">")
25922 t t string)))))
25923 (while (string-match "\\\\\\([_^]\\)" string)
25924 (setq string (replace-match (match-string 1 string) t t string)))
25925 string))
25927 (defun org-export-html-convert-emphasize (string)
25928 "Apply emphasis."
25929 (let ((s 0) rpl)
25930 (while (string-match org-emph-re string s)
25931 (if (not (equal
25932 (substring string (match-beginning 3) (1+ (match-beginning 3)))
25933 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
25934 (setq s (match-beginning 0)
25936 (concat
25937 (match-string 1 string)
25938 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
25939 (match-string 4 string)
25940 (nth 3 (assoc (match-string 3 string)
25941 org-emphasis-alist))
25942 (match-string 5 string))
25943 string (replace-match rpl t t string)
25944 s (+ s (- (length rpl) 2)))
25945 (setq s (1+ s))))
25946 string))
25948 (defvar org-par-open nil)
25949 (defun org-open-par ()
25950 "Insert <p>, but first close previous paragraph if any."
25951 (org-close-par-maybe)
25952 (insert "\n<p>")
25953 (setq org-par-open t))
25954 (defun org-close-par-maybe ()
25955 "Close paragraph if there is one open."
25956 (when org-par-open
25957 (insert "</p>")
25958 (setq org-par-open nil)))
25959 (defun org-close-li ()
25960 "Close <li> if necessary."
25961 (org-close-par-maybe)
25962 (insert "</li>\n"))
25964 (defvar body-only) ; dynamically scoped into this.
25965 (defun org-html-level-start (level title umax with-toc head-count)
25966 "Insert a new level in HTML export.
25967 When TITLE is nil, just close all open levels."
25968 (org-close-par-maybe)
25969 (let ((l org-level-max))
25970 (while (>= l level)
25971 (if (aref org-levels-open (1- l))
25972 (progn
25973 (org-html-level-close l umax)
25974 (aset org-levels-open (1- l) nil)))
25975 (setq l (1- l)))
25976 (when title
25977 ;; If title is nil, this means this function is called to close
25978 ;; all levels, so the rest is done only if title is given
25979 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25980 (setq title (replace-match
25981 (if org-export-with-tags
25982 (save-match-data
25983 (concat
25984 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
25985 (mapconcat 'identity (org-split-string
25986 (match-string 1 title) ":")
25987 "&nbsp;")
25988 "</span>"))
25990 t t title)))
25991 (if (> level umax)
25992 (progn
25993 (if (aref org-levels-open (1- level))
25994 (progn
25995 (org-close-li)
25996 (insert "<li>" title "<br/>\n"))
25997 (aset org-levels-open (1- level) t)
25998 (org-close-par-maybe)
25999 (insert "<ul>\n<li>" title "<br/>\n")))
26000 (aset org-levels-open (1- level) t)
26001 (if (and org-export-with-section-numbers (not body-only))
26002 (setq title (concat (org-section-number level) " " title)))
26003 (setq level (+ level org-export-html-toplevel-hlevel -1))
26004 (if with-toc
26005 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26006 level level head-count title level))
26007 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26008 (org-open-par)))))
26010 (defun org-html-level-close (level max-outline-level)
26011 "Terminate one level in HTML export."
26012 (if (<= level max-outline-level)
26013 (insert "</div>\n")
26014 (org-close-li)
26015 (insert "</ul>\n")))
26017 ;;; iCalendar export
26019 ;;;###autoload
26020 (defun org-export-icalendar-this-file ()
26021 "Export current file as an iCalendar file.
26022 The iCalendar file will be located in the same directory as the Org-mode
26023 file, but with extension `.ics'."
26024 (interactive)
26025 (org-export-icalendar nil buffer-file-name))
26027 ;;;###autoload
26028 (defun org-export-icalendar-all-agenda-files ()
26029 "Export all files in `org-agenda-files' to iCalendar .ics files.
26030 Each iCalendar file will be located in the same directory as the Org-mode
26031 file, but with extension `.ics'."
26032 (interactive)
26033 (apply 'org-export-icalendar nil (org-agenda-files t)))
26035 ;;;###autoload
26036 (defun org-export-icalendar-combine-agenda-files ()
26037 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26038 The file is stored under the name `org-combined-agenda-icalendar-file'."
26039 (interactive)
26040 (apply 'org-export-icalendar t (org-agenda-files t)))
26042 (defun org-export-icalendar (combine &rest files)
26043 "Create iCalendar files for all elements of FILES.
26044 If COMBINE is non-nil, combine all calendar entries into a single large
26045 file and store it under the name `org-combined-agenda-icalendar-file'."
26046 (save-excursion
26047 (org-prepare-agenda-buffers files)
26048 (let* ((dir (org-export-directory
26049 :ical (list :publishing-directory
26050 org-export-publishing-directory)))
26051 file ical-file ical-buffer category started org-agenda-new-buffers)
26053 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26054 (when combine
26055 (setq ical-file
26056 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26057 org-combined-agenda-icalendar-file
26058 (expand-file-name org-combined-agenda-icalendar-file dir))
26059 ical-buffer (org-get-agenda-file-buffer ical-file))
26060 (set-buffer ical-buffer) (erase-buffer))
26061 (while (setq file (pop files))
26062 (catch 'nextfile
26063 (org-check-agenda-file file)
26064 (set-buffer (org-get-agenda-file-buffer file))
26065 (unless combine
26066 (setq ical-file (concat (file-name-as-directory dir)
26067 (file-name-sans-extension
26068 (file-name-nondirectory buffer-file-name))
26069 ".ics"))
26070 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26071 (with-current-buffer ical-buffer (erase-buffer)))
26072 (setq category (or org-category
26073 (file-name-sans-extension
26074 (file-name-nondirectory buffer-file-name))))
26075 (if (symbolp category) (setq category (symbol-name category)))
26076 (let ((standard-output ical-buffer))
26077 (if combine
26078 (and (not started) (setq started t)
26079 (org-start-icalendar-file org-icalendar-combined-name))
26080 (org-start-icalendar-file category))
26081 (org-print-icalendar-entries combine)
26082 (when (or (and combine (not files)) (not combine))
26083 (org-finish-icalendar-file)
26084 (set-buffer ical-buffer)
26085 (save-buffer)
26086 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26087 (org-release-buffers org-agenda-new-buffers))))
26089 (defvar org-after-save-iCalendar-file-hook nil
26090 "Hook run after an iCalendar file has been saved.
26091 The iCalendar buffer is still current when this hook is run.
26092 A good way to use this is to tell a desktop calenndar application to re-read
26093 the iCalendar file.")
26095 (defun org-print-icalendar-entries (&optional combine)
26096 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26097 When COMBINE is non nil, add the category to each line."
26098 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26099 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26100 (dts (org-ical-ts-to-string
26101 (format-time-string (cdr org-time-stamp-formats) (current-time))
26102 "DTSTART"))
26103 hd ts ts2 state status (inc t) pos b sexp rrule
26104 scheduledp deadlinep tmp pri category entry location summary desc
26105 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26106 (org-refresh-category-properties)
26107 (save-excursion
26108 (goto-char (point-min))
26109 (while (re-search-forward re1 nil t)
26110 (catch :skip
26111 (org-agenda-skip)
26112 (setq pos (match-beginning 0)
26113 ts (match-string 0)
26114 inc t
26115 hd (org-get-heading)
26116 summary (org-icalendar-cleanup-string
26117 (org-entry-get nil "SUMMARY"))
26118 desc (org-icalendar-cleanup-string
26119 (or (org-entry-get nil "DESCRIPTION")
26120 (and org-icalendar-include-body (org-get-entry)))
26121 t org-icalendar-include-body)
26122 location (org-icalendar-cleanup-string
26123 (org-entry-get nil "LOCATION"))
26124 category (org-get-category))
26125 (if (looking-at re2)
26126 (progn
26127 (goto-char (match-end 0))
26128 (setq ts2 (match-string 1) inc nil))
26129 (setq tmp (buffer-substring (max (point-min)
26130 (- pos org-ds-keyword-length))
26131 pos)
26132 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26133 (progn
26134 (setq inc nil)
26135 (replace-match "\\1" t nil ts))
26137 deadlinep (string-match org-deadline-regexp tmp)
26138 scheduledp (string-match org-scheduled-regexp tmp)
26139 ;; donep (org-entry-is-done-p)
26141 (if (or (string-match org-tr-regexp hd)
26142 (string-match org-ts-regexp hd))
26143 (setq hd (replace-match "" t t hd)))
26144 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26145 (setq rrule
26146 (concat "\nRRULE:FREQ="
26147 (cdr (assoc
26148 (match-string 2 ts)
26149 '(("d" . "DAILY")("w" . "WEEKLY")
26150 ("m" . "MONTHLY")("y" . "YEARLY"))))
26151 ";INTERVAL=" (match-string 1 ts)))
26152 (setq rrule ""))
26153 (setq summary (or summary hd))
26154 (if (string-match org-bracket-link-regexp summary)
26155 (setq summary
26156 (replace-match (if (match-end 3)
26157 (match-string 3 summary)
26158 (match-string 1 summary))
26159 t t summary)))
26160 (if deadlinep (setq summary (concat "DL: " summary)))
26161 (if scheduledp (setq summary (concat "S: " summary)))
26162 (if (string-match "\\`<%%" ts)
26163 (with-current-buffer sexp-buffer
26164 (insert (substring ts 1 -1) " " summary "\n"))
26165 (princ (format "BEGIN:VEVENT
26167 %s%s
26168 SUMMARY:%s%s%s
26169 CATEGORIES:%s
26170 END:VEVENT\n"
26171 (org-ical-ts-to-string ts "DTSTART")
26172 (org-ical-ts-to-string ts2 "DTEND" inc)
26173 rrule summary
26174 (if (and desc (string-match "\\S-" desc))
26175 (concat "\nDESCRIPTION: " desc) "")
26176 (if (and location (string-match "\\S-" location))
26177 (concat "\nLOCATION: " location) "")
26178 category)))))
26180 (when (and org-icalendar-include-sexps
26181 (condition-case nil (require 'icalendar) (error nil))
26182 (fboundp 'icalendar-export-region))
26183 ;; Get all the literal sexps
26184 (goto-char (point-min))
26185 (while (re-search-forward "^&?%%(" nil t)
26186 (catch :skip
26187 (org-agenda-skip)
26188 (setq b (match-beginning 0))
26189 (goto-char (1- (match-end 0)))
26190 (forward-sexp 1)
26191 (end-of-line 1)
26192 (setq sexp (buffer-substring b (point)))
26193 (with-current-buffer sexp-buffer
26194 (insert sexp "\n"))
26195 (princ (org-diary-to-ical-string sexp-buffer)))))
26197 (when org-icalendar-include-todo
26198 (goto-char (point-min))
26199 (while (re-search-forward org-todo-line-regexp nil t)
26200 (catch :skip
26201 (org-agenda-skip)
26202 (setq state (match-string 2))
26203 (setq status (if (member state org-done-keywords)
26204 "COMPLETED" "NEEDS-ACTION"))
26205 (when (and state
26206 (or (not (member state org-done-keywords))
26207 (eq org-icalendar-include-todo 'all))
26208 (not (member org-archive-tag (org-get-tags-at)))
26210 (setq hd (match-string 3)
26211 summary (org-icalendar-cleanup-string
26212 (org-entry-get nil "SUMMARY"))
26213 desc (org-icalendar-cleanup-string
26214 (or (org-entry-get nil "DESCRIPTION")
26215 (and org-icalendar-include-body (org-get-entry)))
26216 t org-icalendar-include-body)
26217 location (org-icalendar-cleanup-string
26218 (org-entry-get nil "LOCATION")))
26219 (if (string-match org-bracket-link-regexp hd)
26220 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26221 (match-string 1 hd))
26222 t t hd)))
26223 (if (string-match org-priority-regexp hd)
26224 (setq pri (string-to-char (match-string 2 hd))
26225 hd (concat (substring hd 0 (match-beginning 1))
26226 (substring hd (match-end 1))))
26227 (setq pri org-default-priority))
26228 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26229 (- org-lowest-priority org-highest-priority))))))
26231 (princ (format "BEGIN:VTODO
26233 SUMMARY:%s%s%s
26234 CATEGORIES:%s
26235 SEQUENCE:1
26236 PRIORITY:%d
26237 STATUS:%s
26238 END:VTODO\n"
26240 (or summary hd)
26241 (if (and location (string-match "\\S-" location))
26242 (concat "\nLOCATION: " location) "")
26243 (if (and desc (string-match "\\S-" desc))
26244 (concat "\nDESCRIPTION: " desc) "")
26245 category pri status)))))))))
26247 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26248 "Take out stuff and quote what needs to be quoted.
26249 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26250 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26251 characters."
26252 (if (not s)
26254 (when is-body
26255 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26256 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26257 (while (string-match re s) (setq s (replace-match "" t t s)))
26258 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26259 (let ((start 0))
26260 (while (string-match "\\([,;\\]\\)" s start)
26261 (setq start (+ (match-beginning 0) 2)
26262 s (replace-match "\\\\\\1" nil nil s))))
26263 (when is-body
26264 (while (string-match "[ \t]*\n[ \t]*" s)
26265 (setq s (replace-match "\\n" t t s))))
26266 (setq s (org-trim s))
26267 (if is-body
26268 (if maxlength
26269 (if (and (numberp maxlength)
26270 (> (length s) maxlength))
26271 (setq s (substring s 0 maxlength)))))
26274 (defun org-get-entry ()
26275 "Clean-up description string."
26276 (save-excursion
26277 (org-back-to-heading t)
26278 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26280 (defun org-start-icalendar-file (name)
26281 "Start an iCalendar file by inserting the header."
26282 (let ((user user-full-name)
26283 (name (or name "unknown"))
26284 (timezone (cadr (current-time-zone))))
26285 (princ
26286 (format "BEGIN:VCALENDAR
26287 VERSION:2.0
26288 X-WR-CALNAME:%s
26289 PRODID:-//%s//Emacs with Org-mode//EN
26290 X-WR-TIMEZONE:%s
26291 CALSCALE:GREGORIAN\n" name user timezone))))
26293 (defun org-finish-icalendar-file ()
26294 "Finish an iCalendar file by inserting the END statement."
26295 (princ "END:VCALENDAR\n"))
26297 (defun org-ical-ts-to-string (s keyword &optional inc)
26298 "Take a time string S and convert it to iCalendar format.
26299 KEYWORD is added in front, to make a complete line like DTSTART....
26300 When INC is non-nil, increase the hour by two (if time string contains
26301 a time), or the day by one (if it does not contain a time)."
26302 (let ((t1 (org-parse-time-string s 'nodefault))
26303 t2 fmt have-time time)
26304 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26305 (setq t2 t1 have-time t)
26306 (setq t2 (org-parse-time-string s)))
26307 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26308 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26309 (when inc
26310 (if have-time
26311 (if org-agenda-default-appointment-duration
26312 (setq mi (+ org-agenda-default-appointment-duration mi))
26313 (setq h (+ 2 h)))
26314 (setq d (1+ d))))
26315 (setq time (encode-time s mi h d m y)))
26316 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26317 (concat keyword (format-time-string fmt time))))
26319 ;;; XOXO export
26321 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26322 (with-current-buffer buffer
26323 (apply 'insert output)))
26324 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26326 (defun org-export-as-xoxo (&optional buffer)
26327 "Export the org buffer as XOXO.
26328 The XOXO buffer is named *xoxo-<source buffer name>*"
26329 (interactive (list (current-buffer)))
26330 ;; A quickie abstraction
26332 ;; Output everything as XOXO
26333 (with-current-buffer (get-buffer buffer)
26334 (let* ((pos (point))
26335 (opt-plist (org-combine-plists (org-default-export-plist)
26336 (org-infile-export-plist)))
26337 (filename (concat (file-name-as-directory
26338 (org-export-directory :xoxo opt-plist))
26339 (file-name-sans-extension
26340 (file-name-nondirectory buffer-file-name))
26341 ".html"))
26342 (out (find-file-noselect filename))
26343 (last-level 1)
26344 (hanging-li nil))
26345 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26346 ;; Check the output buffer is empty.
26347 (with-current-buffer out (erase-buffer))
26348 ;; Kick off the output
26349 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26350 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26351 (let* ((hd (match-string-no-properties 1))
26352 (level (length hd))
26353 (text (concat
26354 (match-string-no-properties 2)
26355 (save-excursion
26356 (goto-char (match-end 0))
26357 (let ((str ""))
26358 (catch 'loop
26359 (while 't
26360 (forward-line)
26361 (if (looking-at "^[ \t]\\(.*\\)")
26362 (setq str (concat str (match-string-no-properties 1)))
26363 (throw 'loop str)))))))))
26365 ;; Handle level rendering
26366 (cond
26367 ((> level last-level)
26368 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26370 ((< level last-level)
26371 (dotimes (- (- last-level level) 1)
26372 (if hanging-li
26373 (org-export-as-xoxo-insert-into out "</li>\n"))
26374 (org-export-as-xoxo-insert-into out "</ol>\n"))
26375 (when hanging-li
26376 (org-export-as-xoxo-insert-into out "</li>\n")
26377 (setq hanging-li nil)))
26379 ((equal level last-level)
26380 (if hanging-li
26381 (org-export-as-xoxo-insert-into out "</li>\n")))
26384 (setq last-level level)
26386 ;; And output the new li
26387 (setq hanging-li 't)
26388 (if (equal ?+ (elt text 0))
26389 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26390 (org-export-as-xoxo-insert-into out "<li>" text))))
26392 ;; Finally finish off the ol
26393 (dotimes (- last-level 1)
26394 (if hanging-li
26395 (org-export-as-xoxo-insert-into out "</li>\n"))
26396 (org-export-as-xoxo-insert-into out "</ol>\n"))
26398 (goto-char pos)
26399 ;; Finish the buffer off and clean it up.
26400 (switch-to-buffer-other-window out)
26401 (indent-region (point-min) (point-max) nil)
26402 (save-buffer)
26403 (goto-char (point-min))
26407 ;;;; Key bindings
26409 ;; Make `C-c C-x' a prefix key
26410 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26412 ;; TAB key with modifiers
26413 (org-defkey org-mode-map "\C-i" 'org-cycle)
26414 (org-defkey org-mode-map [(tab)] 'org-cycle)
26415 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26416 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26417 (org-defkey org-mode-map "\M-\t" 'org-complete)
26418 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26419 ;; The following line is necessary under Suse GNU/Linux
26420 (unless (featurep 'xemacs)
26421 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26422 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26423 (define-key org-mode-map [backtab] 'org-shifttab)
26425 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26426 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26427 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26429 ;; Cursor keys with modifiers
26430 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26431 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26432 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26433 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26435 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26436 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26437 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26438 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26440 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26441 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26442 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26443 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26445 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26446 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26448 ;;; Extra keys for tty access.
26449 ;; We only set them when really needed because otherwise the
26450 ;; menus don't show the simple keys
26452 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26453 (not window-system))
26454 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26455 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26456 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26457 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26458 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26459 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26460 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26461 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26462 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26463 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26464 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26465 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26466 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26467 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26468 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26469 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26470 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26471 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26472 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26473 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26474 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26475 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26477 ;; All the other keys
26479 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26480 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26481 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26482 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26483 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26484 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26485 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26486 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26487 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26488 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26489 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26490 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26491 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26492 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26493 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26494 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26495 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26496 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26497 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26498 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26499 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26500 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26501 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26502 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26503 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26504 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26505 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26506 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26507 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26508 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26509 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26510 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26511 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26512 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26513 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26514 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26515 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26516 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26517 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26518 (org-defkey org-mode-map "\C-c^" 'org-sort)
26519 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26520 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26521 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26522 (org-defkey org-mode-map "\C-m" 'org-return)
26523 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26524 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26525 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26526 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26527 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26528 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26529 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26530 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26531 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26532 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26533 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26534 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26535 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26536 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26537 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26538 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26539 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26541 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26542 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26543 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26544 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26546 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26547 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26548 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26549 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26550 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26551 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26552 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26553 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26554 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26555 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26556 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26557 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26559 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26561 (when (featurep 'xemacs)
26562 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26564 (defsubst org-table-p () (org-at-table-p))
26566 (defun org-self-insert-command (N)
26567 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26568 If the cursor is in a table looking at whitespace, the whitespace is
26569 overwritten, and the table is not marked as requiring realignment."
26570 (interactive "p")
26571 (if (and (org-table-p)
26572 (progn
26573 ;; check if we blank the field, and if that triggers align
26574 (and org-table-auto-blank-field
26575 (member last-command
26576 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26577 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26578 ;; got extra space, this field does not determine column width
26579 (let (org-table-may-need-update) (org-table-blank-field))
26580 ;; no extra space, this field may determine column width
26581 (org-table-blank-field)))
26583 (eq N 1)
26584 (looking-at "[^|\n]* |"))
26585 (let (org-table-may-need-update)
26586 (goto-char (1- (match-end 0)))
26587 (delete-backward-char 1)
26588 (goto-char (match-beginning 0))
26589 (self-insert-command N))
26590 (setq org-table-may-need-update t)
26591 (self-insert-command N)
26592 (org-fix-tags-on-the-fly)))
26594 (defun org-fix-tags-on-the-fly ()
26595 (when (and (equal (char-after (point-at-bol)) ?*)
26596 (org-on-heading-p))
26597 (org-align-tags-here org-tags-column)))
26599 (defun org-delete-backward-char (N)
26600 "Like `delete-backward-char', insert whitespace at field end in tables.
26601 When deleting backwards, in tables this function will insert whitespace in
26602 front of the next \"|\" separator, to keep the table aligned. The table will
26603 still be marked for re-alignment if the field did fill the entire column,
26604 because, in this case the deletion might narrow the column."
26605 (interactive "p")
26606 (if (and (org-table-p)
26607 (eq N 1)
26608 (string-match "|" (buffer-substring (point-at-bol) (point)))
26609 (looking-at ".*?|"))
26610 (let ((pos (point))
26611 (noalign (looking-at "[^|\n\r]* |"))
26612 (c org-table-may-need-update))
26613 (backward-delete-char N)
26614 (skip-chars-forward "^|")
26615 (insert " ")
26616 (goto-char (1- pos))
26617 ;; noalign: if there were two spaces at the end, this field
26618 ;; does not determine the width of the column.
26619 (if noalign (setq org-table-may-need-update c)))
26620 (backward-delete-char N)
26621 (org-fix-tags-on-the-fly)))
26623 (defun org-delete-char (N)
26624 "Like `delete-char', but insert whitespace at field end in tables.
26625 When deleting characters, in tables this function will insert whitespace in
26626 front of the next \"|\" separator, to keep the table aligned. The table will
26627 still be marked for re-alignment if the field did fill the entire column,
26628 because, in this case the deletion might narrow the column."
26629 (interactive "p")
26630 (if (and (org-table-p)
26631 (not (bolp))
26632 (not (= (char-after) ?|))
26633 (eq N 1))
26634 (if (looking-at ".*?|")
26635 (let ((pos (point))
26636 (noalign (looking-at "[^|\n\r]* |"))
26637 (c org-table-may-need-update))
26638 (replace-match (concat
26639 (substring (match-string 0) 1 -1)
26640 " |"))
26641 (goto-char pos)
26642 ;; noalign: if there were two spaces at the end, this field
26643 ;; does not determine the width of the column.
26644 (if noalign (setq org-table-may-need-update c)))
26645 (delete-char N))
26646 (delete-char N)
26647 (org-fix-tags-on-the-fly)))
26649 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26650 (put 'org-self-insert-command 'delete-selection t)
26651 (put 'orgtbl-self-insert-command 'delete-selection t)
26652 (put 'org-delete-char 'delete-selection 'supersede)
26653 (put 'org-delete-backward-char 'delete-selection 'supersede)
26655 ;; Make `flyspell-mode' delay after some commands
26656 (put 'org-self-insert-command 'flyspell-delayed t)
26657 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26658 (put 'org-delete-char 'flyspell-delayed t)
26659 (put 'org-delete-backward-char 'flyspell-delayed t)
26661 ;; Make pabbrev-mode expand after org-mode commands
26662 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26663 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26665 ;; How to do this: Measure non-white length of current string
26666 ;; If equal to column width, we should realign.
26668 (defun org-remap (map &rest commands)
26669 "In MAP, remap the functions given in COMMANDS.
26670 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26671 (let (new old)
26672 (while commands
26673 (setq old (pop commands) new (pop commands))
26674 (if (fboundp 'command-remapping)
26675 (org-defkey map (vector 'remap old) new)
26676 (substitute-key-definition old new map global-map)))))
26678 (when (eq org-enable-table-editor 'optimized)
26679 ;; If the user wants maximum table support, we need to hijack
26680 ;; some standard editing functions
26681 (org-remap org-mode-map
26682 'self-insert-command 'org-self-insert-command
26683 'delete-char 'org-delete-char
26684 'delete-backward-char 'org-delete-backward-char)
26685 (org-defkey org-mode-map "|" 'org-force-self-insert))
26687 (defun org-shiftcursor-error ()
26688 "Throw an error because Shift-Cursor command was applied in wrong context."
26689 (error "This command is active in special context like tables, headlines or timestamps"))
26691 (defun org-shifttab (&optional arg)
26692 "Global visibility cycling or move to previous table field.
26693 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26694 on context.
26695 See the individual commands for more information."
26696 (interactive "P")
26697 (cond
26698 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26699 (arg (message "Content view to level: ")
26700 (org-content (prefix-numeric-value arg))
26701 (setq org-cycle-global-status 'overview))
26702 (t (call-interactively 'org-global-cycle))))
26704 (defun org-shiftmetaleft ()
26705 "Promote subtree or delete table column.
26706 Calls `org-promote-subtree', `org-outdent-item',
26707 or `org-table-delete-column', depending on context.
26708 See the individual commands for more information."
26709 (interactive)
26710 (cond
26711 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26712 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26713 ((org-at-item-p) (call-interactively 'org-outdent-item))
26714 (t (org-shiftcursor-error))))
26716 (defun org-shiftmetaright ()
26717 "Demote subtree or insert table column.
26718 Calls `org-demote-subtree', `org-indent-item',
26719 or `org-table-insert-column', depending on context.
26720 See the individual commands for more information."
26721 (interactive)
26722 (cond
26723 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26724 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26725 ((org-at-item-p) (call-interactively 'org-indent-item))
26726 (t (org-shiftcursor-error))))
26728 (defun org-shiftmetaup (&optional arg)
26729 "Move subtree up or kill table row.
26730 Calls `org-move-subtree-up' or `org-table-kill-row' or
26731 `org-move-item-up' depending on context. See the individual commands
26732 for more information."
26733 (interactive "P")
26734 (cond
26735 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26736 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26737 ((org-at-item-p) (call-interactively 'org-move-item-up))
26738 (t (org-shiftcursor-error))))
26739 (defun org-shiftmetadown (&optional arg)
26740 "Move subtree down or insert table row.
26741 Calls `org-move-subtree-down' or `org-table-insert-row' or
26742 `org-move-item-down', depending on context. See the individual
26743 commands for more information."
26744 (interactive "P")
26745 (cond
26746 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26747 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26748 ((org-at-item-p) (call-interactively 'org-move-item-down))
26749 (t (org-shiftcursor-error))))
26751 (defun org-metaleft (&optional arg)
26752 "Promote heading or move table column to left.
26753 Calls `org-do-promote' or `org-table-move-column', depending on context.
26754 With no specific context, calls the Emacs default `backward-word'.
26755 See the individual commands for more information."
26756 (interactive "P")
26757 (cond
26758 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26759 ((or (org-on-heading-p) (org-region-active-p))
26760 (call-interactively 'org-do-promote))
26761 ((org-at-item-p) (call-interactively 'org-outdent-item))
26762 (t (call-interactively 'backward-word))))
26764 (defun org-metaright (&optional arg)
26765 "Demote subtree or move table column to right.
26766 Calls `org-do-demote' or `org-table-move-column', depending on context.
26767 With no specific context, calls the Emacs default `forward-word'.
26768 See the individual commands for more information."
26769 (interactive "P")
26770 (cond
26771 ((org-at-table-p) (call-interactively 'org-table-move-column))
26772 ((or (org-on-heading-p) (org-region-active-p))
26773 (call-interactively 'org-do-demote))
26774 ((org-at-item-p) (call-interactively 'org-indent-item))
26775 (t (call-interactively 'forward-word))))
26777 (defun org-metaup (&optional arg)
26778 "Move subtree up or move table row up.
26779 Calls `org-move-subtree-up' or `org-table-move-row' or
26780 `org-move-item-up', depending on context. See the individual commands
26781 for more information."
26782 (interactive "P")
26783 (cond
26784 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26785 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26786 ((org-at-item-p) (call-interactively 'org-move-item-up))
26787 (t (transpose-lines 1) (beginning-of-line -1))))
26789 (defun org-metadown (&optional arg)
26790 "Move subtree down or move table row down.
26791 Calls `org-move-subtree-down' or `org-table-move-row' or
26792 `org-move-item-down', depending on context. See the individual
26793 commands for more information."
26794 (interactive "P")
26795 (cond
26796 ((org-at-table-p) (call-interactively 'org-table-move-row))
26797 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26798 ((org-at-item-p) (call-interactively 'org-move-item-down))
26799 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26801 (defun org-shiftup (&optional arg)
26802 "Increase item in timestamp or increase priority of current headline.
26803 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26804 depending on context. See the individual commands for more information."
26805 (interactive "P")
26806 (cond
26807 ((org-at-timestamp-p t)
26808 (call-interactively (if org-edit-timestamp-down-means-later
26809 'org-timestamp-down 'org-timestamp-up)))
26810 ((org-on-heading-p) (call-interactively 'org-priority-up))
26811 ((org-at-item-p) (call-interactively 'org-previous-item))
26812 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26814 (defun org-shiftdown (&optional arg)
26815 "Decrease item in timestamp or decrease priority of current headline.
26816 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26817 depending on context. See the individual commands for more information."
26818 (interactive "P")
26819 (cond
26820 ((org-at-timestamp-p t)
26821 (call-interactively (if org-edit-timestamp-down-means-later
26822 'org-timestamp-up 'org-timestamp-down)))
26823 ((org-on-heading-p) (call-interactively 'org-priority-down))
26824 (t (call-interactively 'org-next-item))))
26826 (defun org-shiftright ()
26827 "Next TODO keyword or timestamp one day later, depending on context."
26828 (interactive)
26829 (cond
26830 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26831 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26832 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26833 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26834 (t (org-shiftcursor-error))))
26836 (defun org-shiftleft ()
26837 "Previous TODO keyword or timestamp one day earlier, depending on context."
26838 (interactive)
26839 (cond
26840 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26841 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26842 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26843 ((org-at-property-p)
26844 (call-interactively 'org-property-previous-allowed-value))
26845 (t (org-shiftcursor-error))))
26847 (defun org-shiftcontrolright ()
26848 "Switch to next TODO set."
26849 (interactive)
26850 (cond
26851 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26852 (t (org-shiftcursor-error))))
26854 (defun org-shiftcontrolleft ()
26855 "Switch to previous TODO set."
26856 (interactive)
26857 (cond
26858 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26859 (t (org-shiftcursor-error))))
26861 (defun org-ctrl-c-ret ()
26862 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26863 (interactive)
26864 (cond
26865 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26866 (t (call-interactively 'org-insert-heading))))
26868 (defun org-copy-special ()
26869 "Copy region in table or copy current subtree.
26870 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26871 See the individual commands for more information."
26872 (interactive)
26873 (call-interactively
26874 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26876 (defun org-cut-special ()
26877 "Cut region in table or cut current subtree.
26878 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26879 See the individual commands for more information."
26880 (interactive)
26881 (call-interactively
26882 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26884 (defun org-paste-special (arg)
26885 "Paste rectangular region into table, or past subtree relative to level.
26886 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26887 See the individual commands for more information."
26888 (interactive "P")
26889 (if (org-at-table-p)
26890 (org-table-paste-rectangle)
26891 (org-paste-subtree arg)))
26893 (defun org-ctrl-c-ctrl-c (&optional arg)
26894 "Set tags in headline, or update according to changed information at point.
26896 This command does many different things, depending on context:
26898 - If the cursor is in a headline, prompt for tags and insert them
26899 into the current line, aligned to `org-tags-column'. When called
26900 with prefix arg, realign all tags in the current buffer.
26902 - If the cursor is in one of the special #+KEYWORD lines, this
26903 triggers scanning the buffer for these lines and updating the
26904 information.
26906 - If the cursor is inside a table, realign the table. This command
26907 works even if the automatic table editor has been turned off.
26909 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26910 the entire table.
26912 - If the cursor is a the beginning of a dynamic block, update it.
26914 - If the cursor is inside a table created by the table.el package,
26915 activate that table.
26917 - If the current buffer is a remember buffer, close note and file it.
26918 with a prefix argument, file it without further interaction to the default
26919 location.
26921 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26922 links in this buffer.
26924 - If the cursor is on a numbered item in a plain list, renumber the
26925 ordered list.
26927 - If the cursor is on a checkbox, toggle it."
26928 (interactive "P")
26929 (let ((org-enable-table-editor t))
26930 (cond
26931 ((or org-clock-overlays
26932 org-occur-highlights
26933 org-latex-fragment-image-overlays)
26934 (org-remove-clock-overlays)
26935 (org-remove-occur-highlights)
26936 (org-remove-latex-fragment-image-overlays)
26937 (message "Temporary highlights/overlays removed from current buffer"))
26938 ((and (local-variable-p 'org-finish-function (current-buffer))
26939 (fboundp org-finish-function))
26940 (funcall org-finish-function))
26941 ((org-at-property-p)
26942 (call-interactively 'org-property-action))
26943 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
26944 ((org-on-heading-p) (call-interactively 'org-set-tags))
26945 ((org-at-table.el-p)
26946 (require 'table)
26947 (beginning-of-line 1)
26948 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
26949 (call-interactively 'table-recognize-table))
26950 ((org-at-table-p)
26951 (org-table-maybe-eval-formula)
26952 (if arg
26953 (call-interactively 'org-table-recalculate)
26954 (org-table-maybe-recalculate-line))
26955 (call-interactively 'org-table-align))
26956 ((org-at-item-checkbox-p)
26957 (call-interactively 'org-toggle-checkbox))
26958 ((org-at-item-p)
26959 (call-interactively 'org-maybe-renumber-ordered-list))
26960 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
26961 ;; Dynamic block
26962 (beginning-of-line 1)
26963 (org-update-dblock))
26964 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
26965 (cond
26966 ((equal (match-string 1) "TBLFM")
26967 ;; Recalculate the table before this line
26968 (save-excursion
26969 (beginning-of-line 1)
26970 (skip-chars-backward " \r\n\t")
26971 (if (org-at-table-p)
26972 (org-call-with-arg 'org-table-recalculate t))))
26974 (call-interactively 'org-mode-restart))))
26975 (t (error "C-c C-c can do nothing useful at this location.")))))
26977 (defun org-mode-restart ()
26978 "Restart Org-mode, to scan again for special lines.
26979 Also updates the keyword regular expressions."
26980 (interactive)
26981 (let ((org-inhibit-startup t)) (org-mode))
26982 (message "Org-mode restarted to refresh keyword and special line setup"))
26984 (defun org-kill-note-or-show-branches ()
26985 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
26986 (interactive)
26987 (if (not org-finish-function)
26988 (call-interactively 'show-branches)
26989 (let ((org-note-abort t))
26990 (funcall org-finish-function))))
26992 (defun org-return (&optional indent)
26993 "Goto next table row or insert a newline.
26994 Calls `org-table-next-row' or `newline', depending on context.
26995 See the individual commands for more information."
26996 (interactive)
26997 (cond
26998 ((bobp) (if indent (newline-and-indent) (newline)))
26999 ((and (org-at-heading-p)
27000 (looking-at
27001 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27002 (org-show-entry)
27003 (end-of-line 1)
27004 (newline))
27005 ((org-at-table-p)
27006 (org-table-justify-field-maybe)
27007 (call-interactively 'org-table-next-row))
27008 (t (if indent (newline-and-indent) (newline)))))
27010 (defun org-return-indent ()
27011 (interactive)
27012 "Goto next table row or insert a newline and indent.
27013 Calls `org-table-next-row' or `newline-and-indent', depending on
27014 context. See the individual commands for more information."
27015 (org-return t))
27017 (defun org-ctrl-c-minus ()
27018 "Insert separator line in table or modify bullet type in list.
27019 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27020 depending on context."
27021 (interactive)
27022 (cond
27023 ((org-at-table-p)
27024 (call-interactively 'org-table-insert-hline))
27025 ((org-on-heading-p)
27026 ;; Convert to item
27027 (save-excursion
27028 (beginning-of-line 1)
27029 (if (looking-at "\\*+ ")
27030 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27031 ((org-in-item-p)
27032 (call-interactively 'org-cycle-list-bullet))
27033 (t (error "`C-c -' does have no function here."))))
27035 (defun org-meta-return (&optional arg)
27036 "Insert a new heading or wrap a region in a table.
27037 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27038 See the individual commands for more information."
27039 (interactive "P")
27040 (cond
27041 ((org-at-table-p)
27042 (call-interactively 'org-table-wrap-region))
27043 (t (call-interactively 'org-insert-heading))))
27045 ;;; Menu entries
27047 ;; Define the Org-mode menus
27048 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27049 '("Tbl"
27050 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27051 ["Next Field" org-cycle (org-at-table-p)]
27052 ["Previous Field" org-shifttab (org-at-table-p)]
27053 ["Next Row" org-return (org-at-table-p)]
27054 "--"
27055 ["Blank Field" org-table-blank-field (org-at-table-p)]
27056 ["Edit Field" org-table-edit-field (org-at-table-p)]
27057 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27058 "--"
27059 ("Column"
27060 ["Move Column Left" org-metaleft (org-at-table-p)]
27061 ["Move Column Right" org-metaright (org-at-table-p)]
27062 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27063 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27064 ("Row"
27065 ["Move Row Up" org-metaup (org-at-table-p)]
27066 ["Move Row Down" org-metadown (org-at-table-p)]
27067 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27068 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27069 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27070 "--"
27071 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27072 ("Rectangle"
27073 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27074 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27075 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27076 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27077 "--"
27078 ("Calculate"
27079 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27080 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27081 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27082 "--"
27083 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27084 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27085 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27086 "--"
27087 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27088 "--"
27089 ["Sum Column/Rectangle" org-table-sum
27090 (or (org-at-table-p) (org-region-active-p))]
27091 ["Which Column?" org-table-current-column (org-at-table-p)])
27092 ["Debug Formulas"
27093 org-table-toggle-formula-debugger
27094 :style toggle :selected org-table-formula-debug]
27095 ["Show Col/Row Numbers"
27096 org-table-toggle-coordinate-overlays
27097 :style toggle :selected org-table-overlay-coordinates]
27098 "--"
27099 ["Create" org-table-create (and (not (org-at-table-p))
27100 org-enable-table-editor)]
27101 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27102 ["Import from File" org-table-import (not (org-at-table-p))]
27103 ["Export to File" org-table-export (org-at-table-p)]
27104 "--"
27105 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27107 (easy-menu-define org-org-menu org-mode-map "Org menu"
27108 '("Org"
27109 ("Show/Hide"
27110 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27111 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27112 ["Sparse Tree" org-occur t]
27113 ["Reveal Context" org-reveal t]
27114 ["Show All" show-all t]
27115 "--"
27116 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27117 "--"
27118 ["New Heading" org-insert-heading t]
27119 ("Navigate Headings"
27120 ["Up" outline-up-heading t]
27121 ["Next" outline-next-visible-heading t]
27122 ["Previous" outline-previous-visible-heading t]
27123 ["Next Same Level" outline-forward-same-level t]
27124 ["Previous Same Level" outline-backward-same-level t]
27125 "--"
27126 ["Jump" org-goto t])
27127 ("Edit Structure"
27128 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27129 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27130 "--"
27131 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27132 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27133 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27134 "--"
27135 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27136 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27137 ["Demote Heading" org-metaright (not (org-at-table-p))]
27138 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27139 "--"
27140 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27141 "--"
27142 ["Convert to odd levels" org-convert-to-odd-levels t]
27143 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27144 ("Editing"
27145 ["Emphasis..." org-emphasize t])
27146 ("Archive"
27147 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27148 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27149 ; :active t :keys "C-u C-c C-x C-a"]
27150 ["Sparse trees open ARCHIVE trees"
27151 (setq org-sparse-tree-open-archived-trees
27152 (not org-sparse-tree-open-archived-trees))
27153 :style toggle :selected org-sparse-tree-open-archived-trees]
27154 ["Cycling opens ARCHIVE trees"
27155 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27156 :style toggle :selected org-cycle-open-archived-trees]
27157 ["Agenda includes ARCHIVE trees"
27158 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27159 :style toggle :selected (not org-agenda-skip-archived-trees)]
27160 "--"
27161 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27162 ; ["Check and Move Children" (org-archive-subtree '(4))
27163 ; :active t :keys "C-u C-c C-x C-s"]
27165 "--"
27166 ("TODO Lists"
27167 ["TODO/DONE/-" org-todo t]
27168 ("Select keyword"
27169 ["Next keyword" org-shiftright (org-on-heading-p)]
27170 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27171 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27172 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27173 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27174 ["Show TODO Tree" org-show-todo-tree t]
27175 ["Global TODO list" org-todo-list t]
27176 "--"
27177 ["Set Priority" org-priority t]
27178 ["Priority Up" org-shiftup t]
27179 ["Priority Down" org-shiftdown t])
27180 ("TAGS and Properties"
27181 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27182 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27183 "--"
27184 ["Set property" 'org-set-property t]
27185 ["Column view of properties" org-columns t]
27186 ["Insert Column View DBlock" org-insert-columns-dblock t])
27187 ("Dates and Scheduling"
27188 ["Timestamp" org-time-stamp t]
27189 ["Timestamp (inactive)" org-time-stamp-inactive t]
27190 ("Change Date"
27191 ["1 Day Later" org-shiftright t]
27192 ["1 Day Earlier" org-shiftleft t]
27193 ["1 ... Later" org-shiftup t]
27194 ["1 ... Earlier" org-shiftdown t])
27195 ["Compute Time Range" org-evaluate-time-range t]
27196 ["Schedule Item" org-schedule t]
27197 ["Deadline" org-deadline t]
27198 "--"
27199 ["Custom time format" org-toggle-time-stamp-overlays
27200 :style radio :selected org-display-custom-times]
27201 "--"
27202 ["Goto Calendar" org-goto-calendar t]
27203 ["Date from Calendar" org-date-from-calendar t])
27204 ("Logging work"
27205 ["Clock in" org-clock-in t]
27206 ["Clock out" org-clock-out t]
27207 ["Clock cancel" org-clock-cancel t]
27208 ["Goto running clock" org-clock-goto t]
27209 ["Display times" org-clock-display t]
27210 ["Create clock table" org-clock-report t]
27211 "--"
27212 ["Record DONE time"
27213 (progn (setq org-log-done (not org-log-done))
27214 (message "Switching to %s will %s record a timestamp"
27215 (car org-done-keywords)
27216 (if org-log-done "automatically" "not")))
27217 :style toggle :selected org-log-done])
27218 "--"
27219 ["Agenda Command..." org-agenda t]
27220 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27221 ("File List for Agenda")
27222 ("Special views current file"
27223 ["TODO Tree" org-show-todo-tree t]
27224 ["Check Deadlines" org-check-deadlines t]
27225 ["Timeline" org-timeline t]
27226 ["Tags Tree" org-tags-sparse-tree t])
27227 "--"
27228 ("Hyperlinks"
27229 ["Store Link (Global)" org-store-link t]
27230 ["Insert Link" org-insert-link t]
27231 ["Follow Link" org-open-at-point t]
27232 "--"
27233 ["Next link" org-next-link t]
27234 ["Previous link" org-previous-link t]
27235 "--"
27236 ["Descriptive Links"
27237 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27238 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27239 ["Literal Links"
27240 (progn
27241 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27242 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27243 "--"
27244 ["Export/Publish..." org-export t]
27245 ("LaTeX"
27246 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27247 :selected org-cdlatex-mode]
27248 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27249 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27250 ["Modify math symbol" org-cdlatex-math-modify
27251 (org-inside-LaTeX-fragment-p)]
27252 ["Export LaTeX fragments as images"
27253 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27254 :style toggle :selected org-export-with-LaTeX-fragments])
27255 "--"
27256 ("Documentation"
27257 ["Show Version" org-version t]
27258 ["Info Documentation" org-info t])
27259 ("Customize"
27260 ["Browse Org Group" org-customize t]
27261 "--"
27262 ["Expand This Menu" org-create-customize-menu
27263 (fboundp 'customize-menu-create)])
27264 "--"
27265 ["Refresh setup" org-mode-restart t]
27268 (defun org-info (&optional node)
27269 "Read documentation for Org-mode in the info system.
27270 With optional NODE, go directly to that node."
27271 (interactive)
27272 (require 'info)
27273 (Info-goto-node (format "(org)%s" (or node ""))))
27275 (defun org-install-agenda-files-menu ()
27276 (let ((bl (buffer-list)))
27277 (save-excursion
27278 (while bl
27279 (set-buffer (pop bl))
27280 (if (org-mode-p) (setq bl nil)))
27281 (when (org-mode-p)
27282 (easy-menu-change
27283 '("Org") "File List for Agenda"
27284 (append
27285 (list
27286 ["Edit File List" (org-edit-agenda-file-list) t]
27287 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27288 ["Remove Current File from List" org-remove-file t]
27289 ["Cycle through agenda files" org-cycle-agenda-files t]
27290 ["Occur in all agenda files" org-occur-in-agenda-files t]
27291 "--")
27292 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27294 ;;;; Documentation
27296 (defun org-customize ()
27297 "Call the customize function with org as argument."
27298 (interactive)
27299 (customize-browse 'org))
27301 (defun org-create-customize-menu ()
27302 "Create a full customization menu for Org-mode, insert it into the menu."
27303 (interactive)
27304 (if (fboundp 'customize-menu-create)
27305 (progn
27306 (easy-menu-change
27307 '("Org") "Customize"
27308 `(["Browse Org group" org-customize t]
27309 "--"
27310 ,(customize-menu-create 'org)
27311 ["Set" Custom-set t]
27312 ["Save" Custom-save t]
27313 ["Reset to Current" Custom-reset-current t]
27314 ["Reset to Saved" Custom-reset-saved t]
27315 ["Reset to Standard Settings" Custom-reset-standard t]))
27316 (message "\"Org\"-menu now contains full customization menu"))
27317 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27319 ;;;; Miscellaneous stuff
27322 ;;; Generally useful functions
27324 (defun org-context ()
27325 "Return a list of contexts of the current cursor position.
27326 If several contexts apply, all are returned.
27327 Each context entry is a list with a symbol naming the context, and
27328 two positions indicating start and end of the context. Possible
27329 contexts are:
27331 :headline anywhere in a headline
27332 :headline-stars on the leading stars in a headline
27333 :todo-keyword on a TODO keyword (including DONE) in a headline
27334 :tags on the TAGS in a headline
27335 :priority on the priority cookie in a headline
27336 :item on the first line of a plain list item
27337 :item-bullet on the bullet/number of a plain list item
27338 :checkbox on the checkbox in a plain list item
27339 :table in an org-mode table
27340 :table-special on a special filed in a table
27341 :table-table in a table.el table
27342 :link on a hyperlink
27343 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27344 :target on a <<target>>
27345 :radio-target on a <<<radio-target>>>
27346 :latex-fragment on a LaTeX fragment
27347 :latex-preview on a LaTeX fragment with overlayed preview image
27349 This function expects the position to be visible because it uses font-lock
27350 faces as a help to recognize the following contexts: :table-special, :link,
27351 and :keyword."
27352 (let* ((f (get-text-property (point) 'face))
27353 (faces (if (listp f) f (list f)))
27354 (p (point)) clist o)
27355 ;; First the large context
27356 (cond
27357 ((org-on-heading-p t)
27358 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27359 (when (progn
27360 (beginning-of-line 1)
27361 (looking-at org-todo-line-tags-regexp))
27362 (push (org-point-in-group p 1 :headline-stars) clist)
27363 (push (org-point-in-group p 2 :todo-keyword) clist)
27364 (push (org-point-in-group p 4 :tags) clist))
27365 (goto-char p)
27366 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27367 (if (looking-at "\\[#[A-Z0-9]\\]")
27368 (push (org-point-in-group p 0 :priority) clist)))
27370 ((org-at-item-p)
27371 (push (org-point-in-group p 2 :item-bullet) clist)
27372 (push (list :item (point-at-bol)
27373 (save-excursion (org-end-of-item) (point)))
27374 clist)
27375 (and (org-at-item-checkbox-p)
27376 (push (org-point-in-group p 0 :checkbox) clist)))
27378 ((org-at-table-p)
27379 (push (list :table (org-table-begin) (org-table-end)) clist)
27380 (if (memq 'org-formula faces)
27381 (push (list :table-special
27382 (previous-single-property-change p 'face)
27383 (next-single-property-change p 'face)) clist)))
27384 ((org-at-table-p 'any)
27385 (push (list :table-table) clist)))
27386 (goto-char p)
27388 ;; Now the small context
27389 (cond
27390 ((org-at-timestamp-p)
27391 (push (org-point-in-group p 0 :timestamp) clist))
27392 ((memq 'org-link faces)
27393 (push (list :link
27394 (previous-single-property-change p 'face)
27395 (next-single-property-change p 'face)) clist))
27396 ((memq 'org-special-keyword faces)
27397 (push (list :keyword
27398 (previous-single-property-change p 'face)
27399 (next-single-property-change p 'face)) clist))
27400 ((org-on-target-p)
27401 (push (org-point-in-group p 0 :target) clist)
27402 (goto-char (1- (match-beginning 0)))
27403 (if (looking-at org-radio-target-regexp)
27404 (push (org-point-in-group p 0 :radio-target) clist))
27405 (goto-char p))
27406 ((setq o (car (delq nil
27407 (mapcar
27408 (lambda (x)
27409 (if (memq x org-latex-fragment-image-overlays) x))
27410 (org-overlays-at (point))))))
27411 (push (list :latex-fragment
27412 (org-overlay-start o) (org-overlay-end o)) clist)
27413 (push (list :latex-preview
27414 (org-overlay-start o) (org-overlay-end o)) clist))
27415 ((org-inside-LaTeX-fragment-p)
27416 ;; FIXME: positions wrong.
27417 (push (list :latex-fragment (point) (point)) clist)))
27419 (setq clist (nreverse (delq nil clist)))
27420 clist))
27422 ;; FIXME: Compare with at-regexp-p Do we need both?
27423 (defun org-in-regexp (re &optional nlines visually)
27424 "Check if point is inside a match of regexp.
27425 Normally only the current line is checked, but you can include NLINES extra
27426 lines both before and after point into the search.
27427 If VISUALLY is set, require that the cursor is not after the match but
27428 really on, so that the block visually is on the match."
27429 (catch 'exit
27430 (let ((pos (point))
27431 (eol (point-at-eol (+ 1 (or nlines 0))))
27432 (inc (if visually 1 0)))
27433 (save-excursion
27434 (beginning-of-line (- 1 (or nlines 0)))
27435 (while (re-search-forward re eol t)
27436 (if (and (<= (match-beginning 0) pos)
27437 (>= (+ inc (match-end 0)) pos))
27438 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27440 (defun org-at-regexp-p (regexp)
27441 "Is point inside a match of REGEXP in the current line?"
27442 (catch 'exit
27443 (save-excursion
27444 (let ((pos (point)) (end (point-at-eol)))
27445 (beginning-of-line 1)
27446 (while (re-search-forward regexp end t)
27447 (if (and (<= (match-beginning 0) pos)
27448 (>= (match-end 0) pos))
27449 (throw 'exit t)))
27450 nil))))
27452 (defun org-occur-in-agenda-files (regexp &optional nlines)
27453 "Call `multi-occur' with buffers for all agenda files."
27454 (interactive "sOrg-files matching: \np")
27455 (let* ((files (org-agenda-files))
27456 (tnames (mapcar 'file-truename files))
27457 (extra org-agenda-multi-occur-extra-files)
27459 (while (setq f (pop extra))
27460 (unless (member (file-truename f) tnames)
27461 (add-to-list 'files f 'append)
27462 (add-to-list 'tnames (file-truename f) 'append)))
27463 (multi-occur
27464 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27465 regexp)))
27467 (if (boundp 'occur-mode-find-occurrence-hook)
27468 ;; Emacs 23
27469 (add-hook 'occur-mode-find-occurrence-hook
27470 (lambda ()
27471 (when (org-mode-p)
27472 (org-reveal))))
27473 ;; Emacs 22
27474 (defadvice occur-mode-goto-occurrence
27475 (after org-occur-reveal activate)
27476 (and (org-mode-p) (org-reveal)))
27477 (defadvice occur-mode-goto-occurrence-other-window
27478 (after org-occur-reveal activate)
27479 (and (org-mode-p) (org-reveal)))
27480 (defadvice occur-mode-display-occurrence
27481 (after org-occur-reveal activate)
27482 (when (org-mode-p)
27483 (let ((pos (occur-mode-find-occurrence)))
27484 (with-current-buffer (marker-buffer pos)
27485 (save-excursion
27486 (goto-char pos)
27487 (org-reveal)))))))
27489 (defun org-uniquify (list)
27490 "Remove duplicate elements from LIST."
27491 (let (res)
27492 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27493 res))
27495 (defun org-delete-all (elts list)
27496 "Remove all elements in ELTS from LIST."
27497 (while elts
27498 (setq list (delete (pop elts) list)))
27499 list)
27501 (defun org-back-over-empty-lines ()
27502 "Move backwards over witespace, to the beginning of the first empty line.
27503 Returns the number o empty lines passed."
27504 (let ((pos (point)))
27505 (skip-chars-backward " \t\n\r")
27506 (beginning-of-line 2)
27507 (goto-char (min (point) pos))
27508 (count-lines (point) pos)))
27510 (defun org-skip-whitespace ()
27511 (skip-chars-forward " \t\n\r"))
27513 (defun org-point-in-group (point group &optional context)
27514 "Check if POINT is in match-group GROUP.
27515 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27516 match. If the match group does ot exist or point is not inside it,
27517 return nil."
27518 (and (match-beginning group)
27519 (>= point (match-beginning group))
27520 (<= point (match-end group))
27521 (if context
27522 (list context (match-beginning group) (match-end group))
27523 t)))
27525 (defun org-switch-to-buffer-other-window (&rest args)
27526 "Switch to buffer in a second window on the current frame.
27527 In particular, do not allow pop-up frames."
27528 (let (pop-up-frames special-display-buffer-names special-display-regexps
27529 special-display-function)
27530 (apply 'switch-to-buffer-other-window args)))
27532 (defun org-combine-plists (&rest plists)
27533 "Create a single property list from all plists in PLISTS.
27534 The process starts by copying the first list, and then setting properties
27535 from the other lists. Settings in the last list are the most significant
27536 ones and overrule settings in the other lists."
27537 (let ((rtn (copy-sequence (pop plists)))
27538 p v ls)
27539 (while plists
27540 (setq ls (pop plists))
27541 (while ls
27542 (setq p (pop ls) v (pop ls))
27543 (setq rtn (plist-put rtn p v))))
27544 rtn))
27546 (defun org-move-line-down (arg)
27547 "Move the current line down. With prefix argument, move it past ARG lines."
27548 (interactive "p")
27549 (let ((col (current-column))
27550 beg end pos)
27551 (beginning-of-line 1) (setq beg (point))
27552 (beginning-of-line 2) (setq end (point))
27553 (beginning-of-line (+ 1 arg))
27554 (setq pos (move-marker (make-marker) (point)))
27555 (insert (delete-and-extract-region beg end))
27556 (goto-char pos)
27557 (move-to-column col)))
27559 (defun org-move-line-up (arg)
27560 "Move the current line up. With prefix argument, move it past ARG lines."
27561 (interactive "p")
27562 (let ((col (current-column))
27563 beg end pos)
27564 (beginning-of-line 1) (setq beg (point))
27565 (beginning-of-line 2) (setq end (point))
27566 (beginning-of-line (- arg))
27567 (setq pos (move-marker (make-marker) (point)))
27568 (insert (delete-and-extract-region beg end))
27569 (goto-char pos)
27570 (move-to-column col)))
27572 (defun org-replace-escapes (string table)
27573 "Replace %-escapes in STRING with values in TABLE.
27574 TABLE is an association list with keys like \"%a\" and string values.
27575 The sequences in STRING may contain normal field width and padding information,
27576 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27577 so values can contain further %-escapes if they are define later in TABLE."
27578 (let ((case-fold-search nil)
27579 e re rpl)
27580 (while (setq e (pop table))
27581 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27582 (while (string-match re string)
27583 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27584 (cdr e)))
27585 (setq string (replace-match rpl t t string))))
27586 string))
27589 (defun org-sublist (list start end)
27590 "Return a section of LIST, from START to END.
27591 Counting starts at 1."
27592 (let (rtn (c start))
27593 (setq list (nthcdr (1- start) list))
27594 (while (and list (<= c end))
27595 (push (pop list) rtn)
27596 (setq c (1+ c)))
27597 (nreverse rtn)))
27599 (defun org-find-base-buffer-visiting (file)
27600 "Like `find-buffer-visiting' but alway return the base buffer and
27601 not an indirect buffer"
27602 (let ((buf (find-buffer-visiting file)))
27603 (if buf
27604 (or (buffer-base-buffer buf) buf)
27605 nil)))
27607 (defun org-image-file-name-regexp ()
27608 "Return regexp matching the file names of images."
27609 (if (fboundp 'image-file-name-regexp)
27610 (image-file-name-regexp)
27611 (let ((image-file-name-extensions
27612 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27613 "xbm" "xpm" "pbm" "pgm" "ppm")))
27614 (concat "\\."
27615 (regexp-opt (nconc (mapcar 'upcase
27616 image-file-name-extensions)
27617 image-file-name-extensions)
27619 "\\'"))))
27621 (defun org-file-image-p (file)
27622 "Return non-nil if FILE is an image."
27623 (save-match-data
27624 (string-match (org-image-file-name-regexp) file)))
27626 ;;; Paragraph filling stuff.
27627 ;; We want this to be just right, so use the full arsenal.
27629 (defun org-indent-line-function ()
27630 "Indent line like previous, but further if previous was headline or item."
27631 (interactive)
27632 (let* ((pos (point))
27633 (itemp (org-at-item-p))
27634 column bpos bcol tpos tcol bullet btype bullet-type)
27635 ;; Find the previous relevant line
27636 (beginning-of-line 1)
27637 (cond
27638 ((looking-at "#") (setq column 0))
27639 ((looking-at "\\*+ ") (setq column 0))
27641 (beginning-of-line 0)
27642 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27643 (beginning-of-line 0))
27644 (cond
27645 ((looking-at "\\*+[ \t]+")
27646 (goto-char (match-end 0))
27647 (setq column (current-column)))
27648 ((org-in-item-p)
27649 (org-beginning-of-item)
27650 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27651 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27652 (setq bpos (match-beginning 1) tpos (match-end 0)
27653 bcol (progn (goto-char bpos) (current-column))
27654 tcol (progn (goto-char tpos) (current-column))
27655 bullet (match-string 1)
27656 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27657 (if (not itemp)
27658 (setq column tcol)
27659 (goto-char pos)
27660 (beginning-of-line 1)
27661 (if (looking-at "\\S-")
27662 (progn
27663 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27664 (setq bullet (match-string 1)
27665 btype (if (string-match "[0-9]" bullet) "n" bullet))
27666 (setq column (if (equal btype bullet-type) bcol tcol)))
27667 (setq column (org-get-indentation)))))
27668 (t (setq column (org-get-indentation))))))
27669 (goto-char pos)
27670 (if (<= (current-column) (current-indentation))
27671 (indent-line-to column)
27672 (save-excursion (indent-line-to column)))
27673 (setq column (current-column))
27674 (beginning-of-line 1)
27675 (if (looking-at
27676 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27677 (replace-match (concat "\\1" (format org-property-format
27678 (match-string 2) (match-string 3)))
27679 t nil))
27680 (move-to-column column)))
27682 (defun org-set-autofill-regexps ()
27683 (interactive)
27684 ;; In the paragraph separator we include headlines, because filling
27685 ;; text in a line directly attached to a headline would otherwise
27686 ;; fill the headline as well.
27687 (org-set-local 'comment-start-skip "^#+[ \t]*")
27688 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27689 ;; The paragraph starter includes hand-formatted lists.
27690 (org-set-local 'paragraph-start
27691 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27692 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27693 ;; But only if the user has not turned off tables or fixed-width regions
27694 (org-set-local
27695 'auto-fill-inhibit-regexp
27696 (concat "\\*+ \\|#\\+"
27697 "\\|[ \t]*" org-keyword-time-regexp
27698 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27699 (concat
27700 "\\|[ \t]*["
27701 (if org-enable-table-editor "|" "")
27702 (if org-enable-fixed-width-editor ":" "")
27703 "]"))))
27704 ;; We use our own fill-paragraph function, to make sure that tables
27705 ;; and fixed-width regions are not wrapped. That function will pass
27706 ;; through to `fill-paragraph' when appropriate.
27707 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27708 ; Adaptive filling: To get full control, first make sure that
27709 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27710 (org-set-local 'adaptive-fill-regexp "\000")
27711 (org-set-local 'adaptive-fill-function
27712 'org-adaptive-fill-function)
27713 (org-set-local
27714 'align-mode-rules-list
27715 '((org-in-buffer-settings
27716 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27717 (modes . '(org-mode))))))
27719 (defun org-fill-paragraph (&optional justify)
27720 "Re-align a table, pass through to fill-paragraph if no table."
27721 (let ((table-p (org-at-table-p))
27722 (table.el-p (org-at-table.el-p)))
27723 (cond ((and (equal (char-after (point-at-bol)) ?*)
27724 (save-excursion (goto-char (point-at-bol))
27725 (looking-at outline-regexp)))
27726 t) ; skip headlines
27727 (table.el-p t) ; skip table.el tables
27728 (table-p (org-table-align) t) ; align org-mode tables
27729 (t nil)))) ; call paragraph-fill
27731 ;; For reference, this is the default value of adaptive-fill-regexp
27732 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27734 (defun org-adaptive-fill-function ()
27735 "Return a fill prefix for org-mode files.
27736 In particular, this makes sure hanging paragraphs for hand-formatted lists
27737 work correctly."
27738 (cond ((looking-at "#[ \t]+")
27739 (match-string 0))
27740 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27741 (save-excursion
27742 (goto-char (match-end 0))
27743 (make-string (current-column) ?\ )))
27744 (t nil)))
27746 ;;;; Functions extending outline functionality
27749 (defun org-beginning-of-line (&optional arg)
27750 "Go to the beginning of the current line. If that is invisible, continue
27751 to a visible line beginning. This makes the function of C-a more intuitive.
27752 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27753 first attempt, and only move to after the tags when the cursor is already
27754 beyond the end of the headline."
27755 (interactive "P")
27756 (let ((pos (point)))
27757 (beginning-of-line 1)
27758 (if (bobp)
27760 (backward-char 1)
27761 (if (org-invisible-p)
27762 (while (and (not (bobp)) (org-invisible-p))
27763 (backward-char 1)
27764 (beginning-of-line 1))
27765 (forward-char 1)))
27766 (when org-special-ctrl-a/e
27767 (cond
27768 ((and (looking-at org-todo-line-regexp)
27769 (= (char-after (match-end 1)) ?\ ))
27770 (goto-char
27771 (if (eq org-special-ctrl-a/e t)
27772 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27773 ((= pos (point)) (match-beginning 3))
27774 (t (point)))
27775 (cond ((> pos (point)) (point))
27776 ((not (eq last-command this-command)) (point))
27777 (t (match-beginning 3))))))
27778 ((org-at-item-p)
27779 (goto-char
27780 (if (eq org-special-ctrl-a/e t)
27781 (cond ((> pos (match-end 4)) (match-end 4))
27782 ((= pos (point)) (match-end 4))
27783 (t (point)))
27784 (cond ((> pos (point)) (point))
27785 ((not (eq last-command this-command)) (point))
27786 (t (match-end 4))))))))))
27788 (defun org-end-of-line (&optional arg)
27789 "Go to the end of the line.
27790 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27791 first attempt, and only move to after the tags when the cursor is already
27792 beyond the end of the headline."
27793 (interactive "P")
27794 (if (or (not org-special-ctrl-a/e)
27795 (not (org-on-heading-p)))
27796 (end-of-line arg)
27797 (let ((pos (point)))
27798 (beginning-of-line 1)
27799 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27800 (if (eq org-special-ctrl-a/e t)
27801 (if (or (< pos (match-beginning 1))
27802 (= pos (match-end 0)))
27803 (goto-char (match-beginning 1))
27804 (goto-char (match-end 0)))
27805 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27806 (goto-char (match-end 0))
27807 (goto-char (match-beginning 1))))
27808 (end-of-line arg)))))
27810 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27811 (define-key org-mode-map "\C-e" 'org-end-of-line)
27813 (defun org-kill-line (&optional arg)
27814 "Kill line, to tags or end of line."
27815 (interactive "P")
27816 (cond
27817 ((or (not org-special-ctrl-k)
27818 (bolp)
27819 (not (org-on-heading-p)))
27820 (call-interactively 'kill-line))
27821 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27822 (kill-region (point) (match-beginning 1))
27823 (org-set-tags nil t))
27824 (t (kill-region (point) (point-at-eol)))))
27826 (define-key org-mode-map "\C-k" 'org-kill-line)
27828 (defun org-invisible-p ()
27829 "Check if point is at a character currently not visible."
27830 ;; Early versions of noutline don't have `outline-invisible-p'.
27831 (if (fboundp 'outline-invisible-p)
27832 (outline-invisible-p)
27833 (get-char-property (point) 'invisible)))
27835 (defun org-invisible-p2 ()
27836 "Check if point is at a character currently not visible."
27837 (save-excursion
27838 (if (and (eolp) (not (bobp))) (backward-char 1))
27839 ;; Early versions of noutline don't have `outline-invisible-p'.
27840 (if (fboundp 'outline-invisible-p)
27841 (outline-invisible-p)
27842 (get-char-property (point) 'invisible))))
27844 (defalias 'org-back-to-heading 'outline-back-to-heading)
27845 (defalias 'org-on-heading-p 'outline-on-heading-p)
27846 (defalias 'org-at-heading-p 'outline-on-heading-p)
27847 (defun org-at-heading-or-item-p ()
27848 (or (org-on-heading-p) (org-at-item-p)))
27850 (defun org-on-target-p ()
27851 (or (org-in-regexp org-radio-target-regexp)
27852 (org-in-regexp org-target-regexp)))
27854 (defun org-up-heading-all (arg)
27855 "Move to the heading line of which the present line is a subheading.
27856 This function considers both visible and invisible heading lines.
27857 With argument, move up ARG levels."
27858 (if (fboundp 'outline-up-heading-all)
27859 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27860 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27862 (defun org-up-heading-safe ()
27863 "Move to the heading line of which the present line is a subheading.
27864 This version will not throw an error. It will return the level of the
27865 headline found, or nil if no higher level is found."
27866 (let ((pos (point)) start-level level
27867 (re (concat "^" outline-regexp)))
27868 (catch 'exit
27869 (outline-back-to-heading t)
27870 (setq start-level (funcall outline-level))
27871 (if (equal start-level 1) (throw 'exit nil))
27872 (while (re-search-backward re nil t)
27873 (setq level (funcall outline-level))
27874 (if (< level start-level) (throw 'exit level)))
27875 nil)))
27877 (defun org-first-sibling-p ()
27878 "Is this heading the first child of its parents?"
27879 (interactive)
27880 (let ((re (concat "^" outline-regexp))
27881 level l)
27882 (unless (org-at-heading-p t)
27883 (error "Not at a heading"))
27884 (setq level (funcall outline-level))
27885 (save-excursion
27886 (if (not (re-search-backward re nil t))
27888 (setq l (funcall outline-level))
27889 (< l level)))))
27891 (defun org-goto-sibling (&optional previous)
27892 "Goto the next sibling, even if it is invisible.
27893 When PREVIOUS is set, go to the previous sibling instead. Returns t
27894 when a sibling was found. When none is found, return nil and don't
27895 move point."
27896 (let ((fun (if previous 're-search-backward 're-search-forward))
27897 (pos (point))
27898 (re (concat "^" outline-regexp))
27899 level l)
27900 (when (condition-case nil (org-back-to-heading t) (error nil))
27901 (setq level (funcall outline-level))
27902 (catch 'exit
27903 (or previous (forward-char 1))
27904 (while (funcall fun re nil t)
27905 (setq l (funcall outline-level))
27906 (when (< l level) (goto-char pos) (throw 'exit nil))
27907 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27908 (goto-char pos)
27909 nil))))
27911 (defun org-show-siblings ()
27912 "Show all siblings of the current headline."
27913 (save-excursion
27914 (while (org-goto-sibling) (org-flag-heading nil)))
27915 (save-excursion
27916 (while (org-goto-sibling 'previous)
27917 (org-flag-heading nil))))
27919 (defun org-show-hidden-entry ()
27920 "Show an entry where even the heading is hidden."
27921 (save-excursion
27922 (org-show-entry)))
27924 (defun org-flag-heading (flag &optional entry)
27925 "Flag the current heading. FLAG non-nil means make invisible.
27926 When ENTRY is non-nil, show the entire entry."
27927 (save-excursion
27928 (org-back-to-heading t)
27929 ;; Check if we should show the entire entry
27930 (if entry
27931 (progn
27932 (org-show-entry)
27933 (save-excursion
27934 (and (outline-next-heading)
27935 (org-flag-heading nil))))
27936 (outline-flag-region (max (point-min) (1- (point)))
27937 (save-excursion (outline-end-of-heading) (point))
27938 flag))))
27940 (defun org-end-of-subtree (&optional invisible-OK to-heading)
27941 ;; This is an exact copy of the original function, but it uses
27942 ;; `org-back-to-heading', to make it work also in invisible
27943 ;; trees. And is uses an invisible-OK argument.
27944 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
27945 (org-back-to-heading invisible-OK)
27946 (let ((first t)
27947 (level (funcall outline-level)))
27948 (while (and (not (eobp))
27949 (or first (> (funcall outline-level) level)))
27950 (setq first nil)
27951 (outline-next-heading))
27952 (unless to-heading
27953 (if (memq (preceding-char) '(?\n ?\^M))
27954 (progn
27955 ;; Go to end of line before heading
27956 (forward-char -1)
27957 (if (memq (preceding-char) '(?\n ?\^M))
27958 ;; leave blank line before heading
27959 (forward-char -1))))))
27960 (point))
27962 (defun org-show-subtree ()
27963 "Show everything after this heading at deeper levels."
27964 (outline-flag-region
27965 (point)
27966 (save-excursion
27967 (outline-end-of-subtree) (outline-next-heading) (point))
27968 nil))
27970 (defun org-show-entry ()
27971 "Show the body directly following this heading.
27972 Show the heading too, if it is currently invisible."
27973 (interactive)
27974 (save-excursion
27975 (condition-case nil
27976 (progn
27977 (org-back-to-heading t)
27978 (outline-flag-region
27979 (max (point-min) (1- (point)))
27980 (save-excursion
27981 (re-search-forward
27982 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
27983 (or (match-beginning 1) (point-max)))
27984 nil))
27985 (error nil))))
27987 (defun org-make-options-regexp (kwds)
27988 "Make a regular expression for keyword lines."
27989 (concat
27991 "#?[ \t]*\\+\\("
27992 (mapconcat 'regexp-quote kwds "\\|")
27993 "\\):[ \t]*"
27994 "\\(.+\\)"))
27996 ;; Make isearch reveal the necessary context
27997 (defun org-isearch-end ()
27998 "Reveal context after isearch exits."
27999 (when isearch-success ; only if search was successful
28000 (if (featurep 'xemacs)
28001 ;; Under XEmacs, the hook is run in the correct place,
28002 ;; we directly show the context.
28003 (org-show-context 'isearch)
28004 ;; In Emacs the hook runs *before* restoring the overlays.
28005 ;; So we have to use a one-time post-command-hook to do this.
28006 ;; (Emacs 22 has a special variable, see function `org-mode')
28007 (unless (and (boundp 'isearch-mode-end-hook-quit)
28008 isearch-mode-end-hook-quit)
28009 ;; Only when the isearch was not quitted.
28010 (org-add-hook 'post-command-hook 'org-isearch-post-command
28011 'append 'local)))))
28013 (defun org-isearch-post-command ()
28014 "Remove self from hook, and show context."
28015 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28016 (org-show-context 'isearch))
28019 ;;;; Integration with and fixes for other packages
28021 ;;; Imenu support
28023 (defvar org-imenu-markers nil
28024 "All markers currently used by Imenu.")
28025 (make-variable-buffer-local 'org-imenu-markers)
28027 (defun org-imenu-new-marker (&optional pos)
28028 "Return a new marker for use by Imenu, and remember the marker."
28029 (let ((m (make-marker)))
28030 (move-marker m (or pos (point)))
28031 (push m org-imenu-markers)
28034 (defun org-imenu-get-tree ()
28035 "Produce the index for Imenu."
28036 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28037 (setq org-imenu-markers nil)
28038 (let* ((n org-imenu-depth)
28039 (re (concat "^" outline-regexp))
28040 (subs (make-vector (1+ n) nil))
28041 (last-level 0)
28042 m tree level head)
28043 (save-excursion
28044 (save-restriction
28045 (widen)
28046 (goto-char (point-max))
28047 (while (re-search-backward re nil t)
28048 (setq level (org-reduced-level (funcall outline-level)))
28049 (when (<= level n)
28050 (looking-at org-complex-heading-regexp)
28051 (setq head (org-match-string-no-properties 4)
28052 m (org-imenu-new-marker))
28053 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28054 (if (>= level last-level)
28055 (push (cons head m) (aref subs level))
28056 (push (cons head (aref subs (1+ level))) (aref subs level))
28057 (loop for i from (1+ level) to n do (aset subs i nil)))
28058 (setq last-level level)))))
28059 (aref subs 1)))
28061 (eval-after-load "imenu"
28062 '(progn
28063 (add-hook 'imenu-after-jump-hook
28064 (lambda () (org-show-context 'org-goto)))))
28066 ;; Speedbar support
28068 (defun org-speedbar-set-agenda-restriction ()
28069 "Restrict future agenda commands to the location at point in speedbar.
28070 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28071 (interactive)
28072 (let (p m tp np dir txt w)
28073 (cond
28074 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28075 'org-imenu t))
28076 (setq m (get-text-property p 'org-imenu-marker))
28077 (save-excursion
28078 (save-restriction
28079 (set-buffer (marker-buffer m))
28080 (goto-char m)
28081 (org-agenda-set-restriction-lock 'subtree))))
28082 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28083 'speedbar-function 'speedbar-find-file))
28084 (setq tp (previous-single-property-change
28085 (1+ p) 'speedbar-function)
28086 np (next-single-property-change
28087 tp 'speedbar-function)
28088 dir (speedbar-line-directory)
28089 txt (buffer-substring-no-properties (or tp (point-min))
28090 (or np (point-max))))
28091 (save-excursion
28092 (save-restriction
28093 (set-buffer (find-file-noselect
28094 (let ((default-directory dir))
28095 (expand-file-name txt))))
28096 (unless (org-mode-p)
28097 (error "Cannot restrict to non-Org-mode file"))
28098 (org-agenda-set-restriction-lock 'file))))
28099 (t (error "Don't know how to restrict Org-mode's agenda")))
28100 (org-move-overlay org-speedbar-restriction-lock-overlay
28101 (point-at-bol) (point-at-eol))
28102 (setq current-prefix-arg nil)
28103 (org-agenda-maybe-redo)))
28105 (eval-after-load "speedbar"
28106 '(progn
28107 (speedbar-add-supported-extension ".org")
28108 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28109 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28110 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28111 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28112 (add-hook 'speedbar-visiting-tag-hook
28113 (lambda () (org-show-context 'org-goto)))))
28116 ;;; Fixes and Hacks
28118 ;; Make flyspell not check words in links, to not mess up our keymap
28119 (defun org-mode-flyspell-verify ()
28120 "Don't let flyspell put overlays at active buttons."
28121 (not (get-text-property (point) 'keymap)))
28123 ;; Make `bookmark-jump' show the jump location if it was hidden.
28124 (eval-after-load "bookmark"
28125 '(if (boundp 'bookmark-after-jump-hook)
28126 ;; We can use the hook
28127 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28128 ;; Hook not available, use advice
28129 (defadvice bookmark-jump (after org-make-visible activate)
28130 "Make the position visible."
28131 (org-bookmark-jump-unhide))))
28133 (defun org-bookmark-jump-unhide ()
28134 "Unhide the current position, to show the bookmark location."
28135 (and (org-mode-p)
28136 (or (org-invisible-p)
28137 (save-excursion (goto-char (max (point-min) (1- (point))))
28138 (org-invisible-p)))
28139 (org-show-context 'bookmark-jump)))
28141 ;; Fix a bug in htmlize where there are text properties (face nil)
28142 (eval-after-load "htmlize"
28143 '(progn
28144 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28145 "Make sure there are no nil faces"
28146 (setq ad-return-value (delq nil ad-return-value)))))
28148 ;; Make session.el ignore our circular variable
28149 (eval-after-load "session"
28150 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28152 ;;;; Experimental code
28154 (defun org-closed-in-range ()
28155 "Sparse tree of items closed in a certain time range.
28156 Still experimental, may disappear in the future."
28157 (interactive)
28158 ;; Get the time interval from the user.
28159 (let* ((time1 (time-to-seconds
28160 (org-read-date nil 'to-time nil "Starting date: ")))
28161 (time2 (time-to-seconds
28162 (org-read-date nil 'to-time nil "End date:")))
28163 ;; callback function
28164 (callback (lambda ()
28165 (let ((time
28166 (time-to-seconds
28167 (apply 'encode-time
28168 (org-parse-time-string
28169 (match-string 1))))))
28170 ;; check if time in interval
28171 (and (>= time time1) (<= time time2))))))
28172 ;; make tree, check each match with the callback
28173 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28175 ;;;; Finish up
28177 (provide 'org)
28179 (run-hooks 'org-load-hook)
28181 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28182 ;;; org.el ends here