Another bug fix in org-publish, related to the FORCE argument.
[org-mode/org-tableheadings.git] / org.el
blob0b25976305ab47b6ea7cd7b34b05ab51739690e8
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.22a+
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.22a+"
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 (defcustom org-load-hook '(org-load-default-extensions)
155 "Hook that is run after org.el has been loaded.
156 This happens also after `org' has been provided, so
157 requiring something in this hook that does a (require 'org) is ok."
158 :group 'org
159 :type 'hook)
161 (defcustom org-default-extensions '(org-irc)
162 "Extensions that should always be loaded together with org.el
163 If the description starts with <A>, this means the extension
164 will be autoloaded when needed, to preloading is not necessary."
165 :group 'org
166 :type
167 '(set :greedy t
168 (const :tag " Mouse support (org-mouse.el)" org-mouse)
169 (const :tag "<A> Publishing (org-publish.el)" org-publish)
170 (const :tag "<A> LaTeX export (org-export-latex.el)" org-export-latex)
171 (const :tag " IRC/ERC links (org-irc.el)" org-irc)
172 (const :tag " Apple Mail message links under OS X (org-mac-message.el)" org-mac-message)
175 (defun org-load-default-extensions ()
176 "Load all extensions that are listed in `org-default-extensions'."
177 (mapc 'require org-default-extensions))
180 ;; FIXME: Needs a separate group...
181 (defcustom org-completion-fallback-command 'hippie-expand
182 "The expansion command called by \\[org-complete] in normal context.
183 Normal means, no org-mode-specific context."
184 :group 'org
185 :type 'function)
187 (defgroup org-startup nil
188 "Options concerning startup of Org-mode."
189 :tag "Org Startup"
190 :group 'org)
192 (defcustom org-startup-folded t
193 "Non-nil means, entering Org-mode will switch to OVERVIEW.
194 This can also be configured on a per-file basis by adding one of
195 the following lines anywhere in the buffer:
197 #+STARTUP: fold
198 #+STARTUP: nofold
199 #+STARTUP: content"
200 :group 'org-startup
201 :type '(choice
202 (const :tag "nofold: show all" nil)
203 (const :tag "fold: overview" t)
204 (const :tag "content: all headlines" content)))
206 (defcustom org-startup-truncated t
207 "Non-nil means, entering Org-mode will set `truncate-lines'.
208 This is useful since some lines containing links can be very long and
209 uninteresting. Also tables look terrible when wrapped."
210 :group 'org-startup
211 :type 'boolean)
213 (defcustom org-startup-align-all-tables nil
214 "Non-nil means, align all tables when visiting a file.
215 This is useful when the column width in tables is forced with <N> cookies
216 in table fields. Such tables will look correct only after the first re-align.
217 This can also be configured on a per-file basis by adding one of
218 the following lines anywhere in the buffer:
219 #+STARTUP: align
220 #+STARTUP: noalign"
221 :group 'org-startup
222 :type 'boolean)
224 (defcustom org-insert-mode-line-in-empty-file nil
225 "Non-nil means insert the first line setting Org-mode in empty files.
226 When the function `org-mode' is called interactively in an empty file, this
227 normally means that the file name does not automatically trigger Org-mode.
228 To ensure that the file will always be in Org-mode in the future, a
229 line enforcing Org-mode will be inserted into the buffer, if this option
230 has been set."
231 :group 'org-startup
232 :type 'boolean)
234 (defcustom org-replace-disputed-keys nil
235 "Non-nil means use alternative key bindings for some keys.
236 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
237 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
238 If you want to use Org-mode together with one of these other modes,
239 or more generally if you would like to move some Org-mode commands to
240 other keys, set this variable and configure the keys with the variable
241 `org-disputed-keys'.
243 This option is only relevant at load-time of Org-mode, and must be set
244 *before* org.el is loaded. Changing it requires a restart of Emacs to
245 become effective."
246 :group 'org-startup
247 :type 'boolean)
249 (if (fboundp 'defvaralias)
250 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
252 (defcustom org-disputed-keys
253 '(([(shift up)] . [(meta p)])
254 ([(shift down)] . [(meta n)])
255 ([(shift left)] . [(meta -)])
256 ([(shift right)] . [(meta +)])
257 ([(control shift right)] . [(meta shift +)])
258 ([(control shift left)] . [(meta shift -)]))
259 "Keys for which Org-mode and other modes compete.
260 This is an alist, cars are the default keys, second element specifies
261 the alternative to use when `org-replace-disputed-keys' is t.
263 Keys can be specified in any syntax supported by `define-key'.
264 The value of this option takes effect only at Org-mode's startup,
265 therefore you'll have to restart Emacs to apply it after changing."
266 :group 'org-startup
267 :type 'alist)
269 (defun org-key (key)
270 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
271 Or return the original if not disputed."
272 (if org-replace-disputed-keys
273 (let* ((nkey (key-description key))
274 (x (org-find-if (lambda (x)
275 (equal (key-description (car x)) nkey))
276 org-disputed-keys)))
277 (if x (cdr x) key))
278 key))
280 (defun org-find-if (predicate seq)
281 (catch 'exit
282 (while seq
283 (if (funcall predicate (car seq))
284 (throw 'exit (car seq))
285 (pop seq)))))
287 (defun org-defkey (keymap key def)
288 "Define a key, possibly translated, as returned by `org-key'."
289 (define-key keymap (org-key key) def))
291 (defcustom org-ellipsis nil
292 "The ellipsis to use in the Org-mode outline.
293 When nil, just use the standard three dots. When a string, use that instead,
294 When a face, use the standart 3 dots, but with the specified face.
295 The change affects only Org-mode (which will then use its own display table).
296 Changing this requires executing `M-x org-mode' in a buffer to become
297 effective."
298 :group 'org-startup
299 :type '(choice (const :tag "Default" nil)
300 (face :tag "Face" :value org-warning)
301 (string :tag "String" :value "...#")))
303 (defvar org-display-table nil
304 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
306 (defgroup org-keywords nil
307 "Keywords in Org-mode."
308 :tag "Org Keywords"
309 :group 'org)
311 (defcustom org-deadline-string "DEADLINE:"
312 "String to mark deadline entries.
313 A deadline is this string, followed by a time stamp. Should be a word,
314 terminated by a colon. You can insert a schedule keyword and
315 a timestamp with \\[org-deadline].
316 Changes become only effective after restarting Emacs."
317 :group 'org-keywords
318 :type 'string)
320 (defcustom org-scheduled-string "SCHEDULED:"
321 "String to mark scheduled TODO entries.
322 A schedule is this string, followed by a time stamp. Should be a word,
323 terminated by a colon. You can insert a schedule keyword and
324 a timestamp with \\[org-schedule].
325 Changes become only effective after restarting Emacs."
326 :group 'org-keywords
327 :type 'string)
329 (defcustom org-closed-string "CLOSED:"
330 "String used as the prefix for timestamps logging closing a TODO entry."
331 :group 'org-keywords
332 :type 'string)
334 (defcustom org-clock-string "CLOCK:"
335 "String used as prefix for timestamps clocking work hours on an item."
336 :group 'org-keywords
337 :type 'string)
339 (defcustom org-comment-string "COMMENT"
340 "Entries starting with this keyword will never be exported.
341 An entry can be toggled between COMMENT and normal with
342 \\[org-toggle-comment].
343 Changes become only effective after restarting Emacs."
344 :group 'org-keywords
345 :type 'string)
347 (defcustom org-quote-string "QUOTE"
348 "Entries starting with this keyword will be exported in fixed-width font.
349 Quoting applies only to the text in the entry following the headline, and does
350 not extend beyond the next headline, even if that is lower level.
351 An entry can be toggled between QUOTE and normal with
352 \\[org-toggle-fixed-width-section]."
353 :group 'org-keywords
354 :type 'string)
356 (defconst org-repeat-re
357 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
358 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
359 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
360 "Regular expression for specifying repeated events.
361 After a match, group 1 contains the repeat expression.")
363 (defgroup org-structure nil
364 "Options concerning the general structure of Org-mode files."
365 :tag "Org Structure"
366 :group 'org)
368 (defgroup org-reveal-location nil
369 "Options about how to make context of a location visible."
370 :tag "Org Reveal Location"
371 :group 'org-structure)
373 (defconst org-context-choice
374 '(choice
375 (const :tag "Always" t)
376 (const :tag "Never" nil)
377 (repeat :greedy t :tag "Individual contexts"
378 (cons
379 (choice :tag "Context"
380 (const agenda)
381 (const org-goto)
382 (const occur-tree)
383 (const tags-tree)
384 (const link-search)
385 (const mark-goto)
386 (const bookmark-jump)
387 (const isearch)
388 (const default))
389 (boolean))))
390 "Contexts for the reveal options.")
392 (defcustom org-show-hierarchy-above '((default . t))
393 "Non-nil means, show full hierarchy when revealing a location.
394 Org-mode often shows locations in an org-mode file which might have
395 been invisible before. When this is set, the hierarchy of headings
396 above the exposed location is shown.
397 Turning this off for example for sparse trees makes them very compact.
398 Instead of t, this can also be an alist specifying this option for different
399 contexts. Valid contexts are
400 agenda when exposing an entry from the agenda
401 org-goto when using the command `org-goto' on key C-c C-j
402 occur-tree when using the command `org-occur' on key C-c /
403 tags-tree when constructing a sparse tree based on tags matches
404 link-search when exposing search matches associated with a link
405 mark-goto when exposing the jump goal of a mark
406 bookmark-jump when exposing a bookmark location
407 isearch when exiting from an incremental search
408 default default for all contexts not set explicitly"
409 :group 'org-reveal-location
410 :type org-context-choice)
412 (defcustom org-show-following-heading '((default . nil))
413 "Non-nil means, show following heading when revealing a location.
414 Org-mode often shows locations in an org-mode file which might have
415 been invisible before. When this is set, the heading following the
416 match is shown.
417 Turning this off for example for sparse trees makes them very compact,
418 but makes it harder to edit the location of the match. In such a case,
419 use the command \\[org-reveal] to show more context.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. See `org-show-hierarchy-above' for valid contexts."
422 :group 'org-reveal-location
423 :type org-context-choice)
425 (defcustom org-show-siblings '((default . nil) (isearch t))
426 "Non-nil means, show all sibling heading when revealing a location.
427 Org-mode often shows locations in an org-mode file which might have
428 been invisible before. When this is set, the sibling of the current entry
429 heading are all made visible. If `org-show-hierarchy-above' is t,
430 the same happens on each level of the hierarchy above the current entry.
432 By default this is on for the isearch context, off for all other contexts.
433 Turning this off for example for sparse trees makes them very compact,
434 but makes it harder to edit the location of the match. In such a case,
435 use the command \\[org-reveal] to show more context.
436 Instead of t, this can also be an alist specifying this option for different
437 contexts. See `org-show-hierarchy-above' for valid contexts."
438 :group 'org-reveal-location
439 :type org-context-choice)
441 (defcustom org-show-entry-below '((default . nil))
442 "Non-nil means, show the entry below a headline when revealing a location.
443 Org-mode often shows locations in an org-mode file which might have
444 been invisible before. When this is set, the text below the headline that is
445 exposed is also shown.
447 By default this is off for all contexts.
448 Instead of t, this can also be an alist specifying this option for different
449 contexts. See `org-show-hierarchy-above' for valid contexts."
450 :group 'org-reveal-location
451 :type org-context-choice)
453 (defgroup org-cycle nil
454 "Options concerning visibility cycling in Org-mode."
455 :tag "Org Cycle"
456 :group 'org-structure)
458 (defcustom org-drawers '("PROPERTIES" "CLOCK")
459 "Names of drawers. Drawers are not opened by cycling on the headline above.
460 Drawers only open with a TAB on the drawer line itself. A drawer looks like
461 this:
462 :DRAWERNAME:
463 .....
464 :END:
465 The drawer \"PROPERTIES\" is special for capturing properties through
466 the property API.
468 Drawers can be defined on the per-file basis with a line like:
470 #+DRAWERS: HIDDEN STATE PROPERTIES"
471 :group 'org-structure
472 :type '(repeat (string :tag "Drawer Name")))
474 (defcustom org-cycle-global-at-bob nil
475 "Cycle globally if cursor is at beginning of buffer and not at a headline.
476 This makes it possible to do global cycling without having to use S-TAB or
477 C-u TAB. For this special case to work, the first line of the buffer
478 must not be a headline - it may be empty ot some other text. When used in
479 this way, `org-cycle-hook' is disables temporarily, to make sure the
480 cursor stays at the beginning of the buffer.
481 When this option is nil, don't do anything special at the beginning
482 of the buffer."
483 :group 'org-cycle
484 :type 'boolean)
486 (defcustom org-cycle-emulate-tab t
487 "Where should `org-cycle' emulate TAB.
488 nil Never
489 white Only in completely white lines
490 whitestart Only at the beginning of lines, before the first non-white char
491 t Everywhere except in headlines
492 exc-hl-bol Everywhere except at the start of a headline
493 If TAB is used in a place where it does not emulate TAB, the current subtree
494 visibility is cycled."
495 :group 'org-cycle
496 :type '(choice (const :tag "Never" nil)
497 (const :tag "Only in completely white lines" white)
498 (const :tag "Before first char in a line" whitestart)
499 (const :tag "Everywhere except in headlines" t)
500 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
503 (defcustom org-cycle-separator-lines 2
504 "Number of empty lines needed to keep an empty line between collapsed trees.
505 If you leave an empty line between the end of a subtree and the following
506 headline, this empty line is hidden when the subtree is folded.
507 Org-mode will leave (exactly) one empty line visible if the number of
508 empty lines is equal or larger to the number given in this variable.
509 So the default 2 means, at least 2 empty lines after the end of a subtree
510 are needed to produce free space between a collapsed subtree and the
511 following headline.
513 Special case: when 0, never leave empty lines in collapsed view."
514 :group 'org-cycle
515 :type 'integer)
517 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
518 org-cycle-hide-drawers
519 org-cycle-show-empty-lines
520 org-optimize-window-after-visibility-change)
521 "Hook that is run after `org-cycle' has changed the buffer visibility.
522 The function(s) in this hook must accept a single argument which indicates
523 the new state that was set by the most recent `org-cycle' command. The
524 argument is a symbol. After a global state change, it can have the values
525 `overview', `content', or `all'. After a local state change, it can have
526 the values `folded', `children', or `subtree'."
527 :group 'org-cycle
528 :type 'hook)
530 (defgroup org-edit-structure nil
531 "Options concerning structure editing in Org-mode."
532 :tag "Org Edit Structure"
533 :group 'org-structure)
535 (defcustom org-odd-levels-only nil
536 "Non-nil means, skip even levels and only use odd levels for the outline.
537 This has the effect that two stars are being added/taken away in
538 promotion/demotion commands. It also influences how levels are
539 handled by the exporters.
540 Changing it requires restart of `font-lock-mode' to become effective
541 for fontification also in regions already fontified.
542 You may also set this on a per-file basis by adding one of the following
543 lines to the buffer:
545 #+STARTUP: odd
546 #+STARTUP: oddeven"
547 :group 'org-edit-structure
548 :group 'org-font-lock
549 :type 'boolean)
551 (defcustom org-adapt-indentation t
552 "Non-nil means, adapt indentation when promoting and demoting.
553 When this is set and the *entire* text in an entry is indented, the
554 indentation is increased by one space in a demotion command, and
555 decreased by one in a promotion command. If any line in the entry
556 body starts at column 0, indentation is not changed at all."
557 :group 'org-edit-structure
558 :type 'boolean)
560 (defcustom org-special-ctrl-a/e nil
561 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
562 When t, `C-a' will bring back the cursor to the beginning of the
563 headline text, i.e. after the stars and after a possible TODO keyword.
564 In an item, this will be the position after the bullet.
565 When the cursor is already at that position, another `C-a' will bring
566 it to the beginning of the line.
567 `C-e' will jump to the end of the headline, ignoring the presence of tags
568 in the headline. A second `C-e' will then jump to the true end of the
569 line, after any tags.
570 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
571 and only a directly following, identical keypress will bring the cursor
572 to the special positions."
573 :group 'org-edit-structure
574 :type '(choice
575 (const :tag "off" nil)
576 (const :tag "after bullet first" t)
577 (const :tag "border first" reversed)))
579 (if (fboundp 'defvaralias)
580 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
582 (defcustom org-special-ctrl-k nil
583 "Non-nil means `C-k' will behave specially in headlines.
584 When nil, `C-k' will call the default `kill-line' command.
585 When t, the following will happen while the cursor is in the headline:
587 - When the cursor is at the beginning of a headline, kill the entire
588 line and possible the folded subtree below the line.
589 - When in the middle of the headline text, kill the headline up to the tags.
590 - When after the headline text, kill the tags."
591 :group 'org-edit-structure
592 :type 'boolean)
594 (defcustom org-M-RET-may-split-line '((default . t))
595 "Non-nil means, M-RET will split the line at the cursor position.
596 When nil, it will go to the end of the line before making a
597 new line.
598 You may also set this option in a different way for different
599 contexts. Valid contexts are:
601 headline when creating a new headline
602 item when creating a new item
603 table in a table field
604 default the value to be used for all contexts not explicitly
605 customized"
606 :group 'org-structure
607 :group 'org-table
608 :type '(choice
609 (const :tag "Always" t)
610 (const :tag "Never" nil)
611 (repeat :greedy t :tag "Individual contexts"
612 (cons
613 (choice :tag "Context"
614 (const headline)
615 (const item)
616 (const table)
617 (const default))
618 (boolean)))))
621 (defcustom org-blank-before-new-entry '((heading . nil)
622 (plain-list-item . nil))
623 "Should `org-insert-heading' leave a blank line before new heading/item?
624 The value is an alist, with `heading' and `plain-list-item' as car,
625 and a boolean flag as cdr."
626 :group 'org-edit-structure
627 :type '(list
628 (cons (const heading) (boolean))
629 (cons (const plain-list-item) (boolean))))
631 (defcustom org-insert-heading-hook nil
632 "Hook being run after inserting a new heading."
633 :group 'org-edit-structure
634 :type 'hook)
636 (defcustom org-enable-fixed-width-editor t
637 "Non-nil means, lines starting with \":\" are treated as fixed-width.
638 This currently only means, they are never auto-wrapped.
639 When nil, such lines will be treated like ordinary lines.
640 See also the QUOTE keyword."
641 :group 'org-edit-structure
642 :type 'boolean)
644 (defcustom org-goto-auto-isearch t
645 "Non-nil means, typing characters in org-goto starts incremental search."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defgroup org-sparse-trees nil
650 "Options concerning sparse trees in Org-mode."
651 :tag "Org Sparse Trees"
652 :group 'org-structure)
654 (defcustom org-highlight-sparse-tree-matches t
655 "Non-nil means, highlight all matches that define a sparse tree.
656 The highlights will automatically disappear the next time the buffer is
657 changed by an edit command."
658 :group 'org-sparse-trees
659 :type 'boolean)
661 (defcustom org-remove-highlights-with-change t
662 "Non-nil means, any change to the buffer will remove temporary highlights.
663 Such highlights are created by `org-occur' and `org-clock-display'.
664 When nil, `C-c C-c needs to be used to get rid of the highlights.
665 The highlights created by `org-preview-latex-fragment' always need
666 `C-c C-c' to be removed."
667 :group 'org-sparse-trees
668 :group 'org-time
669 :type 'boolean)
672 (defcustom org-occur-hook '(org-first-headline-recenter)
673 "Hook that is run after `org-occur' has constructed a sparse tree.
674 This can be used to recenter the window to show as much of the structure
675 as possible."
676 :group 'org-sparse-trees
677 :type 'hook)
679 (defgroup org-plain-lists nil
680 "Options concerning plain lists in Org-mode."
681 :tag "Org Plain lists"
682 :group 'org-structure)
684 (defcustom org-cycle-include-plain-lists nil
685 "Non-nil means, include plain lists into visibility cycling.
686 This means that during cycling, plain list items will *temporarily* be
687 interpreted as outline headlines with a level given by 1000+i where i is the
688 indentation of the bullet. In all other operations, plain list items are
689 not seen as headlines. For example, you cannot assign a TODO keyword to
690 such an item."
691 :group 'org-plain-lists
692 :type 'boolean)
694 (defcustom org-plain-list-ordered-item-terminator t
695 "The character that makes a line with leading number an ordered list item.
696 Valid values are ?. and ?\). To get both terminators, use t. While
697 ?. may look nicer, it creates the danger that a line with leading
698 number may be incorrectly interpreted as an item. ?\) therefore is
699 the safe choice."
700 :group 'org-plain-lists
701 :type '(choice (const :tag "dot like in \"2.\"" ?.)
702 (const :tag "paren like in \"2)\"" ?\))
703 (const :tab "both" t)))
705 (defcustom org-auto-renumber-ordered-lists t
706 "Non-nil means, automatically renumber ordered plain lists.
707 Renumbering happens when the sequence have been changed with
708 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
709 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
710 :group 'org-plain-lists
711 :type 'boolean)
713 (defcustom org-provide-checkbox-statistics t
714 "Non-nil means, update checkbox statistics after insert and toggle.
715 When this is set, checkbox statistics is updated each time you either insert
716 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
717 with \\[org-ctrl-c-ctrl-c\\]."
718 :group 'org-plain-lists
719 :type 'boolean)
721 (defgroup org-archive nil
722 "Options concerning archiving in Org-mode."
723 :tag "Org Archive"
724 :group 'org-structure)
726 (defcustom org-archive-tag "ARCHIVE"
727 "The tag that marks a subtree as archived.
728 An archived subtree does not open during visibility cycling, and does
729 not contribute to the agenda listings.
730 After changing this, font-lock must be restarted in the relevant buffers to
731 get the proper fontification."
732 :group 'org-archive
733 :group 'org-keywords
734 :type 'string)
736 (defcustom org-agenda-skip-archived-trees t
737 "Non-nil means, the agenda will skip any items located in archived trees.
738 An archived tree is a tree marked with the tag ARCHIVE."
739 :group 'org-archive
740 :group 'org-agenda-skip
741 :type 'boolean)
743 (defcustom org-cycle-open-archived-trees nil
744 "Non-nil means, `org-cycle' will open archived trees.
745 An archived tree is a tree marked with the tag ARCHIVE.
746 When nil, archived trees will stay folded. You can still open them with
747 normal outline commands like `show-all', but not with the cycling commands."
748 :group 'org-archive
749 :group 'org-cycle
750 :type 'boolean)
752 (defcustom org-sparse-tree-open-archived-trees nil
753 "Non-nil means sparse tree construction shows matches in archived trees.
754 When nil, matches in these trees are highlighted, but the trees are kept in
755 collapsed state."
756 :group 'org-archive
757 :group 'org-sparse-trees
758 :type 'boolean)
760 (defcustom org-archive-location "%s_archive::"
761 "The location where subtrees should be archived.
762 This string consists of two parts, separated by a double-colon.
764 The first part is a file name - when omitted, archiving happens in the same
765 file. %s will be replaced by the current file name (without directory part).
766 Archiving to a different file is useful to keep archived entries from
767 contributing to the Org-mode Agenda.
769 The part after the double colon is a headline. The archived entries will be
770 filed under that headline. When omitted, the subtrees are simply filed away
771 at the end of the file, as top-level entries.
773 Here are a few examples:
774 \"%s_archive::\"
775 If the current file is Projects.org, archive in file
776 Projects.org_archive, as top-level trees. This is the default.
778 \"::* Archived Tasks\"
779 Archive in the current file, under the top-level headline
780 \"* Archived Tasks\".
782 \"~/org/archive.org::\"
783 Archive in file ~/org/archive.org (absolute path), as top-level trees.
785 \"basement::** Finished Tasks\"
786 Archive in file ./basement (relative path), as level 3 trees
787 below the level 2 heading \"** Finished Tasks\".
789 You may set this option on a per-file basis by adding to the buffer a
790 line like
792 #+ARCHIVE: basement::** Finished Tasks"
793 :group 'org-archive
794 :type 'string)
796 (defcustom org-archive-mark-done t
797 "Non-nil means, mark entries as DONE when they are moved to the archive file.
798 This can be a string to set the keyword to use. When t, Org-mode will
799 use the first keyword in its list that means done."
800 :group 'org-archive
801 :type '(choice
802 (const :tag "No" nil)
803 (const :tag "Yes" t)
804 (string :tag "Use this keyword")))
806 (defcustom org-archive-stamp-time t
807 "Non-nil means, add a time stamp to entries moved to an archive file.
808 This variable is obsolete and has no effect anymore, instead add ot remove
809 `time' from the variablle `org-archive-save-context-info'."
810 :group 'org-archive
811 :type 'boolean)
813 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
814 "Parts of context info that should be stored as properties when archiving.
815 When a subtree is moved to an archive file, it looses information given by
816 context, like inherited tags, the category, and possibly also the TODO
817 state (depending on the variable `org-archive-mark-done').
818 This variable can be a list of any of the following symbols:
820 time The time of archiving.
821 file The file where the entry originates.
822 itags The local tags, in the headline of the subtree.
823 ltags The tags the subtree inherits from further up the hierarchy.
824 todo The pre-archive TODO state.
825 category The category, taken from file name or #+CATEGORY lines.
826 olpath The outline path to the item. These are all headlines above
827 the current item, separated by /, like a file path.
829 For each symbol present in the list, a property will be created in
830 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
831 information."
832 :group 'org-archive
833 :type '(set :greedy t
834 (const :tag "Time" time)
835 (const :tag "File" file)
836 (const :tag "Category" category)
837 (const :tag "TODO state" todo)
838 (const :tag "TODO state" priority)
839 (const :tag "Inherited tags" itags)
840 (const :tag "Outline path" olpath)
841 (const :tag "Local tags" ltags)))
843 (defgroup org-imenu-and-speedbar nil
844 "Options concerning imenu and speedbar in Org-mode."
845 :tag "Org Imenu and Speedbar"
846 :group 'org-structure)
848 (defcustom org-imenu-depth 2
849 "The maximum level for Imenu access to Org-mode headlines.
850 This also applied for speedbar access."
851 :group 'org-imenu-and-speedbar
852 :type 'number)
854 (defgroup org-table nil
855 "Options concerning tables in Org-mode."
856 :tag "Org Table"
857 :group 'org)
859 (defcustom org-enable-table-editor 'optimized
860 "Non-nil means, lines starting with \"|\" are handled by the table editor.
861 When nil, such lines will be treated like ordinary lines.
863 When equal to the symbol `optimized', the table editor will be optimized to
864 do the following:
865 - Automatic overwrite mode in front of whitespace in table fields.
866 This makes the structure of the table stay in tact as long as the edited
867 field does not exceed the column width.
868 - Minimize the number of realigns. Normally, the table is aligned each time
869 TAB or RET are pressed to move to another field. With optimization this
870 happens only if changes to a field might have changed the column width.
871 Optimization requires replacing the functions `self-insert-command',
872 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
873 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
874 very good at guessing when a re-align will be necessary, but you can always
875 force one with \\[org-ctrl-c-ctrl-c].
877 If you would like to use the optimized version in Org-mode, but the
878 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
880 This variable can be used to turn on and off the table editor during a session,
881 but in order to toggle optimization, a restart is required.
883 See also the variable `org-table-auto-blank-field'."
884 :group 'org-table
885 :type '(choice
886 (const :tag "off" nil)
887 (const :tag "on" t)
888 (const :tag "on, optimized" optimized)))
890 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
891 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
892 In the optimized version, the table editor takes over all simple keys that
893 normally just insert a character. In tables, the characters are inserted
894 in a way to minimize disturbing the table structure (i.e. in overwrite mode
895 for empty fields). Outside tables, the correct binding of the keys is
896 restored.
898 The default for this option is t if the optimized version is also used in
899 Org-mode. See the variable `org-enable-table-editor' for details. Changing
900 this variable requires a restart of Emacs to become effective."
901 :group 'org-table
902 :type 'boolean)
904 (defcustom orgtbl-radio-table-templates
905 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
906 % END RECEIVE ORGTBL %n
907 \\begin{comment}
908 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
909 | | |
910 \\end{comment}\n")
911 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
912 @c END RECEIVE ORGTBL %n
913 @ignore
914 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
915 | | |
916 @end ignore\n")
917 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
918 <!-- END RECEIVE ORGTBL %n -->
919 <!--
920 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
921 | | |
922 -->\n"))
923 "Templates for radio tables in different major modes.
924 All occurrences of %n in a template will be replaced with the name of the
925 table, obtained by prompting the user."
926 :group 'org-table
927 :type '(repeat
928 (list (symbol :tag "Major mode")
929 (string :tag "Format"))))
931 (defgroup org-table-settings nil
932 "Settings for tables in Org-mode."
933 :tag "Org Table Settings"
934 :group 'org-table)
936 (defcustom org-table-default-size "5x2"
937 "The default size for newly created tables, Columns x Rows."
938 :group 'org-table-settings
939 :type 'string)
941 (defcustom org-table-number-regexp
942 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
943 "Regular expression for recognizing numbers in table columns.
944 If a table column contains mostly numbers, it will be aligned to the
945 right. If not, it will be aligned to the left.
947 The default value of this option is a regular expression which allows
948 anything which looks remotely like a number as used in scientific
949 context. For example, all of the following will be considered a
950 number:
951 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
953 Other options offered by the customize interface are more restrictive."
954 :group 'org-table-settings
955 :type '(choice
956 (const :tag "Positive Integers"
957 "^[0-9]+$")
958 (const :tag "Integers"
959 "^[-+]?[0-9]+$")
960 (const :tag "Floating Point Numbers"
961 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
962 (const :tag "Floating Point Number or Integer"
963 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
964 (const :tag "Exponential, Floating point, Integer"
965 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
966 (const :tag "Very General Number-Like, including hex"
967 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
968 (string :tag "Regexp:")))
970 (defcustom org-table-number-fraction 0.5
971 "Fraction of numbers in a column required to make the column align right.
972 In a column all non-white fields are considered. If at least this
973 fraction of fields is matched by `org-table-number-fraction',
974 alignment to the right border applies."
975 :group 'org-table-settings
976 :type 'number)
978 (defgroup org-table-editing nil
979 "Behavior of tables during editing in Org-mode."
980 :tag "Org Table Editing"
981 :group 'org-table)
983 (defcustom org-table-automatic-realign t
984 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
985 When nil, aligning is only done with \\[org-table-align], or after column
986 removal/insertion."
987 :group 'org-table-editing
988 :type 'boolean)
990 (defcustom org-table-auto-blank-field t
991 "Non-nil means, automatically blank table field when starting to type into it.
992 This only happens when typing immediately after a field motion
993 command (TAB, S-TAB or RET).
994 Only relevant when `org-enable-table-editor' is equal to `optimized'."
995 :group 'org-table-editing
996 :type 'boolean)
998 (defcustom org-table-tab-jumps-over-hlines t
999 "Non-nil means, tab in the last column of a table with jump over a hline.
1000 If a horizontal separator line is following the current line,
1001 `org-table-next-field' can either create a new row before that line, or jump
1002 over the line. When this option is nil, a new line will be created before
1003 this line."
1004 :group 'org-table-editing
1005 :type 'boolean)
1007 (defcustom org-table-tab-recognizes-table.el t
1008 "Non-nil means, TAB will automatically notice a table.el table.
1009 When it sees such a table, it moves point into it and - if necessary -
1010 calls `table-recognize-table'."
1011 :group 'org-table-editing
1012 :type 'boolean)
1014 (defgroup org-table-calculation nil
1015 "Options concerning tables in Org-mode."
1016 :tag "Org Table Calculation"
1017 :group 'org-table)
1019 (defcustom org-table-use-standard-references t
1020 "Should org-mode work with table refrences like B3 instead of @3$2?
1021 Possible values are:
1022 nil never use them
1023 from accept as input, do not present for editing
1024 t: accept as input and present for editing"
1025 :group 'org-table-calculation
1026 :type '(choice
1027 (const :tag "Never, don't even check unser input for them" nil)
1028 (const :tag "Always, both as user input, and when editing" t)
1029 (const :tag "Convert user input, don't offer during editing" 'from)))
1031 (defcustom org-table-copy-increment t
1032 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1033 :group 'org-table-calculation
1034 :type 'boolean)
1036 (defcustom org-calc-default-modes
1037 '(calc-internal-prec 12
1038 calc-float-format (float 5)
1039 calc-angle-mode deg
1040 calc-prefer-frac nil
1041 calc-symbolic-mode nil
1042 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1043 calc-display-working-message t
1045 "List with Calc mode settings for use in calc-eval for table formulas.
1046 The list must contain alternating symbols (Calc modes variables and values).
1047 Don't remove any of the default settings, just change the values. Org-mode
1048 relies on the variables to be present in the list."
1049 :group 'org-table-calculation
1050 :type 'plist)
1052 (defcustom org-table-formula-evaluate-inline t
1053 "Non-nil means, TAB and RET evaluate a formula in current table field.
1054 If the current field starts with an equal sign, it is assumed to be a formula
1055 which should be evaluated as described in the manual and in the documentation
1056 string of the command `org-table-eval-formula'. This feature requires the
1057 Emacs calc package.
1058 When this variable is nil, formula calculation is only available through
1059 the command \\[org-table-eval-formula]."
1060 :group 'org-table-calculation
1061 :type 'boolean)
1063 (defcustom org-table-formula-use-constants t
1064 "Non-nil means, interpret constants in formulas in tables.
1065 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1066 by the value given in `org-table-formula-constants', or by a value obtained
1067 from the `constants.el' package."
1068 :group 'org-table-calculation
1069 :type 'boolean)
1071 (defcustom org-table-formula-constants nil
1072 "Alist with constant names and values, for use in table formulas.
1073 The car of each element is a name of a constant, without the `$' before it.
1074 The cdr is the value as a string. For example, if you'd like to use the
1075 speed of light in a formula, you would configure
1077 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1079 and then use it in an equation like `$1*$c'.
1081 Constants can also be defined on a per-file basis using a line like
1083 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1084 :group 'org-table-calculation
1085 :type '(repeat
1086 (cons (string :tag "name")
1087 (string :tag "value"))))
1089 (defvar org-table-formula-constants-local nil
1090 "Local version of `org-table-formula-constants'.")
1091 (make-variable-buffer-local 'org-table-formula-constants-local)
1093 (defcustom org-table-allow-automatic-line-recalculation t
1094 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1095 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1096 :group 'org-table-calculation
1097 :type 'boolean)
1099 (defgroup org-link nil
1100 "Options concerning links in Org-mode."
1101 :tag "Org Link"
1102 :group 'org)
1104 (defvar org-link-abbrev-alist-local nil
1105 "Buffer-local version of `org-link-abbrev-alist', which see.
1106 The value of this is taken from the #+LINK lines.")
1107 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1109 (defcustom org-link-abbrev-alist nil
1110 "Alist of link abbreviations.
1111 The car of each element is a string, to be replaced at the start of a link.
1112 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1113 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1115 [[linkkey:tag][description]]
1117 If REPLACE is a string, the tag will simply be appended to create the link.
1118 If the string contains \"%s\", the tag will be inserted there.
1120 REPLACE may also be a function that will be called with the tag as the
1121 only argument to create the link, which should be returned as a string.
1123 See the manual for examples."
1124 :group 'org-link
1125 :type 'alist)
1127 (defcustom org-descriptive-links t
1128 "Non-nil means, hide link part and only show description of bracket links.
1129 Bracket links are like [[link][descritpion]]. This variable sets the initial
1130 state in new org-mode buffers. The setting can then be toggled on a
1131 per-buffer basis from the Org->Hyperlinks menu."
1132 :group 'org-link
1133 :type 'boolean)
1135 (defcustom org-link-file-path-type 'adaptive
1136 "How the path name in file links should be stored.
1137 Valid values are:
1139 relative Relative to the current directory, i.e. the directory of the file
1140 into which the link is being inserted.
1141 absolute Absolute path, if possible with ~ for home directory.
1142 noabbrev Absolute path, no abbreviation of home directory.
1143 adaptive Use relative path for files in the current directory and sub-
1144 directories of it. For other files, use an absolute path."
1145 :group 'org-link
1146 :type '(choice
1147 (const relative)
1148 (const absolute)
1149 (const noabbrev)
1150 (const adaptive)))
1152 (defcustom org-activate-links '(bracket angle plain radio tag date)
1153 "Types of links that should be activated in Org-mode files.
1154 This is a list of symbols, each leading to the activation of a certain link
1155 type. In principle, it does not hurt to turn on most link types - there may
1156 be a small gain when turning off unused link types. The types are:
1158 bracket The recommended [[link][description]] or [[link]] links with hiding.
1159 angular Links in angular brackes that may contain whitespace like
1160 <bbdb:Carsten Dominik>.
1161 plain Plain links in normal text, no whitespace, like http://google.com.
1162 radio Text that is matched by a radio target, see manual for details.
1163 tag Tag settings in a headline (link to tag search).
1164 date Time stamps (link to calendar).
1166 Changing this variable requires a restart of Emacs to become effective."
1167 :group 'org-link
1168 :type '(set (const :tag "Double bracket links (new style)" bracket)
1169 (const :tag "Angular bracket links (old style)" angular)
1170 (const :tag "plain text links" plain)
1171 (const :tag "Radio target matches" radio)
1172 (const :tag "Tags" tag)
1173 (const :tag "Tags" target)
1174 (const :tag "Timestamps" date)))
1176 (defgroup org-link-store nil
1177 "Options concerning storing links in Org-mode"
1178 :tag "Org Store Link"
1179 :group 'org-link)
1181 (defcustom org-email-link-description-format "Email %c: %.30s"
1182 "Format of the description part of a link to an email or usenet message.
1183 The following %-excapes will be replaced by corresponding information:
1185 %F full \"From\" field
1186 %f name, taken from \"From\" field, address if no name
1187 %T full \"To\" field
1188 %t first name in \"To\" field, address if no name
1189 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1190 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1191 %s subject
1192 %m message-id.
1194 You may use normal field width specification between the % and the letter.
1195 This is for example useful to limit the length of the subject.
1197 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1198 :group 'org-link-store
1199 :type 'string)
1201 (defcustom org-from-is-user-regexp
1202 (let (r1 r2)
1203 (when (and user-mail-address (not (string= user-mail-address "")))
1204 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1205 (when (and user-full-name (not (string= user-full-name "")))
1206 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1207 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1208 "Regexp mached against the \"From:\" header of an email or usenet message.
1209 It should match if the message is from the user him/herself."
1210 :group 'org-link-store
1211 :type 'regexp)
1213 (defcustom org-context-in-file-links t
1214 "Non-nil means, file links from `org-store-link' contain context.
1215 A search string will be added to the file name with :: as separator and
1216 used to find the context when the link is activated by the command
1217 `org-open-at-point'.
1218 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1219 negates this setting for the duration of the command."
1220 :group 'org-link-store
1221 :type 'boolean)
1223 (defcustom org-keep-stored-link-after-insertion nil
1224 "Non-nil means, keep link in list for entire session.
1226 The command `org-store-link' adds a link pointing to the current
1227 location to an internal list. These links accumulate during a session.
1228 The command `org-insert-link' can be used to insert links into any
1229 Org-mode file (offering completion for all stored links). When this
1230 option is nil, every link which has been inserted once using \\[org-insert-link]
1231 will be removed from the list, to make completing the unused links
1232 more efficient."
1233 :group 'org-link-store
1234 :type 'boolean)
1236 (defcustom org-usenet-links-prefer-google nil
1237 "Non-nil means, `org-store-link' will create web links to Google groups.
1238 When nil, Gnus will be used for such links.
1239 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1240 negates this setting for the duration of the command."
1241 :group 'org-link-store
1242 :type 'boolean)
1244 (defgroup org-link-follow nil
1245 "Options concerning following links in Org-mode"
1246 :tag "Org Follow Link"
1247 :group 'org-link)
1249 (defcustom org-tab-follows-link nil
1250 "Non-nil means, on links TAB will follow the link.
1251 Needs to be set before org.el is loaded."
1252 :group 'org-link-follow
1253 :type 'boolean)
1255 (defcustom org-return-follows-link nil
1256 "Non-nil means, on links RET will follow the link.
1257 Needs to be set before org.el is loaded."
1258 :group 'org-link-follow
1259 :type 'boolean)
1261 (defcustom org-mouse-1-follows-link t
1262 "Non-nil means, mouse-1 on a link will follow the link.
1263 A longer mouse click will still set point. Does not wortk on XEmacs.
1264 Needs to be set before org.el is loaded."
1265 :group 'org-link-follow
1266 :type 'boolean)
1268 (defcustom org-mark-ring-length 4
1269 "Number of different positions to be recorded in the ring
1270 Changing this requires a restart of Emacs to work correctly."
1271 :group 'org-link-follow
1272 :type 'interger)
1274 (defcustom org-link-frame-setup
1275 '((vm . vm-visit-folder-other-frame)
1276 (gnus . gnus-other-frame)
1277 (file . find-file-other-window))
1278 "Setup the frame configuration for following links.
1279 When following a link with Emacs, it may often be useful to display
1280 this link in another window or frame. This variable can be used to
1281 set this up for the different types of links.
1282 For VM, use any of
1283 `vm-visit-folder'
1284 `vm-visit-folder-other-frame'
1285 For Gnus, use any of
1286 `gnus'
1287 `gnus-other-frame'
1288 For FILE, use any of
1289 `find-file'
1290 `find-file-other-window'
1291 `find-file-other-frame'
1292 For the calendar, use the variable `calendar-setup'.
1293 For BBDB, it is currently only possible to display the matches in
1294 another window."
1295 :group 'org-link-follow
1296 :type '(list
1297 (cons (const vm)
1298 (choice
1299 (const vm-visit-folder)
1300 (const vm-visit-folder-other-window)
1301 (const vm-visit-folder-other-frame)))
1302 (cons (const gnus)
1303 (choice
1304 (const gnus)
1305 (const gnus-other-frame)))
1306 (cons (const file)
1307 (choice
1308 (const find-file)
1309 (const find-file-other-window)
1310 (const find-file-other-frame)))))
1312 (defcustom org-display-internal-link-with-indirect-buffer nil
1313 "Non-nil means, use indirect buffer to display infile links.
1314 Activating internal links (from one location in a file to another location
1315 in the same file) normally just jumps to the location. When the link is
1316 activated with a C-u prefix (or with mouse-3), the link is displayed in
1317 another window. When this option is set, the other window actually displays
1318 an indirect buffer clone of the current buffer, to avoid any visibility
1319 changes to the current buffer."
1320 :group 'org-link-follow
1321 :type 'boolean)
1323 (defcustom org-open-non-existing-files nil
1324 "Non-nil means, `org-open-file' will open non-existing files.
1325 When nil, an error will be generated."
1326 :group 'org-link-follow
1327 :type 'boolean)
1329 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1330 "Function and arguments to call for following mailto links.
1331 This is a list with the first element being a lisp function, and the
1332 remaining elements being arguments to the function. In string arguments,
1333 %a will be replaced by the address, and %s will be replaced by the subject
1334 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1335 :group 'org-link-follow
1336 :type '(choice
1337 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1338 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1339 (const :tag "message-mail" (message-mail "%a" "%s"))
1340 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1342 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1343 "Non-nil means, ask for confirmation before executing shell links.
1344 Shell links can be dangerous: just think about a link
1346 [[shell:rm -rf ~/*][Google Search]]
1348 This link would show up in your Org-mode document as \"Google Search\",
1349 but really it would remove your entire home directory.
1350 Therefore we advise against setting this variable to nil.
1351 Just change it to `y-or-n-p' of you want to confirm with a
1352 single keystroke rather than having to type \"yes\"."
1353 :group 'org-link-follow
1354 :type '(choice
1355 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1356 (const :tag "with y-or-n (faster)" y-or-n-p)
1357 (const :tag "no confirmation (dangerous)" nil)))
1359 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1360 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1361 Elisp links can be dangerous: just think about a link
1363 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1365 This link would show up in your Org-mode document as \"Google Search\",
1366 but really it would remove your entire home directory.
1367 Therefore we advise against setting this variable to nil.
1368 Just change it to `y-or-n-p' of you want to confirm with a
1369 single keystroke rather than having to type \"yes\"."
1370 :group 'org-link-follow
1371 :type '(choice
1372 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1373 (const :tag "with y-or-n (faster)" y-or-n-p)
1374 (const :tag "no confirmation (dangerous)" nil)))
1376 (defconst org-file-apps-defaults-gnu
1377 '((remote . emacs)
1378 (t . mailcap))
1379 "Default file applications on a UNIX or GNU/Linux system.
1380 See `org-file-apps'.")
1382 (defconst org-file-apps-defaults-macosx
1383 '((remote . emacs)
1384 (t . "open %s")
1385 ("ps" . "gv %s")
1386 ("ps.gz" . "gv %s")
1387 ("eps" . "gv %s")
1388 ("eps.gz" . "gv %s")
1389 ("dvi" . "xdvi %s")
1390 ("fig" . "xfig %s"))
1391 "Default file applications on a MacOS X system.
1392 The system \"open\" is known as a default, but we use X11 applications
1393 for some files for which the OS does not have a good default.
1394 See `org-file-apps'.")
1396 (defconst org-file-apps-defaults-windowsnt
1397 (list
1398 '(remote . emacs)
1399 (cons t
1400 (list (if (featurep 'xemacs)
1401 'mswindows-shell-execute
1402 'w32-shell-execute)
1403 "open" 'file)))
1404 "Default file applications on a Windows NT system.
1405 The system \"open\" is used for most files.
1406 See `org-file-apps'.")
1408 (defcustom org-file-apps
1410 ("txt" . emacs)
1411 ("tex" . emacs)
1412 ("ltx" . emacs)
1413 ("org" . emacs)
1414 ("el" . emacs)
1415 ("bib" . emacs)
1417 "External applications for opening `file:path' items in a document.
1418 Org-mode uses system defaults for different file types, but
1419 you can use this variable to set the application for a given file
1420 extension. The entries in this list are cons cells where the car identifies
1421 files and the cdr the corresponding command. Possible values for the
1422 file identifier are
1423 \"ext\" A string identifying an extension
1424 `directory' Matches a directory
1425 `remote' Matches a remote file, accessible through tramp or efs.
1426 Remote files most likely should be visited through Emacs
1427 because external applications cannot handle such paths.
1428 t Default for all remaining files
1430 Possible values for the command are:
1431 `emacs' The file will be visited by the current Emacs process.
1432 `default' Use the default application for this file type.
1433 string A command to be executed by a shell; %s will be replaced
1434 by the path to the file.
1435 sexp A Lisp form which will be evaluated. The file path will
1436 be available in the Lisp variable `file'.
1437 For more examples, see the system specific constants
1438 `org-file-apps-defaults-macosx'
1439 `org-file-apps-defaults-windowsnt'
1440 `org-file-apps-defaults-gnu'."
1441 :group 'org-link-follow
1442 :type '(repeat
1443 (cons (choice :value ""
1444 (string :tag "Extension")
1445 (const :tag "Default for unrecognized files" t)
1446 (const :tag "Remote file" remote)
1447 (const :tag "Links to a directory" directory))
1448 (choice :value ""
1449 (const :tag "Visit with Emacs" emacs)
1450 (const :tag "Use system default" default)
1451 (string :tag "Command")
1452 (sexp :tag "Lisp form")))))
1454 (defcustom org-mhe-search-all-folders nil
1455 "Non-nil means, that the search for the mh-message will be extended to
1456 all folders if the message cannot be found in the folder given in the link.
1457 Searching all folders is very efficient with one of the search engines
1458 supported by MH-E, but will be slow with pick."
1459 :group 'org-link-follow
1460 :type 'boolean)
1462 (defgroup org-remember nil
1463 "Options concerning interaction with remember.el."
1464 :tag "Org Remember"
1465 :group 'org)
1467 (defcustom org-directory "~/org"
1468 "Directory with org files.
1469 This directory will be used as default to prompt for org files.
1470 Used by the hooks for remember.el."
1471 :group 'org-remember
1472 :type 'directory)
1474 (defcustom org-default-notes-file "~/.notes"
1475 "Default target for storing notes.
1476 Used by the hooks for remember.el. This can be a string, or nil to mean
1477 the value of `remember-data-file'.
1478 You can set this on a per-template basis with the variable
1479 `org-remember-templates'."
1480 :group 'org-remember
1481 :type '(choice
1482 (const :tag "Default from remember-data-file" nil)
1483 file))
1485 (defcustom org-remember-store-without-prompt t
1486 "Non-nil means, `C-c C-c' stores remember note without further promts.
1487 In this case, you need `C-u C-c C-c' to get the prompts for
1488 note file and headline.
1489 When this variable is nil, `C-c C-c' give you the prompts, and
1490 `C-u C-c C-c' trigger the fasttrack."
1491 :group 'org-remember
1492 :type 'boolean)
1494 (defcustom org-remember-interactive-interface 'refile
1495 "The interface to be used for interactive filing of remember notes.
1496 This is only used when the interactive mode for selecting a filing
1497 location is used (see the variable `org-remember-store-without-prompt').
1498 Allowed vaues are:
1499 outline The interface shows an outline of the relevant file
1500 and the correct heading is found by moving through
1501 the outline or by searching with incremental search.
1502 outline-path-completion Headlines in the current buffer are offered via
1503 completion.
1504 refile Use the refile interface, and offer headlines,
1505 possibly from different buffers."
1506 :group 'org-remember
1507 :type '(choice
1508 (const :tag "Refile" refile)
1509 (const :tag "Outline" outline)
1510 (const :tag "Outline-path-completion" outline-path-completion)))
1512 (defcustom org-goto-interface 'outline
1513 "The default interface to be used for `org-goto'.
1514 Allowed vaues are:
1515 outline The interface shows an outline of the relevant file
1516 and the correct heading is found by moving through
1517 the outline or by searching with incremental search.
1518 outline-path-completion Headlines in the current buffer are offered via
1519 completion."
1520 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1521 :type '(choice
1522 (const :tag "Outline" outline)
1523 (const :tag "Outline-path-completion" outline-path-completion)))
1525 (defcustom org-remember-default-headline ""
1526 "The headline that should be the default location in the notes file.
1527 When filing remember notes, the cursor will start at that position.
1528 You can set this on a per-template basis with the variable
1529 `org-remember-templates'."
1530 :group 'org-remember
1531 :type 'string)
1533 (defcustom org-remember-templates nil
1534 "Templates for the creation of remember buffers.
1535 When nil, just let remember make the buffer.
1536 When not nil, this is a list of 5-element lists. In each entry, the first
1537 element is the name of the template, which should be a single short word.
1538 The second element is a character, a unique key to select this template.
1539 The third element is the template. The fourth element is optional and can
1540 specify a destination file for remember items created with this template.
1541 The default file is given by `org-default-notes-file'. An optional fifth
1542 element can specify the headline in that file that should be offered
1543 first when the user is asked to file the entry. The default headline is
1544 given in the variable `org-remember-default-headline'.
1546 The template specifies the structure of the remember buffer. It should have
1547 a first line starting with a star, to act as the org-mode headline.
1548 Furthermore, the following %-escapes will be replaced with content:
1550 %^{prompt} Prompt the user for a string and replace this sequence with it.
1551 A default value and a completion table ca be specified like this:
1552 %^{prompt|default|completion2|completion3|...}
1553 %t time stamp, date only
1554 %T time stamp with date and time
1555 %u, %U like the above, but inactive time stamps
1556 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1557 You may define a prompt like %^{Please specify birthday}t
1558 %n user name (taken from `user-full-name')
1559 %a annotation, normally the link created with org-store-link
1560 %i initial content, the region active. If %i is indented,
1561 the entire inserted text will be indented as well.
1562 %c content of the clipboard, or current kill ring head
1563 %^g prompt for tags, with completion on tags in target file
1564 %^G prompt for tags, with completion all tags in all agenda files
1565 %:keyword specific information for certain link types, see below
1566 %[pathname] insert the contents of the file given by `pathname'
1567 %(sexp) evaluate elisp `(sexp)' and replace with the result
1568 %! Store this note immediately after filling the template
1570 %? After completing the template, position cursor here.
1572 Apart from these general escapes, you can access information specific to the
1573 link type that is created. For example, calling `remember' in emails or gnus
1574 will record the author and the subject of the message, which you can access
1575 with %:author and %:subject, respectively. Here is a complete list of what
1576 is recorded for each link type.
1578 Link type | Available information
1579 -------------------+------------------------------------------------------
1580 bbdb | %:type %:name %:company
1581 vm, wl, mh, rmail | %:type %:subject %:message-id
1582 | %:from %:fromname %:fromaddress
1583 | %:to %:toname %:toaddress
1584 | %:fromto (either \"to NAME\" or \"from NAME\")
1585 gnus | %:group, for messages also all email fields
1586 w3, w3m | %:type %:url
1587 info | %:type %:file %:node
1588 calendar | %:type %:date"
1589 :group 'org-remember
1590 :get (lambda (var) ; Make sure all entries have 5 elements
1591 (mapcar (lambda (x)
1592 (if (not (stringp (car x))) (setq x (cons "" x)))
1593 (cond ((= (length x) 4) (append x '("")))
1594 ((= (length x) 3) (append x '("" "")))
1595 (t x)))
1596 (default-value var)))
1597 :type '(repeat
1598 :tag "enabled"
1599 (list :value ("" ?a "\n" nil nil)
1600 (string :tag "Name")
1601 (character :tag "Selection Key")
1602 (string :tag "Template")
1603 (choice
1604 (file :tag "Destination file")
1605 (const :tag "Prompt for file" nil))
1606 (choice
1607 (string :tag "Destination headline")
1608 (const :tag "Selection interface for heading")))))
1610 (defcustom org-reverse-note-order nil
1611 "Non-nil means, store new notes at the beginning of a file or entry.
1612 When nil, new notes will be filed to the end of a file or entry.
1613 This can also be a list with cons cells of regular expressions that
1614 are matched against file names, and values."
1615 :group 'org-remember
1616 :type '(choice
1617 (const :tag "Reverse always" t)
1618 (const :tag "Reverse never" nil)
1619 (repeat :tag "By file name regexp"
1620 (cons regexp boolean))))
1622 (defcustom org-refile-targets nil
1623 "Targets for refiling entries with \\[org-refile].
1624 This is list of cons cells. Each cell contains:
1625 - a specification of the files to be considered, either a list of files,
1626 or a symbol whose function or value fields will be used to retrieve
1627 a file name or a list of file names. Nil means, refile to a different
1628 heading in the current buffer.
1629 - A specification of how to find candidate refile targets. This may be
1630 any of
1631 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1632 This tag has to be present in all target headlines, inheritance will
1633 not be considered.
1634 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1635 todo keyword.
1636 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1637 headlines that are refiling targets.
1638 - a cons cell (:level . N). Any headline of level N is considered a target.
1639 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1640 ;; FIXME: what if there are a var and func with same name???
1641 :group 'org-remember
1642 :type '(repeat
1643 (cons
1644 (choice :value org-agenda-files
1645 (const :tag "All agenda files" org-agenda-files)
1646 (const :tag "Current buffer" nil)
1647 (function) (variable) (file))
1648 (choice :tag "Identify target headline by"
1649 (cons :tag "Specific tag" (const :tag) (string))
1650 (cons :tag "TODO keyword" (const :todo) (string))
1651 (cons :tag "Regular expression" (const :regexp) (regexp))
1652 (cons :tag "Level number" (const :level) (integer))
1653 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1655 (defcustom org-refile-use-outline-path nil
1656 "Non-nil means, provide refile targets as paths.
1657 So a level 3 headline will be available as level1/level2/level3.
1658 When the value is `file', also include the file name (without directory)
1659 into the path. When `full-file-path', include the full file path."
1660 :group 'org-remember
1661 :type '(choice
1662 (const :tag "Not" nil)
1663 (const :tag "Yes" t)
1664 (const :tag "Start with file name" file)
1665 (const :tag "Start with full file path" full-file-path)))
1667 (defgroup org-todo nil
1668 "Options concerning TODO items in Org-mode."
1669 :tag "Org TODO"
1670 :group 'org)
1672 (defgroup org-progress nil
1673 "Options concerning Progress logging in Org-mode."
1674 :tag "Org Progress"
1675 :group 'org-time)
1677 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1678 "List of TODO entry keyword sequences and their interpretation.
1679 \\<org-mode-map>This is a list of sequences.
1681 Each sequence starts with a symbol, either `sequence' or `type',
1682 indicating if the keywords should be interpreted as a sequence of
1683 action steps, or as different types of TODO items. The first
1684 keywords are states requiring action - these states will select a headline
1685 for inclusion into the global TODO list Org-mode produces. If one of
1686 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1687 signify that no further action is necessary. If \"|\" is not found,
1688 the last keyword is treated as the only DONE state of the sequence.
1690 The command \\[org-todo] cycles an entry through these states, and one
1691 additional state where no keyword is present. For details about this
1692 cycling, see the manual.
1694 TODO keywords and interpretation can also be set on a per-file basis with
1695 the special #+SEQ_TODO and #+TYP_TODO lines.
1697 Each keyword can optionally specify a character for fast state selection
1698 \(in combination with the variable `org-use-fast-todo-selection')
1699 and specifiers for state change logging, using the same syntax
1700 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1701 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1702 indicates to record a time stamp each time this state is selected.
1703 \"WAIT(w@)\" says that the user should in addition be prompted for a
1704 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1705 entering and when leaving this state.
1707 For backward compatibility, this variable may also be just a list
1708 of keywords - in this case the interptetation (sequence or type) will be
1709 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1710 :group 'org-todo
1711 :group 'org-keywords
1712 :type '(choice
1713 (repeat :tag "Old syntax, just keywords"
1714 (string :tag "Keyword"))
1715 (repeat :tag "New syntax"
1716 (cons
1717 (choice
1718 :tag "Interpretation"
1719 (const :tag "Sequence (cycling hits every state)" sequence)
1720 (const :tag "Type (cycling directly to DONE)" type))
1721 (repeat
1722 (string :tag "Keyword"))))))
1724 (defvar org-todo-keywords-1 nil
1725 "All TODO and DONE keywords active in a buffer.")
1726 (make-variable-buffer-local 'org-todo-keywords-1)
1727 (defvar org-todo-keywords-for-agenda nil)
1728 (defvar org-done-keywords-for-agenda nil)
1729 (defvar org-not-done-keywords nil)
1730 (make-variable-buffer-local 'org-not-done-keywords)
1731 (defvar org-done-keywords nil)
1732 (make-variable-buffer-local 'org-done-keywords)
1733 (defvar org-todo-heads nil)
1734 (make-variable-buffer-local 'org-todo-heads)
1735 (defvar org-todo-sets nil)
1736 (make-variable-buffer-local 'org-todo-sets)
1737 (defvar org-todo-log-states nil)
1738 (make-variable-buffer-local 'org-todo-log-states)
1739 (defvar org-todo-kwd-alist nil)
1740 (make-variable-buffer-local 'org-todo-kwd-alist)
1741 (defvar org-todo-key-alist nil)
1742 (make-variable-buffer-local 'org-todo-key-alist)
1743 (defvar org-todo-key-trigger nil)
1744 (make-variable-buffer-local 'org-todo-key-trigger)
1746 (defcustom org-todo-interpretation 'sequence
1747 "Controls how TODO keywords are interpreted.
1748 This variable is in principle obsolete and is only used for
1749 backward compatibility, if the interpretation of todo keywords is
1750 not given already in `org-todo-keywords'. See that variable for
1751 more information."
1752 :group 'org-todo
1753 :group 'org-keywords
1754 :type '(choice (const sequence)
1755 (const type)))
1757 (defcustom org-use-fast-todo-selection 'prefix
1758 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1759 This variable describes if and under what circumstances the cycling
1760 mechanism for TODO keywords will be replaced by a single-key, direct
1761 selection scheme.
1763 When nil, fast selection is never used.
1765 When the symbol `prefix', it will be used when `org-todo' is called with
1766 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1767 in an agenda buffer.
1769 When t, fast selection is used by default. In this case, the prefix
1770 argument forces cycling instead.
1772 In all cases, the special interface is only used if access keys have actually
1773 been assigned by the user, i.e. if keywords in the configuration are followed
1774 by a letter in parenthesis, like TODO(t)."
1775 :group 'org-todo
1776 :type '(choice
1777 (const :tag "Never" nil)
1778 (const :tag "By default" t)
1779 (const :tag "Only with C-u C-c C-t" prefix)))
1781 (defcustom org-after-todo-state-change-hook nil
1782 "Hook which is run after the state of a TODO item was changed.
1783 The new state (a string with a TODO keyword, or nil) is available in the
1784 Lisp variable `state'."
1785 :group 'org-todo
1786 :type 'hook)
1788 (defcustom org-log-done nil
1789 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1790 When equal to the list (done), also prompt for a closing note.
1791 This can also be configured on a per-file basis by adding one of
1792 the following lines anywhere in the buffer:
1794 #+STARTUP: logdone
1795 #+STARTUP: lognotedone
1796 #+STARTUP: nologdone"
1797 :group 'org-todo
1798 :group 'org-progress
1799 :type '(choice
1800 (const :tag "No logging" nil)
1801 (const :tag "Record CLOSED timestamp" time)
1802 (const :tag "Record CLOSED timestamp with closing note." note)))
1804 ;; Normalize old uses of org-log-done.
1805 (cond
1806 ((eq org-log-done t) (setq org-log-done 'time))
1807 ((and (listp org-log-done) (memq 'done org-log-done))
1808 (setq org-log-done 'note)))
1810 ;; FIXME: document
1811 (defcustom org-log-note-clock-out nil
1812 "Non-nil means, recored a note when clocking out of an item.
1813 This can also be configured on a per-file basis by adding one of
1814 the following lines anywhere in the buffer:
1816 #+STARTUP: lognoteclock-out
1817 #+STARTUP: nolognoteclock-out"
1818 :group 'org-todo
1819 :group 'org-progress
1820 :type 'boolean)
1822 (defcustom org-log-done-with-time t
1823 "Non-nil means, the CLOSED time stamp will contain date and time.
1824 When nil, only the date will be recorded."
1825 :group 'org-progress
1826 :type 'boolean)
1828 (defcustom org-log-note-headings
1829 '((done . "CLOSING NOTE %t")
1830 (state . "State %-12s %t")
1831 (clock-out . ""))
1832 "Headings for notes added when clocking out or closing TODO items.
1833 The value is an alist, with the car being a symbol indicating the note
1834 context, and the cdr is the heading to be used. The heading may also be the
1835 empty string.
1836 %t in the heading will be replaced by a time stamp.
1837 %s will be replaced by the new TODO state, in double quotes.
1838 %u will be replaced by the user name.
1839 %U will be replaced by the full user name."
1840 :group 'org-todo
1841 :group 'org-progress
1842 :type '(list :greedy t
1843 (cons (const :tag "Heading when closing an item" done) string)
1844 (cons (const :tag
1845 "Heading when changing todo state (todo sequence only)"
1846 state) string)
1847 (cons (const :tag "Heading when clocking out" clock-out) string)))
1849 (defcustom org-log-states-order-reversed t
1850 "Non-nil means, the latest state change note will be directly after heading.
1851 When nil, the notes will be orderer according to time."
1852 :group 'org-todo
1853 :group 'org-progress
1854 :type 'boolean)
1856 (defcustom org-log-repeat 'time
1857 "Non-nil means, record moving through the DONE state when triggering repeat.
1858 An auto-repeating tasks is immediately switched back to TODO when marked
1859 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1860 the TODO keyword definition, or recording a cloing note by setting
1861 `org-log-done', there will be no record of the task moving trhough DONE.
1862 This variable forces taking a note anyway. Possible values are:
1864 nil Don't force a record
1865 time Record a time stamp
1866 note Record a note
1868 This option can also be set with on a per-file-basis with
1870 #+STARTUP: logrepeat
1871 #+STARTUP: lognoterepeat
1872 #+STARTUP: nologrepeat
1874 You can have local logging settings for a subtree by setting the LOGGING
1875 property to one or more of these keywords."
1876 :group 'org-todo
1877 :group 'org-progress
1878 :type '(choice
1879 (const :tag "Don't force a record" nil)
1880 (const :tag "Force recording the DONE state" time)
1881 (const :tag "Force recording a note with the DONE state" note)))
1883 (defcustom org-clock-into-drawer 2
1884 "Should clocking info be wrapped into a drawer?
1885 When t, clocking info will always be inserted into a :CLOCK: drawer.
1886 If necessary, the drawer will be created.
1887 When nil, the drawer will not be created, but used when present.
1888 When an integer and the number of clocking entries in an item
1889 reaches or exceeds this number, a drawer will be created."
1890 :group 'org-todo
1891 :group 'org-progress
1892 :type '(choice
1893 (const :tag "Always" t)
1894 (const :tag "Only when drawer exists" nil)
1895 (integer :tag "When at least N clock entries")))
1897 (defcustom org-clock-out-when-done t
1898 "When t, the clock will be stopped when the relevant entry is marked DONE.
1899 Nil means, clock will keep running until stopped explicitly with
1900 `C-c C-x C-o', or until the clock is started in a different item."
1901 :group 'org-progress
1902 :type 'boolean)
1904 (defcustom org-clock-in-switch-to-state nil
1905 "Set task to a special todo state while clocking it.
1906 The value should be the state to which the entry should be switched."
1907 :group 'org-progress
1908 :group 'org-todo
1909 :type '(choice
1910 (const :tag "Don't force a state" nil)
1911 (string :tag "State")))
1913 (defgroup org-priorities nil
1914 "Priorities in Org-mode."
1915 :tag "Org Priorities"
1916 :group 'org-todo)
1918 (defcustom org-highest-priority ?A
1919 "The highest priority of TODO items. A character like ?A, ?B etc.
1920 Must have a smaller ASCII number than `org-lowest-priority'."
1921 :group 'org-priorities
1922 :type 'character)
1924 (defcustom org-lowest-priority ?C
1925 "The lowest priority of TODO items. A character like ?A, ?B etc.
1926 Must have a larger ASCII number than `org-highest-priority'."
1927 :group 'org-priorities
1928 :type 'character)
1930 (defcustom org-default-priority ?B
1931 "The default priority of TODO items.
1932 This is the priority an item get if no explicit priority is given."
1933 :group 'org-priorities
1934 :type 'character)
1936 (defcustom org-priority-start-cycle-with-default t
1937 "Non-nil means, start with default priority when starting to cycle.
1938 When this is nil, the first step in the cycle will be (depending on the
1939 command used) one higher or lower that the default priority."
1940 :group 'org-priorities
1941 :type 'boolean)
1943 (defgroup org-time nil
1944 "Options concerning time stamps and deadlines in Org-mode."
1945 :tag "Org Time"
1946 :group 'org)
1948 (defcustom org-insert-labeled-timestamps-at-point nil
1949 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1950 When nil, these labeled time stamps are forces into the second line of an
1951 entry, just after the headline. When scheduling from the global TODO list,
1952 the time stamp will always be forced into the second line."
1953 :group 'org-time
1954 :type 'boolean)
1956 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1957 "Formats for `format-time-string' which are used for time stamps.
1958 It is not recommended to change this constant.")
1960 (defcustom org-time-stamp-rounding-minutes 0
1961 "Number of minutes to round time stamps to upon insertion.
1962 When zero, insert the time unmodified. Useful rounding numbers
1963 should be factors of 60, so for example 5, 10, 15.
1964 When this is not zero, you can still force an exact time-stamp by using
1965 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1966 :group 'org-time
1967 :type 'integer)
1969 (defcustom org-display-custom-times nil
1970 "Non-nil means, overlay custom formats over all time stamps.
1971 The formats are defined through the variable `org-time-stamp-custom-formats'.
1972 To turn this on on a per-file basis, insert anywhere in the file:
1973 #+STARTUP: customtime"
1974 :group 'org-time
1975 :set 'set-default
1976 :type 'sexp)
1977 (make-variable-buffer-local 'org-display-custom-times)
1979 (defcustom org-time-stamp-custom-formats
1980 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1981 "Custom formats for time stamps. See `format-time-string' for the syntax.
1982 These are overlayed over the default ISO format if the variable
1983 `org-display-custom-times' is set. Time like %H:%M should be at the
1984 end of the second format."
1985 :group 'org-time
1986 :type 'sexp)
1988 (defun org-time-stamp-format (&optional long inactive)
1989 "Get the right format for a time string."
1990 (let ((f (if long (cdr org-time-stamp-formats)
1991 (car org-time-stamp-formats))))
1992 (if inactive
1993 (concat "[" (substring f 1 -1) "]")
1994 f)))
1996 (defcustom org-read-date-prefer-future t
1997 "Non-nil means, assume future for incomplete date input from user.
1998 This affects the following situations:
1999 1. The user gives a day, but no month.
2000 For example, if today is the 15th, and you enter \"3\", Org-mode will
2001 read this as the third of *next* month. However, if you enter \"17\",
2002 it will be considered as *this* month.
2003 2. The user gives a month but not a year.
2004 For example, if it is april and you enter \"feb 2\", this will be read
2005 as feb 2, *next* year. \"May 5\", however, will be this year.
2007 When this option is nil, the current month and year will always be used
2008 as defaults."
2009 :group 'org-time
2010 :type 'boolean)
2012 (defcustom org-read-date-display-live t
2013 "Non-nil means, display current interpretation of date prompt live.
2014 This display will be in an overlay, in the minibuffer."
2015 :group 'org-time
2016 :type 'boolean)
2018 (defcustom org-read-date-popup-calendar t
2019 "Non-nil means, pop up a calendar when prompting for a date.
2020 In the calendar, the date can be selected with mouse-1. However, the
2021 minibuffer will also be active, and you can simply enter the date as well.
2022 When nil, only the minibuffer will be available."
2023 :group 'org-time
2024 :type 'boolean)
2025 (if (fboundp 'defvaralias)
2026 (defvaralias 'org-popup-calendar-for-date-prompt
2027 'org-read-date-popup-calendar))
2029 (defcustom org-extend-today-until 0
2030 "The hour when your day really ends.
2031 This has influence for the following applications:
2032 - When switching the agenda to \"today\". It it is still earlier than
2033 the time given here, the day recognized as TODAY is actually yesterday.
2034 - When a date is read from the user and it is still before the time given
2035 here, the current date and time will be assumed to be yesterday, 23:59.
2037 FIXME:
2038 IMPORTANT: This is still a very experimental feature, it may disappear
2039 again or it may be extended to mean more things."
2040 :group 'org-time
2041 :type 'number)
2043 (defcustom org-edit-timestamp-down-means-later nil
2044 "Non-nil means, S-down will increase the time in a time stamp.
2045 When nil, S-up will increase."
2046 :group 'org-time
2047 :type 'boolean)
2049 (defcustom org-calendar-follow-timestamp-change t
2050 "Non-nil means, make the calendar window follow timestamp changes.
2051 When a timestamp is modified and the calendar window is visible, it will be
2052 moved to the new date."
2053 :group 'org-time
2054 :type 'boolean)
2056 (defcustom org-clock-heading-function nil
2057 "When non-nil, should be a function to create `org-clock-heading'.
2058 This is the string shown in the mode line when a clock is running.
2059 The function is called with point at the beginning of the headline."
2060 :group 'org-time ; FIXME: Should we have a separate group????
2061 :type 'function)
2063 (defgroup org-tags nil
2064 "Options concerning tags in Org-mode."
2065 :tag "Org Tags"
2066 :group 'org)
2068 (defcustom org-tag-alist nil
2069 "List of tags allowed in Org-mode files.
2070 When this list is nil, Org-mode will base TAG input on what is already in the
2071 buffer.
2072 The value of this variable is an alist, the car of each entry must be a
2073 keyword as a string, the cdr may be a character that is used to select
2074 that tag through the fast-tag-selection interface.
2075 See the manual for details."
2076 :group 'org-tags
2077 :type '(repeat
2078 (choice
2079 (cons (string :tag "Tag name")
2080 (character :tag "Access char"))
2081 (const :tag "Start radio group" (:startgroup))
2082 (const :tag "End radio group" (:endgroup)))))
2084 (defcustom org-use-fast-tag-selection 'auto
2085 "Non-nil means, use fast tag selection scheme.
2086 This is a special interface to select and deselect tags with single keys.
2087 When nil, fast selection is never used.
2088 When the symbol `auto', fast selection is used if and only if selection
2089 characters for tags have been configured, either through the variable
2090 `org-tag-alist' or through a #+TAGS line in the buffer.
2091 When t, fast selection is always used and selection keys are assigned
2092 automatically if necessary."
2093 :group 'org-tags
2094 :type '(choice
2095 (const :tag "Always" t)
2096 (const :tag "Never" nil)
2097 (const :tag "When selection characters are configured" 'auto)))
2099 (defcustom org-fast-tag-selection-single-key nil
2100 "Non-nil means, fast tag selection exits after first change.
2101 When nil, you have to press RET to exit it.
2102 During fast tag selection, you can toggle this flag with `C-c'.
2103 This variable can also have the value `expert'. In this case, the window
2104 displaying the tags menu is not even shown, until you press C-c again."
2105 :group 'org-tags
2106 :type '(choice
2107 (const :tag "No" nil)
2108 (const :tag "Yes" t)
2109 (const :tag "Expert" expert)))
2111 (defvar org-fast-tag-selection-include-todo nil
2112 "Non-nil means, fast tags selection interface will also offer TODO states.
2113 This is an undocumented feature, you should not rely on it.")
2115 (defcustom org-tags-column -80
2116 "The column to which tags should be indented in a headline.
2117 If this number is positive, it specifies the column. If it is negative,
2118 it means that the tags should be flushright to that column. For example,
2119 -80 works well for a normal 80 character screen."
2120 :group 'org-tags
2121 :type 'integer)
2123 (defcustom org-auto-align-tags t
2124 "Non-nil means, realign tags after pro/demotion of TODO state change.
2125 These operations change the length of a headline and therefore shift
2126 the tags around. With this options turned on, after each such operation
2127 the tags are again aligned to `org-tags-column'."
2128 :group 'org-tags
2129 :type 'boolean)
2131 (defcustom org-use-tag-inheritance t
2132 "Non-nil means, tags in levels apply also for sublevels.
2133 When nil, only the tags directly given in a specific line apply there.
2134 If you turn off this option, you very likely want to turn on the
2135 companion option `org-tags-match-list-sublevels'."
2136 :group 'org-tags
2137 :type 'boolean)
2139 (defcustom org-tags-match-list-sublevels nil
2140 "Non-nil means list also sublevels of headlines matching tag search.
2141 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2142 the sublevels of a headline matching a tag search often also match
2143 the same search. Listing all of them can create very long lists.
2144 Setting this variable to nil causes subtrees of a match to be skipped.
2145 This option is off by default, because inheritance in on. If you turn
2146 inheritance off, you very likely want to turn this option on.
2148 As a special case, if the tag search is restricted to TODO items, the
2149 value of this variable is ignored and sublevels are always checked, to
2150 make sure all corresponding TODO items find their way into the list."
2151 :group 'org-tags
2152 :type 'boolean)
2154 (defvar org-tags-history nil
2155 "History of minibuffer reads for tags.")
2156 (defvar org-last-tags-completion-table nil
2157 "The last used completion table for tags.")
2158 (defvar org-after-tags-change-hook nil
2159 "Hook that is run after the tags in a line have changed.")
2161 (defgroup org-properties nil
2162 "Options concerning properties in Org-mode."
2163 :tag "Org Properties"
2164 :group 'org)
2166 (defcustom org-property-format "%-10s %s"
2167 "How property key/value pairs should be formatted by `indent-line'.
2168 When `indent-line' hits a property definition, it will format the line
2169 according to this format, mainly to make sure that the values are
2170 lined-up with respect to each other."
2171 :group 'org-properties
2172 :type 'string)
2174 (defcustom org-use-property-inheritance nil
2175 "Non-nil means, properties apply also for sublevels.
2176 This setting is only relevant during property searches, not when querying
2177 an entry with `org-entry-get'. To retrieve a property with inheritance,
2178 you need to call `org-entry-get' with the inheritance flag.
2179 Turning this on can cause significant overhead when doing a search, so
2180 this is turned off by default.
2181 When nil, only the properties directly given in the current entry count.
2182 The value may also be a list of properties that shouldhave inheritance.
2184 However, note that some special properties use inheritance under special
2185 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2186 and the properties ending in \"_ALL\" when they are used as descriptor
2187 for valid values of a property."
2188 :group 'org-properties
2189 :type '(choice
2190 (const :tag "Not" nil)
2191 (const :tag "Always" nil)
2192 (repeat :tag "Specific properties" (string :tag "Property"))))
2194 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2195 "The default column format, if no other format has been defined.
2196 This variable can be set on the per-file basis by inserting a line
2198 #+COLUMNS: %25ITEM ....."
2199 :group 'org-properties
2200 :type 'string)
2202 (defcustom org-global-properties nil
2203 "List of property/value pairs that can be inherited by any entry.
2204 You can set buffer-local values for this by adding lines like
2206 #+PROPERTY: NAME VALUE"
2207 :group 'org-properties
2208 :type '(repeat
2209 (cons (string :tag "Property")
2210 (string :tag "Value"))))
2212 (defvar org-local-properties nil
2213 "List of property/value pairs that can be inherited by any entry.
2214 Valid for the current buffer.
2215 This variable is populated from #+PROPERTY lines.")
2217 (defgroup org-agenda nil
2218 "Options concerning agenda views in Org-mode."
2219 :tag "Org Agenda"
2220 :group 'org)
2222 (defvar org-category nil
2223 "Variable used by org files to set a category for agenda display.
2224 Such files should use a file variable to set it, for example
2226 # -*- mode: org; org-category: \"ELisp\"
2228 or contain a special line
2230 #+CATEGORY: ELisp
2232 If the file does not specify a category, then file's base name
2233 is used instead.")
2234 (make-variable-buffer-local 'org-category)
2236 (defcustom org-agenda-files nil
2237 "The files to be used for agenda display.
2238 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2239 \\[org-remove-file]. You can also use customize to edit the list.
2241 If an entry is a directory, all files in that directory that are matched by
2242 `org-agenda-file-regexp' will be part of the file list.
2244 If the value of the variable is not a list but a single file name, then
2245 the list of agenda files is actually stored and maintained in that file, one
2246 agenda file per line."
2247 :group 'org-agenda
2248 :type '(choice
2249 (repeat :tag "List of files and directories" file)
2250 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2252 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2253 "Regular expression to match files for `org-agenda-files'.
2254 If any element in the list in that variable contains a directory instead
2255 of a normal file, all files in that directory that are matched by this
2256 regular expression will be included."
2257 :group 'org-agenda
2258 :type 'regexp)
2260 (defcustom org-agenda-skip-unavailable-files nil
2261 "t means to just skip non-reachable files in `org-agenda-files'.
2262 Nil means to remove them, after a query, from the list."
2263 :group 'org-agenda
2264 :type 'boolean)
2266 (defcustom org-agenda-multi-occur-extra-files nil
2267 "List of extra files to be searched by `org-occur-in-agenda-files'.
2268 The files in `org-agenda-files' are always searched."
2269 :group 'org-agenda
2270 :type '(repeat file))
2272 (defcustom org-agenda-confirm-kill 1
2273 "When set, remote killing from the agenda buffer needs confirmation.
2274 When t, a confirmation is always needed. When a number N, confirmation is
2275 only needed when the text to be killed contains more than N non-white lines."
2276 :group 'org-agenda
2277 :type '(choice
2278 (const :tag "Never" nil)
2279 (const :tag "Always" t)
2280 (number :tag "When more than N lines")))
2282 (defcustom org-calendar-to-agenda-key [?c]
2283 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2284 The command `org-calendar-goto-agenda' will be bound to this key. The
2285 default is the character `c' because then `c' can be used to switch back and
2286 forth between agenda and calendar."
2287 :group 'org-agenda
2288 :type 'sexp)
2290 (defcustom org-agenda-compact-blocks nil
2291 "Non-nil means, make the block agenda more compact.
2292 This is done by leaving out unnecessary lines."
2293 :group 'org-agenda
2294 :type nil)
2296 (defgroup org-agenda-export nil
2297 "Options concerning exporting agenda views in Org-mode."
2298 :tag "Org Agenda Export"
2299 :group 'org-agenda)
2301 (defcustom org-agenda-with-colors t
2302 "Non-nil means, use colors in agenda views."
2303 :group 'org-agenda-export
2304 :type 'boolean)
2306 (defcustom org-agenda-exporter-settings nil
2307 "Alist of variable/value pairs that should be active during agenda export.
2308 This is a good place to set uptions for ps-print and for htmlize."
2309 :group 'org-agenda-export
2310 :type '(repeat
2311 (list
2312 (variable)
2313 (sexp :tag "Value"))))
2315 (defcustom org-agenda-export-html-style ""
2316 "The style specification for exported HTML Agenda files.
2317 If this variable contains a string, it will replace the default <style>
2318 section as produced by `htmlize'.
2319 Since there are different ways of setting style information, this variable
2320 needs to contain the full HTML structure to provide a style, including the
2321 surrounding HTML tags. The style specifications should include definitions
2322 the fonts used by the agenda, here is an example:
2324 <style type=\"text/css\">
2325 p { font-weight: normal; color: gray; }
2326 .org-agenda-structure {
2327 font-size: 110%;
2328 color: #003399;
2329 font-weight: 600;
2331 .org-todo {
2332 color: #cc6666;Week-agenda:
2333 font-weight: bold;
2335 .org-done {
2336 color: #339933;
2338 .title { text-align: center; }
2339 .todo, .deadline { color: red; }
2340 .done { color: green; }
2341 </style>
2343 or, if you want to keep the style in a file,
2345 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2347 As the value of this option simply gets inserted into the HTML <head> header,
2348 you can \"misuse\" it to also add other text to the header. However,
2349 <style>...</style> is required, if not present the variable will be ignored."
2350 :group 'org-agenda-export
2351 :group 'org-export-html
2352 :type 'string)
2354 (defgroup org-agenda-custom-commands nil
2355 "Options concerning agenda views in Org-mode."
2356 :tag "Org Agenda Custom Commands"
2357 :group 'org-agenda)
2359 (defcustom org-agenda-custom-commands nil
2360 "Custom commands for the agenda.
2361 These commands will be offered on the splash screen displayed by the
2362 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2364 (key desc type match options files)
2366 key The key (one or more characters as a string) to be associated
2367 with the command.
2368 desc A description of the commend, when omitted or nil, a default
2369 description is built using MATCH.
2370 type The command type, any of the following symbols:
2371 todo Entries with a specific TODO keyword, in all agenda files.
2372 tags Tags match in all agenda files.
2373 tags-todo Tags match in all agenda files, TODO entries only.
2374 todo-tree Sparse tree of specific TODO keyword in *current* file.
2375 tags-tree Sparse tree with all tags matches in *current* file.
2376 occur-tree Occur sparse tree for *current* file.
2377 ... A user-defined function.
2378 match What to search for:
2379 - a single keyword for TODO keyword searches
2380 - a tags match expression for tags searches
2381 - a regular expression for occur searches
2382 options A list of option settings, similar to that in a let form, so like
2383 this: ((opt1 val1) (opt2 val2) ...)
2384 files A list of files file to write the produced agenda buffer to
2385 with the command `org-store-agenda-views'.
2386 If a file name ends in \".html\", an HTML version of the buffer
2387 is written out. If it ends in \".ps\", a postscript version is
2388 produced. Otherwide, only the plain text is written to the file.
2390 You can also define a set of commands, to create a composite agenda buffer.
2391 In this case, an entry looks like this:
2393 (key desc (cmd1 cmd2 ...) general-options file)
2395 where
2397 desc A description string to be displayed in the dispatcher menu.
2398 cmd An agenda command, similar to the above. However, tree commands
2399 are no allowed, but instead you can get agenda and global todo list.
2400 So valid commands for a set are:
2401 (agenda)
2402 (alltodo)
2403 (stuck)
2404 (todo \"match\" options files)
2405 (tags \"match\" options files)
2406 (tags-todo \"match\" options files)
2408 Each command can carry a list of options, and another set of options can be
2409 given for the whole set of commands. Individual command options take
2410 precedence over the general options.
2412 When using several characters as key to a command, the first characters
2413 are prefix commands. For the dispatcher to display useful information, you
2414 should provide a description for the prefix, like
2416 (setq org-agenda-custom-commands
2417 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2418 (\"hl\" tags \"+HOME+Lisa\")
2419 (\"hp\" tags \"+HOME+Peter\")
2420 (\"hk\" tags \"+HOME+Kim\")))"
2421 :group 'org-agenda-custom-commands
2422 :type '(repeat
2423 (choice :value ("a" "" tags "" nil)
2424 (list :tag "Single command"
2425 (string :tag "Access Key(s) ")
2426 (option (string :tag "Description"))
2427 (choice
2428 (const :tag "Agenda" agenda)
2429 (const :tag "TODO list" alltodo)
2430 (const :tag "Stuck projects" stuck)
2431 (const :tag "Tags search (all agenda files)" tags)
2432 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2433 (const :tag "TODO keyword search (all agenda files)" todo)
2434 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2435 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2436 (const :tag "Occur tree (current buffer)" occur-tree)
2437 (sexp :tag "Other, user-defined function"))
2438 (string :tag "Match")
2439 (repeat :tag "Local options"
2440 (list (variable :tag "Option") (sexp :tag "Value")))
2441 (option (repeat :tag "Export" (file :tag "Export to"))))
2442 (list :tag "Command series, all agenda files"
2443 (string :tag "Access Key(s)")
2444 (string :tag "Description ")
2445 (repeat
2446 (choice
2447 (const :tag "Agenda" (agenda))
2448 (const :tag "TODO list" (alltodo))
2449 (const :tag "Stuck projects" (stuck))
2450 (list :tag "Tags search"
2451 (const :format "" tags)
2452 (string :tag "Match")
2453 (repeat :tag "Local options"
2454 (list (variable :tag "Option")
2455 (sexp :tag "Value"))))
2457 (list :tag "Tags search, TODO entries only"
2458 (const :format "" tags-todo)
2459 (string :tag "Match")
2460 (repeat :tag "Local options"
2461 (list (variable :tag "Option")
2462 (sexp :tag "Value"))))
2464 (list :tag "TODO keyword search"
2465 (const :format "" todo)
2466 (string :tag "Match")
2467 (repeat :tag "Local options"
2468 (list (variable :tag "Option")
2469 (sexp :tag "Value"))))
2471 (list :tag "Other, user-defined function"
2472 (symbol :tag "function")
2473 (string :tag "Match")
2474 (repeat :tag "Local options"
2475 (list (variable :tag "Option")
2476 (sexp :tag "Value"))))))
2478 (repeat :tag "General options"
2479 (list (variable :tag "Option")
2480 (sexp :tag "Value")))
2481 (option (repeat :tag "Export" (file :tag "Export to"))))
2482 (cons :tag "Prefix key documentation"
2483 (string :tag "Access Key(s)")
2484 (string :tag "Description ")))))
2486 (defcustom org-stuck-projects
2487 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2488 "How to identify stuck projects.
2489 This is a list of four items:
2490 1. A tags/todo matcher string that is used to identify a project.
2491 The entire tree below a headline matched by this is considered one project.
2492 2. A list of TODO keywords identifying non-stuck projects.
2493 If the project subtree contains any headline with one of these todo
2494 keywords, the project is considered to be not stuck. If you specify
2495 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2496 3. A list of tags identifying non-stuck projects.
2497 If the project subtree contains any headline with one of these tags,
2498 the project is considered to be not stuck. If you specify \"*\" as
2499 a tag, any tag will mark the project unstuck.
2500 4. An arbitrary regular expression matching non-stuck projects.
2502 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2503 or `C-c a #' to produce the list."
2504 :group 'org-agenda-custom-commands
2505 :type '(list
2506 (string :tag "Tags/TODO match to identify a project")
2507 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2508 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2509 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2512 (defgroup org-agenda-skip nil
2513 "Options concerning skipping parts of agenda files."
2514 :tag "Org Agenda Skip"
2515 :group 'org-agenda)
2517 (defcustom org-agenda-todo-list-sublevels t
2518 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2519 When nil, the sublevels of a TODO entry are not checked, resulting in
2520 potentially much shorter TODO lists."
2521 :group 'org-agenda-skip
2522 :group 'org-todo
2523 :type 'boolean)
2525 (defcustom org-agenda-todo-ignore-with-date nil
2526 "Non-nil means, don't show entries with a date in the global todo list.
2527 You can use this if you prefer to mark mere appointments with a TODO keyword,
2528 but don't want them to show up in the TODO list.
2529 When this is set, it also covers deadlines and scheduled items, the settings
2530 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2531 will be ignored."
2532 :group 'org-agenda-skip
2533 :group 'org-todo
2534 :type 'boolean)
2536 (defcustom org-agenda-todo-ignore-scheduled nil
2537 "Non-nil means, don't show scheduled entries in the global todo list.
2538 The idea behind this is that by scheduling it, you have already taken care
2539 of this item.
2540 See also `org-agenda-todo-ignore-with-date'."
2541 :group 'org-agenda-skip
2542 :group 'org-todo
2543 :type 'boolean)
2545 (defcustom org-agenda-todo-ignore-deadlines nil
2546 "Non-nil means, don't show near deadline entries in the global todo list.
2547 Near means closer than `org-deadline-warning-days' days.
2548 The idea behind this is that such items will appear in the agenda anyway.
2549 See also `org-agenda-todo-ignore-with-date'."
2550 :group 'org-agenda-skip
2551 :group 'org-todo
2552 :type 'boolean)
2554 (defcustom org-agenda-skip-scheduled-if-done nil
2555 "Non-nil means don't show scheduled items in agenda when they are done.
2556 This is relevant for the daily/weekly agenda, not for the TODO list. And
2557 it applies only to the actual date of the scheduling. Warnings about
2558 an item with a past scheduling dates are always turned off when the item
2559 is DONE."
2560 :group 'org-agenda-skip
2561 :type 'boolean)
2563 (defcustom org-agenda-skip-deadline-if-done nil
2564 "Non-nil means don't show deadines when the corresponding item is done.
2565 When nil, the deadline is still shown and should give you a happy feeling.
2566 This is relevant for the daily/weekly agenda. And it applied only to the
2567 actualy date of the deadline. Warnings about approching and past-due
2568 deadlines are always turned off when the item is DONE."
2569 :group 'org-agenda-skip
2570 :type 'boolean)
2572 (defcustom org-agenda-skip-timestamp-if-done nil
2573 "Non-nil means don't select item by timestamp or -range if it is DONE."
2574 :group 'org-agenda-skip
2575 :type 'boolean)
2577 (defcustom org-timeline-show-empty-dates 3
2578 "Non-nil means, `org-timeline' also shows dates without an entry.
2579 When nil, only the days which actually have entries are shown.
2580 When t, all days between the first and the last date are shown.
2581 When an integer, show also empty dates, but if there is a gap of more than
2582 N days, just insert a special line indicating the size of the gap."
2583 :group 'org-agenda-skip
2584 :type '(choice
2585 (const :tag "None" nil)
2586 (const :tag "All" t)
2587 (number :tag "at most")))
2590 (defgroup org-agenda-startup nil
2591 "Options concerning initial settings in the Agenda in Org Mode."
2592 :tag "Org Agenda Startup"
2593 :group 'org-agenda)
2595 (defcustom org-finalize-agenda-hook nil
2596 "Hook run just before displaying an agenda buffer."
2597 :group 'org-agenda-startup
2598 :type 'hook)
2600 (defcustom org-agenda-mouse-1-follows-link nil
2601 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2602 A longer mouse click will still set point. Does not wortk on XEmacs.
2603 Needs to be set before org.el is loaded."
2604 :group 'org-agenda-startup
2605 :type 'boolean)
2607 (defcustom org-agenda-start-with-follow-mode nil
2608 "The initial value of follow-mode in a newly created agenda window."
2609 :group 'org-agenda-startup
2610 :type 'boolean)
2612 (defgroup org-agenda-windows nil
2613 "Options concerning the windows used by the Agenda in Org Mode."
2614 :tag "Org Agenda Windows"
2615 :group 'org-agenda)
2617 (defcustom org-agenda-window-setup 'reorganize-frame
2618 "How the agenda buffer should be displayed.
2619 Possible values for this option are:
2621 current-window Show agenda in the current window, keeping all other windows.
2622 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2623 other-window Use `switch-to-buffer-other-window' to display agenda.
2624 reorganize-frame Show only two windows on the current frame, the current
2625 window and the agenda.
2626 See also the variable `org-agenda-restore-windows-after-quit'."
2627 :group 'org-agenda-windows
2628 :type '(choice
2629 (const current-window)
2630 (const other-frame)
2631 (const other-window)
2632 (const reorganize-frame)))
2634 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2635 "The min and max height of the agenda window as a fraction of frame height.
2636 The value of the variable is a cons cell with two numbers between 0 and 1.
2637 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2638 :group 'org-agenda-windows
2639 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2641 (defcustom org-agenda-restore-windows-after-quit nil
2642 "Non-nil means, restore window configuration open exiting agenda.
2643 Before the window configuration is changed for displaying the agenda,
2644 the current status is recorded. When the agenda is exited with
2645 `q' or `x' and this option is set, the old state is restored. If
2646 `org-agenda-window-setup' is `other-frame', the value of this
2647 option will be ignored.."
2648 :group 'org-agenda-windows
2649 :type 'boolean)
2651 (defcustom org-indirect-buffer-display 'other-window
2652 "How should indirect tree buffers be displayed?
2653 This applies to indirect buffers created with the commands
2654 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2655 Valid values are:
2656 current-window Display in the current window
2657 other-window Just display in another window.
2658 dedicated-frame Create one new frame, and re-use it each time.
2659 new-frame Make a new frame each time. Note that in this case
2660 previously-made indirect buffers are kept, and you need to
2661 kill these buffers yourself."
2662 :group 'org-structure
2663 :group 'org-agenda-windows
2664 :type '(choice
2665 (const :tag "In current window" current-window)
2666 (const :tag "In current frame, other window" other-window)
2667 (const :tag "Each time a new frame" new-frame)
2668 (const :tag "One dedicated frame" dedicated-frame)))
2670 (defgroup org-agenda-daily/weekly nil
2671 "Options concerning the daily/weekly agenda."
2672 :tag "Org Agenda Daily/Weekly"
2673 :group 'org-agenda)
2675 (defcustom org-agenda-ndays 7
2676 "Number of days to include in overview display.
2677 Should be 1 or 7."
2678 :group 'org-agenda-daily/weekly
2679 :type 'number)
2681 (defcustom org-agenda-start-on-weekday 1
2682 "Non-nil means, start the overview always on the specified weekday.
2683 0 denotes Sunday, 1 denotes Monday etc.
2684 When nil, always start on the current day."
2685 :group 'org-agenda-daily/weekly
2686 :type '(choice (const :tag "Today" nil)
2687 (number :tag "Weekday No.")))
2689 (defcustom org-agenda-show-all-dates t
2690 "Non-nil means, `org-agenda' shows every day in the selected range.
2691 When nil, only the days which actually have entries are shown."
2692 :group 'org-agenda-daily/weekly
2693 :type 'boolean)
2695 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2696 "Format string for displaying dates in the agenda.
2697 Used by the daily/weekly agenda and by the timeline. This should be
2698 a format string understood by `format-time-string', or a function returning
2699 the formatted date as a string. The function must take a single argument,
2700 a calendar-style date list like (month day year)."
2701 :group 'org-agenda-daily/weekly
2702 :type '(choice
2703 (string :tag "Format string")
2704 (function :tag "Function")))
2706 (defun org-agenda-format-date-aligned (date)
2707 "Format a date string for display in the daily/weekly agenda, or timeline.
2708 This function makes sure that dates are aligned for easy reading."
2709 (format "%-9s %2d %s %4d"
2710 (calendar-day-name date)
2711 (extract-calendar-day date)
2712 (calendar-month-name (extract-calendar-month date))
2713 (extract-calendar-year date)))
2715 (defcustom org-agenda-include-diary nil
2716 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2717 :group 'org-agenda-daily/weekly
2718 :type 'boolean)
2720 (defcustom org-agenda-include-all-todo nil
2721 "Set means weekly/daily agenda will always contain all TODO entries.
2722 The TODO entries will be listed at the top of the agenda, before
2723 the entries for specific days."
2724 :group 'org-agenda-daily/weekly
2725 :type 'boolean)
2727 (defcustom org-agenda-repeating-timestamp-show-all t
2728 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2729 When nil, only one occurence is shown, either today or the
2730 nearest into the future."
2731 :group 'org-agenda-daily/weekly
2732 :type 'boolean)
2734 (defcustom org-deadline-warning-days 14
2735 "No. of days before expiration during which a deadline becomes active.
2736 This variable governs the display in sparse trees and in the agenda.
2737 When 0 or negative, it means use this number (the absolute value of it)
2738 even if a deadline has a different individual lead time specified."
2739 :group 'org-time
2740 :group 'org-agenda-daily/weekly
2741 :type 'number)
2743 (defcustom org-scheduled-past-days 10000
2744 "No. of days to continue listing scheduled items that are not marked DONE.
2745 When an item is scheduled on a date, it shows up in the agenda on this
2746 day and will be listed until it is marked done for the number of days
2747 given here."
2748 :group 'org-agenda-daily/weekly
2749 :type 'number)
2751 (defgroup org-agenda-time-grid nil
2752 "Options concerning the time grid in the Org-mode Agenda."
2753 :tag "Org Agenda Time Grid"
2754 :group 'org-agenda)
2756 (defcustom org-agenda-use-time-grid t
2757 "Non-nil means, show a time grid in the agenda schedule.
2758 A time grid is a set of lines for specific times (like every two hours between
2759 8:00 and 20:00). The items scheduled for a day at specific times are
2760 sorted in between these lines.
2761 For details about when the grid will be shown, and what it will look like, see
2762 the variable `org-agenda-time-grid'."
2763 :group 'org-agenda-time-grid
2764 :type 'boolean)
2766 (defcustom org-agenda-time-grid
2767 '((daily today require-timed)
2768 "----------------"
2769 (800 1000 1200 1400 1600 1800 2000))
2771 "The settings for time grid for agenda display.
2772 This is a list of three items. The first item is again a list. It contains
2773 symbols specifying conditions when the grid should be displayed:
2775 daily if the agenda shows a single day
2776 weekly if the agenda shows an entire week
2777 today show grid on current date, independent of daily/weekly display
2778 require-timed show grid only if at least one item has a time specification
2780 The second item is a string which will be places behing the grid time.
2782 The third item is a list of integers, indicating the times that should have
2783 a grid line."
2784 :group 'org-agenda-time-grid
2785 :type
2786 '(list
2787 (set :greedy t :tag "Grid Display Options"
2788 (const :tag "Show grid in single day agenda display" daily)
2789 (const :tag "Show grid in weekly agenda display" weekly)
2790 (const :tag "Always show grid for today" today)
2791 (const :tag "Show grid only if any timed entries are present"
2792 require-timed)
2793 (const :tag "Skip grid times already present in an entry"
2794 remove-match))
2795 (string :tag "Grid String")
2796 (repeat :tag "Grid Times" (integer :tag "Time"))))
2798 (defgroup org-agenda-sorting nil
2799 "Options concerning sorting in the Org-mode Agenda."
2800 :tag "Org Agenda Sorting"
2801 :group 'org-agenda)
2803 (defconst org-sorting-choice
2804 '(choice
2805 (const time-up) (const time-down)
2806 (const category-keep) (const category-up) (const category-down)
2807 (const tag-down) (const tag-up)
2808 (const priority-up) (const priority-down))
2809 "Sorting choices.")
2811 (defcustom org-agenda-sorting-strategy
2812 '((agenda time-up category-keep priority-down)
2813 (todo category-keep priority-down)
2814 (tags category-keep priority-down))
2815 "Sorting structure for the agenda items of a single day.
2816 This is a list of symbols which will be used in sequence to determine
2817 if an entry should be listed before another entry. The following
2818 symbols are recognized:
2820 time-up Put entries with time-of-day indications first, early first
2821 time-down Put entries with time-of-day indications first, late first
2822 category-keep Keep the default order of categories, corresponding to the
2823 sequence in `org-agenda-files'.
2824 category-up Sort alphabetically by category, A-Z.
2825 category-down Sort alphabetically by category, Z-A.
2826 tag-up Sort alphabetically by last tag, A-Z.
2827 tag-down Sort alphabetically by last tag, Z-A.
2828 priority-up Sort numerically by priority, high priority last.
2829 priority-down Sort numerically by priority, high priority first.
2831 The different possibilities will be tried in sequence, and testing stops
2832 if one comparison returns a \"not-equal\". For example, the default
2833 '(time-up category-keep priority-down)
2834 means: Pull out all entries having a specified time of day and sort them,
2835 in order to make a time schedule for the current day the first thing in the
2836 agenda listing for the day. Of the entries without a time indication, keep
2837 the grouped in categories, don't sort the categories, but keep them in
2838 the sequence given in `org-agenda-files'. Within each category sort by
2839 priority.
2841 Leaving out `category-keep' would mean that items will be sorted across
2842 categories by priority.
2844 Instead of a single list, this can also be a set of list for specific
2845 contents, with a context symbol in the car of the list, any of
2846 `agenda', `todo', `tags' for the corresponding agenda views."
2847 :group 'org-agenda-sorting
2848 :type `(choice
2849 (repeat :tag "General" ,org-sorting-choice)
2850 (list :tag "Individually"
2851 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2852 (repeat ,org-sorting-choice))
2853 (cons (const :tag "Strategy for TODO lists" todo)
2854 (repeat ,org-sorting-choice))
2855 (cons (const :tag "Strategy for Tags matches" tags)
2856 (repeat ,org-sorting-choice)))))
2858 (defcustom org-sort-agenda-notime-is-late t
2859 "Non-nil means, items without time are considered late.
2860 This is only relevant for sorting. When t, items which have no explicit
2861 time like 15:30 will be considered as 99:01, i.e. later than any items which
2862 do have a time. When nil, the default time is before 0:00. You can use this
2863 option to decide if the schedule for today should come before or after timeless
2864 agenda entries."
2865 :group 'org-agenda-sorting
2866 :type 'boolean)
2868 (defgroup org-agenda-line-format nil
2869 "Options concerning the entry prefix in the Org-mode agenda display."
2870 :tag "Org Agenda Line Format"
2871 :group 'org-agenda)
2873 (defcustom org-agenda-prefix-format
2874 '((agenda . " %-12:c%?-12t% s")
2875 (timeline . " % s")
2876 (todo . " %-12:c")
2877 (tags . " %-12:c"))
2878 "Format specifications for the prefix of items in the agenda views.
2879 An alist with four entries, for the different agenda types. The keys to the
2880 sublists are `agenda', `timeline', `todo', and `tags'. The values
2881 are format strings.
2882 This format works similar to a printf format, with the following meaning:
2884 %c the category of the item, \"Diary\" for entries from the diary, or
2885 as given by the CATEGORY keyword or derived from the file name.
2886 %T the *last* tag of the item. Last because inherited tags come
2887 first in the list.
2888 %t the time-of-day specification if one applies to the entry, in the
2889 format HH:MM
2890 %s Scheduling/Deadline information, a short string
2892 All specifiers work basically like the standard `%s' of printf, but may
2893 contain two additional characters: A question mark just after the `%' and
2894 a whitespace/punctuation character just before the final letter.
2896 If the first character after `%' is a question mark, the entire field
2897 will only be included if the corresponding value applies to the
2898 current entry. This is useful for fields which should have fixed
2899 width when present, but zero width when absent. For example,
2900 \"%?-12t\" will result in a 12 character time field if a time of the
2901 day is specified, but will completely disappear in entries which do
2902 not contain a time.
2904 If there is punctuation or whitespace character just before the final
2905 format letter, this character will be appended to the field value if
2906 the value is not empty. For example, the format \"%-12:c\" leads to
2907 \"Diary: \" if the category is \"Diary\". If the category were be
2908 empty, no additional colon would be interted.
2910 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2911 - Indent the line with two space characters
2912 - Give the category in a 12 chars wide field, padded with whitespace on
2913 the right (because of `-'). Append a colon if there is a category
2914 (because of `:').
2915 - If there is a time-of-day, put it into a 12 chars wide field. If no
2916 time, don't put in an empty field, just skip it (because of '?').
2917 - Finally, put the scheduling information and append a whitespace.
2919 As another example, if you don't want the time-of-day of entries in
2920 the prefix, you could use:
2922 (setq org-agenda-prefix-format \" %-11:c% s\")
2924 See also the variables `org-agenda-remove-times-when-in-prefix' and
2925 `org-agenda-remove-tags'."
2926 :type '(choice
2927 (string :tag "General format")
2928 (list :greedy t :tag "View dependent"
2929 (cons (const agenda) (string :tag "Format"))
2930 (cons (const timeline) (string :tag "Format"))
2931 (cons (const todo) (string :tag "Format"))
2932 (cons (const tags) (string :tag "Format"))))
2933 :group 'org-agenda-line-format)
2935 (defvar org-prefix-format-compiled nil
2936 "The compiled version of the most recently used prefix format.
2937 See the variable `org-agenda-prefix-format'.")
2939 (defcustom org-agenda-todo-keyword-format "%-1s"
2940 "Format for the TODO keyword in agenda lines.
2941 Set this to something like \"%-12s\" if you want all TODO keywords
2942 to occupy a fixed space in the agenda display."
2943 :group 'org-agenda-line-format
2944 :type 'string)
2946 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2947 "Text preceeding scheduled items in the agenda view.
2948 This is a list with two strings. The first applies when the item is
2949 scheduled on the current day. The second applies when it has been scheduled
2950 previously, it may contain a %d to capture how many days ago the item was
2951 scheduled."
2952 :group 'org-agenda-line-format
2953 :type '(list
2954 (string :tag "Scheduled today ")
2955 (string :tag "Scheduled previously")))
2957 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2958 "Text preceeding deadline items in the agenda view.
2959 This is a list with two strings. The first applies when the item has its
2960 deadline on the current day. The second applies when it is in the past or
2961 in the future, it may contain %d to capture how many days away the deadline
2962 is (was)."
2963 :group 'org-agenda-line-format
2964 :type '(list
2965 (string :tag "Deadline today ")
2966 (string :tag "Deadline relative")))
2968 (defcustom org-agenda-remove-times-when-in-prefix t
2969 "Non-nil means, remove duplicate time specifications in agenda items.
2970 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2971 time-of-day specification in a headline or diary entry is extracted and
2972 placed into the prefix. If this option is non-nil, the original specification
2973 \(a timestamp or -range, or just a plain time(range) specification like
2974 11:30-4pm) will be removed for agenda display. This makes the agenda less
2975 cluttered.
2976 The option can be t or nil. It may also be the symbol `beg', indicating
2977 that the time should only be removed what it is located at the beginning of
2978 the headline/diary entry."
2979 :group 'org-agenda-line-format
2980 :type '(choice
2981 (const :tag "Always" t)
2982 (const :tag "Never" nil)
2983 (const :tag "When at beginning of entry" beg)))
2986 (defcustom org-agenda-default-appointment-duration nil
2987 "Default duration for appointments that only have a starting time.
2988 When nil, no duration is specified in such cases.
2989 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2990 :group 'org-agenda-line-format
2991 :type '(choice
2992 (integer :tag "Minutes")
2993 (const :tag "No default duration")))
2996 (defcustom org-agenda-remove-tags nil
2997 "Non-nil means, remove the tags from the headline copy in the agenda.
2998 When this is the symbol `prefix', only remove tags when
2999 `org-agenda-prefix-format' contains a `%T' specifier."
3000 :group 'org-agenda-line-format
3001 :type '(choice
3002 (const :tag "Always" t)
3003 (const :tag "Never" nil)
3004 (const :tag "When prefix format contains %T" prefix)))
3006 (if (fboundp 'defvaralias)
3007 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3008 'org-agenda-remove-tags))
3010 (defcustom org-agenda-tags-column -80
3011 "Shift tags in agenda items to this column.
3012 If this number is positive, it specifies the column. If it is negative,
3013 it means that the tags should be flushright to that column. For example,
3014 -80 works well for a normal 80 character screen."
3015 :group 'org-agenda-line-format
3016 :type 'integer)
3018 (if (fboundp 'defvaralias)
3019 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3021 (defcustom org-agenda-fontify-priorities t
3022 "Non-nil means, highlight low and high priorities in agenda.
3023 When t, the highest priority entries are bold, lowest priority italic.
3024 This may also be an association list of priority faces. The face may be
3025 a names face, or a list like `(:background \"Red\")'."
3026 :group 'org-agenda-line-format
3027 :type '(choice
3028 (const :tag "Never" nil)
3029 (const :tag "Defaults" t)
3030 (repeat :tag "Specify"
3031 (list (character :tag "Priority" :value ?A)
3032 (sexp :tag "face")))))
3034 (defgroup org-latex nil
3035 "Options for embedding LaTeX code into Org-mode"
3036 :tag "Org LaTeX"
3037 :group 'org)
3039 (defcustom org-format-latex-options
3040 '(:foreground default :background default :scale 1.0
3041 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3042 :matchers ("begin" "$" "$$" "\\(" "\\["))
3043 "Options for creating images from LaTeX fragments.
3044 This is a property list with the following properties:
3045 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3046 `default' means use the forground of the default face.
3047 :background the background color, or \"Transparent\".
3048 `default' means use the background of the default face.
3049 :scale a scaling factor for the size of the images
3050 :html-foreground, :html-background, :html-scale
3051 The same numbers for HTML export.
3052 :matchers a list indicating which matchers should be used to
3053 find LaTeX fragments. Valid members of this list are:
3054 \"begin\" find environments
3055 \"$\" find math expressions surrounded by $...$
3056 \"$$\" find math expressions surrounded by $$....$$
3057 \"\\(\" find math expressions surrounded by \\(...\\)
3058 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3059 :group 'org-latex
3060 :type 'plist)
3062 (defcustom org-format-latex-header "\\documentclass{article}
3063 \\usepackage{fullpage} % do not remove
3064 \\usepackage{amssymb}
3065 \\usepackage[usenames]{color}
3066 \\usepackage{amsmath}
3067 \\usepackage{latexsym}
3068 \\usepackage[mathscr]{eucal}
3069 \\pagestyle{empty} % do not remove"
3070 "The document header used for processing LaTeX fragments."
3071 :group 'org-latex
3072 :type 'string)
3074 (defgroup org-export nil
3075 "Options for exporting org-listings."
3076 :tag "Org Export"
3077 :group 'org)
3079 (defgroup org-export-general nil
3080 "General options for exporting Org-mode files."
3081 :tag "Org Export General"
3082 :group 'org-export)
3084 ;; FIXME
3085 (defvar org-export-publishing-directory nil)
3087 (defcustom org-export-with-special-strings t
3088 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3089 When this option is turned on, these strings will be exported as:
3091 Org HTML LaTeX
3092 -----+----------+--------
3093 \\- &shy; \\-
3094 -- &ndash; --
3095 --- &mdash; ---
3096 ... &hellip; \ldots
3098 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3099 :group 'org-export-translation
3100 :type 'boolean)
3102 (defcustom org-export-language-setup
3103 '(("en" "Author" "Date" "Table of Contents")
3104 ("cs" "Autor" "Datum" "Obsah")
3105 ("da" "Ophavsmand" "Dato" "Indhold")
3106 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3107 ("es" "Autor" "Fecha" "\xcdndice")
3108 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3109 ("it" "Autore" "Data" "Indice")
3110 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3111 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3112 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3113 "Terms used in export text, translated to different languages.
3114 Use the variable `org-export-default-language' to set the language,
3115 or use the +OPTION lines for a per-file setting."
3116 :group 'org-export-general
3117 :type '(repeat
3118 (list
3119 (string :tag "HTML language tag")
3120 (string :tag "Author")
3121 (string :tag "Date")
3122 (string :tag "Table of Contents"))))
3124 (defcustom org-export-default-language "en"
3125 "The default language of HTML export, as a string.
3126 This should have an association in `org-export-language-setup'."
3127 :group 'org-export-general
3128 :type 'string)
3130 (defcustom org-export-skip-text-before-1st-heading t
3131 "Non-nil means, skip all text before the first headline when exporting.
3132 When nil, that text is exported as well."
3133 :group 'org-export-general
3134 :type 'boolean)
3136 (defcustom org-export-headline-levels 3
3137 "The last level which is still exported as a headline.
3138 Inferior levels will produce itemize lists when exported.
3139 Note that a numeric prefix argument to an exporter function overrides
3140 this setting.
3142 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3143 :group 'org-export-general
3144 :type 'number)
3146 (defcustom org-export-with-section-numbers t
3147 "Non-nil means, add section numbers to headlines when exporting.
3149 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3150 :group 'org-export-general
3151 :type 'boolean)
3153 (defcustom org-export-with-toc t
3154 "Non-nil means, create a table of contents in exported files.
3155 The TOC contains headlines with levels up to`org-export-headline-levels'.
3156 When an integer, include levels up to N in the toc, this may then be
3157 different from `org-export-headline-levels', but it will not be allowed
3158 to be larger than the number of headline levels.
3159 When nil, no table of contents is made.
3161 Headlines which contain any TODO items will be marked with \"(*)\" in
3162 ASCII export, and with red color in HTML output, if the option
3163 `org-export-mark-todo-in-toc' is set.
3165 In HTML output, the TOC will be clickable.
3167 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3168 or \"toc:3\"."
3169 :group 'org-export-general
3170 :type '(choice
3171 (const :tag "No Table of Contents" nil)
3172 (const :tag "Full Table of Contents" t)
3173 (integer :tag "TOC to level")))
3175 (defcustom org-export-mark-todo-in-toc nil
3176 "Non-nil means, mark TOC lines that contain any open TODO items."
3177 :group 'org-export-general
3178 :type 'boolean)
3180 (defcustom org-export-preserve-breaks nil
3181 "Non-nil means, preserve all line breaks when exporting.
3182 Normally, in HTML output paragraphs will be reformatted. In ASCII
3183 export, line breaks will always be preserved, regardless of this variable.
3185 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3186 :group 'org-export-general
3187 :type 'boolean)
3189 (defcustom org-export-with-archived-trees 'headline
3190 "Whether subtrees with the ARCHIVE tag should be exported.
3191 This can have three different values
3192 nil Do not export, pretend this tree is not present
3193 t Do export the entire tree
3194 headline Only export the headline, but skip the tree below it."
3195 :group 'org-export-general
3196 :group 'org-archive
3197 :type '(choice
3198 (const :tag "not at all" nil)
3199 (const :tag "headline only" 'headline)
3200 (const :tag "entirely" t)))
3202 (defcustom org-export-author-info t
3203 "Non-nil means, insert author name and email into the exported file.
3205 This option can also be set with the +OPTIONS line,
3206 e.g. \"author-info:nil\"."
3207 :group 'org-export-general
3208 :type 'boolean)
3210 (defcustom org-export-time-stamp-file t
3211 "Non-nil means, insert a time stamp into the exported file.
3212 The time stamp shows when the file was created.
3214 This option can also be set with the +OPTIONS line,
3215 e.g. \"timestamp:nil\"."
3216 :group 'org-export-general
3217 :type 'boolean)
3219 (defcustom org-export-with-timestamps t
3220 "If nil, do not export time stamps and associated keywords."
3221 :group 'org-export-general
3222 :type 'boolean)
3224 (defcustom org-export-remove-timestamps-from-toc t
3225 "If nil, remove timestamps from the table of contents entries."
3226 :group 'org-export-general
3227 :type 'boolean)
3229 (defcustom org-export-with-tags 'not-in-toc
3230 "If nil, do not export tags, just remove them from headlines.
3231 If this is the symbol `not-in-toc', tags will be removed from table of
3232 contents entries, but still be shown in the headlines of the document.
3234 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3235 :group 'org-export-general
3236 :type '(choice
3237 (const :tag "Off" nil)
3238 (const :tag "Not in TOC" not-in-toc)
3239 (const :tag "On" t)))
3241 (defcustom org-export-with-drawers nil
3242 "Non-nil means, export with drawers like the property drawer.
3243 When t, all drawers are exported. This may also be a list of
3244 drawer names to export."
3245 :group 'org-export-general
3246 :type '(choice
3247 (const :tag "All drawers" t)
3248 (const :tag "None" nil)
3249 (repeat :tag "Selected drawers"
3250 (string :tag "Drawer name"))))
3252 (defgroup org-export-translation nil
3253 "Options for translating special ascii sequences for the export backends."
3254 :tag "Org Export Translation"
3255 :group 'org-export)
3257 (defcustom org-export-with-emphasize t
3258 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3259 If the export target supports emphasizing text, the word will be
3260 typeset in bold, italic, or underlined, respectively. Works only for
3261 single words, but you can say: I *really* *mean* *this*.
3262 Not all export backends support this.
3264 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3265 :group 'org-export-translation
3266 :type 'boolean)
3268 (defcustom org-export-with-footnotes t
3269 "If nil, export [1] as a footnote marker.
3270 Lines starting with [1] will be formatted as footnotes.
3272 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3273 :group 'org-export-translation
3274 :type 'boolean)
3276 (defcustom org-export-with-sub-superscripts t
3277 "Non-nil means, interpret \"_\" and \"^\" for export.
3278 When this option is turned on, you can use TeX-like syntax for sub- and
3279 superscripts. Several characters after \"_\" or \"^\" will be
3280 considered as a single item - so grouping with {} is normally not
3281 needed. For example, the following things will be parsed as single
3282 sub- or superscripts.
3284 10^24 or 10^tau several digits will be considered 1 item.
3285 10^-12 or 10^-tau a leading sign with digits or a word
3286 x^2-y^3 will be read as x^2 - y^3, because items are
3287 terminated by almost any nonword/nondigit char.
3288 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3290 Still, ambiguity is possible - so when in doubt use {} to enclose the
3291 sub/superscript. If you set this variable to the symbol `{}',
3292 the braces are *required* in order to trigger interpretations as
3293 sub/superscript. This can be helpful in documents that need \"_\"
3294 frequently in plain text.
3296 Not all export backends support this, but HTML does.
3298 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3299 :group 'org-export-translation
3300 :type '(choice
3301 (const :tag "Always interpret" t)
3302 (const :tag "Only with braces" {})
3303 (const :tag "Never interpret" nil)))
3305 (defcustom org-export-with-special-strings t
3306 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3307 When this option is turned on, these strings will be exported as:
3309 \\- : &shy;
3310 -- : &ndash;
3311 --- : &mdash;
3313 Not all export backends support this, but HTML does.
3315 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3316 :group 'org-export-translation
3317 :type 'boolean)
3319 (defcustom org-export-with-TeX-macros t
3320 "Non-nil means, interpret simple TeX-like macros when exporting.
3321 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3322 No only real TeX macros will work here, but the standard HTML entities
3323 for math can be used as macro names as well. For a list of supported
3324 names in HTML export, see the constant `org-html-entities'.
3325 Not all export backends support this.
3327 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3328 :group 'org-export-translation
3329 :group 'org-export-latex
3330 :type 'boolean)
3332 (defcustom org-export-with-LaTeX-fragments nil
3333 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3334 When set, the exporter will find LaTeX environments if the \\begin line is
3335 the first non-white thing on a line. It will also find the math delimiters
3336 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3337 display math.
3339 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3340 :group 'org-export-translation
3341 :group 'org-export-latex
3342 :type 'boolean)
3344 (defcustom org-export-with-fixed-width t
3345 "Non-nil means, lines starting with \":\" will be in fixed width font.
3346 This can be used to have pre-formatted text, fragments of code etc. For
3347 example:
3348 : ;; Some Lisp examples
3349 : (while (defc cnt)
3350 : (ding))
3351 will be looking just like this in also HTML. See also the QUOTE keyword.
3352 Not all export backends support this.
3354 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3355 :group 'org-export-translation
3356 :type 'boolean)
3358 (defcustom org-match-sexp-depth 3
3359 "Number of stacked braces for sub/superscript matching.
3360 This has to be set before loading org.el to be effective."
3361 :group 'org-export-translation
3362 :type 'integer)
3364 (defgroup org-export-tables nil
3365 "Options for exporting tables in Org-mode."
3366 :tag "Org Export Tables"
3367 :group 'org-export)
3369 (defcustom org-export-with-tables t
3370 "If non-nil, lines starting with \"|\" define a table.
3371 For example:
3373 | Name | Address | Birthday |
3374 |-------------+----------+-----------|
3375 | Arthur Dent | England | 29.2.2100 |
3377 Not all export backends support this.
3379 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3380 :group 'org-export-tables
3381 :type 'boolean)
3383 (defcustom org-export-highlight-first-table-line t
3384 "Non-nil means, highlight the first table line.
3385 In HTML export, this means use <th> instead of <td>.
3386 In tables created with table.el, this applies to the first table line.
3387 In Org-mode tables, all lines before the first horizontal separator
3388 line will be formatted with <th> tags."
3389 :group 'org-export-tables
3390 :type 'boolean)
3392 (defcustom org-export-table-remove-special-lines t
3393 "Remove special lines and marking characters in calculating tables.
3394 This removes the special marking character column from tables that are set
3395 up for spreadsheet calculations. It also removes the entire lines
3396 marked with `!', `_', or `^'. The lines with `$' are kept, because
3397 the values of constants may be useful to have."
3398 :group 'org-export-tables
3399 :type 'boolean)
3401 (defcustom org-export-prefer-native-exporter-for-tables nil
3402 "Non-nil means, always export tables created with table.el natively.
3403 Natively means, use the HTML code generator in table.el.
3404 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3405 the table does not use row- or column-spanning). This has the
3406 advantage, that the automatic HTML conversions for math symbols and
3407 sub/superscripts can be applied. Org-mode's HTML generator is also
3408 much faster."
3409 :group 'org-export-tables
3410 :type 'boolean)
3412 (defgroup org-export-ascii nil
3413 "Options specific for ASCII export of Org-mode files."
3414 :tag "Org Export ASCII"
3415 :group 'org-export)
3417 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3418 "Characters for underlining headings in ASCII export.
3419 In the given sequence, these characters will be used for level 1, 2, ..."
3420 :group 'org-export-ascii
3421 :type '(repeat character))
3423 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3424 "Bullet characters for headlines converted to lists in ASCII export.
3425 The first character is used for the first lest level generated in this
3426 way, and so on. If there are more levels than characters given here,
3427 the list will be repeated.
3428 Note that plain lists will keep the same bullets as the have in the
3429 Org-mode file."
3430 :group 'org-export-ascii
3431 :type '(repeat character))
3433 (defgroup org-export-xml nil
3434 "Options specific for XML export of Org-mode files."
3435 :tag "Org Export XML"
3436 :group 'org-export)
3438 (defgroup org-export-html nil
3439 "Options specific for HTML export of Org-mode files."
3440 :tag "Org Export HTML"
3441 :group 'org-export)
3443 (defcustom org-export-html-coding-system nil
3445 :group 'org-export-html
3446 :type 'coding-system)
3448 (defcustom org-export-html-extension "html"
3449 "The extension for exported HTML files."
3450 :group 'org-export-html
3451 :type 'string)
3453 (defcustom org-export-html-style
3454 "<style type=\"text/css\">
3455 html {
3456 font-family: Times, serif;
3457 font-size: 12pt;
3459 .title { text-align: center; }
3460 .todo { color: red; }
3461 .done { color: green; }
3462 .timestamp { color: grey }
3463 .timestamp-kwd { color: CadetBlue }
3464 .tag { background-color:lightblue; font-weight:normal }
3465 .target { background-color: lavender; }
3466 pre {
3467 border: 1pt solid #AEBDCC;
3468 background-color: #F3F5F7;
3469 padding: 5pt;
3470 font-family: courier, monospace;
3472 table { border-collapse: collapse; }
3473 td, th {
3474 vertical-align: top;
3475 <!--border: 1pt solid #ADB9CC;-->
3477 </style>"
3478 "The default style specification for exported HTML files.
3479 Since there are different ways of setting style information, this variable
3480 needs to contain the full HTML structure to provide a style, including the
3481 surrounding HTML tags. The style specifications should include definitions
3482 for new classes todo, done, title, and deadline. For example, legal values
3483 would be:
3485 <style type=\"text/css\">
3486 p { font-weight: normal; color: gray; }
3487 h1 { color: black; }
3488 .title { text-align: center; }
3489 .todo, .deadline { color: red; }
3490 .done { color: green; }
3491 </style>
3493 or, if you want to keep the style in a file,
3495 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3497 As the value of this option simply gets inserted into the HTML <head> header,
3498 you can \"misuse\" it to add arbitrary text to the header."
3499 :group 'org-export-html
3500 :type 'string)
3503 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3504 "Format for typesetting the document title in HTML export."
3505 :group 'org-export-html
3506 :type 'string)
3508 (defcustom org-export-html-toplevel-hlevel 2
3509 "The <H> level for level 1 headings in HTML export."
3510 :group 'org-export-html
3511 :type 'string)
3513 (defcustom org-export-html-link-org-files-as-html t
3514 "Non-nil means, make file links to `file.org' point to `file.html'.
3515 When org-mode is exporting an org-mode file to HTML, links to
3516 non-html files are directly put into a href tag in HTML.
3517 However, links to other Org-mode files (recognized by the
3518 extension `.org.) should become links to the corresponding html
3519 file, assuming that the linked org-mode file will also be
3520 converted to HTML.
3521 When nil, the links still point to the plain `.org' file."
3522 :group 'org-export-html
3523 :type 'boolean)
3525 (defcustom org-export-html-inline-images 'maybe
3526 "Non-nil means, inline images into exported HTML pages.
3527 This is done using an <img> tag. When nil, an anchor with href is used to
3528 link to the image. If this option is `maybe', then images in links with
3529 an empty description will be inlined, while images with a description will
3530 be linked only."
3531 :group 'org-export-html
3532 :type '(choice (const :tag "Never" nil)
3533 (const :tag "Always" t)
3534 (const :tag "When there is no description" maybe)))
3536 ;; FIXME: rename
3537 (defcustom org-export-html-expand t
3538 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3539 When nil, these tags will be exported as plain text and therefore
3540 not be interpreted by a browser.
3542 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3543 :group 'org-export-html
3544 :type 'boolean)
3546 (defcustom org-export-html-table-tag
3547 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3548 "The HTML tag that is used to start a table.
3549 This must be a <table> tag, but you may change the options like
3550 borders and spacing."
3551 :group 'org-export-html
3552 :type 'string)
3554 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3555 "The opening tag for table header fields.
3556 This is customizable so that alignment options can be specified."
3557 :group 'org-export-tables
3558 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3560 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3561 "The opening tag for table data fields.
3562 This is customizable so that alignment options can be specified."
3563 :group 'org-export-tables
3564 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3566 (defcustom org-export-html-with-timestamp nil
3567 "If non-nil, write `org-export-html-html-helper-timestamp'
3568 into the exported HTML text. Otherwise, the buffer will just be saved
3569 to a file."
3570 :group 'org-export-html
3571 :type 'boolean)
3573 (defcustom org-export-html-html-helper-timestamp
3574 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3575 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3576 :group 'org-export-html
3577 :type 'string)
3579 (defgroup org-export-icalendar nil
3580 "Options specific for iCalendar export of Org-mode files."
3581 :tag "Org Export iCalendar"
3582 :group 'org-export)
3584 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3585 "The file name for the iCalendar file covering all agenda files.
3586 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3587 The file name should be absolute, the file will be overwritten without warning."
3588 :group 'org-export-icalendar
3589 :type 'file)
3591 (defcustom org-icalendar-include-todo nil
3592 "Non-nil means, export to iCalendar files should also cover TODO items."
3593 :group 'org-export-icalendar
3594 :type '(choice
3595 (const :tag "None" nil)
3596 (const :tag "Unfinished" t)
3597 (const :tag "All" all)))
3599 (defcustom org-icalendar-include-sexps t
3600 "Non-nil means, export to iCalendar files should also cover sexp entries.
3601 These are entries like in the diary, but directly in an Org-mode file."
3602 :group 'org-export-icalendar
3603 :type 'boolean)
3605 (defcustom org-icalendar-include-body 100
3606 "Amount of text below headline to be included in iCalendar export.
3607 This is a number of characters that should maximally be included.
3608 Properties, scheduling and clocking lines will always be removed.
3609 The text will be inserted into the DESCRIPTION field."
3610 :group 'org-export-icalendar
3611 :type '(choice
3612 (const :tag "Nothing" nil)
3613 (const :tag "Everything" t)
3614 (integer :tag "Max characters")))
3616 (defcustom org-icalendar-combined-name "OrgMode"
3617 "Calendar name for the combined iCalendar representing all agenda files."
3618 :group 'org-export-icalendar
3619 :type 'string)
3621 (defgroup org-font-lock nil
3622 "Font-lock settings for highlighting in Org-mode."
3623 :tag "Org Font Lock"
3624 :group 'org)
3626 (defcustom org-level-color-stars-only nil
3627 "Non-nil means fontify only the stars in each headline.
3628 When nil, the entire headline is fontified.
3629 Changing it requires restart of `font-lock-mode' to become effective
3630 also in regions already fontified."
3631 :group 'org-font-lock
3632 :type 'boolean)
3634 (defcustom org-hide-leading-stars nil
3635 "Non-nil means, hide the first N-1 stars in a headline.
3636 This works by using the face `org-hide' for these stars. This
3637 face is white for a light background, and black for a dark
3638 background. You may have to customize the face `org-hide' to
3639 make this work.
3640 Changing it requires restart of `font-lock-mode' to become effective
3641 also in regions already fontified.
3642 You may also set this on a per-file basis by adding one of the following
3643 lines to the buffer:
3645 #+STARTUP: hidestars
3646 #+STARTUP: showstars"
3647 :group 'org-font-lock
3648 :type 'boolean)
3650 (defcustom org-fontify-done-headline nil
3651 "Non-nil means, change the face of a headline if it is marked DONE.
3652 Normally, only the TODO/DONE keyword indicates the state of a headline.
3653 When this is non-nil, the headline after the keyword is set to the
3654 `org-headline-done' as an additional indication."
3655 :group 'org-font-lock
3656 :type 'boolean)
3658 (defcustom org-fontify-emphasized-text t
3659 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3660 Changing this variable requires a restart of Emacs to take effect."
3661 :group 'org-font-lock
3662 :type 'boolean)
3664 (defcustom org-highlight-latex-fragments-and-specials nil
3665 "Non-nil means, fontify what is treated specially by the exporters."
3666 :group 'org-font-lock
3667 :type 'boolean)
3669 (defcustom org-hide-emphasis-markers nil
3670 "Non-nil mean font-lock should hide the emphasis marker characters."
3671 :group 'org-font-lock
3672 :type 'boolean)
3674 (defvar org-emph-re nil
3675 "Regular expression for matching emphasis.")
3676 (defvar org-verbatim-re nil
3677 "Regular expression for matching verbatim text.")
3678 (defvar org-emphasis-regexp-components) ; defined just below
3679 (defvar org-emphasis-alist) ; defined just below
3680 (defun org-set-emph-re (var val)
3681 "Set variable and compute the emphasis regular expression."
3682 (set var val)
3683 (when (and (boundp 'org-emphasis-alist)
3684 (boundp 'org-emphasis-regexp-components)
3685 org-emphasis-alist org-emphasis-regexp-components)
3686 (let* ((e org-emphasis-regexp-components)
3687 (pre (car e))
3688 (post (nth 1 e))
3689 (border (nth 2 e))
3690 (body (nth 3 e))
3691 (nl (nth 4 e))
3692 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3693 (body1 (concat body "*?"))
3694 (markers (mapconcat 'car org-emphasis-alist ""))
3695 (vmarkers (mapconcat
3696 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3697 org-emphasis-alist "")))
3698 ;; make sure special characters appear at the right position in the class
3699 (if (string-match "\\^" markers)
3700 (setq markers (concat (replace-match "" t t markers) "^")))
3701 (if (string-match "-" markers)
3702 (setq markers (concat (replace-match "" t t markers) "-")))
3703 (if (string-match "\\^" vmarkers)
3704 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3705 (if (string-match "-" vmarkers)
3706 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3707 (if (> nl 0)
3708 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3709 (int-to-string nl) "\\}")))
3710 ;; Make the regexp
3711 (setq org-emph-re
3712 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3713 "\\("
3714 "\\([" markers "]\\)"
3715 "\\("
3716 "[^" border "]\\|"
3717 "[^" border (if (and nil stacked) markers) "]"
3718 body1
3719 "[^" border (if (and nil stacked) markers) "]"
3720 "\\)"
3721 "\\3\\)"
3722 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3723 (setq org-verbatim-re
3724 (concat "\\([" pre "]\\|^\\)"
3725 "\\("
3726 "\\([" vmarkers "]\\)"
3727 "\\("
3728 "[^" border "]\\|"
3729 "[^" border "]"
3730 body1
3731 "[^" border "]"
3732 "\\)"
3733 "\\3\\)"
3734 "\\([" post "]\\|$\\)")))))
3736 (defcustom org-emphasis-regexp-components
3737 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3738 "Components used to build the regular expression for emphasis.
3739 This is a list with 6 entries. Terminology: In an emphasis string
3740 like \" *strong word* \", we call the initial space PREMATCH, the final
3741 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3742 and \"trong wor\" is the body. The different components in this variable
3743 specify what is allowed/forbidden in each part:
3745 pre Chars allowed as prematch. Beginning of line will be allowed too.
3746 post Chars allowed as postmatch. End of line will be allowed too.
3747 border The chars *forbidden* as border characters.
3748 body-regexp A regexp like \".\" to match a body character. Don't use
3749 non-shy groups here, and don't allow newline here.
3750 newline The maximum number of newlines allowed in an emphasis exp.
3752 Use customize to modify this, or restart Emacs after changing it."
3753 :group 'org-font-lock
3754 :set 'org-set-emph-re
3755 :type '(list
3756 (sexp :tag "Allowed chars in pre ")
3757 (sexp :tag "Allowed chars in post ")
3758 (sexp :tag "Forbidden chars in border ")
3759 (sexp :tag "Regexp for body ")
3760 (integer :tag "number of newlines allowed")
3761 (option (boolean :tag "Stacking (DISABLED) "))))
3763 (defcustom org-emphasis-alist
3764 '(("*" bold "<b>" "</b>")
3765 ("/" italic "<i>" "</i>")
3766 ("_" underline "<u>" "</u>")
3767 ("=" org-code "<code>" "</code>" verbatim)
3768 ("~" org-verbatim "" "" verbatim)
3769 ("+" (:strike-through t) "<del>" "</del>")
3771 "Special syntax for emphasized text.
3772 Text starting and ending with a special character will be emphasized, for
3773 example *bold*, _underlined_ and /italic/. This variable sets the marker
3774 characters, the face to be used by font-lock for highlighting in Org-mode
3775 Emacs buffers, and the HTML tags to be used for this.
3776 Use customize to modify this, or restart Emacs after changing it."
3777 :group 'org-font-lock
3778 :set 'org-set-emph-re
3779 :type '(repeat
3780 (list
3781 (string :tag "Marker character")
3782 (choice
3783 (face :tag "Font-lock-face")
3784 (plist :tag "Face property list"))
3785 (string :tag "HTML start tag")
3786 (string :tag "HTML end tag")
3787 (option (const verbatim)))))
3789 ;;; The faces
3791 (defgroup org-faces nil
3792 "Faces in Org-mode."
3793 :tag "Org Faces"
3794 :group 'org-font-lock)
3796 (defun org-compatible-face (inherits specs)
3797 "Make a compatible face specification.
3798 If INHERITS is an existing face and if the Emacs version supports it,
3799 just inherit the face. If not, use SPECS to define the face.
3800 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3801 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3802 to the top of the list. The `min-colors' attribute will be removed from
3803 any other entries, and any resulting duplicates will be removed entirely."
3804 (cond
3805 ((and inherits (facep inherits)
3806 (not (featurep 'xemacs)) (> emacs-major-version 22))
3807 ;; In Emacs 23, we use inheritance where possible.
3808 ;; We only do this in Emacs 23, because only there the outline
3809 ;; faces have been changed to the original org-mode-level-faces.
3810 (list (list t :inherit inherits)))
3811 ((or (featurep 'xemacs) (< emacs-major-version 22))
3812 ;; These do not understand the `min-colors' attribute.
3813 (let (r e a)
3814 (while (setq e (pop specs))
3815 (cond
3816 ((memq (car e) '(t default)) (push e r))
3817 ((setq a (member '(min-colors 8) (car e)))
3818 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3819 (cdr e)))))
3820 ((setq a (assq 'min-colors (car e)))
3821 (setq e (cons (delq a (car e)) (cdr e)))
3822 (or (assoc (car e) r) (push e r)))
3823 (t (or (assoc (car e) r) (push e r)))))
3824 (nreverse r)))
3825 (t specs)))
3826 (put 'org-compatible-face 'lisp-indent-function 1)
3828 (defface org-hide
3829 '((((background light)) (:foreground "white"))
3830 (((background dark)) (:foreground "black")))
3831 "Face used to hide leading stars in headlines.
3832 The forground color of this face should be equal to the background
3833 color of the frame."
3834 :group 'org-faces)
3836 (defface org-level-1 ;; font-lock-function-name-face
3837 (org-compatible-face 'outline-1
3838 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3839 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3840 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3841 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3842 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3843 (t (:bold t))))
3844 "Face used for level 1 headlines."
3845 :group 'org-faces)
3847 (defface org-level-2 ;; font-lock-variable-name-face
3848 (org-compatible-face 'outline-2
3849 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3850 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3851 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3852 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3853 (t (:bold t))))
3854 "Face used for level 2 headlines."
3855 :group 'org-faces)
3857 (defface org-level-3 ;; font-lock-keyword-face
3858 (org-compatible-face 'outline-3
3859 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3860 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3861 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3862 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3863 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3864 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3865 (t (:bold t))))
3866 "Face used for level 3 headlines."
3867 :group 'org-faces)
3869 (defface org-level-4 ;; font-lock-comment-face
3870 (org-compatible-face 'outline-4
3871 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3872 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3873 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3874 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3875 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3876 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3877 (t (:bold t))))
3878 "Face used for level 4 headlines."
3879 :group 'org-faces)
3881 (defface org-level-5 ;; font-lock-type-face
3882 (org-compatible-face 'outline-5
3883 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3884 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3885 (((class color) (min-colors 8)) (:foreground "green"))))
3886 "Face used for level 5 headlines."
3887 :group 'org-faces)
3889 (defface org-level-6 ;; font-lock-constant-face
3890 (org-compatible-face 'outline-6
3891 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3892 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3893 (((class color) (min-colors 8)) (:foreground "magenta"))))
3894 "Face used for level 6 headlines."
3895 :group 'org-faces)
3897 (defface org-level-7 ;; font-lock-builtin-face
3898 (org-compatible-face 'outline-7
3899 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3900 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3901 (((class color) (min-colors 8)) (:foreground "blue"))))
3902 "Face used for level 7 headlines."
3903 :group 'org-faces)
3905 (defface org-level-8 ;; font-lock-string-face
3906 (org-compatible-face 'outline-8
3907 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3908 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3909 (((class color) (min-colors 8)) (:foreground "green"))))
3910 "Face used for level 8 headlines."
3911 :group 'org-faces)
3913 (defface org-special-keyword ;; font-lock-string-face
3914 (org-compatible-face nil
3915 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3916 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3917 (t (:italic t))))
3918 "Face used for special keywords."
3919 :group 'org-faces)
3921 (defface org-drawer ;; font-lock-function-name-face
3922 (org-compatible-face nil
3923 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3924 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3925 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3926 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3927 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3928 (t (:bold t))))
3929 "Face used for drawers."
3930 :group 'org-faces)
3932 (defface org-property-value nil
3933 "Face used for the value of a property."
3934 :group 'org-faces)
3936 (defface org-column
3937 (org-compatible-face nil
3938 '((((class color) (min-colors 16) (background light))
3939 (:background "grey90"))
3940 (((class color) (min-colors 16) (background dark))
3941 (:background "grey30"))
3942 (((class color) (min-colors 8))
3943 (:background "cyan" :foreground "black"))
3944 (t (:inverse-video t))))
3945 "Face for column display of entry properties."
3946 :group 'org-faces)
3948 (when (fboundp 'set-face-attribute)
3949 ;; Make sure that a fixed-width face is used when we have a column table.
3950 (set-face-attribute 'org-column nil
3951 :height (face-attribute 'default :height)
3952 :family (face-attribute 'default :family)))
3954 (defface org-warning
3955 (org-compatible-face 'font-lock-warning-face
3956 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3957 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3958 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3959 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3960 (t (:bold t))))
3961 "Face for deadlines and TODO keywords."
3962 :group 'org-faces)
3964 (defface org-archived ; similar to shadow
3965 (org-compatible-face 'shadow
3966 '((((class color grayscale) (min-colors 88) (background light))
3967 (:foreground "grey50"))
3968 (((class color grayscale) (min-colors 88) (background dark))
3969 (:foreground "grey70"))
3970 (((class color) (min-colors 8) (background light))
3971 (:foreground "green"))
3972 (((class color) (min-colors 8) (background dark))
3973 (:foreground "yellow"))))
3974 "Face for headline with the ARCHIVE tag."
3975 :group 'org-faces)
3977 (defface org-link
3978 '((((class color) (background light)) (:foreground "Purple" :underline t))
3979 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3980 (t (:underline t)))
3981 "Face for links."
3982 :group 'org-faces)
3984 (defface org-ellipsis
3985 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3986 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3987 (t (:strike-through t)))
3988 "Face for the ellipsis in folded text."
3989 :group 'org-faces)
3991 (defface org-target
3992 '((((class color) (background light)) (:underline t))
3993 (((class color) (background dark)) (:underline t))
3994 (t (:underline t)))
3995 "Face for links."
3996 :group 'org-faces)
3998 (defface org-date
3999 '((((class color) (background light)) (:foreground "Purple" :underline t))
4000 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4001 (t (:underline t)))
4002 "Face for links."
4003 :group 'org-faces)
4005 (defface org-sexp-date
4006 '((((class color) (background light)) (:foreground "Purple"))
4007 (((class color) (background dark)) (:foreground "Cyan"))
4008 (t (:underline t)))
4009 "Face for links."
4010 :group 'org-faces)
4012 (defface org-tag
4013 '((t (:bold t)))
4014 "Face for tags."
4015 :group 'org-faces)
4017 (defface org-todo ; font-lock-warning-face
4018 (org-compatible-face nil
4019 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4020 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4021 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4022 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4023 (t (:inverse-video t :bold t))))
4024 "Face for TODO keywords."
4025 :group 'org-faces)
4027 (defface org-done ;; font-lock-type-face
4028 (org-compatible-face nil
4029 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4030 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4031 (((class color) (min-colors 8)) (:foreground "green"))
4032 (t (:bold t))))
4033 "Face used for todo keywords that indicate DONE items."
4034 :group 'org-faces)
4036 (defface org-headline-done ;; font-lock-string-face
4037 (org-compatible-face nil
4038 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4039 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4040 (((class color) (min-colors 8) (background light)) (:bold nil))))
4041 "Face used to indicate that a headline is DONE.
4042 This face is only used if `org-fontify-done-headline' is set. If applies
4043 to the part of the headline after the DONE keyword."
4044 :group 'org-faces)
4046 (defcustom org-todo-keyword-faces nil
4047 "Faces for specific TODO keywords.
4048 This is a list of cons cells, with TODO keywords in the car
4049 and faces in the cdr. The face can be a symbol, or a property
4050 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4051 :group 'org-faces
4052 :group 'org-todo
4053 :type '(repeat
4054 (cons
4055 (string :tag "keyword")
4056 (sexp :tag "face"))))
4058 (defface org-table ;; font-lock-function-name-face
4059 (org-compatible-face nil
4060 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4061 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4062 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4063 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4064 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4065 (((class color) (min-colors 8) (background dark)))))
4066 "Face used for tables."
4067 :group 'org-faces)
4069 (defface org-formula
4070 (org-compatible-face nil
4071 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4072 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4073 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4074 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4075 (t (:bold t :italic t))))
4076 "Face for formulas."
4077 :group 'org-faces)
4079 (defface org-code
4080 (org-compatible-face nil
4081 '((((class color grayscale) (min-colors 88) (background light))
4082 (:foreground "grey50"))
4083 (((class color grayscale) (min-colors 88) (background dark))
4084 (:foreground "grey70"))
4085 (((class color) (min-colors 8) (background light))
4086 (:foreground "green"))
4087 (((class color) (min-colors 8) (background dark))
4088 (:foreground "yellow"))))
4089 "Face for fixed-with text like code snippets."
4090 :group 'org-faces
4091 :version "22.1")
4093 (defface org-verbatim
4094 (org-compatible-face nil
4095 '((((class color grayscale) (min-colors 88) (background light))
4096 (:foreground "grey50" :underline t))
4097 (((class color grayscale) (min-colors 88) (background dark))
4098 (:foreground "grey70" :underline t))
4099 (((class color) (min-colors 8) (background light))
4100 (:foreground "green" :underline t))
4101 (((class color) (min-colors 8) (background dark))
4102 (:foreground "yellow" :underline t))))
4103 "Face for fixed-with text like code snippets."
4104 :group 'org-faces
4105 :version "22.1")
4107 (defface org-agenda-structure ;; font-lock-function-name-face
4108 (org-compatible-face nil
4109 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4110 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4111 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4112 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4113 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4114 (t (:bold t))))
4115 "Face used in agenda for captions and dates."
4116 :group 'org-faces)
4118 (defface org-scheduled-today
4119 (org-compatible-face nil
4120 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4121 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4122 (((class color) (min-colors 8)) (:foreground "green"))
4123 (t (:bold t :italic t))))
4124 "Face for items scheduled for a certain day."
4125 :group 'org-faces)
4127 (defface org-scheduled-previously
4128 (org-compatible-face nil
4129 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4130 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4131 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4132 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4133 (t (:bold t))))
4134 "Face for items scheduled previously, and not yet done."
4135 :group 'org-faces)
4137 (defface org-upcoming-deadline
4138 (org-compatible-face nil
4139 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4140 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4141 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4142 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4143 (t (:bold t))))
4144 "Face for items scheduled previously, and not yet done."
4145 :group 'org-faces)
4147 (defcustom org-agenda-deadline-faces
4148 '((1.0 . org-warning)
4149 (0.5 . org-upcoming-deadline)
4150 (0.0 . default))
4151 "Faces for showing deadlines in the agenda.
4152 This is a list of cons cells. The cdr of each cell is a face to be used,
4153 and it can also just be like '(:foreground \"yellow\").
4154 Each car is a fraction of the head-warning time that must have passed for
4155 this the face in the cdr to be used for display. The numbers must be
4156 given in descending order. The head-warning time is normally taken
4157 from `org-deadline-warning-days', but can also be specified in the deadline
4158 timestamp itself, like this:
4160 DEADLINE: <2007-08-13 Mon -8d>
4162 You may use d for days, w for weeks, m for months and y for years. Months
4163 and years will only be treated in an approximate fashion (30.4 days for a
4164 month and 365.24 days for a year)."
4165 :group 'org-faces
4166 :group 'org-agenda-daily/weekly
4167 :type '(repeat
4168 (cons
4169 (number :tag "Fraction of head-warning time passed")
4170 (sexp :tag "Face"))))
4172 ;; FIXME: this is not a good face yet.
4173 (defface org-agenda-restriction-lock
4174 (org-compatible-face nil
4175 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4176 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4177 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4178 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4179 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4180 (t (:inverse-video t))))
4181 "Face for showing the agenda restriction lock."
4182 :group 'org-faces)
4184 (defface org-time-grid ;; font-lock-variable-name-face
4185 (org-compatible-face nil
4186 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4187 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4188 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4189 "Face used for time grids."
4190 :group 'org-faces)
4192 (defconst org-level-faces
4193 '(org-level-1 org-level-2 org-level-3 org-level-4
4194 org-level-5 org-level-6 org-level-7 org-level-8
4197 (defcustom org-n-level-faces (length org-level-faces)
4198 "The number different faces to be used for headlines.
4199 Org-mode defines 8 different headline faces, so this can be at most 8.
4200 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4201 :type 'number
4202 :group 'org-faces)
4204 ;;; Functions and variables from ther packages
4205 ;; Declared here to avoid compiler warnings
4207 (eval-and-compile
4208 (unless (fboundp 'declare-function)
4209 (defmacro declare-function (fn file &optional arglist fileonly))))
4211 ;; XEmacs only
4212 (defvar outline-mode-menu-heading)
4213 (defvar outline-mode-menu-show)
4214 (defvar outline-mode-menu-hide)
4215 (defvar zmacs-regions) ; XEmacs regions
4217 ;; Emacs only
4218 (defvar mark-active)
4220 ;; Various packages
4221 ;; FIXME: get the argument lists for the UNKNOWN stuff
4222 (declare-function add-to-diary-list "diary-lib"
4223 (date string specifier &optional marker globcolor literal))
4224 (declare-function table--at-cell-p "table" (position &optional object at-column))
4225 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4226 (declare-function Info-goto-node "info" (nodename &optional fork))
4227 (declare-function bbdb "ext:bbdb-com" (string elidep))
4228 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4229 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4230 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4231 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4232 (declare-function bbdb-record-name "ext:bbdb" (record))
4233 (declare-function bibtex-beginning-of-entry "bibtex" ())
4234 (declare-function bibtex-generate-autokey "bibtex" ())
4235 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4236 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4237 (defvar calc-embedded-close-formula)
4238 (defvar calc-embedded-open-formula)
4239 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4240 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4241 (declare-function calendar-check-holidays "holidays" (date))
4242 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4243 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4244 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4245 (declare-function calendar-forward-day "cal-move" (arg))
4246 (declare-function calendar-french-date-string "cal-french" (&optional date))
4247 (declare-function calendar-goto-date "cal-move" (date))
4248 (declare-function calendar-goto-today "cal-move" ())
4249 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4250 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4251 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4252 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4253 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4254 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4255 (defvar calendar-mode-map)
4256 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4257 (declare-function cdlatex-tab "ext:cdlatex" ())
4258 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4259 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4260 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4261 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4262 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4263 (defvar font-lock-unfontify-region-function)
4264 (declare-function gnus-article-show-summary "gnus-art" ())
4265 (declare-function gnus-summary-last-subject "gnus-sum" ())
4266 (defvar gnus-other-frame-object)
4267 (defvar gnus-group-name)
4268 (defvar gnus-article-current)
4269 (defvar Info-current-file)
4270 (defvar Info-current-node)
4271 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4272 (declare-function mh-find-path "mh-utils" ())
4273 (declare-function mh-get-header-field "mh-utils" (field))
4274 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4275 (declare-function mh-header-display "mh-show" ())
4276 (declare-function mh-index-previous-folder "mh-search" ())
4277 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4278 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4279 (declare-function mh-search-choose "mh-search" (&optional searcher))
4280 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4281 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4282 (declare-function mh-show-header-display "mh-show" t t)
4283 (declare-function mh-show-msg "mh-show" (msg))
4284 (declare-function mh-show-show "mh-show" t t)
4285 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4286 (defvar mh-progs)
4287 (defvar mh-current-folder)
4288 (defvar mh-show-folder-buffer)
4289 (defvar mh-index-folder)
4290 (defvar mh-searcher)
4291 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4292 (declare-function parse-time-string "parse-time" (string))
4293 (declare-function remember "remember" (&optional initial))
4294 (declare-function remember-buffer-desc "remember" ())
4295 (declare-function remember-finalize "remember" ())
4296 (defvar remember-save-after-remembering)
4297 (defvar remember-data-file)
4298 (defvar remember-register)
4299 (defvar remember-buffer)
4300 (defvar remember-handler-functions)
4301 (defvar remember-annotation-functions)
4302 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4303 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4304 (declare-function rmail-what-message "rmail" ())
4305 (defvar rmail-current-message)
4306 (defvar texmathp-why)
4307 (declare-function vm-beginning-of-message "ext:vm-page" ())
4308 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4309 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4310 (declare-function vm-isearch-narrow "ext:vm-search" ())
4311 (declare-function vm-isearch-update "ext:vm-search" ())
4312 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4313 (declare-function vm-su-message-id "ext:vm-summary" (m))
4314 (declare-function vm-su-subject "ext:vm-summary" (m))
4315 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4316 (defvar vm-message-pointer)
4317 (defvar vm-folder-directory)
4318 (defvar w3m-current-url)
4319 (defvar w3m-current-title)
4320 ;; backward compatibility to old version of wl
4321 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4322 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4323 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4324 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4325 (declare-function wl-summary-line-from "ext:wl-summary" ())
4326 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4327 (declare-function wl-summary-message-number "ext:wl-summary" ())
4328 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4329 (defvar wl-summary-buffer-elmo-folder)
4330 (defvar wl-summary-buffer-folder-name)
4331 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4333 (defvar org-latex-regexps)
4334 (defvar constants-unit-system)
4336 ;;; Variables for pre-computed regular expressions, all buffer local
4338 (defvar org-drawer-regexp nil
4339 "Matches first line of a hidden block.")
4340 (make-variable-buffer-local 'org-drawer-regexp)
4341 (defvar org-todo-regexp nil
4342 "Matches any of the TODO state keywords.")
4343 (make-variable-buffer-local 'org-todo-regexp)
4344 (defvar org-not-done-regexp nil
4345 "Matches any of the TODO state keywords except the last one.")
4346 (make-variable-buffer-local 'org-not-done-regexp)
4347 (defvar org-todo-line-regexp nil
4348 "Matches a headline and puts TODO state into group 2 if present.")
4349 (make-variable-buffer-local 'org-todo-line-regexp)
4350 (defvar org-complex-heading-regexp nil
4351 "Matches a headline and puts everything into groups:
4352 group 1: the stars
4353 group 2: The todo keyword, maybe
4354 group 3: Priority cookie
4355 group 4: True headline
4356 group 5: Tags")
4357 (make-variable-buffer-local 'org-complex-heading-regexp)
4358 (defvar org-todo-line-tags-regexp nil
4359 "Matches a headline and puts TODO state into group 2 if present.
4360 Also put tags into group 4 if tags are present.")
4361 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4362 (defvar org-nl-done-regexp nil
4363 "Matches newline followed by a headline with the DONE keyword.")
4364 (make-variable-buffer-local 'org-nl-done-regexp)
4365 (defvar org-looking-at-done-regexp nil
4366 "Matches the DONE keyword a point.")
4367 (make-variable-buffer-local 'org-looking-at-done-regexp)
4368 (defvar org-ds-keyword-length 12
4369 "Maximum length of the Deadline and SCHEDULED keywords.")
4370 (make-variable-buffer-local 'org-ds-keyword-length)
4371 (defvar org-deadline-regexp nil
4372 "Matches the DEADLINE keyword.")
4373 (make-variable-buffer-local 'org-deadline-regexp)
4374 (defvar org-deadline-time-regexp nil
4375 "Matches the DEADLINE keyword together with a time stamp.")
4376 (make-variable-buffer-local 'org-deadline-time-regexp)
4377 (defvar org-deadline-line-regexp nil
4378 "Matches the DEADLINE keyword and the rest of the line.")
4379 (make-variable-buffer-local 'org-deadline-line-regexp)
4380 (defvar org-scheduled-regexp nil
4381 "Matches the SCHEDULED keyword.")
4382 (make-variable-buffer-local 'org-scheduled-regexp)
4383 (defvar org-scheduled-time-regexp nil
4384 "Matches the SCHEDULED keyword together with a time stamp.")
4385 (make-variable-buffer-local 'org-scheduled-time-regexp)
4386 (defvar org-closed-time-regexp nil
4387 "Matches the CLOSED keyword together with a time stamp.")
4388 (make-variable-buffer-local 'org-closed-time-regexp)
4390 (defvar org-keyword-time-regexp nil
4391 "Matches any of the 4 keywords, together with the time stamp.")
4392 (make-variable-buffer-local 'org-keyword-time-regexp)
4393 (defvar org-keyword-time-not-clock-regexp nil
4394 "Matches any of the 3 keywords, together with the time stamp.")
4395 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4396 (defvar org-maybe-keyword-time-regexp nil
4397 "Matches a timestamp, possibly preceeded by a keyword.")
4398 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4399 (defvar org-planning-or-clock-line-re nil
4400 "Matches a line with planning or clock info.")
4401 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4403 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4404 rear-nonsticky t mouse-map t fontified t)
4405 "Properties to remove when a string without properties is wanted.")
4407 (defsubst org-match-string-no-properties (num &optional string)
4408 (if (featurep 'xemacs)
4409 (let ((s (match-string num string)))
4410 (remove-text-properties 0 (length s) org-rm-props s)
4412 (match-string-no-properties num string)))
4414 (defsubst org-no-properties (s)
4415 (if (fboundp 'set-text-properties)
4416 (set-text-properties 0 (length s) nil s)
4417 (remove-text-properties 0 (length s) org-rm-props s))
4420 (defsubst org-get-alist-option (option key)
4421 (cond ((eq key t) t)
4422 ((eq option t) t)
4423 ((assoc key option) (cdr (assoc key option)))
4424 (t (cdr (assq 'default option)))))
4426 (defsubst org-inhibit-invisibility ()
4427 "Modified `buffer-invisibility-spec' for Emacs 21.
4428 Some ops with invisible text do not work correctly on Emacs 21. For these
4429 we turn off invisibility temporarily. Use this in a `let' form."
4430 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4432 (defsubst org-set-local (var value)
4433 "Make VAR local in current buffer and set it to VALUE."
4434 (set (make-variable-buffer-local var) value))
4436 (defsubst org-mode-p ()
4437 "Check if the current buffer is in Org-mode."
4438 (eq major-mode 'org-mode))
4440 (defsubst org-last (list)
4441 "Return the last element of LIST."
4442 (car (last list)))
4444 (defun org-let (list &rest body)
4445 (eval (cons 'let (cons list body))))
4446 (put 'org-let 'lisp-indent-function 1)
4448 (defun org-let2 (list1 list2 &rest body)
4449 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4450 (put 'org-let2 'lisp-indent-function 2)
4451 (defconst org-startup-options
4452 '(("fold" org-startup-folded t)
4453 ("overview" org-startup-folded t)
4454 ("nofold" org-startup-folded nil)
4455 ("showall" org-startup-folded nil)
4456 ("content" org-startup-folded content)
4457 ("hidestars" org-hide-leading-stars t)
4458 ("showstars" org-hide-leading-stars nil)
4459 ("odd" org-odd-levels-only t)
4460 ("oddeven" org-odd-levels-only nil)
4461 ("align" org-startup-align-all-tables t)
4462 ("noalign" org-startup-align-all-tables nil)
4463 ("customtime" org-display-custom-times t)
4464 ("logdone" org-log-done time)
4465 ("lognotedone" org-log-done note)
4466 ("nologdone" org-log-done nil)
4467 ("lognoteclock-out" org-log-note-clock-out t)
4468 ("nolognoteclock-out" org-log-note-clock-out nil)
4469 ("logrepeat" org-log-repeat state)
4470 ("lognoterepeat" org-log-repeat note)
4471 ("nologrepeat" org-log-repeat nil)
4472 ("constcgs" constants-unit-system cgs)
4473 ("constSI" constants-unit-system SI))
4474 "Variable associated with STARTUP options for org-mode.
4475 Each element is a list of three items: The startup options as written
4476 in the #+STARTUP line, the corresponding variable, and the value to
4477 set this variable to if the option is found. An optional forth element PUSH
4478 means to push this value onto the list in the variable.")
4480 (defun org-set-regexps-and-options ()
4481 "Precompute regular expressions for current buffer."
4482 (when (org-mode-p)
4483 (org-set-local 'org-todo-kwd-alist nil)
4484 (org-set-local 'org-todo-key-alist nil)
4485 (org-set-local 'org-todo-key-trigger nil)
4486 (org-set-local 'org-todo-keywords-1 nil)
4487 (org-set-local 'org-done-keywords nil)
4488 (org-set-local 'org-todo-heads nil)
4489 (org-set-local 'org-todo-sets nil)
4490 (org-set-local 'org-todo-log-states nil)
4491 (let ((re (org-make-options-regexp
4492 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4493 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4494 "CONSTANTS" "PROPERTY" "DRAWERS")))
4495 (splitre "[ \t]+")
4496 kwds kws0 kwsa key log value cat arch tags const links hw dws
4497 tail sep kws1 prio props drawers)
4498 (save-excursion
4499 (save-restriction
4500 (widen)
4501 (goto-char (point-min))
4502 (while (re-search-forward re nil t)
4503 (setq key (match-string 1) value (org-match-string-no-properties 2))
4504 (cond
4505 ((equal key "CATEGORY")
4506 (if (string-match "[ \t]+$" value)
4507 (setq value (replace-match "" t t value)))
4508 (setq cat value))
4509 ((member key '("SEQ_TODO" "TODO"))
4510 (push (cons 'sequence (org-split-string value splitre)) kwds))
4511 ((equal key "TYP_TODO")
4512 (push (cons 'type (org-split-string value splitre)) kwds))
4513 ((equal key "TAGS")
4514 (setq tags (append tags (org-split-string value splitre))))
4515 ((equal key "COLUMNS")
4516 (org-set-local 'org-columns-default-format value))
4517 ((equal key "LINK")
4518 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4519 (push (cons (match-string 1 value)
4520 (org-trim (match-string 2 value)))
4521 links)))
4522 ((equal key "PRIORITIES")
4523 (setq prio (org-split-string value " +")))
4524 ((equal key "PROPERTY")
4525 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4526 (push (cons (match-string 1 value) (match-string 2 value))
4527 props)))
4528 ((equal key "DRAWERS")
4529 (setq drawers (org-split-string value splitre)))
4530 ((equal key "CONSTANTS")
4531 (setq const (append const (org-split-string value splitre))))
4532 ((equal key "STARTUP")
4533 (let ((opts (org-split-string value splitre))
4534 l var val)
4535 (while (setq l (pop opts))
4536 (when (setq l (assoc l org-startup-options))
4537 (setq var (nth 1 l) val (nth 2 l))
4538 (if (not (nth 3 l))
4539 (set (make-local-variable var) val)
4540 (if (not (listp (symbol-value var)))
4541 (set (make-local-variable var) nil))
4542 (set (make-local-variable var) (symbol-value var))
4543 (add-to-list var val))))))
4544 ((equal key "ARCHIVE")
4545 (string-match " *$" value)
4546 (setq arch (replace-match "" t t value))
4547 (remove-text-properties 0 (length arch)
4548 '(face t fontified t) arch)))
4550 (when cat
4551 (org-set-local 'org-category (intern cat))
4552 (push (cons "CATEGORY" cat) props))
4553 (when prio
4554 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4555 (setq prio (mapcar 'string-to-char prio))
4556 (org-set-local 'org-highest-priority (nth 0 prio))
4557 (org-set-local 'org-lowest-priority (nth 1 prio))
4558 (org-set-local 'org-default-priority (nth 2 prio)))
4559 (and props (org-set-local 'org-local-properties (nreverse props)))
4560 (and drawers (org-set-local 'org-drawers drawers))
4561 (and arch (org-set-local 'org-archive-location arch))
4562 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4563 ;; Process the TODO keywords
4564 (unless kwds
4565 ;; Use the global values as if they had been given locally.
4566 (setq kwds (default-value 'org-todo-keywords))
4567 (if (stringp (car kwds))
4568 (setq kwds (list (cons org-todo-interpretation
4569 (default-value 'org-todo-keywords)))))
4570 (setq kwds (reverse kwds)))
4571 (setq kwds (nreverse kwds))
4572 (let (inter kws kw)
4573 (while (setq kws (pop kwds))
4574 (setq inter (pop kws) sep (member "|" kws)
4575 kws0 (delete "|" (copy-sequence kws))
4576 kwsa nil
4577 kws1 (mapcar
4578 (lambda (x)
4579 ;; 1 2
4580 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4581 (progn
4582 (setq kw (match-string 1 x)
4583 key (and (match-end 2) (match-string 2 x))
4584 log (org-extract-log-state-settings x))
4585 (push (cons kw (and key (string-to-char key))) kwsa)
4586 (and log (push log org-todo-log-states))
4588 (error "Invalid TODO keyword %s" x)))
4589 kws0)
4590 kwsa (if kwsa (append '((:startgroup))
4591 (nreverse kwsa)
4592 '((:endgroup))))
4593 hw (car kws1)
4594 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4595 tail (list inter hw (car dws) (org-last dws)))
4596 (add-to-list 'org-todo-heads hw 'append)
4597 (push kws1 org-todo-sets)
4598 (setq org-done-keywords (append org-done-keywords dws nil))
4599 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4600 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4601 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4602 (setq org-todo-sets (nreverse org-todo-sets)
4603 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4604 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4605 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4606 ;; Process the constants
4607 (when const
4608 (let (e cst)
4609 (while (setq e (pop const))
4610 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4611 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4612 (setq org-table-formula-constants-local cst)))
4614 ;; Process the tags.
4615 (when tags
4616 (let (e tgs)
4617 (while (setq e (pop tags))
4618 (cond
4619 ((equal e "{") (push '(:startgroup) tgs))
4620 ((equal e "}") (push '(:endgroup) tgs))
4621 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4622 (push (cons (match-string 1 e)
4623 (string-to-char (match-string 2 e)))
4624 tgs))
4625 (t (push (list e) tgs))))
4626 (org-set-local 'org-tag-alist nil)
4627 (while (setq e (pop tgs))
4628 (or (and (stringp (car e))
4629 (assoc (car e) org-tag-alist))
4630 (push e org-tag-alist))))))
4632 ;; Compute the regular expressions and other local variables
4633 (if (not org-done-keywords)
4634 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4635 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4636 (length org-scheduled-string)))
4637 org-drawer-regexp
4638 (concat "^[ \t]*:\\("
4639 (mapconcat 'regexp-quote org-drawers "\\|")
4640 "\\):[ \t]*$")
4641 org-not-done-keywords
4642 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4643 org-todo-regexp
4644 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4645 "\\|") "\\)\\>")
4646 org-not-done-regexp
4647 (concat "\\<\\("
4648 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4649 "\\)\\>")
4650 org-todo-line-regexp
4651 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4652 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4653 "\\)\\>\\)?[ \t]*\\(.*\\)")
4654 org-complex-heading-regexp
4655 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4656 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4657 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4658 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4659 org-nl-done-regexp
4660 (concat "\n\\*+[ \t]+"
4661 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4662 "\\)" "\\>")
4663 org-todo-line-tags-regexp
4664 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4665 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4666 (org-re
4667 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4668 org-looking-at-done-regexp
4669 (concat "^" "\\(?:"
4670 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4671 "\\>")
4672 org-deadline-regexp (concat "\\<" org-deadline-string)
4673 org-deadline-time-regexp
4674 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4675 org-deadline-line-regexp
4676 (concat "\\<\\(" org-deadline-string "\\).*")
4677 org-scheduled-regexp
4678 (concat "\\<" org-scheduled-string)
4679 org-scheduled-time-regexp
4680 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4681 org-closed-time-regexp
4682 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4683 org-keyword-time-regexp
4684 (concat "\\<\\(" org-scheduled-string
4685 "\\|" org-deadline-string
4686 "\\|" org-closed-string
4687 "\\|" org-clock-string "\\)"
4688 " *[[<]\\([^]>]+\\)[]>]")
4689 org-keyword-time-not-clock-regexp
4690 (concat "\\<\\(" org-scheduled-string
4691 "\\|" org-deadline-string
4692 "\\|" org-closed-string
4693 "\\)"
4694 " *[[<]\\([^]>]+\\)[]>]")
4695 org-maybe-keyword-time-regexp
4696 (concat "\\(\\<\\(" org-scheduled-string
4697 "\\|" org-deadline-string
4698 "\\|" org-closed-string
4699 "\\|" org-clock-string "\\)\\)?"
4700 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4701 org-planning-or-clock-line-re
4702 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4703 "\\|" org-deadline-string
4704 "\\|" org-closed-string "\\|" org-clock-string
4705 "\\)\\>\\)")
4707 (org-compute-latex-and-specials-regexp)
4708 (org-set-font-lock-defaults)))
4710 (defun org-extract-log-state-settings (x)
4711 "Extract the log state setting from a TODO keyword string.
4712 This will extract info from a string like \"WAIT(w@/!)\"."
4713 (let (kw key log1 log2)
4714 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4715 (setq kw (match-string 1 x)
4716 key (and (match-end 2) (match-string 2 x))
4717 log1 (and (match-end 3) (match-string 3 x))
4718 log2 (and (match-end 4) (match-string 4 x)))
4719 (and (or log1 log2)
4720 (list kw
4721 (and log1 (if (equal log1 "!") 'time 'note))
4722 (and log2 (if (equal log2 "!") 'time 'note)))))))
4724 (defun org-remove-keyword-keys (list)
4725 "Remove a pair of parenthesis at the end of each string in LIST."
4726 (mapcar (lambda (x)
4727 (if (string-match "(.*)$" x)
4728 (substring x 0 (match-beginning 0))
4730 list))
4732 ;; FIXME: this could be done much better, using second characters etc.
4733 (defun org-assign-fast-keys (alist)
4734 "Assign fast keys to a keyword-key alist.
4735 Respect keys that are already there."
4736 (let (new e k c c1 c2 (char ?a))
4737 (while (setq e (pop alist))
4738 (cond
4739 ((equal e '(:startgroup)) (push e new))
4740 ((equal e '(:endgroup)) (push e new))
4742 (setq k (car e) c2 nil)
4743 (if (cdr e)
4744 (setq c (cdr e))
4745 ;; automatically assign a character.
4746 (setq c1 (string-to-char
4747 (downcase (substring
4748 k (if (= (string-to-char k) ?@) 1 0)))))
4749 (if (or (rassoc c1 new) (rassoc c1 alist))
4750 (while (or (rassoc char new) (rassoc char alist))
4751 (setq char (1+ char)))
4752 (setq c2 c1))
4753 (setq c (or c2 char)))
4754 (push (cons k c) new))))
4755 (nreverse new)))
4757 ;;; Some variables ujsed in various places
4759 (defvar org-window-configuration nil
4760 "Used in various places to store a window configuration.")
4761 (defvar org-finish-function nil
4762 "Function to be called when `C-c C-c' is used.
4763 This is for getting out of special buffers like remember.")
4766 ;; FIXME: Occasionally check by commenting these, to make sure
4767 ;; no other functions uses these, forgetting to let-bind them.
4768 (defvar entry)
4769 (defvar state)
4770 (defvar last-state)
4771 (defvar date)
4772 (defvar description)
4774 ;; Defined somewhere in this file, but used before definition.
4775 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4776 (defvar org-agenda-buffer-name)
4777 (defvar org-agenda-undo-list)
4778 (defvar org-agenda-pending-undo-list)
4779 (defvar org-agenda-overriding-header)
4780 (defvar orgtbl-mode)
4781 (defvar org-html-entities)
4782 (defvar org-struct-menu)
4783 (defvar org-org-menu)
4784 (defvar org-tbl-menu)
4785 (defvar org-agenda-keymap)
4787 ;;;; Emacs/XEmacs compatibility
4789 ;; Overlay compatibility functions
4790 (defun org-make-overlay (beg end &optional buffer)
4791 (if (featurep 'xemacs)
4792 (make-extent beg end buffer)
4793 (make-overlay beg end buffer)))
4794 (defun org-delete-overlay (ovl)
4795 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4796 (defun org-detach-overlay (ovl)
4797 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4798 (defun org-move-overlay (ovl beg end &optional buffer)
4799 (if (featurep 'xemacs)
4800 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4801 (move-overlay ovl beg end buffer)))
4802 (defun org-overlay-put (ovl prop value)
4803 (if (featurep 'xemacs)
4804 (set-extent-property ovl prop value)
4805 (overlay-put ovl prop value)))
4806 (defun org-overlay-display (ovl text &optional face evap)
4807 "Make overlay OVL display TEXT with face FACE."
4808 (if (featurep 'xemacs)
4809 (let ((gl (make-glyph text)))
4810 (and face (set-glyph-face gl face))
4811 (set-extent-property ovl 'invisible t)
4812 (set-extent-property ovl 'end-glyph gl))
4813 (overlay-put ovl 'display text)
4814 (if face (overlay-put ovl 'face face))
4815 (if evap (overlay-put ovl 'evaporate t))))
4816 (defun org-overlay-before-string (ovl text &optional face evap)
4817 "Make overlay OVL display TEXT with face FACE."
4818 (if (featurep 'xemacs)
4819 (let ((gl (make-glyph text)))
4820 (and face (set-glyph-face gl face))
4821 (set-extent-property ovl 'begin-glyph gl))
4822 (if face (org-add-props text nil 'face face))
4823 (overlay-put ovl 'before-string text)
4824 (if evap (overlay-put ovl 'evaporate t))))
4825 (defun org-overlay-get (ovl prop)
4826 (if (featurep 'xemacs)
4827 (extent-property ovl prop)
4828 (overlay-get ovl prop)))
4829 (defun org-overlays-at (pos)
4830 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4831 (defun org-overlays-in (&optional start end)
4832 (if (featurep 'xemacs)
4833 (extent-list nil start end)
4834 (overlays-in start end)))
4835 (defun org-overlay-start (o)
4836 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4837 (defun org-overlay-end (o)
4838 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4839 (defun org-find-overlays (prop &optional pos delete)
4840 "Find all overlays specifying PROP at POS or point.
4841 If DELETE is non-nil, delete all those overlays."
4842 (let ((overlays (org-overlays-at (or pos (point))))
4843 ov found)
4844 (while (setq ov (pop overlays))
4845 (if (org-overlay-get ov prop)
4846 (if delete (org-delete-overlay ov) (push ov found))))
4847 found))
4849 ;; Region compatibility
4851 (defun org-add-hook (hook function &optional append local)
4852 "Add-hook, compatible with both Emacsen."
4853 (if (and local (featurep 'xemacs))
4854 (add-local-hook hook function append)
4855 (add-hook hook function append local)))
4857 (defvar org-ignore-region nil
4858 "To temporarily disable the active region.")
4860 (defun org-region-active-p ()
4861 "Is `transient-mark-mode' on and the region active?
4862 Works on both Emacs and XEmacs."
4863 (if org-ignore-region
4865 (if (featurep 'xemacs)
4866 (and zmacs-regions (region-active-p))
4867 (if (fboundp 'use-region-p)
4868 (use-region-p)
4869 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4871 ;; Invisibility compatibility
4873 (defun org-add-to-invisibility-spec (arg)
4874 "Add elements to `buffer-invisibility-spec'.
4875 See documentation for `buffer-invisibility-spec' for the kind of elements
4876 that can be added."
4877 (cond
4878 ((fboundp 'add-to-invisibility-spec)
4879 (add-to-invisibility-spec arg))
4880 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4881 (setq buffer-invisibility-spec (list arg)))
4883 (setq buffer-invisibility-spec
4884 (cons arg buffer-invisibility-spec)))))
4886 (defun org-remove-from-invisibility-spec (arg)
4887 "Remove elements from `buffer-invisibility-spec'."
4888 (if (fboundp 'remove-from-invisibility-spec)
4889 (remove-from-invisibility-spec arg)
4890 (if (consp buffer-invisibility-spec)
4891 (setq buffer-invisibility-spec
4892 (delete arg buffer-invisibility-spec)))))
4894 (defun org-in-invisibility-spec-p (arg)
4895 "Is ARG a member of `buffer-invisibility-spec'?"
4896 (if (consp buffer-invisibility-spec)
4897 (member arg buffer-invisibility-spec)
4898 nil))
4900 ;;;; Define the Org-mode
4902 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4903 (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."))
4906 ;; We use a before-change function to check if a table might need
4907 ;; an update.
4908 (defvar org-table-may-need-update t
4909 "Indicates that a table might need an update.
4910 This variable is set by `org-before-change-function'.
4911 `org-table-align' sets it back to nil.")
4912 (defvar org-mode-map)
4913 (defvar org-mode-hook nil)
4914 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4915 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4916 (defvar org-table-buffer-is-an nil)
4917 (defconst org-outline-regexp "\\*+ ")
4919 ;;;###autoload
4920 (define-derived-mode org-mode outline-mode "Org"
4921 "Outline-based notes management and organizer, alias
4922 \"Carsten's outline-mode for keeping track of everything.\"
4924 Org-mode develops organizational tasks around a NOTES file which
4925 contains information about projects as plain text. Org-mode is
4926 implemented on top of outline-mode, which is ideal to keep the content
4927 of large files well structured. It supports ToDo items, deadlines and
4928 time stamps, which magically appear in the diary listing of the Emacs
4929 calendar. Tables are easily created with a built-in table editor.
4930 Plain text URL-like links connect to websites, emails (VM), Usenet
4931 messages (Gnus), BBDB entries, and any files related to the project.
4932 For printing and sharing of notes, an Org-mode file (or a part of it)
4933 can be exported as a structured ASCII or HTML file.
4935 The following commands are available:
4937 \\{org-mode-map}"
4939 ;; Get rid of Outline menus, they are not needed
4940 ;; Need to do this here because define-derived-mode sets up
4941 ;; the keymap so late. Still, it is a waste to call this each time
4942 ;; we switch another buffer into org-mode.
4943 (if (featurep 'xemacs)
4944 (when (boundp 'outline-mode-menu-heading)
4945 ;; Assume this is Greg's port, it used easymenu
4946 (easy-menu-remove outline-mode-menu-heading)
4947 (easy-menu-remove outline-mode-menu-show)
4948 (easy-menu-remove outline-mode-menu-hide))
4949 (define-key org-mode-map [menu-bar headings] 'undefined)
4950 (define-key org-mode-map [menu-bar hide] 'undefined)
4951 (define-key org-mode-map [menu-bar show] 'undefined))
4953 (easy-menu-add org-org-menu)
4954 (easy-menu-add org-tbl-menu)
4955 (org-install-agenda-files-menu)
4956 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4957 (org-add-to-invisibility-spec '(org-cwidth))
4958 (when (featurep 'xemacs)
4959 (org-set-local 'line-move-ignore-invisible t))
4960 (org-set-local 'outline-regexp org-outline-regexp)
4961 (org-set-local 'outline-level 'org-outline-level)
4962 (when (and org-ellipsis
4963 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4964 (fboundp 'make-glyph-code))
4965 (unless org-display-table
4966 (setq org-display-table (make-display-table)))
4967 (set-display-table-slot
4968 org-display-table 4
4969 (vconcat (mapcar
4970 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4971 org-ellipsis)))
4972 (if (stringp org-ellipsis) org-ellipsis "..."))))
4973 (setq buffer-display-table org-display-table))
4974 (org-set-regexps-and-options)
4975 ;; Calc embedded
4976 (org-set-local 'calc-embedded-open-mode "# ")
4977 (modify-syntax-entry ?# "<")
4978 (modify-syntax-entry ?@ "w")
4979 (if org-startup-truncated (setq truncate-lines t))
4980 (org-set-local 'font-lock-unfontify-region-function
4981 'org-unfontify-region)
4982 ;; Activate before-change-function
4983 (org-set-local 'org-table-may-need-update t)
4984 (org-add-hook 'before-change-functions 'org-before-change-function nil
4985 'local)
4986 ;; Check for running clock before killing a buffer
4987 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4988 ;; Paragraphs and auto-filling
4989 (org-set-autofill-regexps)
4990 (setq indent-line-function 'org-indent-line-function)
4991 (org-update-radio-target-regexp)
4993 ;; Comment characters
4994 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4995 (org-set-local 'comment-padding " ")
4997 ;; Align options lines
4998 (org-set-local
4999 'align-mode-rules-list
5000 '((org-in-buffer-settings
5001 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5002 (modes . '(org-mode)))))
5004 ;; Imenu
5005 (org-set-local 'imenu-create-index-function
5006 'org-imenu-get-tree)
5008 ;; Make isearch reveal context
5009 (if (or (featurep 'xemacs)
5010 (not (boundp 'outline-isearch-open-invisible-function)))
5011 ;; Emacs 21 and XEmacs make use of the hook
5012 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5013 ;; Emacs 22 deals with this through a special variable
5014 (org-set-local 'outline-isearch-open-invisible-function
5015 (lambda (&rest ignore) (org-show-context 'isearch))))
5017 ;; If empty file that did not turn on org-mode automatically, make it to.
5018 (if (and org-insert-mode-line-in-empty-file
5019 (interactive-p)
5020 (= (point-min) (point-max)))
5021 (insert "# -*- mode: org -*-\n\n"))
5023 (unless org-inhibit-startup
5024 (when org-startup-align-all-tables
5025 (let ((bmp (buffer-modified-p)))
5026 (org-table-map-tables 'org-table-align)
5027 (set-buffer-modified-p bmp)))
5028 (org-cycle-hide-drawers 'all)
5029 (cond
5030 ((eq org-startup-folded t)
5031 (org-cycle '(4)))
5032 ((eq org-startup-folded 'content)
5033 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5034 (org-cycle '(4)) (org-cycle '(4)))))))
5036 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5038 (defsubst org-call-with-arg (command arg)
5039 "Call COMMAND interactively, but pretend prefix are was ARG."
5040 (let ((current-prefix-arg arg)) (call-interactively command)))
5042 (defsubst org-current-line (&optional pos)
5043 (save-excursion
5044 (and pos (goto-char pos))
5045 ;; works also in narrowed buffer, because we start at 1, not point-min
5046 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5048 (defun org-current-time ()
5049 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5050 (if (> org-time-stamp-rounding-minutes 0)
5051 (let ((r org-time-stamp-rounding-minutes)
5052 (time (decode-time)))
5053 (apply 'encode-time
5054 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5055 (nthcdr 2 time))))
5056 (current-time)))
5058 (defun org-add-props (string plist &rest props)
5059 "Add text properties to entire string, from beginning to end.
5060 PLIST may be a list of properties, PROPS are individual properties and values
5061 that will be added to PLIST. Returns the string that was modified."
5062 (add-text-properties
5063 0 (length string) (if props (append plist props) plist) string)
5064 string)
5065 (put 'org-add-props 'lisp-indent-function 2)
5068 ;;;; Font-Lock stuff, including the activators
5070 (defvar org-mouse-map (make-sparse-keymap))
5071 (org-defkey org-mouse-map
5072 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5073 (org-defkey org-mouse-map
5074 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5075 (when org-mouse-1-follows-link
5076 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5077 (when org-tab-follows-link
5078 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5079 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5080 (when org-return-follows-link
5081 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5082 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5084 (require 'font-lock)
5086 (defconst org-non-link-chars "]\t\n\r<>")
5087 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5088 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5089 (defvar org-link-re-with-space nil
5090 "Matches a link with spaces, optional angular brackets around it.")
5091 (defvar org-link-re-with-space2 nil
5092 "Matches a link with spaces, optional angular brackets around it.")
5093 (defvar org-angle-link-re nil
5094 "Matches link with angular brackets, spaces are allowed.")
5095 (defvar org-plain-link-re nil
5096 "Matches plain link, without spaces.")
5097 (defvar org-bracket-link-regexp nil
5098 "Matches a link in double brackets.")
5099 (defvar org-bracket-link-analytic-regexp nil
5100 "Regular expression used to analyze links.
5101 Here is what the match groups contain after a match:
5102 1: http:
5103 2: http
5104 3: path
5105 4: [desc]
5106 5: desc")
5107 (defvar org-any-link-re nil
5108 "Regular expression matching any link.")
5110 (defun org-make-link-regexps ()
5111 "Update the link regular expressions.
5112 This should be called after the variable `org-link-types' has changed."
5113 (setq org-link-re-with-space
5114 (concat
5115 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5116 "\\([^" org-non-link-chars " ]"
5117 "[^" org-non-link-chars "]*"
5118 "[^" org-non-link-chars " ]\\)>?")
5119 org-link-re-with-space2
5120 (concat
5121 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5122 "\\([^" org-non-link-chars " ]"
5123 "[^]\t\n\r]*"
5124 "[^" org-non-link-chars " ]\\)>?")
5125 org-angle-link-re
5126 (concat
5127 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5128 "\\([^" org-non-link-chars " ]"
5129 "[^" org-non-link-chars "]*"
5130 "\\)>")
5131 org-plain-link-re
5132 (concat
5133 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5134 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5135 org-bracket-link-regexp
5136 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5137 org-bracket-link-analytic-regexp
5138 (concat
5139 "\\[\\["
5140 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5141 "\\([^]]+\\)"
5142 "\\]"
5143 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5144 "\\]")
5145 org-any-link-re
5146 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5147 org-angle-link-re "\\)\\|\\("
5148 org-plain-link-re "\\)")))
5150 (org-make-link-regexps)
5152 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5153 "Regular expression for fast time stamp matching.")
5154 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5155 "Regular expression for fast time stamp matching.")
5156 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5157 "Regular expression matching time strings for analysis.
5158 This one does not require the space after the date.")
5159 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5160 "Regular expression matching time strings for analysis.")
5161 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5162 "Regular expression matching time stamps, with groups.")
5163 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5164 "Regular expression matching time stamps (also [..]), with groups.")
5165 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5166 "Regular expression matching a time stamp range.")
5167 (defconst org-tr-regexp-both
5168 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5169 "Regular expression matching a time stamp range.")
5170 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5171 org-ts-regexp "\\)?")
5172 "Regular expression matching a time stamp or time stamp range.")
5173 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5174 org-ts-regexp-both "\\)?")
5175 "Regular expression matching a time stamp or time stamp range.
5176 The time stamps may be either active or inactive.")
5178 (defvar org-emph-face nil)
5180 (defun org-do-emphasis-faces (limit)
5181 "Run through the buffer and add overlays to links."
5182 (let (rtn)
5183 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5184 (if (not (= (char-after (match-beginning 3))
5185 (char-after (match-beginning 4))))
5186 (progn
5187 (setq rtn t)
5188 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5189 'face
5190 (nth 1 (assoc (match-string 3)
5191 org-emphasis-alist)))
5192 (add-text-properties (match-beginning 2) (match-end 2)
5193 '(font-lock-multiline t))
5194 (when org-hide-emphasis-markers
5195 (add-text-properties (match-end 4) (match-beginning 5)
5196 '(invisible org-link))
5197 (add-text-properties (match-beginning 3) (match-end 3)
5198 '(invisible org-link)))))
5199 (backward-char 1))
5200 rtn))
5202 (defun org-emphasize (&optional char)
5203 "Insert or change an emphasis, i.e. a font like bold or italic.
5204 If there is an active region, change that region to a new emphasis.
5205 If there is no region, just insert the marker characters and position
5206 the cursor between them.
5207 CHAR should be either the marker character, or the first character of the
5208 HTML tag associated with that emphasis. If CHAR is a space, the means
5209 to remove the emphasis of the selected region.
5210 If char is not given (for example in an interactive call) it
5211 will be prompted for."
5212 (interactive)
5213 (let ((eal org-emphasis-alist) e det
5214 (erc org-emphasis-regexp-components)
5215 (prompt "")
5216 (string "") beg end move tag c s)
5217 (if (org-region-active-p)
5218 (setq beg (region-beginning) end (region-end)
5219 string (buffer-substring beg end))
5220 (setq move t))
5222 (while (setq e (pop eal))
5223 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5224 c (aref tag 0))
5225 (push (cons c (string-to-char (car e))) det)
5226 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5227 (substring tag 1)))))
5228 (unless char
5229 (message "%s" (concat "Emphasis marker or tag:" prompt))
5230 (setq char (read-char-exclusive)))
5231 (setq char (or (cdr (assoc char det)) char))
5232 (if (equal char ?\ )
5233 (setq s "" move nil)
5234 (unless (assoc (char-to-string char) org-emphasis-alist)
5235 (error "No such emphasis marker: \"%c\"" char))
5236 (setq s (char-to-string char)))
5237 (while (and (> (length string) 1)
5238 (equal (substring string 0 1) (substring string -1))
5239 (assoc (substring string 0 1) org-emphasis-alist))
5240 (setq string (substring string 1 -1)))
5241 (setq string (concat s string s))
5242 (if beg (delete-region beg end))
5243 (unless (or (bolp)
5244 (string-match (concat "[" (nth 0 erc) "\n]")
5245 (char-to-string (char-before (point)))))
5246 (insert " "))
5247 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5248 (char-to-string (char-after (point))))
5249 (insert " ") (backward-char 1))
5250 (insert string)
5251 (and move (backward-char 1))))
5253 (defconst org-nonsticky-props
5254 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5257 (defun org-activate-plain-links (limit)
5258 "Run through the buffer and add overlays to links."
5259 (catch 'exit
5260 (let (f)
5261 (while (re-search-forward org-plain-link-re limit t)
5262 (setq f (get-text-property (match-beginning 0) 'face))
5263 (if (or (eq f 'org-tag)
5264 (and (listp f) (memq 'org-tag f)))
5266 (add-text-properties (match-beginning 0) (match-end 0)
5267 (list 'mouse-face 'highlight
5268 'rear-nonsticky org-nonsticky-props
5269 'keymap org-mouse-map
5271 (throw 'exit t))))))
5273 (defun org-activate-code (limit)
5274 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5275 (unless (get-text-property (match-beginning 1) 'face)
5276 (remove-text-properties (match-beginning 0) (match-end 0)
5277 '(display t invisible t intangible t))
5278 t)))
5280 (defun org-activate-angle-links (limit)
5281 "Run through the buffer and add overlays to links."
5282 (if (re-search-forward org-angle-link-re limit t)
5283 (progn
5284 (add-text-properties (match-beginning 0) (match-end 0)
5285 (list 'mouse-face 'highlight
5286 'rear-nonsticky org-nonsticky-props
5287 'keymap org-mouse-map
5289 t)))
5291 (defmacro org-maybe-intangible (props)
5292 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5293 In emacs 21, invisible text is not avoided by the command loop, so the
5294 intangible property is needed to make sure point skips this text.
5295 In Emacs 22, this is not necessary. The intangible text property has
5296 led to problems with flyspell. These problems are fixed in flyspell.el,
5297 but we still avoid setting the property in Emacs 22 and later.
5298 We use a macro so that the test can happen at compilation time."
5299 (if (< emacs-major-version 22)
5300 `(append '(intangible t) ,props)
5301 props))
5303 (defun org-activate-bracket-links (limit)
5304 "Run through the buffer and add overlays to bracketed links."
5305 (if (re-search-forward org-bracket-link-regexp limit t)
5306 (let* ((help (concat "LINK: "
5307 (org-match-string-no-properties 1)))
5308 ;; FIXME: above we should remove the escapes.
5309 ;; but that requires another match, protecting match data,
5310 ;; a lot of overhead for font-lock.
5311 (ip (org-maybe-intangible
5312 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5313 'keymap org-mouse-map 'mouse-face 'highlight
5314 'font-lock-multiline t 'help-echo help)))
5315 (vp (list 'rear-nonsticky org-nonsticky-props
5316 'keymap org-mouse-map 'mouse-face 'highlight
5317 ' font-lock-multiline t 'help-echo help)))
5318 ;; We need to remove the invisible property here. Table narrowing
5319 ;; may have made some of this invisible.
5320 (remove-text-properties (match-beginning 0) (match-end 0)
5321 '(invisible nil))
5322 (if (match-end 3)
5323 (progn
5324 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5325 (add-text-properties (match-beginning 3) (match-end 3) vp)
5326 (add-text-properties (match-end 3) (match-end 0) ip))
5327 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5328 (add-text-properties (match-beginning 1) (match-end 1) vp)
5329 (add-text-properties (match-end 1) (match-end 0) ip))
5330 t)))
5332 (defun org-activate-dates (limit)
5333 "Run through the buffer and add overlays to dates."
5334 (if (re-search-forward org-tsr-regexp-both limit t)
5335 (progn
5336 (add-text-properties (match-beginning 0) (match-end 0)
5337 (list 'mouse-face 'highlight
5338 'rear-nonsticky org-nonsticky-props
5339 'keymap org-mouse-map))
5340 (when org-display-custom-times
5341 (if (match-end 3)
5342 (org-display-custom-time (match-beginning 3) (match-end 3)))
5343 (org-display-custom-time (match-beginning 1) (match-end 1)))
5344 t)))
5346 (defvar org-target-link-regexp nil
5347 "Regular expression matching radio targets in plain text.")
5348 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5349 "Regular expression matching a link target.")
5350 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5351 "Regular expression matching a radio target.")
5352 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5353 "Regular expression matching any target.")
5355 (defun org-activate-target-links (limit)
5356 "Run through the buffer and add overlays to target matches."
5357 (when org-target-link-regexp
5358 (let ((case-fold-search t))
5359 (if (re-search-forward org-target-link-regexp limit t)
5360 (progn
5361 (add-text-properties (match-beginning 0) (match-end 0)
5362 (list 'mouse-face 'highlight
5363 'rear-nonsticky org-nonsticky-props
5364 'keymap org-mouse-map
5365 'help-echo "Radio target link"
5366 'org-linked-text t))
5367 t)))))
5369 (defun org-update-radio-target-regexp ()
5370 "Find all radio targets in this file and update the regular expression."
5371 (interactive)
5372 (when (memq 'radio org-activate-links)
5373 (setq org-target-link-regexp
5374 (org-make-target-link-regexp (org-all-targets 'radio)))
5375 (org-restart-font-lock)))
5377 (defun org-hide-wide-columns (limit)
5378 (let (s e)
5379 (setq s (text-property-any (point) (or limit (point-max))
5380 'org-cwidth t))
5381 (when s
5382 (setq e (next-single-property-change s 'org-cwidth))
5383 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5384 (goto-char e)
5385 t)))
5387 (defvar org-latex-and-specials-regexp nil
5388 "Regular expression for highlighting export special stuff.")
5389 (defvar org-match-substring-regexp)
5390 (defvar org-match-substring-with-braces-regexp)
5391 (defvar org-export-html-special-string-regexps)
5393 (defun org-compute-latex-and-specials-regexp ()
5394 "Compute regular expression for stuff treated specially by exporters."
5395 (if (not org-highlight-latex-fragments-and-specials)
5396 (org-set-local 'org-latex-and-specials-regexp nil)
5397 (let*
5398 ((matchers (plist-get org-format-latex-options :matchers))
5399 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5400 org-latex-regexps)))
5401 (options (org-combine-plists (org-default-export-plist)
5402 (org-infile-export-plist)))
5403 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5404 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5405 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5406 (org-export-html-expand (plist-get options :expand-quoted-html))
5407 (org-export-with-special-strings (plist-get options :special-strings))
5408 (re-sub
5409 (cond
5410 ((equal org-export-with-sub-superscripts '{})
5411 (list org-match-substring-with-braces-regexp))
5412 (org-export-with-sub-superscripts
5413 (list org-match-substring-regexp))
5414 (t nil)))
5415 (re-latex
5416 (if org-export-with-LaTeX-fragments
5417 (mapcar (lambda (x) (nth 1 x)) latexs)))
5418 (re-macros
5419 (if org-export-with-TeX-macros
5420 (list (concat "\\\\"
5421 (regexp-opt
5422 (append (mapcar 'car org-html-entities)
5423 (if (boundp 'org-latex-entities)
5424 org-latex-entities nil))
5425 'words))) ; FIXME
5427 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5428 (re-special (if org-export-with-special-strings
5429 (mapcar (lambda (x) (car x))
5430 org-export-html-special-string-regexps)))
5431 (re-rest
5432 (delq nil
5433 (list
5434 (if org-export-html-expand "@<[^>\n]+>")
5435 ))))
5436 (org-set-local
5437 'org-latex-and-specials-regexp
5438 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5439 re-rest) "\\|")))))
5441 (defface org-latex-and-export-specials
5442 (let ((font (cond ((assq :inherit custom-face-attributes)
5443 '(:inherit underline))
5444 (t '(:underline t)))))
5445 `((((class grayscale) (background light))
5446 (:foreground "DimGray" ,@font))
5447 (((class grayscale) (background dark))
5448 (:foreground "LightGray" ,@font))
5449 (((class color) (background light))
5450 (:foreground "SaddleBrown"))
5451 (((class color) (background dark))
5452 (:foreground "burlywood"))
5453 (t (,@font))))
5454 "Face used to highlight math latex and other special exporter stuff."
5455 :group 'org-faces)
5457 (defun org-do-latex-and-special-faces (limit)
5458 "Run through the buffer and add overlays to links."
5459 (when org-latex-and-specials-regexp
5460 (let (rtn d)
5461 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5462 limit t))
5463 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5464 'face))
5465 '(org-code org-verbatim underline)))
5466 (progn
5467 (setq rtn t
5468 d (cond ((member (char-after (1+ (match-beginning 0)))
5469 '(?_ ?^)) 1)
5470 (t 0)))
5471 (font-lock-prepend-text-property
5472 (+ d (match-beginning 0)) (match-end 0)
5473 'face 'org-latex-and-export-specials)
5474 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5475 '(font-lock-multiline t)))))
5476 rtn)))
5478 (defun org-restart-font-lock ()
5479 "Restart font-lock-mode, to force refontification."
5480 (when (and (boundp 'font-lock-mode) font-lock-mode)
5481 (font-lock-mode -1)
5482 (font-lock-mode 1)))
5484 (defun org-all-targets (&optional radio)
5485 "Return a list of all targets in this file.
5486 With optional argument RADIO, only find radio targets."
5487 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5488 rtn)
5489 (save-excursion
5490 (goto-char (point-min))
5491 (while (re-search-forward re nil t)
5492 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5493 rtn)))
5495 (defun org-make-target-link-regexp (targets)
5496 "Make regular expression matching all strings in TARGETS.
5497 The regular expression finds the targets also if there is a line break
5498 between words."
5499 (and targets
5500 (concat
5501 "\\<\\("
5502 (mapconcat
5503 (lambda (x)
5504 (while (string-match " +" x)
5505 (setq x (replace-match "\\s-+" t t x)))
5507 targets
5508 "\\|")
5509 "\\)\\>")))
5511 (defun org-activate-tags (limit)
5512 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5513 (progn
5514 (add-text-properties (match-beginning 1) (match-end 1)
5515 (list 'mouse-face 'highlight
5516 'rear-nonsticky org-nonsticky-props
5517 'keymap org-mouse-map))
5518 t)))
5520 (defun org-outline-level ()
5521 (save-excursion
5522 (looking-at outline-regexp)
5523 (if (match-beginning 1)
5524 (+ (org-get-string-indentation (match-string 1)) 1000)
5525 (1- (- (match-end 0) (match-beginning 0))))))
5527 (defvar org-font-lock-keywords nil)
5529 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5530 "Regular expression matching a property line.")
5532 (defun org-set-font-lock-defaults ()
5533 (let* ((em org-fontify-emphasized-text)
5534 (lk org-activate-links)
5535 (org-font-lock-extra-keywords
5536 (list
5537 ;; Headlines
5538 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5539 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5540 ;; Table lines
5541 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5542 (1 'org-table t))
5543 ;; Table internals
5544 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5545 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5546 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5547 ;; Drawers
5548 (list org-drawer-regexp '(0 'org-special-keyword t))
5549 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5550 ;; Properties
5551 (list org-property-re
5552 '(1 'org-special-keyword t)
5553 '(3 'org-property-value t))
5554 (if org-format-transports-properties-p
5555 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5556 ;; Links
5557 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5558 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5559 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5560 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5561 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5562 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5563 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5564 '(org-hide-wide-columns (0 nil append))
5565 ;; TODO lines
5566 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5567 '(1 (org-get-todo-face 1) t))
5568 ;; DONE
5569 (if org-fontify-done-headline
5570 (list (concat "^[*]+ +\\<\\("
5571 (mapconcat 'regexp-quote org-done-keywords "\\|")
5572 "\\)\\(.*\\)")
5573 '(2 'org-headline-done t))
5574 nil)
5575 ;; Priorities
5576 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5577 ;; Special keywords
5578 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5579 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5580 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5581 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5582 ;; Emphasis
5583 (if em
5584 (if (featurep 'xemacs)
5585 '(org-do-emphasis-faces (0 nil append))
5586 '(org-do-emphasis-faces)))
5587 ;; Checkboxes
5588 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5589 2 'bold prepend)
5590 (if org-provide-checkbox-statistics
5591 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5592 (0 (org-get-checkbox-statistics-face) t)))
5593 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5594 '(1 'org-archived prepend))
5595 ;; Specials
5596 '(org-do-latex-and-special-faces)
5597 ;; Code
5598 '(org-activate-code (1 'org-code t))
5599 ;; COMMENT
5600 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5601 "\\|" org-quote-string "\\)\\>")
5602 '(1 'org-special-keyword t))
5603 '("^#.*" (0 'font-lock-comment-face t))
5605 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5606 ;; Now set the full font-lock-keywords
5607 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5608 (org-set-local 'font-lock-defaults
5609 '(org-font-lock-keywords t nil nil backward-paragraph))
5610 (kill-local-variable 'font-lock-keywords) nil))
5612 (defvar org-m nil)
5613 (defvar org-l nil)
5614 (defvar org-f nil)
5615 (defun org-get-level-face (n)
5616 "Get the right face for match N in font-lock matching of healdines."
5617 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5618 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5619 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5620 (cond
5621 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5622 ((eq n 2) org-f)
5623 (t (if org-level-color-stars-only nil org-f))))
5625 (defun org-get-todo-face (kwd)
5626 "Get the right face for a TODO keyword KWD.
5627 If KWD is a number, get the corresponding match group."
5628 (if (numberp kwd) (setq kwd (match-string kwd)))
5629 (or (cdr (assoc kwd org-todo-keyword-faces))
5630 (and (member kwd org-done-keywords) 'org-done)
5631 'org-todo))
5633 (defun org-unfontify-region (beg end &optional maybe_loudly)
5634 "Remove fontification and activation overlays from links."
5635 (font-lock-default-unfontify-region beg end)
5636 (let* ((buffer-undo-list t)
5637 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5638 (inhibit-modification-hooks t)
5639 deactivate-mark buffer-file-name buffer-file-truename)
5640 (remove-text-properties beg end
5641 '(mouse-face t keymap t org-linked-text t
5642 invisible t intangible t))))
5644 ;;;; Visibility cycling, including org-goto and indirect buffer
5646 ;;; Cycling
5648 (defvar org-cycle-global-status nil)
5649 (make-variable-buffer-local 'org-cycle-global-status)
5650 (defvar org-cycle-subtree-status nil)
5651 (make-variable-buffer-local 'org-cycle-subtree-status)
5653 ;;;###autoload
5654 (defun org-cycle (&optional arg)
5655 "Visibility cycling for Org-mode.
5657 - When this function is called with a prefix argument, rotate the entire
5658 buffer through 3 states (global cycling)
5659 1. OVERVIEW: Show only top-level headlines.
5660 2. CONTENTS: Show all headlines of all levels, but no body text.
5661 3. SHOW ALL: Show everything.
5663 - When point is at the beginning of a headline, rotate the subtree started
5664 by this line through 3 different states (local cycling)
5665 1. FOLDED: Only the main headline is shown.
5666 2. CHILDREN: The main headline and the direct children are shown.
5667 From this state, you can move to one of the children
5668 and zoom in further.
5669 3. SUBTREE: Show the entire subtree, including body text.
5671 - When there is a numeric prefix, go up to a heading with level ARG, do
5672 a `show-subtree' and return to the previous cursor position. If ARG
5673 is negative, go up that many levels.
5675 - When point is not at the beginning of a headline, execute
5676 `indent-relative', like TAB normally does. See the option
5677 `org-cycle-emulate-tab' for details.
5679 - Special case: if point is at the beginning of the buffer and there is
5680 no headline in line 1, this function will act as if called with prefix arg.
5681 But only if also the variable `org-cycle-global-at-bob' is t."
5682 (interactive "P")
5683 (let* ((outline-regexp
5684 (if (and (org-mode-p) org-cycle-include-plain-lists)
5685 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5686 outline-regexp))
5687 (bob-special (and org-cycle-global-at-bob (bobp)
5688 (not (looking-at outline-regexp))))
5689 (org-cycle-hook
5690 (if bob-special
5691 (delq 'org-optimize-window-after-visibility-change
5692 (copy-sequence org-cycle-hook))
5693 org-cycle-hook))
5694 (pos (point)))
5696 (if (or bob-special (equal arg '(4)))
5697 ;; special case: use global cycling
5698 (setq arg t))
5700 (cond
5702 ((org-at-table-p 'any)
5703 ;; Enter the table or move to the next field in the table
5704 (or (org-table-recognize-table.el)
5705 (progn
5706 (if arg (org-table-edit-field t)
5707 (org-table-justify-field-maybe)
5708 (call-interactively 'org-table-next-field)))))
5710 ((eq arg t) ;; Global cycling
5712 (cond
5713 ((and (eq last-command this-command)
5714 (eq org-cycle-global-status 'overview))
5715 ;; We just created the overview - now do table of contents
5716 ;; This can be slow in very large buffers, so indicate action
5717 (message "CONTENTS...")
5718 (org-content)
5719 (message "CONTENTS...done")
5720 (setq org-cycle-global-status 'contents)
5721 (run-hook-with-args 'org-cycle-hook 'contents))
5723 ((and (eq last-command this-command)
5724 (eq org-cycle-global-status 'contents))
5725 ;; We just showed the table of contents - now show everything
5726 (show-all)
5727 (message "SHOW ALL")
5728 (setq org-cycle-global-status 'all)
5729 (run-hook-with-args 'org-cycle-hook 'all))
5732 ;; Default action: go to overview
5733 (org-overview)
5734 (message "OVERVIEW")
5735 (setq org-cycle-global-status 'overview)
5736 (run-hook-with-args 'org-cycle-hook 'overview))))
5738 ((and org-drawers org-drawer-regexp
5739 (save-excursion
5740 (beginning-of-line 1)
5741 (looking-at org-drawer-regexp)))
5742 ;; Toggle block visibility
5743 (org-flag-drawer
5744 (not (get-char-property (match-end 0) 'invisible))))
5746 ((integerp arg)
5747 ;; Show-subtree, ARG levels up from here.
5748 (save-excursion
5749 (org-back-to-heading)
5750 (outline-up-heading (if (< arg 0) (- arg)
5751 (- (funcall outline-level) arg)))
5752 (org-show-subtree)))
5754 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5755 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5756 ;; At a heading: rotate between three different views
5757 (org-back-to-heading)
5758 (let ((goal-column 0) eoh eol eos)
5759 ;; First, some boundaries
5760 (save-excursion
5761 (org-back-to-heading)
5762 (save-excursion
5763 (beginning-of-line 2)
5764 (while (and (not (eobp)) ;; this is like `next-line'
5765 (get-char-property (1- (point)) 'invisible))
5766 (beginning-of-line 2)) (setq eol (point)))
5767 (outline-end-of-heading) (setq eoh (point))
5768 (org-end-of-subtree t)
5769 (unless (eobp)
5770 (skip-chars-forward " \t\n")
5771 (beginning-of-line 1) ; in case this is an item
5773 (setq eos (1- (point))))
5774 ;; Find out what to do next and set `this-command'
5775 (cond
5776 ((= eos eoh)
5777 ;; Nothing is hidden behind this heading
5778 (message "EMPTY ENTRY")
5779 (setq org-cycle-subtree-status nil)
5780 (save-excursion
5781 (goto-char eos)
5782 (outline-next-heading)
5783 (if (org-invisible-p) (org-flag-heading nil))))
5784 ((or (>= eol eos)
5785 (not (string-match "\\S-" (buffer-substring eol eos))))
5786 ;; Entire subtree is hidden in one line: open it
5787 (org-show-entry)
5788 (show-children)
5789 (message "CHILDREN")
5790 (save-excursion
5791 (goto-char eos)
5792 (outline-next-heading)
5793 (if (org-invisible-p) (org-flag-heading nil)))
5794 (setq org-cycle-subtree-status 'children)
5795 (run-hook-with-args 'org-cycle-hook 'children))
5796 ((and (eq last-command this-command)
5797 (eq org-cycle-subtree-status 'children))
5798 ;; We just showed the children, now show everything.
5799 (org-show-subtree)
5800 (message "SUBTREE")
5801 (setq org-cycle-subtree-status 'subtree)
5802 (run-hook-with-args 'org-cycle-hook 'subtree))
5804 ;; Default action: hide the subtree.
5805 (hide-subtree)
5806 (message "FOLDED")
5807 (setq org-cycle-subtree-status 'folded)
5808 (run-hook-with-args 'org-cycle-hook 'folded)))))
5810 ;; TAB emulation
5811 (buffer-read-only (org-back-to-heading))
5813 ((org-try-cdlatex-tab))
5815 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5816 (or (not (bolp))
5817 (not (looking-at outline-regexp))))
5818 (call-interactively (global-key-binding "\t")))
5820 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5821 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5822 (or (and (eq org-cycle-emulate-tab 'white)
5823 (= (match-end 0) (point-at-eol)))
5824 (and (eq org-cycle-emulate-tab 'whitestart)
5825 (>= (match-end 0) pos))))
5827 (eq org-cycle-emulate-tab t))
5828 ; (if (and (looking-at "[ \n\r\t]")
5829 ; (string-match "^[ \t]*$" (buffer-substring
5830 ; (point-at-bol) (point))))
5831 ; (progn
5832 ; (beginning-of-line 1)
5833 ; (and (looking-at "[ \t]+") (replace-match ""))))
5834 (call-interactively (global-key-binding "\t")))
5836 (t (save-excursion
5837 (org-back-to-heading)
5838 (org-cycle))))))
5840 ;;;###autoload
5841 (defun org-global-cycle (&optional arg)
5842 "Cycle the global visibility. For details see `org-cycle'."
5843 (interactive "P")
5844 (let ((org-cycle-include-plain-lists
5845 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5846 (if (integerp arg)
5847 (progn
5848 (show-all)
5849 (hide-sublevels arg)
5850 (setq org-cycle-global-status 'contents))
5851 (org-cycle '(4)))))
5853 (defun org-overview ()
5854 "Switch to overview mode, shoing only top-level headlines.
5855 Really, this shows all headlines with level equal or greater than the level
5856 of the first headline in the buffer. This is important, because if the
5857 first headline is not level one, then (hide-sublevels 1) gives confusing
5858 results."
5859 (interactive)
5860 (let ((level (save-excursion
5861 (goto-char (point-min))
5862 (if (re-search-forward (concat "^" outline-regexp) nil t)
5863 (progn
5864 (goto-char (match-beginning 0))
5865 (funcall outline-level))))))
5866 (and level (hide-sublevels level))))
5868 (defun org-content (&optional arg)
5869 "Show all headlines in the buffer, like a table of contents.
5870 With numerical argument N, show content up to level N."
5871 (interactive "P")
5872 (save-excursion
5873 ;; Visit all headings and show their offspring
5874 (and (integerp arg) (org-overview))
5875 (goto-char (point-max))
5876 (catch 'exit
5877 (while (and (progn (condition-case nil
5878 (outline-previous-visible-heading 1)
5879 (error (goto-char (point-min))))
5881 (looking-at outline-regexp))
5882 (if (integerp arg)
5883 (show-children (1- arg))
5884 (show-branches))
5885 (if (bobp) (throw 'exit nil))))))
5888 (defun org-optimize-window-after-visibility-change (state)
5889 "Adjust the window after a change in outline visibility.
5890 This function is the default value of the hook `org-cycle-hook'."
5891 (when (get-buffer-window (current-buffer))
5892 (cond
5893 ; ((eq state 'overview) (org-first-headline-recenter 1))
5894 ; ((eq state 'overview) (org-beginning-of-line))
5895 ((eq state 'content) nil)
5896 ((eq state 'all) nil)
5897 ((eq state 'folded) nil)
5898 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5899 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5901 (defun org-compact-display-after-subtree-move ()
5902 (let (beg end)
5903 (save-excursion
5904 (if (org-up-heading-safe)
5905 (progn
5906 (hide-subtree)
5907 (show-entry)
5908 (show-children)
5909 (org-cycle-show-empty-lines 'children)
5910 (org-cycle-hide-drawers 'children))
5911 (org-overview)))))
5913 (defun org-cycle-show-empty-lines (state)
5914 "Show empty lines above all visible headlines.
5915 The region to be covered depends on STATE when called through
5916 `org-cycle-hook'. Lisp program can use t for STATE to get the
5917 entire buffer covered. Note that an empty line is only shown if there
5918 are at least `org-cycle-separator-lines' empty lines before the headeline."
5919 (when (> org-cycle-separator-lines 0)
5920 (save-excursion
5921 (let* ((n org-cycle-separator-lines)
5922 (re (cond
5923 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5924 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5925 (t (let ((ns (number-to-string (- n 2))))
5926 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5927 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5928 beg end)
5929 (cond
5930 ((memq state '(overview contents t))
5931 (setq beg (point-min) end (point-max)))
5932 ((memq state '(children folded))
5933 (setq beg (point) end (progn (org-end-of-subtree t t)
5934 (beginning-of-line 2)
5935 (point)))))
5936 (when beg
5937 (goto-char beg)
5938 (while (re-search-forward re end t)
5939 (if (not (get-char-property (match-end 1) 'invisible))
5940 (outline-flag-region
5941 (match-beginning 1) (match-end 1) nil)))))))
5942 ;; Never hide empty lines at the end of the file.
5943 (save-excursion
5944 (goto-char (point-max))
5945 (outline-previous-heading)
5946 (outline-end-of-heading)
5947 (if (and (looking-at "[ \t\n]+")
5948 (= (match-end 0) (point-max)))
5949 (outline-flag-region (point) (match-end 0) nil))))
5951 (defun org-subtree-end-visible-p ()
5952 "Is the end of the current subtree visible?"
5953 (pos-visible-in-window-p
5954 (save-excursion (org-end-of-subtree t) (point))))
5956 (defun org-first-headline-recenter (&optional N)
5957 "Move cursor to the first headline and recenter the headline.
5958 Optional argument N means, put the headline into the Nth line of the window."
5959 (goto-char (point-min))
5960 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5961 (beginning-of-line)
5962 (recenter (prefix-numeric-value N))))
5964 ;;; Org-goto
5966 (defvar org-goto-window-configuration nil)
5967 (defvar org-goto-marker nil)
5968 (defvar org-goto-map
5969 (let ((map (make-sparse-keymap)))
5970 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5971 (while (setq cmd (pop cmds))
5972 (substitute-key-definition cmd cmd map global-map)))
5973 (suppress-keymap map)
5974 (org-defkey map "\C-m" 'org-goto-ret)
5975 (org-defkey map [(return)] 'org-goto-ret)
5976 (org-defkey map [(left)] 'org-goto-left)
5977 (org-defkey map [(right)] 'org-goto-right)
5978 (org-defkey map [(control ?g)] 'org-goto-quit)
5979 (org-defkey map "\C-i" 'org-cycle)
5980 (org-defkey map [(tab)] 'org-cycle)
5981 (org-defkey map [(down)] 'outline-next-visible-heading)
5982 (org-defkey map [(up)] 'outline-previous-visible-heading)
5983 (if org-goto-auto-isearch
5984 (if (fboundp 'define-key-after)
5985 (define-key-after map [t] 'org-goto-local-auto-isearch)
5986 nil)
5987 (org-defkey map "q" 'org-goto-quit)
5988 (org-defkey map "n" 'outline-next-visible-heading)
5989 (org-defkey map "p" 'outline-previous-visible-heading)
5990 (org-defkey map "f" 'outline-forward-same-level)
5991 (org-defkey map "b" 'outline-backward-same-level)
5992 (org-defkey map "u" 'outline-up-heading))
5993 (org-defkey map "/" 'org-occur)
5994 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5995 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5996 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5997 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5998 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5999 map))
6001 (defconst org-goto-help
6002 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6003 RET=jump to location [Q]uit and return to previous location
6004 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6006 (defvar org-goto-start-pos) ; dynamically scoped parameter
6008 (defun org-goto (&optional alternative-interface)
6009 "Look up a different location in the current file, keeping current visibility.
6011 When you want look-up or go to a different location in a document, the
6012 fastest way is often to fold the entire buffer and then dive into the tree.
6013 This method has the disadvantage, that the previous location will be folded,
6014 which may not be what you want.
6016 This command works around this by showing a copy of the current buffer
6017 in an indirect buffer, in overview mode. You can dive into the tree in
6018 that copy, use org-occur and incremental search to find a location.
6019 When pressing RET or `Q', the command returns to the original buffer in
6020 which the visibility is still unchanged. After RET is will also jump to
6021 the location selected in the indirect buffer and expose the
6022 the headline hierarchy above."
6023 (interactive "P")
6024 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6025 (org-refile-use-outline-path t)
6026 (interface
6027 (if (not alternative-interface)
6028 org-goto-interface
6029 (if (eq org-goto-interface 'outline)
6030 'outline-path-completion
6031 'outline)))
6032 (org-goto-start-pos (point))
6033 (selected-point
6034 (if (eq interface 'outline)
6035 (car (org-get-location (current-buffer) org-goto-help))
6036 (nth 3 (org-refile-get-location "Goto: ")))))
6037 (if selected-point
6038 (progn
6039 (org-mark-ring-push org-goto-start-pos)
6040 (goto-char selected-point)
6041 (if (or (org-invisible-p) (org-invisible-p2))
6042 (org-show-context 'org-goto)))
6043 (message "Quit"))))
6045 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6046 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6047 (defvar org-goto-local-auto-isearch-map) ; defined below
6049 (defun org-get-location (buf help)
6050 "Let the user select a location in the Org-mode buffer BUF.
6051 This function uses a recursive edit. It returns the selected position
6052 or nil."
6053 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6054 (isearch-hide-immediately nil)
6055 (isearch-search-fun-function
6056 (lambda () 'org-goto-local-search-forward-headings))
6057 (org-goto-selected-point org-goto-exit-command))
6058 (save-excursion
6059 (save-window-excursion
6060 (delete-other-windows)
6061 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6062 (switch-to-buffer
6063 (condition-case nil
6064 (make-indirect-buffer (current-buffer) "*org-goto*")
6065 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6066 (with-output-to-temp-buffer "*Help*"
6067 (princ help))
6068 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6069 (setq buffer-read-only nil)
6070 (let ((org-startup-truncated t)
6071 (org-startup-folded nil)
6072 (org-startup-align-all-tables nil))
6073 (org-mode)
6074 (org-overview))
6075 (setq buffer-read-only t)
6076 (if (and (boundp 'org-goto-start-pos)
6077 (integer-or-marker-p org-goto-start-pos))
6078 (let ((org-show-hierarchy-above t)
6079 (org-show-siblings t)
6080 (org-show-following-heading t))
6081 (goto-char org-goto-start-pos)
6082 (and (org-invisible-p) (org-show-context)))
6083 (goto-char (point-min)))
6084 (org-beginning-of-line)
6085 (message "Select location and press RET")
6086 (use-local-map org-goto-map)
6087 (recursive-edit)
6089 (kill-buffer "*org-goto*")
6090 (cons org-goto-selected-point org-goto-exit-command)))
6092 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6093 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6094 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6095 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6097 (defun org-goto-local-search-forward-headings (string bound noerror)
6098 "Search and make sure that anu matches are in headlines."
6099 (catch 'return
6100 (while (search-forward string bound noerror)
6101 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6102 (and (member :headline context)
6103 (not (member :tags context))))
6104 (throw 'return (point))))))
6106 (defun org-goto-local-auto-isearch ()
6107 "Start isearch."
6108 (interactive)
6109 (goto-char (point-min))
6110 (let ((keys (this-command-keys)))
6111 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6112 (isearch-mode t)
6113 (isearch-process-search-char (string-to-char keys)))))
6115 (defun org-goto-ret (&optional arg)
6116 "Finish `org-goto' by going to the new location."
6117 (interactive "P")
6118 (setq org-goto-selected-point (point)
6119 org-goto-exit-command 'return)
6120 (throw 'exit nil))
6122 (defun org-goto-left ()
6123 "Finish `org-goto' by going to the new location."
6124 (interactive)
6125 (if (org-on-heading-p)
6126 (progn
6127 (beginning-of-line 1)
6128 (setq org-goto-selected-point (point)
6129 org-goto-exit-command 'left)
6130 (throw 'exit nil))
6131 (error "Not on a heading")))
6133 (defun org-goto-right ()
6134 "Finish `org-goto' by going to the new location."
6135 (interactive)
6136 (if (org-on-heading-p)
6137 (progn
6138 (setq org-goto-selected-point (point)
6139 org-goto-exit-command 'right)
6140 (throw 'exit nil))
6141 (error "Not on a heading")))
6143 (defun org-goto-quit ()
6144 "Finish `org-goto' without cursor motion."
6145 (interactive)
6146 (setq org-goto-selected-point nil)
6147 (setq org-goto-exit-command 'quit)
6148 (throw 'exit nil))
6150 ;;; Indirect buffer display of subtrees
6152 (defvar org-indirect-dedicated-frame nil
6153 "This is the frame being used for indirect tree display.")
6154 (defvar org-last-indirect-buffer nil)
6156 (defun org-tree-to-indirect-buffer (&optional arg)
6157 "Create indirect buffer and narrow it to current subtree.
6158 With numerical prefix ARG, go up to this level and then take that tree.
6159 If ARG is negative, go up that many levels.
6160 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6161 indirect buffer previously made with this command, to avoid proliferation of
6162 indirect buffers. However, when you call the command with a `C-u' prefix, or
6163 when `org-indirect-buffer-display' is `new-frame', the last buffer
6164 is kept so that you can work with several indirect buffers at the same time.
6165 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6166 requests that a new frame be made for the new buffer, so that the dedicated
6167 frame is not changed."
6168 (interactive "P")
6169 (let ((cbuf (current-buffer))
6170 (cwin (selected-window))
6171 (pos (point))
6172 beg end level heading ibuf)
6173 (save-excursion
6174 (org-back-to-heading t)
6175 (when (numberp arg)
6176 (setq level (org-outline-level))
6177 (if (< arg 0) (setq arg (+ level arg)))
6178 (while (> (setq level (org-outline-level)) arg)
6179 (outline-up-heading 1 t)))
6180 (setq beg (point)
6181 heading (org-get-heading))
6182 (org-end-of-subtree t) (setq end (point)))
6183 (if (and (buffer-live-p org-last-indirect-buffer)
6184 (not (eq org-indirect-buffer-display 'new-frame))
6185 (not arg))
6186 (kill-buffer org-last-indirect-buffer))
6187 (setq ibuf (org-get-indirect-buffer cbuf)
6188 org-last-indirect-buffer ibuf)
6189 (cond
6190 ((or (eq org-indirect-buffer-display 'new-frame)
6191 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6192 (select-frame (make-frame))
6193 (delete-other-windows)
6194 (switch-to-buffer ibuf)
6195 (org-set-frame-title heading))
6196 ((eq org-indirect-buffer-display 'dedicated-frame)
6197 (raise-frame
6198 (select-frame (or (and org-indirect-dedicated-frame
6199 (frame-live-p org-indirect-dedicated-frame)
6200 org-indirect-dedicated-frame)
6201 (setq org-indirect-dedicated-frame (make-frame)))))
6202 (delete-other-windows)
6203 (switch-to-buffer ibuf)
6204 (org-set-frame-title (concat "Indirect: " heading)))
6205 ((eq org-indirect-buffer-display 'current-window)
6206 (switch-to-buffer ibuf))
6207 ((eq org-indirect-buffer-display 'other-window)
6208 (pop-to-buffer ibuf))
6209 (t (error "Invalid value.")))
6210 (if (featurep 'xemacs)
6211 (save-excursion (org-mode) (turn-on-font-lock)))
6212 (narrow-to-region beg end)
6213 (show-all)
6214 (goto-char pos)
6215 (and (window-live-p cwin) (select-window cwin))))
6217 (defun org-get-indirect-buffer (&optional buffer)
6218 (setq buffer (or buffer (current-buffer)))
6219 (let ((n 1) (base (buffer-name buffer)) bname)
6220 (while (buffer-live-p
6221 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6222 (setq n (1+ n)))
6223 (condition-case nil
6224 (make-indirect-buffer buffer bname 'clone)
6225 (error (make-indirect-buffer buffer bname)))))
6227 (defun org-set-frame-title (title)
6228 "Set the title of the current frame to the string TITLE."
6229 ;; FIXME: how to name a single frame in XEmacs???
6230 (unless (featurep 'xemacs)
6231 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6233 ;;;; Structure editing
6235 ;;; Inserting headlines
6237 (defun org-insert-heading (&optional force-heading)
6238 "Insert a new heading or item with same depth at point.
6239 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6240 If point is at the beginning of a headline, insert a sibling before the
6241 current headline. If point is not at the beginning, do not split the line,
6242 but create the new hedline after the current line."
6243 (interactive "P")
6244 (if (= (buffer-size) 0)
6245 (insert "\n* ")
6246 (when (or force-heading (not (org-insert-item)))
6247 (let* ((head (save-excursion
6248 (condition-case nil
6249 (progn
6250 (org-back-to-heading)
6251 (match-string 0))
6252 (error "*"))))
6253 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6254 pos)
6255 (cond
6256 ((and (org-on-heading-p) (bolp)
6257 (or (bobp)
6258 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6259 ;; insert before the current line
6260 (open-line (if blank 2 1)))
6261 ((and (bolp)
6262 (or (bobp)
6263 (save-excursion
6264 (backward-char 1) (not (org-invisible-p)))))
6265 ;; insert right here
6266 nil)
6268 ; ;; in the middle of the line
6269 ; (org-show-entry)
6270 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6271 ; (if (and
6272 ; (org-on-heading-p)
6273 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6274 ; ;; protect the tags
6275 ;; (let ((tags (match-string 2)) pos)
6276 ; (delete-region (match-beginning 1) (match-end 1))
6277 ; (setq pos (point-at-bol))
6278 ; (newline (if blank 2 1))
6279 ; (save-excursion
6280 ; (goto-char pos)
6281 ; (end-of-line 1)
6282 ; (insert " " tags)
6283 ; (org-set-tags nil 'align)))
6284 ; (newline (if blank 2 1)))
6285 ; (newline (if blank 2 1))))
6288 ;; in the middle of the line
6289 (org-show-entry)
6290 (let ((split
6291 (org-get-alist-option org-M-RET-may-split-line 'headline))
6292 tags pos)
6293 (if (org-on-heading-p)
6294 (progn
6295 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6296 (setq tags (and (match-end 2) (match-string 2)))
6297 (and (match-end 1)
6298 (delete-region (match-beginning 1) (match-end 1)))
6299 (setq pos (point-at-bol))
6300 (or split (end-of-line 1))
6301 (delete-horizontal-space)
6302 (newline (if blank 2 1))
6303 (when tags
6304 (save-excursion
6305 (goto-char pos)
6306 (end-of-line 1)
6307 (insert " " tags)
6308 (org-set-tags nil 'align))))
6309 (or split (end-of-line 1))
6310 (newline (if blank 2 1))))))
6311 (insert head) (just-one-space)
6312 (setq pos (point))
6313 (end-of-line 1)
6314 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6315 (run-hooks 'org-insert-heading-hook)))))
6317 (defun org-insert-heading-after-current ()
6318 "Insert a new heading with same level as current, after current subtree."
6319 (interactive)
6320 (org-back-to-heading)
6321 (org-insert-heading)
6322 (org-move-subtree-down)
6323 (end-of-line 1))
6325 (defun org-insert-todo-heading (arg)
6326 "Insert a new heading with the same level and TODO state as current heading.
6327 If the heading has no TODO state, or if the state is DONE, use the first
6328 state (TODO by default). Also with prefix arg, force first state."
6329 (interactive "P")
6330 (when (not (org-insert-item 'checkbox))
6331 (org-insert-heading)
6332 (save-excursion
6333 (org-back-to-heading)
6334 (outline-previous-heading)
6335 (looking-at org-todo-line-regexp))
6336 (if (or arg
6337 (not (match-beginning 2))
6338 (member (match-string 2) org-done-keywords))
6339 (insert (car org-todo-keywords-1) " ")
6340 (insert (match-string 2) " "))))
6342 (defun org-insert-subheading (arg)
6343 "Insert a new subheading and demote it.
6344 Works for outline headings and for plain lists alike."
6345 (interactive "P")
6346 (org-insert-heading arg)
6347 (cond
6348 ((org-on-heading-p) (org-do-demote))
6349 ((org-at-item-p) (org-indent-item 1))))
6351 (defun org-insert-todo-subheading (arg)
6352 "Insert a new subheading with TODO keyword or checkbox and demote it.
6353 Works for outline headings and for plain lists alike."
6354 (interactive "P")
6355 (org-insert-todo-heading arg)
6356 (cond
6357 ((org-on-heading-p) (org-do-demote))
6358 ((org-at-item-p) (org-indent-item 1))))
6360 ;;; Promotion and Demotion
6362 (defun org-promote-subtree ()
6363 "Promote the entire subtree.
6364 See also `org-promote'."
6365 (interactive)
6366 (save-excursion
6367 (org-map-tree 'org-promote))
6368 (org-fix-position-after-promote))
6370 (defun org-demote-subtree ()
6371 "Demote the entire subtree. See `org-demote'.
6372 See also `org-promote'."
6373 (interactive)
6374 (save-excursion
6375 (org-map-tree 'org-demote))
6376 (org-fix-position-after-promote))
6379 (defun org-do-promote ()
6380 "Promote the current heading higher up the tree.
6381 If the region is active in `transient-mark-mode', promote all headings
6382 in the region."
6383 (interactive)
6384 (save-excursion
6385 (if (org-region-active-p)
6386 (org-map-region 'org-promote (region-beginning) (region-end))
6387 (org-promote)))
6388 (org-fix-position-after-promote))
6390 (defun org-do-demote ()
6391 "Demote the current heading lower down the tree.
6392 If the region is active in `transient-mark-mode', demote all headings
6393 in the region."
6394 (interactive)
6395 (save-excursion
6396 (if (org-region-active-p)
6397 (org-map-region 'org-demote (region-beginning) (region-end))
6398 (org-demote)))
6399 (org-fix-position-after-promote))
6401 (defun org-fix-position-after-promote ()
6402 "Make sure that after pro/demotion cursor position is right."
6403 (let ((pos (point)))
6404 (when (save-excursion
6405 (beginning-of-line 1)
6406 (looking-at org-todo-line-regexp)
6407 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6408 (cond ((eobp) (insert " "))
6409 ((eolp) (insert " "))
6410 ((equal (char-after) ?\ ) (forward-char 1))))))
6412 (defun org-reduced-level (l)
6413 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6415 (defun org-get-legal-level (level &optional change)
6416 "Rectify a level change under the influence of `org-odd-levels-only'
6417 LEVEL is a current level, CHANGE is by how much the level should be
6418 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6419 even level numbers will become the next higher odd number."
6420 (if org-odd-levels-only
6421 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6422 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6423 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6424 (max 1 (+ level change))))
6426 (defun org-promote ()
6427 "Promote the current heading higher up the tree.
6428 If the region is active in `transient-mark-mode', promote all headings
6429 in the region."
6430 (org-back-to-heading t)
6431 (let* ((level (save-match-data (funcall outline-level)))
6432 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6433 (diff (abs (- level (length up-head) -1))))
6434 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6435 (replace-match up-head nil t)
6436 ;; Fixup tag positioning
6437 (and org-auto-align-tags (org-set-tags nil t))
6438 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6440 (defun org-demote ()
6441 "Demote the current heading lower down the tree.
6442 If the region is active in `transient-mark-mode', demote all headings
6443 in the region."
6444 (org-back-to-heading t)
6445 (let* ((level (save-match-data (funcall outline-level)))
6446 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6447 (diff (abs (- level (length down-head) -1))))
6448 (replace-match down-head nil t)
6449 ;; Fixup tag positioning
6450 (and org-auto-align-tags (org-set-tags nil t))
6451 (if org-adapt-indentation (org-fixup-indentation diff))))
6453 (defun org-map-tree (fun)
6454 "Call FUN for every heading underneath the current one."
6455 (org-back-to-heading)
6456 (let ((level (funcall outline-level)))
6457 (save-excursion
6458 (funcall fun)
6459 (while (and (progn
6460 (outline-next-heading)
6461 (> (funcall outline-level) level))
6462 (not (eobp)))
6463 (funcall fun)))))
6465 (defun org-map-region (fun beg end)
6466 "Call FUN for every heading between BEG and END."
6467 (let ((org-ignore-region t))
6468 (save-excursion
6469 (setq end (copy-marker end))
6470 (goto-char beg)
6471 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6472 (< (point) end))
6473 (funcall fun))
6474 (while (and (progn
6475 (outline-next-heading)
6476 (< (point) end))
6477 (not (eobp)))
6478 (funcall fun)))))
6480 (defun org-fixup-indentation (diff)
6481 "Change the indentation in the current entry by DIFF
6482 However, if any line in the current entry has no indentation, or if it
6483 would end up with no indentation after the change, nothing at all is done."
6484 (save-excursion
6485 (let ((end (save-excursion (outline-next-heading)
6486 (point-marker)))
6487 (prohibit (if (> diff 0)
6488 "^\\S-"
6489 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6490 col)
6491 (unless (save-excursion (end-of-line 1)
6492 (re-search-forward prohibit end t))
6493 (while (and (< (point) end)
6494 (re-search-forward "^[ \t]+" end t))
6495 (goto-char (match-end 0))
6496 (setq col (current-column))
6497 (if (< diff 0) (replace-match ""))
6498 (indent-to (+ diff col))))
6499 (move-marker end nil))))
6501 (defun org-convert-to-odd-levels ()
6502 "Convert an org-mode file with all levels allowed to one with odd levels.
6503 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6504 level 5 etc."
6505 (interactive)
6506 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6507 (let ((org-odd-levels-only nil) n)
6508 (save-excursion
6509 (goto-char (point-min))
6510 (while (re-search-forward "^\\*\\*+ " nil t)
6511 (setq n (- (length (match-string 0)) 2))
6512 (while (>= (setq n (1- n)) 0)
6513 (org-demote))
6514 (end-of-line 1))))))
6517 (defun org-convert-to-oddeven-levels ()
6518 "Convert an org-mode file with only odd levels to one with odd and even levels.
6519 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6520 section with an even level, conversion would destroy the structure of the file. An error
6521 is signaled in this case."
6522 (interactive)
6523 (goto-char (point-min))
6524 ;; First check if there are no even levels
6525 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6526 (org-show-context t)
6527 (error "Not all levels are odd in this file. Conversion not possible."))
6528 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6529 (let ((org-odd-levels-only nil) n)
6530 (save-excursion
6531 (goto-char (point-min))
6532 (while (re-search-forward "^\\*\\*+ " nil t)
6533 (setq n (/ (1- (length (match-string 0))) 2))
6534 (while (>= (setq n (1- n)) 0)
6535 (org-promote))
6536 (end-of-line 1))))))
6538 (defun org-tr-level (n)
6539 "Make N odd if required."
6540 (if org-odd-levels-only (1+ (/ n 2)) n))
6542 ;;; Vertical tree motion, cutting and pasting of subtrees
6544 (defun org-move-subtree-up (&optional arg)
6545 "Move the current subtree up past ARG headlines of the same level."
6546 (interactive "p")
6547 (org-move-subtree-down (- (prefix-numeric-value arg))))
6549 (defun org-move-subtree-down (&optional arg)
6550 "Move the current subtree down past ARG headlines of the same level."
6551 (interactive "p")
6552 (setq arg (prefix-numeric-value arg))
6553 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6554 'outline-get-last-sibling))
6555 (ins-point (make-marker))
6556 (cnt (abs arg))
6557 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6558 ;; Select the tree
6559 (org-back-to-heading)
6560 (setq beg0 (point))
6561 (save-excursion
6562 (setq ne-beg (org-back-over-empty-lines))
6563 (setq beg (point)))
6564 (save-match-data
6565 (save-excursion (outline-end-of-heading)
6566 (setq folded (org-invisible-p)))
6567 (outline-end-of-subtree))
6568 (outline-next-heading)
6569 (setq ne-end (org-back-over-empty-lines))
6570 (setq end (point))
6571 (goto-char beg0)
6572 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6573 ;; include less whitespace
6574 (save-excursion
6575 (goto-char beg)
6576 (forward-line (- ne-beg ne-end))
6577 (setq beg (point))))
6578 ;; Find insertion point, with error handling
6579 (while (> cnt 0)
6580 (or (and (funcall movfunc) (looking-at outline-regexp))
6581 (progn (goto-char beg0)
6582 (error "Cannot move past superior level or buffer limit")))
6583 (setq cnt (1- cnt)))
6584 (if (> arg 0)
6585 ;; Moving forward - still need to move over subtree
6586 (progn (org-end-of-subtree t t)
6587 (save-excursion
6588 (org-back-over-empty-lines)
6589 (or (bolp) (newline)))))
6590 (setq ne-ins (org-back-over-empty-lines))
6591 (move-marker ins-point (point))
6592 (setq txt (buffer-substring beg end))
6593 (delete-region beg end)
6594 (outline-flag-region (1- beg) beg nil)
6595 (outline-flag-region (1- (point)) (point) nil)
6596 (insert txt)
6597 (or (bolp) (insert "\n"))
6598 (setq ins-end (point))
6599 (goto-char ins-point)
6600 (org-skip-whitespace)
6601 (when (and (< arg 0)
6602 (org-first-sibling-p)
6603 (> ne-ins ne-beg))
6604 ;; Move whitespace back to beginning
6605 (save-excursion
6606 (goto-char ins-end)
6607 (let ((kill-whole-line t))
6608 (kill-line (- ne-ins ne-beg)) (point)))
6609 (insert (make-string (- ne-ins ne-beg) ?\n)))
6610 (move-marker ins-point nil)
6611 (org-compact-display-after-subtree-move)
6612 (unless folded
6613 (org-show-entry)
6614 (show-children)
6615 (org-cycle-hide-drawers 'children))))
6617 (defvar org-subtree-clip ""
6618 "Clipboard for cut and paste of subtrees.
6619 This is actually only a copy of the kill, because we use the normal kill
6620 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6622 (defvar org-subtree-clip-folded nil
6623 "Was the last copied subtree folded?
6624 This is used to fold the tree back after pasting.")
6626 (defun org-cut-subtree (&optional n)
6627 "Cut the current subtree into the clipboard.
6628 With prefix arg N, cut this many sequential subtrees.
6629 This is a short-hand for marking the subtree and then cutting it."
6630 (interactive "p")
6631 (org-copy-subtree n 'cut))
6633 (defun org-copy-subtree (&optional n cut)
6634 "Cut the current subtree into the clipboard.
6635 With prefix arg N, cut this many sequential subtrees.
6636 This is a short-hand for marking the subtree and then copying it.
6637 If CUT is non-nil, actually cut the subtree."
6638 (interactive "p")
6639 (let (beg end folded (beg0 (point)))
6640 (if (interactive-p)
6641 (org-back-to-heading nil) ; take what looks like a subtree
6642 (org-back-to-heading t)) ; take what is really there
6643 (org-back-over-empty-lines)
6644 (setq beg (point))
6645 (skip-chars-forward " \t\r\n")
6646 (save-match-data
6647 (save-excursion (outline-end-of-heading)
6648 (setq folded (org-invisible-p)))
6649 (condition-case nil
6650 (outline-forward-same-level (1- n))
6651 (error nil))
6652 (org-end-of-subtree t t))
6653 (org-back-over-empty-lines)
6654 (setq end (point))
6655 (goto-char beg0)
6656 (when (> end beg)
6657 (setq org-subtree-clip-folded folded)
6658 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6659 (setq org-subtree-clip (current-kill 0))
6660 (message "%s: Subtree(s) with %d characters"
6661 (if cut "Cut" "Copied")
6662 (length org-subtree-clip)))))
6664 (defun org-paste-subtree (&optional level tree)
6665 "Paste the clipboard as a subtree, with modification of headline level.
6666 The entire subtree is promoted or demoted in order to match a new headline
6667 level. By default, the new level is derived from the visible headings
6668 before and after the insertion point, and taken to be the inferior headline
6669 level of the two. So if the previous visible heading is level 3 and the
6670 next is level 4 (or vice versa), level 4 will be used for insertion.
6671 This makes sure that the subtree remains an independent subtree and does
6672 not swallow low level entries.
6674 You can also force a different level, either by using a numeric prefix
6675 argument, or by inserting the heading marker by hand. For example, if the
6676 cursor is after \"*****\", then the tree will be shifted to level 5.
6678 If you want to insert the tree as is, just use \\[yank].
6680 If optional TREE is given, use this text instead of the kill ring."
6681 (interactive "P")
6682 (unless (org-kill-is-subtree-p tree)
6683 (error "%s"
6684 (substitute-command-keys
6685 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6686 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6687 (^re (concat "^\\(" outline-regexp "\\)"))
6688 (re (concat "\\(" outline-regexp "\\)"))
6689 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6691 (old-level (if (string-match ^re txt)
6692 (- (match-end 0) (match-beginning 0) 1)
6693 -1))
6694 (force-level (cond (level (prefix-numeric-value level))
6695 ((string-match
6696 ^re_ (buffer-substring (point-at-bol) (point)))
6697 (- (match-end 1) (match-beginning 1)))
6698 (t nil)))
6699 (previous-level (save-excursion
6700 (condition-case nil
6701 (progn
6702 (outline-previous-visible-heading 1)
6703 (if (looking-at re)
6704 (- (match-end 0) (match-beginning 0) 1)
6706 (error 1))))
6707 (next-level (save-excursion
6708 (condition-case nil
6709 (progn
6710 (or (looking-at outline-regexp)
6711 (outline-next-visible-heading 1))
6712 (if (looking-at re)
6713 (- (match-end 0) (match-beginning 0) 1)
6715 (error 1))))
6716 (new-level (or force-level (max previous-level next-level)))
6717 (shift (if (or (= old-level -1)
6718 (= new-level -1)
6719 (= old-level new-level))
6721 (- new-level old-level)))
6722 (delta (if (> shift 0) -1 1))
6723 (func (if (> shift 0) 'org-demote 'org-promote))
6724 (org-odd-levels-only nil)
6725 beg end)
6726 ;; Remove the forced level indicator
6727 (if force-level
6728 (delete-region (point-at-bol) (point)))
6729 ;; Paste
6730 (beginning-of-line 1)
6731 (org-back-over-empty-lines) ;; FIXME: correct fix????
6732 (setq beg (point))
6733 (insert-before-markers txt) ;; FIXME: correct fix????
6734 (unless (string-match "\n\\'" txt) (insert "\n"))
6735 (setq end (point))
6736 (goto-char beg)
6737 (skip-chars-forward " \t\n\r")
6738 (setq beg (point))
6739 ;; Shift if necessary
6740 (unless (= shift 0)
6741 (save-restriction
6742 (narrow-to-region beg end)
6743 (while (not (= shift 0))
6744 (org-map-region func (point-min) (point-max))
6745 (setq shift (+ delta shift)))
6746 (goto-char (point-min))))
6747 (when (interactive-p)
6748 (message "Clipboard pasted as level %d subtree" new-level))
6749 (if (and kill-ring
6750 (eq org-subtree-clip (current-kill 0))
6751 org-subtree-clip-folded)
6752 ;; The tree was folded before it was killed/copied
6753 (hide-subtree))))
6755 (defun org-kill-is-subtree-p (&optional txt)
6756 "Check if the current kill is an outline subtree, or a set of trees.
6757 Returns nil if kill does not start with a headline, or if the first
6758 headline level is not the largest headline level in the tree.
6759 So this will actually accept several entries of equal levels as well,
6760 which is OK for `org-paste-subtree'.
6761 If optional TXT is given, check this string instead of the current kill."
6762 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6763 (start-level (and kill
6764 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6765 org-outline-regexp "\\)")
6766 kill)
6767 (- (match-end 2) (match-beginning 2) 1)))
6768 (re (concat "^" org-outline-regexp))
6769 (start (1+ (match-beginning 2))))
6770 (if (not start-level)
6771 (progn
6772 nil) ;; does not even start with a heading
6773 (catch 'exit
6774 (while (setq start (string-match re kill (1+ start)))
6775 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6776 (throw 'exit nil)))
6777 t))))
6779 (defun org-narrow-to-subtree ()
6780 "Narrow buffer to the current subtree."
6781 (interactive)
6782 (save-excursion
6783 (save-match-data
6784 (narrow-to-region
6785 (progn (org-back-to-heading) (point))
6786 (progn (org-end-of-subtree t t) (point))))))
6789 ;;; Outline Sorting
6791 (defun org-sort (with-case)
6792 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6793 Optional argument WITH-CASE means sort case-sensitively."
6794 (interactive "P")
6795 (if (org-at-table-p)
6796 (org-call-with-arg 'org-table-sort-lines with-case)
6797 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6799 (defvar org-priority-regexp) ; defined later in the file
6801 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6802 "Sort entries on a certain level of an outline tree.
6803 If there is an active region, the entries in the region are sorted.
6804 Else, if the cursor is before the first entry, sort the top-level items.
6805 Else, the children of the entry at point are sorted.
6807 Sorting can be alphabetically, numerically, and by date/time as given by
6808 the first time stamp in the entry. The command prompts for the sorting
6809 type unless it has been given to the function through the SORTING-TYPE
6810 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6811 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6812 called with point at the beginning of the record. It must return either
6813 a string or a number that should serve as the sorting key for that record.
6815 Comparing entries ignores case by default. However, with an optional argument
6816 WITH-CASE, the sorting considers case as well."
6817 (interactive "P")
6818 (let ((case-func (if with-case 'identity 'downcase))
6819 start beg end stars re re2
6820 txt what tmp plain-list-p)
6821 ;; Find beginning and end of region to sort
6822 (cond
6823 ((org-region-active-p)
6824 ;; we will sort the region
6825 (setq end (region-end)
6826 what "region")
6827 (goto-char (region-beginning))
6828 (if (not (org-on-heading-p)) (outline-next-heading))
6829 (setq start (point)))
6830 ((org-at-item-p)
6831 ;; we will sort this plain list
6832 (org-beginning-of-item-list) (setq start (point))
6833 (org-end-of-item-list) (setq end (point))
6834 (goto-char start)
6835 (setq plain-list-p t
6836 what "plain list"))
6837 ((or (org-on-heading-p)
6838 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6839 ;; we will sort the children of the current headline
6840 (org-back-to-heading)
6841 (setq start (point)
6842 end (progn (org-end-of-subtree t t)
6843 (org-back-over-empty-lines)
6844 (point))
6845 what "children")
6846 (goto-char start)
6847 (show-subtree)
6848 (outline-next-heading))
6850 ;; we will sort the top-level entries in this file
6851 (goto-char (point-min))
6852 (or (org-on-heading-p) (outline-next-heading))
6853 (setq start (point) end (point-max) what "top-level")
6854 (goto-char start)
6855 (show-all)))
6857 (setq beg (point))
6858 (if (>= beg end) (error "Nothing to sort"))
6860 (unless plain-list-p
6861 (looking-at "\\(\\*+\\)")
6862 (setq stars (match-string 1)
6863 re (concat "^" (regexp-quote stars) " +")
6864 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6865 txt (buffer-substring beg end))
6866 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6867 (if (and (not (equal stars "*")) (string-match re2 txt))
6868 (error "Region to sort contains a level above the first entry")))
6870 (unless sorting-type
6871 (message
6872 (if plain-list-p
6873 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6874 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6875 what)
6876 (setq sorting-type (read-char-exclusive))
6878 (and (= (downcase sorting-type) ?f)
6879 (setq getkey-func
6880 (completing-read "Sort using function: "
6881 obarray 'fboundp t nil nil))
6882 (setq getkey-func (intern getkey-func)))
6884 (and (= (downcase sorting-type) ?r)
6885 (setq property
6886 (completing-read "Property: "
6887 (mapcar 'list (org-buffer-property-keys t))
6888 nil t))))
6890 (message "Sorting entries...")
6892 (save-restriction
6893 (narrow-to-region start end)
6895 (let ((dcst (downcase sorting-type))
6896 (now (current-time)))
6897 (sort-subr
6898 (/= dcst sorting-type)
6899 ;; This function moves to the beginning character of the "record" to
6900 ;; be sorted.
6901 (if plain-list-p
6902 (lambda nil
6903 (if (org-at-item-p) t (goto-char (point-max))))
6904 (lambda nil
6905 (if (re-search-forward re nil t)
6906 (goto-char (match-beginning 0))
6907 (goto-char (point-max)))))
6908 ;; This function moves to the last character of the "record" being
6909 ;; sorted.
6910 (if plain-list-p
6911 'org-end-of-item
6912 (lambda nil
6913 (save-match-data
6914 (condition-case nil
6915 (outline-forward-same-level 1)
6916 (error
6917 (goto-char (point-max)))))))
6919 ;; This function returns the value that gets sorted against.
6920 (if plain-list-p
6921 (lambda nil
6922 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6923 (cond
6924 ((= dcst ?n)
6925 (string-to-number (buffer-substring (match-end 0)
6926 (point-at-eol))))
6927 ((= dcst ?a)
6928 (buffer-substring (match-end 0) (point-at-eol)))
6929 ((= dcst ?t)
6930 (if (re-search-forward org-ts-regexp
6931 (point-at-eol) t)
6932 (org-time-string-to-time (match-string 0))
6933 now))
6934 ((= dcst ?f)
6935 (if getkey-func
6936 (progn
6937 (setq tmp (funcall getkey-func))
6938 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6939 tmp)
6940 (error "Invalid key function `%s'" getkey-func)))
6941 (t (error "Invalid sorting type `%c'" sorting-type)))))
6942 (lambda nil
6943 (cond
6944 ((= dcst ?n)
6945 (if (looking-at outline-regexp)
6946 (string-to-number (buffer-substring (match-end 0)
6947 (point-at-eol)))
6948 nil))
6949 ((= dcst ?a)
6950 (funcall case-func (buffer-substring (point-at-bol)
6951 (point-at-eol))))
6952 ((= dcst ?t)
6953 (if (re-search-forward org-ts-regexp
6954 (save-excursion
6955 (forward-line 2)
6956 (point)) t)
6957 (org-time-string-to-time (match-string 0))
6958 now))
6959 ((= dcst ?p)
6960 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6961 (string-to-char (match-string 2))
6962 org-default-priority))
6963 ((= dcst ?r)
6964 (or (org-entry-get nil property) ""))
6965 ((= dcst ?f)
6966 (if getkey-func
6967 (progn
6968 (setq tmp (funcall getkey-func))
6969 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6970 tmp)
6971 (error "Invalid key function `%s'" getkey-func)))
6972 (t (error "Invalid sorting type `%c'" sorting-type)))))
6974 (cond
6975 ((= dcst ?a) 'string<)
6976 ((= dcst ?t) 'time-less-p)
6977 (t nil)))))
6978 (message "Sorting entries...done")))
6980 (defun org-do-sort (table what &optional with-case sorting-type)
6981 "Sort TABLE of WHAT according to SORTING-TYPE.
6982 The user will be prompted for the SORTING-TYPE if the call to this
6983 function does not specify it. WHAT is only for the prompt, to indicate
6984 what is being sorted. The sorting key will be extracted from
6985 the car of the elements of the table.
6986 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6987 (unless sorting-type
6988 (message
6989 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6990 what)
6991 (setq sorting-type (read-char-exclusive)))
6992 (let ((dcst (downcase sorting-type))
6993 extractfun comparefun)
6994 ;; Define the appropriate functions
6995 (cond
6996 ((= dcst ?n)
6997 (setq extractfun 'string-to-number
6998 comparefun (if (= dcst sorting-type) '< '>)))
6999 ((= dcst ?a)
7000 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7001 (lambda(x) (downcase (org-sort-remove-invisible x))))
7002 comparefun (if (= dcst sorting-type)
7003 'string<
7004 (lambda (a b) (and (not (string< a b))
7005 (not (string= a b)))))))
7006 ((= dcst ?t)
7007 (setq extractfun
7008 (lambda (x)
7009 (if (string-match org-ts-regexp x)
7010 (time-to-seconds
7011 (org-time-string-to-time (match-string 0 x)))
7013 comparefun (if (= dcst sorting-type) '< '>)))
7014 (t (error "Invalid sorting type `%c'" sorting-type)))
7016 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7017 table)
7018 (lambda (a b) (funcall comparefun (car a) (car b))))))
7020 ;;;; Plain list items, including checkboxes
7022 ;;; Plain list items
7024 (defun org-at-item-p ()
7025 "Is point in a line starting a hand-formatted item?"
7026 (let ((llt org-plain-list-ordered-item-terminator))
7027 (save-excursion
7028 (goto-char (point-at-bol))
7029 (looking-at
7030 (cond
7031 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7032 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7033 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7034 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7036 (defun org-in-item-p ()
7037 "It the cursor inside a plain list item.
7038 Does not have to be the first line."
7039 (save-excursion
7040 (condition-case nil
7041 (progn
7042 (org-beginning-of-item)
7043 (org-at-item-p)
7045 (error nil))))
7047 (defun org-insert-item (&optional checkbox)
7048 "Insert a new item at the current level.
7049 Return t when things worked, nil when we are not in an item."
7050 (when (save-excursion
7051 (condition-case nil
7052 (progn
7053 (org-beginning-of-item)
7054 (org-at-item-p)
7055 (if (org-invisible-p) (error "Invisible item"))
7057 (error nil)))
7058 (let* ((bul (match-string 0))
7059 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7060 (match-end 0)))
7061 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7062 pos)
7063 (cond
7064 ((and (org-at-item-p) (<= (point) eow))
7065 ;; before the bullet
7066 (beginning-of-line 1)
7067 (open-line (if blank 2 1)))
7068 ((<= (point) eow)
7069 (beginning-of-line 1))
7071 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7072 (end-of-line 1)
7073 (delete-horizontal-space))
7074 (newline (if blank 2 1))))
7075 (insert bul (if checkbox "[ ]" ""))
7076 (just-one-space)
7077 (setq pos (point))
7078 (end-of-line 1)
7079 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7080 (org-maybe-renumber-ordered-list)
7081 (and checkbox (org-update-checkbox-count-maybe))
7084 ;;; Checkboxes
7086 (defun org-at-item-checkbox-p ()
7087 "Is point at a line starting a plain-list item with a checklet?"
7088 (and (org-at-item-p)
7089 (save-excursion
7090 (goto-char (match-end 0))
7091 (skip-chars-forward " \t")
7092 (looking-at "\\[[- X]\\]"))))
7094 (defun org-toggle-checkbox (&optional arg)
7095 "Toggle the checkbox in the current line."
7096 (interactive "P")
7097 (catch 'exit
7098 (let (beg end status (firstnew 'unknown))
7099 (cond
7100 ((org-region-active-p)
7101 (setq beg (region-beginning) end (region-end)))
7102 ((org-on-heading-p)
7103 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7104 ((org-at-item-checkbox-p)
7105 (let ((pos (point)))
7106 (replace-match
7107 (cond (arg "[-]")
7108 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7109 (t "[ ]"))
7110 t t)
7111 (goto-char pos))
7112 (throw 'exit t))
7113 (t (error "Not at a checkbox or heading, and no active region")))
7114 (save-excursion
7115 (goto-char beg)
7116 (while (< (point) end)
7117 (when (org-at-item-checkbox-p)
7118 (setq status (equal (match-string 0) "[X]"))
7119 (when (eq firstnew 'unknown)
7120 (setq firstnew (not status)))
7121 (replace-match
7122 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7123 (beginning-of-line 2)))))
7124 (org-update-checkbox-count-maybe))
7126 (defun org-update-checkbox-count-maybe ()
7127 "Update checkbox statistics unless turned off by user."
7128 (when org-provide-checkbox-statistics
7129 (org-update-checkbox-count)))
7131 (defun org-update-checkbox-count (&optional all)
7132 "Update the checkbox statistics in the current section.
7133 This will find all statistic cookies like [57%] and [6/12] and update them
7134 with the current numbers. With optional prefix argument ALL, do this for
7135 the whole buffer."
7136 (interactive "P")
7137 (save-excursion
7138 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7139 (beg (condition-case nil
7140 (progn (outline-back-to-heading) (point))
7141 (error (point-min))))
7142 (end (move-marker (make-marker)
7143 (progn (outline-next-heading) (point))))
7144 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7145 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7146 (re-find (concat re "\\|" re-box))
7147 beg-cookie end-cookie is-percent c-on c-off lim
7148 eline curr-ind next-ind continue-from startsearch
7149 (cstat 0)
7151 (when all
7152 (goto-char (point-min))
7153 (outline-next-heading)
7154 (setq beg (point) end (point-max)))
7155 (goto-char end)
7156 ;; find each statistic cookie
7157 (while (re-search-backward re-find beg t)
7158 (setq beg-cookie (match-beginning 1)
7159 end-cookie (match-end 1)
7160 cstat (+ cstat (if end-cookie 1 0))
7161 startsearch (point-at-eol)
7162 continue-from (point-at-bol)
7163 is-percent (match-beginning 2)
7164 lim (cond
7165 ((org-on-heading-p) (outline-next-heading) (point))
7166 ((org-at-item-p) (org-end-of-item) (point))
7167 (t nil))
7168 c-on 0
7169 c-off 0)
7170 (when lim
7171 ;; find first checkbox for this cookie and gather
7172 ;; statistics from all that are at this indentation level
7173 (goto-char startsearch)
7174 (if (re-search-forward re-box lim t)
7175 (progn
7176 (org-beginning-of-item)
7177 (setq curr-ind (org-get-indentation))
7178 (setq next-ind curr-ind)
7179 (while (= curr-ind next-ind)
7180 (save-excursion (end-of-line) (setq eline (point)))
7181 (if (re-search-forward re-box eline t)
7182 (if (member (match-string 2) '("[ ]" "[-]"))
7183 (setq c-off (1+ c-off))
7184 (setq c-on (1+ c-on))
7187 (org-end-of-item)
7188 (setq next-ind (org-get-indentation))
7190 (goto-char continue-from)
7191 ;; update cookie
7192 (when end-cookie
7193 (delete-region beg-cookie end-cookie)
7194 (goto-char beg-cookie)
7195 (insert
7196 (if is-percent
7197 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7198 (format "[%d/%d]" c-on (+ c-on c-off)))))
7199 ;; update items checkbox if it has one
7200 (when (org-at-item-p)
7201 (org-beginning-of-item)
7202 (when (and (> (+ c-on c-off) 0)
7203 (re-search-forward re-box (point-at-eol) t))
7204 (setq beg-cookie (match-beginning 2)
7205 end-cookie (match-end 2))
7206 (delete-region beg-cookie end-cookie)
7207 (goto-char beg-cookie)
7208 (cond ((= c-off 0) (insert "[X]"))
7209 ((= c-on 0) (insert "[ ]"))
7210 (t (insert "[-]")))
7212 (goto-char continue-from))
7213 (when (interactive-p)
7214 (message "Checkbox satistics updated %s (%d places)"
7215 (if all "in entire file" "in current outline entry") cstat)))))
7217 (defun org-get-checkbox-statistics-face ()
7218 "Select the face for checkbox statistics.
7219 The face will be `org-done' when all relevant boxes are checked. Otherwise
7220 it will be `org-todo'."
7221 (if (match-end 1)
7222 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7223 (if (and (> (match-end 2) (match-beginning 2))
7224 (equal (match-string 2) (match-string 3)))
7225 'org-done
7226 'org-todo)))
7228 (defun org-get-indentation (&optional line)
7229 "Get the indentation of the current line, interpreting tabs.
7230 When LINE is given, assume it represents a line and compute its indentation."
7231 (if line
7232 (if (string-match "^ *" (org-remove-tabs line))
7233 (match-end 0))
7234 (save-excursion
7235 (beginning-of-line 1)
7236 (skip-chars-forward " \t")
7237 (current-column))))
7239 (defun org-remove-tabs (s &optional width)
7240 "Replace tabulators in S with spaces.
7241 Assumes that s is a single line, starting in column 0."
7242 (setq width (or width tab-width))
7243 (while (string-match "\t" s)
7244 (setq s (replace-match
7245 (make-string
7246 (- (* width (/ (+ (match-beginning 0) width) width))
7247 (match-beginning 0)) ?\ )
7248 t t s)))
7251 (defun org-fix-indentation (line ind)
7252 "Fix indentation in LINE.
7253 IND is a cons cell with target and minimum indentation.
7254 If the current indenation in LINE is smaller than the minimum,
7255 leave it alone. If it is larger than ind, set it to the target."
7256 (let* ((l (org-remove-tabs line))
7257 (i (org-get-indentation l))
7258 (i1 (car ind)) (i2 (cdr ind)))
7259 (if (>= i i2) (setq l (substring line i2)))
7260 (if (> i1 0)
7261 (concat (make-string i1 ?\ ) l)
7262 l)))
7264 (defcustom org-empty-line-terminates-plain-lists nil
7265 "Non-nil means, an empty line ends all plain list levels.
7266 When nil, empty lines are part of the preceeding item."
7267 :group 'org-plain-lists
7268 :type 'boolean)
7270 (defun org-beginning-of-item ()
7271 "Go to the beginning of the current hand-formatted item.
7272 If the cursor is not in an item, throw an error."
7273 (interactive)
7274 (let ((pos (point))
7275 (limit (save-excursion
7276 (condition-case nil
7277 (progn
7278 (org-back-to-heading)
7279 (beginning-of-line 2) (point))
7280 (error (point-min)))))
7281 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7282 ind ind1)
7283 (if (org-at-item-p)
7284 (beginning-of-line 1)
7285 (beginning-of-line 1)
7286 (skip-chars-forward " \t")
7287 (setq ind (current-column))
7288 (if (catch 'exit
7289 (while t
7290 (beginning-of-line 0)
7291 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7293 (if (looking-at "[ \t]*$")
7294 (setq ind1 ind-empty)
7295 (skip-chars-forward " \t")
7296 (setq ind1 (current-column)))
7297 (if (< ind1 ind)
7298 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7300 (goto-char pos)
7301 (error "Not in an item")))))
7303 (defun org-end-of-item ()
7304 "Go to the end of the current hand-formatted item.
7305 If the cursor is not in an item, throw an error."
7306 (interactive)
7307 (let* ((pos (point))
7308 ind1
7309 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7310 (limit (save-excursion (outline-next-heading) (point)))
7311 (ind (save-excursion
7312 (org-beginning-of-item)
7313 (skip-chars-forward " \t")
7314 (current-column)))
7315 (end (catch 'exit
7316 (while t
7317 (beginning-of-line 2)
7318 (if (eobp) (throw 'exit (point)))
7319 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7320 (if (looking-at "[ \t]*$")
7321 (setq ind1 ind-empty)
7322 (skip-chars-forward " \t")
7323 (setq ind1 (current-column)))
7324 (if (<= ind1 ind)
7325 (throw 'exit (point-at-bol)))))))
7326 (if end
7327 (goto-char end)
7328 (goto-char pos)
7329 (error "Not in an item"))))
7331 (defun org-next-item ()
7332 "Move to the beginning of the next item in the current plain list.
7333 Error if not at a plain list, or if this is the last item in the list."
7334 (interactive)
7335 (let (ind ind1 (pos (point)))
7336 (org-beginning-of-item)
7337 (setq ind (org-get-indentation))
7338 (org-end-of-item)
7339 (setq ind1 (org-get-indentation))
7340 (unless (and (org-at-item-p) (= ind ind1))
7341 (goto-char pos)
7342 (error "On last item"))))
7344 (defun org-previous-item ()
7345 "Move to the beginning of the previous item in the current plain list.
7346 Error if not at a plain list, or if this is the first item in the list."
7347 (interactive)
7348 (let (beg ind ind1 (pos (point)))
7349 (org-beginning-of-item)
7350 (setq beg (point))
7351 (setq ind (org-get-indentation))
7352 (goto-char beg)
7353 (catch 'exit
7354 (while t
7355 (beginning-of-line 0)
7356 (if (looking-at "[ \t]*$")
7358 (if (<= (setq ind1 (org-get-indentation)) ind)
7359 (throw 'exit t)))))
7360 (condition-case nil
7361 (if (or (not (org-at-item-p))
7362 (< ind1 (1- ind)))
7363 (error "")
7364 (org-beginning-of-item))
7365 (error (goto-char pos)
7366 (error "On first item")))))
7368 (defun org-first-list-item-p ()
7369 "Is this heading the item in a plain list?"
7370 (unless (org-at-item-p)
7371 (error "Not at a plain list item"))
7372 (org-beginning-of-item)
7373 (= (point) (save-excursion (org-beginning-of-item-list))))
7375 (defun org-move-item-down ()
7376 "Move the plain list item at point down, i.e. swap with following item.
7377 Subitems (items with larger indentation) are considered part of the item,
7378 so this really moves item trees."
7379 (interactive)
7380 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7381 (org-beginning-of-item)
7382 (setq beg0 (point))
7383 (save-excursion
7384 (setq ne-beg (org-back-over-empty-lines))
7385 (setq beg (point)))
7386 (goto-char beg0)
7387 (setq ind (org-get-indentation))
7388 (org-end-of-item)
7389 (setq end0 (point))
7390 (setq ind1 (org-get-indentation))
7391 (setq ne-end (org-back-over-empty-lines))
7392 (setq end (point))
7393 (goto-char beg0)
7394 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7395 ;; include less whitespace
7396 (save-excursion
7397 (goto-char beg)
7398 (forward-line (- ne-beg ne-end))
7399 (setq beg (point))))
7400 (goto-char end0)
7401 (if (and (org-at-item-p) (= ind ind1))
7402 (progn
7403 (org-end-of-item)
7404 (org-back-over-empty-lines)
7405 (setq txt (buffer-substring beg end))
7406 (save-excursion
7407 (delete-region beg end))
7408 (setq pos (point))
7409 (insert txt)
7410 (goto-char pos) (org-skip-whitespace)
7411 (org-maybe-renumber-ordered-list))
7412 (goto-char pos)
7413 (error "Cannot move this item further down"))))
7415 (defun org-move-item-up (arg)
7416 "Move the plain list item at point up, i.e. swap with previous item.
7417 Subitems (items with larger indentation) are considered part of the item,
7418 so this really moves item trees."
7419 (interactive "p")
7420 (let (beg beg0 end ind ind1 (pos (point)) txt
7421 ne-beg ne-ins ins-end)
7422 (org-beginning-of-item)
7423 (setq beg0 (point))
7424 (setq ind (org-get-indentation))
7425 (save-excursion
7426 (setq ne-beg (org-back-over-empty-lines))
7427 (setq beg (point)))
7428 (goto-char beg0)
7429 (org-end-of-item)
7430 (setq end (point))
7431 (goto-char beg0)
7432 (catch 'exit
7433 (while t
7434 (beginning-of-line 0)
7435 (if (looking-at "[ \t]*$")
7436 (if org-empty-line-terminates-plain-lists
7437 (progn
7438 (goto-char pos)
7439 (error "Cannot move this item further up"))
7440 nil)
7441 (if (<= (setq ind1 (org-get-indentation)) ind)
7442 (throw 'exit t)))))
7443 (condition-case nil
7444 (org-beginning-of-item)
7445 (error (goto-char beg)
7446 (error "Cannot move this item further up")))
7447 (setq ind1 (org-get-indentation))
7448 (if (and (org-at-item-p) (= ind ind1))
7449 (progn
7450 (setq ne-ins (org-back-over-empty-lines))
7451 (setq txt (buffer-substring beg end))
7452 (save-excursion
7453 (delete-region beg end))
7454 (setq pos (point))
7455 (insert txt)
7456 (setq ins-end (point))
7457 (goto-char pos) (org-skip-whitespace)
7459 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7460 ;; Move whitespace back to beginning
7461 (save-excursion
7462 (goto-char ins-end)
7463 (let ((kill-whole-line t))
7464 (kill-line (- ne-ins ne-beg)) (point)))
7465 (insert (make-string (- ne-ins ne-beg) ?\n)))
7467 (org-maybe-renumber-ordered-list))
7468 (goto-char pos)
7469 (error "Cannot move this item further up"))))
7471 (defun org-maybe-renumber-ordered-list ()
7472 "Renumber the ordered list at point if setup allows it.
7473 This tests the user option `org-auto-renumber-ordered-lists' before
7474 doing the renumbering."
7475 (interactive)
7476 (when (and org-auto-renumber-ordered-lists
7477 (org-at-item-p))
7478 (if (match-beginning 3)
7479 (org-renumber-ordered-list 1)
7480 (org-fix-bullet-type))))
7482 (defun org-maybe-renumber-ordered-list-safe ()
7483 (condition-case nil
7484 (save-excursion
7485 (org-maybe-renumber-ordered-list))
7486 (error nil)))
7488 (defun org-cycle-list-bullet (&optional which)
7489 "Cycle through the different itemize/enumerate bullets.
7490 This cycle the entire list level through the sequence:
7492 `-' -> `+' -> `*' -> `1.' -> `1)'
7494 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7495 0 meand `-', 1 means `+' etc."
7496 (interactive "P")
7497 (org-preserve-lc
7498 (org-beginning-of-item-list)
7499 (org-at-item-p)
7500 (beginning-of-line 1)
7501 (let ((current (match-string 0))
7502 (prevp (eq which 'previous))
7503 new)
7504 (setq new (cond
7505 ((and (numberp which)
7506 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7507 ((string-match "-" current) (if prevp "1)" "+"))
7508 ((string-match "\\+" current)
7509 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7510 ((string-match "\\*" current) (if prevp "+" "1."))
7511 ((string-match "\\." current) (if prevp "*" "1)"))
7512 ((string-match ")" current) (if prevp "1." "-"))
7513 (t (error "This should not happen"))))
7514 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7515 (org-fix-bullet-type)
7516 (org-maybe-renumber-ordered-list))))
7518 (defun org-get-string-indentation (s)
7519 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7520 (let ((n -1) (i 0) (w tab-width) c)
7521 (catch 'exit
7522 (while (< (setq n (1+ n)) (length s))
7523 (setq c (aref s n))
7524 (cond ((= c ?\ ) (setq i (1+ i)))
7525 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7526 (t (throw 'exit t)))))
7529 (defun org-renumber-ordered-list (arg)
7530 "Renumber an ordered plain list.
7531 Cursor needs to be in the first line of an item, the line that starts
7532 with something like \"1.\" or \"2)\"."
7533 (interactive "p")
7534 (unless (and (org-at-item-p)
7535 (match-beginning 3))
7536 (error "This is not an ordered list"))
7537 (let ((line (org-current-line))
7538 (col (current-column))
7539 (ind (org-get-string-indentation
7540 (buffer-substring (point-at-bol) (match-beginning 3))))
7541 ;; (term (substring (match-string 3) -1))
7542 ind1 (n (1- arg))
7543 fmt)
7544 ;; find where this list begins
7545 (org-beginning-of-item-list)
7546 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7547 (setq fmt (concat "%d" (match-string 1)))
7548 (beginning-of-line 0)
7549 ;; walk forward and replace these numbers
7550 (catch 'exit
7551 (while t
7552 (catch 'next
7553 (beginning-of-line 2)
7554 (if (eobp) (throw 'exit nil))
7555 (if (looking-at "[ \t]*$") (throw 'next nil))
7556 (skip-chars-forward " \t") (setq ind1 (current-column))
7557 (if (> ind1 ind) (throw 'next t))
7558 (if (< ind1 ind) (throw 'exit t))
7559 (if (not (org-at-item-p)) (throw 'exit nil))
7560 (delete-region (match-beginning 2) (match-end 2))
7561 (goto-char (match-beginning 2))
7562 (insert (format fmt (setq n (1+ n)))))))
7563 (goto-line line)
7564 (move-to-column col)))
7566 (defun org-fix-bullet-type ()
7567 "Make sure all items in this list have the same bullet as the firsst item."
7568 (interactive)
7569 (unless (org-at-item-p) (error "This is not a list"))
7570 (let ((line (org-current-line))
7571 (col (current-column))
7572 (ind (current-indentation))
7573 ind1 bullet)
7574 ;; find where this list begins
7575 (org-beginning-of-item-list)
7576 (beginning-of-line 1)
7577 ;; find out what the bullet type is
7578 (looking-at "[ \t]*\\(\\S-+\\)")
7579 (setq bullet (match-string 1))
7580 ;; walk forward and replace these numbers
7581 (beginning-of-line 0)
7582 (catch 'exit
7583 (while t
7584 (catch 'next
7585 (beginning-of-line 2)
7586 (if (eobp) (throw 'exit nil))
7587 (if (looking-at "[ \t]*$") (throw 'next nil))
7588 (skip-chars-forward " \t") (setq ind1 (current-column))
7589 (if (> ind1 ind) (throw 'next t))
7590 (if (< ind1 ind) (throw 'exit t))
7591 (if (not (org-at-item-p)) (throw 'exit nil))
7592 (skip-chars-forward " \t")
7593 (looking-at "\\S-+")
7594 (replace-match bullet))))
7595 (goto-line line)
7596 (move-to-column col)
7597 (if (string-match "[0-9]" bullet)
7598 (org-renumber-ordered-list 1))))
7600 (defun org-beginning-of-item-list ()
7601 "Go to the beginning of the current item list.
7602 I.e. to the first item in this list."
7603 (interactive)
7604 (org-beginning-of-item)
7605 (let ((pos (point-at-bol))
7606 (ind (org-get-indentation))
7607 ind1)
7608 ;; find where this list begins
7609 (catch 'exit
7610 (while t
7611 (catch 'next
7612 (beginning-of-line 0)
7613 (if (looking-at "[ \t]*$")
7614 (throw (if (bobp) 'exit 'next) t))
7615 (skip-chars-forward " \t") (setq ind1 (current-column))
7616 (if (or (< ind1 ind)
7617 (and (= ind1 ind)
7618 (not (org-at-item-p)))
7619 (bobp))
7620 (throw 'exit t)
7621 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7622 (goto-char pos)))
7625 (defun org-end-of-item-list ()
7626 "Go to the end of the current item list.
7627 I.e. to the text after the last item."
7628 (interactive)
7629 (org-beginning-of-item)
7630 (let ((pos (point-at-bol))
7631 (ind (org-get-indentation))
7632 ind1)
7633 ;; find where this list begins
7634 (catch 'exit
7635 (while t
7636 (catch 'next
7637 (beginning-of-line 2)
7638 (if (looking-at "[ \t]*$")
7639 (throw (if (eobp) 'exit 'next) t))
7640 (skip-chars-forward " \t") (setq ind1 (current-column))
7641 (if (or (< ind1 ind)
7642 (and (= ind1 ind)
7643 (not (org-at-item-p)))
7644 (eobp))
7645 (progn
7646 (setq pos (point-at-bol))
7647 (throw 'exit t))))))
7648 (goto-char pos)))
7651 (defvar org-last-indent-begin-marker (make-marker))
7652 (defvar org-last-indent-end-marker (make-marker))
7654 (defun org-outdent-item (arg)
7655 "Outdent a local list item."
7656 (interactive "p")
7657 (org-indent-item (- arg)))
7659 (defun org-indent-item (arg)
7660 "Indent a local list item."
7661 (interactive "p")
7662 (unless (org-at-item-p)
7663 (error "Not on an item"))
7664 (save-excursion
7665 (let (beg end ind ind1 tmp delta ind-down ind-up)
7666 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7667 (setq beg org-last-indent-begin-marker
7668 end org-last-indent-end-marker)
7669 (org-beginning-of-item)
7670 (setq beg (move-marker org-last-indent-begin-marker (point)))
7671 (org-end-of-item)
7672 (setq end (move-marker org-last-indent-end-marker (point))))
7673 (goto-char beg)
7674 (setq tmp (org-item-indent-positions)
7675 ind (car tmp)
7676 ind-down (nth 2 tmp)
7677 ind-up (nth 1 tmp)
7678 delta (if (> arg 0)
7679 (if ind-down (- ind-down ind) 2)
7680 (if ind-up (- ind-up ind) -2)))
7681 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7682 (while (< (point) end)
7683 (beginning-of-line 1)
7684 (skip-chars-forward " \t") (setq ind1 (current-column))
7685 (delete-region (point-at-bol) (point))
7686 (or (eolp) (indent-to-column (+ ind1 delta)))
7687 (beginning-of-line 2))))
7688 (org-fix-bullet-type)
7689 (org-maybe-renumber-ordered-list-safe)
7690 (save-excursion
7691 (beginning-of-line 0)
7692 (condition-case nil (org-beginning-of-item) (error nil))
7693 (org-maybe-renumber-ordered-list-safe)))
7695 (defun org-item-indent-positions ()
7696 "Return indentation for plain list items.
7697 This returns a list with three values: The current indentation, the
7698 parent indentation and the indentation a child should habe.
7699 Assumes cursor in item line."
7700 (let* ((bolpos (point-at-bol))
7701 (ind (org-get-indentation))
7702 ind-down ind-up pos)
7703 (save-excursion
7704 (org-beginning-of-item-list)
7705 (skip-chars-backward "\n\r \t")
7706 (when (org-in-item-p)
7707 (org-beginning-of-item)
7708 (setq ind-up (org-get-indentation))))
7709 (setq pos (point))
7710 (save-excursion
7711 (cond
7712 ((and (condition-case nil (progn (org-previous-item) t)
7713 (error nil))
7714 (or (forward-char 1) t)
7715 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7716 (setq ind-down (org-get-indentation)))
7717 ((and (goto-char pos)
7718 (org-at-item-p))
7719 (goto-char (match-end 0))
7720 (skip-chars-forward " \t")
7721 (setq ind-down (current-column)))))
7722 (list ind ind-up ind-down)))
7724 ;;; The orgstruct minor mode
7726 ;; Define a minor mode which can be used in other modes in order to
7727 ;; integrate the org-mode structure editing commands.
7729 ;; This is really a hack, because the org-mode structure commands use
7730 ;; keys which normally belong to the major mode. Here is how it
7731 ;; works: The minor mode defines all the keys necessary to operate the
7732 ;; structure commands, but wraps the commands into a function which
7733 ;; tests if the cursor is currently at a headline or a plain list
7734 ;; item. If that is the case, the structure command is used,
7735 ;; temporarily setting many Org-mode variables like regular
7736 ;; expressions for filling etc. However, when any of those keys is
7737 ;; used at a different location, function uses `key-binding' to look
7738 ;; up if the key has an associated command in another currently active
7739 ;; keymap (minor modes, major mode, global), and executes that
7740 ;; command. There might be problems if any of the keys is otherwise
7741 ;; used as a prefix key.
7743 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7744 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7745 ;; addresses this by checking explicitly for both bindings.
7747 (defvar orgstruct-mode-map (make-sparse-keymap)
7748 "Keymap for the minor `orgstruct-mode'.")
7750 (defvar org-local-vars nil
7751 "List of local variables, for use by `orgstruct-mode'")
7753 ;;;###autoload
7754 (define-minor-mode orgstruct-mode
7755 "Toggle the minor more `orgstruct-mode'.
7756 This mode is for using Org-mode structure commands in other modes.
7757 The following key behave as if Org-mode was active, if the cursor
7758 is on a headline, or on a plain list item (both in the definition
7759 of Org-mode).
7761 M-up Move entry/item up
7762 M-down Move entry/item down
7763 M-left Promote
7764 M-right Demote
7765 M-S-up Move entry/item up
7766 M-S-down Move entry/item down
7767 M-S-left Promote subtree
7768 M-S-right Demote subtree
7769 M-q Fill paragraph and items like in Org-mode
7770 C-c ^ Sort entries
7771 C-c - Cycle list bullet
7772 TAB Cycle item visibility
7773 M-RET Insert new heading/item
7774 S-M-RET Insert new TODO heading / Chekbox item
7775 C-c C-c Set tags / toggle checkbox"
7776 nil " OrgStruct" nil
7777 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7779 ;;;###autoload
7780 (defun turn-on-orgstruct ()
7781 "Unconditionally turn on `orgstruct-mode'."
7782 (orgstruct-mode 1))
7784 ;;;###autoload
7785 (defun turn-on-orgstruct++ ()
7786 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7787 In addition to setting orgstruct-mode, this also exports all indentation and
7788 autofilling variables from org-mode into the buffer. Note that turning
7789 off orgstruct-mode will *not* remove these additional settings."
7790 (orgstruct-mode 1)
7791 (let (var val)
7792 (mapc
7793 (lambda (x)
7794 (when (string-match
7795 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7796 (symbol-name (car x)))
7797 (setq var (car x) val (nth 1 x))
7798 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7799 org-local-vars)))
7801 (defun orgstruct-error ()
7802 "Error when there is no default binding for a structure key."
7803 (interactive)
7804 (error "This key has no function outside structure elements"))
7806 (defun orgstruct-setup ()
7807 "Setup orgstruct keymaps."
7808 (let ((nfunc 0)
7809 (bindings
7810 (list
7811 '([(meta up)] org-metaup)
7812 '([(meta down)] org-metadown)
7813 '([(meta left)] org-metaleft)
7814 '([(meta right)] org-metaright)
7815 '([(meta shift up)] org-shiftmetaup)
7816 '([(meta shift down)] org-shiftmetadown)
7817 '([(meta shift left)] org-shiftmetaleft)
7818 '([(meta shift right)] org-shiftmetaright)
7819 '([(shift up)] org-shiftup)
7820 '([(shift down)] org-shiftdown)
7821 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7822 '("\M-q" fill-paragraph)
7823 '("\C-c^" org-sort)
7824 '("\C-c-" org-cycle-list-bullet)))
7825 elt key fun cmd)
7826 (while (setq elt (pop bindings))
7827 (setq nfunc (1+ nfunc))
7828 (setq key (org-key (car elt))
7829 fun (nth 1 elt)
7830 cmd (orgstruct-make-binding fun nfunc key))
7831 (org-defkey orgstruct-mode-map key cmd))
7833 ;; Special treatment needed for TAB and RET
7834 (org-defkey orgstruct-mode-map [(tab)]
7835 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7836 (org-defkey orgstruct-mode-map "\C-i"
7837 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7839 (org-defkey orgstruct-mode-map "\M-\C-m"
7840 (orgstruct-make-binding 'org-insert-heading 105
7841 "\M-\C-m" [(meta return)]))
7842 (org-defkey orgstruct-mode-map [(meta return)]
7843 (orgstruct-make-binding 'org-insert-heading 106
7844 [(meta return)] "\M-\C-m"))
7846 (org-defkey orgstruct-mode-map [(shift meta return)]
7847 (orgstruct-make-binding 'org-insert-todo-heading 107
7848 [(meta return)] "\M-\C-m"))
7850 (unless org-local-vars
7851 (setq org-local-vars (org-get-local-variables)))
7855 (defun orgstruct-make-binding (fun n &rest keys)
7856 "Create a function for binding in the structure minor mode.
7857 FUN is the command to call inside a table. N is used to create a unique
7858 command name. KEYS are keys that should be checked in for a command
7859 to execute outside of tables."
7860 (eval
7861 (list 'defun
7862 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7863 '(arg)
7864 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7865 "Outside of structure, run the binding of `"
7866 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7867 "'.")
7868 '(interactive "p")
7869 (list 'if
7870 '(org-context-p 'headline 'item)
7871 (list 'org-run-like-in-org-mode (list 'quote fun))
7872 (list 'let '(orgstruct-mode)
7873 (list 'call-interactively
7874 (append '(or)
7875 (mapcar (lambda (k)
7876 (list 'key-binding k))
7877 keys)
7878 '('orgstruct-error))))))))
7880 (defun org-context-p (&rest contexts)
7881 "Check if local context is and of CONTEXTS.
7882 Possible values in the list of contexts are `table', `headline', and `item'."
7883 (let ((pos (point)))
7884 (goto-char (point-at-bol))
7885 (prog1 (or (and (memq 'table contexts)
7886 (looking-at "[ \t]*|"))
7887 (and (memq 'headline contexts)
7888 (looking-at "\\*+"))
7889 (and (memq 'item contexts)
7890 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7891 (goto-char pos))))
7893 (defun org-get-local-variables ()
7894 "Return a list of all local variables in an org-mode buffer."
7895 (let (varlist)
7896 (with-current-buffer (get-buffer-create "*Org tmp*")
7897 (erase-buffer)
7898 (org-mode)
7899 (setq varlist (buffer-local-variables)))
7900 (kill-buffer "*Org tmp*")
7901 (delq nil
7902 (mapcar
7903 (lambda (x)
7904 (setq x
7905 (if (symbolp x)
7906 (list x)
7907 (list (car x) (list 'quote (cdr x)))))
7908 (if (string-match
7909 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7910 (symbol-name (car x)))
7911 x nil))
7912 varlist))))
7914 ;;;###autoload
7915 (defun org-run-like-in-org-mode (cmd)
7916 (unless org-local-vars
7917 (setq org-local-vars (org-get-local-variables)))
7918 (eval (list 'let org-local-vars
7919 (list 'call-interactively (list 'quote cmd)))))
7921 ;;;; Archiving
7923 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7925 (defun org-archive-subtree (&optional find-done)
7926 "Move the current subtree to the archive.
7927 The archive can be a certain top-level heading in the current file, or in
7928 a different file. The tree will be moved to that location, the subtree
7929 heading be marked DONE, and the current time will be added.
7931 When called with prefix argument FIND-DONE, find whole trees without any
7932 open TODO items and archive them (after getting confirmation from the user).
7933 If the cursor is not at a headline when this comand is called, try all level
7934 1 trees. If the cursor is on a headline, only try the direct children of
7935 this heading."
7936 (interactive "P")
7937 (if find-done
7938 (org-archive-all-done)
7939 ;; Save all relevant TODO keyword-relatex variables
7941 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7942 (tr-org-todo-keywords-1 org-todo-keywords-1)
7943 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7944 (tr-org-done-keywords org-done-keywords)
7945 (tr-org-todo-regexp org-todo-regexp)
7946 (tr-org-todo-line-regexp org-todo-line-regexp)
7947 (tr-org-odd-levels-only org-odd-levels-only)
7948 (this-buffer (current-buffer))
7949 (org-archive-location org-archive-location)
7950 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7951 ;; start of variables that will be used for saving context
7952 ;; The compiler complains about them - keep them anyway!
7953 (file (abbreviate-file-name (buffer-file-name)))
7954 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7955 (time (format-time-string
7956 (substring (cdr org-time-stamp-formats) 1 -1)
7957 (current-time)))
7958 afile heading buffer level newfile-p
7959 category todo priority
7960 ;; start of variables that will be used for savind context
7961 ltags itags prop)
7963 ;; Try to find a local archive location
7964 (save-excursion
7965 (save-restriction
7966 (widen)
7967 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7968 (if (and prop (string-match "\\S-" prop))
7969 (setq org-archive-location prop)
7970 (if (or (re-search-backward re nil t)
7971 (re-search-forward re nil t))
7972 (setq org-archive-location (match-string 1))))))
7974 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7975 (progn
7976 (setq afile (format (match-string 1 org-archive-location)
7977 (file-name-nondirectory buffer-file-name))
7978 heading (match-string 2 org-archive-location)))
7979 (error "Invalid `org-archive-location'"))
7980 (if (> (length afile) 0)
7981 (setq newfile-p (not (file-exists-p afile))
7982 buffer (find-file-noselect afile))
7983 (setq buffer (current-buffer)))
7984 (unless buffer
7985 (error "Cannot access file \"%s\"" afile))
7986 (if (and (> (length heading) 0)
7987 (string-match "^\\*+" heading))
7988 (setq level (match-end 0))
7989 (setq heading nil level 0))
7990 (save-excursion
7991 (org-back-to-heading t)
7992 ;; Get context information that will be lost by moving the tree
7993 (org-refresh-category-properties)
7994 (setq category (org-get-category)
7995 todo (and (looking-at org-todo-line-regexp)
7996 (match-string 2))
7997 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7998 ltags (org-get-tags)
7999 itags (org-delete-all ltags (org-get-tags-at)))
8000 (setq ltags (mapconcat 'identity ltags " ")
8001 itags (mapconcat 'identity itags " "))
8002 ;; We first only copy, in case something goes wrong
8003 ;; we need to protect this-command, to avoid kill-region sets it,
8004 ;; which would lead to duplication of subtrees
8005 (let (this-command) (org-copy-subtree))
8006 (set-buffer buffer)
8007 ;; Enforce org-mode for the archive buffer
8008 (if (not (org-mode-p))
8009 ;; Force the mode for future visits.
8010 (let ((org-insert-mode-line-in-empty-file t)
8011 (org-inhibit-startup t))
8012 (call-interactively 'org-mode)))
8013 (when newfile-p
8014 (goto-char (point-max))
8015 (insert (format "\nArchived entries from file %s\n\n"
8016 (buffer-file-name this-buffer))))
8017 ;; Force the TODO keywords of the original buffer
8018 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8019 (org-todo-keywords-1 tr-org-todo-keywords-1)
8020 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8021 (org-done-keywords tr-org-done-keywords)
8022 (org-todo-regexp tr-org-todo-regexp)
8023 (org-todo-line-regexp tr-org-todo-line-regexp)
8024 (org-odd-levels-only
8025 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8026 org-odd-levels-only
8027 tr-org-odd-levels-only)))
8028 (goto-char (point-min))
8029 (if heading
8030 (progn
8031 (if (re-search-forward
8032 (concat "^" (regexp-quote heading)
8033 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8034 nil t)
8035 (goto-char (match-end 0))
8036 ;; Heading not found, just insert it at the end
8037 (goto-char (point-max))
8038 (or (bolp) (insert "\n"))
8039 (insert "\n" heading "\n")
8040 (end-of-line 0))
8041 ;; Make the subtree visible
8042 (show-subtree)
8043 (org-end-of-subtree t)
8044 (skip-chars-backward " \t\r\n")
8045 (and (looking-at "[ \t\r\n]*")
8046 (replace-match "\n\n")))
8047 ;; No specific heading, just go to end of file.
8048 (goto-char (point-max)) (insert "\n"))
8049 ;; Paste
8050 (org-paste-subtree (org-get-legal-level level 1))
8052 ;; Mark the entry as done
8053 (when (and org-archive-mark-done
8054 (looking-at org-todo-line-regexp)
8055 (or (not (match-end 2))
8056 (not (member (match-string 2) org-done-keywords))))
8057 (let (org-log-done org-todo-log-states)
8058 (org-todo
8059 (car (or (member org-archive-mark-done org-done-keywords)
8060 org-done-keywords)))))
8062 ;; Add the context info
8063 (when org-archive-save-context-info
8064 (let ((l org-archive-save-context-info) e n v)
8065 (while (setq e (pop l))
8066 (when (and (setq v (symbol-value e))
8067 (stringp v) (string-match "\\S-" v))
8068 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8069 (org-entry-put (point) n v)))))
8071 ;; Save the buffer, if it is not the same buffer.
8072 (if (not (eq this-buffer buffer)) (save-buffer))))
8073 ;; Here we are back in the original buffer. Everything seems to have
8074 ;; worked. So now cut the tree and finish up.
8075 (let (this-command) (org-cut-subtree))
8076 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8077 (message "Subtree archived %s"
8078 (if (eq this-buffer buffer)
8079 (concat "under heading: " heading)
8080 (concat "in file: " (abbreviate-file-name afile)))))))
8082 (defun org-refresh-category-properties ()
8083 "Refresh category text properties in teh buffer."
8084 (let ((def-cat (cond
8085 ((null org-category)
8086 (if buffer-file-name
8087 (file-name-sans-extension
8088 (file-name-nondirectory buffer-file-name))
8089 "???"))
8090 ((symbolp org-category) (symbol-name org-category))
8091 (t org-category)))
8092 beg end cat pos optionp)
8093 (org-unmodified
8094 (save-excursion
8095 (save-restriction
8096 (widen)
8097 (goto-char (point-min))
8098 (put-text-property (point) (point-max) 'org-category def-cat)
8099 (while (re-search-forward
8100 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8101 (setq pos (match-end 0)
8102 optionp (equal (char-after (match-beginning 0)) ?#)
8103 cat (org-trim (match-string 2)))
8104 (if optionp
8105 (setq beg (point-at-bol) end (point-max))
8106 (org-back-to-heading t)
8107 (setq beg (point) end (org-end-of-subtree t t)))
8108 (put-text-property beg end 'org-category cat)
8109 (goto-char pos)))))))
8111 (defun org-archive-all-done (&optional tag)
8112 "Archive sublevels of the current tree without open TODO items.
8113 If the cursor is not on a headline, try all level 1 trees. If
8114 it is on a headline, try all direct children.
8115 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8116 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8117 (rea (concat ".*:" org-archive-tag ":"))
8118 (begm (make-marker))
8119 (endm (make-marker))
8120 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8121 "Move subtree to archive (no open TODO items)? "))
8122 beg end (cntarch 0))
8123 (if (org-on-heading-p)
8124 (progn
8125 (setq re1 (concat "^" (regexp-quote
8126 (make-string
8127 (1+ (- (match-end 0) (match-beginning 0) 1))
8128 ?*))
8129 " "))
8130 (move-marker begm (point))
8131 (move-marker endm (org-end-of-subtree t)))
8132 (setq re1 "^* ")
8133 (move-marker begm (point-min))
8134 (move-marker endm (point-max)))
8135 (save-excursion
8136 (goto-char begm)
8137 (while (re-search-forward re1 endm t)
8138 (setq beg (match-beginning 0)
8139 end (save-excursion (org-end-of-subtree t) (point)))
8140 (goto-char beg)
8141 (if (re-search-forward re end t)
8142 (goto-char end)
8143 (goto-char beg)
8144 (if (and (or (not tag) (not (looking-at rea)))
8145 (y-or-n-p question))
8146 (progn
8147 (if tag
8148 (org-toggle-tag org-archive-tag 'on)
8149 (org-archive-subtree))
8150 (setq cntarch (1+ cntarch)))
8151 (goto-char end)))))
8152 (message "%d trees archived" cntarch)))
8154 (defun org-cycle-hide-drawers (state)
8155 "Re-hide all drawers after a visibility state change."
8156 (when (and (org-mode-p)
8157 (not (memq state '(overview folded))))
8158 (save-excursion
8159 (let* ((globalp (memq state '(contents all)))
8160 (beg (if globalp (point-min) (point)))
8161 (end (if globalp (point-max) (org-end-of-subtree t))))
8162 (goto-char beg)
8163 (while (re-search-forward org-drawer-regexp end t)
8164 (org-flag-drawer t))))))
8166 (defun org-flag-drawer (flag)
8167 (save-excursion
8168 (beginning-of-line 1)
8169 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8170 (let ((b (match-end 0))
8171 (outline-regexp org-outline-regexp))
8172 (if (re-search-forward
8173 "^[ \t]*:END:"
8174 (save-excursion (outline-next-heading) (point)) t)
8175 (outline-flag-region b (point-at-eol) flag)
8176 (error ":END: line missing"))))))
8178 (defun org-cycle-hide-archived-subtrees (state)
8179 "Re-hide all archived subtrees after a visibility state change."
8180 (when (and (not org-cycle-open-archived-trees)
8181 (not (memq state '(overview folded))))
8182 (save-excursion
8183 (let* ((globalp (memq state '(contents all)))
8184 (beg (if globalp (point-min) (point)))
8185 (end (if globalp (point-max) (org-end-of-subtree t))))
8186 (org-hide-archived-subtrees beg end)
8187 (goto-char beg)
8188 (if (looking-at (concat ".*:" org-archive-tag ":"))
8189 (message "%s" (substitute-command-keys
8190 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8192 (defun org-force-cycle-archived ()
8193 "Cycle subtree even if it is archived."
8194 (interactive)
8195 (setq this-command 'org-cycle)
8196 (let ((org-cycle-open-archived-trees t))
8197 (call-interactively 'org-cycle)))
8199 (defun org-hide-archived-subtrees (beg end)
8200 "Re-hide all archived subtrees after a visibility state change."
8201 (save-excursion
8202 (let* ((re (concat ":" org-archive-tag ":")))
8203 (goto-char beg)
8204 (while (re-search-forward re end t)
8205 (and (org-on-heading-p) (hide-subtree))
8206 (org-end-of-subtree t)))))
8208 (defun org-toggle-tag (tag &optional onoff)
8209 "Toggle the tag TAG for the current line.
8210 If ONOFF is `on' or `off', don't toggle but set to this state."
8211 (unless (org-on-heading-p t) (error "Not on headling"))
8212 (let (res current)
8213 (save-excursion
8214 (beginning-of-line)
8215 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8216 (point-at-eol) t)
8217 (progn
8218 (setq current (match-string 1))
8219 (replace-match ""))
8220 (setq current ""))
8221 (setq current (nreverse (org-split-string current ":")))
8222 (cond
8223 ((eq onoff 'on)
8224 (setq res t)
8225 (or (member tag current) (push tag current)))
8226 ((eq onoff 'off)
8227 (or (not (member tag current)) (setq current (delete tag current))))
8228 (t (if (member tag current)
8229 (setq current (delete tag current))
8230 (setq res t)
8231 (push tag current))))
8232 (end-of-line 1)
8233 (if current
8234 (progn
8235 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8236 (org-set-tags nil t))
8237 (delete-horizontal-space))
8238 (run-hooks 'org-after-tags-change-hook))
8239 res))
8241 (defun org-toggle-archive-tag (&optional arg)
8242 "Toggle the archive tag for the current headline.
8243 With prefix ARG, check all children of current headline and offer tagging
8244 the children that do not contain any open TODO items."
8245 (interactive "P")
8246 (if arg
8247 (org-archive-all-done 'tag)
8248 (let (set)
8249 (save-excursion
8250 (org-back-to-heading t)
8251 (setq set (org-toggle-tag org-archive-tag))
8252 (when set (hide-subtree)))
8253 (and set (beginning-of-line 1))
8254 (message "Subtree %s" (if set "archived" "unarchived")))))
8257 ;;;; Tables
8259 ;;; The table editor
8261 ;; Watch out: Here we are talking about two different kind of tables.
8262 ;; Most of the code is for the tables created with the Org-mode table editor.
8263 ;; Sometimes, we talk about tables created and edited with the table.el
8264 ;; Emacs package. We call the former org-type tables, and the latter
8265 ;; table.el-type tables.
8267 (defun org-before-change-function (beg end)
8268 "Every change indicates that a table might need an update."
8269 (setq org-table-may-need-update t))
8271 (defconst org-table-line-regexp "^[ \t]*|"
8272 "Detects an org-type table line.")
8273 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8274 "Detects an org-type table line.")
8275 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8276 "Detects a table line marked for automatic recalculation.")
8277 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8278 "Detects a table line marked for automatic recalculation.")
8279 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8280 "Detects a table line marked for automatic recalculation.")
8281 (defconst org-table-hline-regexp "^[ \t]*|-"
8282 "Detects an org-type table hline.")
8283 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8284 "Detects a table-type table hline.")
8285 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8286 "Detects an org-type or table-type table.")
8287 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8288 "Searching from within a table (any type) this finds the first line
8289 outside the table.")
8290 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8291 "Searching from within a table (any type) this finds the first line
8292 outside the table.")
8294 (defvar org-table-last-highlighted-reference nil)
8295 (defvar org-table-formula-history nil)
8297 (defvar org-table-column-names nil
8298 "Alist with column names, derived from the `!' line.")
8299 (defvar org-table-column-name-regexp nil
8300 "Regular expression matching the current column names.")
8301 (defvar org-table-local-parameters nil
8302 "Alist with parameter names, derived from the `$' line.")
8303 (defvar org-table-named-field-locations nil
8304 "Alist with locations of named fields.")
8306 (defvar org-table-current-line-types nil
8307 "Table row types, non-nil only for the duration of a comand.")
8308 (defvar org-table-current-begin-line nil
8309 "Table begin line, non-nil only for the duration of a comand.")
8310 (defvar org-table-current-begin-pos nil
8311 "Table begin position, non-nil only for the duration of a comand.")
8312 (defvar org-table-dlines nil
8313 "Vector of data line line numbers in the current table.")
8314 (defvar org-table-hlines nil
8315 "Vector of hline line numbers in the current table.")
8317 (defconst org-table-range-regexp
8318 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8319 ;; 1 2 3 4 5
8320 "Regular expression for matching ranges in formulas.")
8322 (defconst org-table-range-regexp2
8323 (concat
8324 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8325 "\\.\\."
8326 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8327 "Match a range for reference display.")
8329 (defconst org-table-translate-regexp
8330 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8331 "Match a reference that needs translation, for reference display.")
8333 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8335 (defun org-table-create-with-table.el ()
8336 "Use the table.el package to insert a new table.
8337 If there is already a table at point, convert between Org-mode tables
8338 and table.el tables."
8339 (interactive)
8340 (require 'table)
8341 (cond
8342 ((org-at-table.el-p)
8343 (if (y-or-n-p "Convert table to Org-mode table? ")
8344 (org-table-convert)))
8345 ((org-at-table-p)
8346 (if (y-or-n-p "Convert table to table.el table? ")
8347 (org-table-convert)))
8348 (t (call-interactively 'table-insert))))
8350 (defun org-table-create-or-convert-from-region (arg)
8351 "Convert region to table, or create an empty table.
8352 If there is an active region, convert it to a table, using the function
8353 `org-table-convert-region'. See the documentation of that function
8354 to learn how the prefix argument is interpreted to determine the field
8355 separator.
8356 If there is no such region, create an empty table with `org-table-create'."
8357 (interactive "P")
8358 (if (org-region-active-p)
8359 (org-table-convert-region (region-beginning) (region-end) arg)
8360 (org-table-create arg)))
8362 (defun org-table-create (&optional size)
8363 "Query for a size and insert a table skeleton.
8364 SIZE is a string Columns x Rows like for example \"3x2\"."
8365 (interactive "P")
8366 (unless size
8367 (setq size (read-string
8368 (concat "Table size Columns x Rows [e.g. "
8369 org-table-default-size "]: ")
8370 "" nil org-table-default-size)))
8372 (let* ((pos (point))
8373 (indent (make-string (current-column) ?\ ))
8374 (split (org-split-string size " *x *"))
8375 (rows (string-to-number (nth 1 split)))
8376 (columns (string-to-number (car split)))
8377 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8378 "\n")))
8379 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8380 (point-at-bol) (point)))
8381 (beginning-of-line 1)
8382 (newline))
8383 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8384 (dotimes (i rows) (insert line))
8385 (goto-char pos)
8386 (if (> rows 1)
8387 ;; Insert a hline after the first row.
8388 (progn
8389 (end-of-line 1)
8390 (insert "\n|-")
8391 (goto-char pos)))
8392 (org-table-align)))
8394 (defun org-table-convert-region (beg0 end0 &optional separator)
8395 "Convert region to a table.
8396 The region goes from BEG0 to END0, but these borders will be moved
8397 slightly, to make sure a beginning of line in the first line is included.
8399 SEPARATOR specifies the field separator in the lines. It can have the
8400 following values:
8402 '(4) Use the comma as a field separator
8403 '(16) Use a TAB as field separator
8404 integer When a number, use that many spaces as field separator
8405 nil When nil, the command tries to be smart and figure out the
8406 separator in the following way:
8407 - when each line contains a TAB, assume TAB-separated material
8408 - when each line contains a comme, assume CSV material
8409 - else, assume one or more SPACE charcters as separator."
8410 (interactive "rP")
8411 (let* ((beg (min beg0 end0))
8412 (end (max beg0 end0))
8414 (goto-char beg)
8415 (beginning-of-line 1)
8416 (setq beg (move-marker (make-marker) (point)))
8417 (goto-char end)
8418 (if (bolp) (backward-char 1) (end-of-line 1))
8419 (setq end (move-marker (make-marker) (point)))
8420 ;; Get the right field separator
8421 (unless separator
8422 (goto-char beg)
8423 (setq separator
8424 (cond
8425 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8426 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8427 (t 1))))
8428 (setq re (cond
8429 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8430 ((equal separator '(16)) "^\\|\t")
8431 ((integerp separator)
8432 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8433 (t (error "This should not happen"))))
8434 (goto-char beg)
8435 (while (re-search-forward re end t)
8436 (replace-match "| " t t))
8437 (goto-char beg)
8438 (insert " ")
8439 (org-table-align)))
8441 (defun org-table-import (file arg)
8442 "Import FILE as a table.
8443 The file is assumed to be tab-separated. Such files can be produced by most
8444 spreadsheet and database applications. If no tabs (at least one per line)
8445 are found, lines will be split on whitespace into fields."
8446 (interactive "f\nP")
8447 (or (bolp) (newline))
8448 (let ((beg (point))
8449 (pm (point-max)))
8450 (insert-file-contents file)
8451 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8453 (defun org-table-export ()
8454 "Export table as a tab-separated file.
8455 Such a file can be imported into a spreadsheet program like Excel."
8456 (interactive)
8457 (let* ((beg (org-table-begin))
8458 (end (org-table-end))
8459 (table (buffer-substring beg end))
8460 (file (read-file-name "Export table to: "))
8461 buf)
8462 (unless (or (not (file-exists-p file))
8463 (y-or-n-p (format "Overwrite file %s? " file)))
8464 (error "Abort"))
8465 (with-current-buffer (find-file-noselect file)
8466 (setq buf (current-buffer))
8467 (erase-buffer)
8468 (fundamental-mode)
8469 (insert table)
8470 (goto-char (point-min))
8471 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8472 (replace-match "" t t)
8473 (end-of-line 1))
8474 (goto-char (point-min))
8475 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8476 (replace-match "" t t)
8477 (goto-char (min (1+ (point)) (point-max))))
8478 (goto-char (point-min))
8479 (while (re-search-forward "^-[-+]*$" nil t)
8480 (replace-match "")
8481 (if (looking-at "\n")
8482 (delete-char 1)))
8483 (goto-char (point-min))
8484 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8485 (replace-match "\t" t t))
8486 (save-buffer))
8487 (kill-buffer buf)))
8489 (defvar org-table-aligned-begin-marker (make-marker)
8490 "Marker at the beginning of the table last aligned.
8491 Used to check if cursor still is in that table, to minimize realignment.")
8492 (defvar org-table-aligned-end-marker (make-marker)
8493 "Marker at the end of the table last aligned.
8494 Used to check if cursor still is in that table, to minimize realignment.")
8495 (defvar org-table-last-alignment nil
8496 "List of flags for flushright alignment, from the last re-alignment.
8497 This is being used to correctly align a single field after TAB or RET.")
8498 (defvar org-table-last-column-widths nil
8499 "List of max width of fields in each column.
8500 This is being used to correctly align a single field after TAB or RET.")
8501 (defvar org-table-overlay-coordinates nil
8502 "Overlay coordinates after each align of a table.")
8503 (make-variable-buffer-local 'org-table-overlay-coordinates)
8505 (defvar org-last-recalc-line nil)
8506 (defconst org-narrow-column-arrow "=>"
8507 "Used as display property in narrowed table columns.")
8509 (defun org-table-align ()
8510 "Align the table at point by aligning all vertical bars."
8511 (interactive)
8512 (let* (
8513 ;; Limits of table
8514 (beg (org-table-begin))
8515 (end (org-table-end))
8516 ;; Current cursor position
8517 (linepos (org-current-line))
8518 (colpos (org-table-current-column))
8519 (winstart (window-start))
8520 (winstartline (org-current-line (min winstart (1- (point-max)))))
8521 lines (new "") lengths l typenums ty fields maxfields i
8522 column
8523 (indent "") cnt frac
8524 rfmt hfmt
8525 (spaces '(1 . 1))
8526 (sp1 (car spaces))
8527 (sp2 (cdr spaces))
8528 (rfmt1 (concat
8529 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8530 (hfmt1 (concat
8531 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8532 emptystrings links dates emph narrow fmax f1 len c e)
8533 (untabify beg end)
8534 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8535 ;; Check if we have links or dates
8536 (goto-char beg)
8537 (setq links (re-search-forward org-bracket-link-regexp end t))
8538 (goto-char beg)
8539 (setq emph (and org-hide-emphasis-markers
8540 (re-search-forward org-emph-re end t)))
8541 (goto-char beg)
8542 (setq dates (and org-display-custom-times
8543 (re-search-forward org-ts-regexp-both end t)))
8544 ;; Make sure the link properties are right
8545 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8546 ;; Make sure the date properties are right
8547 (when dates (goto-char beg) (while (org-activate-dates end)))
8548 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8550 ;; Check if we are narrowing any columns
8551 (goto-char beg)
8552 (setq narrow (and org-format-transports-properties-p
8553 (re-search-forward "<[0-9]+>" end t)))
8554 ;; Get the rows
8555 (setq lines (org-split-string
8556 (buffer-substring beg end) "\n"))
8557 ;; Store the indentation of the first line
8558 (if (string-match "^ *" (car lines))
8559 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8560 ;; Mark the hlines by setting the corresponding element to nil
8561 ;; At the same time, we remove trailing space.
8562 (setq lines (mapcar (lambda (l)
8563 (if (string-match "^ *|-" l)
8565 (if (string-match "[ \t]+$" l)
8566 (substring l 0 (match-beginning 0))
8567 l)))
8568 lines))
8569 ;; Get the data fields by splitting the lines.
8570 (setq fields (mapcar
8571 (lambda (l)
8572 (org-split-string l " *| *"))
8573 (delq nil (copy-sequence lines))))
8574 ;; How many fields in the longest line?
8575 (condition-case nil
8576 (setq maxfields (apply 'max (mapcar 'length fields)))
8577 (error
8578 (kill-region beg end)
8579 (org-table-create org-table-default-size)
8580 (error "Empty table - created default table")))
8581 ;; A list of empty strings to fill any short rows on output
8582 (setq emptystrings (make-list maxfields ""))
8583 ;; Check for special formatting.
8584 (setq i -1)
8585 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8586 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8587 ;; Check if there is an explicit width specified
8588 (when narrow
8589 (setq c column fmax nil)
8590 (while c
8591 (setq e (pop c))
8592 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8593 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8594 ;; Find fields that are wider than fmax, and shorten them
8595 (when fmax
8596 (loop for xx in column do
8597 (when (and (stringp xx)
8598 (> (org-string-width xx) fmax))
8599 (org-add-props xx nil
8600 'help-echo
8601 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8602 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8603 (unless (> f1 1)
8604 (error "Cannot narrow field starting with wide link \"%s\""
8605 (match-string 0 xx)))
8606 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8607 (add-text-properties (- f1 2) f1
8608 (list 'display org-narrow-column-arrow)
8609 xx)))))
8610 ;; Get the maximum width for each column
8611 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8612 ;; Get the fraction of numbers, to decide about alignment of the column
8613 (setq cnt 0 frac 0.0)
8614 (loop for x in column do
8615 (if (equal x "")
8617 (setq frac ( / (+ (* frac cnt)
8618 (if (string-match org-table-number-regexp x) 1 0))
8619 (setq cnt (1+ cnt))))))
8620 (push (>= frac org-table-number-fraction) typenums))
8621 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8623 ;; Store the alignment of this table, for later editing of single fields
8624 (setq org-table-last-alignment typenums
8625 org-table-last-column-widths lengths)
8627 ;; With invisible characters, `format' does not get the field width right
8628 ;; So we need to make these fields wide by hand.
8629 (when (or links emph)
8630 (loop for i from 0 upto (1- maxfields) do
8631 (setq len (nth i lengths))
8632 (loop for j from 0 upto (1- (length fields)) do
8633 (setq c (nthcdr i (car (nthcdr j fields))))
8634 (if (and (stringp (car c))
8635 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8636 ; (string-match org-bracket-link-regexp (car c))
8637 (< (org-string-width (car c)) len))
8638 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8640 ;; Compute the formats needed for output of the table
8641 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8642 (while (setq l (pop lengths))
8643 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8644 (setq rfmt (concat rfmt (format rfmt1 ty l))
8645 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8646 (setq rfmt (concat rfmt "\n")
8647 hfmt (concat (substring hfmt 0 -1) "|\n"))
8649 (setq new (mapconcat
8650 (lambda (l)
8651 (if l (apply 'format rfmt
8652 (append (pop fields) emptystrings))
8653 hfmt))
8654 lines ""))
8655 ;; Replace the old one
8656 (delete-region beg end)
8657 (move-marker end nil)
8658 (move-marker org-table-aligned-begin-marker (point))
8659 (insert new)
8660 (move-marker org-table-aligned-end-marker (point))
8661 (when (and orgtbl-mode (not (org-mode-p)))
8662 (goto-char org-table-aligned-begin-marker)
8663 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8664 ;; Try to move to the old location
8665 (goto-line winstartline)
8666 (setq winstart (point-at-bol))
8667 (goto-line linepos)
8668 (set-window-start (selected-window) winstart 'noforce)
8669 (org-table-goto-column colpos)
8670 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8671 (setq org-table-may-need-update nil)
8674 (defun org-string-width (s)
8675 "Compute width of string, ignoring invisible characters.
8676 This ignores character with invisibility property `org-link', and also
8677 characters with property `org-cwidth', because these will become invisible
8678 upon the next fontification round."
8679 (let (b l)
8680 (when (or (eq t buffer-invisibility-spec)
8681 (assq 'org-link buffer-invisibility-spec))
8682 (while (setq b (text-property-any 0 (length s)
8683 'invisible 'org-link s))
8684 (setq s (concat (substring s 0 b)
8685 (substring s (or (next-single-property-change
8686 b 'invisible s) (length s)))))))
8687 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8688 (setq s (concat (substring s 0 b)
8689 (substring s (or (next-single-property-change
8690 b 'org-cwidth s) (length s))))))
8691 (setq l (string-width s) b -1)
8692 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8693 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8696 (defun org-table-begin (&optional table-type)
8697 "Find the beginning of the table and return its position.
8698 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8699 (save-excursion
8700 (if (not (re-search-backward
8701 (if table-type org-table-any-border-regexp
8702 org-table-border-regexp)
8703 nil t))
8704 (progn (goto-char (point-min)) (point))
8705 (goto-char (match-beginning 0))
8706 (beginning-of-line 2)
8707 (point))))
8709 (defun org-table-end (&optional table-type)
8710 "Find the end of the table and return its position.
8711 With argument TABLE-TYPE, go to the end of a table.el-type table."
8712 (save-excursion
8713 (if (not (re-search-forward
8714 (if table-type org-table-any-border-regexp
8715 org-table-border-regexp)
8716 nil t))
8717 (goto-char (point-max))
8718 (goto-char (match-beginning 0)))
8719 (point-marker)))
8721 (defun org-table-justify-field-maybe (&optional new)
8722 "Justify the current field, text to left, number to right.
8723 Optional argument NEW may specify text to replace the current field content."
8724 (cond
8725 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8726 ((org-at-table-hline-p))
8727 ((and (not new)
8728 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8729 (current-buffer)))
8730 (< (point) org-table-aligned-begin-marker)
8731 (>= (point) org-table-aligned-end-marker)))
8732 ;; This is not the same table, force a full re-align
8733 (setq org-table-may-need-update t))
8734 (t ;; realign the current field, based on previous full realign
8735 (let* ((pos (point)) s
8736 (col (org-table-current-column))
8737 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8738 l f n o e)
8739 (when (> col 0)
8740 (skip-chars-backward "^|\n")
8741 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8742 (progn
8743 (setq s (match-string 1)
8744 o (match-string 0)
8745 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8746 e (not (= (match-beginning 2) (match-end 2))))
8747 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8748 l (if e "|" (setq org-table-may-need-update t) ""))
8749 n (format f s))
8750 (if new
8751 (if (<= (length new) l) ;; FIXME: length -> str-width?
8752 (setq n (format f new))
8753 (setq n (concat new "|") org-table-may-need-update t)))
8754 (or (equal n o)
8755 (let (org-table-may-need-update)
8756 (replace-match n t t))))
8757 (setq org-table-may-need-update t))
8758 (goto-char pos))))))
8760 (defun org-table-next-field ()
8761 "Go to the next field in the current table, creating new lines as needed.
8762 Before doing so, re-align the table if necessary."
8763 (interactive)
8764 (org-table-maybe-eval-formula)
8765 (org-table-maybe-recalculate-line)
8766 (if (and org-table-automatic-realign
8767 org-table-may-need-update)
8768 (org-table-align))
8769 (let ((end (org-table-end)))
8770 (if (org-at-table-hline-p)
8771 (end-of-line 1))
8772 (condition-case nil
8773 (progn
8774 (re-search-forward "|" end)
8775 (if (looking-at "[ \t]*$")
8776 (re-search-forward "|" end))
8777 (if (and (looking-at "-")
8778 org-table-tab-jumps-over-hlines
8779 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8780 (goto-char (match-beginning 1)))
8781 (if (looking-at "-")
8782 (progn
8783 (beginning-of-line 0)
8784 (org-table-insert-row 'below))
8785 (if (looking-at " ") (forward-char 1))))
8786 (error
8787 (org-table-insert-row 'below)))))
8789 (defun org-table-previous-field ()
8790 "Go to the previous field in the table.
8791 Before doing so, re-align the table if necessary."
8792 (interactive)
8793 (org-table-justify-field-maybe)
8794 (org-table-maybe-recalculate-line)
8795 (if (and org-table-automatic-realign
8796 org-table-may-need-update)
8797 (org-table-align))
8798 (if (org-at-table-hline-p)
8799 (end-of-line 1))
8800 (re-search-backward "|" (org-table-begin))
8801 (re-search-backward "|" (org-table-begin))
8802 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8803 (re-search-backward "|" (org-table-begin)))
8804 (if (looking-at "| ?")
8805 (goto-char (match-end 0))))
8807 (defun org-table-next-row ()
8808 "Go to the next row (same column) in the current table.
8809 Before doing so, re-align the table if necessary."
8810 (interactive)
8811 (org-table-maybe-eval-formula)
8812 (org-table-maybe-recalculate-line)
8813 (if (or (looking-at "[ \t]*$")
8814 (save-excursion (skip-chars-backward " \t") (bolp)))
8815 (newline)
8816 (if (and org-table-automatic-realign
8817 org-table-may-need-update)
8818 (org-table-align))
8819 (let ((col (org-table-current-column)))
8820 (beginning-of-line 2)
8821 (if (or (not (org-at-table-p))
8822 (org-at-table-hline-p))
8823 (progn
8824 (beginning-of-line 0)
8825 (org-table-insert-row 'below)))
8826 (org-table-goto-column col)
8827 (skip-chars-backward "^|\n\r")
8828 (if (looking-at " ") (forward-char 1)))))
8830 (defun org-table-copy-down (n)
8831 "Copy a field down in the current column.
8832 If the field at the cursor is empty, copy into it the content of the nearest
8833 non-empty field above. With argument N, use the Nth non-empty field.
8834 If the current field is not empty, it is copied down to the next row, and
8835 the cursor is moved with it. Therefore, repeating this command causes the
8836 column to be filled row-by-row.
8837 If the variable `org-table-copy-increment' is non-nil and the field is an
8838 integer or a timestamp, it will be incremented while copying. In the case of
8839 a timestamp, if the cursor is on the year, change the year. If it is on the
8840 month or the day, change that. Point will stay on the current date field
8841 in order to easily repeat the interval."
8842 (interactive "p")
8843 (let* ((colpos (org-table-current-column))
8844 (col (current-column))
8845 (field (org-table-get-field))
8846 (non-empty (string-match "[^ \t]" field))
8847 (beg (org-table-begin))
8848 txt)
8849 (org-table-check-inside-data-field)
8850 (if non-empty
8851 (progn
8852 (setq txt (org-trim field))
8853 (org-table-next-row)
8854 (org-table-blank-field))
8855 (save-excursion
8856 (setq txt
8857 (catch 'exit
8858 (while (progn (beginning-of-line 1)
8859 (re-search-backward org-table-dataline-regexp
8860 beg t))
8861 (org-table-goto-column colpos t)
8862 (if (and (looking-at
8863 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8864 (= (setq n (1- n)) 0))
8865 (throw 'exit (match-string 1))))))))
8866 (if txt
8867 (progn
8868 (if (and org-table-copy-increment
8869 (string-match "^[0-9]+$" txt))
8870 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8871 (insert txt)
8872 (move-to-column col)
8873 (if (and org-table-copy-increment (org-at-timestamp-p t))
8874 (org-timestamp-up 1)
8875 (org-table-maybe-recalculate-line))
8876 (org-table-align)
8877 (move-to-column col))
8878 (error "No non-empty field found"))))
8880 (defun org-table-check-inside-data-field ()
8881 "Is point inside a table data field?
8882 I.e. not on a hline or before the first or after the last column?
8883 This actually throws an error, so it aborts the current command."
8884 (if (or (not (org-at-table-p))
8885 (= (org-table-current-column) 0)
8886 (org-at-table-hline-p)
8887 (looking-at "[ \t]*$"))
8888 (error "Not in table data field")))
8890 (defvar org-table-clip nil
8891 "Clipboard for table regions.")
8893 (defun org-table-blank-field ()
8894 "Blank the current table field or active region."
8895 (interactive)
8896 (org-table-check-inside-data-field)
8897 (if (and (interactive-p) (org-region-active-p))
8898 (let (org-table-clip)
8899 (org-table-cut-region (region-beginning) (region-end)))
8900 (skip-chars-backward "^|")
8901 (backward-char 1)
8902 (if (looking-at "|[^|\n]+")
8903 (let* ((pos (match-beginning 0))
8904 (match (match-string 0))
8905 (len (org-string-width match)))
8906 (replace-match (concat "|" (make-string (1- len) ?\ )))
8907 (goto-char (+ 2 pos))
8908 (substring match 1)))))
8910 (defun org-table-get-field (&optional n replace)
8911 "Return the value of the field in column N of current row.
8912 N defaults to current field.
8913 If REPLACE is a string, replace field with this value. The return value
8914 is always the old value."
8915 (and n (org-table-goto-column n))
8916 (skip-chars-backward "^|\n")
8917 (backward-char 1)
8918 (if (looking-at "|[^|\r\n]*")
8919 (let* ((pos (match-beginning 0))
8920 (val (buffer-substring (1+ pos) (match-end 0))))
8921 (if replace
8922 (replace-match (concat "|" replace) t t))
8923 (goto-char (min (point-at-eol) (+ 2 pos)))
8924 val)
8925 (forward-char 1) ""))
8927 (defun org-table-field-info (arg)
8928 "Show info about the current field, and highlight any reference at point."
8929 (interactive "P")
8930 (org-table-get-specials)
8931 (save-excursion
8932 (let* ((pos (point))
8933 (col (org-table-current-column))
8934 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8935 (name (car (rassoc (list (org-current-line) col)
8936 org-table-named-field-locations)))
8937 (eql (org-table-get-stored-formulas))
8938 (dline (org-table-current-dline))
8939 (ref (format "@%d$%d" dline col))
8940 (ref1 (org-table-convert-refs-to-an ref))
8941 (fequation (or (assoc name eql) (assoc ref eql)))
8942 (cequation (assoc (int-to-string col) eql))
8943 (eqn (or fequation cequation)))
8944 (goto-char pos)
8945 (condition-case nil
8946 (org-table-show-reference 'local)
8947 (error nil))
8948 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8949 dline col
8950 (if cname (concat " or $" cname) "")
8951 dline col ref1
8952 (if name (concat " or $" name) "")
8953 ;; FIXME: formula info not correct if special table line
8954 (if eqn
8955 (concat ", formula: "
8956 (org-table-formula-to-user
8957 (concat
8958 (if (string-match "^[$@]"(car eqn)) "" "$")
8959 (car eqn) "=" (cdr eqn))))
8960 "")))))
8962 (defun org-table-current-column ()
8963 "Find out which column we are in.
8964 When called interactively, column is also displayed in echo area."
8965 (interactive)
8966 (if (interactive-p) (org-table-check-inside-data-field))
8967 (save-excursion
8968 (let ((cnt 0) (pos (point)))
8969 (beginning-of-line 1)
8970 (while (search-forward "|" pos t)
8971 (setq cnt (1+ cnt)))
8972 (if (interactive-p) (message "This is table column %d" cnt))
8973 cnt)))
8975 (defun org-table-current-dline ()
8976 "Find out what table data line we are in.
8977 Only datalins count for this."
8978 (interactive)
8979 (if (interactive-p) (org-table-check-inside-data-field))
8980 (save-excursion
8981 (let ((cnt 0) (pos (point)))
8982 (goto-char (org-table-begin))
8983 (while (<= (point) pos)
8984 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8985 (beginning-of-line 2))
8986 (if (interactive-p) (message "This is table line %d" cnt))
8987 cnt)))
8989 (defun org-table-goto-column (n &optional on-delim force)
8990 "Move the cursor to the Nth column in the current table line.
8991 With optional argument ON-DELIM, stop with point before the left delimiter
8992 of the field.
8993 If there are less than N fields, just go to after the last delimiter.
8994 However, when FORCE is non-nil, create new columns if necessary."
8995 (interactive "p")
8996 (let ((pos (point-at-eol)))
8997 (beginning-of-line 1)
8998 (when (> n 0)
8999 (while (and (> (setq n (1- n)) -1)
9000 (or (search-forward "|" pos t)
9001 (and force
9002 (progn (end-of-line 1)
9003 (skip-chars-backward "^|")
9004 (insert " | "))))))
9005 ; (backward-char 2) t)))))
9006 (when (and force (not (looking-at ".*|")))
9007 (save-excursion (end-of-line 1) (insert " | ")))
9008 (if on-delim
9009 (backward-char 1)
9010 (if (looking-at " ") (forward-char 1))))))
9012 (defun org-at-table-p (&optional table-type)
9013 "Return t if the cursor is inside an org-type table.
9014 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9015 (if org-enable-table-editor
9016 (save-excursion
9017 (beginning-of-line 1)
9018 (looking-at (if table-type org-table-any-line-regexp
9019 org-table-line-regexp)))
9020 nil))
9022 (defun org-at-table.el-p ()
9023 "Return t if and only if we are at a table.el table."
9024 (and (org-at-table-p 'any)
9025 (save-excursion
9026 (goto-char (org-table-begin 'any))
9027 (looking-at org-table1-hline-regexp))))
9029 (defun org-table-recognize-table.el ()
9030 "If there is a table.el table nearby, recognize it and move into it."
9031 (if org-table-tab-recognizes-table.el
9032 (if (org-at-table.el-p)
9033 (progn
9034 (beginning-of-line 1)
9035 (if (looking-at org-table-dataline-regexp)
9037 (if (looking-at org-table1-hline-regexp)
9038 (progn
9039 (beginning-of-line 2)
9040 (if (looking-at org-table-any-border-regexp)
9041 (beginning-of-line -1)))))
9042 (if (re-search-forward "|" (org-table-end t) t)
9043 (progn
9044 (require 'table)
9045 (if (table--at-cell-p (point))
9047 (message "recognizing table.el table...")
9048 (table-recognize-table)
9049 (message "recognizing table.el table...done")))
9050 (error "This should not happen..."))
9052 nil)
9053 nil))
9055 (defun org-at-table-hline-p ()
9056 "Return t if the cursor is inside a hline in a table."
9057 (if org-enable-table-editor
9058 (save-excursion
9059 (beginning-of-line 1)
9060 (looking-at org-table-hline-regexp))
9061 nil))
9063 (defun org-table-insert-column ()
9064 "Insert a new column into the table."
9065 (interactive)
9066 (if (not (org-at-table-p))
9067 (error "Not at a table"))
9068 (org-table-find-dataline)
9069 (let* ((col (max 1 (org-table-current-column)))
9070 (beg (org-table-begin))
9071 (end (org-table-end))
9072 ;; Current cursor position
9073 (linepos (org-current-line))
9074 (colpos col))
9075 (goto-char beg)
9076 (while (< (point) end)
9077 (if (org-at-table-hline-p)
9079 (org-table-goto-column col t)
9080 (insert "| "))
9081 (beginning-of-line 2))
9082 (move-marker end nil)
9083 (goto-line linepos)
9084 (org-table-goto-column colpos)
9085 (org-table-align)
9086 (org-table-fix-formulas "$" nil (1- col) 1)))
9088 (defun org-table-find-dataline ()
9089 "Find a dataline in the current table, which is needed for column commands."
9090 (if (and (org-at-table-p)
9091 (not (org-at-table-hline-p)))
9093 (let ((col (current-column))
9094 (end (org-table-end)))
9095 (move-to-column col)
9096 (while (and (< (point) end)
9097 (or (not (= (current-column) col))
9098 (org-at-table-hline-p)))
9099 (beginning-of-line 2)
9100 (move-to-column col))
9101 (if (and (org-at-table-p)
9102 (not (org-at-table-hline-p)))
9104 (error
9105 "Please position cursor in a data line for column operations")))))
9107 (defun org-table-delete-column ()
9108 "Delete a column from the table."
9109 (interactive)
9110 (if (not (org-at-table-p))
9111 (error "Not at a table"))
9112 (org-table-find-dataline)
9113 (org-table-check-inside-data-field)
9114 (let* ((col (org-table-current-column))
9115 (beg (org-table-begin))
9116 (end (org-table-end))
9117 ;; Current cursor position
9118 (linepos (org-current-line))
9119 (colpos col))
9120 (goto-char beg)
9121 (while (< (point) end)
9122 (if (org-at-table-hline-p)
9124 (org-table-goto-column col t)
9125 (and (looking-at "|[^|\n]+|")
9126 (replace-match "|")))
9127 (beginning-of-line 2))
9128 (move-marker end nil)
9129 (goto-line linepos)
9130 (org-table-goto-column colpos)
9131 (org-table-align)
9132 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9133 col -1 col)))
9135 (defun org-table-move-column-right ()
9136 "Move column to the right."
9137 (interactive)
9138 (org-table-move-column nil))
9139 (defun org-table-move-column-left ()
9140 "Move column to the left."
9141 (interactive)
9142 (org-table-move-column 'left))
9144 (defun org-table-move-column (&optional left)
9145 "Move the current column to the right. With arg LEFT, move to the left."
9146 (interactive "P")
9147 (if (not (org-at-table-p))
9148 (error "Not at a table"))
9149 (org-table-find-dataline)
9150 (org-table-check-inside-data-field)
9151 (let* ((col (org-table-current-column))
9152 (col1 (if left (1- col) col))
9153 (beg (org-table-begin))
9154 (end (org-table-end))
9155 ;; Current cursor position
9156 (linepos (org-current-line))
9157 (colpos (if left (1- col) (1+ col))))
9158 (if (and left (= col 1))
9159 (error "Cannot move column further left"))
9160 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9161 (error "Cannot move column further right"))
9162 (goto-char beg)
9163 (while (< (point) end)
9164 (if (org-at-table-hline-p)
9166 (org-table-goto-column col1 t)
9167 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9168 (replace-match "|\\2|\\1|")))
9169 (beginning-of-line 2))
9170 (move-marker end nil)
9171 (goto-line linepos)
9172 (org-table-goto-column colpos)
9173 (org-table-align)
9174 (org-table-fix-formulas
9175 "$" (list (cons (number-to-string col) (number-to-string colpos))
9176 (cons (number-to-string colpos) (number-to-string col))))))
9178 (defun org-table-move-row-down ()
9179 "Move table row down."
9180 (interactive)
9181 (org-table-move-row nil))
9182 (defun org-table-move-row-up ()
9183 "Move table row up."
9184 (interactive)
9185 (org-table-move-row 'up))
9187 (defun org-table-move-row (&optional up)
9188 "Move the current table line down. With arg UP, move it up."
9189 (interactive "P")
9190 (let* ((col (current-column))
9191 (pos (point))
9192 (hline1p (save-excursion (beginning-of-line 1)
9193 (looking-at org-table-hline-regexp)))
9194 (dline1 (org-table-current-dline))
9195 (dline2 (+ dline1 (if up -1 1)))
9196 (tonew (if up 0 2))
9197 txt hline2p)
9198 (beginning-of-line tonew)
9199 (unless (org-at-table-p)
9200 (goto-char pos)
9201 (error "Cannot move row further"))
9202 (setq hline2p (looking-at org-table-hline-regexp))
9203 (goto-char pos)
9204 (beginning-of-line 1)
9205 (setq pos (point))
9206 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9207 (delete-region (point) (1+ (point-at-eol)))
9208 (beginning-of-line tonew)
9209 (insert txt)
9210 (beginning-of-line 0)
9211 (move-to-column col)
9212 (unless (or hline1p hline2p)
9213 (org-table-fix-formulas
9214 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9215 (cons (number-to-string dline2) (number-to-string dline1)))))))
9217 (defun org-table-insert-row (&optional arg)
9218 "Insert a new row above the current line into the table.
9219 With prefix ARG, insert below the current line."
9220 (interactive "P")
9221 (if (not (org-at-table-p))
9222 (error "Not at a table"))
9223 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9224 (new (org-table-clean-line line)))
9225 ;; Fix the first field if necessary
9226 (if (string-match "^[ \t]*| *[#$] *|" line)
9227 (setq new (replace-match (match-string 0 line) t t new)))
9228 (beginning-of-line (if arg 2 1))
9229 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9230 (beginning-of-line 0)
9231 (re-search-forward "| ?" (point-at-eol) t)
9232 (and (or org-table-may-need-update org-table-overlay-coordinates)
9233 (org-table-align))
9234 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9236 (defun org-table-insert-hline (&optional above)
9237 "Insert a horizontal-line below the current line into the table.
9238 With prefix ABOVE, insert above the current line."
9239 (interactive "P")
9240 (if (not (org-at-table-p))
9241 (error "Not at a table"))
9242 (let ((line (org-table-clean-line
9243 (buffer-substring (point-at-bol) (point-at-eol))))
9244 (col (current-column)))
9245 (while (string-match "|\\( +\\)|" line)
9246 (setq line (replace-match
9247 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9248 ?-) "|") t t line)))
9249 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9250 (beginning-of-line (if above 1 2))
9251 (insert line "\n")
9252 (beginning-of-line (if above 1 -1))
9253 (move-to-column col)
9254 (and org-table-overlay-coordinates (org-table-align))))
9256 (defun org-table-hline-and-move (&optional same-column)
9257 "Insert a hline and move to the row below that line."
9258 (interactive "P")
9259 (let ((col (org-table-current-column)))
9260 (org-table-maybe-eval-formula)
9261 (org-table-maybe-recalculate-line)
9262 (org-table-insert-hline)
9263 (end-of-line 2)
9264 (if (looking-at "\n[ \t]*|-")
9265 (progn (insert "\n|") (org-table-align))
9266 (org-table-next-field))
9267 (if same-column (org-table-goto-column col))))
9269 (defun org-table-clean-line (s)
9270 "Convert a table line S into a string with only \"|\" and space.
9271 In particular, this does handle wide and invisible characters."
9272 (if (string-match "^[ \t]*|-" s)
9273 ;; It's a hline, just map the characters
9274 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9275 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9276 (setq s (replace-match
9277 (concat "|" (make-string (org-string-width (match-string 1 s))
9278 ?\ ) "|")
9279 t t s)))
9282 (defun org-table-kill-row ()
9283 "Delete the current row or horizontal line from the table."
9284 (interactive)
9285 (if (not (org-at-table-p))
9286 (error "Not at a table"))
9287 (let ((col (current-column))
9288 (dline (org-table-current-dline)))
9289 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9290 (if (not (org-at-table-p)) (beginning-of-line 0))
9291 (move-to-column col)
9292 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9293 dline -1 dline)))
9295 (defun org-table-sort-lines (with-case &optional sorting-type)
9296 "Sort table lines according to the column at point.
9298 The position of point indicates the column to be used for
9299 sorting, and the range of lines is the range between the nearest
9300 horizontal separator lines, or the entire table of no such lines
9301 exist. If point is before the first column, you will be prompted
9302 for the sorting column. If there is an active region, the mark
9303 specifies the first line and the sorting column, while point
9304 should be in the last line to be included into the sorting.
9306 The command then prompts for the sorting type which can be
9307 alphabetically, numerically, or by time (as given in a time stamp
9308 in the field). Sorting in reverse order is also possible.
9310 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9312 If SORTING-TYPE is specified when this function is called from a Lisp
9313 program, no prompting will take place. SORTING-TYPE must be a character,
9314 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9315 should be done in reverse order."
9316 (interactive "P")
9317 (let* ((thisline (org-current-line))
9318 (thiscol (org-table-current-column))
9319 beg end bcol ecol tend tbeg column lns pos)
9320 (when (equal thiscol 0)
9321 (if (interactive-p)
9322 (setq thiscol
9323 (string-to-number
9324 (read-string "Use column N for sorting: ")))
9325 (setq thiscol 1))
9326 (org-table-goto-column thiscol))
9327 (org-table-check-inside-data-field)
9328 (if (org-region-active-p)
9329 (progn
9330 (setq beg (region-beginning) end (region-end))
9331 (goto-char beg)
9332 (setq column (org-table-current-column)
9333 beg (point-at-bol))
9334 (goto-char end)
9335 (setq end (point-at-bol 2)))
9336 (setq column (org-table-current-column)
9337 pos (point)
9338 tbeg (org-table-begin)
9339 tend (org-table-end))
9340 (if (re-search-backward org-table-hline-regexp tbeg t)
9341 (setq beg (point-at-bol 2))
9342 (goto-char tbeg)
9343 (setq beg (point-at-bol 1)))
9344 (goto-char pos)
9345 (if (re-search-forward org-table-hline-regexp tend t)
9346 (setq end (point-at-bol 1))
9347 (goto-char tend)
9348 (setq end (point-at-bol))))
9349 (setq beg (move-marker (make-marker) beg)
9350 end (move-marker (make-marker) end))
9351 (untabify beg end)
9352 (goto-char beg)
9353 (org-table-goto-column column)
9354 (skip-chars-backward "^|")
9355 (setq bcol (current-column))
9356 (org-table-goto-column (1+ column))
9357 (skip-chars-backward "^|")
9358 (setq ecol (1- (current-column)))
9359 (org-table-goto-column column)
9360 (setq lns (mapcar (lambda(x) (cons
9361 (org-sort-remove-invisible
9362 (nth (1- column)
9363 (org-split-string x "[ \t]*|[ \t]*")))
9365 (org-split-string (buffer-substring beg end) "\n")))
9366 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9367 (delete-region beg end)
9368 (move-marker beg nil)
9369 (move-marker end nil)
9370 (insert (mapconcat 'cdr lns "\n") "\n")
9371 (goto-line thisline)
9372 (org-table-goto-column thiscol)
9373 (message "%d lines sorted, based on column %d" (length lns) column)))
9375 ;; FIXME: maybe we will not need this? Table sorting is broken....
9376 (defun org-sort-remove-invisible (s)
9377 (remove-text-properties 0 (length s) org-rm-props s)
9378 (while (string-match org-bracket-link-regexp s)
9379 (setq s (replace-match (if (match-end 2)
9380 (match-string 3 s)
9381 (match-string 1 s)) t t s)))
9384 (defun org-table-cut-region (beg end)
9385 "Copy region in table to the clipboard and blank all relevant fields."
9386 (interactive "r")
9387 (org-table-copy-region beg end 'cut))
9389 (defun org-table-copy-region (beg end &optional cut)
9390 "Copy rectangular region in table to clipboard.
9391 A special clipboard is used which can only be accessed
9392 with `org-table-paste-rectangle'."
9393 (interactive "rP")
9394 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9395 region cols
9396 (rpl (if cut " " nil)))
9397 (goto-char beg)
9398 (org-table-check-inside-data-field)
9399 (setq l01 (org-current-line)
9400 c01 (org-table-current-column))
9401 (goto-char end)
9402 (org-table-check-inside-data-field)
9403 (setq l02 (org-current-line)
9404 c02 (org-table-current-column))
9405 (setq l1 (min l01 l02) l2 (max l01 l02)
9406 c1 (min c01 c02) c2 (max c01 c02))
9407 (catch 'exit
9408 (while t
9409 (catch 'nextline
9410 (if (> l1 l2) (throw 'exit t))
9411 (goto-line l1)
9412 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9413 (setq cols nil ic1 c1 ic2 c2)
9414 (while (< ic1 (1+ ic2))
9415 (push (org-table-get-field ic1 rpl) cols)
9416 (setq ic1 (1+ ic1)))
9417 (push (nreverse cols) region)
9418 (setq l1 (1+ l1)))))
9419 (setq org-table-clip (nreverse region))
9420 (if cut (org-table-align))
9421 org-table-clip))
9423 (defun org-table-paste-rectangle ()
9424 "Paste a rectangular region into a table.
9425 The upper right corner ends up in the current field. All involved fields
9426 will be overwritten. If the rectangle does not fit into the present table,
9427 the table is enlarged as needed. The process ignores horizontal separator
9428 lines."
9429 (interactive)
9430 (unless (and org-table-clip (listp org-table-clip))
9431 (error "First cut/copy a region to paste!"))
9432 (org-table-check-inside-data-field)
9433 (let* ((clip org-table-clip)
9434 (line (org-current-line))
9435 (col (org-table-current-column))
9436 (org-enable-table-editor t)
9437 (org-table-automatic-realign nil)
9438 c cols field)
9439 (while (setq cols (pop clip))
9440 (while (org-at-table-hline-p) (beginning-of-line 2))
9441 (if (not (org-at-table-p))
9442 (progn (end-of-line 0) (org-table-next-field)))
9443 (setq c col)
9444 (while (setq field (pop cols))
9445 (org-table-goto-column c nil 'force)
9446 (org-table-get-field nil field)
9447 (setq c (1+ c)))
9448 (beginning-of-line 2))
9449 (goto-line line)
9450 (org-table-goto-column col)
9451 (org-table-align)))
9453 (defun org-table-convert ()
9454 "Convert from `org-mode' table to table.el and back.
9455 Obviously, this only works within limits. When an Org-mode table is
9456 converted to table.el, all horizontal separator lines get lost, because
9457 table.el uses these as cell boundaries and has no notion of horizontal lines.
9458 A table.el table can be converted to an Org-mode table only if it does not
9459 do row or column spanning. Multiline cells will become multiple cells.
9460 Beware, Org-mode does not test if the table can be successfully converted - it
9461 blindly applies a recipe that works for simple tables."
9462 (interactive)
9463 (require 'table)
9464 (if (org-at-table.el-p)
9465 ;; convert to Org-mode table
9466 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9467 (end (move-marker (make-marker) (org-table-end t))))
9468 (table-unrecognize-region beg end)
9469 (goto-char beg)
9470 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9471 (replace-match ""))
9472 (goto-char beg))
9473 (if (org-at-table-p)
9474 ;; convert to table.el table
9475 (let ((beg (move-marker (make-marker) (org-table-begin)))
9476 (end (move-marker (make-marker) (org-table-end))))
9477 ;; first, get rid of all horizontal lines
9478 (goto-char beg)
9479 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9480 (replace-match ""))
9481 ;; insert a hline before first
9482 (goto-char beg)
9483 (org-table-insert-hline 'above)
9484 (beginning-of-line -1)
9485 ;; insert a hline after each line
9486 (while (progn (beginning-of-line 3) (< (point) end))
9487 (org-table-insert-hline))
9488 (goto-char beg)
9489 (setq end (move-marker end (org-table-end)))
9490 ;; replace "+" at beginning and ending of hlines
9491 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9492 (replace-match "\\1+-"))
9493 (goto-char beg)
9494 (while (re-search-forward "-|[ \t]*$" end t)
9495 (replace-match "-+"))
9496 (goto-char beg)))))
9498 (defun org-table-wrap-region (arg)
9499 "Wrap several fields in a column like a paragraph.
9500 This is useful if you'd like to spread the contents of a field over several
9501 lines, in order to keep the table compact.
9503 If there is an active region, and both point and mark are in the same column,
9504 the text in the column is wrapped to minimum width for the given number of
9505 lines. Generally, this makes the table more compact. A prefix ARG may be
9506 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9507 formats the selected text to two lines. If the region was longer than two
9508 lines, the remaining lines remain empty. A negative prefix argument reduces
9509 the current number of lines by that amount. The wrapped text is pasted back
9510 into the table. If you formatted it to more lines than it was before, fields
9511 further down in the table get overwritten - so you might need to make space in
9512 the table first.
9514 If there is no region, the current field is split at the cursor position and
9515 the text fragment to the right of the cursor is prepended to the field one
9516 line down.
9518 If there is no region, but you specify a prefix ARG, the current field gets
9519 blank, and the content is appended to the field above."
9520 (interactive "P")
9521 (org-table-check-inside-data-field)
9522 (if (org-region-active-p)
9523 ;; There is a region: fill as a paragraph
9524 (let* ((beg (region-beginning))
9525 (cline (save-excursion (goto-char beg) (org-current-line)))
9526 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9527 nlines)
9528 (org-table-cut-region (region-beginning) (region-end))
9529 (if (> (length (car org-table-clip)) 1)
9530 (error "Region must be limited to single column"))
9531 (setq nlines (if arg
9532 (if (< arg 1)
9533 (+ (length org-table-clip) arg)
9534 arg)
9535 (length org-table-clip)))
9536 (setq org-table-clip
9537 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9538 nil nlines)))
9539 (goto-line cline)
9540 (org-table-goto-column ccol)
9541 (org-table-paste-rectangle))
9542 ;; No region, split the current field at point
9543 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9544 (skip-chars-forward "^\r\n|"))
9545 (if arg
9546 ;; combine with field above
9547 (let ((s (org-table-blank-field))
9548 (col (org-table-current-column)))
9549 (beginning-of-line 0)
9550 (while (org-at-table-hline-p) (beginning-of-line 0))
9551 (org-table-goto-column col)
9552 (skip-chars-forward "^|")
9553 (skip-chars-backward " ")
9554 (insert " " (org-trim s))
9555 (org-table-align))
9556 ;; split field
9557 (if (looking-at "\\([^|]+\\)+|")
9558 (let ((s (match-string 1)))
9559 (replace-match " |")
9560 (goto-char (match-beginning 0))
9561 (org-table-next-row)
9562 (insert (org-trim s) " ")
9563 (org-table-align))
9564 (org-table-next-row)))))
9566 (defvar org-field-marker nil)
9568 (defun org-table-edit-field (arg)
9569 "Edit table field in a different window.
9570 This is mainly useful for fields that contain hidden parts.
9571 When called with a \\[universal-argument] prefix, just make the full field visible so that
9572 it can be edited in place."
9573 (interactive "P")
9574 (if arg
9575 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9576 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9577 (remove-text-properties b e '(org-cwidth t invisible t
9578 display t intangible t))
9579 (if (and (boundp 'font-lock-mode) font-lock-mode)
9580 (font-lock-fontify-block)))
9581 (let ((pos (move-marker (make-marker) (point)))
9582 (field (org-table-get-field))
9583 (cw (current-window-configuration))
9585 (org-switch-to-buffer-other-window "*Org tmp*")
9586 (erase-buffer)
9587 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9588 (let ((org-inhibit-startup t)) (org-mode))
9589 (goto-char (setq p (point-max)))
9590 (insert (org-trim field))
9591 (remove-text-properties p (point-max)
9592 '(invisible t org-cwidth t display t
9593 intangible t))
9594 (goto-char p)
9595 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9596 (org-set-local 'org-window-configuration cw)
9597 (org-set-local 'org-field-marker pos)
9598 (message "Edit and finish with C-c C-c"))))
9600 (defun org-table-finish-edit-field ()
9601 "Finish editing a table data field.
9602 Remove all newline characters, insert the result into the table, realign
9603 the table and kill the editing buffer."
9604 (let ((pos org-field-marker)
9605 (cw org-window-configuration)
9606 (cb (current-buffer))
9607 text)
9608 (goto-char (point-min))
9609 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9610 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9611 (replace-match " "))
9612 (setq text (org-trim (buffer-string)))
9613 (set-window-configuration cw)
9614 (kill-buffer cb)
9615 (select-window (get-buffer-window (marker-buffer pos)))
9616 (goto-char pos)
9617 (move-marker pos nil)
9618 (org-table-check-inside-data-field)
9619 (org-table-get-field nil text)
9620 (org-table-align)
9621 (message "New field value inserted")))
9623 (defun org-trim (s)
9624 "Remove whitespace at beginning and end of string."
9625 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9626 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9629 (defun org-wrap (string &optional width lines)
9630 "Wrap string to either a number of lines, or a width in characters.
9631 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9632 that costs. If there is a word longer than WIDTH, the text is actually
9633 wrapped to the length of that word.
9634 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9635 many lines, whatever width that takes.
9636 The return value is a list of lines, without newlines at the end."
9637 (let* ((words (org-split-string string "[ \t\n]+"))
9638 (maxword (apply 'max (mapcar 'org-string-width words)))
9639 w ll)
9640 (cond (width
9641 (org-do-wrap words (max maxword width)))
9642 (lines
9643 (setq w maxword)
9644 (setq ll (org-do-wrap words maxword))
9645 (if (<= (length ll) lines)
9647 (setq ll words)
9648 (while (> (length ll) lines)
9649 (setq w (1+ w))
9650 (setq ll (org-do-wrap words w)))
9651 ll))
9652 (t (error "Cannot wrap this")))))
9655 (defun org-do-wrap (words width)
9656 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9657 (let (lines line)
9658 (while words
9659 (setq line (pop words))
9660 (while (and words (< (+ (length line) (length (car words))) width))
9661 (setq line (concat line " " (pop words))))
9662 (setq lines (push line lines)))
9663 (nreverse lines)))
9665 (defun org-split-string (string &optional separators)
9666 "Splits STRING into substrings at SEPARATORS.
9667 No empty strings are returned if there are matches at the beginning
9668 and end of string."
9669 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9670 (start 0)
9671 notfirst
9672 (list nil))
9673 (while (and (string-match rexp string
9674 (if (and notfirst
9675 (= start (match-beginning 0))
9676 (< start (length string)))
9677 (1+ start) start))
9678 (< (match-beginning 0) (length string)))
9679 (setq notfirst t)
9680 (or (eq (match-beginning 0) 0)
9681 (and (eq (match-beginning 0) (match-end 0))
9682 (eq (match-beginning 0) start))
9683 (setq list
9684 (cons (substring string start (match-beginning 0))
9685 list)))
9686 (setq start (match-end 0)))
9687 (or (eq start (length string))
9688 (setq list
9689 (cons (substring string start)
9690 list)))
9691 (nreverse list)))
9693 (defun org-table-map-tables (function)
9694 "Apply FUNCTION to the start of all tables in the buffer."
9695 (save-excursion
9696 (save-restriction
9697 (widen)
9698 (goto-char (point-min))
9699 (while (re-search-forward org-table-any-line-regexp nil t)
9700 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9701 (beginning-of-line 1)
9702 (if (looking-at org-table-line-regexp)
9703 (save-excursion (funcall function)))
9704 (re-search-forward org-table-any-border-regexp nil 1))))
9705 (message "Mapping tables: done"))
9707 (defvar org-timecnt) ; dynamically scoped parameter
9709 (defun org-table-sum (&optional beg end nlast)
9710 "Sum numbers in region of current table column.
9711 The result will be displayed in the echo area, and will be available
9712 as kill to be inserted with \\[yank].
9714 If there is an active region, it is interpreted as a rectangle and all
9715 numbers in that rectangle will be summed. If there is no active
9716 region and point is located in a table column, sum all numbers in that
9717 column.
9719 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9720 numbers are assumed to be times as well (in decimal hours) and the
9721 numbers are added as such.
9723 If NLAST is a number, only the NLAST fields will actually be summed."
9724 (interactive)
9725 (save-excursion
9726 (let (col (org-timecnt 0) diff h m s org-table-clip)
9727 (cond
9728 ((and beg end)) ; beg and end given explicitly
9729 ((org-region-active-p)
9730 (setq beg (region-beginning) end (region-end)))
9732 (setq col (org-table-current-column))
9733 (goto-char (org-table-begin))
9734 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9735 (error "No table data"))
9736 (org-table-goto-column col)
9737 (setq beg (point))
9738 (goto-char (org-table-end))
9739 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9740 (error "No table data"))
9741 (org-table-goto-column col)
9742 (setq end (point))))
9743 (let* ((items (apply 'append (org-table-copy-region beg end)))
9744 (items1 (cond ((not nlast) items)
9745 ((>= nlast (length items)) items)
9746 (t (setq items (reverse items))
9747 (setcdr (nthcdr (1- nlast) items) nil)
9748 (nreverse items))))
9749 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9750 items1)))
9751 (res (apply '+ numbers))
9752 (sres (if (= org-timecnt 0)
9753 (format "%g" res)
9754 (setq diff (* 3600 res)
9755 h (floor (/ diff 3600)) diff (mod diff 3600)
9756 m (floor (/ diff 60)) diff (mod diff 60)
9757 s diff)
9758 (format "%d:%02d:%02d" h m s))))
9759 (kill-new sres)
9760 (if (interactive-p)
9761 (message "%s"
9762 (substitute-command-keys
9763 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9764 (length numbers) sres))))
9765 sres))))
9767 (defun org-table-get-number-for-summing (s)
9768 (let (n)
9769 (if (string-match "^ *|? *" s)
9770 (setq s (replace-match "" nil nil s)))
9771 (if (string-match " *|? *$" s)
9772 (setq s (replace-match "" nil nil s)))
9773 (setq n (string-to-number s))
9774 (cond
9775 ((and (string-match "0" s)
9776 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9777 ((string-match "\\`[ \t]+\\'" s) nil)
9778 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9779 (let ((h (string-to-number (or (match-string 1 s) "0")))
9780 (m (string-to-number (or (match-string 2 s) "0")))
9781 (s (string-to-number (or (match-string 4 s) "0"))))
9782 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9783 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9784 ((equal n 0) nil)
9785 (t n))))
9787 (defun org-table-current-field-formula (&optional key noerror)
9788 "Return the formula active for the current field.
9789 Assumes that specials are in place.
9790 If KEY is given, return the key to this formula.
9791 Otherwise return the formula preceeded with \"=\" or \":=\"."
9792 (let* ((name (car (rassoc (list (org-current-line)
9793 (org-table-current-column))
9794 org-table-named-field-locations)))
9795 (col (org-table-current-column))
9796 (scol (int-to-string col))
9797 (ref (format "@%d$%d" (org-table-current-dline) col))
9798 (stored-list (org-table-get-stored-formulas noerror))
9799 (ass (or (assoc name stored-list)
9800 (assoc ref stored-list)
9801 (assoc scol stored-list))))
9802 (if key
9803 (car ass)
9804 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9805 (cdr ass))))))
9807 (defun org-table-get-formula (&optional equation named)
9808 "Read a formula from the minibuffer, offer stored formula as default.
9809 When NAMED is non-nil, look for a named equation."
9810 (let* ((stored-list (org-table-get-stored-formulas))
9811 (name (car (rassoc (list (org-current-line)
9812 (org-table-current-column))
9813 org-table-named-field-locations)))
9814 (ref (format "@%d$%d" (org-table-current-dline)
9815 (org-table-current-column)))
9816 (refass (assoc ref stored-list))
9817 (scol (if named
9818 (if name name ref)
9819 (int-to-string (org-table-current-column))))
9820 (dummy (and (or name refass) (not named)
9821 (not (y-or-n-p "Replace field formula with column formula? " ))
9822 (error "Abort")))
9823 (name (or name ref))
9824 (org-table-may-need-update nil)
9825 (stored (cdr (assoc scol stored-list)))
9826 (eq (cond
9827 ((and stored equation (string-match "^ *=? *$" equation))
9828 stored)
9829 ((stringp equation)
9830 equation)
9831 (t (org-table-formula-from-user
9832 (read-string
9833 (org-table-formula-to-user
9834 (format "%s formula %s%s="
9835 (if named "Field" "Column")
9836 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9837 scol))
9838 (if stored (org-table-formula-to-user stored) "")
9839 'org-table-formula-history
9840 )))))
9841 mustsave)
9842 (when (not (string-match "\\S-" eq))
9843 ;; remove formula
9844 (setq stored-list (delq (assoc scol stored-list) stored-list))
9845 (org-table-store-formulas stored-list)
9846 (error "Formula removed"))
9847 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9848 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9849 (if (and name (not named))
9850 ;; We set the column equation, delete the named one.
9851 (setq stored-list (delq (assoc name stored-list) stored-list)
9852 mustsave t))
9853 (if stored
9854 (setcdr (assoc scol stored-list) eq)
9855 (setq stored-list (cons (cons scol eq) stored-list)))
9856 (if (or mustsave (not (equal stored eq)))
9857 (org-table-store-formulas stored-list))
9858 eq))
9860 (defun org-table-store-formulas (alist)
9861 "Store the list of formulas below the current table."
9862 (setq alist (sort alist 'org-table-formula-less-p))
9863 (save-excursion
9864 (goto-char (org-table-end))
9865 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9866 (progn
9867 ;; don't overwrite TBLFM, we might use text properties to store stuff
9868 (goto-char (match-beginning 2))
9869 (delete-region (match-beginning 2) (match-end 0)))
9870 (insert "#+TBLFM:"))
9871 (insert " "
9872 (mapconcat (lambda (x)
9873 (concat
9874 (if (equal (string-to-char (car x)) ?@) "" "$")
9875 (car x) "=" (cdr x)))
9876 alist "::")
9877 "\n")))
9879 (defsubst org-table-formula-make-cmp-string (a)
9880 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9881 (concat
9882 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9883 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9884 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9886 (defun org-table-formula-less-p (a b)
9887 "Compare two formulas for sorting."
9888 (let ((as (org-table-formula-make-cmp-string (car a)))
9889 (bs (org-table-formula-make-cmp-string (car b))))
9890 (and as bs (string< as bs))))
9892 (defun org-table-get-stored-formulas (&optional noerror)
9893 "Return an alist with the stored formulas directly after current table."
9894 (interactive)
9895 (let (scol eq eq-alist strings string seen)
9896 (save-excursion
9897 (goto-char (org-table-end))
9898 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9899 (setq strings (org-split-string (match-string 2) " *:: *"))
9900 (while (setq string (pop strings))
9901 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9902 (setq scol (if (match-end 2)
9903 (match-string 2 string)
9904 (match-string 1 string))
9905 eq (match-string 3 string)
9906 eq-alist (cons (cons scol eq) eq-alist))
9907 (if (member scol seen)
9908 (if noerror
9909 (progn
9910 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9911 (ding)
9912 (sit-for 2))
9913 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9914 (push scol seen))))))
9915 (nreverse eq-alist)))
9917 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9918 "Modify the equations after the table structure has been edited.
9919 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9920 For all numbers larger than LIMIT, shift them by DELTA."
9921 (save-excursion
9922 (goto-char (org-table-end))
9923 (when (looking-at "#\\+TBLFM:")
9924 (let ((re (concat key "\\([0-9]+\\)"))
9925 (re2
9926 (when remove
9927 (if (equal key "$")
9928 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9929 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9930 s n a)
9931 (when remove
9932 (while (re-search-forward re2 (point-at-eol) t)
9933 (replace-match "")))
9934 (while (re-search-forward re (point-at-eol) t)
9935 (setq s (match-string 1) n (string-to-number s))
9936 (cond
9937 ((setq a (assoc s replace))
9938 (replace-match (concat key (cdr a)) t t))
9939 ((and limit (> n limit))
9940 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9942 (defun org-table-get-specials ()
9943 "Get the column names and local parameters for this table."
9944 (save-excursion
9945 (let ((beg (org-table-begin)) (end (org-table-end))
9946 names name fields fields1 field cnt
9947 c v l line col types dlines hlines)
9948 (setq org-table-column-names nil
9949 org-table-local-parameters nil
9950 org-table-named-field-locations nil
9951 org-table-current-begin-line nil
9952 org-table-current-begin-pos nil
9953 org-table-current-line-types nil)
9954 (goto-char beg)
9955 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9956 (setq names (org-split-string (match-string 1) " *| *")
9957 cnt 1)
9958 (while (setq name (pop names))
9959 (setq cnt (1+ cnt))
9960 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9961 (push (cons name (int-to-string cnt)) org-table-column-names))))
9962 (setq org-table-column-names (nreverse org-table-column-names))
9963 (setq org-table-column-name-regexp
9964 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9965 (goto-char beg)
9966 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9967 (setq fields (org-split-string (match-string 1) " *| *"))
9968 (while (setq field (pop fields))
9969 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9970 (push (cons (match-string 1 field) (match-string 2 field))
9971 org-table-local-parameters))))
9972 (goto-char beg)
9973 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9974 (setq c (match-string 1)
9975 fields (org-split-string (match-string 2) " *| *"))
9976 (save-excursion
9977 (beginning-of-line (if (equal c "_") 2 0))
9978 (setq line (org-current-line) col 1)
9979 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9980 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9981 (while (and fields1 (setq field (pop fields)))
9982 (setq v (pop fields1) col (1+ col))
9983 (when (and (stringp field) (stringp v)
9984 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9985 (push (cons field v) org-table-local-parameters)
9986 (push (list field line col) org-table-named-field-locations))))
9987 ;; Analyse the line types
9988 (goto-char beg)
9989 (setq org-table-current-begin-line (org-current-line)
9990 org-table-current-begin-pos (point)
9991 l org-table-current-begin-line)
9992 (while (looking-at "[ \t]*|\\(-\\)?")
9993 (push (if (match-end 1) 'hline 'dline) types)
9994 (if (match-end 1) (push l hlines) (push l dlines))
9995 (beginning-of-line 2)
9996 (setq l (1+ l)))
9997 (setq org-table-current-line-types (apply 'vector (nreverse types))
9998 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9999 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10001 (defun org-table-maybe-eval-formula ()
10002 "Check if the current field starts with \"=\" or \":=\".
10003 If yes, store the formula and apply it."
10004 ;; We already know we are in a table. Get field will only return a formula
10005 ;; when appropriate. It might return a separator line, but no problem.
10006 (when org-table-formula-evaluate-inline
10007 (let* ((field (org-trim (or (org-table-get-field) "")))
10008 named eq)
10009 (when (string-match "^:?=\\(.*\\)" field)
10010 (setq named (equal (string-to-char field) ?:)
10011 eq (match-string 1 field))
10012 (if (or (fboundp 'calc-eval)
10013 (equal (substring eq 0 (min 2 (length eq))) "'("))
10014 (org-table-eval-formula (if named '(4) nil)
10015 (org-table-formula-from-user eq))
10016 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10018 (defvar org-recalc-commands nil
10019 "List of commands triggering the recalculation of a line.
10020 Will be filled automatically during use.")
10022 (defvar org-recalc-marks
10023 '((" " . "Unmarked: no special line, no automatic recalculation")
10024 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10025 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10026 ("!" . "Column name definition line. Reference in formula as $name.")
10027 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10028 ("_" . "Names for values in row below this one.")
10029 ("^" . "Names for values in row above this one.")))
10031 (defun org-table-rotate-recalc-marks (&optional newchar)
10032 "Rotate the recalculation mark in the first column.
10033 If in any row, the first field is not consistent with a mark,
10034 insert a new column for the markers.
10035 When there is an active region, change all the lines in the region,
10036 after prompting for the marking character.
10037 After each change, a message will be displayed indicating the meaning
10038 of the new mark."
10039 (interactive)
10040 (unless (org-at-table-p) (error "Not at a table"))
10041 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10042 (beg (org-table-begin))
10043 (end (org-table-end))
10044 (l (org-current-line))
10045 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10046 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10047 (have-col
10048 (save-excursion
10049 (goto-char beg)
10050 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10051 (col (org-table-current-column))
10052 (forcenew (car (assoc newchar org-recalc-marks)))
10053 epos new)
10054 (when l1
10055 (message "Change region to what mark? Type # * ! $ or SPC: ")
10056 (setq newchar (char-to-string (read-char-exclusive))
10057 forcenew (car (assoc newchar org-recalc-marks))))
10058 (if (and newchar (not forcenew))
10059 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10060 newchar))
10061 (if l1 (goto-line l1))
10062 (save-excursion
10063 (beginning-of-line 1)
10064 (unless (looking-at org-table-dataline-regexp)
10065 (error "Not at a table data line")))
10066 (unless have-col
10067 (org-table-goto-column 1)
10068 (org-table-insert-column)
10069 (org-table-goto-column (1+ col)))
10070 (setq epos (point-at-eol))
10071 (save-excursion
10072 (beginning-of-line 1)
10073 (org-table-get-field
10074 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10075 (concat " "
10076 (setq new (or forcenew
10077 (cadr (member (match-string 1) marks))))
10078 " ")
10079 " # ")))
10080 (if (and l1 l2)
10081 (progn
10082 (goto-line l1)
10083 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10084 (and (looking-at org-table-dataline-regexp)
10085 (org-table-get-field 1 (concat " " new " "))))
10086 (goto-line l1)))
10087 (if (not (= epos (point-at-eol))) (org-table-align))
10088 (goto-line l)
10089 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10091 (defun org-table-maybe-recalculate-line ()
10092 "Recompute the current line if marked for it, and if we haven't just done it."
10093 (interactive)
10094 (and org-table-allow-automatic-line-recalculation
10095 (not (and (memq last-command org-recalc-commands)
10096 (equal org-last-recalc-line (org-current-line))))
10097 (save-excursion (beginning-of-line 1)
10098 (looking-at org-table-auto-recalculate-regexp))
10099 (org-table-recalculate) t))
10101 (defvar org-table-formula-debug nil
10102 "Non-nil means, debug table formulas.
10103 When nil, simply write \"#ERROR\" in corrupted fields.")
10104 (make-variable-buffer-local 'org-table-formula-debug)
10106 (defvar modes)
10107 (defsubst org-set-calc-mode (var &optional value)
10108 (if (stringp var)
10109 (setq var (assoc var '(("D" calc-angle-mode deg)
10110 ("R" calc-angle-mode rad)
10111 ("F" calc-prefer-frac t)
10112 ("S" calc-symbolic-mode t)))
10113 value (nth 2 var) var (nth 1 var)))
10114 (if (memq var modes)
10115 (setcar (cdr (memq var modes)) value)
10116 (cons var (cons value modes)))
10117 modes)
10119 (defun org-table-eval-formula (&optional arg equation
10120 suppress-align suppress-const
10121 suppress-store suppress-analysis)
10122 "Replace the table field value at the cursor by the result of a calculation.
10124 This function makes use of Dave Gillespie's Calc package, in my view the
10125 most exciting program ever written for GNU Emacs. So you need to have Calc
10126 installed in order to use this function.
10128 In a table, this command replaces the value in the current field with the
10129 result of a formula. It also installs the formula as the \"current\" column
10130 formula, by storing it in a special line below the table. When called
10131 with a `C-u' prefix, the current field must ba a named field, and the
10132 formula is installed as valid in only this specific field.
10134 When called with two `C-u' prefixes, insert the active equation
10135 for the field back into the current field, so that it can be
10136 edited there. This is useful in order to use \\[org-table-show-reference]
10137 to check the referenced fields.
10139 When called, the command first prompts for a formula, which is read in
10140 the minibuffer. Previously entered formulas are available through the
10141 history list, and the last used formula is offered as a default.
10142 These stored formulas are adapted correctly when moving, inserting, or
10143 deleting columns with the corresponding commands.
10145 The formula can be any algebraic expression understood by the Calc package.
10146 For details, see the Org-mode manual.
10148 This function can also be called from Lisp programs and offers
10149 additional arguments: EQUATION can be the formula to apply. If this
10150 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10151 used to speed-up recursive calls by by-passing unnecessary aligns.
10152 SUPPRESS-CONST suppresses the interpretation of constants in the
10153 formula, assuming that this has been done already outside the function.
10154 SUPPRESS-STORE means the formula should not be stored, either because
10155 it is already stored, or because it is a modified equation that should
10156 not overwrite the stored one."
10157 (interactive "P")
10158 (org-table-check-inside-data-field)
10159 (or suppress-analysis (org-table-get-specials))
10160 (if (equal arg '(16))
10161 (let ((eq (org-table-current-field-formula)))
10162 (or eq (error "No equation active for current field"))
10163 (org-table-get-field nil eq)
10164 (org-table-align)
10165 (setq org-table-may-need-update t))
10166 (let* (fields
10167 (ndown (if (integerp arg) arg 1))
10168 (org-table-automatic-realign nil)
10169 (case-fold-search nil)
10170 (down (> ndown 1))
10171 (formula (if (and equation suppress-store)
10172 equation
10173 (org-table-get-formula equation (equal arg '(4)))))
10174 (n0 (org-table-current-column))
10175 (modes (copy-sequence org-calc-default-modes))
10176 (numbers nil) ; was a variable, now fixed default
10177 (keep-empty nil)
10178 n form form0 bw fmt x ev orig c lispp literal)
10179 ;; Parse the format string. Since we have a lot of modes, this is
10180 ;; a lot of work. However, I think calc still uses most of the time.
10181 (if (string-match ";" formula)
10182 (let ((tmp (org-split-string formula ";")))
10183 (setq formula (car tmp)
10184 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10185 (nth 1 tmp)))
10186 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10187 (setq c (string-to-char (match-string 1 fmt))
10188 n (string-to-number (match-string 2 fmt)))
10189 (if (= c ?p)
10190 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10191 (setq modes (org-set-calc-mode
10192 'calc-float-format
10193 (list (cdr (assoc c '((?n . float) (?f . fix)
10194 (?s . sci) (?e . eng))))
10195 n))))
10196 (setq fmt (replace-match "" t t fmt)))
10197 (if (string-match "[NT]" fmt)
10198 (setq numbers (equal (match-string 0 fmt) "N")
10199 fmt (replace-match "" t t fmt)))
10200 (if (string-match "L" fmt)
10201 (setq literal t
10202 fmt (replace-match "" t t fmt)))
10203 (if (string-match "E" fmt)
10204 (setq keep-empty t
10205 fmt (replace-match "" t t fmt)))
10206 (while (string-match "[DRFS]" fmt)
10207 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10208 (setq fmt (replace-match "" t t fmt)))
10209 (unless (string-match "\\S-" fmt)
10210 (setq fmt nil))))
10211 (if (and (not suppress-const) org-table-formula-use-constants)
10212 (setq formula (org-table-formula-substitute-names formula)))
10213 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10214 (while (> ndown 0)
10215 (setq fields (org-split-string
10216 (org-no-properties
10217 (buffer-substring (point-at-bol) (point-at-eol)))
10218 " *| *"))
10219 (if (eq numbers t)
10220 (setq fields (mapcar
10221 (lambda (x) (number-to-string (string-to-number x)))
10222 fields)))
10223 (setq ndown (1- ndown))
10224 (setq form (copy-sequence formula)
10225 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10226 (if (and lispp literal) (setq lispp 'literal))
10227 ;; Check for old vertical references
10228 (setq form (org-rewrite-old-row-references form))
10229 ;; Insert complex ranges
10230 (while (string-match org-table-range-regexp form)
10231 (setq form
10232 (replace-match
10233 (save-match-data
10234 (org-table-make-reference
10235 (org-table-get-range (match-string 0 form) nil n0)
10236 keep-empty numbers lispp))
10237 t t form)))
10238 ;; Insert simple ranges
10239 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10240 (setq form
10241 (replace-match
10242 (save-match-data
10243 (org-table-make-reference
10244 (org-sublist
10245 fields (string-to-number (match-string 1 form))
10246 (string-to-number (match-string 2 form)))
10247 keep-empty numbers lispp))
10248 t t form)))
10249 (setq form0 form)
10250 ;; Insert the references to fields in same row
10251 (while (string-match "\\$\\([0-9]+\\)" form)
10252 (setq n (string-to-number (match-string 1 form))
10253 x (nth (1- (if (= n 0) n0 n)) fields))
10254 (unless x (error "Invalid field specifier \"%s\""
10255 (match-string 0 form)))
10256 (setq form (replace-match
10257 (save-match-data
10258 (org-table-make-reference x nil numbers lispp))
10259 t t form)))
10261 (if lispp
10262 (setq ev (condition-case nil
10263 (eval (eval (read form)))
10264 (error "#ERROR"))
10265 ev (if (numberp ev) (number-to-string ev) ev))
10266 (or (fboundp 'calc-eval)
10267 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10268 (setq ev (calc-eval (cons form modes)
10269 (if numbers 'num))))
10271 (when org-table-formula-debug
10272 (with-output-to-temp-buffer "*Substitution History*"
10273 (princ (format "Substitution history of formula
10274 Orig: %s
10275 $xyz-> %s
10276 @r$c-> %s
10277 $1-> %s\n" orig formula form0 form))
10278 (if (listp ev)
10279 (princ (format " %s^\nError: %s"
10280 (make-string (car ev) ?\-) (nth 1 ev)))
10281 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10282 ev (or fmt "NONE")
10283 (if fmt (format fmt (string-to-number ev)) ev)))))
10284 (setq bw (get-buffer-window "*Substitution History*"))
10285 (shrink-window-if-larger-than-buffer bw)
10286 (unless (and (interactive-p) (not ndown))
10287 (unless (let (inhibit-redisplay)
10288 (y-or-n-p "Debugging Formula. Continue to next? "))
10289 (org-table-align)
10290 (error "Abort"))
10291 (delete-window bw)
10292 (message "")))
10293 (if (listp ev) (setq fmt nil ev "#ERROR"))
10294 (org-table-justify-field-maybe
10295 (if fmt (format fmt (string-to-number ev)) ev))
10296 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10297 (call-interactively 'org-return)
10298 (setq ndown 0)))
10299 (and down (org-table-maybe-recalculate-line))
10300 (or suppress-align (and org-table-may-need-update
10301 (org-table-align))))))
10303 (defun org-table-put-field-property (prop value)
10304 (save-excursion
10305 (put-text-property (progn (skip-chars-backward "^|") (point))
10306 (progn (skip-chars-forward "^|") (point))
10307 prop value)))
10309 (defun org-table-get-range (desc &optional tbeg col highlight)
10310 "Get a calc vector from a column, accorting to descriptor DESC.
10311 Optional arguments TBEG and COL can give the beginning of the table and
10312 the current column, to avoid unnecessary parsing.
10313 HIGHLIGHT means, just highlight the range."
10314 (if (not (equal (string-to-char desc) ?@))
10315 (setq desc (concat "@" desc)))
10316 (save-excursion
10317 (or tbeg (setq tbeg (org-table-begin)))
10318 (or col (setq col (org-table-current-column)))
10319 (let ((thisline (org-current-line))
10320 beg end c1 c2 r1 r2 rangep tmp)
10321 (unless (string-match org-table-range-regexp desc)
10322 (error "Invalid table range specifier `%s'" desc))
10323 (setq rangep (match-end 3)
10324 r1 (and (match-end 1) (match-string 1 desc))
10325 r2 (and (match-end 4) (match-string 4 desc))
10326 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10327 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10329 (and c1 (setq c1 (+ (string-to-number c1)
10330 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10331 (and c2 (setq c2 (+ (string-to-number c2)
10332 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10333 (if (equal r1 "") (setq r1 nil))
10334 (if (equal r2 "") (setq r2 nil))
10335 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10336 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10337 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10338 (if (not r1) (setq r1 thisline))
10339 (if (not r2) (setq r2 thisline))
10340 (if (not c1) (setq c1 col))
10341 (if (not c2) (setq c2 col))
10342 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10343 ;; just one field
10344 (progn
10345 (goto-line r1)
10346 (while (not (looking-at org-table-dataline-regexp))
10347 (beginning-of-line 2))
10348 (prog1 (org-trim (org-table-get-field c1))
10349 (if highlight (org-table-highlight-rectangle (point) (point)))))
10350 ;; A range, return a vector
10351 ;; First sort the numbers to get a regular ractangle
10352 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10353 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10354 (goto-line r1)
10355 (while (not (looking-at org-table-dataline-regexp))
10356 (beginning-of-line 2))
10357 (org-table-goto-column c1)
10358 (setq beg (point))
10359 (goto-line r2)
10360 (while (not (looking-at org-table-dataline-regexp))
10361 (beginning-of-line 0))
10362 (org-table-goto-column c2)
10363 (setq end (point))
10364 (if highlight
10365 (org-table-highlight-rectangle
10366 beg (progn (skip-chars-forward "^|\n") (point))))
10367 ;; return string representation of calc vector
10368 (mapcar 'org-trim
10369 (apply 'append (org-table-copy-region beg end)))))))
10371 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10372 "Analyze descriptor DESC and retrieve the corresponding line number.
10373 The cursor is currently in line CLINE, the table begins in line BLINE,
10374 and TABLE is a vector with line types."
10375 (if (string-match "^[0-9]+$" desc)
10376 (aref org-table-dlines (string-to-number desc))
10377 (setq cline (or cline (org-current-line))
10378 bline (or bline org-table-current-begin-line)
10379 table (or table org-table-current-line-types))
10380 (if (or
10381 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10382 ;; 1 2 3 4 5 6
10383 (and (not (match-end 3)) (not (match-end 6)))
10384 (and (match-end 3) (match-end 6) (not (match-end 5))))
10385 (error "invalid row descriptor `%s'" desc))
10386 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10387 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10388 (odir (and (match-end 5) (match-string 5 desc)))
10389 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10390 (i (- cline bline))
10391 (rel (and (match-end 6)
10392 (or (and (match-end 1) (not (match-end 3)))
10393 (match-end 5)))))
10394 (if (and hn (not hdir))
10395 (progn
10396 (setq i 0 hdir "+")
10397 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10398 (if (and (not hn) on (not odir))
10399 (error "should never happen");;(aref org-table-dlines on)
10400 (if (and hn (> hn 0))
10401 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10402 (if on
10403 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10404 (+ bline i)))))
10406 (defun org-find-row-type (table i type backwards relative n)
10407 (let ((l (length table)))
10408 (while (> n 0)
10409 (while (and (setq i (+ i (if backwards -1 1)))
10410 (>= i 0) (< i l)
10411 (not (eq (aref table i) type))
10412 (if (and relative (eq (aref table i) 'hline))
10413 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10414 t)))
10415 (setq n (1- n)))
10416 (if (or (< i 0) (>= i l))
10417 (error "Row descriptior leads outside table")
10418 i)))
10420 (defun org-rewrite-old-row-references (s)
10421 (if (string-match "&[-+0-9I]" s)
10422 (error "Formula contains old &row reference, please rewrite using @-syntax")
10425 (defun org-table-make-reference (elements keep-empty numbers lispp)
10426 "Convert list ELEMENTS to something appropriate to insert into formula.
10427 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10428 NUMBERS indicates that everything should be converted to numbers.
10429 LISPP means to return something appropriate for a Lisp list."
10430 (if (stringp elements) ; just a single val
10431 (if lispp
10432 (if (eq lispp 'literal)
10433 elements
10434 (prin1-to-string (if numbers (string-to-number elements) elements)))
10435 (if (equal elements "") (setq elements "0"))
10436 (if numbers (number-to-string (string-to-number elements)) elements))
10437 (unless keep-empty
10438 (setq elements
10439 (delq nil
10440 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10441 elements))))
10442 (setq elements (or elements '("0")))
10443 (if lispp
10444 (mapconcat
10445 (lambda (x)
10446 (if (eq lispp 'literal)
10448 (prin1-to-string (if numbers (string-to-number x) x))))
10449 elements " ")
10450 (concat "[" (mapconcat
10451 (lambda (x)
10452 (if numbers (number-to-string (string-to-number x)) x))
10453 elements
10454 ",") "]"))))
10456 (defun org-table-recalculate (&optional all noalign)
10457 "Recalculate the current table line by applying all stored formulas.
10458 With prefix arg ALL, do this for all lines in the table."
10459 (interactive "P")
10460 (or (memq this-command org-recalc-commands)
10461 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10462 (unless (org-at-table-p) (error "Not at a table"))
10463 (if (equal all '(16))
10464 (org-table-iterate)
10465 (org-table-get-specials)
10466 (let* ((eqlist (sort (org-table-get-stored-formulas)
10467 (lambda (a b) (string< (car a) (car b)))))
10468 (inhibit-redisplay (not debug-on-error))
10469 (line-re org-table-dataline-regexp)
10470 (thisline (org-current-line))
10471 (thiscol (org-table-current-column))
10472 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10473 ;; Insert constants in all formulas
10474 (setq eqlist
10475 (mapcar (lambda (x)
10476 (setcdr x (org-table-formula-substitute-names (cdr x)))
10478 eqlist))
10479 ;; Split the equation list
10480 (while (setq eq (pop eqlist))
10481 (if (<= (string-to-char (car eq)) ?9)
10482 (push eq eqlnum)
10483 (push eq eqlname)))
10484 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10485 (if all
10486 (progn
10487 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10488 (goto-char (setq beg (org-table-begin)))
10489 (if (re-search-forward org-table-calculate-mark-regexp end t)
10490 ;; This is a table with marked lines, compute selected lines
10491 (setq line-re org-table-recalculate-regexp)
10492 ;; Move forward to the first non-header line
10493 (if (and (re-search-forward org-table-dataline-regexp end t)
10494 (re-search-forward org-table-hline-regexp end t)
10495 (re-search-forward org-table-dataline-regexp end t))
10496 (setq beg (match-beginning 0))
10497 nil))) ;; just leave beg where it is
10498 (setq beg (point-at-bol)
10499 end (move-marker (make-marker) (1+ (point-at-eol)))))
10500 (goto-char beg)
10501 (and all (message "Re-applying formulas to full table..."))
10503 ;; First find the named fields, and mark them untouchanble
10504 (remove-text-properties beg end '(org-untouchable t))
10505 (while (setq eq (pop eqlname))
10506 (setq name (car eq)
10507 a (assoc name org-table-named-field-locations))
10508 (and (not a)
10509 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10510 (setq a (list name
10511 (aref org-table-dlines
10512 (string-to-number (match-string 1 name)))
10513 (string-to-number (match-string 2 name)))))
10514 (when (and a (or all (equal (nth 1 a) thisline)))
10515 (message "Re-applying formula to field: %s" name)
10516 (goto-line (nth 1 a))
10517 (org-table-goto-column (nth 2 a))
10518 (push (append a (list (cdr eq))) eqlname1)
10519 (org-table-put-field-property :org-untouchable t)))
10521 ;; Now evauluate the column formulas, but skip fields covered by
10522 ;; field formulas
10523 (goto-char beg)
10524 (while (re-search-forward line-re end t)
10525 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10526 ;; Unprotected line, recalculate
10527 (and all (message "Re-applying formulas to full table...(line %d)"
10528 (setq cnt (1+ cnt))))
10529 (setq org-last-recalc-line (org-current-line))
10530 (setq eql eqlnum)
10531 (while (setq entry (pop eql))
10532 (goto-line org-last-recalc-line)
10533 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10534 (unless (get-text-property (point) :org-untouchable)
10535 (org-table-eval-formula nil (cdr entry)
10536 'noalign 'nocst 'nostore 'noanalysis)))))
10538 ;; Now evaluate the field formulas
10539 (while (setq eq (pop eqlname1))
10540 (message "Re-applying formula to field: %s" (car eq))
10541 (goto-line (nth 1 eq))
10542 (org-table-goto-column (nth 2 eq))
10543 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10544 'nostore 'noanalysis))
10546 (goto-line thisline)
10547 (org-table-goto-column thiscol)
10548 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10549 (or noalign (and org-table-may-need-update (org-table-align))
10550 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10552 ;; back to initial position
10553 (message "Re-applying formulas...done")
10554 (goto-line thisline)
10555 (org-table-goto-column thiscol)
10556 (or noalign (and org-table-may-need-update (org-table-align))
10557 (and all (message "Re-applying formulas...done"))))))
10559 (defun org-table-iterate (&optional arg)
10560 "Recalculate the table until it does not change anymore."
10561 (interactive "P")
10562 (let ((imax (if arg (prefix-numeric-value arg) 10))
10563 (i 0)
10564 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10565 thistbl)
10566 (catch 'exit
10567 (while (< i imax)
10568 (setq i (1+ i))
10569 (org-table-recalculate 'all)
10570 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10571 (if (not (string= lasttbl thistbl))
10572 (setq lasttbl thistbl)
10573 (if (> i 1)
10574 (message "Convergence after %d iterations" i)
10575 (message "Table was already stable"))
10576 (throw 'exit t)))
10577 (error "No convergence after %d iterations" i))))
10579 (defun org-table-formula-substitute-names (f)
10580 "Replace $const with values in string F."
10581 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10582 ;; First, check for column names
10583 (while (setq start (string-match org-table-column-name-regexp f start))
10584 (setq start (1+ start))
10585 (setq a (assoc (match-string 1 f) org-table-column-names))
10586 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10587 ;; Parameters and constants
10588 (setq start 0)
10589 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10590 (setq start (1+ start))
10591 (if (setq a (save-match-data
10592 (org-table-get-constant (match-string 1 f))))
10593 (setq f (replace-match
10594 (concat (if pp "(") a (if pp ")")) t t f))))
10595 (if org-table-formula-debug
10596 (put-text-property 0 (length f) :orig-formula f1 f))
10599 (defun org-table-get-constant (const)
10600 "Find the value for a parameter or constant in a formula.
10601 Parameters get priority."
10602 (or (cdr (assoc const org-table-local-parameters))
10603 (cdr (assoc const org-table-formula-constants-local))
10604 (cdr (assoc const org-table-formula-constants))
10605 (and (fboundp 'constants-get) (constants-get const))
10606 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10607 (org-entry-get nil (substring const 5) 'inherit))
10608 "#UNDEFINED_NAME"))
10610 (defvar org-table-fedit-map
10611 (let ((map (make-sparse-keymap)))
10612 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10613 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10614 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10615 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10616 (org-defkey map "\C-c?" 'org-table-show-reference)
10617 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10618 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10619 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10620 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10621 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10622 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10623 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10624 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10625 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10626 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10627 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10628 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10629 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10630 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10631 map))
10633 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10634 '("Edit-Formulas"
10635 ["Finish and Install" org-table-fedit-finish t]
10636 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10637 ["Abort" org-table-fedit-abort t]
10638 "--"
10639 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10640 ["Complete Lisp Symbol" lisp-complete-symbol t]
10641 "--"
10642 "Shift Reference at Point"
10643 ["Up" org-table-fedit-ref-up t]
10644 ["Down" org-table-fedit-ref-down t]
10645 ["Left" org-table-fedit-ref-left t]
10646 ["Right" org-table-fedit-ref-right t]
10648 "Change Test Row for Column Formulas"
10649 ["Up" org-table-fedit-line-up t]
10650 ["Down" org-table-fedit-line-down t]
10651 "--"
10652 ["Scroll Table Window" org-table-fedit-scroll t]
10653 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10654 ["Show Table Grid" org-table-fedit-toggle-coordinates
10655 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10656 org-table-overlay-coordinates)]
10657 "--"
10658 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10659 :style toggle :selected org-table-buffer-is-an]))
10661 (defvar org-pos)
10663 (defun org-table-edit-formulas ()
10664 "Edit the formulas of the current table in a separate buffer."
10665 (interactive)
10666 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10667 (beginning-of-line 0))
10668 (unless (org-at-table-p) (error "Not at a table"))
10669 (org-table-get-specials)
10670 (let ((key (org-table-current-field-formula 'key 'noerror))
10671 (eql (sort (org-table-get-stored-formulas 'noerror)
10672 'org-table-formula-less-p))
10673 (pos (move-marker (make-marker) (point)))
10674 (startline 1)
10675 (wc (current-window-configuration))
10676 (titles '((column . "# Column Formulas\n")
10677 (field . "# Field Formulas\n")
10678 (named . "# Named Field Formulas\n")))
10679 entry s type title)
10680 (org-switch-to-buffer-other-window "*Edit Formulas*")
10681 (erase-buffer)
10682 ;; Keep global-font-lock-mode from turning on font-lock-mode
10683 (let ((font-lock-global-modes '(not fundamental-mode)))
10684 (fundamental-mode))
10685 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10686 (org-set-local 'org-pos pos)
10687 (org-set-local 'org-window-configuration wc)
10688 (use-local-map org-table-fedit-map)
10689 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10690 (easy-menu-add org-table-fedit-menu)
10691 (setq startline (org-current-line))
10692 (while (setq entry (pop eql))
10693 (setq type (cond
10694 ((equal (string-to-char (car entry)) ?@) 'field)
10695 ((string-match "^[0-9]" (car entry)) 'column)
10696 (t 'named)))
10697 (when (setq title (assq type titles))
10698 (or (bobp) (insert "\n"))
10699 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10700 (setq titles (delq title titles)))
10701 (if (equal key (car entry)) (setq startline (org-current-line)))
10702 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10703 (car entry) " = " (cdr entry) "\n"))
10704 (remove-text-properties 0 (length s) '(face nil) s)
10705 (insert s))
10706 (if (eq org-table-use-standard-references t)
10707 (org-table-fedit-toggle-ref-type))
10708 (goto-line startline)
10709 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10711 (defun org-table-fedit-post-command ()
10712 (when (not (memq this-command '(lisp-complete-symbol)))
10713 (let ((win (selected-window)))
10714 (save-excursion
10715 (condition-case nil
10716 (org-table-show-reference)
10717 (error nil))
10718 (select-window win)))))
10720 (defun org-table-formula-to-user (s)
10721 "Convert a formula from internal to user representation."
10722 (if (eq org-table-use-standard-references t)
10723 (org-table-convert-refs-to-an s)
10726 (defun org-table-formula-from-user (s)
10727 "Convert a formula from user to internal representation."
10728 (if org-table-use-standard-references
10729 (org-table-convert-refs-to-rc s)
10732 (defun org-table-convert-refs-to-rc (s)
10733 "Convert spreadsheet references from AB7 to @7$28.
10734 Works for single references, but also for entire formulas and even the
10735 full TBLFM line."
10736 (let ((start 0))
10737 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10738 (cond
10739 ((match-end 3)
10740 ;; format match, just advance
10741 (setq start (match-end 0)))
10742 ((and (> (match-beginning 0) 0)
10743 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10744 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10745 ;; 3.e5 or something like this.
10746 (setq start (match-end 0)))
10748 (setq start (match-beginning 0)
10749 s (replace-match
10750 (if (equal (match-string 2 s) "&")
10751 (format "$%d" (org-letters-to-number (match-string 1 s)))
10752 (format "@%d$%d"
10753 (string-to-number (match-string 2 s))
10754 (org-letters-to-number (match-string 1 s))))
10755 t t s)))))
10758 (defun org-table-convert-refs-to-an (s)
10759 "Convert spreadsheet references from to @7$28 to AB7.
10760 Works for single references, but also for entire formulas and even the
10761 full TBLFM line."
10762 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10763 (setq s (replace-match
10764 (format "%s%d"
10765 (org-number-to-letters
10766 (string-to-number (match-string 2 s)))
10767 (string-to-number (match-string 1 s)))
10768 t t s)))
10769 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10770 (setq s (replace-match (concat "\\1"
10771 (org-number-to-letters
10772 (string-to-number (match-string 2 s))) "&")
10773 t nil s)))
10776 (defun org-letters-to-number (s)
10777 "Convert a base 26 number represented by letters into an integer.
10778 For example: AB -> 28."
10779 (let ((n 0))
10780 (setq s (upcase s))
10781 (while (> (length s) 0)
10782 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10783 s (substring s 1)))
10786 (defun org-number-to-letters (n)
10787 "Convert an integer into a base 26 number represented by letters.
10788 For example: 28 -> AB."
10789 (let ((s ""))
10790 (while (> n 0)
10791 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10792 n (/ (1- n) 26)))
10795 (defun org-table-fedit-convert-buffer (function)
10796 "Convert all references in this buffer, using FUNTION."
10797 (let ((line (org-current-line)))
10798 (goto-char (point-min))
10799 (while (not (eobp))
10800 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10801 (delete-region (point) (point-at-eol))
10802 (or (eobp) (forward-char 1)))
10803 (goto-line line)))
10805 (defun org-table-fedit-toggle-ref-type ()
10806 "Convert all references in the buffer from B3 to @3$2 and back."
10807 (interactive)
10808 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10809 (org-table-fedit-convert-buffer
10810 (if org-table-buffer-is-an
10811 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10812 (message "Reference type switched to %s"
10813 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10815 (defun org-table-fedit-ref-up ()
10816 "Shift the reference at point one row/hline up."
10817 (interactive)
10818 (org-table-fedit-shift-reference 'up))
10819 (defun org-table-fedit-ref-down ()
10820 "Shift the reference at point one row/hline down."
10821 (interactive)
10822 (org-table-fedit-shift-reference 'down))
10823 (defun org-table-fedit-ref-left ()
10824 "Shift the reference at point one field to the left."
10825 (interactive)
10826 (org-table-fedit-shift-reference 'left))
10827 (defun org-table-fedit-ref-right ()
10828 "Shift the reference at point one field to the right."
10829 (interactive)
10830 (org-table-fedit-shift-reference 'right))
10832 (defun org-table-fedit-shift-reference (dir)
10833 (cond
10834 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10835 (if (memq dir '(left right))
10836 (org-rematch-and-replace 1 (eq dir 'left))
10837 (error "Cannot shift reference in this direction")))
10838 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10839 ;; A B3-like reference
10840 (if (memq dir '(up down))
10841 (org-rematch-and-replace 2 (eq dir 'up))
10842 (org-rematch-and-replace 1 (eq dir 'left))))
10843 ((org-at-regexp-p
10844 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10845 ;; An internal reference
10846 (if (memq dir '(up down))
10847 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10848 (org-rematch-and-replace 5 (eq dir 'left))))))
10850 (defun org-rematch-and-replace (n &optional decr hline)
10851 "Re-match the group N, and replace it with the shifted refrence."
10852 (or (match-end n) (error "Cannot shift reference in this direction"))
10853 (goto-char (match-beginning n))
10854 (and (looking-at (regexp-quote (match-string n)))
10855 (replace-match (org-shift-refpart (match-string 0) decr hline)
10856 t t)))
10858 (defun org-shift-refpart (ref &optional decr hline)
10859 "Shift a refrence part REF.
10860 If DECR is set, decrease the references row/column, else increase.
10861 If HLINE is set, this may be a hline reference, it certainly is not
10862 a translation reference."
10863 (save-match-data
10864 (let* ((sign (string-match "^[-+]" ref)) n)
10866 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10867 (cond
10868 ((and hline (string-match "^I+" ref))
10869 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10870 (setq n (+ n (if decr -1 1)))
10871 (if (= n 0) (setq n (+ n (if decr -1 1))))
10872 (if sign
10873 (setq sign (if (< n 0) "-" "+") n (abs n))
10874 (setq n (max 1 n)))
10875 (concat sign (make-string n ?I)))
10877 ((string-match "^[0-9]+" ref)
10878 (setq n (string-to-number (concat sign ref)))
10879 (setq n (+ n (if decr -1 1)))
10880 (if sign
10881 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10882 (number-to-string (max 1 n))))
10884 ((string-match "^[a-zA-Z]+" ref)
10885 (org-number-to-letters
10886 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10888 (t (error "Cannot shift reference"))))))
10890 (defun org-table-fedit-toggle-coordinates ()
10891 "Toggle the display of coordinates in the refrenced table."
10892 (interactive)
10893 (let ((pos (marker-position org-pos)))
10894 (with-current-buffer (marker-buffer org-pos)
10895 (save-excursion
10896 (goto-char pos)
10897 (org-table-toggle-coordinate-overlays)))))
10899 (defun org-table-fedit-finish (&optional arg)
10900 "Parse the buffer for formula definitions and install them.
10901 With prefix ARG, apply the new formulas to the table."
10902 (interactive "P")
10903 (org-table-remove-rectangle-highlight)
10904 (if org-table-use-standard-references
10905 (progn
10906 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10907 (setq org-table-buffer-is-an nil)))
10908 (let ((pos org-pos) eql var form)
10909 (goto-char (point-min))
10910 (while (re-search-forward
10911 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10912 nil t)
10913 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10914 form (match-string 3))
10915 (setq form (org-trim form))
10916 (when (not (equal form ""))
10917 (while (string-match "[ \t]*\n[ \t]*" form)
10918 (setq form (replace-match " " t t form)))
10919 (when (assoc var eql)
10920 (error "Double formulas for %s" var))
10921 (push (cons var form) eql)))
10922 (setq org-pos nil)
10923 (set-window-configuration org-window-configuration)
10924 (select-window (get-buffer-window (marker-buffer pos)))
10925 (goto-char pos)
10926 (unless (org-at-table-p)
10927 (error "Lost table position - cannot install formulae"))
10928 (org-table-store-formulas eql)
10929 (move-marker pos nil)
10930 (kill-buffer "*Edit Formulas*")
10931 (if arg
10932 (org-table-recalculate 'all)
10933 (message "New formulas installed - press C-u C-c C-c to apply."))))
10935 (defun org-table-fedit-abort ()
10936 "Abort editing formulas, without installing the changes."
10937 (interactive)
10938 (org-table-remove-rectangle-highlight)
10939 (let ((pos org-pos))
10940 (set-window-configuration org-window-configuration)
10941 (select-window (get-buffer-window (marker-buffer pos)))
10942 (goto-char pos)
10943 (move-marker pos nil)
10944 (message "Formula editing aborted without installing changes")))
10946 (defun org-table-fedit-lisp-indent ()
10947 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10948 (interactive)
10949 (let ((pos (point)) beg end ind)
10950 (beginning-of-line 1)
10951 (cond
10952 ((looking-at "[ \t]")
10953 (goto-char pos)
10954 (call-interactively 'lisp-indent-line))
10955 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10956 ((not (fboundp 'pp-buffer))
10957 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10958 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10959 (goto-char (- (match-end 0) 2))
10960 (setq beg (point))
10961 (setq ind (make-string (current-column) ?\ ))
10962 (condition-case nil (forward-sexp 1)
10963 (error
10964 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10965 (setq end (point))
10966 (save-restriction
10967 (narrow-to-region beg end)
10968 (if (eq last-command this-command)
10969 (progn
10970 (goto-char (point-min))
10971 (setq this-command nil)
10972 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10973 (replace-match " ")))
10974 (pp-buffer)
10975 (untabify (point-min) (point-max))
10976 (goto-char (1+ (point-min)))
10977 (while (re-search-forward "^." nil t)
10978 (beginning-of-line 1)
10979 (insert ind))
10980 (goto-char (point-max))
10981 (backward-delete-char 1)))
10982 (goto-char beg))
10983 (t nil))))
10985 (defvar org-show-positions nil)
10987 (defun org-table-show-reference (&optional local)
10988 "Show the location/value of the $ expression at point."
10989 (interactive)
10990 (org-table-remove-rectangle-highlight)
10991 (catch 'exit
10992 (let ((pos (if local (point) org-pos))
10993 (face2 'highlight)
10994 (org-inhibit-highlight-removal t)
10995 (win (selected-window))
10996 (org-show-positions nil)
10997 var name e what match dest)
10998 (if local (org-table-get-specials))
10999 (setq what (cond
11000 ((or (org-at-regexp-p org-table-range-regexp2)
11001 (org-at-regexp-p org-table-translate-regexp)
11002 (org-at-regexp-p org-table-range-regexp))
11003 (setq match
11004 (save-match-data
11005 (org-table-convert-refs-to-rc (match-string 0))))
11006 'range)
11007 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11008 ((org-at-regexp-p "\\$[0-9]+") 'column)
11009 ((not local) nil)
11010 (t (error "No reference at point")))
11011 match (and what (or match (match-string 0))))
11012 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11013 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11014 'secondary-selection))
11015 (org-add-hook 'before-change-functions
11016 'org-table-remove-rectangle-highlight)
11017 (if (eq what 'name) (setq var (substring match 1)))
11018 (when (eq what 'range)
11019 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11020 (setq match (org-table-formula-substitute-names match)))
11021 (unless local
11022 (save-excursion
11023 (end-of-line 1)
11024 (re-search-backward "^\\S-" nil t)
11025 (beginning-of-line 1)
11026 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11027 (setq dest
11028 (save-match-data
11029 (org-table-convert-refs-to-rc (match-string 1))))
11030 (org-table-add-rectangle-overlay
11031 (match-beginning 1) (match-end 1) face2))))
11032 (if (and (markerp pos) (marker-buffer pos))
11033 (if (get-buffer-window (marker-buffer pos))
11034 (select-window (get-buffer-window (marker-buffer pos)))
11035 (org-switch-to-buffer-other-window (get-buffer-window
11036 (marker-buffer pos)))))
11037 (goto-char pos)
11038 (org-table-force-dataline)
11039 (when dest
11040 (setq name (substring dest 1))
11041 (cond
11042 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11043 (setq e (assoc name org-table-named-field-locations))
11044 (goto-line (nth 1 e))
11045 (org-table-goto-column (nth 2 e)))
11046 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11047 (let ((l (string-to-number (match-string 1 dest)))
11048 (c (string-to-number (match-string 2 dest))))
11049 (goto-line (aref org-table-dlines l))
11050 (org-table-goto-column c)))
11051 (t (org-table-goto-column (string-to-number name))))
11052 (move-marker pos (point))
11053 (org-table-highlight-rectangle nil nil face2))
11054 (cond
11055 ((equal dest match))
11056 ((not match))
11057 ((eq what 'range)
11058 (condition-case nil
11059 (save-excursion
11060 (org-table-get-range match nil nil 'highlight))
11061 (error nil)))
11062 ((setq e (assoc var org-table-named-field-locations))
11063 (goto-line (nth 1 e))
11064 (org-table-goto-column (nth 2 e))
11065 (org-table-highlight-rectangle (point) (point))
11066 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11067 ((setq e (assoc var org-table-column-names))
11068 (org-table-goto-column (string-to-number (cdr e)))
11069 (org-table-highlight-rectangle (point) (point))
11070 (goto-char (org-table-begin))
11071 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11072 (org-table-end) t)
11073 (progn
11074 (goto-char (match-beginning 1))
11075 (org-table-highlight-rectangle)
11076 (message "Named column (column %s)" (cdr e)))
11077 (error "Column name not found")))
11078 ((eq what 'column)
11079 ;; column number
11080 (org-table-goto-column (string-to-number (substring match 1)))
11081 (org-table-highlight-rectangle (point) (point))
11082 (message "Column %s" (substring match 1)))
11083 ((setq e (assoc var org-table-local-parameters))
11084 (goto-char (org-table-begin))
11085 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11086 (progn
11087 (goto-char (match-beginning 1))
11088 (org-table-highlight-rectangle)
11089 (message "Local parameter."))
11090 (error "Parameter not found")))
11092 (cond
11093 ((not var) (error "No reference at point"))
11094 ((setq e (assoc var org-table-formula-constants-local))
11095 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11096 var (cdr e)))
11097 ((setq e (assoc var org-table-formula-constants))
11098 (message "Constant: $%s=%s in `org-table-formula-constants'."
11099 var (cdr e)))
11100 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11101 (message "Constant: $%s=%s, from `constants.el'%s."
11102 var e (format " (%s units)" constants-unit-system)))
11103 (t (error "Undefined name $%s" var)))))
11104 (goto-char pos)
11105 (when (and org-show-positions
11106 (not (memq this-command '(org-table-fedit-scroll
11107 org-table-fedit-scroll-down))))
11108 (push pos org-show-positions)
11109 (push org-table-current-begin-pos org-show-positions)
11110 (let ((min (apply 'min org-show-positions))
11111 (max (apply 'max org-show-positions)))
11112 (goto-char min) (recenter 0)
11113 (goto-char max)
11114 (or (pos-visible-in-window-p max) (recenter -1))))
11115 (select-window win))))
11117 (defun org-table-force-dataline ()
11118 "Make sure the cursor is in a dataline in a table."
11119 (unless (save-excursion
11120 (beginning-of-line 1)
11121 (looking-at org-table-dataline-regexp))
11122 (let* ((re org-table-dataline-regexp)
11123 (p1 (save-excursion (re-search-forward re nil 'move)))
11124 (p2 (save-excursion (re-search-backward re nil 'move))))
11125 (cond ((and p1 p2)
11126 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11127 p1 p2)))
11128 ((or p1 p2) (goto-char (or p1 p2)))
11129 (t (error "No table dataline around here"))))))
11131 (defun org-table-fedit-line-up ()
11132 "Move cursor one line up in the window showing the table."
11133 (interactive)
11134 (org-table-fedit-move 'previous-line))
11136 (defun org-table-fedit-line-down ()
11137 "Move cursor one line down in the window showing the table."
11138 (interactive)
11139 (org-table-fedit-move 'next-line))
11141 (defun org-table-fedit-move (command)
11142 "Move the cursor in the window shoinw the table.
11143 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11144 (let ((org-table-allow-automatic-line-recalculation nil)
11145 (pos org-pos) (win (selected-window)) p)
11146 (select-window (get-buffer-window (marker-buffer org-pos)))
11147 (setq p (point))
11148 (call-interactively command)
11149 (while (and (org-at-table-p)
11150 (org-at-table-hline-p))
11151 (call-interactively command))
11152 (or (org-at-table-p) (goto-char p))
11153 (move-marker pos (point))
11154 (select-window win)))
11156 (defun org-table-fedit-scroll (N)
11157 (interactive "p")
11158 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11159 (scroll-other-window N)))
11161 (defun org-table-fedit-scroll-down (N)
11162 (interactive "p")
11163 (org-table-fedit-scroll (- N)))
11165 (defvar org-table-rectangle-overlays nil)
11167 (defun org-table-add-rectangle-overlay (beg end &optional face)
11168 "Add a new overlay."
11169 (let ((ov (org-make-overlay beg end)))
11170 (org-overlay-put ov 'face (or face 'secondary-selection))
11171 (push ov org-table-rectangle-overlays)))
11173 (defun org-table-highlight-rectangle (&optional beg end face)
11174 "Highlight rectangular region in a table."
11175 (setq beg (or beg (point)) end (or end (point)))
11176 (let ((b (min beg end))
11177 (e (max beg end))
11178 l1 c1 l2 c2 tmp)
11179 (and (boundp 'org-show-positions)
11180 (setq org-show-positions (cons b (cons e org-show-positions))))
11181 (goto-char (min beg end))
11182 (setq l1 (org-current-line)
11183 c1 (org-table-current-column))
11184 (goto-char (max beg end))
11185 (setq l2 (org-current-line)
11186 c2 (org-table-current-column))
11187 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11188 (goto-line l1)
11189 (beginning-of-line 1)
11190 (loop for line from l1 to l2 do
11191 (when (looking-at org-table-dataline-regexp)
11192 (org-table-goto-column c1)
11193 (skip-chars-backward "^|\n") (setq beg (point))
11194 (org-table-goto-column c2)
11195 (skip-chars-forward "^|\n") (setq end (point))
11196 (org-table-add-rectangle-overlay beg end face))
11197 (beginning-of-line 2))
11198 (goto-char b))
11199 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11201 (defun org-table-remove-rectangle-highlight (&rest ignore)
11202 "Remove the rectangle overlays."
11203 (unless org-inhibit-highlight-removal
11204 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11205 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11206 (setq org-table-rectangle-overlays nil)))
11208 (defvar org-table-coordinate-overlays nil
11209 "Collects the cooordinate grid overlays, so that they can be removed.")
11210 (make-variable-buffer-local 'org-table-coordinate-overlays)
11212 (defun org-table-overlay-coordinates ()
11213 "Add overlays to the table at point, to show row/column coordinates."
11214 (interactive)
11215 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11216 (setq org-table-coordinate-overlays nil)
11217 (save-excursion
11218 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11219 (goto-char (org-table-begin))
11220 (while (org-at-table-p)
11221 (setq eol (point-at-eol))
11222 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11223 (push ov org-table-coordinate-overlays)
11224 (setq hline (looking-at org-table-hline-regexp))
11225 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11226 (format "%4d" (setq id (1+ id)))))
11227 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11228 (when hline
11229 (setq ic 0)
11230 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11231 (setq beg (1+ (match-beginning 0))
11232 ic (1+ ic)
11233 s1 (concat "$" (int-to-string ic))
11234 s2 (org-number-to-letters ic)
11235 str (if (eq org-table-use-standard-references t) s2 s1))
11236 (setq ov (org-make-overlay beg (+ beg (length str))))
11237 (push ov org-table-coordinate-overlays)
11238 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11239 (beginning-of-line 2)))))
11241 (defun org-table-toggle-coordinate-overlays ()
11242 "Toggle the display of Row/Column numbers in tables."
11243 (interactive)
11244 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11245 (message "Row/Column number display turned %s"
11246 (if org-table-overlay-coordinates "on" "off"))
11247 (if (and (org-at-table-p) org-table-overlay-coordinates)
11248 (org-table-align))
11249 (unless org-table-overlay-coordinates
11250 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11251 (setq org-table-coordinate-overlays nil)))
11253 (defun org-table-toggle-formula-debugger ()
11254 "Toggle the formula debugger in tables."
11255 (interactive)
11256 (setq org-table-formula-debug (not org-table-formula-debug))
11257 (message "Formula debugging has been turned %s"
11258 (if org-table-formula-debug "on" "off")))
11260 ;;; The orgtbl minor mode
11262 ;; Define a minor mode which can be used in other modes in order to
11263 ;; integrate the org-mode table editor.
11265 ;; This is really a hack, because the org-mode table editor uses several
11266 ;; keys which normally belong to the major mode, for example the TAB and
11267 ;; RET keys. Here is how it works: The minor mode defines all the keys
11268 ;; necessary to operate the table editor, but wraps the commands into a
11269 ;; function which tests if the cursor is currently inside a table. If that
11270 ;; is the case, the table editor command is executed. However, when any of
11271 ;; those keys is used outside a table, the function uses `key-binding' to
11272 ;; look up if the key has an associated command in another currently active
11273 ;; keymap (minor modes, major mode, global), and executes that command.
11274 ;; There might be problems if any of the keys used by the table editor is
11275 ;; otherwise used as a prefix key.
11277 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11278 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11279 ;; addresses this by checking explicitly for both bindings.
11281 ;; The optimized version (see variable `orgtbl-optimized') takes over
11282 ;; all keys which are bound to `self-insert-command' in the *global map*.
11283 ;; Some modes bind other commands to simple characters, for example
11284 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11285 ;; active, this binding is ignored inside tables and replaced with a
11286 ;; modified self-insert.
11288 (defvar orgtbl-mode nil
11289 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11290 table editor in arbitrary modes.")
11291 (make-variable-buffer-local 'orgtbl-mode)
11293 (defvar orgtbl-mode-map (make-keymap)
11294 "Keymap for `orgtbl-mode'.")
11296 ;;;###autoload
11297 (defun turn-on-orgtbl ()
11298 "Unconditionally turn on `orgtbl-mode'."
11299 (orgtbl-mode 1))
11301 (defvar org-old-auto-fill-inhibit-regexp nil
11302 "Local variable used by `orgtbl-mode'")
11304 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11305 "Matches a line belonging to an orgtbl.")
11307 (defconst orgtbl-extra-font-lock-keywords
11308 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11309 0 (quote 'org-table) 'prepend))
11310 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11312 ;;;###autoload
11313 (defun orgtbl-mode (&optional arg)
11314 "The `org-mode' table editor as a minor mode for use in other modes."
11315 (interactive)
11316 (if (org-mode-p)
11317 ;; Exit without error, in case some hook functions calls this
11318 ;; by accident in org-mode.
11319 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11320 (setq orgtbl-mode
11321 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11322 (if orgtbl-mode
11323 (progn
11324 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11325 ;; Make sure we are first in minor-mode-map-alist
11326 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11327 (and c (setq minor-mode-map-alist
11328 (cons c (delq c minor-mode-map-alist)))))
11329 (org-set-local (quote org-table-may-need-update) t)
11330 (org-add-hook 'before-change-functions 'org-before-change-function
11331 nil 'local)
11332 (org-set-local 'org-old-auto-fill-inhibit-regexp
11333 auto-fill-inhibit-regexp)
11334 (org-set-local 'auto-fill-inhibit-regexp
11335 (if auto-fill-inhibit-regexp
11336 (concat orgtbl-line-start-regexp "\\|"
11337 auto-fill-inhibit-regexp)
11338 orgtbl-line-start-regexp))
11339 (org-add-to-invisibility-spec '(org-cwidth))
11340 (when (fboundp 'font-lock-add-keywords)
11341 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11342 (org-restart-font-lock))
11343 (easy-menu-add orgtbl-mode-menu)
11344 (run-hooks 'orgtbl-mode-hook))
11345 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11346 (org-cleanup-narrow-column-properties)
11347 (org-remove-from-invisibility-spec '(org-cwidth))
11348 (remove-hook 'before-change-functions 'org-before-change-function t)
11349 (when (fboundp 'font-lock-remove-keywords)
11350 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11351 (org-restart-font-lock))
11352 (easy-menu-remove orgtbl-mode-menu)
11353 (force-mode-line-update 'all))))
11355 (defun org-cleanup-narrow-column-properties ()
11356 "Remove all properties related to narrow-column invisibility."
11357 (let ((s 1))
11358 (while (setq s (text-property-any s (point-max)
11359 'display org-narrow-column-arrow))
11360 (remove-text-properties s (1+ s) '(display t)))
11361 (setq s 1)
11362 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11363 (remove-text-properties s (1+ s) '(org-cwidth t)))
11364 (setq s 1)
11365 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11366 (remove-text-properties s (1+ s) '(invisible t)))))
11368 ;; Install it as a minor mode.
11369 (put 'orgtbl-mode :included t)
11370 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11371 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11373 (defun orgtbl-make-binding (fun n &rest keys)
11374 "Create a function for binding in the table minor mode.
11375 FUN is the command to call inside a table. N is used to create a unique
11376 command name. KEYS are keys that should be checked in for a command
11377 to execute outside of tables."
11378 (eval
11379 (list 'defun
11380 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11381 '(arg)
11382 (concat "In tables, run `" (symbol-name fun) "'.\n"
11383 "Outside of tables, run the binding of `"
11384 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11385 "'.")
11386 '(interactive "p")
11387 (list 'if
11388 '(org-at-table-p)
11389 (list 'call-interactively (list 'quote fun))
11390 (list 'let '(orgtbl-mode)
11391 (list 'call-interactively
11392 (append '(or)
11393 (mapcar (lambda (k)
11394 (list 'key-binding k))
11395 keys)
11396 '('orgtbl-error))))))))
11398 (defun orgtbl-error ()
11399 "Error when there is no default binding for a table key."
11400 (interactive)
11401 (error "This key has no function outside tables"))
11403 (defun orgtbl-setup ()
11404 "Setup orgtbl keymaps."
11405 (let ((nfunc 0)
11406 (bindings
11407 (list
11408 '([(meta shift left)] org-table-delete-column)
11409 '([(meta left)] org-table-move-column-left)
11410 '([(meta right)] org-table-move-column-right)
11411 '([(meta shift right)] org-table-insert-column)
11412 '([(meta shift up)] org-table-kill-row)
11413 '([(meta shift down)] org-table-insert-row)
11414 '([(meta up)] org-table-move-row-up)
11415 '([(meta down)] org-table-move-row-down)
11416 '("\C-c\C-w" org-table-cut-region)
11417 '("\C-c\M-w" org-table-copy-region)
11418 '("\C-c\C-y" org-table-paste-rectangle)
11419 '("\C-c-" org-table-insert-hline)
11420 '("\C-c}" org-table-toggle-coordinate-overlays)
11421 '("\C-c{" org-table-toggle-formula-debugger)
11422 '("\C-m" org-table-next-row)
11423 '([(shift return)] org-table-copy-down)
11424 '("\C-c\C-q" org-table-wrap-region)
11425 '("\C-c?" org-table-field-info)
11426 '("\C-c " org-table-blank-field)
11427 '("\C-c+" org-table-sum)
11428 '("\C-c=" org-table-eval-formula)
11429 '("\C-c'" org-table-edit-formulas)
11430 '("\C-c`" org-table-edit-field)
11431 '("\C-c*" org-table-recalculate)
11432 '("\C-c|" org-table-create-or-convert-from-region)
11433 '("\C-c^" org-table-sort-lines)
11434 '([(control ?#)] org-table-rotate-recalc-marks)))
11435 elt key fun cmd)
11436 (while (setq elt (pop bindings))
11437 (setq nfunc (1+ nfunc))
11438 (setq key (org-key (car elt))
11439 fun (nth 1 elt)
11440 cmd (orgtbl-make-binding fun nfunc key))
11441 (org-defkey orgtbl-mode-map key cmd))
11443 ;; Special treatment needed for TAB and RET
11444 (org-defkey orgtbl-mode-map [(return)]
11445 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11446 (org-defkey orgtbl-mode-map "\C-m"
11447 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11449 (org-defkey orgtbl-mode-map [(tab)]
11450 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11451 (org-defkey orgtbl-mode-map "\C-i"
11452 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11454 (org-defkey orgtbl-mode-map [(shift tab)]
11455 (orgtbl-make-binding 'org-table-previous-field 104
11456 [(shift tab)] [(tab)] "\C-i"))
11458 (org-defkey orgtbl-mode-map "\M-\C-m"
11459 (orgtbl-make-binding 'org-table-wrap-region 105
11460 "\M-\C-m" [(meta return)]))
11461 (org-defkey orgtbl-mode-map [(meta return)]
11462 (orgtbl-make-binding 'org-table-wrap-region 106
11463 [(meta return)] "\M-\C-m"))
11465 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11466 (when orgtbl-optimized
11467 ;; If the user wants maximum table support, we need to hijack
11468 ;; some standard editing functions
11469 (org-remap orgtbl-mode-map
11470 'self-insert-command 'orgtbl-self-insert-command
11471 'delete-char 'org-delete-char
11472 'delete-backward-char 'org-delete-backward-char)
11473 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11474 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11475 '("OrgTbl"
11476 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11477 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11478 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11479 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11480 "--"
11481 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11482 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11483 ["Copy Field from Above"
11484 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11485 "--"
11486 ("Column"
11487 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11488 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11489 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11490 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11491 ("Row"
11492 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11493 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11494 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11495 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11496 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11497 "--"
11498 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11499 ("Rectangle"
11500 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11501 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11502 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11503 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11504 "--"
11505 ("Radio tables"
11506 ["Insert table template" orgtbl-insert-radio-table
11507 (assq major-mode orgtbl-radio-table-templates)]
11508 ["Comment/uncomment table" orgtbl-toggle-comment t])
11509 "--"
11510 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11511 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11512 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11513 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11514 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11515 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11516 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11517 ["Sum Column/Rectangle" org-table-sum
11518 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11519 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11520 ["Debug Formulas"
11521 org-table-toggle-formula-debugger :active (org-at-table-p)
11522 :keys "C-c {"
11523 :style toggle :selected org-table-formula-debug]
11524 ["Show Col/Row Numbers"
11525 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11526 :keys "C-c }"
11527 :style toggle :selected org-table-overlay-coordinates]
11531 (defun orgtbl-ctrl-c-ctrl-c (arg)
11532 "If the cursor is inside a table, realign the table.
11533 It it is a table to be sent away to a receiver, do it.
11534 With prefix arg, also recompute table."
11535 (interactive "P")
11536 (let ((pos (point)) action)
11537 (save-excursion
11538 (beginning-of-line 1)
11539 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11540 ((looking-at "[ \t]*|") pos)
11541 ((looking-at "#\\+TBLFM:") 'recalc))))
11542 (cond
11543 ((integerp action)
11544 (goto-char action)
11545 (org-table-maybe-eval-formula)
11546 (if arg
11547 (call-interactively 'org-table-recalculate)
11548 (org-table-maybe-recalculate-line))
11549 (call-interactively 'org-table-align)
11550 (orgtbl-send-table 'maybe))
11551 ((eq action 'recalc)
11552 (save-excursion
11553 (beginning-of-line 1)
11554 (skip-chars-backward " \r\n\t")
11555 (if (org-at-table-p)
11556 (org-call-with-arg 'org-table-recalculate t))))
11557 (t (let (orgtbl-mode)
11558 (call-interactively (key-binding "\C-c\C-c")))))))
11560 (defun orgtbl-tab (arg)
11561 "Justification and field motion for `orgtbl-mode'."
11562 (interactive "P")
11563 (if arg (org-table-edit-field t)
11564 (org-table-justify-field-maybe)
11565 (org-table-next-field)))
11567 (defun orgtbl-ret ()
11568 "Justification and field motion for `orgtbl-mode'."
11569 (interactive)
11570 (org-table-justify-field-maybe)
11571 (org-table-next-row))
11573 (defun orgtbl-self-insert-command (N)
11574 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11575 If the cursor is in a table looking at whitespace, the whitespace is
11576 overwritten, and the table is not marked as requiring realignment."
11577 (interactive "p")
11578 (if (and (org-at-table-p)
11580 (and org-table-auto-blank-field
11581 (member last-command
11582 '(orgtbl-hijacker-command-100
11583 orgtbl-hijacker-command-101
11584 orgtbl-hijacker-command-102
11585 orgtbl-hijacker-command-103
11586 orgtbl-hijacker-command-104
11587 orgtbl-hijacker-command-105))
11588 (org-table-blank-field))
11590 (eq N 1)
11591 (looking-at "[^|\n]* +|"))
11592 (let (org-table-may-need-update)
11593 (goto-char (1- (match-end 0)))
11594 (delete-backward-char 1)
11595 (goto-char (match-beginning 0))
11596 (self-insert-command N))
11597 (setq org-table-may-need-update t)
11598 (let (orgtbl-mode)
11599 (call-interactively (key-binding (vector last-input-event))))))
11601 (defun org-force-self-insert (N)
11602 "Needed to enforce self-insert under remapping."
11603 (interactive "p")
11604 (self-insert-command N))
11606 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11607 "Regula expression matching exponentials as produced by calc.")
11609 (defvar org-table-clean-did-remove-column nil)
11611 (defun orgtbl-export (table target)
11612 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11613 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11614 org-table-last-alignment org-table-last-column-widths
11615 maxcol column)
11616 (if (not (fboundp func))
11617 (error "Cannot export orgtbl table to %s" target))
11618 (setq lines (org-table-clean-before-export lines))
11619 (setq table
11620 (mapcar
11621 (lambda (x)
11622 (if (string-match org-table-hline-regexp x)
11623 'hline
11624 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11625 lines))
11626 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11627 table)))
11628 (loop for i from (1- maxcol) downto 0 do
11629 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11630 (setq column (delq nil column))
11631 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11632 (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))
11633 (funcall func table nil)))
11635 (defun orgtbl-send-table (&optional maybe)
11636 "Send a tranformed version of this table to the receiver position.
11637 With argument MAYBE, fail quietly if no transformation is defined for
11638 this table."
11639 (interactive)
11640 (catch 'exit
11641 (unless (org-at-table-p) (error "Not at a table"))
11642 ;; when non-interactive, we assume align has just happened.
11643 (when (interactive-p) (org-table-align))
11644 (save-excursion
11645 (goto-char (org-table-begin))
11646 (beginning-of-line 0)
11647 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11648 (if maybe
11649 (throw 'exit nil)
11650 (error "Don't know how to transform this table."))))
11651 (let* ((name (match-string 1))
11653 (transform (intern (match-string 2)))
11654 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11655 (skip (plist-get params :skip))
11656 (skipcols (plist-get params :skipcols))
11657 (txt (buffer-substring-no-properties
11658 (org-table-begin) (org-table-end)))
11659 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11660 (lines (org-table-clean-before-export lines))
11661 (i0 (if org-table-clean-did-remove-column 2 1))
11662 (table (mapcar
11663 (lambda (x)
11664 (if (string-match org-table-hline-regexp x)
11665 'hline
11666 (org-remove-by-index
11667 (org-split-string (org-trim x) "\\s-*|\\s-*")
11668 skipcols i0)))
11669 lines))
11670 (fun (if (= i0 2) 'cdr 'identity))
11671 (org-table-last-alignment
11672 (org-remove-by-index (funcall fun org-table-last-alignment)
11673 skipcols i0))
11674 (org-table-last-column-widths
11675 (org-remove-by-index (funcall fun org-table-last-column-widths)
11676 skipcols i0)))
11678 (unless (fboundp transform)
11679 (error "No such transformation function %s" transform))
11680 (setq txt (funcall transform table params))
11681 ;; Find the insertion place
11682 (save-excursion
11683 (goto-char (point-min))
11684 (unless (re-search-forward
11685 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11686 (error "Don't know where to insert translated table"))
11687 (goto-char (match-beginning 0))
11688 (beginning-of-line 2)
11689 (setq beg (point))
11690 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11691 (error "Cannot find end of insertion region"))
11692 (beginning-of-line 1)
11693 (delete-region beg (point))
11694 (goto-char beg)
11695 (insert txt "\n"))
11696 (message "Table converted and installed at receiver location"))))
11698 (defun org-remove-by-index (list indices &optional i0)
11699 "Remove the elements in LIST with indices in INDICES.
11700 First element has index 0, or I0 if given."
11701 (if (not indices)
11702 list
11703 (if (integerp indices) (setq indices (list indices)))
11704 (setq i0 (1- (or i0 0)))
11705 (delq :rm (mapcar (lambda (x)
11706 (setq i0 (1+ i0))
11707 (if (memq i0 indices) :rm x))
11708 list))))
11710 (defun orgtbl-toggle-comment ()
11711 "Comment or uncomment the orgtbl at point."
11712 (interactive)
11713 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11714 (re2 (concat "^" orgtbl-line-start-regexp))
11715 (commented (save-excursion (beginning-of-line 1)
11716 (cond ((looking-at re1) t)
11717 ((looking-at re2) nil)
11718 (t (error "Not at an org table")))))
11719 (re (if commented re1 re2))
11720 beg end)
11721 (save-excursion
11722 (beginning-of-line 1)
11723 (while (looking-at re) (beginning-of-line 0))
11724 (beginning-of-line 2)
11725 (setq beg (point))
11726 (while (looking-at re) (beginning-of-line 2))
11727 (setq end (point)))
11728 (comment-region beg end (if commented '(4) nil))))
11730 (defun orgtbl-insert-radio-table ()
11731 "Insert a radio table template appropriate for this major mode."
11732 (interactive)
11733 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11734 (txt (nth 1 e))
11735 name pos)
11736 (unless e (error "No radio table setup defined for %s" major-mode))
11737 (setq name (read-string "Table name: "))
11738 (while (string-match "%n" txt)
11739 (setq txt (replace-match name t t txt)))
11740 (or (bolp) (insert "\n"))
11741 (setq pos (point))
11742 (insert txt)
11743 (goto-char pos)))
11745 (defun org-get-param (params header i sym &optional hsym)
11746 "Get parameter value for symbol SYM.
11747 If this is a header line, actually get the value for the symbol with an
11748 additional \"h\" inserted after the colon.
11749 If the value is a protperty list, get the element for the current column.
11750 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11751 (let ((val (plist-get params sym)))
11752 (and hsym header (setq val (or (plist-get params hsym) val)))
11753 (if (consp val) (plist-get val i) val)))
11755 (defun orgtbl-to-generic (table params)
11756 "Convert the orgtbl-mode TABLE to some other format.
11757 This generic routine can be used for many standard cases.
11758 TABLE is a list, each entry either the symbol `hline' for a horizontal
11759 separator line, or a list of fields for that line.
11760 PARAMS is a property list of parameters that can influence the conversion.
11761 For the generic converter, some parameters are obligatory: You need to
11762 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11763 :splice, you must have :tstart and :tend.
11765 Valid parameters are
11767 :tstart String to start the table. Ignored when :splice is t.
11768 :tend String to end the table. Ignored when :splice is t.
11770 :splice When set to t, return only table body lines, don't wrap
11771 them into :tstart and :tend. Default is nil.
11773 :hline String to be inserted on horizontal separation lines.
11774 May be nil to ignore hlines.
11776 :lstart String to start a new table line.
11777 :lend String to end a table line
11778 :sep Separator between two fields
11779 :lfmt Format for entire line, with enough %s to capture all fields.
11780 If this is present, :lstart, :lend, and :sep are ignored.
11781 :fmt A format to be used to wrap the field, should contain
11782 %s for the original field value. For example, to wrap
11783 everything in dollars, you could use :fmt \"$%s$\".
11784 This may also be a property list with column numbers and
11785 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11787 :hlstart :hlend :hlsep :hlfmt :hfmt
11788 Same as above, specific for the header lines in the table.
11789 All lines before the first hline are treated as header.
11790 If any of these is not present, the data line value is used.
11792 :efmt Use this format to print numbers with exponentials.
11793 The format should have %s twice for inserting mantissa
11794 and exponent, for example \"%s\\\\times10^{%s}\". This
11795 may also be a property list with column numbers and
11796 formats. :fmt will still be applied after :efmt.
11798 In addition to this, the parameters :skip and :skipcols are always handled
11799 directly by `orgtbl-send-table'. See manual."
11800 (interactive)
11801 (let* ((p params)
11802 (splicep (plist-get p :splice))
11803 (hline (plist-get p :hline))
11804 rtn line i fm efm lfmt h)
11806 ;; Do we have a header?
11807 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11808 (setq h t))
11810 ;; Put header
11811 (unless splicep
11812 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11814 ;; Now loop over all lines
11815 (while (setq line (pop table))
11816 (if (eq line 'hline)
11817 ;; A horizontal separator line
11818 (progn (if hline (push hline rtn))
11819 (setq h nil)) ; no longer in header
11820 ;; A normal line. Convert the fields, push line onto the result list
11821 (setq i 0)
11822 (setq line
11823 (mapcar
11824 (lambda (f)
11825 (setq i (1+ i)
11826 fm (org-get-param p h i :fmt :hfmt)
11827 efm (org-get-param p h i :efmt))
11828 (if (and efm (string-match orgtbl-exp-regexp f))
11829 (setq f (format
11830 efm (match-string 1 f) (match-string 2 f))))
11831 (if fm (setq f (format fm f)))
11833 line))
11834 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11835 (push (apply 'format lfmt line) rtn)
11836 (push (concat
11837 (org-get-param p h i :lstart :hlstart)
11838 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11839 (org-get-param p h i :lend :hlend))
11840 rtn))))
11842 (unless splicep
11843 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11845 (mapconcat 'identity (nreverse rtn) "\n")))
11847 (defun orgtbl-to-latex (table params)
11848 "Convert the orgtbl-mode TABLE to LaTeX.
11849 TABLE is a list, each entry either the symbol `hline' for a horizontal
11850 separator line, or a list of fields for that line.
11851 PARAMS is a property list of parameters that can influence the conversion.
11852 Supports all parameters from `orgtbl-to-generic'. Most important for
11853 LaTeX are:
11855 :splice When set to t, return only table body lines, don't wrap
11856 them into a tabular environment. Default is nil.
11858 :fmt A format to be used to wrap the field, should contain %s for the
11859 original field value. For example, to wrap everything in dollars,
11860 use :fmt \"$%s$\". This may also be a property list with column
11861 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11863 :efmt Format for transforming numbers with exponentials. The format
11864 should have %s twice for inserting mantissa and exponent, for
11865 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11866 This may also be a property list with column numbers and formats.
11868 The general parameters :skip and :skipcols have already been applied when
11869 this function is called."
11870 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11871 org-table-last-alignment ""))
11872 (params2
11873 (list
11874 :tstart (concat "\\begin{tabular}{" alignment "}")
11875 :tend "\\end{tabular}"
11876 :lstart "" :lend " \\\\" :sep " & "
11877 :efmt "%s\\,(%s)" :hline "\\hline")))
11878 (orgtbl-to-generic table (org-combine-plists params2 params))))
11880 (defun orgtbl-to-html (table params)
11881 "Convert the orgtbl-mode TABLE to LaTeX.
11882 TABLE is a list, each entry either the symbol `hline' for a horizontal
11883 separator line, or a list of fields for that line.
11884 PARAMS is a property list of parameters that can influence the conversion.
11885 Currently this function recognizes the following parameters:
11887 :splice When set to t, return only table body lines, don't wrap
11888 them into a <table> environment. Default is nil.
11890 The general parameters :skip and :skipcols have already been applied when
11891 this function is called. The function does *not* use `orgtbl-to-generic',
11892 so you cannot specify parameters for it."
11893 (let* ((splicep (plist-get params :splice))
11894 html)
11895 ;; Just call the formatter we already have
11896 ;; We need to make text lines for it, so put the fields back together.
11897 (setq html (org-format-org-table-html
11898 (mapcar
11899 (lambda (x)
11900 (if (eq x 'hline)
11901 "|----+----|"
11902 (concat "| " (mapconcat 'identity x " | ") " |")))
11903 table)
11904 splicep))
11905 (if (string-match "\n+\\'" html)
11906 (setq html (replace-match "" t t html)))
11907 html))
11909 (defun orgtbl-to-texinfo (table params)
11910 "Convert the orgtbl-mode TABLE to TeXInfo.
11911 TABLE is a list, each entry either the symbol `hline' for a horizontal
11912 separator line, or a list of fields for that line.
11913 PARAMS is a property list of parameters that can influence the conversion.
11914 Supports all parameters from `orgtbl-to-generic'. Most important for
11915 TeXInfo are:
11917 :splice nil/t When set to t, return only table body lines, don't wrap
11918 them into a multitable environment. Default is nil.
11920 :fmt fmt A format to be used to wrap the field, should contain
11921 %s for the original field value. For example, to wrap
11922 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11923 This may also be a property list with column numbers and
11924 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11926 :cf \"f1 f2..\" The column fractions for the table. By default these
11927 are computed automatically from the width of the columns
11928 under org-mode.
11930 The general parameters :skip and :skipcols have already been applied when
11931 this function is called."
11932 (let* ((total (float (apply '+ org-table-last-column-widths)))
11933 (colfrac (or (plist-get params :cf)
11934 (mapconcat
11935 (lambda (x) (format "%.3f" (/ (float x) total)))
11936 org-table-last-column-widths " ")))
11937 (params2
11938 (list
11939 :tstart (concat "@multitable @columnfractions " colfrac)
11940 :tend "@end multitable"
11941 :lstart "@item " :lend "" :sep " @tab "
11942 :hlstart "@headitem ")))
11943 (orgtbl-to-generic table (org-combine-plists params2 params))))
11945 ;;;; Link Stuff
11947 ;;; Link abbreviations
11949 (defun org-link-expand-abbrev (link)
11950 "Apply replacements as defined in `org-link-abbrev-alist."
11951 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11952 (let* ((key (match-string 1 link))
11953 (as (or (assoc key org-link-abbrev-alist-local)
11954 (assoc key org-link-abbrev-alist)))
11955 (tag (and (match-end 2) (match-string 3 link)))
11956 rpl)
11957 (if (not as)
11958 link
11959 (setq rpl (cdr as))
11960 (cond
11961 ((symbolp rpl) (funcall rpl tag))
11962 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11963 (t (concat rpl tag)))))
11964 link))
11966 ;;; Storing and inserting links
11968 (defvar org-insert-link-history nil
11969 "Minibuffer history for links inserted with `org-insert-link'.")
11971 (defvar org-stored-links nil
11972 "Contains the links stored with `org-store-link'.")
11974 (defvar org-store-link-plist nil
11975 "Plist with info about the most recently link created with `org-store-link'.")
11977 (defvar org-link-protocols nil
11978 "Link protocols added to Org-mode using `org-add-link-type'.")
11980 (defvar org-store-link-functions nil
11981 "List of functions that are called to create and store a link.
11982 Each function will be called in turn until one returns a non-nil
11983 value. Each function should check if it is responsible for creating
11984 this link (for example by looking at the major mode).
11985 If not, it must exit and return nil.
11986 If yes, it should return a non-nil value after a calling
11987 `org-store-link-props' with a list of properties and values.
11988 Special properties are:
11990 :type The link prefix. like \"http\". This must be given.
11991 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11992 This is obligatory as well.
11993 :description Optional default description for the second pair
11994 of brackets in an Org-mode link. The user can still change
11995 this when inserting this link into an Org-mode buffer.
11997 In addition to these, any additional properties can be specified
11998 and then used in remember templates.")
12000 (defun org-add-link-type (type &optional follow publish)
12001 "Add TYPE to the list of `org-link-types'.
12002 Re-compute all regular expressions depending on `org-link-types'
12003 FOLLOW and PUBLISH are two functions. Both take the link path as
12004 an argument.
12005 FOLLOW should do whatever is necessary to follow the link, for example
12006 to find a file or display a mail message.
12008 PUBLISH takes the path and retuns the string that should be used when
12009 this document is published. FIMXE: This is actually not yet implemented."
12010 (add-to-list 'org-link-types type t)
12011 (org-make-link-regexps)
12012 (add-to-list 'org-link-protocols
12013 (list type follow publish)))
12015 (defun org-add-agenda-custom-command (entry)
12016 "Replace or add a command in `org-agenda-custom-commands'.
12017 This is mostly for hacking and trying a new command - once the command
12018 works you probably want to add it to `org-agenda-custom-commands' for good."
12019 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12020 (if ass
12021 (setcdr ass (cdr entry))
12022 (push entry org-agenda-custom-commands))))
12024 ;;;###autoload
12025 (defun org-store-link (arg)
12026 "\\<org-mode-map>Store an org-link to the current location.
12027 This link is added to `org-stored-links' and can later be inserted
12028 into an org-buffer with \\[org-insert-link].
12030 For some link types, a prefix arg is interpreted:
12031 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12032 For file links, arg negates `org-context-in-file-links'."
12033 (interactive "P")
12034 (setq org-store-link-plist nil) ; reset
12035 (let (link cpltxt desc description search txt)
12036 (cond
12038 ((run-hook-with-args-until-success 'org-store-link-functions)
12039 (setq link (plist-get org-store-link-plist :link)
12040 desc (or (plist-get org-store-link-plist :description) link)))
12042 ((eq major-mode 'bbdb-mode)
12043 (let ((name (bbdb-record-name (bbdb-current-record)))
12044 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12045 (setq cpltxt (concat "bbdb:" (or name company))
12046 link (org-make-link cpltxt))
12047 (org-store-link-props :type "bbdb" :name name :company company)))
12049 ((eq major-mode 'Info-mode)
12050 (setq link (org-make-link "info:"
12051 (file-name-nondirectory Info-current-file)
12052 ":" Info-current-node))
12053 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12054 ":" Info-current-node))
12055 (org-store-link-props :type "info" :file Info-current-file
12056 :node Info-current-node))
12058 ((eq major-mode 'calendar-mode)
12059 (let ((cd (calendar-cursor-to-date)))
12060 (setq link
12061 (format-time-string
12062 (car org-time-stamp-formats)
12063 (apply 'encode-time
12064 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12065 nil nil nil))))
12066 (org-store-link-props :type "calendar" :date cd)))
12068 ((or (eq major-mode 'vm-summary-mode)
12069 (eq major-mode 'vm-presentation-mode))
12070 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12071 (vm-follow-summary-cursor)
12072 (save-excursion
12073 (vm-select-folder-buffer)
12074 (let* ((message (car vm-message-pointer))
12075 (folder buffer-file-name)
12076 (subject (vm-su-subject message))
12077 (to (vm-get-header-contents message "To"))
12078 (from (vm-get-header-contents message "From"))
12079 (message-id (vm-su-message-id message)))
12080 (org-store-link-props :type "vm" :from from :to to :subject subject
12081 :message-id message-id)
12082 (setq message-id (org-remove-angle-brackets message-id))
12083 (setq folder (abbreviate-file-name folder))
12084 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12085 folder)
12086 (setq folder (replace-match "" t t folder)))
12087 (setq cpltxt (org-email-link-description))
12088 (setq link (org-make-link "vm:" folder "#" message-id)))))
12090 ((eq major-mode 'wl-summary-mode)
12091 (let* ((msgnum (wl-summary-message-number))
12092 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12093 msgnum 'message-id))
12094 (wl-message-entity
12095 (if (fboundp 'elmo-message-entity)
12096 (elmo-message-entity
12097 wl-summary-buffer-elmo-folder msgnum)
12098 (elmo-msgdb-overview-get-entity
12099 msgnum (wl-summary-buffer-msgdb))))
12100 (from (wl-summary-line-from))
12101 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12102 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12103 (wl-summary-line-subject))))
12104 (org-store-link-props :type "wl" :from from :to to
12105 :subject subject :message-id message-id)
12106 (setq message-id (org-remove-angle-brackets message-id))
12107 (setq cpltxt (org-email-link-description))
12108 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12109 "#" message-id))))
12111 ((or (equal major-mode 'mh-folder-mode)
12112 (equal major-mode 'mh-show-mode))
12113 (let ((from (org-mhe-get-header "From:"))
12114 (to (org-mhe-get-header "To:"))
12115 (message-id (org-mhe-get-header "Message-Id:"))
12116 (subject (org-mhe-get-header "Subject:")))
12117 (org-store-link-props :type "mh" :from from :to to
12118 :subject subject :message-id message-id)
12119 (setq cpltxt (org-email-link-description))
12120 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12121 (org-remove-angle-brackets message-id)))))
12123 ((or (eq major-mode 'rmail-mode)
12124 (eq major-mode 'rmail-summary-mode))
12125 (save-window-excursion
12126 (save-restriction
12127 (when (eq major-mode 'rmail-summary-mode)
12128 (rmail-show-message rmail-current-message))
12129 (rmail-narrow-to-non-pruned-header)
12130 (let ((folder buffer-file-name)
12131 (message-id (mail-fetch-field "message-id"))
12132 (from (mail-fetch-field "from"))
12133 (to (mail-fetch-field "to"))
12134 (subject (mail-fetch-field "subject")))
12135 (org-store-link-props
12136 :type "rmail" :from from :to to
12137 :subject subject :message-id message-id)
12138 (setq message-id (org-remove-angle-brackets message-id))
12139 (setq cpltxt (org-email-link-description))
12140 (setq link (org-make-link "rmail:" folder "#" message-id)))
12141 (rmail-show-message rmail-current-message))))
12143 ((eq major-mode 'gnus-group-mode)
12144 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12145 (gnus-group-group-name)) ; version
12146 ((fboundp 'gnus-group-name)
12147 (gnus-group-name))
12148 (t "???"))))
12149 (unless group (error "Not on a group"))
12150 (org-store-link-props :type "gnus" :group group)
12151 (setq cpltxt (concat
12152 (if (org-xor arg org-usenet-links-prefer-google)
12153 "http://groups.google.com/groups?group="
12154 "gnus:")
12155 group)
12156 link (org-make-link cpltxt))))
12158 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12159 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12160 (let* ((group gnus-newsgroup-name)
12161 (article (gnus-summary-article-number))
12162 (header (gnus-summary-article-header article))
12163 (from (mail-header-from header))
12164 (message-id (mail-header-id header))
12165 (date (mail-header-date header))
12166 (subject (gnus-summary-subject-string)))
12167 (org-store-link-props :type "gnus" :from from :subject subject
12168 :message-id message-id :group group)
12169 (setq cpltxt (org-email-link-description))
12170 (if (org-xor arg org-usenet-links-prefer-google)
12171 (setq link
12172 (concat
12173 cpltxt "\n "
12174 (format "http://groups.google.com/groups?as_umsgid=%s"
12175 (org-fixup-message-id-for-http message-id))))
12176 (setq link (org-make-link "gnus:" group
12177 "#" (number-to-string article))))))
12179 ((eq major-mode 'w3-mode)
12180 (setq cpltxt (url-view-url t)
12181 link (org-make-link cpltxt))
12182 (org-store-link-props :type "w3" :url (url-view-url t)))
12184 ((eq major-mode 'w3m-mode)
12185 (setq cpltxt (or w3m-current-title w3m-current-url)
12186 link (org-make-link w3m-current-url))
12187 (org-store-link-props :type "w3m" :url (url-view-url t)))
12189 ((setq search (run-hook-with-args-until-success
12190 'org-create-file-search-functions))
12191 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12192 "::" search))
12193 (setq cpltxt (or description link)))
12195 ((eq major-mode 'image-mode)
12196 (setq cpltxt (concat "file:"
12197 (abbreviate-file-name buffer-file-name))
12198 link (org-make-link cpltxt))
12199 (org-store-link-props :type "image" :file buffer-file-name))
12201 ((eq major-mode 'dired-mode)
12202 ;; link to the file in the current line
12203 (setq cpltxt (concat "file:"
12204 (abbreviate-file-name
12205 (expand-file-name
12206 (dired-get-filename nil t))))
12207 link (org-make-link cpltxt)))
12209 ((and buffer-file-name (org-mode-p))
12210 ;; Just link to current headline
12211 (setq cpltxt (concat "file:"
12212 (abbreviate-file-name buffer-file-name)))
12213 ;; Add a context search string
12214 (when (org-xor org-context-in-file-links arg)
12215 ;; Check if we are on a target
12216 (if (org-in-regexp "<<\\(.*?\\)>>")
12217 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12218 (setq txt (cond
12219 ((org-on-heading-p) nil)
12220 ((org-region-active-p)
12221 (buffer-substring (region-beginning) (region-end)))
12222 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12223 (when (or (null txt) (string-match "\\S-" txt))
12224 (setq cpltxt
12225 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12226 desc "NONE"))))
12227 (if (string-match "::\\'" cpltxt)
12228 (setq cpltxt (substring cpltxt 0 -2)))
12229 (setq link (org-make-link cpltxt)))
12231 ((buffer-file-name (buffer-base-buffer))
12232 ;; Just link to this file here.
12233 (setq cpltxt (concat "file:"
12234 (abbreviate-file-name
12235 (buffer-file-name (buffer-base-buffer)))))
12236 ;; Add a context string
12237 (when (org-xor org-context-in-file-links arg)
12238 (setq txt (if (org-region-active-p)
12239 (buffer-substring (region-beginning) (region-end))
12240 (buffer-substring (point-at-bol) (point-at-eol))))
12241 ;; Only use search option if there is some text.
12242 (when (string-match "\\S-" txt)
12243 (setq cpltxt
12244 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12245 desc "NONE")))
12246 (setq link (org-make-link cpltxt)))
12248 ((interactive-p)
12249 (error "Cannot link to a buffer which is not visiting a file"))
12251 (t (setq link nil)))
12253 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12254 (setq link (or link cpltxt)
12255 desc (or desc cpltxt))
12256 (if (equal desc "NONE") (setq desc nil))
12258 (if (and (interactive-p) link)
12259 (progn
12260 (setq org-stored-links
12261 (cons (list link desc) org-stored-links))
12262 (message "Stored: %s" (or desc link)))
12263 (and link (org-make-link-string link desc)))))
12265 (defun org-store-link-props (&rest plist)
12266 "Store link properties, extract names and addresses."
12267 (let (x adr)
12268 (when (setq x (plist-get plist :from))
12269 (setq adr (mail-extract-address-components x))
12270 (plist-put plist :fromname (car adr))
12271 (plist-put plist :fromaddress (nth 1 adr)))
12272 (when (setq x (plist-get plist :to))
12273 (setq adr (mail-extract-address-components x))
12274 (plist-put plist :toname (car adr))
12275 (plist-put plist :toaddress (nth 1 adr))))
12276 (let ((from (plist-get plist :from))
12277 (to (plist-get plist :to)))
12278 (when (and from to org-from-is-user-regexp)
12279 (plist-put plist :fromto
12280 (if (string-match org-from-is-user-regexp from)
12281 (concat "to %t")
12282 (concat "from %f")))))
12283 (setq org-store-link-plist plist))
12285 (defun org-email-link-description (&optional fmt)
12286 "Return the description part of an email link.
12287 This takes information from `org-store-link-plist' and formats it
12288 according to FMT (default from `org-email-link-description-format')."
12289 (setq fmt (or fmt org-email-link-description-format))
12290 (let* ((p org-store-link-plist)
12291 (to (plist-get p :toaddress))
12292 (from (plist-get p :fromaddress))
12293 (table
12294 (list
12295 (cons "%c" (plist-get p :fromto))
12296 (cons "%F" (plist-get p :from))
12297 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12298 (cons "%T" (plist-get p :to))
12299 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12300 (cons "%s" (plist-get p :subject))
12301 (cons "%m" (plist-get p :message-id)))))
12302 (when (string-match "%c" fmt)
12303 ;; Check if the user wrote this message
12304 (if (and org-from-is-user-regexp from to
12305 (save-match-data (string-match org-from-is-user-regexp from)))
12306 (setq fmt (replace-match "to %t" t t fmt))
12307 (setq fmt (replace-match "from %f" t t fmt))))
12308 (org-replace-escapes fmt table)))
12310 (defun org-make-org-heading-search-string (&optional string heading)
12311 "Make search string for STRING or current headline."
12312 (interactive)
12313 (let ((s (or string (org-get-heading))))
12314 (unless (and string (not heading))
12315 ;; We are using a headline, clean up garbage in there.
12316 (if (string-match org-todo-regexp s)
12317 (setq s (replace-match "" t t s)))
12318 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12319 (setq s (replace-match "" t t s)))
12320 (setq s (org-trim s))
12321 (if (string-match (concat "^\\(" org-quote-string "\\|"
12322 org-comment-string "\\)") s)
12323 (setq s (replace-match "" t t s)))
12324 (while (string-match org-ts-regexp s)
12325 (setq s (replace-match "" t t s))))
12326 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12327 (setq s (replace-match " " t t s)))
12328 (or string (setq s (concat "*" s))) ; Add * for headlines
12329 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12331 (defun org-make-link (&rest strings)
12332 "Concatenate STRINGS."
12333 (apply 'concat strings))
12335 (defun org-make-link-string (link &optional description)
12336 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12337 (unless (string-match "\\S-" link)
12338 (error "Empty link"))
12339 (when (stringp description)
12340 ;; Remove brackets from the description, they are fatal.
12341 (while (string-match "\\[" description)
12342 (setq description (replace-match "{" t t description)))
12343 (while (string-match "\\]" description)
12344 (setq description (replace-match "}" t t description))))
12345 (when (equal (org-link-escape link) description)
12346 ;; No description needed, it is identical
12347 (setq description nil))
12348 (when (and (not description)
12349 (not (equal link (org-link-escape link))))
12350 (setq description link))
12351 (concat "[[" (org-link-escape link) "]"
12352 (if description (concat "[" description "]") "")
12353 "]"))
12355 (defconst org-link-escape-chars
12356 '((?\ . "%20")
12357 (?\[ . "%5B")
12358 (?\] . "%5D")
12359 (?\340 . "%E0") ; `a
12360 (?\342 . "%E2") ; ^a
12361 (?\347 . "%E7") ; ,c
12362 (?\350 . "%E8") ; `e
12363 (?\351 . "%E9") ; 'e
12364 (?\352 . "%EA") ; ^e
12365 (?\356 . "%EE") ; ^i
12366 (?\364 . "%F4") ; ^o
12367 (?\371 . "%F9") ; `u
12368 (?\373 . "%FB") ; ^u
12369 (?\; . "%3B")
12370 (?? . "%3F")
12371 (?= . "%3D")
12372 (?+ . "%2B")
12374 "Association list of escapes for some characters problematic in links.
12375 This is the list that is used for internal purposes.")
12377 (defconst org-link-escape-chars-browser
12378 '((?\ . "%20")) ; 32 for the SPC char
12379 "Association list of escapes for some characters problematic in links.
12380 This is the list that is used before handing over to the browser.")
12382 (defun org-link-escape (text &optional table)
12383 "Escape charaters in TEXT that are problematic for links."
12384 (setq table (or table org-link-escape-chars))
12385 (when text
12386 (let ((re (mapconcat (lambda (x) (regexp-quote
12387 (char-to-string (car x))))
12388 table "\\|")))
12389 (while (string-match re text)
12390 (setq text
12391 (replace-match
12392 (cdr (assoc (string-to-char (match-string 0 text))
12393 table))
12394 t t text)))
12395 text)))
12397 (defun org-link-unescape (text &optional table)
12398 "Reverse the action of `org-link-escape'."
12399 (setq table (or table org-link-escape-chars))
12400 (when text
12401 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12402 table "\\|")))
12403 (while (string-match re text)
12404 (setq text
12405 (replace-match
12406 (char-to-string (car (rassoc (match-string 0 text) table)))
12407 t t text)))
12408 text)))
12410 (defun org-xor (a b)
12411 "Exclusive or."
12412 (if a (not b) b))
12414 (defun org-get-header (header)
12415 "Find a header field in the current buffer."
12416 (save-excursion
12417 (goto-char (point-min))
12418 (let ((case-fold-search t) s)
12419 (cond
12420 ((eq header 'from)
12421 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12422 (setq s (match-string 1)))
12423 (while (string-match "\"" s)
12424 (setq s (replace-match "" t t s)))
12425 (if (string-match "[<(].*" s)
12426 (setq s (replace-match "" t t s))))
12427 ((eq header 'message-id)
12428 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12429 (setq s (match-string 1))))
12430 ((eq header 'subject)
12431 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12432 (setq s (match-string 1)))))
12433 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12434 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12435 s)))
12438 (defun org-fixup-message-id-for-http (s)
12439 "Replace special characters in a message id, so it can be used in an http query."
12440 (while (string-match "<" s)
12441 (setq s (replace-match "%3C" t t s)))
12442 (while (string-match ">" s)
12443 (setq s (replace-match "%3E" t t s)))
12444 (while (string-match "@" s)
12445 (setq s (replace-match "%40" t t s)))
12448 ;;;###autoload
12449 (defun org-insert-link-global ()
12450 "Insert a link like Org-mode does.
12451 This command can be called in any mode to insert a link in Org-mode syntax."
12452 (interactive)
12453 (org-run-like-in-org-mode 'org-insert-link))
12455 (defun org-insert-link (&optional complete-file)
12456 "Insert a link. At the prompt, enter the link.
12458 Completion can be used to select a link previously stored with
12459 `org-store-link'. When the empty string is entered (i.e. if you just
12460 press RET at the prompt), the link defaults to the most recently
12461 stored link. As SPC triggers completion in the minibuffer, you need to
12462 use M-SPC or C-q SPC to force the insertion of a space character.
12464 You will also be prompted for a description, and if one is given, it will
12465 be displayed in the buffer instead of the link.
12467 If there is already a link at point, this command will allow you to edit link
12468 and description parts.
12470 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12471 selected using completion. The path to the file will be relative to
12472 the current directory if the file is in the current directory or a
12473 subdirectory. Otherwise, the link will be the absolute path as
12474 completed in the minibuffer (i.e. normally ~/path/to/file).
12476 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12477 is in the current directory or below.
12478 With three \\[universal-argument] prefixes, negate the meaning of
12479 `org-keep-stored-link-after-insertion'."
12480 (interactive "P")
12481 (let* ((wcf (current-window-configuration))
12482 (region (if (org-region-active-p)
12483 (buffer-substring (region-beginning) (region-end))))
12484 (remove (and region (list (region-beginning) (region-end))))
12485 (desc region)
12486 tmphist ; byte-compile incorrectly complains about this
12487 link entry file)
12488 (cond
12489 ((org-in-regexp org-bracket-link-regexp 1)
12490 ;; We do have a link at point, and we are going to edit it.
12491 (setq remove (list (match-beginning 0) (match-end 0)))
12492 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12493 (setq link (read-string "Link: "
12494 (org-link-unescape
12495 (org-match-string-no-properties 1)))))
12496 ((or (org-in-regexp org-angle-link-re)
12497 (org-in-regexp org-plain-link-re))
12498 ;; Convert to bracket link
12499 (setq remove (list (match-beginning 0) (match-end 0))
12500 link (read-string "Link: "
12501 (org-remove-angle-brackets (match-string 0)))))
12502 ((equal complete-file '(4))
12503 ;; Completing read for file names.
12504 (setq file (read-file-name "File: "))
12505 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12506 (pwd1 (file-name-as-directory (abbreviate-file-name
12507 (expand-file-name ".")))))
12508 (cond
12509 ((equal complete-file '(16))
12510 (setq link (org-make-link
12511 "file:"
12512 (abbreviate-file-name (expand-file-name file)))))
12513 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12514 (setq link (org-make-link "file:" (match-string 1 file))))
12515 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12516 (expand-file-name file))
12517 (setq link (org-make-link
12518 "file:" (match-string 1 (expand-file-name file)))))
12519 (t (setq link (org-make-link "file:" file))))))
12521 ;; Read link, with completion for stored links.
12522 (with-output-to-temp-buffer "*Org Links*"
12523 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12524 (when org-stored-links
12525 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12526 (princ (mapconcat
12527 (lambda (x)
12528 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12529 (reverse org-stored-links) "\n"))))
12530 (let ((cw (selected-window)))
12531 (select-window (get-buffer-window "*Org Links*"))
12532 (shrink-window-if-larger-than-buffer)
12533 (setq truncate-lines t)
12534 (select-window cw))
12535 ;; Fake a link history, containing the stored links.
12536 (setq tmphist (append (mapcar 'car org-stored-links)
12537 org-insert-link-history))
12538 (unwind-protect
12539 (setq link (org-completing-read
12540 "Link: "
12541 (append
12542 (mapcar (lambda (x) (list (concat (car x) ":")))
12543 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12544 (mapcar (lambda (x) (list (concat x ":")))
12545 org-link-types))
12546 nil nil nil
12547 'tmphist
12548 (or (car (car org-stored-links)))))
12549 (set-window-configuration wcf)
12550 (kill-buffer "*Org Links*"))
12551 (setq entry (assoc link org-stored-links))
12552 (or entry (push link org-insert-link-history))
12553 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12554 (not org-keep-stored-link-after-insertion))
12555 (setq org-stored-links (delq (assoc link org-stored-links)
12556 org-stored-links)))
12557 (setq desc (or desc (nth 1 entry)))))
12559 (if (string-match org-plain-link-re link)
12560 ;; URL-like link, normalize the use of angular brackets.
12561 (setq link (org-make-link (org-remove-angle-brackets link))))
12563 ;; Check if we are linking to the current file with a search option
12564 ;; If yes, simplify the link by using only the search option.
12565 (when (and buffer-file-name
12566 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12567 (let* ((path (match-string 1 link))
12568 (case-fold-search nil)
12569 (search (match-string 2 link)))
12570 (save-match-data
12571 (if (equal (file-truename buffer-file-name) (file-truename path))
12572 ;; We are linking to this same file, with a search option
12573 (setq link search)))))
12575 ;; Check if we can/should use a relative path. If yes, simplify the link
12576 (when (string-match "\\<file:\\(.*\\)" link)
12577 (let* ((path (match-string 1 link))
12578 (origpath path)
12579 (case-fold-search nil))
12580 (cond
12581 ((eq org-link-file-path-type 'absolute)
12582 (setq path (abbreviate-file-name (expand-file-name path))))
12583 ((eq org-link-file-path-type 'noabbrev)
12584 (setq path (expand-file-name path)))
12585 ((eq org-link-file-path-type 'relative)
12586 (setq path (file-relative-name path)))
12588 (save-match-data
12589 (if (string-match (concat "^" (regexp-quote
12590 (file-name-as-directory
12591 (expand-file-name "."))))
12592 (expand-file-name path))
12593 ;; We are linking a file with relative path name.
12594 (setq path (substring (expand-file-name path)
12595 (match-end 0)))))))
12596 (setq link (concat "file:" path))
12597 (if (equal desc origpath)
12598 (setq desc path))))
12600 (setq desc (read-string "Description: " desc))
12601 (unless (string-match "\\S-" desc) (setq desc nil))
12602 (if remove (apply 'delete-region remove))
12603 (insert (org-make-link-string link desc))))
12605 (defun org-completing-read (&rest args)
12606 (let ((minibuffer-local-completion-map
12607 (copy-keymap minibuffer-local-completion-map)))
12608 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12609 (apply 'completing-read args)))
12611 ;;; Opening/following a link
12612 (defvar org-link-search-failed nil)
12614 (defun org-next-link ()
12615 "Move forward to the next link.
12616 If the link is in hidden text, expose it."
12617 (interactive)
12618 (when (and org-link-search-failed (eq this-command last-command))
12619 (goto-char (point-min))
12620 (message "Link search wrapped back to beginning of buffer"))
12621 (setq org-link-search-failed nil)
12622 (let* ((pos (point))
12623 (ct (org-context))
12624 (a (assoc :link ct)))
12625 (if a (goto-char (nth 2 a)))
12626 (if (re-search-forward org-any-link-re nil t)
12627 (progn
12628 (goto-char (match-beginning 0))
12629 (if (org-invisible-p) (org-show-context)))
12630 (goto-char pos)
12631 (setq org-link-search-failed t)
12632 (error "No further link found"))))
12634 (defun org-previous-link ()
12635 "Move backward to the previous link.
12636 If the link is in hidden text, expose it."
12637 (interactive)
12638 (when (and org-link-search-failed (eq this-command last-command))
12639 (goto-char (point-max))
12640 (message "Link search wrapped back to end of buffer"))
12641 (setq org-link-search-failed nil)
12642 (let* ((pos (point))
12643 (ct (org-context))
12644 (a (assoc :link ct)))
12645 (if a (goto-char (nth 1 a)))
12646 (if (re-search-backward org-any-link-re nil t)
12647 (progn
12648 (goto-char (match-beginning 0))
12649 (if (org-invisible-p) (org-show-context)))
12650 (goto-char pos)
12651 (setq org-link-search-failed t)
12652 (error "No further link found"))))
12654 (defun org-find-file-at-mouse (ev)
12655 "Open file link or URL at mouse."
12656 (interactive "e")
12657 (mouse-set-point ev)
12658 (org-open-at-point 'in-emacs))
12660 (defun org-open-at-mouse (ev)
12661 "Open file link or URL at mouse."
12662 (interactive "e")
12663 (mouse-set-point ev)
12664 (org-open-at-point))
12666 (defvar org-window-config-before-follow-link nil
12667 "The window configuration before following a link.
12668 This is saved in case the need arises to restore it.")
12670 (defvar org-open-link-marker (make-marker)
12671 "Marker pointing to the location where `org-open-at-point; was called.")
12673 ;;;###autoload
12674 (defun org-open-at-point-global ()
12675 "Follow a link like Org-mode does.
12676 This command can be called in any mode to follow a link that has
12677 Org-mode syntax."
12678 (interactive)
12679 (org-run-like-in-org-mode 'org-open-at-point))
12681 (defun org-open-at-point (&optional in-emacs)
12682 "Open link at or after point.
12683 If there is no link at point, this function will search forward up to
12684 the end of the current subtree.
12685 Normally, files will be opened by an appropriate application. If the
12686 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12687 (interactive "P")
12688 (catch 'abort
12689 (move-marker org-open-link-marker (point))
12690 (setq org-window-config-before-follow-link (current-window-configuration))
12691 (org-remove-occur-highlights nil nil t)
12692 (if (org-at-timestamp-p t)
12693 (org-follow-timestamp-link)
12694 (let (type path link line search (pos (point)))
12695 (catch 'match
12696 (save-excursion
12697 (skip-chars-forward "^]\n\r")
12698 (when (org-in-regexp org-bracket-link-regexp)
12699 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12700 (while (string-match " *\n *" link)
12701 (setq link (replace-match " " t t link)))
12702 (setq link (org-link-expand-abbrev link))
12703 (if (string-match org-link-re-with-space2 link)
12704 (setq type (match-string 1 link) path (match-string 2 link))
12705 (setq type "thisfile" path link))
12706 (throw 'match t)))
12708 (when (get-text-property (point) 'org-linked-text)
12709 (setq type "thisfile"
12710 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12711 (1+ (point)) (point))
12712 path (buffer-substring
12713 (previous-single-property-change pos 'org-linked-text)
12714 (next-single-property-change pos 'org-linked-text)))
12715 (throw 'match t))
12717 (save-excursion
12718 (when (or (org-in-regexp org-angle-link-re)
12719 (org-in-regexp org-plain-link-re))
12720 (setq type (match-string 1) path (match-string 2))
12721 (throw 'match t)))
12722 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12723 (setq type "tree-match"
12724 path (match-string 1))
12725 (throw 'match t))
12726 (save-excursion
12727 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12728 (setq type "tags"
12729 path (match-string 1))
12730 (while (string-match ":" path)
12731 (setq path (replace-match "+" t t path)))
12732 (throw 'match t))))
12733 (unless path
12734 (error "No link found"))
12735 ;; Remove any trailing spaces in path
12736 (if (string-match " +\\'" path)
12737 (setq path (replace-match "" t t path)))
12739 (cond
12741 ((assoc type org-link-protocols)
12742 (funcall (nth 1 (assoc type org-link-protocols)) path))
12744 ((equal type "mailto")
12745 (let ((cmd (car org-link-mailto-program))
12746 (args (cdr org-link-mailto-program)) args1
12747 (address path) (subject "") a)
12748 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12749 (setq address (match-string 1 path)
12750 subject (org-link-escape (match-string 2 path))))
12751 (while args
12752 (cond
12753 ((not (stringp (car args))) (push (pop args) args1))
12754 (t (setq a (pop args))
12755 (if (string-match "%a" a)
12756 (setq a (replace-match address t t a)))
12757 (if (string-match "%s" a)
12758 (setq a (replace-match subject t t a)))
12759 (push a args1))))
12760 (apply cmd (nreverse args1))))
12762 ((member type '("http" "https" "ftp" "news"))
12763 (browse-url (concat type ":" (org-link-escape
12764 path org-link-escape-chars-browser))))
12766 ((member type '("message"))
12767 (browse-url (concat type ":" path)))
12769 ((string= type "tags")
12770 (org-tags-view in-emacs path))
12771 ((string= type "thisfile")
12772 (if in-emacs
12773 (switch-to-buffer-other-window
12774 (org-get-buffer-for-internal-link (current-buffer)))
12775 (org-mark-ring-push))
12776 (let ((cmd `(org-link-search
12777 ,path
12778 ,(cond ((equal in-emacs '(4)) 'occur)
12779 ((equal in-emacs '(16)) 'org-occur)
12780 (t nil))
12781 ,pos)))
12782 (condition-case nil (eval cmd)
12783 (error (progn (widen) (eval cmd))))))
12785 ((string= type "tree-match")
12786 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12788 ((string= type "file")
12789 (if (string-match "::\\([0-9]+\\)\\'" path)
12790 (setq line (string-to-number (match-string 1 path))
12791 path (substring path 0 (match-beginning 0)))
12792 (if (string-match "::\\(.+\\)\\'" path)
12793 (setq search (match-string 1 path)
12794 path (substring path 0 (match-beginning 0)))))
12795 (if (string-match "[*?{]" (file-name-nondirectory path))
12796 (dired path)
12797 (org-open-file path in-emacs line search)))
12799 ((string= type "news")
12800 (org-follow-gnus-link path))
12802 ((string= type "bbdb")
12803 (org-follow-bbdb-link path))
12805 ((string= type "info")
12806 (org-follow-info-link path))
12808 ((string= type "gnus")
12809 (let (group article)
12810 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12811 (error "Error in Gnus link"))
12812 (setq group (match-string 1 path)
12813 article (match-string 3 path))
12814 (org-follow-gnus-link group article)))
12816 ((string= type "vm")
12817 (let (folder article)
12818 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12819 (error "Error in VM link"))
12820 (setq folder (match-string 1 path)
12821 article (match-string 3 path))
12822 ;; in-emacs is the prefix arg, will be interpreted as read-only
12823 (org-follow-vm-link folder article in-emacs)))
12825 ((string= type "wl")
12826 (let (folder article)
12827 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12828 (error "Error in Wanderlust link"))
12829 (setq folder (match-string 1 path)
12830 article (match-string 3 path))
12831 (org-follow-wl-link folder article)))
12833 ((string= type "mhe")
12834 (let (folder article)
12835 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12836 (error "Error in MHE link"))
12837 (setq folder (match-string 1 path)
12838 article (match-string 3 path))
12839 (org-follow-mhe-link folder article)))
12841 ((string= type "rmail")
12842 (let (folder article)
12843 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12844 (error "Error in RMAIL link"))
12845 (setq folder (match-string 1 path)
12846 article (match-string 3 path))
12847 (org-follow-rmail-link folder article)))
12849 ((string= type "shell")
12850 (let ((cmd path))
12851 (if (or (not org-confirm-shell-link-function)
12852 (funcall org-confirm-shell-link-function
12853 (format "Execute \"%s\" in shell? "
12854 (org-add-props cmd nil
12855 'face 'org-warning))))
12856 (progn
12857 (message "Executing %s" cmd)
12858 (shell-command cmd))
12859 (error "Abort"))))
12861 ((string= type "elisp")
12862 (let ((cmd path))
12863 (if (or (not org-confirm-elisp-link-function)
12864 (funcall org-confirm-elisp-link-function
12865 (format "Execute \"%s\" as elisp? "
12866 (org-add-props cmd nil
12867 'face 'org-warning))))
12868 (message "%s => %s" cmd (eval (read cmd)))
12869 (error "Abort"))))
12872 (browse-url-at-point)))))
12873 (move-marker org-open-link-marker nil)))
12875 ;;; File search
12877 (defvar org-create-file-search-functions nil
12878 "List of functions to construct the right search string for a file link.
12879 These functions are called in turn with point at the location to
12880 which the link should point.
12882 A function in the hook should first test if it would like to
12883 handle this file type, for example by checking the major-mode or
12884 the file extension. If it decides not to handle this file, it
12885 should just return nil to give other functions a chance. If it
12886 does handle the file, it must return the search string to be used
12887 when following the link. The search string will be part of the
12888 file link, given after a double colon, and `org-open-at-point'
12889 will automatically search for it. If special measures must be
12890 taken to make the search successful, another function should be
12891 added to the companion hook `org-execute-file-search-functions',
12892 which see.
12894 A function in this hook may also use `setq' to set the variable
12895 `description' to provide a suggestion for the descriptive text to
12896 be used for this link when it gets inserted into an Org-mode
12897 buffer with \\[org-insert-link].")
12899 (defvar org-execute-file-search-functions nil
12900 "List of functions to execute a file search triggered by a link.
12902 Functions added to this hook must accept a single argument, the
12903 search string that was part of the file link, the part after the
12904 double colon. The function must first check if it would like to
12905 handle this search, for example by checking the major-mode or the
12906 file extension. If it decides not to handle this search, it
12907 should just return nil to give other functions a chance. If it
12908 does handle the search, it must return a non-nil value to keep
12909 other functions from trying.
12911 Each function can access the current prefix argument through the
12912 variable `current-prefix-argument'. Note that a single prefix is
12913 used to force opening a link in Emacs, so it may be good to only
12914 use a numeric or double prefix to guide the search function.
12916 In case this is needed, a function in this hook can also restore
12917 the window configuration before `org-open-at-point' was called using:
12919 (set-window-configuration org-window-config-before-follow-link)")
12921 (defun org-link-search (s &optional type avoid-pos)
12922 "Search for a link search option.
12923 If S is surrounded by forward slashes, it is interpreted as a
12924 regular expression. In org-mode files, this will create an `org-occur'
12925 sparse tree. In ordinary files, `occur' will be used to list matches.
12926 If the current buffer is in `dired-mode', grep will be used to search
12927 in all files. If AVOID-POS is given, ignore matches near that position."
12928 (let ((case-fold-search t)
12929 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12930 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12931 (append '(("") (" ") ("\t") ("\n"))
12932 org-emphasis-alist)
12933 "\\|") "\\)"))
12934 (pos (point))
12935 (pre "") (post "")
12936 words re0 re1 re2 re3 re4 re5 re2a reall)
12937 (cond
12938 ;; First check if there are any special
12939 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12940 ;; Now try the builtin stuff
12941 ((save-excursion
12942 (goto-char (point-min))
12943 (and
12944 (re-search-forward
12945 (concat "<<" (regexp-quote s0) ">>") nil t)
12946 (setq pos (match-beginning 0))))
12947 ;; There is an exact target for this
12948 (goto-char pos))
12949 ((string-match "^/\\(.*\\)/$" s)
12950 ;; A regular expression
12951 (cond
12952 ((org-mode-p)
12953 (org-occur (match-string 1 s)))
12954 ;;((eq major-mode 'dired-mode)
12955 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12956 (t (org-do-occur (match-string 1 s)))))
12958 ;; A normal search strings
12959 (when (equal (string-to-char s) ?*)
12960 ;; Anchor on headlines, post may include tags.
12961 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12962 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12963 s (substring s 1)))
12964 (remove-text-properties
12965 0 (length s)
12966 '(face nil mouse-face nil keymap nil fontified nil) s)
12967 ;; Make a series of regular expressions to find a match
12968 (setq words (org-split-string s "[ \n\r\t]+")
12969 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12970 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12971 "\\)" markers)
12972 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12973 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12974 re1 (concat pre re2 post)
12975 re3 (concat pre re4 post)
12976 re5 (concat pre ".*" re4)
12977 re2 (concat pre re2)
12978 re2a (concat pre re2a)
12979 re4 (concat pre re4)
12980 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12981 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12982 re5 "\\)"
12984 (cond
12985 ((eq type 'org-occur) (org-occur reall))
12986 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12987 (t (goto-char (point-min))
12988 (if (or (org-search-not-self 1 re0 nil t)
12989 (org-search-not-self 1 re1 nil t)
12990 (org-search-not-self 1 re2 nil t)
12991 (org-search-not-self 1 re2a nil t)
12992 (org-search-not-self 1 re3 nil t)
12993 (org-search-not-self 1 re4 nil t)
12994 (org-search-not-self 1 re5 nil t)
12996 (goto-char (match-beginning 1))
12997 (goto-char pos)
12998 (error "No match")))))
13000 ;; Normal string-search
13001 (goto-char (point-min))
13002 (if (search-forward s nil t)
13003 (goto-char (match-beginning 0))
13004 (error "No match"))))
13005 (and (org-mode-p) (org-show-context 'link-search))))
13007 (defun org-search-not-self (group &rest args)
13008 "Execute `re-search-forward', but only accept matches that do not
13009 enclose the position of `org-open-link-marker'."
13010 (let ((m org-open-link-marker))
13011 (catch 'exit
13012 (while (apply 're-search-forward args)
13013 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13014 (goto-char (match-end group))
13015 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13016 (> (match-beginning 0) (marker-position m))
13017 (< (match-end 0) (marker-position m)))
13018 (save-match-data
13019 (or (not (org-in-regexp
13020 org-bracket-link-analytic-regexp 1))
13021 (not (match-end 4)) ; no description
13022 (and (<= (match-beginning 4) (point))
13023 (>= (match-end 4) (point))))))
13024 (throw 'exit (point))))))))
13026 (defun org-get-buffer-for-internal-link (buffer)
13027 "Return a buffer to be used for displaying the link target of internal links."
13028 (cond
13029 ((not org-display-internal-link-with-indirect-buffer)
13030 buffer)
13031 ((string-match "(Clone)$" (buffer-name buffer))
13032 (message "Buffer is already a clone, not making another one")
13033 ;; we also do not modify visibility in this case
13034 buffer)
13035 (t ; make a new indirect buffer for displaying the link
13036 (let* ((bn (buffer-name buffer))
13037 (ibn (concat bn "(Clone)"))
13038 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13039 (with-current-buffer ib (org-overview))
13040 ib))))
13042 (defun org-do-occur (regexp &optional cleanup)
13043 "Call the Emacs command `occur'.
13044 If CLEANUP is non-nil, remove the printout of the regular expression
13045 in the *Occur* buffer. This is useful if the regex is long and not useful
13046 to read."
13047 (occur regexp)
13048 (when cleanup
13049 (let ((cwin (selected-window)) win beg end)
13050 (when (setq win (get-buffer-window "*Occur*"))
13051 (select-window win))
13052 (goto-char (point-min))
13053 (when (re-search-forward "match[a-z]+" nil t)
13054 (setq beg (match-end 0))
13055 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13056 (setq end (1- (match-beginning 0)))))
13057 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13058 (goto-char (point-min))
13059 (select-window cwin))))
13061 ;;; The mark ring for links jumps
13063 (defvar org-mark-ring nil
13064 "Mark ring for positions before jumps in Org-mode.")
13065 (defvar org-mark-ring-last-goto nil
13066 "Last position in the mark ring used to go back.")
13067 ;; Fill and close the ring
13068 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13069 (loop for i from 1 to org-mark-ring-length do
13070 (push (make-marker) org-mark-ring))
13071 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13072 org-mark-ring)
13074 (defun org-mark-ring-push (&optional pos buffer)
13075 "Put the current position or POS into the mark ring and rotate it."
13076 (interactive)
13077 (setq pos (or pos (point)))
13078 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13079 (move-marker (car org-mark-ring)
13080 (or pos (point))
13081 (or buffer (current-buffer)))
13082 (message "%s"
13083 (substitute-command-keys
13084 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13086 (defun org-mark-ring-goto (&optional n)
13087 "Jump to the previous position in the mark ring.
13088 With prefix arg N, jump back that many stored positions. When
13089 called several times in succession, walk through the entire ring.
13090 Org-mode commands jumping to a different position in the current file,
13091 or to another Org-mode file, automatically push the old position
13092 onto the ring."
13093 (interactive "p")
13094 (let (p m)
13095 (if (eq last-command this-command)
13096 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13097 (setq p org-mark-ring))
13098 (setq org-mark-ring-last-goto p)
13099 (setq m (car p))
13100 (switch-to-buffer (marker-buffer m))
13101 (goto-char m)
13102 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13104 (defun org-remove-angle-brackets (s)
13105 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13106 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13108 (defun org-add-angle-brackets (s)
13109 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13110 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13113 ;;; Following specific links
13115 (defun org-follow-timestamp-link ()
13116 (cond
13117 ((org-at-date-range-p t)
13118 (let ((org-agenda-start-on-weekday)
13119 (t1 (match-string 1))
13120 (t2 (match-string 2)))
13121 (setq t1 (time-to-days (org-time-string-to-time t1))
13122 t2 (time-to-days (org-time-string-to-time t2)))
13123 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13124 ((org-at-timestamp-p t)
13125 (org-agenda-list nil (time-to-days (org-time-string-to-time
13126 (substring (match-string 1) 0 10)))
13128 (t (error "This should not happen"))))
13131 (defun org-follow-bbdb-link (name)
13132 "Follow a BBDB link to NAME."
13133 (require 'bbdb)
13134 (let ((inhibit-redisplay (not debug-on-error))
13135 (bbdb-electric-p nil))
13136 (catch 'exit
13137 ;; Exact match on name
13138 (bbdb-name (concat "\\`" name "\\'") nil)
13139 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13140 ;; Exact match on name
13141 (bbdb-company (concat "\\`" name "\\'") nil)
13142 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13143 ;; Partial match on name
13144 (bbdb-name name nil)
13145 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13146 ;; Partial match on company
13147 (bbdb-company name nil)
13148 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13149 ;; General match including network address and notes
13150 (bbdb name nil)
13151 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13152 (delete-window (get-buffer-window "*BBDB*"))
13153 (error "No matching BBDB record")))))
13155 (defun org-follow-info-link (name)
13156 "Follow an info file & node link to NAME."
13157 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13158 (string-match "\\(.*\\)" name))
13159 (progn
13160 (require 'info)
13161 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13162 (Info-find-node (match-string 1 name) (match-string 2 name))
13163 (Info-find-node (match-string 1 name) "Top")))
13164 (message "Could not open: %s" name)))
13166 (defun org-follow-gnus-link (&optional group article)
13167 "Follow a Gnus link to GROUP and ARTICLE."
13168 (require 'gnus)
13169 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13170 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13171 (cond ((and group article)
13172 (gnus-group-read-group 1 nil group)
13173 (gnus-summary-goto-article (string-to-number article) nil t))
13174 (group (gnus-group-jump-to-group group))))
13176 (defun org-follow-vm-link (&optional folder article readonly)
13177 "Follow a VM link to FOLDER and ARTICLE."
13178 (require 'vm)
13179 (setq article (org-add-angle-brackets article))
13180 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13181 ;; ange-ftp or efs or tramp access
13182 (let ((user (or (match-string 1 folder) (user-login-name)))
13183 (host (match-string 2 folder))
13184 (file (match-string 3 folder)))
13185 (cond
13186 ((featurep 'tramp)
13187 ;; use tramp to access the file
13188 (if (featurep 'xemacs)
13189 (setq folder (format "[%s@%s]%s" user host file))
13190 (setq folder (format "/%s@%s:%s" user host file))))
13192 ;; use ange-ftp or efs
13193 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13194 (setq folder (format "/%s@%s:%s" user host file))))))
13195 (when folder
13196 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13197 (sit-for 0.1)
13198 (when article
13199 (vm-select-folder-buffer)
13200 (widen)
13201 (let ((case-fold-search t))
13202 (goto-char (point-min))
13203 (if (not (re-search-forward
13204 (concat "^" "message-id: *" (regexp-quote article))))
13205 (error "Could not find the specified message in this folder"))
13206 (vm-isearch-update)
13207 (vm-isearch-narrow)
13208 (vm-beginning-of-message)
13209 (vm-summarize)))))
13211 (defun org-follow-wl-link (folder article)
13212 "Follow a Wanderlust link to FOLDER and ARTICLE."
13213 (if (and (string= folder "%")
13214 article
13215 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13216 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13217 ;; Thus, we recompose folder and article ids.
13218 (setq folder (format "%s#%s" folder (match-string 1 article))
13219 article (match-string 3 article)))
13220 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13221 (error "No such folder: %s" folder))
13222 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13223 (and article
13224 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13225 (wl-summary-redisplay)))
13227 (defun org-follow-rmail-link (folder article)
13228 "Follow an RMAIL link to FOLDER and ARTICLE."
13229 (setq article (org-add-angle-brackets article))
13230 (let (message-number)
13231 (save-excursion
13232 (save-window-excursion
13233 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13234 (setq message-number
13235 (save-restriction
13236 (widen)
13237 (goto-char (point-max))
13238 (if (re-search-backward
13239 (concat "^Message-ID:\\s-+" (regexp-quote
13240 (or article "")))
13241 nil t)
13242 (rmail-what-message))))))
13243 (if message-number
13244 (progn
13245 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13246 (rmail-show-message message-number)
13247 message-number)
13248 (error "Message not found"))))
13250 ;;; mh-e integration based on planner-mode
13251 (defun org-mhe-get-message-real-folder ()
13252 "Return the name of the current message real folder, so if you use
13253 sequences, it will now work."
13254 (save-excursion
13255 (let* ((folder
13256 (if (equal major-mode 'mh-folder-mode)
13257 mh-current-folder
13258 ;; Refer to the show buffer
13259 mh-show-folder-buffer))
13260 (end-index
13261 (if (boundp 'mh-index-folder)
13262 (min (length mh-index-folder) (length folder))))
13264 ;; a simple test on mh-index-data does not work, because
13265 ;; mh-index-data is always nil in a show buffer.
13266 (if (and (boundp 'mh-index-folder)
13267 (string= mh-index-folder (substring folder 0 end-index)))
13268 (if (equal major-mode 'mh-show-mode)
13269 (save-window-excursion
13270 (let (pop-up-frames)
13271 (when (buffer-live-p (get-buffer folder))
13272 (progn
13273 (pop-to-buffer folder)
13274 (org-mhe-get-message-folder-from-index)
13277 (org-mhe-get-message-folder-from-index)
13279 folder
13283 (defun org-mhe-get-message-folder-from-index ()
13284 "Returns the name of the message folder in a index folder buffer."
13285 (save-excursion
13286 (mh-index-previous-folder)
13287 (re-search-forward "^\\(+.*\\)$" nil t)
13288 (message "%s" (match-string 1))))
13290 (defun org-mhe-get-message-folder ()
13291 "Return the name of the current message folder. Be careful if you
13292 use sequences."
13293 (save-excursion
13294 (if (equal major-mode 'mh-folder-mode)
13295 mh-current-folder
13296 ;; Refer to the show buffer
13297 mh-show-folder-buffer)))
13299 (defun org-mhe-get-message-num ()
13300 "Return the number of the current message. Be careful if you
13301 use sequences."
13302 (save-excursion
13303 (if (equal major-mode 'mh-folder-mode)
13304 (mh-get-msg-num nil)
13305 ;; Refer to the show buffer
13306 (mh-show-buffer-message-number))))
13308 (defun org-mhe-get-header (header)
13309 "Return a header of the message in folder mode. This will create a
13310 show buffer for the corresponding message. If you have a more clever
13311 idea..."
13312 (let* ((folder (org-mhe-get-message-folder))
13313 (num (org-mhe-get-message-num))
13314 (buffer (get-buffer-create (concat "show-" folder)))
13315 (header-field))
13316 (with-current-buffer buffer
13317 (mh-display-msg num folder)
13318 (if (equal major-mode 'mh-folder-mode)
13319 (mh-header-display)
13320 (mh-show-header-display))
13321 (set-buffer buffer)
13322 (setq header-field (mh-get-header-field header))
13323 (if (equal major-mode 'mh-folder-mode)
13324 (mh-show)
13325 (mh-show-show))
13326 header-field)))
13328 (defun org-follow-mhe-link (folder article)
13329 "Follow an MHE link to FOLDER and ARTICLE.
13330 If ARTICLE is nil FOLDER is shown. If the configuration variable
13331 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13332 ARTICLE is searched in all folders. Indexed searches (swish++,
13333 namazu, and others supported by MH-E) will always search in all
13334 folders."
13335 (require 'mh-e)
13336 (require 'mh-search)
13337 (require 'mh-utils)
13338 (mh-find-path)
13339 (if (not article)
13340 (mh-visit-folder (mh-normalize-folder-name folder))
13341 (setq article (org-add-angle-brackets article))
13342 (mh-search-choose)
13343 (if (equal mh-searcher 'pick)
13344 (progn
13345 (mh-search folder (list "--message-id" article))
13346 (when (and org-mhe-search-all-folders
13347 (not (org-mhe-get-message-real-folder)))
13348 (kill-this-buffer)
13349 (mh-search "+" (list "--message-id" article))))
13350 (mh-search "+" article))
13351 (if (org-mhe-get-message-real-folder)
13352 (mh-show-msg 1)
13353 (kill-this-buffer)
13354 (error "Message not found"))))
13356 ;;; BibTeX links
13358 ;; Use the custom search meachnism to construct and use search strings for
13359 ;; file links to BibTeX database entries.
13361 (defun org-create-file-search-in-bibtex ()
13362 "Create the search string and description for a BibTeX database entry."
13363 (when (eq major-mode 'bibtex-mode)
13364 ;; yes, we want to construct this search string.
13365 ;; Make a good description for this entry, using names, year and the title
13366 ;; Put it into the `description' variable which is dynamically scoped.
13367 (let ((bibtex-autokey-names 1)
13368 (bibtex-autokey-names-stretch 1)
13369 (bibtex-autokey-name-case-convert-function 'identity)
13370 (bibtex-autokey-name-separator " & ")
13371 (bibtex-autokey-additional-names " et al.")
13372 (bibtex-autokey-year-length 4)
13373 (bibtex-autokey-name-year-separator " ")
13374 (bibtex-autokey-titlewords 3)
13375 (bibtex-autokey-titleword-separator " ")
13376 (bibtex-autokey-titleword-case-convert-function 'identity)
13377 (bibtex-autokey-titleword-length 'infty)
13378 (bibtex-autokey-year-title-separator ": "))
13379 (setq description (bibtex-generate-autokey)))
13380 ;; Now parse the entry, get the key and return it.
13381 (save-excursion
13382 (bibtex-beginning-of-entry)
13383 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13385 (defun org-execute-file-search-in-bibtex (s)
13386 "Find the link search string S as a key for a database entry."
13387 (when (eq major-mode 'bibtex-mode)
13388 ;; Yes, we want to do the search in this file.
13389 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13390 (goto-char (point-min))
13391 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13392 (regexp-quote s) "[ \t\n]*,") nil t)
13393 (goto-char (match-beginning 0)))
13394 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13395 ;; Use double prefix to indicate that any web link should be browsed
13396 (let ((b (current-buffer)) (p (point)))
13397 ;; Restore the window configuration because we just use the web link
13398 (set-window-configuration org-window-config-before-follow-link)
13399 (save-excursion (set-buffer b) (goto-char p)
13400 (bibtex-url)))
13401 (recenter 0)) ; Move entry start to beginning of window
13402 ;; return t to indicate that the search is done.
13405 ;; Finally add the functions to the right hooks.
13406 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13407 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13409 ;; end of Bibtex link setup
13411 ;;; Following file links
13413 (defun org-open-file (path &optional in-emacs line search)
13414 "Open the file at PATH.
13415 First, this expands any special file name abbreviations. Then the
13416 configuration variable `org-file-apps' is checked if it contains an
13417 entry for this file type, and if yes, the corresponding command is launched.
13418 If no application is found, Emacs simply visits the file.
13419 With optional argument IN-EMACS, Emacs will visit the file.
13420 Optional LINE specifies a line to go to, optional SEARCH a string to
13421 search for. If LINE or SEARCH is given, the file will always be
13422 opened in Emacs.
13423 If the file does not exist, an error is thrown."
13424 (setq in-emacs (or in-emacs line search))
13425 (let* ((file (if (equal path "")
13426 buffer-file-name
13427 (substitute-in-file-name (expand-file-name path))))
13428 (apps (append org-file-apps (org-default-apps)))
13429 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13430 (dirp (if remp nil (file-directory-p file)))
13431 (dfile (downcase file))
13432 (old-buffer (current-buffer))
13433 (old-pos (point))
13434 (old-mode major-mode)
13435 ext cmd)
13436 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13437 (setq ext (match-string 1 dfile))
13438 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13439 (setq ext (match-string 1 dfile))))
13440 (if in-emacs
13441 (setq cmd 'emacs)
13442 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13443 (and dirp (cdr (assoc 'directory apps)))
13444 (cdr (assoc ext apps))
13445 (cdr (assoc t apps)))))
13446 (when (eq cmd 'mailcap)
13447 (require 'mailcap)
13448 (mailcap-parse-mailcaps)
13449 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13450 (command (mailcap-mime-info mime-type)))
13451 (if (stringp command)
13452 (setq cmd command)
13453 (setq cmd 'emacs))))
13454 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13455 (not (file-exists-p file))
13456 (not org-open-non-existing-files))
13457 (error "No such file: %s" file))
13458 (cond
13459 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13460 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13461 (while (string-match "['\"]%s['\"]" cmd)
13462 (setq cmd (replace-match "%s" t t cmd)))
13463 (while (string-match "%s" cmd)
13464 (setq cmd (replace-match
13465 (save-match-data (shell-quote-argument file))
13466 t t cmd)))
13467 (save-window-excursion
13468 (start-process-shell-command cmd nil cmd)))
13469 ((or (stringp cmd)
13470 (eq cmd 'emacs))
13471 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13472 (widen)
13473 (if line (goto-line line)
13474 (if search (org-link-search search))))
13475 ((consp cmd)
13476 (eval cmd))
13477 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13478 (and (org-mode-p) (eq old-mode 'org-mode)
13479 (or (not (equal old-buffer (current-buffer)))
13480 (not (equal old-pos (point))))
13481 (org-mark-ring-push old-pos old-buffer))))
13483 (defun org-default-apps ()
13484 "Return the default applications for this operating system."
13485 (cond
13486 ((eq system-type 'darwin)
13487 org-file-apps-defaults-macosx)
13488 ((eq system-type 'windows-nt)
13489 org-file-apps-defaults-windowsnt)
13490 (t org-file-apps-defaults-gnu)))
13492 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13493 (defun org-file-remote-p (file)
13494 "Test whether FILE specifies a location on a remote system.
13495 Return non-nil if the location is indeed remote.
13497 For example, the filename \"/user@host:/foo\" specifies a location
13498 on the system \"/user@host:\"."
13499 (cond ((fboundp 'file-remote-p)
13500 (file-remote-p file))
13501 ((fboundp 'tramp-handle-file-remote-p)
13502 (tramp-handle-file-remote-p file))
13503 ((and (boundp 'ange-ftp-name-format)
13504 (string-match (car ange-ftp-name-format) file))
13506 (t nil)))
13509 ;;;; Hooks for remember.el, and refiling
13511 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13512 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13514 ;;;###autoload
13515 (defun org-remember-insinuate ()
13516 "Setup remember.el for use wiht Org-mode."
13517 (require 'remember)
13518 (setq remember-annotation-functions '(org-remember-annotation))
13519 (setq remember-handler-functions '(org-remember-handler))
13520 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13522 ;;;###autoload
13523 (defun org-remember-annotation ()
13524 "Return a link to the current location as an annotation for remember.el.
13525 If you are using Org-mode files as target for data storage with
13526 remember.el, then the annotations should include a link compatible with the
13527 conventions in Org-mode. This function returns such a link."
13528 (org-store-link nil))
13530 (defconst org-remember-help
13531 "Select a destination location for the note.
13532 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13533 RET on headline -> Store as sublevel entry to current headline
13534 RET at beg-of-buf -> Append to file as level 2 headline
13535 <left>/<right> -> before/after current headline, same headings level")
13537 (defvar org-remember-previous-location nil)
13538 (defvar org-force-remember-template-char) ;; dynamically scoped
13540 (defun org-select-remember-template (&optional use-char)
13541 (when org-remember-templates
13542 (let* ((templates (mapcar (lambda (x)
13543 (if (stringp (car x))
13544 (append (list (nth 1 x) (car x)) (cddr x))
13545 (append (list (car x) "") (cdr x))))
13546 org-remember-templates))
13547 (char (or use-char
13548 (cond
13549 ((= (length templates) 1)
13550 (caar templates))
13551 ((and (boundp 'org-force-remember-template-char)
13552 org-force-remember-template-char)
13553 (if (stringp org-force-remember-template-char)
13554 (string-to-char org-force-remember-template-char)
13555 org-force-remember-template-char))
13557 (message "Select template: %s"
13558 (mapconcat
13559 (lambda (x)
13560 (cond
13561 ((not (string-match "\\S-" (nth 1 x)))
13562 (format "[%c]" (car x)))
13563 ((equal (downcase (car x))
13564 (downcase (aref (nth 1 x) 0)))
13565 (format "[%c]%s" (car x)
13566 (substring (nth 1 x) 1)))
13567 (t (format "[%c]%s" (car x) (nth 1 x)))))
13568 templates " "))
13569 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13570 (when (equal char0 ?\C-g)
13571 (jump-to-register remember-register)
13572 (kill-buffer remember-buffer))
13573 char0))))))
13574 (cddr (assoc char templates)))))
13576 (defvar x-last-selected-text)
13577 (defvar x-last-selected-text-primary)
13579 ;;;###autoload
13580 (defun org-remember-apply-template (&optional use-char skip-interactive)
13581 "Initialize *remember* buffer with template, invoke `org-mode'.
13582 This function should be placed into `remember-mode-hook' and in fact requires
13583 to be run from that hook to function properly."
13584 (if org-remember-templates
13585 (let* ((entry (org-select-remember-template use-char))
13586 (tpl (car entry))
13587 (plist-p (if org-store-link-plist t nil))
13588 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13589 (string-match "\\S-" (nth 1 entry)))
13590 (nth 1 entry)
13591 org-default-notes-file))
13592 (headline (nth 2 entry))
13593 (v-c (or (and (eq window-system 'x)
13594 (fboundp 'x-cut-buffer-or-selection-value)
13595 (x-cut-buffer-or-selection-value))
13596 (org-bound-and-true-p x-last-selected-text)
13597 (org-bound-and-true-p x-last-selected-text-primary)
13598 (and (> (length kill-ring) 0) (current-kill 0))))
13599 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13600 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13601 (v-u (concat "[" (substring v-t 1 -1) "]"))
13602 (v-U (concat "[" (substring v-T 1 -1) "]"))
13603 ;; `initial' and `annotation' are bound in `remember'
13604 (v-i (if (boundp 'initial) initial))
13605 (v-a (if (and (boundp 'annotation) annotation)
13606 (if (equal annotation "[[]]") "" annotation)
13607 ""))
13608 (v-A (if (and v-a
13609 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13610 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13611 v-a))
13612 (v-n user-full-name)
13613 (org-startup-folded nil)
13614 org-time-was-given org-end-time-was-given x
13615 prompt completions char time pos default histvar)
13616 (setq org-store-link-plist
13617 (append (list :annotation v-a :initial v-i)
13618 org-store-link-plist))
13619 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13620 (erase-buffer)
13621 (insert (substitute-command-keys
13622 (format
13623 "## Filing location: Select interactively, default, or last used:
13624 ## %s to select file and header location interactively.
13625 ## %s \"%s\" -> \"* %s\"
13626 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13627 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13628 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13629 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13630 (abbreviate-file-name (or file org-default-notes-file))
13631 (or headline "")
13632 (or (car org-remember-previous-location) "???")
13633 (or (cdr org-remember-previous-location) "???"))))
13634 (insert tpl) (goto-char (point-min))
13635 ;; Simple %-escapes
13636 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13637 (when (and initial (equal (match-string 0) "%i"))
13638 (save-match-data
13639 (let* ((lead (buffer-substring
13640 (point-at-bol) (match-beginning 0))))
13641 (setq v-i (mapconcat 'identity
13642 (org-split-string initial "\n")
13643 (concat "\n" lead))))))
13644 (replace-match
13645 (or (eval (intern (concat "v-" (match-string 1)))) "")
13646 t t))
13648 ;; %[] Insert contents of a file.
13649 (goto-char (point-min))
13650 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13651 (let ((start (match-beginning 0))
13652 (end (match-end 0))
13653 (filename (expand-file-name (match-string 1))))
13654 (goto-char start)
13655 (delete-region start end)
13656 (condition-case error
13657 (insert-file-contents filename)
13658 (error (insert (format "%%![Couldn't insert %s: %s]"
13659 filename error))))))
13660 ;; %() embedded elisp
13661 (goto-char (point-min))
13662 (while (re-search-forward "%\\((.+)\\)" nil t)
13663 (goto-char (match-beginning 0))
13664 (let ((template-start (point)))
13665 (forward-char 1)
13666 (let ((result
13667 (condition-case error
13668 (eval (read (current-buffer)))
13669 (error (format "%%![Error: %s]" error)))))
13670 (delete-region template-start (point))
13671 (insert result))))
13673 ;; From the property list
13674 (when plist-p
13675 (goto-char (point-min))
13676 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13677 (and (setq x (or (plist-get org-store-link-plist
13678 (intern (match-string 1))) ""))
13679 (replace-match x t t))))
13681 ;; Turn on org-mode in the remember buffer, set local variables
13682 (org-mode)
13683 (org-set-local 'org-finish-function 'org-remember-finalize)
13684 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13685 (org-set-local 'org-default-notes-file file))
13686 (if (and headline (stringp headline) (string-match "\\S-" headline))
13687 (org-set-local 'org-remember-default-headline headline))
13688 ;; Interactive template entries
13689 (goto-char (point-min))
13690 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13691 (setq char (if (match-end 3) (match-string 3))
13692 prompt (if (match-end 2) (match-string 2)))
13693 (goto-char (match-beginning 0))
13694 (replace-match "")
13695 (setq completions nil default nil)
13696 (when prompt
13697 (setq completions (org-split-string prompt "|")
13698 prompt (pop completions)
13699 default (car completions)
13700 histvar (intern (concat
13701 "org-remember-template-prompt-history::"
13702 (or prompt "")))
13703 completions (mapcar 'list completions)))
13704 (cond
13705 ((member char '("G" "g"))
13706 (let* ((org-last-tags-completion-table
13707 (org-global-tags-completion-table
13708 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13709 (org-add-colon-after-tag-completion t)
13710 (ins (completing-read
13711 (if prompt (concat prompt ": ") "Tags: ")
13712 'org-tags-completion-function nil nil nil
13713 'org-tags-history)))
13714 (setq ins (mapconcat 'identity
13715 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13716 ":"))
13717 (when (string-match "\\S-" ins)
13718 (or (equal (char-before) ?:) (insert ":"))
13719 (insert ins)
13720 (or (equal (char-after) ?:) (insert ":")))))
13721 (char
13722 (setq org-time-was-given (equal (upcase char) char))
13723 (setq time (org-read-date (equal (upcase char) "U") t nil
13724 prompt))
13725 (org-insert-time-stamp time org-time-was-given
13726 (member char '("u" "U"))
13727 nil nil (list org-end-time-was-given)))
13729 (insert (org-completing-read
13730 (concat (if prompt prompt "Enter string")
13731 (if default (concat " [" default "]"))
13732 ": ")
13733 completions nil nil nil histvar default)))))
13734 (goto-char (point-min))
13735 (if (re-search-forward "%\\?" nil t)
13736 (replace-match "")
13737 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13738 (org-mode)
13739 (org-set-local 'org-finish-function 'org-remember-finalize))
13740 (when (save-excursion
13741 (goto-char (point-min))
13742 (re-search-forward "%!" nil t))
13743 (replace-match "")
13744 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13746 (defun org-remember-finish-immediately ()
13747 "File remember note immediately.
13748 This should be run in `post-command-hook' and will remove itself
13749 from that hook."
13750 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13751 (when org-finish-function
13752 (funcall org-finish-function)))
13754 (defvar org-clock-marker) ; Defined below
13755 (defun org-remember-finalize ()
13756 "Finalize the remember process."
13757 (unless (fboundp 'remember-finalize)
13758 (defalias 'remember-finalize 'remember-buffer))
13759 (when (and org-clock-marker
13760 (equal (marker-buffer org-clock-marker) (current-buffer)))
13761 ;; FIXME: test this, this is w/o notetaking!
13762 (let (org-log-note-clock-out) (org-clock-out)))
13763 (when buffer-file-name
13764 (save-buffer)
13765 (setq buffer-file-name nil))
13766 (remember-finalize))
13768 ;;;###autoload
13769 (defun org-remember (&optional goto org-force-remember-template-char)
13770 "Call `remember'. If this is already a remember buffer, re-apply template.
13771 If there is an active region, make sure remember uses it as initial content
13772 of the remember buffer.
13774 When called interactively with a `C-u' prefix argument GOTO, don't remember
13775 anything, just go to the file/headline where the selected template usually
13776 stores its notes. With a double prefix arg `C-u C-u', go to the last
13777 note stored by remember.
13779 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13780 associated with a template in `org-remember-templates'."
13781 (interactive "P")
13782 (cond
13783 ((equal goto '(4)) (org-go-to-remember-target))
13784 ((equal goto '(16)) (org-remember-goto-last-stored))
13786 (if (memq org-finish-function '(remember-buffer remember-finalize))
13787 (progn
13788 (when (< (length org-remember-templates) 2)
13789 (error "No other template available"))
13790 (erase-buffer)
13791 (let ((annotation (plist-get org-store-link-plist :annotation))
13792 (initial (plist-get org-store-link-plist :initial)))
13793 (org-remember-apply-template))
13794 (message "Press C-c C-c to remember data"))
13795 (if (org-region-active-p)
13796 (remember (buffer-substring (point) (mark)))
13797 (call-interactively 'remember))))))
13799 (defun org-remember-goto-last-stored ()
13800 "Go to the location where the last remember note was stored."
13801 (interactive)
13802 (bookmark-jump "org-remember-last-stored")
13803 (message "This is the last note stored by remember"))
13805 (defun org-go-to-remember-target (&optional template-key)
13806 "Go to the target location of a remember template.
13807 The user is queried for the template."
13808 (interactive)
13809 (let* ((entry (org-select-remember-template template-key))
13810 (file (nth 1 entry))
13811 (heading (nth 2 entry))
13812 visiting)
13813 (unless (and file (stringp file) (string-match "\\S-" file))
13814 (setq file org-default-notes-file))
13815 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13816 (setq heading org-remember-default-headline))
13817 (setq visiting (org-find-base-buffer-visiting file))
13818 (if (not visiting) (find-file-noselect file))
13819 (switch-to-buffer (or visiting (get-file-buffer file)))
13820 (widen)
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 (goto-char (match-beginning 0))
13827 (error "Target headline not found: %s" heading))))
13829 (defvar org-note-abort nil) ; dynamically scoped
13831 ;;;###autoload
13832 (defun org-remember-handler ()
13833 "Store stuff from remember.el into an org file.
13834 First prompts for an org file. If the user just presses return, the value
13835 of `org-default-notes-file' is used.
13836 Then the command offers the headings tree of the selected file in order to
13837 file the text at a specific location.
13838 You can either immediately press RET to get the note appended to the
13839 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13840 find a better place. Then press RET or <left> or <right> in insert the note.
13842 Key Cursor position Note gets inserted
13843 -----------------------------------------------------------------------------
13844 RET buffer-start as level 1 heading at end of file
13845 RET on headline as sublevel of the heading at cursor
13846 RET no heading at cursor position, level taken from context.
13847 Or use prefix arg to specify level manually.
13848 <left> on headline as same level, before current heading
13849 <right> on headline as same level, after current heading
13851 So the fastest way to store the note is to press RET RET to append it to
13852 the default file. This way your current train of thought is not
13853 interrupted, in accordance with the principles of remember.el.
13854 You can also get the fast execution without prompting by using
13855 C-u C-c C-c to exit the remember buffer. See also the variable
13856 `org-remember-store-without-prompt'.
13858 Before being stored away, the function ensures that the text has a
13859 headline, i.e. a first line that starts with a \"*\". If not, a headline
13860 is constructed from the current date and some additional data.
13862 If the variable `org-adapt-indentation' is non-nil, the entire text is
13863 also indented so that it starts in the same column as the headline
13864 \(i.e. after the stars).
13866 See also the variable `org-reverse-note-order'."
13867 (goto-char (point-min))
13868 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13869 (replace-match ""))
13870 (goto-char (point-max))
13871 (beginning-of-line 1)
13872 (while (looking-at "[ \t]*$\\|##.*")
13873 (delete-region (1- (point)) (point-max))
13874 (beginning-of-line 1))
13875 (catch 'quit
13876 (if org-note-abort (throw 'quit nil))
13877 (let* ((txt (buffer-substring (point-min) (point-max)))
13878 (fastp (org-xor (equal current-prefix-arg '(4))
13879 org-remember-store-without-prompt))
13880 (file (cond
13881 (fastp org-default-notes-file)
13882 ((and (eq org-remember-interactive-interface 'refile)
13883 org-refile-targets)
13884 org-default-notes-file)
13885 ((not (and (equal current-prefix-arg '(16))
13886 org-remember-previous-location))
13887 (org-get-org-file))))
13888 (heading org-remember-default-headline)
13889 (visiting (and file (org-find-base-buffer-visiting file)))
13890 (org-startup-folded nil)
13891 (org-startup-align-all-tables nil)
13892 (org-goto-start-pos 1)
13893 spos exitcmd level indent reversed)
13894 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13895 (setq file (car org-remember-previous-location)
13896 heading (cdr org-remember-previous-location)
13897 fastp t))
13898 (setq current-prefix-arg nil)
13899 (if (string-match "[ \t\n]+\\'" txt)
13900 (setq txt (replace-match "" t t txt)))
13901 ;; Modify text so that it becomes a nice subtree which can be inserted
13902 ;; into an org tree.
13903 (let* ((lines (split-string txt "\n"))
13904 first)
13905 (setq first (car lines) lines (cdr lines))
13906 (if (string-match "^\\*+ " first)
13907 ;; Is already a headline
13908 (setq indent nil)
13909 ;; We need to add a headline: Use time and first buffer line
13910 (setq lines (cons first lines)
13911 first (concat "* " (current-time-string)
13912 " (" (remember-buffer-desc) ")")
13913 indent " "))
13914 (if (and org-adapt-indentation indent)
13915 (setq lines (mapcar
13916 (lambda (x)
13917 (if (string-match "\\S-" x)
13918 (concat indent x) x))
13919 lines)))
13920 (setq txt (concat first "\n"
13921 (mapconcat 'identity lines "\n"))))
13922 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13923 (setq txt (replace-match "\n\n" t t txt))
13924 (if (string-match "[ \t\n]*\\'" txt)
13925 (setq txt (replace-match "\n" t t txt))))
13926 ;; Put the modified text back into the remember buffer, for refile.
13927 (erase-buffer)
13928 (insert txt)
13929 (goto-char (point-min))
13930 (when (and (eq org-remember-interactive-interface 'refile)
13931 (not fastp))
13932 (org-refile nil (or visiting (find-file-noselect file)))
13933 (throw 'quit t))
13934 ;; Find the file
13935 (if (not visiting) (find-file-noselect file))
13936 (with-current-buffer (or visiting (get-file-buffer file))
13937 (unless (org-mode-p)
13938 (error "Target files for remember notes must be in Org-mode"))
13939 (save-excursion
13940 (save-restriction
13941 (widen)
13942 (and (goto-char (point-min))
13943 (not (re-search-forward "^\\* " nil t))
13944 (insert "\n* " (or heading "Notes") "\n"))
13945 (setq reversed (org-notes-order-reversed-p))
13947 ;; Find the default location
13948 (when (and heading (stringp heading) (string-match "\\S-" heading))
13949 (goto-char (point-min))
13950 (if (re-search-forward
13951 (concat "^\\*+[ \t]+" (regexp-quote heading)
13952 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13953 nil t)
13954 (setq org-goto-start-pos (match-beginning 0))
13955 (when fastp
13956 (goto-char (point-max))
13957 (unless (bolp) (newline))
13958 (insert "* " heading "\n")
13959 (setq org-goto-start-pos (point-at-bol 0)))))
13961 ;; Ask the User for a location, using the appropriate interface
13962 (cond
13963 (fastp (setq spos org-goto-start-pos
13964 exitcmd 'return))
13965 ((eq org-remember-interactive-interface 'outline)
13966 (setq spos (org-get-location (current-buffer)
13967 org-remember-help)
13968 exitcmd (cdr spos)
13969 spos (car spos)))
13970 ((eq org-remember-interactive-interface 'outline-path-completion)
13971 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13972 (org-refile-use-outline-path t))
13973 (setq spos (org-refile-get-location "Heading: ")
13974 exitcmd 'return
13975 spos (nth 3 spos))))
13976 (t (error "this should not hapen")))
13977 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13978 ; not handle this note
13979 (goto-char spos)
13980 (cond ((org-on-heading-p t)
13981 (org-back-to-heading t)
13982 (setq level (funcall outline-level))
13983 (cond
13984 ((eq exitcmd 'return)
13985 ;; sublevel of current
13986 (setq org-remember-previous-location
13987 (cons (abbreviate-file-name file)
13988 (org-get-heading 'notags)))
13989 (if reversed
13990 (outline-next-heading)
13991 (org-end-of-subtree t)
13992 (if (not (bolp))
13993 (if (looking-at "[ \t]*\n")
13994 (beginning-of-line 2)
13995 (end-of-line 1)
13996 (insert "\n"))))
13997 (bookmark-set "org-remember-last-stored")
13998 (org-paste-subtree (org-get-legal-level level 1) txt))
13999 ((eq exitcmd 'left)
14000 ;; before current
14001 (bookmark-set "org-remember-last-stored")
14002 (org-paste-subtree level txt))
14003 ((eq exitcmd 'right)
14004 ;; after current
14005 (org-end-of-subtree t)
14006 (bookmark-set "org-remember-last-stored")
14007 (org-paste-subtree level txt))
14008 (t (error "This should not happen"))))
14010 ((and (bobp) (not reversed))
14011 ;; Put it at the end, one level below level 1
14012 (save-restriction
14013 (widen)
14014 (goto-char (point-max))
14015 (if (not (bolp)) (newline))
14016 (bookmark-set "org-remember-last-stored")
14017 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14019 ((and (bobp) reversed)
14020 ;; Put it at the start, as level 1
14021 (save-restriction
14022 (widen)
14023 (goto-char (point-min))
14024 (re-search-forward "^\\*+ " nil t)
14025 (beginning-of-line 1)
14026 (bookmark-set "org-remember-last-stored")
14027 (org-paste-subtree 1 txt)))
14029 ;; Put it right there, with automatic level determined by
14030 ;; org-paste-subtree or from prefix arg
14031 (bookmark-set "org-remember-last-stored")
14032 (org-paste-subtree
14033 (if (numberp current-prefix-arg) current-prefix-arg)
14034 txt)))
14035 (when remember-save-after-remembering
14036 (save-buffer)
14037 (if (not visiting) (kill-buffer (current-buffer)))))))))
14039 t) ;; return t to indicate that we took care of this note.
14041 (defun org-get-org-file ()
14042 "Read a filename, with default directory `org-directory'."
14043 (let ((default (or org-default-notes-file remember-data-file)))
14044 (read-file-name (format "File name [%s]: " default)
14045 (file-name-as-directory org-directory)
14046 default)))
14048 (defun org-notes-order-reversed-p ()
14049 "Check if the current file should receive notes in reversed order."
14050 (cond
14051 ((not org-reverse-note-order) nil)
14052 ((eq t org-reverse-note-order) t)
14053 ((not (listp org-reverse-note-order)) nil)
14054 (t (catch 'exit
14055 (let ((all org-reverse-note-order)
14056 entry)
14057 (while (setq entry (pop all))
14058 (if (string-match (car entry) buffer-file-name)
14059 (throw 'exit (cdr entry))))
14060 nil)))))
14062 ;;; Refiling
14064 (defvar org-refile-target-table nil
14065 "The list of refile targets, created by `org-refile'.")
14067 (defvar org-agenda-new-buffers nil
14068 "Buffers created to visit agenda files.")
14070 (defun org-get-refile-targets (&optional default-buffer)
14071 "Produce a table with refile targets."
14072 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14073 targets txt re files f desc descre)
14074 (with-current-buffer (or default-buffer (current-buffer))
14075 (while (setq entry (pop entries))
14076 (setq files (car entry) desc (cdr entry))
14077 (cond
14078 ((null files) (setq files (list (current-buffer))))
14079 ((eq files 'org-agenda-files)
14080 (setq files (org-agenda-files 'unrestricted)))
14081 ((and (symbolp files) (fboundp files))
14082 (setq files (funcall files)))
14083 ((and (symbolp files) (boundp files))
14084 (setq files (symbol-value files))))
14085 (if (stringp files) (setq files (list files)))
14086 (cond
14087 ((eq (car desc) :tag)
14088 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14089 ((eq (car desc) :todo)
14090 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14091 ((eq (car desc) :regexp)
14092 (setq descre (cdr desc)))
14093 ((eq (car desc) :level)
14094 (setq descre (concat "^\\*\\{" (number-to-string
14095 (if org-odd-levels-only
14096 (1- (* 2 (cdr desc)))
14097 (cdr desc)))
14098 "\\}[ \t]")))
14099 ((eq (car desc) :maxlevel)
14100 (setq descre (concat "^\\*\\{1," (number-to-string
14101 (if org-odd-levels-only
14102 (1- (* 2 (cdr desc)))
14103 (cdr desc)))
14104 "\\}[ \t]")))
14105 (t (error "Bad refiling target description %s" desc)))
14106 (while (setq f (pop files))
14107 (save-excursion
14108 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14109 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14110 (save-excursion
14111 (save-restriction
14112 (widen)
14113 (goto-char (point-min))
14114 (while (re-search-forward descre nil t)
14115 (goto-char (point-at-bol))
14116 (when (looking-at org-complex-heading-regexp)
14117 (setq txt (match-string 4)
14118 re (concat "^" (regexp-quote
14119 (buffer-substring (match-beginning 1)
14120 (match-end 4)))))
14121 (if (match-end 5) (setq re (concat re "[ \t]+"
14122 (regexp-quote
14123 (match-string 5)))))
14124 (setq re (concat re "[ \t]*$"))
14125 (when org-refile-use-outline-path
14126 (setq txt (mapconcat 'identity
14127 (append
14128 (if (eq org-refile-use-outline-path 'file)
14129 (list (file-name-nondirectory
14130 (buffer-file-name (buffer-base-buffer))))
14131 (if (eq org-refile-use-outline-path 'full-file-path)
14132 (list (buffer-file-name (buffer-base-buffer)))))
14133 (org-get-outline-path)
14134 (list txt))
14135 "/")))
14136 (push (list txt f re (point)) targets))
14137 (goto-char (point-at-eol))))))))
14138 (nreverse targets))))
14140 (defun org-get-outline-path ()
14141 "Return the outline path to the current entry, as a list."
14142 (let (rtn)
14143 (save-excursion
14144 (while (org-up-heading-safe)
14145 (when (looking-at org-complex-heading-regexp)
14146 (push (org-match-string-no-properties 4) rtn)))
14147 rtn)))
14149 (defvar org-refile-history nil
14150 "History for refiling operations.")
14152 (defun org-refile (&optional goto default-buffer)
14153 "Move the entry at point to another heading.
14154 The list of target headings is compiled using the information in
14155 `org-refile-targets', which see. This list is created upon first use, and
14156 you can update it by calling this command with a double prefix (`C-u C-u').
14157 FIXME: Can we find a better way of updating?
14159 At the target location, the entry is filed as a subitem of the target heading.
14160 Depending on `org-reverse-note-order', the new subitem will either be the
14161 first of the last subitem.
14163 With prefix arg GOTO, the command will only visit the target location,
14164 not actually move anything.
14165 With a double prefix `C-c C-c', go to the location where the last refiling
14166 operation has put the subtree.
14168 With a double prefix argument, the command can be used to jump to any
14169 heading in the current buffer."
14170 (interactive "P")
14171 (let* ((cbuf (current-buffer))
14172 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14173 pos it nbuf file re level reversed)
14174 (if (equal goto '(16))
14175 (org-refile-goto-last-stored)
14176 (when (setq it (org-refile-get-location
14177 (if goto "Goto: " "Refile to: ") default-buffer))
14178 (setq file (nth 1 it)
14179 re (nth 2 it)
14180 pos (nth 3 it))
14181 (setq nbuf (or (find-buffer-visiting file)
14182 (find-file-noselect file)))
14183 (if goto
14184 (progn
14185 (switch-to-buffer nbuf)
14186 (goto-char pos)
14187 (org-show-context 'org-goto))
14188 (org-copy-special)
14189 (save-excursion
14190 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14191 (find-file-noselect file))))
14192 (setq reversed (org-notes-order-reversed-p))
14193 (save-excursion
14194 (save-restriction
14195 (widen)
14196 (goto-char pos)
14197 (looking-at outline-regexp)
14198 (setq level (org-get-legal-level (funcall outline-level) 1))
14199 (goto-char
14200 (if reversed
14201 (outline-next-heading)
14202 (or (save-excursion (outline-get-next-sibling))
14203 (org-end-of-subtree t t)
14204 (point-max))))
14205 (bookmark-set "org-refile-last-stored")
14206 (org-paste-subtree level))))
14207 (org-cut-special)
14208 (message "Entry refiled to \"%s\"" (car it)))))))
14210 (defun org-refile-goto-last-stored ()
14211 "Go to the location where the last refile was stored."
14212 (interactive)
14213 (bookmark-jump "org-refile-last-stored")
14214 (message "This is the location of the last refile"))
14216 (defun org-refile-get-location (&optional prompt default-buffer)
14217 "Prompt the user for a refile location, using PROMPT."
14218 (let ((org-refile-targets org-refile-targets)
14219 (org-refile-use-outline-path org-refile-use-outline-path))
14220 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14221 (unless org-refile-target-table
14222 (error "No refile targets"))
14223 (let* ((cbuf (current-buffer))
14224 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14225 (fname (and filename (file-truename filename)))
14226 (tbl (mapcar
14227 (lambda (x)
14228 (if (not (equal fname (file-truename (nth 1 x))))
14229 (cons (concat (car x) " (" (file-name-nondirectory
14230 (nth 1 x)) ")")
14231 (cdr x))
14233 org-refile-target-table))
14234 (completion-ignore-case t))
14235 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14236 tbl)))
14238 ;;;; Dynamic blocks
14240 (defun org-find-dblock (name)
14241 "Find the first dynamic block with name NAME in the buffer.
14242 If not found, stay at current position and return nil."
14243 (let (pos)
14244 (save-excursion
14245 (goto-char (point-min))
14246 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14247 nil t)
14248 (match-beginning 0))))
14249 (if pos (goto-char pos))
14250 pos))
14252 (defconst org-dblock-start-re
14253 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14254 "Matches the startline of a dynamic block, with parameters.")
14256 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14257 "Matches the end of a dyhamic block.")
14259 (defun org-create-dblock (plist)
14260 "Create a dynamic block section, with parameters taken from PLIST.
14261 PLIST must containe a :name entry which is used as name of the block."
14262 (unless (bolp) (newline))
14263 (let ((name (plist-get plist :name)))
14264 (insert "#+BEGIN: " name)
14265 (while plist
14266 (if (eq (car plist) :name)
14267 (setq plist (cddr plist))
14268 (insert " " (prin1-to-string (pop plist)))))
14269 (insert "\n\n#+END:\n")
14270 (beginning-of-line -2)))
14272 (defun org-prepare-dblock ()
14273 "Prepare dynamic block for refresh.
14274 This empties the block, puts the cursor at the insert position and returns
14275 the property list including an extra property :name with the block name."
14276 (unless (looking-at org-dblock-start-re)
14277 (error "Not at a dynamic block"))
14278 (let* ((begdel (1+ (match-end 0)))
14279 (name (org-no-properties (match-string 1)))
14280 (params (append (list :name name)
14281 (read (concat "(" (match-string 3) ")")))))
14282 (unless (re-search-forward org-dblock-end-re nil t)
14283 (error "Dynamic block not terminated"))
14284 (delete-region begdel (match-beginning 0))
14285 (goto-char begdel)
14286 (open-line 1)
14287 params))
14289 (defun org-map-dblocks (&optional command)
14290 "Apply COMMAND to all dynamic blocks in the current buffer.
14291 If COMMAND is not given, use `org-update-dblock'."
14292 (let ((cmd (or command 'org-update-dblock))
14293 pos)
14294 (save-excursion
14295 (goto-char (point-min))
14296 (while (re-search-forward org-dblock-start-re nil t)
14297 (goto-char (setq pos (match-beginning 0)))
14298 (condition-case nil
14299 (funcall cmd)
14300 (error (message "Error during update of dynamic block")))
14301 (goto-char pos)
14302 (unless (re-search-forward org-dblock-end-re nil t)
14303 (error "Dynamic block not terminated"))))))
14305 (defun org-dblock-update (&optional arg)
14306 "User command for updating dynamic blocks.
14307 Update the dynamic block at point. With prefix ARG, update all dynamic
14308 blocks in the buffer."
14309 (interactive "P")
14310 (if arg
14311 (org-update-all-dblocks)
14312 (or (looking-at org-dblock-start-re)
14313 (org-beginning-of-dblock))
14314 (org-update-dblock)))
14316 (defun org-update-dblock ()
14317 "Update the dynamic block at point
14318 This means to empty the block, parse for parameters and then call
14319 the correct writing function."
14320 (save-window-excursion
14321 (let* ((pos (point))
14322 (line (org-current-line))
14323 (params (org-prepare-dblock))
14324 (name (plist-get params :name))
14325 (cmd (intern (concat "org-dblock-write:" name))))
14326 (message "Updating dynamic block `%s' at line %d..." name line)
14327 (funcall cmd params)
14328 (message "Updating dynamic block `%s' at line %d...done" name line)
14329 (goto-char pos))))
14331 (defun org-beginning-of-dblock ()
14332 "Find the beginning of the dynamic block at point.
14333 Error if there is no scuh block at point."
14334 (let ((pos (point))
14335 beg)
14336 (end-of-line 1)
14337 (if (and (re-search-backward org-dblock-start-re nil t)
14338 (setq beg (match-beginning 0))
14339 (re-search-forward org-dblock-end-re nil t)
14340 (> (match-end 0) pos))
14341 (goto-char beg)
14342 (goto-char pos)
14343 (error "Not in a dynamic block"))))
14345 (defun org-update-all-dblocks ()
14346 "Update all dynamic blocks in the buffer.
14347 This function can be used in a hook."
14348 (when (org-mode-p)
14349 (org-map-dblocks 'org-update-dblock)))
14352 ;;;; Completion
14354 (defconst org-additional-option-like-keywords
14355 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14356 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14357 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14359 (defun org-complete (&optional arg)
14360 "Perform completion on word at point.
14361 At the beginning of a headline, this completes TODO keywords as given in
14362 `org-todo-keywords'.
14363 If the current word is preceded by a backslash, completes the TeX symbols
14364 that are supported for HTML support.
14365 If the current word is preceded by \"#+\", completes special words for
14366 setting file options.
14367 In the line after \"#+STARTUP:, complete valid keywords.\"
14368 At all other locations, this simply calls the value of
14369 `org-completion-fallback-command'."
14370 (interactive "P")
14371 (org-without-partial-completion
14372 (catch 'exit
14373 (let* ((end (point))
14374 (beg1 (save-excursion
14375 (skip-chars-backward (org-re "[:alnum:]_@"))
14376 (point)))
14377 (beg (save-excursion
14378 (skip-chars-backward "a-zA-Z0-9_:$")
14379 (point)))
14380 (confirm (lambda (x) (stringp (car x))))
14381 (searchhead (equal (char-before beg) ?*))
14382 (tag (and (equal (char-before beg1) ?:)
14383 (equal (char-after (point-at-bol)) ?*)))
14384 (prop (and (equal (char-before beg1) ?:)
14385 (not (equal (char-after (point-at-bol)) ?*))))
14386 (texp (equal (char-before beg) ?\\))
14387 (link (equal (char-before beg) ?\[))
14388 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14389 beg)
14390 "#+"))
14391 (startup (string-match "^#\\+STARTUP:.*"
14392 (buffer-substring (point-at-bol) (point))))
14393 (completion-ignore-case opt)
14394 (type nil)
14395 (tbl nil)
14396 (table (cond
14397 (opt
14398 (setq type :opt)
14399 (append
14400 (mapcar
14401 (lambda (x)
14402 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14403 (cons (match-string 2 x) (match-string 1 x)))
14404 (org-split-string (org-get-current-options) "\n"))
14405 (mapcar 'list org-additional-option-like-keywords)))
14406 (startup
14407 (setq type :startup)
14408 org-startup-options)
14409 (link (append org-link-abbrev-alist-local
14410 org-link-abbrev-alist))
14411 (texp
14412 (setq type :tex)
14413 org-html-entities)
14414 ((string-match "\\`\\*+[ \t]+\\'"
14415 (buffer-substring (point-at-bol) beg))
14416 (setq type :todo)
14417 (mapcar 'list org-todo-keywords-1))
14418 (searchhead
14419 (setq type :searchhead)
14420 (save-excursion
14421 (goto-char (point-min))
14422 (while (re-search-forward org-todo-line-regexp nil t)
14423 (push (list
14424 (org-make-org-heading-search-string
14425 (match-string 3) t))
14426 tbl)))
14427 tbl)
14428 (tag (setq type :tag beg beg1)
14429 (or org-tag-alist (org-get-buffer-tags)))
14430 (prop (setq type :prop beg beg1)
14431 (mapcar 'list (org-buffer-property-keys nil t t)))
14432 (t (progn
14433 (call-interactively org-completion-fallback-command)
14434 (throw 'exit nil)))))
14435 (pattern (buffer-substring-no-properties beg end))
14436 (completion (try-completion pattern table confirm)))
14437 (cond ((eq completion t)
14438 (if (not (assoc (upcase pattern) table))
14439 (message "Already complete")
14440 (if (equal type :opt)
14441 (insert (substring (cdr (assoc (upcase pattern) table))
14442 (length pattern)))
14443 (if (memq type '(:tag :prop)) (insert ":")))))
14444 ((null completion)
14445 (message "Can't find completion for \"%s\"" pattern)
14446 (ding))
14447 ((not (string= pattern completion))
14448 (delete-region beg end)
14449 (if (string-match " +$" completion)
14450 (setq completion (replace-match "" t t completion)))
14451 (insert completion)
14452 (if (get-buffer-window "*Completions*")
14453 (delete-window (get-buffer-window "*Completions*")))
14454 (if (assoc completion table)
14455 (if (eq type :todo) (insert " ")
14456 (if (memq type '(:tag :prop)) (insert ":"))))
14457 (if (and (equal type :opt) (assoc completion table))
14458 (message "%s" (substitute-command-keys
14459 "Press \\[org-complete] again to insert example settings"))))
14461 (message "Making completion list...")
14462 (let ((list (sort (all-completions pattern table confirm)
14463 'string<)))
14464 (with-output-to-temp-buffer "*Completions*"
14465 (condition-case nil
14466 ;; Protection needed for XEmacs and emacs 21
14467 (display-completion-list list pattern)
14468 (error (display-completion-list list)))))
14469 (message "Making completion list...%s" "done")))))))
14471 ;;;; TODO, DEADLINE, Comments
14473 (defun org-toggle-comment ()
14474 "Change the COMMENT state of an entry."
14475 (interactive)
14476 (save-excursion
14477 (org-back-to-heading)
14478 (let (case-fold-search)
14479 (if (looking-at (concat outline-regexp
14480 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14481 (replace-match "" t t nil 1)
14482 (if (looking-at outline-regexp)
14483 (progn
14484 (goto-char (match-end 0))
14485 (insert org-comment-string " ")))))))
14487 (defvar org-last-todo-state-is-todo nil
14488 "This is non-nil when the last TODO state change led to a TODO state.
14489 If the last change removed the TODO tag or switched to DONE, then
14490 this is nil.")
14492 (defvar org-setting-tags nil) ; dynamically skiped
14494 ;; FIXME: better place
14495 (defun org-property-or-variable-value (var &optional inherit)
14496 "Check if there is a property fixing the value of VAR.
14497 If yes, return this value. If not, return the current value of the variable."
14498 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14499 (if (and prop (stringp prop) (string-match "\\S-" prop))
14500 (read prop)
14501 (symbol-value var))))
14503 (defun org-parse-local-options (string var)
14504 "Parse STRING for startup setting relevant for variable VAR."
14505 (let ((rtn (symbol-value var))
14506 e opts)
14507 (save-match-data
14508 (if (or (not string) (not (string-match "\\S-" string)))
14510 (setq opts (delq nil (mapcar (lambda (x)
14511 (setq e (assoc x org-startup-options))
14512 (if (eq (nth 1 e) var) e nil))
14513 (org-split-string string "[ \t]+"))))
14514 (if (not opts)
14516 (setq rtn nil)
14517 (while (setq e (pop opts))
14518 (if (not (nth 3 e))
14519 (setq rtn (nth 2 e))
14520 (if (not (listp rtn)) (setq rtn nil))
14521 (push (nth 2 e) rtn)))
14522 rtn)))))
14524 (defvar org-blocker-hook nil
14525 "Hook for functions that are allowed to block a state change.
14527 Each function gets as its single argument a property list, see
14528 `org-trigger-hook' for more information about this list.
14530 If any of the functions in this hook returns nil, the state change
14531 is blocked.")
14533 (defvar org-trigger-hook nil
14534 "Hook for functions that are triggered by a state change.
14536 Each function gets as its single argument a property list with at least
14537 the following elements:
14539 (:type type-of-change :position pos-at-entry-start
14540 :from old-state :to new-state)
14542 Depending on the type, more properties may be present.
14544 This mechanism is currently implemented for:
14546 TODO state changes
14547 ------------------
14548 :type todo-state-change
14549 :from previous state (keyword as a string), or nil
14550 :to new state (keyword as a string), or nil")
14553 (defun org-todo (&optional arg)
14554 "Change the TODO state of an item.
14555 The state of an item is given by a keyword at the start of the heading,
14556 like
14557 *** TODO Write paper
14558 *** DONE Call mom
14560 The different keywords are specified in the variable `org-todo-keywords'.
14561 By default the available states are \"TODO\" and \"DONE\".
14562 So for this example: when the item starts with TODO, it is changed to DONE.
14563 When it starts with DONE, the DONE is removed. And when neither TODO nor
14564 DONE are present, add TODO at the beginning of the heading.
14566 With C-u prefix arg, use completion to determine the new state.
14567 With numeric prefix arg, switch to that state.
14569 For calling through lisp, arg is also interpreted in the following way:
14570 'none -> empty state
14571 \"\"(empty string) -> switch to empty state
14572 'done -> switch to DONE
14573 'nextset -> switch to the next set of keywords
14574 'previousset -> switch to the previous set of keywords
14575 \"WAITING\" -> switch to the specified keyword, but only if it
14576 really is a member of `org-todo-keywords'."
14577 (interactive "P")
14578 (save-excursion
14579 (catch 'exit
14580 (org-back-to-heading)
14581 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14582 (or (looking-at (concat " +" org-todo-regexp " *"))
14583 (looking-at " *"))
14584 (let* ((match-data (match-data))
14585 (startpos (point-at-bol))
14586 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14587 (org-log-done org-log-done)
14588 (org-log-repeat org-log-repeat)
14589 (org-todo-log-states org-todo-log-states)
14590 (this (match-string 1))
14591 (hl-pos (match-beginning 0))
14592 (head (org-get-todo-sequence-head this))
14593 (ass (assoc head org-todo-kwd-alist))
14594 (interpret (nth 1 ass))
14595 (done-word (nth 3 ass))
14596 (final-done-word (nth 4 ass))
14597 (last-state (or this ""))
14598 (completion-ignore-case t)
14599 (member (member this org-todo-keywords-1))
14600 (tail (cdr member))
14601 (state (cond
14602 ((and org-todo-key-trigger
14603 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14604 (and (not arg) org-use-fast-todo-selection
14605 (not (eq org-use-fast-todo-selection 'prefix)))))
14606 ;; Use fast selection
14607 (org-fast-todo-selection))
14608 ((and (equal arg '(4))
14609 (or (not org-use-fast-todo-selection)
14610 (not org-todo-key-trigger)))
14611 ;; Read a state with completion
14612 (completing-read "State: " (mapcar (lambda(x) (list x))
14613 org-todo-keywords-1)
14614 nil t))
14615 ((eq arg 'right)
14616 (if this
14617 (if tail (car tail) nil)
14618 (car org-todo-keywords-1)))
14619 ((eq arg 'left)
14620 (if (equal member org-todo-keywords-1)
14622 (if this
14623 (nth (- (length org-todo-keywords-1) (length tail) 2)
14624 org-todo-keywords-1)
14625 (org-last org-todo-keywords-1))))
14626 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14627 (setq arg nil))) ; hack to fall back to cycling
14628 (arg
14629 ;; user or caller requests a specific state
14630 (cond
14631 ((equal arg "") nil)
14632 ((eq arg 'none) nil)
14633 ((eq arg 'done) (or done-word (car org-done-keywords)))
14634 ((eq arg 'nextset)
14635 (or (car (cdr (member head org-todo-heads)))
14636 (car org-todo-heads)))
14637 ((eq arg 'previousset)
14638 (let ((org-todo-heads (reverse org-todo-heads)))
14639 (or (car (cdr (member head org-todo-heads)))
14640 (car org-todo-heads))))
14641 ((car (member arg org-todo-keywords-1)))
14642 ((nth (1- (prefix-numeric-value arg))
14643 org-todo-keywords-1))))
14644 ((null member) (or head (car org-todo-keywords-1)))
14645 ((equal this final-done-word) nil) ;; -> make empty
14646 ((null tail) nil) ;; -> first entry
14647 ((eq interpret 'sequence)
14648 (car tail))
14649 ((memq interpret '(type priority))
14650 (if (eq this-command last-command)
14651 (car tail)
14652 (if (> (length tail) 0)
14653 (or done-word (car org-done-keywords))
14654 nil)))
14655 (t nil)))
14656 (next (if state (concat " " state " ") " "))
14657 (change-plist (list :type 'todo-state-change :from this :to state
14658 :position startpos))
14659 dolog now-done-p)
14660 (when org-blocker-hook
14661 (unless (save-excursion
14662 (save-match-data
14663 (run-hook-with-args-until-failure
14664 'org-blocker-hook change-plist)))
14665 (if (interactive-p)
14666 (error "TODO state change from %s to %s blocked" this state)
14667 ;; fail silently
14668 (message "TODO state change from %s to %s blocked" this state)
14669 (throw 'exit nil))))
14670 (store-match-data match-data)
14671 (replace-match next t t)
14672 (unless (pos-visible-in-window-p hl-pos)
14673 (message "TODO state changed to %s" (org-trim next)))
14674 (unless head
14675 (setq head (org-get-todo-sequence-head state)
14676 ass (assoc head org-todo-kwd-alist)
14677 interpret (nth 1 ass)
14678 done-word (nth 3 ass)
14679 final-done-word (nth 4 ass)))
14680 (when (memq arg '(nextset previousset))
14681 (message "Keyword-Set %d/%d: %s"
14682 (- (length org-todo-sets) -1
14683 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14684 (length org-todo-sets)
14685 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14686 (setq org-last-todo-state-is-todo
14687 (not (member state org-done-keywords)))
14688 (setq now-done-p (and (member state org-done-keywords)
14689 (not (member this org-done-keywords))))
14690 (and logging (org-local-logging logging))
14691 (when (and (or org-todo-log-states org-log-done)
14692 (not (memq arg '(nextset previousset))))
14693 ;; we need to look at recording a time and note
14694 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14695 (nth 2 (assoc this org-todo-log-states))))
14696 (when (and state
14697 (member state org-not-done-keywords)
14698 (not (member this org-not-done-keywords)))
14699 ;; This is now a todo state and was not one before
14700 ;; If there was a CLOSED time stamp, get rid of it.
14701 (org-add-planning-info nil nil 'closed))
14702 (when (and now-done-p org-log-done)
14703 ;; It is now done, and it was not done before
14704 (org-add-planning-info 'closed (org-current-time))
14705 (if (and (not dolog) (eq 'note org-log-done))
14706 (org-add-log-maybe 'done state 'findpos 'note)))
14707 (when (and state dolog)
14708 ;; This is a non-nil state, and we need to log it
14709 (org-add-log-maybe 'state state 'findpos dolog)))
14710 ;; Fixup tag positioning
14711 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14712 (run-hooks 'org-after-todo-state-change-hook)
14713 (if (and arg (not (member state org-done-keywords)))
14714 (setq head (org-get-todo-sequence-head state)))
14715 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14716 ;; Do we need to trigger a repeat?
14717 (when now-done-p (org-auto-repeat-maybe state))
14718 ;; Fixup cursor location if close to the keyword
14719 (if (and (outline-on-heading-p)
14720 (not (bolp))
14721 (save-excursion (beginning-of-line 1)
14722 (looking-at org-todo-line-regexp))
14723 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14724 (progn
14725 (goto-char (or (match-end 2) (match-end 1)))
14726 (just-one-space)))
14727 (when org-trigger-hook
14728 (save-excursion
14729 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14731 (defun org-local-logging (value)
14732 "Get logging settings from a property VALUE."
14733 (let* (words w a)
14734 ;; directly set the variables, they are already local.
14735 (setq org-log-done nil
14736 org-log-repeat nil
14737 org-todo-log-states nil)
14738 (setq words (org-split-string value))
14739 (while (setq w (pop words))
14740 (cond
14741 ((setq a (assoc w org-startup-options))
14742 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14743 (set (nth 1 a) (nth 2 a))))
14744 ((setq a (org-extract-log-state-settings w))
14745 (and (member (car a) org-todo-keywords-1)
14746 (push a org-todo-log-states)))))))
14748 (defun org-get-todo-sequence-head (kwd)
14749 "Return the head of the TODO sequence to which KWD belongs.
14750 If KWD is not set, check if there is a text property remembering the
14751 right sequence."
14752 (let (p)
14753 (cond
14754 ((not kwd)
14755 (or (get-text-property (point-at-bol) 'org-todo-head)
14756 (progn
14757 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14758 nil (point-at-eol)))
14759 (get-text-property p 'org-todo-head))))
14760 ((not (member kwd org-todo-keywords-1))
14761 (car org-todo-keywords-1))
14762 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14764 (defun org-fast-todo-selection ()
14765 "Fast TODO keyword selection with single keys.
14766 Returns the new TODO keyword, or nil if no state change should occur."
14767 (let* ((fulltable org-todo-key-alist)
14768 (done-keywords org-done-keywords) ;; needed for the faces.
14769 (maxlen (apply 'max (mapcar
14770 (lambda (x)
14771 (if (stringp (car x)) (string-width (car x)) 0))
14772 fulltable)))
14773 (expert nil)
14774 (fwidth (+ maxlen 3 1 3))
14775 (ncol (/ (- (window-width) 4) fwidth))
14776 tg cnt e c tbl
14777 groups ingroup)
14778 (save-window-excursion
14779 (if expert
14780 (set-buffer (get-buffer-create " *Org todo*"))
14781 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14782 (erase-buffer)
14783 (org-set-local 'org-done-keywords done-keywords)
14784 (setq tbl fulltable cnt 0)
14785 (while (setq e (pop tbl))
14786 (cond
14787 ((equal e '(:startgroup))
14788 (push '() groups) (setq ingroup t)
14789 (when (not (= cnt 0))
14790 (setq cnt 0)
14791 (insert "\n"))
14792 (insert "{ "))
14793 ((equal e '(:endgroup))
14794 (setq ingroup nil cnt 0)
14795 (insert "}\n"))
14797 (setq tg (car e) c (cdr e))
14798 (if ingroup (push tg (car groups)))
14799 (setq tg (org-add-props tg nil 'face
14800 (org-get-todo-face tg)))
14801 (if (and (= cnt 0) (not ingroup)) (insert " "))
14802 (insert "[" c "] " tg (make-string
14803 (- fwidth 4 (length tg)) ?\ ))
14804 (when (= (setq cnt (1+ cnt)) ncol)
14805 (insert "\n")
14806 (if ingroup (insert " "))
14807 (setq cnt 0)))))
14808 (insert "\n")
14809 (goto-char (point-min))
14810 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14811 (fit-window-to-buffer))
14812 (message "[a-z..]:Set [SPC]:clear")
14813 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14814 (cond
14815 ((or (= c ?\C-g)
14816 (and (= c ?q) (not (rassoc c fulltable))))
14817 (setq quit-flag t))
14818 ((= c ?\ ) nil)
14819 ((setq e (rassoc c fulltable) tg (car e))
14821 (t (setq quit-flag t))))))
14823 (defun org-get-repeat ()
14824 "Check if tere is a deadline/schedule with repeater in this entry."
14825 (save-match-data
14826 (save-excursion
14827 (org-back-to-heading t)
14828 (if (re-search-forward
14829 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14830 (match-string 1)))))
14832 (defvar org-last-changed-timestamp)
14833 (defvar org-log-post-message)
14834 (defvar org-log-note-purpose)
14835 (defun org-auto-repeat-maybe (done-word)
14836 "Check if the current headline contains a repeated deadline/schedule.
14837 If yes, set TODO state back to what it was and change the base date
14838 of repeating deadline/scheduled time stamps to new date.
14839 This function is run automatically after each state change to a DONE state."
14840 ;; last-state is dynamically scoped into this function
14841 (let* ((repeat (org-get-repeat))
14842 (aa (assoc last-state org-todo-kwd-alist))
14843 (interpret (nth 1 aa))
14844 (head (nth 2 aa))
14845 (whata '(("d" . day) ("m" . month) ("y" . year)))
14846 (msg "Entry repeats: ")
14847 (org-log-done nil)
14848 re type n what ts)
14849 (when repeat
14850 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14851 (org-todo (if (eq interpret 'type) last-state head))
14852 (when (and org-log-repeat
14853 (or (not (memq 'org-add-log-note
14854 (default-value 'post-command-hook)))
14855 (eq org-log-note-purpose 'done)))
14856 ;; Make sure a note is taken;
14857 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14858 'findpos org-log-repeat))
14859 (org-back-to-heading t)
14860 (org-add-planning-info nil nil 'closed)
14861 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14862 org-deadline-time-regexp "\\)\\|\\("
14863 org-ts-regexp "\\)"))
14864 (while (re-search-forward
14865 re (save-excursion (outline-next-heading) (point)) t)
14866 (setq type (if (match-end 1) org-scheduled-string
14867 (if (match-end 3) org-deadline-string "Plain:"))
14868 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14869 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14870 (setq n (string-to-number (match-string 1 ts))
14871 what (match-string 2 ts))
14872 (if (equal what "w") (setq n (* n 7) what "d"))
14873 (org-timestamp-change n (cdr (assoc what whata)))
14874 (setq msg (concat msg type org-last-changed-timestamp " "))))
14875 (setq org-log-post-message msg)
14876 (message "%s" msg))))
14878 (defun org-show-todo-tree (arg)
14879 "Make a compact tree which shows all headlines marked with TODO.
14880 The tree will show the lines where the regexp matches, and all higher
14881 headlines above the match.
14882 With a \\[universal-argument] prefix, also show the DONE entries.
14883 With a numeric prefix N, construct a sparse tree for the Nth element
14884 of `org-todo-keywords-1'."
14885 (interactive "P")
14886 (let ((case-fold-search nil)
14887 (kwd-re
14888 (cond ((null arg) org-not-done-regexp)
14889 ((equal arg '(4))
14890 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14891 (mapcar 'list org-todo-keywords-1))))
14892 (concat "\\("
14893 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14894 "\\)\\>")))
14895 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14896 (regexp-quote (nth (1- (prefix-numeric-value arg))
14897 org-todo-keywords-1)))
14898 (t (error "Invalid prefix argument: %s" arg)))))
14899 (message "%d TODO entries found"
14900 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14902 (defun org-deadline (&optional remove)
14903 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14904 With argument REMOVE, remove any deadline from the item."
14905 (interactive "P")
14906 (if remove
14907 (progn
14908 (org-remove-timestamp-with-keyword org-deadline-string)
14909 (message "Item no longer has a deadline."))
14910 (org-add-planning-info 'deadline nil 'closed)))
14912 (defun org-schedule (&optional remove)
14913 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14914 With argument REMOVE, remove any scheduling date from the item."
14915 (interactive "P")
14916 (if remove
14917 (progn
14918 (org-remove-timestamp-with-keyword org-scheduled-string)
14919 (message "Item is no longer scheduled."))
14920 (org-add-planning-info 'scheduled nil 'closed)))
14922 (defun org-remove-timestamp-with-keyword (keyword)
14923 "Remove all time stamps with KEYWORD in the current entry."
14924 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14925 beg)
14926 (save-excursion
14927 (org-back-to-heading t)
14928 (setq beg (point))
14929 (org-end-of-subtree t t)
14930 (while (re-search-backward re beg t)
14931 (replace-match "")
14932 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14933 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14935 (defun org-add-planning-info (what &optional time &rest remove)
14936 "Insert new timestamp with keyword in the line directly after the headline.
14937 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14938 If non is given, the user is prompted for a date.
14939 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14940 be removed."
14941 (interactive)
14942 (let (org-time-was-given org-end-time-was-given)
14943 (when what (setq time (or time (org-read-date nil 'to-time))))
14944 (when (and org-insert-labeled-timestamps-at-point
14945 (member what '(scheduled deadline)))
14946 (insert
14947 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14948 (org-insert-time-stamp time org-time-was-given
14949 nil nil nil (list org-end-time-was-given))
14950 (setq what nil))
14951 (save-excursion
14952 (save-restriction
14953 (let (col list elt ts buffer-invisibility-spec)
14954 (org-back-to-heading t)
14955 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14956 (goto-char (match-end 1))
14957 (setq col (current-column))
14958 (goto-char (match-end 0))
14959 (if (eobp) (insert "\n") (forward-char 1))
14960 (if (and (not (looking-at outline-regexp))
14961 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14962 "[^\r\n]*"))
14963 (not (equal (match-string 1) org-clock-string)))
14964 (narrow-to-region (match-beginning 0) (match-end 0))
14965 (insert-before-markers "\n")
14966 (backward-char 1)
14967 (narrow-to-region (point) (point))
14968 (indent-to-column col))
14969 ;; Check if we have to remove something.
14970 (setq list (cons what remove))
14971 (while list
14972 (setq elt (pop list))
14973 (goto-char (point-min))
14974 (when (or (and (eq elt 'scheduled)
14975 (re-search-forward org-scheduled-time-regexp nil t))
14976 (and (eq elt 'deadline)
14977 (re-search-forward org-deadline-time-regexp nil t))
14978 (and (eq elt 'closed)
14979 (re-search-forward org-closed-time-regexp nil t)))
14980 (replace-match "")
14981 (if (looking-at "--+<[^>]+>") (replace-match ""))
14982 (if (looking-at " +") (replace-match ""))))
14983 (goto-char (point-max))
14984 (when what
14985 (insert
14986 (if (not (equal (char-before) ?\ )) " " "")
14987 (cond ((eq what 'scheduled) org-scheduled-string)
14988 ((eq what 'deadline) org-deadline-string)
14989 ((eq what 'closed) org-closed-string))
14990 " ")
14991 (setq ts (org-insert-time-stamp
14992 time
14993 (or org-time-was-given
14994 (and (eq what 'closed) org-log-done-with-time))
14995 (eq what 'closed)
14996 nil nil (list org-end-time-was-given)))
14997 (end-of-line 1))
14998 (goto-char (point-min))
14999 (widen)
15000 (if (looking-at "[ \t]+\r?\n")
15001 (replace-match ""))
15002 ts)))))
15004 (defvar org-log-note-marker (make-marker))
15005 (defvar org-log-note-purpose nil)
15006 (defvar org-log-note-state nil)
15007 (defvar org-log-note-how nil)
15008 (defvar org-log-note-window-configuration nil)
15009 (defvar org-log-note-return-to (make-marker))
15010 (defvar org-log-post-message nil
15011 "Message to be displayed after a log note has been stored.
15012 The auto-repeater uses this.")
15014 (defun org-add-log-maybe (&optional purpose state findpos how)
15015 "Set up the post command hook to take a note.
15016 If this is about to TODO state change, the new state is expected in STATE.
15017 When FINDPOS is non-nil, find the correct position for the note in
15018 the current entry. If not, assume that it can be inserted at point."
15019 (save-excursion
15020 (when findpos
15021 (org-back-to-heading t)
15022 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15023 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15024 "[^\r\n]*\\)?"))
15025 (goto-char (match-end 0))
15026 (unless org-log-states-order-reversed
15027 (and (= (char-after) ?\n) (forward-char 1))
15028 (org-skip-over-state-notes)
15029 (skip-chars-backward " \t\n\r")))
15030 (move-marker org-log-note-marker (point))
15031 (setq org-log-note-purpose purpose
15032 org-log-note-state state
15033 org-log-note-how how)
15034 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15036 (defun org-skip-over-state-notes ()
15037 "Skip past the list of State notes in an entry."
15038 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15039 (while (looking-at "[ \t]*- State")
15040 (condition-case nil
15041 (org-next-item)
15042 (error (org-end-of-item)))))
15044 (defun org-add-log-note (&optional purpose)
15045 "Pop up a window for taking a note, and add this note later at point."
15046 (remove-hook 'post-command-hook 'org-add-log-note)
15047 (setq org-log-note-window-configuration (current-window-configuration))
15048 (delete-other-windows)
15049 (move-marker org-log-note-return-to (point))
15050 (switch-to-buffer (marker-buffer org-log-note-marker))
15051 (goto-char org-log-note-marker)
15052 (org-switch-to-buffer-other-window "*Org Note*")
15053 (erase-buffer)
15054 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15055 (org-store-log-note)
15056 (let ((org-inhibit-startup t)) (org-mode))
15057 (insert (format "# Insert note for %s.
15058 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15059 (cond
15060 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15061 ((eq org-log-note-purpose 'done) "closed todo item")
15062 ((eq org-log-note-purpose 'state)
15063 (format "state change to \"%s\"" org-log-note-state))
15064 (t (error "This should not happen")))))
15065 (org-set-local 'org-finish-function 'org-store-log-note)))
15067 (defun org-store-log-note ()
15068 "Finish taking a log note, and insert it to where it belongs."
15069 (let ((txt (buffer-string))
15070 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15071 lines ind)
15072 (kill-buffer (current-buffer))
15073 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15074 (setq txt (replace-match "" t t txt)))
15075 (if (string-match "\\s-+\\'" txt)
15076 (setq txt (replace-match "" t t txt)))
15077 (setq lines (org-split-string txt "\n"))
15078 (when (and note (string-match "\\S-" note))
15079 (setq note
15080 (org-replace-escapes
15081 note
15082 (list (cons "%u" (user-login-name))
15083 (cons "%U" user-full-name)
15084 (cons "%t" (format-time-string
15085 (org-time-stamp-format 'long 'inactive)
15086 (current-time)))
15087 (cons "%s" (if org-log-note-state
15088 (concat "\"" org-log-note-state "\"")
15089 "")))))
15090 (if lines (setq note (concat note " \\\\")))
15091 (push note lines))
15092 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15093 (when lines
15094 (save-excursion
15095 (set-buffer (marker-buffer org-log-note-marker))
15096 (save-excursion
15097 (goto-char org-log-note-marker)
15098 (move-marker org-log-note-marker nil)
15099 (end-of-line 1)
15100 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15101 (indent-relative nil)
15102 (insert "- " (pop lines))
15103 (org-indent-line-function)
15104 (beginning-of-line 1)
15105 (looking-at "[ \t]*")
15106 (setq ind (concat (match-string 0) " "))
15107 (end-of-line 1)
15108 (while lines (insert "\n" ind (pop lines)))))))
15109 (set-window-configuration org-log-note-window-configuration)
15110 (with-current-buffer (marker-buffer org-log-note-return-to)
15111 (goto-char org-log-note-return-to))
15112 (move-marker org-log-note-return-to nil)
15113 (and org-log-post-message (message "%s" org-log-post-message)))
15115 ;; FIXME: what else would be useful?
15116 ;; - priority
15117 ;; - date
15119 (defun org-sparse-tree (&optional arg)
15120 "Create a sparse tree, prompt for the details.
15121 This command can create sparse trees. You first need to select the type
15122 of match used to create the tree:
15124 t Show entries with a specific TODO keyword.
15125 T Show entries selected by a tags match.
15126 p Enter a property name and its value (both with completion on existing
15127 names/values) and show entries with that property.
15128 r Show entries matching a regular expression
15129 d Show deadlines due within `org-deadline-warning-days'."
15130 (interactive "P")
15131 (let (ans kwd value)
15132 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15133 (setq ans (read-char-exclusive))
15134 (cond
15135 ((equal ans ?d)
15136 (call-interactively 'org-check-deadlines))
15137 ((equal ans ?b)
15138 (call-interactively 'org-check-before-date))
15139 ((equal ans ?t)
15140 (org-show-todo-tree '(4)))
15141 ((equal ans ?T)
15142 (call-interactively 'org-tags-sparse-tree))
15143 ((member ans '(?p ?P))
15144 (setq kwd (completing-read "Property: "
15145 (mapcar 'list (org-buffer-property-keys))))
15146 (setq value (completing-read "Value: "
15147 (mapcar 'list (org-property-values kwd))))
15148 (unless (string-match "\\`{.*}\\'" value)
15149 (setq value (concat "\"" value "\"")))
15150 (org-tags-sparse-tree arg (concat kwd "=" value)))
15151 ((member ans '(?r ?R ?/))
15152 (call-interactively 'org-occur))
15153 (t (error "No such sparse tree command \"%c\"" ans)))))
15155 (defvar org-occur-highlights nil)
15156 (make-variable-buffer-local 'org-occur-highlights)
15158 (defun org-occur (regexp &optional keep-previous callback)
15159 "Make a compact tree which shows all matches of REGEXP.
15160 The tree will show the lines where the regexp matches, and all higher
15161 headlines above the match. It will also show the heading after the match,
15162 to make sure editing the matching entry is easy.
15163 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15164 call to `org-occur' will be kept, to allow stacking of calls to this
15165 command.
15166 If CALLBACK is non-nil, it is a function which is called to confirm
15167 that the match should indeed be shown."
15168 (interactive "sRegexp: \nP")
15169 (or keep-previous (org-remove-occur-highlights nil nil t))
15170 (let ((cnt 0))
15171 (save-excursion
15172 (goto-char (point-min))
15173 (if (or (not keep-previous) ; do not want to keep
15174 (not org-occur-highlights)) ; no previous matches
15175 ;; hide everything
15176 (org-overview))
15177 (while (re-search-forward regexp nil t)
15178 (when (or (not callback)
15179 (save-match-data (funcall callback)))
15180 (setq cnt (1+ cnt))
15181 (when org-highlight-sparse-tree-matches
15182 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15183 (org-show-context 'occur-tree))))
15184 (when org-remove-highlights-with-change
15185 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15186 nil 'local))
15187 (unless org-sparse-tree-open-archived-trees
15188 (org-hide-archived-subtrees (point-min) (point-max)))
15189 (run-hooks 'org-occur-hook)
15190 (if (interactive-p)
15191 (message "%d match(es) for regexp %s" cnt regexp))
15192 cnt))
15194 (defun org-show-context (&optional key)
15195 "Make sure point and context and visible.
15196 How much context is shown depends upon the variables
15197 `org-show-hierarchy-above', `org-show-following-heading'. and
15198 `org-show-siblings'."
15199 (let ((heading-p (org-on-heading-p t))
15200 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15201 (following-p (org-get-alist-option org-show-following-heading key))
15202 (entry-p (org-get-alist-option org-show-entry-below key))
15203 (siblings-p (org-get-alist-option org-show-siblings key)))
15204 (catch 'exit
15205 ;; Show heading or entry text
15206 (if (and heading-p (not entry-p))
15207 (org-flag-heading nil) ; only show the heading
15208 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15209 (org-show-hidden-entry))) ; show entire entry
15210 (when following-p
15211 ;; Show next sibling, or heading below text
15212 (save-excursion
15213 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15214 (org-flag-heading nil))))
15215 (when siblings-p (org-show-siblings))
15216 (when hierarchy-p
15217 ;; show all higher headings, possibly with siblings
15218 (save-excursion
15219 (while (and (condition-case nil
15220 (progn (org-up-heading-all 1) t)
15221 (error nil))
15222 (not (bobp)))
15223 (org-flag-heading nil)
15224 (when siblings-p (org-show-siblings))))))))
15226 (defun org-reveal (&optional siblings)
15227 "Show current entry, hierarchy above it, and the following headline.
15228 This can be used to show a consistent set of context around locations
15229 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15230 not t for the search context.
15232 With optional argument SIBLINGS, on each level of the hierarchy all
15233 siblings are shown. This repairs the tree structure to what it would
15234 look like when opened with hierarchical calls to `org-cycle'."
15235 (interactive "P")
15236 (let ((org-show-hierarchy-above t)
15237 (org-show-following-heading t)
15238 (org-show-siblings (if siblings t org-show-siblings)))
15239 (org-show-context nil)))
15241 (defun org-highlight-new-match (beg end)
15242 "Highlight from BEG to END and mark the highlight is an occur headline."
15243 (let ((ov (org-make-overlay beg end)))
15244 (org-overlay-put ov 'face 'secondary-selection)
15245 (push ov org-occur-highlights)))
15247 (defun org-remove-occur-highlights (&optional beg end noremove)
15248 "Remove the occur highlights from the buffer.
15249 BEG and END are ignored. If NOREMOVE is nil, remove this function
15250 from the `before-change-functions' in the current buffer."
15251 (interactive)
15252 (unless org-inhibit-highlight-removal
15253 (mapc 'org-delete-overlay org-occur-highlights)
15254 (setq org-occur-highlights nil)
15255 (unless noremove
15256 (remove-hook 'before-change-functions
15257 'org-remove-occur-highlights 'local))))
15259 ;;;; Priorities
15261 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15262 "Regular expression matching the priority indicator.")
15264 (defvar org-remove-priority-next-time nil)
15266 (defun org-priority-up ()
15267 "Increase the priority of the current item."
15268 (interactive)
15269 (org-priority 'up))
15271 (defun org-priority-down ()
15272 "Decrease the priority of the current item."
15273 (interactive)
15274 (org-priority 'down))
15276 (defun org-priority (&optional action)
15277 "Change the priority of an item by ARG.
15278 ACTION can be `set', `up', `down', or a character."
15279 (interactive)
15280 (setq action (or action 'set))
15281 (let (current new news have remove)
15282 (save-excursion
15283 (org-back-to-heading)
15284 (if (looking-at org-priority-regexp)
15285 (setq current (string-to-char (match-string 2))
15286 have t)
15287 (setq current org-default-priority))
15288 (cond
15289 ((or (eq action 'set) (integerp action))
15290 (if (integerp action)
15291 (setq new action)
15292 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15293 (setq new (read-char-exclusive)))
15294 (if (and (= (upcase org-highest-priority) org-highest-priority)
15295 (= (upcase org-lowest-priority) org-lowest-priority))
15296 (setq new (upcase new)))
15297 (cond ((equal new ?\ ) (setq remove t))
15298 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15299 (error "Priority must be between `%c' and `%c'"
15300 org-highest-priority org-lowest-priority))))
15301 ((eq action 'up)
15302 (if (and (not have) (eq last-command this-command))
15303 (setq new org-lowest-priority)
15304 (setq new (if (and org-priority-start-cycle-with-default (not have))
15305 org-default-priority (1- current)))))
15306 ((eq action 'down)
15307 (if (and (not have) (eq last-command this-command))
15308 (setq new org-highest-priority)
15309 (setq new (if (and org-priority-start-cycle-with-default (not have))
15310 org-default-priority (1+ current)))))
15311 (t (error "Invalid action")))
15312 (if (or (< (upcase new) org-highest-priority)
15313 (> (upcase new) org-lowest-priority))
15314 (setq remove t))
15315 (setq news (format "%c" new))
15316 (if have
15317 (if remove
15318 (replace-match "" t t nil 1)
15319 (replace-match news t t nil 2))
15320 (if remove
15321 (error "No priority cookie found in line")
15322 (looking-at org-todo-line-regexp)
15323 (if (match-end 2)
15324 (progn
15325 (goto-char (match-end 2))
15326 (insert " [#" news "]"))
15327 (goto-char (match-beginning 3))
15328 (insert "[#" news "] ")))))
15329 (org-preserve-lc (org-set-tags nil 'align))
15330 (if remove
15331 (message "Priority removed")
15332 (message "Priority of current item set to %s" news))))
15335 (defun org-get-priority (s)
15336 "Find priority cookie and return priority."
15337 (save-match-data
15338 (if (not (string-match org-priority-regexp s))
15339 (* 1000 (- org-lowest-priority org-default-priority))
15340 (* 1000 (- org-lowest-priority
15341 (string-to-char (match-string 2 s)))))))
15343 ;;;; Tags
15345 (defun org-scan-tags (action matcher &optional todo-only)
15346 "Scan headline tags with inheritance and produce output ACTION.
15347 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15348 evaluated, testing if a given set of tags qualifies a headline for
15349 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15350 are included in the output."
15351 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15352 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15353 (org-re
15354 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15355 (props (list 'face nil
15356 'done-face 'org-done
15357 'undone-face nil
15358 'mouse-face 'highlight
15359 'org-not-done-regexp org-not-done-regexp
15360 'org-todo-regexp org-todo-regexp
15361 'keymap org-agenda-keymap
15362 'help-echo
15363 (format "mouse-2 or RET jump to org file %s"
15364 (abbreviate-file-name
15365 (or (buffer-file-name (buffer-base-buffer))
15366 (buffer-name (buffer-base-buffer)))))))
15367 (case-fold-search nil)
15368 lspos
15369 tags tags-list tags-alist (llast 0) rtn level category i txt
15370 todo marker entry priority)
15371 (save-excursion
15372 (goto-char (point-min))
15373 (when (eq action 'sparse-tree)
15374 (org-overview)
15375 (org-remove-occur-highlights))
15376 (while (re-search-forward re nil t)
15377 (catch :skip
15378 (setq todo (if (match-end 1) (match-string 2))
15379 tags (if (match-end 4) (match-string 4)))
15380 (goto-char (setq lspos (1+ (match-beginning 0))))
15381 (setq level (org-reduced-level (funcall outline-level))
15382 category (org-get-category))
15383 (setq i llast llast level)
15384 ;; remove tag lists from same and sublevels
15385 (while (>= i level)
15386 (when (setq entry (assoc i tags-alist))
15387 (setq tags-alist (delete entry tags-alist)))
15388 (setq i (1- i)))
15389 ;; add the nex tags
15390 (when tags
15391 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15392 tags-alist
15393 (cons (cons level tags) tags-alist)))
15394 ;; compile tags for current headline
15395 (setq tags-list
15396 (if org-use-tag-inheritance
15397 (apply 'append (mapcar 'cdr tags-alist))
15398 tags))
15399 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15400 (eval matcher)
15401 (or (not org-agenda-skip-archived-trees)
15402 (not (member org-archive-tag tags-list))))
15403 (and (eq action 'agenda) (org-agenda-skip))
15404 ;; list this headline
15406 (if (eq action 'sparse-tree)
15407 (progn
15408 (and org-highlight-sparse-tree-matches
15409 (org-get-heading) (match-end 0)
15410 (org-highlight-new-match
15411 (match-beginning 0) (match-beginning 1)))
15412 (org-show-context 'tags-tree))
15413 (setq txt (org-format-agenda-item
15415 (concat
15416 (if org-tags-match-list-sublevels
15417 (make-string (1- level) ?.) "")
15418 (org-get-heading))
15419 category tags-list)
15420 priority (org-get-priority txt))
15421 (goto-char lspos)
15422 (setq marker (org-agenda-new-marker))
15423 (org-add-props txt props
15424 'org-marker marker 'org-hd-marker marker 'org-category category
15425 'priority priority 'type "tagsmatch")
15426 (push txt rtn))
15427 ;; if we are to skip sublevels, jump to end of subtree
15428 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15429 (when (and (eq action 'sparse-tree)
15430 (not org-sparse-tree-open-archived-trees))
15431 (org-hide-archived-subtrees (point-min) (point-max)))
15432 (nreverse rtn)))
15434 (defvar todo-only) ;; dynamically scoped
15436 (defun org-tags-sparse-tree (&optional todo-only match)
15437 "Create a sparse tree according to tags string MATCH.
15438 MATCH can contain positive and negative selection of tags, like
15439 \"+WORK+URGENT-WITHBOSS\".
15440 If optional argument TODO_ONLY is non-nil, only select lines that are
15441 also TODO lines."
15442 (interactive "P")
15443 (org-prepare-agenda-buffers (list (current-buffer)))
15444 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15446 (defvar org-cached-props nil)
15447 (defun org-cached-entry-get (pom property)
15448 (if (or (eq t org-use-property-inheritance)
15449 (member property org-use-property-inheritance))
15450 ;; Caching is not possible, check it directly
15451 (org-entry-get pom property 'inherit)
15452 ;; Get all properties, so that we can do complicated checks easily
15453 (cdr (assoc property (or org-cached-props
15454 (setq org-cached-props
15455 (org-entry-properties pom)))))))
15457 (defun org-global-tags-completion-table (&optional files)
15458 "Return the list of all tags in all agenda buffer/files."
15459 (save-excursion
15460 (org-uniquify
15461 (delq nil
15462 (apply 'append
15463 (mapcar
15464 (lambda (file)
15465 (set-buffer (find-file-noselect file))
15466 (append (org-get-buffer-tags)
15467 (mapcar (lambda (x) (if (stringp (car-safe x))
15468 (list (car-safe x)) nil))
15469 org-tag-alist)))
15470 (if (and files (car files))
15471 files
15472 (org-agenda-files))))))))
15474 (defun org-make-tags-matcher (match)
15475 "Create the TAGS//TODO matcher form for the selection string MATCH."
15476 ;; todo-only is scoped dynamically into this function, and the function
15477 ;; may change it it the matcher asksk for it.
15478 (unless match
15479 ;; Get a new match request, with completion
15480 (let ((org-last-tags-completion-table
15481 (org-global-tags-completion-table)))
15482 (setq match (completing-read
15483 "Match: " 'org-tags-completion-function nil nil nil
15484 'org-tags-history))))
15486 ;; Parse the string and create a lisp form
15487 (let ((match0 match)
15488 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15489 minus tag mm
15490 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15491 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15492 (if (string-match "/+" match)
15493 ;; match contains also a todo-matching request
15494 (progn
15495 (setq tagsmatch (substring match 0 (match-beginning 0))
15496 todomatch (substring match (match-end 0)))
15497 (if (string-match "^!" todomatch)
15498 (setq todo-only t todomatch (substring todomatch 1)))
15499 (if (string-match "^\\s-*$" todomatch)
15500 (setq todomatch nil)))
15501 ;; only matching tags
15502 (setq tagsmatch match todomatch nil))
15504 ;; Make the tags matcher
15505 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15506 (setq tagsmatcher t)
15507 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15508 (while (setq term (pop orterms))
15509 (while (and (equal (substring term -1) "\\") orterms)
15510 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15511 (while (string-match re term)
15512 (setq minus (and (match-end 1)
15513 (equal (match-string 1 term) "-"))
15514 tag (match-string 2 term)
15515 re-p (equal (string-to-char tag) ?{)
15516 level-p (match-end 3)
15517 prop-p (match-end 4)
15518 mm (cond
15519 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15520 (level-p `(= level ,(string-to-number
15521 (match-string 3 term))))
15522 (prop-p
15523 (setq pn (match-string 4 term)
15524 pv (match-string 5 term)
15525 cat-p (equal pn "CATEGORY")
15526 re-p (equal (string-to-char pv) ?{)
15527 pv (substring pv 1 -1))
15528 (if (equal pn "CATEGORY")
15529 (setq gv '(get-text-property (point) 'org-category))
15530 (setq gv `(org-cached-entry-get nil ,pn)))
15531 (if re-p
15532 `(string-match ,pv (or ,gv ""))
15533 `(equal ,pv (or ,gv ""))))
15534 (t `(member ,(downcase tag) tags-list)))
15535 mm (if minus (list 'not mm) mm)
15536 term (substring term (match-end 0)))
15537 (push mm tagsmatcher))
15538 (push (if (> (length tagsmatcher) 1)
15539 (cons 'and tagsmatcher)
15540 (car tagsmatcher))
15541 orlist)
15542 (setq tagsmatcher nil))
15543 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15544 (setq tagsmatcher
15545 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15547 ;; Make the todo matcher
15548 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15549 (setq todomatcher t)
15550 (setq orterms (org-split-string todomatch "|") orlist nil)
15551 (while (setq term (pop orterms))
15552 (while (string-match re term)
15553 (setq minus (and (match-end 1)
15554 (equal (match-string 1 term) "-"))
15555 kwd (match-string 2 term)
15556 re-p (equal (string-to-char kwd) ?{)
15557 term (substring term (match-end 0))
15558 mm (if re-p
15559 `(string-match ,(substring kwd 1 -1) todo)
15560 (list 'equal 'todo kwd))
15561 mm (if minus (list 'not mm) mm))
15562 (push mm todomatcher))
15563 (push (if (> (length todomatcher) 1)
15564 (cons 'and todomatcher)
15565 (car todomatcher))
15566 orlist)
15567 (setq todomatcher nil))
15568 (setq todomatcher (if (> (length orlist) 1)
15569 (cons 'or orlist) (car orlist))))
15571 ;; Return the string and lisp forms of the matcher
15572 (setq matcher (if todomatcher
15573 (list 'and tagsmatcher todomatcher)
15574 tagsmatcher))
15575 (cons match0 matcher)))
15577 (defun org-match-any-p (re list)
15578 "Does re match any element of list?"
15579 (setq list (mapcar (lambda (x) (string-match re x)) list))
15580 (delq nil list))
15582 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15583 (defvar org-tags-overlay (org-make-overlay 1 1))
15584 (org-detach-overlay org-tags-overlay)
15586 (defun org-align-tags-here (to-col)
15587 ;; Assumes that this is a headline
15588 (let ((pos (point)) (col (current-column)) tags)
15589 (beginning-of-line 1)
15590 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15591 (< pos (match-beginning 2)))
15592 (progn
15593 (setq tags (match-string 2))
15594 (goto-char (match-beginning 1))
15595 (insert " ")
15596 (delete-region (point) (1+ (match-end 0)))
15597 (backward-char 1)
15598 (move-to-column
15599 (max (1+ (current-column))
15600 (1+ col)
15601 (if (> to-col 0)
15602 to-col
15603 (- (abs to-col) (length tags))))
15605 (insert tags)
15606 (move-to-column (min (current-column) col) t))
15607 (goto-char pos))))
15609 (defun org-set-tags (&optional arg just-align)
15610 "Set the tags for the current headline.
15611 With prefix ARG, realign all tags in headings in the current buffer."
15612 (interactive "P")
15613 (let* ((re (concat "^" outline-regexp))
15614 (current (org-get-tags-string))
15615 (col (current-column))
15616 (org-setting-tags t)
15617 table current-tags inherited-tags ; computed below when needed
15618 tags p0 c0 c1 rpl)
15619 (if arg
15620 (save-excursion
15621 (goto-char (point-min))
15622 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15623 (while (re-search-forward re nil t)
15624 (org-set-tags nil t)
15625 (end-of-line 1)))
15626 (message "All tags realigned to column %d" org-tags-column))
15627 (if just-align
15628 (setq tags current)
15629 ;; Get a new set of tags from the user
15630 (save-excursion
15631 (setq table (or org-tag-alist (org-get-buffer-tags))
15632 org-last-tags-completion-table table
15633 current-tags (org-split-string current ":")
15634 inherited-tags (nreverse
15635 (nthcdr (length current-tags)
15636 (nreverse (org-get-tags-at))))
15637 tags
15638 (if (or (eq t org-use-fast-tag-selection)
15639 (and org-use-fast-tag-selection
15640 (delq nil (mapcar 'cdr table))))
15641 (org-fast-tag-selection
15642 current-tags inherited-tags table
15643 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15644 (let ((org-add-colon-after-tag-completion t))
15645 (org-trim
15646 (org-without-partial-completion
15647 (completing-read "Tags: " 'org-tags-completion-function
15648 nil nil current 'org-tags-history)))))))
15649 (while (string-match "[-+&]+" tags)
15650 ;; No boolean logic, just a list
15651 (setq tags (replace-match ":" t t tags))))
15653 (if (string-match "\\`[\t ]*\\'" tags)
15654 (setq tags "")
15655 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15656 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15658 ;; Insert new tags at the correct column
15659 (beginning-of-line 1)
15660 (cond
15661 ((and (equal current "") (equal tags "")))
15662 ((re-search-forward
15663 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15664 (point-at-eol) t)
15665 (if (equal tags "")
15666 (setq rpl "")
15667 (goto-char (match-beginning 0))
15668 (setq c0 (current-column) p0 (point)
15669 c1 (max (1+ c0) (if (> org-tags-column 0)
15670 org-tags-column
15671 (- (- org-tags-column) (length tags))))
15672 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15673 (replace-match rpl t t)
15674 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15675 tags)
15676 (t (error "Tags alignment failed")))
15677 (move-to-column col)
15678 (unless just-align
15679 (run-hooks 'org-after-tags-change-hook)))))
15681 (defun org-change-tag-in-region (beg end tag off)
15682 "Add or remove TAG for each entry in the region.
15683 This works in the agenda, and also in an org-mode buffer."
15684 (interactive
15685 (list (region-beginning) (region-end)
15686 (let ((org-last-tags-completion-table
15687 (if (org-mode-p)
15688 (org-get-buffer-tags)
15689 (org-global-tags-completion-table))))
15690 (completing-read
15691 "Tag: " 'org-tags-completion-function nil nil nil
15692 'org-tags-history))
15693 (progn
15694 (message "[s]et or [r]emove? ")
15695 (equal (read-char-exclusive) ?r))))
15696 (if (fboundp 'deactivate-mark) (deactivate-mark))
15697 (let ((agendap (equal major-mode 'org-agenda-mode))
15698 l1 l2 m buf pos newhead (cnt 0))
15699 (goto-char end)
15700 (setq l2 (1- (org-current-line)))
15701 (goto-char beg)
15702 (setq l1 (org-current-line))
15703 (loop for l from l1 to l2 do
15704 (goto-line l)
15705 (setq m (get-text-property (point) 'org-hd-marker))
15706 (when (or (and (org-mode-p) (org-on-heading-p))
15707 (and agendap m))
15708 (setq buf (if agendap (marker-buffer m) (current-buffer))
15709 pos (if agendap m (point)))
15710 (with-current-buffer buf
15711 (save-excursion
15712 (save-restriction
15713 (goto-char pos)
15714 (setq cnt (1+ cnt))
15715 (org-toggle-tag tag (if off 'off 'on))
15716 (setq newhead (org-get-heading)))))
15717 (and agendap (org-agenda-change-all-lines newhead m))))
15718 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15720 (defun org-tags-completion-function (string predicate &optional flag)
15721 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15722 (confirm (lambda (x) (stringp (car x)))))
15723 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15724 (setq s1 (match-string 1 string)
15725 s2 (match-string 2 string))
15726 (setq s1 "" s2 string))
15727 (cond
15728 ((eq flag nil)
15729 ;; try completion
15730 (setq rtn (try-completion s2 ctable confirm))
15731 (if (stringp rtn)
15732 (setq rtn
15733 (concat s1 s2 (substring rtn (length s2))
15734 (if (and org-add-colon-after-tag-completion
15735 (assoc rtn ctable))
15736 ":" ""))))
15737 rtn)
15738 ((eq flag t)
15739 ;; all-completions
15740 (all-completions s2 ctable confirm)
15742 ((eq flag 'lambda)
15743 ;; exact match?
15744 (assoc s2 ctable)))
15747 (defun org-fast-tag-insert (kwd tags face &optional end)
15748 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15749 (insert (format "%-12s" (concat kwd ":"))
15750 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15751 (or end "")))
15753 (defun org-fast-tag-show-exit (flag)
15754 (save-excursion
15755 (goto-line 3)
15756 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15757 (replace-match ""))
15758 (when flag
15759 (end-of-line 1)
15760 (move-to-column (- (window-width) 19) t)
15761 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15763 (defun org-set-current-tags-overlay (current prefix)
15764 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15765 (if (featurep 'xemacs)
15766 (org-overlay-display org-tags-overlay (concat prefix s)
15767 'secondary-selection)
15768 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15769 (org-overlay-display org-tags-overlay (concat prefix s)))))
15771 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15772 "Fast tag selection with single keys.
15773 CURRENT is the current list of tags in the headline, INHERITED is the
15774 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15775 possibly with grouping information. TODO-TABLE is a similar table with
15776 TODO keywords, should these have keys assigned to them.
15777 If the keys are nil, a-z are automatically assigned.
15778 Returns the new tags string, or nil to not change the current settings."
15779 (let* ((fulltable (append table todo-table))
15780 (maxlen (apply 'max (mapcar
15781 (lambda (x)
15782 (if (stringp (car x)) (string-width (car x)) 0))
15783 fulltable)))
15784 (buf (current-buffer))
15785 (expert (eq org-fast-tag-selection-single-key 'expert))
15786 (buffer-tags nil)
15787 (fwidth (+ maxlen 3 1 3))
15788 (ncol (/ (- (window-width) 4) fwidth))
15789 (i-face 'org-done)
15790 (c-face 'org-todo)
15791 tg cnt e c char c1 c2 ntable tbl rtn
15792 ov-start ov-end ov-prefix
15793 (exit-after-next org-fast-tag-selection-single-key)
15794 (done-keywords org-done-keywords)
15795 groups ingroup)
15796 (save-excursion
15797 (beginning-of-line 1)
15798 (if (looking-at
15799 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15800 (setq ov-start (match-beginning 1)
15801 ov-end (match-end 1)
15802 ov-prefix "")
15803 (setq ov-start (1- (point-at-eol))
15804 ov-end (1+ ov-start))
15805 (skip-chars-forward "^\n\r")
15806 (setq ov-prefix
15807 (concat
15808 (buffer-substring (1- (point)) (point))
15809 (if (> (current-column) org-tags-column)
15811 (make-string (- org-tags-column (current-column)) ?\ ))))))
15812 (org-move-overlay org-tags-overlay ov-start ov-end)
15813 (save-window-excursion
15814 (if expert
15815 (set-buffer (get-buffer-create " *Org tags*"))
15816 (delete-other-windows)
15817 (split-window-vertically)
15818 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15819 (erase-buffer)
15820 (org-set-local 'org-done-keywords done-keywords)
15821 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15822 (org-fast-tag-insert "Current" current c-face "\n\n")
15823 (org-fast-tag-show-exit exit-after-next)
15824 (org-set-current-tags-overlay current ov-prefix)
15825 (setq tbl fulltable char ?a cnt 0)
15826 (while (setq e (pop tbl))
15827 (cond
15828 ((equal e '(:startgroup))
15829 (push '() groups) (setq ingroup t)
15830 (when (not (= cnt 0))
15831 (setq cnt 0)
15832 (insert "\n"))
15833 (insert "{ "))
15834 ((equal e '(:endgroup))
15835 (setq ingroup nil cnt 0)
15836 (insert "}\n"))
15838 (setq tg (car e) c2 nil)
15839 (if (cdr e)
15840 (setq c (cdr e))
15841 ;; automatically assign a character.
15842 (setq c1 (string-to-char
15843 (downcase (substring
15844 tg (if (= (string-to-char tg) ?@) 1 0)))))
15845 (if (or (rassoc c1 ntable) (rassoc c1 table))
15846 (while (or (rassoc char ntable) (rassoc char table))
15847 (setq char (1+ char)))
15848 (setq c2 c1))
15849 (setq c (or c2 char)))
15850 (if ingroup (push tg (car groups)))
15851 (setq tg (org-add-props tg nil 'face
15852 (cond
15853 ((not (assoc tg table))
15854 (org-get-todo-face tg))
15855 ((member tg current) c-face)
15856 ((member tg inherited) i-face)
15857 (t nil))))
15858 (if (and (= cnt 0) (not ingroup)) (insert " "))
15859 (insert "[" c "] " tg (make-string
15860 (- fwidth 4 (length tg)) ?\ ))
15861 (push (cons tg c) ntable)
15862 (when (= (setq cnt (1+ cnt)) ncol)
15863 (insert "\n")
15864 (if ingroup (insert " "))
15865 (setq cnt 0)))))
15866 (setq ntable (nreverse ntable))
15867 (insert "\n")
15868 (goto-char (point-min))
15869 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15870 (fit-window-to-buffer))
15871 (setq rtn
15872 (catch 'exit
15873 (while t
15874 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15875 (if groups " [!] no groups" " [!]groups")
15876 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15877 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15878 (cond
15879 ((= c ?\r) (throw 'exit t))
15880 ((= c ?!)
15881 (setq groups (not groups))
15882 (goto-char (point-min))
15883 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15884 ((= c ?\C-c)
15885 (if (not expert)
15886 (org-fast-tag-show-exit
15887 (setq exit-after-next (not exit-after-next)))
15888 (setq expert nil)
15889 (delete-other-windows)
15890 (split-window-vertically)
15891 (org-switch-to-buffer-other-window " *Org tags*")
15892 (and (fboundp 'fit-window-to-buffer)
15893 (fit-window-to-buffer))))
15894 ((or (= c ?\C-g)
15895 (and (= c ?q) (not (rassoc c ntable))))
15896 (org-detach-overlay org-tags-overlay)
15897 (setq quit-flag t))
15898 ((= c ?\ )
15899 (setq current nil)
15900 (if exit-after-next (setq exit-after-next 'now)))
15901 ((= c ?\t)
15902 (condition-case nil
15903 (setq tg (completing-read
15904 "Tag: "
15905 (or buffer-tags
15906 (with-current-buffer buf
15907 (org-get-buffer-tags)))))
15908 (quit (setq tg "")))
15909 (when (string-match "\\S-" tg)
15910 (add-to-list 'buffer-tags (list tg))
15911 (if (member tg current)
15912 (setq current (delete tg current))
15913 (push tg current)))
15914 (if exit-after-next (setq exit-after-next 'now)))
15915 ((setq e (rassoc c todo-table) tg (car e))
15916 (with-current-buffer buf
15917 (save-excursion (org-todo tg)))
15918 (if exit-after-next (setq exit-after-next 'now)))
15919 ((setq e (rassoc c ntable) tg (car e))
15920 (if (member tg current)
15921 (setq current (delete tg current))
15922 (loop for g in groups do
15923 (if (member tg g)
15924 (mapc (lambda (x)
15925 (setq current (delete x current)))
15926 g)))
15927 (push tg current))
15928 (if exit-after-next (setq exit-after-next 'now))))
15930 ;; Create a sorted list
15931 (setq current
15932 (sort current
15933 (lambda (a b)
15934 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15935 (if (eq exit-after-next 'now) (throw 'exit t))
15936 (goto-char (point-min))
15937 (beginning-of-line 2)
15938 (delete-region (point) (point-at-eol))
15939 (org-fast-tag-insert "Current" current c-face)
15940 (org-set-current-tags-overlay current ov-prefix)
15941 (while (re-search-forward
15942 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15943 (setq tg (match-string 1))
15944 (add-text-properties
15945 (match-beginning 1) (match-end 1)
15946 (list 'face
15947 (cond
15948 ((member tg current) c-face)
15949 ((member tg inherited) i-face)
15950 (t (get-text-property (match-beginning 1) 'face))))))
15951 (goto-char (point-min)))))
15952 (org-detach-overlay org-tags-overlay)
15953 (if rtn
15954 (mapconcat 'identity current ":")
15955 nil))))
15957 (defun org-get-tags-string ()
15958 "Get the TAGS string in the current headline."
15959 (unless (org-on-heading-p t)
15960 (error "Not on a heading"))
15961 (save-excursion
15962 (beginning-of-line 1)
15963 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15964 (org-match-string-no-properties 1)
15965 "")))
15967 (defun org-get-tags ()
15968 "Get the list of tags specified in the current headline."
15969 (org-split-string (org-get-tags-string) ":"))
15971 (defun org-get-buffer-tags ()
15972 "Get a table of all tags used in the buffer, for completion."
15973 (let (tags)
15974 (save-excursion
15975 (goto-char (point-min))
15976 (while (re-search-forward
15977 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15978 (when (equal (char-after (point-at-bol 0)) ?*)
15979 (mapc (lambda (x) (add-to-list 'tags x))
15980 (org-split-string (org-match-string-no-properties 1) ":")))))
15981 (mapcar 'list tags)))
15984 ;;;; Properties
15986 ;;; Setting and retrieving properties
15988 (defconst org-special-properties
15989 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15990 "TIMESTAMP" "TIMESTAMP_IA")
15991 "The special properties valid in Org-mode.
15993 These are properties that are not defined in the property drawer,
15994 but in some other way.")
15996 (defconst org-default-properties
15997 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15998 "LOCATION" "LOGGING" "COLUMNS")
15999 "Some properties that are used by Org-mode for various purposes.
16000 Being in this list makes sure that they are offered for completion.")
16002 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16003 "Regular expression matching the first line of a property drawer.")
16005 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16006 "Regular expression matching the first line of a property drawer.")
16008 (defun org-property-action ()
16009 "Do an action on properties."
16010 (interactive)
16011 (let (c)
16012 (org-at-property-p)
16013 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16014 (setq c (read-char-exclusive))
16015 (cond
16016 ((equal c ?s)
16017 (call-interactively 'org-set-property))
16018 ((equal c ?d)
16019 (call-interactively 'org-delete-property))
16020 ((equal c ?D)
16021 (call-interactively 'org-delete-property-globally))
16022 ((equal c ?c)
16023 (call-interactively 'org-compute-property-at-point))
16024 (t (error "No such property action %c" c)))))
16026 (defun org-at-property-p ()
16027 "Is the cursor in a property line?"
16028 ;; FIXME: Does not check if we are actually in the drawer.
16029 ;; FIXME: also returns true on any drawers.....
16030 ;; This is used by C-c C-c for property action.
16031 (save-excursion
16032 (beginning-of-line 1)
16033 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16035 (defmacro org-with-point-at (pom &rest body)
16036 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16037 (declare (indent 1) (debug t))
16038 `(save-excursion
16039 (if (markerp pom) (set-buffer (marker-buffer pom)))
16040 (save-excursion
16041 (goto-char (or pom (point)))
16042 ,@body)))
16044 (defun org-get-property-block (&optional beg end force)
16045 "Return the (beg . end) range of the body of the property drawer.
16046 BEG and END can be beginning and end of subtree, if not given
16047 they will be found.
16048 If the drawer does not exist and FORCE is non-nil, create the drawer."
16049 (catch 'exit
16050 (save-excursion
16051 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16052 (end (or end (progn (outline-next-heading) (point)))))
16053 (goto-char beg)
16054 (if (re-search-forward org-property-start-re end t)
16055 (setq beg (1+ (match-end 0)))
16056 (if force
16057 (save-excursion
16058 (org-insert-property-drawer)
16059 (setq end (progn (outline-next-heading) (point))))
16060 (throw 'exit nil))
16061 (goto-char beg)
16062 (if (re-search-forward org-property-start-re end t)
16063 (setq beg (1+ (match-end 0)))))
16064 (if (re-search-forward org-property-end-re end t)
16065 (setq end (match-beginning 0))
16066 (or force (throw 'exit nil))
16067 (goto-char beg)
16068 (setq end beg)
16069 (org-indent-line-function)
16070 (insert ":END:\n"))
16071 (cons beg end)))))
16073 (defun org-entry-properties (&optional pom which)
16074 "Get all properties of the entry at point-or-marker POM.
16075 This includes the TODO keyword, the tags, time strings for deadline,
16076 scheduled, and clocking, and any additional properties defined in the
16077 entry. The return value is an alist, keys may occur multiple times
16078 if the property key was used several times.
16079 POM may also be nil, in which case the current entry is used.
16080 If WHICH is nil or `all', get all properties. If WHICH is
16081 `special' or `standard', only get that subclass."
16082 (setq which (or which 'all))
16083 (org-with-point-at pom
16084 (let ((clockstr (substring org-clock-string 0 -1))
16085 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16086 beg end range props sum-props key value string clocksum)
16087 (save-excursion
16088 (when (condition-case nil (org-back-to-heading t) (error nil))
16089 (setq beg (point))
16090 (setq sum-props (get-text-property (point) 'org-summaries))
16091 (setq clocksum (get-text-property (point) :org-clock-minutes))
16092 (outline-next-heading)
16093 (setq end (point))
16094 (when (memq which '(all special))
16095 ;; Get the special properties, like TODO and tags
16096 (goto-char beg)
16097 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16098 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16099 (when (looking-at org-priority-regexp)
16100 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16101 (when (and (setq value (org-get-tags-string))
16102 (string-match "\\S-" value))
16103 (push (cons "TAGS" value) props))
16104 (when (setq value (org-get-tags-at))
16105 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16106 props))
16107 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16108 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16109 string (if (equal key clockstr)
16110 (org-no-properties
16111 (org-trim
16112 (buffer-substring
16113 (match-beginning 3) (goto-char (point-at-eol)))))
16114 (substring (org-match-string-no-properties 3) 1 -1)))
16115 (unless key
16116 (if (= (char-after (match-beginning 3)) ?\[)
16117 (setq key "TIMESTAMP_IA")
16118 (setq key "TIMESTAMP")))
16119 (when (or (equal key clockstr) (not (assoc key props)))
16120 (push (cons key string) props)))
16124 (when (memq which '(all standard))
16125 ;; Get the standard properties, like :PORP: ...
16126 (setq range (org-get-property-block beg end))
16127 (when range
16128 (goto-char (car range))
16129 (while (re-search-forward
16130 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16131 (cdr range) t)
16132 (setq key (org-match-string-no-properties 1)
16133 value (org-trim (or (org-match-string-no-properties 2) "")))
16134 (unless (member key excluded)
16135 (push (cons key (or value "")) props)))))
16136 (if clocksum
16137 (push (cons "CLOCKSUM"
16138 (org-column-number-to-string (/ (float clocksum) 60.)
16139 'add_times))
16140 props))
16141 (append sum-props (nreverse props)))))))
16143 (defun org-entry-get (pom property &optional inherit)
16144 "Get value of PROPERTY for entry at point-or-marker POM.
16145 If INHERIT is non-nil and the entry does not have the property,
16146 then also check higher levels of the hierarchy.
16147 If the property is present but empty, the return value is the empty string.
16148 If the property is not present at all, nil is returned."
16149 (org-with-point-at pom
16150 (if inherit
16151 (org-entry-get-with-inheritance property)
16152 (if (member property org-special-properties)
16153 ;; We need a special property. Use brute force, get all properties.
16154 (cdr (assoc property (org-entry-properties nil 'special)))
16155 (let ((range (org-get-property-block)))
16156 (if (and range
16157 (goto-char (car range))
16158 (re-search-forward
16159 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16160 (cdr range) t))
16161 ;; Found the property, return it.
16162 (if (match-end 1)
16163 (org-match-string-no-properties 1)
16164 "")))))))
16166 (defun org-entry-delete (pom property)
16167 "Delete the property PROPERTY from entry at point-or-marker POM."
16168 (org-with-point-at pom
16169 (if (member property org-special-properties)
16170 nil ; cannot delete these properties.
16171 (let ((range (org-get-property-block)))
16172 (if (and range
16173 (goto-char (car range))
16174 (re-search-forward
16175 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16176 (cdr range) t))
16177 (progn
16178 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16180 nil)))))
16182 ;; Multi-values properties are properties that contain multiple values
16183 ;; These values are assumed to be single words, separated by whitespace.
16184 (defun org-entry-add-to-multivalued-property (pom property value)
16185 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16186 (let* ((old (org-entry-get pom property))
16187 (values (and old (org-split-string old "[ \t]"))))
16188 (unless (member value values)
16189 (setq values (cons value values))
16190 (org-entry-put pom property
16191 (mapconcat 'identity values " ")))))
16193 (defun org-entry-remove-from-multivalued-property (pom property value)
16194 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16195 (let* ((old (org-entry-get pom property))
16196 (values (and old (org-split-string old "[ \t]"))))
16197 (when (member value values)
16198 (setq values (delete value values))
16199 (org-entry-put pom property
16200 (mapconcat 'identity values " ")))))
16202 (defun org-entry-member-in-multivalued-property (pom property value)
16203 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16204 (let* ((old (org-entry-get pom property))
16205 (values (and old (org-split-string old "[ \t]"))))
16206 (member value values)))
16208 (defvar org-entry-property-inherited-from (make-marker))
16210 (defun org-entry-get-with-inheritance (property)
16211 "Get entry property, and search higher levels if not present."
16212 (let (tmp)
16213 (save-excursion
16214 (save-restriction
16215 (widen)
16216 (catch 'ex
16217 (while t
16218 (when (setq tmp (org-entry-get nil property))
16219 (org-back-to-heading t)
16220 (move-marker org-entry-property-inherited-from (point))
16221 (throw 'ex tmp))
16222 (or (org-up-heading-safe) (throw 'ex nil)))))
16223 (or tmp (cdr (assoc property org-local-properties))
16224 (cdr (assoc property org-global-properties))))))
16226 (defun org-entry-put (pom property value)
16227 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16228 (org-with-point-at pom
16229 (org-back-to-heading t)
16230 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16231 range)
16232 (cond
16233 ((equal property "TODO")
16234 (when (and (stringp value) (string-match "\\S-" value)
16235 (not (member value org-todo-keywords-1)))
16236 (error "\"%s\" is not a valid TODO state" value))
16237 (if (or (not value)
16238 (not (string-match "\\S-" value)))
16239 (setq value 'none))
16240 (org-todo value)
16241 (org-set-tags nil 'align))
16242 ((equal property "PRIORITY")
16243 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16244 (string-to-char value) ?\ ))
16245 (org-set-tags nil 'align))
16246 ((equal property "SCHEDULED")
16247 (if (re-search-forward org-scheduled-time-regexp end t)
16248 (cond
16249 ((eq value 'earlier) (org-timestamp-change -1 'day))
16250 ((eq value 'later) (org-timestamp-change 1 'day))
16251 (t (call-interactively 'org-schedule)))
16252 (call-interactively 'org-schedule)))
16253 ((equal property "DEADLINE")
16254 (if (re-search-forward org-deadline-time-regexp end t)
16255 (cond
16256 ((eq value 'earlier) (org-timestamp-change -1 'day))
16257 ((eq value 'later) (org-timestamp-change 1 'day))
16258 (t (call-interactively 'org-deadline)))
16259 (call-interactively 'org-deadline)))
16260 ((member property org-special-properties)
16261 (error "The %s property can not yet be set with `org-entry-put'"
16262 property))
16263 (t ; a non-special property
16264 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16265 (setq range (org-get-property-block beg end 'force))
16266 (goto-char (car range))
16267 (if (re-search-forward
16268 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16269 (progn
16270 (delete-region (match-beginning 1) (match-end 1))
16271 (goto-char (match-beginning 1)))
16272 (goto-char (cdr range))
16273 (insert "\n")
16274 (backward-char 1)
16275 (org-indent-line-function)
16276 (insert ":" property ":"))
16277 (and value (insert " " value))
16278 (org-indent-line-function)))))))
16280 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16281 "Get all property keys in the current buffer.
16282 With INCLUDE-SPECIALS, also list the special properties that relect things
16283 like tags and TODO state.
16284 With INCLUDE-DEFAULTS, also include properties that has special meaning
16285 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16286 With INCLUDE-COLUMNS, also include property names given in COLUMN
16287 formats in the current buffer."
16288 (let (rtn range cfmt cols s p)
16289 (save-excursion
16290 (save-restriction
16291 (widen)
16292 (goto-char (point-min))
16293 (while (re-search-forward org-property-start-re nil t)
16294 (setq range (org-get-property-block))
16295 (goto-char (car range))
16296 (while (re-search-forward
16297 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16298 (cdr range) t)
16299 (add-to-list 'rtn (org-match-string-no-properties 1)))
16300 (outline-next-heading))))
16302 (when include-specials
16303 (setq rtn (append org-special-properties rtn)))
16305 (when include-defaults
16306 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16308 (when include-columns
16309 (save-excursion
16310 (save-restriction
16311 (widen)
16312 (goto-char (point-min))
16313 (while (re-search-forward
16314 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16315 nil t)
16316 (setq cfmt (match-string 2) s 0)
16317 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16318 cfmt s)
16319 (setq s (match-end 0)
16320 p (match-string 1 cfmt))
16321 (unless (or (equal p "ITEM")
16322 (member p org-special-properties))
16323 (add-to-list 'rtn (match-string 1 cfmt))))))))
16325 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16327 (defun org-property-values (key)
16328 "Return a list of all values of property KEY."
16329 (save-excursion
16330 (save-restriction
16331 (widen)
16332 (goto-char (point-min))
16333 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16334 values)
16335 (while (re-search-forward re nil t)
16336 (add-to-list 'values (org-trim (match-string 1))))
16337 (delete "" values)))))
16339 (defun org-insert-property-drawer ()
16340 "Insert a property drawer into the current entry."
16341 (interactive)
16342 (org-back-to-heading t)
16343 (looking-at outline-regexp)
16344 (let ((indent (- (match-end 0)(match-beginning 0)))
16345 (beg (point))
16346 (re (concat "^[ \t]*" org-keyword-time-regexp))
16347 end hiddenp)
16348 (outline-next-heading)
16349 (setq end (point))
16350 (goto-char beg)
16351 (while (re-search-forward re end t))
16352 (setq hiddenp (org-invisible-p))
16353 (end-of-line 1)
16354 (and (equal (char-after) ?\n) (forward-char 1))
16355 (org-skip-over-state-notes)
16356 (skip-chars-backward " \t\n\r")
16357 (if (eq (char-before) ?*) (forward-char 1))
16358 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16359 (beginning-of-line 0)
16360 (indent-to-column indent)
16361 (beginning-of-line 2)
16362 (indent-to-column indent)
16363 (beginning-of-line 0)
16364 (if hiddenp
16365 (save-excursion
16366 (org-back-to-heading t)
16367 (hide-entry))
16368 (org-flag-drawer t))))
16370 (defun org-set-property (property value)
16371 "In the current entry, set PROPERTY to VALUE.
16372 When called interactively, this will prompt for a property name, offering
16373 completion on existing and default properties. And then it will prompt
16374 for a value, offering competion either on allowed values (via an inherited
16375 xxx_ALL property) or on existing values in other instances of this property
16376 in the current file."
16377 (interactive
16378 (let* ((prop (completing-read
16379 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16380 (cur (org-entry-get nil prop))
16381 (allowed (org-property-get-allowed-values nil prop 'table))
16382 (existing (mapcar 'list (org-property-values prop)))
16383 (val (if allowed
16384 (completing-read "Value: " allowed nil 'req-match)
16385 (completing-read
16386 (concat "Value" (if (and cur (string-match "\\S-" cur))
16387 (concat "[" cur "]") "")
16388 ": ")
16389 existing nil nil "" nil cur))))
16390 (list prop (if (equal val "") cur val))))
16391 (unless (equal (org-entry-get nil property) value)
16392 (org-entry-put nil property value)))
16394 (defun org-delete-property (property)
16395 "In the current entry, delete PROPERTY."
16396 (interactive
16397 (let* ((prop (completing-read
16398 "Property: " (org-entry-properties nil 'standard))))
16399 (list prop)))
16400 (message "Property %s %s" property
16401 (if (org-entry-delete nil property)
16402 "deleted"
16403 "was not present in the entry")))
16405 (defun org-delete-property-globally (property)
16406 "Remove PROPERTY globally, from all entries."
16407 (interactive
16408 (let* ((prop (completing-read
16409 "Globally remove property: "
16410 (mapcar 'list (org-buffer-property-keys)))))
16411 (list prop)))
16412 (save-excursion
16413 (save-restriction
16414 (widen)
16415 (goto-char (point-min))
16416 (let ((cnt 0))
16417 (while (re-search-forward
16418 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16419 nil t)
16420 (setq cnt (1+ cnt))
16421 (replace-match ""))
16422 (message "Property \"%s\" removed from %d entries" property cnt)))))
16424 (defvar org-columns-current-fmt-compiled) ; defined below
16426 (defun org-compute-property-at-point ()
16427 "Compute the property at point.
16428 This looks for an enclosing column format, extracts the operator and
16429 then applies it to the proerty in the column format's scope."
16430 (interactive)
16431 (unless (org-at-property-p)
16432 (error "Not at a property"))
16433 (let ((prop (org-match-string-no-properties 2)))
16434 (org-columns-get-format-and-top-level)
16435 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16436 (error "No operator defined for property %s" prop))
16437 (org-columns-compute prop)))
16439 (defun org-property-get-allowed-values (pom property &optional table)
16440 "Get allowed values for the property PROPERTY.
16441 When TABLE is non-nil, return an alist that can directly be used for
16442 completion."
16443 (let (vals)
16444 (cond
16445 ((equal property "TODO")
16446 (setq vals (org-with-point-at pom
16447 (append org-todo-keywords-1 '("")))))
16448 ((equal property "PRIORITY")
16449 (let ((n org-lowest-priority))
16450 (while (>= n org-highest-priority)
16451 (push (char-to-string n) vals)
16452 (setq n (1- n)))))
16453 ((member property org-special-properties))
16455 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16457 (when (and vals (string-match "\\S-" vals))
16458 (setq vals (car (read-from-string (concat "(" vals ")"))))
16459 (setq vals (mapcar (lambda (x)
16460 (cond ((stringp x) x)
16461 ((numberp x) (number-to-string x))
16462 ((symbolp x) (symbol-name x))
16463 (t "???")))
16464 vals)))))
16465 (if table (mapcar 'list vals) vals)))
16467 (defun org-property-previous-allowed-value (&optional previous)
16468 "Switch to the next allowed value for this property."
16469 (interactive)
16470 (org-property-next-allowed-value t))
16472 (defun org-property-next-allowed-value (&optional previous)
16473 "Switch to the next allowed value for this property."
16474 (interactive)
16475 (unless (org-at-property-p)
16476 (error "Not at a property"))
16477 (let* ((key (match-string 2))
16478 (value (match-string 3))
16479 (allowed (or (org-property-get-allowed-values (point) key)
16480 (and (member value '("[ ]" "[-]" "[X]"))
16481 '("[ ]" "[X]"))))
16482 nval)
16483 (unless allowed
16484 (error "Allowed values for this property have not been defined"))
16485 (if previous (setq allowed (reverse allowed)))
16486 (if (member value allowed)
16487 (setq nval (car (cdr (member value allowed)))))
16488 (setq nval (or nval (car allowed)))
16489 (if (equal nval value)
16490 (error "Only one allowed value for this property"))
16491 (org-at-property-p)
16492 (replace-match (concat " :" key ": " nval) t t)
16493 (org-indent-line-function)
16494 (beginning-of-line 1)
16495 (skip-chars-forward " \t")))
16497 (defun org-find-entry-with-id (ident)
16498 "Locate the entry that contains the ID property with exact value IDENT.
16499 IDENT can be a string, a symbol or a number, this function will search for
16500 the string representation of it.
16501 Return the position where this entry starts, or nil if there is no such entry."
16502 (let ((id (cond
16503 ((stringp ident) ident)
16504 ((symbol-name ident) (symbol-name ident))
16505 ((numberp ident) (number-to-string ident))
16506 (t (error "IDENT %s must be a string, symbol or number" ident))))
16507 (case-fold-search nil))
16508 (save-excursion
16509 (save-restriction
16510 (widen)
16511 (goto-char (point-min))
16512 (when (re-search-forward
16513 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16514 nil t)
16515 (org-back-to-heading)
16516 (point))))))
16518 ;;; Column View
16520 (defvar org-columns-overlays nil
16521 "Holds the list of current column overlays.")
16523 (defvar org-columns-current-fmt nil
16524 "Local variable, holds the currently active column format.")
16525 (defvar org-columns-current-fmt-compiled nil
16526 "Local variable, holds the currently active column format.
16527 This is the compiled version of the format.")
16528 (defvar org-columns-current-widths nil
16529 "Loval variable, holds the currently widths of fields.")
16530 (defvar org-columns-current-maxwidths nil
16531 "Loval variable, holds the currently active maximum column widths.")
16532 (defvar org-columns-begin-marker (make-marker)
16533 "Points to the position where last a column creation command was called.")
16534 (defvar org-columns-top-level-marker (make-marker)
16535 "Points to the position where current columns region starts.")
16537 (defvar org-columns-map (make-sparse-keymap)
16538 "The keymap valid in column display.")
16540 (defun org-columns-content ()
16541 "Switch to contents view while in columns view."
16542 (interactive)
16543 (org-overview)
16544 (org-content))
16546 (org-defkey org-columns-map "c" 'org-columns-content)
16547 (org-defkey org-columns-map "o" 'org-overview)
16548 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16549 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16550 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16551 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16552 (org-defkey org-columns-map "v" 'org-columns-show-value)
16553 (org-defkey org-columns-map "q" 'org-columns-quit)
16554 (org-defkey org-columns-map "r" 'org-columns-redo)
16555 (org-defkey org-columns-map "g" 'org-columns-redo)
16556 (org-defkey org-columns-map [left] 'backward-char)
16557 (org-defkey org-columns-map "\M-b" 'backward-char)
16558 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16559 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16560 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16561 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16562 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16563 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16564 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16565 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16566 (org-defkey org-columns-map "<" 'org-columns-narrow)
16567 (org-defkey org-columns-map ">" 'org-columns-widen)
16568 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16569 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16570 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16571 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16573 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16574 '("Column"
16575 ["Edit property" org-columns-edit-value t]
16576 ["Next allowed value" org-columns-next-allowed-value t]
16577 ["Previous allowed value" org-columns-previous-allowed-value t]
16578 ["Show full value" org-columns-show-value t]
16579 ["Edit allowed values" org-columns-edit-allowed t]
16580 "--"
16581 ["Edit column attributes" org-columns-edit-attributes t]
16582 ["Increase column width" org-columns-widen t]
16583 ["Decrease column width" org-columns-narrow t]
16584 "--"
16585 ["Move column right" org-columns-move-right t]
16586 ["Move column left" org-columns-move-left t]
16587 ["Add column" org-columns-new t]
16588 ["Delete column" org-columns-delete t]
16589 "--"
16590 ["CONTENTS" org-columns-content t]
16591 ["OVERVIEW" org-overview t]
16592 ["Refresh columns display" org-columns-redo t]
16593 "--"
16594 ["Open link" org-columns-open-link t]
16595 "--"
16596 ["Quit" org-columns-quit t]))
16598 (defun org-columns-new-overlay (beg end &optional string face)
16599 "Create a new column overlay and add it to the list."
16600 (let ((ov (org-make-overlay beg end)))
16601 (org-overlay-put ov 'face (or face 'secondary-selection))
16602 (org-overlay-display ov string face)
16603 (push ov org-columns-overlays)
16604 ov))
16606 (defun org-columns-display-here (&optional props)
16607 "Overlay the current line with column display."
16608 (interactive)
16609 (let* ((fmt org-columns-current-fmt-compiled)
16610 (beg (point-at-bol))
16611 (level-face (save-excursion
16612 (beginning-of-line 1)
16613 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16614 (org-get-level-face 2))))
16615 (color (list :foreground
16616 (face-attribute (or level-face 'default) :foreground)))
16617 props pom property ass width f string ov column val modval)
16618 ;; Check if the entry is in another buffer.
16619 (unless props
16620 (if (eq major-mode 'org-agenda-mode)
16621 (setq pom (or (get-text-property (point) 'org-hd-marker)
16622 (get-text-property (point) 'org-marker))
16623 props (if pom (org-entry-properties pom) nil))
16624 (setq props (org-entry-properties nil))))
16625 ;; Walk the format
16626 (while (setq column (pop fmt))
16627 (setq property (car column)
16628 ass (if (equal property "ITEM")
16629 (cons "ITEM"
16630 (save-match-data
16631 (org-no-properties
16632 (org-remove-tabs
16633 (buffer-substring-no-properties
16634 (point-at-bol) (point-at-eol))))))
16635 (assoc property props))
16636 width (or (cdr (assoc property org-columns-current-maxwidths))
16637 (nth 2 column)
16638 (length property))
16639 f (format "%%-%d.%ds | " width width)
16640 val (or (cdr ass) "")
16641 modval (if (equal property "ITEM")
16642 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16643 string (format f (or modval val)))
16644 ;; Create the overlay
16645 (org-unmodified
16646 (setq ov (org-columns-new-overlay
16647 beg (setq beg (1+ beg)) string
16648 (list color 'org-column)))
16649 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16650 (org-overlay-put ov 'keymap org-columns-map)
16651 (org-overlay-put ov 'org-columns-key property)
16652 (org-overlay-put ov 'org-columns-value (cdr ass))
16653 (org-overlay-put ov 'org-columns-value-modified modval)
16654 (org-overlay-put ov 'org-columns-pom pom)
16655 (org-overlay-put ov 'org-columns-format f))
16656 (if (or (not (char-after beg))
16657 (equal (char-after beg) ?\n))
16658 (let ((inhibit-read-only t))
16659 (save-excursion
16660 (goto-char beg)
16661 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16662 ;; Make the rest of the line disappear.
16663 (org-unmodified
16664 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16665 (org-overlay-put ov 'invisible t)
16666 (org-overlay-put ov 'keymap org-columns-map)
16667 (org-overlay-put ov 'intangible t)
16668 (push ov org-columns-overlays)
16669 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16670 (org-overlay-put ov 'keymap org-columns-map)
16671 (push ov org-columns-overlays)
16672 (let ((inhibit-read-only t))
16673 (put-text-property (max (point-min) (1- (point-at-bol)))
16674 (min (point-max) (1+ (point-at-eol)))
16675 'read-only "Type `e' to edit property")))))
16677 (defvar org-previous-header-line-format nil
16678 "The header line format before column view was turned on.")
16679 (defvar org-columns-inhibit-recalculation nil
16680 "Inhibit recomputing of columns on column view startup.")
16683 (defvar header-line-format)
16684 (defun org-columns-display-here-title ()
16685 "Overlay the newline before the current line with the table title."
16686 (interactive)
16687 (let ((fmt org-columns-current-fmt-compiled)
16688 string (title "")
16689 property width f column str widths)
16690 (while (setq column (pop fmt))
16691 (setq property (car column)
16692 str (or (nth 1 column) property)
16693 width (or (cdr (assoc property org-columns-current-maxwidths))
16694 (nth 2 column)
16695 (length str))
16696 widths (push width widths)
16697 f (format "%%-%d.%ds | " width width)
16698 string (format f str)
16699 title (concat title string)))
16700 (setq title (concat
16701 (org-add-props " " nil 'display '(space :align-to 0))
16702 (org-add-props title nil 'face '(:weight bold :underline t))))
16703 (org-set-local 'org-previous-header-line-format header-line-format)
16704 (org-set-local 'org-columns-current-widths (nreverse widths))
16705 (setq header-line-format title)))
16707 (defun org-columns-remove-overlays ()
16708 "Remove all currently active column overlays."
16709 (interactive)
16710 (when (marker-buffer org-columns-begin-marker)
16711 (with-current-buffer (marker-buffer org-columns-begin-marker)
16712 (when (local-variable-p 'org-previous-header-line-format)
16713 (setq header-line-format org-previous-header-line-format)
16714 (kill-local-variable 'org-previous-header-line-format))
16715 (move-marker org-columns-begin-marker nil)
16716 (move-marker org-columns-top-level-marker nil)
16717 (org-unmodified
16718 (mapc 'org-delete-overlay org-columns-overlays)
16719 (setq org-columns-overlays nil)
16720 (let ((inhibit-read-only t))
16721 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16723 (defun org-columns-cleanup-item (item fmt)
16724 "Remove from ITEM what is a column in the format FMT."
16725 (if (not org-complex-heading-regexp)
16726 item
16727 (when (string-match org-complex-heading-regexp item)
16728 (concat
16729 (org-add-props (concat (match-string 1 item) " ") nil
16730 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16731 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16732 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16733 " " (match-string 4 item)
16734 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16736 (defun org-columns-show-value ()
16737 "Show the full value of the property."
16738 (interactive)
16739 (let ((value (get-char-property (point) 'org-columns-value)))
16740 (message "Value is: %s" (or value ""))))
16742 (defun org-columns-quit ()
16743 "Remove the column overlays and in this way exit column editing."
16744 (interactive)
16745 (org-unmodified
16746 (org-columns-remove-overlays)
16747 (let ((inhibit-read-only t))
16748 (remove-text-properties (point-min) (point-max) '(read-only t))))
16749 (when (eq major-mode 'org-agenda-mode)
16750 (message
16751 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16753 (defun org-columns-check-computed ()
16754 "Check if this column value is computed.
16755 If yes, throw an error indicating that changing it does not make sense."
16756 (let ((val (get-char-property (point) 'org-columns-value)))
16757 (when (and (stringp val)
16758 (get-char-property 0 'org-computed val))
16759 (error "This value is computed from the entry's children"))))
16761 (defun org-columns-todo (&optional arg)
16762 "Change the TODO state during column view."
16763 (interactive "P")
16764 (org-columns-edit-value "TODO"))
16766 (defun org-columns-set-tags-or-toggle (&optional arg)
16767 "Toggle checkbox at point, or set tags for current headline."
16768 (interactive "P")
16769 (if (string-match "\\`\\[[ xX-]\\]\\'"
16770 (get-char-property (point) 'org-columns-value))
16771 (org-columns-next-allowed-value)
16772 (org-columns-edit-value "TAGS")))
16774 (defun org-columns-edit-value (&optional key)
16775 "Edit the value of the property at point in column view.
16776 Where possible, use the standard interface for changing this line."
16777 (interactive)
16778 (org-columns-check-computed)
16779 (let* ((external-key key)
16780 (col (current-column))
16781 (key (or key (get-char-property (point) 'org-columns-key)))
16782 (value (get-char-property (point) 'org-columns-value))
16783 (bol (point-at-bol)) (eol (point-at-eol))
16784 (pom (or (get-text-property bol 'org-hd-marker)
16785 (point))) ; keep despite of compiler waring
16786 (line-overlays
16787 (delq nil (mapcar (lambda (x)
16788 (and (eq (overlay-buffer x) (current-buffer))
16789 (>= (overlay-start x) bol)
16790 (<= (overlay-start x) eol)
16792 org-columns-overlays)))
16793 nval eval allowed)
16794 (cond
16795 ((equal key "CLOCKSUM")
16796 (error "This special column cannot be edited"))
16797 ((equal key "ITEM")
16798 (setq eval '(org-with-point-at pom
16799 (org-edit-headline))))
16800 ((equal key "TODO")
16801 (setq eval '(org-with-point-at pom
16802 (let ((current-prefix-arg
16803 (if external-key current-prefix-arg '(4))))
16804 (call-interactively 'org-todo)))))
16805 ((equal key "PRIORITY")
16806 (setq eval '(org-with-point-at pom
16807 (call-interactively 'org-priority))))
16808 ((equal key "TAGS")
16809 (setq eval '(org-with-point-at pom
16810 (let ((org-fast-tag-selection-single-key
16811 (if (eq org-fast-tag-selection-single-key 'expert)
16812 t org-fast-tag-selection-single-key)))
16813 (call-interactively 'org-set-tags)))))
16814 ((equal key "DEADLINE")
16815 (setq eval '(org-with-point-at pom
16816 (call-interactively 'org-deadline))))
16817 ((equal key "SCHEDULED")
16818 (setq eval '(org-with-point-at pom
16819 (call-interactively 'org-schedule))))
16821 (setq allowed (org-property-get-allowed-values pom key 'table))
16822 (if allowed
16823 (setq nval (completing-read "Value: " allowed nil t))
16824 (setq nval (read-string "Edit: " value)))
16825 (setq nval (org-trim nval))
16826 (when (not (equal nval value))
16827 (setq eval '(org-entry-put pom key nval)))))
16828 (when eval
16829 (let ((inhibit-read-only t))
16830 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16831 (unwind-protect
16832 (progn
16833 (setq org-columns-overlays
16834 (org-delete-all line-overlays org-columns-overlays))
16835 (mapc 'org-delete-overlay line-overlays)
16836 (org-columns-eval eval))
16837 (org-columns-display-here))))
16838 (move-to-column col)
16839 (if (and (org-mode-p)
16840 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16841 (org-columns-update key))))
16843 (defun org-edit-headline () ; FIXME: this is not columns specific
16844 "Edit the current headline, the part without TODO keyword, TAGS."
16845 (org-back-to-heading)
16846 (when (looking-at org-todo-line-regexp)
16847 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16848 (txt (match-string 3))
16849 (post "")
16850 txt2)
16851 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16852 (setq post (match-string 0 txt)
16853 txt (substring txt 0 (match-beginning 0))))
16854 (setq txt2 (read-string "Edit: " txt))
16855 (when (not (equal txt txt2))
16856 (beginning-of-line 1)
16857 (insert pre txt2 post)
16858 (delete-region (point) (point-at-eol))
16859 (org-set-tags nil t)))))
16861 (defun org-columns-edit-allowed ()
16862 "Edit the list of allowed values for the current property."
16863 (interactive)
16864 (let* ((key (get-char-property (point) 'org-columns-key))
16865 (key1 (concat key "_ALL"))
16866 (allowed (org-entry-get (point) key1 t))
16867 nval)
16868 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16869 (setq nval (read-string "Allowed: " allowed))
16870 (org-entry-put
16871 (cond ((marker-position org-entry-property-inherited-from)
16872 org-entry-property-inherited-from)
16873 ((marker-position org-columns-top-level-marker)
16874 org-columns-top-level-marker))
16875 key1 nval)))
16877 (defmacro org-no-warnings (&rest body)
16878 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16880 (defun org-columns-eval (form)
16881 (let (hidep)
16882 (save-excursion
16883 (beginning-of-line 1)
16884 ;; `next-line' is needed here, because it skips invisible line.
16885 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16886 (setq hidep (org-on-heading-p 1)))
16887 (eval form)
16888 (and hidep (hide-entry))))
16890 (defun org-columns-previous-allowed-value ()
16891 "Switch to the previous allowed value for this column."
16892 (interactive)
16893 (org-columns-next-allowed-value t))
16895 (defun org-columns-next-allowed-value (&optional previous)
16896 "Switch to the next allowed value for this column."
16897 (interactive)
16898 (org-columns-check-computed)
16899 (let* ((col (current-column))
16900 (key (get-char-property (point) 'org-columns-key))
16901 (value (get-char-property (point) 'org-columns-value))
16902 (bol (point-at-bol)) (eol (point-at-eol))
16903 (pom (or (get-text-property bol 'org-hd-marker)
16904 (point))) ; keep despite of compiler waring
16905 (line-overlays
16906 (delq nil (mapcar (lambda (x)
16907 (and (eq (overlay-buffer x) (current-buffer))
16908 (>= (overlay-start x) bol)
16909 (<= (overlay-start x) eol)
16911 org-columns-overlays)))
16912 (allowed (or (org-property-get-allowed-values pom key)
16913 (and (memq
16914 (nth 4 (assoc key org-columns-current-fmt-compiled))
16915 '(checkbox checkbox-n-of-m checkbox-percent))
16916 '("[ ]" "[X]"))))
16917 nval)
16918 (when (equal key "ITEM")
16919 (error "Cannot edit item headline from here"))
16920 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16921 (error "Allowed values for this property have not been defined"))
16922 (if (member key '("SCHEDULED" "DEADLINE"))
16923 (setq nval (if previous 'earlier 'later))
16924 (if previous (setq allowed (reverse allowed)))
16925 (if (member value allowed)
16926 (setq nval (car (cdr (member value allowed)))))
16927 (setq nval (or nval (car allowed)))
16928 (if (equal nval value)
16929 (error "Only one allowed value for this property")))
16930 (let ((inhibit-read-only t))
16931 (remove-text-properties (1- bol) eol '(read-only t))
16932 (unwind-protect
16933 (progn
16934 (setq org-columns-overlays
16935 (org-delete-all line-overlays org-columns-overlays))
16936 (mapc 'org-delete-overlay line-overlays)
16937 (org-columns-eval '(org-entry-put pom key nval)))
16938 (org-columns-display-here)))
16939 (move-to-column col)
16940 (if (and (org-mode-p)
16941 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16942 (org-columns-update key))))
16944 (defun org-verify-version (task)
16945 (cond
16946 ((eq task 'columns)
16947 (if (or (featurep 'xemacs)
16948 (< emacs-major-version 22))
16949 (error "Emacs 22 is required for the columns feature")))))
16951 (defun org-columns-open-link (&optional arg)
16952 (interactive "P")
16953 (let ((value (get-char-property (point) 'org-columns-value)))
16954 (org-open-link-from-string value arg)))
16956 (defun org-open-link-from-string (s &optional arg)
16957 "Open a link in the string S, as if it was in Org-mode."
16958 (interactive)
16959 (with-temp-buffer
16960 (let ((org-inhibit-startup t))
16961 (org-mode)
16962 (insert s)
16963 (goto-char (point-min))
16964 (org-open-at-point arg))))
16966 (defun org-columns-get-format-and-top-level ()
16967 (let (fmt)
16968 (when (condition-case nil (org-back-to-heading) (error nil))
16969 (move-marker org-entry-property-inherited-from nil)
16970 (setq fmt (org-entry-get nil "COLUMNS" t)))
16971 (setq fmt (or fmt org-columns-default-format))
16972 (org-set-local 'org-columns-current-fmt fmt)
16973 (org-columns-compile-format fmt)
16974 (if (marker-position org-entry-property-inherited-from)
16975 (move-marker org-columns-top-level-marker
16976 org-entry-property-inherited-from)
16977 (move-marker org-columns-top-level-marker (point)))
16978 fmt))
16980 (defun org-columns ()
16981 "Turn on column view on an org-mode file."
16982 (interactive)
16983 (org-verify-version 'columns)
16984 (org-columns-remove-overlays)
16985 (move-marker org-columns-begin-marker (point))
16986 (let (beg end fmt cache maxwidths)
16987 (setq fmt (org-columns-get-format-and-top-level))
16988 (save-excursion
16989 (goto-char org-columns-top-level-marker)
16990 (setq beg (point))
16991 (unless org-columns-inhibit-recalculation
16992 (org-columns-compute-all))
16993 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16994 (point-max)))
16995 ;; Get and cache the properties
16996 (goto-char beg)
16997 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16998 (save-excursion
16999 (save-restriction
17000 (narrow-to-region beg end)
17001 (org-clock-sum))))
17002 (while (re-search-forward (concat "^" outline-regexp) end t)
17003 (push (cons (org-current-line) (org-entry-properties)) cache))
17004 (when cache
17005 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17006 (org-set-local 'org-columns-current-maxwidths maxwidths)
17007 (org-columns-display-here-title)
17008 (mapc (lambda (x)
17009 (goto-line (car x))
17010 (org-columns-display-here (cdr x)))
17011 cache)))))
17013 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17014 "Insert a new column, to the leeft o the current column."
17015 (interactive)
17016 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17017 cell)
17018 (setq prop (completing-read
17019 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17020 nil nil prop))
17021 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17022 (setq width (read-string "Column width: " (if width (number-to-string width))))
17023 (if (string-match "\\S-" width)
17024 (setq width (string-to-number width))
17025 (setq width nil))
17026 (setq fmt (completing-read "Summary [none]: "
17027 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17028 nil t))
17029 (if (string-match "\\S-" fmt)
17030 (setq fmt (intern fmt))
17031 (setq fmt nil))
17032 (if (eq fmt 'none) (setq fmt nil))
17033 (if editp
17034 (progn
17035 (setcar editp prop)
17036 (setcdr editp (list title width nil fmt)))
17037 (setq cell (nthcdr (1- (current-column))
17038 org-columns-current-fmt-compiled))
17039 (setcdr cell (cons (list prop title width nil fmt)
17040 (cdr cell))))
17041 (org-columns-store-format)
17042 (org-columns-redo)))
17044 (defun org-columns-delete ()
17045 "Delete the column at point from columns view."
17046 (interactive)
17047 (let* ((n (current-column))
17048 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17049 (when (y-or-n-p
17050 (format "Are you sure you want to remove column \"%s\"? " title))
17051 (setq org-columns-current-fmt-compiled
17052 (delq (nth n org-columns-current-fmt-compiled)
17053 org-columns-current-fmt-compiled))
17054 (org-columns-store-format)
17055 (org-columns-redo)
17056 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17057 (backward-char 1)))))
17059 (defun org-columns-edit-attributes ()
17060 "Edit the attributes of the current column."
17061 (interactive)
17062 (let* ((n (current-column))
17063 (info (nth n org-columns-current-fmt-compiled)))
17064 (apply 'org-columns-new info)))
17066 (defun org-columns-widen (arg)
17067 "Make the column wider by ARG characters."
17068 (interactive "p")
17069 (let* ((n (current-column))
17070 (entry (nth n org-columns-current-fmt-compiled))
17071 (width (or (nth 2 entry)
17072 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17073 (setq width (max 1 (+ width arg)))
17074 (setcar (nthcdr 2 entry) width)
17075 (org-columns-store-format)
17076 (org-columns-redo)))
17078 (defun org-columns-narrow (arg)
17079 "Make the column nrrower by ARG characters."
17080 (interactive "p")
17081 (org-columns-widen (- arg)))
17083 (defun org-columns-move-right ()
17084 "Swap this column with the one to the right."
17085 (interactive)
17086 (let* ((n (current-column))
17087 (cell (nthcdr n org-columns-current-fmt-compiled))
17089 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17090 (error "Cannot shift this column further to the right"))
17091 (setq e (car cell))
17092 (setcar cell (car (cdr cell)))
17093 (setcdr cell (cons e (cdr (cdr cell))))
17094 (org-columns-store-format)
17095 (org-columns-redo)
17096 (forward-char 1)))
17098 (defun org-columns-move-left ()
17099 "Swap this column with the one to the left."
17100 (interactive)
17101 (let* ((n (current-column)))
17102 (when (= n 0)
17103 (error "Cannot shift this column further to the left"))
17104 (backward-char 1)
17105 (org-columns-move-right)
17106 (backward-char 1)))
17108 (defun org-columns-store-format ()
17109 "Store the text version of the current columns format in appropriate place.
17110 This is either in the COLUMNS property of the node starting the current column
17111 display, or in the #+COLUMNS line of the current buffer."
17112 (let (fmt (cnt 0))
17113 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17114 (org-set-local 'org-columns-current-fmt fmt)
17115 (if (marker-position org-columns-top-level-marker)
17116 (save-excursion
17117 (goto-char org-columns-top-level-marker)
17118 (if (and (org-at-heading-p)
17119 (org-entry-get nil "COLUMNS"))
17120 (org-entry-put nil "COLUMNS" fmt)
17121 (goto-char (point-min))
17122 ;; Overwrite all #+COLUMNS lines....
17123 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17124 (setq cnt (1+ cnt))
17125 (replace-match (concat "#+COLUMNS: " fmt) t t))
17126 (unless (> cnt 0)
17127 (goto-char (point-min))
17128 (or (org-on-heading-p t) (outline-next-heading))
17129 (let ((inhibit-read-only t))
17130 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17131 (org-set-local 'org-columns-default-format fmt))))))
17133 (defvar org-overriding-columns-format nil
17134 "When set, overrides any other definition.")
17135 (defvar org-agenda-view-columns-initially nil
17136 "When set, switch to columns view immediately after creating the agenda.")
17138 (defun org-agenda-columns ()
17139 "Turn on column view in the agenda."
17140 (interactive)
17141 (org-verify-version 'columns)
17142 (org-columns-remove-overlays)
17143 (move-marker org-columns-begin-marker (point))
17144 (let (fmt cache maxwidths m)
17145 (cond
17146 ((and (local-variable-p 'org-overriding-columns-format)
17147 org-overriding-columns-format)
17148 (setq fmt org-overriding-columns-format))
17149 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17150 (setq fmt (org-entry-get m "COLUMNS" t)))
17151 ((and (boundp 'org-columns-current-fmt)
17152 (local-variable-p 'org-columns-current-fmt)
17153 org-columns-current-fmt)
17154 (setq fmt org-columns-current-fmt))
17155 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17156 (setq m (get-text-property m 'org-hd-marker))
17157 (setq fmt (org-entry-get m "COLUMNS" t))))
17158 (setq fmt (or fmt org-columns-default-format))
17159 (org-set-local 'org-columns-current-fmt fmt)
17160 (org-columns-compile-format fmt)
17161 (save-excursion
17162 ;; Get and cache the properties
17163 (goto-char (point-min))
17164 (while (not (eobp))
17165 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17166 (get-text-property (point) 'org-marker)))
17167 (push (cons (org-current-line) (org-entry-properties m)) cache))
17168 (beginning-of-line 2))
17169 (when cache
17170 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17171 (org-set-local 'org-columns-current-maxwidths maxwidths)
17172 (org-columns-display-here-title)
17173 (mapc (lambda (x)
17174 (goto-line (car x))
17175 (org-columns-display-here (cdr x)))
17176 cache)))))
17178 (defun org-columns-get-autowidth-alist (s cache)
17179 "Derive the maximum column widths from the format and the cache."
17180 (let ((start 0) rtn)
17181 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17182 (push (cons (match-string 1 s) 1) rtn)
17183 (setq start (match-end 0)))
17184 (mapc (lambda (x)
17185 (setcdr x (apply 'max
17186 (mapcar
17187 (lambda (y)
17188 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17189 cache))))
17190 rtn)
17191 rtn))
17193 (defun org-columns-compute-all ()
17194 "Compute all columns that have operators defined."
17195 (org-unmodified
17196 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17197 (let ((columns org-columns-current-fmt-compiled) col)
17198 (while (setq col (pop columns))
17199 (when (nth 3 col)
17200 (save-excursion
17201 (org-columns-compute (car col)))))))
17203 (defun org-columns-update (property)
17204 "Recompute PROPERTY, and update the columns display for it."
17205 (org-columns-compute property)
17206 (let (fmt val pos)
17207 (save-excursion
17208 (mapc (lambda (ov)
17209 (when (equal (org-overlay-get ov 'org-columns-key) property)
17210 (setq pos (org-overlay-start ov))
17211 (goto-char pos)
17212 (when (setq val (cdr (assoc property
17213 (get-text-property
17214 (point-at-bol) 'org-summaries))))
17215 (setq fmt (org-overlay-get ov 'org-columns-format))
17216 (org-overlay-put ov 'org-columns-value val)
17217 (org-overlay-put ov 'display (format fmt val)))))
17218 org-columns-overlays))))
17220 (defun org-columns-compute (property)
17221 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17222 (interactive)
17223 (let* ((re (concat "^" outline-regexp))
17224 (lmax 30) ; Does anyone use deeper levels???
17225 (lsum (make-vector lmax 0))
17226 (lflag (make-vector lmax nil))
17227 (level 0)
17228 (ass (assoc property org-columns-current-fmt-compiled))
17229 (format (nth 4 ass))
17230 (printf (nth 5 ass))
17231 (beg org-columns-top-level-marker)
17232 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17233 (save-excursion
17234 ;; Find the region to compute
17235 (goto-char beg)
17236 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17237 (goto-char end)
17238 ;; Walk the tree from the back and do the computations
17239 (while (re-search-backward re beg t)
17240 (setq sumpos (match-beginning 0)
17241 last-level level
17242 level (org-outline-level)
17243 val (org-entry-get nil property)
17244 valflag (and val (string-match "\\S-" val)))
17245 (cond
17246 ((< level last-level)
17247 ;; put the sum of lower levels here as a property
17248 (setq sum (aref lsum last-level) ; current sum
17249 flag (aref lflag last-level) ; any valid entries from children?
17250 str (org-column-number-to-string sum format printf)
17251 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17252 useval (if flag str1 (if valflag val ""))
17253 sum-alist (get-text-property sumpos 'org-summaries))
17254 (if (assoc property sum-alist)
17255 (setcdr (assoc property sum-alist) useval)
17256 (push (cons property useval) sum-alist)
17257 (org-unmodified
17258 (add-text-properties sumpos (1+ sumpos)
17259 (list 'org-summaries sum-alist))))
17260 (when val
17261 (org-entry-put nil property (if flag str val)))
17262 ;; add current to current level accumulator
17263 (when (or flag valflag)
17264 (aset lsum level (+ (aref lsum level)
17265 (if flag sum (org-column-string-to-number
17266 (if flag str val) format))))
17267 (aset lflag level t))
17268 ;; clear accumulators for deeper levels
17269 (loop for l from (1+ level) to (1- lmax) do
17270 (aset lsum l 0)
17271 (aset lflag l nil)))
17272 ((>= level last-level)
17273 ;; add what we have here to the accumulator for this level
17274 (aset lsum level (+ (aref lsum level)
17275 (org-column-string-to-number (or val "0") format)))
17276 (and valflag (aset lflag level t)))
17277 (t (error "This should not happen")))))))
17279 (defun org-columns-redo ()
17280 "Construct the column display again."
17281 (interactive)
17282 (message "Recomputing columns...")
17283 (save-excursion
17284 (if (marker-position org-columns-begin-marker)
17285 (goto-char org-columns-begin-marker))
17286 (org-columns-remove-overlays)
17287 (if (org-mode-p)
17288 (call-interactively 'org-columns)
17289 (call-interactively 'org-agenda-columns)))
17290 (message "Recomputing columns...done"))
17292 (defun org-columns-not-in-agenda ()
17293 (if (eq major-mode 'org-agenda-mode)
17294 (error "This command is only allowed in Org-mode buffers")))
17297 (defun org-string-to-number (s)
17298 "Convert string to number, and interpret hh:mm:ss."
17299 (if (not (string-match ":" s))
17300 (string-to-number s)
17301 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17302 (while l
17303 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17304 sum)))
17306 (defun org-column-number-to-string (n fmt &optional printf)
17307 "Convert a computed column number to a string value, according to FMT."
17308 (cond
17309 ((eq fmt 'add_times)
17310 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17311 (format "%d:%02d" h m)))
17312 ((eq fmt 'checkbox)
17313 (cond ((= n (floor n)) "[X]")
17314 ((> n 1.) "[-]")
17315 (t "[ ]")))
17316 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17317 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17318 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17319 (printf (format printf n))
17320 ((eq fmt 'currency)
17321 (format "%.2f" n))
17322 (t (number-to-string n))))
17324 (defun org-nofm-to-completion (n m &optional percent)
17325 (if (not percent)
17326 (format "[%d/%d]" n m)
17327 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17329 (defun org-column-string-to-number (s fmt)
17330 "Convert a column value to a number that can be used for column computing."
17331 (cond
17332 ((string-match ":" s)
17333 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17334 (while l
17335 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17336 sum))
17337 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17338 (if (equal s "[X]") 1. 0.000001))
17339 (t (string-to-number s))))
17341 (defun org-columns-uncompile-format (cfmt)
17342 "Turn the compiled columns format back into a string representation."
17343 (let ((rtn "") e s prop title op width fmt printf)
17344 (while (setq e (pop cfmt))
17345 (setq prop (car e)
17346 title (nth 1 e)
17347 width (nth 2 e)
17348 op (nth 3 e)
17349 fmt (nth 4 e)
17350 printf (nth 5 e))
17351 (cond
17352 ((eq fmt 'add_times) (setq op ":"))
17353 ((eq fmt 'checkbox) (setq op "X"))
17354 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17355 ((eq fmt 'checkbox-percent) (setq op "X%"))
17356 ((eq fmt 'add_numbers) (setq op "+"))
17357 ((eq fmt 'currency) (setq op "$")))
17358 (if (and op printf) (setq op (concat op ";" printf)))
17359 (if (equal title prop) (setq title nil))
17360 (setq s (concat "%" (if width (number-to-string width))
17361 prop
17362 (if title (concat "(" title ")"))
17363 (if op (concat "{" op "}"))))
17364 (setq rtn (concat rtn " " s)))
17365 (org-trim rtn)))
17367 (defun org-columns-compile-format (fmt)
17368 "Turn a column format string into an alist of specifications.
17369 The alist has one entry for each column in the format. The elements of
17370 that list are:
17371 property the property
17372 title the title field for the columns
17373 width the column width in characters, can be nil for automatic
17374 operator the operator if any
17375 format the output format for computed results, derived from operator
17376 printf a printf format for computed values"
17377 (let ((start 0) width prop title op f printf)
17378 (setq org-columns-current-fmt-compiled nil)
17379 (while (string-match
17380 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17381 fmt start)
17382 (setq start (match-end 0)
17383 width (match-string 1 fmt)
17384 prop (match-string 2 fmt)
17385 title (or (match-string 3 fmt) prop)
17386 op (match-string 4 fmt)
17387 f nil
17388 printf nil)
17389 (if width (setq width (string-to-number width)))
17390 (when (and op (string-match ";" op))
17391 (setq printf (substring op (match-end 0))
17392 op (substring op 0 (match-beginning 0))))
17393 (cond
17394 ((equal op "+") (setq f 'add_numbers))
17395 ((equal op "$") (setq f 'currency))
17396 ((equal op ":") (setq f 'add_times))
17397 ((equal op "X") (setq f 'checkbox))
17398 ((equal op "X/") (setq f 'checkbox-n-of-m))
17399 ((equal op "X%") (setq f 'checkbox-percent))
17401 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17402 (setq org-columns-current-fmt-compiled
17403 (nreverse org-columns-current-fmt-compiled))))
17406 ;;; Dynamic block for Column view
17408 (defun org-columns-capture-view ()
17409 "Get the column view of the current buffer and return it as a list.
17410 The list will contains the title row and all other rows. Each row is
17411 a list of fields."
17412 (save-excursion
17413 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17414 (n (length title)) row tbl)
17415 (goto-char (point-min))
17416 (while (re-search-forward "^\\*+ " nil t)
17417 (when (get-char-property (match-beginning 0) 'org-columns-key)
17418 (setq row nil)
17419 (loop for i from 0 to (1- n) do
17420 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17421 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17423 row))
17424 (setq row (nreverse row))
17425 (push row tbl)))
17426 (append (list title 'hline) (nreverse tbl)))))
17428 (defun org-dblock-write:columnview (params)
17429 "Write the column view table.
17430 PARAMS is a property list of parameters:
17432 :width enforce same column widths with <N> specifiers.
17433 :id the :ID: property of the entry where the columns view
17434 should be built, as a string. When `local', call locally.
17435 When `global' call column view with the cursor at the beginning
17436 of the buffer (usually this means that the whole buffer switches
17437 to column view).
17438 :hlines When t, insert a hline before each item. When a number, insert
17439 a hline before each level <= that number.
17440 :vlines When t, make each column a colgroup to enforce vertical lines."
17441 (let ((pos (move-marker (make-marker) (point)))
17442 (hlines (plist-get params :hlines))
17443 (vlines (plist-get params :vlines))
17444 tbl id idpos nfields tmp)
17445 (save-excursion
17446 (save-restriction
17447 (when (setq id (plist-get params :id))
17448 (cond ((not id) nil)
17449 ((eq id 'global) (goto-char (point-min)))
17450 ((eq id 'local) nil)
17451 ((setq idpos (org-find-entry-with-id id))
17452 (goto-char idpos))
17453 (t (error "Cannot find entry with :ID: %s" id))))
17454 (org-columns)
17455 (setq tbl (org-columns-capture-view))
17456 (setq nfields (length (car tbl)))
17457 (org-columns-quit)))
17458 (goto-char pos)
17459 (move-marker pos nil)
17460 (when tbl
17461 (when (plist-get params :hlines)
17462 (setq tmp nil)
17463 (while tbl
17464 (if (eq (car tbl) 'hline)
17465 (push (pop tbl) tmp)
17466 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17467 (if (and (not (eq (car tmp) 'hline))
17468 (or (eq hlines t)
17469 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17470 (push 'hline tmp)))
17471 (push (pop tbl) tmp)))
17472 (setq tbl (nreverse tmp)))
17473 (when vlines
17474 (setq tbl (mapcar (lambda (x)
17475 (if (eq 'hline x) x (cons "" x)))
17476 tbl))
17477 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17478 (setq pos (point))
17479 (insert (org-listtable-to-string tbl))
17480 (when (plist-get params :width)
17481 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17482 org-columns-current-widths "|")))
17483 (goto-char pos)
17484 (org-table-align))))
17486 (defun org-listtable-to-string (tbl)
17487 "Convert a listtable TBL to a string that contains the Org-mode table.
17488 The table still need to be alligned. The resulting string has no leading
17489 and tailing newline characters."
17490 (mapconcat
17491 (lambda (x)
17492 (cond
17493 ((listp x)
17494 (concat "|" (mapconcat 'identity x "|") "|"))
17495 ((eq x 'hline) "|-|")
17496 (t (error "Garbage in listtable: %s" x))))
17497 tbl "\n"))
17499 (defun org-insert-columns-dblock ()
17500 "Create a dynamic block capturing a column view table."
17501 (interactive)
17502 (let ((defaults '(:name "columnview" :hlines 1))
17503 (id (completing-read
17504 "Capture columns (local, global, entry with :ID: property) [local]: "
17505 (append '(("global") ("local"))
17506 (mapcar 'list (org-property-values "ID"))))))
17507 (if (equal id "") (setq id 'local))
17508 (if (equal id "global") (setq id 'global))
17509 (setq defaults (append defaults (list :id id)))
17510 (org-create-dblock defaults)
17511 (org-update-dblock)))
17513 ;;;; Timestamps
17515 (defvar org-last-changed-timestamp nil)
17516 (defvar org-time-was-given) ; dynamically scoped parameter
17517 (defvar org-end-time-was-given) ; dynamically scoped parameter
17518 (defvar org-ts-what) ; dynamically scoped parameter
17520 (defun org-time-stamp (arg)
17521 "Prompt for a date/time and insert a time stamp.
17522 If the user specifies a time like HH:MM, or if this command is called
17523 with a prefix argument, the time stamp will contain date and time.
17524 Otherwise, only the date will be included. All parts of a date not
17525 specified by the user will be filled in from the current date/time.
17526 So if you press just return without typing anything, the time stamp
17527 will represent the current date/time. If there is already a timestamp
17528 at the cursor, it will be modified."
17529 (interactive "P")
17530 (let* ((ts nil)
17531 (default-time
17532 ;; Default time is either today, or, when entering a range,
17533 ;; the range start.
17534 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17535 (save-excursion
17536 (re-search-backward
17537 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17538 (- (point) 20) t)))
17539 (apply 'encode-time (org-parse-time-string (match-string 1)))
17540 (current-time)))
17541 (default-input (and ts (org-get-compact-tod ts)))
17542 org-time-was-given org-end-time-was-given time)
17543 (cond
17544 ((and (org-at-timestamp-p)
17545 (eq last-command 'org-time-stamp)
17546 (eq this-command 'org-time-stamp))
17547 (insert "--")
17548 (setq time (let ((this-command this-command))
17549 (org-read-date arg 'totime nil nil default-time default-input)))
17550 (org-insert-time-stamp time (or org-time-was-given arg)))
17551 ((org-at-timestamp-p)
17552 (setq time (let ((this-command this-command))
17553 (org-read-date arg 'totime nil nil default-time default-input)))
17554 (when (org-at-timestamp-p) ; just to get the match data
17555 (replace-match "")
17556 (setq org-last-changed-timestamp
17557 (org-insert-time-stamp
17558 time (or org-time-was-given arg)
17559 nil nil nil (list org-end-time-was-given))))
17560 (message "Timestamp updated"))
17562 (setq time (let ((this-command this-command))
17563 (org-read-date arg 'totime nil nil default-time default-input)))
17564 (org-insert-time-stamp time (or org-time-was-given arg)
17565 nil nil nil (list org-end-time-was-given))))))
17567 ;; FIXME: can we use this for something else????
17568 ;; like computing time differences?????
17569 (defun org-get-compact-tod (s)
17570 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17571 (let* ((t1 (match-string 1 s))
17572 (h1 (string-to-number (match-string 2 s)))
17573 (m1 (string-to-number (match-string 3 s)))
17574 (t2 (and (match-end 4) (match-string 5 s)))
17575 (h2 (and t2 (string-to-number (match-string 6 s))))
17576 (m2 (and t2 (string-to-number (match-string 7 s))))
17577 dh dm)
17578 (if (not t2)
17580 (setq dh (- h2 h1) dm (- m2 m1))
17581 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17582 (concat t1 "+" (number-to-string dh)
17583 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17585 (defun org-time-stamp-inactive (&optional arg)
17586 "Insert an inactive time stamp.
17587 An inactive time stamp is enclosed in square brackets instead of angle
17588 brackets. It is inactive in the sense that it does not trigger agenda entries,
17589 does not link to the calendar and cannot be changed with the S-cursor keys.
17590 So these are more for recording a certain time/date."
17591 (interactive "P")
17592 (let (org-time-was-given org-end-time-was-given time)
17593 (setq time (org-read-date arg 'totime))
17594 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17595 nil nil (list org-end-time-was-given))))
17597 (defvar org-date-ovl (org-make-overlay 1 1))
17598 (org-overlay-put org-date-ovl 'face 'org-warning)
17599 (org-detach-overlay org-date-ovl)
17601 (defvar org-ans1) ; dynamically scoped parameter
17602 (defvar org-ans2) ; dynamically scoped parameter
17604 (defvar org-plain-time-of-day-regexp) ; defined below
17606 (defvar org-read-date-overlay nil)
17607 (defvar org-dcst nil) ; dynamically scoped
17609 (defun org-read-date (&optional with-time to-time from-string prompt
17610 default-time default-input)
17611 "Read a date, possibly a time, and make things smooth for the user.
17612 The prompt will suggest to enter an ISO date, but you can also enter anything
17613 which will at least partially be understood by `parse-time-string'.
17614 Unrecognized parts of the date will default to the current day, month, year,
17615 hour and minute. If this command is called to replace a timestamp at point,
17616 of to enter the second timestamp of a range, the default time is taken from the
17617 existing stamp. For example,
17618 3-2-5 --> 2003-02-05
17619 feb 15 --> currentyear-02-15
17620 sep 12 9 --> 2009-09-12
17621 12:45 --> today 12:45
17622 22 sept 0:34 --> currentyear-09-22 0:34
17623 12 --> currentyear-currentmonth-12
17624 Fri --> nearest Friday (today or later)
17625 etc.
17627 Furthermore you can specify a relative date by giving, as the *first* thing
17628 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17629 change in days weeks, months, years.
17630 With a single plus or minus, the date is relative to today. With a double
17631 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17632 +4d --> four days from today
17633 +4 --> same as above
17634 +2w --> two weeks from today
17635 ++5 --> five days from default date
17637 The function understands only English month and weekday abbreviations,
17638 but this can be configured with the variables `parse-time-months' and
17639 `parse-time-weekdays'.
17641 While prompting, a calendar is popped up - you can also select the
17642 date with the mouse (button 1). The calendar shows a period of three
17643 months. To scroll it to other months, use the keys `>' and `<'.
17644 If you don't like the calendar, turn it off with
17645 \(setq org-read-date-popup-calendar nil)
17647 With optional argument TO-TIME, the date will immediately be converted
17648 to an internal time.
17649 With an optional argument WITH-TIME, the prompt will suggest to also
17650 insert a time. Note that when WITH-TIME is not set, you can still
17651 enter a time, and this function will inform the calling routine about
17652 this change. The calling routine may then choose to change the format
17653 used to insert the time stamp into the buffer to include the time.
17654 With optional argument FROM-STRING, read from this string instead from
17655 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17656 the time/date that is used for everything that is not specified by the
17657 user."
17658 (require 'parse-time)
17659 (let* ((org-time-stamp-rounding-minutes
17660 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17661 (org-dcst org-display-custom-times)
17662 (ct (org-current-time))
17663 (def (or default-time ct))
17664 (defdecode (decode-time def))
17665 (dummy (progn
17666 (when (< (nth 2 defdecode) org-extend-today-until)
17667 (setcar (nthcdr 2 defdecode) -1)
17668 (setcar (nthcdr 1 defdecode) 59)
17669 (setq def (apply 'encode-time defdecode)
17670 defdecode (decode-time def)))))
17671 (calendar-move-hook nil)
17672 (view-diary-entries-initially nil)
17673 (view-calendar-holidays-initially nil)
17674 (timestr (format-time-string
17675 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17676 (prompt (concat (if prompt (concat prompt " ") "")
17677 (format "Date+time [%s]: " timestr)))
17678 ans (org-ans0 "") org-ans1 org-ans2 final)
17680 (cond
17681 (from-string (setq ans from-string))
17682 (org-read-date-popup-calendar
17683 (save-excursion
17684 (save-window-excursion
17685 (calendar)
17686 (calendar-forward-day (- (time-to-days def)
17687 (calendar-absolute-from-gregorian
17688 (calendar-current-date))))
17689 (org-eval-in-calendar nil t)
17690 (let* ((old-map (current-local-map))
17691 (map (copy-keymap calendar-mode-map))
17692 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17693 (org-defkey map (kbd "RET") 'org-calendar-select)
17694 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17695 'org-calendar-select-mouse)
17696 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17697 'org-calendar-select-mouse)
17698 (org-defkey minibuffer-local-map [(meta shift left)]
17699 (lambda () (interactive)
17700 (org-eval-in-calendar '(calendar-backward-month 1))))
17701 (org-defkey minibuffer-local-map [(meta shift right)]
17702 (lambda () (interactive)
17703 (org-eval-in-calendar '(calendar-forward-month 1))))
17704 (org-defkey minibuffer-local-map [(meta shift up)]
17705 (lambda () (interactive)
17706 (org-eval-in-calendar '(calendar-backward-year 1))))
17707 (org-defkey minibuffer-local-map [(meta shift down)]
17708 (lambda () (interactive)
17709 (org-eval-in-calendar '(calendar-forward-year 1))))
17710 (org-defkey minibuffer-local-map [(shift up)]
17711 (lambda () (interactive)
17712 (org-eval-in-calendar '(calendar-backward-week 1))))
17713 (org-defkey minibuffer-local-map [(shift down)]
17714 (lambda () (interactive)
17715 (org-eval-in-calendar '(calendar-forward-week 1))))
17716 (org-defkey minibuffer-local-map [(shift left)]
17717 (lambda () (interactive)
17718 (org-eval-in-calendar '(calendar-backward-day 1))))
17719 (org-defkey minibuffer-local-map [(shift right)]
17720 (lambda () (interactive)
17721 (org-eval-in-calendar '(calendar-forward-day 1))))
17722 (org-defkey minibuffer-local-map ">"
17723 (lambda () (interactive)
17724 (org-eval-in-calendar '(scroll-calendar-left 1))))
17725 (org-defkey minibuffer-local-map "<"
17726 (lambda () (interactive)
17727 (org-eval-in-calendar '(scroll-calendar-right 1))))
17728 (unwind-protect
17729 (progn
17730 (use-local-map map)
17731 (add-hook 'post-command-hook 'org-read-date-display)
17732 (setq org-ans0 (read-string prompt default-input nil nil))
17733 ;; org-ans0: from prompt
17734 ;; org-ans1: from mouse click
17735 ;; org-ans2: from calendar motion
17736 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17737 (remove-hook 'post-command-hook 'org-read-date-display)
17738 (use-local-map old-map)
17739 (when org-read-date-overlay
17740 (org-delete-overlay org-read-date-overlay)
17741 (setq org-read-date-overlay nil)))))))
17743 (t ; Naked prompt only
17744 (unwind-protect
17745 (setq ans (read-string prompt default-input nil timestr))
17746 (when org-read-date-overlay
17747 (org-delete-overlay org-read-date-overlay)
17748 (setq org-read-date-overlay nil)))))
17750 (setq final (org-read-date-analyze ans def defdecode))
17752 (if to-time
17753 (apply 'encode-time final)
17754 (if (and (boundp 'org-time-was-given) org-time-was-given)
17755 (format "%04d-%02d-%02d %02d:%02d"
17756 (nth 5 final) (nth 4 final) (nth 3 final)
17757 (nth 2 final) (nth 1 final))
17758 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17759 (defvar def)
17760 (defvar defdecode)
17761 (defvar with-time)
17762 (defun org-read-date-display ()
17763 "Display the currrent date prompt interpretation in the minibuffer."
17764 (when org-read-date-display-live
17765 (when org-read-date-overlay
17766 (org-delete-overlay org-read-date-overlay))
17767 (let ((p (point)))
17768 (end-of-line 1)
17769 (while (not (equal (buffer-substring
17770 (max (point-min) (- (point) 4)) (point))
17771 " "))
17772 (insert " "))
17773 (goto-char p))
17774 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17775 " " (or org-ans1 org-ans2)))
17776 (org-end-time-was-given nil)
17777 (f (org-read-date-analyze ans def defdecode))
17778 (fmts (if org-dcst
17779 org-time-stamp-custom-formats
17780 org-time-stamp-formats))
17781 (fmt (if (or with-time
17782 (and (boundp 'org-time-was-given) org-time-was-given))
17783 (cdr fmts)
17784 (car fmts)))
17785 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17786 (when (and org-end-time-was-given
17787 (string-match org-plain-time-of-day-regexp txt))
17788 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17789 org-end-time-was-given
17790 (substring txt (match-end 0)))))
17791 (setq org-read-date-overlay
17792 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17793 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17795 (defun org-read-date-analyze (ans def defdecode)
17796 "Analyze the combined answer of the date prompt."
17797 ;; FIXME: cleanup and comment
17798 (let (delta deltan deltaw deltadef year month day
17799 hour minute second wday pm h2 m2 tl wday1)
17801 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17802 (setq ans (replace-match "" t t ans)
17803 deltan (car delta)
17804 deltaw (nth 1 delta)
17805 deltadef (nth 2 delta)))
17807 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17808 (when (string-match
17809 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17810 (setq year (if (match-end 2)
17811 (string-to-number (match-string 2 ans))
17812 (string-to-number (format-time-string "%Y")))
17813 month (string-to-number (match-string 3 ans))
17814 day (string-to-number (match-string 4 ans)))
17815 (if (< year 100) (setq year (+ 2000 year)))
17816 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17817 t nil ans)))
17818 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17819 ;; If there is a time with am/pm, and *no* time without it, we convert
17820 ;; so that matching will be successful.
17821 (loop for i from 1 to 2 do ; twice, for end time as well
17822 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17823 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17824 (setq hour (string-to-number (match-string 1 ans))
17825 minute (if (match-end 3)
17826 (string-to-number (match-string 3 ans))
17828 pm (equal ?p
17829 (string-to-char (downcase (match-string 4 ans)))))
17830 (if (and (= hour 12) (not pm))
17831 (setq hour 0)
17832 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17833 (setq ans (replace-match (format "%02d:%02d" hour minute)
17834 t t ans))))
17836 ;; Check if a time range is given as a duration
17837 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17838 (setq hour (string-to-number (match-string 1 ans))
17839 h2 (+ hour (string-to-number (match-string 3 ans)))
17840 minute (string-to-number (match-string 2 ans))
17841 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17842 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17843 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17845 ;; Check if there is a time range
17846 (when (boundp 'org-end-time-was-given)
17847 (setq org-time-was-given nil)
17848 (when (and (string-match org-plain-time-of-day-regexp ans)
17849 (match-end 8))
17850 (setq org-end-time-was-given (match-string 8 ans))
17851 (setq ans (concat (substring ans 0 (match-beginning 7))
17852 (substring ans (match-end 7))))))
17854 (setq tl (parse-time-string ans)
17855 day (or (nth 3 tl) (nth 3 defdecode))
17856 month (or (nth 4 tl)
17857 (if (and org-read-date-prefer-future
17858 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17859 (1+ (nth 4 defdecode))
17860 (nth 4 defdecode)))
17861 year (or (nth 5 tl)
17862 (if (and org-read-date-prefer-future
17863 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17864 (1+ (nth 5 defdecode))
17865 (nth 5 defdecode)))
17866 hour (or (nth 2 tl) (nth 2 defdecode))
17867 minute (or (nth 1 tl) (nth 1 defdecode))
17868 second (or (nth 0 tl) 0)
17869 wday (nth 6 tl))
17870 (when deltan
17871 (unless deltadef
17872 (let ((now (decode-time (current-time))))
17873 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17874 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17875 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17876 ((equal deltaw "m") (setq month (+ month deltan)))
17877 ((equal deltaw "y") (setq year (+ year deltan)))))
17878 (when (and wday (not (nth 3 tl)))
17879 ;; Weekday was given, but no day, so pick that day in the week
17880 ;; on or after the derived date.
17881 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17882 (unless (equal wday wday1)
17883 (setq day (+ day (% (- wday wday1 -7) 7)))))
17884 (if (and (boundp 'org-time-was-given)
17885 (nth 2 tl))
17886 (setq org-time-was-given t))
17887 (if (< year 100) (setq year (+ 2000 year)))
17888 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17889 (list second minute hour day month year)))
17891 (defvar parse-time-weekdays)
17893 (defun org-read-date-get-relative (s today default)
17894 "Check string S for special relative date string.
17895 TODAY and DEFAULT are internal times, for today and for a default.
17896 Return shift list (N what def-flag)
17897 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17898 N is the number of WHATs to shift.
17899 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17900 the DEFAULT date rather than TODAY."
17901 (when (string-match
17902 (concat
17903 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17904 "\\([0-9]+\\)?"
17905 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17906 "\\([ \t]\\|$\\)") s)
17907 (let* ((dir (if (match-end 1)
17908 (string-to-char (substring (match-string 1 s) -1))
17909 ?+))
17910 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17911 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17912 (what (if (match-end 3) (match-string 3 s) "d"))
17913 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17914 (date (if rel default today))
17915 (wday (nth 6 (decode-time date)))
17916 delta)
17917 (if wday1
17918 (progn
17919 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17920 (if (= dir ?-) (setq delta (- delta 7)))
17921 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17922 (list delta "d" rel))
17923 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17925 (defun org-eval-in-calendar (form &optional keepdate)
17926 "Eval FORM in the calendar window and return to current window.
17927 Also, store the cursor date in variable org-ans2."
17928 (let ((sw (selected-window)))
17929 (select-window (get-buffer-window "*Calendar*"))
17930 (eval form)
17931 (when (and (not keepdate) (calendar-cursor-to-date))
17932 (let* ((date (calendar-cursor-to-date))
17933 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17934 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17935 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17936 (select-window sw)))
17938 ; ;; Update the prompt to show new default date
17939 ; (save-excursion
17940 ; (goto-char (point-min))
17941 ; (when (and org-ans2
17942 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17943 ; (get-text-property (match-end 0) 'field))
17944 ; (let ((inhibit-read-only t))
17945 ; (replace-match (concat "[" org-ans2 "]") t t)
17946 ; (add-text-properties (point-min) (1+ (match-end 0))
17947 ; (text-properties-at (1+ (point-min)))))))))
17949 (defun org-calendar-select ()
17950 "Return to `org-read-date' with the date currently selected.
17951 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17952 (interactive)
17953 (when (calendar-cursor-to-date)
17954 (let* ((date (calendar-cursor-to-date))
17955 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17956 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17957 (if (active-minibuffer-window) (exit-minibuffer))))
17959 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17960 "Insert a date stamp for the date given by the internal TIME.
17961 WITH-HM means, use the stamp format that includes the time of the day.
17962 INACTIVE means use square brackets instead of angular ones, so that the
17963 stamp will not contribute to the agenda.
17964 PRE and POST are optional strings to be inserted before and after the
17965 stamp.
17966 The command returns the inserted time stamp."
17967 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17968 stamp)
17969 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17970 (insert-before-markers (or pre ""))
17971 (insert-before-markers (setq stamp (format-time-string fmt time)))
17972 (when (listp extra)
17973 (setq extra (car extra))
17974 (if (and (stringp extra)
17975 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17976 (setq extra (format "-%02d:%02d"
17977 (string-to-number (match-string 1 extra))
17978 (string-to-number (match-string 2 extra))))
17979 (setq extra nil)))
17980 (when extra
17981 (backward-char 1)
17982 (insert-before-markers extra)
17983 (forward-char 1))
17984 (insert-before-markers (or post ""))
17985 stamp))
17987 (defun org-toggle-time-stamp-overlays ()
17988 "Toggle the use of custom time stamp formats."
17989 (interactive)
17990 (setq org-display-custom-times (not org-display-custom-times))
17991 (unless org-display-custom-times
17992 (let ((p (point-min)) (bmp (buffer-modified-p)))
17993 (while (setq p (next-single-property-change p 'display))
17994 (if (and (get-text-property p 'display)
17995 (eq (get-text-property p 'face) 'org-date))
17996 (remove-text-properties
17997 p (setq p (next-single-property-change p 'display))
17998 '(display t))))
17999 (set-buffer-modified-p bmp)))
18000 (if (featurep 'xemacs)
18001 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18002 (org-restart-font-lock)
18003 (setq org-table-may-need-update t)
18004 (if org-display-custom-times
18005 (message "Time stamps are overlayed with custom format")
18006 (message "Time stamp overlays removed")))
18008 (defun org-display-custom-time (beg end)
18009 "Overlay modified time stamp format over timestamp between BED and END."
18010 (let* ((ts (buffer-substring beg end))
18011 t1 w1 with-hm tf time str w2 (off 0))
18012 (save-match-data
18013 (setq t1 (org-parse-time-string ts t))
18014 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18015 (setq off (- (match-end 0) (match-beginning 0)))))
18016 (setq end (- end off))
18017 (setq w1 (- end beg)
18018 with-hm (and (nth 1 t1) (nth 2 t1))
18019 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18020 time (org-fix-decoded-time t1)
18021 str (org-add-props
18022 (format-time-string
18023 (substring tf 1 -1) (apply 'encode-time time))
18024 nil 'mouse-face 'highlight)
18025 w2 (length str))
18026 (if (not (= w2 w1))
18027 (add-text-properties (1+ beg) (+ 2 beg)
18028 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18029 (if (featurep 'xemacs)
18030 (progn
18031 (put-text-property beg end 'invisible t)
18032 (put-text-property beg end 'end-glyph (make-glyph str)))
18033 (put-text-property beg end 'display str))))
18035 (defun org-translate-time (string)
18036 "Translate all timestamps in STRING to custom format.
18037 But do this only if the variable `org-display-custom-times' is set."
18038 (when org-display-custom-times
18039 (save-match-data
18040 (let* ((start 0)
18041 (re org-ts-regexp-both)
18042 t1 with-hm inactive tf time str beg end)
18043 (while (setq start (string-match re string start))
18044 (setq beg (match-beginning 0)
18045 end (match-end 0)
18046 t1 (save-match-data
18047 (org-parse-time-string (substring string beg end) t))
18048 with-hm (and (nth 1 t1) (nth 2 t1))
18049 inactive (equal (substring string beg (1+ beg)) "[")
18050 tf (funcall (if with-hm 'cdr 'car)
18051 org-time-stamp-custom-formats)
18052 time (org-fix-decoded-time t1)
18053 str (format-time-string
18054 (concat
18055 (if inactive "[" "<") (substring tf 1 -1)
18056 (if inactive "]" ">"))
18057 (apply 'encode-time time))
18058 string (replace-match str t t string)
18059 start (+ start (length str)))))))
18060 string)
18062 (defun org-fix-decoded-time (time)
18063 "Set 0 instead of nil for the first 6 elements of time.
18064 Don't touch the rest."
18065 (let ((n 0))
18066 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18068 (defun org-days-to-time (timestamp-string)
18069 "Difference between TIMESTAMP-STRING and now in days."
18070 (- (time-to-days (org-time-string-to-time timestamp-string))
18071 (time-to-days (current-time))))
18073 (defun org-deadline-close (timestamp-string &optional ndays)
18074 "Is the time in TIMESTAMP-STRING close to the current date?"
18075 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18076 (and (< (org-days-to-time timestamp-string) ndays)
18077 (not (org-entry-is-done-p))))
18079 (defun org-get-wdays (ts)
18080 "Get the deadline lead time appropriate for timestring TS."
18081 (cond
18082 ((<= org-deadline-warning-days 0)
18083 ;; 0 or negative, enforce this value no matter what
18084 (- org-deadline-warning-days))
18085 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18086 ;; lead time is specified.
18087 (floor (* (string-to-number (match-string 1 ts))
18088 (cdr (assoc (match-string 2 ts)
18089 '(("d" . 1) ("w" . 7)
18090 ("m" . 30.4) ("y" . 365.25)))))))
18091 ;; go for the default.
18092 (t org-deadline-warning-days)))
18094 (defun org-calendar-select-mouse (ev)
18095 "Return to `org-read-date' with the date currently selected.
18096 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18097 (interactive "e")
18098 (mouse-set-point ev)
18099 (when (calendar-cursor-to-date)
18100 (let* ((date (calendar-cursor-to-date))
18101 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18102 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18103 (if (active-minibuffer-window) (exit-minibuffer))))
18105 (defun org-check-deadlines (ndays)
18106 "Check if there are any deadlines due or past due.
18107 A deadline is considered due if it happens within `org-deadline-warning-days'
18108 days from today's date. If the deadline appears in an entry marked DONE,
18109 it is not shown. The prefix arg NDAYS can be used to test that many
18110 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18111 (interactive "P")
18112 (let* ((org-warn-days
18113 (cond
18114 ((equal ndays '(4)) 100000)
18115 (ndays (prefix-numeric-value ndays))
18116 (t (abs org-deadline-warning-days))))
18117 (case-fold-search nil)
18118 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18119 (callback
18120 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18122 (message "%d deadlines past-due or due within %d days"
18123 (org-occur regexp nil callback)
18124 org-warn-days)))
18126 (defun org-check-before-date (date)
18127 "Check if there are deadlines or scheduled entries before DATE."
18128 (interactive (list (org-read-date)))
18129 (let ((case-fold-search nil)
18130 (regexp (concat "\\<\\(" org-deadline-string
18131 "\\|" org-scheduled-string
18132 "\\) *<\\([^>]+\\)>"))
18133 (callback
18134 (lambda () (time-less-p
18135 (org-time-string-to-time (match-string 2))
18136 (org-time-string-to-time date)))))
18137 (message "%d entries before %s"
18138 (org-occur regexp nil callback) date)))
18140 (defun org-evaluate-time-range (&optional to-buffer)
18141 "Evaluate a time range by computing the difference between start and end.
18142 Normally the result is just printed in the echo area, but with prefix arg
18143 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18144 If the time range is actually in a table, the result is inserted into the
18145 next column.
18146 For time difference computation, a year is assumed to be exactly 365
18147 days in order to avoid rounding problems."
18148 (interactive "P")
18150 (org-clock-update-time-maybe)
18151 (save-excursion
18152 (unless (org-at-date-range-p t)
18153 (goto-char (point-at-bol))
18154 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18155 (if (not (org-at-date-range-p t))
18156 (error "Not at a time-stamp range, and none found in current line")))
18157 (let* ((ts1 (match-string 1))
18158 (ts2 (match-string 2))
18159 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18160 (match-end (match-end 0))
18161 (time1 (org-time-string-to-time ts1))
18162 (time2 (org-time-string-to-time ts2))
18163 (t1 (time-to-seconds time1))
18164 (t2 (time-to-seconds time2))
18165 (diff (abs (- t2 t1)))
18166 (negative (< (- t2 t1) 0))
18167 ;; (ys (floor (* 365 24 60 60)))
18168 (ds (* 24 60 60))
18169 (hs (* 60 60))
18170 (fy "%dy %dd %02d:%02d")
18171 (fy1 "%dy %dd")
18172 (fd "%dd %02d:%02d")
18173 (fd1 "%dd")
18174 (fh "%02d:%02d")
18175 y d h m align)
18176 (if havetime
18177 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18179 d (floor (/ diff ds)) diff (mod diff ds)
18180 h (floor (/ diff hs)) diff (mod diff hs)
18181 m (floor (/ diff 60)))
18182 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18184 d (floor (+ (/ diff ds) 0.5))
18185 h 0 m 0))
18186 (if (not to-buffer)
18187 (message "%s" (org-make-tdiff-string y d h m))
18188 (if (org-at-table-p)
18189 (progn
18190 (goto-char match-end)
18191 (setq align t)
18192 (and (looking-at " *|") (goto-char (match-end 0))))
18193 (goto-char match-end))
18194 (if (looking-at
18195 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18196 (replace-match ""))
18197 (if negative (insert " -"))
18198 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18199 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18200 (insert " " (format fh h m))))
18201 (if align (org-table-align))
18202 (message "Time difference inserted")))))
18204 (defun org-make-tdiff-string (y d h m)
18205 (let ((fmt "")
18206 (l nil))
18207 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18208 l (push y l)))
18209 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18210 l (push d l)))
18211 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18212 l (push h l)))
18213 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18214 l (push m l)))
18215 (apply 'format fmt (nreverse l))))
18217 (defun org-time-string-to-time (s)
18218 (apply 'encode-time (org-parse-time-string s)))
18220 (defun org-time-string-to-absolute (s &optional daynr prefer)
18221 "Convert a time stamp to an absolute day number.
18222 If there is a specifyer for a cyclic time stamp, get the closest date to
18223 DAYNR."
18224 (cond
18225 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18226 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18227 daynr
18228 (+ daynr 1000)))
18229 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18230 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18231 (time-to-days (current-time))) (match-string 0 s)
18232 prefer))
18233 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18235 (defun org-time-from-absolute (d)
18236 "Return the time corresponding to date D.
18237 D may be an absolute day number, or a calendar-type list (month day year)."
18238 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18239 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18241 (defun org-calendar-holiday ()
18242 "List of holidays, for Diary display in Org-mode."
18243 (require 'holidays)
18244 (let ((hl (funcall
18245 (if (fboundp 'calendar-check-holidays)
18246 'calendar-check-holidays 'check-calendar-holidays) date)))
18247 (if hl (mapconcat 'identity hl "; "))))
18249 (defun org-diary-sexp-entry (sexp entry date)
18250 "Process a SEXP diary ENTRY for DATE."
18251 (require 'diary-lib)
18252 (let ((result (if calendar-debug-sexp
18253 (let ((stack-trace-on-error t))
18254 (eval (car (read-from-string sexp))))
18255 (condition-case nil
18256 (eval (car (read-from-string sexp)))
18257 (error
18258 (beep)
18259 (message "Bad sexp at line %d in %s: %s"
18260 (org-current-line)
18261 (buffer-file-name) sexp)
18262 (sleep-for 2))))))
18263 (cond ((stringp result) result)
18264 ((and (consp result)
18265 (stringp (cdr result))) (cdr result))
18266 (result entry)
18267 (t nil))))
18269 (defun org-diary-to-ical-string (frombuf)
18270 "Get iCalendar entries from diary entries in buffer FROMBUF.
18271 This uses the icalendar.el library."
18272 (let* ((tmpdir (if (featurep 'xemacs)
18273 (temp-directory)
18274 temporary-file-directory))
18275 (tmpfile (make-temp-name
18276 (expand-file-name "orgics" tmpdir)))
18277 buf rtn b e)
18278 (save-excursion
18279 (set-buffer frombuf)
18280 (icalendar-export-region (point-min) (point-max) tmpfile)
18281 (setq buf (find-buffer-visiting tmpfile))
18282 (set-buffer buf)
18283 (goto-char (point-min))
18284 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18285 (setq b (match-beginning 0)))
18286 (goto-char (point-max))
18287 (if (re-search-backward "^END:VEVENT" nil t)
18288 (setq e (match-end 0)))
18289 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18290 (kill-buffer buf)
18291 (kill-buffer frombuf)
18292 (delete-file tmpfile)
18293 rtn))
18295 (defun org-closest-date (start current change prefer)
18296 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18297 When PREFER is `past' return a date that is either CURRENT or past.
18298 When PREFER is `future', return a date that is either CURRENT or future."
18299 ;; Make the proper lists from the dates
18300 (catch 'exit
18301 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18302 dn dw sday cday n1 n2
18303 d m y y1 y2 date1 date2 nmonths nm ny m2)
18305 (setq start (org-date-to-gregorian start)
18306 current (org-date-to-gregorian
18307 (if org-agenda-repeating-timestamp-show-all
18308 current
18309 (time-to-days (current-time))))
18310 sday (calendar-absolute-from-gregorian start)
18311 cday (calendar-absolute-from-gregorian current))
18313 (if (<= cday sday) (throw 'exit sday))
18315 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18316 (setq dn (string-to-number (match-string 1 change))
18317 dw (cdr (assoc (match-string 2 change) a1)))
18318 (error "Invalid change specifyer: %s" change))
18319 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18320 (cond
18321 ((eq dw 'day)
18322 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18323 n2 (+ n1 dn)))
18324 ((eq dw 'year)
18325 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18326 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18327 (setq date1 (list m d y1)
18328 n1 (calendar-absolute-from-gregorian date1)
18329 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18330 n2 (calendar-absolute-from-gregorian date2)))
18331 ((eq dw 'month)
18332 ;; approx number of month between the tow dates
18333 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18334 ;; How often does dn fit in there?
18335 (setq d (nth 1 start) m (car start) y (nth 2 start)
18336 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18337 m (+ m nm)
18338 ny (floor (/ m 12))
18339 y (+ y ny)
18340 m (- m (* ny 12)))
18341 (while (> m 12) (setq m (- m 12) y (1+ y)))
18342 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18343 (setq m2 (+ m dn) y2 y)
18344 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18345 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18346 (while (< n2 cday)
18347 (setq n1 n2 m m2 y y2)
18348 (setq m2 (+ m dn) y2 y)
18349 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18350 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18352 (if org-agenda-repeating-timestamp-show-all
18353 (cond
18354 ((eq prefer 'past) n1)
18355 ((eq prefer 'future) (if (= cday n1) n1 n2))
18356 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18357 (cond
18358 ((eq prefer 'past) n1)
18359 ((eq prefer 'future) (if (= cday n1) n1 n2))
18360 (t (if (= cday n1) n1 n2)))))))
18362 (defun org-date-to-gregorian (date)
18363 "Turn any specification of DATE into a gregorian date for the calendar."
18364 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18365 ((and (listp date) (= (length date) 3)) date)
18366 ((stringp date)
18367 (setq date (org-parse-time-string date))
18368 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18369 ((listp date)
18370 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18372 (defun org-parse-time-string (s &optional nodefault)
18373 "Parse the standard Org-mode time string.
18374 This should be a lot faster than the normal `parse-time-string'.
18375 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18376 hour and minute fields will be nil if not given."
18377 (if (string-match org-ts-regexp0 s)
18378 (list 0
18379 (if (or (match-beginning 8) (not nodefault))
18380 (string-to-number (or (match-string 8 s) "0")))
18381 (if (or (match-beginning 7) (not nodefault))
18382 (string-to-number (or (match-string 7 s) "0")))
18383 (string-to-number (match-string 4 s))
18384 (string-to-number (match-string 3 s))
18385 (string-to-number (match-string 2 s))
18386 nil nil nil)
18387 (make-list 9 0)))
18389 (defun org-timestamp-up (&optional arg)
18390 "Increase the date item at the cursor by one.
18391 If the cursor is on the year, change the year. If it is on the month or
18392 the day, change that.
18393 With prefix ARG, change by that many units."
18394 (interactive "p")
18395 (org-timestamp-change (prefix-numeric-value arg)))
18397 (defun org-timestamp-down (&optional arg)
18398 "Decrease the date item at the cursor by one.
18399 If the cursor is on the year, change the year. If it is on the month or
18400 the day, change that.
18401 With prefix ARG, change by that many units."
18402 (interactive "p")
18403 (org-timestamp-change (- (prefix-numeric-value arg))))
18405 (defun org-timestamp-up-day (&optional arg)
18406 "Increase the date in the time stamp by one day.
18407 With prefix ARG, change that many days."
18408 (interactive "p")
18409 (if (and (not (org-at-timestamp-p t))
18410 (org-on-heading-p))
18411 (org-todo 'up)
18412 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18414 (defun org-timestamp-down-day (&optional arg)
18415 "Decrease the date in the time stamp by one day.
18416 With prefix ARG, change that many days."
18417 (interactive "p")
18418 (if (and (not (org-at-timestamp-p t))
18419 (org-on-heading-p))
18420 (org-todo 'down)
18421 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18423 (defsubst org-pos-in-match-range (pos n)
18424 (and (match-beginning n)
18425 (<= (match-beginning n) pos)
18426 (>= (match-end n) pos)))
18428 (defun org-at-timestamp-p (&optional inactive-ok)
18429 "Determine if the cursor is in or at a timestamp."
18430 (interactive)
18431 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18432 (pos (point))
18433 (ans (or (looking-at tsr)
18434 (save-excursion
18435 (skip-chars-backward "^[<\n\r\t")
18436 (if (> (point) (point-min)) (backward-char 1))
18437 (and (looking-at tsr)
18438 (> (- (match-end 0) pos) -1))))))
18439 (and ans
18440 (boundp 'org-ts-what)
18441 (setq org-ts-what
18442 (cond
18443 ((= pos (match-beginning 0)) 'bracket)
18444 ((= pos (1- (match-end 0))) 'bracket)
18445 ((org-pos-in-match-range pos 2) 'year)
18446 ((org-pos-in-match-range pos 3) 'month)
18447 ((org-pos-in-match-range pos 7) 'hour)
18448 ((org-pos-in-match-range pos 8) 'minute)
18449 ((or (org-pos-in-match-range pos 4)
18450 (org-pos-in-match-range pos 5)) 'day)
18451 ((and (> pos (or (match-end 8) (match-end 5)))
18452 (< pos (match-end 0)))
18453 (- pos (or (match-end 8) (match-end 5))))
18454 (t 'day))))
18455 ans))
18457 (defun org-toggle-timestamp-type ()
18459 (interactive)
18460 (when (org-at-timestamp-p t)
18461 (save-excursion
18462 (goto-char (match-beginning 0))
18463 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18464 (goto-char (1- (match-end 0)))
18465 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18466 (message "Timestamp is now %sactive"
18467 (if (equal (char-before) ?>) "in" ""))))
18469 (defun org-timestamp-change (n &optional what)
18470 "Change the date in the time stamp at point.
18471 The date will be changed by N times WHAT. WHAT can be `day', `month',
18472 `year', `minute', `second'. If WHAT is not given, the cursor position
18473 in the timestamp determines what will be changed."
18474 (let ((pos (point))
18475 with-hm inactive
18476 org-ts-what
18477 extra
18478 ts time time0)
18479 (if (not (org-at-timestamp-p t))
18480 (error "Not at a timestamp"))
18481 (if (and (not what) (eq org-ts-what 'bracket))
18482 (org-toggle-timestamp-type)
18483 (if (and (not what) (not (eq org-ts-what 'day))
18484 org-display-custom-times
18485 (get-text-property (point) 'display)
18486 (not (get-text-property (1- (point)) 'display)))
18487 (setq org-ts-what 'day))
18488 (setq org-ts-what (or what org-ts-what)
18489 inactive (= (char-after (match-beginning 0)) ?\[)
18490 ts (match-string 0))
18491 (replace-match "")
18492 (if (string-match
18493 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18495 (setq extra (match-string 1 ts)))
18496 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18497 (setq with-hm t))
18498 (setq time0 (org-parse-time-string ts))
18499 (setq time
18500 (encode-time (or (car time0) 0)
18501 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18502 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18503 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18504 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18505 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18506 (nthcdr 6 time0)))
18507 (when (integerp org-ts-what)
18508 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18509 (if (eq what 'calendar)
18510 (let ((cal-date (org-get-date-from-calendar)))
18511 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18512 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18513 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18514 (setcar time0 (or (car time0) 0))
18515 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18516 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18517 (setq time (apply 'encode-time time0))))
18518 (setq org-last-changed-timestamp
18519 (org-insert-time-stamp time with-hm inactive nil nil extra))
18520 (org-clock-update-time-maybe)
18521 (goto-char pos)
18522 ;; Try to recenter the calendar window, if any
18523 (if (and org-calendar-follow-timestamp-change
18524 (get-buffer-window "*Calendar*" t)
18525 (memq org-ts-what '(day month year)))
18526 (org-recenter-calendar (time-to-days time))))))
18528 ;; FIXME: does not yet work for lead times
18529 (defun org-modify-ts-extra (s pos n)
18530 "Change the different parts of the lead-time and repeat fields in timestamp."
18531 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18532 ng h m new)
18533 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18534 (cond
18535 ((or (org-pos-in-match-range pos 2)
18536 (org-pos-in-match-range pos 3))
18537 (setq m (string-to-number (match-string 3 s))
18538 h (string-to-number (match-string 2 s)))
18539 (if (org-pos-in-match-range pos 2)
18540 (setq h (+ h n))
18541 (setq m (+ m n)))
18542 (if (< m 0) (setq m (+ m 60) h (1- h)))
18543 (if (> m 59) (setq m (- m 60) h (1+ h)))
18544 (setq h (min 24 (max 0 h)))
18545 (setq ng 1 new (format "-%02d:%02d" h m)))
18546 ((org-pos-in-match-range pos 6)
18547 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18548 ((org-pos-in-match-range pos 5)
18549 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18551 (when ng
18552 (setq s (concat
18553 (substring s 0 (match-beginning ng))
18555 (substring s (match-end ng))))))
18558 (defun org-recenter-calendar (date)
18559 "If the calendar is visible, recenter it to DATE."
18560 (let* ((win (selected-window))
18561 (cwin (get-buffer-window "*Calendar*" t))
18562 (calendar-move-hook nil))
18563 (when cwin
18564 (select-window cwin)
18565 (calendar-goto-date (if (listp date) date
18566 (calendar-gregorian-from-absolute date)))
18567 (select-window win))))
18569 (defun org-goto-calendar (&optional arg)
18570 "Go to the Emacs calendar at the current date.
18571 If there is a time stamp in the current line, go to that date.
18572 A prefix ARG can be used to force the current date."
18573 (interactive "P")
18574 (let ((tsr org-ts-regexp) diff
18575 (calendar-move-hook nil)
18576 (view-calendar-holidays-initially nil)
18577 (view-diary-entries-initially nil))
18578 (if (or (org-at-timestamp-p)
18579 (save-excursion
18580 (beginning-of-line 1)
18581 (looking-at (concat ".*" tsr))))
18582 (let ((d1 (time-to-days (current-time)))
18583 (d2 (time-to-days
18584 (org-time-string-to-time (match-string 1)))))
18585 (setq diff (- d2 d1))))
18586 (calendar)
18587 (calendar-goto-today)
18588 (if (and diff (not arg)) (calendar-forward-day diff))))
18590 (defun org-get-date-from-calendar ()
18591 "Return a list (month day year) of date at point in calendar."
18592 (with-current-buffer "*Calendar*"
18593 (save-match-data
18594 (calendar-cursor-to-date))))
18596 (defun org-date-from-calendar ()
18597 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18598 If there is already a time stamp at the cursor position, update it."
18599 (interactive)
18600 (if (org-at-timestamp-p t)
18601 (org-timestamp-change 0 'calendar)
18602 (let ((cal-date (org-get-date-from-calendar)))
18603 (org-insert-time-stamp
18604 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18606 (defvar appt-time-msg-list)
18608 ;;;###autoload
18609 (defun org-agenda-to-appt (&optional refresh filter)
18610 "Activate appointments found in `org-agenda-files'.
18611 With a \\[universal-argument] prefix, refresh the list of
18612 appointements.
18614 If FILTER is t, interactively prompt the user for a regular
18615 expression, and filter out entries that don't match it.
18617 If FILTER is a string, use this string as a regular expression
18618 for filtering entries out.
18620 FILTER can also be an alist with the car of each cell being
18621 either 'headline or 'category. For example:
18623 '((headline \"IMPORTANT\")
18624 (category \"Work\"))
18626 will only add headlines containing IMPORTANT or headlines
18627 belonging to the \"Work\" category."
18628 (interactive "P")
18629 (require 'calendar)
18630 (if refresh (setq appt-time-msg-list nil))
18631 (if (eq filter t)
18632 (setq filter (read-from-minibuffer "Regexp filter: ")))
18633 (let* ((cnt 0) ; count added events
18634 (org-agenda-new-buffers nil)
18635 (org-deadline-warning-days 0)
18636 (today (org-date-to-gregorian
18637 (time-to-days (current-time))))
18638 (files (org-agenda-files)) entries file)
18639 ;; Get all entries which may contain an appt
18640 (while (setq file (pop files))
18641 (setq entries
18642 (append entries
18643 (org-agenda-get-day-entries
18644 file today :timestamp :scheduled :deadline))))
18645 (setq entries (delq nil entries))
18646 ;; Map thru entries and find if we should filter them out
18647 (mapc
18648 (lambda(x)
18649 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18650 (cat (get-text-property 1 'org-category x))
18651 (tod (get-text-property 1 'time-of-day x))
18652 (ok (or (null filter)
18653 (and (stringp filter) (string-match filter evt))
18654 (and (listp filter)
18655 (or (string-match
18656 (cadr (assoc 'category filter)) cat)
18657 (string-match
18658 (cadr (assoc 'headline filter)) evt))))))
18659 ;; FIXME: Shall we remove text-properties for the appt text?
18660 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18661 (when (and ok tod)
18662 (setq tod (number-to-string tod)
18663 tod (when (string-match
18664 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18665 (concat (match-string 1 tod) ":"
18666 (match-string 2 tod))))
18667 (appt-add tod evt)
18668 (setq cnt (1+ cnt))))) entries)
18669 (org-release-buffers org-agenda-new-buffers)
18670 (if (eq cnt 0)
18671 (message "No event to add")
18672 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18674 ;;; The clock for measuring work time.
18676 (defvar org-mode-line-string "")
18677 (put 'org-mode-line-string 'risky-local-variable t)
18679 (defvar org-mode-line-timer nil)
18680 (defvar org-clock-heading "")
18681 (defvar org-clock-start-time "")
18683 (defun org-update-mode-line ()
18684 (let* ((delta (- (time-to-seconds (current-time))
18685 (time-to-seconds org-clock-start-time)))
18686 (h (floor delta 3600))
18687 (m (floor (- delta (* 3600 h)) 60)))
18688 (setq org-mode-line-string
18689 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18690 'help-echo "Org-mode clock is running"))
18691 (force-mode-line-update)))
18693 (defvar org-clock-marker (make-marker)
18694 "Marker recording the last clock-in.")
18695 (defvar org-clock-mode-line-entry nil
18696 "Information for the modeline about the running clock.")
18698 (defun org-clock-in ()
18699 "Start the clock on the current item.
18700 If necessary, clock-out of the currently active clock."
18701 (interactive)
18702 (org-clock-out t)
18703 (let (ts)
18704 (save-excursion
18705 (org-back-to-heading t)
18706 (when (and org-clock-in-switch-to-state
18707 (not (looking-at (concat outline-regexp "[ \t]*"
18708 org-clock-in-switch-to-state
18709 "\\>"))))
18710 (org-todo org-clock-in-switch-to-state))
18711 (if (and org-clock-heading-function
18712 (functionp org-clock-heading-function))
18713 (setq org-clock-heading (funcall org-clock-heading-function))
18714 (if (looking-at org-complex-heading-regexp)
18715 (setq org-clock-heading (match-string 4))
18716 (setq org-clock-heading "???")))
18717 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18718 (org-clock-find-position)
18720 (insert "\n") (backward-char 1)
18721 (indent-relative)
18722 (insert org-clock-string " ")
18723 (setq org-clock-start-time (current-time))
18724 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18725 (move-marker org-clock-marker (point) (buffer-base-buffer))
18726 (or global-mode-string (setq global-mode-string '("")))
18727 (or (memq 'org-mode-line-string global-mode-string)
18728 (setq global-mode-string
18729 (append global-mode-string '(org-mode-line-string))))
18730 (org-update-mode-line)
18731 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18732 (message "Clock started at %s" ts))))
18734 (defun org-clock-find-position ()
18735 "Find the location where the next clock line should be inserted."
18736 (org-back-to-heading t)
18737 (catch 'exit
18738 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18739 (re (concat "^[ \t]*" org-clock-string))
18740 (cnt 0)
18741 first last)
18742 (goto-char beg)
18743 (when (eobp) (newline) (setq end (max (point) end)))
18744 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18745 ;; we seem to have a CLOCK drawer, so go there.
18746 (beginning-of-line 2)
18747 (throw 'exit t))
18748 ;; Lets count the CLOCK lines
18749 (goto-char beg)
18750 (while (re-search-forward re end t)
18751 (setq first (or first (match-beginning 0))
18752 last (match-beginning 0)
18753 cnt (1+ cnt)))
18754 (when (and (integerp org-clock-into-drawer)
18755 (>= (1+ cnt) org-clock-into-drawer))
18756 ;; Wrap current entries into a new drawer
18757 (goto-char last)
18758 (beginning-of-line 2)
18759 (if (org-at-item-p) (org-end-of-item))
18760 (insert ":END:\n")
18761 (beginning-of-line 0)
18762 (org-indent-line-function)
18763 (goto-char first)
18764 (insert ":CLOCK:\n")
18765 (beginning-of-line 0)
18766 (org-indent-line-function)
18767 (org-flag-drawer t)
18768 (beginning-of-line 2)
18769 (throw 'exit nil))
18771 (goto-char beg)
18772 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18773 (not (equal (match-string 1) org-clock-string)))
18774 ;; Planning info, skip to after it
18775 (beginning-of-line 2)
18776 (or (bolp) (newline)))
18777 (when (eq t org-clock-into-drawer)
18778 (insert ":CLOCK:\n:END:\n")
18779 (beginning-of-line -1)
18780 (org-indent-line-function)
18781 (org-flag-drawer t)
18782 (beginning-of-line 2)
18783 (org-indent-line-function)))))
18785 (defun org-clock-out (&optional fail-quietly)
18786 "Stop the currently running clock.
18787 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18788 (interactive)
18789 (catch 'exit
18790 (if (not (marker-buffer org-clock-marker))
18791 (if fail-quietly (throw 'exit t) (error "No active clock")))
18792 (let (ts te s h m)
18793 (save-excursion
18794 (set-buffer (marker-buffer org-clock-marker))
18795 (goto-char org-clock-marker)
18796 (beginning-of-line 1)
18797 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18798 (equal (match-string 1) org-clock-string))
18799 (setq ts (match-string 2))
18800 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18801 (goto-char (match-end 0))
18802 (delete-region (point) (point-at-eol))
18803 (insert "--")
18804 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18805 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18806 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18807 h (floor (/ s 3600))
18808 s (- s (* 3600 h))
18809 m (floor (/ s 60))
18810 s (- s (* 60 s)))
18811 (insert " => " (format "%2d:%02d" h m))
18812 (move-marker org-clock-marker nil)
18813 (when org-log-note-clock-out
18814 (org-add-log-maybe 'clock-out))
18815 (when org-mode-line-timer
18816 (cancel-timer org-mode-line-timer)
18817 (setq org-mode-line-timer nil))
18818 (setq global-mode-string
18819 (delq 'org-mode-line-string global-mode-string))
18820 (force-mode-line-update)
18821 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18823 (defun org-clock-cancel ()
18824 "Cancel the running clock be removing the start timestamp."
18825 (interactive)
18826 (if (not (marker-buffer org-clock-marker))
18827 (error "No active clock"))
18828 (save-excursion
18829 (set-buffer (marker-buffer org-clock-marker))
18830 (goto-char org-clock-marker)
18831 (delete-region (1- (point-at-bol)) (point-at-eol)))
18832 (setq global-mode-string
18833 (delq 'org-mode-line-string global-mode-string))
18834 (force-mode-line-update)
18835 (message "Clock canceled"))
18837 (defun org-clock-goto (&optional delete-windows)
18838 "Go to the currently clocked-in entry."
18839 (interactive "P")
18840 (if (not (marker-buffer org-clock-marker))
18841 (error "No active clock"))
18842 (switch-to-buffer-other-window
18843 (marker-buffer org-clock-marker))
18844 (if delete-windows (delete-other-windows))
18845 (goto-char org-clock-marker)
18846 (org-show-entry)
18847 (org-back-to-heading)
18848 (recenter))
18850 (defvar org-clock-file-total-minutes nil
18851 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18852 (make-variable-buffer-local 'org-clock-file-total-minutes)
18854 (defun org-clock-sum (&optional tstart tend)
18855 "Sum the times for each subtree.
18856 Puts the resulting times in minutes as a text property on each headline."
18857 (interactive)
18858 (let* ((bmp (buffer-modified-p))
18859 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18860 org-clock-string
18861 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18862 (lmax 30)
18863 (ltimes (make-vector lmax 0))
18864 (t1 0)
18865 (level 0)
18866 ts te dt
18867 time)
18868 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18869 (save-excursion
18870 (goto-char (point-max))
18871 (while (re-search-backward re nil t)
18872 (cond
18873 ((match-end 2)
18874 ;; Two time stamps
18875 (setq ts (match-string 2)
18876 te (match-string 3)
18877 ts (time-to-seconds
18878 (apply 'encode-time (org-parse-time-string ts)))
18879 te (time-to-seconds
18880 (apply 'encode-time (org-parse-time-string te)))
18881 ts (if tstart (max ts tstart) ts)
18882 te (if tend (min te tend) te)
18883 dt (- te ts)
18884 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18885 ((match-end 4)
18886 ;; A naket time
18887 (setq t1 (+ t1 (string-to-number (match-string 5))
18888 (* 60 (string-to-number (match-string 4))))))
18889 (t ;; A headline
18890 (setq level (- (match-end 1) (match-beginning 1)))
18891 (when (or (> t1 0) (> (aref ltimes level) 0))
18892 (loop for l from 0 to level do
18893 (aset ltimes l (+ (aref ltimes l) t1)))
18894 (setq t1 0 time (aref ltimes level))
18895 (loop for l from level to (1- lmax) do
18896 (aset ltimes l 0))
18897 (goto-char (match-beginning 0))
18898 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18899 (setq org-clock-file-total-minutes (aref ltimes 0)))
18900 (set-buffer-modified-p bmp)))
18902 (defun org-clock-display (&optional total-only)
18903 "Show subtree times in the entire buffer.
18904 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18905 in the echo area."
18906 (interactive)
18907 (org-remove-clock-overlays)
18908 (let (time h m p)
18909 (org-clock-sum)
18910 (unless total-only
18911 (save-excursion
18912 (goto-char (point-min))
18913 (while (or (and (equal (setq p (point)) (point-min))
18914 (get-text-property p :org-clock-minutes))
18915 (setq p (next-single-property-change
18916 (point) :org-clock-minutes)))
18917 (goto-char p)
18918 (when (setq time (get-text-property p :org-clock-minutes))
18919 (org-put-clock-overlay time (funcall outline-level))))
18920 (setq h (/ org-clock-file-total-minutes 60)
18921 m (- org-clock-file-total-minutes (* 60 h)))
18922 ;; Arrange to remove the overlays upon next change.
18923 (when org-remove-highlights-with-change
18924 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18925 nil 'local))))
18926 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18928 (defvar org-clock-overlays nil)
18929 (make-variable-buffer-local 'org-clock-overlays)
18931 (defun org-put-clock-overlay (time &optional level)
18932 "Put an overlays on the current line, displaying TIME.
18933 If LEVEL is given, prefix time with a corresponding number of stars.
18934 This creates a new overlay and stores it in `org-clock-overlays', so that it
18935 will be easy to remove."
18936 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18937 (l (if level (org-get-legal-level level 0) 0))
18938 (off 0)
18939 ov tx)
18940 (move-to-column c)
18941 (unless (eolp) (skip-chars-backward "^ \t"))
18942 (skip-chars-backward " \t")
18943 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18944 tx (concat (buffer-substring (1- (point)) (point))
18945 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18946 (org-add-props (format "%s %2d:%02d%s"
18947 (make-string l ?*) h m
18948 (make-string (- 10 l) ?\ ))
18949 '(face secondary-selection))
18950 ""))
18951 (if (not (featurep 'xemacs))
18952 (org-overlay-put ov 'display tx)
18953 (org-overlay-put ov 'invisible t)
18954 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18955 (push ov org-clock-overlays)))
18957 (defun org-remove-clock-overlays (&optional beg end noremove)
18958 "Remove the occur highlights from the buffer.
18959 BEG and END are ignored. If NOREMOVE is nil, remove this function
18960 from the `before-change-functions' in the current buffer."
18961 (interactive)
18962 (unless org-inhibit-highlight-removal
18963 (mapc 'org-delete-overlay org-clock-overlays)
18964 (setq org-clock-overlays nil)
18965 (unless noremove
18966 (remove-hook 'before-change-functions
18967 'org-remove-clock-overlays 'local))))
18969 (defun org-clock-out-if-current ()
18970 "Clock out if the current entry contains the running clock.
18971 This is used to stop the clock after a TODO entry is marked DONE,
18972 and is only done if the variable `org-clock-out-when-done' is not nil."
18973 (when (and org-clock-out-when-done
18974 (member state org-done-keywords)
18975 (equal (marker-buffer org-clock-marker) (current-buffer))
18976 (< (point) org-clock-marker)
18977 (> (save-excursion (outline-next-heading) (point))
18978 org-clock-marker))
18979 ;; Clock out, but don't accept a logging message for this.
18980 (let ((org-log-note-clock-out nil))
18981 (org-clock-out))))
18983 (add-hook 'org-after-todo-state-change-hook
18984 'org-clock-out-if-current)
18986 (defun org-check-running-clock ()
18987 "Check if the current buffer contains the running clock.
18988 If yes, offer to stop it and to save the buffer with the changes."
18989 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18990 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18991 (buffer-name))))
18992 (org-clock-out)
18993 (when (y-or-n-p "Save changed buffer?")
18994 (save-buffer))))
18996 (defun org-clock-report (&optional arg)
18997 "Create a table containing a report about clocked time.
18998 If the cursor is inside an existing clocktable block, then the table
18999 will be updated. If not, a new clocktable will be inserted.
19000 When called with a prefix argument, move to the first clock table in the
19001 buffer and update it."
19002 (interactive "P")
19003 (org-remove-clock-overlays)
19004 (when arg
19005 (org-find-dblock "clocktable")
19006 (org-show-entry))
19007 (if (org-in-clocktable-p)
19008 (goto-char (org-in-clocktable-p))
19009 (org-create-dblock (list :name "clocktable"
19010 :maxlevel 2 :scope 'file)))
19011 (org-update-dblock))
19013 (defun org-in-clocktable-p ()
19014 "Check if the cursor is in a clocktable."
19015 (let ((pos (point)) start)
19016 (save-excursion
19017 (end-of-line 1)
19018 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19019 (setq start (match-beginning 0))
19020 (re-search-forward "^#\\+END:.*" nil t)
19021 (>= (match-end 0) pos)
19022 start))))
19024 (defun org-clock-update-time-maybe ()
19025 "If this is a CLOCK line, update it and return t.
19026 Otherwise, return nil."
19027 (interactive)
19028 (save-excursion
19029 (beginning-of-line 1)
19030 (skip-chars-forward " \t")
19031 (when (looking-at org-clock-string)
19032 (let ((re (concat "[ \t]*" org-clock-string
19033 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19034 "\\([ \t]*=>.*\\)?"))
19035 ts te h m s)
19036 (if (not (looking-at re))
19038 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19039 (end-of-line 1)
19040 (setq ts (match-string 1)
19041 te (match-string 2))
19042 (setq s (- (time-to-seconds
19043 (apply 'encode-time (org-parse-time-string te)))
19044 (time-to-seconds
19045 (apply 'encode-time (org-parse-time-string ts))))
19046 h (floor (/ s 3600))
19047 s (- s (* 3600 h))
19048 m (floor (/ s 60))
19049 s (- s (* 60 s)))
19050 (insert " => " (format "%2d:%02d" h m))
19051 t)))))
19053 (defun org-clock-special-range (key &optional time as-strings)
19054 "Return two times bordering a special time range.
19055 Key is a symbol specifying the range and can be one of `today', `yesterday',
19056 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19057 A week starts Monday 0:00 and ends Sunday 24:00.
19058 The range is determined relative to TIME. TIME defaults to the current time.
19059 The return value is a cons cell with two internal times like the ones
19060 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19061 the returned times will be formatted strings."
19062 (let* ((tm (decode-time (or time (current-time))))
19063 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19064 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19065 (dow (nth 6 tm))
19066 s1 m1 h1 d1 month1 y1 diff ts te fm)
19067 (cond
19068 ((eq key 'today)
19069 (setq h 0 m 0 h1 24 m1 0))
19070 ((eq key 'yesterday)
19071 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19072 ((eq key 'thisweek)
19073 (setq diff (if (= dow 0) 6 (1- dow))
19074 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19075 ((eq key 'lastweek)
19076 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19077 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19078 ((eq key 'thismonth)
19079 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19080 ((eq key 'lastmonth)
19081 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19082 ((eq key 'thisyear)
19083 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19084 ((eq key 'lastyear)
19085 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19086 (t (error "No such time block %s" key)))
19087 (setq ts (encode-time s m h d month y)
19088 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19089 (or d1 d) (or month1 month) (or y1 y)))
19090 (setq fm (cdr org-time-stamp-formats))
19091 (if as-strings
19092 (cons (format-time-string fm ts) (format-time-string fm te))
19093 (cons ts te))))
19095 (defun org-dblock-write:clocktable (params)
19096 "Write the standard clocktable."
19097 (catch 'exit
19098 (let* ((hlchars '((1 . "*") (2 . "/")))
19099 (ins (make-marker))
19100 (total-time nil)
19101 (scope (plist-get params :scope))
19102 (tostring (plist-get params :tostring))
19103 (multifile (plist-get params :multifile))
19104 (header (plist-get params :header))
19105 (maxlevel (or (plist-get params :maxlevel) 3))
19106 (step (plist-get params :step))
19107 (emph (plist-get params :emphasize))
19108 (ts (plist-get params :tstart))
19109 (te (plist-get params :tend))
19110 (block (plist-get params :block))
19111 ipos time h m p level hlc hdl
19112 cc beg end pos tbl)
19113 (when step
19114 (org-clocktable-steps params)
19115 (throw 'exit nil))
19116 (when block
19117 (setq cc (org-clock-special-range block nil t)
19118 ts (car cc) te (cdr cc)))
19119 (if ts (setq ts (time-to-seconds
19120 (apply 'encode-time (org-parse-time-string ts)))))
19121 (if te (setq te (time-to-seconds
19122 (apply 'encode-time (org-parse-time-string te)))))
19123 (move-marker ins (point))
19124 (setq ipos (point))
19126 ;; Get the right scope
19127 (setq pos (point))
19128 (save-restriction
19129 (cond
19130 ((not scope))
19131 ((eq scope 'file) (widen))
19132 ((eq scope 'subtree) (org-narrow-to-subtree))
19133 ((eq scope 'tree)
19134 (while (org-up-heading-safe))
19135 (org-narrow-to-subtree))
19136 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19137 (symbol-name scope)))
19138 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19139 (catch 'exit
19140 (while (org-up-heading-safe)
19141 (looking-at outline-regexp)
19142 (if (<= (org-reduced-level (funcall outline-level)) level)
19143 (throw 'exit nil))))
19144 (org-narrow-to-subtree))
19145 ((or (listp scope) (eq scope 'agenda))
19146 (let* ((files (if (listp scope) scope (org-agenda-files)))
19147 (scope 'agenda)
19148 (p1 (copy-sequence params))
19149 file)
19150 (plist-put p1 :tostring t)
19151 (plist-put p1 :multifile t)
19152 (plist-put p1 :scope 'file)
19153 (org-prepare-agenda-buffers files)
19154 (while (setq file (pop files))
19155 (with-current-buffer (find-buffer-visiting file)
19156 (push (org-clocktable-add-file
19157 file (org-dblock-write:clocktable p1)) tbl)
19158 (setq total-time (+ (or total-time 0)
19159 org-clock-file-total-minutes)))))))
19160 (goto-char pos)
19162 (unless (eq scope 'agenda)
19163 (org-clock-sum ts te)
19164 (goto-char (point-min))
19165 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19166 (goto-char p)
19167 (when (setq time (get-text-property p :org-clock-minutes))
19168 (save-excursion
19169 (beginning-of-line 1)
19170 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19171 (setq level (org-reduced-level
19172 (- (match-end 1) (match-beginning 1))))
19173 (<= level maxlevel))
19174 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19175 hdl (match-string 2)
19176 h (/ time 60)
19177 m (- time (* 60 h)))
19178 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19179 (push (concat
19180 "| " (int-to-string level) "|" hlc hdl hlc " |"
19181 (make-string (1- level) ?|)
19182 hlc (format "%d:%02d" h m) hlc
19183 " |") tbl))))))
19184 (setq tbl (nreverse tbl))
19185 (if tostring
19186 (if tbl (mapconcat 'identity tbl "\n") nil)
19187 (goto-char ins)
19188 (insert-before-markers
19189 (or header
19190 (concat
19191 "Clock summary at ["
19192 (substring
19193 (format-time-string (cdr org-time-stamp-formats))
19194 1 -1)
19195 "]."
19196 (if block
19197 (format " Considered range is /%s/." block)
19199 "\n\n"))
19200 (if (eq scope 'agenda) "|File" "")
19201 "|L|Headline|Time|\n")
19202 (setq total-time (or total-time org-clock-file-total-minutes)
19203 h (/ total-time 60)
19204 m (- total-time (* 60 h)))
19205 (insert-before-markers
19206 "|-\n|"
19207 (if (eq scope 'agenda) "|" "")
19209 "*Total time*| "
19210 (format "*%d:%02d*" h m)
19211 "|\n|-\n")
19212 (setq tbl (delq nil tbl))
19213 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19214 (equal (substring (car tbl) 0 2) "|-"))
19215 (pop tbl))
19216 (insert-before-markers (mapconcat
19217 'identity (delq nil tbl)
19218 (if (eq scope 'agenda) "\n|-\n" "\n")))
19219 (backward-delete-char 1)
19220 (goto-char ipos)
19221 (skip-chars-forward "^|")
19222 (org-table-align))))))
19224 (defun org-clocktable-steps (params)
19225 (let* ((p1 (copy-sequence params))
19226 (ts (plist-get p1 :tstart))
19227 (te (plist-get p1 :tend))
19228 (step0 (plist-get p1 :step))
19229 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19230 (block (plist-get p1 :block))
19232 (when block
19233 (setq cc (org-clock-special-range block nil t)
19234 ts (car cc) te (cdr cc)))
19235 (if ts (setq ts (time-to-seconds
19236 (apply 'encode-time (org-parse-time-string ts)))))
19237 (if te (setq te (time-to-seconds
19238 (apply 'encode-time (org-parse-time-string te)))))
19239 (plist-put p1 :header "")
19240 (plist-put p1 :step nil)
19241 (plist-put p1 :block nil)
19242 (while (< ts te)
19243 (or (bolp) (insert "\n"))
19244 (plist-put p1 :tstart (format-time-string
19245 (car org-time-stamp-formats)
19246 (seconds-to-time ts)))
19247 (plist-put p1 :tend (format-time-string
19248 (car org-time-stamp-formats)
19249 (seconds-to-time (setq ts (+ ts step)))))
19250 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19251 (plist-get p1 :tstart) "\n")
19252 (org-dblock-write:clocktable p1)
19253 (re-search-forward "#\\+END:")
19254 (end-of-line 0))))
19257 (defun org-clocktable-add-file (file table)
19258 (if table
19259 (let ((lines (org-split-string table "\n"))
19260 (ff (file-name-nondirectory file)))
19261 (mapconcat 'identity
19262 (mapcar (lambda (x)
19263 (if (string-match org-table-dataline-regexp x)
19264 (concat "|" ff x)
19266 lines)
19267 "\n"))))
19269 ;; FIXME: I don't think anybody uses this, ask David
19270 (defun org-collect-clock-time-entries ()
19271 "Return an internal list with clocking information.
19272 This list has one entry for each CLOCK interval.
19273 FIXME: describe the elements."
19274 (interactive)
19275 (let ((re (concat "^[ \t]*" org-clock-string
19276 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19277 rtn beg end next cont level title total closedp leafp
19278 clockpos titlepos h m donep)
19279 (save-excursion
19280 (org-clock-sum)
19281 (goto-char (point-min))
19282 (while (re-search-forward re nil t)
19283 (setq clockpos (match-beginning 0)
19284 beg (match-string 1) end (match-string 2)
19285 cont (match-end 0))
19286 (setq beg (apply 'encode-time (org-parse-time-string beg))
19287 end (apply 'encode-time (org-parse-time-string end)))
19288 (org-back-to-heading t)
19289 (setq donep (org-entry-is-done-p))
19290 (setq titlepos (point)
19291 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19292 h (/ total 60) m (- total (* 60 h))
19293 total (cons h m))
19294 (looking-at "\\(\\*+\\) +\\(.*\\)")
19295 (setq level (- (match-end 1) (match-beginning 1))
19296 title (org-match-string-no-properties 2))
19297 (save-excursion (outline-next-heading) (setq next (point)))
19298 (setq closedp (re-search-forward org-closed-time-regexp next t))
19299 (goto-char next)
19300 (setq leafp (and (looking-at "^\\*+ ")
19301 (<= (- (match-end 0) (point)) level)))
19302 (push (list beg end clockpos closedp donep
19303 total title titlepos level leafp)
19304 rtn)
19305 (goto-char cont)))
19306 (nreverse rtn)))
19308 ;;;; Agenda, and Diary Integration
19310 ;;; Define the Org-agenda-mode
19312 (defvar org-agenda-mode-map (make-sparse-keymap)
19313 "Keymap for `org-agenda-mode'.")
19315 (defvar org-agenda-menu) ; defined later in this file.
19316 (defvar org-agenda-follow-mode nil)
19317 (defvar org-agenda-show-log nil)
19318 (defvar org-agenda-redo-command nil)
19319 (defvar org-agenda-mode-hook nil)
19320 (defvar org-agenda-type nil)
19321 (defvar org-agenda-force-single-file nil)
19323 (defun org-agenda-mode ()
19324 "Mode for time-sorted view on action items in Org-mode files.
19326 The following commands are available:
19328 \\{org-agenda-mode-map}"
19329 (interactive)
19330 (kill-all-local-variables)
19331 (setq org-agenda-undo-list nil
19332 org-agenda-pending-undo-list nil)
19333 (setq major-mode 'org-agenda-mode)
19334 ;; Keep global-font-lock-mode from turning on font-lock-mode
19335 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19336 (setq mode-name "Org-Agenda")
19337 (use-local-map org-agenda-mode-map)
19338 (easy-menu-add org-agenda-menu)
19339 (if org-startup-truncated (setq truncate-lines t))
19340 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19341 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19342 ;; Make sure properties are removed when copying text
19343 (when (boundp 'buffer-substring-filters)
19344 (org-set-local 'buffer-substring-filters
19345 (cons (lambda (x)
19346 (set-text-properties 0 (length x) nil x) x)
19347 buffer-substring-filters)))
19348 (unless org-agenda-keep-modes
19349 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19350 org-agenda-show-log nil))
19351 (easy-menu-change
19352 '("Agenda") "Agenda Files"
19353 (append
19354 (list
19355 (vector
19356 (if (get 'org-agenda-files 'org-restrict)
19357 "Restricted to single file"
19358 "Edit File List")
19359 '(org-edit-agenda-file-list)
19360 (not (get 'org-agenda-files 'org-restrict)))
19361 "--")
19362 (mapcar 'org-file-menu-entry (org-agenda-files))))
19363 (org-agenda-set-mode-name)
19364 (apply
19365 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19366 (list 'org-agenda-mode-hook)))
19368 (substitute-key-definition 'undo 'org-agenda-undo
19369 org-agenda-mode-map global-map)
19370 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19371 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19372 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19373 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19374 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19375 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19376 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19377 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19378 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19379 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19380 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19381 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19382 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19383 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19384 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19385 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19386 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19387 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19388 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19389 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19390 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19391 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19392 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19393 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19394 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19395 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19396 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19397 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19398 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19400 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19401 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19402 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19403 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19404 (while l (org-defkey org-agenda-mode-map
19405 (int-to-string (pop l)) 'digit-argument)))
19407 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19408 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19409 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19410 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19411 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19412 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19413 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19414 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19415 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19416 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19417 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19418 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19419 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19420 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19421 (org-defkey org-agenda-mode-map "n" 'next-line)
19422 (org-defkey org-agenda-mode-map "p" 'previous-line)
19423 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19424 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19425 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19426 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19427 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19428 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19429 (eval-after-load "calendar"
19430 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19431 'org-calendar-goto-agenda))
19432 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19433 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19434 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19435 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19436 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19437 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19438 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19439 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19440 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19441 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19442 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19443 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19444 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19445 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19446 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19447 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19448 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19449 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19450 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19451 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19452 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19453 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19455 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19456 "Local keymap for agenda entries from Org-mode.")
19458 (org-defkey org-agenda-keymap
19459 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19460 (org-defkey org-agenda-keymap
19461 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19462 (when org-agenda-mouse-1-follows-link
19463 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19464 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19465 '("Agenda"
19466 ("Agenda Files")
19467 "--"
19468 ["Show" org-agenda-show t]
19469 ["Go To (other window)" org-agenda-goto t]
19470 ["Go To (this window)" org-agenda-switch-to t]
19471 ["Follow Mode" org-agenda-follow-mode
19472 :style toggle :selected org-agenda-follow-mode :active t]
19473 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19474 "--"
19475 ["Cycle TODO" org-agenda-todo t]
19476 ["Archive subtree" org-agenda-archive t]
19477 ["Delete subtree" org-agenda-kill t]
19478 "--"
19479 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19480 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19481 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19482 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19483 "--"
19484 ("Tags and Properties"
19485 ["Show all Tags" org-agenda-show-tags t]
19486 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19487 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19488 "--"
19489 ["Column View" org-columns t])
19490 ("Date/Schedule"
19491 ["Schedule" org-agenda-schedule t]
19492 ["Set Deadline" org-agenda-deadline t]
19493 "--"
19494 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19495 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19496 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19497 ("Clock"
19498 ["Clock in" org-agenda-clock-in t]
19499 ["Clock out" org-agenda-clock-out t]
19500 ["Clock cancel" org-agenda-clock-cancel t]
19501 ["Goto running clock" org-clock-goto t])
19502 ("Priority"
19503 ["Set Priority" org-agenda-priority t]
19504 ["Increase Priority" org-agenda-priority-up t]
19505 ["Decrease Priority" org-agenda-priority-down t]
19506 ["Show Priority" org-agenda-show-priority t])
19507 ("Calendar/Diary"
19508 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19509 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19510 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19511 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19512 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19513 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19514 "--"
19515 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19516 "--"
19517 ("View"
19518 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19519 :style radio :selected (equal org-agenda-ndays 1)]
19520 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19521 :style radio :selected (equal org-agenda-ndays 7)]
19522 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19523 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19524 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19525 :style radio :selected (member org-agenda-ndays '(365 366))]
19526 "--"
19527 ["Show Logbook entries" org-agenda-log-mode
19528 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19529 ["Include Diary" org-agenda-toggle-diary
19530 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19531 ["Use Time Grid" org-agenda-toggle-time-grid
19532 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19533 ["Write view to file" org-write-agenda t]
19534 ["Rebuild buffer" org-agenda-redo t]
19535 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19536 "--"
19537 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19538 "--"
19539 ["Quit" org-agenda-quit t]
19540 ["Exit and Release Buffers" org-agenda-exit t]
19543 ;;; Agenda undo
19545 (defvar org-agenda-allow-remote-undo t
19546 "Non-nil means, allow remote undo from the agenda buffer.")
19547 (defvar org-agenda-undo-list nil
19548 "List of undoable operations in the agenda since last refresh.")
19549 (defvar org-agenda-undo-has-started-in nil
19550 "Buffers that have already seen `undo-start' in the current undo sequence.")
19551 (defvar org-agenda-pending-undo-list nil
19552 "In a series of undo commands, this is the list of remaning undo items.")
19554 (defmacro org-if-unprotected (&rest body)
19555 "Execute BODY if there is no `org-protected' text property at point."
19556 (declare (debug t))
19557 `(unless (get-text-property (point) 'org-protected)
19558 ,@body))
19560 (defmacro org-with-remote-undo (_buffer &rest _body)
19561 "Execute BODY while recording undo information in two buffers."
19562 (declare (indent 1) (debug t))
19563 `(let ((_cline (org-current-line))
19564 (_cmd this-command)
19565 (_buf1 (current-buffer))
19566 (_buf2 ,_buffer)
19567 (_undo1 buffer-undo-list)
19568 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19569 _c1 _c2)
19570 ,@_body
19571 (when org-agenda-allow-remote-undo
19572 (setq _c1 (org-verify-change-for-undo
19573 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19574 _c2 (org-verify-change-for-undo
19575 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19576 (when (or _c1 _c2)
19577 ;; make sure there are undo boundaries
19578 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19579 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19580 ;; remember which buffer to undo
19581 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19582 org-agenda-undo-list)))))
19584 (defun org-agenda-undo ()
19585 "Undo a remote editing step in the agenda.
19586 This undoes changes both in the agenda buffer and in the remote buffer
19587 that have been changed along."
19588 (interactive)
19589 (or org-agenda-allow-remote-undo
19590 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19591 (if (not (eq this-command last-command))
19592 (setq org-agenda-undo-has-started-in nil
19593 org-agenda-pending-undo-list org-agenda-undo-list))
19594 (if (not org-agenda-pending-undo-list)
19595 (error "No further undo information"))
19596 (let* ((entry (pop org-agenda-pending-undo-list))
19597 buf line cmd rembuf)
19598 (setq cmd (pop entry) line (pop entry))
19599 (setq rembuf (nth 2 entry))
19600 (org-with-remote-undo rembuf
19601 (while (bufferp (setq buf (pop entry)))
19602 (if (pop entry)
19603 (with-current-buffer buf
19604 (let ((last-undo-buffer buf)
19605 (inhibit-read-only t))
19606 (unless (memq buf org-agenda-undo-has-started-in)
19607 (push buf org-agenda-undo-has-started-in)
19608 (make-local-variable 'pending-undo-list)
19609 (undo-start))
19610 (while (and pending-undo-list
19611 (listp pending-undo-list)
19612 (not (car pending-undo-list)))
19613 (pop pending-undo-list))
19614 (undo-more 1))))))
19615 (goto-line line)
19616 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19618 (defun org-verify-change-for-undo (l1 l2)
19619 "Verify that a real change occurred between the undo lists L1 and L2."
19620 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19621 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19622 (not (eq l1 l2)))
19624 ;;; Agenda dispatch
19626 (defvar org-agenda-restrict nil)
19627 (defvar org-agenda-restrict-begin (make-marker))
19628 (defvar org-agenda-restrict-end (make-marker))
19629 (defvar org-agenda-last-dispatch-buffer nil)
19630 (defvar org-agenda-overriding-restriction nil)
19632 ;;;###autoload
19633 (defun org-agenda (arg &optional keys restriction)
19634 "Dispatch agenda commands to collect entries to the agenda buffer.
19635 Prompts for a command to execute. Any prefix arg will be passed
19636 on to the selected command. The default selections are:
19638 a Call `org-agenda-list' to display the agenda for current day or week.
19639 t Call `org-todo-list' to display the global todo list.
19640 T Call `org-todo-list' to display the global todo list, select only
19641 entries with a specific TODO keyword (the user gets a prompt).
19642 m Call `org-tags-view' to display headlines with tags matching
19643 a condition (the user is prompted for the condition).
19644 M Like `m', but select only TODO entries, no ordinary headlines.
19645 L Create a timeline for the current buffer.
19646 e Export views to associated files.
19648 More commands can be added by configuring the variable
19649 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19650 searches can be pre-defined in this way.
19652 If the current buffer is in Org-mode and visiting a file, you can also
19653 first press `<' once to indicate that the agenda should be temporarily
19654 \(until the next use of \\[org-agenda]) restricted to the current file.
19655 Pressing `<' twice means to restrict to the current subtree or region
19656 \(if active)."
19657 (interactive "P")
19658 (catch 'exit
19659 (let* ((prefix-descriptions nil)
19660 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19661 (org-agenda-custom-commands
19662 ;; normalize different versions
19663 (delq nil
19664 (mapcar
19665 (lambda (x)
19666 (cond ((stringp (cdr x))
19667 (push x prefix-descriptions)
19668 nil)
19669 ((stringp (nth 1 x)) x)
19670 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19671 (t (cons (car x) (cons "" (cdr x))))))
19672 org-agenda-custom-commands)))
19673 (buf (current-buffer))
19674 (bfn (buffer-file-name (buffer-base-buffer)))
19675 entry key type match lprops ans)
19676 ;; Turn off restriction unless there is an overriding one
19677 (unless org-agenda-overriding-restriction
19678 (put 'org-agenda-files 'org-restrict nil)
19679 (setq org-agenda-restrict nil)
19680 (move-marker org-agenda-restrict-begin nil)
19681 (move-marker org-agenda-restrict-end nil))
19682 ;; Delete old local properties
19683 (put 'org-agenda-redo-command 'org-lprops nil)
19684 ;; Remember where this call originated
19685 (setq org-agenda-last-dispatch-buffer (current-buffer))
19686 (unless keys
19687 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19688 keys (car ans)
19689 restriction (cdr ans)))
19690 ;; Estabish the restriction, if any
19691 (when (and (not org-agenda-overriding-restriction) restriction)
19692 (put 'org-agenda-files 'org-restrict (list bfn))
19693 (cond
19694 ((eq restriction 'region)
19695 (setq org-agenda-restrict t)
19696 (move-marker org-agenda-restrict-begin (region-beginning))
19697 (move-marker org-agenda-restrict-end (region-end)))
19698 ((eq restriction 'subtree)
19699 (save-excursion
19700 (setq org-agenda-restrict t)
19701 (org-back-to-heading t)
19702 (move-marker org-agenda-restrict-begin (point))
19703 (move-marker org-agenda-restrict-end
19704 (progn (org-end-of-subtree t)))))))
19706 (require 'calendar) ; FIXME: can we avoid this for some commands?
19707 ;; For example the todo list should not need it (but does...)
19708 (cond
19709 ((setq entry (assoc keys org-agenda-custom-commands))
19710 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19711 (progn
19712 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19713 (put 'org-agenda-redo-command 'org-lprops lprops)
19714 (cond
19715 ((eq type 'agenda)
19716 (org-let lprops '(org-agenda-list current-prefix-arg)))
19717 ((eq type 'alltodo)
19718 (org-let lprops '(org-todo-list current-prefix-arg)))
19719 ((eq type 'stuck)
19720 (org-let lprops '(org-agenda-list-stuck-projects
19721 current-prefix-arg)))
19722 ((eq type 'tags)
19723 (org-let lprops '(org-tags-view current-prefix-arg match)))
19724 ((eq type 'tags-todo)
19725 (org-let lprops '(org-tags-view '(4) match)))
19726 ((eq type 'todo)
19727 (org-let lprops '(org-todo-list match)))
19728 ((eq type 'tags-tree)
19729 (org-check-for-org-mode)
19730 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19731 ((eq type 'todo-tree)
19732 (org-check-for-org-mode)
19733 (org-let lprops
19734 '(org-occur (concat "^" outline-regexp "[ \t]*"
19735 (regexp-quote match) "\\>"))))
19736 ((eq type 'occur-tree)
19737 (org-check-for-org-mode)
19738 (org-let lprops '(org-occur match)))
19739 ((functionp type)
19740 (org-let lprops '(funcall type match)))
19741 ((fboundp type)
19742 (org-let lprops '(funcall type match)))
19743 (t (error "Invalid custom agenda command type %s" type))))
19744 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19745 ((equal keys "C")
19746 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19747 (customize-variable 'org-agenda-custom-commands))
19748 ((equal keys "a") (call-interactively 'org-agenda-list))
19749 ((equal keys "t") (call-interactively 'org-todo-list))
19750 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19751 ((equal keys "m") (call-interactively 'org-tags-view))
19752 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19753 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19754 ((equal keys "L")
19755 (unless (org-mode-p)
19756 (error "This is not an Org-mode file"))
19757 (unless restriction
19758 (put 'org-agenda-files 'org-restrict (list bfn))
19759 (org-call-with-arg 'org-timeline arg)))
19760 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19761 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19762 ((equal keys "!") (customize-variable 'org-stuck-projects))
19763 (t (error "Invalid agenda key"))))))
19765 (defun org-agenda-normalize-custom-commands (cmds)
19766 (delq nil
19767 (mapcar
19768 (lambda (x)
19769 (cond ((stringp (cdr x)) nil)
19770 ((stringp (nth 1 x)) x)
19771 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19772 (t (cons (car x) (cons "" (cdr x))))))
19773 cmds)))
19775 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19776 "The user interface for selecting an agenda command."
19777 (catch 'exit
19778 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19779 (restrict-ok (and bfn (org-mode-p)))
19780 (region-p (org-region-active-p))
19781 (custom org-agenda-custom-commands)
19782 (selstring "")
19783 restriction second-time
19784 c entry key type match prefixes rmheader header-end custom1 desc)
19785 (save-window-excursion
19786 (delete-other-windows)
19787 (org-switch-to-buffer-other-window " *Agenda Commands*")
19788 (erase-buffer)
19789 (insert (eval-when-compile
19790 (let ((header
19792 Press key for an agenda command: < Buffer,subtree/region restriction
19793 -------------------------------- > Remove restriction
19794 a Agenda for current week or day e Export agenda views
19795 t List of all TODO entries T Entries with special TODO kwd
19796 m Match a TAGS query M Like m, but only TODO entries
19797 L Timeline for current buffer # List stuck projects (!=configure)
19798 / Multi-occur C Configure custom agenda commands
19800 (start 0))
19801 (while (string-match
19802 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19803 header start)
19804 (setq start (match-end 0))
19805 (add-text-properties (match-beginning 2) (match-end 2)
19806 '(face bold) header))
19807 header)))
19808 (setq header-end (move-marker (make-marker) (point)))
19809 (while t
19810 (setq custom1 custom)
19811 (when (eq rmheader t)
19812 (goto-line 1)
19813 (re-search-forward ":" nil t)
19814 (delete-region (match-end 0) (point-at-eol))
19815 (forward-char 1)
19816 (looking-at "-+")
19817 (delete-region (match-end 0) (point-at-eol))
19818 (move-marker header-end (match-end 0)))
19819 (goto-char header-end)
19820 (delete-region (point) (point-max))
19821 (while (setq entry (pop custom1))
19822 (setq key (car entry) desc (nth 1 entry)
19823 type (nth 2 entry) match (nth 3 entry))
19824 (if (> (length key) 1)
19825 (add-to-list 'prefixes (string-to-char key))
19826 (insert
19827 (format
19828 "\n%-4s%-14s: %s"
19829 (org-add-props (copy-sequence key)
19830 '(face bold))
19831 (cond
19832 ((string-match "\\S-" desc) desc)
19833 ((eq type 'agenda) "Agenda for current week or day")
19834 ((eq type 'alltodo) "List of all TODO entries")
19835 ((eq type 'stuck) "List of stuck projects")
19836 ((eq type 'todo) "TODO keyword")
19837 ((eq type 'tags) "Tags query")
19838 ((eq type 'tags-todo) "Tags (TODO)")
19839 ((eq type 'tags-tree) "Tags tree")
19840 ((eq type 'todo-tree) "TODO kwd tree")
19841 ((eq type 'occur-tree) "Occur tree")
19842 ((functionp type) (if (symbolp type)
19843 (symbol-name type)
19844 "Lambda expression"))
19845 (t "???"))
19846 (cond
19847 ((stringp match)
19848 (org-add-props match nil 'face 'org-warning))
19849 (match
19850 (format "set of %d commands" (length match)))
19851 (t ""))))))
19852 (when prefixes
19853 (mapc (lambda (x)
19854 (insert
19855 (format "\n%s %s"
19856 (org-add-props (char-to-string x)
19857 nil 'face 'bold)
19858 (or (cdr (assoc (concat selstring (char-to-string x))
19859 prefix-descriptions))
19860 "Prefix key"))))
19861 prefixes))
19862 (goto-char (point-min))
19863 (when (fboundp 'fit-window-to-buffer)
19864 (if second-time
19865 (if (not (pos-visible-in-window-p (point-max)))
19866 (fit-window-to-buffer))
19867 (setq second-time t)
19868 (fit-window-to-buffer)))
19869 (message "Press key for agenda command%s:"
19870 (if (or restrict-ok org-agenda-overriding-restriction)
19871 (if org-agenda-overriding-restriction
19872 " (restriction lock active)"
19873 (if restriction
19874 (format " (restricted to %s)" restriction)
19875 " (unrestricted)"))
19876 ""))
19877 (setq c (read-char-exclusive))
19878 (message "")
19879 (cond
19880 ((assoc (char-to-string c) custom)
19881 (setq selstring (concat selstring (char-to-string c)))
19882 (throw 'exit (cons selstring restriction)))
19883 ((memq c prefixes)
19884 (setq selstring (concat selstring (char-to-string c))
19885 prefixes nil
19886 rmheader (or rmheader t)
19887 custom (delq nil (mapcar
19888 (lambda (x)
19889 (if (or (= (length (car x)) 1)
19890 (/= (string-to-char (car x)) c))
19892 (cons (substring (car x) 1) (cdr x))))
19893 custom))))
19894 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19895 (message "Restriction is only possible in Org-mode buffers")
19896 (ding) (sit-for 1))
19897 ((eq c ?1)
19898 (org-agenda-remove-restriction-lock 'noupdate)
19899 (setq restriction 'buffer))
19900 ((eq c ?0)
19901 (org-agenda-remove-restriction-lock 'noupdate)
19902 (setq restriction (if region-p 'region 'subtree)))
19903 ((eq c ?<)
19904 (org-agenda-remove-restriction-lock 'noupdate)
19905 (setq restriction
19906 (cond
19907 ((eq restriction 'buffer)
19908 (if region-p 'region 'subtree))
19909 ((memq restriction '(subtree region))
19910 nil)
19911 (t 'buffer))))
19912 ((eq c ?>)
19913 (org-agenda-remove-restriction-lock 'noupdate)
19914 (setq restriction nil))
19915 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19916 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19917 ((and (> (length selstring) 0) (eq c ?\d))
19918 (delete-window)
19919 (org-agenda-get-restriction-and-command prefix-descriptions))
19921 ((equal c ?q) (error "Abort"))
19922 (t (error "Invalid key %c" c))))))))
19924 (defun org-run-agenda-series (name series)
19925 (org-prepare-agenda name)
19926 (let* ((org-agenda-multi t)
19927 (redo (list 'org-run-agenda-series name (list 'quote series)))
19928 (cmds (car series))
19929 (gprops (nth 1 series))
19930 match ;; The byte compiler incorrectly complains about this. Keep it!
19931 cmd type lprops)
19932 (while (setq cmd (pop cmds))
19933 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19934 (cond
19935 ((eq type 'agenda)
19936 (org-let2 gprops lprops
19937 '(call-interactively 'org-agenda-list)))
19938 ((eq type 'alltodo)
19939 (org-let2 gprops lprops
19940 '(call-interactively 'org-todo-list)))
19941 ((eq type 'stuck)
19942 (org-let2 gprops lprops
19943 '(call-interactively 'org-agenda-list-stuck-projects)))
19944 ((eq type 'tags)
19945 (org-let2 gprops lprops
19946 '(org-tags-view current-prefix-arg match)))
19947 ((eq type 'tags-todo)
19948 (org-let2 gprops lprops
19949 '(org-tags-view '(4) match)))
19950 ((eq type 'todo)
19951 (org-let2 gprops lprops
19952 '(org-todo-list match)))
19953 ((fboundp type)
19954 (org-let2 gprops lprops
19955 '(funcall type match)))
19956 (t (error "Invalid type in command series"))))
19957 (widen)
19958 (setq org-agenda-redo-command redo)
19959 (goto-char (point-min)))
19960 (org-finalize-agenda))
19962 ;;;###autoload
19963 (defmacro org-batch-agenda (cmd-key &rest parameters)
19964 "Run an agenda command in batch mode and send the result to STDOUT.
19965 If CMD-KEY is a string of length 1, it is used as a key in
19966 `org-agenda-custom-commands' and triggers this command. If it is a
19967 longer string it is used as a tags/todo match string.
19968 Paramters are alternating variable names and values that will be bound
19969 before running the agenda command."
19970 (let (pars)
19971 (while parameters
19972 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19973 (if (> (length cmd-key) 2)
19974 (eval (list 'let (nreverse pars)
19975 (list 'org-tags-view nil cmd-key)))
19976 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19977 (set-buffer org-agenda-buffer-name)
19978 (princ (org-encode-for-stdout (buffer-string)))))
19980 (defun org-encode-for-stdout (string)
19981 (if (fboundp 'encode-coding-string)
19982 (encode-coding-string string buffer-file-coding-system)
19983 string))
19985 (defvar org-agenda-info nil)
19987 ;;;###autoload
19988 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19989 "Run an agenda command in batch mode and send the result to STDOUT.
19990 If CMD-KEY is a string of length 1, it is used as a key in
19991 `org-agenda-custom-commands' and triggers this command. If it is a
19992 longer string it is used as a tags/todo match string.
19993 Paramters are alternating variable names and values that will be bound
19994 before running the agenda command.
19996 The output gives a line for each selected agenda item. Each
19997 item is a list of comma-separated values, like this:
19999 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20001 category The category of the item
20002 head The headline, without TODO kwd, TAGS and PRIORITY
20003 type The type of the agenda entry, can be
20004 todo selected in TODO match
20005 tagsmatch selected in tags match
20006 diary imported from diary
20007 deadline a deadline on given date
20008 scheduled scheduled on given date
20009 timestamp entry has timestamp on given date
20010 closed entry was closed on given date
20011 upcoming-deadline warning about deadline
20012 past-scheduled forwarded scheduled item
20013 block entry has date block including g. date
20014 todo The todo keyword, if any
20015 tags All tags including inherited ones, separated by colons
20016 date The relevant date, like 2007-2-14
20017 time The time, like 15:00-16:50
20018 extra Sting with extra planning info
20019 priority-l The priority letter if any was given
20020 priority-n The computed numerical priority
20021 agenda-day The day in the agenda where this is listed"
20023 (let (pars)
20024 (while parameters
20025 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20026 (push (list 'org-agenda-remove-tags t) pars)
20027 (if (> (length cmd-key) 2)
20028 (eval (list 'let (nreverse pars)
20029 (list 'org-tags-view nil cmd-key)))
20030 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20031 (set-buffer org-agenda-buffer-name)
20032 (let* ((lines (org-split-string (buffer-string) "\n"))
20033 line)
20034 (while (setq line (pop lines))
20035 (catch 'next
20036 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20037 (setq org-agenda-info
20038 (org-fix-agenda-info (text-properties-at 0 line)))
20039 (princ
20040 (org-encode-for-stdout
20041 (mapconcat 'org-agenda-export-csv-mapper
20042 '(org-category txt type todo tags date time-of-day extra
20043 priority-letter priority agenda-day)
20044 ",")))
20045 (princ "\n"))))))
20047 (defun org-fix-agenda-info (props)
20048 "Make sure all properties on an agenda item have a canonical form,
20049 so the export commands can easily use it."
20050 (let (tmp re)
20051 (when (setq tmp (plist-get props 'tags))
20052 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20053 (when (setq tmp (plist-get props 'date))
20054 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20055 (let ((calendar-date-display-form '(year "-" month "-" day)))
20056 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20058 (setq tmp (calendar-date-string tmp)))
20059 (setq props (plist-put props 'date tmp)))
20060 (when (setq tmp (plist-get props 'day))
20061 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20062 (let ((calendar-date-display-form '(year "-" month "-" day)))
20063 (setq tmp (calendar-date-string tmp)))
20064 (setq props (plist-put props 'day tmp))
20065 (setq props (plist-put props 'agenda-day tmp)))
20066 (when (setq tmp (plist-get props 'txt))
20067 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20068 (plist-put props 'priority-letter (match-string 1 tmp))
20069 (setq tmp (replace-match "" t t tmp)))
20070 (when (and (setq re (plist-get props 'org-todo-regexp))
20071 (setq re (concat "\\`\\.*" re " ?"))
20072 (string-match re tmp))
20073 (plist-put props 'todo (match-string 1 tmp))
20074 (setq tmp (replace-match "" t t tmp)))
20075 (plist-put props 'txt tmp)))
20076 props)
20078 (defun org-agenda-export-csv-mapper (prop)
20079 (let ((res (plist-get org-agenda-info prop)))
20080 (setq res
20081 (cond
20082 ((not res) "")
20083 ((stringp res) res)
20084 (t (prin1-to-string res))))
20085 (while (string-match "," res)
20086 (setq res (replace-match ";" t t res)))
20087 (org-trim res)))
20090 ;;;###autoload
20091 (defun org-store-agenda-views (&rest parameters)
20092 (interactive)
20093 (eval (list 'org-batch-store-agenda-views)))
20095 ;; FIXME, why is this a macro?????
20096 ;;;###autoload
20097 (defmacro org-batch-store-agenda-views (&rest parameters)
20098 "Run all custom agenda commands that have a file argument."
20099 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20100 (pop-up-frames nil)
20101 (dir default-directory)
20102 pars cmd thiscmdkey files opts)
20103 (while parameters
20104 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20105 (setq pars (reverse pars))
20106 (save-window-excursion
20107 (while cmds
20108 (setq cmd (pop cmds)
20109 thiscmdkey (car cmd)
20110 opts (nth 4 cmd)
20111 files (nth 5 cmd))
20112 (if (stringp files) (setq files (list files)))
20113 (when files
20114 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20115 (list 'org-agenda nil thiscmdkey)))
20116 (set-buffer org-agenda-buffer-name)
20117 (while files
20118 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20119 (list 'org-write-agenda
20120 (expand-file-name (pop files) dir) t))))
20121 (and (get-buffer org-agenda-buffer-name)
20122 (kill-buffer org-agenda-buffer-name)))))))
20124 (defun org-write-agenda (file &optional nosettings)
20125 "Write the current buffer (an agenda view) as a file.
20126 Depending on the extension of the file name, plain text (.txt),
20127 HTML (.html or .htm) or Postscript (.ps) is produced.
20128 If NOSETTINGS is given, do not scope the settings of
20129 `org-agenda-exporter-settings' into the export commands. This is used when
20130 the settings have already been scoped and we do not wish to overrule other,
20131 higher priority settings."
20132 (interactive "FWrite agenda to file: ")
20133 (if (not (file-writable-p file))
20134 (error "Cannot write agenda to file %s" file))
20135 (cond
20136 ((string-match "\\.html?\\'" file) (require 'htmlize))
20137 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20138 (org-let (if nosettings nil org-agenda-exporter-settings)
20139 '(save-excursion
20140 (save-window-excursion
20141 (cond
20142 ((string-match "\\.html?\\'" file)
20143 (set-buffer (htmlize-buffer (current-buffer)))
20145 (when (and org-agenda-export-html-style
20146 (string-match "<style>" org-agenda-export-html-style))
20147 ;; replace <style> section with org-agenda-export-html-style
20148 (goto-char (point-min))
20149 (kill-region (- (search-forward "<style") 6)
20150 (search-forward "</style>"))
20151 (insert org-agenda-export-html-style))
20152 (write-file file)
20153 (kill-buffer (current-buffer))
20154 (message "HTML written to %s" file))
20155 ((string-match "\\.ps\\'" file)
20156 (ps-print-buffer-with-faces file)
20157 (message "Postscript written to %s" file))
20159 (let ((bs (buffer-string)))
20160 (find-file file)
20161 (insert bs)
20162 (save-buffer 0)
20163 (kill-buffer (current-buffer))
20164 (message "Plain text written to %s" file))))))
20165 (set-buffer org-agenda-buffer-name)))
20167 (defmacro org-no-read-only (&rest body)
20168 "Inhibit read-only for BODY."
20169 `(let ((inhibit-read-only t)) ,@body))
20171 (defun org-check-for-org-mode ()
20172 "Make sure current buffer is in org-mode. Error if not."
20173 (or (org-mode-p)
20174 (error "Cannot execute org-mode agenda command on buffer in %s."
20175 major-mode)))
20177 (defun org-fit-agenda-window ()
20178 "Fit the window to the buffer size."
20179 (and (memq org-agenda-window-setup '(reorganize-frame))
20180 (fboundp 'fit-window-to-buffer)
20181 (fit-window-to-buffer
20183 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20184 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20186 ;;; Agenda file list
20188 (defun org-agenda-files (&optional unrestricted)
20189 "Get the list of agenda files.
20190 Optional UNRESTRICTED means return the full list even if a restriction
20191 is currently in place."
20192 (let ((files
20193 (cond
20194 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20195 ((stringp org-agenda-files) (org-read-agenda-file-list))
20196 ((listp org-agenda-files) org-agenda-files)
20197 (t (error "Invalid value of `org-agenda-files'")))))
20198 (setq files (apply 'append
20199 (mapcar (lambda (f)
20200 (if (file-directory-p f)
20201 (directory-files f t
20202 org-agenda-file-regexp)
20203 (list f)))
20204 files)))
20205 (if org-agenda-skip-unavailable-files
20206 (delq nil
20207 (mapcar (function
20208 (lambda (file)
20209 (and (file-readable-p file) file)))
20210 files))
20211 files))) ; `org-check-agenda-file' will remove them from the list
20213 (defun org-edit-agenda-file-list ()
20214 "Edit the list of agenda files.
20215 Depending on setup, this either uses customize to edit the variable
20216 `org-agenda-files', or it visits the file that is holding the list. In the
20217 latter case, the buffer is set up in a way that saving it automatically kills
20218 the buffer and restores the previous window configuration."
20219 (interactive)
20220 (if (stringp org-agenda-files)
20221 (let ((cw (current-window-configuration)))
20222 (find-file org-agenda-files)
20223 (org-set-local 'org-window-configuration cw)
20224 (org-add-hook 'after-save-hook
20225 (lambda ()
20226 (set-window-configuration
20227 (prog1 org-window-configuration
20228 (kill-buffer (current-buffer))))
20229 (org-install-agenda-files-menu)
20230 (message "New agenda file list installed"))
20231 nil 'local)
20232 (message "%s" (substitute-command-keys
20233 "Edit list and finish with \\[save-buffer]")))
20234 (customize-variable 'org-agenda-files)))
20236 (defun org-store-new-agenda-file-list (list)
20237 "Set new value for the agenda file list and save it correcly."
20238 (if (stringp org-agenda-files)
20239 (let ((f org-agenda-files) b)
20240 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20241 (with-temp-file f
20242 (insert (mapconcat 'identity list "\n") "\n")))
20243 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20244 (setq org-agenda-files list)
20245 (customize-save-variable 'org-agenda-files org-agenda-files))))
20247 (defun org-read-agenda-file-list ()
20248 "Read the list of agenda files from a file."
20249 (when (stringp org-agenda-files)
20250 (with-temp-buffer
20251 (insert-file-contents org-agenda-files)
20252 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20255 ;;;###autoload
20256 (defun org-cycle-agenda-files ()
20257 "Cycle through the files in `org-agenda-files'.
20258 If the current buffer visits an agenda file, find the next one in the list.
20259 If the current buffer does not, find the first agenda file."
20260 (interactive)
20261 (let* ((fs (org-agenda-files t))
20262 (files (append fs (list (car fs))))
20263 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20264 file)
20265 (unless files (error "No agenda files"))
20266 (catch 'exit
20267 (while (setq file (pop files))
20268 (if (equal (file-truename file) tcf)
20269 (when (car files)
20270 (find-file (car files))
20271 (throw 'exit t))))
20272 (find-file (car fs)))
20273 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20275 (defun org-agenda-file-to-front (&optional to-end)
20276 "Move/add the current file to the top of the agenda file list.
20277 If the file is not present in the list, it is added to the front. If it is
20278 present, it is moved there. With optional argument TO-END, add/move to the
20279 end of the list."
20280 (interactive "P")
20281 (let ((org-agenda-skip-unavailable-files nil)
20282 (file-alist (mapcar (lambda (x)
20283 (cons (file-truename x) x))
20284 (org-agenda-files t)))
20285 (ctf (file-truename buffer-file-name))
20286 x had)
20287 (setq x (assoc ctf file-alist) had x)
20289 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20290 (if to-end
20291 (setq file-alist (append (delq x file-alist) (list x)))
20292 (setq file-alist (cons x (delq x file-alist))))
20293 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20294 (org-install-agenda-files-menu)
20295 (message "File %s to %s of agenda file list"
20296 (if had "moved" "added") (if to-end "end" "front"))))
20298 (defun org-remove-file (&optional file)
20299 "Remove current file from the list of files in variable `org-agenda-files'.
20300 These are the files which are being checked for agenda entries.
20301 Optional argument FILE means, use this file instead of the current."
20302 (interactive)
20303 (let* ((org-agenda-skip-unavailable-files nil)
20304 (file (or file buffer-file-name))
20305 (true-file (file-truename file))
20306 (afile (abbreviate-file-name file))
20307 (files (delq nil (mapcar
20308 (lambda (x)
20309 (if (equal true-file
20310 (file-truename x))
20311 nil x))
20312 (org-agenda-files t)))))
20313 (if (not (= (length files) (length (org-agenda-files t))))
20314 (progn
20315 (org-store-new-agenda-file-list files)
20316 (org-install-agenda-files-menu)
20317 (message "Removed file: %s" afile))
20318 (message "File was not in list: %s (not removed)" afile))))
20320 (defun org-file-menu-entry (file)
20321 (vector file (list 'find-file file) t))
20323 (defun org-check-agenda-file (file)
20324 "Make sure FILE exists. If not, ask user what to do."
20325 (when (not (file-exists-p file))
20326 (message "non-existent file %s. [R]emove from list or [A]bort?"
20327 (abbreviate-file-name file))
20328 (let ((r (downcase (read-char-exclusive))))
20329 (cond
20330 ((equal r ?r)
20331 (org-remove-file file)
20332 (throw 'nextfile t))
20333 (t (error "Abort"))))))
20335 ;;; Agenda prepare and finalize
20337 (defvar org-agenda-multi nil) ; dynammically scoped
20338 (defvar org-agenda-buffer-name "*Org Agenda*")
20339 (defvar org-pre-agenda-window-conf nil)
20340 (defvar org-agenda-name nil)
20341 (defun org-prepare-agenda (&optional name)
20342 (setq org-todo-keywords-for-agenda nil)
20343 (setq org-done-keywords-for-agenda nil)
20344 (if org-agenda-multi
20345 (progn
20346 (setq buffer-read-only nil)
20347 (goto-char (point-max))
20348 (unless (or (bobp) org-agenda-compact-blocks)
20349 (insert "\n" (make-string (window-width) ?=) "\n"))
20350 (narrow-to-region (point) (point-max)))
20351 (org-agenda-reset-markers)
20352 (org-prepare-agenda-buffers (org-agenda-files))
20353 (setq org-todo-keywords-for-agenda
20354 (org-uniquify org-todo-keywords-for-agenda))
20355 (setq org-done-keywords-for-agenda
20356 (org-uniquify org-done-keywords-for-agenda))
20357 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20358 (awin (get-buffer-window abuf)))
20359 (cond
20360 ((equal (current-buffer) abuf) nil)
20361 (awin (select-window awin))
20362 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20363 ((equal org-agenda-window-setup 'current-window)
20364 (switch-to-buffer abuf))
20365 ((equal org-agenda-window-setup 'other-window)
20366 (org-switch-to-buffer-other-window abuf))
20367 ((equal org-agenda-window-setup 'other-frame)
20368 (switch-to-buffer-other-frame abuf))
20369 ((equal org-agenda-window-setup 'reorganize-frame)
20370 (delete-other-windows)
20371 (org-switch-to-buffer-other-window abuf))))
20372 (setq buffer-read-only nil)
20373 (erase-buffer)
20374 (org-agenda-mode)
20375 (and name (not org-agenda-name)
20376 (org-set-local 'org-agenda-name name)))
20377 (setq buffer-read-only nil))
20379 (defun org-finalize-agenda ()
20380 "Finishing touch for the agenda buffer, called just before displaying it."
20381 (unless org-agenda-multi
20382 (save-excursion
20383 (let ((inhibit-read-only t))
20384 (goto-char (point-min))
20385 (while (org-activate-bracket-links (point-max))
20386 (add-text-properties (match-beginning 0) (match-end 0)
20387 '(face org-link)))
20388 (org-agenda-align-tags)
20389 (unless org-agenda-with-colors
20390 (remove-text-properties (point-min) (point-max) '(face nil))))
20391 (if (and (boundp 'org-overriding-columns-format)
20392 org-overriding-columns-format)
20393 (org-set-local 'org-overriding-columns-format
20394 org-overriding-columns-format))
20395 (if (and (boundp 'org-agenda-view-columns-initially)
20396 org-agenda-view-columns-initially)
20397 (org-agenda-columns))
20398 (when org-agenda-fontify-priorities
20399 (org-fontify-priorities))
20400 (run-hooks 'org-finalize-agenda-hook)
20401 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20404 (defun org-fontify-priorities ()
20405 "Make highest priority lines bold, and lowest italic."
20406 (interactive)
20407 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20408 (org-delete-overlay o)))
20409 (org-overlays-in (point-min) (point-max)))
20410 (save-excursion
20411 (let ((inhibit-read-only t)
20412 b e p ov h l)
20413 (goto-char (point-min))
20414 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20415 (setq h (or (get-char-property (point) 'org-highest-priority)
20416 org-highest-priority)
20417 l (or (get-char-property (point) 'org-lowest-priority)
20418 org-lowest-priority)
20419 p (string-to-char (match-string 1))
20420 b (match-beginning 0) e (point-at-eol)
20421 ov (org-make-overlay b e))
20422 (org-overlay-put
20423 ov 'face
20424 (cond ((listp org-agenda-fontify-priorities)
20425 (cdr (assoc p org-agenda-fontify-priorities)))
20426 ((equal p l) 'italic)
20427 ((equal p h) 'bold)))
20428 (org-overlay-put ov 'org-type 'org-priority)))))
20430 (defun org-prepare-agenda-buffers (files)
20431 "Create buffers for all agenda files, protect archived trees and comments."
20432 (interactive)
20433 (let ((pa '(:org-archived t))
20434 (pc '(:org-comment t))
20435 (pall '(:org-archived t :org-comment t))
20436 (inhibit-read-only t)
20437 (rea (concat ":" org-archive-tag ":"))
20438 bmp file re)
20439 (save-excursion
20440 (save-restriction
20441 (while (setq file (pop files))
20442 (if (bufferp file)
20443 (set-buffer file)
20444 (org-check-agenda-file file)
20445 (set-buffer (org-get-agenda-file-buffer file)))
20446 (widen)
20447 (setq bmp (buffer-modified-p))
20448 (org-refresh-category-properties)
20449 (setq org-todo-keywords-for-agenda
20450 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20451 (setq org-done-keywords-for-agenda
20452 (append org-done-keywords-for-agenda org-done-keywords))
20453 (save-excursion
20454 (remove-text-properties (point-min) (point-max) pall)
20455 (when org-agenda-skip-archived-trees
20456 (goto-char (point-min))
20457 (while (re-search-forward rea nil t)
20458 (if (org-on-heading-p t)
20459 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20460 (goto-char (point-min))
20461 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20462 (while (re-search-forward re nil t)
20463 (add-text-properties
20464 (match-beginning 0) (org-end-of-subtree t) pc)))
20465 (set-buffer-modified-p bmp))))))
20467 (defvar org-agenda-skip-function nil
20468 "Function to be called at each match during agenda construction.
20469 If this function returns nil, the current match should not be skipped.
20470 Otherwise, the function must return a position from where the search
20471 should be continued.
20472 This may also be a Lisp form, it will be evaluated.
20473 Never set this variable using `setq' or so, because then it will apply
20474 to all future agenda commands. Instead, bind it with `let' to scope
20475 it dynamically into the agenda-constructing command. A good way to set
20476 it is through options in org-agenda-custom-commands.")
20478 (defun org-agenda-skip ()
20479 "Throw to `:skip' in places that should be skipped.
20480 Also moves point to the end of the skipped region, so that search can
20481 continue from there."
20482 (let ((p (point-at-bol)) to fp)
20483 (and org-agenda-skip-archived-trees
20484 (get-text-property p :org-archived)
20485 (org-end-of-subtree t)
20486 (throw :skip t))
20487 (and (get-text-property p :org-comment)
20488 (org-end-of-subtree t)
20489 (throw :skip t))
20490 (if (equal (char-after p) ?#) (throw :skip t))
20491 (when (and (or (setq fp (functionp org-agenda-skip-function))
20492 (consp org-agenda-skip-function))
20493 (setq to (save-excursion
20494 (save-match-data
20495 (if fp
20496 (funcall org-agenda-skip-function)
20497 (eval org-agenda-skip-function))))))
20498 (goto-char to)
20499 (throw :skip t))))
20501 (defvar org-agenda-markers nil
20502 "List of all currently active markers created by `org-agenda'.")
20503 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20504 "Creation time of the last agenda marker.")
20506 (defun org-agenda-new-marker (&optional pos)
20507 "Return a new agenda marker.
20508 Org-mode keeps a list of these markers and resets them when they are
20509 no longer in use."
20510 (let ((m (copy-marker (or pos (point)))))
20511 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20512 (push m org-agenda-markers)
20515 (defun org-agenda-reset-markers ()
20516 "Reset markers created by `org-agenda'."
20517 (while org-agenda-markers
20518 (move-marker (pop org-agenda-markers) nil)))
20520 (defun org-get-agenda-file-buffer (file)
20521 "Get a buffer visiting FILE. If the buffer needs to be created, add
20522 it to the list of buffers which might be released later."
20523 (let ((buf (org-find-base-buffer-visiting file)))
20524 (if buf
20525 buf ; just return it
20526 ;; Make a new buffer and remember it
20527 (setq buf (find-file-noselect file))
20528 (if buf (push buf org-agenda-new-buffers))
20529 buf)))
20531 (defun org-release-buffers (blist)
20532 "Release all buffers in list, asking the user for confirmation when needed.
20533 When a buffer is unmodified, it is just killed. When modified, it is saved
20534 \(if the user agrees) and then killed."
20535 (let (buf file)
20536 (while (setq buf (pop blist))
20537 (setq file (buffer-file-name buf))
20538 (when (and (buffer-modified-p buf)
20539 file
20540 (y-or-n-p (format "Save file %s? " file)))
20541 (with-current-buffer buf (save-buffer)))
20542 (kill-buffer buf))))
20544 (defun org-get-category (&optional pos)
20545 "Get the category applying to position POS."
20546 (get-text-property (or pos (point)) 'org-category))
20548 ;;; Agenda timeline
20550 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20552 (defun org-timeline (&optional include-all)
20553 "Show a time-sorted view of the entries in the current org file.
20554 Only entries with a time stamp of today or later will be listed. With
20555 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20556 under the current date.
20557 If the buffer contains an active region, only check the region for
20558 dates."
20559 (interactive "P")
20560 (require 'calendar)
20561 (org-compile-prefix-format 'timeline)
20562 (org-set-sorting-strategy 'timeline)
20563 (let* ((dopast t)
20564 (dotodo include-all)
20565 (doclosed org-agenda-show-log)
20566 (entry buffer-file-name)
20567 (date (calendar-current-date))
20568 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20569 (end (if (org-region-active-p) (region-end) (point-max)))
20570 (day-numbers (org-get-all-dates beg end 'no-ranges
20571 t doclosed ; always include today
20572 org-timeline-show-empty-dates))
20573 (org-deadline-warning-days 0)
20574 (org-agenda-only-exact-dates t)
20575 (today (time-to-days (current-time)))
20576 (past t)
20577 args
20578 s e rtn d emptyp)
20579 (setq org-agenda-redo-command
20580 (list 'progn
20581 (list 'org-switch-to-buffer-other-window (current-buffer))
20582 (list 'org-timeline (list 'quote include-all))))
20583 (if (not dopast)
20584 ;; Remove past dates from the list of dates.
20585 (setq day-numbers (delq nil (mapcar (lambda(x)
20586 (if (>= x today) x nil))
20587 day-numbers))))
20588 (org-prepare-agenda (concat "Timeline "
20589 (file-name-nondirectory buffer-file-name)))
20590 (if doclosed (push :closed args))
20591 (push :timestamp args)
20592 (push :deadline args)
20593 (push :scheduled args)
20594 (push :sexp args)
20595 (if dotodo (push :todo args))
20596 (while (setq d (pop day-numbers))
20597 (if (and (listp d) (eq (car d) :omitted))
20598 (progn
20599 (setq s (point))
20600 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20601 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20602 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20603 (if (and (>= d today)
20604 dopast
20605 past)
20606 (progn
20607 (setq past nil)
20608 (insert (make-string 79 ?-) "\n")))
20609 (setq date (calendar-gregorian-from-absolute d))
20610 (setq s (point))
20611 (setq rtn (and (not emptyp)
20612 (apply 'org-agenda-get-day-entries entry
20613 date args)))
20614 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20615 (progn
20616 (insert
20617 (if (stringp org-agenda-format-date)
20618 (format-time-string org-agenda-format-date
20619 (org-time-from-absolute date))
20620 (funcall org-agenda-format-date date))
20621 "\n")
20622 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20623 (put-text-property s (1- (point)) 'org-date-line t)
20624 (if (equal d today)
20625 (put-text-property s (1- (point)) 'org-today t))
20626 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20627 (put-text-property s (1- (point)) 'day d)))))
20628 (goto-char (point-min))
20629 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20630 (point-min)))
20631 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20632 (org-finalize-agenda)
20633 (setq buffer-read-only t)))
20635 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20636 "Return a list of all relevant day numbers from BEG to END buffer positions.
20637 If NO-RANGES is non-nil, include only the start and end dates of a range,
20638 not every single day in the range. If FORCE-TODAY is non-nil, make
20639 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20640 inactive time stamps (those in square brackets) are included.
20641 When EMPTY is non-nil, also include days without any entries."
20642 (let ((re (concat
20643 (if pre-re pre-re "")
20644 (if inactive org-ts-regexp-both org-ts-regexp)))
20645 dates dates1 date day day1 day2 ts1 ts2)
20646 (if force-today
20647 (setq dates (list (time-to-days (current-time)))))
20648 (save-excursion
20649 (goto-char beg)
20650 (while (re-search-forward re end t)
20651 (setq day (time-to-days (org-time-string-to-time
20652 (substring (match-string 1) 0 10))))
20653 (or (memq day dates) (push day dates)))
20654 (unless no-ranges
20655 (goto-char beg)
20656 (while (re-search-forward org-tr-regexp end t)
20657 (setq ts1 (substring (match-string 1) 0 10)
20658 ts2 (substring (match-string 2) 0 10)
20659 day1 (time-to-days (org-time-string-to-time ts1))
20660 day2 (time-to-days (org-time-string-to-time ts2)))
20661 (while (< (setq day1 (1+ day1)) day2)
20662 (or (memq day1 dates) (push day1 dates)))))
20663 (setq dates (sort dates '<))
20664 (when empty
20665 (while (setq day (pop dates))
20666 (setq day2 (car dates))
20667 (push day dates1)
20668 (when (and day2 empty)
20669 (if (or (eq empty t)
20670 (and (numberp empty) (<= (- day2 day) empty)))
20671 (while (< (setq day (1+ day)) day2)
20672 (push (list day) dates1))
20673 (push (cons :omitted (- day2 day)) dates1))))
20674 (setq dates (nreverse dates1)))
20675 dates)))
20677 ;;; Agenda Daily/Weekly
20679 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20680 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20681 (defvar org-agenda-last-arguments nil
20682 "The arguments of the previous call to org-agenda")
20683 (defvar org-starting-day nil) ; local variable in the agenda buffer
20684 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20685 (defvar org-include-all-loc nil) ; local variable
20686 (defvar org-agenda-remove-date nil) ; dynamically scoped
20688 ;;;###autoload
20689 (defun org-agenda-list (&optional include-all start-day ndays)
20690 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20691 The view will be for the current day or week, but from the overview buffer
20692 you will be able to go to other days/weeks.
20694 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20695 all unfinished TODO items will also be shown, before the agenda.
20696 This feature is considered obsolete, please use the TODO list or a block
20697 agenda instead.
20699 With a numeric prefix argument in an interactive call, the agenda will
20700 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20701 the number of days. NDAYS defaults to `org-agenda-ndays'.
20703 START-DAY defaults to TODAY, or to the most recent match for the weekday
20704 given in `org-agenda-start-on-weekday'."
20705 (interactive "P")
20706 (if (and (integerp include-all) (> include-all 0))
20707 (setq ndays include-all include-all nil))
20708 (setq ndays (or ndays org-agenda-ndays)
20709 start-day (or start-day org-agenda-start-day))
20710 (if org-agenda-overriding-arguments
20711 (setq include-all (car org-agenda-overriding-arguments)
20712 start-day (nth 1 org-agenda-overriding-arguments)
20713 ndays (nth 2 org-agenda-overriding-arguments)))
20714 (if (stringp start-day)
20715 ;; Convert to an absolute day number
20716 (setq start-day (time-to-days (org-read-date nil t start-day))))
20717 (setq org-agenda-last-arguments (list include-all start-day ndays))
20718 (org-compile-prefix-format 'agenda)
20719 (org-set-sorting-strategy 'agenda)
20720 (require 'calendar)
20721 (let* ((org-agenda-start-on-weekday
20722 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20723 org-agenda-start-on-weekday nil))
20724 (thefiles (org-agenda-files))
20725 (files thefiles)
20726 (today (time-to-days
20727 (time-subtract (current-time)
20728 (list 0 (* 3600 org-extend-today-until) 0))))
20729 (sd (or start-day today))
20730 (start (if (or (null org-agenda-start-on-weekday)
20731 (< org-agenda-ndays 7))
20733 (let* ((nt (calendar-day-of-week
20734 (calendar-gregorian-from-absolute sd)))
20735 (n1 org-agenda-start-on-weekday)
20736 (d (- nt n1)))
20737 (- sd (+ (if (< d 0) 7 0) d)))))
20738 (day-numbers (list start))
20739 (day-cnt 0)
20740 (inhibit-redisplay (not debug-on-error))
20741 s e rtn rtnall file date d start-pos end-pos todayp nd)
20742 (setq org-agenda-redo-command
20743 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20744 ;; Make the list of days
20745 (setq ndays (or ndays org-agenda-ndays)
20746 nd ndays)
20747 (while (> ndays 1)
20748 (push (1+ (car day-numbers)) day-numbers)
20749 (setq ndays (1- ndays)))
20750 (setq day-numbers (nreverse day-numbers))
20751 (org-prepare-agenda "Day/Week")
20752 (org-set-local 'org-starting-day (car day-numbers))
20753 (org-set-local 'org-include-all-loc include-all)
20754 (org-set-local 'org-agenda-span
20755 (org-agenda-ndays-to-span nd))
20756 (when (and (or include-all org-agenda-include-all-todo)
20757 (member today day-numbers))
20758 (setq files thefiles
20759 rtnall nil)
20760 (while (setq file (pop files))
20761 (catch 'nextfile
20762 (org-check-agenda-file file)
20763 (setq date (calendar-gregorian-from-absolute today)
20764 rtn (org-agenda-get-day-entries
20765 file date :todo))
20766 (setq rtnall (append rtnall rtn))))
20767 (when rtnall
20768 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20769 (add-text-properties (point-min) (1- (point))
20770 (list 'face 'org-agenda-structure))
20771 (insert (org-finalize-agenda-entries rtnall) "\n")))
20772 (unless org-agenda-compact-blocks
20773 (setq s (point))
20774 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20775 "-agenda:\n")
20776 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20777 'org-date-line t)))
20778 (while (setq d (pop day-numbers))
20779 (setq date (calendar-gregorian-from-absolute d)
20780 s (point))
20781 (if (or (setq todayp (= d today))
20782 (and (not start-pos) (= d sd)))
20783 (setq start-pos (point))
20784 (if (and start-pos (not end-pos))
20785 (setq end-pos (point))))
20786 (setq files thefiles
20787 rtnall nil)
20788 (while (setq file (pop files))
20789 (catch 'nextfile
20790 (org-check-agenda-file file)
20791 (if org-agenda-show-log
20792 (setq rtn (org-agenda-get-day-entries
20793 file date
20794 :deadline :scheduled :timestamp :sexp :closed))
20795 (setq rtn (org-agenda-get-day-entries
20796 file date
20797 :deadline :scheduled :sexp :timestamp)))
20798 (setq rtnall (append rtnall rtn))))
20799 (if org-agenda-include-diary
20800 (progn
20801 (require 'diary-lib)
20802 (setq rtn (org-get-entries-from-diary date))
20803 (setq rtnall (append rtnall rtn))))
20804 (if (or rtnall org-agenda-show-all-dates)
20805 (progn
20806 (setq day-cnt (1+ day-cnt))
20807 (insert
20808 (if (stringp org-agenda-format-date)
20809 (format-time-string org-agenda-format-date
20810 (org-time-from-absolute date))
20811 (funcall org-agenda-format-date date))
20812 "\n")
20813 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20814 (put-text-property s (1- (point)) 'org-date-line t)
20815 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20816 (if todayp (put-text-property s (1- (point)) 'org-today t))
20817 (if rtnall (insert
20818 (org-finalize-agenda-entries
20819 (org-agenda-add-time-grid-maybe
20820 rtnall nd todayp))
20821 "\n"))
20822 (put-text-property s (1- (point)) 'day d)
20823 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20824 (goto-char (point-min))
20825 (org-fit-agenda-window)
20826 (unless (and (pos-visible-in-window-p (point-min))
20827 (pos-visible-in-window-p (point-max)))
20828 (goto-char (1- (point-max)))
20829 (recenter -1)
20830 (if (not (pos-visible-in-window-p (or start-pos 1)))
20831 (progn
20832 (goto-char (or start-pos 1))
20833 (recenter 1))))
20834 (goto-char (or start-pos 1))
20835 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20836 (org-finalize-agenda)
20837 (setq buffer-read-only t)
20838 (message "")))
20840 (defun org-agenda-ndays-to-span (n)
20841 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20843 ;;; Agenda TODO list
20845 (defvar org-select-this-todo-keyword nil)
20846 (defvar org-last-arg nil)
20848 ;;;###autoload
20849 (defun org-todo-list (arg)
20850 "Show all TODO entries from all agenda file in a single list.
20851 The prefix arg can be used to select a specific TODO keyword and limit
20852 the list to these. When using \\[universal-argument], you will be prompted
20853 for a keyword. A numeric prefix directly selects the Nth keyword in
20854 `org-todo-keywords-1'."
20855 (interactive "P")
20856 (require 'calendar)
20857 (org-compile-prefix-format 'todo)
20858 (org-set-sorting-strategy 'todo)
20859 (org-prepare-agenda "TODO")
20860 (let* ((today (time-to-days (current-time)))
20861 (date (calendar-gregorian-from-absolute today))
20862 (kwds org-todo-keywords-for-agenda)
20863 (completion-ignore-case t)
20864 (org-select-this-todo-keyword
20865 (if (stringp arg) arg
20866 (and arg (integerp arg) (> arg 0)
20867 (nth (1- arg) kwds))))
20868 rtn rtnall files file pos)
20869 (when (equal arg '(4))
20870 (setq org-select-this-todo-keyword
20871 (completing-read "Keyword (or KWD1|K2D2|...): "
20872 (mapcar 'list kwds) nil nil)))
20873 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20874 (org-set-local 'org-last-arg arg)
20875 (setq org-agenda-redo-command
20876 '(org-todo-list (or current-prefix-arg org-last-arg)))
20877 (setq files (org-agenda-files)
20878 rtnall nil)
20879 (while (setq file (pop files))
20880 (catch 'nextfile
20881 (org-check-agenda-file file)
20882 (setq rtn (org-agenda-get-day-entries file date :todo))
20883 (setq rtnall (append rtnall rtn))))
20884 (if org-agenda-overriding-header
20885 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20886 nil 'face 'org-agenda-structure) "\n")
20887 (insert "Global list of TODO items of type: ")
20888 (add-text-properties (point-min) (1- (point))
20889 (list 'face 'org-agenda-structure))
20890 (setq pos (point))
20891 (insert (or org-select-this-todo-keyword "ALL") "\n")
20892 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20893 (setq pos (point))
20894 (unless org-agenda-multi
20895 (insert "Available with `N r': (0)ALL")
20896 (let ((n 0) s)
20897 (mapc (lambda (x)
20898 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20899 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20900 (insert "\n "))
20901 (insert " " s))
20902 kwds))
20903 (insert "\n"))
20904 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20905 (when rtnall
20906 (insert (org-finalize-agenda-entries rtnall) "\n"))
20907 (goto-char (point-min))
20908 (org-fit-agenda-window)
20909 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20910 (org-finalize-agenda)
20911 (setq buffer-read-only t)))
20913 ;;; Agenda tags match
20915 ;;;###autoload
20916 (defun org-tags-view (&optional todo-only match)
20917 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20918 The prefix arg TODO-ONLY limits the search to TODO entries."
20919 (interactive "P")
20920 (org-compile-prefix-format 'tags)
20921 (org-set-sorting-strategy 'tags)
20922 (let* ((org-tags-match-list-sublevels
20923 (if todo-only t org-tags-match-list-sublevels))
20924 (completion-ignore-case t)
20925 rtn rtnall files file pos matcher
20926 buffer)
20927 (setq matcher (org-make-tags-matcher match)
20928 match (car matcher) matcher (cdr matcher))
20929 (org-prepare-agenda (concat "TAGS " match))
20930 (setq org-agenda-redo-command
20931 (list 'org-tags-view (list 'quote todo-only)
20932 (list 'if 'current-prefix-arg nil match)))
20933 (setq files (org-agenda-files)
20934 rtnall nil)
20935 (while (setq file (pop files))
20936 (catch 'nextfile
20937 (org-check-agenda-file file)
20938 (setq buffer (if (file-exists-p file)
20939 (org-get-agenda-file-buffer file)
20940 (error "No such file %s" file)))
20941 (if (not buffer)
20942 ;; If file does not exist, merror message to agenda
20943 (setq rtn (list
20944 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20945 rtnall (append rtnall rtn))
20946 (with-current-buffer buffer
20947 (unless (org-mode-p)
20948 (error "Agenda file %s is not in `org-mode'" file))
20949 (save-excursion
20950 (save-restriction
20951 (if org-agenda-restrict
20952 (narrow-to-region org-agenda-restrict-begin
20953 org-agenda-restrict-end)
20954 (widen))
20955 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20956 (setq rtnall (append rtnall rtn))))))))
20957 (if org-agenda-overriding-header
20958 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20959 nil 'face 'org-agenda-structure) "\n")
20960 (insert "Headlines with TAGS match: ")
20961 (add-text-properties (point-min) (1- (point))
20962 (list 'face 'org-agenda-structure))
20963 (setq pos (point))
20964 (insert match "\n")
20965 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20966 (setq pos (point))
20967 (unless org-agenda-multi
20968 (insert "Press `C-u r' to search again with new search string\n"))
20969 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20970 (when rtnall
20971 (insert (org-finalize-agenda-entries rtnall) "\n"))
20972 (goto-char (point-min))
20973 (org-fit-agenda-window)
20974 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20975 (org-finalize-agenda)
20976 (setq buffer-read-only t)))
20978 ;;; Agenda Finding stuck projects
20980 (defvar org-agenda-skip-regexp nil
20981 "Regular expression used in skipping subtrees for the agenda.
20982 This is basically a temporary global variable that can be set and then
20983 used by user-defined selections using `org-agenda-skip-function'.")
20985 (defvar org-agenda-overriding-header nil
20986 "When this is set during todo and tags searches, will replace header.")
20988 (defun org-agenda-skip-subtree-when-regexp-matches ()
20989 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20990 If yes, it returns the end position of this tree, causing agenda commands
20991 to skip this subtree. This is a function that can be put into
20992 `org-agenda-skip-function' for the duration of a command."
20993 (let ((end (save-excursion (org-end-of-subtree t)))
20994 skip)
20995 (save-excursion
20996 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20997 (and skip end)))
20999 (defun org-agenda-skip-entry-if (&rest conditions)
21000 "Skip entry if any of CONDITIONS is true.
21001 See `org-agenda-skip-if' for details."
21002 (org-agenda-skip-if nil conditions))
21004 (defun org-agenda-skip-subtree-if (&rest conditions)
21005 "Skip entry if any of CONDITIONS is true.
21006 See `org-agenda-skip-if' for details."
21007 (org-agenda-skip-if t conditions))
21009 (defun org-agenda-skip-if (subtree conditions)
21010 "Checks current entity for CONDITIONS.
21011 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21012 the entry, i.e. the text before the next heading is checked.
21014 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21015 from different tests. Valid conditions are:
21017 scheduled Check if there is a scheduled cookie
21018 notscheduled Check if there is no scheduled cookie
21019 deadline Check if there is a deadline
21020 notdeadline Check if there is no deadline
21021 regexp Check if regexp matches
21022 notregexp Check if regexp does not match.
21024 The regexp is taken from the conditions list, it must come right after
21025 the `regexp' or `notregexp' element.
21027 If any of these conditions is met, this function returns the end point of
21028 the entity, causing the search to continue from there. This is a function
21029 that can be put into `org-agenda-skip-function' for the duration of a command."
21030 (let (beg end m)
21031 (org-back-to-heading t)
21032 (setq beg (point)
21033 end (if subtree
21034 (progn (org-end-of-subtree t) (point))
21035 (progn (outline-next-heading) (1- (point)))))
21036 (goto-char beg)
21037 (and
21039 (and (memq 'scheduled conditions)
21040 (re-search-forward org-scheduled-time-regexp end t))
21041 (and (memq 'notscheduled conditions)
21042 (not (re-search-forward org-scheduled-time-regexp end t)))
21043 (and (memq 'deadline conditions)
21044 (re-search-forward org-deadline-time-regexp end t))
21045 (and (memq 'notdeadline conditions)
21046 (not (re-search-forward org-deadline-time-regexp end t)))
21047 (and (setq m (memq 'regexp conditions))
21048 (stringp (nth 1 m))
21049 (re-search-forward (nth 1 m) end t))
21050 (and (setq m (memq 'notregexp conditions))
21051 (stringp (nth 1 m))
21052 (not (re-search-forward (nth 1 m) end t))))
21053 end)))
21055 ;;;###autoload
21056 (defun org-agenda-list-stuck-projects (&rest ignore)
21057 "Create agenda view for projects that are stuck.
21058 Stuck projects are project that have no next actions. For the definitions
21059 of what a project is and how to check if it stuck, customize the variable
21060 `org-stuck-projects'.
21061 MATCH is being ignored."
21062 (interactive)
21063 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21064 ;; FIXME: we could have used org-agenda-skip-if here.
21065 (org-agenda-overriding-header "List of stuck projects: ")
21066 (matcher (nth 0 org-stuck-projects))
21067 (todo (nth 1 org-stuck-projects))
21068 (todo-wds (if (member "*" todo)
21069 (progn
21070 (org-prepare-agenda-buffers (org-agenda-files))
21071 (org-delete-all
21072 org-done-keywords-for-agenda
21073 (copy-sequence org-todo-keywords-for-agenda)))
21074 todo))
21075 (todo-re (concat "^\\*+[ \t]+\\("
21076 (mapconcat 'identity todo-wds "\\|")
21077 "\\)\\>"))
21078 (tags (nth 2 org-stuck-projects))
21079 (tags-re (if (member "*" tags)
21080 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21081 (concat "^\\*+ .*:\\("
21082 (mapconcat 'identity tags "\\|")
21083 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21084 (gen-re (nth 3 org-stuck-projects))
21085 (re-list
21086 (delq nil
21087 (list
21088 (if todo todo-re)
21089 (if tags tags-re)
21090 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21091 gen-re)))))
21092 (setq org-agenda-skip-regexp
21093 (if re-list
21094 (mapconcat 'identity re-list "\\|")
21095 (error "No information how to identify unstuck projects")))
21096 (org-tags-view nil matcher)
21097 (with-current-buffer org-agenda-buffer-name
21098 (setq org-agenda-redo-command
21099 '(org-agenda-list-stuck-projects
21100 (or current-prefix-arg org-last-arg))))))
21102 ;;; Diary integration
21104 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21106 (defun org-get-entries-from-diary (date)
21107 "Get the (Emacs Calendar) diary entries for DATE."
21108 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21109 (diary-display-hook '(fancy-diary-display))
21110 (pop-up-frames nil)
21111 (list-diary-entries-hook
21112 (cons 'org-diary-default-entry list-diary-entries-hook))
21113 (diary-file-name-prefix-function nil) ; turn this feature off
21114 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21115 entries
21116 (org-disable-agenda-to-diary t))
21117 (save-excursion
21118 (save-window-excursion
21119 (funcall (if (fboundp 'diary-list-entries)
21120 'diary-list-entries 'list-diary-entries)
21121 date 1)))
21122 (if (not (get-buffer fancy-diary-buffer))
21123 (setq entries nil)
21124 (with-current-buffer fancy-diary-buffer
21125 (setq buffer-read-only nil)
21126 (if (zerop (buffer-size))
21127 ;; No entries
21128 (setq entries nil)
21129 ;; Omit the date and other unnecessary stuff
21130 (org-agenda-cleanup-fancy-diary)
21131 ;; Add prefix to each line and extend the text properties
21132 (if (zerop (buffer-size))
21133 (setq entries nil)
21134 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21135 (set-buffer-modified-p nil)
21136 (kill-buffer fancy-diary-buffer)))
21137 (when entries
21138 (setq entries (org-split-string entries "\n"))
21139 (setq entries
21140 (mapcar
21141 (lambda (x)
21142 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21143 ;; Extend the text properties to the beginning of the line
21144 (org-add-props x (text-properties-at (1- (length x)) x)
21145 'type "diary" 'date date))
21146 entries)))))
21148 (defun org-agenda-cleanup-fancy-diary ()
21149 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21150 This gets rid of the date, the underline under the date, and
21151 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21152 date. It also removes lines that contain only whitespace."
21153 (goto-char (point-min))
21154 (if (looking-at ".*?:[ \t]*")
21155 (progn
21156 (replace-match "")
21157 (re-search-forward "\n=+$" nil t)
21158 (replace-match "")
21159 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21160 (re-search-forward "\n=+$" nil t)
21161 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21162 (goto-char (point-min))
21163 (while (re-search-forward "^ +\n" nil t)
21164 (replace-match ""))
21165 (goto-char (point-min))
21166 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21167 (replace-match "")))
21169 ;; Make sure entries from the diary have the right text properties.
21170 (eval-after-load "diary-lib"
21171 '(if (boundp 'diary-modify-entry-list-string-function)
21172 ;; We can rely on the hook, nothing to do
21174 ;; Hook not avaiable, must use advice to make this work
21175 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21176 "Make the position visible."
21177 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21178 (stringp string)
21179 buffer-file-name)
21180 (setq string (org-modify-diary-entry-string string))))))
21182 (defun org-modify-diary-entry-string (string)
21183 "Add text properties to string, allowing org-mode to act on it."
21184 (org-add-props string nil
21185 'mouse-face 'highlight
21186 'keymap org-agenda-keymap
21187 'help-echo (if buffer-file-name
21188 (format "mouse-2 or RET jump to diary file %s"
21189 (abbreviate-file-name buffer-file-name))
21191 'org-agenda-diary-link t
21192 'org-marker (org-agenda-new-marker (point-at-bol))))
21194 (defun org-diary-default-entry ()
21195 "Add a dummy entry to the diary.
21196 Needed to avoid empty dates which mess up holiday display."
21197 ;; Catch the error if dealing with the new add-to-diary-alist
21198 (when org-disable-agenda-to-diary
21199 (condition-case nil
21200 (add-to-diary-list original-date "Org-mode dummy" "")
21201 (error
21202 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21204 ;;;###autoload
21205 (defun org-diary (&rest args)
21206 "Return diary information from org-files.
21207 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21208 It accesses org files and extracts information from those files to be
21209 listed in the diary. The function accepts arguments specifying what
21210 items should be listed. The following arguments are allowed:
21212 :timestamp List the headlines of items containing a date stamp or
21213 date range matching the selected date. Deadlines will
21214 also be listed, on the expiration day.
21216 :sexp List entries resulting from diary-like sexps.
21218 :deadline List any deadlines past due, or due within
21219 `org-deadline-warning-days'. The listing occurs only
21220 in the diary for *today*, not at any other date. If
21221 an entry is marked DONE, it is no longer listed.
21223 :scheduled List all items which are scheduled for the given date.
21224 The diary for *today* also contains items which were
21225 scheduled earlier and are not yet marked DONE.
21227 :todo List all TODO items from the org-file. This may be a
21228 long list - so this is not turned on by default.
21229 Like deadlines, these entries only show up in the
21230 diary for *today*, not at any other date.
21232 The call in the diary file should look like this:
21234 &%%(org-diary) ~/path/to/some/orgfile.org
21236 Use a separate line for each org file to check. Or, if you omit the file name,
21237 all files listed in `org-agenda-files' will be checked automatically:
21239 &%%(org-diary)
21241 If you don't give any arguments (as in the example above), the default
21242 arguments (:deadline :scheduled :timestamp :sexp) are used.
21243 So the example above may also be written as
21245 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21247 The function expects the lisp variables `entry' and `date' to be provided
21248 by the caller, because this is how the calendar works. Don't use this
21249 function from a program - use `org-agenda-get-day-entries' instead."
21250 (when (> (- (time-to-seconds (current-time))
21251 org-agenda-last-marker-time)
21253 (org-agenda-reset-markers))
21254 (org-compile-prefix-format 'agenda)
21255 (org-set-sorting-strategy 'agenda)
21256 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21257 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21258 (list entry)
21259 (org-agenda-files t)))
21260 file rtn results)
21261 (org-prepare-agenda-buffers files)
21262 ;; If this is called during org-agenda, don't return any entries to
21263 ;; the calendar. Org Agenda will list these entries itself.
21264 (if org-disable-agenda-to-diary (setq files nil))
21265 (while (setq file (pop files))
21266 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21267 (setq results (append results rtn)))
21268 (if results
21269 (concat (org-finalize-agenda-entries results) "\n"))))
21271 ;;; Agenda entry finders
21273 (defun org-agenda-get-day-entries (file date &rest args)
21274 "Does the work for `org-diary' and `org-agenda'.
21275 FILE is the path to a file to be checked for entries. DATE is date like
21276 the one returned by `calendar-current-date'. ARGS are symbols indicating
21277 which kind of entries should be extracted. For details about these, see
21278 the documentation of `org-diary'."
21279 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21280 (let* ((org-startup-folded nil)
21281 (org-startup-align-all-tables nil)
21282 (buffer (if (file-exists-p file)
21283 (org-get-agenda-file-buffer file)
21284 (error "No such file %s" file)))
21285 arg results rtn)
21286 (if (not buffer)
21287 ;; If file does not exist, make sure an error message ends up in diary
21288 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21289 (with-current-buffer buffer
21290 (unless (org-mode-p)
21291 (error "Agenda file %s is not in `org-mode'" file))
21292 (let ((case-fold-search nil))
21293 (save-excursion
21294 (save-restriction
21295 (if org-agenda-restrict
21296 (narrow-to-region org-agenda-restrict-begin
21297 org-agenda-restrict-end)
21298 (widen))
21299 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21300 (while (setq arg (pop args))
21301 (cond
21302 ((and (eq arg :todo)
21303 (equal date (calendar-current-date)))
21304 (setq rtn (org-agenda-get-todos))
21305 (setq results (append results rtn)))
21306 ((eq arg :timestamp)
21307 (setq rtn (org-agenda-get-blocks))
21308 (setq results (append results rtn))
21309 (setq rtn (org-agenda-get-timestamps))
21310 (setq results (append results rtn)))
21311 ((eq arg :sexp)
21312 (setq rtn (org-agenda-get-sexps))
21313 (setq results (append results rtn)))
21314 ((eq arg :scheduled)
21315 (setq rtn (org-agenda-get-scheduled))
21316 (setq results (append results rtn)))
21317 ((eq arg :closed)
21318 (setq rtn (org-agenda-get-closed))
21319 (setq results (append results rtn)))
21320 ((eq arg :deadline)
21321 (setq rtn (org-agenda-get-deadlines))
21322 (setq results (append results rtn))))))))
21323 results))))
21325 (defun org-entry-is-todo-p ()
21326 (member (org-get-todo-state) org-not-done-keywords))
21328 (defun org-entry-is-done-p ()
21329 (member (org-get-todo-state) org-done-keywords))
21331 (defun org-get-todo-state ()
21332 (save-excursion
21333 (org-back-to-heading t)
21334 (and (looking-at org-todo-line-regexp)
21335 (match-end 2)
21336 (match-string 2))))
21338 (defun org-at-date-range-p (&optional inactive-ok)
21339 "Is the cursor inside a date range?"
21340 (interactive)
21341 (save-excursion
21342 (catch 'exit
21343 (let ((pos (point)))
21344 (skip-chars-backward "^[<\r\n")
21345 (skip-chars-backward "<[")
21346 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21347 (>= (match-end 0) pos)
21348 (throw 'exit t))
21349 (skip-chars-backward "^<[\r\n")
21350 (skip-chars-backward "<[")
21351 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21352 (>= (match-end 0) pos)
21353 (throw 'exit t)))
21354 nil)))
21356 (defun org-agenda-get-todos ()
21357 "Return the TODO information for agenda display."
21358 (let* ((props (list 'face nil
21359 'done-face 'org-done
21360 'org-not-done-regexp org-not-done-regexp
21361 'org-todo-regexp org-todo-regexp
21362 'mouse-face 'highlight
21363 'keymap org-agenda-keymap
21364 'help-echo
21365 (format "mouse-2 or RET jump to org file %s"
21366 (abbreviate-file-name buffer-file-name))))
21367 ;; FIXME: get rid of the \n at some point but watch out
21368 (regexp (concat "^\\*+[ \t]+\\("
21369 (if org-select-this-todo-keyword
21370 (if (equal org-select-this-todo-keyword "*")
21371 org-todo-regexp
21372 (concat "\\<\\("
21373 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21374 "\\)\\>"))
21375 org-not-done-regexp)
21376 "[^\n\r]*\\)"))
21377 marker priority category tags
21378 ee txt beg end)
21379 (goto-char (point-min))
21380 (while (re-search-forward regexp nil t)
21381 (catch :skip
21382 (save-match-data
21383 (beginning-of-line)
21384 (setq beg (point) end (progn (outline-next-heading) (point)))
21385 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21386 (re-search-forward org-ts-regexp end t))
21387 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21388 (re-search-forward org-scheduled-time-regexp end t))
21389 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21390 (re-search-forward org-deadline-time-regexp end t)
21391 (org-deadline-close (match-string 1))))
21392 (goto-char (1+ beg))
21393 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21394 (throw :skip nil)))
21395 (goto-char beg)
21396 (org-agenda-skip)
21397 (goto-char (match-beginning 1))
21398 (setq marker (org-agenda-new-marker (match-beginning 0))
21399 category (org-get-category)
21400 tags (org-get-tags-at (point))
21401 txt (org-format-agenda-item "" (match-string 1) category tags)
21402 priority (1+ (org-get-priority txt)))
21403 (org-add-props txt props
21404 'org-marker marker 'org-hd-marker marker
21405 'priority priority 'org-category category
21406 'type "todo")
21407 (push txt ee)
21408 (if org-agenda-todo-list-sublevels
21409 (goto-char (match-end 1))
21410 (org-end-of-subtree 'invisible))))
21411 (nreverse ee)))
21413 (defconst org-agenda-no-heading-message
21414 "No heading for this item in buffer or region.")
21416 (defun org-agenda-get-timestamps ()
21417 "Return the date stamp information for agenda display."
21418 (let* ((props (list 'face nil
21419 'org-not-done-regexp org-not-done-regexp
21420 'org-todo-regexp org-todo-regexp
21421 'mouse-face 'highlight
21422 'keymap org-agenda-keymap
21423 'help-echo
21424 (format "mouse-2 or RET jump to org file %s"
21425 (abbreviate-file-name buffer-file-name))))
21426 (d1 (calendar-absolute-from-gregorian date))
21427 (remove-re
21428 (concat
21429 (regexp-quote
21430 (format-time-string
21431 "<%Y-%m-%d"
21432 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21433 ".*?>"))
21434 (regexp
21435 (concat
21436 (regexp-quote
21437 (substring
21438 (format-time-string
21439 (car org-time-stamp-formats)
21440 (apply 'encode-time ; DATE bound by calendar
21441 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21442 0 11))
21443 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21444 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21445 marker hdmarker deadlinep scheduledp donep tmp priority category
21446 ee txt timestr tags b0 b3 e3 head)
21447 (goto-char (point-min))
21448 (while (re-search-forward regexp nil t)
21449 (setq b0 (match-beginning 0)
21450 b3 (match-beginning 3) e3 (match-end 3))
21451 (catch :skip
21452 (and (org-at-date-range-p) (throw :skip nil))
21453 (org-agenda-skip)
21454 (if (and (match-end 1)
21455 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21456 (throw :skip nil))
21457 (if (and e3
21458 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21459 (throw :skip nil))
21460 (setq marker (org-agenda-new-marker b0)
21461 category (org-get-category b0)
21462 tmp (buffer-substring (max (point-min)
21463 (- b0 org-ds-keyword-length))
21465 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21466 deadlinep (string-match org-deadline-regexp tmp)
21467 scheduledp (string-match org-scheduled-regexp tmp)
21468 donep (org-entry-is-done-p))
21469 (if (or scheduledp deadlinep) (throw :skip t))
21470 (if (string-match ">" timestr)
21471 ;; substring should only run to end of time stamp
21472 (setq timestr (substring timestr 0 (match-end 0))))
21473 (save-excursion
21474 (if (re-search-backward "^\\*+ " nil t)
21475 (progn
21476 (goto-char (match-beginning 0))
21477 (setq hdmarker (org-agenda-new-marker)
21478 tags (org-get-tags-at))
21479 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21480 (setq head (match-string 1))
21481 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21482 (setq txt (org-format-agenda-item
21483 nil head category tags timestr nil
21484 remove-re)))
21485 (setq txt org-agenda-no-heading-message))
21486 (setq priority (org-get-priority txt))
21487 (org-add-props txt props
21488 'org-marker marker 'org-hd-marker hdmarker)
21489 (org-add-props txt nil 'priority priority
21490 'org-category category 'date date
21491 'type "timestamp")
21492 (push txt ee))
21493 (outline-next-heading)))
21494 (nreverse ee)))
21496 (defun org-agenda-get-sexps ()
21497 "Return the sexp information for agenda display."
21498 (require 'diary-lib)
21499 (let* ((props (list 'face nil
21500 'mouse-face 'highlight
21501 'keymap org-agenda-keymap
21502 'help-echo
21503 (format "mouse-2 or RET jump to org file %s"
21504 (abbreviate-file-name buffer-file-name))))
21505 (regexp "^&?%%(")
21506 marker category ee txt tags entry result beg b sexp sexp-entry)
21507 (goto-char (point-min))
21508 (while (re-search-forward regexp nil t)
21509 (catch :skip
21510 (org-agenda-skip)
21511 (setq beg (match-beginning 0))
21512 (goto-char (1- (match-end 0)))
21513 (setq b (point))
21514 (forward-sexp 1)
21515 (setq sexp (buffer-substring b (point)))
21516 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21517 (org-trim (match-string 1))
21518 ""))
21519 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21520 (when result
21521 (setq marker (org-agenda-new-marker beg)
21522 category (org-get-category beg))
21524 (if (string-match "\\S-" result)
21525 (setq txt result)
21526 (setq txt "SEXP entry returned empty string"))
21528 (setq txt (org-format-agenda-item
21529 "" txt category tags 'time))
21530 (org-add-props txt props 'org-marker marker)
21531 (org-add-props txt nil
21532 'org-category category 'date date
21533 'type "sexp")
21534 (push txt ee))))
21535 (nreverse ee)))
21537 (defun org-agenda-get-closed ()
21538 "Return the logged TODO entries for agenda display."
21539 (let* ((props (list 'mouse-face 'highlight
21540 'org-not-done-regexp org-not-done-regexp
21541 'org-todo-regexp org-todo-regexp
21542 'keymap org-agenda-keymap
21543 'help-echo
21544 (format "mouse-2 or RET jump to org file %s"
21545 (abbreviate-file-name buffer-file-name))))
21546 (regexp (concat
21547 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21548 (regexp-quote
21549 (substring
21550 (format-time-string
21551 (car org-time-stamp-formats)
21552 (apply 'encode-time ; DATE bound by calendar
21553 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21554 1 11))))
21555 marker hdmarker priority category tags closedp
21556 ee txt timestr)
21557 (goto-char (point-min))
21558 (while (re-search-forward regexp nil t)
21559 (catch :skip
21560 (org-agenda-skip)
21561 (setq marker (org-agenda-new-marker (match-beginning 0))
21562 closedp (equal (match-string 1) org-closed-string)
21563 category (org-get-category (match-beginning 0))
21564 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21565 ;; donep (org-entry-is-done-p)
21567 (if (string-match "\\]" timestr)
21568 ;; substring should only run to end of time stamp
21569 (setq timestr (substring timestr 0 (match-end 0))))
21570 (save-excursion
21571 (if (re-search-backward "^\\*+ " nil t)
21572 (progn
21573 (goto-char (match-beginning 0))
21574 (setq hdmarker (org-agenda-new-marker)
21575 tags (org-get-tags-at))
21576 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21577 (setq txt (org-format-agenda-item
21578 (if closedp "Closed: " "Clocked: ")
21579 (match-string 1) category tags timestr)))
21580 (setq txt org-agenda-no-heading-message))
21581 (setq priority 100000)
21582 (org-add-props txt props
21583 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21584 'priority priority 'org-category category
21585 'type "closed" 'date date
21586 'undone-face 'org-warning 'done-face 'org-done)
21587 (push txt ee))
21588 (goto-char (point-at-eol))))
21589 (nreverse ee)))
21591 (defun org-agenda-get-deadlines ()
21592 "Return the deadline information for agenda display."
21593 (let* ((props (list 'mouse-face 'highlight
21594 'org-not-done-regexp org-not-done-regexp
21595 'org-todo-regexp org-todo-regexp
21596 'keymap org-agenda-keymap
21597 'help-echo
21598 (format "mouse-2 or RET jump to org file %s"
21599 (abbreviate-file-name buffer-file-name))))
21600 (regexp org-deadline-time-regexp)
21601 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21602 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21603 d2 diff dfrac wdays pos pos1 category tags
21604 ee txt head face s upcomingp donep timestr)
21605 (goto-char (point-min))
21606 (while (re-search-forward regexp nil t)
21607 (catch :skip
21608 (org-agenda-skip)
21609 (setq s (match-string 1)
21610 pos (1- (match-beginning 1))
21611 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21612 diff (- d2 d1)
21613 wdays (org-get-wdays s)
21614 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21615 upcomingp (and todayp (> diff 0)))
21616 ;; When to show a deadline in the calendar:
21617 ;; If the expiration is within wdays warning time.
21618 ;; Past-due deadlines are only shown on the current date
21619 (if (or (and (<= diff wdays)
21620 (and todayp (not org-agenda-only-exact-dates)))
21621 (= diff 0))
21622 (save-excursion
21623 (setq category (org-get-category))
21624 (if (re-search-backward "^\\*+[ \t]+" nil t)
21625 (progn
21626 (goto-char (match-end 0))
21627 (setq pos1 (match-beginning 0))
21628 (setq tags (org-get-tags-at pos1))
21629 (setq head (buffer-substring-no-properties
21630 (point)
21631 (progn (skip-chars-forward "^\r\n")
21632 (point))))
21633 (setq donep (string-match org-looking-at-done-regexp head))
21634 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21635 (setq timestr
21636 (concat (substring s (match-beginning 1)) " "))
21637 (setq timestr 'time))
21638 (if (and donep
21639 (or org-agenda-skip-deadline-if-done
21640 (not (= diff 0))))
21641 (setq txt nil)
21642 (setq txt (org-format-agenda-item
21643 (if (= diff 0)
21644 (car org-agenda-deadline-leaders)
21645 (format (nth 1 org-agenda-deadline-leaders)
21646 diff))
21647 head category tags timestr))))
21648 (setq txt org-agenda-no-heading-message))
21649 (when txt
21650 (setq face (org-agenda-deadline-face dfrac))
21651 (org-add-props txt props
21652 'org-marker (org-agenda-new-marker pos)
21653 'org-hd-marker (org-agenda-new-marker pos1)
21654 'priority (+ (- diff)
21655 (org-get-priority txt))
21656 'org-category category
21657 'type (if upcomingp "upcoming-deadline" "deadline")
21658 'date (if upcomingp date d2)
21659 'face (if donep 'org-done face)
21660 'undone-face face 'done-face 'org-done)
21661 (push txt ee))))))
21662 (nreverse ee)))
21664 (defun org-agenda-deadline-face (fraction)
21665 "Return the face to displaying a deadline item.
21666 FRACTION is what fraction of the head-warning time has passed."
21667 (let ((faces org-agenda-deadline-faces) f)
21668 (catch 'exit
21669 (while (setq f (pop faces))
21670 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21672 (defun org-agenda-get-scheduled ()
21673 "Return the scheduled information for agenda display."
21674 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21675 'org-todo-regexp org-todo-regexp
21676 'done-face 'org-done
21677 'mouse-face 'highlight
21678 'keymap org-agenda-keymap
21679 'help-echo
21680 (format "mouse-2 or RET jump to org file %s"
21681 (abbreviate-file-name buffer-file-name))))
21682 (regexp org-scheduled-time-regexp)
21683 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21684 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21685 d2 diff pos pos1 category tags
21686 ee txt head pastschedp donep face timestr s)
21687 (goto-char (point-min))
21688 (while (re-search-forward regexp nil t)
21689 (catch :skip
21690 (org-agenda-skip)
21691 (setq s (match-string 1)
21692 pos (1- (match-beginning 1))
21693 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21694 ;;; is this right?
21695 ;;; do we need to do this for deadleine too????
21696 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21697 diff (- d2 d1))
21698 (setq pastschedp (and todayp (< diff 0)))
21699 ;; When to show a scheduled item in the calendar:
21700 ;; If it is on or past the date.
21701 (if (or (and (< diff 0)
21702 (and todayp (not org-agenda-only-exact-dates)))
21703 (= diff 0))
21704 (save-excursion
21705 (setq category (org-get-category))
21706 (if (re-search-backward "^\\*+[ \t]+" nil t)
21707 (progn
21708 (goto-char (match-end 0))
21709 (setq pos1 (match-beginning 0))
21710 (setq tags (org-get-tags-at))
21711 (setq head (buffer-substring-no-properties
21712 (point)
21713 (progn (skip-chars-forward "^\r\n") (point))))
21714 (setq donep (string-match org-looking-at-done-regexp head))
21715 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21716 (setq timestr
21717 (concat (substring s (match-beginning 1)) " "))
21718 (setq timestr 'time))
21719 (if (and donep
21720 (or org-agenda-skip-scheduled-if-done
21721 (not (= diff 0))))
21722 (setq txt nil)
21723 (setq txt (org-format-agenda-item
21724 (if (= diff 0)
21725 (car org-agenda-scheduled-leaders)
21726 (format (nth 1 org-agenda-scheduled-leaders)
21727 (- 1 diff)))
21728 head category tags timestr))))
21729 (setq txt org-agenda-no-heading-message))
21730 (when txt
21731 (setq face (if pastschedp
21732 'org-scheduled-previously
21733 'org-scheduled-today))
21734 (org-add-props txt props
21735 'undone-face face
21736 'face (if donep 'org-done face)
21737 'org-marker (org-agenda-new-marker pos)
21738 'org-hd-marker (org-agenda-new-marker pos1)
21739 'type (if pastschedp "past-scheduled" "scheduled")
21740 'date (if pastschedp d2 date)
21741 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21742 'org-category category)
21743 (push txt ee))))))
21744 (nreverse ee)))
21746 (defun org-agenda-get-blocks ()
21747 "Return the date-range information for agenda display."
21748 (let* ((props (list 'face nil
21749 'org-not-done-regexp org-not-done-regexp
21750 'org-todo-regexp org-todo-regexp
21751 'mouse-face 'highlight
21752 'keymap org-agenda-keymap
21753 'help-echo
21754 (format "mouse-2 or RET jump to org file %s"
21755 (abbreviate-file-name buffer-file-name))))
21756 (regexp org-tr-regexp)
21757 (d0 (calendar-absolute-from-gregorian date))
21758 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21759 donep head)
21760 (goto-char (point-min))
21761 (while (re-search-forward regexp nil t)
21762 (catch :skip
21763 (org-agenda-skip)
21764 (setq pos (point))
21765 (setq timestr (match-string 0)
21766 s1 (match-string 1)
21767 s2 (match-string 2)
21768 d1 (time-to-days (org-time-string-to-time s1))
21769 d2 (time-to-days (org-time-string-to-time s2)))
21770 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21771 ;; Only allow days between the limits, because the normal
21772 ;; date stamps will catch the limits.
21773 (save-excursion
21774 (setq marker (org-agenda-new-marker (point)))
21775 (setq category (org-get-category))
21776 (if (re-search-backward "^\\*+ " nil t)
21777 (progn
21778 (goto-char (match-beginning 0))
21779 (setq hdmarker (org-agenda-new-marker (point)))
21780 (setq tags (org-get-tags-at))
21781 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21782 (setq head (match-string 1))
21783 (and org-agenda-skip-timestamp-if-done
21784 (org-entry-is-done-p)
21785 (throw :skip t))
21786 (setq txt (org-format-agenda-item
21787 (format (if (= d1 d2) "" "(%d/%d): ")
21788 (1+ (- d0 d1)) (1+ (- d2 d1)))
21789 head category tags
21790 (if (= d0 d1) timestr))))
21791 (setq txt org-agenda-no-heading-message))
21792 (org-add-props txt props
21793 'org-marker marker 'org-hd-marker hdmarker
21794 'type "block" 'date date
21795 'priority (org-get-priority txt) 'org-category category)
21796 (push txt ee)))
21797 (goto-char pos)))
21798 ;; Sort the entries by expiration date.
21799 (nreverse ee)))
21801 ;;; Agenda presentation and sorting
21803 (defconst org-plain-time-of-day-regexp
21804 (concat
21805 "\\(\\<[012]?[0-9]"
21806 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21807 "\\(--?"
21808 "\\(\\<[012]?[0-9]"
21809 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21810 "\\)?")
21811 "Regular expression to match a plain time or time range.
21812 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21813 groups carry important information:
21814 0 the full match
21815 1 the first time, range or not
21816 8 the second time, if it is a range.")
21818 (defconst org-plain-time-extension-regexp
21819 (concat
21820 "\\(\\<[012]?[0-9]"
21821 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21822 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21823 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21824 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21825 groups carry important information:
21826 0 the full match
21827 7 hours of duration
21828 9 minutes of duration")
21830 (defconst org-stamp-time-of-day-regexp
21831 (concat
21832 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21833 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21834 "\\(--?"
21835 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21836 "Regular expression to match a timestamp time or time range.
21837 After a match, the following groups carry important information:
21838 0 the full match
21839 1 date plus weekday, for backreferencing to make sure both times on same day
21840 2 the first time, range or not
21841 4 the second time, if it is a range.")
21843 (defvar org-prefix-has-time nil
21844 "A flag, set by `org-compile-prefix-format'.
21845 The flag is set if the currently compiled format contains a `%t'.")
21846 (defvar org-prefix-has-tag nil
21847 "A flag, set by `org-compile-prefix-format'.
21848 The flag is set if the currently compiled format contains a `%T'.")
21850 (defun org-format-agenda-item (extra txt &optional category tags dotime
21851 noprefix remove-re)
21852 "Format TXT to be inserted into the agenda buffer.
21853 In particular, it adds the prefix and corresponding text properties. EXTRA
21854 must be a string and replaces the `%s' specifier in the prefix format.
21855 CATEGORY (string, symbol or nil) may be used to overrule the default
21856 category taken from local variable or file name. It will replace the `%c'
21857 specifier in the format. DOTIME, when non-nil, indicates that a
21858 time-of-day should be extracted from TXT for sorting of this entry, and for
21859 the `%t' specifier in the format. When DOTIME is a string, this string is
21860 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21861 only the correctly processes TXT should be returned - this is used by
21862 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21863 Any match of REMOVE-RE will be removed from TXT."
21864 (save-match-data
21865 ;; Diary entries sometimes have extra whitespace at the beginning
21866 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21867 (let* ((category (or category
21868 org-category
21869 (if buffer-file-name
21870 (file-name-sans-extension
21871 (file-name-nondirectory buffer-file-name))
21872 "")))
21873 (tag (if tags (nth (1- (length tags)) tags) ""))
21874 time ; time and tag are needed for the eval of the prefix format
21875 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21876 (time-of-day (and dotime (org-get-time-of-day ts)))
21877 stamp plain s0 s1 s2 rtn srp)
21878 (when (and dotime time-of-day org-prefix-has-time)
21879 ;; Extract starting and ending time and move them to prefix
21880 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21881 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21882 (setq s0 (match-string 0 ts)
21883 srp (and stamp (match-end 3))
21884 s1 (match-string (if plain 1 2) ts)
21885 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21887 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21888 ;; them, we might want to remove them there to avoid duplication.
21889 ;; The user can turn this off with a variable.
21890 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21891 (string-match (concat (regexp-quote s0) " *") txt)
21892 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21893 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21894 (= (match-beginning 0) 0)
21896 (setq txt (replace-match "" nil nil txt))))
21897 ;; Normalize the time(s) to 24 hour
21898 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21899 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21901 (when (and s1 (not s2) org-agenda-default-appointment-duration
21902 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21903 (let ((m (+ (string-to-number (match-string 2 s1))
21904 (* 60 (string-to-number (match-string 1 s1)))
21905 org-agenda-default-appointment-duration))
21907 (setq h (/ m 60) m (- m (* h 60)))
21908 (setq s2 (format "%02d:%02d" h m))))
21910 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21911 txt)
21912 ;; Tags are in the string
21913 (if (or (eq org-agenda-remove-tags t)
21914 (and org-agenda-remove-tags
21915 org-prefix-has-tag))
21916 (setq txt (replace-match "" t t txt))
21917 (setq txt (replace-match
21918 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21919 (match-string 2 txt))
21920 t t txt))))
21922 (when remove-re
21923 (while (string-match remove-re txt)
21924 (setq txt (replace-match "" t t txt))))
21926 ;; Create the final string
21927 (if noprefix
21928 (setq rtn txt)
21929 ;; Prepare the variables needed in the eval of the compiled format
21930 (setq time (cond (s2 (concat s1 "-" s2))
21931 (s1 (concat s1 "......"))
21932 (t ""))
21933 extra (or extra "")
21934 category (if (symbolp category) (symbol-name category) category))
21935 ;; Evaluate the compiled format
21936 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21938 ;; And finally add the text properties
21939 (org-add-props rtn nil
21940 'org-category (downcase category) 'tags tags
21941 'org-highest-priority org-highest-priority
21942 'org-lowest-priority org-lowest-priority
21943 'prefix-length (- (length rtn) (length txt))
21944 'time-of-day time-of-day
21945 'txt txt
21946 'time time
21947 'extra extra
21948 'dotime dotime))))
21950 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21951 (defvar org-agenda-sorting-strategy-selected nil)
21953 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21954 (catch 'exit
21955 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21956 ((and todayp (member 'today (car org-agenda-time-grid))))
21957 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21958 ((member 'weekly (car org-agenda-time-grid)))
21959 (t (throw 'exit list)))
21960 (let* ((have (delq nil (mapcar
21961 (lambda (x) (get-text-property 1 'time-of-day x))
21962 list)))
21963 (string (nth 1 org-agenda-time-grid))
21964 (gridtimes (nth 2 org-agenda-time-grid))
21965 (req (car org-agenda-time-grid))
21966 (remove (member 'remove-match req))
21967 new time)
21968 (if (and (member 'require-timed req) (not have))
21969 ;; don't show empty grid
21970 (throw 'exit list))
21971 (while (setq time (pop gridtimes))
21972 (unless (and remove (member time have))
21973 (setq time (int-to-string time))
21974 (push (org-format-agenda-item
21975 nil string "" nil
21976 (concat (substring time 0 -2) ":" (substring time -2)))
21977 new)
21978 (put-text-property
21979 1 (length (car new)) 'face 'org-time-grid (car new))))
21980 (if (member 'time-up org-agenda-sorting-strategy-selected)
21981 (append new list)
21982 (append list new)))))
21984 (defun org-compile-prefix-format (key)
21985 "Compile the prefix format into a Lisp form that can be evaluated.
21986 The resulting form is returned and stored in the variable
21987 `org-prefix-format-compiled'."
21988 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21989 (let ((s (cond
21990 ((stringp org-agenda-prefix-format)
21991 org-agenda-prefix-format)
21992 ((assq key org-agenda-prefix-format)
21993 (cdr (assq key org-agenda-prefix-format)))
21994 (t " %-12:c%?-12t% s")))
21995 (start 0)
21996 varform vars var e c f opt)
21997 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21998 s start)
21999 (setq var (cdr (assoc (match-string 4 s)
22000 '(("c" . category) ("t" . time) ("s" . extra)
22001 ("T" . tag))))
22002 c (or (match-string 3 s) "")
22003 opt (match-beginning 1)
22004 start (1+ (match-beginning 0)))
22005 (if (equal var 'time) (setq org-prefix-has-time t))
22006 (if (equal var 'tag) (setq org-prefix-has-tag t))
22007 (setq f (concat "%" (match-string 2 s) "s"))
22008 (if opt
22009 (setq varform
22010 `(if (equal "" ,var)
22012 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22013 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22014 (setq s (replace-match "%s" t nil s))
22015 (push varform vars))
22016 (setq vars (nreverse vars))
22017 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22019 (defun org-set-sorting-strategy (key)
22020 (if (symbolp (car org-agenda-sorting-strategy))
22021 ;; the old format
22022 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22023 (setq org-agenda-sorting-strategy-selected
22024 (or (cdr (assq key org-agenda-sorting-strategy))
22025 (cdr (assq 'agenda org-agenda-sorting-strategy))
22026 '(time-up category-keep priority-down)))))
22028 (defun org-get-time-of-day (s &optional string mod24)
22029 "Check string S for a time of day.
22030 If found, return it as a military time number between 0 and 2400.
22031 If not found, return nil.
22032 The optional STRING argument forces conversion into a 5 character wide string
22033 HH:MM."
22034 (save-match-data
22035 (when
22036 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22037 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22038 (let* ((h (string-to-number (match-string 1 s)))
22039 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22040 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22041 (am-p (equal ampm "am"))
22042 (h1 (cond ((not ampm) h)
22043 ((= h 12) (if am-p 0 12))
22044 (t (+ h (if am-p 0 12)))))
22045 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22046 (mod h1 24) h1))
22047 (t0 (+ (* 100 h2) m))
22048 (t1 (concat (if (>= h1 24) "+" " ")
22049 (if (< t0 100) "0" "")
22050 (if (< t0 10) "0" "")
22051 (int-to-string t0))))
22052 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22054 (defun org-finalize-agenda-entries (list &optional nosort)
22055 "Sort and concatenate the agenda items."
22056 (setq list (mapcar 'org-agenda-highlight-todo list))
22057 (if nosort
22058 list
22059 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22061 (defun org-agenda-highlight-todo (x)
22062 (let (re pl)
22063 (if (eq x 'line)
22064 (save-excursion
22065 (beginning-of-line 1)
22066 (setq re (get-text-property (point) 'org-todo-regexp))
22067 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22068 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22069 (add-text-properties (match-beginning 0) (match-end 0)
22070 (list 'face (org-get-todo-face 0)))
22071 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22072 (delete-region (match-beginning 1) (1- (match-end 0)))
22073 (goto-char (match-beginning 1))
22074 (insert (format org-agenda-todo-keyword-format s)))))
22075 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22076 pl (get-text-property 0 'prefix-length x))
22077 (when (and re
22078 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22079 x (or pl 0)) pl))
22080 (add-text-properties
22081 (or (match-end 1) (match-end 0)) (match-end 0)
22082 (list 'face (org-get-todo-face (match-string 2 x)))
22084 (setq x (concat (substring x 0 (match-end 1))
22085 (format org-agenda-todo-keyword-format
22086 (match-string 2 x))
22088 (substring x (match-end 3)))))
22089 x)))
22091 (defsubst org-cmp-priority (a b)
22092 "Compare the priorities of string A and B."
22093 (let ((pa (or (get-text-property 1 'priority a) 0))
22094 (pb (or (get-text-property 1 'priority b) 0)))
22095 (cond ((> pa pb) +1)
22096 ((< pa pb) -1)
22097 (t nil))))
22099 (defsubst org-cmp-category (a b)
22100 "Compare the string values of categories of strings A and B."
22101 (let ((ca (or (get-text-property 1 'org-category a) ""))
22102 (cb (or (get-text-property 1 'org-category b) "")))
22103 (cond ((string-lessp ca cb) -1)
22104 ((string-lessp cb ca) +1)
22105 (t nil))))
22107 (defsubst org-cmp-tag (a b)
22108 "Compare the string values of categories of strings A and B."
22109 (let ((ta (car (last (get-text-property 1 'tags a))))
22110 (tb (car (last (get-text-property 1 'tags b)))))
22111 (cond ((not ta) +1)
22112 ((not tb) -1)
22113 ((string-lessp ta tb) -1)
22114 ((string-lessp tb ta) +1)
22115 (t nil))))
22117 (defsubst org-cmp-time (a b)
22118 "Compare the time-of-day values of strings A and B."
22119 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22120 (ta (or (get-text-property 1 'time-of-day a) def))
22121 (tb (or (get-text-property 1 'time-of-day b) def)))
22122 (cond ((< ta tb) -1)
22123 ((< tb ta) +1)
22124 (t nil))))
22126 (defun org-entries-lessp (a b)
22127 "Predicate for sorting agenda entries."
22128 ;; The following variables will be used when the form is evaluated.
22129 ;; So even though the compiler complains, keep them.
22130 (let* ((time-up (org-cmp-time a b))
22131 (time-down (if time-up (- time-up) nil))
22132 (priority-up (org-cmp-priority a b))
22133 (priority-down (if priority-up (- priority-up) nil))
22134 (category-up (org-cmp-category a b))
22135 (category-down (if category-up (- category-up) nil))
22136 (category-keep (if category-up +1 nil))
22137 (tag-up (org-cmp-tag a b))
22138 (tag-down (if tag-up (- tag-up) nil)))
22139 (cdr (assoc
22140 (eval (cons 'or org-agenda-sorting-strategy-selected))
22141 '((-1 . t) (1 . nil) (nil . nil))))))
22143 ;;; Agenda restriction lock
22145 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22146 "Overlay to mark the headline to which arenda commands are restricted.")
22147 (org-overlay-put org-agenda-restriction-lock-overlay
22148 'face 'org-agenda-restriction-lock)
22149 (org-overlay-put org-agenda-restriction-lock-overlay
22150 'help-echo "Agendas are currently limited to this subtree.")
22151 (org-detach-overlay org-agenda-restriction-lock-overlay)
22152 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22153 "Overlay marking the agenda restriction line in speedbar.")
22154 (org-overlay-put org-speedbar-restriction-lock-overlay
22155 'face 'org-agenda-restriction-lock)
22156 (org-overlay-put org-speedbar-restriction-lock-overlay
22157 'help-echo "Agendas are currently limited to this item.")
22158 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22160 (defun org-agenda-set-restriction-lock (&optional type)
22161 "Set restriction lock for agenda, to current subtree or file.
22162 Restriction will be the file if TYPE is `file', or if type is the
22163 universal prefix '(4), or if the cursor is before the first headline
22164 in the file. Otherwise, restriction will be to the current subtree."
22165 (interactive "P")
22166 (and (equal type '(4)) (setq type 'file))
22167 (setq type (cond
22168 (type type)
22169 ((org-at-heading-p) 'subtree)
22170 ((condition-case nil (org-back-to-heading t) (error nil))
22171 'subtree)
22172 (t 'file)))
22173 (if (eq type 'subtree)
22174 (progn
22175 (setq org-agenda-restrict t)
22176 (setq org-agenda-overriding-restriction 'subtree)
22177 (put 'org-agenda-files 'org-restrict
22178 (list (buffer-file-name (buffer-base-buffer))))
22179 (org-back-to-heading t)
22180 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22181 (move-marker org-agenda-restrict-begin (point))
22182 (move-marker org-agenda-restrict-end
22183 (save-excursion (org-end-of-subtree t)))
22184 (message "Locking agenda restriction to subtree"))
22185 (put 'org-agenda-files 'org-restrict
22186 (list (buffer-file-name (buffer-base-buffer))))
22187 (setq org-agenda-restrict nil)
22188 (setq org-agenda-overriding-restriction 'file)
22189 (move-marker org-agenda-restrict-begin nil)
22190 (move-marker org-agenda-restrict-end nil)
22191 (message "Locking agenda restriction to file"))
22192 (setq current-prefix-arg nil)
22193 (org-agenda-maybe-redo))
22195 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22196 "Remove the agenda restriction lock."
22197 (interactive "P")
22198 (org-detach-overlay org-agenda-restriction-lock-overlay)
22199 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22200 (setq org-agenda-overriding-restriction nil)
22201 (setq org-agenda-restrict nil)
22202 (put 'org-agenda-files 'org-restrict nil)
22203 (move-marker org-agenda-restrict-begin nil)
22204 (move-marker org-agenda-restrict-end nil)
22205 (setq current-prefix-arg nil)
22206 (message "Agenda restriction lock removed")
22207 (or noupdate (org-agenda-maybe-redo)))
22209 (defun org-agenda-maybe-redo ()
22210 "If there is any window showing the agenda view, update it."
22211 (let ((w (get-buffer-window org-agenda-buffer-name t))
22212 (w0 (selected-window)))
22213 (when w
22214 (select-window w)
22215 (org-agenda-redo)
22216 (select-window w0)
22217 (if org-agenda-overriding-restriction
22218 (message "Agenda view shifted to new %s restriction"
22219 org-agenda-overriding-restriction)
22220 (message "Agenda restriction lock removed")))))
22222 ;;; Agenda commands
22224 (defun org-agenda-check-type (error &rest types)
22225 "Check if agenda buffer is of allowed type.
22226 If ERROR is non-nil, throw an error, otherwise just return nil."
22227 (if (memq org-agenda-type types)
22229 (if error
22230 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22231 nil)))
22233 (defun org-agenda-quit ()
22234 "Exit agenda by removing the window or the buffer."
22235 (interactive)
22236 (let ((buf (current-buffer)))
22237 (if (not (one-window-p)) (delete-window))
22238 (kill-buffer buf)
22239 (org-agenda-reset-markers)
22240 (org-columns-remove-overlays))
22241 ;; Maybe restore the pre-agenda window configuration.
22242 (and org-agenda-restore-windows-after-quit
22243 (not (eq org-agenda-window-setup 'other-frame))
22244 org-pre-agenda-window-conf
22245 (set-window-configuration org-pre-agenda-window-conf)))
22247 (defun org-agenda-exit ()
22248 "Exit agenda by removing the window or the buffer.
22249 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22250 Org-mode buffers visited directly by the user will not be touched."
22251 (interactive)
22252 (org-release-buffers org-agenda-new-buffers)
22253 (setq org-agenda-new-buffers nil)
22254 (org-agenda-quit))
22256 (defun org-agenda-execute (arg)
22257 "Execute another agenda command, keeping same window.\\<global-map>
22258 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22259 (interactive "P")
22260 (let ((org-agenda-window-setup 'current-window))
22261 (org-agenda arg)))
22263 (defun org-save-all-org-buffers ()
22264 "Save all Org-mode buffers without user confirmation."
22265 (interactive)
22266 (message "Saving all Org-mode buffers...")
22267 (save-some-buffers t 'org-mode-p)
22268 (message "Saving all Org-mode buffers... done"))
22270 (defun org-agenda-redo ()
22271 "Rebuild Agenda.
22272 When this is the global TODO list, a prefix argument will be interpreted."
22273 (interactive)
22274 (let* ((org-agenda-keep-modes t)
22275 (line (org-current-line))
22276 (window-line (- line (org-current-line (window-start))))
22277 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22278 (message "Rebuilding agenda buffer...")
22279 (org-let lprops '(eval org-agenda-redo-command))
22280 (setq org-agenda-undo-list nil
22281 org-agenda-pending-undo-list nil)
22282 (message "Rebuilding agenda buffer...done")
22283 (goto-line line)
22284 (recenter window-line)))
22286 (defun org-agenda-goto-date (date)
22287 "Jump to DATE in agenda."
22288 (interactive (list (org-read-date)))
22289 (org-agenda-list nil date))
22291 (defun org-agenda-goto-today ()
22292 "Go to today."
22293 (interactive)
22294 (org-agenda-check-type t 'timeline 'agenda)
22295 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22296 (cond
22297 (tdpos (goto-char tdpos))
22298 ((eq org-agenda-type 'agenda)
22299 (let* ((sd (time-to-days
22300 (time-subtract (current-time)
22301 (list 0 (* 3600 org-extend-today-until) 0))))
22302 (comp (org-agenda-compute-time-span sd org-agenda-span))
22303 (org-agenda-overriding-arguments org-agenda-last-arguments))
22304 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22305 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22306 (org-agenda-redo)
22307 (org-agenda-find-same-or-today-or-agenda)))
22308 (t (error "Cannot find today")))))
22310 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22311 (goto-char
22312 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22313 (text-property-any (point-min) (point-max) 'org-today t)
22314 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22315 (point-min))))
22317 (defun org-agenda-later (arg)
22318 "Go forward in time by thee current span.
22319 With prefix ARG, go forward that many times the current span."
22320 (interactive "p")
22321 (org-agenda-check-type t 'agenda)
22322 (let* ((span org-agenda-span)
22323 (sd org-starting-day)
22324 (greg (calendar-gregorian-from-absolute sd))
22325 (cnt (get-text-property (point) 'org-day-cnt))
22326 greg2 nd)
22327 (cond
22328 ((eq span 'day)
22329 (setq sd (+ arg sd) nd 1))
22330 ((eq span 'week)
22331 (setq sd (+ (* 7 arg) sd) nd 7))
22332 ((eq span 'month)
22333 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22334 sd (calendar-absolute-from-gregorian greg2))
22335 (setcar greg2 (1+ (car greg2)))
22336 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22337 ((eq span 'year)
22338 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22339 sd (calendar-absolute-from-gregorian greg2))
22340 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22341 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22342 (let ((org-agenda-overriding-arguments
22343 (list (car org-agenda-last-arguments) sd nd t)))
22344 (org-agenda-redo)
22345 (org-agenda-find-same-or-today-or-agenda cnt))))
22347 (defun org-agenda-earlier (arg)
22348 "Go backward in time by the current span.
22349 With prefix ARG, go backward that many times the current span."
22350 (interactive "p")
22351 (org-agenda-later (- arg)))
22353 (defun org-agenda-day-view ()
22354 "Switch to daily view for agenda."
22355 (interactive)
22356 (setq org-agenda-ndays 1)
22357 (org-agenda-change-time-span 'day))
22358 (defun org-agenda-week-view ()
22359 "Switch to daily view for agenda."
22360 (interactive)
22361 (setq org-agenda-ndays 7)
22362 (org-agenda-change-time-span 'week))
22363 (defun org-agenda-month-view ()
22364 "Switch to daily view for agenda."
22365 (interactive)
22366 (org-agenda-change-time-span 'month))
22367 (defun org-agenda-year-view ()
22368 "Switch to daily view for agenda."
22369 (interactive)
22370 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22371 (org-agenda-change-time-span 'year)
22372 (error "Abort")))
22374 (defun org-agenda-change-time-span (span)
22375 "Change the agenda view to SPAN.
22376 SPAN may be `day', `week', `month', `year'."
22377 (org-agenda-check-type t 'agenda)
22378 (if (equal org-agenda-span span)
22379 (error "Viewing span is already \"%s\"" span))
22380 (let* ((sd (or (get-text-property (point) 'day)
22381 org-starting-day))
22382 (computed (org-agenda-compute-time-span sd span))
22383 (org-agenda-overriding-arguments
22384 (list (car org-agenda-last-arguments)
22385 (car computed) (cdr computed) t)))
22386 (org-agenda-redo)
22387 (org-agenda-find-same-or-today-or-agenda))
22388 (org-agenda-set-mode-name)
22389 (message "Switched to %s view" span))
22391 (defun org-agenda-compute-time-span (sd span)
22392 "Compute starting date and number of days for agenda.
22393 SPAN may be `day', `week', `month', `year'. The return value
22394 is a cons cell with the starting date and the number of days,
22395 so that the date SD will be in that range."
22396 (let* ((greg (calendar-gregorian-from-absolute sd))
22398 (cond
22399 ((eq span 'day)
22400 (setq nd 1))
22401 ((eq span 'week)
22402 (let* ((nt (calendar-day-of-week
22403 (calendar-gregorian-from-absolute sd)))
22404 (d (if org-agenda-start-on-weekday
22405 (- nt org-agenda-start-on-weekday)
22406 0)))
22407 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22408 (setq nd 7)))
22409 ((eq span 'month)
22410 (setq sd (calendar-absolute-from-gregorian
22411 (list (car greg) 1 (nth 2 greg)))
22412 nd (- (calendar-absolute-from-gregorian
22413 (list (1+ (car greg)) 1 (nth 2 greg)))
22414 sd)))
22415 ((eq span 'year)
22416 (setq sd (calendar-absolute-from-gregorian
22417 (list 1 1 (nth 2 greg)))
22418 nd (- (calendar-absolute-from-gregorian
22419 (list 1 1 (1+ (nth 2 greg))))
22420 sd))))
22421 (cons sd nd)))
22423 ;; FIXME: does not work if user makes date format that starts with a blank
22424 (defun org-agenda-next-date-line (&optional arg)
22425 "Jump to the next line indicating a date in agenda buffer."
22426 (interactive "p")
22427 (org-agenda-check-type t 'agenda 'timeline)
22428 (beginning-of-line 1)
22429 (if (looking-at "^\\S-") (forward-char 1))
22430 (if (not (re-search-forward "^\\S-" nil t arg))
22431 (progn
22432 (backward-char 1)
22433 (error "No next date after this line in this buffer")))
22434 (goto-char (match-beginning 0)))
22436 (defun org-agenda-previous-date-line (&optional arg)
22437 "Jump to the previous line indicating a date in agenda buffer."
22438 (interactive "p")
22439 (org-agenda-check-type t 'agenda 'timeline)
22440 (beginning-of-line 1)
22441 (if (not (re-search-backward "^\\S-" nil t arg))
22442 (error "No previous date before this line in this buffer")))
22444 ;; Initialize the highlight
22445 (defvar org-hl (org-make-overlay 1 1))
22446 (org-overlay-put org-hl 'face 'highlight)
22448 (defun org-highlight (begin end &optional buffer)
22449 "Highlight a region with overlay."
22450 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22451 org-hl begin end (or buffer (current-buffer))))
22453 (defun org-unhighlight ()
22454 "Detach overlay INDEX."
22455 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22457 ;; FIXME this is currently not used.
22458 (defun org-highlight-until-next-command (beg end &optional buffer)
22459 (org-highlight beg end buffer)
22460 (add-hook 'pre-command-hook 'org-unhighlight-once))
22461 (defun org-unhighlight-once ()
22462 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22463 (org-unhighlight))
22465 (defun org-agenda-follow-mode ()
22466 "Toggle follow mode in an agenda buffer."
22467 (interactive)
22468 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22469 (org-agenda-set-mode-name)
22470 (message "Follow mode is %s"
22471 (if org-agenda-follow-mode "on" "off")))
22473 (defun org-agenda-log-mode ()
22474 "Toggle log mode in an agenda buffer."
22475 (interactive)
22476 (org-agenda-check-type t 'agenda 'timeline)
22477 (setq org-agenda-show-log (not org-agenda-show-log))
22478 (org-agenda-set-mode-name)
22479 (org-agenda-redo)
22480 (message "Log mode is %s"
22481 (if org-agenda-show-log "on" "off")))
22483 (defun org-agenda-toggle-diary ()
22484 "Toggle diary inclusion in an agenda buffer."
22485 (interactive)
22486 (org-agenda-check-type t 'agenda)
22487 (setq org-agenda-include-diary (not org-agenda-include-diary))
22488 (org-agenda-redo)
22489 (org-agenda-set-mode-name)
22490 (message "Diary inclusion turned %s"
22491 (if org-agenda-include-diary "on" "off")))
22493 (defun org-agenda-toggle-time-grid ()
22494 "Toggle time grid in an agenda buffer."
22495 (interactive)
22496 (org-agenda-check-type t 'agenda)
22497 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22498 (org-agenda-redo)
22499 (org-agenda-set-mode-name)
22500 (message "Time-grid turned %s"
22501 (if org-agenda-use-time-grid "on" "off")))
22503 (defun org-agenda-set-mode-name ()
22504 "Set the mode name to indicate all the small mode settings."
22505 (setq mode-name
22506 (concat "Org-Agenda"
22507 (if (equal org-agenda-ndays 1) " Day" "")
22508 (if (equal org-agenda-ndays 7) " Week" "")
22509 (if org-agenda-follow-mode " Follow" "")
22510 (if org-agenda-include-diary " Diary" "")
22511 (if org-agenda-use-time-grid " Grid" "")
22512 (if org-agenda-show-log " Log" "")))
22513 (force-mode-line-update))
22515 (defun org-agenda-post-command-hook ()
22516 (and (eolp) (not (bolp)) (backward-char 1))
22517 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22518 (if (and org-agenda-follow-mode
22519 (get-text-property (point) 'org-marker))
22520 (org-agenda-show)))
22522 (defun org-agenda-show-priority ()
22523 "Show the priority of the current item.
22524 This priority is composed of the main priority given with the [#A] cookies,
22525 and by additional input from the age of a schedules or deadline entry."
22526 (interactive)
22527 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22528 (message "Priority is %d" (if pri pri -1000))))
22530 (defun org-agenda-show-tags ()
22531 "Show the tags applicable to the current item."
22532 (interactive)
22533 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22534 (if tags
22535 (message "Tags are :%s:"
22536 (org-no-properties (mapconcat 'identity tags ":")))
22537 (message "No tags associated with this line"))))
22539 (defun org-agenda-goto (&optional highlight)
22540 "Go to the Org-mode file which contains the item at point."
22541 (interactive)
22542 (let* ((marker (or (get-text-property (point) 'org-marker)
22543 (org-agenda-error)))
22544 (buffer (marker-buffer marker))
22545 (pos (marker-position marker)))
22546 (switch-to-buffer-other-window buffer)
22547 (widen)
22548 (goto-char pos)
22549 (when (org-mode-p)
22550 (org-show-context 'agenda)
22551 (save-excursion
22552 (and (outline-next-heading)
22553 (org-flag-heading nil)))) ; show the next heading
22554 (recenter (/ (window-height) 2))
22555 (run-hooks 'org-agenda-after-show-hook)
22556 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22558 (defvar org-agenda-after-show-hook nil
22559 "Normal hook run after an item has been shown from the agenda.
22560 Point is in the buffer where the item originated.")
22562 (defun org-agenda-kill ()
22563 "Kill the entry or subtree belonging to the current agenda entry."
22564 (interactive)
22565 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22566 (let* ((marker (or (get-text-property (point) 'org-marker)
22567 (org-agenda-error)))
22568 (buffer (marker-buffer marker))
22569 (pos (marker-position marker))
22570 (type (get-text-property (point) 'type))
22571 dbeg dend (n 0) conf)
22572 (org-with-remote-undo buffer
22573 (with-current-buffer buffer
22574 (save-excursion
22575 (goto-char pos)
22576 (if (and (org-mode-p) (not (member type '("sexp"))))
22577 (setq dbeg (progn (org-back-to-heading t) (point))
22578 dend (org-end-of-subtree t t))
22579 (setq dbeg (point-at-bol)
22580 dend (min (point-max) (1+ (point-at-eol)))))
22581 (goto-char dbeg)
22582 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22583 (setq conf (or (eq t org-agenda-confirm-kill)
22584 (and (numberp org-agenda-confirm-kill)
22585 (> n org-agenda-confirm-kill))))
22586 (and conf
22587 (not (y-or-n-p
22588 (format "Delete entry with %d lines in buffer \"%s\"? "
22589 n (buffer-name buffer))))
22590 (error "Abort"))
22591 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22592 (with-current-buffer buffer (delete-region dbeg dend))
22593 (message "Agenda item and source killed"))))
22595 (defun org-agenda-archive ()
22596 "Kill the entry or subtree belonging to the current agenda entry."
22597 (interactive)
22598 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22599 (let* ((marker (or (get-text-property (point) 'org-marker)
22600 (org-agenda-error)))
22601 (buffer (marker-buffer marker))
22602 (pos (marker-position marker)))
22603 (org-with-remote-undo buffer
22604 (with-current-buffer buffer
22605 (if (org-mode-p)
22606 (save-excursion
22607 (goto-char pos)
22608 (org-remove-subtree-entries-from-agenda)
22609 (org-back-to-heading t)
22610 (org-archive-subtree))
22611 (error "Archiving works only in Org-mode files"))))))
22613 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22614 "Remove all lines in the agenda that correspond to a given subtree.
22615 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22616 If this information is not given, the function uses the tree at point."
22617 (let ((buf (or buf (current-buffer))) m p)
22618 (save-excursion
22619 (unless (and beg end)
22620 (org-back-to-heading t)
22621 (setq beg (point))
22622 (org-end-of-subtree t)
22623 (setq end (point)))
22624 (set-buffer (get-buffer org-agenda-buffer-name))
22625 (save-excursion
22626 (goto-char (point-max))
22627 (beginning-of-line 1)
22628 (while (not (bobp))
22629 (when (and (setq m (get-text-property (point) 'org-marker))
22630 (equal buf (marker-buffer m))
22631 (setq p (marker-position m))
22632 (>= p beg)
22633 (<= p end))
22634 (let ((inhibit-read-only t))
22635 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22636 (beginning-of-line 0))))))
22638 (defun org-agenda-open-link ()
22639 "Follow the link in the current line, if any."
22640 (interactive)
22641 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22642 (save-excursion
22643 (save-restriction
22644 (narrow-to-region (point-at-bol) (point-at-eol))
22645 (org-open-at-point))))
22647 (defun org-agenda-copy-local-variable (var)
22648 "Get a variable from a referenced buffer and install it here."
22649 (let ((m (get-text-property (point) 'org-marker)))
22650 (when (and m (buffer-live-p (marker-buffer m)))
22651 (org-set-local var (with-current-buffer (marker-buffer m)
22652 (symbol-value var))))))
22654 (defun org-agenda-switch-to (&optional delete-other-windows)
22655 "Go to the Org-mode file which contains the item at point."
22656 (interactive)
22657 (let* ((marker (or (get-text-property (point) 'org-marker)
22658 (org-agenda-error)))
22659 (buffer (marker-buffer marker))
22660 (pos (marker-position marker)))
22661 (switch-to-buffer buffer)
22662 (and delete-other-windows (delete-other-windows))
22663 (widen)
22664 (goto-char pos)
22665 (when (org-mode-p)
22666 (org-show-context 'agenda)
22667 (save-excursion
22668 (and (outline-next-heading)
22669 (org-flag-heading nil)))))) ; show the next heading
22671 (defun org-agenda-goto-mouse (ev)
22672 "Go to the Org-mode file which contains the item at the mouse click."
22673 (interactive "e")
22674 (mouse-set-point ev)
22675 (org-agenda-goto))
22677 (defun org-agenda-show ()
22678 "Display the Org-mode file which contains the item at point."
22679 (interactive)
22680 (let ((win (selected-window)))
22681 (org-agenda-goto t)
22682 (select-window win)))
22684 (defun org-agenda-recenter (arg)
22685 "Display the Org-mode file which contains the item at point and recenter."
22686 (interactive "P")
22687 (let ((win (selected-window)))
22688 (org-agenda-goto t)
22689 (recenter arg)
22690 (select-window win)))
22692 (defun org-agenda-show-mouse (ev)
22693 "Display the Org-mode file which contains the item at the mouse click."
22694 (interactive "e")
22695 (mouse-set-point ev)
22696 (org-agenda-show))
22698 (defun org-agenda-check-no-diary ()
22699 "Check if the entry is a diary link and abort if yes."
22700 (if (get-text-property (point) 'org-agenda-diary-link)
22701 (org-agenda-error)))
22703 (defun org-agenda-error ()
22704 (error "Command not allowed in this line"))
22706 (defun org-agenda-tree-to-indirect-buffer ()
22707 "Show the subtree corresponding to the current entry in an indirect buffer.
22708 This calls the command `org-tree-to-indirect-buffer' from the original
22709 Org-mode buffer.
22710 With numerical prefix arg ARG, go up to this level and then take that tree.
22711 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22712 dedicated frame)."
22713 (interactive)
22714 (org-agenda-check-no-diary)
22715 (let* ((marker (or (get-text-property (point) 'org-marker)
22716 (org-agenda-error)))
22717 (buffer (marker-buffer marker))
22718 (pos (marker-position marker)))
22719 (with-current-buffer buffer
22720 (save-excursion
22721 (goto-char pos)
22722 (call-interactively 'org-tree-to-indirect-buffer)))))
22724 (defvar org-last-heading-marker (make-marker)
22725 "Marker pointing to the headline that last changed its TODO state
22726 by a remote command from the agenda.")
22728 (defun org-agenda-todo-nextset ()
22729 "Switch TODO entry to next sequence."
22730 (interactive)
22731 (org-agenda-todo 'nextset))
22733 (defun org-agenda-todo-previousset ()
22734 "Switch TODO entry to previous sequence."
22735 (interactive)
22736 (org-agenda-todo 'previousset))
22738 (defun org-agenda-todo (&optional arg)
22739 "Cycle TODO state of line at point, also in Org-mode file.
22740 This changes the line at point, all other lines in the agenda referring to
22741 the same tree node, and the headline of the tree node in the Org-mode file."
22742 (interactive "P")
22743 (org-agenda-check-no-diary)
22744 (let* ((col (current-column))
22745 (marker (or (get-text-property (point) 'org-marker)
22746 (org-agenda-error)))
22747 (buffer (marker-buffer marker))
22748 (pos (marker-position marker))
22749 (hdmarker (get-text-property (point) 'org-hd-marker))
22750 (inhibit-read-only t)
22751 newhead)
22752 (org-with-remote-undo buffer
22753 (with-current-buffer buffer
22754 (widen)
22755 (goto-char pos)
22756 (org-show-context 'agenda)
22757 (save-excursion
22758 (and (outline-next-heading)
22759 (org-flag-heading nil))) ; show the next heading
22760 (org-todo arg)
22761 (and (bolp) (forward-char 1))
22762 (setq newhead (org-get-heading))
22763 (save-excursion
22764 (org-back-to-heading)
22765 (move-marker org-last-heading-marker (point))))
22766 (beginning-of-line 1)
22767 (save-excursion
22768 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22769 (move-to-column col))))
22771 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22772 "Change all lines in the agenda buffer which match HDMARKER.
22773 The new content of the line will be NEWHEAD (as modified by
22774 `org-format-agenda-item'). HDMARKER is checked with
22775 `equal' against all `org-hd-marker' text properties in the file.
22776 If FIXFACE is non-nil, the face of each item is modified acording to
22777 the new TODO state."
22778 (let* ((inhibit-read-only t)
22779 props m pl undone-face done-face finish new dotime cat tags)
22780 (save-excursion
22781 (goto-char (point-max))
22782 (beginning-of-line 1)
22783 (while (not finish)
22784 (setq finish (bobp))
22785 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22786 (equal m hdmarker))
22787 (setq props (text-properties-at (point))
22788 dotime (get-text-property (point) 'dotime)
22789 cat (get-text-property (point) 'org-category)
22790 tags (get-text-property (point) 'tags)
22791 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22792 pl (get-text-property (point) 'prefix-length)
22793 undone-face (get-text-property (point) 'undone-face)
22794 done-face (get-text-property (point) 'done-face))
22795 (move-to-column pl)
22796 (cond
22797 ((equal new "")
22798 (beginning-of-line 1)
22799 (and (looking-at ".*\n?") (replace-match "")))
22800 ((looking-at ".*")
22801 (replace-match new t t)
22802 (beginning-of-line 1)
22803 (add-text-properties (point-at-bol) (point-at-eol) props)
22804 (when fixface
22805 (add-text-properties
22806 (point-at-bol) (point-at-eol)
22807 (list 'face
22808 (if org-last-todo-state-is-todo
22809 undone-face done-face))))
22810 (org-agenda-highlight-todo 'line)
22811 (beginning-of-line 1))
22812 (t (error "Line update did not work"))))
22813 (beginning-of-line 0)))
22814 (org-finalize-agenda)))
22816 (defun org-agenda-align-tags (&optional line)
22817 "Align all tags in agenda items to `org-agenda-tags-column'."
22818 (let ((inhibit-read-only t) l c)
22819 (save-excursion
22820 (goto-char (if line (point-at-bol) (point-min)))
22821 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22822 (if line (point-at-eol) nil) t)
22823 (add-text-properties
22824 (match-beginning 2) (match-end 2)
22825 (list 'face (list 'org-tag (get-text-property
22826 (match-beginning 2) 'face))))
22827 (setq l (- (match-end 2) (match-beginning 2))
22828 c (if (< org-agenda-tags-column 0)
22829 (- (abs org-agenda-tags-column) l)
22830 org-agenda-tags-column))
22831 (delete-region (match-beginning 1) (match-end 1))
22832 (goto-char (match-beginning 1))
22833 (insert (org-add-props
22834 (make-string (max 1 (- c (current-column))) ?\ )
22835 (text-properties-at (point))))))))
22837 (defun org-agenda-priority-up ()
22838 "Increase the priority of line at point, also in Org-mode file."
22839 (interactive)
22840 (org-agenda-priority 'up))
22842 (defun org-agenda-priority-down ()
22843 "Decrease the priority of line at point, also in Org-mode file."
22844 (interactive)
22845 (org-agenda-priority 'down))
22847 (defun org-agenda-priority (&optional force-direction)
22848 "Set the priority of line at point, also in Org-mode file.
22849 This changes the line at point, all other lines in the agenda referring to
22850 the same tree node, and the headline of the tree node in the Org-mode file."
22851 (interactive)
22852 (org-agenda-check-no-diary)
22853 (let* ((marker (or (get-text-property (point) 'org-marker)
22854 (org-agenda-error)))
22855 (hdmarker (get-text-property (point) 'org-hd-marker))
22856 (buffer (marker-buffer hdmarker))
22857 (pos (marker-position hdmarker))
22858 (inhibit-read-only t)
22859 newhead)
22860 (org-with-remote-undo buffer
22861 (with-current-buffer buffer
22862 (widen)
22863 (goto-char pos)
22864 (org-show-context 'agenda)
22865 (save-excursion
22866 (and (outline-next-heading)
22867 (org-flag-heading nil))) ; show the next heading
22868 (funcall 'org-priority force-direction)
22869 (end-of-line 1)
22870 (setq newhead (org-get-heading)))
22871 (org-agenda-change-all-lines newhead hdmarker)
22872 (beginning-of-line 1))))
22874 (defun org-get-tags-at (&optional pos)
22875 "Get a list of all headline tags applicable at POS.
22876 POS defaults to point. If tags are inherited, the list contains
22877 the targets in the same sequence as the headlines appear, i.e.
22878 the tags of the current headline come last."
22879 (interactive)
22880 (let (tags lastpos)
22881 (save-excursion
22882 (save-restriction
22883 (widen)
22884 (goto-char (or pos (point)))
22885 (save-match-data
22886 (org-back-to-heading t)
22887 (condition-case nil
22888 (while (not (equal lastpos (point)))
22889 (setq lastpos (point))
22890 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22891 (setq tags (append (org-split-string
22892 (org-match-string-no-properties 1) ":")
22893 tags)))
22894 (or org-use-tag-inheritance (error ""))
22895 (org-up-heading-all 1))
22896 (error nil))))
22897 tags)))
22899 ;; FIXME: should fix the tags property of the agenda line.
22900 (defun org-agenda-set-tags ()
22901 "Set tags for the current headline."
22902 (interactive)
22903 (org-agenda-check-no-diary)
22904 (if (and (org-region-active-p) (interactive-p))
22905 (call-interactively 'org-change-tag-in-region)
22906 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22907 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22908 (org-agenda-error)))
22909 (buffer (marker-buffer hdmarker))
22910 (pos (marker-position hdmarker))
22911 (inhibit-read-only t)
22912 newhead)
22913 (org-with-remote-undo buffer
22914 (with-current-buffer buffer
22915 (widen)
22916 (goto-char pos)
22917 (save-excursion
22918 (org-show-context 'agenda))
22919 (save-excursion
22920 (and (outline-next-heading)
22921 (org-flag-heading nil))) ; show the next heading
22922 (goto-char pos)
22923 (call-interactively 'org-set-tags)
22924 (end-of-line 1)
22925 (setq newhead (org-get-heading)))
22926 (org-agenda-change-all-lines newhead hdmarker)
22927 (beginning-of-line 1)))))
22929 (defun org-agenda-toggle-archive-tag ()
22930 "Toggle the archive tag for the current entry."
22931 (interactive)
22932 (org-agenda-check-no-diary)
22933 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22934 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22935 (org-agenda-error)))
22936 (buffer (marker-buffer hdmarker))
22937 (pos (marker-position hdmarker))
22938 (inhibit-read-only t)
22939 newhead)
22940 (org-with-remote-undo buffer
22941 (with-current-buffer buffer
22942 (widen)
22943 (goto-char pos)
22944 (org-show-context 'agenda)
22945 (save-excursion
22946 (and (outline-next-heading)
22947 (org-flag-heading nil))) ; show the next heading
22948 (call-interactively 'org-toggle-archive-tag)
22949 (end-of-line 1)
22950 (setq newhead (org-get-heading)))
22951 (org-agenda-change-all-lines newhead hdmarker)
22952 (beginning-of-line 1))))
22954 (defun org-agenda-date-later (arg &optional what)
22955 "Change the date of this item to one day later."
22956 (interactive "p")
22957 (org-agenda-check-type t 'agenda 'timeline)
22958 (org-agenda-check-no-diary)
22959 (let* ((marker (or (get-text-property (point) 'org-marker)
22960 (org-agenda-error)))
22961 (buffer (marker-buffer marker))
22962 (pos (marker-position marker)))
22963 (org-with-remote-undo buffer
22964 (with-current-buffer buffer
22965 (widen)
22966 (goto-char pos)
22967 (if (not (org-at-timestamp-p))
22968 (error "Cannot find time stamp"))
22969 (org-timestamp-change arg (or what 'day)))
22970 (org-agenda-show-new-time marker org-last-changed-timestamp))
22971 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22973 (defun org-agenda-date-earlier (arg &optional what)
22974 "Change the date of this item to one day earlier."
22975 (interactive "p")
22976 (org-agenda-date-later (- arg) what))
22978 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22979 "Show new date stamp via text properties."
22980 ;; We use text properties to make this undoable
22981 (let ((inhibit-read-only t))
22982 (setq stamp (concat " " prefix " => " stamp))
22983 (save-excursion
22984 (goto-char (point-max))
22985 (while (not (bobp))
22986 (when (equal marker (get-text-property (point) 'org-marker))
22987 (move-to-column (- (window-width) (length stamp)) t)
22988 (if (featurep 'xemacs)
22989 ;; Use `duplicable' property to trigger undo recording
22990 (let ((ex (make-extent nil nil))
22991 (gl (make-glyph stamp)))
22992 (set-glyph-face gl 'secondary-selection)
22993 (set-extent-properties
22994 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22995 (insert-extent ex (1- (point)) (point-at-eol)))
22996 (add-text-properties
22997 (1- (point)) (point-at-eol)
22998 (list 'display (org-add-props stamp nil
22999 'face 'secondary-selection))))
23000 (beginning-of-line 1))
23001 (beginning-of-line 0)))))
23003 (defun org-agenda-date-prompt (arg)
23004 "Change the date of this item. Date is prompted for, with default today.
23005 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23006 be used to request time specification in the time stamp."
23007 (interactive "P")
23008 (org-agenda-check-type t 'agenda 'timeline)
23009 (org-agenda-check-no-diary)
23010 (let* ((marker (or (get-text-property (point) 'org-marker)
23011 (org-agenda-error)))
23012 (buffer (marker-buffer marker))
23013 (pos (marker-position marker)))
23014 (org-with-remote-undo buffer
23015 (with-current-buffer buffer
23016 (widen)
23017 (goto-char pos)
23018 (if (not (org-at-timestamp-p))
23019 (error "Cannot find time stamp"))
23020 (org-time-stamp arg)
23021 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23023 (defun org-agenda-schedule (arg)
23024 "Schedule the item at point."
23025 (interactive "P")
23026 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23027 (org-agenda-check-no-diary)
23028 (let* ((marker (or (get-text-property (point) 'org-marker)
23029 (org-agenda-error)))
23030 (buffer (marker-buffer marker))
23031 (pos (marker-position marker))
23032 (org-insert-labeled-timestamps-at-point nil)
23034 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23035 (set-marker-insertion-type marker t)
23036 (org-with-remote-undo buffer
23037 (with-current-buffer buffer
23038 (widen)
23039 (goto-char pos)
23040 (setq ts (org-schedule arg)))
23041 (org-agenda-show-new-time marker ts "S"))
23042 (message "Item scheduled for %s" ts)))
23044 (defun org-agenda-deadline (arg)
23045 "Schedule the item at point."
23046 (interactive "P")
23047 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23048 (org-agenda-check-no-diary)
23049 (let* ((marker (or (get-text-property (point) 'org-marker)
23050 (org-agenda-error)))
23051 (buffer (marker-buffer marker))
23052 (pos (marker-position marker))
23053 (org-insert-labeled-timestamps-at-point nil)
23055 (org-with-remote-undo buffer
23056 (with-current-buffer buffer
23057 (widen)
23058 (goto-char pos)
23059 (setq ts (org-deadline arg)))
23060 (org-agenda-show-new-time marker ts "S"))
23061 (message "Deadline for this item set to %s" ts)))
23063 (defun org-get-heading (&optional no-tags)
23064 "Return the heading of the current entry, without the stars."
23065 (save-excursion
23066 (org-back-to-heading t)
23067 (if (looking-at
23068 (if no-tags
23069 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23070 "\\*+[ \t]+\\([^\r\n]*\\)"))
23071 (match-string 1) "")))
23073 (defun org-agenda-clock-in (&optional arg)
23074 "Start the clock on the currently selected item."
23075 (interactive "P")
23076 (org-agenda-check-no-diary)
23077 (let* ((marker (or (get-text-property (point) 'org-marker)
23078 (org-agenda-error)))
23079 (pos (marker-position marker)))
23080 (org-with-remote-undo (marker-buffer marker)
23081 (with-current-buffer (marker-buffer marker)
23082 (widen)
23083 (goto-char pos)
23084 (org-clock-in)))))
23086 (defun org-agenda-clock-out (&optional arg)
23087 "Stop the currently running clock."
23088 (interactive "P")
23089 (unless (marker-buffer org-clock-marker)
23090 (error "No running clock"))
23091 (org-with-remote-undo (marker-buffer org-clock-marker)
23092 (org-clock-out)))
23094 (defun org-agenda-clock-cancel (&optional arg)
23095 "Cancel the currently running clock."
23096 (interactive "P")
23097 (unless (marker-buffer org-clock-marker)
23098 (error "No running clock"))
23099 (org-with-remote-undo (marker-buffer org-clock-marker)
23100 (org-clock-cancel)))
23102 (defun org-agenda-diary-entry ()
23103 "Make a diary entry, like the `i' command from the calendar.
23104 All the standard commands work: block, weekly etc."
23105 (interactive)
23106 (org-agenda-check-type t 'agenda 'timeline)
23107 (require 'diary-lib)
23108 (let* ((char (progn
23109 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23110 (read-char-exclusive)))
23111 (cmd (cdr (assoc char
23112 '((?d . insert-diary-entry)
23113 (?w . insert-weekly-diary-entry)
23114 (?m . insert-monthly-diary-entry)
23115 (?y . insert-yearly-diary-entry)
23116 (?a . insert-anniversary-diary-entry)
23117 (?b . insert-block-diary-entry)
23118 (?c . insert-cyclic-diary-entry)))))
23119 (oldf (symbol-function 'calendar-cursor-to-date))
23120 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23121 (point (point))
23122 (mark (or (mark t) (point))))
23123 (unless cmd
23124 (error "No command associated with <%c>" char))
23125 (unless (and (get-text-property point 'day)
23126 (or (not (equal ?b char))
23127 (get-text-property mark 'day)))
23128 (error "Don't know which date to use for diary entry"))
23129 ;; We implement this by hacking the `calendar-cursor-to-date' function
23130 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23131 (let ((calendar-mark-ring
23132 (list (calendar-gregorian-from-absolute
23133 (or (get-text-property mark 'day)
23134 (get-text-property point 'day))))))
23135 (unwind-protect
23136 (progn
23137 (fset 'calendar-cursor-to-date
23138 (lambda (&optional error)
23139 (calendar-gregorian-from-absolute
23140 (get-text-property point 'day))))
23141 (call-interactively cmd))
23142 (fset 'calendar-cursor-to-date oldf)))))
23145 (defun org-agenda-execute-calendar-command (cmd)
23146 "Execute a calendar command from the agenda, with the date associated to
23147 the cursor position."
23148 (org-agenda-check-type t 'agenda 'timeline)
23149 (require 'diary-lib)
23150 (unless (get-text-property (point) 'day)
23151 (error "Don't know which date to use for calendar command"))
23152 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23153 (point (point))
23154 (date (calendar-gregorian-from-absolute
23155 (get-text-property point 'day)))
23156 ;; the following 3 vars are needed in the calendar
23157 (displayed-day (extract-calendar-day date))
23158 (displayed-month (extract-calendar-month date))
23159 (displayed-year (extract-calendar-year date)))
23160 (unwind-protect
23161 (progn
23162 (fset 'calendar-cursor-to-date
23163 (lambda (&optional error)
23164 (calendar-gregorian-from-absolute
23165 (get-text-property point 'day))))
23166 (call-interactively cmd))
23167 (fset 'calendar-cursor-to-date oldf))))
23169 (defun org-agenda-phases-of-moon ()
23170 "Display the phases of the moon for the 3 months around the cursor date."
23171 (interactive)
23172 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23174 (defun org-agenda-holidays ()
23175 "Display the holidays for the 3 months around the cursor date."
23176 (interactive)
23177 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23179 (defun org-agenda-sunrise-sunset (arg)
23180 "Display sunrise and sunset for the cursor date.
23181 Latitude and longitude can be specified with the variables
23182 `calendar-latitude' and `calendar-longitude'. When called with prefix
23183 argument, latitude and longitude will be prompted for."
23184 (interactive "P")
23185 (let ((calendar-longitude (if arg nil calendar-longitude))
23186 (calendar-latitude (if arg nil calendar-latitude))
23187 (calendar-location-name
23188 (if arg "the given coordinates" calendar-location-name)))
23189 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23191 (defun org-agenda-goto-calendar ()
23192 "Open the Emacs calendar with the date at the cursor."
23193 (interactive)
23194 (org-agenda-check-type t 'agenda 'timeline)
23195 (let* ((day (or (get-text-property (point) 'day)
23196 (error "Don't know which date to open in calendar")))
23197 (date (calendar-gregorian-from-absolute day))
23198 (calendar-move-hook nil)
23199 (view-calendar-holidays-initially nil)
23200 (view-diary-entries-initially nil))
23201 (calendar)
23202 (calendar-goto-date date)))
23204 (defun org-calendar-goto-agenda ()
23205 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23206 This is a command that has to be installed in `calendar-mode-map'."
23207 (interactive)
23208 (org-agenda-list nil (calendar-absolute-from-gregorian
23209 (calendar-cursor-to-date))
23210 nil))
23212 (defun org-agenda-convert-date ()
23213 (interactive)
23214 (org-agenda-check-type t 'agenda 'timeline)
23215 (let ((day (get-text-property (point) 'day))
23216 date s)
23217 (unless day
23218 (error "Don't know which date to convert"))
23219 (setq date (calendar-gregorian-from-absolute day))
23220 (setq s (concat
23221 "Gregorian: " (calendar-date-string date) "\n"
23222 "ISO: " (calendar-iso-date-string date) "\n"
23223 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23224 "Julian: " (calendar-julian-date-string date) "\n"
23225 "Astron. JD: " (calendar-astro-date-string date)
23226 " (Julian date number at noon UTC)\n"
23227 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23228 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23229 "French: " (calendar-french-date-string date) "\n"
23230 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23231 "Mayan: " (calendar-mayan-date-string date) "\n"
23232 "Coptic: " (calendar-coptic-date-string date) "\n"
23233 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23234 "Persian: " (calendar-persian-date-string date) "\n"
23235 "Chinese: " (calendar-chinese-date-string date) "\n"))
23236 (with-output-to-temp-buffer "*Dates*"
23237 (princ s))
23238 (if (fboundp 'fit-window-to-buffer)
23239 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23242 ;;;; Embedded LaTeX
23244 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23245 "Keymap for the minor `org-cdlatex-mode'.")
23247 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23248 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23249 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23250 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23251 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23253 (defvar org-cdlatex-texmathp-advice-is-done nil
23254 "Flag remembering if we have applied the advice to texmathp already.")
23256 (define-minor-mode org-cdlatex-mode
23257 "Toggle the minor `org-cdlatex-mode'.
23258 This mode supports entering LaTeX environment and math in LaTeX fragments
23259 in Org-mode.
23260 \\{org-cdlatex-mode-map}"
23261 nil " OCDL" nil
23262 (when org-cdlatex-mode (require 'cdlatex))
23263 (unless org-cdlatex-texmathp-advice-is-done
23264 (setq org-cdlatex-texmathp-advice-is-done t)
23265 (defadvice texmathp (around org-math-always-on activate)
23266 "Always return t in org-mode buffers.
23267 This is because we want to insert math symbols without dollars even outside
23268 the LaTeX math segments. If Orgmode thinks that point is actually inside
23269 en embedded LaTeX fragement, let texmathp do its job.
23270 \\[org-cdlatex-mode-map]"
23271 (interactive)
23272 (let (p)
23273 (cond
23274 ((not (org-mode-p)) ad-do-it)
23275 ((eq this-command 'cdlatex-math-symbol)
23276 (setq ad-return-value t
23277 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23279 (let ((p (org-inside-LaTeX-fragment-p)))
23280 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23281 (setq ad-return-value t
23282 texmathp-why '("Org-mode embedded math" . 0))
23283 (if p ad-do-it)))))))))
23285 (defun turn-on-org-cdlatex ()
23286 "Unconditionally turn on `org-cdlatex-mode'."
23287 (org-cdlatex-mode 1))
23289 (defun org-inside-LaTeX-fragment-p ()
23290 "Test if point is inside a LaTeX fragment.
23291 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23292 sequence appearing also before point.
23293 Even though the matchers for math are configurable, this function assumes
23294 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23295 delimiters are skipped when they have been removed by customization.
23296 The return value is nil, or a cons cell with the delimiter and
23297 and the position of this delimiter.
23299 This function does a reasonably good job, but can locally be fooled by
23300 for example currency specifications. For example it will assume being in
23301 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23302 fragments that are properly closed, but during editing, we have to live
23303 with the uncertainty caused by missing closing delimiters. This function
23304 looks only before point, not after."
23305 (catch 'exit
23306 (let ((pos (point))
23307 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23308 (lim (progn
23309 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23310 (point)))
23311 dd-on str (start 0) m re)
23312 (goto-char pos)
23313 (when dodollar
23314 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23315 re (nth 1 (assoc "$" org-latex-regexps)))
23316 (while (string-match re str start)
23317 (cond
23318 ((= (match-end 0) (length str))
23319 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23320 ((= (match-end 0) (- (length str) 5))
23321 (throw 'exit nil))
23322 (t (setq start (match-end 0))))))
23323 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23324 (goto-char pos)
23325 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23326 (and (match-beginning 2) (throw 'exit nil))
23327 ;; count $$
23328 (while (re-search-backward "\\$\\$" lim t)
23329 (setq dd-on (not dd-on)))
23330 (goto-char pos)
23331 (if dd-on (cons "$$" m))))))
23334 (defun org-try-cdlatex-tab ()
23335 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23336 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23337 - inside a LaTeX fragment, or
23338 - after the first word in a line, where an abbreviation expansion could
23339 insert a LaTeX environment."
23340 (when org-cdlatex-mode
23341 (cond
23342 ((save-excursion
23343 (skip-chars-backward "a-zA-Z0-9*")
23344 (skip-chars-backward " \t")
23345 (bolp))
23346 (cdlatex-tab) t)
23347 ((org-inside-LaTeX-fragment-p)
23348 (cdlatex-tab) t)
23349 (t nil))))
23351 (defun org-cdlatex-underscore-caret (&optional arg)
23352 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23353 Revert to the normal definition outside of these fragments."
23354 (interactive "P")
23355 (if (org-inside-LaTeX-fragment-p)
23356 (call-interactively 'cdlatex-sub-superscript)
23357 (let (org-cdlatex-mode)
23358 (call-interactively (key-binding (vector last-input-event))))))
23360 (defun org-cdlatex-math-modify (&optional arg)
23361 "Execute `cdlatex-math-modify' in LaTeX fragments.
23362 Revert to the normal definition outside of these fragments."
23363 (interactive "P")
23364 (if (org-inside-LaTeX-fragment-p)
23365 (call-interactively 'cdlatex-math-modify)
23366 (let (org-cdlatex-mode)
23367 (call-interactively (key-binding (vector last-input-event))))))
23369 (defvar org-latex-fragment-image-overlays nil
23370 "List of overlays carrying the images of latex fragments.")
23371 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23373 (defun org-remove-latex-fragment-image-overlays ()
23374 "Remove all overlays with LaTeX fragment images in current buffer."
23375 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23376 (setq org-latex-fragment-image-overlays nil))
23378 (defun org-preview-latex-fragment (&optional subtree)
23379 "Preview the LaTeX fragment at point, or all locally or globally.
23380 If the cursor is in a LaTeX fragment, create the image and overlay
23381 it over the source code. If there is no fragment at point, display
23382 all fragments in the current text, from one headline to the next. With
23383 prefix SUBTREE, display all fragments in the current subtree. With a
23384 double prefix `C-u C-u', or when the cursor is before the first headline,
23385 display all fragments in the buffer.
23386 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23387 (interactive "P")
23388 (org-remove-latex-fragment-image-overlays)
23389 (save-excursion
23390 (save-restriction
23391 (let (beg end at msg)
23392 (cond
23393 ((or (equal subtree '(16))
23394 (not (save-excursion
23395 (re-search-backward (concat "^" outline-regexp) nil t))))
23396 (setq beg (point-min) end (point-max)
23397 msg "Creating images for buffer...%s"))
23398 ((equal subtree '(4))
23399 (org-back-to-heading)
23400 (setq beg (point) end (org-end-of-subtree t)
23401 msg "Creating images for subtree...%s"))
23403 (if (setq at (org-inside-LaTeX-fragment-p))
23404 (goto-char (max (point-min) (- (cdr at) 2)))
23405 (org-back-to-heading))
23406 (setq beg (point) end (progn (outline-next-heading) (point))
23407 msg (if at "Creating image...%s"
23408 "Creating images for entry...%s"))))
23409 (message msg "")
23410 (narrow-to-region beg end)
23411 (goto-char beg)
23412 (org-format-latex
23413 (concat "ltxpng/" (file-name-sans-extension
23414 (file-name-nondirectory
23415 buffer-file-name)))
23416 default-directory 'overlays msg at 'forbuffer)
23417 (message msg "done. Use `C-c C-c' to remove images.")))))
23419 (defvar org-latex-regexps
23420 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23421 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23422 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23423 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23424 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23425 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23426 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23427 "Regular expressions for matching embedded LaTeX.")
23429 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23430 "Replace LaTeX fragments with links to an image, and produce images."
23431 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23432 (let* ((prefixnodir (file-name-nondirectory prefix))
23433 (absprefix (expand-file-name prefix dir))
23434 (todir (file-name-directory absprefix))
23435 (opt org-format-latex-options)
23436 (matchers (plist-get opt :matchers))
23437 (re-list org-latex-regexps)
23438 (cnt 0) txt link beg end re e checkdir
23439 m n block linkfile movefile ov)
23440 ;; Check if there are old images files with this prefix, and remove them
23441 (when (file-directory-p todir)
23442 (mapc 'delete-file
23443 (directory-files
23444 todir 'full
23445 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23446 ;; Check the different regular expressions
23447 (while (setq e (pop re-list))
23448 (setq m (car e) re (nth 1 e) n (nth 2 e)
23449 block (if (nth 3 e) "\n\n" ""))
23450 (when (member m matchers)
23451 (goto-char (point-min))
23452 (while (re-search-forward re nil t)
23453 (when (or (not at) (equal (cdr at) (match-beginning n)))
23454 (setq txt (match-string n)
23455 beg (match-beginning n) end (match-end n)
23456 cnt (1+ cnt)
23457 linkfile (format "%s_%04d.png" prefix cnt)
23458 movefile (format "%s_%04d.png" absprefix cnt)
23459 link (concat block "[[file:" linkfile "]]" block))
23460 (if msg (message msg cnt))
23461 (goto-char beg)
23462 (unless checkdir ; make sure the directory exists
23463 (setq checkdir t)
23464 (or (file-directory-p todir) (make-directory todir)))
23465 (org-create-formula-image
23466 txt movefile opt forbuffer)
23467 (if overlays
23468 (progn
23469 (setq ov (org-make-overlay beg end))
23470 (if (featurep 'xemacs)
23471 (progn
23472 (org-overlay-put ov 'invisible t)
23473 (org-overlay-put
23474 ov 'end-glyph
23475 (make-glyph (vector 'png :file movefile))))
23476 (org-overlay-put
23477 ov 'display
23478 (list 'image :type 'png :file movefile :ascent 'center)))
23479 (push ov org-latex-fragment-image-overlays)
23480 (goto-char end))
23481 (delete-region beg end)
23482 (insert link))))))))
23484 ;; This function borrows from Ganesh Swami's latex2png.el
23485 (defun org-create-formula-image (string tofile options buffer)
23486 (let* ((tmpdir (if (featurep 'xemacs)
23487 (temp-directory)
23488 temporary-file-directory))
23489 (texfilebase (make-temp-name
23490 (expand-file-name "orgtex" tmpdir)))
23491 (texfile (concat texfilebase ".tex"))
23492 (dvifile (concat texfilebase ".dvi"))
23493 (pngfile (concat texfilebase ".png"))
23494 (fnh (face-attribute 'default :height nil))
23495 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23496 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23497 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23498 "Black"))
23499 (bg (or (plist-get options (if buffer :background :html-background))
23500 "Transparent")))
23501 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23502 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23503 (with-temp-file texfile
23504 (insert org-format-latex-header
23505 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23506 (let ((dir default-directory))
23507 (condition-case nil
23508 (progn
23509 (cd tmpdir)
23510 (call-process "latex" nil nil nil texfile))
23511 (error nil))
23512 (cd dir))
23513 (if (not (file-exists-p dvifile))
23514 (progn (message "Failed to create dvi file from %s" texfile) nil)
23515 (call-process "dvipng" nil nil nil
23516 "-E" "-fg" fg "-bg" bg
23517 "-D" dpi
23518 ;;"-x" scale "-y" scale
23519 "-T" "tight"
23520 "-o" pngfile
23521 dvifile)
23522 (if (not (file-exists-p pngfile))
23523 (progn (message "Failed to create png file from %s" texfile) nil)
23524 ;; Use the requested file name and clean up
23525 (copy-file pngfile tofile 'replace)
23526 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23527 (delete-file (concat texfilebase e)))
23528 pngfile))))
23530 (defun org-dvipng-color (attr)
23531 "Return an rgb color specification for dvipng."
23532 (apply 'format "rgb %s %s %s"
23533 (mapcar 'org-normalize-color
23534 (color-values (face-attribute 'default attr nil)))))
23536 (defun org-normalize-color (value)
23537 "Return string to be used as color value for an RGB component."
23538 (format "%g" (/ value 65535.0)))
23540 ;;;; Exporting
23542 ;;; Variables, constants, and parameter plists
23544 (defconst org-level-max 20)
23546 (defvar org-export-html-preamble nil
23547 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23548 (defvar org-export-html-postamble nil
23549 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23550 (defvar org-export-html-auto-preamble t
23551 "Should default preamble be inserted? Set by publishing functions.")
23552 (defvar org-export-html-auto-postamble t
23553 "Should default postamble be inserted? Set by publishing functions.")
23554 (defvar org-current-export-file nil) ; dynamically scoped parameter
23555 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23558 (defconst org-export-plist-vars
23559 '((:language . org-export-default-language)
23560 (:customtime . org-display-custom-times)
23561 (:headline-levels . org-export-headline-levels)
23562 (:section-numbers . org-export-with-section-numbers)
23563 (:table-of-contents . org-export-with-toc)
23564 (:preserve-breaks . org-export-preserve-breaks)
23565 (:archived-trees . org-export-with-archived-trees)
23566 (:emphasize . org-export-with-emphasize)
23567 (:sub-superscript . org-export-with-sub-superscripts)
23568 (:special-strings . org-export-with-special-strings)
23569 (:footnotes . org-export-with-footnotes)
23570 (:drawers . org-export-with-drawers)
23571 (:tags . org-export-with-tags)
23572 (:TeX-macros . org-export-with-TeX-macros)
23573 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23574 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23575 (:fixed-width . org-export-with-fixed-width)
23576 (:timestamps . org-export-with-timestamps)
23577 (:author-info . org-export-author-info)
23578 (:time-stamp-file . org-export-time-stamp-file)
23579 (:tables . org-export-with-tables)
23580 (:table-auto-headline . org-export-highlight-first-table-line)
23581 (:style . org-export-html-style)
23582 (:agenda-style . org-agenda-export-html-style)
23583 (:convert-org-links . org-export-html-link-org-files-as-html)
23584 (:inline-images . org-export-html-inline-images)
23585 (:html-extension . org-export-html-extension)
23586 (:html-table-tag . org-export-html-table-tag)
23587 (:expand-quoted-html . org-export-html-expand)
23588 (:timestamp . org-export-html-with-timestamp)
23589 (:publishing-directory . org-export-publishing-directory)
23590 (:preamble . org-export-html-preamble)
23591 (:postamble . org-export-html-postamble)
23592 (:auto-preamble . org-export-html-auto-preamble)
23593 (:auto-postamble . org-export-html-auto-postamble)
23594 (:author . user-full-name)
23595 (:email . user-mail-address)))
23597 (defun org-default-export-plist ()
23598 "Return the property list with default settings for the export variables."
23599 (let ((l org-export-plist-vars) rtn e)
23600 (while (setq e (pop l))
23601 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23602 rtn))
23604 (defun org-infile-export-plist ()
23605 "Return the property list with file-local settings for export."
23606 (save-excursion
23607 (save-restriction
23608 (widen)
23609 (goto-char 0)
23610 (let ((re (org-make-options-regexp
23611 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23612 p key val text options)
23613 (while (re-search-forward re nil t)
23614 (setq key (org-match-string-no-properties 1)
23615 val (org-match-string-no-properties 2))
23616 (cond
23617 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23618 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23619 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23620 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23621 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23622 ((string-equal key "TEXT")
23623 (setq text (if text (concat text "\n" val) val)))
23624 ((string-equal key "OPTIONS") (setq options val))))
23625 (setq p (plist-put p :text text))
23626 (when options
23627 (let ((op '(("H" . :headline-levels)
23628 ("num" . :section-numbers)
23629 ("toc" . :table-of-contents)
23630 ("\\n" . :preserve-breaks)
23631 ("@" . :expand-quoted-html)
23632 (":" . :fixed-width)
23633 ("|" . :tables)
23634 ("^" . :sub-superscript)
23635 ("-" . :special-strings)
23636 ("f" . :footnotes)
23637 ("d" . :drawers)
23638 ("tags" . :tags)
23639 ("*" . :emphasize)
23640 ("TeX" . :TeX-macros)
23641 ("LaTeX" . :LaTeX-fragments)
23642 ("skip" . :skip-before-1st-heading)
23643 ("author" . :author-info)
23644 ("timestamp" . :time-stamp-file)))
23646 (while (setq o (pop op))
23647 (if (string-match (concat (regexp-quote (car o))
23648 ":\\([^ \t\n\r;,.]*\\)")
23649 options)
23650 (setq p (plist-put p (cdr o)
23651 (car (read-from-string
23652 (match-string 1 options)))))))))
23653 p))))
23655 (defun org-export-directory (type plist)
23656 (let* ((val (plist-get plist :publishing-directory))
23657 (dir (if (listp val)
23658 (or (cdr (assoc type val)) ".")
23659 val)))
23660 dir))
23662 (defun org-skip-comments (lines)
23663 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23664 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23665 (re2 "^\\(\\*+\\)[ \t\n\r]")
23666 (case-fold-search nil)
23667 rtn line level)
23668 (while (setq line (pop lines))
23669 (cond
23670 ((and (string-match re1 line)
23671 (setq level (- (match-end 1) (match-beginning 1))))
23672 ;; Beginning of a COMMENT subtree. Skip it.
23673 (while (and (setq line (pop lines))
23674 (or (not (string-match re2 line))
23675 (> (- (match-end 1) (match-beginning 1)) level))))
23676 (setq lines (cons line lines)))
23677 ((string-match "^#" line)
23678 ;; an ordinary comment line
23680 ((and org-export-table-remove-special-lines
23681 (string-match "^[ \t]*|" line)
23682 (or (string-match "^[ \t]*| *[!_^] *|" line)
23683 (and (string-match "| *<[0-9]+> *|" line)
23684 (not (string-match "| *[^ <|]" line)))))
23685 ;; a special table line that should be removed
23687 (t (setq rtn (cons line rtn)))))
23688 (nreverse rtn)))
23690 (defun org-export (&optional arg)
23691 (interactive)
23692 (let ((help "[t] insert the export option template
23693 \[v] limit export to visible part of outline tree
23695 \[a] export as ASCII
23697 \[h] export as HTML
23698 \[H] export as HTML to temporary buffer
23699 \[R] export region as HTML
23700 \[b] export as HTML and browse immediately
23701 \[x] export as XOXO
23703 \[l] export as LaTeX
23704 \[L] export as LaTeX to temporary buffer
23706 \[i] export current file as iCalendar file
23707 \[I] export all agenda files as iCalendar files
23708 \[c] export agenda files into combined iCalendar file
23710 \[F] publish current file
23711 \[P] publish current project
23712 \[X] publish... (project will be prompted for)
23713 \[A] publish all projects")
23714 (cmds
23715 '((?t . org-insert-export-options-template)
23716 (?v . org-export-visible)
23717 (?a . org-export-as-ascii)
23718 (?h . org-export-as-html)
23719 (?b . org-export-as-html-and-open)
23720 (?H . org-export-as-html-to-buffer)
23721 (?R . org-export-region-as-html)
23722 (?x . org-export-as-xoxo)
23723 (?l . org-export-as-latex)
23724 (?L . org-export-as-latex-to-buffer)
23725 (?i . org-export-icalendar-this-file)
23726 (?I . org-export-icalendar-all-agenda-files)
23727 (?c . org-export-icalendar-combine-agenda-files)
23728 (?F . org-publish-current-file)
23729 (?P . org-publish-current-project)
23730 (?X . org-publish)
23731 (?A . org-publish-all)))
23732 r1 r2 ass)
23733 (save-window-excursion
23734 (delete-other-windows)
23735 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23736 (princ help))
23737 (message "Select command: ")
23738 (setq r1 (read-char-exclusive)))
23739 (setq r2 (if (< r1 27) (+ r1 96) r1))
23740 (if (setq ass (assq r2 cmds))
23741 (call-interactively (cdr ass))
23742 (error "No command associated with key %c" r1))))
23744 (defconst org-html-entities
23745 '(("nbsp")
23746 ("iexcl")
23747 ("cent")
23748 ("pound")
23749 ("curren")
23750 ("yen")
23751 ("brvbar")
23752 ("vert" . "&#124;")
23753 ("sect")
23754 ("uml")
23755 ("copy")
23756 ("ordf")
23757 ("laquo")
23758 ("not")
23759 ("shy")
23760 ("reg")
23761 ("macr")
23762 ("deg")
23763 ("plusmn")
23764 ("sup2")
23765 ("sup3")
23766 ("acute")
23767 ("micro")
23768 ("para")
23769 ("middot")
23770 ("odot"."o")
23771 ("star"."*")
23772 ("cedil")
23773 ("sup1")
23774 ("ordm")
23775 ("raquo")
23776 ("frac14")
23777 ("frac12")
23778 ("frac34")
23779 ("iquest")
23780 ("Agrave")
23781 ("Aacute")
23782 ("Acirc")
23783 ("Atilde")
23784 ("Auml")
23785 ("Aring") ("AA"."&Aring;")
23786 ("AElig")
23787 ("Ccedil")
23788 ("Egrave")
23789 ("Eacute")
23790 ("Ecirc")
23791 ("Euml")
23792 ("Igrave")
23793 ("Iacute")
23794 ("Icirc")
23795 ("Iuml")
23796 ("ETH")
23797 ("Ntilde")
23798 ("Ograve")
23799 ("Oacute")
23800 ("Ocirc")
23801 ("Otilde")
23802 ("Ouml")
23803 ("times")
23804 ("Oslash")
23805 ("Ugrave")
23806 ("Uacute")
23807 ("Ucirc")
23808 ("Uuml")
23809 ("Yacute")
23810 ("THORN")
23811 ("szlig")
23812 ("agrave")
23813 ("aacute")
23814 ("acirc")
23815 ("atilde")
23816 ("auml")
23817 ("aring")
23818 ("aelig")
23819 ("ccedil")
23820 ("egrave")
23821 ("eacute")
23822 ("ecirc")
23823 ("euml")
23824 ("igrave")
23825 ("iacute")
23826 ("icirc")
23827 ("iuml")
23828 ("eth")
23829 ("ntilde")
23830 ("ograve")
23831 ("oacute")
23832 ("ocirc")
23833 ("otilde")
23834 ("ouml")
23835 ("divide")
23836 ("oslash")
23837 ("ugrave")
23838 ("uacute")
23839 ("ucirc")
23840 ("uuml")
23841 ("yacute")
23842 ("thorn")
23843 ("yuml")
23844 ("fnof")
23845 ("Alpha")
23846 ("Beta")
23847 ("Gamma")
23848 ("Delta")
23849 ("Epsilon")
23850 ("Zeta")
23851 ("Eta")
23852 ("Theta")
23853 ("Iota")
23854 ("Kappa")
23855 ("Lambda")
23856 ("Mu")
23857 ("Nu")
23858 ("Xi")
23859 ("Omicron")
23860 ("Pi")
23861 ("Rho")
23862 ("Sigma")
23863 ("Tau")
23864 ("Upsilon")
23865 ("Phi")
23866 ("Chi")
23867 ("Psi")
23868 ("Omega")
23869 ("alpha")
23870 ("beta")
23871 ("gamma")
23872 ("delta")
23873 ("epsilon")
23874 ("varepsilon"."&epsilon;")
23875 ("zeta")
23876 ("eta")
23877 ("theta")
23878 ("iota")
23879 ("kappa")
23880 ("lambda")
23881 ("mu")
23882 ("nu")
23883 ("xi")
23884 ("omicron")
23885 ("pi")
23886 ("rho")
23887 ("sigmaf") ("varsigma"."&sigmaf;")
23888 ("sigma")
23889 ("tau")
23890 ("upsilon")
23891 ("phi")
23892 ("chi")
23893 ("psi")
23894 ("omega")
23895 ("thetasym") ("vartheta"."&thetasym;")
23896 ("upsih")
23897 ("piv")
23898 ("bull") ("bullet"."&bull;")
23899 ("hellip") ("dots"."&hellip;")
23900 ("prime")
23901 ("Prime")
23902 ("oline")
23903 ("frasl")
23904 ("weierp")
23905 ("image")
23906 ("real")
23907 ("trade")
23908 ("alefsym")
23909 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23910 ("uarr") ("uparrow"."&uarr;")
23911 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23912 ("darr")("downarrow"."&darr;")
23913 ("harr") ("leftrightarrow"."&harr;")
23914 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23915 ("lArr") ("Leftarrow"."&lArr;")
23916 ("uArr") ("Uparrow"."&uArr;")
23917 ("rArr") ("Rightarrow"."&rArr;")
23918 ("dArr") ("Downarrow"."&dArr;")
23919 ("hArr") ("Leftrightarrow"."&hArr;")
23920 ("forall")
23921 ("part") ("partial"."&part;")
23922 ("exist") ("exists"."&exist;")
23923 ("empty") ("emptyset"."&empty;")
23924 ("nabla")
23925 ("isin") ("in"."&isin;")
23926 ("notin")
23927 ("ni")
23928 ("prod")
23929 ("sum")
23930 ("minus")
23931 ("lowast") ("ast"."&lowast;")
23932 ("radic")
23933 ("prop") ("proptp"."&prop;")
23934 ("infin") ("infty"."&infin;")
23935 ("ang") ("angle"."&ang;")
23936 ("and") ("wedge"."&and;")
23937 ("or") ("vee"."&or;")
23938 ("cap")
23939 ("cup")
23940 ("int")
23941 ("there4")
23942 ("sim")
23943 ("cong") ("simeq"."&cong;")
23944 ("asymp")("approx"."&asymp;")
23945 ("ne") ("neq"."&ne;")
23946 ("equiv")
23947 ("le")
23948 ("ge")
23949 ("sub") ("subset"."&sub;")
23950 ("sup") ("supset"."&sup;")
23951 ("nsub")
23952 ("sube")
23953 ("supe")
23954 ("oplus")
23955 ("otimes")
23956 ("perp")
23957 ("sdot") ("cdot"."&sdot;")
23958 ("lceil")
23959 ("rceil")
23960 ("lfloor")
23961 ("rfloor")
23962 ("lang")
23963 ("rang")
23964 ("loz") ("Diamond"."&loz;")
23965 ("spades") ("spadesuit"."&spades;")
23966 ("clubs") ("clubsuit"."&clubs;")
23967 ("hearts") ("diamondsuit"."&hearts;")
23968 ("diams") ("diamondsuit"."&diams;")
23969 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23970 ("quot")
23971 ("amp")
23972 ("lt")
23973 ("gt")
23974 ("OElig")
23975 ("oelig")
23976 ("Scaron")
23977 ("scaron")
23978 ("Yuml")
23979 ("circ")
23980 ("tilde")
23981 ("ensp")
23982 ("emsp")
23983 ("thinsp")
23984 ("zwnj")
23985 ("zwj")
23986 ("lrm")
23987 ("rlm")
23988 ("ndash")
23989 ("mdash")
23990 ("lsquo")
23991 ("rsquo")
23992 ("sbquo")
23993 ("ldquo")
23994 ("rdquo")
23995 ("bdquo")
23996 ("dagger")
23997 ("Dagger")
23998 ("permil")
23999 ("lsaquo")
24000 ("rsaquo")
24001 ("euro")
24003 ("arccos"."arccos")
24004 ("arcsin"."arcsin")
24005 ("arctan"."arctan")
24006 ("arg"."arg")
24007 ("cos"."cos")
24008 ("cosh"."cosh")
24009 ("cot"."cot")
24010 ("coth"."coth")
24011 ("csc"."csc")
24012 ("deg"."deg")
24013 ("det"."det")
24014 ("dim"."dim")
24015 ("exp"."exp")
24016 ("gcd"."gcd")
24017 ("hom"."hom")
24018 ("inf"."inf")
24019 ("ker"."ker")
24020 ("lg"."lg")
24021 ("lim"."lim")
24022 ("liminf"."liminf")
24023 ("limsup"."limsup")
24024 ("ln"."ln")
24025 ("log"."log")
24026 ("max"."max")
24027 ("min"."min")
24028 ("Pr"."Pr")
24029 ("sec"."sec")
24030 ("sin"."sin")
24031 ("sinh"."sinh")
24032 ("sup"."sup")
24033 ("tan"."tan")
24034 ("tanh"."tanh")
24036 "Entities for TeX->HTML translation.
24037 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24038 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24039 In that case, \"\\ent\" will be translated to \"&other;\".
24040 The list contains HTML entities for Latin-1, Greek and other symbols.
24041 It is supplemented by a number of commonly used TeX macros with appropriate
24042 translations. There is currently no way for users to extend this.")
24044 ;;; General functions for all backends
24046 (defun org-cleaned-string-for-export (string &rest parameters)
24047 "Cleanup a buffer STRING so that links can be created safely."
24048 (interactive)
24049 (let* ((re-radio (and org-target-link-regexp
24050 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24051 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24052 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24053 (re-archive (concat ":" org-archive-tag ":"))
24054 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24055 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24056 (htmlp (plist-get parameters :for-html))
24057 (asciip (plist-get parameters :for-ascii))
24058 (latexp (plist-get parameters :for-LaTeX))
24059 (commentsp (plist-get parameters :comments))
24060 (archived-trees (plist-get parameters :archived-trees))
24061 (inhibit-read-only t)
24062 (drawers org-drawers)
24063 (exp-drawers (plist-get parameters :drawers))
24064 (outline-regexp "\\*+ ")
24065 a b xx
24066 rtn p)
24067 (with-current-buffer (get-buffer-create " org-mode-tmp")
24068 (erase-buffer)
24069 (insert string)
24070 ;; Remove license-to-kill stuff
24071 (while (setq p (text-property-any (point-min) (point-max)
24072 :org-license-to-kill t))
24073 (delete-region p (next-single-property-change p :org-license-to-kill)))
24075 (let ((org-inhibit-startup t)) (org-mode))
24076 (untabify (point-min) (point-max))
24078 ;; Get rid of drawers
24079 (unless (eq t exp-drawers)
24080 (goto-char (point-min))
24081 (let ((re (concat "^[ \t]*:\\("
24082 (mapconcat
24083 'identity
24084 (org-delete-all exp-drawers
24085 (copy-sequence drawers))
24086 "\\|")
24087 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24088 (while (re-search-forward re nil t)
24089 (replace-match ""))))
24091 ;; Get the correct stuff before the first headline
24092 (when (plist-get parameters :skip-before-1st-heading)
24093 (goto-char (point-min))
24094 (when (re-search-forward "^\\*+[ \t]" nil t)
24095 (delete-region (point-min) (match-beginning 0))
24096 (goto-char (point-min))
24097 (insert "\n")))
24098 (when (plist-get parameters :add-text)
24099 (goto-char (point-min))
24100 (insert (plist-get parameters :add-text) "\n"))
24102 ;; Get rid of archived trees
24103 (when (not (eq archived-trees t))
24104 (goto-char (point-min))
24105 (while (re-search-forward re-archive nil t)
24106 (if (not (org-on-heading-p t))
24107 (org-end-of-subtree t)
24108 (beginning-of-line 1)
24109 (setq a (if archived-trees
24110 (1+ (point-at-eol)) (point))
24111 b (org-end-of-subtree t))
24112 (if (> b a) (delete-region a b)))))
24114 ;; Find targets in comments and move them out of comments,
24115 ;; but mark them as targets that should be invisible
24116 (goto-char (point-min))
24117 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24118 (replace-match "\\1(INVISIBLE)"))
24120 ;; Protect backend specific stuff, throw away the others.
24121 (let ((formatters
24122 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24123 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24124 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24125 fmt)
24126 (goto-char (point-min))
24127 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24128 (goto-char (match-end 0))
24129 (while (not (looking-at "#\\+END_EXAMPLE"))
24130 (insert ": ")
24131 (beginning-of-line 2)))
24132 (goto-char (point-min))
24133 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24134 (add-text-properties (match-beginning 0) (match-end 0)
24135 '(org-protected t)))
24136 (while formatters
24137 (setq fmt (pop formatters))
24138 (when (car fmt)
24139 (goto-char (point-min))
24140 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24141 ":[ \t]*\\(.*\\)") nil t)
24142 (replace-match "\\1" t)
24143 (add-text-properties
24144 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24145 '(org-protected t))))
24146 (goto-char (point-min))
24147 (while (re-search-forward
24148 (concat "^#\\+"
24149 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24150 (cadddr fmt) "\\>.*\n?") nil t)
24151 (if (car fmt)
24152 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24153 '(org-protected t))
24154 (delete-region (match-beginning 0) (match-end 0))))))
24156 ;; Protect quoted subtrees
24157 (goto-char (point-min))
24158 (while (re-search-forward re-quote nil t)
24159 (goto-char (match-beginning 0))
24160 (end-of-line 1)
24161 (add-text-properties (point) (org-end-of-subtree t)
24162 '(org-protected t)))
24164 ;; Protect verbatim elements
24165 (goto-char (point-min))
24166 (while (re-search-forward org-verbatim-re nil t)
24167 (add-text-properties (match-beginning 4) (match-end 4)
24168 '(org-protected t))
24169 (goto-char (1+ (match-end 4))))
24171 ;; Remove subtrees that are commented
24172 (goto-char (point-min))
24173 (while (re-search-forward re-commented nil t)
24174 (goto-char (match-beginning 0))
24175 (delete-region (point) (org-end-of-subtree t)))
24177 ;; Remove special table lines
24178 (when org-export-table-remove-special-lines
24179 (goto-char (point-min))
24180 (while (re-search-forward "^[ \t]*|" nil t)
24181 (beginning-of-line 1)
24182 (if (or (looking-at "[ \t]*| *[!_^] *|")
24183 (and (looking-at ".*?| *<[0-9]+> *|")
24184 (not (looking-at ".*?| *[^ <|]"))))
24185 (delete-region (max (point-min) (1- (point-at-bol)))
24186 (point-at-eol))
24187 (end-of-line 1))))
24189 ;; Specific LaTeX stuff
24190 (when latexp
24191 (require 'org-export-latex nil)
24192 (org-export-latex-cleaned-string))
24194 (when asciip
24195 (org-export-ascii-clean-string))
24197 ;; Specific HTML stuff
24198 (when htmlp
24199 ;; Convert LaTeX fragments to images
24200 (when (plist-get parameters :LaTeX-fragments)
24201 (org-format-latex
24202 (concat "ltxpng/" (file-name-sans-extension
24203 (file-name-nondirectory
24204 org-current-export-file)))
24205 org-current-export-dir nil "Creating LaTeX image %s"))
24206 (message "Exporting..."))
24208 ;; Remove or replace comments
24209 (goto-char (point-min))
24210 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24211 (if commentsp
24212 (progn (add-text-properties
24213 (match-beginning 0) (match-end 0) '(org-protected t))
24214 (replace-match (format commentsp (match-string 1)) t t))
24215 (replace-match "")))
24217 ;; Find matches for radio targets and turn them into internal links
24218 (goto-char (point-min))
24219 (when re-radio
24220 (while (re-search-forward re-radio nil t)
24221 (org-if-unprotected
24222 (replace-match "\\1[[\\2]]"))))
24224 ;; Find all links that contain a newline and put them into a single line
24225 (goto-char (point-min))
24226 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24227 (org-if-unprotected
24228 (replace-match "\\1 \\3")
24229 (goto-char (match-beginning 0))))
24232 ;; Normalize links: Convert angle and plain links into bracket links
24233 ;; Expand link abbreviations
24234 (goto-char (point-min))
24235 (while (re-search-forward re-plain-link nil t)
24236 (goto-char (1- (match-end 0)))
24237 (org-if-unprotected
24238 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24239 ":" (match-string 3) "]]")))
24240 ;; added 'org-link face to links
24241 (put-text-property 0 (length s) 'face 'org-link s)
24242 (replace-match s t t))))
24243 (goto-char (point-min))
24244 (while (re-search-forward re-angle-link nil t)
24245 (goto-char (1- (match-end 0)))
24246 (org-if-unprotected
24247 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24248 ":" (match-string 3) "]]")))
24249 (put-text-property 0 (length s) 'face 'org-link s)
24250 (replace-match s t t))))
24251 (goto-char (point-min))
24252 (while (re-search-forward org-bracket-link-regexp nil t)
24253 (org-if-unprotected
24254 (let* ((s (concat "[[" (setq xx (save-match-data
24255 (org-link-expand-abbrev (match-string 1))))
24257 (if (match-end 3)
24258 (match-string 2)
24259 (concat "[" xx "]"))
24260 "]")))
24261 (put-text-property 0 (length s) 'face 'org-link s)
24262 (replace-match s t t))))
24264 ;; Find multiline emphasis and put them into single line
24265 (when (plist-get parameters :emph-multiline)
24266 (goto-char (point-min))
24267 (while (re-search-forward org-emph-re nil t)
24268 (if (not (= (char-after (match-beginning 3))
24269 (char-after (match-beginning 4))))
24270 (org-if-unprotected
24271 (subst-char-in-region (match-beginning 0) (match-end 0)
24272 ?\n ?\ t)
24273 (goto-char (1- (match-end 0))))
24274 (goto-char (1+ (match-beginning 0))))))
24276 (setq rtn (buffer-string)))
24277 (kill-buffer " org-mode-tmp")
24278 rtn))
24280 (defun org-export-grab-title-from-buffer ()
24281 "Get a title for the current document, from looking at the buffer."
24282 (let ((inhibit-read-only t))
24283 (save-excursion
24284 (goto-char (point-min))
24285 (let ((end (save-excursion (outline-next-heading) (point))))
24286 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24287 ;; Mark the line so that it will not be exported as normal text.
24288 (org-unmodified
24289 (add-text-properties (match-beginning 0) (match-end 0)
24290 (list :org-license-to-kill t)))
24291 ;; Return the title string
24292 (org-trim (match-string 0)))))))
24294 (defun org-export-get-title-from-subtree ()
24295 "Return subtree title and exclude it from export."
24296 (let (title (m (mark)))
24297 (save-excursion
24298 (goto-char (region-beginning))
24299 (when (and (org-at-heading-p)
24300 (>= (org-end-of-subtree t t) (region-end)))
24301 ;; This is a subtree, we take the title from the first heading
24302 (goto-char (region-beginning))
24303 (looking-at org-todo-line-regexp)
24304 (setq title (match-string 3))
24305 (org-unmodified
24306 (add-text-properties (point) (1+ (point-at-eol))
24307 (list :org-license-to-kill t)))))
24308 title))
24310 (defun org-solidify-link-text (s &optional alist)
24311 "Take link text and make a safe target out of it."
24312 (save-match-data
24313 (let* ((rtn
24314 (mapconcat
24315 'identity
24316 (org-split-string s "[ \t\r\n]+") "--"))
24317 (a (assoc rtn alist)))
24318 (or (cdr a) rtn))))
24320 (defun org-get-min-level (lines)
24321 "Get the minimum level in LINES."
24322 (let ((re "^\\(\\*+\\) ") l min)
24323 (catch 'exit
24324 (while (setq l (pop lines))
24325 (if (string-match re l)
24326 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24327 1)))
24329 ;; Variable holding the vector with section numbers
24330 (defvar org-section-numbers (make-vector org-level-max 0))
24332 (defun org-init-section-numbers ()
24333 "Initialize the vector for the section numbers."
24334 (let* ((level -1)
24335 (numbers (nreverse (org-split-string "" "\\.")))
24336 (depth (1- (length org-section-numbers)))
24337 (i depth) number-string)
24338 (while (>= i 0)
24339 (if (> i level)
24340 (aset org-section-numbers i 0)
24341 (setq number-string (or (car numbers) "0"))
24342 (if (string-match "\\`[A-Z]\\'" number-string)
24343 (aset org-section-numbers i
24344 (- (string-to-char number-string) ?A -1))
24345 (aset org-section-numbers i (string-to-number number-string)))
24346 (pop numbers))
24347 (setq i (1- i)))))
24349 (defun org-section-number (&optional level)
24350 "Return a string with the current section number.
24351 When LEVEL is non-nil, increase section numbers on that level."
24352 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24353 (when level
24354 (when (> level -1)
24355 (aset org-section-numbers
24356 level (1+ (aref org-section-numbers level))))
24357 (setq idx (1+ level))
24358 (while (<= idx depth)
24359 (if (not (= idx 1))
24360 (aset org-section-numbers idx 0))
24361 (setq idx (1+ idx))))
24362 (setq idx 0)
24363 (while (<= idx depth)
24364 (setq n (aref org-section-numbers idx))
24365 (setq string (concat string (if (not (string= string "")) "." "")
24366 (int-to-string n)))
24367 (setq idx (1+ idx)))
24368 (save-match-data
24369 (if (string-match "\\`\\([@0]\\.\\)+" string)
24370 (setq string (replace-match "" t nil string)))
24371 (if (string-match "\\(\\.0\\)+\\'" string)
24372 (setq string (replace-match "" t nil string))))
24373 string))
24375 ;;; ASCII export
24377 (defvar org-last-level nil) ; dynamically scoped variable
24378 (defvar org-min-level nil) ; dynamically scoped variable
24379 (defvar org-levels-open nil) ; dynamically scoped parameter
24380 (defvar org-ascii-current-indentation nil) ; For communication
24382 (defun org-export-as-ascii (arg)
24383 "Export the outline as a pretty ASCII file.
24384 If there is an active region, export only the region.
24385 The prefix ARG specifies how many levels of the outline should become
24386 underlined headlines. The default is 3."
24387 (interactive "P")
24388 (setq-default org-todo-line-regexp org-todo-line-regexp)
24389 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24390 (org-infile-export-plist)))
24391 (region-p (org-region-active-p))
24392 (subtree-p
24393 (when region-p
24394 (save-excursion
24395 (goto-char (region-beginning))
24396 (and (org-at-heading-p)
24397 (>= (org-end-of-subtree t t) (region-end))))))
24398 (custom-times org-display-custom-times)
24399 (org-ascii-current-indentation '(0 . 0))
24400 (level 0) line txt
24401 (umax nil)
24402 (umax-toc nil)
24403 (case-fold-search nil)
24404 (filename (concat (file-name-as-directory
24405 (org-export-directory :ascii opt-plist))
24406 (file-name-sans-extension
24407 (or (and subtree-p
24408 (org-entry-get (region-beginning)
24409 "EXPORT_FILE_NAME" t))
24410 (file-name-nondirectory buffer-file-name)))
24411 ".txt"))
24412 (filename (if (equal (file-truename filename)
24413 (file-truename buffer-file-name))
24414 (concat filename ".txt")
24415 filename))
24416 (buffer (find-file-noselect filename))
24417 (org-levels-open (make-vector org-level-max nil))
24418 (odd org-odd-levels-only)
24419 (date (plist-get opt-plist :date))
24420 (author (plist-get opt-plist :author))
24421 (title (or (and subtree-p (org-export-get-title-from-subtree))
24422 (plist-get opt-plist :title)
24423 (and (not
24424 (plist-get opt-plist :skip-before-1st-heading))
24425 (org-export-grab-title-from-buffer))
24426 (file-name-sans-extension
24427 (file-name-nondirectory buffer-file-name))))
24428 (email (plist-get opt-plist :email))
24429 (language (plist-get opt-plist :language))
24430 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24431 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24432 (todo nil)
24433 (lang-words nil)
24434 (region
24435 (buffer-substring
24436 (if (org-region-active-p) (region-beginning) (point-min))
24437 (if (org-region-active-p) (region-end) (point-max))))
24438 (lines (org-split-string
24439 (org-cleaned-string-for-export
24440 region
24441 :for-ascii t
24442 :skip-before-1st-heading
24443 (plist-get opt-plist :skip-before-1st-heading)
24444 :drawers (plist-get opt-plist :drawers)
24445 :verbatim-multiline t
24446 :archived-trees
24447 (plist-get opt-plist :archived-trees)
24448 :add-text (plist-get opt-plist :text))
24449 "\n"))
24450 thetoc have-headings first-heading-pos
24451 table-open table-buffer)
24453 (let ((inhibit-read-only t))
24454 (org-unmodified
24455 (remove-text-properties (point-min) (point-max)
24456 '(:org-license-to-kill t))))
24458 (setq org-min-level (org-get-min-level lines))
24459 (setq org-last-level org-min-level)
24460 (org-init-section-numbers)
24462 (find-file-noselect filename)
24464 (setq lang-words (or (assoc language org-export-language-setup)
24465 (assoc "en" org-export-language-setup)))
24466 (switch-to-buffer-other-window buffer)
24467 (erase-buffer)
24468 (fundamental-mode)
24469 ;; create local variables for all options, to make sure all called
24470 ;; functions get the correct information
24471 (mapc (lambda (x)
24472 (set (make-local-variable (cdr x))
24473 (plist-get opt-plist (car x))))
24474 org-export-plist-vars)
24475 (org-set-local 'org-odd-levels-only odd)
24476 (setq umax (if arg (prefix-numeric-value arg)
24477 org-export-headline-levels))
24478 (setq umax-toc (if (integerp org-export-with-toc)
24479 (min org-export-with-toc umax)
24480 umax))
24482 ;; File header
24483 (if title (org-insert-centered title ?=))
24484 (insert "\n")
24485 (if (and (or author email)
24486 org-export-author-info)
24487 (insert (concat (nth 1 lang-words) ": " (or author "")
24488 (if email (concat " <" email ">") "")
24489 "\n")))
24491 (cond
24492 ((and date (string-match "%" date))
24493 (setq date (format-time-string date (current-time))))
24494 (date)
24495 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24497 (if (and date org-export-time-stamp-file)
24498 (insert (concat (nth 2 lang-words) ": " date"\n")))
24500 (insert "\n\n")
24502 (if org-export-with-toc
24503 (progn
24504 (push (concat (nth 3 lang-words) "\n") thetoc)
24505 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24506 (mapc '(lambda (line)
24507 (if (string-match org-todo-line-regexp
24508 line)
24509 ;; This is a headline
24510 (progn
24511 (setq have-headings t)
24512 (setq level (- (match-end 1) (match-beginning 1))
24513 level (org-tr-level level)
24514 txt (match-string 3 line)
24515 todo
24516 (or (and org-export-mark-todo-in-toc
24517 (match-beginning 2)
24518 (not (member (match-string 2 line)
24519 org-done-keywords)))
24520 ; TODO, not DONE
24521 (and org-export-mark-todo-in-toc
24522 (= level umax-toc)
24523 (org-search-todo-below
24524 line lines level))))
24525 (setq txt (org-html-expand-for-ascii txt))
24527 (while (string-match org-bracket-link-regexp txt)
24528 (setq txt
24529 (replace-match
24530 (match-string (if (match-end 2) 3 1) txt)
24531 t t txt)))
24533 (if (and (memq org-export-with-tags '(not-in-toc nil))
24534 (string-match
24535 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24536 txt))
24537 (setq txt (replace-match "" t t txt)))
24538 (if (string-match quote-re0 txt)
24539 (setq txt (replace-match "" t t txt)))
24541 (if org-export-with-section-numbers
24542 (setq txt (concat (org-section-number level)
24543 " " txt)))
24544 (if (<= level umax-toc)
24545 (progn
24546 (push
24547 (concat
24548 (make-string
24549 (* (max 0 (- level org-min-level)) 4) ?\ )
24550 (format (if todo "%s (*)\n" "%s\n") txt))
24551 thetoc)
24552 (setq org-last-level level))
24553 ))))
24554 lines)
24555 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24557 (org-init-section-numbers)
24558 (while (setq line (pop lines))
24559 ;; Remove the quoted HTML tags.
24560 (setq line (org-html-expand-for-ascii line))
24561 ;; Remove targets
24562 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24563 (setq line (replace-match "" t t line)))
24564 ;; Replace internal links
24565 (while (string-match org-bracket-link-regexp line)
24566 (setq line (replace-match
24567 (if (match-end 3) "[\\3]" "[\\1]")
24568 t nil line)))
24569 (when custom-times
24570 (setq line (org-translate-time line)))
24571 (cond
24572 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24573 ;; a Headline
24574 (setq first-heading-pos (or first-heading-pos (point)))
24575 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24576 txt (match-string 2 line))
24577 (org-ascii-level-start level txt umax lines))
24579 ((and org-export-with-tables
24580 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24581 (if (not table-open)
24582 ;; New table starts
24583 (setq table-open t table-buffer nil))
24584 ;; Accumulate lines
24585 (setq table-buffer (cons line table-buffer))
24586 (when (or (not lines)
24587 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24588 (car lines))))
24589 (setq table-open nil
24590 table-buffer (nreverse table-buffer))
24591 (insert (mapconcat
24592 (lambda (x)
24593 (org-fix-indentation x org-ascii-current-indentation))
24594 (org-format-table-ascii table-buffer)
24595 "\n") "\n")))
24597 (setq line (org-fix-indentation line org-ascii-current-indentation))
24598 (if (and org-export-with-fixed-width
24599 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24600 (setq line (replace-match "\\1" nil nil line)))
24601 (insert line "\n"))))
24603 (normal-mode)
24605 ;; insert the table of contents
24606 (when thetoc
24607 (goto-char (point-min))
24608 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24609 (progn
24610 (goto-char (match-beginning 0))
24611 (replace-match ""))
24612 (goto-char first-heading-pos))
24613 (mapc 'insert thetoc)
24614 (or (looking-at "[ \t]*\n[ \t]*\n")
24615 (insert "\n\n")))
24617 ;; Convert whitespace place holders
24618 (goto-char (point-min))
24619 (let (beg end)
24620 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24621 (setq end (next-single-property-change beg 'org-whitespace))
24622 (goto-char beg)
24623 (delete-region beg end)
24624 (insert (make-string (- end beg) ?\ ))))
24626 (save-buffer)
24627 ;; remove display and invisible chars
24628 (let (beg end)
24629 (goto-char (point-min))
24630 (while (setq beg (next-single-property-change (point) 'display))
24631 (setq end (next-single-property-change beg 'display))
24632 (delete-region beg end)
24633 (goto-char beg)
24634 (insert "=>"))
24635 (goto-char (point-min))
24636 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24637 (setq end (next-single-property-change beg 'org-cwidth))
24638 (delete-region beg end)
24639 (goto-char beg)))
24640 (goto-char (point-min))))
24642 (defun org-export-ascii-clean-string ()
24643 "Do extra work for ASCII export"
24644 (goto-char (point-min))
24645 (while (re-search-forward org-verbatim-re nil t)
24646 (goto-char (match-end 2))
24647 (backward-delete-char 1) (insert "'")
24648 (goto-char (match-beginning 2))
24649 (delete-char 1) (insert "`")
24650 (goto-char (match-end 2))))
24652 (defun org-search-todo-below (line lines level)
24653 "Search the subtree below LINE for any TODO entries."
24654 (let ((rest (cdr (memq line lines)))
24655 (re org-todo-line-regexp)
24656 line lv todo)
24657 (catch 'exit
24658 (while (setq line (pop rest))
24659 (if (string-match re line)
24660 (progn
24661 (setq lv (- (match-end 1) (match-beginning 1))
24662 todo (and (match-beginning 2)
24663 (not (member (match-string 2 line)
24664 org-done-keywords))))
24665 ; TODO, not DONE
24666 (if (<= lv level) (throw 'exit nil))
24667 (if todo (throw 'exit t))))))))
24669 (defun org-html-expand-for-ascii (line)
24670 "Handle quoted HTML for ASCII export."
24671 (if org-export-html-expand
24672 (while (string-match "@<[^<>\n]*>" line)
24673 ;; We just remove the tags for now.
24674 (setq line (replace-match "" nil nil line))))
24675 line)
24677 (defun org-insert-centered (s &optional underline)
24678 "Insert the string S centered and underline it with character UNDERLINE."
24679 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24680 (insert (make-string ind ?\ ) s "\n")
24681 (if underline
24682 (insert (make-string ind ?\ )
24683 (make-string (string-width s) underline)
24684 "\n"))))
24686 (defun org-ascii-level-start (level title umax &optional lines)
24687 "Insert a new level in ASCII export."
24688 (let (char (n (- level umax 1)) (ind 0))
24689 (if (> level umax)
24690 (progn
24691 (insert (make-string (* 2 n) ?\ )
24692 (char-to-string (nth (% n (length org-export-ascii-bullets))
24693 org-export-ascii-bullets))
24694 " " title "\n")
24695 ;; find the indentation of the next non-empty line
24696 (catch 'stop
24697 (while lines
24698 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24699 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24700 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24701 (pop lines)))
24702 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24703 (if (or (not (equal (char-before) ?\n))
24704 (not (equal (char-before (1- (point))) ?\n)))
24705 (insert "\n"))
24706 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24707 (unless org-export-with-tags
24708 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24709 (setq title (replace-match "" t t title))))
24710 (if org-export-with-section-numbers
24711 (setq title (concat (org-section-number level) " " title)))
24712 (insert title "\n" (make-string (string-width title) char) "\n")
24713 (setq org-ascii-current-indentation '(0 . 0)))))
24715 (defun org-export-visible (type arg)
24716 "Create a copy of the visible part of the current buffer, and export it.
24717 The copy is created in a temporary buffer and removed after use.
24718 TYPE is the final key (as a string) that also select the export command in
24719 the `C-c C-e' export dispatcher.
24720 As a special case, if the you type SPC at the prompt, the temporary
24721 org-mode file will not be removed but presented to you so that you can
24722 continue to use it. The prefix arg ARG is passed through to the exporting
24723 command."
24724 (interactive
24725 (list (progn
24726 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24727 (read-char-exclusive))
24728 current-prefix-arg))
24729 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24730 (error "Invalid export key"))
24731 (let* ((binding (cdr (assoc type
24732 '((?a . org-export-as-ascii)
24733 (?\C-a . org-export-as-ascii)
24734 (?b . org-export-as-html-and-open)
24735 (?\C-b . org-export-as-html-and-open)
24736 (?h . org-export-as-html)
24737 (?H . org-export-as-html-to-buffer)
24738 (?R . org-export-region-as-html)
24739 (?x . org-export-as-xoxo)))))
24740 (keepp (equal type ?\ ))
24741 (file buffer-file-name)
24742 (buffer (get-buffer-create "*Org Export Visible*"))
24743 s e)
24744 ;; Need to hack the drawers here.
24745 (save-excursion
24746 (goto-char (point-min))
24747 (while (re-search-forward org-drawer-regexp nil t)
24748 (goto-char (match-beginning 1))
24749 (or (org-invisible-p) (org-flag-drawer nil))))
24750 (with-current-buffer buffer (erase-buffer))
24751 (save-excursion
24752 (setq s (goto-char (point-min)))
24753 (while (not (= (point) (point-max)))
24754 (goto-char (org-find-invisible))
24755 (append-to-buffer buffer s (point))
24756 (setq s (goto-char (org-find-visible))))
24757 (org-cycle-hide-drawers 'all)
24758 (goto-char (point-min))
24759 (unless keepp
24760 ;; Copy all comment lines to the end, to make sure #+ settings are
24761 ;; still available for the second export step. Kind of a hack, but
24762 ;; does do the trick.
24763 (if (looking-at "#[^\r\n]*")
24764 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24765 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24766 (append-to-buffer buffer (1+ (match-beginning 0))
24767 (min (point-max) (1+ (match-end 0))))))
24768 (set-buffer buffer)
24769 (let ((buffer-file-name file)
24770 (org-inhibit-startup t))
24771 (org-mode)
24772 (show-all)
24773 (unless keepp (funcall binding arg))))
24774 (if (not keepp)
24775 (kill-buffer buffer)
24776 (switch-to-buffer-other-window buffer)
24777 (goto-char (point-min)))))
24779 (defun org-find-visible ()
24780 (let ((s (point)))
24781 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24782 (get-char-property s 'invisible)))
24784 (defun org-find-invisible ()
24785 (let ((s (point)))
24786 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24787 (not (get-char-property s 'invisible))))
24790 ;;; HTML export
24792 (defun org-get-current-options ()
24793 "Return a string with current options as keyword options.
24794 Does include HTML export options as well as TODO and CATEGORY stuff."
24795 (format
24796 "#+TITLE: %s
24797 #+AUTHOR: %s
24798 #+EMAIL: %s
24799 #+LANGUAGE: %s
24800 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24801 #+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
24802 #+CATEGORY: %s
24803 #+SEQ_TODO: %s
24804 #+TYP_TODO: %s
24805 #+PRIORITIES: %c %c %c
24806 #+DRAWERS: %s
24807 #+STARTUP: %s %s %s %s %s
24808 #+TAGS: %s
24809 #+ARCHIVE: %s
24810 #+LINK: %s
24812 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24813 org-export-headline-levels
24814 org-export-with-section-numbers
24815 org-export-with-toc
24816 org-export-preserve-breaks
24817 org-export-html-expand
24818 org-export-with-fixed-width
24819 org-export-with-tables
24820 org-export-with-sub-superscripts
24821 org-export-with-special-strings
24822 org-export-with-footnotes
24823 org-export-with-emphasize
24824 org-export-with-TeX-macros
24825 org-export-with-LaTeX-fragments
24826 org-export-skip-text-before-1st-heading
24827 org-export-with-drawers
24828 org-export-with-tags
24829 (file-name-nondirectory buffer-file-name)
24830 "TODO FEEDBACK VERIFY DONE"
24831 "Me Jason Marie DONE"
24832 org-highest-priority org-lowest-priority org-default-priority
24833 (mapconcat 'identity org-drawers " ")
24834 (cdr (assoc org-startup-folded
24835 '((nil . "showall") (t . "overview") (content . "content"))))
24836 (if org-odd-levels-only "odd" "oddeven")
24837 (if org-hide-leading-stars "hidestars" "showstars")
24838 (if org-startup-align-all-tables "align" "noalign")
24839 (cond ((eq org-log-done t) "logdone")
24840 ((equal org-log-done 'note) "lognotedone")
24841 ((not org-log-done) "nologdone"))
24842 (or (mapconcat (lambda (x)
24843 (cond
24844 ((equal '(:startgroup) x) "{")
24845 ((equal '(:endgroup) x) "}")
24846 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24847 (t (car x))))
24848 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24849 org-archive-location
24850 "org file:~/org/%s.org"
24853 (defun org-insert-export-options-template ()
24854 "Insert into the buffer a template with information for exporting."
24855 (interactive)
24856 (if (not (bolp)) (newline))
24857 (let ((s (org-get-current-options)))
24858 (and (string-match "#\\+CATEGORY" s)
24859 (setq s (substring s 0 (match-beginning 0))))
24860 (insert s)))
24862 (defun org-toggle-fixed-width-section (arg)
24863 "Toggle the fixed-width export.
24864 If there is no active region, the QUOTE keyword at the current headline is
24865 inserted or removed. When present, it causes the text between this headline
24866 and the next to be exported as fixed-width text, and unmodified.
24867 If there is an active region, this command adds or removes a colon as the
24868 first character of this line. If the first character of a line is a colon,
24869 this line is also exported in fixed-width font."
24870 (interactive "P")
24871 (let* ((cc 0)
24872 (regionp (org-region-active-p))
24873 (beg (if regionp (region-beginning) (point)))
24874 (end (if regionp (region-end)))
24875 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24876 (case-fold-search nil)
24877 (re "[ \t]*\\(:\\)")
24878 off)
24879 (if regionp
24880 (save-excursion
24881 (goto-char beg)
24882 (setq cc (current-column))
24883 (beginning-of-line 1)
24884 (setq off (looking-at re))
24885 (while (> nlines 0)
24886 (setq nlines (1- nlines))
24887 (beginning-of-line 1)
24888 (cond
24889 (arg
24890 (move-to-column cc t)
24891 (insert ":\n")
24892 (forward-line -1))
24893 ((and off (looking-at re))
24894 (replace-match "" t t nil 1))
24895 ((not off) (move-to-column cc t) (insert ":")))
24896 (forward-line 1)))
24897 (save-excursion
24898 (org-back-to-heading)
24899 (if (looking-at (concat outline-regexp
24900 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24901 (replace-match "" t t nil 1)
24902 (if (looking-at outline-regexp)
24903 (progn
24904 (goto-char (match-end 0))
24905 (insert org-quote-string " "))))))))
24907 (defun org-export-as-html-and-open (arg)
24908 "Export the outline as HTML and immediately open it with a browser.
24909 If there is an active region, export only the region.
24910 The prefix ARG specifies how many levels of the outline should become
24911 headlines. The default is 3. Lower levels will become bulleted lists."
24912 (interactive "P")
24913 (org-export-as-html arg 'hidden)
24914 (org-open-file buffer-file-name))
24916 (defun org-export-as-html-batch ()
24917 "Call `org-export-as-html', may be used in batch processing as
24918 emacs --batch
24919 --load=$HOME/lib/emacs/org.el
24920 --eval \"(setq org-export-headline-levels 2)\"
24921 --visit=MyFile --funcall org-export-as-html-batch"
24922 (org-export-as-html org-export-headline-levels 'hidden))
24924 (defun org-export-as-html-to-buffer (arg)
24925 "Call `org-exort-as-html` with output to a temporary buffer.
24926 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24927 (interactive "P")
24928 (org-export-as-html arg nil nil "*Org HTML Export*")
24929 (switch-to-buffer-other-window "*Org HTML Export*"))
24931 (defun org-replace-region-by-html (beg end)
24932 "Assume the current region has org-mode syntax, and convert it to HTML.
24933 This can be used in any buffer. For example, you could write an
24934 itemized list in org-mode syntax in an HTML buffer and then use this
24935 command to convert it."
24936 (interactive "r")
24937 (let (reg html buf pop-up-frames)
24938 (save-window-excursion
24939 (if (org-mode-p)
24940 (setq html (org-export-region-as-html
24941 beg end t 'string))
24942 (setq reg (buffer-substring beg end)
24943 buf (get-buffer-create "*Org tmp*"))
24944 (with-current-buffer buf
24945 (erase-buffer)
24946 (insert reg)
24947 (org-mode)
24948 (setq html (org-export-region-as-html
24949 (point-min) (point-max) t 'string)))
24950 (kill-buffer buf)))
24951 (delete-region beg end)
24952 (insert html)))
24954 (defun org-export-region-as-html (beg end &optional body-only buffer)
24955 "Convert region from BEG to END in org-mode buffer to HTML.
24956 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24957 contents, and only produce the region of converted text, useful for
24958 cut-and-paste operations.
24959 If BUFFER is a buffer or a string, use/create that buffer as a target
24960 of the converted HTML. If BUFFER is the symbol `string', return the
24961 produced HTML as a string and leave not buffer behind. For example,
24962 a Lisp program could call this function in the following way:
24964 (setq html (org-export-region-as-html beg end t 'string))
24966 When called interactively, the output buffer is selected, and shown
24967 in a window. A non-interactive call will only retunr the buffer."
24968 (interactive "r\nP")
24969 (when (interactive-p)
24970 (setq buffer "*Org HTML Export*"))
24971 (let ((transient-mark-mode t) (zmacs-regions t)
24972 rtn)
24973 (goto-char end)
24974 (set-mark (point)) ;; to activate the region
24975 (goto-char beg)
24976 (setq rtn (org-export-as-html
24977 nil nil nil
24978 buffer body-only))
24979 (if (fboundp 'deactivate-mark) (deactivate-mark))
24980 (if (and (interactive-p) (bufferp rtn))
24981 (switch-to-buffer-other-window rtn)
24982 rtn)))
24984 (defvar html-table-tag nil) ; dynamically scoped into this.
24985 (defun org-export-as-html (arg &optional hidden ext-plist
24986 to-buffer body-only)
24987 "Export the outline as a pretty HTML file.
24988 If there is an active region, export only the region. The prefix
24989 ARG specifies how many levels of the outline should become
24990 headlines. The default is 3. Lower levels will become bulleted
24991 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24992 EXT-PLIST is a property list with external parameters overriding
24993 org-mode's default settings, but still inferior to file-local
24994 settings. When TO-BUFFER is non-nil, create a buffer with that
24995 name and export to that buffer. If TO-BUFFER is the symbol `string',
24996 don't leave any buffer behind but just return the resulting HTML as
24997 a string. When BODY-ONLY is set, don't produce the file header and footer,
24998 simply return the content of <body>...</body>, without even
24999 the body tags themselves."
25000 (interactive "P")
25002 ;; Make sure we have a file name when we need it.
25003 (when (and (not (or to-buffer body-only))
25004 (not buffer-file-name))
25005 (if (buffer-base-buffer)
25006 (org-set-local 'buffer-file-name
25007 (with-current-buffer (buffer-base-buffer)
25008 buffer-file-name))
25009 (error "Need a file name to be able to export.")))
25011 (message "Exporting...")
25012 (setq-default org-todo-line-regexp org-todo-line-regexp)
25013 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25014 (setq-default org-done-keywords org-done-keywords)
25015 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25016 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25017 ext-plist
25018 (org-infile-export-plist)))
25020 (style (plist-get opt-plist :style))
25021 (html-extension (plist-get opt-plist :html-extension))
25022 (link-validate (plist-get opt-plist :link-validation-function))
25023 valid thetoc have-headings first-heading-pos
25024 (odd org-odd-levels-only)
25025 (region-p (org-region-active-p))
25026 (subtree-p
25027 (when region-p
25028 (save-excursion
25029 (goto-char (region-beginning))
25030 (and (org-at-heading-p)
25031 (>= (org-end-of-subtree t t) (region-end))))))
25032 ;; The following two are dynamically scoped into other
25033 ;; routines below.
25034 (org-current-export-dir (org-export-directory :html opt-plist))
25035 (org-current-export-file buffer-file-name)
25036 (level 0) (line "") (origline "") txt todo
25037 (umax nil)
25038 (umax-toc nil)
25039 (filename (if to-buffer nil
25040 (expand-file-name
25041 (concat
25042 (file-name-sans-extension
25043 (or (and subtree-p
25044 (org-entry-get (region-beginning)
25045 "EXPORT_FILE_NAME" t))
25046 (file-name-nondirectory buffer-file-name)))
25047 "." html-extension)
25048 (file-name-as-directory
25049 (org-export-directory :html opt-plist)))))
25050 (current-dir (if buffer-file-name
25051 (file-name-directory buffer-file-name)
25052 default-directory))
25053 (buffer (if to-buffer
25054 (cond
25055 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25056 (t (get-buffer-create to-buffer)))
25057 (find-file-noselect filename)))
25058 (org-levels-open (make-vector org-level-max nil))
25059 (date (plist-get opt-plist :date))
25060 (author (plist-get opt-plist :author))
25061 (title (or (and subtree-p (org-export-get-title-from-subtree))
25062 (plist-get opt-plist :title)
25063 (and (not
25064 (plist-get opt-plist :skip-before-1st-heading))
25065 (org-export-grab-title-from-buffer))
25066 (and buffer-file-name
25067 (file-name-sans-extension
25068 (file-name-nondirectory buffer-file-name)))
25069 "UNTITLED"))
25070 (html-table-tag (plist-get opt-plist :html-table-tag))
25071 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25072 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25073 (inquote nil)
25074 (infixed nil)
25075 (in-local-list nil)
25076 (local-list-num nil)
25077 (local-list-indent nil)
25078 (llt org-plain-list-ordered-item-terminator)
25079 (email (plist-get opt-plist :email))
25080 (language (plist-get opt-plist :language))
25081 (lang-words nil)
25082 (target-alist nil) tg
25083 (head-count 0) cnt
25084 (start 0)
25085 (coding-system (and (boundp 'buffer-file-coding-system)
25086 buffer-file-coding-system))
25087 (coding-system-for-write (or org-export-html-coding-system
25088 coding-system))
25089 (save-buffer-coding-system (or org-export-html-coding-system
25090 coding-system))
25091 (charset (and coding-system-for-write
25092 (fboundp 'coding-system-get)
25093 (coding-system-get coding-system-for-write
25094 'mime-charset)))
25095 (region
25096 (buffer-substring
25097 (if region-p (region-beginning) (point-min))
25098 (if region-p (region-end) (point-max))))
25099 (lines
25100 (org-split-string
25101 (org-cleaned-string-for-export
25102 region
25103 :emph-multiline t
25104 :for-html t
25105 :skip-before-1st-heading
25106 (plist-get opt-plist :skip-before-1st-heading)
25107 :drawers (plist-get opt-plist :drawers)
25108 :archived-trees
25109 (plist-get opt-plist :archived-trees)
25110 :add-text
25111 (plist-get opt-plist :text)
25112 :LaTeX-fragments
25113 (plist-get opt-plist :LaTeX-fragments))
25114 "[\r\n]"))
25115 table-open type
25116 table-buffer table-orig-buffer
25117 ind start-is-num starter didclose
25118 rpl path desc descp desc1 desc2 link
25121 (let ((inhibit-read-only t))
25122 (org-unmodified
25123 (remove-text-properties (point-min) (point-max)
25124 '(:org-license-to-kill t))))
25126 (message "Exporting...")
25128 (setq org-min-level (org-get-min-level lines))
25129 (setq org-last-level org-min-level)
25130 (org-init-section-numbers)
25132 (cond
25133 ((and date (string-match "%" date))
25134 (setq date (format-time-string date (current-time))))
25135 (date)
25136 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25138 ;; Get the language-dependent settings
25139 (setq lang-words (or (assoc language org-export-language-setup)
25140 (assoc "en" org-export-language-setup)))
25142 ;; Switch to the output buffer
25143 (set-buffer buffer)
25144 (let ((inhibit-read-only t)) (erase-buffer))
25145 (fundamental-mode)
25147 (and (fboundp 'set-buffer-file-coding-system)
25148 (set-buffer-file-coding-system coding-system-for-write))
25150 (let ((case-fold-search nil)
25151 (org-odd-levels-only odd))
25152 ;; create local variables for all options, to make sure all called
25153 ;; functions get the correct information
25154 (mapc (lambda (x)
25155 (set (make-local-variable (cdr x))
25156 (plist-get opt-plist (car x))))
25157 org-export-plist-vars)
25158 (setq umax (if arg (prefix-numeric-value arg)
25159 org-export-headline-levels))
25160 (setq umax-toc (if (integerp org-export-with-toc)
25161 (min org-export-with-toc umax)
25162 umax))
25163 (unless body-only
25164 ;; File header
25165 (insert (format
25166 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25167 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25168 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25169 lang=\"%s\" xml:lang=\"%s\">
25170 <head>
25171 <title>%s</title>
25172 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25173 <meta name=\"generator\" content=\"Org-mode\"/>
25174 <meta name=\"generated\" content=\"%s\"/>
25175 <meta name=\"author\" content=\"%s\"/>
25177 </head><body>
25179 language language (org-html-expand title)
25180 (or charset "iso-8859-1") date author style))
25182 (insert (or (plist-get opt-plist :preamble) ""))
25184 (when (plist-get opt-plist :auto-preamble)
25185 (if title (insert (format org-export-html-title-format
25186 (org-html-expand title))))))
25188 (if (and org-export-with-toc (not body-only))
25189 (progn
25190 (push (format "<h%d>%s</h%d>\n"
25191 org-export-html-toplevel-hlevel
25192 (nth 3 lang-words)
25193 org-export-html-toplevel-hlevel)
25194 thetoc)
25195 (push "<ul>\n<li>" thetoc)
25196 (setq lines
25197 (mapcar '(lambda (line)
25198 (if (string-match org-todo-line-regexp line)
25199 ;; This is a headline
25200 (progn
25201 (setq have-headings t)
25202 (setq level (- (match-end 1) (match-beginning 1))
25203 level (org-tr-level level)
25204 txt (save-match-data
25205 (org-html-expand
25206 (org-export-cleanup-toc-line
25207 (match-string 3 line))))
25208 todo
25209 (or (and org-export-mark-todo-in-toc
25210 (match-beginning 2)
25211 (not (member (match-string 2 line)
25212 org-done-keywords)))
25213 ; TODO, not DONE
25214 (and org-export-mark-todo-in-toc
25215 (= level umax-toc)
25216 (org-search-todo-below
25217 line lines level))))
25218 (if (string-match
25219 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25220 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25221 (if (string-match quote-re0 txt)
25222 (setq txt (replace-match "" t t txt)))
25223 (if org-export-with-section-numbers
25224 (setq txt (concat (org-section-number level)
25225 " " txt)))
25226 (if (<= level (max umax umax-toc))
25227 (setq head-count (+ head-count 1)))
25228 (if (<= level umax-toc)
25229 (progn
25230 (if (> level org-last-level)
25231 (progn
25232 (setq cnt (- level org-last-level))
25233 (while (>= (setq cnt (1- cnt)) 0)
25234 (push "\n<ul>\n<li>" thetoc))
25235 (push "\n" thetoc)))
25236 (if (< level org-last-level)
25237 (progn
25238 (setq cnt (- org-last-level level))
25239 (while (>= (setq cnt (1- cnt)) 0)
25240 (push "</li>\n</ul>" thetoc))
25241 (push "\n" thetoc)))
25242 ;; Check for targets
25243 (while (string-match org-target-regexp line)
25244 (setq tg (match-string 1 line)
25245 line (replace-match
25246 (concat "@<span class=\"target\">" tg "@</span> ")
25247 t t line))
25248 (push (cons (org-solidify-link-text tg)
25249 (format "sec-%d" head-count))
25250 target-alist))
25251 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25252 (setq txt (replace-match "" t t txt)))
25253 (push
25254 (format
25255 (if todo
25256 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25257 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25258 head-count txt) thetoc)
25260 (setq org-last-level level))
25262 line)
25263 lines))
25264 (while (> org-last-level (1- org-min-level))
25265 (setq org-last-level (1- org-last-level))
25266 (push "</li>\n</ul>\n" thetoc))
25267 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25269 (setq head-count 0)
25270 (org-init-section-numbers)
25272 (while (setq line (pop lines) origline line)
25273 (catch 'nextline
25275 ;; end of quote section?
25276 (when (and inquote (string-match "^\\*+ " line))
25277 (insert "</pre>\n")
25278 (setq inquote nil))
25279 ;; inside a quote section?
25280 (when inquote
25281 (insert (org-html-protect line) "\n")
25282 (throw 'nextline nil))
25284 ;; verbatim lines
25285 (when (and org-export-with-fixed-width
25286 (string-match "^[ \t]*:\\(.*\\)" line))
25287 (when (not infixed)
25288 (setq infixed t)
25289 (insert "<pre>\n"))
25290 (insert (org-html-protect (match-string 1 line)) "\n")
25291 (when (and lines
25292 (not (string-match "^[ \t]*\\(:.*\\)"
25293 (car lines))))
25294 (setq infixed nil)
25295 (insert "</pre>\n"))
25296 (throw 'nextline nil))
25298 ;; Protected HTML
25299 (when (get-text-property 0 'org-protected line)
25300 (let (par)
25301 (when (re-search-backward
25302 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25303 (setq par (match-string 1))
25304 (replace-match "\\2\n"))
25305 (insert line "\n")
25306 (while (and lines
25307 (or (= (length (car lines)) 0)
25308 (get-text-property 0 'org-protected (car lines))))
25309 (insert (pop lines) "\n"))
25310 (and par (insert "<p>\n")))
25311 (throw 'nextline nil))
25313 ;; Horizontal line
25314 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25315 (insert "\n<hr/>\n")
25316 (throw 'nextline nil))
25318 ;; make targets to anchors
25319 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25320 (cond
25321 ((match-end 2)
25322 (setq line (replace-match
25323 (concat "@<a name=\""
25324 (org-solidify-link-text (match-string 1 line))
25325 "\">\\nbsp@</a>")
25326 t t line)))
25327 ((and org-export-with-toc (equal (string-to-char line) ?*))
25328 (setq line (replace-match
25329 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25330 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25331 t t line)))
25333 (setq line (replace-match
25334 (concat "@<a name=\""
25335 (org-solidify-link-text (match-string 1 line))
25336 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25337 t t line)))))
25339 (setq line (org-html-handle-time-stamps line))
25341 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25342 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25343 ;; Also handle sub_superscripts and checkboxes
25344 (or (string-match org-table-hline-regexp line)
25345 (setq line (org-html-expand line)))
25347 ;; Format the links
25348 (setq start 0)
25349 (while (string-match org-bracket-link-analytic-regexp line start)
25350 (setq start (match-beginning 0))
25351 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25352 (setq path (match-string 3 line))
25353 (setq desc1 (if (match-end 5) (match-string 5 line))
25354 desc2 (if (match-end 2) (concat type ":" path) path)
25355 descp (and desc1 (not (equal desc1 desc2)))
25356 desc (or desc1 desc2))
25357 ;; Make an image out of the description if that is so wanted
25358 (when (and descp (org-file-image-p desc))
25359 (save-match-data
25360 (if (string-match "^file:" desc)
25361 (setq desc (substring desc (match-end 0)))))
25362 (setq desc (concat "<img src=\"" desc "\"/>")))
25363 ;; FIXME: do we need to unescape here somewhere?
25364 (cond
25365 ((equal type "internal")
25366 (setq rpl
25367 (concat
25368 "<a href=\"#"
25369 (org-solidify-link-text
25370 (save-match-data (org-link-unescape path)) target-alist)
25371 "\">" desc "</a>")))
25372 ((member type '("http" "https"))
25373 ;; standard URL, just check if we need to inline an image
25374 (if (and (or (eq t org-export-html-inline-images)
25375 (and org-export-html-inline-images (not descp)))
25376 (org-file-image-p path))
25377 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25378 (setq link (concat type ":" path))
25379 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25380 ((member type '("ftp" "mailto" "news"))
25381 ;; standard URL
25382 (setq link (concat type ":" path))
25383 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25384 ((string= type "file")
25385 ;; FILE link
25386 (let* ((filename path)
25387 (abs-p (file-name-absolute-p filename))
25388 thefile file-is-image-p search)
25389 (save-match-data
25390 (if (string-match "::\\(.*\\)" filename)
25391 (setq search (match-string 1 filename)
25392 filename (replace-match "" t nil filename)))
25393 (setq valid
25394 (if (functionp link-validate)
25395 (funcall link-validate filename current-dir)
25397 (setq file-is-image-p (org-file-image-p filename))
25398 (setq thefile (if abs-p (expand-file-name filename) filename))
25399 (when (and org-export-html-link-org-files-as-html
25400 (string-match "\\.org$" thefile))
25401 (setq thefile (concat (substring thefile 0
25402 (match-beginning 0))
25403 "." html-extension))
25404 (if (and search
25405 ;; make sure this is can be used as target search
25406 (not (string-match "^[0-9]*$" search))
25407 (not (string-match "^\\*" search))
25408 (not (string-match "^/.*/$" search)))
25409 (setq thefile (concat thefile "#"
25410 (org-solidify-link-text
25411 (org-link-unescape search)))))
25412 (when (string-match "^file:" desc)
25413 (setq desc (replace-match "" t t desc))
25414 (if (string-match "\\.org$" desc)
25415 (setq desc (replace-match "" t t desc))))))
25416 (setq rpl (if (and file-is-image-p
25417 (or (eq t org-export-html-inline-images)
25418 (and org-export-html-inline-images
25419 (not descp))))
25420 (concat "<img src=\"" thefile "\"/>")
25421 (concat "<a href=\"" thefile "\">" desc "</a>")))
25422 (if (not valid) (setq rpl desc))))
25423 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25424 (setq rpl (concat "<i>&lt;" type ":"
25425 (save-match-data (org-link-unescape path))
25426 "&gt;</i>"))))
25427 (setq line (replace-match rpl t t line)
25428 start (+ start (length rpl))))
25430 ;; TODO items
25431 (if (and (string-match org-todo-line-regexp line)
25432 (match-beginning 2))
25434 (setq line
25435 (concat (substring line 0 (match-beginning 2))
25436 "<span class=\""
25437 (if (member (match-string 2 line)
25438 org-done-keywords)
25439 "done" "todo")
25440 "\">" (match-string 2 line)
25441 "</span>" (substring line (match-end 2)))))
25443 ;; Does this contain a reference to a footnote?
25444 (when org-export-with-footnotes
25445 (setq start 0)
25446 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25447 (if (get-text-property (match-beginning 2) 'org-protected line)
25448 (setq start (match-end 2))
25449 (let ((n (match-string 2 line)))
25450 (setq line
25451 (replace-match
25452 (format
25453 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25454 (match-string 1 line) n n n)
25455 t t line))))))
25457 (cond
25458 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25459 ;; This is a headline
25460 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25461 txt (match-string 2 line))
25462 (if (string-match quote-re0 txt)
25463 (setq txt (replace-match "" t t txt)))
25464 (if (<= level (max umax umax-toc))
25465 (setq head-count (+ head-count 1)))
25466 (when in-local-list
25467 ;; Close any local lists before inserting a new header line
25468 (while local-list-num
25469 (org-close-li)
25470 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25471 (pop local-list-num))
25472 (setq local-list-indent nil
25473 in-local-list nil))
25474 (setq first-heading-pos (or first-heading-pos (point)))
25475 (org-html-level-start level txt umax
25476 (and org-export-with-toc (<= level umax))
25477 head-count)
25478 ;; QUOTES
25479 (when (string-match quote-re line)
25480 (insert "<pre>")
25481 (setq inquote t)))
25483 ((and org-export-with-tables
25484 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25485 (if (not table-open)
25486 ;; New table starts
25487 (setq table-open t table-buffer nil table-orig-buffer nil))
25488 ;; Accumulate lines
25489 (setq table-buffer (cons line table-buffer)
25490 table-orig-buffer (cons origline table-orig-buffer))
25491 (when (or (not lines)
25492 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25493 (car lines))))
25494 (setq table-open nil
25495 table-buffer (nreverse table-buffer)
25496 table-orig-buffer (nreverse table-orig-buffer))
25497 (org-close-par-maybe)
25498 (insert (org-format-table-html table-buffer table-orig-buffer))))
25500 ;; Normal lines
25501 (when (string-match
25502 (cond
25503 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25504 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25505 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25506 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25507 line)
25508 (setq ind (org-get-string-indentation line)
25509 start-is-num (match-beginning 4)
25510 starter (if (match-beginning 2)
25511 (substring (match-string 2 line) 0 -1))
25512 line (substring line (match-beginning 5)))
25513 (unless (string-match "[^ \t]" line)
25514 ;; empty line. Pretend indentation is large.
25515 (setq ind (if org-empty-line-terminates-plain-lists
25517 (1+ (or (car local-list-indent) 1)))))
25518 (setq didclose nil)
25519 (while (and in-local-list
25520 (or (and (= ind (car local-list-indent))
25521 (not starter))
25522 (< ind (car local-list-indent))))
25523 (setq didclose t)
25524 (org-close-li)
25525 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25526 (pop local-list-num) (pop local-list-indent)
25527 (setq in-local-list local-list-indent))
25528 (cond
25529 ((and starter
25530 (or (not in-local-list)
25531 (> ind (car local-list-indent))))
25532 ;; Start new (level of) list
25533 (org-close-par-maybe)
25534 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25535 (push start-is-num local-list-num)
25536 (push ind local-list-indent)
25537 (setq in-local-list t))
25538 (starter
25539 ;; continue current list
25540 (org-close-li)
25541 (insert "<li>\n"))
25542 (didclose
25543 ;; we did close a list, normal text follows: need <p>
25544 (org-open-par)))
25545 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25546 (setq line
25547 (replace-match
25548 (if (equal (match-string 1 line) "X")
25549 "<b>[X]</b>"
25550 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25551 t t line))))
25553 ;; Empty lines start a new paragraph. If hand-formatted lists
25554 ;; are not fully interpreted, lines starting with "-", "+", "*"
25555 ;; also start a new paragraph.
25556 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25558 ;; Is this the start of a footnote?
25559 (when org-export-with-footnotes
25560 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25561 (org-close-par-maybe)
25562 (let ((n (match-string 1 line)))
25563 (setq line (replace-match
25564 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25566 ;; Check if the line break needs to be conserved
25567 (cond
25568 ((string-match "\\\\\\\\[ \t]*$" line)
25569 (setq line (replace-match "<br/>" t t line)))
25570 (org-export-preserve-breaks
25571 (setq line (concat line "<br/>"))))
25573 (insert line "\n")))))
25575 ;; Properly close all local lists and other lists
25576 (when inquote (insert "</pre>\n"))
25577 (when in-local-list
25578 ;; Close any local lists before inserting a new header line
25579 (while local-list-num
25580 (org-close-li)
25581 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25582 (pop local-list-num))
25583 (setq local-list-indent nil
25584 in-local-list nil))
25585 (org-html-level-start 1 nil umax
25586 (and org-export-with-toc (<= level umax))
25587 head-count)
25589 (unless body-only
25590 (when (plist-get opt-plist :auto-postamble)
25591 (insert "<div id=\"postamble\">")
25592 (when (and org-export-author-info author)
25593 (insert "<p class=\"author\"> "
25594 (nth 1 lang-words) ": " author "\n")
25595 (when email
25596 (if (listp (split-string email ",+ *"))
25597 (mapc (lambda(e)
25598 (insert "<a href=\"mailto:" e "\">&lt;"
25599 e "&gt;</a>\n"))
25600 (split-string email ",+ *"))
25601 (insert "<a href=\"mailto:" email "\">&lt;"
25602 email "&gt;</a>\n")))
25603 (insert "</p>\n"))
25604 (when (and date org-export-time-stamp-file)
25605 (insert "<p class=\"date\"> "
25606 (nth 2 lang-words) ": "
25607 date "</p>\n"))
25608 (insert "</div>"))
25610 (if org-export-html-with-timestamp
25611 (insert org-export-html-html-helper-timestamp))
25612 (insert (or (plist-get opt-plist :postamble) ""))
25613 (insert "</body>\n</html>\n"))
25615 (normal-mode)
25616 (if (eq major-mode default-major-mode) (html-mode))
25618 ;; insert the table of contents
25619 (goto-char (point-min))
25620 (when thetoc
25621 (if (or (re-search-forward
25622 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25623 (re-search-forward
25624 "\\[TABLE-OF-CONTENTS\\]" nil t))
25625 (progn
25626 (goto-char (match-beginning 0))
25627 (replace-match ""))
25628 (goto-char first-heading-pos)
25629 (when (looking-at "\\s-*</p>")
25630 (goto-char (match-end 0))
25631 (insert "\n")))
25632 (insert "<div id=\"table-of-contents\">\n")
25633 (mapc 'insert thetoc)
25634 (insert "</div>\n"))
25635 ;; remove empty paragraphs and lists
25636 (goto-char (point-min))
25637 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25638 (replace-match ""))
25639 (goto-char (point-min))
25640 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25641 (replace-match ""))
25642 (goto-char (point-min))
25643 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25644 (replace-match ""))
25645 ;; Convert whitespace place holders
25646 (goto-char (point-min))
25647 (let (beg end n)
25648 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25649 (setq n (get-text-property beg 'org-whitespace)
25650 end (next-single-property-change beg 'org-whitespace))
25651 (goto-char beg)
25652 (delete-region beg end)
25653 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25654 (make-string n ?x)))))
25656 (or to-buffer (save-buffer))
25657 (goto-char (point-min))
25658 (message "Exporting... done")
25659 (if (eq to-buffer 'string)
25660 (prog1 (buffer-substring (point-min) (point-max))
25661 (kill-buffer (current-buffer)))
25662 (current-buffer)))))
25664 (defvar org-table-colgroup-info nil)
25665 (defun org-format-table-ascii (lines)
25666 "Format a table for ascii export."
25667 (if (stringp lines)
25668 (setq lines (org-split-string lines "\n")))
25669 (if (not (string-match "^[ \t]*|" (car lines)))
25670 ;; Table made by table.el - test for spanning
25671 lines
25673 ;; A normal org table
25674 ;; Get rid of hlines at beginning and end
25675 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25676 (setq lines (nreverse lines))
25677 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25678 (setq lines (nreverse lines))
25679 (when org-export-table-remove-special-lines
25680 ;; Check if the table has a marking column. If yes remove the
25681 ;; column and the special lines
25682 (setq lines (org-table-clean-before-export lines)))
25683 ;; Get rid of the vertical lines except for grouping
25684 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25685 rtn line vl1 start)
25686 (while (setq line (pop lines))
25687 (if (string-match org-table-hline-regexp line)
25688 (and (string-match "|\\(.*\\)|" line)
25689 (setq line (replace-match " \\1" t nil line)))
25690 (setq start 0 vl1 vl)
25691 (while (string-match "|" line start)
25692 (setq start (match-end 0))
25693 (or (pop vl1) (setq line (replace-match " " t t line)))))
25694 (push line rtn))
25695 (nreverse rtn))))
25697 (defun org-colgroup-info-to-vline-list (info)
25698 (let (vl new last)
25699 (while info
25700 (setq last new new (pop info))
25701 (if (or (memq last '(:end :startend))
25702 (memq new '(:start :startend)))
25703 (push t vl)
25704 (push nil vl)))
25705 (setq vl (nreverse vl))
25706 (and vl (setcar vl nil))
25707 vl))
25709 (defun org-format-table-html (lines olines)
25710 "Find out which HTML converter to use and return the HTML code."
25711 (if (stringp lines)
25712 (setq lines (org-split-string lines "\n")))
25713 (if (string-match "^[ \t]*|" (car lines))
25714 ;; A normal org table
25715 (org-format-org-table-html lines)
25716 ;; Table made by table.el - test for spanning
25717 (let* ((hlines (delq nil (mapcar
25718 (lambda (x)
25719 (if (string-match "^[ \t]*\\+-" x) x
25720 nil))
25721 lines)))
25722 (first (car hlines))
25723 (ll (and (string-match "\\S-+" first)
25724 (match-string 0 first)))
25725 (re (concat "^[ \t]*" (regexp-quote ll)))
25726 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25727 hlines))))
25728 (if (and (not spanning)
25729 (not org-export-prefer-native-exporter-for-tables))
25730 ;; We can use my own converter with HTML conversions
25731 (org-format-table-table-html lines)
25732 ;; Need to use the code generator in table.el, with the original text.
25733 (org-format-table-table-html-using-table-generate-source olines)))))
25735 (defun org-format-org-table-html (lines &optional splice)
25736 "Format a table into HTML."
25737 ;; Get rid of hlines at beginning and end
25738 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25739 (setq lines (nreverse lines))
25740 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25741 (setq lines (nreverse lines))
25742 (when org-export-table-remove-special-lines
25743 ;; Check if the table has a marking column. If yes remove the
25744 ;; column and the special lines
25745 (setq lines (org-table-clean-before-export lines)))
25747 (let ((head (and org-export-highlight-first-table-line
25748 (delq nil (mapcar
25749 (lambda (x) (string-match "^[ \t]*|-" x))
25750 (cdr lines)))))
25751 (nlines 0) fnum i
25752 tbopen line fields html gr colgropen)
25753 (if splice (setq head nil))
25754 (unless splice (push (if head "<thead>" "<tbody>") html))
25755 (setq tbopen t)
25756 (while (setq line (pop lines))
25757 (catch 'next-line
25758 (if (string-match "^[ \t]*|-" line)
25759 (progn
25760 (unless splice
25761 (push (if head "</thead>" "</tbody>") html)
25762 (if lines (push "<tbody>" html) (setq tbopen nil)))
25763 (setq head nil) ;; head ends here, first time around
25764 ;; ignore this line
25765 (throw 'next-line t)))
25766 ;; Break the line into fields
25767 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25768 (unless fnum (setq fnum (make-vector (length fields) 0)))
25769 (setq nlines (1+ nlines) i -1)
25770 (push (concat "<tr>"
25771 (mapconcat
25772 (lambda (x)
25773 (setq i (1+ i))
25774 (if (and (< i nlines)
25775 (string-match org-table-number-regexp x))
25776 (incf (aref fnum i)))
25777 (if head
25778 (concat (car org-export-table-header-tags) x
25779 (cdr org-export-table-header-tags))
25780 (concat (car org-export-table-data-tags) x
25781 (cdr org-export-table-data-tags))))
25782 fields "")
25783 "</tr>")
25784 html)))
25785 (unless splice (if tbopen (push "</tbody>" html)))
25786 (unless splice (push "</table>\n" html))
25787 (setq html (nreverse html))
25788 (unless splice
25789 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25790 (push (mapconcat
25791 (lambda (x)
25792 (setq gr (pop org-table-colgroup-info))
25793 (format "%s<col align=\"%s\"></col>%s"
25794 (if (memq gr '(:start :startend))
25795 (prog1
25796 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25797 (setq colgropen t))
25799 (if (> (/ (float x) nlines) org-table-number-fraction)
25800 "right" "left")
25801 (if (memq gr '(:end :startend))
25802 (progn (setq colgropen nil) "</colgroup>")
25803 "")))
25804 fnum "")
25805 html)
25806 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25807 (push html-table-tag html))
25808 (concat (mapconcat 'identity html "\n") "\n")))
25810 (defun org-table-clean-before-export (lines)
25811 "Check if the table has a marking column.
25812 If yes remove the column and the special lines."
25813 (setq org-table-colgroup-info nil)
25814 (if (memq nil
25815 (mapcar
25816 (lambda (x) (or (string-match "^[ \t]*|-" x)
25817 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25818 lines))
25819 (progn
25820 (setq org-table-clean-did-remove-column nil)
25821 (delq nil
25822 (mapcar
25823 (lambda (x)
25824 (cond
25825 ((string-match "^[ \t]*| */ *|" x)
25826 (setq org-table-colgroup-info
25827 (mapcar (lambda (x)
25828 (cond ((member x '("<" "&lt;")) :start)
25829 ((member x '(">" "&gt;")) :end)
25830 ((member x '("<>" "&lt;&gt;")) :startend)
25831 (t nil)))
25832 (org-split-string x "[ \t]*|[ \t]*")))
25833 nil)
25834 (t x)))
25835 lines)))
25836 (setq org-table-clean-did-remove-column t)
25837 (delq nil
25838 (mapcar
25839 (lambda (x)
25840 (cond
25841 ((string-match "^[ \t]*| */ *|" x)
25842 (setq org-table-colgroup-info
25843 (mapcar (lambda (x)
25844 (cond ((member x '("<" "&lt;")) :start)
25845 ((member x '(">" "&gt;")) :end)
25846 ((member x '("<>" "&lt;&gt;")) :startend)
25847 (t nil)))
25848 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25849 nil)
25850 ((string-match "^[ \t]*| *[!_^/] *|" x)
25851 nil) ; ignore this line
25852 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25853 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25854 ;; remove the first column
25855 (replace-match "\\1|" t nil x))))
25856 lines))))
25858 (defun org-format-table-table-html (lines)
25859 "Format a table generated by table.el into HTML.
25860 This conversion does *not* use `table-generate-source' from table.el.
25861 This has the advantage that Org-mode's HTML conversions can be used.
25862 But it has the disadvantage, that no cell- or row-spanning is allowed."
25863 (let (line field-buffer
25864 (head org-export-highlight-first-table-line)
25865 fields html empty)
25866 (setq html (concat html-table-tag "\n"))
25867 (while (setq line (pop lines))
25868 (setq empty "&nbsp;")
25869 (catch 'next-line
25870 (if (string-match "^[ \t]*\\+-" line)
25871 (progn
25872 (if field-buffer
25873 (progn
25874 (setq
25875 html
25876 (concat
25877 html
25878 "<tr>"
25879 (mapconcat
25880 (lambda (x)
25881 (if (equal x "") (setq x empty))
25882 (if head
25883 (concat (car org-export-table-header-tags) x
25884 (cdr org-export-table-header-tags))
25885 (concat (car org-export-table-data-tags) x
25886 (cdr org-export-table-data-tags))))
25887 field-buffer "\n")
25888 "</tr>\n"))
25889 (setq head nil)
25890 (setq field-buffer nil)))
25891 ;; Ignore this line
25892 (throw 'next-line t)))
25893 ;; Break the line into fields and store the fields
25894 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25895 (if field-buffer
25896 (setq field-buffer (mapcar
25897 (lambda (x)
25898 (concat x "<br/>" (pop fields)))
25899 field-buffer))
25900 (setq field-buffer fields))))
25901 (setq html (concat html "</table>\n"))
25902 html))
25904 (defun org-format-table-table-html-using-table-generate-source (lines)
25905 "Format a table into html, using `table-generate-source' from table.el.
25906 This has the advantage that cell- or row-spanning is allowed.
25907 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25908 (require 'table)
25909 (with-current-buffer (get-buffer-create " org-tmp1 ")
25910 (erase-buffer)
25911 (insert (mapconcat 'identity lines "\n"))
25912 (goto-char (point-min))
25913 (if (not (re-search-forward "|[^+]" nil t))
25914 (error "Error processing table"))
25915 (table-recognize-table)
25916 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25917 (table-generate-source 'html " org-tmp2 ")
25918 (set-buffer " org-tmp2 ")
25919 (buffer-substring (point-min) (point-max))))
25921 (defun org-html-handle-time-stamps (s)
25922 "Format time stamps in string S, or remove them."
25923 (catch 'exit
25924 (let (r b)
25925 (while (string-match org-maybe-keyword-time-regexp s)
25926 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25927 ;; never export CLOCK
25928 (throw 'exit ""))
25929 (or b (setq b (substring s 0 (match-beginning 0))))
25930 (if (not org-export-with-timestamps)
25931 (setq r (concat r (substring s 0 (match-beginning 0)))
25932 s (substring s (match-end 0)))
25933 (setq r (concat
25934 r (substring s 0 (match-beginning 0))
25935 (if (match-end 1)
25936 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25937 (match-string 1 s)))
25938 (format " @<span class=\"timestamp\">%s@</span>"
25939 (substring
25940 (org-translate-time (match-string 3 s)) 1 -1)))
25941 s (substring s (match-end 0)))))
25942 ;; Line break if line started and ended with time stamp stuff
25943 (if (not r)
25945 (setq r (concat r s))
25946 (unless (string-match "\\S-" (concat b s))
25947 (setq r (concat r "@<br/>")))
25948 r))))
25950 (defun org-html-protect (s)
25951 ;; convert & to &amp;, < to &lt; and > to &gt;
25952 (let ((start 0))
25953 (while (string-match "&" s start)
25954 (setq s (replace-match "&amp;" t t s)
25955 start (1+ (match-beginning 0))))
25956 (while (string-match "<" s)
25957 (setq s (replace-match "&lt;" t t s)))
25958 (while (string-match ">" s)
25959 (setq s (replace-match "&gt;" t t s))))
25962 (defun org-export-cleanup-toc-line (s)
25963 "Remove tags and time staps from lines going into the toc."
25964 (when (memq org-export-with-tags '(not-in-toc nil))
25965 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25966 (setq s (replace-match "" t t s))))
25967 (when org-export-remove-timestamps-from-toc
25968 (while (string-match org-maybe-keyword-time-regexp s)
25969 (setq s (replace-match "" t t s))))
25970 (while (string-match org-bracket-link-regexp s)
25971 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25972 t t s)))
25975 (defun org-html-expand (string)
25976 "Prepare STRING for HTML export. Applies all active conversions.
25977 If there are links in the string, don't modify these."
25978 (let* ((re (concat org-bracket-link-regexp "\\|"
25979 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25980 m s l res)
25981 (while (setq m (string-match re string))
25982 (setq s (substring string 0 m)
25983 l (match-string 0 string)
25984 string (substring string (match-end 0)))
25985 (push (org-html-do-expand s) res)
25986 (push l res))
25987 (push (org-html-do-expand string) res)
25988 (apply 'concat (nreverse res))))
25990 (defun org-html-do-expand (s)
25991 "Apply all active conversions to translate special ASCII to HTML."
25992 (setq s (org-html-protect s))
25993 (if org-export-html-expand
25994 (let ((start 0))
25995 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25996 (setq s (replace-match "<\\1>" t nil s)))))
25997 (if org-export-with-emphasize
25998 (setq s (org-export-html-convert-emphasize s)))
25999 (if org-export-with-special-strings
26000 (setq s (org-export-html-convert-special-strings s)))
26001 (if org-export-with-sub-superscripts
26002 (setq s (org-export-html-convert-sub-super s)))
26003 (if org-export-with-TeX-macros
26004 (let ((start 0) wd ass)
26005 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26006 (if (get-text-property (match-beginning 0) 'org-protected s)
26007 (setq start (match-end 0))
26008 (setq wd (match-string 1 s))
26009 (if (setq ass (assoc wd org-html-entities))
26010 (setq s (replace-match (or (cdr ass)
26011 (concat "&" (car ass) ";"))
26012 t t s))
26013 (setq start (+ start (length wd))))))))
26016 (defun org-create-multibrace-regexp (left right n)
26017 "Create a regular expression which will match a balanced sexp.
26018 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26019 as single character strings.
26020 The regexp returned will match the entire expression including the
26021 delimiters. It will also define a single group which contains the
26022 match except for the outermost delimiters. The maximum depth of
26023 stacked delimiters is N. Escaping delimiters is not possible."
26024 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26025 (or "\\|")
26026 (re nothing)
26027 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26028 (while (> n 1)
26029 (setq n (1- n)
26030 re (concat re or next)
26031 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26032 (concat left "\\(" re "\\)" right)))
26034 (defvar org-match-substring-regexp
26035 (concat
26036 "\\([^\\]\\)\\([_^]\\)\\("
26037 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26038 "\\|"
26039 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26040 "\\|"
26041 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26042 "The regular expression matching a sub- or superscript.")
26044 (defvar org-match-substring-with-braces-regexp
26045 (concat
26046 "\\([^\\]\\)\\([_^]\\)\\("
26047 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26048 "\\)")
26049 "The regular expression matching a sub- or superscript, forcing braces.")
26051 (defconst org-export-html-special-string-regexps
26052 '(("\\\\-" . "&shy;")
26053 ("---\\([^-]\\)" . "&mdash;\\1")
26054 ("--\\([^-]\\)" . "&ndash;\\1")
26055 ("\\.\\.\\." . "&hellip;"))
26056 "Regular expressions for special string conversion.")
26058 (defun org-export-html-convert-special-strings (string)
26059 "Convert special characters in STRING to HTML."
26060 (let ((all org-export-html-special-string-regexps)
26061 e a re rpl start)
26062 (while (setq a (pop all))
26063 (setq re (car a) rpl (cdr a) start 0)
26064 (while (string-match re string start)
26065 (if (get-text-property (match-beginning 0) 'org-protected string)
26066 (setq start (match-end 0))
26067 (setq string (replace-match rpl t nil string)))))
26068 string))
26070 (defun org-export-html-convert-sub-super (string)
26071 "Convert sub- and superscripts in STRING to HTML."
26072 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26073 (while (string-match org-match-substring-regexp string s)
26074 (cond
26075 ((and requireb (match-end 8)) (setq s (match-end 2)))
26076 ((get-text-property (match-beginning 2) 'org-protected string)
26077 (setq s (match-end 2)))
26079 (setq s (match-end 1)
26080 key (if (string= (match-string 2 string) "_") "sub" "sup")
26081 c (or (match-string 8 string)
26082 (match-string 6 string)
26083 (match-string 5 string))
26084 string (replace-match
26085 (concat (match-string 1 string)
26086 "<" key ">" c "</" key ">")
26087 t t string)))))
26088 (while (string-match "\\\\\\([_^]\\)" string)
26089 (setq string (replace-match (match-string 1 string) t t string)))
26090 string))
26092 (defun org-export-html-convert-emphasize (string)
26093 "Apply emphasis."
26094 (let ((s 0) rpl)
26095 (while (string-match org-emph-re string s)
26096 (if (not (equal
26097 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26098 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26099 (setq s (match-beginning 0)
26101 (concat
26102 (match-string 1 string)
26103 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26104 (match-string 4 string)
26105 (nth 3 (assoc (match-string 3 string)
26106 org-emphasis-alist))
26107 (match-string 5 string))
26108 string (replace-match rpl t t string)
26109 s (+ s (- (length rpl) 2)))
26110 (setq s (1+ s))))
26111 string))
26113 (defvar org-par-open nil)
26114 (defun org-open-par ()
26115 "Insert <p>, but first close previous paragraph if any."
26116 (org-close-par-maybe)
26117 (insert "\n<p>")
26118 (setq org-par-open t))
26119 (defun org-close-par-maybe ()
26120 "Close paragraph if there is one open."
26121 (when org-par-open
26122 (insert "</p>")
26123 (setq org-par-open nil)))
26124 (defun org-close-li ()
26125 "Close <li> if necessary."
26126 (org-close-par-maybe)
26127 (insert "</li>\n"))
26129 (defvar body-only) ; dynamically scoped into this.
26130 (defun org-html-level-start (level title umax with-toc head-count)
26131 "Insert a new level in HTML export.
26132 When TITLE is nil, just close all open levels."
26133 (org-close-par-maybe)
26134 (let ((l org-level-max))
26135 (while (>= l level)
26136 (if (aref org-levels-open (1- l))
26137 (progn
26138 (org-html-level-close l umax)
26139 (aset org-levels-open (1- l) nil)))
26140 (setq l (1- l)))
26141 (when title
26142 ;; If title is nil, this means this function is called to close
26143 ;; all levels, so the rest is done only if title is given
26144 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26145 (setq title (replace-match
26146 (if org-export-with-tags
26147 (save-match-data
26148 (concat
26149 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26150 (mapconcat 'identity (org-split-string
26151 (match-string 1 title) ":")
26152 "&nbsp;")
26153 "</span>"))
26155 t t title)))
26156 (if (> level umax)
26157 (progn
26158 (if (aref org-levels-open (1- level))
26159 (progn
26160 (org-close-li)
26161 (insert "<li>" title "<br/>\n"))
26162 (aset org-levels-open (1- level) t)
26163 (org-close-par-maybe)
26164 (insert "<ul>\n<li>" title "<br/>\n")))
26165 (aset org-levels-open (1- level) t)
26166 (if (and org-export-with-section-numbers (not body-only))
26167 (setq title (concat (org-section-number level) " " title)))
26168 (setq level (+ level org-export-html-toplevel-hlevel -1))
26169 (if with-toc
26170 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26171 level level head-count title level))
26172 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26173 (org-open-par)))))
26175 (defun org-html-level-close (level max-outline-level)
26176 "Terminate one level in HTML export."
26177 (if (<= level max-outline-level)
26178 (insert "</div>\n")
26179 (org-close-li)
26180 (insert "</ul>\n")))
26182 ;;; iCalendar export
26184 ;;;###autoload
26185 (defun org-export-icalendar-this-file ()
26186 "Export current file as an iCalendar file.
26187 The iCalendar file will be located in the same directory as the Org-mode
26188 file, but with extension `.ics'."
26189 (interactive)
26190 (org-export-icalendar nil buffer-file-name))
26192 ;;;###autoload
26193 (defun org-export-icalendar-all-agenda-files ()
26194 "Export all files in `org-agenda-files' to iCalendar .ics files.
26195 Each iCalendar file will be located in the same directory as the Org-mode
26196 file, but with extension `.ics'."
26197 (interactive)
26198 (apply 'org-export-icalendar nil (org-agenda-files t)))
26200 ;;;###autoload
26201 (defun org-export-icalendar-combine-agenda-files ()
26202 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26203 The file is stored under the name `org-combined-agenda-icalendar-file'."
26204 (interactive)
26205 (apply 'org-export-icalendar t (org-agenda-files t)))
26207 (defun org-export-icalendar (combine &rest files)
26208 "Create iCalendar files for all elements of FILES.
26209 If COMBINE is non-nil, combine all calendar entries into a single large
26210 file and store it under the name `org-combined-agenda-icalendar-file'."
26211 (save-excursion
26212 (org-prepare-agenda-buffers files)
26213 (let* ((dir (org-export-directory
26214 :ical (list :publishing-directory
26215 org-export-publishing-directory)))
26216 file ical-file ical-buffer category started org-agenda-new-buffers)
26218 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26219 (when combine
26220 (setq ical-file
26221 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26222 org-combined-agenda-icalendar-file
26223 (expand-file-name org-combined-agenda-icalendar-file dir))
26224 ical-buffer (org-get-agenda-file-buffer ical-file))
26225 (set-buffer ical-buffer) (erase-buffer))
26226 (while (setq file (pop files))
26227 (catch 'nextfile
26228 (org-check-agenda-file file)
26229 (set-buffer (org-get-agenda-file-buffer file))
26230 (unless combine
26231 (setq ical-file (concat (file-name-as-directory dir)
26232 (file-name-sans-extension
26233 (file-name-nondirectory buffer-file-name))
26234 ".ics"))
26235 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26236 (with-current-buffer ical-buffer (erase-buffer)))
26237 (setq category (or org-category
26238 (file-name-sans-extension
26239 (file-name-nondirectory buffer-file-name))))
26240 (if (symbolp category) (setq category (symbol-name category)))
26241 (let ((standard-output ical-buffer))
26242 (if combine
26243 (and (not started) (setq started t)
26244 (org-start-icalendar-file org-icalendar-combined-name))
26245 (org-start-icalendar-file category))
26246 (org-print-icalendar-entries combine)
26247 (when (or (and combine (not files)) (not combine))
26248 (org-finish-icalendar-file)
26249 (set-buffer ical-buffer)
26250 (save-buffer)
26251 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26252 (org-release-buffers org-agenda-new-buffers))))
26254 (defvar org-after-save-iCalendar-file-hook nil
26255 "Hook run after an iCalendar file has been saved.
26256 The iCalendar buffer is still current when this hook is run.
26257 A good way to use this is to tell a desktop calenndar application to re-read
26258 the iCalendar file.")
26260 (defun org-print-icalendar-entries (&optional combine)
26261 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26262 When COMBINE is non nil, add the category to each line."
26263 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26264 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26265 (dts (org-ical-ts-to-string
26266 (format-time-string (cdr org-time-stamp-formats) (current-time))
26267 "DTSTART"))
26268 hd ts ts2 state status (inc t) pos b sexp rrule
26269 scheduledp deadlinep tmp pri category entry location summary desc
26270 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26271 (org-refresh-category-properties)
26272 (save-excursion
26273 (goto-char (point-min))
26274 (while (re-search-forward re1 nil t)
26275 (catch :skip
26276 (org-agenda-skip)
26277 (setq pos (match-beginning 0)
26278 ts (match-string 0)
26279 inc t
26280 hd (org-get-heading)
26281 summary (org-icalendar-cleanup-string
26282 (org-entry-get nil "SUMMARY"))
26283 desc (org-icalendar-cleanup-string
26284 (or (org-entry-get nil "DESCRIPTION")
26285 (and org-icalendar-include-body (org-get-entry)))
26286 t org-icalendar-include-body)
26287 location (org-icalendar-cleanup-string
26288 (org-entry-get nil "LOCATION"))
26289 category (org-get-category))
26290 (if (looking-at re2)
26291 (progn
26292 (goto-char (match-end 0))
26293 (setq ts2 (match-string 1) inc nil))
26294 (setq tmp (buffer-substring (max (point-min)
26295 (- pos org-ds-keyword-length))
26296 pos)
26297 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26298 (progn
26299 (setq inc nil)
26300 (replace-match "\\1" t nil ts))
26302 deadlinep (string-match org-deadline-regexp tmp)
26303 scheduledp (string-match org-scheduled-regexp tmp)
26304 ;; donep (org-entry-is-done-p)
26306 (if (or (string-match org-tr-regexp hd)
26307 (string-match org-ts-regexp hd))
26308 (setq hd (replace-match "" t t hd)))
26309 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26310 (setq rrule
26311 (concat "\nRRULE:FREQ="
26312 (cdr (assoc
26313 (match-string 2 ts)
26314 '(("d" . "DAILY")("w" . "WEEKLY")
26315 ("m" . "MONTHLY")("y" . "YEARLY"))))
26316 ";INTERVAL=" (match-string 1 ts)))
26317 (setq rrule ""))
26318 (setq summary (or summary hd))
26319 (if (string-match org-bracket-link-regexp summary)
26320 (setq summary
26321 (replace-match (if (match-end 3)
26322 (match-string 3 summary)
26323 (match-string 1 summary))
26324 t t summary)))
26325 (if deadlinep (setq summary (concat "DL: " summary)))
26326 (if scheduledp (setq summary (concat "S: " summary)))
26327 (if (string-match "\\`<%%" ts)
26328 (with-current-buffer sexp-buffer
26329 (insert (substring ts 1 -1) " " summary "\n"))
26330 (princ (format "BEGIN:VEVENT
26332 %s%s
26333 SUMMARY:%s%s%s
26334 CATEGORIES:%s
26335 END:VEVENT\n"
26336 (org-ical-ts-to-string ts "DTSTART")
26337 (org-ical-ts-to-string ts2 "DTEND" inc)
26338 rrule summary
26339 (if (and desc (string-match "\\S-" desc))
26340 (concat "\nDESCRIPTION: " desc) "")
26341 (if (and location (string-match "\\S-" location))
26342 (concat "\nLOCATION: " location) "")
26343 category)))))
26345 (when (and org-icalendar-include-sexps
26346 (condition-case nil (require 'icalendar) (error nil))
26347 (fboundp 'icalendar-export-region))
26348 ;; Get all the literal sexps
26349 (goto-char (point-min))
26350 (while (re-search-forward "^&?%%(" nil t)
26351 (catch :skip
26352 (org-agenda-skip)
26353 (setq b (match-beginning 0))
26354 (goto-char (1- (match-end 0)))
26355 (forward-sexp 1)
26356 (end-of-line 1)
26357 (setq sexp (buffer-substring b (point)))
26358 (with-current-buffer sexp-buffer
26359 (insert sexp "\n"))
26360 (princ (org-diary-to-ical-string sexp-buffer)))))
26362 (when org-icalendar-include-todo
26363 (goto-char (point-min))
26364 (while (re-search-forward org-todo-line-regexp nil t)
26365 (catch :skip
26366 (org-agenda-skip)
26367 (setq state (match-string 2))
26368 (setq status (if (member state org-done-keywords)
26369 "COMPLETED" "NEEDS-ACTION"))
26370 (when (and state
26371 (or (not (member state org-done-keywords))
26372 (eq org-icalendar-include-todo 'all))
26373 (not (member org-archive-tag (org-get-tags-at)))
26375 (setq hd (match-string 3)
26376 summary (org-icalendar-cleanup-string
26377 (org-entry-get nil "SUMMARY"))
26378 desc (org-icalendar-cleanup-string
26379 (or (org-entry-get nil "DESCRIPTION")
26380 (and org-icalendar-include-body (org-get-entry)))
26381 t org-icalendar-include-body)
26382 location (org-icalendar-cleanup-string
26383 (org-entry-get nil "LOCATION")))
26384 (if (string-match org-bracket-link-regexp hd)
26385 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26386 (match-string 1 hd))
26387 t t hd)))
26388 (if (string-match org-priority-regexp hd)
26389 (setq pri (string-to-char (match-string 2 hd))
26390 hd (concat (substring hd 0 (match-beginning 1))
26391 (substring hd (match-end 1))))
26392 (setq pri org-default-priority))
26393 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26394 (- org-lowest-priority org-highest-priority))))))
26396 (princ (format "BEGIN:VTODO
26398 SUMMARY:%s%s%s
26399 CATEGORIES:%s
26400 SEQUENCE:1
26401 PRIORITY:%d
26402 STATUS:%s
26403 END:VTODO\n"
26405 (or summary hd)
26406 (if (and location (string-match "\\S-" location))
26407 (concat "\nLOCATION: " location) "")
26408 (if (and desc (string-match "\\S-" desc))
26409 (concat "\nDESCRIPTION: " desc) "")
26410 category pri status)))))))))
26412 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26413 "Take out stuff and quote what needs to be quoted.
26414 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26415 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26416 characters."
26417 (if (not s)
26419 (when is-body
26420 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26421 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26422 (while (string-match re s) (setq s (replace-match "" t t s)))
26423 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26424 (let ((start 0))
26425 (while (string-match "\\([,;\\]\\)" s start)
26426 (setq start (+ (match-beginning 0) 2)
26427 s (replace-match "\\\\\\1" nil nil s))))
26428 (when is-body
26429 (while (string-match "[ \t]*\n[ \t]*" s)
26430 (setq s (replace-match "\\n" t t s))))
26431 (setq s (org-trim s))
26432 (if is-body
26433 (if maxlength
26434 (if (and (numberp maxlength)
26435 (> (length s) maxlength))
26436 (setq s (substring s 0 maxlength)))))
26439 (defun org-get-entry ()
26440 "Clean-up description string."
26441 (save-excursion
26442 (org-back-to-heading t)
26443 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26445 (defun org-start-icalendar-file (name)
26446 "Start an iCalendar file by inserting the header."
26447 (let ((user user-full-name)
26448 (name (or name "unknown"))
26449 (timezone (cadr (current-time-zone))))
26450 (princ
26451 (format "BEGIN:VCALENDAR
26452 VERSION:2.0
26453 X-WR-CALNAME:%s
26454 PRODID:-//%s//Emacs with Org-mode//EN
26455 X-WR-TIMEZONE:%s
26456 CALSCALE:GREGORIAN\n" name user timezone))))
26458 (defun org-finish-icalendar-file ()
26459 "Finish an iCalendar file by inserting the END statement."
26460 (princ "END:VCALENDAR\n"))
26462 (defun org-ical-ts-to-string (s keyword &optional inc)
26463 "Take a time string S and convert it to iCalendar format.
26464 KEYWORD is added in front, to make a complete line like DTSTART....
26465 When INC is non-nil, increase the hour by two (if time string contains
26466 a time), or the day by one (if it does not contain a time)."
26467 (let ((t1 (org-parse-time-string s 'nodefault))
26468 t2 fmt have-time time)
26469 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26470 (setq t2 t1 have-time t)
26471 (setq t2 (org-parse-time-string s)))
26472 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26473 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26474 (when inc
26475 (if have-time
26476 (if org-agenda-default-appointment-duration
26477 (setq mi (+ org-agenda-default-appointment-duration mi))
26478 (setq h (+ 2 h)))
26479 (setq d (1+ d))))
26480 (setq time (encode-time s mi h d m y)))
26481 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26482 (concat keyword (format-time-string fmt time))))
26484 ;;; XOXO export
26486 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26487 (with-current-buffer buffer
26488 (apply 'insert output)))
26489 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26491 (defun org-export-as-xoxo (&optional buffer)
26492 "Export the org buffer as XOXO.
26493 The XOXO buffer is named *xoxo-<source buffer name>*"
26494 (interactive (list (current-buffer)))
26495 ;; A quickie abstraction
26497 ;; Output everything as XOXO
26498 (with-current-buffer (get-buffer buffer)
26499 (let* ((pos (point))
26500 (opt-plist (org-combine-plists (org-default-export-plist)
26501 (org-infile-export-plist)))
26502 (filename (concat (file-name-as-directory
26503 (org-export-directory :xoxo opt-plist))
26504 (file-name-sans-extension
26505 (file-name-nondirectory buffer-file-name))
26506 ".html"))
26507 (out (find-file-noselect filename))
26508 (last-level 1)
26509 (hanging-li nil))
26510 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26511 ;; Check the output buffer is empty.
26512 (with-current-buffer out (erase-buffer))
26513 ;; Kick off the output
26514 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26515 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26516 (let* ((hd (match-string-no-properties 1))
26517 (level (length hd))
26518 (text (concat
26519 (match-string-no-properties 2)
26520 (save-excursion
26521 (goto-char (match-end 0))
26522 (let ((str ""))
26523 (catch 'loop
26524 (while 't
26525 (forward-line)
26526 (if (looking-at "^[ \t]\\(.*\\)")
26527 (setq str (concat str (match-string-no-properties 1)))
26528 (throw 'loop str)))))))))
26530 ;; Handle level rendering
26531 (cond
26532 ((> level last-level)
26533 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26535 ((< level last-level)
26536 (dotimes (- (- last-level level) 1)
26537 (if hanging-li
26538 (org-export-as-xoxo-insert-into out "</li>\n"))
26539 (org-export-as-xoxo-insert-into out "</ol>\n"))
26540 (when hanging-li
26541 (org-export-as-xoxo-insert-into out "</li>\n")
26542 (setq hanging-li nil)))
26544 ((equal level last-level)
26545 (if hanging-li
26546 (org-export-as-xoxo-insert-into out "</li>\n")))
26549 (setq last-level level)
26551 ;; And output the new li
26552 (setq hanging-li 't)
26553 (if (equal ?+ (elt text 0))
26554 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26555 (org-export-as-xoxo-insert-into out "<li>" text))))
26557 ;; Finally finish off the ol
26558 (dotimes (- last-level 1)
26559 (if hanging-li
26560 (org-export-as-xoxo-insert-into out "</li>\n"))
26561 (org-export-as-xoxo-insert-into out "</ol>\n"))
26563 (goto-char pos)
26564 ;; Finish the buffer off and clean it up.
26565 (switch-to-buffer-other-window out)
26566 (indent-region (point-min) (point-max) nil)
26567 (save-buffer)
26568 (goto-char (point-min))
26572 ;;;; Key bindings
26574 ;; Make `C-c C-x' a prefix key
26575 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26577 ;; TAB key with modifiers
26578 (org-defkey org-mode-map "\C-i" 'org-cycle)
26579 (org-defkey org-mode-map [(tab)] 'org-cycle)
26580 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26581 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26582 (org-defkey org-mode-map "\M-\t" 'org-complete)
26583 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26584 ;; The following line is necessary under Suse GNU/Linux
26585 (unless (featurep 'xemacs)
26586 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26587 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26588 (define-key org-mode-map [backtab] 'org-shifttab)
26590 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26591 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26592 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26594 ;; Cursor keys with modifiers
26595 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26596 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26597 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26598 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26600 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26601 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26602 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26603 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26605 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26606 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26607 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26608 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26610 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26611 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26613 ;;; Extra keys for tty access.
26614 ;; We only set them when really needed because otherwise the
26615 ;; menus don't show the simple keys
26617 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26618 (not window-system))
26619 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26620 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26621 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26622 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26623 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26624 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26625 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26626 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26627 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26628 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26629 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26630 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26631 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26632 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26633 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26634 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26635 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26636 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26637 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26638 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26639 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26640 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26642 ;; All the other keys
26644 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26645 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26646 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26647 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26648 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26649 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26650 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26651 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26652 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26653 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26654 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26655 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26656 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26657 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26658 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26659 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26660 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26661 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26662 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26663 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26664 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26665 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26666 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26667 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26668 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26669 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26670 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26671 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26672 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26673 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26674 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26675 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26676 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26677 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26678 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26679 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26680 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26681 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26682 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26683 (org-defkey org-mode-map "\C-c^" 'org-sort)
26684 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26685 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26686 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26687 (org-defkey org-mode-map "\C-m" 'org-return)
26688 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26689 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26690 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26691 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26692 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26693 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26694 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26695 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26696 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26697 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26698 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26699 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26700 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26701 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26702 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26703 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26704 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26706 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26707 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26708 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26709 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26711 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26712 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26713 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26714 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26715 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26716 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26717 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26718 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26719 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26720 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26721 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26722 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26724 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26726 (when (featurep 'xemacs)
26727 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26729 (defsubst org-table-p () (org-at-table-p))
26731 (defun org-self-insert-command (N)
26732 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26733 If the cursor is in a table looking at whitespace, the whitespace is
26734 overwritten, and the table is not marked as requiring realignment."
26735 (interactive "p")
26736 (if (and (org-table-p)
26737 (progn
26738 ;; check if we blank the field, and if that triggers align
26739 (and org-table-auto-blank-field
26740 (member last-command
26741 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26742 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26743 ;; got extra space, this field does not determine column width
26744 (let (org-table-may-need-update) (org-table-blank-field))
26745 ;; no extra space, this field may determine column width
26746 (org-table-blank-field)))
26748 (eq N 1)
26749 (looking-at "[^|\n]* |"))
26750 (let (org-table-may-need-update)
26751 (goto-char (1- (match-end 0)))
26752 (delete-backward-char 1)
26753 (goto-char (match-beginning 0))
26754 (self-insert-command N))
26755 (setq org-table-may-need-update t)
26756 (self-insert-command N)
26757 (org-fix-tags-on-the-fly)))
26759 (defun org-fix-tags-on-the-fly ()
26760 (when (and (equal (char-after (point-at-bol)) ?*)
26761 (org-on-heading-p))
26762 (org-align-tags-here org-tags-column)))
26764 (defun org-delete-backward-char (N)
26765 "Like `delete-backward-char', insert whitespace at field end in tables.
26766 When deleting backwards, in tables this function will insert whitespace in
26767 front of the next \"|\" separator, to keep the table aligned. The table will
26768 still be marked for re-alignment if the field did fill the entire column,
26769 because, in this case the deletion might narrow the column."
26770 (interactive "p")
26771 (if (and (org-table-p)
26772 (eq N 1)
26773 (string-match "|" (buffer-substring (point-at-bol) (point)))
26774 (looking-at ".*?|"))
26775 (let ((pos (point))
26776 (noalign (looking-at "[^|\n\r]* |"))
26777 (c org-table-may-need-update))
26778 (backward-delete-char N)
26779 (skip-chars-forward "^|")
26780 (insert " ")
26781 (goto-char (1- pos))
26782 ;; noalign: if there were two spaces at the end, this field
26783 ;; does not determine the width of the column.
26784 (if noalign (setq org-table-may-need-update c)))
26785 (backward-delete-char N)
26786 (org-fix-tags-on-the-fly)))
26788 (defun org-delete-char (N)
26789 "Like `delete-char', but insert whitespace at field end in tables.
26790 When deleting characters, in tables this function will insert whitespace in
26791 front of the next \"|\" separator, to keep the table aligned. The table will
26792 still be marked for re-alignment if the field did fill the entire column,
26793 because, in this case the deletion might narrow the column."
26794 (interactive "p")
26795 (if (and (org-table-p)
26796 (not (bolp))
26797 (not (= (char-after) ?|))
26798 (eq N 1))
26799 (if (looking-at ".*?|")
26800 (let ((pos (point))
26801 (noalign (looking-at "[^|\n\r]* |"))
26802 (c org-table-may-need-update))
26803 (replace-match (concat
26804 (substring (match-string 0) 1 -1)
26805 " |"))
26806 (goto-char pos)
26807 ;; noalign: if there were two spaces at the end, this field
26808 ;; does not determine the width of the column.
26809 (if noalign (setq org-table-may-need-update c)))
26810 (delete-char N))
26811 (delete-char N)
26812 (org-fix-tags-on-the-fly)))
26814 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26815 (put 'org-self-insert-command 'delete-selection t)
26816 (put 'orgtbl-self-insert-command 'delete-selection t)
26817 (put 'org-delete-char 'delete-selection 'supersede)
26818 (put 'org-delete-backward-char 'delete-selection 'supersede)
26820 ;; Make `flyspell-mode' delay after some commands
26821 (put 'org-self-insert-command 'flyspell-delayed t)
26822 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26823 (put 'org-delete-char 'flyspell-delayed t)
26824 (put 'org-delete-backward-char 'flyspell-delayed t)
26826 ;; Make pabbrev-mode expand after org-mode commands
26827 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26828 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26830 ;; How to do this: Measure non-white length of current string
26831 ;; If equal to column width, we should realign.
26833 (defun org-remap (map &rest commands)
26834 "In MAP, remap the functions given in COMMANDS.
26835 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26836 (let (new old)
26837 (while commands
26838 (setq old (pop commands) new (pop commands))
26839 (if (fboundp 'command-remapping)
26840 (org-defkey map (vector 'remap old) new)
26841 (substitute-key-definition old new map global-map)))))
26843 (when (eq org-enable-table-editor 'optimized)
26844 ;; If the user wants maximum table support, we need to hijack
26845 ;; some standard editing functions
26846 (org-remap org-mode-map
26847 'self-insert-command 'org-self-insert-command
26848 'delete-char 'org-delete-char
26849 'delete-backward-char 'org-delete-backward-char)
26850 (org-defkey org-mode-map "|" 'org-force-self-insert))
26852 (defun org-shiftcursor-error ()
26853 "Throw an error because Shift-Cursor command was applied in wrong context."
26854 (error "This command is active in special context like tables, headlines or timestamps"))
26856 (defun org-shifttab (&optional arg)
26857 "Global visibility cycling or move to previous table field.
26858 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26859 on context.
26860 See the individual commands for more information."
26861 (interactive "P")
26862 (cond
26863 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26864 (arg (message "Content view to level: ")
26865 (org-content (prefix-numeric-value arg))
26866 (setq org-cycle-global-status 'overview))
26867 (t (call-interactively 'org-global-cycle))))
26869 (defun org-shiftmetaleft ()
26870 "Promote subtree or delete table column.
26871 Calls `org-promote-subtree', `org-outdent-item',
26872 or `org-table-delete-column', depending on context.
26873 See the individual commands for more information."
26874 (interactive)
26875 (cond
26876 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26877 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26878 ((org-at-item-p) (call-interactively 'org-outdent-item))
26879 (t (org-shiftcursor-error))))
26881 (defun org-shiftmetaright ()
26882 "Demote subtree or insert table column.
26883 Calls `org-demote-subtree', `org-indent-item',
26884 or `org-table-insert-column', depending on context.
26885 See the individual commands for more information."
26886 (interactive)
26887 (cond
26888 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26889 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26890 ((org-at-item-p) (call-interactively 'org-indent-item))
26891 (t (org-shiftcursor-error))))
26893 (defun org-shiftmetaup (&optional arg)
26894 "Move subtree up or kill table row.
26895 Calls `org-move-subtree-up' or `org-table-kill-row' or
26896 `org-move-item-up' depending on context. See the individual commands
26897 for more information."
26898 (interactive "P")
26899 (cond
26900 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26901 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26902 ((org-at-item-p) (call-interactively 'org-move-item-up))
26903 (t (org-shiftcursor-error))))
26904 (defun org-shiftmetadown (&optional arg)
26905 "Move subtree down or insert table row.
26906 Calls `org-move-subtree-down' or `org-table-insert-row' or
26907 `org-move-item-down', depending on context. See the individual
26908 commands for more information."
26909 (interactive "P")
26910 (cond
26911 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26912 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26913 ((org-at-item-p) (call-interactively 'org-move-item-down))
26914 (t (org-shiftcursor-error))))
26916 (defun org-metaleft (&optional arg)
26917 "Promote heading or move table column to left.
26918 Calls `org-do-promote' or `org-table-move-column', depending on context.
26919 With no specific context, calls the Emacs default `backward-word'.
26920 See the individual commands for more information."
26921 (interactive "P")
26922 (cond
26923 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26924 ((or (org-on-heading-p) (org-region-active-p))
26925 (call-interactively 'org-do-promote))
26926 ((org-at-item-p) (call-interactively 'org-outdent-item))
26927 (t (call-interactively 'backward-word))))
26929 (defun org-metaright (&optional arg)
26930 "Demote subtree or move table column to right.
26931 Calls `org-do-demote' or `org-table-move-column', depending on context.
26932 With no specific context, calls the Emacs default `forward-word'.
26933 See the individual commands for more information."
26934 (interactive "P")
26935 (cond
26936 ((org-at-table-p) (call-interactively 'org-table-move-column))
26937 ((or (org-on-heading-p) (org-region-active-p))
26938 (call-interactively 'org-do-demote))
26939 ((org-at-item-p) (call-interactively 'org-indent-item))
26940 (t (call-interactively 'forward-word))))
26942 (defun org-metaup (&optional arg)
26943 "Move subtree up or move table row up.
26944 Calls `org-move-subtree-up' or `org-table-move-row' or
26945 `org-move-item-up', depending on context. See the individual commands
26946 for more information."
26947 (interactive "P")
26948 (cond
26949 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26950 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26951 ((org-at-item-p) (call-interactively 'org-move-item-up))
26952 (t (transpose-lines 1) (beginning-of-line -1))))
26954 (defun org-metadown (&optional arg)
26955 "Move subtree down or move table row down.
26956 Calls `org-move-subtree-down' or `org-table-move-row' or
26957 `org-move-item-down', depending on context. See the individual
26958 commands for more information."
26959 (interactive "P")
26960 (cond
26961 ((org-at-table-p) (call-interactively 'org-table-move-row))
26962 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26963 ((org-at-item-p) (call-interactively 'org-move-item-down))
26964 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26966 (defun org-shiftup (&optional arg)
26967 "Increase item in timestamp or increase priority of current headline.
26968 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26969 depending on context. See the individual commands for more information."
26970 (interactive "P")
26971 (cond
26972 ((org-at-timestamp-p t)
26973 (call-interactively (if org-edit-timestamp-down-means-later
26974 'org-timestamp-down 'org-timestamp-up)))
26975 ((org-on-heading-p) (call-interactively 'org-priority-up))
26976 ((org-at-item-p) (call-interactively 'org-previous-item))
26977 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26979 (defun org-shiftdown (&optional arg)
26980 "Decrease item in timestamp or decrease priority of current headline.
26981 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26982 depending on context. See the individual commands for more information."
26983 (interactive "P")
26984 (cond
26985 ((org-at-timestamp-p t)
26986 (call-interactively (if org-edit-timestamp-down-means-later
26987 'org-timestamp-up 'org-timestamp-down)))
26988 ((org-on-heading-p) (call-interactively 'org-priority-down))
26989 (t (call-interactively 'org-next-item))))
26991 (defun org-shiftright ()
26992 "Next TODO keyword or timestamp one day later, depending on context."
26993 (interactive)
26994 (cond
26995 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26996 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26997 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26998 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26999 (t (org-shiftcursor-error))))
27001 (defun org-shiftleft ()
27002 "Previous TODO keyword or timestamp one day earlier, depending on context."
27003 (interactive)
27004 (cond
27005 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27006 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27007 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27008 ((org-at-property-p)
27009 (call-interactively 'org-property-previous-allowed-value))
27010 (t (org-shiftcursor-error))))
27012 (defun org-shiftcontrolright ()
27013 "Switch to next TODO set."
27014 (interactive)
27015 (cond
27016 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27017 (t (org-shiftcursor-error))))
27019 (defun org-shiftcontrolleft ()
27020 "Switch to previous TODO set."
27021 (interactive)
27022 (cond
27023 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27024 (t (org-shiftcursor-error))))
27026 (defun org-ctrl-c-ret ()
27027 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27028 (interactive)
27029 (cond
27030 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27031 (t (call-interactively 'org-insert-heading))))
27033 (defun org-copy-special ()
27034 "Copy region in table or copy current subtree.
27035 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27036 See the individual commands for more information."
27037 (interactive)
27038 (call-interactively
27039 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27041 (defun org-cut-special ()
27042 "Cut region in table or cut current subtree.
27043 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27044 See the individual commands for more information."
27045 (interactive)
27046 (call-interactively
27047 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27049 (defun org-paste-special (arg)
27050 "Paste rectangular region into table, or past subtree relative to level.
27051 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27052 See the individual commands for more information."
27053 (interactive "P")
27054 (if (org-at-table-p)
27055 (org-table-paste-rectangle)
27056 (org-paste-subtree arg)))
27058 (defun org-ctrl-c-ctrl-c (&optional arg)
27059 "Set tags in headline, or update according to changed information at point.
27061 This command does many different things, depending on context:
27063 - If the cursor is in a headline, prompt for tags and insert them
27064 into the current line, aligned to `org-tags-column'. When called
27065 with prefix arg, realign all tags in the current buffer.
27067 - If the cursor is in one of the special #+KEYWORD lines, this
27068 triggers scanning the buffer for these lines and updating the
27069 information.
27071 - If the cursor is inside a table, realign the table. This command
27072 works even if the automatic table editor has been turned off.
27074 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27075 the entire table.
27077 - If the cursor is a the beginning of a dynamic block, update it.
27079 - If the cursor is inside a table created by the table.el package,
27080 activate that table.
27082 - If the current buffer is a remember buffer, close note and file it.
27083 with a prefix argument, file it without further interaction to the default
27084 location.
27086 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27087 links in this buffer.
27089 - If the cursor is on a numbered item in a plain list, renumber the
27090 ordered list.
27092 - If the cursor is on a checkbox, toggle it."
27093 (interactive "P")
27094 (let ((org-enable-table-editor t))
27095 (cond
27096 ((or org-clock-overlays
27097 org-occur-highlights
27098 org-latex-fragment-image-overlays)
27099 (org-remove-clock-overlays)
27100 (org-remove-occur-highlights)
27101 (org-remove-latex-fragment-image-overlays)
27102 (message "Temporary highlights/overlays removed from current buffer"))
27103 ((and (local-variable-p 'org-finish-function (current-buffer))
27104 (fboundp org-finish-function))
27105 (funcall org-finish-function))
27106 ((org-at-property-p)
27107 (call-interactively 'org-property-action))
27108 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27109 ((org-on-heading-p) (call-interactively 'org-set-tags))
27110 ((org-at-table.el-p)
27111 (require 'table)
27112 (beginning-of-line 1)
27113 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27114 (call-interactively 'table-recognize-table))
27115 ((org-at-table-p)
27116 (org-table-maybe-eval-formula)
27117 (if arg
27118 (call-interactively 'org-table-recalculate)
27119 (org-table-maybe-recalculate-line))
27120 (call-interactively 'org-table-align))
27121 ((org-at-item-checkbox-p)
27122 (call-interactively 'org-toggle-checkbox))
27123 ((org-at-item-p)
27124 (call-interactively 'org-maybe-renumber-ordered-list))
27125 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27126 ;; Dynamic block
27127 (beginning-of-line 1)
27128 (org-update-dblock))
27129 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27130 (cond
27131 ((equal (match-string 1) "TBLFM")
27132 ;; Recalculate the table before this line
27133 (save-excursion
27134 (beginning-of-line 1)
27135 (skip-chars-backward " \r\n\t")
27136 (if (org-at-table-p)
27137 (org-call-with-arg 'org-table-recalculate t))))
27139 (call-interactively 'org-mode-restart))))
27140 (t (error "C-c C-c can do nothing useful at this location.")))))
27142 (defun org-mode-restart ()
27143 "Restart Org-mode, to scan again for special lines.
27144 Also updates the keyword regular expressions."
27145 (interactive)
27146 (let ((org-inhibit-startup t)) (org-mode))
27147 (message "Org-mode restarted to refresh keyword and special line setup"))
27149 (defun org-kill-note-or-show-branches ()
27150 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27151 (interactive)
27152 (if (not org-finish-function)
27153 (call-interactively 'show-branches)
27154 (let ((org-note-abort t))
27155 (funcall org-finish-function))))
27157 (defun org-return (&optional indent)
27158 "Goto next table row or insert a newline.
27159 Calls `org-table-next-row' or `newline', depending on context.
27160 See the individual commands for more information."
27161 (interactive)
27162 (cond
27163 ((bobp) (if indent (newline-and-indent) (newline)))
27164 ((and (org-at-heading-p)
27165 (looking-at
27166 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27167 (org-show-entry)
27168 (end-of-line 1)
27169 (newline))
27170 ((org-at-table-p)
27171 (org-table-justify-field-maybe)
27172 (call-interactively 'org-table-next-row))
27173 (t (if indent (newline-and-indent) (newline)))))
27175 (defun org-return-indent ()
27176 (interactive)
27177 "Goto next table row or insert a newline and indent.
27178 Calls `org-table-next-row' or `newline-and-indent', depending on
27179 context. See the individual commands for more information."
27180 (org-return t))
27182 (defun org-ctrl-c-minus ()
27183 "Insert separator line in table or modify bullet type in list.
27184 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27185 depending on context."
27186 (interactive)
27187 (cond
27188 ((org-at-table-p)
27189 (call-interactively 'org-table-insert-hline))
27190 ((org-on-heading-p)
27191 ;; Convert to item
27192 (save-excursion
27193 (beginning-of-line 1)
27194 (if (looking-at "\\*+ ")
27195 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27196 ((org-in-item-p)
27197 (call-interactively 'org-cycle-list-bullet))
27198 (t (error "`C-c -' does have no function here."))))
27200 (defun org-meta-return (&optional arg)
27201 "Insert a new heading or wrap a region in a table.
27202 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27203 See the individual commands for more information."
27204 (interactive "P")
27205 (cond
27206 ((org-at-table-p)
27207 (call-interactively 'org-table-wrap-region))
27208 (t (call-interactively 'org-insert-heading))))
27210 ;;; Menu entries
27212 ;; Define the Org-mode menus
27213 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27214 '("Tbl"
27215 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27216 ["Next Field" org-cycle (org-at-table-p)]
27217 ["Previous Field" org-shifttab (org-at-table-p)]
27218 ["Next Row" org-return (org-at-table-p)]
27219 "--"
27220 ["Blank Field" org-table-blank-field (org-at-table-p)]
27221 ["Edit Field" org-table-edit-field (org-at-table-p)]
27222 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27223 "--"
27224 ("Column"
27225 ["Move Column Left" org-metaleft (org-at-table-p)]
27226 ["Move Column Right" org-metaright (org-at-table-p)]
27227 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27228 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27229 ("Row"
27230 ["Move Row Up" org-metaup (org-at-table-p)]
27231 ["Move Row Down" org-metadown (org-at-table-p)]
27232 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27233 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27234 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27235 "--"
27236 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27237 ("Rectangle"
27238 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27239 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27240 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27241 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27242 "--"
27243 ("Calculate"
27244 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27245 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27246 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27247 "--"
27248 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27249 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27250 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27251 "--"
27252 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27253 "--"
27254 ["Sum Column/Rectangle" org-table-sum
27255 (or (org-at-table-p) (org-region-active-p))]
27256 ["Which Column?" org-table-current-column (org-at-table-p)])
27257 ["Debug Formulas"
27258 org-table-toggle-formula-debugger
27259 :style toggle :selected org-table-formula-debug]
27260 ["Show Col/Row Numbers"
27261 org-table-toggle-coordinate-overlays
27262 :style toggle :selected org-table-overlay-coordinates]
27263 "--"
27264 ["Create" org-table-create (and (not (org-at-table-p))
27265 org-enable-table-editor)]
27266 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27267 ["Import from File" org-table-import (not (org-at-table-p))]
27268 ["Export to File" org-table-export (org-at-table-p)]
27269 "--"
27270 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27272 (easy-menu-define org-org-menu org-mode-map "Org menu"
27273 '("Org"
27274 ("Show/Hide"
27275 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27276 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27277 ["Sparse Tree" org-occur t]
27278 ["Reveal Context" org-reveal t]
27279 ["Show All" show-all t]
27280 "--"
27281 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27282 "--"
27283 ["New Heading" org-insert-heading t]
27284 ("Navigate Headings"
27285 ["Up" outline-up-heading t]
27286 ["Next" outline-next-visible-heading t]
27287 ["Previous" outline-previous-visible-heading t]
27288 ["Next Same Level" outline-forward-same-level t]
27289 ["Previous Same Level" outline-backward-same-level t]
27290 "--"
27291 ["Jump" org-goto t])
27292 ("Edit Structure"
27293 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27294 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27295 "--"
27296 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27297 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27298 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27299 "--"
27300 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27301 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27302 ["Demote Heading" org-metaright (not (org-at-table-p))]
27303 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27304 "--"
27305 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27306 "--"
27307 ["Convert to odd levels" org-convert-to-odd-levels t]
27308 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27309 ("Editing"
27310 ["Emphasis..." org-emphasize t])
27311 ("Archive"
27312 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27313 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27314 ; :active t :keys "C-u C-c C-x C-a"]
27315 ["Sparse trees open ARCHIVE trees"
27316 (setq org-sparse-tree-open-archived-trees
27317 (not org-sparse-tree-open-archived-trees))
27318 :style toggle :selected org-sparse-tree-open-archived-trees]
27319 ["Cycling opens ARCHIVE trees"
27320 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27321 :style toggle :selected org-cycle-open-archived-trees]
27322 ["Agenda includes ARCHIVE trees"
27323 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27324 :style toggle :selected (not org-agenda-skip-archived-trees)]
27325 "--"
27326 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27327 ; ["Check and Move Children" (org-archive-subtree '(4))
27328 ; :active t :keys "C-u C-c C-x C-s"]
27330 "--"
27331 ("TODO Lists"
27332 ["TODO/DONE/-" org-todo t]
27333 ("Select keyword"
27334 ["Next keyword" org-shiftright (org-on-heading-p)]
27335 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27336 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27337 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27338 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27339 ["Show TODO Tree" org-show-todo-tree t]
27340 ["Global TODO list" org-todo-list t]
27341 "--"
27342 ["Set Priority" org-priority t]
27343 ["Priority Up" org-shiftup t]
27344 ["Priority Down" org-shiftdown t])
27345 ("TAGS and Properties"
27346 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27347 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27348 "--"
27349 ["Set property" 'org-set-property t]
27350 ["Column view of properties" org-columns t]
27351 ["Insert Column View DBlock" org-insert-columns-dblock t])
27352 ("Dates and Scheduling"
27353 ["Timestamp" org-time-stamp t]
27354 ["Timestamp (inactive)" org-time-stamp-inactive t]
27355 ("Change Date"
27356 ["1 Day Later" org-shiftright t]
27357 ["1 Day Earlier" org-shiftleft t]
27358 ["1 ... Later" org-shiftup t]
27359 ["1 ... Earlier" org-shiftdown t])
27360 ["Compute Time Range" org-evaluate-time-range t]
27361 ["Schedule Item" org-schedule t]
27362 ["Deadline" org-deadline t]
27363 "--"
27364 ["Custom time format" org-toggle-time-stamp-overlays
27365 :style radio :selected org-display-custom-times]
27366 "--"
27367 ["Goto Calendar" org-goto-calendar t]
27368 ["Date from Calendar" org-date-from-calendar t])
27369 ("Logging work"
27370 ["Clock in" org-clock-in t]
27371 ["Clock out" org-clock-out t]
27372 ["Clock cancel" org-clock-cancel t]
27373 ["Goto running clock" org-clock-goto t]
27374 ["Display times" org-clock-display t]
27375 ["Create clock table" org-clock-report t]
27376 "--"
27377 ["Record DONE time"
27378 (progn (setq org-log-done (not org-log-done))
27379 (message "Switching to %s will %s record a timestamp"
27380 (car org-done-keywords)
27381 (if org-log-done "automatically" "not")))
27382 :style toggle :selected org-log-done])
27383 "--"
27384 ["Agenda Command..." org-agenda t]
27385 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27386 ("File List for Agenda")
27387 ("Special views current file"
27388 ["TODO Tree" org-show-todo-tree t]
27389 ["Check Deadlines" org-check-deadlines t]
27390 ["Timeline" org-timeline t]
27391 ["Tags Tree" org-tags-sparse-tree t])
27392 "--"
27393 ("Hyperlinks"
27394 ["Store Link (Global)" org-store-link t]
27395 ["Insert Link" org-insert-link t]
27396 ["Follow Link" org-open-at-point t]
27397 "--"
27398 ["Next link" org-next-link t]
27399 ["Previous link" org-previous-link t]
27400 "--"
27401 ["Descriptive Links"
27402 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27403 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27404 ["Literal Links"
27405 (progn
27406 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27407 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27408 "--"
27409 ["Export/Publish..." org-export t]
27410 ("LaTeX"
27411 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27412 :selected org-cdlatex-mode]
27413 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27414 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27415 ["Modify math symbol" org-cdlatex-math-modify
27416 (org-inside-LaTeX-fragment-p)]
27417 ["Export LaTeX fragments as images"
27418 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27419 :style toggle :selected org-export-with-LaTeX-fragments])
27420 "--"
27421 ("Documentation"
27422 ["Show Version" org-version t]
27423 ["Info Documentation" org-info t])
27424 ("Customize"
27425 ["Browse Org Group" org-customize t]
27426 "--"
27427 ["Expand This Menu" org-create-customize-menu
27428 (fboundp 'customize-menu-create)])
27429 "--"
27430 ["Refresh setup" org-mode-restart t]
27433 (defun org-info (&optional node)
27434 "Read documentation for Org-mode in the info system.
27435 With optional NODE, go directly to that node."
27436 (interactive)
27437 (require 'info)
27438 (Info-goto-node (format "(org)%s" (or node ""))))
27440 (defun org-install-agenda-files-menu ()
27441 (let ((bl (buffer-list)))
27442 (save-excursion
27443 (while bl
27444 (set-buffer (pop bl))
27445 (if (org-mode-p) (setq bl nil)))
27446 (when (org-mode-p)
27447 (easy-menu-change
27448 '("Org") "File List for Agenda"
27449 (append
27450 (list
27451 ["Edit File List" (org-edit-agenda-file-list) t]
27452 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27453 ["Remove Current File from List" org-remove-file t]
27454 ["Cycle through agenda files" org-cycle-agenda-files t]
27455 ["Occur in all agenda files" org-occur-in-agenda-files t]
27456 "--")
27457 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27459 ;;;; Documentation
27461 (defun org-customize ()
27462 "Call the customize function with org as argument."
27463 (interactive)
27464 (customize-browse 'org))
27466 (defun org-create-customize-menu ()
27467 "Create a full customization menu for Org-mode, insert it into the menu."
27468 (interactive)
27469 (if (fboundp 'customize-menu-create)
27470 (progn
27471 (easy-menu-change
27472 '("Org") "Customize"
27473 `(["Browse Org group" org-customize t]
27474 "--"
27475 ,(customize-menu-create 'org)
27476 ["Set" Custom-set t]
27477 ["Save" Custom-save t]
27478 ["Reset to Current" Custom-reset-current t]
27479 ["Reset to Saved" Custom-reset-saved t]
27480 ["Reset to Standard Settings" Custom-reset-standard t]))
27481 (message "\"Org\"-menu now contains full customization menu"))
27482 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27484 ;;;; Miscellaneous stuff
27487 ;;; Generally useful functions
27489 (defun org-context ()
27490 "Return a list of contexts of the current cursor position.
27491 If several contexts apply, all are returned.
27492 Each context entry is a list with a symbol naming the context, and
27493 two positions indicating start and end of the context. Possible
27494 contexts are:
27496 :headline anywhere in a headline
27497 :headline-stars on the leading stars in a headline
27498 :todo-keyword on a TODO keyword (including DONE) in a headline
27499 :tags on the TAGS in a headline
27500 :priority on the priority cookie in a headline
27501 :item on the first line of a plain list item
27502 :item-bullet on the bullet/number of a plain list item
27503 :checkbox on the checkbox in a plain list item
27504 :table in an org-mode table
27505 :table-special on a special filed in a table
27506 :table-table in a table.el table
27507 :link on a hyperlink
27508 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27509 :target on a <<target>>
27510 :radio-target on a <<<radio-target>>>
27511 :latex-fragment on a LaTeX fragment
27512 :latex-preview on a LaTeX fragment with overlayed preview image
27514 This function expects the position to be visible because it uses font-lock
27515 faces as a help to recognize the following contexts: :table-special, :link,
27516 and :keyword."
27517 (let* ((f (get-text-property (point) 'face))
27518 (faces (if (listp f) f (list f)))
27519 (p (point)) clist o)
27520 ;; First the large context
27521 (cond
27522 ((org-on-heading-p t)
27523 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27524 (when (progn
27525 (beginning-of-line 1)
27526 (looking-at org-todo-line-tags-regexp))
27527 (push (org-point-in-group p 1 :headline-stars) clist)
27528 (push (org-point-in-group p 2 :todo-keyword) clist)
27529 (push (org-point-in-group p 4 :tags) clist))
27530 (goto-char p)
27531 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27532 (if (looking-at "\\[#[A-Z0-9]\\]")
27533 (push (org-point-in-group p 0 :priority) clist)))
27535 ((org-at-item-p)
27536 (push (org-point-in-group p 2 :item-bullet) clist)
27537 (push (list :item (point-at-bol)
27538 (save-excursion (org-end-of-item) (point)))
27539 clist)
27540 (and (org-at-item-checkbox-p)
27541 (push (org-point-in-group p 0 :checkbox) clist)))
27543 ((org-at-table-p)
27544 (push (list :table (org-table-begin) (org-table-end)) clist)
27545 (if (memq 'org-formula faces)
27546 (push (list :table-special
27547 (previous-single-property-change p 'face)
27548 (next-single-property-change p 'face)) clist)))
27549 ((org-at-table-p 'any)
27550 (push (list :table-table) clist)))
27551 (goto-char p)
27553 ;; Now the small context
27554 (cond
27555 ((org-at-timestamp-p)
27556 (push (org-point-in-group p 0 :timestamp) clist))
27557 ((memq 'org-link faces)
27558 (push (list :link
27559 (previous-single-property-change p 'face)
27560 (next-single-property-change p 'face)) clist))
27561 ((memq 'org-special-keyword faces)
27562 (push (list :keyword
27563 (previous-single-property-change p 'face)
27564 (next-single-property-change p 'face)) clist))
27565 ((org-on-target-p)
27566 (push (org-point-in-group p 0 :target) clist)
27567 (goto-char (1- (match-beginning 0)))
27568 (if (looking-at org-radio-target-regexp)
27569 (push (org-point-in-group p 0 :radio-target) clist))
27570 (goto-char p))
27571 ((setq o (car (delq nil
27572 (mapcar
27573 (lambda (x)
27574 (if (memq x org-latex-fragment-image-overlays) x))
27575 (org-overlays-at (point))))))
27576 (push (list :latex-fragment
27577 (org-overlay-start o) (org-overlay-end o)) clist)
27578 (push (list :latex-preview
27579 (org-overlay-start o) (org-overlay-end o)) clist))
27580 ((org-inside-LaTeX-fragment-p)
27581 ;; FIXME: positions wrong.
27582 (push (list :latex-fragment (point) (point)) clist)))
27584 (setq clist (nreverse (delq nil clist)))
27585 clist))
27587 ;; FIXME: Compare with at-regexp-p Do we need both?
27588 (defun org-in-regexp (re &optional nlines visually)
27589 "Check if point is inside a match of regexp.
27590 Normally only the current line is checked, but you can include NLINES extra
27591 lines both before and after point into the search.
27592 If VISUALLY is set, require that the cursor is not after the match but
27593 really on, so that the block visually is on the match."
27594 (catch 'exit
27595 (let ((pos (point))
27596 (eol (point-at-eol (+ 1 (or nlines 0))))
27597 (inc (if visually 1 0)))
27598 (save-excursion
27599 (beginning-of-line (- 1 (or nlines 0)))
27600 (while (re-search-forward re eol t)
27601 (if (and (<= (match-beginning 0) pos)
27602 (>= (+ inc (match-end 0)) pos))
27603 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27605 (defun org-at-regexp-p (regexp)
27606 "Is point inside a match of REGEXP in the current line?"
27607 (catch 'exit
27608 (save-excursion
27609 (let ((pos (point)) (end (point-at-eol)))
27610 (beginning-of-line 1)
27611 (while (re-search-forward regexp end t)
27612 (if (and (<= (match-beginning 0) pos)
27613 (>= (match-end 0) pos))
27614 (throw 'exit t)))
27615 nil))))
27617 (defun org-occur-in-agenda-files (regexp &optional nlines)
27618 "Call `multi-occur' with buffers for all agenda files."
27619 (interactive "sOrg-files matching: \np")
27620 (let* ((files (org-agenda-files))
27621 (tnames (mapcar 'file-truename files))
27622 (extra org-agenda-multi-occur-extra-files)
27624 (while (setq f (pop extra))
27625 (unless (member (file-truename f) tnames)
27626 (add-to-list 'files f 'append)
27627 (add-to-list 'tnames (file-truename f) 'append)))
27628 (multi-occur
27629 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27630 regexp)))
27632 (if (boundp 'occur-mode-find-occurrence-hook)
27633 ;; Emacs 23
27634 (add-hook 'occur-mode-find-occurrence-hook
27635 (lambda ()
27636 (when (org-mode-p)
27637 (org-reveal))))
27638 ;; Emacs 22
27639 (defadvice occur-mode-goto-occurrence
27640 (after org-occur-reveal activate)
27641 (and (org-mode-p) (org-reveal)))
27642 (defadvice occur-mode-goto-occurrence-other-window
27643 (after org-occur-reveal activate)
27644 (and (org-mode-p) (org-reveal)))
27645 (defadvice occur-mode-display-occurrence
27646 (after org-occur-reveal activate)
27647 (when (org-mode-p)
27648 (let ((pos (occur-mode-find-occurrence)))
27649 (with-current-buffer (marker-buffer pos)
27650 (save-excursion
27651 (goto-char pos)
27652 (org-reveal)))))))
27654 (defun org-uniquify (list)
27655 "Remove duplicate elements from LIST."
27656 (let (res)
27657 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27658 res))
27660 (defun org-delete-all (elts list)
27661 "Remove all elements in ELTS from LIST."
27662 (while elts
27663 (setq list (delete (pop elts) list)))
27664 list)
27666 (defun org-back-over-empty-lines ()
27667 "Move backwards over witespace, to the beginning of the first empty line.
27668 Returns the number o empty lines passed."
27669 (let ((pos (point)))
27670 (skip-chars-backward " \t\n\r")
27671 (beginning-of-line 2)
27672 (goto-char (min (point) pos))
27673 (count-lines (point) pos)))
27675 (defun org-skip-whitespace ()
27676 (skip-chars-forward " \t\n\r"))
27678 (defun org-point-in-group (point group &optional context)
27679 "Check if POINT is in match-group GROUP.
27680 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27681 match. If the match group does ot exist or point is not inside it,
27682 return nil."
27683 (and (match-beginning group)
27684 (>= point (match-beginning group))
27685 (<= point (match-end group))
27686 (if context
27687 (list context (match-beginning group) (match-end group))
27688 t)))
27690 (defun org-switch-to-buffer-other-window (&rest args)
27691 "Switch to buffer in a second window on the current frame.
27692 In particular, do not allow pop-up frames."
27693 (let (pop-up-frames special-display-buffer-names special-display-regexps
27694 special-display-function)
27695 (apply 'switch-to-buffer-other-window args)))
27697 (defun org-combine-plists (&rest plists)
27698 "Create a single property list from all plists in PLISTS.
27699 The process starts by copying the first list, and then setting properties
27700 from the other lists. Settings in the last list are the most significant
27701 ones and overrule settings in the other lists."
27702 (let ((rtn (copy-sequence (pop plists)))
27703 p v ls)
27704 (while plists
27705 (setq ls (pop plists))
27706 (while ls
27707 (setq p (pop ls) v (pop ls))
27708 (setq rtn (plist-put rtn p v))))
27709 rtn))
27711 (defun org-move-line-down (arg)
27712 "Move the current line down. With prefix argument, move it past ARG lines."
27713 (interactive "p")
27714 (let ((col (current-column))
27715 beg end pos)
27716 (beginning-of-line 1) (setq beg (point))
27717 (beginning-of-line 2) (setq end (point))
27718 (beginning-of-line (+ 1 arg))
27719 (setq pos (move-marker (make-marker) (point)))
27720 (insert (delete-and-extract-region beg end))
27721 (goto-char pos)
27722 (move-to-column col)))
27724 (defun org-move-line-up (arg)
27725 "Move the current line up. With prefix argument, move it past ARG lines."
27726 (interactive "p")
27727 (let ((col (current-column))
27728 beg end pos)
27729 (beginning-of-line 1) (setq beg (point))
27730 (beginning-of-line 2) (setq end (point))
27731 (beginning-of-line (- arg))
27732 (setq pos (move-marker (make-marker) (point)))
27733 (insert (delete-and-extract-region beg end))
27734 (goto-char pos)
27735 (move-to-column col)))
27737 (defun org-replace-escapes (string table)
27738 "Replace %-escapes in STRING with values in TABLE.
27739 TABLE is an association list with keys like \"%a\" and string values.
27740 The sequences in STRING may contain normal field width and padding information,
27741 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27742 so values can contain further %-escapes if they are define later in TABLE."
27743 (let ((case-fold-search nil)
27744 e re rpl)
27745 (while (setq e (pop table))
27746 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27747 (while (string-match re string)
27748 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27749 (cdr e)))
27750 (setq string (replace-match rpl t t string))))
27751 string))
27754 (defun org-sublist (list start end)
27755 "Return a section of LIST, from START to END.
27756 Counting starts at 1."
27757 (let (rtn (c start))
27758 (setq list (nthcdr (1- start) list))
27759 (while (and list (<= c end))
27760 (push (pop list) rtn)
27761 (setq c (1+ c)))
27762 (nreverse rtn)))
27764 (defun org-find-base-buffer-visiting (file)
27765 "Like `find-buffer-visiting' but alway return the base buffer and
27766 not an indirect buffer"
27767 (let ((buf (find-buffer-visiting file)))
27768 (if buf
27769 (or (buffer-base-buffer buf) buf)
27770 nil)))
27772 (defun org-image-file-name-regexp ()
27773 "Return regexp matching the file names of images."
27774 (if (fboundp 'image-file-name-regexp)
27775 (image-file-name-regexp)
27776 (let ((image-file-name-extensions
27777 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27778 "xbm" "xpm" "pbm" "pgm" "ppm")))
27779 (concat "\\."
27780 (regexp-opt (nconc (mapcar 'upcase
27781 image-file-name-extensions)
27782 image-file-name-extensions)
27784 "\\'"))))
27786 (defun org-file-image-p (file)
27787 "Return non-nil if FILE is an image."
27788 (save-match-data
27789 (string-match (org-image-file-name-regexp) file)))
27791 ;;; Paragraph filling stuff.
27792 ;; We want this to be just right, so use the full arsenal.
27794 (defun org-indent-line-function ()
27795 "Indent line like previous, but further if previous was headline or item."
27796 (interactive)
27797 (let* ((pos (point))
27798 (itemp (org-at-item-p))
27799 column bpos bcol tpos tcol bullet btype bullet-type)
27800 ;; Find the previous relevant line
27801 (beginning-of-line 1)
27802 (cond
27803 ((looking-at "#") (setq column 0))
27804 ((looking-at "\\*+ ") (setq column 0))
27806 (beginning-of-line 0)
27807 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27808 (beginning-of-line 0))
27809 (cond
27810 ((looking-at "\\*+[ \t]+")
27811 (goto-char (match-end 0))
27812 (setq column (current-column)))
27813 ((org-in-item-p)
27814 (org-beginning-of-item)
27815 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27816 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27817 (setq bpos (match-beginning 1) tpos (match-end 0)
27818 bcol (progn (goto-char bpos) (current-column))
27819 tcol (progn (goto-char tpos) (current-column))
27820 bullet (match-string 1)
27821 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27822 (if (not itemp)
27823 (setq column tcol)
27824 (goto-char pos)
27825 (beginning-of-line 1)
27826 (if (looking-at "\\S-")
27827 (progn
27828 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27829 (setq bullet (match-string 1)
27830 btype (if (string-match "[0-9]" bullet) "n" bullet))
27831 (setq column (if (equal btype bullet-type) bcol tcol)))
27832 (setq column (org-get-indentation)))))
27833 (t (setq column (org-get-indentation))))))
27834 (goto-char pos)
27835 (if (<= (current-column) (current-indentation))
27836 (indent-line-to column)
27837 (save-excursion (indent-line-to column)))
27838 (setq column (current-column))
27839 (beginning-of-line 1)
27840 (if (looking-at
27841 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27842 (replace-match (concat "\\1" (format org-property-format
27843 (match-string 2) (match-string 3)))
27844 t nil))
27845 (move-to-column column)))
27847 (defun org-set-autofill-regexps ()
27848 (interactive)
27849 ;; In the paragraph separator we include headlines, because filling
27850 ;; text in a line directly attached to a headline would otherwise
27851 ;; fill the headline as well.
27852 (org-set-local 'comment-start-skip "^#+[ \t]*")
27853 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27854 ;; The paragraph starter includes hand-formatted lists.
27855 (org-set-local 'paragraph-start
27856 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27857 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27858 ;; But only if the user has not turned off tables or fixed-width regions
27859 (org-set-local
27860 'auto-fill-inhibit-regexp
27861 (concat "\\*+ \\|#\\+"
27862 "\\|[ \t]*" org-keyword-time-regexp
27863 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27864 (concat
27865 "\\|[ \t]*["
27866 (if org-enable-table-editor "|" "")
27867 (if org-enable-fixed-width-editor ":" "")
27868 "]"))))
27869 ;; We use our own fill-paragraph function, to make sure that tables
27870 ;; and fixed-width regions are not wrapped. That function will pass
27871 ;; through to `fill-paragraph' when appropriate.
27872 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27873 ; Adaptive filling: To get full control, first make sure that
27874 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27875 (org-set-local 'adaptive-fill-regexp "\000")
27876 (org-set-local 'adaptive-fill-function
27877 'org-adaptive-fill-function)
27878 (org-set-local
27879 'align-mode-rules-list
27880 '((org-in-buffer-settings
27881 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27882 (modes . '(org-mode))))))
27884 (defun org-fill-paragraph (&optional justify)
27885 "Re-align a table, pass through to fill-paragraph if no table."
27886 (let ((table-p (org-at-table-p))
27887 (table.el-p (org-at-table.el-p)))
27888 (cond ((and (equal (char-after (point-at-bol)) ?*)
27889 (save-excursion (goto-char (point-at-bol))
27890 (looking-at outline-regexp)))
27891 t) ; skip headlines
27892 (table.el-p t) ; skip table.el tables
27893 (table-p (org-table-align) t) ; align org-mode tables
27894 (t nil)))) ; call paragraph-fill
27896 ;; For reference, this is the default value of adaptive-fill-regexp
27897 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27899 (defun org-adaptive-fill-function ()
27900 "Return a fill prefix for org-mode files.
27901 In particular, this makes sure hanging paragraphs for hand-formatted lists
27902 work correctly."
27903 (cond ((looking-at "#[ \t]+")
27904 (match-string 0))
27905 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27906 (save-excursion
27907 (goto-char (match-end 0))
27908 (make-string (current-column) ?\ )))
27909 (t nil)))
27911 ;;;; Functions extending outline functionality
27914 (defun org-beginning-of-line (&optional arg)
27915 "Go to the beginning of the current line. If that is invisible, continue
27916 to a visible line beginning. This makes the function of C-a more intuitive.
27917 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27918 first attempt, and only move to after the tags when the cursor is already
27919 beyond the end of the headline."
27920 (interactive "P")
27921 (let ((pos (point)))
27922 (beginning-of-line 1)
27923 (if (bobp)
27925 (backward-char 1)
27926 (if (org-invisible-p)
27927 (while (and (not (bobp)) (org-invisible-p))
27928 (backward-char 1)
27929 (beginning-of-line 1))
27930 (forward-char 1)))
27931 (when org-special-ctrl-a/e
27932 (cond
27933 ((and (looking-at org-todo-line-regexp)
27934 (= (char-after (match-end 1)) ?\ ))
27935 (goto-char
27936 (if (eq org-special-ctrl-a/e t)
27937 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27938 ((= pos (point)) (match-beginning 3))
27939 (t (point)))
27940 (cond ((> pos (point)) (point))
27941 ((not (eq last-command this-command)) (point))
27942 (t (match-beginning 3))))))
27943 ((org-at-item-p)
27944 (goto-char
27945 (if (eq org-special-ctrl-a/e t)
27946 (cond ((> pos (match-end 4)) (match-end 4))
27947 ((= pos (point)) (match-end 4))
27948 (t (point)))
27949 (cond ((> pos (point)) (point))
27950 ((not (eq last-command this-command)) (point))
27951 (t (match-end 4))))))))))
27953 (defun org-end-of-line (&optional arg)
27954 "Go to the end of the line.
27955 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27956 first attempt, and only move to after the tags when the cursor is already
27957 beyond the end of the headline."
27958 (interactive "P")
27959 (if (or (not org-special-ctrl-a/e)
27960 (not (org-on-heading-p)))
27961 (end-of-line arg)
27962 (let ((pos (point)))
27963 (beginning-of-line 1)
27964 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27965 (if (eq org-special-ctrl-a/e t)
27966 (if (or (< pos (match-beginning 1))
27967 (= pos (match-end 0)))
27968 (goto-char (match-beginning 1))
27969 (goto-char (match-end 0)))
27970 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27971 (goto-char (match-end 0))
27972 (goto-char (match-beginning 1))))
27973 (end-of-line arg)))))
27975 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27976 (define-key org-mode-map "\C-e" 'org-end-of-line)
27978 (defun org-kill-line (&optional arg)
27979 "Kill line, to tags or end of line."
27980 (interactive "P")
27981 (cond
27982 ((or (not org-special-ctrl-k)
27983 (bolp)
27984 (not (org-on-heading-p)))
27985 (call-interactively 'kill-line))
27986 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27987 (kill-region (point) (match-beginning 1))
27988 (org-set-tags nil t))
27989 (t (kill-region (point) (point-at-eol)))))
27991 (define-key org-mode-map "\C-k" 'org-kill-line)
27993 (defun org-invisible-p ()
27994 "Check if point is at a character currently not visible."
27995 ;; Early versions of noutline don't have `outline-invisible-p'.
27996 (if (fboundp 'outline-invisible-p)
27997 (outline-invisible-p)
27998 (get-char-property (point) 'invisible)))
28000 (defun org-invisible-p2 ()
28001 "Check if point is at a character currently not visible."
28002 (save-excursion
28003 (if (and (eolp) (not (bobp))) (backward-char 1))
28004 ;; Early versions of noutline don't have `outline-invisible-p'.
28005 (if (fboundp 'outline-invisible-p)
28006 (outline-invisible-p)
28007 (get-char-property (point) 'invisible))))
28009 (defalias 'org-back-to-heading 'outline-back-to-heading)
28010 (defalias 'org-on-heading-p 'outline-on-heading-p)
28011 (defalias 'org-at-heading-p 'outline-on-heading-p)
28012 (defun org-at-heading-or-item-p ()
28013 (or (org-on-heading-p) (org-at-item-p)))
28015 (defun org-on-target-p ()
28016 (or (org-in-regexp org-radio-target-regexp)
28017 (org-in-regexp org-target-regexp)))
28019 (defun org-up-heading-all (arg)
28020 "Move to the heading line of which the present line is a subheading.
28021 This function considers both visible and invisible heading lines.
28022 With argument, move up ARG levels."
28023 (if (fboundp 'outline-up-heading-all)
28024 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28025 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28027 (defun org-up-heading-safe ()
28028 "Move to the heading line of which the present line is a subheading.
28029 This version will not throw an error. It will return the level of the
28030 headline found, or nil if no higher level is found."
28031 (let ((pos (point)) start-level level
28032 (re (concat "^" outline-regexp)))
28033 (catch 'exit
28034 (outline-back-to-heading t)
28035 (setq start-level (funcall outline-level))
28036 (if (equal start-level 1) (throw 'exit nil))
28037 (while (re-search-backward re nil t)
28038 (setq level (funcall outline-level))
28039 (if (< level start-level) (throw 'exit level)))
28040 nil)))
28042 (defun org-first-sibling-p ()
28043 "Is this heading the first child of its parents?"
28044 (interactive)
28045 (let ((re (concat "^" outline-regexp))
28046 level l)
28047 (unless (org-at-heading-p t)
28048 (error "Not at a heading"))
28049 (setq level (funcall outline-level))
28050 (save-excursion
28051 (if (not (re-search-backward re nil t))
28053 (setq l (funcall outline-level))
28054 (< l level)))))
28056 (defun org-goto-sibling (&optional previous)
28057 "Goto the next sibling, even if it is invisible.
28058 When PREVIOUS is set, go to the previous sibling instead. Returns t
28059 when a sibling was found. When none is found, return nil and don't
28060 move point."
28061 (let ((fun (if previous 're-search-backward 're-search-forward))
28062 (pos (point))
28063 (re (concat "^" outline-regexp))
28064 level l)
28065 (when (condition-case nil (org-back-to-heading t) (error nil))
28066 (setq level (funcall outline-level))
28067 (catch 'exit
28068 (or previous (forward-char 1))
28069 (while (funcall fun re nil t)
28070 (setq l (funcall outline-level))
28071 (when (< l level) (goto-char pos) (throw 'exit nil))
28072 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28073 (goto-char pos)
28074 nil))))
28076 (defun org-show-siblings ()
28077 "Show all siblings of the current headline."
28078 (save-excursion
28079 (while (org-goto-sibling) (org-flag-heading nil)))
28080 (save-excursion
28081 (while (org-goto-sibling 'previous)
28082 (org-flag-heading nil))))
28084 (defun org-show-hidden-entry ()
28085 "Show an entry where even the heading is hidden."
28086 (save-excursion
28087 (org-show-entry)))
28089 (defun org-flag-heading (flag &optional entry)
28090 "Flag the current heading. FLAG non-nil means make invisible.
28091 When ENTRY is non-nil, show the entire entry."
28092 (save-excursion
28093 (org-back-to-heading t)
28094 ;; Check if we should show the entire entry
28095 (if entry
28096 (progn
28097 (org-show-entry)
28098 (save-excursion
28099 (and (outline-next-heading)
28100 (org-flag-heading nil))))
28101 (outline-flag-region (max (point-min) (1- (point)))
28102 (save-excursion (outline-end-of-heading) (point))
28103 flag))))
28105 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28106 ;; This is an exact copy of the original function, but it uses
28107 ;; `org-back-to-heading', to make it work also in invisible
28108 ;; trees. And is uses an invisible-OK argument.
28109 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28110 (org-back-to-heading invisible-OK)
28111 (let ((first t)
28112 (level (funcall outline-level)))
28113 (while (and (not (eobp))
28114 (or first (> (funcall outline-level) level)))
28115 (setq first nil)
28116 (outline-next-heading))
28117 (unless to-heading
28118 (if (memq (preceding-char) '(?\n ?\^M))
28119 (progn
28120 ;; Go to end of line before heading
28121 (forward-char -1)
28122 (if (memq (preceding-char) '(?\n ?\^M))
28123 ;; leave blank line before heading
28124 (forward-char -1))))))
28125 (point))
28127 (defun org-show-subtree ()
28128 "Show everything after this heading at deeper levels."
28129 (outline-flag-region
28130 (point)
28131 (save-excursion
28132 (outline-end-of-subtree) (outline-next-heading) (point))
28133 nil))
28135 (defun org-show-entry ()
28136 "Show the body directly following this heading.
28137 Show the heading too, if it is currently invisible."
28138 (interactive)
28139 (save-excursion
28140 (condition-case nil
28141 (progn
28142 (org-back-to-heading t)
28143 (outline-flag-region
28144 (max (point-min) (1- (point)))
28145 (save-excursion
28146 (re-search-forward
28147 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28148 (or (match-beginning 1) (point-max)))
28149 nil))
28150 (error nil))))
28152 (defun org-make-options-regexp (kwds)
28153 "Make a regular expression for keyword lines."
28154 (concat
28156 "#?[ \t]*\\+\\("
28157 (mapconcat 'regexp-quote kwds "\\|")
28158 "\\):[ \t]*"
28159 "\\(.+\\)"))
28161 ;; Make isearch reveal the necessary context
28162 (defun org-isearch-end ()
28163 "Reveal context after isearch exits."
28164 (when isearch-success ; only if search was successful
28165 (if (featurep 'xemacs)
28166 ;; Under XEmacs, the hook is run in the correct place,
28167 ;; we directly show the context.
28168 (org-show-context 'isearch)
28169 ;; In Emacs the hook runs *before* restoring the overlays.
28170 ;; So we have to use a one-time post-command-hook to do this.
28171 ;; (Emacs 22 has a special variable, see function `org-mode')
28172 (unless (and (boundp 'isearch-mode-end-hook-quit)
28173 isearch-mode-end-hook-quit)
28174 ;; Only when the isearch was not quitted.
28175 (org-add-hook 'post-command-hook 'org-isearch-post-command
28176 'append 'local)))))
28178 (defun org-isearch-post-command ()
28179 "Remove self from hook, and show context."
28180 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28181 (org-show-context 'isearch))
28184 ;;;; Integration with and fixes for other packages
28186 ;;; Imenu support
28188 (defvar org-imenu-markers nil
28189 "All markers currently used by Imenu.")
28190 (make-variable-buffer-local 'org-imenu-markers)
28192 (defun org-imenu-new-marker (&optional pos)
28193 "Return a new marker for use by Imenu, and remember the marker."
28194 (let ((m (make-marker)))
28195 (move-marker m (or pos (point)))
28196 (push m org-imenu-markers)
28199 (defun org-imenu-get-tree ()
28200 "Produce the index for Imenu."
28201 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28202 (setq org-imenu-markers nil)
28203 (let* ((n org-imenu-depth)
28204 (re (concat "^" outline-regexp))
28205 (subs (make-vector (1+ n) nil))
28206 (last-level 0)
28207 m tree level head)
28208 (save-excursion
28209 (save-restriction
28210 (widen)
28211 (goto-char (point-max))
28212 (while (re-search-backward re nil t)
28213 (setq level (org-reduced-level (funcall outline-level)))
28214 (when (<= level n)
28215 (looking-at org-complex-heading-regexp)
28216 (setq head (org-match-string-no-properties 4)
28217 m (org-imenu-new-marker))
28218 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28219 (if (>= level last-level)
28220 (push (cons head m) (aref subs level))
28221 (push (cons head (aref subs (1+ level))) (aref subs level))
28222 (loop for i from (1+ level) to n do (aset subs i nil)))
28223 (setq last-level level)))))
28224 (aref subs 1)))
28226 (eval-after-load "imenu"
28227 '(progn
28228 (add-hook 'imenu-after-jump-hook
28229 (lambda () (org-show-context 'org-goto)))))
28231 ;; Speedbar support
28233 (defun org-speedbar-set-agenda-restriction ()
28234 "Restrict future agenda commands to the location at point in speedbar.
28235 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28236 (interactive)
28237 (let (p m tp np dir txt w)
28238 (cond
28239 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28240 'org-imenu t))
28241 (setq m (get-text-property p 'org-imenu-marker))
28242 (save-excursion
28243 (save-restriction
28244 (set-buffer (marker-buffer m))
28245 (goto-char m)
28246 (org-agenda-set-restriction-lock 'subtree))))
28247 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28248 'speedbar-function 'speedbar-find-file))
28249 (setq tp (previous-single-property-change
28250 (1+ p) 'speedbar-function)
28251 np (next-single-property-change
28252 tp 'speedbar-function)
28253 dir (speedbar-line-directory)
28254 txt (buffer-substring-no-properties (or tp (point-min))
28255 (or np (point-max))))
28256 (save-excursion
28257 (save-restriction
28258 (set-buffer (find-file-noselect
28259 (let ((default-directory dir))
28260 (expand-file-name txt))))
28261 (unless (org-mode-p)
28262 (error "Cannot restrict to non-Org-mode file"))
28263 (org-agenda-set-restriction-lock 'file))))
28264 (t (error "Don't know how to restrict Org-mode's agenda")))
28265 (org-move-overlay org-speedbar-restriction-lock-overlay
28266 (point-at-bol) (point-at-eol))
28267 (setq current-prefix-arg nil)
28268 (org-agenda-maybe-redo)))
28270 (eval-after-load "speedbar"
28271 '(progn
28272 (speedbar-add-supported-extension ".org")
28273 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28274 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28275 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28276 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28277 (add-hook 'speedbar-visiting-tag-hook
28278 (lambda () (org-show-context 'org-goto)))))
28281 ;;; Fixes and Hacks
28283 ;; Make flyspell not check words in links, to not mess up our keymap
28284 (defun org-mode-flyspell-verify ()
28285 "Don't let flyspell put overlays at active buttons."
28286 (not (get-text-property (point) 'keymap)))
28288 ;; Make `bookmark-jump' show the jump location if it was hidden.
28289 (eval-after-load "bookmark"
28290 '(if (boundp 'bookmark-after-jump-hook)
28291 ;; We can use the hook
28292 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28293 ;; Hook not available, use advice
28294 (defadvice bookmark-jump (after org-make-visible activate)
28295 "Make the position visible."
28296 (org-bookmark-jump-unhide))))
28298 (defun org-bookmark-jump-unhide ()
28299 "Unhide the current position, to show the bookmark location."
28300 (and (org-mode-p)
28301 (or (org-invisible-p)
28302 (save-excursion (goto-char (max (point-min) (1- (point))))
28303 (org-invisible-p)))
28304 (org-show-context 'bookmark-jump)))
28306 ;; Fix a bug in htmlize where there are text properties (face nil)
28307 (eval-after-load "htmlize"
28308 '(progn
28309 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28310 "Make sure there are no nil faces"
28311 (setq ad-return-value (delq nil ad-return-value)))))
28313 ;; Make session.el ignore our circular variable
28314 (eval-after-load "session"
28315 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28317 ;;;; Experimental code
28319 (defun org-closed-in-range ()
28320 "Sparse tree of items closed in a certain time range.
28321 Still experimental, may disappear in the future."
28322 (interactive)
28323 ;; Get the time interval from the user.
28324 (let* ((time1 (time-to-seconds
28325 (org-read-date nil 'to-time nil "Starting date: ")))
28326 (time2 (time-to-seconds
28327 (org-read-date nil 'to-time nil "End date:")))
28328 ;; callback function
28329 (callback (lambda ()
28330 (let ((time
28331 (time-to-seconds
28332 (apply 'encode-time
28333 (org-parse-time-string
28334 (match-string 1))))))
28335 ;; check if time in interval
28336 (and (>= time time1) (<= time time2))))))
28337 ;; make tree, check each match with the callback
28338 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28340 ;;;; Finish up
28342 (provide 'org)
28344 (run-hooks 'org-load-hook)
28346 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28347 ;;; org.el ends here