Merge branch 'master' of git+ssh://repo.or.cz/srv/git/org-mode
[org-mode.git] / org.el
blobbafe6082084c4dec6a58c6e23a9d845a8aee717c
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)))
174 (defun org-load-default-extensions ()
175 "Load all extensions that are listed in `org-default-extensions'."
176 (mapc 'require org-default-extensions))
178 ;; FIXME: Needs a separate group...
179 (defcustom org-completion-fallback-command 'hippie-expand
180 "The expansion command called by \\[org-complete] in normal context.
181 Normal means, no org-mode-specific context."
182 :group 'org
183 :type 'function)
185 (defgroup org-startup nil
186 "Options concerning startup of Org-mode."
187 :tag "Org Startup"
188 :group 'org)
190 (defcustom org-startup-folded t
191 "Non-nil means, entering Org-mode will switch to OVERVIEW.
192 This can also be configured on a per-file basis by adding one of
193 the following lines anywhere in the buffer:
195 #+STARTUP: fold
196 #+STARTUP: nofold
197 #+STARTUP: content"
198 :group 'org-startup
199 :type '(choice
200 (const :tag "nofold: show all" nil)
201 (const :tag "fold: overview" t)
202 (const :tag "content: all headlines" content)))
204 (defcustom org-startup-truncated t
205 "Non-nil means, entering Org-mode will set `truncate-lines'.
206 This is useful since some lines containing links can be very long and
207 uninteresting. Also tables look terrible when wrapped."
208 :group 'org-startup
209 :type 'boolean)
211 (defcustom org-startup-align-all-tables nil
212 "Non-nil means, align all tables when visiting a file.
213 This is useful when the column width in tables is forced with <N> cookies
214 in table fields. Such tables will look correct only after the first re-align.
215 This can also be configured on a per-file basis by adding one of
216 the following lines anywhere in the buffer:
217 #+STARTUP: align
218 #+STARTUP: noalign"
219 :group 'org-startup
220 :type 'boolean)
222 (defcustom org-insert-mode-line-in-empty-file nil
223 "Non-nil means insert the first line setting Org-mode in empty files.
224 When the function `org-mode' is called interactively in an empty file, this
225 normally means that the file name does not automatically trigger Org-mode.
226 To ensure that the file will always be in Org-mode in the future, a
227 line enforcing Org-mode will be inserted into the buffer, if this option
228 has been set."
229 :group 'org-startup
230 :type 'boolean)
232 (defcustom org-replace-disputed-keys nil
233 "Non-nil means use alternative key bindings for some keys.
234 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
235 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
236 If you want to use Org-mode together with one of these other modes,
237 or more generally if you would like to move some Org-mode commands to
238 other keys, set this variable and configure the keys with the variable
239 `org-disputed-keys'.
241 This option is only relevant at load-time of Org-mode, and must be set
242 *before* org.el is loaded. Changing it requires a restart of Emacs to
243 become effective."
244 :group 'org-startup
245 :type 'boolean)
247 (if (fboundp 'defvaralias)
248 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
250 (defcustom org-disputed-keys
251 '(([(shift up)] . [(meta p)])
252 ([(shift down)] . [(meta n)])
253 ([(shift left)] . [(meta -)])
254 ([(shift right)] . [(meta +)])
255 ([(control shift right)] . [(meta shift +)])
256 ([(control shift left)] . [(meta shift -)]))
257 "Keys for which Org-mode and other modes compete.
258 This is an alist, cars are the default keys, second element specifies
259 the alternative to use when `org-replace-disputed-keys' is t.
261 Keys can be specified in any syntax supported by `define-key'.
262 The value of this option takes effect only at Org-mode's startup,
263 therefore you'll have to restart Emacs to apply it after changing."
264 :group 'org-startup
265 :type 'alist)
267 (defun org-key (key)
268 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
269 Or return the original if not disputed."
270 (if org-replace-disputed-keys
271 (let* ((nkey (key-description key))
272 (x (org-find-if (lambda (x)
273 (equal (key-description (car x)) nkey))
274 org-disputed-keys)))
275 (if x (cdr x) key))
276 key))
278 (defun org-find-if (predicate seq)
279 (catch 'exit
280 (while seq
281 (if (funcall predicate (car seq))
282 (throw 'exit (car seq))
283 (pop seq)))))
285 (defun org-defkey (keymap key def)
286 "Define a key, possibly translated, as returned by `org-key'."
287 (define-key keymap (org-key key) def))
289 (defcustom org-ellipsis nil
290 "The ellipsis to use in the Org-mode outline.
291 When nil, just use the standard three dots. When a string, use that instead,
292 When a face, use the standart 3 dots, but with the specified face.
293 The change affects only Org-mode (which will then use its own display table).
294 Changing this requires executing `M-x org-mode' in a buffer to become
295 effective."
296 :group 'org-startup
297 :type '(choice (const :tag "Default" nil)
298 (face :tag "Face" :value org-warning)
299 (string :tag "String" :value "...#")))
301 (defvar org-display-table nil
302 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
304 (defgroup org-keywords nil
305 "Keywords in Org-mode."
306 :tag "Org Keywords"
307 :group 'org)
309 (defcustom org-deadline-string "DEADLINE:"
310 "String to mark deadline entries.
311 A deadline is this string, followed by a time stamp. Should be a word,
312 terminated by a colon. You can insert a schedule keyword and
313 a timestamp with \\[org-deadline].
314 Changes become only effective after restarting Emacs."
315 :group 'org-keywords
316 :type 'string)
318 (defcustom org-scheduled-string "SCHEDULED:"
319 "String to mark scheduled TODO entries.
320 A schedule is this string, followed by a time stamp. Should be a word,
321 terminated by a colon. You can insert a schedule keyword and
322 a timestamp with \\[org-schedule].
323 Changes become only effective after restarting Emacs."
324 :group 'org-keywords
325 :type 'string)
327 (defcustom org-closed-string "CLOSED:"
328 "String used as the prefix for timestamps logging closing a TODO entry."
329 :group 'org-keywords
330 :type 'string)
332 (defcustom org-clock-string "CLOCK:"
333 "String used as prefix for timestamps clocking work hours on an item."
334 :group 'org-keywords
335 :type 'string)
337 (defcustom org-comment-string "COMMENT"
338 "Entries starting with this keyword will never be exported.
339 An entry can be toggled between COMMENT and normal with
340 \\[org-toggle-comment].
341 Changes become only effective after restarting Emacs."
342 :group 'org-keywords
343 :type 'string)
345 (defcustom org-quote-string "QUOTE"
346 "Entries starting with this keyword will be exported in fixed-width font.
347 Quoting applies only to the text in the entry following the headline, and does
348 not extend beyond the next headline, even if that is lower level.
349 An entry can be toggled between QUOTE and normal with
350 \\[org-toggle-fixed-width-section]."
351 :group 'org-keywords
352 :type 'string)
354 (defconst org-repeat-re
355 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
356 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
357 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
358 "Regular expression for specifying repeated events.
359 After a match, group 1 contains the repeat expression.")
361 (defgroup org-structure nil
362 "Options concerning the general structure of Org-mode files."
363 :tag "Org Structure"
364 :group 'org)
366 (defgroup org-reveal-location nil
367 "Options about how to make context of a location visible."
368 :tag "Org Reveal Location"
369 :group 'org-structure)
371 (defconst org-context-choice
372 '(choice
373 (const :tag "Always" t)
374 (const :tag "Never" nil)
375 (repeat :greedy t :tag "Individual contexts"
376 (cons
377 (choice :tag "Context"
378 (const agenda)
379 (const org-goto)
380 (const occur-tree)
381 (const tags-tree)
382 (const link-search)
383 (const mark-goto)
384 (const bookmark-jump)
385 (const isearch)
386 (const default))
387 (boolean))))
388 "Contexts for the reveal options.")
390 (defcustom org-show-hierarchy-above '((default . t))
391 "Non-nil means, show full hierarchy when revealing a location.
392 Org-mode often shows locations in an org-mode file which might have
393 been invisible before. When this is set, the hierarchy of headings
394 above the exposed location is shown.
395 Turning this off for example for sparse trees makes them very compact.
396 Instead of t, this can also be an alist specifying this option for different
397 contexts. Valid contexts are
398 agenda when exposing an entry from the agenda
399 org-goto when using the command `org-goto' on key C-c C-j
400 occur-tree when using the command `org-occur' on key C-c /
401 tags-tree when constructing a sparse tree based on tags matches
402 link-search when exposing search matches associated with a link
403 mark-goto when exposing the jump goal of a mark
404 bookmark-jump when exposing a bookmark location
405 isearch when exiting from an incremental search
406 default default for all contexts not set explicitly"
407 :group 'org-reveal-location
408 :type org-context-choice)
410 (defcustom org-show-following-heading '((default . nil))
411 "Non-nil means, show following heading when revealing a location.
412 Org-mode often shows locations in an org-mode file which might have
413 been invisible before. When this is set, the heading following the
414 match is shown.
415 Turning this off for example for sparse trees makes them very compact,
416 but makes it harder to edit the location of the match. In such a case,
417 use the command \\[org-reveal] to show more context.
418 Instead of t, this can also be an alist specifying this option for different
419 contexts. See `org-show-hierarchy-above' for valid contexts."
420 :group 'org-reveal-location
421 :type org-context-choice)
423 (defcustom org-show-siblings '((default . nil) (isearch t))
424 "Non-nil means, show all sibling heading when revealing a location.
425 Org-mode often shows locations in an org-mode file which might have
426 been invisible before. When this is set, the sibling of the current entry
427 heading are all made visible. If `org-show-hierarchy-above' is t,
428 the same happens on each level of the hierarchy above the current entry.
430 By default this is on for the isearch context, off for all other contexts.
431 Turning this off for example for sparse trees makes them very compact,
432 but makes it harder to edit the location of the match. In such a case,
433 use the command \\[org-reveal] to show more context.
434 Instead of t, this can also be an alist specifying this option for different
435 contexts. See `org-show-hierarchy-above' for valid contexts."
436 :group 'org-reveal-location
437 :type org-context-choice)
439 (defcustom org-show-entry-below '((default . nil))
440 "Non-nil means, show the entry below a headline when revealing a location.
441 Org-mode often shows locations in an org-mode file which might have
442 been invisible before. When this is set, the text below the headline that is
443 exposed is also shown.
445 By default this is off for all contexts.
446 Instead of t, this can also be an alist specifying this option for different
447 contexts. See `org-show-hierarchy-above' for valid contexts."
448 :group 'org-reveal-location
449 :type org-context-choice)
451 (defgroup org-cycle nil
452 "Options concerning visibility cycling in Org-mode."
453 :tag "Org Cycle"
454 :group 'org-structure)
456 (defcustom org-drawers '("PROPERTIES" "CLOCK")
457 "Names of drawers. Drawers are not opened by cycling on the headline above.
458 Drawers only open with a TAB on the drawer line itself. A drawer looks like
459 this:
460 :DRAWERNAME:
461 .....
462 :END:
463 The drawer \"PROPERTIES\" is special for capturing properties through
464 the property API.
466 Drawers can be defined on the per-file basis with a line like:
468 #+DRAWERS: HIDDEN STATE PROPERTIES"
469 :group 'org-structure
470 :type '(repeat (string :tag "Drawer Name")))
472 (defcustom org-cycle-global-at-bob nil
473 "Cycle globally if cursor is at beginning of buffer and not at a headline.
474 This makes it possible to do global cycling without having to use S-TAB or
475 C-u TAB. For this special case to work, the first line of the buffer
476 must not be a headline - it may be empty ot some other text. When used in
477 this way, `org-cycle-hook' is disables temporarily, to make sure the
478 cursor stays at the beginning of the buffer.
479 When this option is nil, don't do anything special at the beginning
480 of the buffer."
481 :group 'org-cycle
482 :type 'boolean)
484 (defcustom org-cycle-emulate-tab t
485 "Where should `org-cycle' emulate TAB.
486 nil Never
487 white Only in completely white lines
488 whitestart Only at the beginning of lines, before the first non-white char
489 t Everywhere except in headlines
490 exc-hl-bol Everywhere except at the start of a headline
491 If TAB is used in a place where it does not emulate TAB, the current subtree
492 visibility is cycled."
493 :group 'org-cycle
494 :type '(choice (const :tag "Never" nil)
495 (const :tag "Only in completely white lines" white)
496 (const :tag "Before first char in a line" whitestart)
497 (const :tag "Everywhere except in headlines" t)
498 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
501 (defcustom org-cycle-separator-lines 2
502 "Number of empty lines needed to keep an empty line between collapsed trees.
503 If you leave an empty line between the end of a subtree and the following
504 headline, this empty line is hidden when the subtree is folded.
505 Org-mode will leave (exactly) one empty line visible if the number of
506 empty lines is equal or larger to the number given in this variable.
507 So the default 2 means, at least 2 empty lines after the end of a subtree
508 are needed to produce free space between a collapsed subtree and the
509 following headline.
511 Special case: when 0, never leave empty lines in collapsed view."
512 :group 'org-cycle
513 :type 'integer)
515 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
516 org-cycle-hide-drawers
517 org-cycle-show-empty-lines
518 org-optimize-window-after-visibility-change)
519 "Hook that is run after `org-cycle' has changed the buffer visibility.
520 The function(s) in this hook must accept a single argument which indicates
521 the new state that was set by the most recent `org-cycle' command. The
522 argument is a symbol. After a global state change, it can have the values
523 `overview', `content', or `all'. After a local state change, it can have
524 the values `folded', `children', or `subtree'."
525 :group 'org-cycle
526 :type 'hook)
528 (defgroup org-edit-structure nil
529 "Options concerning structure editing in Org-mode."
530 :tag "Org Edit Structure"
531 :group 'org-structure)
533 (defcustom org-odd-levels-only nil
534 "Non-nil means, skip even levels and only use odd levels for the outline.
535 This has the effect that two stars are being added/taken away in
536 promotion/demotion commands. It also influences how levels are
537 handled by the exporters.
538 Changing it requires restart of `font-lock-mode' to become effective
539 for fontification also in regions already fontified.
540 You may also set this on a per-file basis by adding one of the following
541 lines to the buffer:
543 #+STARTUP: odd
544 #+STARTUP: oddeven"
545 :group 'org-edit-structure
546 :group 'org-font-lock
547 :type 'boolean)
549 (defcustom org-adapt-indentation t
550 "Non-nil means, adapt indentation when promoting and demoting.
551 When this is set and the *entire* text in an entry is indented, the
552 indentation is increased by one space in a demotion command, and
553 decreased by one in a promotion command. If any line in the entry
554 body starts at column 0, indentation is not changed at all."
555 :group 'org-edit-structure
556 :type 'boolean)
558 (defcustom org-special-ctrl-a/e nil
559 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
560 When t, `C-a' will bring back the cursor to the beginning of the
561 headline text, i.e. after the stars and after a possible TODO keyword.
562 In an item, this will be the position after the bullet.
563 When the cursor is already at that position, another `C-a' will bring
564 it to the beginning of the line.
565 `C-e' will jump to the end of the headline, ignoring the presence of tags
566 in the headline. A second `C-e' will then jump to the true end of the
567 line, after any tags.
568 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
569 and only a directly following, identical keypress will bring the cursor
570 to the special positions."
571 :group 'org-edit-structure
572 :type '(choice
573 (const :tag "off" nil)
574 (const :tag "after bullet first" t)
575 (const :tag "border first" reversed)))
577 (if (fboundp 'defvaralias)
578 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
580 (defcustom org-special-ctrl-k nil
581 "Non-nil means `C-k' will behave specially in headlines.
582 When nil, `C-k' will call the default `kill-line' command.
583 When t, the following will happen while the cursor is in the headline:
585 - When the cursor is at the beginning of a headline, kill the entire
586 line and possible the folded subtree below the line.
587 - When in the middle of the headline text, kill the headline up to the tags.
588 - When after the headline text, kill the tags."
589 :group 'org-edit-structure
590 :type 'boolean)
592 (defcustom org-M-RET-may-split-line '((default . t))
593 "Non-nil means, M-RET will split the line at the cursor position.
594 When nil, it will go to the end of the line before making a
595 new line.
596 You may also set this option in a different way for different
597 contexts. Valid contexts are:
599 headline when creating a new headline
600 item when creating a new item
601 table in a table field
602 default the value to be used for all contexts not explicitly
603 customized"
604 :group 'org-structure
605 :group 'org-table
606 :type '(choice
607 (const :tag "Always" t)
608 (const :tag "Never" nil)
609 (repeat :greedy t :tag "Individual contexts"
610 (cons
611 (choice :tag "Context"
612 (const headline)
613 (const item)
614 (const table)
615 (const default))
616 (boolean)))))
619 (defcustom org-blank-before-new-entry '((heading . nil)
620 (plain-list-item . nil))
621 "Should `org-insert-heading' leave a blank line before new heading/item?
622 The value is an alist, with `heading' and `plain-list-item' as car,
623 and a boolean flag as cdr."
624 :group 'org-edit-structure
625 :type '(list
626 (cons (const heading) (boolean))
627 (cons (const plain-list-item) (boolean))))
629 (defcustom org-insert-heading-hook nil
630 "Hook being run after inserting a new heading."
631 :group 'org-edit-structure
632 :type 'hook)
634 (defcustom org-enable-fixed-width-editor t
635 "Non-nil means, lines starting with \":\" are treated as fixed-width.
636 This currently only means, they are never auto-wrapped.
637 When nil, such lines will be treated like ordinary lines.
638 See also the QUOTE keyword."
639 :group 'org-edit-structure
640 :type 'boolean)
642 (defcustom org-goto-auto-isearch t
643 "Non-nil means, typing characters in org-goto starts incremental search."
644 :group 'org-edit-structure
645 :type 'boolean)
647 (defgroup org-sparse-trees nil
648 "Options concerning sparse trees in Org-mode."
649 :tag "Org Sparse Trees"
650 :group 'org-structure)
652 (defcustom org-highlight-sparse-tree-matches t
653 "Non-nil means, highlight all matches that define a sparse tree.
654 The highlights will automatically disappear the next time the buffer is
655 changed by an edit command."
656 :group 'org-sparse-trees
657 :type 'boolean)
659 (defcustom org-remove-highlights-with-change t
660 "Non-nil means, any change to the buffer will remove temporary highlights.
661 Such highlights are created by `org-occur' and `org-clock-display'.
662 When nil, `C-c C-c needs to be used to get rid of the highlights.
663 The highlights created by `org-preview-latex-fragment' always need
664 `C-c C-c' to be removed."
665 :group 'org-sparse-trees
666 :group 'org-time
667 :type 'boolean)
670 (defcustom org-occur-hook '(org-first-headline-recenter)
671 "Hook that is run after `org-occur' has constructed a sparse tree.
672 This can be used to recenter the window to show as much of the structure
673 as possible."
674 :group 'org-sparse-trees
675 :type 'hook)
677 (defgroup org-plain-lists nil
678 "Options concerning plain lists in Org-mode."
679 :tag "Org Plain lists"
680 :group 'org-structure)
682 (defcustom org-cycle-include-plain-lists nil
683 "Non-nil means, include plain lists into visibility cycling.
684 This means that during cycling, plain list items will *temporarily* be
685 interpreted as outline headlines with a level given by 1000+i where i is the
686 indentation of the bullet. In all other operations, plain list items are
687 not seen as headlines. For example, you cannot assign a TODO keyword to
688 such an item."
689 :group 'org-plain-lists
690 :type 'boolean)
692 (defcustom org-plain-list-ordered-item-terminator t
693 "The character that makes a line with leading number an ordered list item.
694 Valid values are ?. and ?\). To get both terminators, use t. While
695 ?. may look nicer, it creates the danger that a line with leading
696 number may be incorrectly interpreted as an item. ?\) therefore is
697 the safe choice."
698 :group 'org-plain-lists
699 :type '(choice (const :tag "dot like in \"2.\"" ?.)
700 (const :tag "paren like in \"2)\"" ?\))
701 (const :tab "both" t)))
703 (defcustom org-auto-renumber-ordered-lists t
704 "Non-nil means, automatically renumber ordered plain lists.
705 Renumbering happens when the sequence have been changed with
706 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
707 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
708 :group 'org-plain-lists
709 :type 'boolean)
711 (defcustom org-provide-checkbox-statistics t
712 "Non-nil means, update checkbox statistics after insert and toggle.
713 When this is set, checkbox statistics is updated each time you either insert
714 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
715 with \\[org-ctrl-c-ctrl-c\\]."
716 :group 'org-plain-lists
717 :type 'boolean)
719 (defgroup org-archive nil
720 "Options concerning archiving in Org-mode."
721 :tag "Org Archive"
722 :group 'org-structure)
724 (defcustom org-archive-tag "ARCHIVE"
725 "The tag that marks a subtree as archived.
726 An archived subtree does not open during visibility cycling, and does
727 not contribute to the agenda listings.
728 After changing this, font-lock must be restarted in the relevant buffers to
729 get the proper fontification."
730 :group 'org-archive
731 :group 'org-keywords
732 :type 'string)
734 (defcustom org-agenda-skip-archived-trees t
735 "Non-nil means, the agenda will skip any items located in archived trees.
736 An archived tree is a tree marked with the tag ARCHIVE."
737 :group 'org-archive
738 :group 'org-agenda-skip
739 :type 'boolean)
741 (defcustom org-cycle-open-archived-trees nil
742 "Non-nil means, `org-cycle' will open archived trees.
743 An archived tree is a tree marked with the tag ARCHIVE.
744 When nil, archived trees will stay folded. You can still open them with
745 normal outline commands like `show-all', but not with the cycling commands."
746 :group 'org-archive
747 :group 'org-cycle
748 :type 'boolean)
750 (defcustom org-sparse-tree-open-archived-trees nil
751 "Non-nil means sparse tree construction shows matches in archived trees.
752 When nil, matches in these trees are highlighted, but the trees are kept in
753 collapsed state."
754 :group 'org-archive
755 :group 'org-sparse-trees
756 :type 'boolean)
758 (defcustom org-archive-location "%s_archive::"
759 "The location where subtrees should be archived.
760 This string consists of two parts, separated by a double-colon.
762 The first part is a file name - when omitted, archiving happens in the same
763 file. %s will be replaced by the current file name (without directory part).
764 Archiving to a different file is useful to keep archived entries from
765 contributing to the Org-mode Agenda.
767 The part after the double colon is a headline. The archived entries will be
768 filed under that headline. When omitted, the subtrees are simply filed away
769 at the end of the file, as top-level entries.
771 Here are a few examples:
772 \"%s_archive::\"
773 If the current file is Projects.org, archive in file
774 Projects.org_archive, as top-level trees. This is the default.
776 \"::* Archived Tasks\"
777 Archive in the current file, under the top-level headline
778 \"* Archived Tasks\".
780 \"~/org/archive.org::\"
781 Archive in file ~/org/archive.org (absolute path), as top-level trees.
783 \"basement::** Finished Tasks\"
784 Archive in file ./basement (relative path), as level 3 trees
785 below the level 2 heading \"** Finished Tasks\".
787 You may set this option on a per-file basis by adding to the buffer a
788 line like
790 #+ARCHIVE: basement::** Finished Tasks"
791 :group 'org-archive
792 :type 'string)
794 (defcustom org-archive-mark-done t
795 "Non-nil means, mark entries as DONE when they are moved to the archive file.
796 This can be a string to set the keyword to use. When t, Org-mode will
797 use the first keyword in its list that means done."
798 :group 'org-archive
799 :type '(choice
800 (const :tag "No" nil)
801 (const :tag "Yes" t)
802 (string :tag "Use this keyword")))
804 (defcustom org-archive-stamp-time t
805 "Non-nil means, add a time stamp to entries moved to an archive file.
806 This variable is obsolete and has no effect anymore, instead add ot remove
807 `time' from the variablle `org-archive-save-context-info'."
808 :group 'org-archive
809 :type 'boolean)
811 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
812 "Parts of context info that should be stored as properties when archiving.
813 When a subtree is moved to an archive file, it looses information given by
814 context, like inherited tags, the category, and possibly also the TODO
815 state (depending on the variable `org-archive-mark-done').
816 This variable can be a list of any of the following symbols:
818 time The time of archiving.
819 file The file where the entry originates.
820 itags The local tags, in the headline of the subtree.
821 ltags The tags the subtree inherits from further up the hierarchy.
822 todo The pre-archive TODO state.
823 category The category, taken from file name or #+CATEGORY lines.
824 olpath The outline path to the item. These are all headlines above
825 the current item, separated by /, like a file path.
827 For each symbol present in the list, a property will be created in
828 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
829 information."
830 :group 'org-archive
831 :type '(set :greedy t
832 (const :tag "Time" time)
833 (const :tag "File" file)
834 (const :tag "Category" category)
835 (const :tag "TODO state" todo)
836 (const :tag "TODO state" priority)
837 (const :tag "Inherited tags" itags)
838 (const :tag "Outline path" olpath)
839 (const :tag "Local tags" ltags)))
841 (defgroup org-imenu-and-speedbar nil
842 "Options concerning imenu and speedbar in Org-mode."
843 :tag "Org Imenu and Speedbar"
844 :group 'org-structure)
846 (defcustom org-imenu-depth 2
847 "The maximum level for Imenu access to Org-mode headlines.
848 This also applied for speedbar access."
849 :group 'org-imenu-and-speedbar
850 :type 'number)
852 (defgroup org-table nil
853 "Options concerning tables in Org-mode."
854 :tag "Org Table"
855 :group 'org)
857 (defcustom org-enable-table-editor 'optimized
858 "Non-nil means, lines starting with \"|\" are handled by the table editor.
859 When nil, such lines will be treated like ordinary lines.
861 When equal to the symbol `optimized', the table editor will be optimized to
862 do the following:
863 - Automatic overwrite mode in front of whitespace in table fields.
864 This makes the structure of the table stay in tact as long as the edited
865 field does not exceed the column width.
866 - Minimize the number of realigns. Normally, the table is aligned each time
867 TAB or RET are pressed to move to another field. With optimization this
868 happens only if changes to a field might have changed the column width.
869 Optimization requires replacing the functions `self-insert-command',
870 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
871 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
872 very good at guessing when a re-align will be necessary, but you can always
873 force one with \\[org-ctrl-c-ctrl-c].
875 If you would like to use the optimized version in Org-mode, but the
876 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
878 This variable can be used to turn on and off the table editor during a session,
879 but in order to toggle optimization, a restart is required.
881 See also the variable `org-table-auto-blank-field'."
882 :group 'org-table
883 :type '(choice
884 (const :tag "off" nil)
885 (const :tag "on" t)
886 (const :tag "on, optimized" optimized)))
888 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
889 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
890 In the optimized version, the table editor takes over all simple keys that
891 normally just insert a character. In tables, the characters are inserted
892 in a way to minimize disturbing the table structure (i.e. in overwrite mode
893 for empty fields). Outside tables, the correct binding of the keys is
894 restored.
896 The default for this option is t if the optimized version is also used in
897 Org-mode. See the variable `org-enable-table-editor' for details. Changing
898 this variable requires a restart of Emacs to become effective."
899 :group 'org-table
900 :type 'boolean)
902 (defcustom orgtbl-radio-table-templates
903 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
904 % END RECEIVE ORGTBL %n
905 \\begin{comment}
906 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
907 | | |
908 \\end{comment}\n")
909 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
910 @c END RECEIVE ORGTBL %n
911 @ignore
912 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
913 | | |
914 @end ignore\n")
915 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
916 <!-- END RECEIVE ORGTBL %n -->
917 <!--
918 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
919 | | |
920 -->\n"))
921 "Templates for radio tables in different major modes.
922 All occurrences of %n in a template will be replaced with the name of the
923 table, obtained by prompting the user."
924 :group 'org-table
925 :type '(repeat
926 (list (symbol :tag "Major mode")
927 (string :tag "Format"))))
929 (defgroup org-table-settings nil
930 "Settings for tables in Org-mode."
931 :tag "Org Table Settings"
932 :group 'org-table)
934 (defcustom org-table-default-size "5x2"
935 "The default size for newly created tables, Columns x Rows."
936 :group 'org-table-settings
937 :type 'string)
939 (defcustom org-table-number-regexp
940 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
941 "Regular expression for recognizing numbers in table columns.
942 If a table column contains mostly numbers, it will be aligned to the
943 right. If not, it will be aligned to the left.
945 The default value of this option is a regular expression which allows
946 anything which looks remotely like a number as used in scientific
947 context. For example, all of the following will be considered a
948 number:
949 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
951 Other options offered by the customize interface are more restrictive."
952 :group 'org-table-settings
953 :type '(choice
954 (const :tag "Positive Integers"
955 "^[0-9]+$")
956 (const :tag "Integers"
957 "^[-+]?[0-9]+$")
958 (const :tag "Floating Point Numbers"
959 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
960 (const :tag "Floating Point Number or Integer"
961 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
962 (const :tag "Exponential, Floating point, Integer"
963 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
964 (const :tag "Very General Number-Like, including hex"
965 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
966 (string :tag "Regexp:")))
968 (defcustom org-table-number-fraction 0.5
969 "Fraction of numbers in a column required to make the column align right.
970 In a column all non-white fields are considered. If at least this
971 fraction of fields is matched by `org-table-number-fraction',
972 alignment to the right border applies."
973 :group 'org-table-settings
974 :type 'number)
976 (defgroup org-table-editing nil
977 "Behavior of tables during editing in Org-mode."
978 :tag "Org Table Editing"
979 :group 'org-table)
981 (defcustom org-table-automatic-realign t
982 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
983 When nil, aligning is only done with \\[org-table-align], or after column
984 removal/insertion."
985 :group 'org-table-editing
986 :type 'boolean)
988 (defcustom org-table-auto-blank-field t
989 "Non-nil means, automatically blank table field when starting to type into it.
990 This only happens when typing immediately after a field motion
991 command (TAB, S-TAB or RET).
992 Only relevant when `org-enable-table-editor' is equal to `optimized'."
993 :group 'org-table-editing
994 :type 'boolean)
996 (defcustom org-table-tab-jumps-over-hlines t
997 "Non-nil means, tab in the last column of a table with jump over a hline.
998 If a horizontal separator line is following the current line,
999 `org-table-next-field' can either create a new row before that line, or jump
1000 over the line. When this option is nil, a new line will be created before
1001 this line."
1002 :group 'org-table-editing
1003 :type 'boolean)
1005 (defcustom org-table-tab-recognizes-table.el t
1006 "Non-nil means, TAB will automatically notice a table.el table.
1007 When it sees such a table, it moves point into it and - if necessary -
1008 calls `table-recognize-table'."
1009 :group 'org-table-editing
1010 :type 'boolean)
1012 (defgroup org-table-calculation nil
1013 "Options concerning tables in Org-mode."
1014 :tag "Org Table Calculation"
1015 :group 'org-table)
1017 (defcustom org-table-use-standard-references t
1018 "Should org-mode work with table refrences like B3 instead of @3$2?
1019 Possible values are:
1020 nil never use them
1021 from accept as input, do not present for editing
1022 t: accept as input and present for editing"
1023 :group 'org-table-calculation
1024 :type '(choice
1025 (const :tag "Never, don't even check unser input for them" nil)
1026 (const :tag "Always, both as user input, and when editing" t)
1027 (const :tag "Convert user input, don't offer during editing" 'from)))
1029 (defcustom org-table-copy-increment t
1030 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1031 :group 'org-table-calculation
1032 :type 'boolean)
1034 (defcustom org-calc-default-modes
1035 '(calc-internal-prec 12
1036 calc-float-format (float 5)
1037 calc-angle-mode deg
1038 calc-prefer-frac nil
1039 calc-symbolic-mode nil
1040 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1041 calc-display-working-message t
1043 "List with Calc mode settings for use in calc-eval for table formulas.
1044 The list must contain alternating symbols (Calc modes variables and values).
1045 Don't remove any of the default settings, just change the values. Org-mode
1046 relies on the variables to be present in the list."
1047 :group 'org-table-calculation
1048 :type 'plist)
1050 (defcustom org-table-formula-evaluate-inline t
1051 "Non-nil means, TAB and RET evaluate a formula in current table field.
1052 If the current field starts with an equal sign, it is assumed to be a formula
1053 which should be evaluated as described in the manual and in the documentation
1054 string of the command `org-table-eval-formula'. This feature requires the
1055 Emacs calc package.
1056 When this variable is nil, formula calculation is only available through
1057 the command \\[org-table-eval-formula]."
1058 :group 'org-table-calculation
1059 :type 'boolean)
1061 (defcustom org-table-formula-use-constants t
1062 "Non-nil means, interpret constants in formulas in tables.
1063 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1064 by the value given in `org-table-formula-constants', or by a value obtained
1065 from the `constants.el' package."
1066 :group 'org-table-calculation
1067 :type 'boolean)
1069 (defcustom org-table-formula-constants nil
1070 "Alist with constant names and values, for use in table formulas.
1071 The car of each element is a name of a constant, without the `$' before it.
1072 The cdr is the value as a string. For example, if you'd like to use the
1073 speed of light in a formula, you would configure
1075 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1077 and then use it in an equation like `$1*$c'.
1079 Constants can also be defined on a per-file basis using a line like
1081 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1082 :group 'org-table-calculation
1083 :type '(repeat
1084 (cons (string :tag "name")
1085 (string :tag "value"))))
1087 (defvar org-table-formula-constants-local nil
1088 "Local version of `org-table-formula-constants'.")
1089 (make-variable-buffer-local 'org-table-formula-constants-local)
1091 (defcustom org-table-allow-automatic-line-recalculation t
1092 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1093 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1094 :group 'org-table-calculation
1095 :type 'boolean)
1097 (defgroup org-link nil
1098 "Options concerning links in Org-mode."
1099 :tag "Org Link"
1100 :group 'org)
1102 (defvar org-link-abbrev-alist-local nil
1103 "Buffer-local version of `org-link-abbrev-alist', which see.
1104 The value of this is taken from the #+LINK lines.")
1105 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1107 (defcustom org-link-abbrev-alist nil
1108 "Alist of link abbreviations.
1109 The car of each element is a string, to be replaced at the start of a link.
1110 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1111 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1113 [[linkkey:tag][description]]
1115 If REPLACE is a string, the tag will simply be appended to create the link.
1116 If the string contains \"%s\", the tag will be inserted there.
1118 REPLACE may also be a function that will be called with the tag as the
1119 only argument to create the link, which should be returned as a string.
1121 See the manual for examples."
1122 :group 'org-link
1123 :type 'alist)
1125 (defcustom org-descriptive-links t
1126 "Non-nil means, hide link part and only show description of bracket links.
1127 Bracket links are like [[link][descritpion]]. This variable sets the initial
1128 state in new org-mode buffers. The setting can then be toggled on a
1129 per-buffer basis from the Org->Hyperlinks menu."
1130 :group 'org-link
1131 :type 'boolean)
1133 (defcustom org-link-file-path-type 'adaptive
1134 "How the path name in file links should be stored.
1135 Valid values are:
1137 relative Relative to the current directory, i.e. the directory of the file
1138 into which the link is being inserted.
1139 absolute Absolute path, if possible with ~ for home directory.
1140 noabbrev Absolute path, no abbreviation of home directory.
1141 adaptive Use relative path for files in the current directory and sub-
1142 directories of it. For other files, use an absolute path."
1143 :group 'org-link
1144 :type '(choice
1145 (const relative)
1146 (const absolute)
1147 (const noabbrev)
1148 (const adaptive)))
1150 (defcustom org-activate-links '(bracket angle plain radio tag date)
1151 "Types of links that should be activated in Org-mode files.
1152 This is a list of symbols, each leading to the activation of a certain link
1153 type. In principle, it does not hurt to turn on most link types - there may
1154 be a small gain when turning off unused link types. The types are:
1156 bracket The recommended [[link][description]] or [[link]] links with hiding.
1157 angular Links in angular brackes that may contain whitespace like
1158 <bbdb:Carsten Dominik>.
1159 plain Plain links in normal text, no whitespace, like http://google.com.
1160 radio Text that is matched by a radio target, see manual for details.
1161 tag Tag settings in a headline (link to tag search).
1162 date Time stamps (link to calendar).
1164 Changing this variable requires a restart of Emacs to become effective."
1165 :group 'org-link
1166 :type '(set (const :tag "Double bracket links (new style)" bracket)
1167 (const :tag "Angular bracket links (old style)" angular)
1168 (const :tag "Plain text links" plain)
1169 (const :tag "Radio target matches" radio)
1170 (const :tag "Tags" tag)
1171 (const :tag "Timestamps" date)))
1173 (defgroup org-link-store nil
1174 "Options concerning storing links in Org-mode"
1175 :tag "Org Store Link"
1176 :group 'org-link)
1178 (defcustom org-email-link-description-format "Email %c: %.30s"
1179 "Format of the description part of a link to an email or usenet message.
1180 The following %-excapes will be replaced by corresponding information:
1182 %F full \"From\" field
1183 %f name, taken from \"From\" field, address if no name
1184 %T full \"To\" field
1185 %t first name in \"To\" field, address if no name
1186 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1187 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1188 %s subject
1189 %m message-id.
1191 You may use normal field width specification between the % and the letter.
1192 This is for example useful to limit the length of the subject.
1194 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1195 :group 'org-link-store
1196 :type 'string)
1198 (defcustom org-from-is-user-regexp
1199 (let (r1 r2)
1200 (when (and user-mail-address (not (string= user-mail-address "")))
1201 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1202 (when (and user-full-name (not (string= user-full-name "")))
1203 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1204 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1205 "Regexp mached against the \"From:\" header of an email or usenet message.
1206 It should match if the message is from the user him/herself."
1207 :group 'org-link-store
1208 :type 'regexp)
1210 (defcustom org-context-in-file-links t
1211 "Non-nil means, file links from `org-store-link' contain context.
1212 A search string will be added to the file name with :: as separator and
1213 used to find the context when the link is activated by the command
1214 `org-open-at-point'.
1215 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1216 negates this setting for the duration of the command."
1217 :group 'org-link-store
1218 :type 'boolean)
1220 (defcustom org-keep-stored-link-after-insertion nil
1221 "Non-nil means, keep link in list for entire session.
1223 The command `org-store-link' adds a link pointing to the current
1224 location to an internal list. These links accumulate during a session.
1225 The command `org-insert-link' can be used to insert links into any
1226 Org-mode file (offering completion for all stored links). When this
1227 option is nil, every link which has been inserted once using \\[org-insert-link]
1228 will be removed from the list, to make completing the unused links
1229 more efficient."
1230 :group 'org-link-store
1231 :type 'boolean)
1233 (defcustom org-usenet-links-prefer-google nil
1234 "Non-nil means, `org-store-link' will create web links to Google groups.
1235 When nil, Gnus will be used for such links.
1236 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1237 negates this setting for the duration of the command."
1238 :group 'org-link-store
1239 :type 'boolean)
1241 (defgroup org-link-follow nil
1242 "Options concerning following links in Org-mode"
1243 :tag "Org Follow Link"
1244 :group 'org-link)
1246 (defcustom org-tab-follows-link nil
1247 "Non-nil means, on links TAB will follow the link.
1248 Needs to be set before org.el is loaded."
1249 :group 'org-link-follow
1250 :type 'boolean)
1252 (defcustom org-return-follows-link nil
1253 "Non-nil means, on links RET will follow the link.
1254 Needs to be set before org.el is loaded."
1255 :group 'org-link-follow
1256 :type 'boolean)
1258 (defcustom org-mouse-1-follows-link mouse-1-click-follows-link
1259 "Non-nil means, mouse-1 on a link will follow the link.
1260 A longer mouse click will still set point. Does not work on XEmacs.
1261 Needs to be set before org.el is loaded."
1262 :group 'org-link-follow
1263 :type 'boolean)
1265 (defcustom org-mark-ring-length 4
1266 "Number of different positions to be recorded in the ring
1267 Changing this requires a restart of Emacs to work correctly."
1268 :group 'org-link-follow
1269 :type 'interger)
1271 (defcustom org-link-frame-setup
1272 '((vm . vm-visit-folder-other-frame)
1273 (gnus . gnus-other-frame)
1274 (file . find-file-other-window))
1275 "Setup the frame configuration for following links.
1276 When following a link with Emacs, it may often be useful to display
1277 this link in another window or frame. This variable can be used to
1278 set this up for the different types of links.
1279 For VM, use any of
1280 `vm-visit-folder'
1281 `vm-visit-folder-other-frame'
1282 For Gnus, use any of
1283 `gnus'
1284 `gnus-other-frame'
1285 For FILE, use any of
1286 `find-file'
1287 `find-file-other-window'
1288 `find-file-other-frame'
1289 For the calendar, use the variable `calendar-setup'.
1290 For BBDB, it is currently only possible to display the matches in
1291 another window."
1292 :group 'org-link-follow
1293 :type '(list
1294 (cons (const vm)
1295 (choice
1296 (const vm-visit-folder)
1297 (const vm-visit-folder-other-window)
1298 (const vm-visit-folder-other-frame)))
1299 (cons (const gnus)
1300 (choice
1301 (const gnus)
1302 (const gnus-other-frame)))
1303 (cons (const file)
1304 (choice
1305 (const find-file)
1306 (const find-file-other-window)
1307 (const find-file-other-frame)))))
1309 (defcustom org-display-internal-link-with-indirect-buffer nil
1310 "Non-nil means, use indirect buffer to display infile links.
1311 Activating internal links (from one location in a file to another location
1312 in the same file) normally just jumps to the location. When the link is
1313 activated with a C-u prefix (or with mouse-3), the link is displayed in
1314 another window. When this option is set, the other window actually displays
1315 an indirect buffer clone of the current buffer, to avoid any visibility
1316 changes to the current buffer."
1317 :group 'org-link-follow
1318 :type 'boolean)
1320 (defcustom org-open-non-existing-files nil
1321 "Non-nil means, `org-open-file' will open non-existing files.
1322 When nil, an error will be generated."
1323 :group 'org-link-follow
1324 :type 'boolean)
1326 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1327 "Function and arguments to call for following mailto links.
1328 This is a list with the first element being a lisp function, and the
1329 remaining elements being arguments to the function. In string arguments,
1330 %a will be replaced by the address, and %s will be replaced by the subject
1331 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1332 :group 'org-link-follow
1333 :type '(choice
1334 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1335 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1336 (const :tag "message-mail" (message-mail "%a" "%s"))
1337 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1339 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1340 "Non-nil means, ask for confirmation before executing shell links.
1341 Shell links can be dangerous: just think about a link
1343 [[shell:rm -rf ~/*][Google Search]]
1345 This link would show up in your Org-mode document as \"Google Search\",
1346 but really it would remove your entire home directory.
1347 Therefore we advise against setting this variable to nil.
1348 Just change it to `y-or-n-p' of you want to confirm with a
1349 single keystroke rather than having to type \"yes\"."
1350 :group 'org-link-follow
1351 :type '(choice
1352 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1353 (const :tag "with y-or-n (faster)" y-or-n-p)
1354 (const :tag "no confirmation (dangerous)" nil)))
1356 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1357 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1358 Elisp links can be dangerous: just think about a link
1360 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1362 This link would show up in your Org-mode document as \"Google Search\",
1363 but really it would remove your entire home directory.
1364 Therefore we advise against setting this variable to nil.
1365 Just change it to `y-or-n-p' of you want to confirm with a
1366 single keystroke rather than having to type \"yes\"."
1367 :group 'org-link-follow
1368 :type '(choice
1369 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1370 (const :tag "with y-or-n (faster)" y-or-n-p)
1371 (const :tag "no confirmation (dangerous)" nil)))
1373 (defconst org-file-apps-defaults-gnu
1374 '((remote . emacs)
1375 (t . mailcap))
1376 "Default file applications on a UNIX or GNU/Linux system.
1377 See `org-file-apps'.")
1379 (defconst org-file-apps-defaults-macosx
1380 '((remote . emacs)
1381 (t . "open %s")
1382 ("ps" . "gv %s")
1383 ("ps.gz" . "gv %s")
1384 ("eps" . "gv %s")
1385 ("eps.gz" . "gv %s")
1386 ("dvi" . "xdvi %s")
1387 ("fig" . "xfig %s"))
1388 "Default file applications on a MacOS X system.
1389 The system \"open\" is known as a default, but we use X11 applications
1390 for some files for which the OS does not have a good default.
1391 See `org-file-apps'.")
1393 (defconst org-file-apps-defaults-windowsnt
1394 (list
1395 '(remote . emacs)
1396 (cons t
1397 (list (if (featurep 'xemacs)
1398 'mswindows-shell-execute
1399 'w32-shell-execute)
1400 "open" 'file)))
1401 "Default file applications on a Windows NT system.
1402 The system \"open\" is used for most files.
1403 See `org-file-apps'.")
1405 (defcustom org-file-apps
1407 ("txt" . emacs)
1408 ("tex" . emacs)
1409 ("ltx" . emacs)
1410 ("org" . emacs)
1411 ("el" . emacs)
1412 ("bib" . emacs)
1414 "External applications for opening `file:path' items in a document.
1415 Org-mode uses system defaults for different file types, but
1416 you can use this variable to set the application for a given file
1417 extension. The entries in this list are cons cells where the car identifies
1418 files and the cdr the corresponding command. Possible values for the
1419 file identifier are
1420 \"ext\" A string identifying an extension
1421 `directory' Matches a directory
1422 `remote' Matches a remote file, accessible through tramp or efs.
1423 Remote files most likely should be visited through Emacs
1424 because external applications cannot handle such paths.
1425 t Default for all remaining files
1427 Possible values for the command are:
1428 `emacs' The file will be visited by the current Emacs process.
1429 `default' Use the default application for this file type.
1430 string A command to be executed by a shell; %s will be replaced
1431 by the path to the file.
1432 sexp A Lisp form which will be evaluated. The file path will
1433 be available in the Lisp variable `file'.
1434 For more examples, see the system specific constants
1435 `org-file-apps-defaults-macosx'
1436 `org-file-apps-defaults-windowsnt'
1437 `org-file-apps-defaults-gnu'."
1438 :group 'org-link-follow
1439 :type '(repeat
1440 (cons (choice :value ""
1441 (string :tag "Extension")
1442 (const :tag "Default for unrecognized files" t)
1443 (const :tag "Remote file" remote)
1444 (const :tag "Links to a directory" directory))
1445 (choice :value ""
1446 (const :tag "Visit with Emacs" emacs)
1447 (const :tag "Use system default" default)
1448 (string :tag "Command")
1449 (sexp :tag "Lisp form")))))
1451 (defcustom org-mhe-search-all-folders nil
1452 "Non-nil means, that the search for the mh-message will be extended to
1453 all folders if the message cannot be found in the folder given in the link.
1454 Searching all folders is very efficient with one of the search engines
1455 supported by MH-E, but will be slow with pick."
1456 :group 'org-link-follow
1457 :type 'boolean)
1459 (defgroup org-remember nil
1460 "Options concerning interaction with remember.el."
1461 :tag "Org Remember"
1462 :group 'org)
1464 (defcustom org-directory "~/org"
1465 "Directory with org files.
1466 This directory will be used as default to prompt for org files.
1467 Used by the hooks for remember.el."
1468 :group 'org-remember
1469 :type 'directory)
1471 (defcustom org-default-notes-file "~/.notes"
1472 "Default target for storing notes.
1473 Used by the hooks for remember.el. This can be a string, or nil to mean
1474 the value of `remember-data-file'.
1475 You can set this on a per-template basis with the variable
1476 `org-remember-templates'."
1477 :group 'org-remember
1478 :type '(choice
1479 (const :tag "Default from remember-data-file" nil)
1480 file))
1482 (defcustom org-remember-store-without-prompt t
1483 "Non-nil means, `C-c C-c' stores remember note without further promts.
1484 In this case, you need `C-u C-c C-c' to get the prompts for
1485 note file and headline.
1486 When this variable is nil, `C-c C-c' give you the prompts, and
1487 `C-u C-c C-c' trigger the fasttrack."
1488 :group 'org-remember
1489 :type 'boolean)
1491 (defcustom org-remember-interactive-interface 'refile
1492 "The interface to be used for interactive filing of remember notes.
1493 This is only used when the interactive mode for selecting a filing
1494 location is used (see the variable `org-remember-store-without-prompt').
1495 Allowed vaues are:
1496 outline The interface shows an outline of the relevant file
1497 and the correct heading is found by moving through
1498 the outline or by searching with incremental search.
1499 outline-path-completion Headlines in the current buffer are offered via
1500 completion.
1501 refile Use the refile interface, and offer headlines,
1502 possibly from different buffers."
1503 :group 'org-remember
1504 :type '(choice
1505 (const :tag "Refile" refile)
1506 (const :tag "Outline" outline)
1507 (const :tag "Outline-path-completion" outline-path-completion)))
1509 (defcustom org-goto-interface 'outline
1510 "The default interface to be used for `org-goto'.
1511 Allowed vaues are:
1512 outline The interface shows an outline of the relevant file
1513 and the correct heading is found by moving through
1514 the outline or by searching with incremental search.
1515 outline-path-completion Headlines in the current buffer are offered via
1516 completion."
1517 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1518 :type '(choice
1519 (const :tag "Outline" outline)
1520 (const :tag "Outline-path-completion" outline-path-completion)))
1522 (defcustom org-remember-default-headline ""
1523 "The headline that should be the default location in the notes file.
1524 When filing remember notes, the cursor will start at that position.
1525 You can set this on a per-template basis with the variable
1526 `org-remember-templates'."
1527 :group 'org-remember
1528 :type 'string)
1530 (defcustom org-remember-templates nil
1531 "Templates for the creation of remember buffers.
1532 When nil, just let remember make the buffer.
1533 When not nil, this is a list of 5-element lists. In each entry, the first
1534 element is the name of the template, which should be a single short word.
1535 The second element is a character, a unique key to select this template.
1536 The third element is the template. The fourth element is optional and can
1537 specify a destination file for remember items created with this template.
1538 The default file is given by `org-default-notes-file'. An optional fifth
1539 element can specify the headline in that file that should be offered
1540 first when the user is asked to file the entry. The default headline is
1541 given in the variable `org-remember-default-headline'.
1543 The template specifies the structure of the remember buffer. It should have
1544 a first line starting with a star, to act as the org-mode headline.
1545 Furthermore, the following %-escapes will be replaced with content:
1547 %^{prompt} Prompt the user for a string and replace this sequence with it.
1548 A default value and a completion table ca be specified like this:
1549 %^{prompt|default|completion2|completion3|...}
1550 %t time stamp, date only
1551 %T time stamp with date and time
1552 %u, %U like the above, but inactive time stamps
1553 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1554 You may define a prompt like %^{Please specify birthday}t
1555 %n user name (taken from `user-full-name')
1556 %a annotation, normally the link created with org-store-link
1557 %i initial content, the region active. If %i is indented,
1558 the entire inserted text will be indented as well.
1559 %c content of the clipboard, or current kill ring head
1560 %^g prompt for tags, with completion on tags in target file
1561 %^G prompt for tags, with completion all tags in all agenda files
1562 %:keyword specific information for certain link types, see below
1563 %[pathname] insert the contents of the file given by `pathname'
1564 %(sexp) evaluate elisp `(sexp)' and replace with the result
1565 %! Store this note immediately after filling the template
1567 %? After completing the template, position cursor here.
1569 Apart from these general escapes, you can access information specific to the
1570 link type that is created. For example, calling `remember' in emails or gnus
1571 will record the author and the subject of the message, which you can access
1572 with %:author and %:subject, respectively. Here is a complete list of what
1573 is recorded for each link type.
1575 Link type | Available information
1576 -------------------+------------------------------------------------------
1577 bbdb | %:type %:name %:company
1578 vm, wl, mh, rmail | %:type %:subject %:message-id
1579 | %:from %:fromname %:fromaddress
1580 | %:to %:toname %:toaddress
1581 | %:fromto (either \"to NAME\" or \"from NAME\")
1582 gnus | %:group, for messages also all email fields
1583 w3, w3m | %:type %:url
1584 info | %:type %:file %:node
1585 calendar | %:type %:date"
1586 :group 'org-remember
1587 :get (lambda (var) ; Make sure all entries have 5 elements
1588 (mapcar (lambda (x)
1589 (if (not (stringp (car x))) (setq x (cons "" x)))
1590 (cond ((= (length x) 4) (append x '("")))
1591 ((= (length x) 3) (append x '("" "")))
1592 (t x)))
1593 (default-value var)))
1594 :type '(repeat
1595 :tag "enabled"
1596 (list :value ("" ?a "\n" nil nil)
1597 (string :tag "Name")
1598 (character :tag "Selection Key")
1599 (string :tag "Template")
1600 (choice
1601 (file :tag "Destination file")
1602 (const :tag "Prompt for file" nil))
1603 (choice
1604 (string :tag "Destination headline")
1605 (const :tag "Selection interface for heading")))))
1607 (defcustom org-reverse-note-order nil
1608 "Non-nil means, store new notes at the beginning of a file or entry.
1609 When nil, new notes will be filed to the end of a file or entry.
1610 This can also be a list with cons cells of regular expressions that
1611 are matched against file names, and values."
1612 :group 'org-remember
1613 :type '(choice
1614 (const :tag "Reverse always" t)
1615 (const :tag "Reverse never" nil)
1616 (repeat :tag "By file name regexp"
1617 (cons regexp boolean))))
1619 (defcustom org-refile-targets nil
1620 "Targets for refiling entries with \\[org-refile].
1621 This is list of cons cells. Each cell contains:
1622 - a specification of the files to be considered, either a list of files,
1623 or a symbol whose function or value fields will be used to retrieve
1624 a file name or a list of file names. Nil means, refile to a different
1625 heading in the current buffer.
1626 - A specification of how to find candidate refile targets. This may be
1627 any of
1628 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1629 This tag has to be present in all target headlines, inheritance will
1630 not be considered.
1631 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1632 todo keyword.
1633 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1634 headlines that are refiling targets.
1635 - a cons cell (:level . N). Any headline of level N is considered a target.
1636 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1637 ;; FIXME: what if there are a var and func with same name???
1638 :group 'org-remember
1639 :type '(repeat
1640 (cons
1641 (choice :value org-agenda-files
1642 (const :tag "All agenda files" org-agenda-files)
1643 (const :tag "Current buffer" nil)
1644 (function) (variable) (file))
1645 (choice :tag "Identify target headline by"
1646 (cons :tag "Specific tag" (const :tag) (string))
1647 (cons :tag "TODO keyword" (const :todo) (string))
1648 (cons :tag "Regular expression" (const :regexp) (regexp))
1649 (cons :tag "Level number" (const :level) (integer))
1650 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1652 (defcustom org-refile-use-outline-path nil
1653 "Non-nil means, provide refile targets as paths.
1654 So a level 3 headline will be available as level1/level2/level3.
1655 When the value is `file', also include the file name (without directory)
1656 into the path. When `full-file-path', include the full file path."
1657 :group 'org-remember
1658 :type '(choice
1659 (const :tag "Not" nil)
1660 (const :tag "Yes" t)
1661 (const :tag "Start with file name" file)
1662 (const :tag "Start with full file path" full-file-path)))
1664 (defgroup org-todo nil
1665 "Options concerning TODO items in Org-mode."
1666 :tag "Org TODO"
1667 :group 'org)
1669 (defgroup org-progress nil
1670 "Options concerning Progress logging in Org-mode."
1671 :tag "Org Progress"
1672 :group 'org-time)
1674 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1675 "List of TODO entry keyword sequences and their interpretation.
1676 \\<org-mode-map>This is a list of sequences.
1678 Each sequence starts with a symbol, either `sequence' or `type',
1679 indicating if the keywords should be interpreted as a sequence of
1680 action steps, or as different types of TODO items. The first
1681 keywords are states requiring action - these states will select a headline
1682 for inclusion into the global TODO list Org-mode produces. If one of
1683 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1684 signify that no further action is necessary. If \"|\" is not found,
1685 the last keyword is treated as the only DONE state of the sequence.
1687 The command \\[org-todo] cycles an entry through these states, and one
1688 additional state where no keyword is present. For details about this
1689 cycling, see the manual.
1691 TODO keywords and interpretation can also be set on a per-file basis with
1692 the special #+SEQ_TODO and #+TYP_TODO lines.
1694 Each keyword can optionally specify a character for fast state selection
1695 \(in combination with the variable `org-use-fast-todo-selection')
1696 and specifiers for state change logging, using the same syntax
1697 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1698 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1699 indicates to record a time stamp each time this state is selected.
1700 \"WAIT(w@)\" says that the user should in addition be prompted for a
1701 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1702 entering and when leaving this state.
1704 For backward compatibility, this variable may also be just a list
1705 of keywords - in this case the interptetation (sequence or type) will be
1706 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1707 :group 'org-todo
1708 :group 'org-keywords
1709 :type '(choice
1710 (repeat :tag "Old syntax, just keywords"
1711 (string :tag "Keyword"))
1712 (repeat :tag "New syntax"
1713 (cons
1714 (choice
1715 :tag "Interpretation"
1716 (const :tag "Sequence (cycling hits every state)" sequence)
1717 (const :tag "Type (cycling directly to DONE)" type))
1718 (repeat
1719 (string :tag "Keyword"))))))
1721 (defvar org-todo-keywords-1 nil
1722 "All TODO and DONE keywords active in a buffer.")
1723 (make-variable-buffer-local 'org-todo-keywords-1)
1724 (defvar org-todo-keywords-for-agenda nil)
1725 (defvar org-done-keywords-for-agenda nil)
1726 (defvar org-not-done-keywords nil)
1727 (make-variable-buffer-local 'org-not-done-keywords)
1728 (defvar org-done-keywords nil)
1729 (make-variable-buffer-local 'org-done-keywords)
1730 (defvar org-todo-heads nil)
1731 (make-variable-buffer-local 'org-todo-heads)
1732 (defvar org-todo-sets nil)
1733 (make-variable-buffer-local 'org-todo-sets)
1734 (defvar org-todo-log-states nil)
1735 (make-variable-buffer-local 'org-todo-log-states)
1736 (defvar org-todo-kwd-alist nil)
1737 (make-variable-buffer-local 'org-todo-kwd-alist)
1738 (defvar org-todo-key-alist nil)
1739 (make-variable-buffer-local 'org-todo-key-alist)
1740 (defvar org-todo-key-trigger nil)
1741 (make-variable-buffer-local 'org-todo-key-trigger)
1743 (defcustom org-todo-interpretation 'sequence
1744 "Controls how TODO keywords are interpreted.
1745 This variable is in principle obsolete and is only used for
1746 backward compatibility, if the interpretation of todo keywords is
1747 not given already in `org-todo-keywords'. See that variable for
1748 more information."
1749 :group 'org-todo
1750 :group 'org-keywords
1751 :type '(choice (const sequence)
1752 (const type)))
1754 (defcustom org-use-fast-todo-selection 'prefix
1755 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1756 This variable describes if and under what circumstances the cycling
1757 mechanism for TODO keywords will be replaced by a single-key, direct
1758 selection scheme.
1760 When nil, fast selection is never used.
1762 When the symbol `prefix', it will be used when `org-todo' is called with
1763 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1764 in an agenda buffer.
1766 When t, fast selection is used by default. In this case, the prefix
1767 argument forces cycling instead.
1769 In all cases, the special interface is only used if access keys have actually
1770 been assigned by the user, i.e. if keywords in the configuration are followed
1771 by a letter in parenthesis, like TODO(t)."
1772 :group 'org-todo
1773 :type '(choice
1774 (const :tag "Never" nil)
1775 (const :tag "By default" t)
1776 (const :tag "Only with C-u C-c C-t" prefix)))
1778 (defcustom org-after-todo-state-change-hook nil
1779 "Hook which is run after the state of a TODO item was changed.
1780 The new state (a string with a TODO keyword, or nil) is available in the
1781 Lisp variable `state'."
1782 :group 'org-todo
1783 :type 'hook)
1785 (defcustom org-log-done nil
1786 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1787 When equal to the list (done), also prompt for a closing note.
1788 This can also be configured on a per-file basis by adding one of
1789 the following lines anywhere in the buffer:
1791 #+STARTUP: logdone
1792 #+STARTUP: lognotedone
1793 #+STARTUP: nologdone"
1794 :group 'org-todo
1795 :group 'org-progress
1796 :type '(choice
1797 (const :tag "No logging" nil)
1798 (const :tag "Record CLOSED timestamp" time)
1799 (const :tag "Record CLOSED timestamp with closing note." note)))
1801 ;; Normalize old uses of org-log-done.
1802 (cond
1803 ((eq org-log-done t) (setq org-log-done 'time))
1804 ((and (listp org-log-done) (memq 'done org-log-done))
1805 (setq org-log-done 'note)))
1807 ;; FIXME: document
1808 (defcustom org-log-note-clock-out nil
1809 "Non-nil means, recored a note when clocking out of an item.
1810 This can also be configured on a per-file basis by adding one of
1811 the following lines anywhere in the buffer:
1813 #+STARTUP: lognoteclock-out
1814 #+STARTUP: nolognoteclock-out"
1815 :group 'org-todo
1816 :group 'org-progress
1817 :type 'boolean)
1819 (defcustom org-log-done-with-time t
1820 "Non-nil means, the CLOSED time stamp will contain date and time.
1821 When nil, only the date will be recorded."
1822 :group 'org-progress
1823 :type 'boolean)
1825 (defcustom org-log-note-headings
1826 '((done . "CLOSING NOTE %t")
1827 (state . "State %-12s %t")
1828 (clock-out . ""))
1829 "Headings for notes added when clocking out or closing TODO items.
1830 The value is an alist, with the car being a symbol indicating the note
1831 context, and the cdr is the heading to be used. The heading may also be the
1832 empty string.
1833 %t in the heading will be replaced by a time stamp.
1834 %s will be replaced by the new TODO state, in double quotes.
1835 %u will be replaced by the user name.
1836 %U will be replaced by the full user name."
1837 :group 'org-todo
1838 :group 'org-progress
1839 :type '(list :greedy t
1840 (cons (const :tag "Heading when closing an item" done) string)
1841 (cons (const :tag
1842 "Heading when changing todo state (todo sequence only)"
1843 state) string)
1844 (cons (const :tag "Heading when clocking out" clock-out) string)))
1846 (defcustom org-log-states-order-reversed t
1847 "Non-nil means, the latest state change note will be directly after heading.
1848 When nil, the notes will be orderer according to time."
1849 :group 'org-todo
1850 :group 'org-progress
1851 :type 'boolean)
1853 (defcustom org-log-repeat 'time
1854 "Non-nil means, record moving through the DONE state when triggering repeat.
1855 An auto-repeating tasks is immediately switched back to TODO when marked
1856 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1857 the TODO keyword definition, or recording a cloing note by setting
1858 `org-log-done', there will be no record of the task moving trhough DONE.
1859 This variable forces taking a note anyway. Possible values are:
1861 nil Don't force a record
1862 time Record a time stamp
1863 note Record a note
1865 This option can also be set with on a per-file-basis with
1867 #+STARTUP: logrepeat
1868 #+STARTUP: lognoterepeat
1869 #+STARTUP: nologrepeat
1871 You can have local logging settings for a subtree by setting the LOGGING
1872 property to one or more of these keywords."
1873 :group 'org-todo
1874 :group 'org-progress
1875 :type '(choice
1876 (const :tag "Don't force a record" nil)
1877 (const :tag "Force recording the DONE state" time)
1878 (const :tag "Force recording a note with the DONE state" note)))
1880 (defcustom org-clock-into-drawer 2
1881 "Should clocking info be wrapped into a drawer?
1882 When t, clocking info will always be inserted into a :CLOCK: drawer.
1883 If necessary, the drawer will be created.
1884 When nil, the drawer will not be created, but used when present.
1885 When an integer and the number of clocking entries in an item
1886 reaches or exceeds this number, a drawer will be created."
1887 :group 'org-todo
1888 :group 'org-progress
1889 :type '(choice
1890 (const :tag "Always" t)
1891 (const :tag "Only when drawer exists" nil)
1892 (integer :tag "When at least N clock entries")))
1894 (defcustom org-clock-out-when-done t
1895 "When t, the clock will be stopped when the relevant entry is marked DONE.
1896 Nil means, clock will keep running until stopped explicitly with
1897 `C-c C-x C-o', or until the clock is started in a different item."
1898 :group 'org-progress
1899 :type 'boolean)
1901 (defcustom org-clock-in-switch-to-state nil
1902 "Set task to a special todo state while clocking it.
1903 The value should be the state to which the entry should be switched."
1904 :group 'org-progress
1905 :group 'org-todo
1906 :type '(choice
1907 (const :tag "Don't force a state" nil)
1908 (string :tag "State")))
1910 (defgroup org-priorities nil
1911 "Priorities in Org-mode."
1912 :tag "Org Priorities"
1913 :group 'org-todo)
1915 (defcustom org-highest-priority ?A
1916 "The highest priority of TODO items. A character like ?A, ?B etc.
1917 Must have a smaller ASCII number than `org-lowest-priority'."
1918 :group 'org-priorities
1919 :type 'character)
1921 (defcustom org-lowest-priority ?C
1922 "The lowest priority of TODO items. A character like ?A, ?B etc.
1923 Must have a larger ASCII number than `org-highest-priority'."
1924 :group 'org-priorities
1925 :type 'character)
1927 (defcustom org-default-priority ?B
1928 "The default priority of TODO items.
1929 This is the priority an item get if no explicit priority is given."
1930 :group 'org-priorities
1931 :type 'character)
1933 (defcustom org-priority-start-cycle-with-default t
1934 "Non-nil means, start with default priority when starting to cycle.
1935 When this is nil, the first step in the cycle will be (depending on the
1936 command used) one higher or lower that the default priority."
1937 :group 'org-priorities
1938 :type 'boolean)
1940 (defgroup org-time nil
1941 "Options concerning time stamps and deadlines in Org-mode."
1942 :tag "Org Time"
1943 :group 'org)
1945 (defcustom org-insert-labeled-timestamps-at-point nil
1946 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1947 When nil, these labeled time stamps are forces into the second line of an
1948 entry, just after the headline. When scheduling from the global TODO list,
1949 the time stamp will always be forced into the second line."
1950 :group 'org-time
1951 :type 'boolean)
1953 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1954 "Formats for `format-time-string' which are used for time stamps.
1955 It is not recommended to change this constant.")
1957 (defcustom org-time-stamp-rounding-minutes 0
1958 "Number of minutes to round time stamps to upon insertion.
1959 When zero, insert the time unmodified. Useful rounding numbers
1960 should be factors of 60, so for example 5, 10, 15.
1961 When this is not zero, you can still force an exact time-stamp by using
1962 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1963 :group 'org-time
1964 :type 'integer)
1966 (defcustom org-display-custom-times nil
1967 "Non-nil means, overlay custom formats over all time stamps.
1968 The formats are defined through the variable `org-time-stamp-custom-formats'.
1969 To turn this on on a per-file basis, insert anywhere in the file:
1970 #+STARTUP: customtime"
1971 :group 'org-time
1972 :set 'set-default
1973 :type 'sexp)
1974 (make-variable-buffer-local 'org-display-custom-times)
1976 (defcustom org-time-stamp-custom-formats
1977 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1978 "Custom formats for time stamps. See `format-time-string' for the syntax.
1979 These are overlayed over the default ISO format if the variable
1980 `org-display-custom-times' is set. Time like %H:%M should be at the
1981 end of the second format."
1982 :group 'org-time
1983 :type 'sexp)
1985 (defun org-time-stamp-format (&optional long inactive)
1986 "Get the right format for a time string."
1987 (let ((f (if long (cdr org-time-stamp-formats)
1988 (car org-time-stamp-formats))))
1989 (if inactive
1990 (concat "[" (substring f 1 -1) "]")
1991 f)))
1993 (defcustom org-read-date-prefer-future t
1994 "Non-nil means, assume future for incomplete date input from user.
1995 This affects the following situations:
1996 1. The user gives a day, but no month.
1997 For example, if today is the 15th, and you enter \"3\", Org-mode will
1998 read this as the third of *next* month. However, if you enter \"17\",
1999 it will be considered as *this* month.
2000 2. The user gives a month but not a year.
2001 For example, if it is april and you enter \"feb 2\", this will be read
2002 as feb 2, *next* year. \"May 5\", however, will be this year.
2004 When this option is nil, the current month and year will always be used
2005 as defaults."
2006 :group 'org-time
2007 :type 'boolean)
2009 (defcustom org-read-date-display-live t
2010 "Non-nil means, display current interpretation of date prompt live.
2011 This display will be in an overlay, in the minibuffer."
2012 :group 'org-time
2013 :type 'boolean)
2015 (defcustom org-read-date-popup-calendar t
2016 "Non-nil means, pop up a calendar when prompting for a date.
2017 In the calendar, the date can be selected with mouse-1. However, the
2018 minibuffer will also be active, and you can simply enter the date as well.
2019 When nil, only the minibuffer will be available."
2020 :group 'org-time
2021 :type 'boolean)
2022 (if (fboundp 'defvaralias)
2023 (defvaralias 'org-popup-calendar-for-date-prompt
2024 'org-read-date-popup-calendar))
2026 (defcustom org-extend-today-until 0
2027 "The hour when your day really ends.
2028 This has influence for the following applications:
2029 - When switching the agenda to \"today\". It it is still earlier than
2030 the time given here, the day recognized as TODAY is actually yesterday.
2031 - When a date is read from the user and it is still before the time given
2032 here, the current date and time will be assumed to be yesterday, 23:59.
2034 FIXME:
2035 IMPORTANT: This is still a very experimental feature, it may disappear
2036 again or it may be extended to mean more things."
2037 :group 'org-time
2038 :type 'number)
2040 (defcustom org-edit-timestamp-down-means-later nil
2041 "Non-nil means, S-down will increase the time in a time stamp.
2042 When nil, S-up will increase."
2043 :group 'org-time
2044 :type 'boolean)
2046 (defcustom org-calendar-follow-timestamp-change t
2047 "Non-nil means, make the calendar window follow timestamp changes.
2048 When a timestamp is modified and the calendar window is visible, it will be
2049 moved to the new date."
2050 :group 'org-time
2051 :type 'boolean)
2053 (defcustom org-clock-heading-function nil
2054 "When non-nil, should be a function to create `org-clock-heading'.
2055 This is the string shown in the mode line when a clock is running.
2056 The function is called with point at the beginning of the headline."
2057 :group 'org-time ; FIXME: Should we have a separate group????
2058 :type 'function)
2060 (defgroup org-tags nil
2061 "Options concerning tags in Org-mode."
2062 :tag "Org Tags"
2063 :group 'org)
2065 (defcustom org-tag-alist nil
2066 "List of tags allowed in Org-mode files.
2067 When this list is nil, Org-mode will base TAG input on what is already in the
2068 buffer.
2069 The value of this variable is an alist, the car of each entry must be a
2070 keyword as a string, the cdr may be a character that is used to select
2071 that tag through the fast-tag-selection interface.
2072 See the manual for details."
2073 :group 'org-tags
2074 :type '(repeat
2075 (choice
2076 (cons (string :tag "Tag name")
2077 (character :tag "Access char"))
2078 (const :tag "Start radio group" (:startgroup))
2079 (const :tag "End radio group" (:endgroup)))))
2081 (defcustom org-use-fast-tag-selection 'auto
2082 "Non-nil means, use fast tag selection scheme.
2083 This is a special interface to select and deselect tags with single keys.
2084 When nil, fast selection is never used.
2085 When the symbol `auto', fast selection is used if and only if selection
2086 characters for tags have been configured, either through the variable
2087 `org-tag-alist' or through a #+TAGS line in the buffer.
2088 When t, fast selection is always used and selection keys are assigned
2089 automatically if necessary."
2090 :group 'org-tags
2091 :type '(choice
2092 (const :tag "Always" t)
2093 (const :tag "Never" nil)
2094 (const :tag "When selection characters are configured" 'auto)))
2096 (defcustom org-fast-tag-selection-single-key nil
2097 "Non-nil means, fast tag selection exits after first change.
2098 When nil, you have to press RET to exit it.
2099 During fast tag selection, you can toggle this flag with `C-c'.
2100 This variable can also have the value `expert'. In this case, the window
2101 displaying the tags menu is not even shown, until you press C-c again."
2102 :group 'org-tags
2103 :type '(choice
2104 (const :tag "No" nil)
2105 (const :tag "Yes" t)
2106 (const :tag "Expert" expert)))
2108 (defvar org-fast-tag-selection-include-todo nil
2109 "Non-nil means, fast tags selection interface will also offer TODO states.
2110 This is an undocumented feature, you should not rely on it.")
2112 (defcustom org-tags-column -80
2113 "The column to which tags should be indented in a headline.
2114 If this number is positive, it specifies the column. If it is negative,
2115 it means that the tags should be flushright to that column. For example,
2116 -80 works well for a normal 80 character screen."
2117 :group 'org-tags
2118 :type 'integer)
2120 (defcustom org-auto-align-tags t
2121 "Non-nil means, realign tags after pro/demotion of TODO state change.
2122 These operations change the length of a headline and therefore shift
2123 the tags around. With this options turned on, after each such operation
2124 the tags are again aligned to `org-tags-column'."
2125 :group 'org-tags
2126 :type 'boolean)
2128 (defcustom org-use-tag-inheritance t
2129 "Non-nil means, tags in levels apply also for sublevels.
2130 When nil, only the tags directly given in a specific line apply there.
2131 If you turn off this option, you very likely want to turn on the
2132 companion option `org-tags-match-list-sublevels'."
2133 :group 'org-tags
2134 :type 'boolean)
2136 (defcustom org-tags-match-list-sublevels nil
2137 "Non-nil means list also sublevels of headlines matching tag search.
2138 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2139 the sublevels of a headline matching a tag search often also match
2140 the same search. Listing all of them can create very long lists.
2141 Setting this variable to nil causes subtrees of a match to be skipped.
2142 This option is off by default, because inheritance in on. If you turn
2143 inheritance off, you very likely want to turn this option on.
2145 As a special case, if the tag search is restricted to TODO items, the
2146 value of this variable is ignored and sublevels are always checked, to
2147 make sure all corresponding TODO items find their way into the list."
2148 :group 'org-tags
2149 :type 'boolean)
2151 (defvar org-tags-history nil
2152 "History of minibuffer reads for tags.")
2153 (defvar org-last-tags-completion-table nil
2154 "The last used completion table for tags.")
2155 (defvar org-after-tags-change-hook nil
2156 "Hook that is run after the tags in a line have changed.")
2158 (defgroup org-properties nil
2159 "Options concerning properties in Org-mode."
2160 :tag "Org Properties"
2161 :group 'org)
2163 (defcustom org-property-format "%-10s %s"
2164 "How property key/value pairs should be formatted by `indent-line'.
2165 When `indent-line' hits a property definition, it will format the line
2166 according to this format, mainly to make sure that the values are
2167 lined-up with respect to each other."
2168 :group 'org-properties
2169 :type 'string)
2171 (defcustom org-use-property-inheritance nil
2172 "Non-nil means, properties apply also for sublevels.
2173 This setting is only relevant during property searches, not when querying
2174 an entry with `org-entry-get'. To retrieve a property with inheritance,
2175 you need to call `org-entry-get' with the inheritance flag.
2176 Turning this on can cause significant overhead when doing a search, so
2177 this is turned off by default.
2178 When nil, only the properties directly given in the current entry count.
2179 The value may also be a list of properties that shouldhave inheritance.
2181 However, note that some special properties use inheritance under special
2182 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2183 and the properties ending in \"_ALL\" when they are used as descriptor
2184 for valid values of a property."
2185 :group 'org-properties
2186 :type '(choice
2187 (const :tag "Not" nil)
2188 (const :tag "Always" nil)
2189 (repeat :tag "Specific properties" (string :tag "Property"))))
2191 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2192 "The default column format, if no other format has been defined.
2193 This variable can be set on the per-file basis by inserting a line
2195 #+COLUMNS: %25ITEM ....."
2196 :group 'org-properties
2197 :type 'string)
2199 (defcustom org-global-properties nil
2200 "List of property/value pairs that can be inherited by any entry.
2201 You can set buffer-local values for this by adding lines like
2203 #+PROPERTY: NAME VALUE"
2204 :group 'org-properties
2205 :type '(repeat
2206 (cons (string :tag "Property")
2207 (string :tag "Value"))))
2209 (defvar org-local-properties nil
2210 "List of property/value pairs that can be inherited by any entry.
2211 Valid for the current buffer.
2212 This variable is populated from #+PROPERTY lines.")
2214 (defgroup org-agenda nil
2215 "Options concerning agenda views in Org-mode."
2216 :tag "Org Agenda"
2217 :group 'org)
2219 (defvar org-category nil
2220 "Variable used by org files to set a category for agenda display.
2221 Such files should use a file variable to set it, for example
2223 # -*- mode: org; org-category: \"ELisp\"
2225 or contain a special line
2227 #+CATEGORY: ELisp
2229 If the file does not specify a category, then file's base name
2230 is used instead.")
2231 (make-variable-buffer-local 'org-category)
2233 (defcustom org-agenda-files nil
2234 "The files to be used for agenda display.
2235 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2236 \\[org-remove-file]. You can also use customize to edit the list.
2238 If an entry is a directory, all files in that directory that are matched by
2239 `org-agenda-file-regexp' will be part of the file list.
2241 If the value of the variable is not a list but a single file name, then
2242 the list of agenda files is actually stored and maintained in that file, one
2243 agenda file per line."
2244 :group 'org-agenda
2245 :type '(choice
2246 (repeat :tag "List of files and directories" file)
2247 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2249 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2250 "Regular expression to match files for `org-agenda-files'.
2251 If any element in the list in that variable contains a directory instead
2252 of a normal file, all files in that directory that are matched by this
2253 regular expression will be included."
2254 :group 'org-agenda
2255 :type 'regexp)
2257 (defcustom org-agenda-skip-unavailable-files nil
2258 "t means to just skip non-reachable files in `org-agenda-files'.
2259 Nil means to remove them, after a query, from the list."
2260 :group 'org-agenda
2261 :type 'boolean)
2263 (defcustom org-agenda-multi-occur-extra-files nil
2264 "List of extra files to be searched by `org-occur-in-agenda-files'.
2265 The files in `org-agenda-files' are always searched."
2266 :group 'org-agenda
2267 :type '(repeat file))
2269 (defcustom org-agenda-confirm-kill 1
2270 "When set, remote killing from the agenda buffer needs confirmation.
2271 When t, a confirmation is always needed. When a number N, confirmation is
2272 only needed when the text to be killed contains more than N non-white lines."
2273 :group 'org-agenda
2274 :type '(choice
2275 (const :tag "Never" nil)
2276 (const :tag "Always" t)
2277 (number :tag "When more than N lines")))
2279 (defcustom org-calendar-to-agenda-key [?c]
2280 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2281 The command `org-calendar-goto-agenda' will be bound to this key. The
2282 default is the character `c' because then `c' can be used to switch back and
2283 forth between agenda and calendar."
2284 :group 'org-agenda
2285 :type 'sexp)
2287 (defcustom org-agenda-compact-blocks nil
2288 "Non-nil means, make the block agenda more compact.
2289 This is done by leaving out unnecessary lines."
2290 :group 'org-agenda
2291 :type nil)
2293 (defgroup org-agenda-export nil
2294 "Options concerning exporting agenda views in Org-mode."
2295 :tag "Org Agenda Export"
2296 :group 'org-agenda)
2298 (defcustom org-agenda-with-colors t
2299 "Non-nil means, use colors in agenda views."
2300 :group 'org-agenda-export
2301 :type 'boolean)
2303 (defcustom org-agenda-exporter-settings nil
2304 "Alist of variable/value pairs that should be active during agenda export.
2305 This is a good place to set uptions for ps-print and for htmlize."
2306 :group 'org-agenda-export
2307 :type '(repeat
2308 (list
2309 (variable)
2310 (sexp :tag "Value"))))
2312 (defcustom org-agenda-export-html-style ""
2313 "The style specification for exported HTML Agenda files.
2314 If this variable contains a string, it will replace the default <style>
2315 section as produced by `htmlize'.
2316 Since there are different ways of setting style information, this variable
2317 needs to contain the full HTML structure to provide a style, including the
2318 surrounding HTML tags. The style specifications should include definitions
2319 the fonts used by the agenda, here is an example:
2321 <style type=\"text/css\">
2322 p { font-weight: normal; color: gray; }
2323 .org-agenda-structure {
2324 font-size: 110%;
2325 color: #003399;
2326 font-weight: 600;
2328 .org-todo {
2329 color: #cc6666;Week-agenda:
2330 font-weight: bold;
2332 .org-done {
2333 color: #339933;
2335 .title { text-align: center; }
2336 .todo, .deadline { color: red; }
2337 .done { color: green; }
2338 </style>
2340 or, if you want to keep the style in a file,
2342 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2344 As the value of this option simply gets inserted into the HTML <head> header,
2345 you can \"misuse\" it to also add other text to the header. However,
2346 <style>...</style> is required, if not present the variable will be ignored."
2347 :group 'org-agenda-export
2348 :group 'org-export-html
2349 :type 'string)
2351 (defgroup org-agenda-custom-commands nil
2352 "Options concerning agenda views in Org-mode."
2353 :tag "Org Agenda Custom Commands"
2354 :group 'org-agenda)
2356 (defcustom org-agenda-custom-commands nil
2357 "Custom commands for the agenda.
2358 These commands will be offered on the splash screen displayed by the
2359 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2361 (key desc type match options files)
2363 key The key (one or more characters as a string) to be associated
2364 with the command.
2365 desc A description of the commend, when omitted or nil, a default
2366 description is built using MATCH.
2367 type The command type, any of the following symbols:
2368 todo Entries with a specific TODO keyword, in all agenda files.
2369 tags Tags match in all agenda files.
2370 tags-todo Tags match in all agenda files, TODO entries only.
2371 todo-tree Sparse tree of specific TODO keyword in *current* file.
2372 tags-tree Sparse tree with all tags matches in *current* file.
2373 occur-tree Occur sparse tree for *current* file.
2374 ... A user-defined function.
2375 match What to search for:
2376 - a single keyword for TODO keyword searches
2377 - a tags match expression for tags searches
2378 - a regular expression for occur searches
2379 options A list of option settings, similar to that in a let form, so like
2380 this: ((opt1 val1) (opt2 val2) ...)
2381 files A list of files file to write the produced agenda buffer to
2382 with the command `org-store-agenda-views'.
2383 If a file name ends in \".html\", an HTML version of the buffer
2384 is written out. If it ends in \".ps\", a postscript version is
2385 produced. Otherwide, only the plain text is written to the file.
2387 You can also define a set of commands, to create a composite agenda buffer.
2388 In this case, an entry looks like this:
2390 (key desc (cmd1 cmd2 ...) general-options file)
2392 where
2394 desc A description string to be displayed in the dispatcher menu.
2395 cmd An agenda command, similar to the above. However, tree commands
2396 are no allowed, but instead you can get agenda and global todo list.
2397 So valid commands for a set are:
2398 (agenda)
2399 (alltodo)
2400 (stuck)
2401 (todo \"match\" options files)
2402 (tags \"match\" options files)
2403 (tags-todo \"match\" options files)
2405 Each command can carry a list of options, and another set of options can be
2406 given for the whole set of commands. Individual command options take
2407 precedence over the general options.
2409 When using several characters as key to a command, the first characters
2410 are prefix commands. For the dispatcher to display useful information, you
2411 should provide a description for the prefix, like
2413 (setq org-agenda-custom-commands
2414 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2415 (\"hl\" tags \"+HOME+Lisa\")
2416 (\"hp\" tags \"+HOME+Peter\")
2417 (\"hk\" tags \"+HOME+Kim\")))"
2418 :group 'org-agenda-custom-commands
2419 :type '(repeat
2420 (choice :value ("a" "" tags "" nil)
2421 (list :tag "Single command"
2422 (string :tag "Access Key(s) ")
2423 (option (string :tag "Description"))
2424 (choice
2425 (const :tag "Agenda" agenda)
2426 (const :tag "TODO list" alltodo)
2427 (const :tag "Stuck projects" stuck)
2428 (const :tag "Tags search (all agenda files)" tags)
2429 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2430 (const :tag "TODO keyword search (all agenda files)" todo)
2431 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2432 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2433 (const :tag "Occur tree (current buffer)" occur-tree)
2434 (sexp :tag "Other, user-defined function"))
2435 (string :tag "Match")
2436 (repeat :tag "Local options"
2437 (list (variable :tag "Option") (sexp :tag "Value")))
2438 (option (repeat :tag "Export" (file :tag "Export to"))))
2439 (list :tag "Command series, all agenda files"
2440 (string :tag "Access Key(s)")
2441 (string :tag "Description ")
2442 (repeat
2443 (choice
2444 (const :tag "Agenda" (agenda))
2445 (const :tag "TODO list" (alltodo))
2446 (const :tag "Stuck projects" (stuck))
2447 (list :tag "Tags search"
2448 (const :format "" tags)
2449 (string :tag "Match")
2450 (repeat :tag "Local options"
2451 (list (variable :tag "Option")
2452 (sexp :tag "Value"))))
2454 (list :tag "Tags search, TODO entries only"
2455 (const :format "" tags-todo)
2456 (string :tag "Match")
2457 (repeat :tag "Local options"
2458 (list (variable :tag "Option")
2459 (sexp :tag "Value"))))
2461 (list :tag "TODO keyword search"
2462 (const :format "" todo)
2463 (string :tag "Match")
2464 (repeat :tag "Local options"
2465 (list (variable :tag "Option")
2466 (sexp :tag "Value"))))
2468 (list :tag "Other, user-defined function"
2469 (symbol :tag "function")
2470 (string :tag "Match")
2471 (repeat :tag "Local options"
2472 (list (variable :tag "Option")
2473 (sexp :tag "Value"))))))
2475 (repeat :tag "General options"
2476 (list (variable :tag "Option")
2477 (sexp :tag "Value")))
2478 (option (repeat :tag "Export" (file :tag "Export to"))))
2479 (cons :tag "Prefix key documentation"
2480 (string :tag "Access Key(s)")
2481 (string :tag "Description ")))))
2483 (defcustom org-stuck-projects
2484 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2485 "How to identify stuck projects.
2486 This is a list of four items:
2487 1. A tags/todo matcher string that is used to identify a project.
2488 The entire tree below a headline matched by this is considered one project.
2489 2. A list of TODO keywords identifying non-stuck projects.
2490 If the project subtree contains any headline with one of these todo
2491 keywords, the project is considered to be not stuck. If you specify
2492 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2493 3. A list of tags identifying non-stuck projects.
2494 If the project subtree contains any headline with one of these tags,
2495 the project is considered to be not stuck. If you specify \"*\" as
2496 a tag, any tag will mark the project unstuck.
2497 4. An arbitrary regular expression matching non-stuck projects.
2499 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2500 or `C-c a #' to produce the list."
2501 :group 'org-agenda-custom-commands
2502 :type '(list
2503 (string :tag "Tags/TODO match to identify a project")
2504 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2505 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2506 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2509 (defgroup org-agenda-skip nil
2510 "Options concerning skipping parts of agenda files."
2511 :tag "Org Agenda Skip"
2512 :group 'org-agenda)
2514 (defcustom org-agenda-todo-list-sublevels t
2515 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2516 When nil, the sublevels of a TODO entry are not checked, resulting in
2517 potentially much shorter TODO lists."
2518 :group 'org-agenda-skip
2519 :group 'org-todo
2520 :type 'boolean)
2522 (defcustom org-agenda-todo-ignore-with-date nil
2523 "Non-nil means, don't show entries with a date in the global todo list.
2524 You can use this if you prefer to mark mere appointments with a TODO keyword,
2525 but don't want them to show up in the TODO list.
2526 When this is set, it also covers deadlines and scheduled items, the settings
2527 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2528 will be ignored."
2529 :group 'org-agenda-skip
2530 :group 'org-todo
2531 :type 'boolean)
2533 (defcustom org-agenda-todo-ignore-scheduled nil
2534 "Non-nil means, don't show scheduled entries in the global todo list.
2535 The idea behind this is that by scheduling it, you have already taken care
2536 of this item.
2537 See also `org-agenda-todo-ignore-with-date'."
2538 :group 'org-agenda-skip
2539 :group 'org-todo
2540 :type 'boolean)
2542 (defcustom org-agenda-todo-ignore-deadlines nil
2543 "Non-nil means, don't show near deadline entries in the global todo list.
2544 Near means closer than `org-deadline-warning-days' days.
2545 The idea behind this is that such items will appear in the agenda anyway.
2546 See also `org-agenda-todo-ignore-with-date'."
2547 :group 'org-agenda-skip
2548 :group 'org-todo
2549 :type 'boolean)
2551 (defcustom org-agenda-skip-scheduled-if-done nil
2552 "Non-nil means don't show scheduled items in agenda when they are done.
2553 This is relevant for the daily/weekly agenda, not for the TODO list. And
2554 it applies only to the actual date of the scheduling. Warnings about
2555 an item with a past scheduling dates are always turned off when the item
2556 is DONE."
2557 :group 'org-agenda-skip
2558 :type 'boolean)
2560 (defcustom org-agenda-skip-deadline-if-done nil
2561 "Non-nil means don't show deadines when the corresponding item is done.
2562 When nil, the deadline is still shown and should give you a happy feeling.
2563 This is relevant for the daily/weekly agenda. And it applied only to the
2564 actualy date of the deadline. Warnings about approching and past-due
2565 deadlines are always turned off when the item is DONE."
2566 :group 'org-agenda-skip
2567 :type 'boolean)
2569 (defcustom org-agenda-skip-timestamp-if-done nil
2570 "Non-nil means don't select item by timestamp or -range if it is DONE."
2571 :group 'org-agenda-skip
2572 :type 'boolean)
2574 (defcustom org-timeline-show-empty-dates 3
2575 "Non-nil means, `org-timeline' also shows dates without an entry.
2576 When nil, only the days which actually have entries are shown.
2577 When t, all days between the first and the last date are shown.
2578 When an integer, show also empty dates, but if there is a gap of more than
2579 N days, just insert a special line indicating the size of the gap."
2580 :group 'org-agenda-skip
2581 :type '(choice
2582 (const :tag "None" nil)
2583 (const :tag "All" t)
2584 (number :tag "at most")))
2587 (defgroup org-agenda-startup nil
2588 "Options concerning initial settings in the Agenda in Org Mode."
2589 :tag "Org Agenda Startup"
2590 :group 'org-agenda)
2592 (defcustom org-finalize-agenda-hook nil
2593 "Hook run just before displaying an agenda buffer."
2594 :group 'org-agenda-startup
2595 :type 'hook)
2597 (defcustom org-agenda-mouse-1-follows-link nil
2598 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2599 A longer mouse click will still set point. Does not work on XEmacs.
2600 Needs to be set before org.el is loaded."
2601 :group 'org-agenda-startup
2602 :type 'boolean)
2604 (defcustom org-agenda-start-with-follow-mode nil
2605 "The initial value of follow-mode in a newly created agenda window."
2606 :group 'org-agenda-startup
2607 :type 'boolean)
2609 (defgroup org-agenda-windows nil
2610 "Options concerning the windows used by the Agenda in Org Mode."
2611 :tag "Org Agenda Windows"
2612 :group 'org-agenda)
2614 (defcustom org-agenda-window-setup 'reorganize-frame
2615 "How the agenda buffer should be displayed.
2616 Possible values for this option are:
2618 current-window Show agenda in the current window, keeping all other windows.
2619 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2620 other-window Use `switch-to-buffer-other-window' to display agenda.
2621 reorganize-frame Show only two windows on the current frame, the current
2622 window and the agenda.
2623 See also the variable `org-agenda-restore-windows-after-quit'."
2624 :group 'org-agenda-windows
2625 :type '(choice
2626 (const current-window)
2627 (const other-frame)
2628 (const other-window)
2629 (const reorganize-frame)))
2631 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2632 "The min and max height of the agenda window as a fraction of frame height.
2633 The value of the variable is a cons cell with two numbers between 0 and 1.
2634 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2635 :group 'org-agenda-windows
2636 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2638 (defcustom org-agenda-restore-windows-after-quit nil
2639 "Non-nil means, restore window configuration open exiting agenda.
2640 Before the window configuration is changed for displaying the agenda,
2641 the current status is recorded. When the agenda is exited with
2642 `q' or `x' and this option is set, the old state is restored. If
2643 `org-agenda-window-setup' is `other-frame', the value of this
2644 option will be ignored.."
2645 :group 'org-agenda-windows
2646 :type 'boolean)
2648 (defcustom org-indirect-buffer-display 'other-window
2649 "How should indirect tree buffers be displayed?
2650 This applies to indirect buffers created with the commands
2651 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2652 Valid values are:
2653 current-window Display in the current window
2654 other-window Just display in another window.
2655 dedicated-frame Create one new frame, and re-use it each time.
2656 new-frame Make a new frame each time. Note that in this case
2657 previously-made indirect buffers are kept, and you need to
2658 kill these buffers yourself."
2659 :group 'org-structure
2660 :group 'org-agenda-windows
2661 :type '(choice
2662 (const :tag "In current window" current-window)
2663 (const :tag "In current frame, other window" other-window)
2664 (const :tag "Each time a new frame" new-frame)
2665 (const :tag "One dedicated frame" dedicated-frame)))
2667 (defgroup org-agenda-daily/weekly nil
2668 "Options concerning the daily/weekly agenda."
2669 :tag "Org Agenda Daily/Weekly"
2670 :group 'org-agenda)
2672 (defcustom org-agenda-ndays 7
2673 "Number of days to include in overview display.
2674 Should be 1 or 7."
2675 :group 'org-agenda-daily/weekly
2676 :type 'number)
2678 (defcustom org-agenda-start-on-weekday 1
2679 "Non-nil means, start the overview always on the specified weekday.
2680 0 denotes Sunday, 1 denotes Monday etc.
2681 When nil, always start on the current day."
2682 :group 'org-agenda-daily/weekly
2683 :type '(choice (const :tag "Today" nil)
2684 (number :tag "Weekday No.")))
2686 (defcustom org-agenda-show-all-dates t
2687 "Non-nil means, `org-agenda' shows every day in the selected range.
2688 When nil, only the days which actually have entries are shown."
2689 :group 'org-agenda-daily/weekly
2690 :type 'boolean)
2692 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2693 "Format string for displaying dates in the agenda.
2694 Used by the daily/weekly agenda and by the timeline. This should be
2695 a format string understood by `format-time-string', or a function returning
2696 the formatted date as a string. The function must take a single argument,
2697 a calendar-style date list like (month day year)."
2698 :group 'org-agenda-daily/weekly
2699 :type '(choice
2700 (string :tag "Format string")
2701 (function :tag "Function")))
2703 (defun org-agenda-format-date-aligned (date)
2704 "Format a date string for display in the daily/weekly agenda, or timeline.
2705 This function makes sure that dates are aligned for easy reading."
2706 (format "%-9s %2d %s %4d"
2707 (calendar-day-name date)
2708 (extract-calendar-day date)
2709 (calendar-month-name (extract-calendar-month date))
2710 (extract-calendar-year date)))
2712 (defcustom org-agenda-include-diary nil
2713 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2714 :group 'org-agenda-daily/weekly
2715 :type 'boolean)
2717 (defcustom org-agenda-include-all-todo nil
2718 "Set means weekly/daily agenda will always contain all TODO entries.
2719 The TODO entries will be listed at the top of the agenda, before
2720 the entries for specific days."
2721 :group 'org-agenda-daily/weekly
2722 :type 'boolean)
2724 (defcustom org-agenda-repeating-timestamp-show-all t
2725 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2726 When nil, only one occurence is shown, either today or the
2727 nearest into the future."
2728 :group 'org-agenda-daily/weekly
2729 :type 'boolean)
2731 (defcustom org-deadline-warning-days 14
2732 "No. of days before expiration during which a deadline becomes active.
2733 This variable governs the display in sparse trees and in the agenda.
2734 When 0 or negative, it means use this number (the absolute value of it)
2735 even if a deadline has a different individual lead time specified."
2736 :group 'org-time
2737 :group 'org-agenda-daily/weekly
2738 :type 'number)
2740 (defcustom org-scheduled-past-days 10000
2741 "No. of days to continue listing scheduled items that are not marked DONE.
2742 When an item is scheduled on a date, it shows up in the agenda on this
2743 day and will be listed until it is marked done for the number of days
2744 given here."
2745 :group 'org-agenda-daily/weekly
2746 :type 'number)
2748 (defgroup org-agenda-time-grid nil
2749 "Options concerning the time grid in the Org-mode Agenda."
2750 :tag "Org Agenda Time Grid"
2751 :group 'org-agenda)
2753 (defcustom org-agenda-use-time-grid t
2754 "Non-nil means, show a time grid in the agenda schedule.
2755 A time grid is a set of lines for specific times (like every two hours between
2756 8:00 and 20:00). The items scheduled for a day at specific times are
2757 sorted in between these lines.
2758 For details about when the grid will be shown, and what it will look like, see
2759 the variable `org-agenda-time-grid'."
2760 :group 'org-agenda-time-grid
2761 :type 'boolean)
2763 (defcustom org-agenda-time-grid
2764 '((daily today require-timed)
2765 "----------------"
2766 (800 1000 1200 1400 1600 1800 2000))
2768 "The settings for time grid for agenda display.
2769 This is a list of three items. The first item is again a list. It contains
2770 symbols specifying conditions when the grid should be displayed:
2772 daily if the agenda shows a single day
2773 weekly if the agenda shows an entire week
2774 today show grid on current date, independent of daily/weekly display
2775 require-timed show grid only if at least one item has a time specification
2777 The second item is a string which will be places behing the grid time.
2779 The third item is a list of integers, indicating the times that should have
2780 a grid line."
2781 :group 'org-agenda-time-grid
2782 :type
2783 '(list
2784 (set :greedy t :tag "Grid Display Options"
2785 (const :tag "Show grid in single day agenda display" daily)
2786 (const :tag "Show grid in weekly agenda display" weekly)
2787 (const :tag "Always show grid for today" today)
2788 (const :tag "Show grid only if any timed entries are present"
2789 require-timed)
2790 (const :tag "Skip grid times already present in an entry"
2791 remove-match))
2792 (string :tag "Grid String")
2793 (repeat :tag "Grid Times" (integer :tag "Time"))))
2795 (defgroup org-agenda-sorting nil
2796 "Options concerning sorting in the Org-mode Agenda."
2797 :tag "Org Agenda Sorting"
2798 :group 'org-agenda)
2800 (defconst org-sorting-choice
2801 '(choice
2802 (const time-up) (const time-down)
2803 (const category-keep) (const category-up) (const category-down)
2804 (const tag-down) (const tag-up)
2805 (const priority-up) (const priority-down))
2806 "Sorting choices.")
2808 (defcustom org-agenda-sorting-strategy
2809 '((agenda time-up category-keep priority-down)
2810 (todo category-keep priority-down)
2811 (tags category-keep priority-down))
2812 "Sorting structure for the agenda items of a single day.
2813 This is a list of symbols which will be used in sequence to determine
2814 if an entry should be listed before another entry. The following
2815 symbols are recognized:
2817 time-up Put entries with time-of-day indications first, early first
2818 time-down Put entries with time-of-day indications first, late first
2819 category-keep Keep the default order of categories, corresponding to the
2820 sequence in `org-agenda-files'.
2821 category-up Sort alphabetically by category, A-Z.
2822 category-down Sort alphabetically by category, Z-A.
2823 tag-up Sort alphabetically by last tag, A-Z.
2824 tag-down Sort alphabetically by last tag, Z-A.
2825 priority-up Sort numerically by priority, high priority last.
2826 priority-down Sort numerically by priority, high priority first.
2828 The different possibilities will be tried in sequence, and testing stops
2829 if one comparison returns a \"not-equal\". For example, the default
2830 '(time-up category-keep priority-down)
2831 means: Pull out all entries having a specified time of day and sort them,
2832 in order to make a time schedule for the current day the first thing in the
2833 agenda listing for the day. Of the entries without a time indication, keep
2834 the grouped in categories, don't sort the categories, but keep them in
2835 the sequence given in `org-agenda-files'. Within each category sort by
2836 priority.
2838 Leaving out `category-keep' would mean that items will be sorted across
2839 categories by priority.
2841 Instead of a single list, this can also be a set of list for specific
2842 contents, with a context symbol in the car of the list, any of
2843 `agenda', `todo', `tags' for the corresponding agenda views."
2844 :group 'org-agenda-sorting
2845 :type `(choice
2846 (repeat :tag "General" ,org-sorting-choice)
2847 (list :tag "Individually"
2848 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2849 (repeat ,org-sorting-choice))
2850 (cons (const :tag "Strategy for TODO lists" todo)
2851 (repeat ,org-sorting-choice))
2852 (cons (const :tag "Strategy for Tags matches" tags)
2853 (repeat ,org-sorting-choice)))))
2855 (defcustom org-sort-agenda-notime-is-late t
2856 "Non-nil means, items without time are considered late.
2857 This is only relevant for sorting. When t, items which have no explicit
2858 time like 15:30 will be considered as 99:01, i.e. later than any items which
2859 do have a time. When nil, the default time is before 0:00. You can use this
2860 option to decide if the schedule for today should come before or after timeless
2861 agenda entries."
2862 :group 'org-agenda-sorting
2863 :type 'boolean)
2865 (defgroup org-agenda-line-format nil
2866 "Options concerning the entry prefix in the Org-mode agenda display."
2867 :tag "Org Agenda Line Format"
2868 :group 'org-agenda)
2870 (defcustom org-agenda-prefix-format
2871 '((agenda . " %-12:c%?-12t% s")
2872 (timeline . " % s")
2873 (todo . " %-12:c")
2874 (tags . " %-12:c"))
2875 "Format specifications for the prefix of items in the agenda views.
2876 An alist with four entries, for the different agenda types. The keys to the
2877 sublists are `agenda', `timeline', `todo', and `tags'. The values
2878 are format strings.
2879 This format works similar to a printf format, with the following meaning:
2881 %c the category of the item, \"Diary\" for entries from the diary, or
2882 as given by the CATEGORY keyword or derived from the file name.
2883 %T the *last* tag of the item. Last because inherited tags come
2884 first in the list.
2885 %t the time-of-day specification if one applies to the entry, in the
2886 format HH:MM
2887 %s Scheduling/Deadline information, a short string
2889 All specifiers work basically like the standard `%s' of printf, but may
2890 contain two additional characters: A question mark just after the `%' and
2891 a whitespace/punctuation character just before the final letter.
2893 If the first character after `%' is a question mark, the entire field
2894 will only be included if the corresponding value applies to the
2895 current entry. This is useful for fields which should have fixed
2896 width when present, but zero width when absent. For example,
2897 \"%?-12t\" will result in a 12 character time field if a time of the
2898 day is specified, but will completely disappear in entries which do
2899 not contain a time.
2901 If there is punctuation or whitespace character just before the final
2902 format letter, this character will be appended to the field value if
2903 the value is not empty. For example, the format \"%-12:c\" leads to
2904 \"Diary: \" if the category is \"Diary\". If the category were be
2905 empty, no additional colon would be interted.
2907 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2908 - Indent the line with two space characters
2909 - Give the category in a 12 chars wide field, padded with whitespace on
2910 the right (because of `-'). Append a colon if there is a category
2911 (because of `:').
2912 - If there is a time-of-day, put it into a 12 chars wide field. If no
2913 time, don't put in an empty field, just skip it (because of '?').
2914 - Finally, put the scheduling information and append a whitespace.
2916 As another example, if you don't want the time-of-day of entries in
2917 the prefix, you could use:
2919 (setq org-agenda-prefix-format \" %-11:c% s\")
2921 See also the variables `org-agenda-remove-times-when-in-prefix' and
2922 `org-agenda-remove-tags'."
2923 :type '(choice
2924 (string :tag "General format")
2925 (list :greedy t :tag "View dependent"
2926 (cons (const agenda) (string :tag "Format"))
2927 (cons (const timeline) (string :tag "Format"))
2928 (cons (const todo) (string :tag "Format"))
2929 (cons (const tags) (string :tag "Format"))))
2930 :group 'org-agenda-line-format)
2932 (defvar org-prefix-format-compiled nil
2933 "The compiled version of the most recently used prefix format.
2934 See the variable `org-agenda-prefix-format'.")
2936 (defcustom org-agenda-todo-keyword-format "%-1s"
2937 "Format for the TODO keyword in agenda lines.
2938 Set this to something like \"%-12s\" if you want all TODO keywords
2939 to occupy a fixed space in the agenda display."
2940 :group 'org-agenda-line-format
2941 :type 'string)
2943 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2944 "Text preceeding scheduled items in the agenda view.
2945 This is a list with two strings. The first applies when the item is
2946 scheduled on the current day. The second applies when it has been scheduled
2947 previously, it may contain a %d to capture how many days ago the item was
2948 scheduled."
2949 :group 'org-agenda-line-format
2950 :type '(list
2951 (string :tag "Scheduled today ")
2952 (string :tag "Scheduled previously")))
2954 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2955 "Text preceeding deadline items in the agenda view.
2956 This is a list with two strings. The first applies when the item has its
2957 deadline on the current day. The second applies when it is in the past or
2958 in the future, it may contain %d to capture how many days away the deadline
2959 is (was)."
2960 :group 'org-agenda-line-format
2961 :type '(list
2962 (string :tag "Deadline today ")
2963 (string :tag "Deadline relative")))
2965 (defcustom org-agenda-remove-times-when-in-prefix t
2966 "Non-nil means, remove duplicate time specifications in agenda items.
2967 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2968 time-of-day specification in a headline or diary entry is extracted and
2969 placed into the prefix. If this option is non-nil, the original specification
2970 \(a timestamp or -range, or just a plain time(range) specification like
2971 11:30-4pm) will be removed for agenda display. This makes the agenda less
2972 cluttered.
2973 The option can be t or nil. It may also be the symbol `beg', indicating
2974 that the time should only be removed what it is located at the beginning of
2975 the headline/diary entry."
2976 :group 'org-agenda-line-format
2977 :type '(choice
2978 (const :tag "Always" t)
2979 (const :tag "Never" nil)
2980 (const :tag "When at beginning of entry" beg)))
2983 (defcustom org-agenda-default-appointment-duration nil
2984 "Default duration for appointments that only have a starting time.
2985 When nil, no duration is specified in such cases.
2986 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2987 :group 'org-agenda-line-format
2988 :type '(choice
2989 (integer :tag "Minutes")
2990 (const :tag "No default duration")))
2993 (defcustom org-agenda-remove-tags nil
2994 "Non-nil means, remove the tags from the headline copy in the agenda.
2995 When this is the symbol `prefix', only remove tags when
2996 `org-agenda-prefix-format' contains a `%T' specifier."
2997 :group 'org-agenda-line-format
2998 :type '(choice
2999 (const :tag "Always" t)
3000 (const :tag "Never" nil)
3001 (const :tag "When prefix format contains %T" prefix)))
3003 (if (fboundp 'defvaralias)
3004 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3005 'org-agenda-remove-tags))
3007 (defcustom org-agenda-tags-column -80
3008 "Shift tags in agenda items to this column.
3009 If this number is positive, it specifies the column. If it is negative,
3010 it means that the tags should be flushright to that column. For example,
3011 -80 works well for a normal 80 character screen."
3012 :group 'org-agenda-line-format
3013 :type 'integer)
3015 (if (fboundp 'defvaralias)
3016 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3018 (defcustom org-agenda-fontify-priorities t
3019 "Non-nil means, highlight low and high priorities in agenda.
3020 When t, the highest priority entries are bold, lowest priority italic.
3021 This may also be an association list of priority faces. The face may be
3022 a names face, or a list like `(:background \"Red\")'."
3023 :group 'org-agenda-line-format
3024 :type '(choice
3025 (const :tag "Never" nil)
3026 (const :tag "Defaults" t)
3027 (repeat :tag "Specify"
3028 (list (character :tag "Priority" :value ?A)
3029 (sexp :tag "face")))))
3031 (defgroup org-latex nil
3032 "Options for embedding LaTeX code into Org-mode"
3033 :tag "Org LaTeX"
3034 :group 'org)
3036 (defcustom org-format-latex-options
3037 '(:foreground default :background default :scale 1.0
3038 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3039 :matchers ("begin" "$" "$$" "\\(" "\\["))
3040 "Options for creating images from LaTeX fragments.
3041 This is a property list with the following properties:
3042 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3043 `default' means use the forground of the default face.
3044 :background the background color, or \"Transparent\".
3045 `default' means use the background of the default face.
3046 :scale a scaling factor for the size of the images
3047 :html-foreground, :html-background, :html-scale
3048 The same numbers for HTML export.
3049 :matchers a list indicating which matchers should be used to
3050 find LaTeX fragments. Valid members of this list are:
3051 \"begin\" find environments
3052 \"$\" find math expressions surrounded by $...$
3053 \"$$\" find math expressions surrounded by $$....$$
3054 \"\\(\" find math expressions surrounded by \\(...\\)
3055 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3056 :group 'org-latex
3057 :type 'plist)
3059 (defcustom org-format-latex-header "\\documentclass{article}
3060 \\usepackage{fullpage} % do not remove
3061 \\usepackage{amssymb}
3062 \\usepackage[usenames]{color}
3063 \\usepackage{amsmath}
3064 \\usepackage{latexsym}
3065 \\usepackage[mathscr]{eucal}
3066 \\pagestyle{empty} % do not remove"
3067 "The document header used for processing LaTeX fragments."
3068 :group 'org-latex
3069 :type 'string)
3071 (defgroup org-export nil
3072 "Options for exporting org-listings."
3073 :tag "Org Export"
3074 :group 'org)
3076 (defgroup org-export-general nil
3077 "General options for exporting Org-mode files."
3078 :tag "Org Export General"
3079 :group 'org-export)
3081 ;; FIXME
3082 (defvar org-export-publishing-directory nil)
3084 (defcustom org-export-with-special-strings t
3085 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3086 When this option is turned on, these strings will be exported as:
3088 Org HTML LaTeX
3089 -----+----------+--------
3090 \\- &shy; \\-
3091 -- &ndash; --
3092 --- &mdash; ---
3093 ... &hellip; \ldots
3095 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3096 :group 'org-export-translation
3097 :type 'boolean)
3099 (defcustom org-export-language-setup
3100 '(("en" "Author" "Date" "Table of Contents")
3101 ("cs" "Autor" "Datum" "Obsah")
3102 ("da" "Ophavsmand" "Dato" "Indhold")
3103 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3104 ("es" "Autor" "Fecha" "\xcdndice")
3105 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3106 ("it" "Autore" "Data" "Indice")
3107 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3108 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3109 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3110 "Terms used in export text, translated to different languages.
3111 Use the variable `org-export-default-language' to set the language,
3112 or use the +OPTION lines for a per-file setting."
3113 :group 'org-export-general
3114 :type '(repeat
3115 (list
3116 (string :tag "HTML language tag")
3117 (string :tag "Author")
3118 (string :tag "Date")
3119 (string :tag "Table of Contents"))))
3121 (defcustom org-export-default-language "en"
3122 "The default language of HTML export, as a string.
3123 This should have an association in `org-export-language-setup'."
3124 :group 'org-export-general
3125 :type 'string)
3127 (defcustom org-export-skip-text-before-1st-heading t
3128 "Non-nil means, skip all text before the first headline when exporting.
3129 When nil, that text is exported as well."
3130 :group 'org-export-general
3131 :type 'boolean)
3133 (defcustom org-export-headline-levels 3
3134 "The last level which is still exported as a headline.
3135 Inferior levels will produce itemize lists when exported.
3136 Note that a numeric prefix argument to an exporter function overrides
3137 this setting.
3139 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3140 :group 'org-export-general
3141 :type 'number)
3143 (defcustom org-export-with-section-numbers t
3144 "Non-nil means, add section numbers to headlines when exporting.
3146 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3147 :group 'org-export-general
3148 :type 'boolean)
3150 (defcustom org-export-with-toc t
3151 "Non-nil means, create a table of contents in exported files.
3152 The TOC contains headlines with levels up to`org-export-headline-levels'.
3153 When an integer, include levels up to N in the toc, this may then be
3154 different from `org-export-headline-levels', but it will not be allowed
3155 to be larger than the number of headline levels.
3156 When nil, no table of contents is made.
3158 Headlines which contain any TODO items will be marked with \"(*)\" in
3159 ASCII export, and with red color in HTML output, if the option
3160 `org-export-mark-todo-in-toc' is set.
3162 In HTML output, the TOC will be clickable.
3164 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3165 or \"toc:3\"."
3166 :group 'org-export-general
3167 :type '(choice
3168 (const :tag "No Table of Contents" nil)
3169 (const :tag "Full Table of Contents" t)
3170 (integer :tag "TOC to level")))
3172 (defcustom org-export-mark-todo-in-toc nil
3173 "Non-nil means, mark TOC lines that contain any open TODO items."
3174 :group 'org-export-general
3175 :type 'boolean)
3177 (defcustom org-export-preserve-breaks nil
3178 "Non-nil means, preserve all line breaks when exporting.
3179 Normally, in HTML output paragraphs will be reformatted. In ASCII
3180 export, line breaks will always be preserved, regardless of this variable.
3182 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3183 :group 'org-export-general
3184 :type 'boolean)
3186 (defcustom org-export-with-archived-trees 'headline
3187 "Whether subtrees with the ARCHIVE tag should be exported.
3188 This can have three different values
3189 nil Do not export, pretend this tree is not present
3190 t Do export the entire tree
3191 headline Only export the headline, but skip the tree below it."
3192 :group 'org-export-general
3193 :group 'org-archive
3194 :type '(choice
3195 (const :tag "not at all" nil)
3196 (const :tag "headline only" 'headline)
3197 (const :tag "entirely" t)))
3199 (defcustom org-export-author-info t
3200 "Non-nil means, insert author name and email into the exported file.
3202 This option can also be set with the +OPTIONS line,
3203 e.g. \"author-info:nil\"."
3204 :group 'org-export-general
3205 :type 'boolean)
3207 (defcustom org-export-time-stamp-file t
3208 "Non-nil means, insert a time stamp into the exported file.
3209 The time stamp shows when the file was created.
3211 This option can also be set with the +OPTIONS line,
3212 e.g. \"timestamp:nil\"."
3213 :group 'org-export-general
3214 :type 'boolean)
3216 (defcustom org-export-with-timestamps t
3217 "If nil, do not export time stamps and associated keywords."
3218 :group 'org-export-general
3219 :type 'boolean)
3221 (defcustom org-export-remove-timestamps-from-toc t
3222 "If nil, remove timestamps from the table of contents entries."
3223 :group 'org-export-general
3224 :type 'boolean)
3226 (defcustom org-export-with-tags 'not-in-toc
3227 "If nil, do not export tags, just remove them from headlines.
3228 If this is the symbol `not-in-toc', tags will be removed from table of
3229 contents entries, but still be shown in the headlines of the document.
3231 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3232 :group 'org-export-general
3233 :type '(choice
3234 (const :tag "Off" nil)
3235 (const :tag "Not in TOC" not-in-toc)
3236 (const :tag "On" t)))
3238 (defcustom org-export-with-drawers nil
3239 "Non-nil means, export with drawers like the property drawer.
3240 When t, all drawers are exported. This may also be a list of
3241 drawer names to export."
3242 :group 'org-export-general
3243 :type '(choice
3244 (const :tag "All drawers" t)
3245 (const :tag "None" nil)
3246 (repeat :tag "Selected drawers"
3247 (string :tag "Drawer name"))))
3249 (defgroup org-export-translation nil
3250 "Options for translating special ascii sequences for the export backends."
3251 :tag "Org Export Translation"
3252 :group 'org-export)
3254 (defcustom org-export-with-emphasize t
3255 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3256 If the export target supports emphasizing text, the word will be
3257 typeset in bold, italic, or underlined, respectively. Works only for
3258 single words, but you can say: I *really* *mean* *this*.
3259 Not all export backends support this.
3261 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3262 :group 'org-export-translation
3263 :type 'boolean)
3265 (defcustom org-export-with-footnotes t
3266 "If nil, export [1] as a footnote marker.
3267 Lines starting with [1] will be formatted as footnotes.
3269 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3270 :group 'org-export-translation
3271 :type 'boolean)
3273 (defcustom org-export-with-sub-superscripts t
3274 "Non-nil means, interpret \"_\" and \"^\" for export.
3275 When this option is turned on, you can use TeX-like syntax for sub- and
3276 superscripts. Several characters after \"_\" or \"^\" will be
3277 considered as a single item - so grouping with {} is normally not
3278 needed. For example, the following things will be parsed as single
3279 sub- or superscripts.
3281 10^24 or 10^tau several digits will be considered 1 item.
3282 10^-12 or 10^-tau a leading sign with digits or a word
3283 x^2-y^3 will be read as x^2 - y^3, because items are
3284 terminated by almost any nonword/nondigit char.
3285 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3287 Still, ambiguity is possible - so when in doubt use {} to enclose the
3288 sub/superscript. If you set this variable to the symbol `{}',
3289 the braces are *required* in order to trigger interpretations as
3290 sub/superscript. This can be helpful in documents that need \"_\"
3291 frequently in plain text.
3293 Not all export backends support this, but HTML does.
3295 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3296 :group 'org-export-translation
3297 :type '(choice
3298 (const :tag "Always interpret" t)
3299 (const :tag "Only with braces" {})
3300 (const :tag "Never interpret" nil)))
3302 (defcustom org-export-with-special-strings t
3303 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3304 When this option is turned on, these strings will be exported as:
3306 \\- : &shy;
3307 -- : &ndash;
3308 --- : &mdash;
3310 Not all export backends support this, but HTML does.
3312 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3313 :group 'org-export-translation
3314 :type 'boolean)
3316 (defcustom org-export-with-TeX-macros t
3317 "Non-nil means, interpret simple TeX-like macros when exporting.
3318 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3319 No only real TeX macros will work here, but the standard HTML entities
3320 for math can be used as macro names as well. For a list of supported
3321 names in HTML export, see the constant `org-html-entities'.
3322 Not all export backends support this.
3324 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3325 :group 'org-export-translation
3326 :group 'org-export-latex
3327 :type 'boolean)
3329 (defcustom org-export-with-LaTeX-fragments nil
3330 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3331 When set, the exporter will find LaTeX environments if the \\begin line is
3332 the first non-white thing on a line. It will also find the math delimiters
3333 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3334 display math.
3336 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3337 :group 'org-export-translation
3338 :group 'org-export-latex
3339 :type 'boolean)
3341 (defcustom org-export-with-fixed-width t
3342 "Non-nil means, lines starting with \":\" will be in fixed width font.
3343 This can be used to have pre-formatted text, fragments of code etc. For
3344 example:
3345 : ;; Some Lisp examples
3346 : (while (defc cnt)
3347 : (ding))
3348 will be looking just like this in also HTML. See also the QUOTE keyword.
3349 Not all export backends support this.
3351 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3352 :group 'org-export-translation
3353 :type 'boolean)
3355 (defcustom org-match-sexp-depth 3
3356 "Number of stacked braces for sub/superscript matching.
3357 This has to be set before loading org.el to be effective."
3358 :group 'org-export-translation
3359 :type 'integer)
3361 (defgroup org-export-tables nil
3362 "Options for exporting tables in Org-mode."
3363 :tag "Org Export Tables"
3364 :group 'org-export)
3366 (defcustom org-export-with-tables t
3367 "If non-nil, lines starting with \"|\" define a table.
3368 For example:
3370 | Name | Address | Birthday |
3371 |-------------+----------+-----------|
3372 | Arthur Dent | England | 29.2.2100 |
3374 Not all export backends support this.
3376 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3377 :group 'org-export-tables
3378 :type 'boolean)
3380 (defcustom org-export-highlight-first-table-line t
3381 "Non-nil means, highlight the first table line.
3382 In HTML export, this means use <th> instead of <td>.
3383 In tables created with table.el, this applies to the first table line.
3384 In Org-mode tables, all lines before the first horizontal separator
3385 line will be formatted with <th> tags."
3386 :group 'org-export-tables
3387 :type 'boolean)
3389 (defcustom org-export-table-remove-special-lines t
3390 "Remove special lines and marking characters in calculating tables.
3391 This removes the special marking character column from tables that are set
3392 up for spreadsheet calculations. It also removes the entire lines
3393 marked with `!', `_', or `^'. The lines with `$' are kept, because
3394 the values of constants may be useful to have."
3395 :group 'org-export-tables
3396 :type 'boolean)
3398 (defcustom org-export-prefer-native-exporter-for-tables nil
3399 "Non-nil means, always export tables created with table.el natively.
3400 Natively means, use the HTML code generator in table.el.
3401 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3402 the table does not use row- or column-spanning). This has the
3403 advantage, that the automatic HTML conversions for math symbols and
3404 sub/superscripts can be applied. Org-mode's HTML generator is also
3405 much faster."
3406 :group 'org-export-tables
3407 :type 'boolean)
3409 (defgroup org-export-ascii nil
3410 "Options specific for ASCII export of Org-mode files."
3411 :tag "Org Export ASCII"
3412 :group 'org-export)
3414 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3415 "Characters for underlining headings in ASCII export.
3416 In the given sequence, these characters will be used for level 1, 2, ..."
3417 :group 'org-export-ascii
3418 :type '(repeat character))
3420 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3421 "Bullet characters for headlines converted to lists in ASCII export.
3422 The first character is used for the first lest level generated in this
3423 way, and so on. If there are more levels than characters given here,
3424 the list will be repeated.
3425 Note that plain lists will keep the same bullets as the have in the
3426 Org-mode file."
3427 :group 'org-export-ascii
3428 :type '(repeat character))
3430 (defgroup org-export-xml nil
3431 "Options specific for XML export of Org-mode files."
3432 :tag "Org Export XML"
3433 :group 'org-export)
3435 (defgroup org-export-html nil
3436 "Options specific for HTML export of Org-mode files."
3437 :tag "Org Export HTML"
3438 :group 'org-export)
3440 (defcustom org-export-html-coding-system nil
3442 :group 'org-export-html
3443 :type 'coding-system)
3445 (defcustom org-export-html-extension "html"
3446 "The extension for exported HTML files."
3447 :group 'org-export-html
3448 :type 'string)
3450 (defcustom org-export-html-style
3451 "<style type=\"text/css\">
3452 html {
3453 font-family: Times, serif;
3454 font-size: 12pt;
3456 .title { text-align: center; }
3457 .todo { color: red; }
3458 .done { color: green; }
3459 .timestamp { color: grey }
3460 .timestamp-kwd { color: CadetBlue }
3461 .tag { background-color:lightblue; font-weight:normal }
3462 .target { background-color: lavender; }
3463 pre {
3464 border: 1pt solid #AEBDCC;
3465 background-color: #F3F5F7;
3466 padding: 5pt;
3467 font-family: courier, monospace;
3469 table { border-collapse: collapse; }
3470 td, th {
3471 vertical-align: top;
3472 <!--border: 1pt solid #ADB9CC;-->
3474 </style>"
3475 "The default style specification for exported HTML files.
3476 Since there are different ways of setting style information, this variable
3477 needs to contain the full HTML structure to provide a style, including the
3478 surrounding HTML tags. The style specifications should include definitions
3479 for new classes todo, done, title, and deadline. For example, legal values
3480 would be:
3482 <style type=\"text/css\">
3483 p { font-weight: normal; color: gray; }
3484 h1 { color: black; }
3485 .title { text-align: center; }
3486 .todo, .deadline { color: red; }
3487 .done { color: green; }
3488 </style>
3490 or, if you want to keep the style in a file,
3492 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3494 As the value of this option simply gets inserted into the HTML <head> header,
3495 you can \"misuse\" it to add arbitrary text to the header."
3496 :group 'org-export-html
3497 :type 'string)
3500 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3501 "Format for typesetting the document title in HTML export."
3502 :group 'org-export-html
3503 :type 'string)
3505 (defcustom org-export-html-toplevel-hlevel 2
3506 "The <H> level for level 1 headings in HTML export."
3507 :group 'org-export-html
3508 :type 'string)
3510 (defcustom org-export-html-link-org-files-as-html t
3511 "Non-nil means, make file links to `file.org' point to `file.html'.
3512 When org-mode is exporting an org-mode file to HTML, links to
3513 non-html files are directly put into a href tag in HTML.
3514 However, links to other Org-mode files (recognized by the
3515 extension `.org.) should become links to the corresponding html
3516 file, assuming that the linked org-mode file will also be
3517 converted to HTML.
3518 When nil, the links still point to the plain `.org' file."
3519 :group 'org-export-html
3520 :type 'boolean)
3522 (defcustom org-export-html-inline-images 'maybe
3523 "Non-nil means, inline images into exported HTML pages.
3524 This is done using an <img> tag. When nil, an anchor with href is used to
3525 link to the image. If this option is `maybe', then images in links with
3526 an empty description will be inlined, while images with a description will
3527 be linked only."
3528 :group 'org-export-html
3529 :type '(choice (const :tag "Never" nil)
3530 (const :tag "Always" t)
3531 (const :tag "When there is no description" maybe)))
3533 ;; FIXME: rename
3534 (defcustom org-export-html-expand t
3535 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3536 When nil, these tags will be exported as plain text and therefore
3537 not be interpreted by a browser.
3539 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3540 :group 'org-export-html
3541 :type 'boolean)
3543 (defcustom org-export-html-table-tag
3544 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3545 "The HTML tag that is used to start a table.
3546 This must be a <table> tag, but you may change the options like
3547 borders and spacing."
3548 :group 'org-export-html
3549 :type 'string)
3551 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3552 "The opening tag for table header fields.
3553 This is customizable so that alignment options can be specified."
3554 :group 'org-export-tables
3555 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3557 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3558 "The opening tag for table data fields.
3559 This is customizable so that alignment options can be specified."
3560 :group 'org-export-tables
3561 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3563 (defcustom org-export-html-with-timestamp nil
3564 "If non-nil, write `org-export-html-html-helper-timestamp'
3565 into the exported HTML text. Otherwise, the buffer will just be saved
3566 to a file."
3567 :group 'org-export-html
3568 :type 'boolean)
3570 (defcustom org-export-html-html-helper-timestamp
3571 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3572 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3573 :group 'org-export-html
3574 :type 'string)
3576 (defgroup org-export-icalendar nil
3577 "Options specific for iCalendar export of Org-mode files."
3578 :tag "Org Export iCalendar"
3579 :group 'org-export)
3581 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3582 "The file name for the iCalendar file covering all agenda files.
3583 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3584 The file name should be absolute, the file will be overwritten without warning."
3585 :group 'org-export-icalendar
3586 :type 'file)
3588 (defcustom org-icalendar-include-todo nil
3589 "Non-nil means, export to iCalendar files should also cover TODO items."
3590 :group 'org-export-icalendar
3591 :type '(choice
3592 (const :tag "None" nil)
3593 (const :tag "Unfinished" t)
3594 (const :tag "All" all)))
3596 (defcustom org-icalendar-include-sexps t
3597 "Non-nil means, export to iCalendar files should also cover sexp entries.
3598 These are entries like in the diary, but directly in an Org-mode file."
3599 :group 'org-export-icalendar
3600 :type 'boolean)
3602 (defcustom org-icalendar-include-body 100
3603 "Amount of text below headline to be included in iCalendar export.
3604 This is a number of characters that should maximally be included.
3605 Properties, scheduling and clocking lines will always be removed.
3606 The text will be inserted into the DESCRIPTION field."
3607 :group 'org-export-icalendar
3608 :type '(choice
3609 (const :tag "Nothing" nil)
3610 (const :tag "Everything" t)
3611 (integer :tag "Max characters")))
3613 (defcustom org-icalendar-combined-name "OrgMode"
3614 "Calendar name for the combined iCalendar representing all agenda files."
3615 :group 'org-export-icalendar
3616 :type 'string)
3618 (defgroup org-font-lock nil
3619 "Font-lock settings for highlighting in Org-mode."
3620 :tag "Org Font Lock"
3621 :group 'org)
3623 (defcustom org-level-color-stars-only nil
3624 "Non-nil means fontify only the stars in each headline.
3625 When nil, the entire headline is fontified.
3626 Changing it requires restart of `font-lock-mode' to become effective
3627 also in regions already fontified."
3628 :group 'org-font-lock
3629 :type 'boolean)
3631 (defcustom org-hide-leading-stars nil
3632 "Non-nil means, hide the first N-1 stars in a headline.
3633 This works by using the face `org-hide' for these stars. This
3634 face is white for a light background, and black for a dark
3635 background. You may have to customize the face `org-hide' to
3636 make this work.
3637 Changing it requires restart of `font-lock-mode' to become effective
3638 also in regions already fontified.
3639 You may also set this on a per-file basis by adding one of the following
3640 lines to the buffer:
3642 #+STARTUP: hidestars
3643 #+STARTUP: showstars"
3644 :group 'org-font-lock
3645 :type 'boolean)
3647 (defcustom org-fontify-done-headline nil
3648 "Non-nil means, change the face of a headline if it is marked DONE.
3649 Normally, only the TODO/DONE keyword indicates the state of a headline.
3650 When this is non-nil, the headline after the keyword is set to the
3651 `org-headline-done' as an additional indication."
3652 :group 'org-font-lock
3653 :type 'boolean)
3655 (defcustom org-fontify-emphasized-text t
3656 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3657 Changing this variable requires a restart of Emacs to take effect."
3658 :group 'org-font-lock
3659 :type 'boolean)
3661 (defcustom org-highlight-latex-fragments-and-specials nil
3662 "Non-nil means, fontify what is treated specially by the exporters."
3663 :group 'org-font-lock
3664 :type 'boolean)
3666 (defcustom org-hide-emphasis-markers nil
3667 "Non-nil mean font-lock should hide the emphasis marker characters."
3668 :group 'org-font-lock
3669 :type 'boolean)
3671 (defvar org-emph-re nil
3672 "Regular expression for matching emphasis.")
3673 (defvar org-verbatim-re nil
3674 "Regular expression for matching verbatim text.")
3675 (defvar org-emphasis-regexp-components) ; defined just below
3676 (defvar org-emphasis-alist) ; defined just below
3677 (defun org-set-emph-re (var val)
3678 "Set variable and compute the emphasis regular expression."
3679 (set var val)
3680 (when (and (boundp 'org-emphasis-alist)
3681 (boundp 'org-emphasis-regexp-components)
3682 org-emphasis-alist org-emphasis-regexp-components)
3683 (let* ((e org-emphasis-regexp-components)
3684 (pre (car e))
3685 (post (nth 1 e))
3686 (border (nth 2 e))
3687 (body (nth 3 e))
3688 (nl (nth 4 e))
3689 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3690 (body1 (concat body "*?"))
3691 (markers (mapconcat 'car org-emphasis-alist ""))
3692 (vmarkers (mapconcat
3693 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3694 org-emphasis-alist "")))
3695 ;; make sure special characters appear at the right position in the class
3696 (if (string-match "\\^" markers)
3697 (setq markers (concat (replace-match "" t t markers) "^")))
3698 (if (string-match "-" markers)
3699 (setq markers (concat (replace-match "" t t markers) "-")))
3700 (if (string-match "\\^" vmarkers)
3701 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3702 (if (string-match "-" vmarkers)
3703 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3704 (if (> nl 0)
3705 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3706 (int-to-string nl) "\\}")))
3707 ;; Make the regexp
3708 (setq org-emph-re
3709 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3710 "\\("
3711 "\\([" markers "]\\)"
3712 "\\("
3713 "[^" border "]\\|"
3714 "[^" border (if (and nil stacked) markers) "]"
3715 body1
3716 "[^" border (if (and nil stacked) markers) "]"
3717 "\\)"
3718 "\\3\\)"
3719 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3720 (setq org-verbatim-re
3721 (concat "\\([" pre "]\\|^\\)"
3722 "\\("
3723 "\\([" vmarkers "]\\)"
3724 "\\("
3725 "[^" border "]\\|"
3726 "[^" border "]"
3727 body1
3728 "[^" border "]"
3729 "\\)"
3730 "\\3\\)"
3731 "\\([" post "]\\|$\\)")))))
3733 (defcustom org-emphasis-regexp-components
3734 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3735 "Components used to build the regular expression for emphasis.
3736 This is a list with 6 entries. Terminology: In an emphasis string
3737 like \" *strong word* \", we call the initial space PREMATCH, the final
3738 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3739 and \"trong wor\" is the body. The different components in this variable
3740 specify what is allowed/forbidden in each part:
3742 pre Chars allowed as prematch. Beginning of line will be allowed too.
3743 post Chars allowed as postmatch. End of line will be allowed too.
3744 border The chars *forbidden* as border characters.
3745 body-regexp A regexp like \".\" to match a body character. Don't use
3746 non-shy groups here, and don't allow newline here.
3747 newline The maximum number of newlines allowed in an emphasis exp.
3749 Use customize to modify this, or restart Emacs after changing it."
3750 :group 'org-font-lock
3751 :set 'org-set-emph-re
3752 :type '(list
3753 (sexp :tag "Allowed chars in pre ")
3754 (sexp :tag "Allowed chars in post ")
3755 (sexp :tag "Forbidden chars in border ")
3756 (sexp :tag "Regexp for body ")
3757 (integer :tag "number of newlines allowed")
3758 (option (boolean :tag "Stacking (DISABLED) "))))
3760 (defcustom org-emphasis-alist
3761 '(("*" bold "<b>" "</b>")
3762 ("/" italic "<i>" "</i>")
3763 ("_" underline "<u>" "</u>")
3764 ("=" org-code "<code>" "</code>" verbatim)
3765 ("~" org-verbatim "" "" verbatim)
3766 ("+" (:strike-through t) "<del>" "</del>")
3768 "Special syntax for emphasized text.
3769 Text starting and ending with a special character will be emphasized, for
3770 example *bold*, _underlined_ and /italic/. This variable sets the marker
3771 characters, the face to be used by font-lock for highlighting in Org-mode
3772 Emacs buffers, and the HTML tags to be used for this.
3773 Use customize to modify this, or restart Emacs after changing it."
3774 :group 'org-font-lock
3775 :set 'org-set-emph-re
3776 :type '(repeat
3777 (list
3778 (string :tag "Marker character")
3779 (choice
3780 (face :tag "Font-lock-face")
3781 (plist :tag "Face property list"))
3782 (string :tag "HTML start tag")
3783 (string :tag "HTML end tag")
3784 (option (const verbatim)))))
3786 ;;; The faces
3788 (defgroup org-faces nil
3789 "Faces in Org-mode."
3790 :tag "Org Faces"
3791 :group 'org-font-lock)
3793 (defun org-compatible-face (inherits specs)
3794 "Make a compatible face specification.
3795 If INHERITS is an existing face and if the Emacs version supports it,
3796 just inherit the face. If not, use SPECS to define the face.
3797 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3798 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3799 to the top of the list. The `min-colors' attribute will be removed from
3800 any other entries, and any resulting duplicates will be removed entirely."
3801 (cond
3802 ((and inherits (facep inherits)
3803 (not (featurep 'xemacs)) (> emacs-major-version 22))
3804 ;; In Emacs 23, we use inheritance where possible.
3805 ;; We only do this in Emacs 23, because only there the outline
3806 ;; faces have been changed to the original org-mode-level-faces.
3807 (list (list t :inherit inherits)))
3808 ((or (featurep 'xemacs) (< emacs-major-version 22))
3809 ;; These do not understand the `min-colors' attribute.
3810 (let (r e a)
3811 (while (setq e (pop specs))
3812 (cond
3813 ((memq (car e) '(t default)) (push e r))
3814 ((setq a (member '(min-colors 8) (car e)))
3815 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3816 (cdr e)))))
3817 ((setq a (assq 'min-colors (car e)))
3818 (setq e (cons (delq a (car e)) (cdr e)))
3819 (or (assoc (car e) r) (push e r)))
3820 (t (or (assoc (car e) r) (push e r)))))
3821 (nreverse r)))
3822 (t specs)))
3823 (put 'org-compatible-face 'lisp-indent-function 1)
3825 (defface org-hide
3826 '((((background light)) (:foreground "white"))
3827 (((background dark)) (:foreground "black")))
3828 "Face used to hide leading stars in headlines.
3829 The forground color of this face should be equal to the background
3830 color of the frame."
3831 :group 'org-faces)
3833 (defface org-level-1 ;; font-lock-function-name-face
3834 (org-compatible-face 'outline-1
3835 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3836 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3837 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3838 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3839 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3840 (t (:bold t))))
3841 "Face used for level 1 headlines."
3842 :group 'org-faces)
3844 (defface org-level-2 ;; font-lock-variable-name-face
3845 (org-compatible-face 'outline-2
3846 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3847 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3848 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3849 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3850 (t (:bold t))))
3851 "Face used for level 2 headlines."
3852 :group 'org-faces)
3854 (defface org-level-3 ;; font-lock-keyword-face
3855 (org-compatible-face 'outline-3
3856 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3857 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3858 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3859 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3860 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3861 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3862 (t (:bold t))))
3863 "Face used for level 3 headlines."
3864 :group 'org-faces)
3866 (defface org-level-4 ;; font-lock-comment-face
3867 (org-compatible-face 'outline-4
3868 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3869 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3870 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3871 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3872 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3873 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3874 (t (:bold t))))
3875 "Face used for level 4 headlines."
3876 :group 'org-faces)
3878 (defface org-level-5 ;; font-lock-type-face
3879 (org-compatible-face 'outline-5
3880 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3881 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3882 (((class color) (min-colors 8)) (:foreground "green"))))
3883 "Face used for level 5 headlines."
3884 :group 'org-faces)
3886 (defface org-level-6 ;; font-lock-constant-face
3887 (org-compatible-face 'outline-6
3888 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3889 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3890 (((class color) (min-colors 8)) (:foreground "magenta"))))
3891 "Face used for level 6 headlines."
3892 :group 'org-faces)
3894 (defface org-level-7 ;; font-lock-builtin-face
3895 (org-compatible-face 'outline-7
3896 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3897 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3898 (((class color) (min-colors 8)) (:foreground "blue"))))
3899 "Face used for level 7 headlines."
3900 :group 'org-faces)
3902 (defface org-level-8 ;; font-lock-string-face
3903 (org-compatible-face 'outline-8
3904 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3905 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3906 (((class color) (min-colors 8)) (:foreground "green"))))
3907 "Face used for level 8 headlines."
3908 :group 'org-faces)
3910 (defface org-special-keyword ;; font-lock-string-face
3911 (org-compatible-face nil
3912 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3913 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3914 (t (:italic t))))
3915 "Face used for special keywords."
3916 :group 'org-faces)
3918 (defface org-drawer ;; font-lock-function-name-face
3919 (org-compatible-face nil
3920 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3921 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3922 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3923 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3924 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3925 (t (:bold t))))
3926 "Face used for drawers."
3927 :group 'org-faces)
3929 (defface org-property-value nil
3930 "Face used for the value of a property."
3931 :group 'org-faces)
3933 (defface org-column
3934 (org-compatible-face nil
3935 '((((class color) (min-colors 16) (background light))
3936 (:background "grey90"))
3937 (((class color) (min-colors 16) (background dark))
3938 (:background "grey30"))
3939 (((class color) (min-colors 8))
3940 (:background "cyan" :foreground "black"))
3941 (t (:inverse-video t))))
3942 "Face for column display of entry properties."
3943 :group 'org-faces)
3945 (when (fboundp 'set-face-attribute)
3946 ;; Make sure that a fixed-width face is used when we have a column table.
3947 (set-face-attribute 'org-column nil
3948 :height (face-attribute 'default :height)
3949 :family (face-attribute 'default :family)))
3951 (defface org-warning
3952 (org-compatible-face 'font-lock-warning-face
3953 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3954 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3955 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3956 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3957 (t (:bold t))))
3958 "Face for deadlines and TODO keywords."
3959 :group 'org-faces)
3961 (defface org-archived ; similar to shadow
3962 (org-compatible-face 'shadow
3963 '((((class color grayscale) (min-colors 88) (background light))
3964 (:foreground "grey50"))
3965 (((class color grayscale) (min-colors 88) (background dark))
3966 (:foreground "grey70"))
3967 (((class color) (min-colors 8) (background light))
3968 (:foreground "green"))
3969 (((class color) (min-colors 8) (background dark))
3970 (:foreground "yellow"))))
3971 "Face for headline with the ARCHIVE tag."
3972 :group 'org-faces)
3974 (defface org-link
3975 '((((class color) (background light)) (:foreground "Purple" :underline t))
3976 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3977 (t (:underline t)))
3978 "Face for links."
3979 :group 'org-faces)
3981 (defface org-ellipsis
3982 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3983 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3984 (t (:strike-through t)))
3985 "Face for the ellipsis in folded text."
3986 :group 'org-faces)
3988 (defface org-target
3989 '((((class color) (background light)) (:underline t))
3990 (((class color) (background dark)) (:underline t))
3991 (t (:underline t)))
3992 "Face for links."
3993 :group 'org-faces)
3995 (defface org-date
3996 '((((class color) (background light)) (:foreground "Purple" :underline t))
3997 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3998 (t (:underline t)))
3999 "Face for links."
4000 :group 'org-faces)
4002 (defface org-sexp-date
4003 '((((class color) (background light)) (:foreground "Purple"))
4004 (((class color) (background dark)) (:foreground "Cyan"))
4005 (t (:underline t)))
4006 "Face for links."
4007 :group 'org-faces)
4009 (defface org-tag
4010 '((t (:bold t)))
4011 "Face for tags."
4012 :group 'org-faces)
4014 (defface org-todo ; font-lock-warning-face
4015 (org-compatible-face nil
4016 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4017 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4018 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4019 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4020 (t (:inverse-video t :bold t))))
4021 "Face for TODO keywords."
4022 :group 'org-faces)
4024 (defface org-done ;; font-lock-type-face
4025 (org-compatible-face nil
4026 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4027 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4028 (((class color) (min-colors 8)) (:foreground "green"))
4029 (t (:bold t))))
4030 "Face used for todo keywords that indicate DONE items."
4031 :group 'org-faces)
4033 (defface org-headline-done ;; font-lock-string-face
4034 (org-compatible-face nil
4035 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4036 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4037 (((class color) (min-colors 8) (background light)) (:bold nil))))
4038 "Face used to indicate that a headline is DONE.
4039 This face is only used if `org-fontify-done-headline' is set. If applies
4040 to the part of the headline after the DONE keyword."
4041 :group 'org-faces)
4043 (defcustom org-todo-keyword-faces nil
4044 "Faces for specific TODO keywords.
4045 This is a list of cons cells, with TODO keywords in the car
4046 and faces in the cdr. The face can be a symbol, or a property
4047 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4048 :group 'org-faces
4049 :group 'org-todo
4050 :type '(repeat
4051 (cons
4052 (string :tag "keyword")
4053 (sexp :tag "face"))))
4055 (defface org-table ;; font-lock-function-name-face
4056 (org-compatible-face nil
4057 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4058 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4059 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4060 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4061 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4062 (((class color) (min-colors 8) (background dark)))))
4063 "Face used for tables."
4064 :group 'org-faces)
4066 (defface org-formula
4067 (org-compatible-face nil
4068 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4069 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4070 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4071 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4072 (t (:bold t :italic t))))
4073 "Face for formulas."
4074 :group 'org-faces)
4076 (defface org-code
4077 (org-compatible-face nil
4078 '((((class color grayscale) (min-colors 88) (background light))
4079 (:foreground "grey50"))
4080 (((class color grayscale) (min-colors 88) (background dark))
4081 (:foreground "grey70"))
4082 (((class color) (min-colors 8) (background light))
4083 (:foreground "green"))
4084 (((class color) (min-colors 8) (background dark))
4085 (:foreground "yellow"))))
4086 "Face for fixed-with text like code snippets."
4087 :group 'org-faces
4088 :version "22.1")
4090 (defface org-verbatim
4091 (org-compatible-face nil
4092 '((((class color grayscale) (min-colors 88) (background light))
4093 (:foreground "grey50" :underline t))
4094 (((class color grayscale) (min-colors 88) (background dark))
4095 (:foreground "grey70" :underline t))
4096 (((class color) (min-colors 8) (background light))
4097 (:foreground "green" :underline t))
4098 (((class color) (min-colors 8) (background dark))
4099 (:foreground "yellow" :underline t))))
4100 "Face for fixed-with text like code snippets."
4101 :group 'org-faces
4102 :version "22.1")
4104 (defface org-agenda-structure ;; font-lock-function-name-face
4105 (org-compatible-face nil
4106 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4107 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4108 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4109 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4110 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4111 (t (:bold t))))
4112 "Face used in agenda for captions and dates."
4113 :group 'org-faces)
4115 (defface org-scheduled-today
4116 (org-compatible-face nil
4117 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4118 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4119 (((class color) (min-colors 8)) (:foreground "green"))
4120 (t (:bold t :italic t))))
4121 "Face for items scheduled for a certain day."
4122 :group 'org-faces)
4124 (defface org-scheduled-previously
4125 (org-compatible-face nil
4126 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4127 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4128 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4129 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4130 (t (:bold t))))
4131 "Face for items scheduled previously, and not yet done."
4132 :group 'org-faces)
4134 (defface org-upcoming-deadline
4135 (org-compatible-face nil
4136 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4137 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4138 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4139 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4140 (t (:bold t))))
4141 "Face for items scheduled previously, and not yet done."
4142 :group 'org-faces)
4144 (defcustom org-agenda-deadline-faces
4145 '((1.0 . org-warning)
4146 (0.5 . org-upcoming-deadline)
4147 (0.0 . default))
4148 "Faces for showing deadlines in the agenda.
4149 This is a list of cons cells. The cdr of each cell is a face to be used,
4150 and it can also just be like '(:foreground \"yellow\").
4151 Each car is a fraction of the head-warning time that must have passed for
4152 this the face in the cdr to be used for display. The numbers must be
4153 given in descending order. The head-warning time is normally taken
4154 from `org-deadline-warning-days', but can also be specified in the deadline
4155 timestamp itself, like this:
4157 DEADLINE: <2007-08-13 Mon -8d>
4159 You may use d for days, w for weeks, m for months and y for years. Months
4160 and years will only be treated in an approximate fashion (30.4 days for a
4161 month and 365.24 days for a year)."
4162 :group 'org-faces
4163 :group 'org-agenda-daily/weekly
4164 :type '(repeat
4165 (cons
4166 (number :tag "Fraction of head-warning time passed")
4167 (sexp :tag "Face"))))
4169 ;; FIXME: this is not a good face yet.
4170 (defface org-agenda-restriction-lock
4171 (org-compatible-face nil
4172 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4173 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4174 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4175 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4176 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4177 (t (:inverse-video t))))
4178 "Face for showing the agenda restriction lock."
4179 :group 'org-faces)
4181 (defface org-time-grid ;; font-lock-variable-name-face
4182 (org-compatible-face nil
4183 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4184 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4185 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4186 "Face used for time grids."
4187 :group 'org-faces)
4189 (defconst org-level-faces
4190 '(org-level-1 org-level-2 org-level-3 org-level-4
4191 org-level-5 org-level-6 org-level-7 org-level-8
4194 (defcustom org-n-level-faces (length org-level-faces)
4195 "The number of different faces to be used for headlines.
4196 Org-mode defines 8 different headline faces, so this can be at most 8.
4197 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4198 :type 'number
4199 :group 'org-faces)
4201 ;;; Functions and variables from ther packages
4202 ;; Declared here to avoid compiler warnings
4204 (eval-and-compile
4205 (unless (fboundp 'declare-function)
4206 (defmacro declare-function (fn file &optional arglist fileonly))))
4208 ;; XEmacs only
4209 (defvar outline-mode-menu-heading)
4210 (defvar outline-mode-menu-show)
4211 (defvar outline-mode-menu-hide)
4212 (defvar zmacs-regions) ; XEmacs regions
4214 ;; Emacs only
4215 (defvar mark-active)
4217 ;; Various packages
4218 ;; FIXME: get the argument lists for the UNKNOWN stuff
4219 (declare-function add-to-diary-list "diary-lib"
4220 (date string specifier &optional marker globcolor literal))
4221 (declare-function table--at-cell-p "table" (position &optional object at-column))
4222 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4223 (declare-function bbdb "ext:bbdb-com" (string elidep))
4224 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4225 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4226 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4227 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4228 (declare-function bbdb-record-name "ext:bbdb" (record))
4229 (declare-function bibtex-beginning-of-entry "bibtex" ())
4230 (declare-function bibtex-generate-autokey "bibtex" ())
4231 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4232 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4233 (defvar calc-embedded-close-formula)
4234 (defvar calc-embedded-open-formula)
4235 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4236 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4237 (declare-function calendar-check-holidays "holidays" (date))
4238 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4239 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4240 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4241 (declare-function calendar-forward-day "cal-move" (arg))
4242 (declare-function calendar-french-date-string "cal-french" (&optional date))
4243 (declare-function calendar-goto-date "cal-move" (date))
4244 (declare-function calendar-goto-today "cal-move" ())
4245 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4246 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4247 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4248 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4249 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4250 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4251 (defvar calendar-mode-map)
4252 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4253 (declare-function cdlatex-tab "ext:cdlatex" ())
4254 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4255 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4256 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4257 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4258 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4259 (defvar font-lock-unfontify-region-function)
4260 (declare-function gnus-article-show-summary "gnus-art" ())
4261 (declare-function gnus-summary-last-subject "gnus-sum" ())
4262 (defvar gnus-other-frame-object)
4263 (defvar gnus-group-name)
4264 (defvar gnus-article-current)
4265 (defvar Info-current-file)
4266 (defvar Info-current-node)
4267 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4268 (declare-function mh-find-path "mh-utils" ())
4269 (declare-function mh-get-header-field "mh-utils" (field))
4270 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4271 (declare-function mh-header-display "mh-show" ())
4272 (declare-function mh-index-previous-folder "mh-search" ())
4273 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4274 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4275 (declare-function mh-search-choose "mh-search" (&optional searcher))
4276 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4277 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4278 (declare-function mh-show-header-display "mh-show" t t)
4279 (declare-function mh-show-msg "mh-show" (msg))
4280 (declare-function mh-show-show "mh-show" t t)
4281 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4282 (defvar mh-progs)
4283 (defvar mh-current-folder)
4284 (defvar mh-show-folder-buffer)
4285 (defvar mh-index-folder)
4286 (defvar mh-searcher)
4287 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4288 (declare-function parse-time-string "parse-time" (string))
4289 (declare-function remember "remember" (&optional initial))
4290 (declare-function remember-buffer-desc "remember" ())
4291 (declare-function remember-finalize "remember" ())
4292 (defvar remember-save-after-remembering)
4293 (defvar remember-data-file)
4294 (defvar remember-register)
4295 (defvar remember-buffer)
4296 (defvar remember-handler-functions)
4297 (defvar remember-annotation-functions)
4298 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4299 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4300 (declare-function rmail-what-message "rmail" ())
4301 (defvar rmail-current-message)
4302 (defvar texmathp-why)
4303 (declare-function vm-beginning-of-message "ext:vm-page" ())
4304 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4305 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4306 (declare-function vm-isearch-narrow "ext:vm-search" ())
4307 (declare-function vm-isearch-update "ext:vm-search" ())
4308 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4309 (declare-function vm-su-message-id "ext:vm-summary" (m))
4310 (declare-function vm-su-subject "ext:vm-summary" (m))
4311 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4312 (defvar vm-message-pointer)
4313 (defvar vm-folder-directory)
4314 (defvar w3m-current-url)
4315 (defvar w3m-current-title)
4316 ;; backward compatibility to old version of wl
4317 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4318 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4319 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4320 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4321 (declare-function wl-summary-line-from "ext:wl-summary" ())
4322 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4323 (declare-function wl-summary-message-number "ext:wl-summary" ())
4324 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4325 (defvar wl-summary-buffer-elmo-folder)
4326 (defvar wl-summary-buffer-folder-name)
4327 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4329 (defvar org-latex-regexps)
4330 (defvar constants-unit-system)
4332 ;;; Variables for pre-computed regular expressions, all buffer local
4334 (defvar org-drawer-regexp nil
4335 "Matches first line of a hidden block.")
4336 (make-variable-buffer-local 'org-drawer-regexp)
4337 (defvar org-todo-regexp nil
4338 "Matches any of the TODO state keywords.")
4339 (make-variable-buffer-local 'org-todo-regexp)
4340 (defvar org-not-done-regexp nil
4341 "Matches any of the TODO state keywords except the last one.")
4342 (make-variable-buffer-local 'org-not-done-regexp)
4343 (defvar org-todo-line-regexp nil
4344 "Matches a headline and puts TODO state into group 2 if present.")
4345 (make-variable-buffer-local 'org-todo-line-regexp)
4346 (defvar org-complex-heading-regexp nil
4347 "Matches a headline and puts everything into groups:
4348 group 1: the stars
4349 group 2: The todo keyword, maybe
4350 group 3: Priority cookie
4351 group 4: True headline
4352 group 5: Tags")
4353 (make-variable-buffer-local 'org-complex-heading-regexp)
4354 (defvar org-todo-line-tags-regexp nil
4355 "Matches a headline and puts TODO state into group 2 if present.
4356 Also put tags into group 4 if tags are present.")
4357 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4358 (defvar org-nl-done-regexp nil
4359 "Matches newline followed by a headline with the DONE keyword.")
4360 (make-variable-buffer-local 'org-nl-done-regexp)
4361 (defvar org-looking-at-done-regexp nil
4362 "Matches the DONE keyword a point.")
4363 (make-variable-buffer-local 'org-looking-at-done-regexp)
4364 (defvar org-ds-keyword-length 12
4365 "Maximum length of the Deadline and SCHEDULED keywords.")
4366 (make-variable-buffer-local 'org-ds-keyword-length)
4367 (defvar org-deadline-regexp nil
4368 "Matches the DEADLINE keyword.")
4369 (make-variable-buffer-local 'org-deadline-regexp)
4370 (defvar org-deadline-time-regexp nil
4371 "Matches the DEADLINE keyword together with a time stamp.")
4372 (make-variable-buffer-local 'org-deadline-time-regexp)
4373 (defvar org-deadline-line-regexp nil
4374 "Matches the DEADLINE keyword and the rest of the line.")
4375 (make-variable-buffer-local 'org-deadline-line-regexp)
4376 (defvar org-scheduled-regexp nil
4377 "Matches the SCHEDULED keyword.")
4378 (make-variable-buffer-local 'org-scheduled-regexp)
4379 (defvar org-scheduled-time-regexp nil
4380 "Matches the SCHEDULED keyword together with a time stamp.")
4381 (make-variable-buffer-local 'org-scheduled-time-regexp)
4382 (defvar org-closed-time-regexp nil
4383 "Matches the CLOSED keyword together with a time stamp.")
4384 (make-variable-buffer-local 'org-closed-time-regexp)
4386 (defvar org-keyword-time-regexp nil
4387 "Matches any of the 4 keywords, together with the time stamp.")
4388 (make-variable-buffer-local 'org-keyword-time-regexp)
4389 (defvar org-keyword-time-not-clock-regexp nil
4390 "Matches any of the 3 keywords, together with the time stamp.")
4391 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4392 (defvar org-maybe-keyword-time-regexp nil
4393 "Matches a timestamp, possibly preceeded by a keyword.")
4394 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4395 (defvar org-planning-or-clock-line-re nil
4396 "Matches a line with planning or clock info.")
4397 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4399 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4400 rear-nonsticky t mouse-map t fontified t)
4401 "Properties to remove when a string without properties is wanted.")
4403 (defsubst org-match-string-no-properties (num &optional string)
4404 (if (featurep 'xemacs)
4405 (let ((s (match-string num string)))
4406 (remove-text-properties 0 (length s) org-rm-props s)
4408 (match-string-no-properties num string)))
4410 (defsubst org-no-properties (s)
4411 (if (fboundp 'set-text-properties)
4412 (set-text-properties 0 (length s) nil s)
4413 (remove-text-properties 0 (length s) org-rm-props s))
4416 (defsubst org-get-alist-option (option key)
4417 (cond ((eq key t) t)
4418 ((eq option t) t)
4419 ((assoc key option) (cdr (assoc key option)))
4420 (t (cdr (assq 'default option)))))
4422 (defsubst org-inhibit-invisibility ()
4423 "Modified `buffer-invisibility-spec' for Emacs 21.
4424 Some ops with invisible text do not work correctly on Emacs 21. For these
4425 we turn off invisibility temporarily. Use this in a `let' form."
4426 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4428 (defsubst org-set-local (var value)
4429 "Make VAR local in current buffer and set it to VALUE."
4430 (set (make-variable-buffer-local var) value))
4432 (defsubst org-mode-p ()
4433 "Check if the current buffer is in Org-mode."
4434 (eq major-mode 'org-mode))
4436 (defsubst org-last (list)
4437 "Return the last element of LIST."
4438 (car (last list)))
4440 (defun org-let (list &rest body)
4441 (eval (cons 'let (cons list body))))
4442 (put 'org-let 'lisp-indent-function 1)
4444 (defun org-let2 (list1 list2 &rest body)
4445 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4446 (put 'org-let2 'lisp-indent-function 2)
4447 (defconst org-startup-options
4448 '(("fold" org-startup-folded t)
4449 ("overview" org-startup-folded t)
4450 ("nofold" org-startup-folded nil)
4451 ("showall" org-startup-folded nil)
4452 ("content" org-startup-folded content)
4453 ("hidestars" org-hide-leading-stars t)
4454 ("showstars" org-hide-leading-stars nil)
4455 ("odd" org-odd-levels-only t)
4456 ("oddeven" org-odd-levels-only nil)
4457 ("align" org-startup-align-all-tables t)
4458 ("noalign" org-startup-align-all-tables nil)
4459 ("customtime" org-display-custom-times t)
4460 ("logdone" org-log-done time)
4461 ("lognotedone" org-log-done note)
4462 ("nologdone" org-log-done nil)
4463 ("lognoteclock-out" org-log-note-clock-out t)
4464 ("nolognoteclock-out" org-log-note-clock-out nil)
4465 ("logrepeat" org-log-repeat state)
4466 ("lognoterepeat" org-log-repeat note)
4467 ("nologrepeat" org-log-repeat nil)
4468 ("constcgs" constants-unit-system cgs)
4469 ("constSI" constants-unit-system SI))
4470 "Variable associated with STARTUP options for org-mode.
4471 Each element is a list of three items: The startup options as written
4472 in the #+STARTUP line, the corresponding variable, and the value to
4473 set this variable to if the option is found. An optional forth element PUSH
4474 means to push this value onto the list in the variable.")
4476 (defun org-set-regexps-and-options ()
4477 "Precompute regular expressions for current buffer."
4478 (when (org-mode-p)
4479 (org-set-local 'org-todo-kwd-alist nil)
4480 (org-set-local 'org-todo-key-alist nil)
4481 (org-set-local 'org-todo-key-trigger nil)
4482 (org-set-local 'org-todo-keywords-1 nil)
4483 (org-set-local 'org-done-keywords nil)
4484 (org-set-local 'org-todo-heads nil)
4485 (org-set-local 'org-todo-sets nil)
4486 (org-set-local 'org-todo-log-states nil)
4487 (let ((re (org-make-options-regexp
4488 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4489 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4490 "CONSTANTS" "PROPERTY" "DRAWERS")))
4491 (splitre "[ \t]+")
4492 kwds kws0 kwsa key log value cat arch tags const links hw dws
4493 tail sep kws1 prio props drawers)
4494 (save-excursion
4495 (save-restriction
4496 (widen)
4497 (goto-char (point-min))
4498 (while (re-search-forward re nil t)
4499 (setq key (match-string 1) value (org-match-string-no-properties 2))
4500 (cond
4501 ((equal key "CATEGORY")
4502 (if (string-match "[ \t]+$" value)
4503 (setq value (replace-match "" t t value)))
4504 (setq cat value))
4505 ((member key '("SEQ_TODO" "TODO"))
4506 (push (cons 'sequence (org-split-string value splitre)) kwds))
4507 ((equal key "TYP_TODO")
4508 (push (cons 'type (org-split-string value splitre)) kwds))
4509 ((equal key "TAGS")
4510 (setq tags (append tags (org-split-string value splitre))))
4511 ((equal key "COLUMNS")
4512 (org-set-local 'org-columns-default-format value))
4513 ((equal key "LINK")
4514 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4515 (push (cons (match-string 1 value)
4516 (org-trim (match-string 2 value)))
4517 links)))
4518 ((equal key "PRIORITIES")
4519 (setq prio (org-split-string value " +")))
4520 ((equal key "PROPERTY")
4521 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4522 (push (cons (match-string 1 value) (match-string 2 value))
4523 props)))
4524 ((equal key "DRAWERS")
4525 (setq drawers (org-split-string value splitre)))
4526 ((equal key "CONSTANTS")
4527 (setq const (append const (org-split-string value splitre))))
4528 ((equal key "STARTUP")
4529 (let ((opts (org-split-string value splitre))
4530 l var val)
4531 (while (setq l (pop opts))
4532 (when (setq l (assoc l org-startup-options))
4533 (setq var (nth 1 l) val (nth 2 l))
4534 (if (not (nth 3 l))
4535 (set (make-local-variable var) val)
4536 (if (not (listp (symbol-value var)))
4537 (set (make-local-variable var) nil))
4538 (set (make-local-variable var) (symbol-value var))
4539 (add-to-list var val))))))
4540 ((equal key "ARCHIVE")
4541 (string-match " *$" value)
4542 (setq arch (replace-match "" t t value))
4543 (remove-text-properties 0 (length arch)
4544 '(face t fontified t) arch)))
4546 (when cat
4547 (org-set-local 'org-category (intern cat))
4548 (push (cons "CATEGORY" cat) props))
4549 (when prio
4550 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4551 (setq prio (mapcar 'string-to-char prio))
4552 (org-set-local 'org-highest-priority (nth 0 prio))
4553 (org-set-local 'org-lowest-priority (nth 1 prio))
4554 (org-set-local 'org-default-priority (nth 2 prio)))
4555 (and props (org-set-local 'org-local-properties (nreverse props)))
4556 (and drawers (org-set-local 'org-drawers drawers))
4557 (and arch (org-set-local 'org-archive-location arch))
4558 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4559 ;; Process the TODO keywords
4560 (unless kwds
4561 ;; Use the global values as if they had been given locally.
4562 (setq kwds (default-value 'org-todo-keywords))
4563 (if (stringp (car kwds))
4564 (setq kwds (list (cons org-todo-interpretation
4565 (default-value 'org-todo-keywords)))))
4566 (setq kwds (reverse kwds)))
4567 (setq kwds (nreverse kwds))
4568 (let (inter kws kw)
4569 (while (setq kws (pop kwds))
4570 (setq inter (pop kws) sep (member "|" kws)
4571 kws0 (delete "|" (copy-sequence kws))
4572 kwsa nil
4573 kws1 (mapcar
4574 (lambda (x)
4575 ;; 1 2
4576 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4577 (progn
4578 (setq kw (match-string 1 x)
4579 key (and (match-end 2) (match-string 2 x))
4580 log (org-extract-log-state-settings x))
4581 (push (cons kw (and key (string-to-char key))) kwsa)
4582 (and log (push log org-todo-log-states))
4584 (error "Invalid TODO keyword %s" x)))
4585 kws0)
4586 kwsa (if kwsa (append '((:startgroup))
4587 (nreverse kwsa)
4588 '((:endgroup))))
4589 hw (car kws1)
4590 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4591 tail (list inter hw (car dws) (org-last dws)))
4592 (add-to-list 'org-todo-heads hw 'append)
4593 (push kws1 org-todo-sets)
4594 (setq org-done-keywords (append org-done-keywords dws nil))
4595 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4596 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4597 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4598 (setq org-todo-sets (nreverse org-todo-sets)
4599 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4600 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4601 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4602 ;; Process the constants
4603 (when const
4604 (let (e cst)
4605 (while (setq e (pop const))
4606 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4607 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4608 (setq org-table-formula-constants-local cst)))
4610 ;; Process the tags.
4611 (when tags
4612 (let (e tgs)
4613 (while (setq e (pop tags))
4614 (cond
4615 ((equal e "{") (push '(:startgroup) tgs))
4616 ((equal e "}") (push '(:endgroup) tgs))
4617 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4618 (push (cons (match-string 1 e)
4619 (string-to-char (match-string 2 e)))
4620 tgs))
4621 (t (push (list e) tgs))))
4622 (org-set-local 'org-tag-alist nil)
4623 (while (setq e (pop tgs))
4624 (or (and (stringp (car e))
4625 (assoc (car e) org-tag-alist))
4626 (push e org-tag-alist))))))
4628 ;; Compute the regular expressions and other local variables
4629 (if (not org-done-keywords)
4630 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4631 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4632 (length org-scheduled-string)))
4633 org-drawer-regexp
4634 (concat "^[ \t]*:\\("
4635 (mapconcat 'regexp-quote org-drawers "\\|")
4636 "\\):[ \t]*$")
4637 org-not-done-keywords
4638 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4639 org-todo-regexp
4640 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4641 "\\|") "\\)\\>")
4642 org-not-done-regexp
4643 (concat "\\<\\("
4644 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4645 "\\)\\>")
4646 org-todo-line-regexp
4647 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4648 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4649 "\\)\\>\\)?[ \t]*\\(.*\\)")
4650 org-complex-heading-regexp
4651 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4652 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4653 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4654 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4655 org-nl-done-regexp
4656 (concat "\n\\*+[ \t]+"
4657 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4658 "\\)" "\\>")
4659 org-todo-line-tags-regexp
4660 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4661 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4662 (org-re
4663 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4664 org-looking-at-done-regexp
4665 (concat "^" "\\(?:"
4666 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4667 "\\>")
4668 org-deadline-regexp (concat "\\<" org-deadline-string)
4669 org-deadline-time-regexp
4670 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4671 org-deadline-line-regexp
4672 (concat "\\<\\(" org-deadline-string "\\).*")
4673 org-scheduled-regexp
4674 (concat "\\<" org-scheduled-string)
4675 org-scheduled-time-regexp
4676 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4677 org-closed-time-regexp
4678 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4679 org-keyword-time-regexp
4680 (concat "\\<\\(" org-scheduled-string
4681 "\\|" org-deadline-string
4682 "\\|" org-closed-string
4683 "\\|" org-clock-string "\\)"
4684 " *[[<]\\([^]>]+\\)[]>]")
4685 org-keyword-time-not-clock-regexp
4686 (concat "\\<\\(" org-scheduled-string
4687 "\\|" org-deadline-string
4688 "\\|" org-closed-string
4689 "\\)"
4690 " *[[<]\\([^]>]+\\)[]>]")
4691 org-maybe-keyword-time-regexp
4692 (concat "\\(\\<\\(" org-scheduled-string
4693 "\\|" org-deadline-string
4694 "\\|" org-closed-string
4695 "\\|" org-clock-string "\\)\\)?"
4696 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4697 org-planning-or-clock-line-re
4698 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4699 "\\|" org-deadline-string
4700 "\\|" org-closed-string "\\|" org-clock-string
4701 "\\)\\>\\)")
4703 (org-compute-latex-and-specials-regexp)
4704 (org-set-font-lock-defaults)))
4706 (defun org-extract-log-state-settings (x)
4707 "Extract the log state setting from a TODO keyword string.
4708 This will extract info from a string like \"WAIT(w@/!)\"."
4709 (let (kw key log1 log2)
4710 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4711 (setq kw (match-string 1 x)
4712 key (and (match-end 2) (match-string 2 x))
4713 log1 (and (match-end 3) (match-string 3 x))
4714 log2 (and (match-end 4) (match-string 4 x)))
4715 (and (or log1 log2)
4716 (list kw
4717 (and log1 (if (equal log1 "!") 'time 'note))
4718 (and log2 (if (equal log2 "!") 'time 'note)))))))
4720 (defun org-remove-keyword-keys (list)
4721 "Remove a pair of parenthesis at the end of each string in LIST."
4722 (mapcar (lambda (x)
4723 (if (string-match "(.*)$" x)
4724 (substring x 0 (match-beginning 0))
4726 list))
4728 ;; FIXME: this could be done much better, using second characters etc.
4729 (defun org-assign-fast-keys (alist)
4730 "Assign fast keys to a keyword-key alist.
4731 Respect keys that are already there."
4732 (let (new e k c c1 c2 (char ?a))
4733 (while (setq e (pop alist))
4734 (cond
4735 ((equal e '(:startgroup)) (push e new))
4736 ((equal e '(:endgroup)) (push e new))
4738 (setq k (car e) c2 nil)
4739 (if (cdr e)
4740 (setq c (cdr e))
4741 ;; automatically assign a character.
4742 (setq c1 (string-to-char
4743 (downcase (substring
4744 k (if (= (string-to-char k) ?@) 1 0)))))
4745 (if (or (rassoc c1 new) (rassoc c1 alist))
4746 (while (or (rassoc char new) (rassoc char alist))
4747 (setq char (1+ char)))
4748 (setq c2 c1))
4749 (setq c (or c2 char)))
4750 (push (cons k c) new))))
4751 (nreverse new)))
4753 ;;; Some variables ujsed in various places
4755 (defvar org-window-configuration nil
4756 "Used in various places to store a window configuration.")
4757 (defvar org-finish-function nil
4758 "Function to be called when `C-c C-c' is used.
4759 This is for getting out of special buffers like remember.")
4762 ;; FIXME: Occasionally check by commenting these, to make sure
4763 ;; no other functions uses these, forgetting to let-bind them.
4764 (defvar entry)
4765 (defvar state)
4766 (defvar last-state)
4767 (defvar date)
4768 (defvar description)
4770 ;; Defined somewhere in this file, but used before definition.
4771 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4772 (defvar org-agenda-buffer-name)
4773 (defvar org-agenda-undo-list)
4774 (defvar org-agenda-pending-undo-list)
4775 (defvar org-agenda-overriding-header)
4776 (defvar orgtbl-mode)
4777 (defvar org-html-entities)
4778 (defvar org-struct-menu)
4779 (defvar org-org-menu)
4780 (defvar org-tbl-menu)
4781 (defvar org-agenda-keymap)
4783 ;;;; Emacs/XEmacs compatibility
4785 ;; Overlay compatibility functions
4786 (defun org-make-overlay (beg end &optional buffer)
4787 (if (featurep 'xemacs)
4788 (make-extent beg end buffer)
4789 (make-overlay beg end buffer)))
4790 (defun org-delete-overlay (ovl)
4791 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4792 (defun org-detach-overlay (ovl)
4793 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4794 (defun org-move-overlay (ovl beg end &optional buffer)
4795 (if (featurep 'xemacs)
4796 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4797 (move-overlay ovl beg end buffer)))
4798 (defun org-overlay-put (ovl prop value)
4799 (if (featurep 'xemacs)
4800 (set-extent-property ovl prop value)
4801 (overlay-put ovl prop value)))
4802 (defun org-overlay-display (ovl text &optional face evap)
4803 "Make overlay OVL display TEXT with face FACE."
4804 (if (featurep 'xemacs)
4805 (let ((gl (make-glyph text)))
4806 (and face (set-glyph-face gl face))
4807 (set-extent-property ovl 'invisible t)
4808 (set-extent-property ovl 'end-glyph gl))
4809 (overlay-put ovl 'display text)
4810 (if face (overlay-put ovl 'face face))
4811 (if evap (overlay-put ovl 'evaporate t))))
4812 (defun org-overlay-before-string (ovl text &optional face evap)
4813 "Make overlay OVL display TEXT with face FACE."
4814 (if (featurep 'xemacs)
4815 (let ((gl (make-glyph text)))
4816 (and face (set-glyph-face gl face))
4817 (set-extent-property ovl 'begin-glyph gl))
4818 (if face (org-add-props text nil 'face face))
4819 (overlay-put ovl 'before-string text)
4820 (if evap (overlay-put ovl 'evaporate t))))
4821 (defun org-overlay-get (ovl prop)
4822 (if (featurep 'xemacs)
4823 (extent-property ovl prop)
4824 (overlay-get ovl prop)))
4825 (defun org-overlays-at (pos)
4826 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4827 (defun org-overlays-in (&optional start end)
4828 (if (featurep 'xemacs)
4829 (extent-list nil start end)
4830 (overlays-in start end)))
4831 (defun org-overlay-start (o)
4832 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4833 (defun org-overlay-end (o)
4834 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4835 (defun org-find-overlays (prop &optional pos delete)
4836 "Find all overlays specifying PROP at POS or point.
4837 If DELETE is non-nil, delete all those overlays."
4838 (let ((overlays (org-overlays-at (or pos (point))))
4839 ov found)
4840 (while (setq ov (pop overlays))
4841 (if (org-overlay-get ov prop)
4842 (if delete (org-delete-overlay ov) (push ov found))))
4843 found))
4845 ;; Region compatibility
4847 (defun org-add-hook (hook function &optional append local)
4848 "Add-hook, compatible with both Emacsen."
4849 (if (and local (featurep 'xemacs))
4850 (add-local-hook hook function append)
4851 (add-hook hook function append local)))
4853 (defvar org-ignore-region nil
4854 "To temporarily disable the active region.")
4856 (defun org-region-active-p ()
4857 "Is `transient-mark-mode' on and the region active?
4858 Works on both Emacs and XEmacs."
4859 (if org-ignore-region
4861 (if (featurep 'xemacs)
4862 (and zmacs-regions (region-active-p))
4863 (if (fboundp 'use-region-p)
4864 (use-region-p)
4865 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4867 ;; Invisibility compatibility
4869 (defun org-add-to-invisibility-spec (arg)
4870 "Add elements to `buffer-invisibility-spec'.
4871 See documentation for `buffer-invisibility-spec' for the kind of elements
4872 that can be added."
4873 (cond
4874 ((fboundp 'add-to-invisibility-spec)
4875 (add-to-invisibility-spec arg))
4876 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4877 (setq buffer-invisibility-spec (list arg)))
4879 (setq buffer-invisibility-spec
4880 (cons arg buffer-invisibility-spec)))))
4882 (defun org-remove-from-invisibility-spec (arg)
4883 "Remove elements from `buffer-invisibility-spec'."
4884 (if (fboundp 'remove-from-invisibility-spec)
4885 (remove-from-invisibility-spec arg)
4886 (if (consp buffer-invisibility-spec)
4887 (setq buffer-invisibility-spec
4888 (delete arg buffer-invisibility-spec)))))
4890 (defun org-in-invisibility-spec-p (arg)
4891 "Is ARG a member of `buffer-invisibility-spec'?"
4892 (if (consp buffer-invisibility-spec)
4893 (member arg buffer-invisibility-spec)
4894 nil))
4896 ;;;; Define the Org-mode
4898 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4899 (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."))
4902 ;; We use a before-change function to check if a table might need
4903 ;; an update.
4904 (defvar org-table-may-need-update t
4905 "Indicates that a table might need an update.
4906 This variable is set by `org-before-change-function'.
4907 `org-table-align' sets it back to nil.")
4908 (defvar org-mode-map)
4909 (defvar org-mode-hook nil)
4910 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4911 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4912 (defvar org-table-buffer-is-an nil)
4913 (defconst org-outline-regexp "\\*+ ")
4915 ;;;###autoload
4916 (define-derived-mode org-mode outline-mode "Org"
4917 "Outline-based notes management and organizer, alias
4918 \"Carsten's outline-mode for keeping track of everything.\"
4920 Org-mode develops organizational tasks around a NOTES file which
4921 contains information about projects as plain text. Org-mode is
4922 implemented on top of outline-mode, which is ideal to keep the content
4923 of large files well structured. It supports ToDo items, deadlines and
4924 time stamps, which magically appear in the diary listing of the Emacs
4925 calendar. Tables are easily created with a built-in table editor.
4926 Plain text URL-like links connect to websites, emails (VM), Usenet
4927 messages (Gnus), BBDB entries, and any files related to the project.
4928 For printing and sharing of notes, an Org-mode file (or a part of it)
4929 can be exported as a structured ASCII or HTML file.
4931 The following commands are available:
4933 \\{org-mode-map}"
4935 ;; Get rid of Outline menus, they are not needed
4936 ;; Need to do this here because define-derived-mode sets up
4937 ;; the keymap so late. Still, it is a waste to call this each time
4938 ;; we switch another buffer into org-mode.
4939 (if (featurep 'xemacs)
4940 (when (boundp 'outline-mode-menu-heading)
4941 ;; Assume this is Greg's port, it used easymenu
4942 (easy-menu-remove outline-mode-menu-heading)
4943 (easy-menu-remove outline-mode-menu-show)
4944 (easy-menu-remove outline-mode-menu-hide))
4945 (define-key org-mode-map [menu-bar headings] 'undefined)
4946 (define-key org-mode-map [menu-bar hide] 'undefined)
4947 (define-key org-mode-map [menu-bar show] 'undefined))
4949 (easy-menu-add org-org-menu)
4950 (easy-menu-add org-tbl-menu)
4951 (org-install-agenda-files-menu)
4952 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4953 (org-add-to-invisibility-spec '(org-cwidth))
4954 (when (featurep 'xemacs)
4955 (org-set-local 'line-move-ignore-invisible t))
4956 (org-set-local 'outline-regexp org-outline-regexp)
4957 (org-set-local 'outline-level 'org-outline-level)
4958 (when (and org-ellipsis
4959 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4960 (fboundp 'make-glyph-code))
4961 (unless org-display-table
4962 (setq org-display-table (make-display-table)))
4963 (set-display-table-slot
4964 org-display-table 4
4965 (vconcat (mapcar
4966 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4967 org-ellipsis)))
4968 (if (stringp org-ellipsis) org-ellipsis "..."))))
4969 (setq buffer-display-table org-display-table))
4970 (org-set-regexps-and-options)
4971 ;; Calc embedded
4972 (org-set-local 'calc-embedded-open-mode "# ")
4973 (modify-syntax-entry ?# "<")
4974 (modify-syntax-entry ?@ "w")
4975 (if org-startup-truncated (setq truncate-lines t))
4976 (org-set-local 'font-lock-unfontify-region-function
4977 'org-unfontify-region)
4978 ;; Activate before-change-function
4979 (org-set-local 'org-table-may-need-update t)
4980 (org-add-hook 'before-change-functions 'org-before-change-function nil
4981 'local)
4982 ;; Check for running clock before killing a buffer
4983 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4984 ;; Paragraphs and auto-filling
4985 (org-set-autofill-regexps)
4986 (setq indent-line-function 'org-indent-line-function)
4987 (org-update-radio-target-regexp)
4989 ;; Comment characters
4990 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4991 (org-set-local 'comment-padding " ")
4993 ;; Align options lines
4994 (org-set-local
4995 'align-mode-rules-list
4996 '((org-in-buffer-settings
4997 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4998 (modes . '(org-mode)))))
5000 ;; Imenu
5001 (org-set-local 'imenu-create-index-function
5002 'org-imenu-get-tree)
5004 ;; Make isearch reveal context
5005 (if (or (featurep 'xemacs)
5006 (not (boundp 'outline-isearch-open-invisible-function)))
5007 ;; Emacs 21 and XEmacs make use of the hook
5008 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5009 ;; Emacs 22 deals with this through a special variable
5010 (org-set-local 'outline-isearch-open-invisible-function
5011 (lambda (&rest ignore) (org-show-context 'isearch))))
5013 ;; If empty file that did not turn on org-mode automatically, make it to.
5014 (if (and org-insert-mode-line-in-empty-file
5015 (interactive-p)
5016 (= (point-min) (point-max)))
5017 (insert "# -*- mode: org -*-\n\n"))
5019 (unless org-inhibit-startup
5020 (when org-startup-align-all-tables
5021 (let ((bmp (buffer-modified-p)))
5022 (org-table-map-tables 'org-table-align)
5023 (set-buffer-modified-p bmp)))
5024 (org-cycle-hide-drawers 'all)
5025 (cond
5026 ((eq org-startup-folded t)
5027 (org-cycle '(4)))
5028 ((eq org-startup-folded 'content)
5029 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5030 (org-cycle '(4)) (org-cycle '(4)))))))
5032 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5034 (defsubst org-call-with-arg (command arg)
5035 "Call COMMAND interactively, but pretend prefix are was ARG."
5036 (let ((current-prefix-arg arg)) (call-interactively command)))
5038 (defsubst org-current-line (&optional pos)
5039 (save-excursion
5040 (and pos (goto-char pos))
5041 ;; works also in narrowed buffer, because we start at 1, not point-min
5042 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5044 (defun org-current-time ()
5045 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5046 (if (> org-time-stamp-rounding-minutes 0)
5047 (let ((r org-time-stamp-rounding-minutes)
5048 (time (decode-time)))
5049 (apply 'encode-time
5050 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5051 (nthcdr 2 time))))
5052 (current-time)))
5054 (defun org-add-props (string plist &rest props)
5055 "Add text properties to entire string, from beginning to end.
5056 PLIST may be a list of properties, PROPS are individual properties and values
5057 that will be added to PLIST. Returns the string that was modified."
5058 (add-text-properties
5059 0 (length string) (if props (append plist props) plist) string)
5060 string)
5061 (put 'org-add-props 'lisp-indent-function 2)
5064 ;;;; Font-Lock stuff, including the activators
5066 (defvar org-mouse-map (make-sparse-keymap))
5067 (org-defkey org-mouse-map
5068 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5069 (org-defkey org-mouse-map
5070 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5071 (when org-mouse-1-follows-link
5072 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5073 (when org-tab-follows-link
5074 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5075 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5076 (when org-return-follows-link
5077 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5078 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5080 (require 'font-lock)
5082 (defconst org-non-link-chars "]\t\n\r<>")
5083 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5084 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5085 (defvar org-link-re-with-space nil
5086 "Matches a link with spaces, optional angular brackets around it.")
5087 (defvar org-link-re-with-space2 nil
5088 "Matches a link with spaces, optional angular brackets around it.")
5089 (defvar org-angle-link-re nil
5090 "Matches link with angular brackets, spaces are allowed.")
5091 (defvar org-plain-link-re nil
5092 "Matches plain link, without spaces.")
5093 (defvar org-bracket-link-regexp nil
5094 "Matches a link in double brackets.")
5095 (defvar org-bracket-link-analytic-regexp nil
5096 "Regular expression used to analyze links.
5097 Here is what the match groups contain after a match:
5098 1: http:
5099 2: http
5100 3: path
5101 4: [desc]
5102 5: desc")
5103 (defvar org-any-link-re nil
5104 "Regular expression matching any link.")
5106 (defun org-make-link-regexps ()
5107 "Update the link regular expressions.
5108 This should be called after the variable `org-link-types' has changed."
5109 (setq org-link-re-with-space
5110 (concat
5111 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5112 "\\([^" org-non-link-chars " ]"
5113 "[^" org-non-link-chars "]*"
5114 "[^" org-non-link-chars " ]\\)>?")
5115 org-link-re-with-space2
5116 (concat
5117 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5118 "\\([^" org-non-link-chars " ]"
5119 "[^]\t\n\r]*"
5120 "[^" org-non-link-chars " ]\\)>?")
5121 org-angle-link-re
5122 (concat
5123 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5124 "\\([^" org-non-link-chars " ]"
5125 "[^" org-non-link-chars "]*"
5126 "\\)>")
5127 org-plain-link-re
5128 (concat
5129 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5130 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5131 org-bracket-link-regexp
5132 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5133 org-bracket-link-analytic-regexp
5134 (concat
5135 "\\[\\["
5136 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5137 "\\([^]]+\\)"
5138 "\\]"
5139 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5140 "\\]")
5141 org-any-link-re
5142 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5143 org-angle-link-re "\\)\\|\\("
5144 org-plain-link-re "\\)")))
5146 (org-make-link-regexps)
5148 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5149 "Regular expression for fast time stamp matching.")
5150 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5151 "Regular expression for fast time stamp matching.")
5152 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5153 "Regular expression matching time strings for analysis.
5154 This one does not require the space after the date.")
5155 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5156 "Regular expression matching time strings for analysis.")
5157 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5158 "Regular expression matching time stamps, with groups.")
5159 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5160 "Regular expression matching time stamps (also [..]), with groups.")
5161 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5162 "Regular expression matching a time stamp range.")
5163 (defconst org-tr-regexp-both
5164 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5165 "Regular expression matching a time stamp range.")
5166 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5167 org-ts-regexp "\\)?")
5168 "Regular expression matching a time stamp or time stamp range.")
5169 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5170 org-ts-regexp-both "\\)?")
5171 "Regular expression matching a time stamp or time stamp range.
5172 The time stamps may be either active or inactive.")
5174 (defvar org-emph-face nil)
5176 (defun org-do-emphasis-faces (limit)
5177 "Run through the buffer and add overlays to links."
5178 (let (rtn)
5179 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5180 (if (not (= (char-after (match-beginning 3))
5181 (char-after (match-beginning 4))))
5182 (progn
5183 (setq rtn t)
5184 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5185 'face
5186 (nth 1 (assoc (match-string 3)
5187 org-emphasis-alist)))
5188 (add-text-properties (match-beginning 2) (match-end 2)
5189 '(font-lock-multiline t))
5190 (when org-hide-emphasis-markers
5191 (add-text-properties (match-end 4) (match-beginning 5)
5192 '(invisible org-link))
5193 (add-text-properties (match-beginning 3) (match-end 3)
5194 '(invisible org-link)))))
5195 (backward-char 1))
5196 rtn))
5198 (defun org-emphasize (&optional char)
5199 "Insert or change an emphasis, i.e. a font like bold or italic.
5200 If there is an active region, change that region to a new emphasis.
5201 If there is no region, just insert the marker characters and position
5202 the cursor between them.
5203 CHAR should be either the marker character, or the first character of the
5204 HTML tag associated with that emphasis. If CHAR is a space, the means
5205 to remove the emphasis of the selected region.
5206 If char is not given (for example in an interactive call) it
5207 will be prompted for."
5208 (interactive)
5209 (let ((eal org-emphasis-alist) e det
5210 (erc org-emphasis-regexp-components)
5211 (prompt "")
5212 (string "") beg end move tag c s)
5213 (if (org-region-active-p)
5214 (setq beg (region-beginning) end (region-end)
5215 string (buffer-substring beg end))
5216 (setq move t))
5218 (while (setq e (pop eal))
5219 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5220 c (aref tag 0))
5221 (push (cons c (string-to-char (car e))) det)
5222 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5223 (substring tag 1)))))
5224 (unless char
5225 (message "%s" (concat "Emphasis marker or tag:" prompt))
5226 (setq char (read-char-exclusive)))
5227 (setq char (or (cdr (assoc char det)) char))
5228 (if (equal char ?\ )
5229 (setq s "" move nil)
5230 (unless (assoc (char-to-string char) org-emphasis-alist)
5231 (error "No such emphasis marker: \"%c\"" char))
5232 (setq s (char-to-string char)))
5233 (while (and (> (length string) 1)
5234 (equal (substring string 0 1) (substring string -1))
5235 (assoc (substring string 0 1) org-emphasis-alist))
5236 (setq string (substring string 1 -1)))
5237 (setq string (concat s string s))
5238 (if beg (delete-region beg end))
5239 (unless (or (bolp)
5240 (string-match (concat "[" (nth 0 erc) "\n]")
5241 (char-to-string (char-before (point)))))
5242 (insert " "))
5243 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5244 (char-to-string (char-after (point))))
5245 (insert " ") (backward-char 1))
5246 (insert string)
5247 (and move (backward-char 1))))
5249 (defconst org-nonsticky-props
5250 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5253 (defun org-activate-plain-links (limit)
5254 "Run through the buffer and add overlays to links."
5255 (catch 'exit
5256 (let (f)
5257 (while (re-search-forward org-plain-link-re limit t)
5258 (setq f (get-text-property (match-beginning 0) 'face))
5259 (if (or (eq f 'org-tag)
5260 (and (listp f) (memq 'org-tag f)))
5262 (add-text-properties (match-beginning 0) (match-end 0)
5263 (list 'mouse-face 'highlight
5264 'rear-nonsticky org-nonsticky-props
5265 'keymap org-mouse-map
5267 (throw 'exit t))))))
5269 (defun org-activate-code (limit)
5270 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5271 (unless (get-text-property (match-beginning 1) 'face)
5272 (remove-text-properties (match-beginning 0) (match-end 0)
5273 '(display t invisible t intangible t))
5274 t)))
5276 (defun org-activate-angle-links (limit)
5277 "Run through the buffer and add overlays to links."
5278 (if (re-search-forward org-angle-link-re limit t)
5279 (progn
5280 (add-text-properties (match-beginning 0) (match-end 0)
5281 (list 'mouse-face 'highlight
5282 'rear-nonsticky org-nonsticky-props
5283 'keymap org-mouse-map
5285 t)))
5287 (defmacro org-maybe-intangible (props)
5288 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5289 In emacs 21, invisible text is not avoided by the command loop, so the
5290 intangible property is needed to make sure point skips this text.
5291 In Emacs 22, this is not necessary. The intangible text property has
5292 led to problems with flyspell. These problems are fixed in flyspell.el,
5293 but we still avoid setting the property in Emacs 22 and later.
5294 We use a macro so that the test can happen at compilation time."
5295 (if (< emacs-major-version 22)
5296 `(append '(intangible t) ,props)
5297 props))
5299 (defun org-activate-bracket-links (limit)
5300 "Run through the buffer and add overlays to bracketed links."
5301 (if (re-search-forward org-bracket-link-regexp limit t)
5302 (let* ((help (concat "LINK: "
5303 (org-match-string-no-properties 1)))
5304 ;; FIXME: above we should remove the escapes.
5305 ;; but that requires another match, protecting match data,
5306 ;; a lot of overhead for font-lock.
5307 (ip (org-maybe-intangible
5308 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5309 'keymap org-mouse-map 'mouse-face 'highlight
5310 'font-lock-multiline t 'help-echo help)))
5311 (vp (list 'rear-nonsticky org-nonsticky-props
5312 'keymap org-mouse-map 'mouse-face 'highlight
5313 ' font-lock-multiline t 'help-echo help)))
5314 ;; We need to remove the invisible property here. Table narrowing
5315 ;; may have made some of this invisible.
5316 (remove-text-properties (match-beginning 0) (match-end 0)
5317 '(invisible nil))
5318 (if (match-end 3)
5319 (progn
5320 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5321 (add-text-properties (match-beginning 3) (match-end 3) vp)
5322 (add-text-properties (match-end 3) (match-end 0) ip))
5323 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5324 (add-text-properties (match-beginning 1) (match-end 1) vp)
5325 (add-text-properties (match-end 1) (match-end 0) ip))
5326 t)))
5328 (defun org-activate-dates (limit)
5329 "Run through the buffer and add overlays to dates."
5330 (if (re-search-forward org-tsr-regexp-both limit t)
5331 (progn
5332 (add-text-properties (match-beginning 0) (match-end 0)
5333 (list 'mouse-face 'highlight
5334 'rear-nonsticky org-nonsticky-props
5335 'keymap org-mouse-map))
5336 (when org-display-custom-times
5337 (if (match-end 3)
5338 (org-display-custom-time (match-beginning 3) (match-end 3)))
5339 (org-display-custom-time (match-beginning 1) (match-end 1)))
5340 t)))
5342 (defvar org-target-link-regexp nil
5343 "Regular expression matching radio targets in plain text.")
5344 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5345 "Regular expression matching a link target.")
5346 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5347 "Regular expression matching a radio target.")
5348 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5349 "Regular expression matching any target.")
5351 (defun org-activate-target-links (limit)
5352 "Run through the buffer and add overlays to target matches."
5353 (when org-target-link-regexp
5354 (let ((case-fold-search t))
5355 (if (re-search-forward org-target-link-regexp limit t)
5356 (progn
5357 (add-text-properties (match-beginning 0) (match-end 0)
5358 (list 'mouse-face 'highlight
5359 'rear-nonsticky org-nonsticky-props
5360 'keymap org-mouse-map
5361 'help-echo "Radio target link"
5362 'org-linked-text t))
5363 t)))))
5365 (defun org-update-radio-target-regexp ()
5366 "Find all radio targets in this file and update the regular expression."
5367 (interactive)
5368 (when (memq 'radio org-activate-links)
5369 (setq org-target-link-regexp
5370 (org-make-target-link-regexp (org-all-targets 'radio)))
5371 (org-restart-font-lock)))
5373 (defun org-hide-wide-columns (limit)
5374 (let (s e)
5375 (setq s (text-property-any (point) (or limit (point-max))
5376 'org-cwidth t))
5377 (when s
5378 (setq e (next-single-property-change s 'org-cwidth))
5379 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5380 (goto-char e)
5381 t)))
5383 (defvar org-latex-and-specials-regexp nil
5384 "Regular expression for highlighting export special stuff.")
5385 (defvar org-match-substring-regexp)
5386 (defvar org-match-substring-with-braces-regexp)
5387 (defvar org-export-html-special-string-regexps)
5389 (defun org-compute-latex-and-specials-regexp ()
5390 "Compute regular expression for stuff treated specially by exporters."
5391 (if (not org-highlight-latex-fragments-and-specials)
5392 (org-set-local 'org-latex-and-specials-regexp nil)
5393 (let*
5394 ((matchers (plist-get org-format-latex-options :matchers))
5395 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5396 org-latex-regexps)))
5397 (options (org-combine-plists (org-default-export-plist)
5398 (org-infile-export-plist)))
5399 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5400 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5401 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5402 (org-export-html-expand (plist-get options :expand-quoted-html))
5403 (org-export-with-special-strings (plist-get options :special-strings))
5404 (re-sub
5405 (cond
5406 ((equal org-export-with-sub-superscripts '{})
5407 (list org-match-substring-with-braces-regexp))
5408 (org-export-with-sub-superscripts
5409 (list org-match-substring-regexp))
5410 (t nil)))
5411 (re-latex
5412 (if org-export-with-LaTeX-fragments
5413 (mapcar (lambda (x) (nth 1 x)) latexs)))
5414 (re-macros
5415 (if org-export-with-TeX-macros
5416 (list (concat "\\\\"
5417 (regexp-opt
5418 (append (mapcar 'car org-html-entities)
5419 (if (boundp 'org-latex-entities)
5420 org-latex-entities nil))
5421 'words))) ; FIXME
5423 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5424 (re-special (if org-export-with-special-strings
5425 (mapcar (lambda (x) (car x))
5426 org-export-html-special-string-regexps)))
5427 (re-rest
5428 (delq nil
5429 (list
5430 (if org-export-html-expand "@<[^>\n]+>")
5431 ))))
5432 (org-set-local
5433 'org-latex-and-specials-regexp
5434 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5435 re-rest) "\\|")))))
5437 (defface org-latex-and-export-specials
5438 (let ((font (cond ((assq :inherit custom-face-attributes)
5439 '(:inherit underline))
5440 (t '(:underline t)))))
5441 `((((class grayscale) (background light))
5442 (:foreground "DimGray" ,@font))
5443 (((class grayscale) (background dark))
5444 (:foreground "LightGray" ,@font))
5445 (((class color) (background light))
5446 (:foreground "SaddleBrown"))
5447 (((class color) (background dark))
5448 (:foreground "burlywood"))
5449 (t (,@font))))
5450 "Face used to highlight math latex and other special exporter stuff."
5451 :group 'org-faces)
5453 (defun org-do-latex-and-special-faces (limit)
5454 "Run through the buffer and add overlays to links."
5455 (when org-latex-and-specials-regexp
5456 (let (rtn d)
5457 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5458 limit t))
5459 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5460 'face))
5461 '(org-code org-verbatim underline)))
5462 (progn
5463 (setq rtn t
5464 d (cond ((member (char-after (1+ (match-beginning 0)))
5465 '(?_ ?^)) 1)
5466 (t 0)))
5467 (font-lock-prepend-text-property
5468 (+ d (match-beginning 0)) (match-end 0)
5469 'face 'org-latex-and-export-specials)
5470 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5471 '(font-lock-multiline t)))))
5472 rtn)))
5474 (defun org-restart-font-lock ()
5475 "Restart font-lock-mode, to force refontification."
5476 (when (and (boundp 'font-lock-mode) font-lock-mode)
5477 (font-lock-mode -1)
5478 (font-lock-mode 1)))
5480 (defun org-all-targets (&optional radio)
5481 "Return a list of all targets in this file.
5482 With optional argument RADIO, only find radio targets."
5483 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5484 rtn)
5485 (save-excursion
5486 (goto-char (point-min))
5487 (while (re-search-forward re nil t)
5488 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5489 rtn)))
5491 (defun org-make-target-link-regexp (targets)
5492 "Make regular expression matching all strings in TARGETS.
5493 The regular expression finds the targets also if there is a line break
5494 between words."
5495 (and targets
5496 (concat
5497 "\\<\\("
5498 (mapconcat
5499 (lambda (x)
5500 (while (string-match " +" x)
5501 (setq x (replace-match "\\s-+" t t x)))
5503 targets
5504 "\\|")
5505 "\\)\\>")))
5507 (defun org-activate-tags (limit)
5508 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5509 (progn
5510 (add-text-properties (match-beginning 1) (match-end 1)
5511 (list 'mouse-face 'highlight
5512 'rear-nonsticky org-nonsticky-props
5513 'keymap org-mouse-map))
5514 t)))
5516 (defun org-outline-level ()
5517 (save-excursion
5518 (looking-at outline-regexp)
5519 (if (match-beginning 1)
5520 (+ (org-get-string-indentation (match-string 1)) 1000)
5521 (1- (- (match-end 0) (match-beginning 0))))))
5523 (defvar org-font-lock-keywords nil)
5525 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5526 "Regular expression matching a property line.")
5528 (defun org-set-font-lock-defaults ()
5529 (let* ((em org-fontify-emphasized-text)
5530 (lk org-activate-links)
5531 (org-font-lock-extra-keywords
5532 (list
5533 ;; Headlines
5534 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5535 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5536 ;; Table lines
5537 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5538 (1 'org-table t))
5539 ;; Table internals
5540 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5541 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5542 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5543 ;; Drawers
5544 (list org-drawer-regexp '(0 'org-special-keyword t))
5545 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5546 ;; Properties
5547 (list org-property-re
5548 '(1 'org-special-keyword t)
5549 '(3 'org-property-value t))
5550 (if org-format-transports-properties-p
5551 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5552 ;; Links
5553 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5554 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5555 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5556 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5557 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5558 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5559 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5560 '(org-hide-wide-columns (0 nil append))
5561 ;; TODO lines
5562 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5563 '(1 (org-get-todo-face 1) t))
5564 ;; DONE
5565 (if org-fontify-done-headline
5566 (list (concat "^[*]+ +\\<\\("
5567 (mapconcat 'regexp-quote org-done-keywords "\\|")
5568 "\\)\\(.*\\)")
5569 '(2 'org-headline-done t))
5570 nil)
5571 ;; Priorities
5572 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5573 ;; Special keywords
5574 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5575 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5576 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5577 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5578 ;; Emphasis
5579 (if em
5580 (if (featurep 'xemacs)
5581 '(org-do-emphasis-faces (0 nil append))
5582 '(org-do-emphasis-faces)))
5583 ;; Checkboxes
5584 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5585 2 'bold prepend)
5586 (if org-provide-checkbox-statistics
5587 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5588 (0 (org-get-checkbox-statistics-face) t)))
5589 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5590 '(1 'org-archived prepend))
5591 ;; Specials
5592 '(org-do-latex-and-special-faces)
5593 ;; Code
5594 '(org-activate-code (1 'org-code t))
5595 ;; COMMENT
5596 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5597 "\\|" org-quote-string "\\)\\>")
5598 '(1 'org-special-keyword t))
5599 '("^#.*" (0 'font-lock-comment-face t))
5601 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5602 ;; Now set the full font-lock-keywords
5603 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5604 (org-set-local 'font-lock-defaults
5605 '(org-font-lock-keywords t nil nil backward-paragraph))
5606 (kill-local-variable 'font-lock-keywords) nil))
5608 (defvar org-m nil)
5609 (defvar org-l nil)
5610 (defvar org-f nil)
5611 (defun org-get-level-face (n)
5612 "Get the right face for match N in font-lock matching of healdines."
5613 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5614 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5615 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5616 (cond
5617 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5618 ((eq n 2) org-f)
5619 (t (if org-level-color-stars-only nil org-f))))
5621 (defun org-get-todo-face (kwd)
5622 "Get the right face for a TODO keyword KWD.
5623 If KWD is a number, get the corresponding match group."
5624 (if (numberp kwd) (setq kwd (match-string kwd)))
5625 (or (cdr (assoc kwd org-todo-keyword-faces))
5626 (and (member kwd org-done-keywords) 'org-done)
5627 'org-todo))
5629 (defun org-unfontify-region (beg end &optional maybe_loudly)
5630 "Remove fontification and activation overlays from links."
5631 (font-lock-default-unfontify-region beg end)
5632 (let* ((buffer-undo-list t)
5633 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5634 (inhibit-modification-hooks t)
5635 deactivate-mark buffer-file-name buffer-file-truename)
5636 (remove-text-properties beg end
5637 '(mouse-face t keymap t org-linked-text t
5638 invisible t intangible t))))
5640 ;;;; Visibility cycling, including org-goto and indirect buffer
5642 ;;; Cycling
5644 (defvar org-cycle-global-status nil)
5645 (make-variable-buffer-local 'org-cycle-global-status)
5646 (defvar org-cycle-subtree-status nil)
5647 (make-variable-buffer-local 'org-cycle-subtree-status)
5649 ;;;###autoload
5650 (defun org-cycle (&optional arg)
5651 "Visibility cycling for Org-mode.
5653 - When this function is called with a prefix argument, rotate the entire
5654 buffer through 3 states (global cycling)
5655 1. OVERVIEW: Show only top-level headlines.
5656 2. CONTENTS: Show all headlines of all levels, but no body text.
5657 3. SHOW ALL: Show everything.
5659 - When point is at the beginning of a headline, rotate the subtree started
5660 by this line through 3 different states (local cycling)
5661 1. FOLDED: Only the main headline is shown.
5662 2. CHILDREN: The main headline and the direct children are shown.
5663 From this state, you can move to one of the children
5664 and zoom in further.
5665 3. SUBTREE: Show the entire subtree, including body text.
5667 - When there is a numeric prefix, go up to a heading with level ARG, do
5668 a `show-subtree' and return to the previous cursor position. If ARG
5669 is negative, go up that many levels.
5671 - When point is not at the beginning of a headline, execute
5672 `indent-relative', like TAB normally does. See the option
5673 `org-cycle-emulate-tab' for details.
5675 - Special case: if point is at the beginning of the buffer and there is
5676 no headline in line 1, this function will act as if called with prefix arg.
5677 But only if also the variable `org-cycle-global-at-bob' is t."
5678 (interactive "P")
5679 (let* ((outline-regexp
5680 (if (and (org-mode-p) org-cycle-include-plain-lists)
5681 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5682 outline-regexp))
5683 (bob-special (and org-cycle-global-at-bob (bobp)
5684 (not (looking-at outline-regexp))))
5685 (org-cycle-hook
5686 (if bob-special
5687 (delq 'org-optimize-window-after-visibility-change
5688 (copy-sequence org-cycle-hook))
5689 org-cycle-hook))
5690 (pos (point)))
5692 (if (or bob-special (equal arg '(4)))
5693 ;; special case: use global cycling
5694 (setq arg t))
5696 (cond
5698 ((org-at-table-p 'any)
5699 ;; Enter the table or move to the next field in the table
5700 (or (org-table-recognize-table.el)
5701 (progn
5702 (if arg (org-table-edit-field t)
5703 (org-table-justify-field-maybe)
5704 (call-interactively 'org-table-next-field)))))
5706 ((eq arg t) ;; Global cycling
5708 (cond
5709 ((and (eq last-command this-command)
5710 (eq org-cycle-global-status 'overview))
5711 ;; We just created the overview - now do table of contents
5712 ;; This can be slow in very large buffers, so indicate action
5713 (message "CONTENTS...")
5714 (org-content)
5715 (message "CONTENTS...done")
5716 (setq org-cycle-global-status 'contents)
5717 (run-hook-with-args 'org-cycle-hook 'contents))
5719 ((and (eq last-command this-command)
5720 (eq org-cycle-global-status 'contents))
5721 ;; We just showed the table of contents - now show everything
5722 (show-all)
5723 (message "SHOW ALL")
5724 (setq org-cycle-global-status 'all)
5725 (run-hook-with-args 'org-cycle-hook 'all))
5728 ;; Default action: go to overview
5729 (org-overview)
5730 (message "OVERVIEW")
5731 (setq org-cycle-global-status 'overview)
5732 (run-hook-with-args 'org-cycle-hook 'overview))))
5734 ((and org-drawers org-drawer-regexp
5735 (save-excursion
5736 (beginning-of-line 1)
5737 (looking-at org-drawer-regexp)))
5738 ;; Toggle block visibility
5739 (org-flag-drawer
5740 (not (get-char-property (match-end 0) 'invisible))))
5742 ((integerp arg)
5743 ;; Show-subtree, ARG levels up from here.
5744 (save-excursion
5745 (org-back-to-heading)
5746 (outline-up-heading (if (< arg 0) (- arg)
5747 (- (funcall outline-level) arg)))
5748 (org-show-subtree)))
5750 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5751 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5752 ;; At a heading: rotate between three different views
5753 (org-back-to-heading)
5754 (let ((goal-column 0) eoh eol eos)
5755 ;; First, some boundaries
5756 (save-excursion
5757 (org-back-to-heading)
5758 (save-excursion
5759 (beginning-of-line 2)
5760 (while (and (not (eobp)) ;; this is like `next-line'
5761 (get-char-property (1- (point)) 'invisible))
5762 (beginning-of-line 2)) (setq eol (point)))
5763 (outline-end-of-heading) (setq eoh (point))
5764 (org-end-of-subtree t)
5765 (unless (eobp)
5766 (skip-chars-forward " \t\n")
5767 (beginning-of-line 1) ; in case this is an item
5769 (setq eos (1- (point))))
5770 ;; Find out what to do next and set `this-command'
5771 (cond
5772 ((= eos eoh)
5773 ;; Nothing is hidden behind this heading
5774 (message "EMPTY ENTRY")
5775 (setq org-cycle-subtree-status nil)
5776 (save-excursion
5777 (goto-char eos)
5778 (outline-next-heading)
5779 (if (org-invisible-p) (org-flag-heading nil))))
5780 ((or (>= eol eos)
5781 (not (string-match "\\S-" (buffer-substring eol eos))))
5782 ;; Entire subtree is hidden in one line: open it
5783 (org-show-entry)
5784 (show-children)
5785 (message "CHILDREN")
5786 (save-excursion
5787 (goto-char eos)
5788 (outline-next-heading)
5789 (if (org-invisible-p) (org-flag-heading nil)))
5790 (setq org-cycle-subtree-status 'children)
5791 (run-hook-with-args 'org-cycle-hook 'children))
5792 ((and (eq last-command this-command)
5793 (eq org-cycle-subtree-status 'children))
5794 ;; We just showed the children, now show everything.
5795 (org-show-subtree)
5796 (message "SUBTREE")
5797 (setq org-cycle-subtree-status 'subtree)
5798 (run-hook-with-args 'org-cycle-hook 'subtree))
5800 ;; Default action: hide the subtree.
5801 (hide-subtree)
5802 (message "FOLDED")
5803 (setq org-cycle-subtree-status 'folded)
5804 (run-hook-with-args 'org-cycle-hook 'folded)))))
5806 ;; TAB emulation
5807 (buffer-read-only (org-back-to-heading))
5809 ((org-try-cdlatex-tab))
5811 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5812 (or (not (bolp))
5813 (not (looking-at outline-regexp))))
5814 (call-interactively (global-key-binding "\t")))
5816 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5817 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5818 (or (and (eq org-cycle-emulate-tab 'white)
5819 (= (match-end 0) (point-at-eol)))
5820 (and (eq org-cycle-emulate-tab 'whitestart)
5821 (>= (match-end 0) pos))))
5823 (eq org-cycle-emulate-tab t))
5824 ; (if (and (looking-at "[ \n\r\t]")
5825 ; (string-match "^[ \t]*$" (buffer-substring
5826 ; (point-at-bol) (point))))
5827 ; (progn
5828 ; (beginning-of-line 1)
5829 ; (and (looking-at "[ \t]+") (replace-match ""))))
5830 (call-interactively (global-key-binding "\t")))
5832 (t (save-excursion
5833 (org-back-to-heading)
5834 (org-cycle))))))
5836 ;;;###autoload
5837 (defun org-global-cycle (&optional arg)
5838 "Cycle the global visibility. For details see `org-cycle'."
5839 (interactive "P")
5840 (let ((org-cycle-include-plain-lists
5841 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5842 (if (integerp arg)
5843 (progn
5844 (show-all)
5845 (hide-sublevels arg)
5846 (setq org-cycle-global-status 'contents))
5847 (org-cycle '(4)))))
5849 (defun org-overview ()
5850 "Switch to overview mode, shoing only top-level headlines.
5851 Really, this shows all headlines with level equal or greater than the level
5852 of the first headline in the buffer. This is important, because if the
5853 first headline is not level one, then (hide-sublevels 1) gives confusing
5854 results."
5855 (interactive)
5856 (let ((level (save-excursion
5857 (goto-char (point-min))
5858 (if (re-search-forward (concat "^" outline-regexp) nil t)
5859 (progn
5860 (goto-char (match-beginning 0))
5861 (funcall outline-level))))))
5862 (and level (hide-sublevels level))))
5864 (defun org-content (&optional arg)
5865 "Show all headlines in the buffer, like a table of contents.
5866 With numerical argument N, show content up to level N."
5867 (interactive "P")
5868 (save-excursion
5869 ;; Visit all headings and show their offspring
5870 (and (integerp arg) (org-overview))
5871 (goto-char (point-max))
5872 (catch 'exit
5873 (while (and (progn (condition-case nil
5874 (outline-previous-visible-heading 1)
5875 (error (goto-char (point-min))))
5877 (looking-at outline-regexp))
5878 (if (integerp arg)
5879 (show-children (1- arg))
5880 (show-branches))
5881 (if (bobp) (throw 'exit nil))))))
5884 (defun org-optimize-window-after-visibility-change (state)
5885 "Adjust the window after a change in outline visibility.
5886 This function is the default value of the hook `org-cycle-hook'."
5887 (when (get-buffer-window (current-buffer))
5888 (cond
5889 ; ((eq state 'overview) (org-first-headline-recenter 1))
5890 ; ((eq state 'overview) (org-beginning-of-line))
5891 ((eq state 'content) nil)
5892 ((eq state 'all) nil)
5893 ((eq state 'folded) nil)
5894 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5895 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5897 (defun org-compact-display-after-subtree-move ()
5898 (let (beg end)
5899 (save-excursion
5900 (if (org-up-heading-safe)
5901 (progn
5902 (hide-subtree)
5903 (show-entry)
5904 (show-children)
5905 (org-cycle-show-empty-lines 'children)
5906 (org-cycle-hide-drawers 'children))
5907 (org-overview)))))
5909 (defun org-cycle-show-empty-lines (state)
5910 "Show empty lines above all visible headlines.
5911 The region to be covered depends on STATE when called through
5912 `org-cycle-hook'. Lisp program can use t for STATE to get the
5913 entire buffer covered. Note that an empty line is only shown if there
5914 are at least `org-cycle-separator-lines' empty lines before the headeline."
5915 (when (> org-cycle-separator-lines 0)
5916 (save-excursion
5917 (let* ((n org-cycle-separator-lines)
5918 (re (cond
5919 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5920 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5921 (t (let ((ns (number-to-string (- n 2))))
5922 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5923 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5924 beg end)
5925 (cond
5926 ((memq state '(overview contents t))
5927 (setq beg (point-min) end (point-max)))
5928 ((memq state '(children folded))
5929 (setq beg (point) end (progn (org-end-of-subtree t t)
5930 (beginning-of-line 2)
5931 (point)))))
5932 (when beg
5933 (goto-char beg)
5934 (while (re-search-forward re end t)
5935 (if (not (get-char-property (match-end 1) 'invisible))
5936 (outline-flag-region
5937 (match-beginning 1) (match-end 1) nil)))))))
5938 ;; Never hide empty lines at the end of the file.
5939 (save-excursion
5940 (goto-char (point-max))
5941 (outline-previous-heading)
5942 (outline-end-of-heading)
5943 (if (and (looking-at "[ \t\n]+")
5944 (= (match-end 0) (point-max)))
5945 (outline-flag-region (point) (match-end 0) nil))))
5947 (defun org-subtree-end-visible-p ()
5948 "Is the end of the current subtree visible?"
5949 (pos-visible-in-window-p
5950 (save-excursion (org-end-of-subtree t) (point))))
5952 (defun org-first-headline-recenter (&optional N)
5953 "Move cursor to the first headline and recenter the headline.
5954 Optional argument N means, put the headline into the Nth line of the window."
5955 (goto-char (point-min))
5956 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5957 (beginning-of-line)
5958 (recenter (prefix-numeric-value N))))
5960 ;;; Org-goto
5962 (defvar org-goto-window-configuration nil)
5963 (defvar org-goto-marker nil)
5964 (defvar org-goto-map
5965 (let ((map (make-sparse-keymap)))
5966 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5967 (while (setq cmd (pop cmds))
5968 (substitute-key-definition cmd cmd map global-map)))
5969 (suppress-keymap map)
5970 (org-defkey map "\C-m" 'org-goto-ret)
5971 (org-defkey map [(return)] 'org-goto-ret)
5972 (org-defkey map [(left)] 'org-goto-left)
5973 (org-defkey map [(right)] 'org-goto-right)
5974 (org-defkey map [(control ?g)] 'org-goto-quit)
5975 (org-defkey map "\C-i" 'org-cycle)
5976 (org-defkey map [(tab)] 'org-cycle)
5977 (org-defkey map [(down)] 'outline-next-visible-heading)
5978 (org-defkey map [(up)] 'outline-previous-visible-heading)
5979 (if org-goto-auto-isearch
5980 (if (fboundp 'define-key-after)
5981 (define-key-after map [t] 'org-goto-local-auto-isearch)
5982 nil)
5983 (org-defkey map "q" 'org-goto-quit)
5984 (org-defkey map "n" 'outline-next-visible-heading)
5985 (org-defkey map "p" 'outline-previous-visible-heading)
5986 (org-defkey map "f" 'outline-forward-same-level)
5987 (org-defkey map "b" 'outline-backward-same-level)
5988 (org-defkey map "u" 'outline-up-heading))
5989 (org-defkey map "/" 'org-occur)
5990 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5991 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5992 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5993 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5994 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5995 map))
5997 (defconst org-goto-help
5998 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5999 RET=jump to location [Q]uit and return to previous location
6000 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6002 (defvar org-goto-start-pos) ; dynamically scoped parameter
6004 (defun org-goto (&optional alternative-interface)
6005 "Look up a different location in the current file, keeping current visibility.
6007 When you want look-up or go to a different location in a document, the
6008 fastest way is often to fold the entire buffer and then dive into the tree.
6009 This method has the disadvantage, that the previous location will be folded,
6010 which may not be what you want.
6012 This command works around this by showing a copy of the current buffer
6013 in an indirect buffer, in overview mode. You can dive into the tree in
6014 that copy, use org-occur and incremental search to find a location.
6015 When pressing RET or `Q', the command returns to the original buffer in
6016 which the visibility is still unchanged. After RET is will also jump to
6017 the location selected in the indirect buffer and expose the
6018 the headline hierarchy above."
6019 (interactive "P")
6020 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6021 (org-refile-use-outline-path t)
6022 (interface
6023 (if (not alternative-interface)
6024 org-goto-interface
6025 (if (eq org-goto-interface 'outline)
6026 'outline-path-completion
6027 'outline)))
6028 (org-goto-start-pos (point))
6029 (selected-point
6030 (if (eq interface 'outline)
6031 (car (org-get-location (current-buffer) org-goto-help))
6032 (nth 3 (org-refile-get-location "Goto: ")))))
6033 (if selected-point
6034 (progn
6035 (org-mark-ring-push org-goto-start-pos)
6036 (goto-char selected-point)
6037 (if (or (org-invisible-p) (org-invisible-p2))
6038 (org-show-context 'org-goto)))
6039 (message "Quit"))))
6041 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6042 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6043 (defvar org-goto-local-auto-isearch-map) ; defined below
6045 (defun org-get-location (buf help)
6046 "Let the user select a location in the Org-mode buffer BUF.
6047 This function uses a recursive edit. It returns the selected position
6048 or nil."
6049 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6050 (isearch-hide-immediately nil)
6051 (isearch-search-fun-function
6052 (lambda () 'org-goto-local-search-forward-headings))
6053 (org-goto-selected-point org-goto-exit-command))
6054 (save-excursion
6055 (save-window-excursion
6056 (delete-other-windows)
6057 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6058 (switch-to-buffer
6059 (condition-case nil
6060 (make-indirect-buffer (current-buffer) "*org-goto*")
6061 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6062 (with-output-to-temp-buffer "*Help*"
6063 (princ help))
6064 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6065 (setq buffer-read-only nil)
6066 (let ((org-startup-truncated t)
6067 (org-startup-folded nil)
6068 (org-startup-align-all-tables nil))
6069 (org-mode)
6070 (org-overview))
6071 (setq buffer-read-only t)
6072 (if (and (boundp 'org-goto-start-pos)
6073 (integer-or-marker-p org-goto-start-pos))
6074 (let ((org-show-hierarchy-above t)
6075 (org-show-siblings t)
6076 (org-show-following-heading t))
6077 (goto-char org-goto-start-pos)
6078 (and (org-invisible-p) (org-show-context)))
6079 (goto-char (point-min)))
6080 (org-beginning-of-line)
6081 (message "Select location and press RET")
6082 (use-local-map org-goto-map)
6083 (recursive-edit)
6085 (kill-buffer "*org-goto*")
6086 (cons org-goto-selected-point org-goto-exit-command)))
6088 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6089 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6090 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6091 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6093 (defun org-goto-local-search-forward-headings (string bound noerror)
6094 "Search and make sure that anu matches are in headlines."
6095 (catch 'return
6096 (while (search-forward string bound noerror)
6097 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6098 (and (member :headline context)
6099 (not (member :tags context))))
6100 (throw 'return (point))))))
6102 (defun org-goto-local-auto-isearch ()
6103 "Start isearch."
6104 (interactive)
6105 (goto-char (point-min))
6106 (let ((keys (this-command-keys)))
6107 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6108 (isearch-mode t)
6109 (isearch-process-search-char (string-to-char keys)))))
6111 (defun org-goto-ret (&optional arg)
6112 "Finish `org-goto' by going to the new location."
6113 (interactive "P")
6114 (setq org-goto-selected-point (point)
6115 org-goto-exit-command 'return)
6116 (throw 'exit nil))
6118 (defun org-goto-left ()
6119 "Finish `org-goto' by going to the new location."
6120 (interactive)
6121 (if (org-on-heading-p)
6122 (progn
6123 (beginning-of-line 1)
6124 (setq org-goto-selected-point (point)
6125 org-goto-exit-command 'left)
6126 (throw 'exit nil))
6127 (error "Not on a heading")))
6129 (defun org-goto-right ()
6130 "Finish `org-goto' by going to the new location."
6131 (interactive)
6132 (if (org-on-heading-p)
6133 (progn
6134 (setq org-goto-selected-point (point)
6135 org-goto-exit-command 'right)
6136 (throw 'exit nil))
6137 (error "Not on a heading")))
6139 (defun org-goto-quit ()
6140 "Finish `org-goto' without cursor motion."
6141 (interactive)
6142 (setq org-goto-selected-point nil)
6143 (setq org-goto-exit-command 'quit)
6144 (throw 'exit nil))
6146 ;;; Indirect buffer display of subtrees
6148 (defvar org-indirect-dedicated-frame nil
6149 "This is the frame being used for indirect tree display.")
6150 (defvar org-last-indirect-buffer nil)
6152 (defun org-tree-to-indirect-buffer (&optional arg)
6153 "Create indirect buffer and narrow it to current subtree.
6154 With numerical prefix ARG, go up to this level and then take that tree.
6155 If ARG is negative, go up that many levels.
6156 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6157 indirect buffer previously made with this command, to avoid proliferation of
6158 indirect buffers. However, when you call the command with a `C-u' prefix, or
6159 when `org-indirect-buffer-display' is `new-frame', the last buffer
6160 is kept so that you can work with several indirect buffers at the same time.
6161 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6162 requests that a new frame be made for the new buffer, so that the dedicated
6163 frame is not changed."
6164 (interactive "P")
6165 (let ((cbuf (current-buffer))
6166 (cwin (selected-window))
6167 (pos (point))
6168 beg end level heading ibuf)
6169 (save-excursion
6170 (org-back-to-heading t)
6171 (when (numberp arg)
6172 (setq level (org-outline-level))
6173 (if (< arg 0) (setq arg (+ level arg)))
6174 (while (> (setq level (org-outline-level)) arg)
6175 (outline-up-heading 1 t)))
6176 (setq beg (point)
6177 heading (org-get-heading))
6178 (org-end-of-subtree t) (setq end (point)))
6179 (if (and (buffer-live-p org-last-indirect-buffer)
6180 (not (eq org-indirect-buffer-display 'new-frame))
6181 (not arg))
6182 (kill-buffer org-last-indirect-buffer))
6183 (setq ibuf (org-get-indirect-buffer cbuf)
6184 org-last-indirect-buffer ibuf)
6185 (cond
6186 ((or (eq org-indirect-buffer-display 'new-frame)
6187 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6188 (select-frame (make-frame))
6189 (delete-other-windows)
6190 (switch-to-buffer ibuf)
6191 (org-set-frame-title heading))
6192 ((eq org-indirect-buffer-display 'dedicated-frame)
6193 (raise-frame
6194 (select-frame (or (and org-indirect-dedicated-frame
6195 (frame-live-p org-indirect-dedicated-frame)
6196 org-indirect-dedicated-frame)
6197 (setq org-indirect-dedicated-frame (make-frame)))))
6198 (delete-other-windows)
6199 (switch-to-buffer ibuf)
6200 (org-set-frame-title (concat "Indirect: " heading)))
6201 ((eq org-indirect-buffer-display 'current-window)
6202 (switch-to-buffer ibuf))
6203 ((eq org-indirect-buffer-display 'other-window)
6204 (pop-to-buffer ibuf))
6205 (t (error "Invalid value.")))
6206 (if (featurep 'xemacs)
6207 (save-excursion (org-mode) (turn-on-font-lock)))
6208 (narrow-to-region beg end)
6209 (show-all)
6210 (goto-char pos)
6211 (and (window-live-p cwin) (select-window cwin))))
6213 (defun org-get-indirect-buffer (&optional buffer)
6214 (setq buffer (or buffer (current-buffer)))
6215 (let ((n 1) (base (buffer-name buffer)) bname)
6216 (while (buffer-live-p
6217 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6218 (setq n (1+ n)))
6219 (condition-case nil
6220 (make-indirect-buffer buffer bname 'clone)
6221 (error (make-indirect-buffer buffer bname)))))
6223 (defun org-set-frame-title (title)
6224 "Set the title of the current frame to the string TITLE."
6225 ;; FIXME: how to name a single frame in XEmacs???
6226 (unless (featurep 'xemacs)
6227 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6229 ;;;; Structure editing
6231 ;;; Inserting headlines
6233 (defun org-insert-heading (&optional force-heading)
6234 "Insert a new heading or item with same depth at point.
6235 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6236 If point is at the beginning of a headline, insert a sibling before the
6237 current headline. If point is not at the beginning, do not split the line,
6238 but create the new hedline after the current line."
6239 (interactive "P")
6240 (if (= (buffer-size) 0)
6241 (insert "\n* ")
6242 (when (or force-heading (not (org-insert-item)))
6243 (let* ((head (save-excursion
6244 (condition-case nil
6245 (progn
6246 (org-back-to-heading)
6247 (match-string 0))
6248 (error "*"))))
6249 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6250 pos)
6251 (cond
6252 ((and (org-on-heading-p) (bolp)
6253 (or (bobp)
6254 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6255 ;; insert before the current line
6256 (open-line (if blank 2 1)))
6257 ((and (bolp)
6258 (or (bobp)
6259 (save-excursion
6260 (backward-char 1) (not (org-invisible-p)))))
6261 ;; insert right here
6262 nil)
6264 ; ;; in the middle of the line
6265 ; (org-show-entry)
6266 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6267 ; (if (and
6268 ; (org-on-heading-p)
6269 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6270 ; ;; protect the tags
6271 ;; (let ((tags (match-string 2)) pos)
6272 ; (delete-region (match-beginning 1) (match-end 1))
6273 ; (setq pos (point-at-bol))
6274 ; (newline (if blank 2 1))
6275 ; (save-excursion
6276 ; (goto-char pos)
6277 ; (end-of-line 1)
6278 ; (insert " " tags)
6279 ; (org-set-tags nil 'align)))
6280 ; (newline (if blank 2 1)))
6281 ; (newline (if blank 2 1))))
6284 ;; in the middle of the line
6285 (org-show-entry)
6286 (let ((split
6287 (org-get-alist-option org-M-RET-may-split-line 'headline))
6288 tags pos)
6289 (if (org-on-heading-p)
6290 (progn
6291 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6292 (setq tags (and (match-end 2) (match-string 2)))
6293 (and (match-end 1)
6294 (delete-region (match-beginning 1) (match-end 1)))
6295 (setq pos (point-at-bol))
6296 (or split (end-of-line 1))
6297 (delete-horizontal-space)
6298 (newline (if blank 2 1))
6299 (when tags
6300 (save-excursion
6301 (goto-char pos)
6302 (end-of-line 1)
6303 (insert " " tags)
6304 (org-set-tags nil 'align))))
6305 (or split (end-of-line 1))
6306 (newline (if blank 2 1))))))
6307 (insert head) (just-one-space)
6308 (setq pos (point))
6309 (end-of-line 1)
6310 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6311 (run-hooks 'org-insert-heading-hook)))))
6313 (defun org-insert-heading-after-current ()
6314 "Insert a new heading with same level as current, after current subtree."
6315 (interactive)
6316 (org-back-to-heading)
6317 (org-insert-heading)
6318 (org-move-subtree-down)
6319 (end-of-line 1))
6321 (defun org-insert-todo-heading (arg)
6322 "Insert a new heading with the same level and TODO state as current heading.
6323 If the heading has no TODO state, or if the state is DONE, use the first
6324 state (TODO by default). Also with prefix arg, force first state."
6325 (interactive "P")
6326 (when (not (org-insert-item 'checkbox))
6327 (org-insert-heading)
6328 (save-excursion
6329 (org-back-to-heading)
6330 (outline-previous-heading)
6331 (looking-at org-todo-line-regexp))
6332 (if (or arg
6333 (not (match-beginning 2))
6334 (member (match-string 2) org-done-keywords))
6335 (insert (car org-todo-keywords-1) " ")
6336 (insert (match-string 2) " "))))
6338 (defun org-insert-subheading (arg)
6339 "Insert a new subheading and demote it.
6340 Works for outline headings and for plain lists alike."
6341 (interactive "P")
6342 (org-insert-heading arg)
6343 (cond
6344 ((org-on-heading-p) (org-do-demote))
6345 ((org-at-item-p) (org-indent-item 1))))
6347 (defun org-insert-todo-subheading (arg)
6348 "Insert a new subheading with TODO keyword or checkbox and demote it.
6349 Works for outline headings and for plain lists alike."
6350 (interactive "P")
6351 (org-insert-todo-heading arg)
6352 (cond
6353 ((org-on-heading-p) (org-do-demote))
6354 ((org-at-item-p) (org-indent-item 1))))
6356 ;;; Promotion and Demotion
6358 (defun org-promote-subtree ()
6359 "Promote the entire subtree.
6360 See also `org-promote'."
6361 (interactive)
6362 (save-excursion
6363 (org-map-tree 'org-promote))
6364 (org-fix-position-after-promote))
6366 (defun org-demote-subtree ()
6367 "Demote the entire subtree. See `org-demote'.
6368 See also `org-promote'."
6369 (interactive)
6370 (save-excursion
6371 (org-map-tree 'org-demote))
6372 (org-fix-position-after-promote))
6375 (defun org-do-promote ()
6376 "Promote the current heading higher up the tree.
6377 If the region is active in `transient-mark-mode', promote all headings
6378 in the region."
6379 (interactive)
6380 (save-excursion
6381 (if (org-region-active-p)
6382 (org-map-region 'org-promote (region-beginning) (region-end))
6383 (org-promote)))
6384 (org-fix-position-after-promote))
6386 (defun org-do-demote ()
6387 "Demote the current heading lower down the tree.
6388 If the region is active in `transient-mark-mode', demote all headings
6389 in the region."
6390 (interactive)
6391 (save-excursion
6392 (if (org-region-active-p)
6393 (org-map-region 'org-demote (region-beginning) (region-end))
6394 (org-demote)))
6395 (org-fix-position-after-promote))
6397 (defun org-fix-position-after-promote ()
6398 "Make sure that after pro/demotion cursor position is right."
6399 (let ((pos (point)))
6400 (when (save-excursion
6401 (beginning-of-line 1)
6402 (looking-at org-todo-line-regexp)
6403 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6404 (cond ((eobp) (insert " "))
6405 ((eolp) (insert " "))
6406 ((equal (char-after) ?\ ) (forward-char 1))))))
6408 (defun org-reduced-level (l)
6409 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6411 (defun org-get-legal-level (level &optional change)
6412 "Rectify a level change under the influence of `org-odd-levels-only'
6413 LEVEL is a current level, CHANGE is by how much the level should be
6414 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6415 even level numbers will become the next higher odd number."
6416 (if org-odd-levels-only
6417 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6418 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6419 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6420 (max 1 (+ level change))))
6422 (defun org-promote ()
6423 "Promote the current heading higher up the tree.
6424 If the region is active in `transient-mark-mode', promote all headings
6425 in the region."
6426 (org-back-to-heading t)
6427 (let* ((level (save-match-data (funcall outline-level)))
6428 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6429 (diff (abs (- level (length up-head) -1))))
6430 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6431 (replace-match up-head nil t)
6432 ;; Fixup tag positioning
6433 (and org-auto-align-tags (org-set-tags nil t))
6434 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6436 (defun org-demote ()
6437 "Demote the current heading lower down the tree.
6438 If the region is active in `transient-mark-mode', demote all headings
6439 in the region."
6440 (org-back-to-heading t)
6441 (let* ((level (save-match-data (funcall outline-level)))
6442 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6443 (diff (abs (- level (length down-head) -1))))
6444 (replace-match down-head nil t)
6445 ;; Fixup tag positioning
6446 (and org-auto-align-tags (org-set-tags nil t))
6447 (if org-adapt-indentation (org-fixup-indentation diff))))
6449 (defun org-map-tree (fun)
6450 "Call FUN for every heading underneath the current one."
6451 (org-back-to-heading)
6452 (let ((level (funcall outline-level)))
6453 (save-excursion
6454 (funcall fun)
6455 (while (and (progn
6456 (outline-next-heading)
6457 (> (funcall outline-level) level))
6458 (not (eobp)))
6459 (funcall fun)))))
6461 (defun org-map-region (fun beg end)
6462 "Call FUN for every heading between BEG and END."
6463 (let ((org-ignore-region t))
6464 (save-excursion
6465 (setq end (copy-marker end))
6466 (goto-char beg)
6467 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6468 (< (point) end))
6469 (funcall fun))
6470 (while (and (progn
6471 (outline-next-heading)
6472 (< (point) end))
6473 (not (eobp)))
6474 (funcall fun)))))
6476 (defun org-fixup-indentation (diff)
6477 "Change the indentation in the current entry by DIFF
6478 However, if any line in the current entry has no indentation, or if it
6479 would end up with no indentation after the change, nothing at all is done."
6480 (save-excursion
6481 (let ((end (save-excursion (outline-next-heading)
6482 (point-marker)))
6483 (prohibit (if (> diff 0)
6484 "^\\S-"
6485 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6486 col)
6487 (unless (save-excursion (end-of-line 1)
6488 (re-search-forward prohibit end t))
6489 (while (and (< (point) end)
6490 (re-search-forward "^[ \t]+" end t))
6491 (goto-char (match-end 0))
6492 (setq col (current-column))
6493 (if (< diff 0) (replace-match ""))
6494 (indent-to (+ diff col))))
6495 (move-marker end nil))))
6497 (defun org-convert-to-odd-levels ()
6498 "Convert an org-mode file with all levels allowed to one with odd levels.
6499 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6500 level 5 etc."
6501 (interactive)
6502 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6503 (let ((org-odd-levels-only nil) n)
6504 (save-excursion
6505 (goto-char (point-min))
6506 (while (re-search-forward "^\\*\\*+ " nil t)
6507 (setq n (- (length (match-string 0)) 2))
6508 (while (>= (setq n (1- n)) 0)
6509 (org-demote))
6510 (end-of-line 1))))))
6513 (defun org-convert-to-oddeven-levels ()
6514 "Convert an org-mode file with only odd levels to one with odd and even levels.
6515 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6516 section with an even level, conversion would destroy the structure of the file. An error
6517 is signaled in this case."
6518 (interactive)
6519 (goto-char (point-min))
6520 ;; First check if there are no even levels
6521 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6522 (org-show-context t)
6523 (error "Not all levels are odd in this file. Conversion not possible."))
6524 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6525 (let ((org-odd-levels-only nil) n)
6526 (save-excursion
6527 (goto-char (point-min))
6528 (while (re-search-forward "^\\*\\*+ " nil t)
6529 (setq n (/ (1- (length (match-string 0))) 2))
6530 (while (>= (setq n (1- n)) 0)
6531 (org-promote))
6532 (end-of-line 1))))))
6534 (defun org-tr-level (n)
6535 "Make N odd if required."
6536 (if org-odd-levels-only (1+ (/ n 2)) n))
6538 ;;; Vertical tree motion, cutting and pasting of subtrees
6540 (defun org-move-subtree-up (&optional arg)
6541 "Move the current subtree up past ARG headlines of the same level."
6542 (interactive "p")
6543 (org-move-subtree-down (- (prefix-numeric-value arg))))
6545 (defun org-move-subtree-down (&optional arg)
6546 "Move the current subtree down past ARG headlines of the same level."
6547 (interactive "p")
6548 (setq arg (prefix-numeric-value arg))
6549 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6550 'outline-get-last-sibling))
6551 (ins-point (make-marker))
6552 (cnt (abs arg))
6553 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6554 ;; Select the tree
6555 (org-back-to-heading)
6556 (setq beg0 (point))
6557 (save-excursion
6558 (setq ne-beg (org-back-over-empty-lines))
6559 (setq beg (point)))
6560 (save-match-data
6561 (save-excursion (outline-end-of-heading)
6562 (setq folded (org-invisible-p)))
6563 (outline-end-of-subtree))
6564 (outline-next-heading)
6565 (setq ne-end (org-back-over-empty-lines))
6566 (setq end (point))
6567 (goto-char beg0)
6568 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6569 ;; include less whitespace
6570 (save-excursion
6571 (goto-char beg)
6572 (forward-line (- ne-beg ne-end))
6573 (setq beg (point))))
6574 ;; Find insertion point, with error handling
6575 (while (> cnt 0)
6576 (or (and (funcall movfunc) (looking-at outline-regexp))
6577 (progn (goto-char beg0)
6578 (error "Cannot move past superior level or buffer limit")))
6579 (setq cnt (1- cnt)))
6580 (if (> arg 0)
6581 ;; Moving forward - still need to move over subtree
6582 (progn (org-end-of-subtree t t)
6583 (save-excursion
6584 (org-back-over-empty-lines)
6585 (or (bolp) (newline)))))
6586 (setq ne-ins (org-back-over-empty-lines))
6587 (move-marker ins-point (point))
6588 (setq txt (buffer-substring beg end))
6589 (delete-region beg end)
6590 (outline-flag-region (1- beg) beg nil)
6591 (outline-flag-region (1- (point)) (point) nil)
6592 (insert txt)
6593 (or (bolp) (insert "\n"))
6594 (setq ins-end (point))
6595 (goto-char ins-point)
6596 (org-skip-whitespace)
6597 (when (and (< arg 0)
6598 (org-first-sibling-p)
6599 (> ne-ins ne-beg))
6600 ;; Move whitespace back to beginning
6601 (save-excursion
6602 (goto-char ins-end)
6603 (let ((kill-whole-line t))
6604 (kill-line (- ne-ins ne-beg)) (point)))
6605 (insert (make-string (- ne-ins ne-beg) ?\n)))
6606 (move-marker ins-point nil)
6607 (org-compact-display-after-subtree-move)
6608 (unless folded
6609 (org-show-entry)
6610 (show-children)
6611 (org-cycle-hide-drawers 'children))))
6613 (defvar org-subtree-clip ""
6614 "Clipboard for cut and paste of subtrees.
6615 This is actually only a copy of the kill, because we use the normal kill
6616 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6618 (defvar org-subtree-clip-folded nil
6619 "Was the last copied subtree folded?
6620 This is used to fold the tree back after pasting.")
6622 (defun org-cut-subtree (&optional n)
6623 "Cut the current subtree into the clipboard.
6624 With prefix arg N, cut this many sequential subtrees.
6625 This is a short-hand for marking the subtree and then cutting it."
6626 (interactive "p")
6627 (org-copy-subtree n 'cut))
6629 (defun org-copy-subtree (&optional n cut)
6630 "Cut the current subtree into the clipboard.
6631 With prefix arg N, cut this many sequential subtrees.
6632 This is a short-hand for marking the subtree and then copying it.
6633 If CUT is non-nil, actually cut the subtree."
6634 (interactive "p")
6635 (let (beg end folded (beg0 (point)))
6636 (if (interactive-p)
6637 (org-back-to-heading nil) ; take what looks like a subtree
6638 (org-back-to-heading t)) ; take what is really there
6639 (org-back-over-empty-lines)
6640 (setq beg (point))
6641 (skip-chars-forward " \t\r\n")
6642 (save-match-data
6643 (save-excursion (outline-end-of-heading)
6644 (setq folded (org-invisible-p)))
6645 (condition-case nil
6646 (outline-forward-same-level (1- n))
6647 (error nil))
6648 (org-end-of-subtree t t))
6649 (org-back-over-empty-lines)
6650 (setq end (point))
6651 (goto-char beg0)
6652 (when (> end beg)
6653 (setq org-subtree-clip-folded folded)
6654 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6655 (setq org-subtree-clip (current-kill 0))
6656 (message "%s: Subtree(s) with %d characters"
6657 (if cut "Cut" "Copied")
6658 (length org-subtree-clip)))))
6660 (defun org-paste-subtree (&optional level tree)
6661 "Paste the clipboard as a subtree, with modification of headline level.
6662 The entire subtree is promoted or demoted in order to match a new headline
6663 level. By default, the new level is derived from the visible headings
6664 before and after the insertion point, and taken to be the inferior headline
6665 level of the two. So if the previous visible heading is level 3 and the
6666 next is level 4 (or vice versa), level 4 will be used for insertion.
6667 This makes sure that the subtree remains an independent subtree and does
6668 not swallow low level entries.
6670 You can also force a different level, either by using a numeric prefix
6671 argument, or by inserting the heading marker by hand. For example, if the
6672 cursor is after \"*****\", then the tree will be shifted to level 5.
6674 If you want to insert the tree as is, just use \\[yank].
6676 If optional TREE is given, use this text instead of the kill ring."
6677 (interactive "P")
6678 (unless (org-kill-is-subtree-p tree)
6679 (error "%s"
6680 (substitute-command-keys
6681 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6682 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6683 (^re (concat "^\\(" outline-regexp "\\)"))
6684 (re (concat "\\(" outline-regexp "\\)"))
6685 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6687 (old-level (if (string-match ^re txt)
6688 (- (match-end 0) (match-beginning 0) 1)
6689 -1))
6690 (force-level (cond (level (prefix-numeric-value level))
6691 ((string-match
6692 ^re_ (buffer-substring (point-at-bol) (point)))
6693 (- (match-end 1) (match-beginning 1)))
6694 (t nil)))
6695 (previous-level (save-excursion
6696 (condition-case nil
6697 (progn
6698 (outline-previous-visible-heading 1)
6699 (if (looking-at re)
6700 (- (match-end 0) (match-beginning 0) 1)
6702 (error 1))))
6703 (next-level (save-excursion
6704 (condition-case nil
6705 (progn
6706 (or (looking-at outline-regexp)
6707 (outline-next-visible-heading 1))
6708 (if (looking-at re)
6709 (- (match-end 0) (match-beginning 0) 1)
6711 (error 1))))
6712 (new-level (or force-level (max previous-level next-level)))
6713 (shift (if (or (= old-level -1)
6714 (= new-level -1)
6715 (= old-level new-level))
6717 (- new-level old-level)))
6718 (delta (if (> shift 0) -1 1))
6719 (func (if (> shift 0) 'org-demote 'org-promote))
6720 (org-odd-levels-only nil)
6721 beg end)
6722 ;; Remove the forced level indicator
6723 (if force-level
6724 (delete-region (point-at-bol) (point)))
6725 ;; Paste
6726 (beginning-of-line 1)
6727 (org-back-over-empty-lines) ;; FIXME: correct fix????
6728 (setq beg (point))
6729 (insert-before-markers txt) ;; FIXME: correct fix????
6730 (unless (string-match "\n\\'" txt) (insert "\n"))
6731 (setq end (point))
6732 (goto-char beg)
6733 (skip-chars-forward " \t\n\r")
6734 (setq beg (point))
6735 ;; Shift if necessary
6736 (unless (= shift 0)
6737 (save-restriction
6738 (narrow-to-region beg end)
6739 (while (not (= shift 0))
6740 (org-map-region func (point-min) (point-max))
6741 (setq shift (+ delta shift)))
6742 (goto-char (point-min))))
6743 (when (interactive-p)
6744 (message "Clipboard pasted as level %d subtree" new-level))
6745 (if (and kill-ring
6746 (eq org-subtree-clip (current-kill 0))
6747 org-subtree-clip-folded)
6748 ;; The tree was folded before it was killed/copied
6749 (hide-subtree))))
6751 (defun org-kill-is-subtree-p (&optional txt)
6752 "Check if the current kill is an outline subtree, or a set of trees.
6753 Returns nil if kill does not start with a headline, or if the first
6754 headline level is not the largest headline level in the tree.
6755 So this will actually accept several entries of equal levels as well,
6756 which is OK for `org-paste-subtree'.
6757 If optional TXT is given, check this string instead of the current kill."
6758 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6759 (start-level (and kill
6760 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6761 org-outline-regexp "\\)")
6762 kill)
6763 (- (match-end 2) (match-beginning 2) 1)))
6764 (re (concat "^" org-outline-regexp))
6765 (start (1+ (match-beginning 2))))
6766 (if (not start-level)
6767 (progn
6768 nil) ;; does not even start with a heading
6769 (catch 'exit
6770 (while (setq start (string-match re kill (1+ start)))
6771 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6772 (throw 'exit nil)))
6773 t))))
6775 (defun org-narrow-to-subtree ()
6776 "Narrow buffer to the current subtree."
6777 (interactive)
6778 (save-excursion
6779 (save-match-data
6780 (narrow-to-region
6781 (progn (org-back-to-heading) (point))
6782 (progn (org-end-of-subtree t t) (point))))))
6785 ;;; Outline Sorting
6787 (defun org-sort (with-case)
6788 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6789 Optional argument WITH-CASE means sort case-sensitively."
6790 (interactive "P")
6791 (if (org-at-table-p)
6792 (org-call-with-arg 'org-table-sort-lines with-case)
6793 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6795 (defvar org-priority-regexp) ; defined later in the file
6797 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6798 "Sort entries on a certain level of an outline tree.
6799 If there is an active region, the entries in the region are sorted.
6800 Else, if the cursor is before the first entry, sort the top-level items.
6801 Else, the children of the entry at point are sorted.
6803 Sorting can be alphabetically, numerically, and by date/time as given by
6804 the first time stamp in the entry. The command prompts for the sorting
6805 type unless it has been given to the function through the SORTING-TYPE
6806 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6807 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6808 called with point at the beginning of the record. It must return either
6809 a string or a number that should serve as the sorting key for that record.
6811 Comparing entries ignores case by default. However, with an optional argument
6812 WITH-CASE, the sorting considers case as well."
6813 (interactive "P")
6814 (let ((case-func (if with-case 'identity 'downcase))
6815 start beg end stars re re2
6816 txt what tmp plain-list-p)
6817 ;; Find beginning and end of region to sort
6818 (cond
6819 ((org-region-active-p)
6820 ;; we will sort the region
6821 (setq end (region-end)
6822 what "region")
6823 (goto-char (region-beginning))
6824 (if (not (org-on-heading-p)) (outline-next-heading))
6825 (setq start (point)))
6826 ((org-at-item-p)
6827 ;; we will sort this plain list
6828 (org-beginning-of-item-list) (setq start (point))
6829 (org-end-of-item-list) (setq end (point))
6830 (goto-char start)
6831 (setq plain-list-p t
6832 what "plain list"))
6833 ((or (org-on-heading-p)
6834 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6835 ;; we will sort the children of the current headline
6836 (org-back-to-heading)
6837 (setq start (point)
6838 end (progn (org-end-of-subtree t t)
6839 (org-back-over-empty-lines)
6840 (point))
6841 what "children")
6842 (goto-char start)
6843 (show-subtree)
6844 (outline-next-heading))
6846 ;; we will sort the top-level entries in this file
6847 (goto-char (point-min))
6848 (or (org-on-heading-p) (outline-next-heading))
6849 (setq start (point) end (point-max) what "top-level")
6850 (goto-char start)
6851 (show-all)))
6853 (setq beg (point))
6854 (if (>= beg end) (error "Nothing to sort"))
6856 (unless plain-list-p
6857 (looking-at "\\(\\*+\\)")
6858 (setq stars (match-string 1)
6859 re (concat "^" (regexp-quote stars) " +")
6860 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6861 txt (buffer-substring beg end))
6862 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6863 (if (and (not (equal stars "*")) (string-match re2 txt))
6864 (error "Region to sort contains a level above the first entry")))
6866 (unless sorting-type
6867 (message
6868 (if plain-list-p
6869 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6870 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6871 what)
6872 (setq sorting-type (read-char-exclusive))
6874 (and (= (downcase sorting-type) ?f)
6875 (setq getkey-func
6876 (completing-read "Sort using function: "
6877 obarray 'fboundp t nil nil))
6878 (setq getkey-func (intern getkey-func)))
6880 (and (= (downcase sorting-type) ?r)
6881 (setq property
6882 (completing-read "Property: "
6883 (mapcar 'list (org-buffer-property-keys t))
6884 nil t))))
6886 (message "Sorting entries...")
6888 (save-restriction
6889 (narrow-to-region start end)
6891 (let ((dcst (downcase sorting-type))
6892 (now (current-time)))
6893 (sort-subr
6894 (/= dcst sorting-type)
6895 ;; This function moves to the beginning character of the "record" to
6896 ;; be sorted.
6897 (if plain-list-p
6898 (lambda nil
6899 (if (org-at-item-p) t (goto-char (point-max))))
6900 (lambda nil
6901 (if (re-search-forward re nil t)
6902 (goto-char (match-beginning 0))
6903 (goto-char (point-max)))))
6904 ;; This function moves to the last character of the "record" being
6905 ;; sorted.
6906 (if plain-list-p
6907 'org-end-of-item
6908 (lambda nil
6909 (save-match-data
6910 (condition-case nil
6911 (outline-forward-same-level 1)
6912 (error
6913 (goto-char (point-max)))))))
6915 ;; This function returns the value that gets sorted against.
6916 (if plain-list-p
6917 (lambda nil
6918 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6919 (cond
6920 ((= dcst ?n)
6921 (string-to-number (buffer-substring (match-end 0)
6922 (point-at-eol))))
6923 ((= dcst ?a)
6924 (buffer-substring (match-end 0) (point-at-eol)))
6925 ((= dcst ?t)
6926 (if (re-search-forward org-ts-regexp
6927 (point-at-eol) t)
6928 (org-time-string-to-time (match-string 0))
6929 now))
6930 ((= dcst ?f)
6931 (if getkey-func
6932 (progn
6933 (setq tmp (funcall getkey-func))
6934 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6935 tmp)
6936 (error "Invalid key function `%s'" getkey-func)))
6937 (t (error "Invalid sorting type `%c'" sorting-type)))))
6938 (lambda nil
6939 (cond
6940 ((= dcst ?n)
6941 (if (looking-at outline-regexp)
6942 (string-to-number (buffer-substring (match-end 0)
6943 (point-at-eol)))
6944 nil))
6945 ((= dcst ?a)
6946 (funcall case-func (buffer-substring (point-at-bol)
6947 (point-at-eol))))
6948 ((= dcst ?t)
6949 (if (re-search-forward org-ts-regexp
6950 (save-excursion
6951 (forward-line 2)
6952 (point)) t)
6953 (org-time-string-to-time (match-string 0))
6954 now))
6955 ((= dcst ?p)
6956 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6957 (string-to-char (match-string 2))
6958 org-default-priority))
6959 ((= dcst ?r)
6960 (or (org-entry-get nil property) ""))
6961 ((= dcst ?f)
6962 (if getkey-func
6963 (progn
6964 (setq tmp (funcall getkey-func))
6965 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6966 tmp)
6967 (error "Invalid key function `%s'" getkey-func)))
6968 (t (error "Invalid sorting type `%c'" sorting-type)))))
6970 (cond
6971 ((= dcst ?a) 'string<)
6972 ((= dcst ?t) 'time-less-p)
6973 (t nil)))))
6974 (message "Sorting entries...done")))
6976 (defun org-do-sort (table what &optional with-case sorting-type)
6977 "Sort TABLE of WHAT according to SORTING-TYPE.
6978 The user will be prompted for the SORTING-TYPE if the call to this
6979 function does not specify it. WHAT is only for the prompt, to indicate
6980 what is being sorted. The sorting key will be extracted from
6981 the car of the elements of the table.
6982 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6983 (unless sorting-type
6984 (message
6985 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6986 what)
6987 (setq sorting-type (read-char-exclusive)))
6988 (let ((dcst (downcase sorting-type))
6989 extractfun comparefun)
6990 ;; Define the appropriate functions
6991 (cond
6992 ((= dcst ?n)
6993 (setq extractfun 'string-to-number
6994 comparefun (if (= dcst sorting-type) '< '>)))
6995 ((= dcst ?a)
6996 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6997 (lambda(x) (downcase (org-sort-remove-invisible x))))
6998 comparefun (if (= dcst sorting-type)
6999 'string<
7000 (lambda (a b) (and (not (string< a b))
7001 (not (string= a b)))))))
7002 ((= dcst ?t)
7003 (setq extractfun
7004 (lambda (x)
7005 (if (string-match org-ts-regexp x)
7006 (time-to-seconds
7007 (org-time-string-to-time (match-string 0 x)))
7009 comparefun (if (= dcst sorting-type) '< '>)))
7010 (t (error "Invalid sorting type `%c'" sorting-type)))
7012 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7013 table)
7014 (lambda (a b) (funcall comparefun (car a) (car b))))))
7016 ;;;; Plain list items, including checkboxes
7018 ;;; Plain list items
7020 (defun org-at-item-p ()
7021 "Is point in a line starting a hand-formatted item?"
7022 (let ((llt org-plain-list-ordered-item-terminator))
7023 (save-excursion
7024 (goto-char (point-at-bol))
7025 (looking-at
7026 (cond
7027 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7028 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7029 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7030 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7032 (defun org-in-item-p ()
7033 "It the cursor inside a plain list item.
7034 Does not have to be the first line."
7035 (save-excursion
7036 (condition-case nil
7037 (progn
7038 (org-beginning-of-item)
7039 (org-at-item-p)
7041 (error nil))))
7043 (defun org-insert-item (&optional checkbox)
7044 "Insert a new item at the current level.
7045 Return t when things worked, nil when we are not in an item."
7046 (when (save-excursion
7047 (condition-case nil
7048 (progn
7049 (org-beginning-of-item)
7050 (org-at-item-p)
7051 (if (org-invisible-p) (error "Invisible item"))
7053 (error nil)))
7054 (let* ((bul (match-string 0))
7055 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7056 (match-end 0)))
7057 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7058 pos)
7059 (cond
7060 ((and (org-at-item-p) (<= (point) eow))
7061 ;; before the bullet
7062 (beginning-of-line 1)
7063 (open-line (if blank 2 1)))
7064 ((<= (point) eow)
7065 (beginning-of-line 1))
7067 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7068 (end-of-line 1)
7069 (delete-horizontal-space))
7070 (newline (if blank 2 1))))
7071 (insert bul (if checkbox "[ ]" ""))
7072 (just-one-space)
7073 (setq pos (point))
7074 (end-of-line 1)
7075 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7076 (org-maybe-renumber-ordered-list)
7077 (and checkbox (org-update-checkbox-count-maybe))
7080 ;;; Checkboxes
7082 (defun org-at-item-checkbox-p ()
7083 "Is point at a line starting a plain-list item with a checklet?"
7084 (and (org-at-item-p)
7085 (save-excursion
7086 (goto-char (match-end 0))
7087 (skip-chars-forward " \t")
7088 (looking-at "\\[[- X]\\]"))))
7090 (defun org-toggle-checkbox (&optional arg)
7091 "Toggle the checkbox in the current line."
7092 (interactive "P")
7093 (catch 'exit
7094 (let (beg end status (firstnew 'unknown))
7095 (cond
7096 ((org-region-active-p)
7097 (setq beg (region-beginning) end (region-end)))
7098 ((org-on-heading-p)
7099 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7100 ((org-at-item-checkbox-p)
7101 (let ((pos (point)))
7102 (replace-match
7103 (cond (arg "[-]")
7104 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7105 (t "[ ]"))
7106 t t)
7107 (goto-char pos))
7108 (throw 'exit t))
7109 (t (error "Not at a checkbox or heading, and no active region")))
7110 (save-excursion
7111 (goto-char beg)
7112 (while (< (point) end)
7113 (when (org-at-item-checkbox-p)
7114 (setq status (equal (match-string 0) "[X]"))
7115 (when (eq firstnew 'unknown)
7116 (setq firstnew (not status)))
7117 (replace-match
7118 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7119 (beginning-of-line 2)))))
7120 (org-update-checkbox-count-maybe))
7122 (defun org-update-checkbox-count-maybe ()
7123 "Update checkbox statistics unless turned off by user."
7124 (when org-provide-checkbox-statistics
7125 (org-update-checkbox-count)))
7127 (defun org-update-checkbox-count (&optional all)
7128 "Update the checkbox statistics in the current section.
7129 This will find all statistic cookies like [57%] and [6/12] and update them
7130 with the current numbers. With optional prefix argument ALL, do this for
7131 the whole buffer."
7132 (interactive "P")
7133 (save-excursion
7134 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7135 (beg (condition-case nil
7136 (progn (outline-back-to-heading) (point))
7137 (error (point-min))))
7138 (end (move-marker (make-marker)
7139 (progn (outline-next-heading) (point))))
7140 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7141 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7142 (re-find (concat re "\\|" re-box))
7143 beg-cookie end-cookie is-percent c-on c-off lim
7144 eline curr-ind next-ind continue-from startsearch
7145 (cstat 0)
7147 (when all
7148 (goto-char (point-min))
7149 (outline-next-heading)
7150 (setq beg (point) end (point-max)))
7151 (goto-char end)
7152 ;; find each statistic cookie
7153 (while (re-search-backward re-find beg t)
7154 (setq beg-cookie (match-beginning 1)
7155 end-cookie (match-end 1)
7156 cstat (+ cstat (if end-cookie 1 0))
7157 startsearch (point-at-eol)
7158 continue-from (point-at-bol)
7159 is-percent (match-beginning 2)
7160 lim (cond
7161 ((org-on-heading-p) (outline-next-heading) (point))
7162 ((org-at-item-p) (org-end-of-item) (point))
7163 (t nil))
7164 c-on 0
7165 c-off 0)
7166 (when lim
7167 ;; find first checkbox for this cookie and gather
7168 ;; statistics from all that are at this indentation level
7169 (goto-char startsearch)
7170 (if (re-search-forward re-box lim t)
7171 (progn
7172 (org-beginning-of-item)
7173 (setq curr-ind (org-get-indentation))
7174 (setq next-ind curr-ind)
7175 (while (= curr-ind next-ind)
7176 (save-excursion (end-of-line) (setq eline (point)))
7177 (if (re-search-forward re-box eline t)
7178 (if (member (match-string 2) '("[ ]" "[-]"))
7179 (setq c-off (1+ c-off))
7180 (setq c-on (1+ c-on))
7183 (org-end-of-item)
7184 (setq next-ind (org-get-indentation))
7186 (goto-char continue-from)
7187 ;; update cookie
7188 (when end-cookie
7189 (delete-region beg-cookie end-cookie)
7190 (goto-char beg-cookie)
7191 (insert
7192 (if is-percent
7193 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7194 (format "[%d/%d]" c-on (+ c-on c-off)))))
7195 ;; update items checkbox if it has one
7196 (when (org-at-item-p)
7197 (org-beginning-of-item)
7198 (when (and (> (+ c-on c-off) 0)
7199 (re-search-forward re-box (point-at-eol) t))
7200 (setq beg-cookie (match-beginning 2)
7201 end-cookie (match-end 2))
7202 (delete-region beg-cookie end-cookie)
7203 (goto-char beg-cookie)
7204 (cond ((= c-off 0) (insert "[X]"))
7205 ((= c-on 0) (insert "[ ]"))
7206 (t (insert "[-]")))
7208 (goto-char continue-from))
7209 (when (interactive-p)
7210 (message "Checkbox satistics updated %s (%d places)"
7211 (if all "in entire file" "in current outline entry") cstat)))))
7213 (defun org-get-checkbox-statistics-face ()
7214 "Select the face for checkbox statistics.
7215 The face will be `org-done' when all relevant boxes are checked. Otherwise
7216 it will be `org-todo'."
7217 (if (match-end 1)
7218 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7219 (if (and (> (match-end 2) (match-beginning 2))
7220 (equal (match-string 2) (match-string 3)))
7221 'org-done
7222 'org-todo)))
7224 (defun org-get-indentation (&optional line)
7225 "Get the indentation of the current line, interpreting tabs.
7226 When LINE is given, assume it represents a line and compute its indentation."
7227 (if line
7228 (if (string-match "^ *" (org-remove-tabs line))
7229 (match-end 0))
7230 (save-excursion
7231 (beginning-of-line 1)
7232 (skip-chars-forward " \t")
7233 (current-column))))
7235 (defun org-remove-tabs (s &optional width)
7236 "Replace tabulators in S with spaces.
7237 Assumes that s is a single line, starting in column 0."
7238 (setq width (or width tab-width))
7239 (while (string-match "\t" s)
7240 (setq s (replace-match
7241 (make-string
7242 (- (* width (/ (+ (match-beginning 0) width) width))
7243 (match-beginning 0)) ?\ )
7244 t t s)))
7247 (defun org-fix-indentation (line ind)
7248 "Fix indentation in LINE.
7249 IND is a cons cell with target and minimum indentation.
7250 If the current indenation in LINE is smaller than the minimum,
7251 leave it alone. If it is larger than ind, set it to the target."
7252 (let* ((l (org-remove-tabs line))
7253 (i (org-get-indentation l))
7254 (i1 (car ind)) (i2 (cdr ind)))
7255 (if (>= i i2) (setq l (substring line i2)))
7256 (if (> i1 0)
7257 (concat (make-string i1 ?\ ) l)
7258 l)))
7260 (defcustom org-empty-line-terminates-plain-lists nil
7261 "Non-nil means, an empty line ends all plain list levels.
7262 When nil, empty lines are part of the preceeding item."
7263 :group 'org-plain-lists
7264 :type 'boolean)
7266 (defun org-beginning-of-item ()
7267 "Go to the beginning of the current hand-formatted item.
7268 If the cursor is not in an item, throw an error."
7269 (interactive)
7270 (let ((pos (point))
7271 (limit (save-excursion
7272 (condition-case nil
7273 (progn
7274 (org-back-to-heading)
7275 (beginning-of-line 2) (point))
7276 (error (point-min)))))
7277 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7278 ind ind1)
7279 (if (org-at-item-p)
7280 (beginning-of-line 1)
7281 (beginning-of-line 1)
7282 (skip-chars-forward " \t")
7283 (setq ind (current-column))
7284 (if (catch 'exit
7285 (while t
7286 (beginning-of-line 0)
7287 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7289 (if (looking-at "[ \t]*$")
7290 (setq ind1 ind-empty)
7291 (skip-chars-forward " \t")
7292 (setq ind1 (current-column)))
7293 (if (< ind1 ind)
7294 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7296 (goto-char pos)
7297 (error "Not in an item")))))
7299 (defun org-end-of-item ()
7300 "Go to the end of the current hand-formatted item.
7301 If the cursor is not in an item, throw an error."
7302 (interactive)
7303 (let* ((pos (point))
7304 ind1
7305 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7306 (limit (save-excursion (outline-next-heading) (point)))
7307 (ind (save-excursion
7308 (org-beginning-of-item)
7309 (skip-chars-forward " \t")
7310 (current-column)))
7311 (end (catch 'exit
7312 (while t
7313 (beginning-of-line 2)
7314 (if (eobp) (throw 'exit (point)))
7315 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7316 (if (looking-at "[ \t]*$")
7317 (setq ind1 ind-empty)
7318 (skip-chars-forward " \t")
7319 (setq ind1 (current-column)))
7320 (if (<= ind1 ind)
7321 (throw 'exit (point-at-bol)))))))
7322 (if end
7323 (goto-char end)
7324 (goto-char pos)
7325 (error "Not in an item"))))
7327 (defun org-next-item ()
7328 "Move to the beginning of the next item in the current plain list.
7329 Error if not at a plain list, or if this is the last item in the list."
7330 (interactive)
7331 (let (ind ind1 (pos (point)))
7332 (org-beginning-of-item)
7333 (setq ind (org-get-indentation))
7334 (org-end-of-item)
7335 (setq ind1 (org-get-indentation))
7336 (unless (and (org-at-item-p) (= ind ind1))
7337 (goto-char pos)
7338 (error "On last item"))))
7340 (defun org-previous-item ()
7341 "Move to the beginning of the previous item in the current plain list.
7342 Error if not at a plain list, or if this is the first item in the list."
7343 (interactive)
7344 (let (beg ind ind1 (pos (point)))
7345 (org-beginning-of-item)
7346 (setq beg (point))
7347 (setq ind (org-get-indentation))
7348 (goto-char beg)
7349 (catch 'exit
7350 (while t
7351 (beginning-of-line 0)
7352 (if (looking-at "[ \t]*$")
7354 (if (<= (setq ind1 (org-get-indentation)) ind)
7355 (throw 'exit t)))))
7356 (condition-case nil
7357 (if (or (not (org-at-item-p))
7358 (< ind1 (1- ind)))
7359 (error "")
7360 (org-beginning-of-item))
7361 (error (goto-char pos)
7362 (error "On first item")))))
7364 (defun org-first-list-item-p ()
7365 "Is this heading the item in a plain list?"
7366 (unless (org-at-item-p)
7367 (error "Not at a plain list item"))
7368 (org-beginning-of-item)
7369 (= (point) (save-excursion (org-beginning-of-item-list))))
7371 (defun org-move-item-down ()
7372 "Move the plain list item at point down, i.e. swap with following item.
7373 Subitems (items with larger indentation) are considered part of the item,
7374 so this really moves item trees."
7375 (interactive)
7376 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7377 (org-beginning-of-item)
7378 (setq beg0 (point))
7379 (save-excursion
7380 (setq ne-beg (org-back-over-empty-lines))
7381 (setq beg (point)))
7382 (goto-char beg0)
7383 (setq ind (org-get-indentation))
7384 (org-end-of-item)
7385 (setq end0 (point))
7386 (setq ind1 (org-get-indentation))
7387 (setq ne-end (org-back-over-empty-lines))
7388 (setq end (point))
7389 (goto-char beg0)
7390 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7391 ;; include less whitespace
7392 (save-excursion
7393 (goto-char beg)
7394 (forward-line (- ne-beg ne-end))
7395 (setq beg (point))))
7396 (goto-char end0)
7397 (if (and (org-at-item-p) (= ind ind1))
7398 (progn
7399 (org-end-of-item)
7400 (org-back-over-empty-lines)
7401 (setq txt (buffer-substring beg end))
7402 (save-excursion
7403 (delete-region beg end))
7404 (setq pos (point))
7405 (insert txt)
7406 (goto-char pos) (org-skip-whitespace)
7407 (org-maybe-renumber-ordered-list))
7408 (goto-char pos)
7409 (error "Cannot move this item further down"))))
7411 (defun org-move-item-up (arg)
7412 "Move the plain list item at point up, i.e. swap with previous item.
7413 Subitems (items with larger indentation) are considered part of the item,
7414 so this really moves item trees."
7415 (interactive "p")
7416 (let (beg beg0 end ind ind1 (pos (point)) txt
7417 ne-beg ne-ins ins-end)
7418 (org-beginning-of-item)
7419 (setq beg0 (point))
7420 (setq ind (org-get-indentation))
7421 (save-excursion
7422 (setq ne-beg (org-back-over-empty-lines))
7423 (setq beg (point)))
7424 (goto-char beg0)
7425 (org-end-of-item)
7426 (setq end (point))
7427 (goto-char beg0)
7428 (catch 'exit
7429 (while t
7430 (beginning-of-line 0)
7431 (if (looking-at "[ \t]*$")
7432 (if org-empty-line-terminates-plain-lists
7433 (progn
7434 (goto-char pos)
7435 (error "Cannot move this item further up"))
7436 nil)
7437 (if (<= (setq ind1 (org-get-indentation)) ind)
7438 (throw 'exit t)))))
7439 (condition-case nil
7440 (org-beginning-of-item)
7441 (error (goto-char beg)
7442 (error "Cannot move this item further up")))
7443 (setq ind1 (org-get-indentation))
7444 (if (and (org-at-item-p) (= ind ind1))
7445 (progn
7446 (setq ne-ins (org-back-over-empty-lines))
7447 (setq txt (buffer-substring beg end))
7448 (save-excursion
7449 (delete-region beg end))
7450 (setq pos (point))
7451 (insert txt)
7452 (setq ins-end (point))
7453 (goto-char pos) (org-skip-whitespace)
7455 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7456 ;; Move whitespace back to beginning
7457 (save-excursion
7458 (goto-char ins-end)
7459 (let ((kill-whole-line t))
7460 (kill-line (- ne-ins ne-beg)) (point)))
7461 (insert (make-string (- ne-ins ne-beg) ?\n)))
7463 (org-maybe-renumber-ordered-list))
7464 (goto-char pos)
7465 (error "Cannot move this item further up"))))
7467 (defun org-maybe-renumber-ordered-list ()
7468 "Renumber the ordered list at point if setup allows it.
7469 This tests the user option `org-auto-renumber-ordered-lists' before
7470 doing the renumbering."
7471 (interactive)
7472 (when (and org-auto-renumber-ordered-lists
7473 (org-at-item-p))
7474 (if (match-beginning 3)
7475 (org-renumber-ordered-list 1)
7476 (org-fix-bullet-type))))
7478 (defun org-maybe-renumber-ordered-list-safe ()
7479 (condition-case nil
7480 (save-excursion
7481 (org-maybe-renumber-ordered-list))
7482 (error nil)))
7484 (defun org-cycle-list-bullet (&optional which)
7485 "Cycle through the different itemize/enumerate bullets.
7486 This cycle the entire list level through the sequence:
7488 `-' -> `+' -> `*' -> `1.' -> `1)'
7490 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7491 0 meand `-', 1 means `+' etc."
7492 (interactive "P")
7493 (org-preserve-lc
7494 (org-beginning-of-item-list)
7495 (org-at-item-p)
7496 (beginning-of-line 1)
7497 (let ((current (match-string 0))
7498 (prevp (eq which 'previous))
7499 new)
7500 (setq new (cond
7501 ((and (numberp which)
7502 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7503 ((string-match "-" current) (if prevp "1)" "+"))
7504 ((string-match "\\+" current)
7505 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7506 ((string-match "\\*" current) (if prevp "+" "1."))
7507 ((string-match "\\." current) (if prevp "*" "1)"))
7508 ((string-match ")" current) (if prevp "1." "-"))
7509 (t (error "This should not happen"))))
7510 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7511 (org-fix-bullet-type)
7512 (org-maybe-renumber-ordered-list))))
7514 (defun org-get-string-indentation (s)
7515 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7516 (let ((n -1) (i 0) (w tab-width) c)
7517 (catch 'exit
7518 (while (< (setq n (1+ n)) (length s))
7519 (setq c (aref s n))
7520 (cond ((= c ?\ ) (setq i (1+ i)))
7521 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7522 (t (throw 'exit t)))))
7525 (defun org-renumber-ordered-list (arg)
7526 "Renumber an ordered plain list.
7527 Cursor needs to be in the first line of an item, the line that starts
7528 with something like \"1.\" or \"2)\"."
7529 (interactive "p")
7530 (unless (and (org-at-item-p)
7531 (match-beginning 3))
7532 (error "This is not an ordered list"))
7533 (let ((line (org-current-line))
7534 (col (current-column))
7535 (ind (org-get-string-indentation
7536 (buffer-substring (point-at-bol) (match-beginning 3))))
7537 ;; (term (substring (match-string 3) -1))
7538 ind1 (n (1- arg))
7539 fmt)
7540 ;; find where this list begins
7541 (org-beginning-of-item-list)
7542 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7543 (setq fmt (concat "%d" (match-string 1)))
7544 (beginning-of-line 0)
7545 ;; walk forward and replace these numbers
7546 (catch 'exit
7547 (while t
7548 (catch 'next
7549 (beginning-of-line 2)
7550 (if (eobp) (throw 'exit nil))
7551 (if (looking-at "[ \t]*$") (throw 'next nil))
7552 (skip-chars-forward " \t") (setq ind1 (current-column))
7553 (if (> ind1 ind) (throw 'next t))
7554 (if (< ind1 ind) (throw 'exit t))
7555 (if (not (org-at-item-p)) (throw 'exit nil))
7556 (delete-region (match-beginning 2) (match-end 2))
7557 (goto-char (match-beginning 2))
7558 (insert (format fmt (setq n (1+ n)))))))
7559 (goto-line line)
7560 (move-to-column col)))
7562 (defun org-fix-bullet-type ()
7563 "Make sure all items in this list have the same bullet as the firsst item."
7564 (interactive)
7565 (unless (org-at-item-p) (error "This is not a list"))
7566 (let ((line (org-current-line))
7567 (col (current-column))
7568 (ind (current-indentation))
7569 ind1 bullet)
7570 ;; find where this list begins
7571 (org-beginning-of-item-list)
7572 (beginning-of-line 1)
7573 ;; find out what the bullet type is
7574 (looking-at "[ \t]*\\(\\S-+\\)")
7575 (setq bullet (match-string 1))
7576 ;; walk forward and replace these numbers
7577 (beginning-of-line 0)
7578 (catch 'exit
7579 (while t
7580 (catch 'next
7581 (beginning-of-line 2)
7582 (if (eobp) (throw 'exit nil))
7583 (if (looking-at "[ \t]*$") (throw 'next nil))
7584 (skip-chars-forward " \t") (setq ind1 (current-column))
7585 (if (> ind1 ind) (throw 'next t))
7586 (if (< ind1 ind) (throw 'exit t))
7587 (if (not (org-at-item-p)) (throw 'exit nil))
7588 (skip-chars-forward " \t")
7589 (looking-at "\\S-+")
7590 (replace-match bullet))))
7591 (goto-line line)
7592 (move-to-column col)
7593 (if (string-match "[0-9]" bullet)
7594 (org-renumber-ordered-list 1))))
7596 (defun org-beginning-of-item-list ()
7597 "Go to the beginning of the current item list.
7598 I.e. to the first item in this list."
7599 (interactive)
7600 (org-beginning-of-item)
7601 (let ((pos (point-at-bol))
7602 (ind (org-get-indentation))
7603 ind1)
7604 ;; find where this list begins
7605 (catch 'exit
7606 (while t
7607 (catch 'next
7608 (beginning-of-line 0)
7609 (if (looking-at "[ \t]*$")
7610 (throw (if (bobp) 'exit 'next) t))
7611 (skip-chars-forward " \t") (setq ind1 (current-column))
7612 (if (or (< ind1 ind)
7613 (and (= ind1 ind)
7614 (not (org-at-item-p)))
7615 (bobp))
7616 (throw 'exit t)
7617 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7618 (goto-char pos)))
7621 (defun org-end-of-item-list ()
7622 "Go to the end of the current item list.
7623 I.e. to the text after the last item."
7624 (interactive)
7625 (org-beginning-of-item)
7626 (let ((pos (point-at-bol))
7627 (ind (org-get-indentation))
7628 ind1)
7629 ;; find where this list begins
7630 (catch 'exit
7631 (while t
7632 (catch 'next
7633 (beginning-of-line 2)
7634 (if (looking-at "[ \t]*$")
7635 (throw (if (eobp) 'exit 'next) t))
7636 (skip-chars-forward " \t") (setq ind1 (current-column))
7637 (if (or (< ind1 ind)
7638 (and (= ind1 ind)
7639 (not (org-at-item-p)))
7640 (eobp))
7641 (progn
7642 (setq pos (point-at-bol))
7643 (throw 'exit t))))))
7644 (goto-char pos)))
7647 (defvar org-last-indent-begin-marker (make-marker))
7648 (defvar org-last-indent-end-marker (make-marker))
7650 (defun org-outdent-item (arg)
7651 "Outdent a local list item."
7652 (interactive "p")
7653 (org-indent-item (- arg)))
7655 (defun org-indent-item (arg)
7656 "Indent a local list item."
7657 (interactive "p")
7658 (unless (org-at-item-p)
7659 (error "Not on an item"))
7660 (save-excursion
7661 (let (beg end ind ind1 tmp delta ind-down ind-up)
7662 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7663 (setq beg org-last-indent-begin-marker
7664 end org-last-indent-end-marker)
7665 (org-beginning-of-item)
7666 (setq beg (move-marker org-last-indent-begin-marker (point)))
7667 (org-end-of-item)
7668 (setq end (move-marker org-last-indent-end-marker (point))))
7669 (goto-char beg)
7670 (setq tmp (org-item-indent-positions)
7671 ind (car tmp)
7672 ind-down (nth 2 tmp)
7673 ind-up (nth 1 tmp)
7674 delta (if (> arg 0)
7675 (if ind-down (- ind-down ind) 2)
7676 (if ind-up (- ind-up ind) -2)))
7677 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7678 (while (< (point) end)
7679 (beginning-of-line 1)
7680 (skip-chars-forward " \t") (setq ind1 (current-column))
7681 (delete-region (point-at-bol) (point))
7682 (or (eolp) (indent-to-column (+ ind1 delta)))
7683 (beginning-of-line 2))))
7684 (org-fix-bullet-type)
7685 (org-maybe-renumber-ordered-list-safe)
7686 (save-excursion
7687 (beginning-of-line 0)
7688 (condition-case nil (org-beginning-of-item) (error nil))
7689 (org-maybe-renumber-ordered-list-safe)))
7691 (defun org-item-indent-positions ()
7692 "Return indentation for plain list items.
7693 This returns a list with three values: The current indentation, the
7694 parent indentation and the indentation a child should habe.
7695 Assumes cursor in item line."
7696 (let* ((bolpos (point-at-bol))
7697 (ind (org-get-indentation))
7698 ind-down ind-up pos)
7699 (save-excursion
7700 (org-beginning-of-item-list)
7701 (skip-chars-backward "\n\r \t")
7702 (when (org-in-item-p)
7703 (org-beginning-of-item)
7704 (setq ind-up (org-get-indentation))))
7705 (setq pos (point))
7706 (save-excursion
7707 (cond
7708 ((and (condition-case nil (progn (org-previous-item) t)
7709 (error nil))
7710 (or (forward-char 1) t)
7711 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7712 (setq ind-down (org-get-indentation)))
7713 ((and (goto-char pos)
7714 (org-at-item-p))
7715 (goto-char (match-end 0))
7716 (skip-chars-forward " \t")
7717 (setq ind-down (current-column)))))
7718 (list ind ind-up ind-down)))
7720 ;;; The orgstruct minor mode
7722 ;; Define a minor mode which can be used in other modes in order to
7723 ;; integrate the org-mode structure editing commands.
7725 ;; This is really a hack, because the org-mode structure commands use
7726 ;; keys which normally belong to the major mode. Here is how it
7727 ;; works: The minor mode defines all the keys necessary to operate the
7728 ;; structure commands, but wraps the commands into a function which
7729 ;; tests if the cursor is currently at a headline or a plain list
7730 ;; item. If that is the case, the structure command is used,
7731 ;; temporarily setting many Org-mode variables like regular
7732 ;; expressions for filling etc. However, when any of those keys is
7733 ;; used at a different location, function uses `key-binding' to look
7734 ;; up if the key has an associated command in another currently active
7735 ;; keymap (minor modes, major mode, global), and executes that
7736 ;; command. There might be problems if any of the keys is otherwise
7737 ;; used as a prefix key.
7739 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7740 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7741 ;; addresses this by checking explicitly for both bindings.
7743 (defvar orgstruct-mode-map (make-sparse-keymap)
7744 "Keymap for the minor `orgstruct-mode'.")
7746 (defvar org-local-vars nil
7747 "List of local variables, for use by `orgstruct-mode'")
7749 ;;;###autoload
7750 (define-minor-mode orgstruct-mode
7751 "Toggle the minor more `orgstruct-mode'.
7752 This mode is for using Org-mode structure commands in other modes.
7753 The following key behave as if Org-mode was active, if the cursor
7754 is on a headline, or on a plain list item (both in the definition
7755 of Org-mode).
7757 M-up Move entry/item up
7758 M-down Move entry/item down
7759 M-left Promote
7760 M-right Demote
7761 M-S-up Move entry/item up
7762 M-S-down Move entry/item down
7763 M-S-left Promote subtree
7764 M-S-right Demote subtree
7765 M-q Fill paragraph and items like in Org-mode
7766 C-c ^ Sort entries
7767 C-c - Cycle list bullet
7768 TAB Cycle item visibility
7769 M-RET Insert new heading/item
7770 S-M-RET Insert new TODO heading / Chekbox item
7771 C-c C-c Set tags / toggle checkbox"
7772 nil " OrgStruct" nil
7773 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7775 ;;;###autoload
7776 (defun turn-on-orgstruct ()
7777 "Unconditionally turn on `orgstruct-mode'."
7778 (orgstruct-mode 1))
7780 ;;;###autoload
7781 (defun turn-on-orgstruct++ ()
7782 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7783 In addition to setting orgstruct-mode, this also exports all indentation and
7784 autofilling variables from org-mode into the buffer. Note that turning
7785 off orgstruct-mode will *not* remove these additional settings."
7786 (orgstruct-mode 1)
7787 (let (var val)
7788 (mapc
7789 (lambda (x)
7790 (when (string-match
7791 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7792 (symbol-name (car x)))
7793 (setq var (car x) val (nth 1 x))
7794 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7795 org-local-vars)))
7797 (defun orgstruct-error ()
7798 "Error when there is no default binding for a structure key."
7799 (interactive)
7800 (error "This key has no function outside structure elements"))
7802 (defun orgstruct-setup ()
7803 "Setup orgstruct keymaps."
7804 (let ((nfunc 0)
7805 (bindings
7806 (list
7807 '([(meta up)] org-metaup)
7808 '([(meta down)] org-metadown)
7809 '([(meta left)] org-metaleft)
7810 '([(meta right)] org-metaright)
7811 '([(meta shift up)] org-shiftmetaup)
7812 '([(meta shift down)] org-shiftmetadown)
7813 '([(meta shift left)] org-shiftmetaleft)
7814 '([(meta shift right)] org-shiftmetaright)
7815 '([(shift up)] org-shiftup)
7816 '([(shift down)] org-shiftdown)
7817 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7818 '("\M-q" fill-paragraph)
7819 '("\C-c^" org-sort)
7820 '("\C-c-" org-cycle-list-bullet)))
7821 elt key fun cmd)
7822 (while (setq elt (pop bindings))
7823 (setq nfunc (1+ nfunc))
7824 (setq key (org-key (car elt))
7825 fun (nth 1 elt)
7826 cmd (orgstruct-make-binding fun nfunc key))
7827 (org-defkey orgstruct-mode-map key cmd))
7829 ;; Special treatment needed for TAB and RET
7830 (org-defkey orgstruct-mode-map [(tab)]
7831 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7832 (org-defkey orgstruct-mode-map "\C-i"
7833 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7835 (org-defkey orgstruct-mode-map "\M-\C-m"
7836 (orgstruct-make-binding 'org-insert-heading 105
7837 "\M-\C-m" [(meta return)]))
7838 (org-defkey orgstruct-mode-map [(meta return)]
7839 (orgstruct-make-binding 'org-insert-heading 106
7840 [(meta return)] "\M-\C-m"))
7842 (org-defkey orgstruct-mode-map [(shift meta return)]
7843 (orgstruct-make-binding 'org-insert-todo-heading 107
7844 [(meta return)] "\M-\C-m"))
7846 (unless org-local-vars
7847 (setq org-local-vars (org-get-local-variables)))
7851 (defun orgstruct-make-binding (fun n &rest keys)
7852 "Create a function for binding in the structure minor mode.
7853 FUN is the command to call inside a table. N is used to create a unique
7854 command name. KEYS are keys that should be checked in for a command
7855 to execute outside of tables."
7856 (eval
7857 (list 'defun
7858 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7859 '(arg)
7860 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7861 "Outside of structure, run the binding of `"
7862 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7863 "'.")
7864 '(interactive "p")
7865 (list 'if
7866 '(org-context-p 'headline 'item)
7867 (list 'org-run-like-in-org-mode (list 'quote fun))
7868 (list 'let '(orgstruct-mode)
7869 (list 'call-interactively
7870 (append '(or)
7871 (mapcar (lambda (k)
7872 (list 'key-binding k))
7873 keys)
7874 '('orgstruct-error))))))))
7876 (defun org-context-p (&rest contexts)
7877 "Check if local context is and of CONTEXTS.
7878 Possible values in the list of contexts are `table', `headline', and `item'."
7879 (let ((pos (point)))
7880 (goto-char (point-at-bol))
7881 (prog1 (or (and (memq 'table contexts)
7882 (looking-at "[ \t]*|"))
7883 (and (memq 'headline contexts)
7884 (looking-at "\\*+"))
7885 (and (memq 'item contexts)
7886 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7887 (goto-char pos))))
7889 (defun org-get-local-variables ()
7890 "Return a list of all local variables in an org-mode buffer."
7891 (let (varlist)
7892 (with-current-buffer (get-buffer-create "*Org tmp*")
7893 (erase-buffer)
7894 (org-mode)
7895 (setq varlist (buffer-local-variables)))
7896 (kill-buffer "*Org tmp*")
7897 (delq nil
7898 (mapcar
7899 (lambda (x)
7900 (setq x
7901 (if (symbolp x)
7902 (list x)
7903 (list (car x) (list 'quote (cdr x)))))
7904 (if (string-match
7905 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7906 (symbol-name (car x)))
7907 x nil))
7908 varlist))))
7910 ;;;###autoload
7911 (defun org-run-like-in-org-mode (cmd)
7912 (unless org-local-vars
7913 (setq org-local-vars (org-get-local-variables)))
7914 (eval (list 'let org-local-vars
7915 (list 'call-interactively (list 'quote cmd)))))
7917 ;;;; Archiving
7919 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7921 (defun org-archive-subtree (&optional find-done)
7922 "Move the current subtree to the archive.
7923 The archive can be a certain top-level heading in the current file, or in
7924 a different file. The tree will be moved to that location, the subtree
7925 heading be marked DONE, and the current time will be added.
7927 When called with prefix argument FIND-DONE, find whole trees without any
7928 open TODO items and archive them (after getting confirmation from the user).
7929 If the cursor is not at a headline when this comand is called, try all level
7930 1 trees. If the cursor is on a headline, only try the direct children of
7931 this heading."
7932 (interactive "P")
7933 (if find-done
7934 (org-archive-all-done)
7935 ;; Save all relevant TODO keyword-relatex variables
7937 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7938 (tr-org-todo-keywords-1 org-todo-keywords-1)
7939 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7940 (tr-org-done-keywords org-done-keywords)
7941 (tr-org-todo-regexp org-todo-regexp)
7942 (tr-org-todo-line-regexp org-todo-line-regexp)
7943 (tr-org-odd-levels-only org-odd-levels-only)
7944 (this-buffer (current-buffer))
7945 (org-archive-location org-archive-location)
7946 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7947 ;; start of variables that will be used for saving context
7948 ;; The compiler complains about them - keep them anyway!
7949 (file (abbreviate-file-name (buffer-file-name)))
7950 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7951 (time (format-time-string
7952 (substring (cdr org-time-stamp-formats) 1 -1)
7953 (current-time)))
7954 afile heading buffer level newfile-p
7955 category todo priority
7956 ;; start of variables that will be used for savind context
7957 ltags itags prop)
7959 ;; Try to find a local archive location
7960 (save-excursion
7961 (save-restriction
7962 (widen)
7963 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7964 (if (and prop (string-match "\\S-" prop))
7965 (setq org-archive-location prop)
7966 (if (or (re-search-backward re nil t)
7967 (re-search-forward re nil t))
7968 (setq org-archive-location (match-string 1))))))
7970 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7971 (progn
7972 (setq afile (format (match-string 1 org-archive-location)
7973 (file-name-nondirectory buffer-file-name))
7974 heading (match-string 2 org-archive-location)))
7975 (error "Invalid `org-archive-location'"))
7976 (if (> (length afile) 0)
7977 (setq newfile-p (not (file-exists-p afile))
7978 buffer (find-file-noselect afile))
7979 (setq buffer (current-buffer)))
7980 (unless buffer
7981 (error "Cannot access file \"%s\"" afile))
7982 (if (and (> (length heading) 0)
7983 (string-match "^\\*+" heading))
7984 (setq level (match-end 0))
7985 (setq heading nil level 0))
7986 (save-excursion
7987 (org-back-to-heading t)
7988 ;; Get context information that will be lost by moving the tree
7989 (org-refresh-category-properties)
7990 (setq category (org-get-category)
7991 todo (and (looking-at org-todo-line-regexp)
7992 (match-string 2))
7993 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7994 ltags (org-get-tags)
7995 itags (org-delete-all ltags (org-get-tags-at)))
7996 (setq ltags (mapconcat 'identity ltags " ")
7997 itags (mapconcat 'identity itags " "))
7998 ;; We first only copy, in case something goes wrong
7999 ;; we need to protect this-command, to avoid kill-region sets it,
8000 ;; which would lead to duplication of subtrees
8001 (let (this-command) (org-copy-subtree))
8002 (set-buffer buffer)
8003 ;; Enforce org-mode for the archive buffer
8004 (if (not (org-mode-p))
8005 ;; Force the mode for future visits.
8006 (let ((org-insert-mode-line-in-empty-file t)
8007 (org-inhibit-startup t))
8008 (call-interactively 'org-mode)))
8009 (when newfile-p
8010 (goto-char (point-max))
8011 (insert (format "\nArchived entries from file %s\n\n"
8012 (buffer-file-name this-buffer))))
8013 ;; Force the TODO keywords of the original buffer
8014 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8015 (org-todo-keywords-1 tr-org-todo-keywords-1)
8016 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8017 (org-done-keywords tr-org-done-keywords)
8018 (org-todo-regexp tr-org-todo-regexp)
8019 (org-todo-line-regexp tr-org-todo-line-regexp)
8020 (org-odd-levels-only
8021 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8022 org-odd-levels-only
8023 tr-org-odd-levels-only)))
8024 (goto-char (point-min))
8025 (if heading
8026 (progn
8027 (if (re-search-forward
8028 (concat "^" (regexp-quote heading)
8029 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8030 nil t)
8031 (goto-char (match-end 0))
8032 ;; Heading not found, just insert it at the end
8033 (goto-char (point-max))
8034 (or (bolp) (insert "\n"))
8035 (insert "\n" heading "\n")
8036 (end-of-line 0))
8037 ;; Make the subtree visible
8038 (show-subtree)
8039 (org-end-of-subtree t)
8040 (skip-chars-backward " \t\r\n")
8041 (and (looking-at "[ \t\r\n]*")
8042 (replace-match "\n\n")))
8043 ;; No specific heading, just go to end of file.
8044 (goto-char (point-max)) (insert "\n"))
8045 ;; Paste
8046 (org-paste-subtree (org-get-legal-level level 1))
8048 ;; Mark the entry as done
8049 (when (and org-archive-mark-done
8050 (looking-at org-todo-line-regexp)
8051 (or (not (match-end 2))
8052 (not (member (match-string 2) org-done-keywords))))
8053 (let (org-log-done org-todo-log-states)
8054 (org-todo
8055 (car (or (member org-archive-mark-done org-done-keywords)
8056 org-done-keywords)))))
8058 ;; Add the context info
8059 (when org-archive-save-context-info
8060 (let ((l org-archive-save-context-info) e n v)
8061 (while (setq e (pop l))
8062 (when (and (setq v (symbol-value e))
8063 (stringp v) (string-match "\\S-" v))
8064 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8065 (org-entry-put (point) n v)))))
8067 ;; Save the buffer, if it is not the same buffer.
8068 (if (not (eq this-buffer buffer)) (save-buffer))))
8069 ;; Here we are back in the original buffer. Everything seems to have
8070 ;; worked. So now cut the tree and finish up.
8071 (let (this-command) (org-cut-subtree))
8072 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8073 (message "Subtree archived %s"
8074 (if (eq this-buffer buffer)
8075 (concat "under heading: " heading)
8076 (concat "in file: " (abbreviate-file-name afile)))))))
8078 (defun org-refresh-category-properties ()
8079 "Refresh category text properties in teh buffer."
8080 (let ((def-cat (cond
8081 ((null org-category)
8082 (if buffer-file-name
8083 (file-name-sans-extension
8084 (file-name-nondirectory buffer-file-name))
8085 "???"))
8086 ((symbolp org-category) (symbol-name org-category))
8087 (t org-category)))
8088 beg end cat pos optionp)
8089 (org-unmodified
8090 (save-excursion
8091 (save-restriction
8092 (widen)
8093 (goto-char (point-min))
8094 (put-text-property (point) (point-max) 'org-category def-cat)
8095 (while (re-search-forward
8096 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8097 (setq pos (match-end 0)
8098 optionp (equal (char-after (match-beginning 0)) ?#)
8099 cat (org-trim (match-string 2)))
8100 (if optionp
8101 (setq beg (point-at-bol) end (point-max))
8102 (org-back-to-heading t)
8103 (setq beg (point) end (org-end-of-subtree t t)))
8104 (put-text-property beg end 'org-category cat)
8105 (goto-char pos)))))))
8107 (defun org-archive-all-done (&optional tag)
8108 "Archive sublevels of the current tree without open TODO items.
8109 If the cursor is not on a headline, try all level 1 trees. If
8110 it is on a headline, try all direct children.
8111 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8112 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8113 (rea (concat ".*:" org-archive-tag ":"))
8114 (begm (make-marker))
8115 (endm (make-marker))
8116 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8117 "Move subtree to archive (no open TODO items)? "))
8118 beg end (cntarch 0))
8119 (if (org-on-heading-p)
8120 (progn
8121 (setq re1 (concat "^" (regexp-quote
8122 (make-string
8123 (1+ (- (match-end 0) (match-beginning 0) 1))
8124 ?*))
8125 " "))
8126 (move-marker begm (point))
8127 (move-marker endm (org-end-of-subtree t)))
8128 (setq re1 "^* ")
8129 (move-marker begm (point-min))
8130 (move-marker endm (point-max)))
8131 (save-excursion
8132 (goto-char begm)
8133 (while (re-search-forward re1 endm t)
8134 (setq beg (match-beginning 0)
8135 end (save-excursion (org-end-of-subtree t) (point)))
8136 (goto-char beg)
8137 (if (re-search-forward re end t)
8138 (goto-char end)
8139 (goto-char beg)
8140 (if (and (or (not tag) (not (looking-at rea)))
8141 (y-or-n-p question))
8142 (progn
8143 (if tag
8144 (org-toggle-tag org-archive-tag 'on)
8145 (org-archive-subtree))
8146 (setq cntarch (1+ cntarch)))
8147 (goto-char end)))))
8148 (message "%d trees archived" cntarch)))
8150 (defun org-cycle-hide-drawers (state)
8151 "Re-hide all drawers after a visibility state change."
8152 (when (and (org-mode-p)
8153 (not (memq state '(overview folded))))
8154 (save-excursion
8155 (let* ((globalp (memq state '(contents all)))
8156 (beg (if globalp (point-min) (point)))
8157 (end (if globalp (point-max) (org-end-of-subtree t))))
8158 (goto-char beg)
8159 (while (re-search-forward org-drawer-regexp end t)
8160 (org-flag-drawer t))))))
8162 (defun org-flag-drawer (flag)
8163 (save-excursion
8164 (beginning-of-line 1)
8165 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8166 (let ((b (match-end 0))
8167 (outline-regexp org-outline-regexp))
8168 (if (re-search-forward
8169 "^[ \t]*:END:"
8170 (save-excursion (outline-next-heading) (point)) t)
8171 (outline-flag-region b (point-at-eol) flag)
8172 (error ":END: line missing"))))))
8174 (defun org-cycle-hide-archived-subtrees (state)
8175 "Re-hide all archived subtrees after a visibility state change."
8176 (when (and (not org-cycle-open-archived-trees)
8177 (not (memq state '(overview folded))))
8178 (save-excursion
8179 (let* ((globalp (memq state '(contents all)))
8180 (beg (if globalp (point-min) (point)))
8181 (end (if globalp (point-max) (org-end-of-subtree t))))
8182 (org-hide-archived-subtrees beg end)
8183 (goto-char beg)
8184 (if (looking-at (concat ".*:" org-archive-tag ":"))
8185 (message "%s" (substitute-command-keys
8186 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8188 (defun org-force-cycle-archived ()
8189 "Cycle subtree even if it is archived."
8190 (interactive)
8191 (setq this-command 'org-cycle)
8192 (let ((org-cycle-open-archived-trees t))
8193 (call-interactively 'org-cycle)))
8195 (defun org-hide-archived-subtrees (beg end)
8196 "Re-hide all archived subtrees after a visibility state change."
8197 (save-excursion
8198 (let* ((re (concat ":" org-archive-tag ":")))
8199 (goto-char beg)
8200 (while (re-search-forward re end t)
8201 (and (org-on-heading-p) (hide-subtree))
8202 (org-end-of-subtree t)))))
8204 (defun org-toggle-tag (tag &optional onoff)
8205 "Toggle the tag TAG for the current line.
8206 If ONOFF is `on' or `off', don't toggle but set to this state."
8207 (unless (org-on-heading-p t) (error "Not on headling"))
8208 (let (res current)
8209 (save-excursion
8210 (beginning-of-line)
8211 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8212 (point-at-eol) t)
8213 (progn
8214 (setq current (match-string 1))
8215 (replace-match ""))
8216 (setq current ""))
8217 (setq current (nreverse (org-split-string current ":")))
8218 (cond
8219 ((eq onoff 'on)
8220 (setq res t)
8221 (or (member tag current) (push tag current)))
8222 ((eq onoff 'off)
8223 (or (not (member tag current)) (setq current (delete tag current))))
8224 (t (if (member tag current)
8225 (setq current (delete tag current))
8226 (setq res t)
8227 (push tag current))))
8228 (end-of-line 1)
8229 (if current
8230 (progn
8231 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8232 (org-set-tags nil t))
8233 (delete-horizontal-space))
8234 (run-hooks 'org-after-tags-change-hook))
8235 res))
8237 (defun org-toggle-archive-tag (&optional arg)
8238 "Toggle the archive tag for the current headline.
8239 With prefix ARG, check all children of current headline and offer tagging
8240 the children that do not contain any open TODO items."
8241 (interactive "P")
8242 (if arg
8243 (org-archive-all-done 'tag)
8244 (let (set)
8245 (save-excursion
8246 (org-back-to-heading t)
8247 (setq set (org-toggle-tag org-archive-tag))
8248 (when set (hide-subtree)))
8249 (and set (beginning-of-line 1))
8250 (message "Subtree %s" (if set "archived" "unarchived")))))
8253 ;;;; Tables
8255 ;;; The table editor
8257 ;; Watch out: Here we are talking about two different kind of tables.
8258 ;; Most of the code is for the tables created with the Org-mode table editor.
8259 ;; Sometimes, we talk about tables created and edited with the table.el
8260 ;; Emacs package. We call the former org-type tables, and the latter
8261 ;; table.el-type tables.
8263 (defun org-before-change-function (beg end)
8264 "Every change indicates that a table might need an update."
8265 (setq org-table-may-need-update t))
8267 (defconst org-table-line-regexp "^[ \t]*|"
8268 "Detects an org-type table line.")
8269 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8270 "Detects an org-type table line.")
8271 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8272 "Detects a table line marked for automatic recalculation.")
8273 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8274 "Detects a table line marked for automatic recalculation.")
8275 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8276 "Detects a table line marked for automatic recalculation.")
8277 (defconst org-table-hline-regexp "^[ \t]*|-"
8278 "Detects an org-type table hline.")
8279 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8280 "Detects a table-type table hline.")
8281 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8282 "Detects an org-type or table-type table.")
8283 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8284 "Searching from within a table (any type) this finds the first line
8285 outside the table.")
8286 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8287 "Searching from within a table (any type) this finds the first line
8288 outside the table.")
8290 (defvar org-table-last-highlighted-reference nil)
8291 (defvar org-table-formula-history nil)
8293 (defvar org-table-column-names nil
8294 "Alist with column names, derived from the `!' line.")
8295 (defvar org-table-column-name-regexp nil
8296 "Regular expression matching the current column names.")
8297 (defvar org-table-local-parameters nil
8298 "Alist with parameter names, derived from the `$' line.")
8299 (defvar org-table-named-field-locations nil
8300 "Alist with locations of named fields.")
8302 (defvar org-table-current-line-types nil
8303 "Table row types, non-nil only for the duration of a comand.")
8304 (defvar org-table-current-begin-line nil
8305 "Table begin line, non-nil only for the duration of a comand.")
8306 (defvar org-table-current-begin-pos nil
8307 "Table begin position, non-nil only for the duration of a comand.")
8308 (defvar org-table-dlines nil
8309 "Vector of data line line numbers in the current table.")
8310 (defvar org-table-hlines nil
8311 "Vector of hline line numbers in the current table.")
8313 (defconst org-table-range-regexp
8314 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8315 ;; 1 2 3 4 5
8316 "Regular expression for matching ranges in formulas.")
8318 (defconst org-table-range-regexp2
8319 (concat
8320 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8321 "\\.\\."
8322 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8323 "Match a range for reference display.")
8325 (defconst org-table-translate-regexp
8326 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8327 "Match a reference that needs translation, for reference display.")
8329 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8331 (defun org-table-create-with-table.el ()
8332 "Use the table.el package to insert a new table.
8333 If there is already a table at point, convert between Org-mode tables
8334 and table.el tables."
8335 (interactive)
8336 (require 'table)
8337 (cond
8338 ((org-at-table.el-p)
8339 (if (y-or-n-p "Convert table to Org-mode table? ")
8340 (org-table-convert)))
8341 ((org-at-table-p)
8342 (if (y-or-n-p "Convert table to table.el table? ")
8343 (org-table-convert)))
8344 (t (call-interactively 'table-insert))))
8346 (defun org-table-create-or-convert-from-region (arg)
8347 "Convert region to table, or create an empty table.
8348 If there is an active region, convert it to a table, using the function
8349 `org-table-convert-region'. See the documentation of that function
8350 to learn how the prefix argument is interpreted to determine the field
8351 separator.
8352 If there is no such region, create an empty table with `org-table-create'."
8353 (interactive "P")
8354 (if (org-region-active-p)
8355 (org-table-convert-region (region-beginning) (region-end) arg)
8356 (org-table-create arg)))
8358 (defun org-table-create (&optional size)
8359 "Query for a size and insert a table skeleton.
8360 SIZE is a string Columns x Rows like for example \"3x2\"."
8361 (interactive "P")
8362 (unless size
8363 (setq size (read-string
8364 (concat "Table size Columns x Rows [e.g. "
8365 org-table-default-size "]: ")
8366 "" nil org-table-default-size)))
8368 (let* ((pos (point))
8369 (indent (make-string (current-column) ?\ ))
8370 (split (org-split-string size " *x *"))
8371 (rows (string-to-number (nth 1 split)))
8372 (columns (string-to-number (car split)))
8373 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8374 "\n")))
8375 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8376 (point-at-bol) (point)))
8377 (beginning-of-line 1)
8378 (newline))
8379 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8380 (dotimes (i rows) (insert line))
8381 (goto-char pos)
8382 (if (> rows 1)
8383 ;; Insert a hline after the first row.
8384 (progn
8385 (end-of-line 1)
8386 (insert "\n|-")
8387 (goto-char pos)))
8388 (org-table-align)))
8390 (defun org-table-convert-region (beg0 end0 &optional separator)
8391 "Convert region to a table.
8392 The region goes from BEG0 to END0, but these borders will be moved
8393 slightly, to make sure a beginning of line in the first line is included.
8395 SEPARATOR specifies the field separator in the lines. It can have the
8396 following values:
8398 '(4) Use the comma as a field separator
8399 '(16) Use a TAB as field separator
8400 integer When a number, use that many spaces as field separator
8401 nil When nil, the command tries to be smart and figure out the
8402 separator in the following way:
8403 - when each line contains a TAB, assume TAB-separated material
8404 - when each line contains a comme, assume CSV material
8405 - else, assume one or more SPACE charcters as separator."
8406 (interactive "rP")
8407 (let* ((beg (min beg0 end0))
8408 (end (max beg0 end0))
8410 (goto-char beg)
8411 (beginning-of-line 1)
8412 (setq beg (move-marker (make-marker) (point)))
8413 (goto-char end)
8414 (if (bolp) (backward-char 1) (end-of-line 1))
8415 (setq end (move-marker (make-marker) (point)))
8416 ;; Get the right field separator
8417 (unless separator
8418 (goto-char beg)
8419 (setq separator
8420 (cond
8421 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8422 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8423 (t 1))))
8424 (setq re (cond
8425 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8426 ((equal separator '(16)) "^\\|\t")
8427 ((integerp separator)
8428 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8429 (t (error "This should not happen"))))
8430 (goto-char beg)
8431 (while (re-search-forward re end t)
8432 (replace-match "| " t t))
8433 (goto-char beg)
8434 (insert " ")
8435 (org-table-align)))
8437 (defun org-table-import (file arg)
8438 "Import FILE as a table.
8439 The file is assumed to be tab-separated. Such files can be produced by most
8440 spreadsheet and database applications. If no tabs (at least one per line)
8441 are found, lines will be split on whitespace into fields."
8442 (interactive "f\nP")
8443 (or (bolp) (newline))
8444 (let ((beg (point))
8445 (pm (point-max)))
8446 (insert-file-contents file)
8447 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8449 (defun org-table-export ()
8450 "Export table as a tab-separated file.
8451 Such a file can be imported into a spreadsheet program like Excel."
8452 (interactive)
8453 (let* ((beg (org-table-begin))
8454 (end (org-table-end))
8455 (table (buffer-substring beg end))
8456 (file (read-file-name "Export table to: "))
8457 buf)
8458 (unless (or (not (file-exists-p file))
8459 (y-or-n-p (format "Overwrite file %s? " file)))
8460 (error "Abort"))
8461 (with-current-buffer (find-file-noselect file)
8462 (setq buf (current-buffer))
8463 (erase-buffer)
8464 (fundamental-mode)
8465 (insert table)
8466 (goto-char (point-min))
8467 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8468 (replace-match "" t t)
8469 (end-of-line 1))
8470 (goto-char (point-min))
8471 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8472 (replace-match "" t t)
8473 (goto-char (min (1+ (point)) (point-max))))
8474 (goto-char (point-min))
8475 (while (re-search-forward "^-[-+]*$" nil t)
8476 (replace-match "")
8477 (if (looking-at "\n")
8478 (delete-char 1)))
8479 (goto-char (point-min))
8480 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8481 (replace-match "\t" t t))
8482 (save-buffer))
8483 (kill-buffer buf)))
8485 (defvar org-table-aligned-begin-marker (make-marker)
8486 "Marker at the beginning of the table last aligned.
8487 Used to check if cursor still is in that table, to minimize realignment.")
8488 (defvar org-table-aligned-end-marker (make-marker)
8489 "Marker at the end of the table last aligned.
8490 Used to check if cursor still is in that table, to minimize realignment.")
8491 (defvar org-table-last-alignment nil
8492 "List of flags for flushright alignment, from the last re-alignment.
8493 This is being used to correctly align a single field after TAB or RET.")
8494 (defvar org-table-last-column-widths nil
8495 "List of max width of fields in each column.
8496 This is being used to correctly align a single field after TAB or RET.")
8497 (defvar org-table-overlay-coordinates nil
8498 "Overlay coordinates after each align of a table.")
8499 (make-variable-buffer-local 'org-table-overlay-coordinates)
8501 (defvar org-last-recalc-line nil)
8502 (defconst org-narrow-column-arrow "=>"
8503 "Used as display property in narrowed table columns.")
8505 (defun org-table-align ()
8506 "Align the table at point by aligning all vertical bars."
8507 (interactive)
8508 (let* (
8509 ;; Limits of table
8510 (beg (org-table-begin))
8511 (end (org-table-end))
8512 ;; Current cursor position
8513 (linepos (org-current-line))
8514 (colpos (org-table-current-column))
8515 (winstart (window-start))
8516 (winstartline (org-current-line (min winstart (1- (point-max)))))
8517 lines (new "") lengths l typenums ty fields maxfields i
8518 column
8519 (indent "") cnt frac
8520 rfmt hfmt
8521 (spaces '(1 . 1))
8522 (sp1 (car spaces))
8523 (sp2 (cdr spaces))
8524 (rfmt1 (concat
8525 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8526 (hfmt1 (concat
8527 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8528 emptystrings links dates emph narrow fmax f1 len c e)
8529 (untabify beg end)
8530 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8531 ;; Check if we have links or dates
8532 (goto-char beg)
8533 (setq links (re-search-forward org-bracket-link-regexp end t))
8534 (goto-char beg)
8535 (setq emph (and org-hide-emphasis-markers
8536 (re-search-forward org-emph-re end t)))
8537 (goto-char beg)
8538 (setq dates (and org-display-custom-times
8539 (re-search-forward org-ts-regexp-both end t)))
8540 ;; Make sure the link properties are right
8541 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8542 ;; Make sure the date properties are right
8543 (when dates (goto-char beg) (while (org-activate-dates end)))
8544 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8546 ;; Check if we are narrowing any columns
8547 (goto-char beg)
8548 (setq narrow (and org-format-transports-properties-p
8549 (re-search-forward "<[0-9]+>" end t)))
8550 ;; Get the rows
8551 (setq lines (org-split-string
8552 (buffer-substring beg end) "\n"))
8553 ;; Store the indentation of the first line
8554 (if (string-match "^ *" (car lines))
8555 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8556 ;; Mark the hlines by setting the corresponding element to nil
8557 ;; At the same time, we remove trailing space.
8558 (setq lines (mapcar (lambda (l)
8559 (if (string-match "^ *|-" l)
8561 (if (string-match "[ \t]+$" l)
8562 (substring l 0 (match-beginning 0))
8563 l)))
8564 lines))
8565 ;; Get the data fields by splitting the lines.
8566 (setq fields (mapcar
8567 (lambda (l)
8568 (org-split-string l " *| *"))
8569 (delq nil (copy-sequence lines))))
8570 ;; How many fields in the longest line?
8571 (condition-case nil
8572 (setq maxfields (apply 'max (mapcar 'length fields)))
8573 (error
8574 (kill-region beg end)
8575 (org-table-create org-table-default-size)
8576 (error "Empty table - created default table")))
8577 ;; A list of empty strings to fill any short rows on output
8578 (setq emptystrings (make-list maxfields ""))
8579 ;; Check for special formatting.
8580 (setq i -1)
8581 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8582 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8583 ;; Check if there is an explicit width specified
8584 (when narrow
8585 (setq c column fmax nil)
8586 (while c
8587 (setq e (pop c))
8588 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8589 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8590 ;; Find fields that are wider than fmax, and shorten them
8591 (when fmax
8592 (loop for xx in column do
8593 (when (and (stringp xx)
8594 (> (org-string-width xx) fmax))
8595 (org-add-props xx nil
8596 'help-echo
8597 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8598 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8599 (unless (> f1 1)
8600 (error "Cannot narrow field starting with wide link \"%s\""
8601 (match-string 0 xx)))
8602 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8603 (add-text-properties (- f1 2) f1
8604 (list 'display org-narrow-column-arrow)
8605 xx)))))
8606 ;; Get the maximum width for each column
8607 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8608 ;; Get the fraction of numbers, to decide about alignment of the column
8609 (setq cnt 0 frac 0.0)
8610 (loop for x in column do
8611 (if (equal x "")
8613 (setq frac ( / (+ (* frac cnt)
8614 (if (string-match org-table-number-regexp x) 1 0))
8615 (setq cnt (1+ cnt))))))
8616 (push (>= frac org-table-number-fraction) typenums))
8617 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8619 ;; Store the alignment of this table, for later editing of single fields
8620 (setq org-table-last-alignment typenums
8621 org-table-last-column-widths lengths)
8623 ;; With invisible characters, `format' does not get the field width right
8624 ;; So we need to make these fields wide by hand.
8625 (when (or links emph)
8626 (loop for i from 0 upto (1- maxfields) do
8627 (setq len (nth i lengths))
8628 (loop for j from 0 upto (1- (length fields)) do
8629 (setq c (nthcdr i (car (nthcdr j fields))))
8630 (if (and (stringp (car c))
8631 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8632 ; (string-match org-bracket-link-regexp (car c))
8633 (< (org-string-width (car c)) len))
8634 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8636 ;; Compute the formats needed for output of the table
8637 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8638 (while (setq l (pop lengths))
8639 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8640 (setq rfmt (concat rfmt (format rfmt1 ty l))
8641 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8642 (setq rfmt (concat rfmt "\n")
8643 hfmt (concat (substring hfmt 0 -1) "|\n"))
8645 (setq new (mapconcat
8646 (lambda (l)
8647 (if l (apply 'format rfmt
8648 (append (pop fields) emptystrings))
8649 hfmt))
8650 lines ""))
8651 ;; Replace the old one
8652 (delete-region beg end)
8653 (move-marker end nil)
8654 (move-marker org-table-aligned-begin-marker (point))
8655 (insert new)
8656 (move-marker org-table-aligned-end-marker (point))
8657 (when (and orgtbl-mode (not (org-mode-p)))
8658 (goto-char org-table-aligned-begin-marker)
8659 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8660 ;; Try to move to the old location
8661 (goto-line winstartline)
8662 (setq winstart (point-at-bol))
8663 (goto-line linepos)
8664 (set-window-start (selected-window) winstart 'noforce)
8665 (org-table-goto-column colpos)
8666 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8667 (setq org-table-may-need-update nil)
8670 (defun org-string-width (s)
8671 "Compute width of string, ignoring invisible characters.
8672 This ignores character with invisibility property `org-link', and also
8673 characters with property `org-cwidth', because these will become invisible
8674 upon the next fontification round."
8675 (let (b l)
8676 (when (or (eq t buffer-invisibility-spec)
8677 (assq 'org-link buffer-invisibility-spec))
8678 (while (setq b (text-property-any 0 (length s)
8679 'invisible 'org-link s))
8680 (setq s (concat (substring s 0 b)
8681 (substring s (or (next-single-property-change
8682 b 'invisible s) (length s)))))))
8683 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8684 (setq s (concat (substring s 0 b)
8685 (substring s (or (next-single-property-change
8686 b 'org-cwidth s) (length s))))))
8687 (setq l (string-width s) b -1)
8688 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8689 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8692 (defun org-table-begin (&optional table-type)
8693 "Find the beginning of the table and return its position.
8694 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8695 (save-excursion
8696 (if (not (re-search-backward
8697 (if table-type org-table-any-border-regexp
8698 org-table-border-regexp)
8699 nil t))
8700 (progn (goto-char (point-min)) (point))
8701 (goto-char (match-beginning 0))
8702 (beginning-of-line 2)
8703 (point))))
8705 (defun org-table-end (&optional table-type)
8706 "Find the end of the table and return its position.
8707 With argument TABLE-TYPE, go to the end of a table.el-type table."
8708 (save-excursion
8709 (if (not (re-search-forward
8710 (if table-type org-table-any-border-regexp
8711 org-table-border-regexp)
8712 nil t))
8713 (goto-char (point-max))
8714 (goto-char (match-beginning 0)))
8715 (point-marker)))
8717 (defun org-table-justify-field-maybe (&optional new)
8718 "Justify the current field, text to left, number to right.
8719 Optional argument NEW may specify text to replace the current field content."
8720 (cond
8721 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8722 ((org-at-table-hline-p))
8723 ((and (not new)
8724 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8725 (current-buffer)))
8726 (< (point) org-table-aligned-begin-marker)
8727 (>= (point) org-table-aligned-end-marker)))
8728 ;; This is not the same table, force a full re-align
8729 (setq org-table-may-need-update t))
8730 (t ;; realign the current field, based on previous full realign
8731 (let* ((pos (point)) s
8732 (col (org-table-current-column))
8733 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8734 l f n o e)
8735 (when (> col 0)
8736 (skip-chars-backward "^|\n")
8737 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8738 (progn
8739 (setq s (match-string 1)
8740 o (match-string 0)
8741 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8742 e (not (= (match-beginning 2) (match-end 2))))
8743 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8744 l (if e "|" (setq org-table-may-need-update t) ""))
8745 n (format f s))
8746 (if new
8747 (if (<= (length new) l) ;; FIXME: length -> str-width?
8748 (setq n (format f new))
8749 (setq n (concat new "|") org-table-may-need-update t)))
8750 (or (equal n o)
8751 (let (org-table-may-need-update)
8752 (replace-match n t t))))
8753 (setq org-table-may-need-update t))
8754 (goto-char pos))))))
8756 (defun org-table-next-field ()
8757 "Go to the next field in the current table, creating new lines as needed.
8758 Before doing so, re-align the table if necessary."
8759 (interactive)
8760 (org-table-maybe-eval-formula)
8761 (org-table-maybe-recalculate-line)
8762 (if (and org-table-automatic-realign
8763 org-table-may-need-update)
8764 (org-table-align))
8765 (let ((end (org-table-end)))
8766 (if (org-at-table-hline-p)
8767 (end-of-line 1))
8768 (condition-case nil
8769 (progn
8770 (re-search-forward "|" end)
8771 (if (looking-at "[ \t]*$")
8772 (re-search-forward "|" end))
8773 (if (and (looking-at "-")
8774 org-table-tab-jumps-over-hlines
8775 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8776 (goto-char (match-beginning 1)))
8777 (if (looking-at "-")
8778 (progn
8779 (beginning-of-line 0)
8780 (org-table-insert-row 'below))
8781 (if (looking-at " ") (forward-char 1))))
8782 (error
8783 (org-table-insert-row 'below)))))
8785 (defun org-table-previous-field ()
8786 "Go to the previous field in the table.
8787 Before doing so, re-align the table if necessary."
8788 (interactive)
8789 (org-table-justify-field-maybe)
8790 (org-table-maybe-recalculate-line)
8791 (if (and org-table-automatic-realign
8792 org-table-may-need-update)
8793 (org-table-align))
8794 (if (org-at-table-hline-p)
8795 (end-of-line 1))
8796 (re-search-backward "|" (org-table-begin))
8797 (re-search-backward "|" (org-table-begin))
8798 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8799 (re-search-backward "|" (org-table-begin)))
8800 (if (looking-at "| ?")
8801 (goto-char (match-end 0))))
8803 (defun org-table-next-row ()
8804 "Go to the next row (same column) in the current table.
8805 Before doing so, re-align the table if necessary."
8806 (interactive)
8807 (org-table-maybe-eval-formula)
8808 (org-table-maybe-recalculate-line)
8809 (if (or (looking-at "[ \t]*$")
8810 (save-excursion (skip-chars-backward " \t") (bolp)))
8811 (newline)
8812 (if (and org-table-automatic-realign
8813 org-table-may-need-update)
8814 (org-table-align))
8815 (let ((col (org-table-current-column)))
8816 (beginning-of-line 2)
8817 (if (or (not (org-at-table-p))
8818 (org-at-table-hline-p))
8819 (progn
8820 (beginning-of-line 0)
8821 (org-table-insert-row 'below)))
8822 (org-table-goto-column col)
8823 (skip-chars-backward "^|\n\r")
8824 (if (looking-at " ") (forward-char 1)))))
8826 (defun org-table-copy-down (n)
8827 "Copy a field down in the current column.
8828 If the field at the cursor is empty, copy into it the content of the nearest
8829 non-empty field above. With argument N, use the Nth non-empty field.
8830 If the current field is not empty, it is copied down to the next row, and
8831 the cursor is moved with it. Therefore, repeating this command causes the
8832 column to be filled row-by-row.
8833 If the variable `org-table-copy-increment' is non-nil and the field is an
8834 integer or a timestamp, it will be incremented while copying. In the case of
8835 a timestamp, if the cursor is on the year, change the year. If it is on the
8836 month or the day, change that. Point will stay on the current date field
8837 in order to easily repeat the interval."
8838 (interactive "p")
8839 (let* ((colpos (org-table-current-column))
8840 (col (current-column))
8841 (field (org-table-get-field))
8842 (non-empty (string-match "[^ \t]" field))
8843 (beg (org-table-begin))
8844 txt)
8845 (org-table-check-inside-data-field)
8846 (if non-empty
8847 (progn
8848 (setq txt (org-trim field))
8849 (org-table-next-row)
8850 (org-table-blank-field))
8851 (save-excursion
8852 (setq txt
8853 (catch 'exit
8854 (while (progn (beginning-of-line 1)
8855 (re-search-backward org-table-dataline-regexp
8856 beg t))
8857 (org-table-goto-column colpos t)
8858 (if (and (looking-at
8859 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8860 (= (setq n (1- n)) 0))
8861 (throw 'exit (match-string 1))))))))
8862 (if txt
8863 (progn
8864 (if (and org-table-copy-increment
8865 (string-match "^[0-9]+$" txt))
8866 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8867 (insert txt)
8868 (move-to-column col)
8869 (if (and org-table-copy-increment (org-at-timestamp-p t))
8870 (org-timestamp-up 1)
8871 (org-table-maybe-recalculate-line))
8872 (org-table-align)
8873 (move-to-column col))
8874 (error "No non-empty field found"))))
8876 (defun org-table-check-inside-data-field ()
8877 "Is point inside a table data field?
8878 I.e. not on a hline or before the first or after the last column?
8879 This actually throws an error, so it aborts the current command."
8880 (if (or (not (org-at-table-p))
8881 (= (org-table-current-column) 0)
8882 (org-at-table-hline-p)
8883 (looking-at "[ \t]*$"))
8884 (error "Not in table data field")))
8886 (defvar org-table-clip nil
8887 "Clipboard for table regions.")
8889 (defun org-table-blank-field ()
8890 "Blank the current table field or active region."
8891 (interactive)
8892 (org-table-check-inside-data-field)
8893 (if (and (interactive-p) (org-region-active-p))
8894 (let (org-table-clip)
8895 (org-table-cut-region (region-beginning) (region-end)))
8896 (skip-chars-backward "^|")
8897 (backward-char 1)
8898 (if (looking-at "|[^|\n]+")
8899 (let* ((pos (match-beginning 0))
8900 (match (match-string 0))
8901 (len (org-string-width match)))
8902 (replace-match (concat "|" (make-string (1- len) ?\ )))
8903 (goto-char (+ 2 pos))
8904 (substring match 1)))))
8906 (defun org-table-get-field (&optional n replace)
8907 "Return the value of the field in column N of current row.
8908 N defaults to current field.
8909 If REPLACE is a string, replace field with this value. The return value
8910 is always the old value."
8911 (and n (org-table-goto-column n))
8912 (skip-chars-backward "^|\n")
8913 (backward-char 1)
8914 (if (looking-at "|[^|\r\n]*")
8915 (let* ((pos (match-beginning 0))
8916 (val (buffer-substring (1+ pos) (match-end 0))))
8917 (if replace
8918 (replace-match (concat "|" replace) t t))
8919 (goto-char (min (point-at-eol) (+ 2 pos)))
8920 val)
8921 (forward-char 1) ""))
8923 (defun org-table-field-info (arg)
8924 "Show info about the current field, and highlight any reference at point."
8925 (interactive "P")
8926 (org-table-get-specials)
8927 (save-excursion
8928 (let* ((pos (point))
8929 (col (org-table-current-column))
8930 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8931 (name (car (rassoc (list (org-current-line) col)
8932 org-table-named-field-locations)))
8933 (eql (org-table-get-stored-formulas))
8934 (dline (org-table-current-dline))
8935 (ref (format "@%d$%d" dline col))
8936 (ref1 (org-table-convert-refs-to-an ref))
8937 (fequation (or (assoc name eql) (assoc ref eql)))
8938 (cequation (assoc (int-to-string col) eql))
8939 (eqn (or fequation cequation)))
8940 (goto-char pos)
8941 (condition-case nil
8942 (org-table-show-reference 'local)
8943 (error nil))
8944 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8945 dline col
8946 (if cname (concat " or $" cname) "")
8947 dline col ref1
8948 (if name (concat " or $" name) "")
8949 ;; FIXME: formula info not correct if special table line
8950 (if eqn
8951 (concat ", formula: "
8952 (org-table-formula-to-user
8953 (concat
8954 (if (string-match "^[$@]"(car eqn)) "" "$")
8955 (car eqn) "=" (cdr eqn))))
8956 "")))))
8958 (defun org-table-current-column ()
8959 "Find out which column we are in.
8960 When called interactively, column is also displayed in echo area."
8961 (interactive)
8962 (if (interactive-p) (org-table-check-inside-data-field))
8963 (save-excursion
8964 (let ((cnt 0) (pos (point)))
8965 (beginning-of-line 1)
8966 (while (search-forward "|" pos t)
8967 (setq cnt (1+ cnt)))
8968 (if (interactive-p) (message "This is table column %d" cnt))
8969 cnt)))
8971 (defun org-table-current-dline ()
8972 "Find out what table data line we are in.
8973 Only datalins count for this."
8974 (interactive)
8975 (if (interactive-p) (org-table-check-inside-data-field))
8976 (save-excursion
8977 (let ((cnt 0) (pos (point)))
8978 (goto-char (org-table-begin))
8979 (while (<= (point) pos)
8980 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8981 (beginning-of-line 2))
8982 (if (interactive-p) (message "This is table line %d" cnt))
8983 cnt)))
8985 (defun org-table-goto-column (n &optional on-delim force)
8986 "Move the cursor to the Nth column in the current table line.
8987 With optional argument ON-DELIM, stop with point before the left delimiter
8988 of the field.
8989 If there are less than N fields, just go to after the last delimiter.
8990 However, when FORCE is non-nil, create new columns if necessary."
8991 (interactive "p")
8992 (let ((pos (point-at-eol)))
8993 (beginning-of-line 1)
8994 (when (> n 0)
8995 (while (and (> (setq n (1- n)) -1)
8996 (or (search-forward "|" pos t)
8997 (and force
8998 (progn (end-of-line 1)
8999 (skip-chars-backward "^|")
9000 (insert " | "))))))
9001 ; (backward-char 2) t)))))
9002 (when (and force (not (looking-at ".*|")))
9003 (save-excursion (end-of-line 1) (insert " | ")))
9004 (if on-delim
9005 (backward-char 1)
9006 (if (looking-at " ") (forward-char 1))))))
9008 (defun org-at-table-p (&optional table-type)
9009 "Return t if the cursor is inside an org-type table.
9010 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9011 (if org-enable-table-editor
9012 (save-excursion
9013 (beginning-of-line 1)
9014 (looking-at (if table-type org-table-any-line-regexp
9015 org-table-line-regexp)))
9016 nil))
9018 (defun org-at-table.el-p ()
9019 "Return t if and only if we are at a table.el table."
9020 (and (org-at-table-p 'any)
9021 (save-excursion
9022 (goto-char (org-table-begin 'any))
9023 (looking-at org-table1-hline-regexp))))
9025 (defun org-table-recognize-table.el ()
9026 "If there is a table.el table nearby, recognize it and move into it."
9027 (if org-table-tab-recognizes-table.el
9028 (if (org-at-table.el-p)
9029 (progn
9030 (beginning-of-line 1)
9031 (if (looking-at org-table-dataline-regexp)
9033 (if (looking-at org-table1-hline-regexp)
9034 (progn
9035 (beginning-of-line 2)
9036 (if (looking-at org-table-any-border-regexp)
9037 (beginning-of-line -1)))))
9038 (if (re-search-forward "|" (org-table-end t) t)
9039 (progn
9040 (require 'table)
9041 (if (table--at-cell-p (point))
9043 (message "recognizing table.el table...")
9044 (table-recognize-table)
9045 (message "recognizing table.el table...done")))
9046 (error "This should not happen..."))
9048 nil)
9049 nil))
9051 (defun org-at-table-hline-p ()
9052 "Return t if the cursor is inside a hline in a table."
9053 (if org-enable-table-editor
9054 (save-excursion
9055 (beginning-of-line 1)
9056 (looking-at org-table-hline-regexp))
9057 nil))
9059 (defun org-table-insert-column ()
9060 "Insert a new column into the table."
9061 (interactive)
9062 (if (not (org-at-table-p))
9063 (error "Not at a table"))
9064 (org-table-find-dataline)
9065 (let* ((col (max 1 (org-table-current-column)))
9066 (beg (org-table-begin))
9067 (end (org-table-end))
9068 ;; Current cursor position
9069 (linepos (org-current-line))
9070 (colpos col))
9071 (goto-char beg)
9072 (while (< (point) end)
9073 (if (org-at-table-hline-p)
9075 (org-table-goto-column col t)
9076 (insert "| "))
9077 (beginning-of-line 2))
9078 (move-marker end nil)
9079 (goto-line linepos)
9080 (org-table-goto-column colpos)
9081 (org-table-align)
9082 (org-table-fix-formulas "$" nil (1- col) 1)))
9084 (defun org-table-find-dataline ()
9085 "Find a dataline in the current table, which is needed for column commands."
9086 (if (and (org-at-table-p)
9087 (not (org-at-table-hline-p)))
9089 (let ((col (current-column))
9090 (end (org-table-end)))
9091 (move-to-column col)
9092 (while (and (< (point) end)
9093 (or (not (= (current-column) col))
9094 (org-at-table-hline-p)))
9095 (beginning-of-line 2)
9096 (move-to-column col))
9097 (if (and (org-at-table-p)
9098 (not (org-at-table-hline-p)))
9100 (error
9101 "Please position cursor in a data line for column operations")))))
9103 (defun org-table-delete-column ()
9104 "Delete a column from the table."
9105 (interactive)
9106 (if (not (org-at-table-p))
9107 (error "Not at a table"))
9108 (org-table-find-dataline)
9109 (org-table-check-inside-data-field)
9110 (let* ((col (org-table-current-column))
9111 (beg (org-table-begin))
9112 (end (org-table-end))
9113 ;; Current cursor position
9114 (linepos (org-current-line))
9115 (colpos col))
9116 (goto-char beg)
9117 (while (< (point) end)
9118 (if (org-at-table-hline-p)
9120 (org-table-goto-column col t)
9121 (and (looking-at "|[^|\n]+|")
9122 (replace-match "|")))
9123 (beginning-of-line 2))
9124 (move-marker end nil)
9125 (goto-line linepos)
9126 (org-table-goto-column colpos)
9127 (org-table-align)
9128 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9129 col -1 col)))
9131 (defun org-table-move-column-right ()
9132 "Move column to the right."
9133 (interactive)
9134 (org-table-move-column nil))
9135 (defun org-table-move-column-left ()
9136 "Move column to the left."
9137 (interactive)
9138 (org-table-move-column 'left))
9140 (defun org-table-move-column (&optional left)
9141 "Move the current column to the right. With arg LEFT, move to the left."
9142 (interactive "P")
9143 (if (not (org-at-table-p))
9144 (error "Not at a table"))
9145 (org-table-find-dataline)
9146 (org-table-check-inside-data-field)
9147 (let* ((col (org-table-current-column))
9148 (col1 (if left (1- col) col))
9149 (beg (org-table-begin))
9150 (end (org-table-end))
9151 ;; Current cursor position
9152 (linepos (org-current-line))
9153 (colpos (if left (1- col) (1+ col))))
9154 (if (and left (= col 1))
9155 (error "Cannot move column further left"))
9156 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9157 (error "Cannot move column further right"))
9158 (goto-char beg)
9159 (while (< (point) end)
9160 (if (org-at-table-hline-p)
9162 (org-table-goto-column col1 t)
9163 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9164 (replace-match "|\\2|\\1|")))
9165 (beginning-of-line 2))
9166 (move-marker end nil)
9167 (goto-line linepos)
9168 (org-table-goto-column colpos)
9169 (org-table-align)
9170 (org-table-fix-formulas
9171 "$" (list (cons (number-to-string col) (number-to-string colpos))
9172 (cons (number-to-string colpos) (number-to-string col))))))
9174 (defun org-table-move-row-down ()
9175 "Move table row down."
9176 (interactive)
9177 (org-table-move-row nil))
9178 (defun org-table-move-row-up ()
9179 "Move table row up."
9180 (interactive)
9181 (org-table-move-row 'up))
9183 (defun org-table-move-row (&optional up)
9184 "Move the current table line down. With arg UP, move it up."
9185 (interactive "P")
9186 (let* ((col (current-column))
9187 (pos (point))
9188 (hline1p (save-excursion (beginning-of-line 1)
9189 (looking-at org-table-hline-regexp)))
9190 (dline1 (org-table-current-dline))
9191 (dline2 (+ dline1 (if up -1 1)))
9192 (tonew (if up 0 2))
9193 txt hline2p)
9194 (beginning-of-line tonew)
9195 (unless (org-at-table-p)
9196 (goto-char pos)
9197 (error "Cannot move row further"))
9198 (setq hline2p (looking-at org-table-hline-regexp))
9199 (goto-char pos)
9200 (beginning-of-line 1)
9201 (setq pos (point))
9202 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9203 (delete-region (point) (1+ (point-at-eol)))
9204 (beginning-of-line tonew)
9205 (insert txt)
9206 (beginning-of-line 0)
9207 (move-to-column col)
9208 (unless (or hline1p hline2p)
9209 (org-table-fix-formulas
9210 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9211 (cons (number-to-string dline2) (number-to-string dline1)))))))
9213 (defun org-table-insert-row (&optional arg)
9214 "Insert a new row above the current line into the table.
9215 With prefix ARG, insert below the current line."
9216 (interactive "P")
9217 (if (not (org-at-table-p))
9218 (error "Not at a table"))
9219 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9220 (new (org-table-clean-line line)))
9221 ;; Fix the first field if necessary
9222 (if (string-match "^[ \t]*| *[#$] *|" line)
9223 (setq new (replace-match (match-string 0 line) t t new)))
9224 (beginning-of-line (if arg 2 1))
9225 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9226 (beginning-of-line 0)
9227 (re-search-forward "| ?" (point-at-eol) t)
9228 (and (or org-table-may-need-update org-table-overlay-coordinates)
9229 (org-table-align))
9230 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9232 (defun org-table-insert-hline (&optional above)
9233 "Insert a horizontal-line below the current line into the table.
9234 With prefix ABOVE, insert above the current line."
9235 (interactive "P")
9236 (if (not (org-at-table-p))
9237 (error "Not at a table"))
9238 (let ((line (org-table-clean-line
9239 (buffer-substring (point-at-bol) (point-at-eol))))
9240 (col (current-column)))
9241 (while (string-match "|\\( +\\)|" line)
9242 (setq line (replace-match
9243 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9244 ?-) "|") t t line)))
9245 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9246 (beginning-of-line (if above 1 2))
9247 (insert line "\n")
9248 (beginning-of-line (if above 1 -1))
9249 (move-to-column col)
9250 (and org-table-overlay-coordinates (org-table-align))))
9252 (defun org-table-hline-and-move (&optional same-column)
9253 "Insert a hline and move to the row below that line."
9254 (interactive "P")
9255 (let ((col (org-table-current-column)))
9256 (org-table-maybe-eval-formula)
9257 (org-table-maybe-recalculate-line)
9258 (org-table-insert-hline)
9259 (end-of-line 2)
9260 (if (looking-at "\n[ \t]*|-")
9261 (progn (insert "\n|") (org-table-align))
9262 (org-table-next-field))
9263 (if same-column (org-table-goto-column col))))
9265 (defun org-table-clean-line (s)
9266 "Convert a table line S into a string with only \"|\" and space.
9267 In particular, this does handle wide and invisible characters."
9268 (if (string-match "^[ \t]*|-" s)
9269 ;; It's a hline, just map the characters
9270 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9271 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9272 (setq s (replace-match
9273 (concat "|" (make-string (org-string-width (match-string 1 s))
9274 ?\ ) "|")
9275 t t s)))
9278 (defun org-table-kill-row ()
9279 "Delete the current row or horizontal line from the table."
9280 (interactive)
9281 (if (not (org-at-table-p))
9282 (error "Not at a table"))
9283 (let ((col (current-column))
9284 (dline (org-table-current-dline)))
9285 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9286 (if (not (org-at-table-p)) (beginning-of-line 0))
9287 (move-to-column col)
9288 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9289 dline -1 dline)))
9291 (defun org-table-sort-lines (with-case &optional sorting-type)
9292 "Sort table lines according to the column at point.
9294 The position of point indicates the column to be used for
9295 sorting, and the range of lines is the range between the nearest
9296 horizontal separator lines, or the entire table of no such lines
9297 exist. If point is before the first column, you will be prompted
9298 for the sorting column. If there is an active region, the mark
9299 specifies the first line and the sorting column, while point
9300 should be in the last line to be included into the sorting.
9302 The command then prompts for the sorting type which can be
9303 alphabetically, numerically, or by time (as given in a time stamp
9304 in the field). Sorting in reverse order is also possible.
9306 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9308 If SORTING-TYPE is specified when this function is called from a Lisp
9309 program, no prompting will take place. SORTING-TYPE must be a character,
9310 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9311 should be done in reverse order."
9312 (interactive "P")
9313 (let* ((thisline (org-current-line))
9314 (thiscol (org-table-current-column))
9315 beg end bcol ecol tend tbeg column lns pos)
9316 (when (equal thiscol 0)
9317 (if (interactive-p)
9318 (setq thiscol
9319 (string-to-number
9320 (read-string "Use column N for sorting: ")))
9321 (setq thiscol 1))
9322 (org-table-goto-column thiscol))
9323 (org-table-check-inside-data-field)
9324 (if (org-region-active-p)
9325 (progn
9326 (setq beg (region-beginning) end (region-end))
9327 (goto-char beg)
9328 (setq column (org-table-current-column)
9329 beg (point-at-bol))
9330 (goto-char end)
9331 (setq end (point-at-bol 2)))
9332 (setq column (org-table-current-column)
9333 pos (point)
9334 tbeg (org-table-begin)
9335 tend (org-table-end))
9336 (if (re-search-backward org-table-hline-regexp tbeg t)
9337 (setq beg (point-at-bol 2))
9338 (goto-char tbeg)
9339 (setq beg (point-at-bol 1)))
9340 (goto-char pos)
9341 (if (re-search-forward org-table-hline-regexp tend t)
9342 (setq end (point-at-bol 1))
9343 (goto-char tend)
9344 (setq end (point-at-bol))))
9345 (setq beg (move-marker (make-marker) beg)
9346 end (move-marker (make-marker) end))
9347 (untabify beg end)
9348 (goto-char beg)
9349 (org-table-goto-column column)
9350 (skip-chars-backward "^|")
9351 (setq bcol (current-column))
9352 (org-table-goto-column (1+ column))
9353 (skip-chars-backward "^|")
9354 (setq ecol (1- (current-column)))
9355 (org-table-goto-column column)
9356 (setq lns (mapcar (lambda(x) (cons
9357 (org-sort-remove-invisible
9358 (nth (1- column)
9359 (org-split-string x "[ \t]*|[ \t]*")))
9361 (org-split-string (buffer-substring beg end) "\n")))
9362 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9363 (delete-region beg end)
9364 (move-marker beg nil)
9365 (move-marker end nil)
9366 (insert (mapconcat 'cdr lns "\n") "\n")
9367 (goto-line thisline)
9368 (org-table-goto-column thiscol)
9369 (message "%d lines sorted, based on column %d" (length lns) column)))
9371 ;; FIXME: maybe we will not need this? Table sorting is broken....
9372 (defun org-sort-remove-invisible (s)
9373 (remove-text-properties 0 (length s) org-rm-props s)
9374 (while (string-match org-bracket-link-regexp s)
9375 (setq s (replace-match (if (match-end 2)
9376 (match-string 3 s)
9377 (match-string 1 s)) t t s)))
9380 (defun org-table-cut-region (beg end)
9381 "Copy region in table to the clipboard and blank all relevant fields."
9382 (interactive "r")
9383 (org-table-copy-region beg end 'cut))
9385 (defun org-table-copy-region (beg end &optional cut)
9386 "Copy rectangular region in table to clipboard.
9387 A special clipboard is used which can only be accessed
9388 with `org-table-paste-rectangle'."
9389 (interactive "rP")
9390 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9391 region cols
9392 (rpl (if cut " " nil)))
9393 (goto-char beg)
9394 (org-table-check-inside-data-field)
9395 (setq l01 (org-current-line)
9396 c01 (org-table-current-column))
9397 (goto-char end)
9398 (org-table-check-inside-data-field)
9399 (setq l02 (org-current-line)
9400 c02 (org-table-current-column))
9401 (setq l1 (min l01 l02) l2 (max l01 l02)
9402 c1 (min c01 c02) c2 (max c01 c02))
9403 (catch 'exit
9404 (while t
9405 (catch 'nextline
9406 (if (> l1 l2) (throw 'exit t))
9407 (goto-line l1)
9408 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9409 (setq cols nil ic1 c1 ic2 c2)
9410 (while (< ic1 (1+ ic2))
9411 (push (org-table-get-field ic1 rpl) cols)
9412 (setq ic1 (1+ ic1)))
9413 (push (nreverse cols) region)
9414 (setq l1 (1+ l1)))))
9415 (setq org-table-clip (nreverse region))
9416 (if cut (org-table-align))
9417 org-table-clip))
9419 (defun org-table-paste-rectangle ()
9420 "Paste a rectangular region into a table.
9421 The upper right corner ends up in the current field. All involved fields
9422 will be overwritten. If the rectangle does not fit into the present table,
9423 the table is enlarged as needed. The process ignores horizontal separator
9424 lines."
9425 (interactive)
9426 (unless (and org-table-clip (listp org-table-clip))
9427 (error "First cut/copy a region to paste!"))
9428 (org-table-check-inside-data-field)
9429 (let* ((clip org-table-clip)
9430 (line (org-current-line))
9431 (col (org-table-current-column))
9432 (org-enable-table-editor t)
9433 (org-table-automatic-realign nil)
9434 c cols field)
9435 (while (setq cols (pop clip))
9436 (while (org-at-table-hline-p) (beginning-of-line 2))
9437 (if (not (org-at-table-p))
9438 (progn (end-of-line 0) (org-table-next-field)))
9439 (setq c col)
9440 (while (setq field (pop cols))
9441 (org-table-goto-column c nil 'force)
9442 (org-table-get-field nil field)
9443 (setq c (1+ c)))
9444 (beginning-of-line 2))
9445 (goto-line line)
9446 (org-table-goto-column col)
9447 (org-table-align)))
9449 (defun org-table-convert ()
9450 "Convert from `org-mode' table to table.el and back.
9451 Obviously, this only works within limits. When an Org-mode table is
9452 converted to table.el, all horizontal separator lines get lost, because
9453 table.el uses these as cell boundaries and has no notion of horizontal lines.
9454 A table.el table can be converted to an Org-mode table only if it does not
9455 do row or column spanning. Multiline cells will become multiple cells.
9456 Beware, Org-mode does not test if the table can be successfully converted - it
9457 blindly applies a recipe that works for simple tables."
9458 (interactive)
9459 (require 'table)
9460 (if (org-at-table.el-p)
9461 ;; convert to Org-mode table
9462 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9463 (end (move-marker (make-marker) (org-table-end t))))
9464 (table-unrecognize-region beg end)
9465 (goto-char beg)
9466 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9467 (replace-match ""))
9468 (goto-char beg))
9469 (if (org-at-table-p)
9470 ;; convert to table.el table
9471 (let ((beg (move-marker (make-marker) (org-table-begin)))
9472 (end (move-marker (make-marker) (org-table-end))))
9473 ;; first, get rid of all horizontal lines
9474 (goto-char beg)
9475 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9476 (replace-match ""))
9477 ;; insert a hline before first
9478 (goto-char beg)
9479 (org-table-insert-hline 'above)
9480 (beginning-of-line -1)
9481 ;; insert a hline after each line
9482 (while (progn (beginning-of-line 3) (< (point) end))
9483 (org-table-insert-hline))
9484 (goto-char beg)
9485 (setq end (move-marker end (org-table-end)))
9486 ;; replace "+" at beginning and ending of hlines
9487 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9488 (replace-match "\\1+-"))
9489 (goto-char beg)
9490 (while (re-search-forward "-|[ \t]*$" end t)
9491 (replace-match "-+"))
9492 (goto-char beg)))))
9494 (defun org-table-wrap-region (arg)
9495 "Wrap several fields in a column like a paragraph.
9496 This is useful if you'd like to spread the contents of a field over several
9497 lines, in order to keep the table compact.
9499 If there is an active region, and both point and mark are in the same column,
9500 the text in the column is wrapped to minimum width for the given number of
9501 lines. Generally, this makes the table more compact. A prefix ARG may be
9502 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9503 formats the selected text to two lines. If the region was longer than two
9504 lines, the remaining lines remain empty. A negative prefix argument reduces
9505 the current number of lines by that amount. The wrapped text is pasted back
9506 into the table. If you formatted it to more lines than it was before, fields
9507 further down in the table get overwritten - so you might need to make space in
9508 the table first.
9510 If there is no region, the current field is split at the cursor position and
9511 the text fragment to the right of the cursor is prepended to the field one
9512 line down.
9514 If there is no region, but you specify a prefix ARG, the current field gets
9515 blank, and the content is appended to the field above."
9516 (interactive "P")
9517 (org-table-check-inside-data-field)
9518 (if (org-region-active-p)
9519 ;; There is a region: fill as a paragraph
9520 (let* ((beg (region-beginning))
9521 (cline (save-excursion (goto-char beg) (org-current-line)))
9522 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9523 nlines)
9524 (org-table-cut-region (region-beginning) (region-end))
9525 (if (> (length (car org-table-clip)) 1)
9526 (error "Region must be limited to single column"))
9527 (setq nlines (if arg
9528 (if (< arg 1)
9529 (+ (length org-table-clip) arg)
9530 arg)
9531 (length org-table-clip)))
9532 (setq org-table-clip
9533 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9534 nil nlines)))
9535 (goto-line cline)
9536 (org-table-goto-column ccol)
9537 (org-table-paste-rectangle))
9538 ;; No region, split the current field at point
9539 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9540 (skip-chars-forward "^\r\n|"))
9541 (if arg
9542 ;; combine with field above
9543 (let ((s (org-table-blank-field))
9544 (col (org-table-current-column)))
9545 (beginning-of-line 0)
9546 (while (org-at-table-hline-p) (beginning-of-line 0))
9547 (org-table-goto-column col)
9548 (skip-chars-forward "^|")
9549 (skip-chars-backward " ")
9550 (insert " " (org-trim s))
9551 (org-table-align))
9552 ;; split field
9553 (if (looking-at "\\([^|]+\\)+|")
9554 (let ((s (match-string 1)))
9555 (replace-match " |")
9556 (goto-char (match-beginning 0))
9557 (org-table-next-row)
9558 (insert (org-trim s) " ")
9559 (org-table-align))
9560 (org-table-next-row)))))
9562 (defvar org-field-marker nil)
9564 (defun org-table-edit-field (arg)
9565 "Edit table field in a different window.
9566 This is mainly useful for fields that contain hidden parts.
9567 When called with a \\[universal-argument] prefix, just make the full field visible so that
9568 it can be edited in place."
9569 (interactive "P")
9570 (if arg
9571 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9572 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9573 (remove-text-properties b e '(org-cwidth t invisible t
9574 display t intangible t))
9575 (if (and (boundp 'font-lock-mode) font-lock-mode)
9576 (font-lock-fontify-block)))
9577 (let ((pos (move-marker (make-marker) (point)))
9578 (field (org-table-get-field))
9579 (cw (current-window-configuration))
9581 (org-switch-to-buffer-other-window "*Org tmp*")
9582 (erase-buffer)
9583 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9584 (let ((org-inhibit-startup t)) (org-mode))
9585 (goto-char (setq p (point-max)))
9586 (insert (org-trim field))
9587 (remove-text-properties p (point-max)
9588 '(invisible t org-cwidth t display t
9589 intangible t))
9590 (goto-char p)
9591 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9592 (org-set-local 'org-window-configuration cw)
9593 (org-set-local 'org-field-marker pos)
9594 (message "Edit and finish with C-c C-c"))))
9596 (defun org-table-finish-edit-field ()
9597 "Finish editing a table data field.
9598 Remove all newline characters, insert the result into the table, realign
9599 the table and kill the editing buffer."
9600 (let ((pos org-field-marker)
9601 (cw org-window-configuration)
9602 (cb (current-buffer))
9603 text)
9604 (goto-char (point-min))
9605 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9606 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9607 (replace-match " "))
9608 (setq text (org-trim (buffer-string)))
9609 (set-window-configuration cw)
9610 (kill-buffer cb)
9611 (select-window (get-buffer-window (marker-buffer pos)))
9612 (goto-char pos)
9613 (move-marker pos nil)
9614 (org-table-check-inside-data-field)
9615 (org-table-get-field nil text)
9616 (org-table-align)
9617 (message "New field value inserted")))
9619 (defun org-trim (s)
9620 "Remove whitespace at beginning and end of string."
9621 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9622 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9625 (defun org-wrap (string &optional width lines)
9626 "Wrap string to either a number of lines, or a width in characters.
9627 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9628 that costs. If there is a word longer than WIDTH, the text is actually
9629 wrapped to the length of that word.
9630 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9631 many lines, whatever width that takes.
9632 The return value is a list of lines, without newlines at the end."
9633 (let* ((words (org-split-string string "[ \t\n]+"))
9634 (maxword (apply 'max (mapcar 'org-string-width words)))
9635 w ll)
9636 (cond (width
9637 (org-do-wrap words (max maxword width)))
9638 (lines
9639 (setq w maxword)
9640 (setq ll (org-do-wrap words maxword))
9641 (if (<= (length ll) lines)
9643 (setq ll words)
9644 (while (> (length ll) lines)
9645 (setq w (1+ w))
9646 (setq ll (org-do-wrap words w)))
9647 ll))
9648 (t (error "Cannot wrap this")))))
9651 (defun org-do-wrap (words width)
9652 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9653 (let (lines line)
9654 (while words
9655 (setq line (pop words))
9656 (while (and words (< (+ (length line) (length (car words))) width))
9657 (setq line (concat line " " (pop words))))
9658 (setq lines (push line lines)))
9659 (nreverse lines)))
9661 (defun org-split-string (string &optional separators)
9662 "Splits STRING into substrings at SEPARATORS.
9663 No empty strings are returned if there are matches at the beginning
9664 and end of string."
9665 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9666 (start 0)
9667 notfirst
9668 (list nil))
9669 (while (and (string-match rexp string
9670 (if (and notfirst
9671 (= start (match-beginning 0))
9672 (< start (length string)))
9673 (1+ start) start))
9674 (< (match-beginning 0) (length string)))
9675 (setq notfirst t)
9676 (or (eq (match-beginning 0) 0)
9677 (and (eq (match-beginning 0) (match-end 0))
9678 (eq (match-beginning 0) start))
9679 (setq list
9680 (cons (substring string start (match-beginning 0))
9681 list)))
9682 (setq start (match-end 0)))
9683 (or (eq start (length string))
9684 (setq list
9685 (cons (substring string start)
9686 list)))
9687 (nreverse list)))
9689 (defun org-table-map-tables (function)
9690 "Apply FUNCTION to the start of all tables in the buffer."
9691 (save-excursion
9692 (save-restriction
9693 (widen)
9694 (goto-char (point-min))
9695 (while (re-search-forward org-table-any-line-regexp nil t)
9696 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9697 (beginning-of-line 1)
9698 (if (looking-at org-table-line-regexp)
9699 (save-excursion (funcall function)))
9700 (re-search-forward org-table-any-border-regexp nil 1))))
9701 (message "Mapping tables: done"))
9703 (defvar org-timecnt) ; dynamically scoped parameter
9705 (defun org-table-sum (&optional beg end nlast)
9706 "Sum numbers in region of current table column.
9707 The result will be displayed in the echo area, and will be available
9708 as kill to be inserted with \\[yank].
9710 If there is an active region, it is interpreted as a rectangle and all
9711 numbers in that rectangle will be summed. If there is no active
9712 region and point is located in a table column, sum all numbers in that
9713 column.
9715 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9716 numbers are assumed to be times as well (in decimal hours) and the
9717 numbers are added as such.
9719 If NLAST is a number, only the NLAST fields will actually be summed."
9720 (interactive)
9721 (save-excursion
9722 (let (col (org-timecnt 0) diff h m s org-table-clip)
9723 (cond
9724 ((and beg end)) ; beg and end given explicitly
9725 ((org-region-active-p)
9726 (setq beg (region-beginning) end (region-end)))
9728 (setq col (org-table-current-column))
9729 (goto-char (org-table-begin))
9730 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9731 (error "No table data"))
9732 (org-table-goto-column col)
9733 (setq beg (point))
9734 (goto-char (org-table-end))
9735 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9736 (error "No table data"))
9737 (org-table-goto-column col)
9738 (setq end (point))))
9739 (let* ((items (apply 'append (org-table-copy-region beg end)))
9740 (items1 (cond ((not nlast) items)
9741 ((>= nlast (length items)) items)
9742 (t (setq items (reverse items))
9743 (setcdr (nthcdr (1- nlast) items) nil)
9744 (nreverse items))))
9745 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9746 items1)))
9747 (res (apply '+ numbers))
9748 (sres (if (= org-timecnt 0)
9749 (format "%g" res)
9750 (setq diff (* 3600 res)
9751 h (floor (/ diff 3600)) diff (mod diff 3600)
9752 m (floor (/ diff 60)) diff (mod diff 60)
9753 s diff)
9754 (format "%d:%02d:%02d" h m s))))
9755 (kill-new sres)
9756 (if (interactive-p)
9757 (message "%s"
9758 (substitute-command-keys
9759 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9760 (length numbers) sres))))
9761 sres))))
9763 (defun org-table-get-number-for-summing (s)
9764 (let (n)
9765 (if (string-match "^ *|? *" s)
9766 (setq s (replace-match "" nil nil s)))
9767 (if (string-match " *|? *$" s)
9768 (setq s (replace-match "" nil nil s)))
9769 (setq n (string-to-number s))
9770 (cond
9771 ((and (string-match "0" s)
9772 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9773 ((string-match "\\`[ \t]+\\'" s) nil)
9774 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9775 (let ((h (string-to-number (or (match-string 1 s) "0")))
9776 (m (string-to-number (or (match-string 2 s) "0")))
9777 (s (string-to-number (or (match-string 4 s) "0"))))
9778 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9779 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9780 ((equal n 0) nil)
9781 (t n))))
9783 (defun org-table-current-field-formula (&optional key noerror)
9784 "Return the formula active for the current field.
9785 Assumes that specials are in place.
9786 If KEY is given, return the key to this formula.
9787 Otherwise return the formula preceeded with \"=\" or \":=\"."
9788 (let* ((name (car (rassoc (list (org-current-line)
9789 (org-table-current-column))
9790 org-table-named-field-locations)))
9791 (col (org-table-current-column))
9792 (scol (int-to-string col))
9793 (ref (format "@%d$%d" (org-table-current-dline) col))
9794 (stored-list (org-table-get-stored-formulas noerror))
9795 (ass (or (assoc name stored-list)
9796 (assoc ref stored-list)
9797 (assoc scol stored-list))))
9798 (if key
9799 (car ass)
9800 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9801 (cdr ass))))))
9803 (defun org-table-get-formula (&optional equation named)
9804 "Read a formula from the minibuffer, offer stored formula as default.
9805 When NAMED is non-nil, look for a named equation."
9806 (let* ((stored-list (org-table-get-stored-formulas))
9807 (name (car (rassoc (list (org-current-line)
9808 (org-table-current-column))
9809 org-table-named-field-locations)))
9810 (ref (format "@%d$%d" (org-table-current-dline)
9811 (org-table-current-column)))
9812 (refass (assoc ref stored-list))
9813 (scol (if named
9814 (if name name ref)
9815 (int-to-string (org-table-current-column))))
9816 (dummy (and (or name refass) (not named)
9817 (not (y-or-n-p "Replace field formula with column formula? " ))
9818 (error "Abort")))
9819 (name (or name ref))
9820 (org-table-may-need-update nil)
9821 (stored (cdr (assoc scol stored-list)))
9822 (eq (cond
9823 ((and stored equation (string-match "^ *=? *$" equation))
9824 stored)
9825 ((stringp equation)
9826 equation)
9827 (t (org-table-formula-from-user
9828 (read-string
9829 (org-table-formula-to-user
9830 (format "%s formula %s%s="
9831 (if named "Field" "Column")
9832 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9833 scol))
9834 (if stored (org-table-formula-to-user stored) "")
9835 'org-table-formula-history
9836 )))))
9837 mustsave)
9838 (when (not (string-match "\\S-" eq))
9839 ;; remove formula
9840 (setq stored-list (delq (assoc scol stored-list) stored-list))
9841 (org-table-store-formulas stored-list)
9842 (error "Formula removed"))
9843 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9844 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9845 (if (and name (not named))
9846 ;; We set the column equation, delete the named one.
9847 (setq stored-list (delq (assoc name stored-list) stored-list)
9848 mustsave t))
9849 (if stored
9850 (setcdr (assoc scol stored-list) eq)
9851 (setq stored-list (cons (cons scol eq) stored-list)))
9852 (if (or mustsave (not (equal stored eq)))
9853 (org-table-store-formulas stored-list))
9854 eq))
9856 (defun org-table-store-formulas (alist)
9857 "Store the list of formulas below the current table."
9858 (setq alist (sort alist 'org-table-formula-less-p))
9859 (save-excursion
9860 (goto-char (org-table-end))
9861 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9862 (progn
9863 ;; don't overwrite TBLFM, we might use text properties to store stuff
9864 (goto-char (match-beginning 2))
9865 (delete-region (match-beginning 2) (match-end 0)))
9866 (insert "#+TBLFM:"))
9867 (insert " "
9868 (mapconcat (lambda (x)
9869 (concat
9870 (if (equal (string-to-char (car x)) ?@) "" "$")
9871 (car x) "=" (cdr x)))
9872 alist "::")
9873 "\n")))
9875 (defsubst org-table-formula-make-cmp-string (a)
9876 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9877 (concat
9878 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9879 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9880 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9882 (defun org-table-formula-less-p (a b)
9883 "Compare two formulas for sorting."
9884 (let ((as (org-table-formula-make-cmp-string (car a)))
9885 (bs (org-table-formula-make-cmp-string (car b))))
9886 (and as bs (string< as bs))))
9888 (defun org-table-get-stored-formulas (&optional noerror)
9889 "Return an alist with the stored formulas directly after current table."
9890 (interactive)
9891 (let (scol eq eq-alist strings string seen)
9892 (save-excursion
9893 (goto-char (org-table-end))
9894 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9895 (setq strings (org-split-string (match-string 2) " *:: *"))
9896 (while (setq string (pop strings))
9897 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9898 (setq scol (if (match-end 2)
9899 (match-string 2 string)
9900 (match-string 1 string))
9901 eq (match-string 3 string)
9902 eq-alist (cons (cons scol eq) eq-alist))
9903 (if (member scol seen)
9904 (if noerror
9905 (progn
9906 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9907 (ding)
9908 (sit-for 2))
9909 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9910 (push scol seen))))))
9911 (nreverse eq-alist)))
9913 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9914 "Modify the equations after the table structure has been edited.
9915 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9916 For all numbers larger than LIMIT, shift them by DELTA."
9917 (save-excursion
9918 (goto-char (org-table-end))
9919 (when (looking-at "#\\+TBLFM:")
9920 (let ((re (concat key "\\([0-9]+\\)"))
9921 (re2
9922 (when remove
9923 (if (equal key "$")
9924 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9925 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9926 s n a)
9927 (when remove
9928 (while (re-search-forward re2 (point-at-eol) t)
9929 (replace-match "")))
9930 (while (re-search-forward re (point-at-eol) t)
9931 (setq s (match-string 1) n (string-to-number s))
9932 (cond
9933 ((setq a (assoc s replace))
9934 (replace-match (concat key (cdr a)) t t))
9935 ((and limit (> n limit))
9936 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9938 (defun org-table-get-specials ()
9939 "Get the column names and local parameters for this table."
9940 (save-excursion
9941 (let ((beg (org-table-begin)) (end (org-table-end))
9942 names name fields fields1 field cnt
9943 c v l line col types dlines hlines)
9944 (setq org-table-column-names nil
9945 org-table-local-parameters nil
9946 org-table-named-field-locations nil
9947 org-table-current-begin-line nil
9948 org-table-current-begin-pos nil
9949 org-table-current-line-types nil)
9950 (goto-char beg)
9951 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9952 (setq names (org-split-string (match-string 1) " *| *")
9953 cnt 1)
9954 (while (setq name (pop names))
9955 (setq cnt (1+ cnt))
9956 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9957 (push (cons name (int-to-string cnt)) org-table-column-names))))
9958 (setq org-table-column-names (nreverse org-table-column-names))
9959 (setq org-table-column-name-regexp
9960 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9961 (goto-char beg)
9962 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9963 (setq fields (org-split-string (match-string 1) " *| *"))
9964 (while (setq field (pop fields))
9965 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9966 (push (cons (match-string 1 field) (match-string 2 field))
9967 org-table-local-parameters))))
9968 (goto-char beg)
9969 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9970 (setq c (match-string 1)
9971 fields (org-split-string (match-string 2) " *| *"))
9972 (save-excursion
9973 (beginning-of-line (if (equal c "_") 2 0))
9974 (setq line (org-current-line) col 1)
9975 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9976 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9977 (while (and fields1 (setq field (pop fields)))
9978 (setq v (pop fields1) col (1+ col))
9979 (when (and (stringp field) (stringp v)
9980 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9981 (push (cons field v) org-table-local-parameters)
9982 (push (list field line col) org-table-named-field-locations))))
9983 ;; Analyse the line types
9984 (goto-char beg)
9985 (setq org-table-current-begin-line (org-current-line)
9986 org-table-current-begin-pos (point)
9987 l org-table-current-begin-line)
9988 (while (looking-at "[ \t]*|\\(-\\)?")
9989 (push (if (match-end 1) 'hline 'dline) types)
9990 (if (match-end 1) (push l hlines) (push l dlines))
9991 (beginning-of-line 2)
9992 (setq l (1+ l)))
9993 (setq org-table-current-line-types (apply 'vector (nreverse types))
9994 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9995 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9997 (defun org-table-maybe-eval-formula ()
9998 "Check if the current field starts with \"=\" or \":=\".
9999 If yes, store the formula and apply it."
10000 ;; We already know we are in a table. Get field will only return a formula
10001 ;; when appropriate. It might return a separator line, but no problem.
10002 (when org-table-formula-evaluate-inline
10003 (let* ((field (org-trim (or (org-table-get-field) "")))
10004 named eq)
10005 (when (string-match "^:?=\\(.*\\)" field)
10006 (setq named (equal (string-to-char field) ?:)
10007 eq (match-string 1 field))
10008 (if (or (fboundp 'calc-eval)
10009 (equal (substring eq 0 (min 2 (length eq))) "'("))
10010 (org-table-eval-formula (if named '(4) nil)
10011 (org-table-formula-from-user eq))
10012 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10014 (defvar org-recalc-commands nil
10015 "List of commands triggering the recalculation of a line.
10016 Will be filled automatically during use.")
10018 (defvar org-recalc-marks
10019 '((" " . "Unmarked: no special line, no automatic recalculation")
10020 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10021 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10022 ("!" . "Column name definition line. Reference in formula as $name.")
10023 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10024 ("_" . "Names for values in row below this one.")
10025 ("^" . "Names for values in row above this one.")))
10027 (defun org-table-rotate-recalc-marks (&optional newchar)
10028 "Rotate the recalculation mark in the first column.
10029 If in any row, the first field is not consistent with a mark,
10030 insert a new column for the markers.
10031 When there is an active region, change all the lines in the region,
10032 after prompting for the marking character.
10033 After each change, a message will be displayed indicating the meaning
10034 of the new mark."
10035 (interactive)
10036 (unless (org-at-table-p) (error "Not at a table"))
10037 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10038 (beg (org-table-begin))
10039 (end (org-table-end))
10040 (l (org-current-line))
10041 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10042 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10043 (have-col
10044 (save-excursion
10045 (goto-char beg)
10046 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10047 (col (org-table-current-column))
10048 (forcenew (car (assoc newchar org-recalc-marks)))
10049 epos new)
10050 (when l1
10051 (message "Change region to what mark? Type # * ! $ or SPC: ")
10052 (setq newchar (char-to-string (read-char-exclusive))
10053 forcenew (car (assoc newchar org-recalc-marks))))
10054 (if (and newchar (not forcenew))
10055 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10056 newchar))
10057 (if l1 (goto-line l1))
10058 (save-excursion
10059 (beginning-of-line 1)
10060 (unless (looking-at org-table-dataline-regexp)
10061 (error "Not at a table data line")))
10062 (unless have-col
10063 (org-table-goto-column 1)
10064 (org-table-insert-column)
10065 (org-table-goto-column (1+ col)))
10066 (setq epos (point-at-eol))
10067 (save-excursion
10068 (beginning-of-line 1)
10069 (org-table-get-field
10070 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10071 (concat " "
10072 (setq new (or forcenew
10073 (cadr (member (match-string 1) marks))))
10074 " ")
10075 " # ")))
10076 (if (and l1 l2)
10077 (progn
10078 (goto-line l1)
10079 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10080 (and (looking-at org-table-dataline-regexp)
10081 (org-table-get-field 1 (concat " " new " "))))
10082 (goto-line l1)))
10083 (if (not (= epos (point-at-eol))) (org-table-align))
10084 (goto-line l)
10085 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10087 (defun org-table-maybe-recalculate-line ()
10088 "Recompute the current line if marked for it, and if we haven't just done it."
10089 (interactive)
10090 (and org-table-allow-automatic-line-recalculation
10091 (not (and (memq last-command org-recalc-commands)
10092 (equal org-last-recalc-line (org-current-line))))
10093 (save-excursion (beginning-of-line 1)
10094 (looking-at org-table-auto-recalculate-regexp))
10095 (org-table-recalculate) t))
10097 (defvar org-table-formula-debug nil
10098 "Non-nil means, debug table formulas.
10099 When nil, simply write \"#ERROR\" in corrupted fields.")
10100 (make-variable-buffer-local 'org-table-formula-debug)
10102 (defvar modes)
10103 (defsubst org-set-calc-mode (var &optional value)
10104 (if (stringp var)
10105 (setq var (assoc var '(("D" calc-angle-mode deg)
10106 ("R" calc-angle-mode rad)
10107 ("F" calc-prefer-frac t)
10108 ("S" calc-symbolic-mode t)))
10109 value (nth 2 var) var (nth 1 var)))
10110 (if (memq var modes)
10111 (setcar (cdr (memq var modes)) value)
10112 (cons var (cons value modes)))
10113 modes)
10115 (defun org-table-eval-formula (&optional arg equation
10116 suppress-align suppress-const
10117 suppress-store suppress-analysis)
10118 "Replace the table field value at the cursor by the result of a calculation.
10120 This function makes use of Dave Gillespie's Calc package, in my view the
10121 most exciting program ever written for GNU Emacs. So you need to have Calc
10122 installed in order to use this function.
10124 In a table, this command replaces the value in the current field with the
10125 result of a formula. It also installs the formula as the \"current\" column
10126 formula, by storing it in a special line below the table. When called
10127 with a `C-u' prefix, the current field must ba a named field, and the
10128 formula is installed as valid in only this specific field.
10130 When called with two `C-u' prefixes, insert the active equation
10131 for the field back into the current field, so that it can be
10132 edited there. This is useful in order to use \\[org-table-show-reference]
10133 to check the referenced fields.
10135 When called, the command first prompts for a formula, which is read in
10136 the minibuffer. Previously entered formulas are available through the
10137 history list, and the last used formula is offered as a default.
10138 These stored formulas are adapted correctly when moving, inserting, or
10139 deleting columns with the corresponding commands.
10141 The formula can be any algebraic expression understood by the Calc package.
10142 For details, see the Org-mode manual.
10144 This function can also be called from Lisp programs and offers
10145 additional arguments: EQUATION can be the formula to apply. If this
10146 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10147 used to speed-up recursive calls by by-passing unnecessary aligns.
10148 SUPPRESS-CONST suppresses the interpretation of constants in the
10149 formula, assuming that this has been done already outside the function.
10150 SUPPRESS-STORE means the formula should not be stored, either because
10151 it is already stored, or because it is a modified equation that should
10152 not overwrite the stored one."
10153 (interactive "P")
10154 (org-table-check-inside-data-field)
10155 (or suppress-analysis (org-table-get-specials))
10156 (if (equal arg '(16))
10157 (let ((eq (org-table-current-field-formula)))
10158 (or eq (error "No equation active for current field"))
10159 (org-table-get-field nil eq)
10160 (org-table-align)
10161 (setq org-table-may-need-update t))
10162 (let* (fields
10163 (ndown (if (integerp arg) arg 1))
10164 (org-table-automatic-realign nil)
10165 (case-fold-search nil)
10166 (down (> ndown 1))
10167 (formula (if (and equation suppress-store)
10168 equation
10169 (org-table-get-formula equation (equal arg '(4)))))
10170 (n0 (org-table-current-column))
10171 (modes (copy-sequence org-calc-default-modes))
10172 (numbers nil) ; was a variable, now fixed default
10173 (keep-empty nil)
10174 n form form0 bw fmt x ev orig c lispp literal)
10175 ;; Parse the format string. Since we have a lot of modes, this is
10176 ;; a lot of work. However, I think calc still uses most of the time.
10177 (if (string-match ";" formula)
10178 (let ((tmp (org-split-string formula ";")))
10179 (setq formula (car tmp)
10180 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10181 (nth 1 tmp)))
10182 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10183 (setq c (string-to-char (match-string 1 fmt))
10184 n (string-to-number (match-string 2 fmt)))
10185 (if (= c ?p)
10186 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10187 (setq modes (org-set-calc-mode
10188 'calc-float-format
10189 (list (cdr (assoc c '((?n . float) (?f . fix)
10190 (?s . sci) (?e . eng))))
10191 n))))
10192 (setq fmt (replace-match "" t t fmt)))
10193 (if (string-match "[NT]" fmt)
10194 (setq numbers (equal (match-string 0 fmt) "N")
10195 fmt (replace-match "" t t fmt)))
10196 (if (string-match "L" fmt)
10197 (setq literal t
10198 fmt (replace-match "" t t fmt)))
10199 (if (string-match "E" fmt)
10200 (setq keep-empty t
10201 fmt (replace-match "" t t fmt)))
10202 (while (string-match "[DRFS]" fmt)
10203 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10204 (setq fmt (replace-match "" t t fmt)))
10205 (unless (string-match "\\S-" fmt)
10206 (setq fmt nil))))
10207 (if (and (not suppress-const) org-table-formula-use-constants)
10208 (setq formula (org-table-formula-substitute-names formula)))
10209 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10210 (while (> ndown 0)
10211 (setq fields (org-split-string
10212 (org-no-properties
10213 (buffer-substring (point-at-bol) (point-at-eol)))
10214 " *| *"))
10215 (if (eq numbers t)
10216 (setq fields (mapcar
10217 (lambda (x) (number-to-string (string-to-number x)))
10218 fields)))
10219 (setq ndown (1- ndown))
10220 (setq form (copy-sequence formula)
10221 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10222 (if (and lispp literal) (setq lispp 'literal))
10223 ;; Check for old vertical references
10224 (setq form (org-rewrite-old-row-references form))
10225 ;; Insert complex ranges
10226 (while (string-match org-table-range-regexp form)
10227 (setq form
10228 (replace-match
10229 (save-match-data
10230 (org-table-make-reference
10231 (org-table-get-range (match-string 0 form) nil n0)
10232 keep-empty numbers lispp))
10233 t t form)))
10234 ;; Insert simple ranges
10235 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10236 (setq form
10237 (replace-match
10238 (save-match-data
10239 (org-table-make-reference
10240 (org-sublist
10241 fields (string-to-number (match-string 1 form))
10242 (string-to-number (match-string 2 form)))
10243 keep-empty numbers lispp))
10244 t t form)))
10245 (setq form0 form)
10246 ;; Insert the references to fields in same row
10247 (while (string-match "\\$\\([0-9]+\\)" form)
10248 (setq n (string-to-number (match-string 1 form))
10249 x (nth (1- (if (= n 0) n0 n)) fields))
10250 (unless x (error "Invalid field specifier \"%s\""
10251 (match-string 0 form)))
10252 (setq form (replace-match
10253 (save-match-data
10254 (org-table-make-reference x nil numbers lispp))
10255 t t form)))
10257 (if lispp
10258 (setq ev (condition-case nil
10259 (eval (eval (read form)))
10260 (error "#ERROR"))
10261 ev (if (numberp ev) (number-to-string ev) ev))
10262 (or (fboundp 'calc-eval)
10263 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10264 (setq ev (calc-eval (cons form modes)
10265 (if numbers 'num))))
10267 (when org-table-formula-debug
10268 (with-output-to-temp-buffer "*Substitution History*"
10269 (princ (format "Substitution history of formula
10270 Orig: %s
10271 $xyz-> %s
10272 @r$c-> %s
10273 $1-> %s\n" orig formula form0 form))
10274 (if (listp ev)
10275 (princ (format " %s^\nError: %s"
10276 (make-string (car ev) ?\-) (nth 1 ev)))
10277 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10278 ev (or fmt "NONE")
10279 (if fmt (format fmt (string-to-number ev)) ev)))))
10280 (setq bw (get-buffer-window "*Substitution History*"))
10281 (shrink-window-if-larger-than-buffer bw)
10282 (unless (and (interactive-p) (not ndown))
10283 (unless (let (inhibit-redisplay)
10284 (y-or-n-p "Debugging Formula. Continue to next? "))
10285 (org-table-align)
10286 (error "Abort"))
10287 (delete-window bw)
10288 (message "")))
10289 (if (listp ev) (setq fmt nil ev "#ERROR"))
10290 (org-table-justify-field-maybe
10291 (if fmt (format fmt (string-to-number ev)) ev))
10292 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10293 (call-interactively 'org-return)
10294 (setq ndown 0)))
10295 (and down (org-table-maybe-recalculate-line))
10296 (or suppress-align (and org-table-may-need-update
10297 (org-table-align))))))
10299 (defun org-table-put-field-property (prop value)
10300 (save-excursion
10301 (put-text-property (progn (skip-chars-backward "^|") (point))
10302 (progn (skip-chars-forward "^|") (point))
10303 prop value)))
10305 (defun org-table-get-range (desc &optional tbeg col highlight)
10306 "Get a calc vector from a column, accorting to descriptor DESC.
10307 Optional arguments TBEG and COL can give the beginning of the table and
10308 the current column, to avoid unnecessary parsing.
10309 HIGHLIGHT means, just highlight the range."
10310 (if (not (equal (string-to-char desc) ?@))
10311 (setq desc (concat "@" desc)))
10312 (save-excursion
10313 (or tbeg (setq tbeg (org-table-begin)))
10314 (or col (setq col (org-table-current-column)))
10315 (let ((thisline (org-current-line))
10316 beg end c1 c2 r1 r2 rangep tmp)
10317 (unless (string-match org-table-range-regexp desc)
10318 (error "Invalid table range specifier `%s'" desc))
10319 (setq rangep (match-end 3)
10320 r1 (and (match-end 1) (match-string 1 desc))
10321 r2 (and (match-end 4) (match-string 4 desc))
10322 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10323 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10325 (and c1 (setq c1 (+ (string-to-number c1)
10326 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10327 (and c2 (setq c2 (+ (string-to-number c2)
10328 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10329 (if (equal r1 "") (setq r1 nil))
10330 (if (equal r2 "") (setq r2 nil))
10331 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10332 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10333 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10334 (if (not r1) (setq r1 thisline))
10335 (if (not r2) (setq r2 thisline))
10336 (if (not c1) (setq c1 col))
10337 (if (not c2) (setq c2 col))
10338 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10339 ;; just one field
10340 (progn
10341 (goto-line r1)
10342 (while (not (looking-at org-table-dataline-regexp))
10343 (beginning-of-line 2))
10344 (prog1 (org-trim (org-table-get-field c1))
10345 (if highlight (org-table-highlight-rectangle (point) (point)))))
10346 ;; A range, return a vector
10347 ;; First sort the numbers to get a regular ractangle
10348 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10349 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10350 (goto-line r1)
10351 (while (not (looking-at org-table-dataline-regexp))
10352 (beginning-of-line 2))
10353 (org-table-goto-column c1)
10354 (setq beg (point))
10355 (goto-line r2)
10356 (while (not (looking-at org-table-dataline-regexp))
10357 (beginning-of-line 0))
10358 (org-table-goto-column c2)
10359 (setq end (point))
10360 (if highlight
10361 (org-table-highlight-rectangle
10362 beg (progn (skip-chars-forward "^|\n") (point))))
10363 ;; return string representation of calc vector
10364 (mapcar 'org-trim
10365 (apply 'append (org-table-copy-region beg end)))))))
10367 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10368 "Analyze descriptor DESC and retrieve the corresponding line number.
10369 The cursor is currently in line CLINE, the table begins in line BLINE,
10370 and TABLE is a vector with line types."
10371 (if (string-match "^[0-9]+$" desc)
10372 (aref org-table-dlines (string-to-number desc))
10373 (setq cline (or cline (org-current-line))
10374 bline (or bline org-table-current-begin-line)
10375 table (or table org-table-current-line-types))
10376 (if (or
10377 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10378 ;; 1 2 3 4 5 6
10379 (and (not (match-end 3)) (not (match-end 6)))
10380 (and (match-end 3) (match-end 6) (not (match-end 5))))
10381 (error "invalid row descriptor `%s'" desc))
10382 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10383 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10384 (odir (and (match-end 5) (match-string 5 desc)))
10385 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10386 (i (- cline bline))
10387 (rel (and (match-end 6)
10388 (or (and (match-end 1) (not (match-end 3)))
10389 (match-end 5)))))
10390 (if (and hn (not hdir))
10391 (progn
10392 (setq i 0 hdir "+")
10393 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10394 (if (and (not hn) on (not odir))
10395 (error "should never happen");;(aref org-table-dlines on)
10396 (if (and hn (> hn 0))
10397 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10398 (if on
10399 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10400 (+ bline i)))))
10402 (defun org-find-row-type (table i type backwards relative n)
10403 (let ((l (length table)))
10404 (while (> n 0)
10405 (while (and (setq i (+ i (if backwards -1 1)))
10406 (>= i 0) (< i l)
10407 (not (eq (aref table i) type))
10408 (if (and relative (eq (aref table i) 'hline))
10409 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10410 t)))
10411 (setq n (1- n)))
10412 (if (or (< i 0) (>= i l))
10413 (error "Row descriptior leads outside table")
10414 i)))
10416 (defun org-rewrite-old-row-references (s)
10417 (if (string-match "&[-+0-9I]" s)
10418 (error "Formula contains old &row reference, please rewrite using @-syntax")
10421 (defun org-table-make-reference (elements keep-empty numbers lispp)
10422 "Convert list ELEMENTS to something appropriate to insert into formula.
10423 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10424 NUMBERS indicates that everything should be converted to numbers.
10425 LISPP means to return something appropriate for a Lisp list."
10426 (if (stringp elements) ; just a single val
10427 (if lispp
10428 (if (eq lispp 'literal)
10429 elements
10430 (prin1-to-string (if numbers (string-to-number elements) elements)))
10431 (if (equal elements "") (setq elements "0"))
10432 (if numbers (number-to-string (string-to-number elements)) elements))
10433 (unless keep-empty
10434 (setq elements
10435 (delq nil
10436 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10437 elements))))
10438 (setq elements (or elements '("0")))
10439 (if lispp
10440 (mapconcat
10441 (lambda (x)
10442 (if (eq lispp 'literal)
10444 (prin1-to-string (if numbers (string-to-number x) x))))
10445 elements " ")
10446 (concat "[" (mapconcat
10447 (lambda (x)
10448 (if numbers (number-to-string (string-to-number x)) x))
10449 elements
10450 ",") "]"))))
10452 (defun org-table-recalculate (&optional all noalign)
10453 "Recalculate the current table line by applying all stored formulas.
10454 With prefix arg ALL, do this for all lines in the table."
10455 (interactive "P")
10456 (or (memq this-command org-recalc-commands)
10457 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10458 (unless (org-at-table-p) (error "Not at a table"))
10459 (if (equal all '(16))
10460 (org-table-iterate)
10461 (org-table-get-specials)
10462 (let* ((eqlist (sort (org-table-get-stored-formulas)
10463 (lambda (a b) (string< (car a) (car b)))))
10464 (inhibit-redisplay (not debug-on-error))
10465 (line-re org-table-dataline-regexp)
10466 (thisline (org-current-line))
10467 (thiscol (org-table-current-column))
10468 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10469 ;; Insert constants in all formulas
10470 (setq eqlist
10471 (mapcar (lambda (x)
10472 (setcdr x (org-table-formula-substitute-names (cdr x)))
10474 eqlist))
10475 ;; Split the equation list
10476 (while (setq eq (pop eqlist))
10477 (if (<= (string-to-char (car eq)) ?9)
10478 (push eq eqlnum)
10479 (push eq eqlname)))
10480 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10481 (if all
10482 (progn
10483 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10484 (goto-char (setq beg (org-table-begin)))
10485 (if (re-search-forward org-table-calculate-mark-regexp end t)
10486 ;; This is a table with marked lines, compute selected lines
10487 (setq line-re org-table-recalculate-regexp)
10488 ;; Move forward to the first non-header line
10489 (if (and (re-search-forward org-table-dataline-regexp end t)
10490 (re-search-forward org-table-hline-regexp end t)
10491 (re-search-forward org-table-dataline-regexp end t))
10492 (setq beg (match-beginning 0))
10493 nil))) ;; just leave beg where it is
10494 (setq beg (point-at-bol)
10495 end (move-marker (make-marker) (1+ (point-at-eol)))))
10496 (goto-char beg)
10497 (and all (message "Re-applying formulas to full table..."))
10499 ;; First find the named fields, and mark them untouchanble
10500 (remove-text-properties beg end '(org-untouchable t))
10501 (while (setq eq (pop eqlname))
10502 (setq name (car eq)
10503 a (assoc name org-table-named-field-locations))
10504 (and (not a)
10505 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10506 (setq a (list name
10507 (aref org-table-dlines
10508 (string-to-number (match-string 1 name)))
10509 (string-to-number (match-string 2 name)))))
10510 (when (and a (or all (equal (nth 1 a) thisline)))
10511 (message "Re-applying formula to field: %s" name)
10512 (goto-line (nth 1 a))
10513 (org-table-goto-column (nth 2 a))
10514 (push (append a (list (cdr eq))) eqlname1)
10515 (org-table-put-field-property :org-untouchable t)))
10517 ;; Now evauluate the column formulas, but skip fields covered by
10518 ;; field formulas
10519 (goto-char beg)
10520 (while (re-search-forward line-re end t)
10521 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10522 ;; Unprotected line, recalculate
10523 (and all (message "Re-applying formulas to full table...(line %d)"
10524 (setq cnt (1+ cnt))))
10525 (setq org-last-recalc-line (org-current-line))
10526 (setq eql eqlnum)
10527 (while (setq entry (pop eql))
10528 (goto-line org-last-recalc-line)
10529 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10530 (unless (get-text-property (point) :org-untouchable)
10531 (org-table-eval-formula nil (cdr entry)
10532 'noalign 'nocst 'nostore 'noanalysis)))))
10534 ;; Now evaluate the field formulas
10535 (while (setq eq (pop eqlname1))
10536 (message "Re-applying formula to field: %s" (car eq))
10537 (goto-line (nth 1 eq))
10538 (org-table-goto-column (nth 2 eq))
10539 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10540 'nostore 'noanalysis))
10542 (goto-line thisline)
10543 (org-table-goto-column thiscol)
10544 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10545 (or noalign (and org-table-may-need-update (org-table-align))
10546 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10548 ;; back to initial position
10549 (message "Re-applying formulas...done")
10550 (goto-line thisline)
10551 (org-table-goto-column thiscol)
10552 (or noalign (and org-table-may-need-update (org-table-align))
10553 (and all (message "Re-applying formulas...done"))))))
10555 (defun org-table-iterate (&optional arg)
10556 "Recalculate the table until it does not change anymore."
10557 (interactive "P")
10558 (let ((imax (if arg (prefix-numeric-value arg) 10))
10559 (i 0)
10560 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10561 thistbl)
10562 (catch 'exit
10563 (while (< i imax)
10564 (setq i (1+ i))
10565 (org-table-recalculate 'all)
10566 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10567 (if (not (string= lasttbl thistbl))
10568 (setq lasttbl thistbl)
10569 (if (> i 1)
10570 (message "Convergence after %d iterations" i)
10571 (message "Table was already stable"))
10572 (throw 'exit t)))
10573 (error "No convergence after %d iterations" i))))
10575 (defun org-table-formula-substitute-names (f)
10576 "Replace $const with values in string F."
10577 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10578 ;; First, check for column names
10579 (while (setq start (string-match org-table-column-name-regexp f start))
10580 (setq start (1+ start))
10581 (setq a (assoc (match-string 1 f) org-table-column-names))
10582 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10583 ;; Parameters and constants
10584 (setq start 0)
10585 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10586 (setq start (1+ start))
10587 (if (setq a (save-match-data
10588 (org-table-get-constant (match-string 1 f))))
10589 (setq f (replace-match
10590 (concat (if pp "(") a (if pp ")")) t t f))))
10591 (if org-table-formula-debug
10592 (put-text-property 0 (length f) :orig-formula f1 f))
10595 (defun org-table-get-constant (const)
10596 "Find the value for a parameter or constant in a formula.
10597 Parameters get priority."
10598 (or (cdr (assoc const org-table-local-parameters))
10599 (cdr (assoc const org-table-formula-constants-local))
10600 (cdr (assoc const org-table-formula-constants))
10601 (and (fboundp 'constants-get) (constants-get const))
10602 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10603 (org-entry-get nil (substring const 5) 'inherit))
10604 "#UNDEFINED_NAME"))
10606 (defvar org-table-fedit-map
10607 (let ((map (make-sparse-keymap)))
10608 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10609 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10610 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10611 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10612 (org-defkey map "\C-c?" 'org-table-show-reference)
10613 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10614 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10615 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10616 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10617 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10618 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10619 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10620 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10621 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10622 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10623 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10624 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10625 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10626 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10627 map))
10629 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10630 '("Edit-Formulas"
10631 ["Finish and Install" org-table-fedit-finish t]
10632 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10633 ["Abort" org-table-fedit-abort t]
10634 "--"
10635 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10636 ["Complete Lisp Symbol" lisp-complete-symbol t]
10637 "--"
10638 "Shift Reference at Point"
10639 ["Up" org-table-fedit-ref-up t]
10640 ["Down" org-table-fedit-ref-down t]
10641 ["Left" org-table-fedit-ref-left t]
10642 ["Right" org-table-fedit-ref-right t]
10644 "Change Test Row for Column Formulas"
10645 ["Up" org-table-fedit-line-up t]
10646 ["Down" org-table-fedit-line-down t]
10647 "--"
10648 ["Scroll Table Window" org-table-fedit-scroll t]
10649 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10650 ["Show Table Grid" org-table-fedit-toggle-coordinates
10651 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10652 org-table-overlay-coordinates)]
10653 "--"
10654 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10655 :style toggle :selected org-table-buffer-is-an]))
10657 (defvar org-pos)
10659 (defun org-table-edit-formulas ()
10660 "Edit the formulas of the current table in a separate buffer."
10661 (interactive)
10662 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10663 (beginning-of-line 0))
10664 (unless (org-at-table-p) (error "Not at a table"))
10665 (org-table-get-specials)
10666 (let ((key (org-table-current-field-formula 'key 'noerror))
10667 (eql (sort (org-table-get-stored-formulas 'noerror)
10668 'org-table-formula-less-p))
10669 (pos (move-marker (make-marker) (point)))
10670 (startline 1)
10671 (wc (current-window-configuration))
10672 (titles '((column . "# Column Formulas\n")
10673 (field . "# Field Formulas\n")
10674 (named . "# Named Field Formulas\n")))
10675 entry s type title)
10676 (org-switch-to-buffer-other-window "*Edit Formulas*")
10677 (erase-buffer)
10678 ;; Keep global-font-lock-mode from turning on font-lock-mode
10679 (let ((font-lock-global-modes '(not fundamental-mode)))
10680 (fundamental-mode))
10681 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10682 (org-set-local 'org-pos pos)
10683 (org-set-local 'org-window-configuration wc)
10684 (use-local-map org-table-fedit-map)
10685 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10686 (easy-menu-add org-table-fedit-menu)
10687 (setq startline (org-current-line))
10688 (while (setq entry (pop eql))
10689 (setq type (cond
10690 ((equal (string-to-char (car entry)) ?@) 'field)
10691 ((string-match "^[0-9]" (car entry)) 'column)
10692 (t 'named)))
10693 (when (setq title (assq type titles))
10694 (or (bobp) (insert "\n"))
10695 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10696 (setq titles (delq title titles)))
10697 (if (equal key (car entry)) (setq startline (org-current-line)))
10698 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10699 (car entry) " = " (cdr entry) "\n"))
10700 (remove-text-properties 0 (length s) '(face nil) s)
10701 (insert s))
10702 (if (eq org-table-use-standard-references t)
10703 (org-table-fedit-toggle-ref-type))
10704 (goto-line startline)
10705 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10707 (defun org-table-fedit-post-command ()
10708 (when (not (memq this-command '(lisp-complete-symbol)))
10709 (let ((win (selected-window)))
10710 (save-excursion
10711 (condition-case nil
10712 (org-table-show-reference)
10713 (error nil))
10714 (select-window win)))))
10716 (defun org-table-formula-to-user (s)
10717 "Convert a formula from internal to user representation."
10718 (if (eq org-table-use-standard-references t)
10719 (org-table-convert-refs-to-an s)
10722 (defun org-table-formula-from-user (s)
10723 "Convert a formula from user to internal representation."
10724 (if org-table-use-standard-references
10725 (org-table-convert-refs-to-rc s)
10728 (defun org-table-convert-refs-to-rc (s)
10729 "Convert spreadsheet references from AB7 to @7$28.
10730 Works for single references, but also for entire formulas and even the
10731 full TBLFM line."
10732 (let ((start 0))
10733 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10734 (cond
10735 ((match-end 3)
10736 ;; format match, just advance
10737 (setq start (match-end 0)))
10738 ((and (> (match-beginning 0) 0)
10739 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10740 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10741 ;; 3.e5 or something like this.
10742 (setq start (match-end 0)))
10744 (setq start (match-beginning 0)
10745 s (replace-match
10746 (if (equal (match-string 2 s) "&")
10747 (format "$%d" (org-letters-to-number (match-string 1 s)))
10748 (format "@%d$%d"
10749 (string-to-number (match-string 2 s))
10750 (org-letters-to-number (match-string 1 s))))
10751 t t s)))))
10754 (defun org-table-convert-refs-to-an (s)
10755 "Convert spreadsheet references from to @7$28 to AB7.
10756 Works for single references, but also for entire formulas and even the
10757 full TBLFM line."
10758 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10759 (setq s (replace-match
10760 (format "%s%d"
10761 (org-number-to-letters
10762 (string-to-number (match-string 2 s)))
10763 (string-to-number (match-string 1 s)))
10764 t t s)))
10765 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10766 (setq s (replace-match (concat "\\1"
10767 (org-number-to-letters
10768 (string-to-number (match-string 2 s))) "&")
10769 t nil s)))
10772 (defun org-letters-to-number (s)
10773 "Convert a base 26 number represented by letters into an integer.
10774 For example: AB -> 28."
10775 (let ((n 0))
10776 (setq s (upcase s))
10777 (while (> (length s) 0)
10778 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10779 s (substring s 1)))
10782 (defun org-number-to-letters (n)
10783 "Convert an integer into a base 26 number represented by letters.
10784 For example: 28 -> AB."
10785 (let ((s ""))
10786 (while (> n 0)
10787 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10788 n (/ (1- n) 26)))
10791 (defun org-table-fedit-convert-buffer (function)
10792 "Convert all references in this buffer, using FUNTION."
10793 (let ((line (org-current-line)))
10794 (goto-char (point-min))
10795 (while (not (eobp))
10796 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10797 (delete-region (point) (point-at-eol))
10798 (or (eobp) (forward-char 1)))
10799 (goto-line line)))
10801 (defun org-table-fedit-toggle-ref-type ()
10802 "Convert all references in the buffer from B3 to @3$2 and back."
10803 (interactive)
10804 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10805 (org-table-fedit-convert-buffer
10806 (if org-table-buffer-is-an
10807 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10808 (message "Reference type switched to %s"
10809 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10811 (defun org-table-fedit-ref-up ()
10812 "Shift the reference at point one row/hline up."
10813 (interactive)
10814 (org-table-fedit-shift-reference 'up))
10815 (defun org-table-fedit-ref-down ()
10816 "Shift the reference at point one row/hline down."
10817 (interactive)
10818 (org-table-fedit-shift-reference 'down))
10819 (defun org-table-fedit-ref-left ()
10820 "Shift the reference at point one field to the left."
10821 (interactive)
10822 (org-table-fedit-shift-reference 'left))
10823 (defun org-table-fedit-ref-right ()
10824 "Shift the reference at point one field to the right."
10825 (interactive)
10826 (org-table-fedit-shift-reference 'right))
10828 (defun org-table-fedit-shift-reference (dir)
10829 (cond
10830 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10831 (if (memq dir '(left right))
10832 (org-rematch-and-replace 1 (eq dir 'left))
10833 (error "Cannot shift reference in this direction")))
10834 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10835 ;; A B3-like reference
10836 (if (memq dir '(up down))
10837 (org-rematch-and-replace 2 (eq dir 'up))
10838 (org-rematch-and-replace 1 (eq dir 'left))))
10839 ((org-at-regexp-p
10840 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10841 ;; An internal reference
10842 (if (memq dir '(up down))
10843 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10844 (org-rematch-and-replace 5 (eq dir 'left))))))
10846 (defun org-rematch-and-replace (n &optional decr hline)
10847 "Re-match the group N, and replace it with the shifted refrence."
10848 (or (match-end n) (error "Cannot shift reference in this direction"))
10849 (goto-char (match-beginning n))
10850 (and (looking-at (regexp-quote (match-string n)))
10851 (replace-match (org-shift-refpart (match-string 0) decr hline)
10852 t t)))
10854 (defun org-shift-refpart (ref &optional decr hline)
10855 "Shift a refrence part REF.
10856 If DECR is set, decrease the references row/column, else increase.
10857 If HLINE is set, this may be a hline reference, it certainly is not
10858 a translation reference."
10859 (save-match-data
10860 (let* ((sign (string-match "^[-+]" ref)) n)
10862 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10863 (cond
10864 ((and hline (string-match "^I+" ref))
10865 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10866 (setq n (+ n (if decr -1 1)))
10867 (if (= n 0) (setq n (+ n (if decr -1 1))))
10868 (if sign
10869 (setq sign (if (< n 0) "-" "+") n (abs n))
10870 (setq n (max 1 n)))
10871 (concat sign (make-string n ?I)))
10873 ((string-match "^[0-9]+" ref)
10874 (setq n (string-to-number (concat sign ref)))
10875 (setq n (+ n (if decr -1 1)))
10876 (if sign
10877 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10878 (number-to-string (max 1 n))))
10880 ((string-match "^[a-zA-Z]+" ref)
10881 (org-number-to-letters
10882 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10884 (t (error "Cannot shift reference"))))))
10886 (defun org-table-fedit-toggle-coordinates ()
10887 "Toggle the display of coordinates in the refrenced table."
10888 (interactive)
10889 (let ((pos (marker-position org-pos)))
10890 (with-current-buffer (marker-buffer org-pos)
10891 (save-excursion
10892 (goto-char pos)
10893 (org-table-toggle-coordinate-overlays)))))
10895 (defun org-table-fedit-finish (&optional arg)
10896 "Parse the buffer for formula definitions and install them.
10897 With prefix ARG, apply the new formulas to the table."
10898 (interactive "P")
10899 (org-table-remove-rectangle-highlight)
10900 (if org-table-use-standard-references
10901 (progn
10902 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10903 (setq org-table-buffer-is-an nil)))
10904 (let ((pos org-pos) eql var form)
10905 (goto-char (point-min))
10906 (while (re-search-forward
10907 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10908 nil t)
10909 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10910 form (match-string 3))
10911 (setq form (org-trim form))
10912 (when (not (equal form ""))
10913 (while (string-match "[ \t]*\n[ \t]*" form)
10914 (setq form (replace-match " " t t form)))
10915 (when (assoc var eql)
10916 (error "Double formulas for %s" var))
10917 (push (cons var form) eql)))
10918 (setq org-pos nil)
10919 (set-window-configuration org-window-configuration)
10920 (select-window (get-buffer-window (marker-buffer pos)))
10921 (goto-char pos)
10922 (unless (org-at-table-p)
10923 (error "Lost table position - cannot install formulae"))
10924 (org-table-store-formulas eql)
10925 (move-marker pos nil)
10926 (kill-buffer "*Edit Formulas*")
10927 (if arg
10928 (org-table-recalculate 'all)
10929 (message "New formulas installed - press C-u C-c C-c to apply."))))
10931 (defun org-table-fedit-abort ()
10932 "Abort editing formulas, without installing the changes."
10933 (interactive)
10934 (org-table-remove-rectangle-highlight)
10935 (let ((pos org-pos))
10936 (set-window-configuration org-window-configuration)
10937 (select-window (get-buffer-window (marker-buffer pos)))
10938 (goto-char pos)
10939 (move-marker pos nil)
10940 (message "Formula editing aborted without installing changes")))
10942 (defun org-table-fedit-lisp-indent ()
10943 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10944 (interactive)
10945 (let ((pos (point)) beg end ind)
10946 (beginning-of-line 1)
10947 (cond
10948 ((looking-at "[ \t]")
10949 (goto-char pos)
10950 (call-interactively 'lisp-indent-line))
10951 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10952 ((not (fboundp 'pp-buffer))
10953 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10954 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10955 (goto-char (- (match-end 0) 2))
10956 (setq beg (point))
10957 (setq ind (make-string (current-column) ?\ ))
10958 (condition-case nil (forward-sexp 1)
10959 (error
10960 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10961 (setq end (point))
10962 (save-restriction
10963 (narrow-to-region beg end)
10964 (if (eq last-command this-command)
10965 (progn
10966 (goto-char (point-min))
10967 (setq this-command nil)
10968 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10969 (replace-match " ")))
10970 (pp-buffer)
10971 (untabify (point-min) (point-max))
10972 (goto-char (1+ (point-min)))
10973 (while (re-search-forward "^." nil t)
10974 (beginning-of-line 1)
10975 (insert ind))
10976 (goto-char (point-max))
10977 (backward-delete-char 1)))
10978 (goto-char beg))
10979 (t nil))))
10981 (defvar org-show-positions nil)
10983 (defun org-table-show-reference (&optional local)
10984 "Show the location/value of the $ expression at point."
10985 (interactive)
10986 (org-table-remove-rectangle-highlight)
10987 (catch 'exit
10988 (let ((pos (if local (point) org-pos))
10989 (face2 'highlight)
10990 (org-inhibit-highlight-removal t)
10991 (win (selected-window))
10992 (org-show-positions nil)
10993 var name e what match dest)
10994 (if local (org-table-get-specials))
10995 (setq what (cond
10996 ((or (org-at-regexp-p org-table-range-regexp2)
10997 (org-at-regexp-p org-table-translate-regexp)
10998 (org-at-regexp-p org-table-range-regexp))
10999 (setq match
11000 (save-match-data
11001 (org-table-convert-refs-to-rc (match-string 0))))
11002 'range)
11003 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11004 ((org-at-regexp-p "\\$[0-9]+") 'column)
11005 ((not local) nil)
11006 (t (error "No reference at point")))
11007 match (and what (or match (match-string 0))))
11008 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11009 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11010 'secondary-selection))
11011 (org-add-hook 'before-change-functions
11012 'org-table-remove-rectangle-highlight)
11013 (if (eq what 'name) (setq var (substring match 1)))
11014 (when (eq what 'range)
11015 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11016 (setq match (org-table-formula-substitute-names match)))
11017 (unless local
11018 (save-excursion
11019 (end-of-line 1)
11020 (re-search-backward "^\\S-" nil t)
11021 (beginning-of-line 1)
11022 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11023 (setq dest
11024 (save-match-data
11025 (org-table-convert-refs-to-rc (match-string 1))))
11026 (org-table-add-rectangle-overlay
11027 (match-beginning 1) (match-end 1) face2))))
11028 (if (and (markerp pos) (marker-buffer pos))
11029 (if (get-buffer-window (marker-buffer pos))
11030 (select-window (get-buffer-window (marker-buffer pos)))
11031 (org-switch-to-buffer-other-window (get-buffer-window
11032 (marker-buffer pos)))))
11033 (goto-char pos)
11034 (org-table-force-dataline)
11035 (when dest
11036 (setq name (substring dest 1))
11037 (cond
11038 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11039 (setq e (assoc name org-table-named-field-locations))
11040 (goto-line (nth 1 e))
11041 (org-table-goto-column (nth 2 e)))
11042 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11043 (let ((l (string-to-number (match-string 1 dest)))
11044 (c (string-to-number (match-string 2 dest))))
11045 (goto-line (aref org-table-dlines l))
11046 (org-table-goto-column c)))
11047 (t (org-table-goto-column (string-to-number name))))
11048 (move-marker pos (point))
11049 (org-table-highlight-rectangle nil nil face2))
11050 (cond
11051 ((equal dest match))
11052 ((not match))
11053 ((eq what 'range)
11054 (condition-case nil
11055 (save-excursion
11056 (org-table-get-range match nil nil 'highlight))
11057 (error nil)))
11058 ((setq e (assoc var org-table-named-field-locations))
11059 (goto-line (nth 1 e))
11060 (org-table-goto-column (nth 2 e))
11061 (org-table-highlight-rectangle (point) (point))
11062 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11063 ((setq e (assoc var org-table-column-names))
11064 (org-table-goto-column (string-to-number (cdr e)))
11065 (org-table-highlight-rectangle (point) (point))
11066 (goto-char (org-table-begin))
11067 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11068 (org-table-end) t)
11069 (progn
11070 (goto-char (match-beginning 1))
11071 (org-table-highlight-rectangle)
11072 (message "Named column (column %s)" (cdr e)))
11073 (error "Column name not found")))
11074 ((eq what 'column)
11075 ;; column number
11076 (org-table-goto-column (string-to-number (substring match 1)))
11077 (org-table-highlight-rectangle (point) (point))
11078 (message "Column %s" (substring match 1)))
11079 ((setq e (assoc var org-table-local-parameters))
11080 (goto-char (org-table-begin))
11081 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11082 (progn
11083 (goto-char (match-beginning 1))
11084 (org-table-highlight-rectangle)
11085 (message "Local parameter."))
11086 (error "Parameter not found")))
11088 (cond
11089 ((not var) (error "No reference at point"))
11090 ((setq e (assoc var org-table-formula-constants-local))
11091 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11092 var (cdr e)))
11093 ((setq e (assoc var org-table-formula-constants))
11094 (message "Constant: $%s=%s in `org-table-formula-constants'."
11095 var (cdr e)))
11096 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11097 (message "Constant: $%s=%s, from `constants.el'%s."
11098 var e (format " (%s units)" constants-unit-system)))
11099 (t (error "Undefined name $%s" var)))))
11100 (goto-char pos)
11101 (when (and org-show-positions
11102 (not (memq this-command '(org-table-fedit-scroll
11103 org-table-fedit-scroll-down))))
11104 (push pos org-show-positions)
11105 (push org-table-current-begin-pos org-show-positions)
11106 (let ((min (apply 'min org-show-positions))
11107 (max (apply 'max org-show-positions)))
11108 (goto-char min) (recenter 0)
11109 (goto-char max)
11110 (or (pos-visible-in-window-p max) (recenter -1))))
11111 (select-window win))))
11113 (defun org-table-force-dataline ()
11114 "Make sure the cursor is in a dataline in a table."
11115 (unless (save-excursion
11116 (beginning-of-line 1)
11117 (looking-at org-table-dataline-regexp))
11118 (let* ((re org-table-dataline-regexp)
11119 (p1 (save-excursion (re-search-forward re nil 'move)))
11120 (p2 (save-excursion (re-search-backward re nil 'move))))
11121 (cond ((and p1 p2)
11122 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11123 p1 p2)))
11124 ((or p1 p2) (goto-char (or p1 p2)))
11125 (t (error "No table dataline around here"))))))
11127 (defun org-table-fedit-line-up ()
11128 "Move cursor one line up in the window showing the table."
11129 (interactive)
11130 (org-table-fedit-move 'previous-line))
11132 (defun org-table-fedit-line-down ()
11133 "Move cursor one line down in the window showing the table."
11134 (interactive)
11135 (org-table-fedit-move 'next-line))
11137 (defun org-table-fedit-move (command)
11138 "Move the cursor in the window shoinw the table.
11139 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11140 (let ((org-table-allow-automatic-line-recalculation nil)
11141 (pos org-pos) (win (selected-window)) p)
11142 (select-window (get-buffer-window (marker-buffer org-pos)))
11143 (setq p (point))
11144 (call-interactively command)
11145 (while (and (org-at-table-p)
11146 (org-at-table-hline-p))
11147 (call-interactively command))
11148 (or (org-at-table-p) (goto-char p))
11149 (move-marker pos (point))
11150 (select-window win)))
11152 (defun org-table-fedit-scroll (N)
11153 (interactive "p")
11154 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11155 (scroll-other-window N)))
11157 (defun org-table-fedit-scroll-down (N)
11158 (interactive "p")
11159 (org-table-fedit-scroll (- N)))
11161 (defvar org-table-rectangle-overlays nil)
11163 (defun org-table-add-rectangle-overlay (beg end &optional face)
11164 "Add a new overlay."
11165 (let ((ov (org-make-overlay beg end)))
11166 (org-overlay-put ov 'face (or face 'secondary-selection))
11167 (push ov org-table-rectangle-overlays)))
11169 (defun org-table-highlight-rectangle (&optional beg end face)
11170 "Highlight rectangular region in a table."
11171 (setq beg (or beg (point)) end (or end (point)))
11172 (let ((b (min beg end))
11173 (e (max beg end))
11174 l1 c1 l2 c2 tmp)
11175 (and (boundp 'org-show-positions)
11176 (setq org-show-positions (cons b (cons e org-show-positions))))
11177 (goto-char (min beg end))
11178 (setq l1 (org-current-line)
11179 c1 (org-table-current-column))
11180 (goto-char (max beg end))
11181 (setq l2 (org-current-line)
11182 c2 (org-table-current-column))
11183 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11184 (goto-line l1)
11185 (beginning-of-line 1)
11186 (loop for line from l1 to l2 do
11187 (when (looking-at org-table-dataline-regexp)
11188 (org-table-goto-column c1)
11189 (skip-chars-backward "^|\n") (setq beg (point))
11190 (org-table-goto-column c2)
11191 (skip-chars-forward "^|\n") (setq end (point))
11192 (org-table-add-rectangle-overlay beg end face))
11193 (beginning-of-line 2))
11194 (goto-char b))
11195 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11197 (defun org-table-remove-rectangle-highlight (&rest ignore)
11198 "Remove the rectangle overlays."
11199 (unless org-inhibit-highlight-removal
11200 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11201 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11202 (setq org-table-rectangle-overlays nil)))
11204 (defvar org-table-coordinate-overlays nil
11205 "Collects the cooordinate grid overlays, so that they can be removed.")
11206 (make-variable-buffer-local 'org-table-coordinate-overlays)
11208 (defun org-table-overlay-coordinates ()
11209 "Add overlays to the table at point, to show row/column coordinates."
11210 (interactive)
11211 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11212 (setq org-table-coordinate-overlays nil)
11213 (save-excursion
11214 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11215 (goto-char (org-table-begin))
11216 (while (org-at-table-p)
11217 (setq eol (point-at-eol))
11218 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11219 (push ov org-table-coordinate-overlays)
11220 (setq hline (looking-at org-table-hline-regexp))
11221 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11222 (format "%4d" (setq id (1+ id)))))
11223 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11224 (when hline
11225 (setq ic 0)
11226 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11227 (setq beg (1+ (match-beginning 0))
11228 ic (1+ ic)
11229 s1 (concat "$" (int-to-string ic))
11230 s2 (org-number-to-letters ic)
11231 str (if (eq org-table-use-standard-references t) s2 s1))
11232 (setq ov (org-make-overlay beg (+ beg (length str))))
11233 (push ov org-table-coordinate-overlays)
11234 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11235 (beginning-of-line 2)))))
11237 (defun org-table-toggle-coordinate-overlays ()
11238 "Toggle the display of Row/Column numbers in tables."
11239 (interactive)
11240 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11241 (message "Row/Column number display turned %s"
11242 (if org-table-overlay-coordinates "on" "off"))
11243 (if (and (org-at-table-p) org-table-overlay-coordinates)
11244 (org-table-align))
11245 (unless org-table-overlay-coordinates
11246 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11247 (setq org-table-coordinate-overlays nil)))
11249 (defun org-table-toggle-formula-debugger ()
11250 "Toggle the formula debugger in tables."
11251 (interactive)
11252 (setq org-table-formula-debug (not org-table-formula-debug))
11253 (message "Formula debugging has been turned %s"
11254 (if org-table-formula-debug "on" "off")))
11256 ;;; The orgtbl minor mode
11258 ;; Define a minor mode which can be used in other modes in order to
11259 ;; integrate the org-mode table editor.
11261 ;; This is really a hack, because the org-mode table editor uses several
11262 ;; keys which normally belong to the major mode, for example the TAB and
11263 ;; RET keys. Here is how it works: The minor mode defines all the keys
11264 ;; necessary to operate the table editor, but wraps the commands into a
11265 ;; function which tests if the cursor is currently inside a table. If that
11266 ;; is the case, the table editor command is executed. However, when any of
11267 ;; those keys is used outside a table, the function uses `key-binding' to
11268 ;; look up if the key has an associated command in another currently active
11269 ;; keymap (minor modes, major mode, global), and executes that command.
11270 ;; There might be problems if any of the keys used by the table editor is
11271 ;; otherwise used as a prefix key.
11273 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11274 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11275 ;; addresses this by checking explicitly for both bindings.
11277 ;; The optimized version (see variable `orgtbl-optimized') takes over
11278 ;; all keys which are bound to `self-insert-command' in the *global map*.
11279 ;; Some modes bind other commands to simple characters, for example
11280 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11281 ;; active, this binding is ignored inside tables and replaced with a
11282 ;; modified self-insert.
11284 (defvar orgtbl-mode nil
11285 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11286 table editor in arbitrary modes.")
11287 (make-variable-buffer-local 'orgtbl-mode)
11289 (defvar orgtbl-mode-map (make-keymap)
11290 "Keymap for `orgtbl-mode'.")
11292 ;;;###autoload
11293 (defun turn-on-orgtbl ()
11294 "Unconditionally turn on `orgtbl-mode'."
11295 (orgtbl-mode 1))
11297 (defvar org-old-auto-fill-inhibit-regexp nil
11298 "Local variable used by `orgtbl-mode'")
11300 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11301 "Matches a line belonging to an orgtbl.")
11303 (defconst orgtbl-extra-font-lock-keywords
11304 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11305 0 (quote 'org-table) 'prepend))
11306 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11308 ;;;###autoload
11309 (defun orgtbl-mode (&optional arg)
11310 "The `org-mode' table editor as a minor mode for use in other modes."
11311 (interactive)
11312 (if (org-mode-p)
11313 ;; Exit without error, in case some hook functions calls this
11314 ;; by accident in org-mode.
11315 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11316 (setq orgtbl-mode
11317 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11318 (if orgtbl-mode
11319 (progn
11320 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11321 ;; Make sure we are first in minor-mode-map-alist
11322 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11323 (and c (setq minor-mode-map-alist
11324 (cons c (delq c minor-mode-map-alist)))))
11325 (org-set-local (quote org-table-may-need-update) t)
11326 (org-add-hook 'before-change-functions 'org-before-change-function
11327 nil 'local)
11328 (org-set-local 'org-old-auto-fill-inhibit-regexp
11329 auto-fill-inhibit-regexp)
11330 (org-set-local 'auto-fill-inhibit-regexp
11331 (if auto-fill-inhibit-regexp
11332 (concat orgtbl-line-start-regexp "\\|"
11333 auto-fill-inhibit-regexp)
11334 orgtbl-line-start-regexp))
11335 (org-add-to-invisibility-spec '(org-cwidth))
11336 (when (fboundp 'font-lock-add-keywords)
11337 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11338 (org-restart-font-lock))
11339 (easy-menu-add orgtbl-mode-menu)
11340 (run-hooks 'orgtbl-mode-hook))
11341 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11342 (org-cleanup-narrow-column-properties)
11343 (org-remove-from-invisibility-spec '(org-cwidth))
11344 (remove-hook 'before-change-functions 'org-before-change-function t)
11345 (when (fboundp 'font-lock-remove-keywords)
11346 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11347 (org-restart-font-lock))
11348 (easy-menu-remove orgtbl-mode-menu)
11349 (force-mode-line-update 'all))))
11351 (defun org-cleanup-narrow-column-properties ()
11352 "Remove all properties related to narrow-column invisibility."
11353 (let ((s 1))
11354 (while (setq s (text-property-any s (point-max)
11355 'display org-narrow-column-arrow))
11356 (remove-text-properties s (1+ s) '(display t)))
11357 (setq s 1)
11358 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11359 (remove-text-properties s (1+ s) '(org-cwidth t)))
11360 (setq s 1)
11361 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11362 (remove-text-properties s (1+ s) '(invisible t)))))
11364 ;; Install it as a minor mode.
11365 (put 'orgtbl-mode :included t)
11366 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11367 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11369 (defun orgtbl-make-binding (fun n &rest keys)
11370 "Create a function for binding in the table minor mode.
11371 FUN is the command to call inside a table. N is used to create a unique
11372 command name. KEYS are keys that should be checked in for a command
11373 to execute outside of tables."
11374 (eval
11375 (list 'defun
11376 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11377 '(arg)
11378 (concat "In tables, run `" (symbol-name fun) "'.\n"
11379 "Outside of tables, run the binding of `"
11380 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11381 "'.")
11382 '(interactive "p")
11383 (list 'if
11384 '(org-at-table-p)
11385 (list 'call-interactively (list 'quote fun))
11386 (list 'let '(orgtbl-mode)
11387 (list 'call-interactively
11388 (append '(or)
11389 (mapcar (lambda (k)
11390 (list 'key-binding k))
11391 keys)
11392 '('orgtbl-error))))))))
11394 (defun orgtbl-error ()
11395 "Error when there is no default binding for a table key."
11396 (interactive)
11397 (error "This key has no function outside tables"))
11399 (defun orgtbl-setup ()
11400 "Setup orgtbl keymaps."
11401 (let ((nfunc 0)
11402 (bindings
11403 (list
11404 '([(meta shift left)] org-table-delete-column)
11405 '([(meta left)] org-table-move-column-left)
11406 '([(meta right)] org-table-move-column-right)
11407 '([(meta shift right)] org-table-insert-column)
11408 '([(meta shift up)] org-table-kill-row)
11409 '([(meta shift down)] org-table-insert-row)
11410 '([(meta up)] org-table-move-row-up)
11411 '([(meta down)] org-table-move-row-down)
11412 '("\C-c\C-w" org-table-cut-region)
11413 '("\C-c\M-w" org-table-copy-region)
11414 '("\C-c\C-y" org-table-paste-rectangle)
11415 '("\C-c-" org-table-insert-hline)
11416 '("\C-c}" org-table-toggle-coordinate-overlays)
11417 '("\C-c{" org-table-toggle-formula-debugger)
11418 '("\C-m" org-table-next-row)
11419 '([(shift return)] org-table-copy-down)
11420 '("\C-c\C-q" org-table-wrap-region)
11421 '("\C-c?" org-table-field-info)
11422 '("\C-c " org-table-blank-field)
11423 '("\C-c+" org-table-sum)
11424 '("\C-c=" org-table-eval-formula)
11425 '("\C-c'" org-table-edit-formulas)
11426 '("\C-c`" org-table-edit-field)
11427 '("\C-c*" org-table-recalculate)
11428 '("\C-c|" org-table-create-or-convert-from-region)
11429 '("\C-c^" org-table-sort-lines)
11430 '([(control ?#)] org-table-rotate-recalc-marks)))
11431 elt key fun cmd)
11432 (while (setq elt (pop bindings))
11433 (setq nfunc (1+ nfunc))
11434 (setq key (org-key (car elt))
11435 fun (nth 1 elt)
11436 cmd (orgtbl-make-binding fun nfunc key))
11437 (org-defkey orgtbl-mode-map key cmd))
11439 ;; Special treatment needed for TAB and RET
11440 (org-defkey orgtbl-mode-map [(return)]
11441 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11442 (org-defkey orgtbl-mode-map "\C-m"
11443 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11445 (org-defkey orgtbl-mode-map [(tab)]
11446 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11447 (org-defkey orgtbl-mode-map "\C-i"
11448 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11450 (org-defkey orgtbl-mode-map [(shift tab)]
11451 (orgtbl-make-binding 'org-table-previous-field 104
11452 [(shift tab)] [(tab)] "\C-i"))
11454 (org-defkey orgtbl-mode-map "\M-\C-m"
11455 (orgtbl-make-binding 'org-table-wrap-region 105
11456 "\M-\C-m" [(meta return)]))
11457 (org-defkey orgtbl-mode-map [(meta return)]
11458 (orgtbl-make-binding 'org-table-wrap-region 106
11459 [(meta return)] "\M-\C-m"))
11461 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11462 (when orgtbl-optimized
11463 ;; If the user wants maximum table support, we need to hijack
11464 ;; some standard editing functions
11465 (org-remap orgtbl-mode-map
11466 'self-insert-command 'orgtbl-self-insert-command
11467 'delete-char 'org-delete-char
11468 'delete-backward-char 'org-delete-backward-char)
11469 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11470 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11471 '("OrgTbl"
11472 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11473 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11474 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11475 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11476 "--"
11477 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11478 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11479 ["Copy Field from Above"
11480 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11481 "--"
11482 ("Column"
11483 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11484 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11485 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11486 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11487 ("Row"
11488 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11489 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11490 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11491 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11492 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11493 "--"
11494 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11495 ("Rectangle"
11496 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11497 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11498 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11499 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11500 "--"
11501 ("Radio tables"
11502 ["Insert table template" orgtbl-insert-radio-table
11503 (assq major-mode orgtbl-radio-table-templates)]
11504 ["Comment/uncomment table" orgtbl-toggle-comment t])
11505 "--"
11506 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11507 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11508 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11509 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11510 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11511 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11512 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11513 ["Sum Column/Rectangle" org-table-sum
11514 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11515 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11516 ["Debug Formulas"
11517 org-table-toggle-formula-debugger :active (org-at-table-p)
11518 :keys "C-c {"
11519 :style toggle :selected org-table-formula-debug]
11520 ["Show Col/Row Numbers"
11521 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11522 :keys "C-c }"
11523 :style toggle :selected org-table-overlay-coordinates]
11527 (defun orgtbl-ctrl-c-ctrl-c (arg)
11528 "If the cursor is inside a table, realign the table.
11529 It it is a table to be sent away to a receiver, do it.
11530 With prefix arg, also recompute table."
11531 (interactive "P")
11532 (let ((pos (point)) action)
11533 (save-excursion
11534 (beginning-of-line 1)
11535 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11536 ((looking-at "[ \t]*|") pos)
11537 ((looking-at "#\\+TBLFM:") 'recalc))))
11538 (cond
11539 ((integerp action)
11540 (goto-char action)
11541 (org-table-maybe-eval-formula)
11542 (if arg
11543 (call-interactively 'org-table-recalculate)
11544 (org-table-maybe-recalculate-line))
11545 (call-interactively 'org-table-align)
11546 (orgtbl-send-table 'maybe))
11547 ((eq action 'recalc)
11548 (save-excursion
11549 (beginning-of-line 1)
11550 (skip-chars-backward " \r\n\t")
11551 (if (org-at-table-p)
11552 (org-call-with-arg 'org-table-recalculate t))))
11553 (t (let (orgtbl-mode)
11554 (call-interactively (key-binding "\C-c\C-c")))))))
11556 (defun orgtbl-tab (arg)
11557 "Justification and field motion for `orgtbl-mode'."
11558 (interactive "P")
11559 (if arg (org-table-edit-field t)
11560 (org-table-justify-field-maybe)
11561 (org-table-next-field)))
11563 (defun orgtbl-ret ()
11564 "Justification and field motion for `orgtbl-mode'."
11565 (interactive)
11566 (org-table-justify-field-maybe)
11567 (org-table-next-row))
11569 (defun orgtbl-self-insert-command (N)
11570 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11571 If the cursor is in a table looking at whitespace, the whitespace is
11572 overwritten, and the table is not marked as requiring realignment."
11573 (interactive "p")
11574 (if (and (org-at-table-p)
11576 (and org-table-auto-blank-field
11577 (member last-command
11578 '(orgtbl-hijacker-command-100
11579 orgtbl-hijacker-command-101
11580 orgtbl-hijacker-command-102
11581 orgtbl-hijacker-command-103
11582 orgtbl-hijacker-command-104
11583 orgtbl-hijacker-command-105))
11584 (org-table-blank-field))
11586 (eq N 1)
11587 (looking-at "[^|\n]* +|"))
11588 (let (org-table-may-need-update)
11589 (goto-char (1- (match-end 0)))
11590 (delete-backward-char 1)
11591 (goto-char (match-beginning 0))
11592 (self-insert-command N))
11593 (setq org-table-may-need-update t)
11594 (let (orgtbl-mode)
11595 (call-interactively (key-binding (vector last-input-event))))))
11597 (defun org-force-self-insert (N)
11598 "Needed to enforce self-insert under remapping."
11599 (interactive "p")
11600 (self-insert-command N))
11602 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11603 "Regula expression matching exponentials as produced by calc.")
11605 (defvar org-table-clean-did-remove-column nil)
11607 (defun orgtbl-export (table target)
11608 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11609 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11610 org-table-last-alignment org-table-last-column-widths
11611 maxcol column)
11612 (if (not (fboundp func))
11613 (error "Cannot export orgtbl table to %s" target))
11614 (setq lines (org-table-clean-before-export lines))
11615 (setq table
11616 (mapcar
11617 (lambda (x)
11618 (if (string-match org-table-hline-regexp x)
11619 'hline
11620 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11621 lines))
11622 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11623 table)))
11624 (loop for i from (1- maxcol) downto 0 do
11625 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11626 (setq column (delq nil column))
11627 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11628 (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))
11629 (funcall func table nil)))
11631 (defun orgtbl-send-table (&optional maybe)
11632 "Send a tranformed version of this table to the receiver position.
11633 With argument MAYBE, fail quietly if no transformation is defined for
11634 this table."
11635 (interactive)
11636 (catch 'exit
11637 (unless (org-at-table-p) (error "Not at a table"))
11638 ;; when non-interactive, we assume align has just happened.
11639 (when (interactive-p) (org-table-align))
11640 (save-excursion
11641 (goto-char (org-table-begin))
11642 (beginning-of-line 0)
11643 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11644 (if maybe
11645 (throw 'exit nil)
11646 (error "Don't know how to transform this table."))))
11647 (let* ((name (match-string 1))
11649 (transform (intern (match-string 2)))
11650 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11651 (skip (plist-get params :skip))
11652 (skipcols (plist-get params :skipcols))
11653 (txt (buffer-substring-no-properties
11654 (org-table-begin) (org-table-end)))
11655 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11656 (lines (org-table-clean-before-export lines))
11657 (i0 (if org-table-clean-did-remove-column 2 1))
11658 (table (mapcar
11659 (lambda (x)
11660 (if (string-match org-table-hline-regexp x)
11661 'hline
11662 (org-remove-by-index
11663 (org-split-string (org-trim x) "\\s-*|\\s-*")
11664 skipcols i0)))
11665 lines))
11666 (fun (if (= i0 2) 'cdr 'identity))
11667 (org-table-last-alignment
11668 (org-remove-by-index (funcall fun org-table-last-alignment)
11669 skipcols i0))
11670 (org-table-last-column-widths
11671 (org-remove-by-index (funcall fun org-table-last-column-widths)
11672 skipcols i0)))
11674 (unless (fboundp transform)
11675 (error "No such transformation function %s" transform))
11676 (setq txt (funcall transform table params))
11677 ;; Find the insertion place
11678 (save-excursion
11679 (goto-char (point-min))
11680 (unless (re-search-forward
11681 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11682 (error "Don't know where to insert translated table"))
11683 (goto-char (match-beginning 0))
11684 (beginning-of-line 2)
11685 (setq beg (point))
11686 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11687 (error "Cannot find end of insertion region"))
11688 (beginning-of-line 1)
11689 (delete-region beg (point))
11690 (goto-char beg)
11691 (insert txt "\n"))
11692 (message "Table converted and installed at receiver location"))))
11694 (defun org-remove-by-index (list indices &optional i0)
11695 "Remove the elements in LIST with indices in INDICES.
11696 First element has index 0, or I0 if given."
11697 (if (not indices)
11698 list
11699 (if (integerp indices) (setq indices (list indices)))
11700 (setq i0 (1- (or i0 0)))
11701 (delq :rm (mapcar (lambda (x)
11702 (setq i0 (1+ i0))
11703 (if (memq i0 indices) :rm x))
11704 list))))
11706 (defun orgtbl-toggle-comment ()
11707 "Comment or uncomment the orgtbl at point."
11708 (interactive)
11709 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11710 (re2 (concat "^" orgtbl-line-start-regexp))
11711 (commented (save-excursion (beginning-of-line 1)
11712 (cond ((looking-at re1) t)
11713 ((looking-at re2) nil)
11714 (t (error "Not at an org table")))))
11715 (re (if commented re1 re2))
11716 beg end)
11717 (save-excursion
11718 (beginning-of-line 1)
11719 (while (looking-at re) (beginning-of-line 0))
11720 (beginning-of-line 2)
11721 (setq beg (point))
11722 (while (looking-at re) (beginning-of-line 2))
11723 (setq end (point)))
11724 (comment-region beg end (if commented '(4) nil))))
11726 (defun orgtbl-insert-radio-table ()
11727 "Insert a radio table template appropriate for this major mode."
11728 (interactive)
11729 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11730 (txt (nth 1 e))
11731 name pos)
11732 (unless e (error "No radio table setup defined for %s" major-mode))
11733 (setq name (read-string "Table name: "))
11734 (while (string-match "%n" txt)
11735 (setq txt (replace-match name t t txt)))
11736 (or (bolp) (insert "\n"))
11737 (setq pos (point))
11738 (insert txt)
11739 (goto-char pos)))
11741 (defun org-get-param (params header i sym &optional hsym)
11742 "Get parameter value for symbol SYM.
11743 If this is a header line, actually get the value for the symbol with an
11744 additional \"h\" inserted after the colon.
11745 If the value is a protperty list, get the element for the current column.
11746 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11747 (let ((val (plist-get params sym)))
11748 (and hsym header (setq val (or (plist-get params hsym) val)))
11749 (if (consp val) (plist-get val i) val)))
11751 (defun orgtbl-to-generic (table params)
11752 "Convert the orgtbl-mode TABLE to some other format.
11753 This generic routine can be used for many standard cases.
11754 TABLE is a list, each entry either the symbol `hline' for a horizontal
11755 separator line, or a list of fields for that line.
11756 PARAMS is a property list of parameters that can influence the conversion.
11757 For the generic converter, some parameters are obligatory: You need to
11758 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11759 :splice, you must have :tstart and :tend.
11761 Valid parameters are
11763 :tstart String to start the table. Ignored when :splice is t.
11764 :tend String to end the table. Ignored when :splice is t.
11766 :splice When set to t, return only table body lines, don't wrap
11767 them into :tstart and :tend. Default is nil.
11769 :hline String to be inserted on horizontal separation lines.
11770 May be nil to ignore hlines.
11772 :lstart String to start a new table line.
11773 :lend String to end a table line
11774 :sep Separator between two fields
11775 :lfmt Format for entire line, with enough %s to capture all fields.
11776 If this is present, :lstart, :lend, and :sep are ignored.
11777 :fmt A format to be used to wrap the field, should contain
11778 %s for the original field value. For example, to wrap
11779 everything in dollars, you could use :fmt \"$%s$\".
11780 This may also be a property list with column numbers and
11781 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11783 :hlstart :hlend :hlsep :hlfmt :hfmt
11784 Same as above, specific for the header lines in the table.
11785 All lines before the first hline are treated as header.
11786 If any of these is not present, the data line value is used.
11788 :efmt Use this format to print numbers with exponentials.
11789 The format should have %s twice for inserting mantissa
11790 and exponent, for example \"%s\\\\times10^{%s}\". This
11791 may also be a property list with column numbers and
11792 formats. :fmt will still be applied after :efmt.
11794 In addition to this, the parameters :skip and :skipcols are always handled
11795 directly by `orgtbl-send-table'. See manual."
11796 (interactive)
11797 (let* ((p params)
11798 (splicep (plist-get p :splice))
11799 (hline (plist-get p :hline))
11800 rtn line i fm efm lfmt h)
11802 ;; Do we have a header?
11803 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11804 (setq h t))
11806 ;; Put header
11807 (unless splicep
11808 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11810 ;; Now loop over all lines
11811 (while (setq line (pop table))
11812 (if (eq line 'hline)
11813 ;; A horizontal separator line
11814 (progn (if hline (push hline rtn))
11815 (setq h nil)) ; no longer in header
11816 ;; A normal line. Convert the fields, push line onto the result list
11817 (setq i 0)
11818 (setq line
11819 (mapcar
11820 (lambda (f)
11821 (setq i (1+ i)
11822 fm (org-get-param p h i :fmt :hfmt)
11823 efm (org-get-param p h i :efmt))
11824 (if (and efm (string-match orgtbl-exp-regexp f))
11825 (setq f (format
11826 efm (match-string 1 f) (match-string 2 f))))
11827 (if fm (setq f (format fm f)))
11829 line))
11830 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11831 (push (apply 'format lfmt line) rtn)
11832 (push (concat
11833 (org-get-param p h i :lstart :hlstart)
11834 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11835 (org-get-param p h i :lend :hlend))
11836 rtn))))
11838 (unless splicep
11839 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11841 (mapconcat 'identity (nreverse rtn) "\n")))
11843 (defun orgtbl-to-latex (table params)
11844 "Convert the orgtbl-mode TABLE to LaTeX.
11845 TABLE is a list, each entry either the symbol `hline' for a horizontal
11846 separator line, or a list of fields for that line.
11847 PARAMS is a property list of parameters that can influence the conversion.
11848 Supports all parameters from `orgtbl-to-generic'. Most important for
11849 LaTeX are:
11851 :splice When set to t, return only table body lines, don't wrap
11852 them into a tabular environment. Default is nil.
11854 :fmt A format to be used to wrap the field, should contain %s for the
11855 original field value. For example, to wrap everything in dollars,
11856 use :fmt \"$%s$\". This may also be a property list with column
11857 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11859 :efmt Format for transforming numbers with exponentials. The format
11860 should have %s twice for inserting mantissa and exponent, for
11861 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11862 This may also be a property list with column numbers and formats.
11864 The general parameters :skip and :skipcols have already been applied when
11865 this function is called."
11866 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11867 org-table-last-alignment ""))
11868 (params2
11869 (list
11870 :tstart (concat "\\begin{tabular}{" alignment "}")
11871 :tend "\\end{tabular}"
11872 :lstart "" :lend " \\\\" :sep " & "
11873 :efmt "%s\\,(%s)" :hline "\\hline")))
11874 (orgtbl-to-generic table (org-combine-plists params2 params))))
11876 (defun orgtbl-to-html (table params)
11877 "Convert the orgtbl-mode TABLE to LaTeX.
11878 TABLE is a list, each entry either the symbol `hline' for a horizontal
11879 separator line, or a list of fields for that line.
11880 PARAMS is a property list of parameters that can influence the conversion.
11881 Currently this function recognizes the following parameters:
11883 :splice When set to t, return only table body lines, don't wrap
11884 them into a <table> environment. Default is nil.
11886 The general parameters :skip and :skipcols have already been applied when
11887 this function is called. The function does *not* use `orgtbl-to-generic',
11888 so you cannot specify parameters for it."
11889 (let* ((splicep (plist-get params :splice))
11890 html)
11891 ;; Just call the formatter we already have
11892 ;; We need to make text lines for it, so put the fields back together.
11893 (setq html (org-format-org-table-html
11894 (mapcar
11895 (lambda (x)
11896 (if (eq x 'hline)
11897 "|----+----|"
11898 (concat "| " (mapconcat 'identity x " | ") " |")))
11899 table)
11900 splicep))
11901 (if (string-match "\n+\\'" html)
11902 (setq html (replace-match "" t t html)))
11903 html))
11905 (defun orgtbl-to-texinfo (table params)
11906 "Convert the orgtbl-mode TABLE to TeXInfo.
11907 TABLE is a list, each entry either the symbol `hline' for a horizontal
11908 separator line, or a list of fields for that line.
11909 PARAMS is a property list of parameters that can influence the conversion.
11910 Supports all parameters from `orgtbl-to-generic'. Most important for
11911 TeXInfo are:
11913 :splice nil/t When set to t, return only table body lines, don't wrap
11914 them into a multitable environment. Default is nil.
11916 :fmt fmt A format to be used to wrap the field, should contain
11917 %s for the original field value. For example, to wrap
11918 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11919 This may also be a property list with column numbers and
11920 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11922 :cf \"f1 f2..\" The column fractions for the table. By default these
11923 are computed automatically from the width of the columns
11924 under org-mode.
11926 The general parameters :skip and :skipcols have already been applied when
11927 this function is called."
11928 (let* ((total (float (apply '+ org-table-last-column-widths)))
11929 (colfrac (or (plist-get params :cf)
11930 (mapconcat
11931 (lambda (x) (format "%.3f" (/ (float x) total)))
11932 org-table-last-column-widths " ")))
11933 (params2
11934 (list
11935 :tstart (concat "@multitable @columnfractions " colfrac)
11936 :tend "@end multitable"
11937 :lstart "@item " :lend "" :sep " @tab "
11938 :hlstart "@headitem ")))
11939 (orgtbl-to-generic table (org-combine-plists params2 params))))
11941 ;;;; Link Stuff
11943 ;;; Link abbreviations
11945 (defun org-link-expand-abbrev (link)
11946 "Apply replacements as defined in `org-link-abbrev-alist."
11947 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11948 (let* ((key (match-string 1 link))
11949 (as (or (assoc key org-link-abbrev-alist-local)
11950 (assoc key org-link-abbrev-alist)))
11951 (tag (and (match-end 2) (match-string 3 link)))
11952 rpl)
11953 (if (not as)
11954 link
11955 (setq rpl (cdr as))
11956 (cond
11957 ((symbolp rpl) (funcall rpl tag))
11958 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11959 (t (concat rpl tag)))))
11960 link))
11962 ;;; Storing and inserting links
11964 (defvar org-insert-link-history nil
11965 "Minibuffer history for links inserted with `org-insert-link'.")
11967 (defvar org-stored-links nil
11968 "Contains the links stored with `org-store-link'.")
11970 (defvar org-store-link-plist nil
11971 "Plist with info about the most recently link created with `org-store-link'.")
11973 (defvar org-link-protocols nil
11974 "Link protocols added to Org-mode using `org-add-link-type'.")
11976 (defvar org-store-link-functions nil
11977 "List of functions that are called to create and store a link.
11978 Each function will be called in turn until one returns a non-nil
11979 value. Each function should check if it is responsible for creating
11980 this link (for example by looking at the major mode).
11981 If not, it must exit and return nil.
11982 If yes, it should return a non-nil value after a calling
11983 `org-store-link-props' with a list of properties and values.
11984 Special properties are:
11986 :type The link prefix. like \"http\". This must be given.
11987 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11988 This is obligatory as well.
11989 :description Optional default description for the second pair
11990 of brackets in an Org-mode link. The user can still change
11991 this when inserting this link into an Org-mode buffer.
11993 In addition to these, any additional properties can be specified
11994 and then used in remember templates.")
11996 (defun org-add-link-type (type &optional follow publish)
11997 "Add TYPE to the list of `org-link-types'.
11998 Re-compute all regular expressions depending on `org-link-types'
11999 FOLLOW and PUBLISH are two functions. Both take the link path as
12000 an argument.
12001 FOLLOW should do whatever is necessary to follow the link, for example
12002 to find a file or display a mail message.
12004 PUBLISH takes the path and retuns the string that should be used when
12005 this document is published. FIMXE: This is actually not yet implemented."
12006 (add-to-list 'org-link-types type t)
12007 (org-make-link-regexps)
12008 (add-to-list 'org-link-protocols
12009 (list type follow publish)))
12011 (defun org-add-agenda-custom-command (entry)
12012 "Replace or add a command in `org-agenda-custom-commands'.
12013 This is mostly for hacking and trying a new command - once the command
12014 works you probably want to add it to `org-agenda-custom-commands' for good."
12015 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12016 (if ass
12017 (setcdr ass (cdr entry))
12018 (push entry org-agenda-custom-commands))))
12020 ;;;###autoload
12021 (defun org-store-link (arg)
12022 "\\<org-mode-map>Store an org-link to the current location.
12023 This link is added to `org-stored-links' and can later be inserted
12024 into an org-buffer with \\[org-insert-link].
12026 For some link types, a prefix arg is interpreted:
12027 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12028 For file links, arg negates `org-context-in-file-links'."
12029 (interactive "P")
12030 (setq org-store-link-plist nil) ; reset
12031 (let (link cpltxt desc description search txt)
12032 (cond
12034 ((run-hook-with-args-until-success 'org-store-link-functions)
12035 (setq link (plist-get org-store-link-plist :link)
12036 desc (or (plist-get org-store-link-plist :description) link)))
12038 ((eq major-mode 'bbdb-mode)
12039 (let ((name (bbdb-record-name (bbdb-current-record)))
12040 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12041 (setq cpltxt (concat "bbdb:" (or name company))
12042 link (org-make-link cpltxt))
12043 (org-store-link-props :type "bbdb" :name name :company company)))
12045 ((eq major-mode 'Info-mode)
12046 (setq link (org-make-link "info:"
12047 (file-name-nondirectory Info-current-file)
12048 ":" Info-current-node))
12049 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12050 ":" Info-current-node))
12051 (org-store-link-props :type "info" :file Info-current-file
12052 :node Info-current-node))
12054 ((eq major-mode 'calendar-mode)
12055 (let ((cd (calendar-cursor-to-date)))
12056 (setq link
12057 (format-time-string
12058 (car org-time-stamp-formats)
12059 (apply 'encode-time
12060 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12061 nil nil nil))))
12062 (org-store-link-props :type "calendar" :date cd)))
12064 ((or (eq major-mode 'vm-summary-mode)
12065 (eq major-mode 'vm-presentation-mode))
12066 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12067 (vm-follow-summary-cursor)
12068 (save-excursion
12069 (vm-select-folder-buffer)
12070 (let* ((message (car vm-message-pointer))
12071 (folder buffer-file-name)
12072 (subject (vm-su-subject message))
12073 (to (vm-get-header-contents message "To"))
12074 (from (vm-get-header-contents message "From"))
12075 (message-id (vm-su-message-id message)))
12076 (org-store-link-props :type "vm" :from from :to to :subject subject
12077 :message-id message-id)
12078 (setq message-id (org-remove-angle-brackets message-id))
12079 (setq folder (abbreviate-file-name folder))
12080 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12081 folder)
12082 (setq folder (replace-match "" t t folder)))
12083 (setq cpltxt (org-email-link-description))
12084 (setq link (org-make-link "vm:" folder "#" message-id)))))
12086 ((eq major-mode 'wl-summary-mode)
12087 (let* ((msgnum (wl-summary-message-number))
12088 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12089 msgnum 'message-id))
12090 (wl-message-entity
12091 (if (fboundp 'elmo-message-entity)
12092 (elmo-message-entity
12093 wl-summary-buffer-elmo-folder msgnum)
12094 (elmo-msgdb-overview-get-entity
12095 msgnum (wl-summary-buffer-msgdb))))
12096 (from (wl-summary-line-from))
12097 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12098 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12099 (wl-summary-line-subject))))
12100 (org-store-link-props :type "wl" :from from :to to
12101 :subject subject :message-id message-id)
12102 (setq message-id (org-remove-angle-brackets message-id))
12103 (setq cpltxt (org-email-link-description))
12104 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12105 "#" message-id))))
12107 ((or (equal major-mode 'mh-folder-mode)
12108 (equal major-mode 'mh-show-mode))
12109 (let ((from (org-mhe-get-header "From:"))
12110 (to (org-mhe-get-header "To:"))
12111 (message-id (org-mhe-get-header "Message-Id:"))
12112 (subject (org-mhe-get-header "Subject:")))
12113 (org-store-link-props :type "mh" :from from :to to
12114 :subject subject :message-id message-id)
12115 (setq cpltxt (org-email-link-description))
12116 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12117 (org-remove-angle-brackets message-id)))))
12119 ((or (eq major-mode 'rmail-mode)
12120 (eq major-mode 'rmail-summary-mode))
12121 (save-window-excursion
12122 (save-restriction
12123 (when (eq major-mode 'rmail-summary-mode)
12124 (rmail-show-message rmail-current-message))
12125 (rmail-narrow-to-non-pruned-header)
12126 (let ((folder buffer-file-name)
12127 (message-id (mail-fetch-field "message-id"))
12128 (from (mail-fetch-field "from"))
12129 (to (mail-fetch-field "to"))
12130 (subject (mail-fetch-field "subject")))
12131 (org-store-link-props
12132 :type "rmail" :from from :to to
12133 :subject subject :message-id message-id)
12134 (setq message-id (org-remove-angle-brackets message-id))
12135 (setq cpltxt (org-email-link-description))
12136 (setq link (org-make-link "rmail:" folder "#" message-id)))
12137 (rmail-show-message rmail-current-message))))
12139 ((eq major-mode 'gnus-group-mode)
12140 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12141 (gnus-group-group-name)) ; version
12142 ((fboundp 'gnus-group-name)
12143 (gnus-group-name))
12144 (t "???"))))
12145 (unless group (error "Not on a group"))
12146 (org-store-link-props :type "gnus" :group group)
12147 (setq cpltxt (concat
12148 (if (org-xor arg org-usenet-links-prefer-google)
12149 "http://groups.google.com/groups?group="
12150 "gnus:")
12151 group)
12152 link (org-make-link cpltxt))))
12154 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12155 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12156 (let* ((group gnus-newsgroup-name)
12157 (article (gnus-summary-article-number))
12158 (header (gnus-summary-article-header article))
12159 (from (mail-header-from header))
12160 (message-id (mail-header-id header))
12161 (date (mail-header-date header))
12162 (subject (gnus-summary-subject-string)))
12163 (org-store-link-props :type "gnus" :from from :subject subject
12164 :message-id message-id :group group)
12165 (setq cpltxt (org-email-link-description))
12166 (if (org-xor arg org-usenet-links-prefer-google)
12167 (setq link
12168 (concat
12169 cpltxt "\n "
12170 (format "http://groups.google.com/groups?as_umsgid=%s"
12171 (org-fixup-message-id-for-http message-id))))
12172 (setq link (org-make-link "gnus:" group
12173 "#" (number-to-string article))))))
12175 ((eq major-mode 'w3-mode)
12176 (setq cpltxt (url-view-url t)
12177 link (org-make-link cpltxt))
12178 (org-store-link-props :type "w3" :url (url-view-url t)))
12180 ((eq major-mode 'w3m-mode)
12181 (setq cpltxt (or w3m-current-title w3m-current-url)
12182 link (org-make-link w3m-current-url))
12183 (org-store-link-props :type "w3m" :url (url-view-url t)))
12185 ((setq search (run-hook-with-args-until-success
12186 'org-create-file-search-functions))
12187 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12188 "::" search))
12189 (setq cpltxt (or description link)))
12191 ((eq major-mode 'image-mode)
12192 (setq cpltxt (concat "file:"
12193 (abbreviate-file-name buffer-file-name))
12194 link (org-make-link cpltxt))
12195 (org-store-link-props :type "image" :file buffer-file-name))
12197 ((eq major-mode 'dired-mode)
12198 ;; link to the file in the current line
12199 (setq cpltxt (concat "file:"
12200 (abbreviate-file-name
12201 (expand-file-name
12202 (dired-get-filename nil t))))
12203 link (org-make-link cpltxt)))
12205 ((and buffer-file-name (org-mode-p))
12206 ;; Just link to current headline
12207 (setq cpltxt (concat "file:"
12208 (abbreviate-file-name buffer-file-name)))
12209 ;; Add a context search string
12210 (when (org-xor org-context-in-file-links arg)
12211 ;; Check if we are on a target
12212 (if (org-in-regexp "<<\\(.*?\\)>>")
12213 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12214 (setq txt (cond
12215 ((org-on-heading-p) nil)
12216 ((org-region-active-p)
12217 (buffer-substring (region-beginning) (region-end)))
12218 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12219 (when (or (null txt) (string-match "\\S-" txt))
12220 (setq cpltxt
12221 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12222 desc "NONE"))))
12223 (if (string-match "::\\'" cpltxt)
12224 (setq cpltxt (substring cpltxt 0 -2)))
12225 (setq link (org-make-link cpltxt)))
12227 ((buffer-file-name (buffer-base-buffer))
12228 ;; Just link to this file here.
12229 (setq cpltxt (concat "file:"
12230 (abbreviate-file-name
12231 (buffer-file-name (buffer-base-buffer)))))
12232 ;; Add a context string
12233 (when (org-xor org-context-in-file-links arg)
12234 (setq txt (if (org-region-active-p)
12235 (buffer-substring (region-beginning) (region-end))
12236 (buffer-substring (point-at-bol) (point-at-eol))))
12237 ;; Only use search option if there is some text.
12238 (when (string-match "\\S-" txt)
12239 (setq cpltxt
12240 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12241 desc "NONE")))
12242 (setq link (org-make-link cpltxt)))
12244 ((interactive-p)
12245 (error "Cannot link to a buffer which is not visiting a file"))
12247 (t (setq link nil)))
12249 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12250 (setq link (or link cpltxt)
12251 desc (or desc cpltxt))
12252 (if (equal desc "NONE") (setq desc nil))
12254 (if (and (interactive-p) link)
12255 (progn
12256 (setq org-stored-links
12257 (cons (list link desc) org-stored-links))
12258 (message "Stored: %s" (or desc link)))
12259 (and link (org-make-link-string link desc)))))
12261 (defun org-store-link-props (&rest plist)
12262 "Store link properties, extract names and addresses."
12263 (let (x adr)
12264 (when (setq x (plist-get plist :from))
12265 (setq adr (mail-extract-address-components x))
12266 (plist-put plist :fromname (car adr))
12267 (plist-put plist :fromaddress (nth 1 adr)))
12268 (when (setq x (plist-get plist :to))
12269 (setq adr (mail-extract-address-components x))
12270 (plist-put plist :toname (car adr))
12271 (plist-put plist :toaddress (nth 1 adr))))
12272 (let ((from (plist-get plist :from))
12273 (to (plist-get plist :to)))
12274 (when (and from to org-from-is-user-regexp)
12275 (plist-put plist :fromto
12276 (if (string-match org-from-is-user-regexp from)
12277 (concat "to %t")
12278 (concat "from %f")))))
12279 (setq org-store-link-plist plist))
12281 (defun org-email-link-description (&optional fmt)
12282 "Return the description part of an email link.
12283 This takes information from `org-store-link-plist' and formats it
12284 according to FMT (default from `org-email-link-description-format')."
12285 (setq fmt (or fmt org-email-link-description-format))
12286 (let* ((p org-store-link-plist)
12287 (to (plist-get p :toaddress))
12288 (from (plist-get p :fromaddress))
12289 (table
12290 (list
12291 (cons "%c" (plist-get p :fromto))
12292 (cons "%F" (plist-get p :from))
12293 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12294 (cons "%T" (plist-get p :to))
12295 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12296 (cons "%s" (plist-get p :subject))
12297 (cons "%m" (plist-get p :message-id)))))
12298 (when (string-match "%c" fmt)
12299 ;; Check if the user wrote this message
12300 (if (and org-from-is-user-regexp from to
12301 (save-match-data (string-match org-from-is-user-regexp from)))
12302 (setq fmt (replace-match "to %t" t t fmt))
12303 (setq fmt (replace-match "from %f" t t fmt))))
12304 (org-replace-escapes fmt table)))
12306 (defun org-make-org-heading-search-string (&optional string heading)
12307 "Make search string for STRING or current headline."
12308 (interactive)
12309 (let ((s (or string (org-get-heading))))
12310 (unless (and string (not heading))
12311 ;; We are using a headline, clean up garbage in there.
12312 (if (string-match org-todo-regexp s)
12313 (setq s (replace-match "" t t s)))
12314 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12315 (setq s (replace-match "" t t s)))
12316 (setq s (org-trim s))
12317 (if (string-match (concat "^\\(" org-quote-string "\\|"
12318 org-comment-string "\\)") s)
12319 (setq s (replace-match "" t t s)))
12320 (while (string-match org-ts-regexp s)
12321 (setq s (replace-match "" t t s))))
12322 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12323 (setq s (replace-match " " t t s)))
12324 (or string (setq s (concat "*" s))) ; Add * for headlines
12325 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12327 (defun org-make-link (&rest strings)
12328 "Concatenate STRINGS."
12329 (apply 'concat strings))
12331 (defun org-make-link-string (link &optional description)
12332 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12333 (unless (string-match "\\S-" link)
12334 (error "Empty link"))
12335 (when (stringp description)
12336 ;; Remove brackets from the description, they are fatal.
12337 (while (string-match "\\[" description)
12338 (setq description (replace-match "{" t t description)))
12339 (while (string-match "\\]" description)
12340 (setq description (replace-match "}" t t description))))
12341 (when (equal (org-link-escape link) description)
12342 ;; No description needed, it is identical
12343 (setq description nil))
12344 (when (and (not description)
12345 (not (equal link (org-link-escape link))))
12346 (setq description link))
12347 (concat "[[" (org-link-escape link) "]"
12348 (if description (concat "[" description "]") "")
12349 "]"))
12351 (defconst org-link-escape-chars
12352 '((?\ . "%20")
12353 (?\[ . "%5B")
12354 (?\] . "%5D")
12355 (?\340 . "%E0") ; `a
12356 (?\342 . "%E2") ; ^a
12357 (?\347 . "%E7") ; ,c
12358 (?\350 . "%E8") ; `e
12359 (?\351 . "%E9") ; 'e
12360 (?\352 . "%EA") ; ^e
12361 (?\356 . "%EE") ; ^i
12362 (?\364 . "%F4") ; ^o
12363 (?\371 . "%F9") ; `u
12364 (?\373 . "%FB") ; ^u
12365 (?\; . "%3B")
12366 (?? . "%3F")
12367 (?= . "%3D")
12368 (?+ . "%2B")
12370 "Association list of escapes for some characters problematic in links.
12371 This is the list that is used for internal purposes.")
12373 (defconst org-link-escape-chars-browser
12374 '((?\ . "%20")) ; 32 for the SPC char
12375 "Association list of escapes for some characters problematic in links.
12376 This is the list that is used before handing over to the browser.")
12378 (defun org-link-escape (text &optional table)
12379 "Escape charaters in TEXT that are problematic for links."
12380 (setq table (or table org-link-escape-chars))
12381 (when text
12382 (let ((re (mapconcat (lambda (x) (regexp-quote
12383 (char-to-string (car x))))
12384 table "\\|")))
12385 (while (string-match re text)
12386 (setq text
12387 (replace-match
12388 (cdr (assoc (string-to-char (match-string 0 text))
12389 table))
12390 t t text)))
12391 text)))
12393 (defun org-link-unescape (text &optional table)
12394 "Reverse the action of `org-link-escape'."
12395 (setq table (or table org-link-escape-chars))
12396 (when text
12397 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12398 table "\\|")))
12399 (while (string-match re text)
12400 (setq text
12401 (replace-match
12402 (char-to-string (car (rassoc (match-string 0 text) table)))
12403 t t text)))
12404 text)))
12406 (defun org-xor (a b)
12407 "Exclusive or."
12408 (if a (not b) b))
12410 (defun org-get-header (header)
12411 "Find a header field in the current buffer."
12412 (save-excursion
12413 (goto-char (point-min))
12414 (let ((case-fold-search t) s)
12415 (cond
12416 ((eq header 'from)
12417 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12418 (setq s (match-string 1)))
12419 (while (string-match "\"" s)
12420 (setq s (replace-match "" t t s)))
12421 (if (string-match "[<(].*" s)
12422 (setq s (replace-match "" t t s))))
12423 ((eq header 'message-id)
12424 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12425 (setq s (match-string 1))))
12426 ((eq header 'subject)
12427 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12428 (setq s (match-string 1)))))
12429 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12430 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12431 s)))
12434 (defun org-fixup-message-id-for-http (s)
12435 "Replace special characters in a message id, so it can be used in an http query."
12436 (while (string-match "<" s)
12437 (setq s (replace-match "%3C" t t s)))
12438 (while (string-match ">" s)
12439 (setq s (replace-match "%3E" t t s)))
12440 (while (string-match "@" s)
12441 (setq s (replace-match "%40" t t s)))
12444 ;;;###autoload
12445 (defun org-insert-link-global ()
12446 "Insert a link like Org-mode does.
12447 This command can be called in any mode to insert a link in Org-mode syntax."
12448 (interactive)
12449 (org-run-like-in-org-mode 'org-insert-link))
12451 (defun org-insert-link (&optional complete-file)
12452 "Insert a link. At the prompt, enter the link.
12454 Completion can be used to select a link previously stored with
12455 `org-store-link'. When the empty string is entered (i.e. if you just
12456 press RET at the prompt), the link defaults to the most recently
12457 stored link. As SPC triggers completion in the minibuffer, you need to
12458 use M-SPC or C-q SPC to force the insertion of a space character.
12460 You will also be prompted for a description, and if one is given, it will
12461 be displayed in the buffer instead of the link.
12463 If there is already a link at point, this command will allow you to edit link
12464 and description parts.
12466 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12467 selected using completion. The path to the file will be relative to
12468 the current directory if the file is in the current directory or a
12469 subdirectory. Otherwise, the link will be the absolute path as
12470 completed in the minibuffer (i.e. normally ~/path/to/file).
12472 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12473 is in the current directory or below.
12474 With three \\[universal-argument] prefixes, negate the meaning of
12475 `org-keep-stored-link-after-insertion'."
12476 (interactive "P")
12477 (let* ((wcf (current-window-configuration))
12478 (region (if (org-region-active-p)
12479 (buffer-substring (region-beginning) (region-end))))
12480 (remove (and region (list (region-beginning) (region-end))))
12481 (desc region)
12482 tmphist ; byte-compile incorrectly complains about this
12483 link entry file)
12484 (cond
12485 ((org-in-regexp org-bracket-link-regexp 1)
12486 ;; We do have a link at point, and we are going to edit it.
12487 (setq remove (list (match-beginning 0) (match-end 0)))
12488 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12489 (setq link (read-string "Link: "
12490 (org-link-unescape
12491 (org-match-string-no-properties 1)))))
12492 ((or (org-in-regexp org-angle-link-re)
12493 (org-in-regexp org-plain-link-re))
12494 ;; Convert to bracket link
12495 (setq remove (list (match-beginning 0) (match-end 0))
12496 link (read-string "Link: "
12497 (org-remove-angle-brackets (match-string 0)))))
12498 ((equal complete-file '(4))
12499 ;; Completing read for file names.
12500 (setq file (read-file-name "File: "))
12501 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12502 (pwd1 (file-name-as-directory (abbreviate-file-name
12503 (expand-file-name ".")))))
12504 (cond
12505 ((equal complete-file '(16))
12506 (setq link (org-make-link
12507 "file:"
12508 (abbreviate-file-name (expand-file-name file)))))
12509 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12510 (setq link (org-make-link "file:" (match-string 1 file))))
12511 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12512 (expand-file-name file))
12513 (setq link (org-make-link
12514 "file:" (match-string 1 (expand-file-name file)))))
12515 (t (setq link (org-make-link "file:" file))))))
12517 ;; Read link, with completion for stored links.
12518 (with-output-to-temp-buffer "*Org Links*"
12519 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12520 (when org-stored-links
12521 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12522 (princ (mapconcat
12523 (lambda (x)
12524 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12525 (reverse org-stored-links) "\n"))))
12526 (let ((cw (selected-window)))
12527 (select-window (get-buffer-window "*Org Links*"))
12528 (shrink-window-if-larger-than-buffer)
12529 (setq truncate-lines t)
12530 (select-window cw))
12531 ;; Fake a link history, containing the stored links.
12532 (setq tmphist (append (mapcar 'car org-stored-links)
12533 org-insert-link-history))
12534 (unwind-protect
12535 (setq link (org-completing-read
12536 "Link: "
12537 (append
12538 (mapcar (lambda (x) (list (concat (car x) ":")))
12539 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12540 (mapcar (lambda (x) (list (concat x ":")))
12541 org-link-types))
12542 nil nil nil
12543 'tmphist
12544 (or (car (car org-stored-links)))))
12545 (set-window-configuration wcf)
12546 (kill-buffer "*Org Links*"))
12547 (setq entry (assoc link org-stored-links))
12548 (or entry (push link org-insert-link-history))
12549 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12550 (not org-keep-stored-link-after-insertion))
12551 (setq org-stored-links (delq (assoc link org-stored-links)
12552 org-stored-links)))
12553 (setq desc (or desc (nth 1 entry)))))
12555 (if (string-match org-plain-link-re link)
12556 ;; URL-like link, normalize the use of angular brackets.
12557 (setq link (org-make-link (org-remove-angle-brackets link))))
12559 ;; Check if we are linking to the current file with a search option
12560 ;; If yes, simplify the link by using only the search option.
12561 (when (and buffer-file-name
12562 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12563 (let* ((path (match-string 1 link))
12564 (case-fold-search nil)
12565 (search (match-string 2 link)))
12566 (save-match-data
12567 (if (equal (file-truename buffer-file-name) (file-truename path))
12568 ;; We are linking to this same file, with a search option
12569 (setq link search)))))
12571 ;; Check if we can/should use a relative path. If yes, simplify the link
12572 (when (string-match "\\<file:\\(.*\\)" link)
12573 (let* ((path (match-string 1 link))
12574 (origpath path)
12575 (case-fold-search nil))
12576 (cond
12577 ((eq org-link-file-path-type 'absolute)
12578 (setq path (abbreviate-file-name (expand-file-name path))))
12579 ((eq org-link-file-path-type 'noabbrev)
12580 (setq path (expand-file-name path)))
12581 ((eq org-link-file-path-type 'relative)
12582 (setq path (file-relative-name path)))
12584 (save-match-data
12585 (if (string-match (concat "^" (regexp-quote
12586 (file-name-as-directory
12587 (expand-file-name "."))))
12588 (expand-file-name path))
12589 ;; We are linking a file with relative path name.
12590 (setq path (substring (expand-file-name path)
12591 (match-end 0)))))))
12592 (setq link (concat "file:" path))
12593 (if (equal desc origpath)
12594 (setq desc path))))
12596 (setq desc (read-string "Description: " desc))
12597 (unless (string-match "\\S-" desc) (setq desc nil))
12598 (if remove (apply 'delete-region remove))
12599 (insert (org-make-link-string link desc))))
12601 (defun org-completing-read (&rest args)
12602 (let ((minibuffer-local-completion-map
12603 (copy-keymap minibuffer-local-completion-map)))
12604 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12605 (apply 'completing-read args)))
12607 ;;; Opening/following a link
12608 (defvar org-link-search-failed nil)
12610 (defun org-next-link ()
12611 "Move forward to the next link.
12612 If the link is in hidden text, expose it."
12613 (interactive)
12614 (when (and org-link-search-failed (eq this-command last-command))
12615 (goto-char (point-min))
12616 (message "Link search wrapped back to beginning of buffer"))
12617 (setq org-link-search-failed nil)
12618 (let* ((pos (point))
12619 (ct (org-context))
12620 (a (assoc :link ct)))
12621 (if a (goto-char (nth 2 a)))
12622 (if (re-search-forward org-any-link-re nil t)
12623 (progn
12624 (goto-char (match-beginning 0))
12625 (if (org-invisible-p) (org-show-context)))
12626 (goto-char pos)
12627 (setq org-link-search-failed t)
12628 (error "No further link found"))))
12630 (defun org-previous-link ()
12631 "Move backward to the previous link.
12632 If the link is in hidden text, expose it."
12633 (interactive)
12634 (when (and org-link-search-failed (eq this-command last-command))
12635 (goto-char (point-max))
12636 (message "Link search wrapped back to end of buffer"))
12637 (setq org-link-search-failed nil)
12638 (let* ((pos (point))
12639 (ct (org-context))
12640 (a (assoc :link ct)))
12641 (if a (goto-char (nth 1 a)))
12642 (if (re-search-backward org-any-link-re nil t)
12643 (progn
12644 (goto-char (match-beginning 0))
12645 (if (org-invisible-p) (org-show-context)))
12646 (goto-char pos)
12647 (setq org-link-search-failed t)
12648 (error "No further link found"))))
12650 (defun org-find-file-at-mouse (ev)
12651 "Open file link or URL at mouse."
12652 (interactive "e")
12653 (mouse-set-point ev)
12654 (org-open-at-point 'in-emacs))
12656 (defun org-open-at-mouse (ev)
12657 "Open file link or URL at mouse."
12658 (interactive "e")
12659 (mouse-set-point ev)
12660 (org-open-at-point))
12662 (defvar org-window-config-before-follow-link nil
12663 "The window configuration before following a link.
12664 This is saved in case the need arises to restore it.")
12666 (defvar org-open-link-marker (make-marker)
12667 "Marker pointing to the location where `org-open-at-point; was called.")
12669 ;;;###autoload
12670 (defun org-open-at-point-global ()
12671 "Follow a link like Org-mode does.
12672 This command can be called in any mode to follow a link that has
12673 Org-mode syntax."
12674 (interactive)
12675 (org-run-like-in-org-mode 'org-open-at-point))
12677 (defun org-open-at-point (&optional in-emacs)
12678 "Open link at or after point.
12679 If there is no link at point, this function will search forward up to
12680 the end of the current subtree.
12681 Normally, files will be opened by an appropriate application. If the
12682 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12683 (interactive "P")
12684 (move-marker org-open-link-marker (point))
12685 (setq org-window-config-before-follow-link (current-window-configuration))
12686 (org-remove-occur-highlights nil nil t)
12687 (if (org-at-timestamp-p t)
12688 (org-follow-timestamp-link)
12689 (let (type path link line search (pos (point)))
12690 (catch 'match
12691 (save-excursion
12692 (skip-chars-forward "^]\n\r")
12693 (when (org-in-regexp org-bracket-link-regexp)
12694 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12695 (while (string-match " *\n *" link)
12696 (setq link (replace-match " " t t link)))
12697 (setq link (org-link-expand-abbrev link))
12698 (if (string-match org-link-re-with-space2 link)
12699 (setq type (match-string 1 link) path (match-string 2 link))
12700 (setq type "thisfile" path link))
12701 (throw 'match t)))
12703 (when (get-text-property (point) 'org-linked-text)
12704 (setq type "thisfile"
12705 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12706 (1+ (point)) (point))
12707 path (buffer-substring
12708 (previous-single-property-change pos 'org-linked-text)
12709 (next-single-property-change pos 'org-linked-text)))
12710 (throw 'match t))
12712 (save-excursion
12713 (when (or (org-in-regexp org-angle-link-re)
12714 (org-in-regexp org-plain-link-re))
12715 (setq type (match-string 1) path (match-string 2))
12716 (throw 'match t)))
12717 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12718 (setq type "tree-match"
12719 path (match-string 1))
12720 (throw 'match t))
12721 (save-excursion
12722 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12723 (setq type "tags"
12724 path (match-string 1))
12725 (while (string-match ":" path)
12726 (setq path (replace-match "+" t t path)))
12727 (throw 'match t))))
12728 (unless path
12729 (error "No link found"))
12730 ;; Remove any trailing spaces in path
12731 (if (string-match " +\\'" path)
12732 (setq path (replace-match "" t t path)))
12734 (cond
12736 ((assoc type org-link-protocols)
12737 (funcall (nth 1 (assoc type org-link-protocols)) path))
12739 ((equal type "mailto")
12740 (let ((cmd (car org-link-mailto-program))
12741 (args (cdr org-link-mailto-program)) args1
12742 (address path) (subject "") a)
12743 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12744 (setq address (match-string 1 path)
12745 subject (org-link-escape (match-string 2 path))))
12746 (while args
12747 (cond
12748 ((not (stringp (car args))) (push (pop args) args1))
12749 (t (setq a (pop args))
12750 (if (string-match "%a" a)
12751 (setq a (replace-match address t t a)))
12752 (if (string-match "%s" a)
12753 (setq a (replace-match subject t t a)))
12754 (push a args1))))
12755 (apply cmd (nreverse args1))))
12757 ((member type '("http" "https" "ftp" "news"))
12758 (browse-url (concat type ":" (org-link-escape
12759 path org-link-escape-chars-browser))))
12761 ((member type '("message"))
12762 (browse-url (concat type ":" path)))
12764 ((string= type "tags")
12765 (org-tags-view in-emacs path))
12766 ((string= type "thisfile")
12767 (if in-emacs
12768 (switch-to-buffer-other-window
12769 (org-get-buffer-for-internal-link (current-buffer)))
12770 (org-mark-ring-push))
12771 (let ((cmd `(org-link-search
12772 ,path
12773 ,(cond ((equal in-emacs '(4)) 'occur)
12774 ((equal in-emacs '(16)) 'org-occur)
12775 (t nil))
12776 ,pos)))
12777 (condition-case nil (eval cmd)
12778 (error (progn (widen) (eval cmd))))))
12780 ((string= type "tree-match")
12781 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12783 ((string= type "file")
12784 (if (string-match "::\\([0-9]+\\)\\'" path)
12785 (setq line (string-to-number (match-string 1 path))
12786 path (substring path 0 (match-beginning 0)))
12787 (if (string-match "::\\(.+\\)\\'" path)
12788 (setq search (match-string 1 path)
12789 path (substring path 0 (match-beginning 0)))))
12790 (if (string-match "[*?{]" (file-name-nondirectory path))
12791 (dired path)
12792 (org-open-file path in-emacs line search)))
12794 ((string= type "news")
12795 (org-follow-gnus-link path))
12797 ((string= type "bbdb")
12798 (org-follow-bbdb-link path))
12800 ((string= type "info")
12801 (org-follow-info-link path))
12803 ((string= type "gnus")
12804 (let (group article)
12805 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12806 (error "Error in Gnus link"))
12807 (setq group (match-string 1 path)
12808 article (match-string 3 path))
12809 (org-follow-gnus-link group article)))
12811 ((string= type "vm")
12812 (let (folder article)
12813 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12814 (error "Error in VM link"))
12815 (setq folder (match-string 1 path)
12816 article (match-string 3 path))
12817 ;; in-emacs is the prefix arg, will be interpreted as read-only
12818 (org-follow-vm-link folder article in-emacs)))
12820 ((string= type "wl")
12821 (let (folder article)
12822 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12823 (error "Error in Wanderlust link"))
12824 (setq folder (match-string 1 path)
12825 article (match-string 3 path))
12826 (org-follow-wl-link folder article)))
12828 ((string= type "mhe")
12829 (let (folder article)
12830 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12831 (error "Error in MHE link"))
12832 (setq folder (match-string 1 path)
12833 article (match-string 3 path))
12834 (org-follow-mhe-link folder article)))
12836 ((string= type "rmail")
12837 (let (folder article)
12838 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12839 (error "Error in RMAIL link"))
12840 (setq folder (match-string 1 path)
12841 article (match-string 3 path))
12842 (org-follow-rmail-link folder article)))
12844 ((string= type "shell")
12845 (let ((cmd path))
12846 (if (or (not org-confirm-shell-link-function)
12847 (funcall org-confirm-shell-link-function
12848 (format "Execute \"%s\" in shell? "
12849 (org-add-props cmd nil
12850 'face 'org-warning))))
12851 (progn
12852 (message "Executing %s" cmd)
12853 (shell-command cmd))
12854 (error "Abort"))))
12856 ((string= type "elisp")
12857 (let ((cmd path))
12858 (if (or (not org-confirm-elisp-link-function)
12859 (funcall org-confirm-elisp-link-function
12860 (format "Execute \"%s\" as elisp? "
12861 (org-add-props cmd nil
12862 'face 'org-warning))))
12863 (message "%s => %s" cmd (eval (read cmd)))
12864 (error "Abort"))))
12867 (browse-url-at-point)))))
12868 (move-marker org-open-link-marker nil))
12870 ;;; File search
12872 (defvar org-create-file-search-functions nil
12873 "List of functions to construct the right search string for a file link.
12874 These functions are called in turn with point at the location to
12875 which the link should point.
12877 A function in the hook should first test if it would like to
12878 handle this file type, for example by checking the major-mode or
12879 the file extension. If it decides not to handle this file, it
12880 should just return nil to give other functions a chance. If it
12881 does handle the file, it must return the search string to be used
12882 when following the link. The search string will be part of the
12883 file link, given after a double colon, and `org-open-at-point'
12884 will automatically search for it. If special measures must be
12885 taken to make the search successful, another function should be
12886 added to the companion hook `org-execute-file-search-functions',
12887 which see.
12889 A function in this hook may also use `setq' to set the variable
12890 `description' to provide a suggestion for the descriptive text to
12891 be used for this link when it gets inserted into an Org-mode
12892 buffer with \\[org-insert-link].")
12894 (defvar org-execute-file-search-functions nil
12895 "List of functions to execute a file search triggered by a link.
12897 Functions added to this hook must accept a single argument, the
12898 search string that was part of the file link, the part after the
12899 double colon. The function must first check if it would like to
12900 handle this search, for example by checking the major-mode or the
12901 file extension. If it decides not to handle this search, it
12902 should just return nil to give other functions a chance. If it
12903 does handle the search, it must return a non-nil value to keep
12904 other functions from trying.
12906 Each function can access the current prefix argument through the
12907 variable `current-prefix-argument'. Note that a single prefix is
12908 used to force opening a link in Emacs, so it may be good to only
12909 use a numeric or double prefix to guide the search function.
12911 In case this is needed, a function in this hook can also restore
12912 the window configuration before `org-open-at-point' was called using:
12914 (set-window-configuration org-window-config-before-follow-link)")
12916 (defun org-link-search (s &optional type avoid-pos)
12917 "Search for a link search option.
12918 If S is surrounded by forward slashes, it is interpreted as a
12919 regular expression. In org-mode files, this will create an `org-occur'
12920 sparse tree. In ordinary files, `occur' will be used to list matches.
12921 If the current buffer is in `dired-mode', grep will be used to search
12922 in all files. If AVOID-POS is given, ignore matches near that position."
12923 (let ((case-fold-search t)
12924 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12925 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12926 (append '(("") (" ") ("\t") ("\n"))
12927 org-emphasis-alist)
12928 "\\|") "\\)"))
12929 (pos (point))
12930 (pre "") (post "")
12931 words re0 re1 re2 re3 re4 re5 re2a reall)
12932 (cond
12933 ;; First check if there are any special
12934 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12935 ;; Now try the builtin stuff
12936 ((save-excursion
12937 (goto-char (point-min))
12938 (and
12939 (re-search-forward
12940 (concat "<<" (regexp-quote s0) ">>") nil t)
12941 (setq pos (match-beginning 0))))
12942 ;; There is an exact target for this
12943 (goto-char pos))
12944 ((string-match "^/\\(.*\\)/$" s)
12945 ;; A regular expression
12946 (cond
12947 ((org-mode-p)
12948 (org-occur (match-string 1 s)))
12949 ;;((eq major-mode 'dired-mode)
12950 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12951 (t (org-do-occur (match-string 1 s)))))
12953 ;; A normal search strings
12954 (when (equal (string-to-char s) ?*)
12955 ;; Anchor on headlines, post may include tags.
12956 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12957 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12958 s (substring s 1)))
12959 (remove-text-properties
12960 0 (length s)
12961 '(face nil mouse-face nil keymap nil fontified nil) s)
12962 ;; Make a series of regular expressions to find a match
12963 (setq words (org-split-string s "[ \n\r\t]+")
12964 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12965 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12966 "\\)" markers)
12967 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12968 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12969 re1 (concat pre re2 post)
12970 re3 (concat pre re4 post)
12971 re5 (concat pre ".*" re4)
12972 re2 (concat pre re2)
12973 re2a (concat pre re2a)
12974 re4 (concat pre re4)
12975 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12976 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12977 re5 "\\)"
12979 (cond
12980 ((eq type 'org-occur) (org-occur reall))
12981 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12982 (t (goto-char (point-min))
12983 (if (or (org-search-not-self 1 re0 nil t)
12984 (org-search-not-self 1 re1 nil t)
12985 (org-search-not-self 1 re2 nil t)
12986 (org-search-not-self 1 re2a nil t)
12987 (org-search-not-self 1 re3 nil t)
12988 (org-search-not-self 1 re4 nil t)
12989 (org-search-not-self 1 re5 nil t)
12991 (goto-char (match-beginning 1))
12992 (goto-char pos)
12993 (error "No match")))))
12995 ;; Normal string-search
12996 (goto-char (point-min))
12997 (if (search-forward s nil t)
12998 (goto-char (match-beginning 0))
12999 (error "No match"))))
13000 (and (org-mode-p) (org-show-context 'link-search))))
13002 (defun org-search-not-self (group &rest args)
13003 "Execute `re-search-forward', but only accept matches that do not
13004 enclose the position of `org-open-link-marker'."
13005 (let ((m org-open-link-marker))
13006 (catch 'exit
13007 (while (apply 're-search-forward args)
13008 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13009 (goto-char (match-end group))
13010 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13011 (> (match-beginning 0) (marker-position m))
13012 (< (match-end 0) (marker-position m)))
13013 (save-match-data
13014 (or (not (org-in-regexp
13015 org-bracket-link-analytic-regexp 1))
13016 (not (match-end 4)) ; no description
13017 (and (<= (match-beginning 4) (point))
13018 (>= (match-end 4) (point))))))
13019 (throw 'exit (point))))))))
13021 (defun org-get-buffer-for-internal-link (buffer)
13022 "Return a buffer to be used for displaying the link target of internal links."
13023 (cond
13024 ((not org-display-internal-link-with-indirect-buffer)
13025 buffer)
13026 ((string-match "(Clone)$" (buffer-name buffer))
13027 (message "Buffer is already a clone, not making another one")
13028 ;; we also do not modify visibility in this case
13029 buffer)
13030 (t ; make a new indirect buffer for displaying the link
13031 (let* ((bn (buffer-name buffer))
13032 (ibn (concat bn "(Clone)"))
13033 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13034 (with-current-buffer ib (org-overview))
13035 ib))))
13037 (defun org-do-occur (regexp &optional cleanup)
13038 "Call the Emacs command `occur'.
13039 If CLEANUP is non-nil, remove the printout of the regular expression
13040 in the *Occur* buffer. This is useful if the regex is long and not useful
13041 to read."
13042 (occur regexp)
13043 (when cleanup
13044 (let ((cwin (selected-window)) win beg end)
13045 (when (setq win (get-buffer-window "*Occur*"))
13046 (select-window win))
13047 (goto-char (point-min))
13048 (when (re-search-forward "match[a-z]+" nil t)
13049 (setq beg (match-end 0))
13050 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13051 (setq end (1- (match-beginning 0)))))
13052 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13053 (goto-char (point-min))
13054 (select-window cwin))))
13056 ;;; The mark ring for links jumps
13058 (defvar org-mark-ring nil
13059 "Mark ring for positions before jumps in Org-mode.")
13060 (defvar org-mark-ring-last-goto nil
13061 "Last position in the mark ring used to go back.")
13062 ;; Fill and close the ring
13063 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13064 (loop for i from 1 to org-mark-ring-length do
13065 (push (make-marker) org-mark-ring))
13066 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13067 org-mark-ring)
13069 (defun org-mark-ring-push (&optional pos buffer)
13070 "Put the current position or POS into the mark ring and rotate it."
13071 (interactive)
13072 (setq pos (or pos (point)))
13073 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13074 (move-marker (car org-mark-ring)
13075 (or pos (point))
13076 (or buffer (current-buffer)))
13077 (message "%s"
13078 (substitute-command-keys
13079 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13081 (defun org-mark-ring-goto (&optional n)
13082 "Jump to the previous position in the mark ring.
13083 With prefix arg N, jump back that many stored positions. When
13084 called several times in succession, walk through the entire ring.
13085 Org-mode commands jumping to a different position in the current file,
13086 or to another Org-mode file, automatically push the old position
13087 onto the ring."
13088 (interactive "p")
13089 (let (p m)
13090 (if (eq last-command this-command)
13091 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13092 (setq p org-mark-ring))
13093 (setq org-mark-ring-last-goto p)
13094 (setq m (car p))
13095 (switch-to-buffer (marker-buffer m))
13096 (goto-char m)
13097 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13099 (defun org-remove-angle-brackets (s)
13100 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13101 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13103 (defun org-add-angle-brackets (s)
13104 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13105 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13108 ;;; Following specific links
13110 (defun org-follow-timestamp-link ()
13111 (cond
13112 ((org-at-date-range-p t)
13113 (let ((org-agenda-start-on-weekday)
13114 (t1 (match-string 1))
13115 (t2 (match-string 2)))
13116 (setq t1 (time-to-days (org-time-string-to-time t1))
13117 t2 (time-to-days (org-time-string-to-time t2)))
13118 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13119 ((org-at-timestamp-p t)
13120 (org-agenda-list nil (time-to-days (org-time-string-to-time
13121 (substring (match-string 1) 0 10)))
13123 (t (error "This should not happen"))))
13126 (defun org-follow-bbdb-link (name)
13127 "Follow a BBDB link to NAME."
13128 (require 'bbdb)
13129 (let ((inhibit-redisplay (not debug-on-error))
13130 (bbdb-electric-p nil))
13131 (catch 'exit
13132 ;; Exact match on name
13133 (bbdb-name (concat "\\`" name "\\'") nil)
13134 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13135 ;; Exact match on name
13136 (bbdb-company (concat "\\`" name "\\'") nil)
13137 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13138 ;; Partial match on name
13139 (bbdb-name name nil)
13140 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13141 ;; Partial match on company
13142 (bbdb-company name nil)
13143 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13144 ;; General match including network address and notes
13145 (bbdb name nil)
13146 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13147 (delete-window (get-buffer-window "*BBDB*"))
13148 (error "No matching BBDB record")))))
13150 (defun org-follow-info-link (name)
13151 "Follow an info file & node link to NAME."
13152 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13153 (string-match "\\(.*\\)" name))
13154 (progn
13155 (require 'info)
13156 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13157 (Info-find-node (match-string 1 name) (match-string 2 name))
13158 (Info-find-node (match-string 1 name) "Top")))
13159 (message "Could not open: %s" name)))
13161 (defun org-follow-gnus-link (&optional group article)
13162 "Follow a Gnus link to GROUP and ARTICLE."
13163 (require 'gnus)
13164 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13165 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13166 (cond ((and group article)
13167 (gnus-group-read-group 1 nil group)
13168 (gnus-summary-goto-article (string-to-number article) nil t))
13169 (group (gnus-group-jump-to-group group))))
13171 (defun org-follow-vm-link (&optional folder article readonly)
13172 "Follow a VM link to FOLDER and ARTICLE."
13173 (require 'vm)
13174 (setq article (org-add-angle-brackets article))
13175 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13176 ;; ange-ftp or efs or tramp access
13177 (let ((user (or (match-string 1 folder) (user-login-name)))
13178 (host (match-string 2 folder))
13179 (file (match-string 3 folder)))
13180 (cond
13181 ((featurep 'tramp)
13182 ;; use tramp to access the file
13183 (if (featurep 'xemacs)
13184 (setq folder (format "[%s@%s]%s" user host file))
13185 (setq folder (format "/%s@%s:%s" user host file))))
13187 ;; use ange-ftp or efs
13188 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13189 (setq folder (format "/%s@%s:%s" user host file))))))
13190 (when folder
13191 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13192 (sit-for 0.1)
13193 (when article
13194 (vm-select-folder-buffer)
13195 (widen)
13196 (let ((case-fold-search t))
13197 (goto-char (point-min))
13198 (if (not (re-search-forward
13199 (concat "^" "message-id: *" (regexp-quote article))))
13200 (error "Could not find the specified message in this folder"))
13201 (vm-isearch-update)
13202 (vm-isearch-narrow)
13203 (vm-beginning-of-message)
13204 (vm-summarize)))))
13206 (defun org-follow-wl-link (folder article)
13207 "Follow a Wanderlust link to FOLDER and ARTICLE."
13208 (if (and (string= folder "%")
13209 article
13210 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13211 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13212 ;; Thus, we recompose folder and article ids.
13213 (setq folder (format "%s#%s" folder (match-string 1 article))
13214 article (match-string 3 article)))
13215 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13216 (error "No such folder: %s" folder))
13217 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13218 (and article
13219 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13220 (wl-summary-redisplay)))
13222 (defun org-follow-rmail-link (folder article)
13223 "Follow an RMAIL link to FOLDER and ARTICLE."
13224 (setq article (org-add-angle-brackets article))
13225 (let (message-number)
13226 (save-excursion
13227 (save-window-excursion
13228 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13229 (setq message-number
13230 (save-restriction
13231 (widen)
13232 (goto-char (point-max))
13233 (if (re-search-backward
13234 (concat "^Message-ID:\\s-+" (regexp-quote
13235 (or article "")))
13236 nil t)
13237 (rmail-what-message))))))
13238 (if message-number
13239 (progn
13240 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13241 (rmail-show-message message-number)
13242 message-number)
13243 (error "Message not found"))))
13245 ;;; mh-e integration based on planner-mode
13246 (defun org-mhe-get-message-real-folder ()
13247 "Return the name of the current message real folder, so if you use
13248 sequences, it will now work."
13249 (save-excursion
13250 (let* ((folder
13251 (if (equal major-mode 'mh-folder-mode)
13252 mh-current-folder
13253 ;; Refer to the show buffer
13254 mh-show-folder-buffer))
13255 (end-index
13256 (if (boundp 'mh-index-folder)
13257 (min (length mh-index-folder) (length folder))))
13259 ;; a simple test on mh-index-data does not work, because
13260 ;; mh-index-data is always nil in a show buffer.
13261 (if (and (boundp 'mh-index-folder)
13262 (string= mh-index-folder (substring folder 0 end-index)))
13263 (if (equal major-mode 'mh-show-mode)
13264 (save-window-excursion
13265 (let (pop-up-frames)
13266 (when (buffer-live-p (get-buffer folder))
13267 (progn
13268 (pop-to-buffer folder)
13269 (org-mhe-get-message-folder-from-index)
13272 (org-mhe-get-message-folder-from-index)
13274 folder
13278 (defun org-mhe-get-message-folder-from-index ()
13279 "Returns the name of the message folder in a index folder buffer."
13280 (save-excursion
13281 (mh-index-previous-folder)
13282 (re-search-forward "^\\(+.*\\)$" nil t)
13283 (message "%s" (match-string 1))))
13285 (defun org-mhe-get-message-folder ()
13286 "Return the name of the current message folder. Be careful if you
13287 use sequences."
13288 (save-excursion
13289 (if (equal major-mode 'mh-folder-mode)
13290 mh-current-folder
13291 ;; Refer to the show buffer
13292 mh-show-folder-buffer)))
13294 (defun org-mhe-get-message-num ()
13295 "Return the number of the current message. Be careful if you
13296 use sequences."
13297 (save-excursion
13298 (if (equal major-mode 'mh-folder-mode)
13299 (mh-get-msg-num nil)
13300 ;; Refer to the show buffer
13301 (mh-show-buffer-message-number))))
13303 (defun org-mhe-get-header (header)
13304 "Return a header of the message in folder mode. This will create a
13305 show buffer for the corresponding message. If you have a more clever
13306 idea..."
13307 (let* ((folder (org-mhe-get-message-folder))
13308 (num (org-mhe-get-message-num))
13309 (buffer (get-buffer-create (concat "show-" folder)))
13310 (header-field))
13311 (with-current-buffer buffer
13312 (mh-display-msg num folder)
13313 (if (equal major-mode 'mh-folder-mode)
13314 (mh-header-display)
13315 (mh-show-header-display))
13316 (set-buffer buffer)
13317 (setq header-field (mh-get-header-field header))
13318 (if (equal major-mode 'mh-folder-mode)
13319 (mh-show)
13320 (mh-show-show))
13321 header-field)))
13323 (defun org-follow-mhe-link (folder article)
13324 "Follow an MHE link to FOLDER and ARTICLE.
13325 If ARTICLE is nil FOLDER is shown. If the configuration variable
13326 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13327 ARTICLE is searched in all folders. Indexed searches (swish++,
13328 namazu, and others supported by MH-E) will always search in all
13329 folders."
13330 (require 'mh-e)
13331 (require 'mh-search)
13332 (require 'mh-utils)
13333 (mh-find-path)
13334 (if (not article)
13335 (mh-visit-folder (mh-normalize-folder-name folder))
13336 (setq article (org-add-angle-brackets article))
13337 (mh-search-choose)
13338 (if (equal mh-searcher 'pick)
13339 (progn
13340 (mh-search folder (list "--message-id" article))
13341 (when (and org-mhe-search-all-folders
13342 (not (org-mhe-get-message-real-folder)))
13343 (kill-this-buffer)
13344 (mh-search "+" (list "--message-id" article))))
13345 (mh-search "+" article))
13346 (if (org-mhe-get-message-real-folder)
13347 (mh-show-msg 1)
13348 (kill-this-buffer)
13349 (error "Message not found"))))
13351 ;;; BibTeX links
13353 ;; Use the custom search meachnism to construct and use search strings for
13354 ;; file links to BibTeX database entries.
13356 (defun org-create-file-search-in-bibtex ()
13357 "Create the search string and description for a BibTeX database entry."
13358 (when (eq major-mode 'bibtex-mode)
13359 ;; yes, we want to construct this search string.
13360 ;; Make a good description for this entry, using names, year and the title
13361 ;; Put it into the `description' variable which is dynamically scoped.
13362 (let ((bibtex-autokey-names 1)
13363 (bibtex-autokey-names-stretch 1)
13364 (bibtex-autokey-name-case-convert-function 'identity)
13365 (bibtex-autokey-name-separator " & ")
13366 (bibtex-autokey-additional-names " et al.")
13367 (bibtex-autokey-year-length 4)
13368 (bibtex-autokey-name-year-separator " ")
13369 (bibtex-autokey-titlewords 3)
13370 (bibtex-autokey-titleword-separator " ")
13371 (bibtex-autokey-titleword-case-convert-function 'identity)
13372 (bibtex-autokey-titleword-length 'infty)
13373 (bibtex-autokey-year-title-separator ": "))
13374 (setq description (bibtex-generate-autokey)))
13375 ;; Now parse the entry, get the key and return it.
13376 (save-excursion
13377 (bibtex-beginning-of-entry)
13378 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13380 (defun org-execute-file-search-in-bibtex (s)
13381 "Find the link search string S as a key for a database entry."
13382 (when (eq major-mode 'bibtex-mode)
13383 ;; Yes, we want to do the search in this file.
13384 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13385 (goto-char (point-min))
13386 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13387 (regexp-quote s) "[ \t\n]*,") nil t)
13388 (goto-char (match-beginning 0)))
13389 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13390 ;; Use double prefix to indicate that any web link should be browsed
13391 (let ((b (current-buffer)) (p (point)))
13392 ;; Restore the window configuration because we just use the web link
13393 (set-window-configuration org-window-config-before-follow-link)
13394 (save-excursion (set-buffer b) (goto-char p)
13395 (bibtex-url)))
13396 (recenter 0)) ; Move entry start to beginning of window
13397 ;; return t to indicate that the search is done.
13400 ;; Finally add the functions to the right hooks.
13401 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13402 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13404 ;; end of Bibtex link setup
13406 ;;; Following file links
13408 (defun org-open-file (path &optional in-emacs line search)
13409 "Open the file at PATH.
13410 First, this expands any special file name abbreviations. Then the
13411 configuration variable `org-file-apps' is checked if it contains an
13412 entry for this file type, and if yes, the corresponding command is launched.
13413 If no application is found, Emacs simply visits the file.
13414 With optional argument IN-EMACS, Emacs will visit the file.
13415 Optional LINE specifies a line to go to, optional SEARCH a string to
13416 search for. If LINE or SEARCH is given, the file will always be
13417 opened in Emacs.
13418 If the file does not exist, an error is thrown."
13419 (setq in-emacs (or in-emacs line search))
13420 (let* ((file (if (equal path "")
13421 buffer-file-name
13422 (substitute-in-file-name (expand-file-name path))))
13423 (apps (append org-file-apps (org-default-apps)))
13424 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13425 (dirp (if remp nil (file-directory-p file)))
13426 (dfile (downcase file))
13427 (old-buffer (current-buffer))
13428 (old-pos (point))
13429 (old-mode major-mode)
13430 ext cmd)
13431 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13432 (setq ext (match-string 1 dfile))
13433 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13434 (setq ext (match-string 1 dfile))))
13435 (if in-emacs
13436 (setq cmd 'emacs)
13437 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13438 (and dirp (cdr (assoc 'directory apps)))
13439 (cdr (assoc ext apps))
13440 (cdr (assoc t apps)))))
13441 (when (eq cmd 'mailcap)
13442 (require 'mailcap)
13443 (mailcap-parse-mailcaps)
13444 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13445 (command (mailcap-mime-info mime-type)))
13446 (if (stringp command)
13447 (setq cmd command)
13448 (setq cmd 'emacs))))
13449 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13450 (not (file-exists-p file))
13451 (not org-open-non-existing-files))
13452 (error "No such file: %s" file))
13453 (cond
13454 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13455 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13456 (while (string-match "['\"]%s['\"]" cmd)
13457 (setq cmd (replace-match "%s" t t cmd)))
13458 (while (string-match "%s" cmd)
13459 (setq cmd (replace-match
13460 (save-match-data (shell-quote-argument file))
13461 t t cmd)))
13462 (save-window-excursion
13463 (start-process-shell-command cmd nil cmd)))
13464 ((or (stringp cmd)
13465 (eq cmd 'emacs))
13466 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13467 (widen)
13468 (if line (goto-line line)
13469 (if search (org-link-search search))))
13470 ((consp cmd)
13471 (eval cmd))
13472 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13473 (and (org-mode-p) (eq old-mode 'org-mode)
13474 (or (not (equal old-buffer (current-buffer)))
13475 (not (equal old-pos (point))))
13476 (org-mark-ring-push old-pos old-buffer))))
13478 (defun org-default-apps ()
13479 "Return the default applications for this operating system."
13480 (cond
13481 ((eq system-type 'darwin)
13482 org-file-apps-defaults-macosx)
13483 ((eq system-type 'windows-nt)
13484 org-file-apps-defaults-windowsnt)
13485 (t org-file-apps-defaults-gnu)))
13487 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13488 (defun org-file-remote-p (file)
13489 "Test whether FILE specifies a location on a remote system.
13490 Return non-nil if the location is indeed remote.
13492 For example, the filename \"/user@host:/foo\" specifies a location
13493 on the system \"/user@host:\"."
13494 (cond ((fboundp 'file-remote-p)
13495 (file-remote-p file))
13496 ((fboundp 'tramp-handle-file-remote-p)
13497 (tramp-handle-file-remote-p file))
13498 ((and (boundp 'ange-ftp-name-format)
13499 (string-match (car ange-ftp-name-format) file))
13501 (t nil)))
13504 ;;;; Hooks for remember.el, and refiling
13506 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13507 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13509 ;;;###autoload
13510 (defun org-remember-insinuate ()
13511 "Setup remember.el for use wiht Org-mode."
13512 (require 'remember)
13513 (setq remember-annotation-functions '(org-remember-annotation))
13514 (setq remember-handler-functions '(org-remember-handler))
13515 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13517 ;;;###autoload
13518 (defun org-remember-annotation ()
13519 "Return a link to the current location as an annotation for remember.el.
13520 If you are using Org-mode files as target for data storage with
13521 remember.el, then the annotations should include a link compatible with the
13522 conventions in Org-mode. This function returns such a link."
13523 (org-store-link nil))
13525 (defconst org-remember-help
13526 "Select a destination location for the note.
13527 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13528 RET on headline -> Store as sublevel entry to current headline
13529 RET at beg-of-buf -> Append to file as level 2 headline
13530 <left>/<right> -> before/after current headline, same headings level")
13532 (defvar org-remember-previous-location nil)
13533 (defvar org-force-remember-template-char) ;; dynamically scoped
13535 (defun org-select-remember-template (&optional use-char)
13536 (when org-remember-templates
13537 (let* ((templates (mapcar (lambda (x)
13538 (if (stringp (car x))
13539 (append (list (nth 1 x) (car x)) (cddr x))
13540 (append (list (car x) "") (cdr x))))
13541 org-remember-templates))
13542 (char (or use-char
13543 (cond
13544 ((= (length templates) 1)
13545 (caar templates))
13546 ((and (boundp 'org-force-remember-template-char)
13547 org-force-remember-template-char)
13548 (if (stringp org-force-remember-template-char)
13549 (string-to-char org-force-remember-template-char)
13550 org-force-remember-template-char))
13552 (message "Select template: %s"
13553 (mapconcat
13554 (lambda (x)
13555 (cond
13556 ((not (string-match "\\S-" (nth 1 x)))
13557 (format "[%c]" (car x)))
13558 ((equal (downcase (car x))
13559 (downcase (aref (nth 1 x) 0)))
13560 (format "[%c]%s" (car x)
13561 (substring (nth 1 x) 1)))
13562 (t (format "[%c]%s" (car x) (nth 1 x)))))
13563 templates " "))
13564 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13565 (when (equal char0 ?\C-g)
13566 (jump-to-register remember-register)
13567 (kill-buffer remember-buffer))
13568 char0))))))
13569 (cddr (assoc char templates)))))
13571 (defvar x-last-selected-text)
13572 (defvar x-last-selected-text-primary)
13574 ;;;###autoload
13575 (defun org-remember-apply-template (&optional use-char skip-interactive)
13576 "Initialize *remember* buffer with template, invoke `org-mode'.
13577 This function should be placed into `remember-mode-hook' and in fact requires
13578 to be run from that hook to function properly."
13579 (if org-remember-templates
13580 (let* ((entry (org-select-remember-template use-char))
13581 (tpl (car entry))
13582 (plist-p (if org-store-link-plist t nil))
13583 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13584 (string-match "\\S-" (nth 1 entry)))
13585 (nth 1 entry)
13586 org-default-notes-file))
13587 (headline (nth 2 entry))
13588 (v-c (or (and (eq window-system 'x)
13589 (fboundp 'x-cut-buffer-or-selection-value)
13590 (x-cut-buffer-or-selection-value))
13591 (org-bound-and-true-p x-last-selected-text)
13592 (org-bound-and-true-p x-last-selected-text-primary)
13593 (and (> (length kill-ring) 0) (current-kill 0))))
13594 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13595 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13596 (v-u (concat "[" (substring v-t 1 -1) "]"))
13597 (v-U (concat "[" (substring v-T 1 -1) "]"))
13598 ;; `initial' and `annotation' are bound in `remember'
13599 (v-i (if (boundp 'initial) initial))
13600 (v-a (if (and (boundp 'annotation) annotation)
13601 (if (equal annotation "[[]]") "" annotation)
13602 ""))
13603 (v-A (if (and v-a
13604 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13605 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13606 v-a))
13607 (v-n user-full-name)
13608 (org-startup-folded nil)
13609 org-time-was-given org-end-time-was-given x
13610 prompt completions char time pos default histvar)
13611 (setq org-store-link-plist
13612 (append (list :annotation v-a :initial v-i)
13613 org-store-link-plist))
13614 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13615 (erase-buffer)
13616 (insert (substitute-command-keys
13617 (format
13618 "## Filing location: Select interactively, default, or last used:
13619 ## %s to select file and header location interactively.
13620 ## %s \"%s\" -> \"* %s\"
13621 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13622 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13623 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13624 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13625 (abbreviate-file-name (or file org-default-notes-file))
13626 (or headline "")
13627 (or (car org-remember-previous-location) "???")
13628 (or (cdr org-remember-previous-location) "???"))))
13629 (insert tpl) (goto-char (point-min))
13630 ;; Simple %-escapes
13631 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13632 (when (and initial (equal (match-string 0) "%i"))
13633 (save-match-data
13634 (let* ((lead (buffer-substring
13635 (point-at-bol) (match-beginning 0))))
13636 (setq v-i (mapconcat 'identity
13637 (org-split-string initial "\n")
13638 (concat "\n" lead))))))
13639 (replace-match
13640 (or (eval (intern (concat "v-" (match-string 1)))) "")
13641 t t))
13643 ;; %[] Insert contents of a file.
13644 (goto-char (point-min))
13645 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13646 (let ((start (match-beginning 0))
13647 (end (match-end 0))
13648 (filename (expand-file-name (match-string 1))))
13649 (goto-char start)
13650 (delete-region start end)
13651 (condition-case error
13652 (insert-file-contents filename)
13653 (error (insert (format "%%![Couldn't insert %s: %s]"
13654 filename error))))))
13655 ;; %() embedded elisp
13656 (goto-char (point-min))
13657 (while (re-search-forward "%\\((.+)\\)" nil t)
13658 (goto-char (match-beginning 0))
13659 (let ((template-start (point)))
13660 (forward-char 1)
13661 (let ((result
13662 (condition-case error
13663 (eval (read (current-buffer)))
13664 (error (format "%%![Error: %s]" error)))))
13665 (delete-region template-start (point))
13666 (insert result))))
13668 ;; From the property list
13669 (when plist-p
13670 (goto-char (point-min))
13671 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13672 (and (setq x (or (plist-get org-store-link-plist
13673 (intern (match-string 1))) ""))
13674 (replace-match x t t))))
13676 ;; Turn on org-mode in the remember buffer, set local variables
13677 (org-mode)
13678 (org-set-local 'org-finish-function 'org-remember-finalize)
13679 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13680 (org-set-local 'org-default-notes-file file))
13681 (if (and headline (stringp headline) (string-match "\\S-" headline))
13682 (org-set-local 'org-remember-default-headline headline))
13683 ;; Interactive template entries
13684 (goto-char (point-min))
13685 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13686 (setq char (if (match-end 3) (match-string 3))
13687 prompt (if (match-end 2) (match-string 2)))
13688 (goto-char (match-beginning 0))
13689 (replace-match "")
13690 (setq completions nil default nil)
13691 (when prompt
13692 (setq completions (org-split-string prompt "|")
13693 prompt (pop completions)
13694 default (car completions)
13695 histvar (intern (concat
13696 "org-remember-template-prompt-history::"
13697 (or prompt "")))
13698 completions (mapcar 'list completions)))
13699 (cond
13700 ((member char '("G" "g"))
13701 (let* ((org-last-tags-completion-table
13702 (org-global-tags-completion-table
13703 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13704 (org-add-colon-after-tag-completion t)
13705 (ins (completing-read
13706 (if prompt (concat prompt ": ") "Tags: ")
13707 'org-tags-completion-function nil nil nil
13708 'org-tags-history)))
13709 (setq ins (mapconcat 'identity
13710 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13711 ":"))
13712 (when (string-match "\\S-" ins)
13713 (or (equal (char-before) ?:) (insert ":"))
13714 (insert ins)
13715 (or (equal (char-after) ?:) (insert ":")))))
13716 (char
13717 (setq org-time-was-given (equal (upcase char) char))
13718 (setq time (org-read-date (equal (upcase char) "U") t nil
13719 prompt))
13720 (org-insert-time-stamp time org-time-was-given
13721 (member char '("u" "U"))
13722 nil nil (list org-end-time-was-given)))
13724 (insert (org-completing-read
13725 (concat (if prompt prompt "Enter string")
13726 (if default (concat " [" default "]"))
13727 ": ")
13728 completions nil nil nil histvar default)))))
13729 (goto-char (point-min))
13730 (if (re-search-forward "%\\?" nil t)
13731 (replace-match "")
13732 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13733 (org-mode)
13734 (org-set-local 'org-finish-function 'org-remember-finalize))
13735 (when (save-excursion
13736 (goto-char (point-min))
13737 (re-search-forward "%!" nil t))
13738 (replace-match "")
13739 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13741 (defun org-remember-finish-immediately ()
13742 "File remember note immediately.
13743 This should be run in `post-command-hook' and will remove itself
13744 from that hook."
13745 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13746 (when org-finish-function
13747 (funcall org-finish-function)))
13749 (defvar org-clock-marker) ; Defined below
13750 (defun org-remember-finalize ()
13751 "Finalize the remember process."
13752 (unless (fboundp 'remember-finalize)
13753 (defalias 'remember-finalize 'remember-buffer))
13754 (when (and org-clock-marker
13755 (equal (marker-buffer org-clock-marker) (current-buffer)))
13756 ;; FIXME: test this, this is w/o notetaking!
13757 (let (org-log-note-clock-out) (org-clock-out)))
13758 (when buffer-file-name
13759 (save-buffer)
13760 (setq buffer-file-name nil))
13761 (remember-finalize))
13763 ;;;###autoload
13764 (defun org-remember (&optional goto org-force-remember-template-char)
13765 "Call `remember'. If this is already a remember buffer, re-apply template.
13766 If there is an active region, make sure remember uses it as initial content
13767 of the remember buffer.
13769 When called interactively with a `C-u' prefix argument GOTO, don't remember
13770 anything, just go to the file/headline where the selected template usually
13771 stores its notes. With a double prefix arg `C-u C-u', go to the last
13772 note stored by remember.
13774 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13775 associated with a template in `org-remember-templates'."
13776 (interactive "P")
13777 (cond
13778 ((equal goto '(4)) (org-go-to-remember-target))
13779 ((equal goto '(16)) (org-remember-goto-last-stored))
13781 (if (memq org-finish-function '(remember-buffer remember-finalize))
13782 (progn
13783 (when (< (length org-remember-templates) 2)
13784 (error "No other template available"))
13785 (erase-buffer)
13786 (let ((annotation (plist-get org-store-link-plist :annotation))
13787 (initial (plist-get org-store-link-plist :initial)))
13788 (org-remember-apply-template))
13789 (message "Press C-c C-c to remember data"))
13790 (if (org-region-active-p)
13791 (remember (buffer-substring (point) (mark)))
13792 (call-interactively 'remember))))))
13794 (defun org-remember-goto-last-stored ()
13795 "Go to the location where the last remember note was stored."
13796 (interactive)
13797 (bookmark-jump "org-remember-last-stored")
13798 (message "This is the last note stored by remember"))
13800 (defun org-go-to-remember-target (&optional template-key)
13801 "Go to the target location of a remember template.
13802 The user is queried for the template."
13803 (interactive)
13804 (let* ((entry (org-select-remember-template template-key))
13805 (file (nth 1 entry))
13806 (heading (nth 2 entry))
13807 visiting)
13808 (unless (and file (stringp file) (string-match "\\S-" file))
13809 (setq file org-default-notes-file))
13810 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13811 (setq heading org-remember-default-headline))
13812 (setq visiting (org-find-base-buffer-visiting file))
13813 (if (not visiting) (find-file-noselect file))
13814 (switch-to-buffer (or visiting (get-file-buffer file)))
13815 (widen)
13816 (goto-char (point-min))
13817 (if (re-search-forward
13818 (concat "^\\*+[ \t]+" (regexp-quote heading)
13819 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13820 nil t)
13821 (goto-char (match-beginning 0))
13822 (error "Target headline not found: %s" heading))))
13824 (defvar org-note-abort nil) ; dynamically scoped
13826 ;;;###autoload
13827 (defun org-remember-handler ()
13828 "Store stuff from remember.el into an org file.
13829 First prompts for an org file. If the user just presses return, the value
13830 of `org-default-notes-file' is used.
13831 Then the command offers the headings tree of the selected file in order to
13832 file the text at a specific location.
13833 You can either immediately press RET to get the note appended to the
13834 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13835 find a better place. Then press RET or <left> or <right> in insert the note.
13837 Key Cursor position Note gets inserted
13838 -----------------------------------------------------------------------------
13839 RET buffer-start as level 1 heading at end of file
13840 RET on headline as sublevel of the heading at cursor
13841 RET no heading at cursor position, level taken from context.
13842 Or use prefix arg to specify level manually.
13843 <left> on headline as same level, before current heading
13844 <right> on headline as same level, after current heading
13846 So the fastest way to store the note is to press RET RET to append it to
13847 the default file. This way your current train of thought is not
13848 interrupted, in accordance with the principles of remember.el.
13849 You can also get the fast execution without prompting by using
13850 C-u C-c C-c to exit the remember buffer. See also the variable
13851 `org-remember-store-without-prompt'.
13853 Before being stored away, the function ensures that the text has a
13854 headline, i.e. a first line that starts with a \"*\". If not, a headline
13855 is constructed from the current date and some additional data.
13857 If the variable `org-adapt-indentation' is non-nil, the entire text is
13858 also indented so that it starts in the same column as the headline
13859 \(i.e. after the stars).
13861 See also the variable `org-reverse-note-order'."
13862 (goto-char (point-min))
13863 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13864 (replace-match ""))
13865 (goto-char (point-max))
13866 (beginning-of-line 1)
13867 (while (looking-at "[ \t]*$\\|##.*")
13868 (delete-region (1- (point)) (point-max))
13869 (beginning-of-line 1))
13870 (catch 'quit
13871 (if org-note-abort (throw 'quit nil))
13872 (let* ((txt (buffer-substring (point-min) (point-max)))
13873 (fastp (org-xor (equal current-prefix-arg '(4))
13874 org-remember-store-without-prompt))
13875 (file (cond
13876 (fastp org-default-notes-file)
13877 ((and (eq org-remember-interactive-interface 'refile)
13878 org-refile-targets)
13879 org-default-notes-file)
13880 ((not (and (equal current-prefix-arg '(16))
13881 org-remember-previous-location))
13882 (org-get-org-file))))
13883 (heading org-remember-default-headline)
13884 (visiting (and file (org-find-base-buffer-visiting file)))
13885 (org-startup-folded nil)
13886 (org-startup-align-all-tables nil)
13887 (org-goto-start-pos 1)
13888 spos exitcmd level indent reversed)
13889 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13890 (setq file (car org-remember-previous-location)
13891 heading (cdr org-remember-previous-location)
13892 fastp t))
13893 (setq current-prefix-arg nil)
13894 (if (string-match "[ \t\n]+\\'" txt)
13895 (setq txt (replace-match "" t t txt)))
13896 ;; Modify text so that it becomes a nice subtree which can be inserted
13897 ;; into an org tree.
13898 (let* ((lines (split-string txt "\n"))
13899 first)
13900 (setq first (car lines) lines (cdr lines))
13901 (if (string-match "^\\*+ " first)
13902 ;; Is already a headline
13903 (setq indent nil)
13904 ;; We need to add a headline: Use time and first buffer line
13905 (setq lines (cons first lines)
13906 first (concat "* " (current-time-string)
13907 " (" (remember-buffer-desc) ")")
13908 indent " "))
13909 (if (and org-adapt-indentation indent)
13910 (setq lines (mapcar
13911 (lambda (x)
13912 (if (string-match "\\S-" x)
13913 (concat indent x) x))
13914 lines)))
13915 (setq txt (concat first "\n"
13916 (mapconcat 'identity lines "\n"))))
13917 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13918 (setq txt (replace-match "\n\n" t t txt))
13919 (if (string-match "[ \t\n]*\\'" txt)
13920 (setq txt (replace-match "\n" t t txt))))
13921 ;; Put the modified text back into the remember buffer, for refile.
13922 (erase-buffer)
13923 (insert txt)
13924 (goto-char (point-min))
13925 (when (and (eq org-remember-interactive-interface 'refile)
13926 (not fastp))
13927 (org-refile nil (or visiting (find-file-noselect file)))
13928 (throw 'quit t))
13929 ;; Find the file
13930 (if (not visiting) (find-file-noselect file))
13931 (with-current-buffer (or visiting (get-file-buffer file))
13932 (unless (org-mode-p)
13933 (error "Target files for remember notes must be in Org-mode"))
13934 (save-excursion
13935 (save-restriction
13936 (widen)
13937 (and (goto-char (point-min))
13938 (not (re-search-forward "^\\* " nil t))
13939 (insert "\n* " (or heading "Notes") "\n"))
13940 (setq reversed (org-notes-order-reversed-p))
13942 ;; Find the default location
13943 (when (and heading (stringp heading) (string-match "\\S-" heading))
13944 (goto-char (point-min))
13945 (if (re-search-forward
13946 (concat "^\\*+[ \t]+" (regexp-quote heading)
13947 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13948 nil t)
13949 (setq org-goto-start-pos (match-beginning 0))
13950 (when fastp
13951 (goto-char (point-max))
13952 (unless (bolp) (newline))
13953 (insert "* " heading "\n")
13954 (setq org-goto-start-pos (point-at-bol 0)))))
13956 ;; Ask the User for a location, using the appropriate interface
13957 (cond
13958 (fastp (setq spos org-goto-start-pos
13959 exitcmd 'return))
13960 ((eq org-remember-interactive-interface 'outline)
13961 (setq spos (org-get-location (current-buffer)
13962 org-remember-help)
13963 exitcmd (cdr spos)
13964 spos (car spos)))
13965 ((eq org-remember-interactive-interface 'outline-path-completion)
13966 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13967 (org-refile-use-outline-path t))
13968 (setq spos (org-refile-get-location "Heading: ")
13969 exitcmd 'return
13970 spos (nth 3 spos))))
13971 (t (error "this should not hapen")))
13972 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13973 ; not handle this note
13974 (goto-char spos)
13975 (cond ((org-on-heading-p t)
13976 (org-back-to-heading t)
13977 (setq level (funcall outline-level))
13978 (cond
13979 ((eq exitcmd 'return)
13980 ;; sublevel of current
13981 (setq org-remember-previous-location
13982 (cons (abbreviate-file-name file)
13983 (org-get-heading 'notags)))
13984 (if reversed
13985 (outline-next-heading)
13986 (org-end-of-subtree t)
13987 (if (not (bolp))
13988 (if (looking-at "[ \t]*\n")
13989 (beginning-of-line 2)
13990 (end-of-line 1)
13991 (insert "\n"))))
13992 (bookmark-set "org-remember-last-stored")
13993 (org-paste-subtree (org-get-legal-level level 1) txt))
13994 ((eq exitcmd 'left)
13995 ;; before current
13996 (bookmark-set "org-remember-last-stored")
13997 (org-paste-subtree level txt))
13998 ((eq exitcmd 'right)
13999 ;; after current
14000 (org-end-of-subtree t)
14001 (bookmark-set "org-remember-last-stored")
14002 (org-paste-subtree level txt))
14003 (t (error "This should not happen"))))
14005 ((and (bobp) (not reversed))
14006 ;; Put it at the end, one level below level 1
14007 (save-restriction
14008 (widen)
14009 (goto-char (point-max))
14010 (if (not (bolp)) (newline))
14011 (bookmark-set "org-remember-last-stored")
14012 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14014 ((and (bobp) reversed)
14015 ;; Put it at the start, as level 1
14016 (save-restriction
14017 (widen)
14018 (goto-char (point-min))
14019 (re-search-forward "^\\*+ " nil t)
14020 (beginning-of-line 1)
14021 (bookmark-set "org-remember-last-stored")
14022 (org-paste-subtree 1 txt)))
14024 ;; Put it right there, with automatic level determined by
14025 ;; org-paste-subtree or from prefix arg
14026 (bookmark-set "org-remember-last-stored")
14027 (org-paste-subtree
14028 (if (numberp current-prefix-arg) current-prefix-arg)
14029 txt)))
14030 (when remember-save-after-remembering
14031 (save-buffer)
14032 (if (not visiting) (kill-buffer (current-buffer)))))))))
14034 t) ;; return t to indicate that we took care of this note.
14036 (defun org-get-org-file ()
14037 "Read a filename, with default directory `org-directory'."
14038 (let ((default (or org-default-notes-file remember-data-file)))
14039 (read-file-name (format "File name [%s]: " default)
14040 (file-name-as-directory org-directory)
14041 default)))
14043 (defun org-notes-order-reversed-p ()
14044 "Check if the current file should receive notes in reversed order."
14045 (cond
14046 ((not org-reverse-note-order) nil)
14047 ((eq t org-reverse-note-order) t)
14048 ((not (listp org-reverse-note-order)) nil)
14049 (t (catch 'exit
14050 (let ((all org-reverse-note-order)
14051 entry)
14052 (while (setq entry (pop all))
14053 (if (string-match (car entry) buffer-file-name)
14054 (throw 'exit (cdr entry))))
14055 nil)))))
14057 ;;; Refiling
14059 (defvar org-refile-target-table nil
14060 "The list of refile targets, created by `org-refile'.")
14062 (defvar org-agenda-new-buffers nil
14063 "Buffers created to visit agenda files.")
14065 (defun org-get-refile-targets (&optional default-buffer)
14066 "Produce a table with refile targets."
14067 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14068 targets txt re files f desc descre)
14069 (with-current-buffer (or default-buffer (current-buffer))
14070 (while (setq entry (pop entries))
14071 (setq files (car entry) desc (cdr entry))
14072 (cond
14073 ((null files) (setq files (list (current-buffer))))
14074 ((eq files 'org-agenda-files)
14075 (setq files (org-agenda-files 'unrestricted)))
14076 ((and (symbolp files) (fboundp files))
14077 (setq files (funcall files)))
14078 ((and (symbolp files) (boundp files))
14079 (setq files (symbol-value files))))
14080 (if (stringp files) (setq files (list files)))
14081 (cond
14082 ((eq (car desc) :tag)
14083 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14084 ((eq (car desc) :todo)
14085 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14086 ((eq (car desc) :regexp)
14087 (setq descre (cdr desc)))
14088 ((eq (car desc) :level)
14089 (setq descre (concat "^\\*\\{" (number-to-string
14090 (if org-odd-levels-only
14091 (1- (* 2 (cdr desc)))
14092 (cdr desc)))
14093 "\\}[ \t]")))
14094 ((eq (car desc) :maxlevel)
14095 (setq descre (concat "^\\*\\{1," (number-to-string
14096 (if org-odd-levels-only
14097 (1- (* 2 (cdr desc)))
14098 (cdr desc)))
14099 "\\}[ \t]")))
14100 (t (error "Bad refiling target description %s" desc)))
14101 (while (setq f (pop files))
14102 (save-excursion
14103 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14104 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14105 (save-excursion
14106 (save-restriction
14107 (widen)
14108 (goto-char (point-min))
14109 (while (re-search-forward descre nil t)
14110 (goto-char (point-at-bol))
14111 (when (looking-at org-complex-heading-regexp)
14112 (setq txt (match-string 4)
14113 re (concat "^" (regexp-quote
14114 (buffer-substring (match-beginning 1)
14115 (match-end 4)))))
14116 (if (match-end 5) (setq re (concat re "[ \t]+"
14117 (regexp-quote
14118 (match-string 5)))))
14119 (setq re (concat re "[ \t]*$"))
14120 (when org-refile-use-outline-path
14121 (setq txt (mapconcat 'identity
14122 (append
14123 (if (eq org-refile-use-outline-path 'file)
14124 (list (file-name-nondirectory
14125 (buffer-file-name (buffer-base-buffer))))
14126 (if (eq org-refile-use-outline-path 'full-file-path)
14127 (list (buffer-file-name (buffer-base-buffer)))))
14128 (org-get-outline-path)
14129 (list txt))
14130 "/")))
14131 (push (list txt f re (point)) targets))
14132 (goto-char (point-at-eol))))))))
14133 (nreverse targets))))
14135 (defun org-get-outline-path ()
14136 "Return the outline path to the current entry, as a list."
14137 (let (rtn)
14138 (save-excursion
14139 (while (org-up-heading-safe)
14140 (when (looking-at org-complex-heading-regexp)
14141 (push (org-match-string-no-properties 4) rtn)))
14142 rtn)))
14144 (defvar org-refile-history nil
14145 "History for refiling operations.")
14147 (defun org-refile (&optional goto default-buffer)
14148 "Move the entry at point to another heading.
14149 The list of target headings is compiled using the information in
14150 `org-refile-targets', which see. This list is created upon first use, and
14151 you can update it by calling this command with a double prefix (`C-u C-u').
14152 FIXME: Can we find a better way of updating?
14154 At the target location, the entry is filed as a subitem of the target heading.
14155 Depending on `org-reverse-note-order', the new subitem will either be the
14156 first of the last subitem.
14158 With prefix arg GOTO, the command will only visit the target location,
14159 not actually move anything.
14160 With a double prefix `C-c C-c', go to the location where the last refiling
14161 operation has put the subtree.
14163 With a double prefix argument, the command can be used to jump to any
14164 heading in the current buffer."
14165 (interactive "P")
14166 (let* ((cbuf (current-buffer))
14167 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14168 pos it nbuf file re level reversed)
14169 (if (equal goto '(16))
14170 (org-refile-goto-last-stored)
14171 (when (setq it (org-refile-get-location
14172 (if goto "Goto: " "Refile to: ") default-buffer))
14173 (setq file (nth 1 it)
14174 re (nth 2 it)
14175 pos (nth 3 it))
14176 (setq nbuf (or (find-buffer-visiting file)
14177 (find-file-noselect file)))
14178 (if goto
14179 (progn
14180 (switch-to-buffer nbuf)
14181 (goto-char pos)
14182 (org-show-context 'org-goto))
14183 (org-copy-special)
14184 (save-excursion
14185 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14186 (find-file-noselect file))))
14187 (setq reversed (org-notes-order-reversed-p))
14188 (save-excursion
14189 (save-restriction
14190 (widen)
14191 (goto-char pos)
14192 (looking-at outline-regexp)
14193 (setq level (org-get-legal-level (funcall outline-level) 1))
14194 (goto-char
14195 (if reversed
14196 (outline-next-heading)
14197 (or (save-excursion (outline-get-next-sibling))
14198 (org-end-of-subtree t t)
14199 (point-max))))
14200 (bookmark-set "org-refile-last-stored")
14201 (org-paste-subtree level))))
14202 (org-cut-special)
14203 (message "Entry refiled to \"%s\"" (car it)))))))
14205 (defun org-refile-goto-last-stored ()
14206 "Go to the location where the last refile was stored."
14207 (interactive)
14208 (bookmark-jump "org-refile-last-stored")
14209 (message "This is the location of the last refile"))
14211 (defun org-refile-get-location (&optional prompt default-buffer)
14212 "Prompt the user for a refile location, using PROMPT."
14213 (let ((org-refile-targets org-refile-targets)
14214 (org-refile-use-outline-path org-refile-use-outline-path))
14215 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14216 (unless org-refile-target-table
14217 (error "No refile targets"))
14218 (let* ((cbuf (current-buffer))
14219 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14220 (fname (and filename (file-truename filename)))
14221 (tbl (mapcar
14222 (lambda (x)
14223 (if (not (equal fname (file-truename (nth 1 x))))
14224 (cons (concat (car x) " (" (file-name-nondirectory
14225 (nth 1 x)) ")")
14226 (cdr x))
14228 org-refile-target-table))
14229 (completion-ignore-case t))
14230 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14231 tbl)))
14233 ;;;; Dynamic blocks
14235 (defun org-find-dblock (name)
14236 "Find the first dynamic block with name NAME in the buffer.
14237 If not found, stay at current position and return nil."
14238 (let (pos)
14239 (save-excursion
14240 (goto-char (point-min))
14241 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14242 nil t)
14243 (match-beginning 0))))
14244 (if pos (goto-char pos))
14245 pos))
14247 (defconst org-dblock-start-re
14248 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14249 "Matches the startline of a dynamic block, with parameters.")
14251 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14252 "Matches the end of a dyhamic block.")
14254 (defun org-create-dblock (plist)
14255 "Create a dynamic block section, with parameters taken from PLIST.
14256 PLIST must containe a :name entry which is used as name of the block."
14257 (unless (bolp) (newline))
14258 (let ((name (plist-get plist :name)))
14259 (insert "#+BEGIN: " name)
14260 (while plist
14261 (if (eq (car plist) :name)
14262 (setq plist (cddr plist))
14263 (insert " " (prin1-to-string (pop plist)))))
14264 (insert "\n\n#+END:\n")
14265 (beginning-of-line -2)))
14267 (defun org-prepare-dblock ()
14268 "Prepare dynamic block for refresh.
14269 This empties the block, puts the cursor at the insert position and returns
14270 the property list including an extra property :name with the block name."
14271 (unless (looking-at org-dblock-start-re)
14272 (error "Not at a dynamic block"))
14273 (let* ((begdel (1+ (match-end 0)))
14274 (name (org-no-properties (match-string 1)))
14275 (params (append (list :name name)
14276 (read (concat "(" (match-string 3) ")")))))
14277 (unless (re-search-forward org-dblock-end-re nil t)
14278 (error "Dynamic block not terminated"))
14279 (delete-region begdel (match-beginning 0))
14280 (goto-char begdel)
14281 (open-line 1)
14282 params))
14284 (defun org-map-dblocks (&optional command)
14285 "Apply COMMAND to all dynamic blocks in the current buffer.
14286 If COMMAND is not given, use `org-update-dblock'."
14287 (let ((cmd (or command 'org-update-dblock))
14288 pos)
14289 (save-excursion
14290 (goto-char (point-min))
14291 (while (re-search-forward org-dblock-start-re nil t)
14292 (goto-char (setq pos (match-beginning 0)))
14293 (condition-case nil
14294 (funcall cmd)
14295 (error (message "Error during update of dynamic block")))
14296 (goto-char pos)
14297 (unless (re-search-forward org-dblock-end-re nil t)
14298 (error "Dynamic block not terminated"))))))
14300 (defun org-dblock-update (&optional arg)
14301 "User command for updating dynamic blocks.
14302 Update the dynamic block at point. With prefix ARG, update all dynamic
14303 blocks in the buffer."
14304 (interactive "P")
14305 (if arg
14306 (org-update-all-dblocks)
14307 (or (looking-at org-dblock-start-re)
14308 (org-beginning-of-dblock))
14309 (org-update-dblock)))
14311 (defun org-update-dblock ()
14312 "Update the dynamic block at point
14313 This means to empty the block, parse for parameters and then call
14314 the correct writing function."
14315 (save-window-excursion
14316 (let* ((pos (point))
14317 (line (org-current-line))
14318 (params (org-prepare-dblock))
14319 (name (plist-get params :name))
14320 (cmd (intern (concat "org-dblock-write:" name))))
14321 (message "Updating dynamic block `%s' at line %d..." name line)
14322 (funcall cmd params)
14323 (message "Updating dynamic block `%s' at line %d...done" name line)
14324 (goto-char pos))))
14326 (defun org-beginning-of-dblock ()
14327 "Find the beginning of the dynamic block at point.
14328 Error if there is no scuh block at point."
14329 (let ((pos (point))
14330 beg)
14331 (end-of-line 1)
14332 (if (and (re-search-backward org-dblock-start-re nil t)
14333 (setq beg (match-beginning 0))
14334 (re-search-forward org-dblock-end-re nil t)
14335 (> (match-end 0) pos))
14336 (goto-char beg)
14337 (goto-char pos)
14338 (error "Not in a dynamic block"))))
14340 (defun org-update-all-dblocks ()
14341 "Update all dynamic blocks in the buffer.
14342 This function can be used in a hook."
14343 (when (org-mode-p)
14344 (org-map-dblocks 'org-update-dblock)))
14347 ;;;; Completion
14349 (defconst org-additional-option-like-keywords
14350 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14351 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14352 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14354 (defun org-complete (&optional arg)
14355 "Perform completion on word at point.
14356 At the beginning of a headline, this completes TODO keywords as given in
14357 `org-todo-keywords'.
14358 If the current word is preceded by a backslash, completes the TeX symbols
14359 that are supported for HTML support.
14360 If the current word is preceded by \"#+\", completes special words for
14361 setting file options.
14362 In the line after \"#+STARTUP:, complete valid keywords.\"
14363 At all other locations, this simply calls the value of
14364 `org-completion-fallback-command'."
14365 (interactive "P")
14366 (org-without-partial-completion
14367 (catch 'exit
14368 (let* ((end (point))
14369 (beg1 (save-excursion
14370 (skip-chars-backward (org-re "[:alnum:]_@"))
14371 (point)))
14372 (beg (save-excursion
14373 (skip-chars-backward "a-zA-Z0-9_:$")
14374 (point)))
14375 (confirm (lambda (x) (stringp (car x))))
14376 (searchhead (equal (char-before beg) ?*))
14377 (tag (and (equal (char-before beg1) ?:)
14378 (equal (char-after (point-at-bol)) ?*)))
14379 (prop (and (equal (char-before beg1) ?:)
14380 (not (equal (char-after (point-at-bol)) ?*))))
14381 (texp (equal (char-before beg) ?\\))
14382 (link (equal (char-before beg) ?\[))
14383 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14384 beg)
14385 "#+"))
14386 (startup (string-match "^#\\+STARTUP:.*"
14387 (buffer-substring (point-at-bol) (point))))
14388 (completion-ignore-case opt)
14389 (type nil)
14390 (tbl nil)
14391 (table (cond
14392 (opt
14393 (setq type :opt)
14394 (append
14395 (mapcar
14396 (lambda (x)
14397 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14398 (cons (match-string 2 x) (match-string 1 x)))
14399 (org-split-string (org-get-current-options) "\n"))
14400 (mapcar 'list org-additional-option-like-keywords)))
14401 (startup
14402 (setq type :startup)
14403 org-startup-options)
14404 (link (append org-link-abbrev-alist-local
14405 org-link-abbrev-alist))
14406 (texp
14407 (setq type :tex)
14408 org-html-entities)
14409 ((string-match "\\`\\*+[ \t]+\\'"
14410 (buffer-substring (point-at-bol) beg))
14411 (setq type :todo)
14412 (mapcar 'list org-todo-keywords-1))
14413 (searchhead
14414 (setq type :searchhead)
14415 (save-excursion
14416 (goto-char (point-min))
14417 (while (re-search-forward org-todo-line-regexp nil t)
14418 (push (list
14419 (org-make-org-heading-search-string
14420 (match-string 3) t))
14421 tbl)))
14422 tbl)
14423 (tag (setq type :tag beg beg1)
14424 (or org-tag-alist (org-get-buffer-tags)))
14425 (prop (setq type :prop beg beg1)
14426 (mapcar 'list (org-buffer-property-keys nil t t)))
14427 (t (progn
14428 (call-interactively org-completion-fallback-command)
14429 (throw 'exit nil)))))
14430 (pattern (buffer-substring-no-properties beg end))
14431 (completion (try-completion pattern table confirm)))
14432 (cond ((eq completion t)
14433 (if (not (assoc (upcase pattern) table))
14434 (message "Already complete")
14435 (if (equal type :opt)
14436 (insert (substring (cdr (assoc (upcase pattern) table))
14437 (length pattern)))
14438 (if (memq type '(:tag :prop)) (insert ":")))))
14439 ((null completion)
14440 (message "Can't find completion for \"%s\"" pattern)
14441 (ding))
14442 ((not (string= pattern completion))
14443 (delete-region beg end)
14444 (if (string-match " +$" completion)
14445 (setq completion (replace-match "" t t completion)))
14446 (insert completion)
14447 (if (get-buffer-window "*Completions*")
14448 (delete-window (get-buffer-window "*Completions*")))
14449 (if (assoc completion table)
14450 (if (eq type :todo) (insert " ")
14451 (if (memq type '(:tag :prop)) (insert ":"))))
14452 (if (and (equal type :opt) (assoc completion table))
14453 (message "%s" (substitute-command-keys
14454 "Press \\[org-complete] again to insert example settings"))))
14456 (message "Making completion list...")
14457 (let ((list (sort (all-completions pattern table confirm)
14458 'string<)))
14459 (with-output-to-temp-buffer "*Completions*"
14460 (condition-case nil
14461 ;; Protection needed for XEmacs and emacs 21
14462 (display-completion-list list pattern)
14463 (error (display-completion-list list)))))
14464 (message "Making completion list...%s" "done")))))))
14466 ;;;; TODO, DEADLINE, Comments
14468 (defun org-toggle-comment ()
14469 "Change the COMMENT state of an entry."
14470 (interactive)
14471 (save-excursion
14472 (org-back-to-heading)
14473 (let (case-fold-search)
14474 (if (looking-at (concat outline-regexp
14475 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14476 (replace-match "" t t nil 1)
14477 (if (looking-at outline-regexp)
14478 (progn
14479 (goto-char (match-end 0))
14480 (insert org-comment-string " ")))))))
14482 (defvar org-last-todo-state-is-todo nil
14483 "This is non-nil when the last TODO state change led to a TODO state.
14484 If the last change removed the TODO tag or switched to DONE, then
14485 this is nil.")
14487 (defvar org-setting-tags nil) ; dynamically skiped
14489 ;; FIXME: better place
14490 (defun org-property-or-variable-value (var &optional inherit)
14491 "Check if there is a property fixing the value of VAR.
14492 If yes, return this value. If not, return the current value of the variable."
14493 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14494 (if (and prop (stringp prop) (string-match "\\S-" prop))
14495 (read prop)
14496 (symbol-value var))))
14498 (defun org-parse-local-options (string var)
14499 "Parse STRING for startup setting relevant for variable VAR."
14500 (let ((rtn (symbol-value var))
14501 e opts)
14502 (save-match-data
14503 (if (or (not string) (not (string-match "\\S-" string)))
14505 (setq opts (delq nil (mapcar (lambda (x)
14506 (setq e (assoc x org-startup-options))
14507 (if (eq (nth 1 e) var) e nil))
14508 (org-split-string string "[ \t]+"))))
14509 (if (not opts)
14511 (setq rtn nil)
14512 (while (setq e (pop opts))
14513 (if (not (nth 3 e))
14514 (setq rtn (nth 2 e))
14515 (if (not (listp rtn)) (setq rtn nil))
14516 (push (nth 2 e) rtn)))
14517 rtn)))))
14519 (defvar org-blocker-hook nil
14520 "Hook for functions that are allowed to block a state change.
14522 Each function gets as its single argument a property list, see
14523 `org-trigger-hook' for more information about this list.
14525 If any of the functions in this hook returns nil, the state change
14526 is blocked.")
14528 (defvar org-trigger-hook nil
14529 "Hook for functions that are triggered by a state change.
14531 Each function gets as its single argument a property list with at least
14532 the following elements:
14534 (:type type-of-change :position pos-at-entry-start
14535 :from old-state :to new-state)
14537 Depending on the type, more properties may be present.
14539 This mechanism is currently implemented for:
14541 TODO state changes
14542 ------------------
14543 :type todo-state-change
14544 :from previous state (keyword as a string), or nil
14545 :to new state (keyword as a string), or nil")
14548 (defun org-todo (&optional arg)
14549 "Change the TODO state of an item.
14550 The state of an item is given by a keyword at the start of the heading,
14551 like
14552 *** TODO Write paper
14553 *** DONE Call mom
14555 The different keywords are specified in the variable `org-todo-keywords'.
14556 By default the available states are \"TODO\" and \"DONE\".
14557 So for this example: when the item starts with TODO, it is changed to DONE.
14558 When it starts with DONE, the DONE is removed. And when neither TODO nor
14559 DONE are present, add TODO at the beginning of the heading.
14561 With C-u prefix arg, use completion to determine the new state.
14562 With numeric prefix arg, switch to that state.
14564 For calling through lisp, arg is also interpreted in the following way:
14565 'none -> empty state
14566 \"\"(empty string) -> switch to empty state
14567 'done -> switch to DONE
14568 'nextset -> switch to the next set of keywords
14569 'previousset -> switch to the previous set of keywords
14570 \"WAITING\" -> switch to the specified keyword, but only if it
14571 really is a member of `org-todo-keywords'."
14572 (interactive "P")
14573 (save-excursion
14574 (catch 'exit
14575 (org-back-to-heading)
14576 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14577 (or (looking-at (concat " +" org-todo-regexp " *"))
14578 (looking-at " *"))
14579 (let* ((match-data (match-data))
14580 (startpos (point-at-bol))
14581 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14582 (org-log-done org-log-done)
14583 (org-log-repeat org-log-repeat)
14584 (org-todo-log-states org-todo-log-states)
14585 (this (match-string 1))
14586 (hl-pos (match-beginning 0))
14587 (head (org-get-todo-sequence-head this))
14588 (ass (assoc head org-todo-kwd-alist))
14589 (interpret (nth 1 ass))
14590 (done-word (nth 3 ass))
14591 (final-done-word (nth 4 ass))
14592 (last-state (or this ""))
14593 (completion-ignore-case t)
14594 (member (member this org-todo-keywords-1))
14595 (tail (cdr member))
14596 (state (cond
14597 ((and org-todo-key-trigger
14598 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14599 (and (not arg) org-use-fast-todo-selection
14600 (not (eq org-use-fast-todo-selection 'prefix)))))
14601 ;; Use fast selection
14602 (org-fast-todo-selection))
14603 ((and (equal arg '(4))
14604 (or (not org-use-fast-todo-selection)
14605 (not org-todo-key-trigger)))
14606 ;; Read a state with completion
14607 (completing-read "State: " (mapcar (lambda(x) (list x))
14608 org-todo-keywords-1)
14609 nil t))
14610 ((eq arg 'right)
14611 (if this
14612 (if tail (car tail) nil)
14613 (car org-todo-keywords-1)))
14614 ((eq arg 'left)
14615 (if (equal member org-todo-keywords-1)
14617 (if this
14618 (nth (- (length org-todo-keywords-1) (length tail) 2)
14619 org-todo-keywords-1)
14620 (org-last org-todo-keywords-1))))
14621 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14622 (setq arg nil))) ; hack to fall back to cycling
14623 (arg
14624 ;; user or caller requests a specific state
14625 (cond
14626 ((equal arg "") nil)
14627 ((eq arg 'none) nil)
14628 ((eq arg 'done) (or done-word (car org-done-keywords)))
14629 ((eq arg 'nextset)
14630 (or (car (cdr (member head org-todo-heads)))
14631 (car org-todo-heads)))
14632 ((eq arg 'previousset)
14633 (let ((org-todo-heads (reverse org-todo-heads)))
14634 (or (car (cdr (member head org-todo-heads)))
14635 (car org-todo-heads))))
14636 ((car (member arg org-todo-keywords-1)))
14637 ((nth (1- (prefix-numeric-value arg))
14638 org-todo-keywords-1))))
14639 ((null member) (or head (car org-todo-keywords-1)))
14640 ((equal this final-done-word) nil) ;; -> make empty
14641 ((null tail) nil) ;; -> first entry
14642 ((eq interpret 'sequence)
14643 (car tail))
14644 ((memq interpret '(type priority))
14645 (if (eq this-command last-command)
14646 (car tail)
14647 (if (> (length tail) 0)
14648 (or done-word (car org-done-keywords))
14649 nil)))
14650 (t nil)))
14651 (next (if state (concat " " state " ") " "))
14652 (change-plist (list :type 'todo-state-change :from this :to state
14653 :position startpos))
14654 dolog now-done-p)
14655 (when org-blocker-hook
14656 (unless (save-excursion
14657 (save-match-data
14658 (run-hook-with-args-until-failure
14659 'org-blocker-hook change-plist)))
14660 (if (interactive-p)
14661 (error "TODO state change from %s to %s blocked" this state)
14662 ;; fail silently
14663 (message "TODO state change from %s to %s blocked" this state)
14664 (throw 'exit nil))))
14665 (store-match-data match-data)
14666 (replace-match next t t)
14667 (unless (pos-visible-in-window-p hl-pos)
14668 (message "TODO state changed to %s" (org-trim next)))
14669 (unless head
14670 (setq head (org-get-todo-sequence-head state)
14671 ass (assoc head org-todo-kwd-alist)
14672 interpret (nth 1 ass)
14673 done-word (nth 3 ass)
14674 final-done-word (nth 4 ass)))
14675 (when (memq arg '(nextset previousset))
14676 (message "Keyword-Set %d/%d: %s"
14677 (- (length org-todo-sets) -1
14678 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14679 (length org-todo-sets)
14680 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14681 (setq org-last-todo-state-is-todo
14682 (not (member state org-done-keywords)))
14683 (setq now-done-p (and (member state org-done-keywords)
14684 (not (member this org-done-keywords))))
14685 (and logging (org-local-logging logging))
14686 (when (and (or org-todo-log-states org-log-done)
14687 (not (memq arg '(nextset previousset))))
14688 ;; we need to look at recording a time and note
14689 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14690 (nth 2 (assoc this org-todo-log-states))))
14691 (when (and state
14692 (member state org-not-done-keywords)
14693 (not (member this org-not-done-keywords)))
14694 ;; This is now a todo state and was not one before
14695 ;; If there was a CLOSED time stamp, get rid of it.
14696 (org-add-planning-info nil nil 'closed))
14697 (when (and now-done-p org-log-done)
14698 ;; It is now done, and it was not done before
14699 (org-add-planning-info 'closed (org-current-time))
14700 (if (and (not dolog) (eq 'note org-log-done))
14701 (org-add-log-maybe 'done state 'findpos 'note)))
14702 (when (and state dolog)
14703 ;; This is a non-nil state, and we need to log it
14704 (org-add-log-maybe 'state state 'findpos dolog)))
14705 ;; Fixup tag positioning
14706 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14707 (run-hooks 'org-after-todo-state-change-hook)
14708 (if (and arg (not (member state org-done-keywords)))
14709 (setq head (org-get-todo-sequence-head state)))
14710 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14711 ;; Do we need to trigger a repeat?
14712 (when now-done-p (org-auto-repeat-maybe state))
14713 ;; Fixup cursor location if close to the keyword
14714 (if (and (outline-on-heading-p)
14715 (not (bolp))
14716 (save-excursion (beginning-of-line 1)
14717 (looking-at org-todo-line-regexp))
14718 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14719 (progn
14720 (goto-char (or (match-end 2) (match-end 1)))
14721 (just-one-space)))
14722 (when org-trigger-hook
14723 (save-excursion
14724 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14726 (defun org-local-logging (value)
14727 "Get logging settings from a property VALUE."
14728 (let* (words w a)
14729 ;; directly set the variables, they are already local.
14730 (setq org-log-done nil
14731 org-log-repeat nil
14732 org-todo-log-states nil)
14733 (setq words (org-split-string value))
14734 (while (setq w (pop words))
14735 (cond
14736 ((setq a (assoc w org-startup-options))
14737 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14738 (set (nth 1 a) (nth 2 a))))
14739 ((setq a (org-extract-log-state-settings w))
14740 (and (member (car a) org-todo-keywords-1)
14741 (push a org-todo-log-states)))))))
14743 (defun org-get-todo-sequence-head (kwd)
14744 "Return the head of the TODO sequence to which KWD belongs.
14745 If KWD is not set, check if there is a text property remembering the
14746 right sequence."
14747 (let (p)
14748 (cond
14749 ((not kwd)
14750 (or (get-text-property (point-at-bol) 'org-todo-head)
14751 (progn
14752 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14753 nil (point-at-eol)))
14754 (get-text-property p 'org-todo-head))))
14755 ((not (member kwd org-todo-keywords-1))
14756 (car org-todo-keywords-1))
14757 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14759 (defun org-fast-todo-selection ()
14760 "Fast TODO keyword selection with single keys.
14761 Returns the new TODO keyword, or nil if no state change should occur."
14762 (let* ((fulltable org-todo-key-alist)
14763 (done-keywords org-done-keywords) ;; needed for the faces.
14764 (maxlen (apply 'max (mapcar
14765 (lambda (x)
14766 (if (stringp (car x)) (string-width (car x)) 0))
14767 fulltable)))
14768 (expert nil)
14769 (fwidth (+ maxlen 3 1 3))
14770 (ncol (/ (- (window-width) 4) fwidth))
14771 tg cnt e c tbl
14772 groups ingroup)
14773 (save-window-excursion
14774 (if expert
14775 (set-buffer (get-buffer-create " *Org todo*"))
14776 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14777 (erase-buffer)
14778 (org-set-local 'org-done-keywords done-keywords)
14779 (setq tbl fulltable cnt 0)
14780 (while (setq e (pop tbl))
14781 (cond
14782 ((equal e '(:startgroup))
14783 (push '() groups) (setq ingroup t)
14784 (when (not (= cnt 0))
14785 (setq cnt 0)
14786 (insert "\n"))
14787 (insert "{ "))
14788 ((equal e '(:endgroup))
14789 (setq ingroup nil cnt 0)
14790 (insert "}\n"))
14792 (setq tg (car e) c (cdr e))
14793 (if ingroup (push tg (car groups)))
14794 (setq tg (org-add-props tg nil 'face
14795 (org-get-todo-face tg)))
14796 (if (and (= cnt 0) (not ingroup)) (insert " "))
14797 (insert "[" c "] " tg (make-string
14798 (- fwidth 4 (length tg)) ?\ ))
14799 (when (= (setq cnt (1+ cnt)) ncol)
14800 (insert "\n")
14801 (if ingroup (insert " "))
14802 (setq cnt 0)))))
14803 (insert "\n")
14804 (goto-char (point-min))
14805 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14806 (fit-window-to-buffer))
14807 (message "[a-z..]:Set [SPC]:clear")
14808 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14809 (cond
14810 ((or (= c ?\C-g)
14811 (and (= c ?q) (not (rassoc c fulltable))))
14812 (setq quit-flag t))
14813 ((= c ?\ ) nil)
14814 ((setq e (rassoc c fulltable) tg (car e))
14816 (t (setq quit-flag t))))))
14818 (defun org-get-repeat ()
14819 "Check if tere is a deadline/schedule with repeater in this entry."
14820 (save-match-data
14821 (save-excursion
14822 (org-back-to-heading t)
14823 (if (re-search-forward
14824 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14825 (match-string 1)))))
14827 (defvar org-last-changed-timestamp)
14828 (defvar org-log-post-message)
14829 (defvar org-log-note-purpose)
14830 (defun org-auto-repeat-maybe (done-word)
14831 "Check if the current headline contains a repeated deadline/schedule.
14832 If yes, set TODO state back to what it was and change the base date
14833 of repeating deadline/scheduled time stamps to new date.
14834 This function is run automatically after each state change to a DONE state."
14835 ;; last-state is dynamically scoped into this function
14836 (let* ((repeat (org-get-repeat))
14837 (aa (assoc last-state org-todo-kwd-alist))
14838 (interpret (nth 1 aa))
14839 (head (nth 2 aa))
14840 (whata '(("d" . day) ("m" . month) ("y" . year)))
14841 (msg "Entry repeats: ")
14842 (org-log-done nil)
14843 (org-todo-log-states nil)
14844 re type n what ts)
14845 (when repeat
14846 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14847 (org-todo (if (eq interpret 'type) last-state head))
14848 (when (and org-log-repeat
14849 (or (not (memq 'org-add-log-note
14850 (default-value 'post-command-hook)))
14851 (eq org-log-note-purpose 'done)))
14852 ;; Make sure a note is taken;
14853 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14854 'findpos org-log-repeat))
14855 (org-back-to-heading t)
14856 (org-add-planning-info nil nil 'closed)
14857 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14858 org-deadline-time-regexp "\\)\\|\\("
14859 org-ts-regexp "\\)"))
14860 (while (re-search-forward
14861 re (save-excursion (outline-next-heading) (point)) t)
14862 (setq type (if (match-end 1) org-scheduled-string
14863 (if (match-end 3) org-deadline-string "Plain:"))
14864 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14865 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14866 (setq n (string-to-number (match-string 1 ts))
14867 what (match-string 2 ts))
14868 (if (equal what "w") (setq n (* n 7) what "d"))
14869 (org-timestamp-change n (cdr (assoc what whata)))
14870 (setq msg (concat msg type org-last-changed-timestamp " "))))
14871 (setq org-log-post-message msg)
14872 (message "%s" msg))))
14874 (defun org-show-todo-tree (arg)
14875 "Make a compact tree which shows all headlines marked with TODO.
14876 The tree will show the lines where the regexp matches, and all higher
14877 headlines above the match.
14878 With a \\[universal-argument] prefix, also show the DONE entries.
14879 With a numeric prefix N, construct a sparse tree for the Nth element
14880 of `org-todo-keywords-1'."
14881 (interactive "P")
14882 (let ((case-fold-search nil)
14883 (kwd-re
14884 (cond ((null arg) org-not-done-regexp)
14885 ((equal arg '(4))
14886 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14887 (mapcar 'list org-todo-keywords-1))))
14888 (concat "\\("
14889 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14890 "\\)\\>")))
14891 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14892 (regexp-quote (nth (1- (prefix-numeric-value arg))
14893 org-todo-keywords-1)))
14894 (t (error "Invalid prefix argument: %s" arg)))))
14895 (message "%d TODO entries found"
14896 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14898 (defun org-deadline (&optional remove)
14899 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14900 With argument REMOVE, remove any deadline from the item."
14901 (interactive "P")
14902 (if remove
14903 (progn
14904 (org-remove-timestamp-with-keyword org-deadline-string)
14905 (message "Item no longer has a deadline."))
14906 (org-add-planning-info 'deadline nil 'closed)))
14908 (defun org-schedule (&optional remove)
14909 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14910 With argument REMOVE, remove any scheduling date from the item."
14911 (interactive "P")
14912 (if remove
14913 (progn
14914 (org-remove-timestamp-with-keyword org-scheduled-string)
14915 (message "Item is no longer scheduled."))
14916 (org-add-planning-info 'scheduled nil 'closed)))
14918 (defun org-remove-timestamp-with-keyword (keyword)
14919 "Remove all time stamps with KEYWORD in the current entry."
14920 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14921 beg)
14922 (save-excursion
14923 (org-back-to-heading t)
14924 (setq beg (point))
14925 (org-end-of-subtree t t)
14926 (while (re-search-backward re beg t)
14927 (replace-match "")
14928 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14929 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14931 (defun org-add-planning-info (what &optional time &rest remove)
14932 "Insert new timestamp with keyword in the line directly after the headline.
14933 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14934 If non is given, the user is prompted for a date.
14935 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14936 be removed."
14937 (interactive)
14938 (let (org-time-was-given org-end-time-was-given)
14939 (when what (setq time (or time (org-read-date nil 'to-time))))
14940 (when (and org-insert-labeled-timestamps-at-point
14941 (member what '(scheduled deadline)))
14942 (insert
14943 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14944 (org-insert-time-stamp time org-time-was-given
14945 nil nil nil (list org-end-time-was-given))
14946 (setq what nil))
14947 (save-excursion
14948 (save-restriction
14949 (let (col list elt ts buffer-invisibility-spec)
14950 (org-back-to-heading t)
14951 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14952 (goto-char (match-end 1))
14953 (setq col (current-column))
14954 (goto-char (match-end 0))
14955 (if (eobp) (insert "\n") (forward-char 1))
14956 (if (and (not (looking-at outline-regexp))
14957 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14958 "[^\r\n]*"))
14959 (not (equal (match-string 1) org-clock-string)))
14960 (narrow-to-region (match-beginning 0) (match-end 0))
14961 (insert-before-markers "\n")
14962 (backward-char 1)
14963 (narrow-to-region (point) (point))
14964 (indent-to-column col))
14965 ;; Check if we have to remove something.
14966 (setq list (cons what remove))
14967 (while list
14968 (setq elt (pop list))
14969 (goto-char (point-min))
14970 (when (or (and (eq elt 'scheduled)
14971 (re-search-forward org-scheduled-time-regexp nil t))
14972 (and (eq elt 'deadline)
14973 (re-search-forward org-deadline-time-regexp nil t))
14974 (and (eq elt 'closed)
14975 (re-search-forward org-closed-time-regexp nil t)))
14976 (replace-match "")
14977 (if (looking-at "--+<[^>]+>") (replace-match ""))
14978 (if (looking-at " +") (replace-match ""))))
14979 (goto-char (point-max))
14980 (when what
14981 (insert
14982 (if (not (equal (char-before) ?\ )) " " "")
14983 (cond ((eq what 'scheduled) org-scheduled-string)
14984 ((eq what 'deadline) org-deadline-string)
14985 ((eq what 'closed) org-closed-string))
14986 " ")
14987 (setq ts (org-insert-time-stamp
14988 time
14989 (or org-time-was-given
14990 (and (eq what 'closed) org-log-done-with-time))
14991 (eq what 'closed)
14992 nil nil (list org-end-time-was-given)))
14993 (end-of-line 1))
14994 (goto-char (point-min))
14995 (widen)
14996 (if (looking-at "[ \t]+\r?\n")
14997 (replace-match ""))
14998 ts)))))
15000 (defvar org-log-note-marker (make-marker))
15001 (defvar org-log-note-purpose nil)
15002 (defvar org-log-note-state nil)
15003 (defvar org-log-note-how nil)
15004 (defvar org-log-note-window-configuration nil)
15005 (defvar org-log-note-return-to (make-marker))
15006 (defvar org-log-post-message nil
15007 "Message to be displayed after a log note has been stored.
15008 The auto-repeater uses this.")
15010 (defun org-add-log-maybe (&optional purpose state findpos how)
15011 "Set up the post command hook to take a note.
15012 If this is about to TODO state change, the new state is expected in STATE.
15013 When FINDPOS is non-nil, find the correct position for the note in
15014 the current entry. If not, assume that it can be inserted at point."
15015 (save-excursion
15016 (when findpos
15017 (org-back-to-heading t)
15018 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15019 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15020 "[^\r\n]*\\)?"))
15021 (goto-char (match-end 0))
15022 (unless org-log-states-order-reversed
15023 (and (= (char-after) ?\n) (forward-char 1))
15024 (org-skip-over-state-notes)
15025 (skip-chars-backward " \t\n\r")))
15026 (move-marker org-log-note-marker (point))
15027 (setq org-log-note-purpose purpose
15028 org-log-note-state state
15029 org-log-note-how how)
15030 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15032 (defun org-skip-over-state-notes ()
15033 "Skip past the list of State notes in an entry."
15034 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15035 (while (looking-at "[ \t]*- State")
15036 (condition-case nil
15037 (org-next-item)
15038 (error (org-end-of-item)))))
15040 (defun org-add-log-note (&optional purpose)
15041 "Pop up a window for taking a note, and add this note later at point."
15042 (remove-hook 'post-command-hook 'org-add-log-note)
15043 (setq org-log-note-window-configuration (current-window-configuration))
15044 (delete-other-windows)
15045 (move-marker org-log-note-return-to (point))
15046 (switch-to-buffer (marker-buffer org-log-note-marker))
15047 (goto-char org-log-note-marker)
15048 (org-switch-to-buffer-other-window "*Org Note*")
15049 (erase-buffer)
15050 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15051 (org-store-log-note)
15052 (let ((org-inhibit-startup t)) (org-mode))
15053 (insert (format "# Insert note for %s.
15054 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15055 (cond
15056 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15057 ((eq org-log-note-purpose 'done) "closed todo item")
15058 ((eq org-log-note-purpose 'state)
15059 (format "state change to \"%s\"" org-log-note-state))
15060 (t (error "This should not happen")))))
15061 (org-set-local 'org-finish-function 'org-store-log-note)))
15063 (defun org-store-log-note ()
15064 "Finish taking a log note, and insert it to where it belongs."
15065 (let ((txt (buffer-string))
15066 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15067 lines ind)
15068 (kill-buffer (current-buffer))
15069 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15070 (setq txt (replace-match "" t t txt)))
15071 (if (string-match "\\s-+\\'" txt)
15072 (setq txt (replace-match "" t t txt)))
15073 (setq lines (org-split-string txt "\n"))
15074 (when (and note (string-match "\\S-" note))
15075 (setq note
15076 (org-replace-escapes
15077 note
15078 (list (cons "%u" (user-login-name))
15079 (cons "%U" user-full-name)
15080 (cons "%t" (format-time-string
15081 (org-time-stamp-format 'long 'inactive)
15082 (current-time)))
15083 (cons "%s" (if org-log-note-state
15084 (concat "\"" org-log-note-state "\"")
15085 "")))))
15086 (if lines (setq note (concat note " \\\\")))
15087 (push note lines))
15088 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15089 (when lines
15090 (save-excursion
15091 (set-buffer (marker-buffer org-log-note-marker))
15092 (save-excursion
15093 (goto-char org-log-note-marker)
15094 (move-marker org-log-note-marker nil)
15095 (end-of-line 1)
15096 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15097 (indent-relative nil)
15098 (insert "- " (pop lines))
15099 (org-indent-line-function)
15100 (beginning-of-line 1)
15101 (looking-at "[ \t]*")
15102 (setq ind (concat (match-string 0) " "))
15103 (end-of-line 1)
15104 (while lines (insert "\n" ind (pop lines)))))))
15105 (set-window-configuration org-log-note-window-configuration)
15106 (with-current-buffer (marker-buffer org-log-note-return-to)
15107 (goto-char org-log-note-return-to))
15108 (move-marker org-log-note-return-to nil)
15109 (and org-log-post-message (message "%s" org-log-post-message)))
15111 ;; FIXME: what else would be useful?
15112 ;; - priority
15113 ;; - date
15115 (defun org-sparse-tree (&optional arg)
15116 "Create a sparse tree, prompt for the details.
15117 This command can create sparse trees. You first need to select the type
15118 of match used to create the tree:
15120 t Show entries with a specific TODO keyword.
15121 T Show entries selected by a tags match.
15122 p Enter a property name and its value (both with completion on existing
15123 names/values) and show entries with that property.
15124 r Show entries matching a regular expression
15125 d Show deadlines due within `org-deadline-warning-days'."
15126 (interactive "P")
15127 (let (ans kwd value)
15128 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15129 (setq ans (read-char-exclusive))
15130 (cond
15131 ((equal ans ?d)
15132 (call-interactively 'org-check-deadlines))
15133 ((equal ans ?b)
15134 (call-interactively 'org-check-before-date))
15135 ((equal ans ?t)
15136 (org-show-todo-tree '(4)))
15137 ((equal ans ?T)
15138 (call-interactively 'org-tags-sparse-tree))
15139 ((member ans '(?p ?P))
15140 (setq kwd (completing-read "Property: "
15141 (mapcar 'list (org-buffer-property-keys))))
15142 (setq value (completing-read "Value: "
15143 (mapcar 'list (org-property-values kwd))))
15144 (unless (string-match "\\`{.*}\\'" value)
15145 (setq value (concat "\"" value "\"")))
15146 (org-tags-sparse-tree arg (concat kwd "=" value)))
15147 ((member ans '(?r ?R ?/))
15148 (call-interactively 'org-occur))
15149 (t (error "No such sparse tree command \"%c\"" ans)))))
15151 (defvar org-occur-highlights nil)
15152 (make-variable-buffer-local 'org-occur-highlights)
15154 (defun org-occur (regexp &optional keep-previous callback)
15155 "Make a compact tree which shows all matches of REGEXP.
15156 The tree will show the lines where the regexp matches, and all higher
15157 headlines above the match. It will also show the heading after the match,
15158 to make sure editing the matching entry is easy.
15159 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15160 call to `org-occur' will be kept, to allow stacking of calls to this
15161 command.
15162 If CALLBACK is non-nil, it is a function which is called to confirm
15163 that the match should indeed be shown."
15164 (interactive "sRegexp: \nP")
15165 (or keep-previous (org-remove-occur-highlights nil nil t))
15166 (let ((cnt 0))
15167 (save-excursion
15168 (goto-char (point-min))
15169 (if (or (not keep-previous) ; do not want to keep
15170 (not org-occur-highlights)) ; no previous matches
15171 ;; hide everything
15172 (org-overview))
15173 (while (re-search-forward regexp nil t)
15174 (when (or (not callback)
15175 (save-match-data (funcall callback)))
15176 (setq cnt (1+ cnt))
15177 (when org-highlight-sparse-tree-matches
15178 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15179 (org-show-context 'occur-tree))))
15180 (when org-remove-highlights-with-change
15181 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15182 nil 'local))
15183 (unless org-sparse-tree-open-archived-trees
15184 (org-hide-archived-subtrees (point-min) (point-max)))
15185 (run-hooks 'org-occur-hook)
15186 (if (interactive-p)
15187 (message "%d match(es) for regexp %s" cnt regexp))
15188 cnt))
15190 (defun org-show-context (&optional key)
15191 "Make sure point and context and visible.
15192 How much context is shown depends upon the variables
15193 `org-show-hierarchy-above', `org-show-following-heading'. and
15194 `org-show-siblings'."
15195 (let ((heading-p (org-on-heading-p t))
15196 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15197 (following-p (org-get-alist-option org-show-following-heading key))
15198 (entry-p (org-get-alist-option org-show-entry-below key))
15199 (siblings-p (org-get-alist-option org-show-siblings key)))
15200 (catch 'exit
15201 ;; Show heading or entry text
15202 (if (and heading-p (not entry-p))
15203 (org-flag-heading nil) ; only show the heading
15204 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15205 (org-show-hidden-entry))) ; show entire entry
15206 (when following-p
15207 ;; Show next sibling, or heading below text
15208 (save-excursion
15209 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15210 (org-flag-heading nil))))
15211 (when siblings-p (org-show-siblings))
15212 (when hierarchy-p
15213 ;; show all higher headings, possibly with siblings
15214 (save-excursion
15215 (while (and (condition-case nil
15216 (progn (org-up-heading-all 1) t)
15217 (error nil))
15218 (not (bobp)))
15219 (org-flag-heading nil)
15220 (when siblings-p (org-show-siblings))))))))
15222 (defun org-reveal (&optional siblings)
15223 "Show current entry, hierarchy above it, and the following headline.
15224 This can be used to show a consistent set of context around locations
15225 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15226 not t for the search context.
15228 With optional argument SIBLINGS, on each level of the hierarchy all
15229 siblings are shown. This repairs the tree structure to what it would
15230 look like when opened with hierarchical calls to `org-cycle'."
15231 (interactive "P")
15232 (let ((org-show-hierarchy-above t)
15233 (org-show-following-heading t)
15234 (org-show-siblings (if siblings t org-show-siblings)))
15235 (org-show-context nil)))
15237 (defun org-highlight-new-match (beg end)
15238 "Highlight from BEG to END and mark the highlight is an occur headline."
15239 (let ((ov (org-make-overlay beg end)))
15240 (org-overlay-put ov 'face 'secondary-selection)
15241 (push ov org-occur-highlights)))
15243 (defun org-remove-occur-highlights (&optional beg end noremove)
15244 "Remove the occur highlights from the buffer.
15245 BEG and END are ignored. If NOREMOVE is nil, remove this function
15246 from the `before-change-functions' in the current buffer."
15247 (interactive)
15248 (unless org-inhibit-highlight-removal
15249 (mapc 'org-delete-overlay org-occur-highlights)
15250 (setq org-occur-highlights nil)
15251 (unless noremove
15252 (remove-hook 'before-change-functions
15253 'org-remove-occur-highlights 'local))))
15255 ;;;; Priorities
15257 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15258 "Regular expression matching the priority indicator.")
15260 (defvar org-remove-priority-next-time nil)
15262 (defun org-priority-up ()
15263 "Increase the priority of the current item."
15264 (interactive)
15265 (org-priority 'up))
15267 (defun org-priority-down ()
15268 "Decrease the priority of the current item."
15269 (interactive)
15270 (org-priority 'down))
15272 (defun org-priority (&optional action)
15273 "Change the priority of an item by ARG.
15274 ACTION can be `set', `up', `down', or a character."
15275 (interactive)
15276 (setq action (or action 'set))
15277 (let (current new news have remove)
15278 (save-excursion
15279 (org-back-to-heading)
15280 (if (looking-at org-priority-regexp)
15281 (setq current (string-to-char (match-string 2))
15282 have t)
15283 (setq current org-default-priority))
15284 (cond
15285 ((or (eq action 'set) (integerp action))
15286 (if (integerp action)
15287 (setq new action)
15288 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15289 (setq new (read-char-exclusive)))
15290 (if (and (= (upcase org-highest-priority) org-highest-priority)
15291 (= (upcase org-lowest-priority) org-lowest-priority))
15292 (setq new (upcase new)))
15293 (cond ((equal new ?\ ) (setq remove t))
15294 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15295 (error "Priority must be between `%c' and `%c'"
15296 org-highest-priority org-lowest-priority))))
15297 ((eq action 'up)
15298 (if (and (not have) (eq last-command this-command))
15299 (setq new org-lowest-priority)
15300 (setq new (if (and org-priority-start-cycle-with-default (not have))
15301 org-default-priority (1- current)))))
15302 ((eq action 'down)
15303 (if (and (not have) (eq last-command this-command))
15304 (setq new org-highest-priority)
15305 (setq new (if (and org-priority-start-cycle-with-default (not have))
15306 org-default-priority (1+ current)))))
15307 (t (error "Invalid action")))
15308 (if (or (< (upcase new) org-highest-priority)
15309 (> (upcase new) org-lowest-priority))
15310 (setq remove t))
15311 (setq news (format "%c" new))
15312 (if have
15313 (if remove
15314 (replace-match "" t t nil 1)
15315 (replace-match news t t nil 2))
15316 (if remove
15317 (error "No priority cookie found in line")
15318 (looking-at org-todo-line-regexp)
15319 (if (match-end 2)
15320 (progn
15321 (goto-char (match-end 2))
15322 (insert " [#" news "]"))
15323 (goto-char (match-beginning 3))
15324 (insert "[#" news "] ")))))
15325 (org-preserve-lc (org-set-tags nil 'align))
15326 (if remove
15327 (message "Priority removed")
15328 (message "Priority of current item set to %s" news))))
15331 (defun org-get-priority (s)
15332 "Find priority cookie and return priority."
15333 (save-match-data
15334 (if (not (string-match org-priority-regexp s))
15335 (* 1000 (- org-lowest-priority org-default-priority))
15336 (* 1000 (- org-lowest-priority
15337 (string-to-char (match-string 2 s)))))))
15339 ;;;; Tags
15341 (defun org-scan-tags (action matcher &optional todo-only)
15342 "Scan headline tags with inheritance and produce output ACTION.
15343 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15344 evaluated, testing if a given set of tags qualifies a headline for
15345 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15346 are included in the output."
15347 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15348 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15349 (org-re
15350 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15351 (props (list 'face nil
15352 'done-face 'org-done
15353 'undone-face nil
15354 'mouse-face 'highlight
15355 'org-not-done-regexp org-not-done-regexp
15356 'org-todo-regexp org-todo-regexp
15357 'keymap org-agenda-keymap
15358 'help-echo
15359 (format "mouse-2 or RET jump to org file %s"
15360 (abbreviate-file-name
15361 (or (buffer-file-name (buffer-base-buffer))
15362 (buffer-name (buffer-base-buffer)))))))
15363 (case-fold-search nil)
15364 lspos
15365 tags tags-list tags-alist (llast 0) rtn level category i txt
15366 todo marker entry priority)
15367 (save-excursion
15368 (goto-char (point-min))
15369 (when (eq action 'sparse-tree)
15370 (org-overview)
15371 (org-remove-occur-highlights))
15372 (while (re-search-forward re nil t)
15373 (catch :skip
15374 (setq todo (if (match-end 1) (match-string 2))
15375 tags (if (match-end 4) (match-string 4)))
15376 (goto-char (setq lspos (1+ (match-beginning 0))))
15377 (setq level (org-reduced-level (funcall outline-level))
15378 category (org-get-category))
15379 (setq i llast llast level)
15380 ;; remove tag lists from same and sublevels
15381 (while (>= i level)
15382 (when (setq entry (assoc i tags-alist))
15383 (setq tags-alist (delete entry tags-alist)))
15384 (setq i (1- i)))
15385 ;; add the nex tags
15386 (when tags
15387 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15388 tags-alist
15389 (cons (cons level tags) tags-alist)))
15390 ;; compile tags for current headline
15391 (setq tags-list
15392 (if org-use-tag-inheritance
15393 (apply 'append (mapcar 'cdr tags-alist))
15394 tags))
15395 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15396 (eval matcher)
15397 (or (not org-agenda-skip-archived-trees)
15398 (not (member org-archive-tag tags-list))))
15399 (and (eq action 'agenda) (org-agenda-skip))
15400 ;; list this headline
15402 (if (eq action 'sparse-tree)
15403 (progn
15404 (and org-highlight-sparse-tree-matches
15405 (org-get-heading) (match-end 0)
15406 (org-highlight-new-match
15407 (match-beginning 0) (match-beginning 1)))
15408 (org-show-context 'tags-tree))
15409 (setq txt (org-format-agenda-item
15411 (concat
15412 (if org-tags-match-list-sublevels
15413 (make-string (1- level) ?.) "")
15414 (org-get-heading))
15415 category tags-list)
15416 priority (org-get-priority txt))
15417 (goto-char lspos)
15418 (setq marker (org-agenda-new-marker))
15419 (org-add-props txt props
15420 'org-marker marker 'org-hd-marker marker 'org-category category
15421 'priority priority 'type "tagsmatch")
15422 (push txt rtn))
15423 ;; if we are to skip sublevels, jump to end of subtree
15424 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15425 (when (and (eq action 'sparse-tree)
15426 (not org-sparse-tree-open-archived-trees))
15427 (org-hide-archived-subtrees (point-min) (point-max)))
15428 (nreverse rtn)))
15430 (defvar todo-only) ;; dynamically scoped
15432 (defun org-tags-sparse-tree (&optional todo-only match)
15433 "Create a sparse tree according to tags string MATCH.
15434 MATCH can contain positive and negative selection of tags, like
15435 \"+WORK+URGENT-WITHBOSS\".
15436 If optional argument TODO_ONLY is non-nil, only select lines that are
15437 also TODO lines."
15438 (interactive "P")
15439 (org-prepare-agenda-buffers (list (current-buffer)))
15440 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15442 (defvar org-cached-props nil)
15443 (defun org-cached-entry-get (pom property)
15444 (if (or (eq t org-use-property-inheritance)
15445 (member property org-use-property-inheritance))
15446 ;; Caching is not possible, check it directly
15447 (org-entry-get pom property 'inherit)
15448 ;; Get all properties, so that we can do complicated checks easily
15449 (cdr (assoc property (or org-cached-props
15450 (setq org-cached-props
15451 (org-entry-properties pom)))))))
15453 (defun org-global-tags-completion-table (&optional files)
15454 "Return the list of all tags in all agenda buffer/files."
15455 (save-excursion
15456 (org-uniquify
15457 (delq nil
15458 (apply 'append
15459 (mapcar
15460 (lambda (file)
15461 (set-buffer (find-file-noselect file))
15462 (append (org-get-buffer-tags)
15463 (mapcar (lambda (x) (if (stringp (car-safe x))
15464 (list (car-safe x)) nil))
15465 org-tag-alist)))
15466 (if (and files (car files))
15467 files
15468 (org-agenda-files))))))))
15470 (defun org-make-tags-matcher (match)
15471 "Create the TAGS//TODO matcher form for the selection string MATCH."
15472 ;; todo-only is scoped dynamically into this function, and the function
15473 ;; may change it it the matcher asksk for it.
15474 (unless match
15475 ;; Get a new match request, with completion
15476 (let ((org-last-tags-completion-table
15477 (org-global-tags-completion-table)))
15478 (setq match (completing-read
15479 "Match: " 'org-tags-completion-function nil nil nil
15480 'org-tags-history))))
15482 ;; Parse the string and create a lisp form
15483 (let ((match0 match)
15484 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15485 minus tag mm
15486 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15487 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15488 (if (string-match "/+" match)
15489 ;; match contains also a todo-matching request
15490 (progn
15491 (setq tagsmatch (substring match 0 (match-beginning 0))
15492 todomatch (substring match (match-end 0)))
15493 (if (string-match "^!" todomatch)
15494 (setq todo-only t todomatch (substring todomatch 1)))
15495 (if (string-match "^\\s-*$" todomatch)
15496 (setq todomatch nil)))
15497 ;; only matching tags
15498 (setq tagsmatch match todomatch nil))
15500 ;; Make the tags matcher
15501 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15502 (setq tagsmatcher t)
15503 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15504 (while (setq term (pop orterms))
15505 (while (and (equal (substring term -1) "\\") orterms)
15506 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15507 (while (string-match re term)
15508 (setq minus (and (match-end 1)
15509 (equal (match-string 1 term) "-"))
15510 tag (match-string 2 term)
15511 re-p (equal (string-to-char tag) ?{)
15512 level-p (match-end 3)
15513 prop-p (match-end 4)
15514 mm (cond
15515 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15516 (level-p `(= level ,(string-to-number
15517 (match-string 3 term))))
15518 (prop-p
15519 (setq pn (match-string 4 term)
15520 pv (match-string 5 term)
15521 cat-p (equal pn "CATEGORY")
15522 re-p (equal (string-to-char pv) ?{)
15523 pv (substring pv 1 -1))
15524 (if (equal pn "CATEGORY")
15525 (setq gv '(get-text-property (point) 'org-category))
15526 (setq gv `(org-cached-entry-get nil ,pn)))
15527 (if re-p
15528 `(string-match ,pv (or ,gv ""))
15529 `(equal ,pv (or ,gv ""))))
15530 (t `(member ,(downcase tag) tags-list)))
15531 mm (if minus (list 'not mm) mm)
15532 term (substring term (match-end 0)))
15533 (push mm tagsmatcher))
15534 (push (if (> (length tagsmatcher) 1)
15535 (cons 'and tagsmatcher)
15536 (car tagsmatcher))
15537 orlist)
15538 (setq tagsmatcher nil))
15539 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15540 (setq tagsmatcher
15541 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15543 ;; Make the todo matcher
15544 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15545 (setq todomatcher t)
15546 (setq orterms (org-split-string todomatch "|") orlist nil)
15547 (while (setq term (pop orterms))
15548 (while (string-match re term)
15549 (setq minus (and (match-end 1)
15550 (equal (match-string 1 term) "-"))
15551 kwd (match-string 2 term)
15552 re-p (equal (string-to-char kwd) ?{)
15553 term (substring term (match-end 0))
15554 mm (if re-p
15555 `(string-match ,(substring kwd 1 -1) todo)
15556 (list 'equal 'todo kwd))
15557 mm (if minus (list 'not mm) mm))
15558 (push mm todomatcher))
15559 (push (if (> (length todomatcher) 1)
15560 (cons 'and todomatcher)
15561 (car todomatcher))
15562 orlist)
15563 (setq todomatcher nil))
15564 (setq todomatcher (if (> (length orlist) 1)
15565 (cons 'or orlist) (car orlist))))
15567 ;; Return the string and lisp forms of the matcher
15568 (setq matcher (if todomatcher
15569 (list 'and tagsmatcher todomatcher)
15570 tagsmatcher))
15571 (cons match0 matcher)))
15573 (defun org-match-any-p (re list)
15574 "Does re match any element of list?"
15575 (setq list (mapcar (lambda (x) (string-match re x)) list))
15576 (delq nil list))
15578 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15579 (defvar org-tags-overlay (org-make-overlay 1 1))
15580 (org-detach-overlay org-tags-overlay)
15582 (defun org-align-tags-here (to-col)
15583 ;; Assumes that this is a headline
15584 (let ((pos (point)) (col (current-column)) tags)
15585 (beginning-of-line 1)
15586 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15587 (< pos (match-beginning 2)))
15588 (progn
15589 (setq tags (match-string 2))
15590 (goto-char (match-beginning 1))
15591 (insert " ")
15592 (delete-region (point) (1+ (match-end 0)))
15593 (backward-char 1)
15594 (move-to-column
15595 (max (1+ (current-column))
15596 (1+ col)
15597 (if (> to-col 0)
15598 to-col
15599 (- (abs to-col) (length tags))))
15601 (insert tags)
15602 (move-to-column (min (current-column) col) t))
15603 (goto-char pos))))
15605 (defun org-set-tags (&optional arg just-align)
15606 "Set the tags for the current headline.
15607 With prefix ARG, realign all tags in headings in the current buffer."
15608 (interactive "P")
15609 (let* ((re (concat "^" outline-regexp))
15610 (current (org-get-tags-string))
15611 (col (current-column))
15612 (org-setting-tags t)
15613 table current-tags inherited-tags ; computed below when needed
15614 tags p0 c0 c1 rpl)
15615 (if arg
15616 (save-excursion
15617 (goto-char (point-min))
15618 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15619 (while (re-search-forward re nil t)
15620 (org-set-tags nil t)
15621 (end-of-line 1)))
15622 (message "All tags realigned to column %d" org-tags-column))
15623 (if just-align
15624 (setq tags current)
15625 ;; Get a new set of tags from the user
15626 (save-excursion
15627 (setq table (or org-tag-alist (org-get-buffer-tags))
15628 org-last-tags-completion-table table
15629 current-tags (org-split-string current ":")
15630 inherited-tags (nreverse
15631 (nthcdr (length current-tags)
15632 (nreverse (org-get-tags-at))))
15633 tags
15634 (if (or (eq t org-use-fast-tag-selection)
15635 (and org-use-fast-tag-selection
15636 (delq nil (mapcar 'cdr table))))
15637 (org-fast-tag-selection
15638 current-tags inherited-tags table
15639 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15640 (let ((org-add-colon-after-tag-completion t))
15641 (org-trim
15642 (org-without-partial-completion
15643 (completing-read "Tags: " 'org-tags-completion-function
15644 nil nil current 'org-tags-history)))))))
15645 (while (string-match "[-+&]+" tags)
15646 ;; No boolean logic, just a list
15647 (setq tags (replace-match ":" t t tags))))
15649 (if (string-match "\\`[\t ]*\\'" tags)
15650 (setq tags "")
15651 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15652 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15654 ;; Insert new tags at the correct column
15655 (beginning-of-line 1)
15656 (cond
15657 ((and (equal current "") (equal tags "")))
15658 ((re-search-forward
15659 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15660 (point-at-eol) t)
15661 (if (equal tags "")
15662 (setq rpl "")
15663 (goto-char (match-beginning 0))
15664 (setq c0 (current-column) p0 (point)
15665 c1 (max (1+ c0) (if (> org-tags-column 0)
15666 org-tags-column
15667 (- (- org-tags-column) (length tags))))
15668 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15669 (replace-match rpl t t)
15670 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15671 tags)
15672 (t (error "Tags alignment failed")))
15673 (move-to-column col)
15674 (unless just-align
15675 (run-hooks 'org-after-tags-change-hook)))))
15677 (defun org-change-tag-in-region (beg end tag off)
15678 "Add or remove TAG for each entry in the region.
15679 This works in the agenda, and also in an org-mode buffer."
15680 (interactive
15681 (list (region-beginning) (region-end)
15682 (let ((org-last-tags-completion-table
15683 (if (org-mode-p)
15684 (org-get-buffer-tags)
15685 (org-global-tags-completion-table))))
15686 (completing-read
15687 "Tag: " 'org-tags-completion-function nil nil nil
15688 'org-tags-history))
15689 (progn
15690 (message "[s]et or [r]emove? ")
15691 (equal (read-char-exclusive) ?r))))
15692 (if (fboundp 'deactivate-mark) (deactivate-mark))
15693 (let ((agendap (equal major-mode 'org-agenda-mode))
15694 l1 l2 m buf pos newhead (cnt 0))
15695 (goto-char end)
15696 (setq l2 (1- (org-current-line)))
15697 (goto-char beg)
15698 (setq l1 (org-current-line))
15699 (loop for l from l1 to l2 do
15700 (goto-line l)
15701 (setq m (get-text-property (point) 'org-hd-marker))
15702 (when (or (and (org-mode-p) (org-on-heading-p))
15703 (and agendap m))
15704 (setq buf (if agendap (marker-buffer m) (current-buffer))
15705 pos (if agendap m (point)))
15706 (with-current-buffer buf
15707 (save-excursion
15708 (save-restriction
15709 (goto-char pos)
15710 (setq cnt (1+ cnt))
15711 (org-toggle-tag tag (if off 'off 'on))
15712 (setq newhead (org-get-heading)))))
15713 (and agendap (org-agenda-change-all-lines newhead m))))
15714 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15716 (defun org-tags-completion-function (string predicate &optional flag)
15717 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15718 (confirm (lambda (x) (stringp (car x)))))
15719 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15720 (setq s1 (match-string 1 string)
15721 s2 (match-string 2 string))
15722 (setq s1 "" s2 string))
15723 (cond
15724 ((eq flag nil)
15725 ;; try completion
15726 (setq rtn (try-completion s2 ctable confirm))
15727 (if (stringp rtn)
15728 (setq rtn
15729 (concat s1 s2 (substring rtn (length s2))
15730 (if (and org-add-colon-after-tag-completion
15731 (assoc rtn ctable))
15732 ":" ""))))
15733 rtn)
15734 ((eq flag t)
15735 ;; all-completions
15736 (all-completions s2 ctable confirm)
15738 ((eq flag 'lambda)
15739 ;; exact match?
15740 (assoc s2 ctable)))
15743 (defun org-fast-tag-insert (kwd tags face &optional end)
15744 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15745 (insert (format "%-12s" (concat kwd ":"))
15746 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15747 (or end "")))
15749 (defun org-fast-tag-show-exit (flag)
15750 (save-excursion
15751 (goto-line 3)
15752 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15753 (replace-match ""))
15754 (when flag
15755 (end-of-line 1)
15756 (move-to-column (- (window-width) 19) t)
15757 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15759 (defun org-set-current-tags-overlay (current prefix)
15760 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15761 (if (featurep 'xemacs)
15762 (org-overlay-display org-tags-overlay (concat prefix s)
15763 'secondary-selection)
15764 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15765 (org-overlay-display org-tags-overlay (concat prefix s)))))
15767 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15768 "Fast tag selection with single keys.
15769 CURRENT is the current list of tags in the headline, INHERITED is the
15770 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15771 possibly with grouping information. TODO-TABLE is a similar table with
15772 TODO keywords, should these have keys assigned to them.
15773 If the keys are nil, a-z are automatically assigned.
15774 Returns the new tags string, or nil to not change the current settings."
15775 (let* ((fulltable (append table todo-table))
15776 (maxlen (apply 'max (mapcar
15777 (lambda (x)
15778 (if (stringp (car x)) (string-width (car x)) 0))
15779 fulltable)))
15780 (buf (current-buffer))
15781 (expert (eq org-fast-tag-selection-single-key 'expert))
15782 (buffer-tags nil)
15783 (fwidth (+ maxlen 3 1 3))
15784 (ncol (/ (- (window-width) 4) fwidth))
15785 (i-face 'org-done)
15786 (c-face 'org-todo)
15787 tg cnt e c char c1 c2 ntable tbl rtn
15788 ov-start ov-end ov-prefix
15789 (exit-after-next org-fast-tag-selection-single-key)
15790 (done-keywords org-done-keywords)
15791 groups ingroup)
15792 (save-excursion
15793 (beginning-of-line 1)
15794 (if (looking-at
15795 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15796 (setq ov-start (match-beginning 1)
15797 ov-end (match-end 1)
15798 ov-prefix "")
15799 (setq ov-start (1- (point-at-eol))
15800 ov-end (1+ ov-start))
15801 (skip-chars-forward "^\n\r")
15802 (setq ov-prefix
15803 (concat
15804 (buffer-substring (1- (point)) (point))
15805 (if (> (current-column) org-tags-column)
15807 (make-string (- org-tags-column (current-column)) ?\ ))))))
15808 (org-move-overlay org-tags-overlay ov-start ov-end)
15809 (save-window-excursion
15810 (if expert
15811 (set-buffer (get-buffer-create " *Org tags*"))
15812 (delete-other-windows)
15813 (split-window-vertically)
15814 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15815 (erase-buffer)
15816 (org-set-local 'org-done-keywords done-keywords)
15817 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15818 (org-fast-tag-insert "Current" current c-face "\n\n")
15819 (org-fast-tag-show-exit exit-after-next)
15820 (org-set-current-tags-overlay current ov-prefix)
15821 (setq tbl fulltable char ?a cnt 0)
15822 (while (setq e (pop tbl))
15823 (cond
15824 ((equal e '(:startgroup))
15825 (push '() groups) (setq ingroup t)
15826 (when (not (= cnt 0))
15827 (setq cnt 0)
15828 (insert "\n"))
15829 (insert "{ "))
15830 ((equal e '(:endgroup))
15831 (setq ingroup nil cnt 0)
15832 (insert "}\n"))
15834 (setq tg (car e) c2 nil)
15835 (if (cdr e)
15836 (setq c (cdr e))
15837 ;; automatically assign a character.
15838 (setq c1 (string-to-char
15839 (downcase (substring
15840 tg (if (= (string-to-char tg) ?@) 1 0)))))
15841 (if (or (rassoc c1 ntable) (rassoc c1 table))
15842 (while (or (rassoc char ntable) (rassoc char table))
15843 (setq char (1+ char)))
15844 (setq c2 c1))
15845 (setq c (or c2 char)))
15846 (if ingroup (push tg (car groups)))
15847 (setq tg (org-add-props tg nil 'face
15848 (cond
15849 ((not (assoc tg table))
15850 (org-get-todo-face tg))
15851 ((member tg current) c-face)
15852 ((member tg inherited) i-face)
15853 (t nil))))
15854 (if (and (= cnt 0) (not ingroup)) (insert " "))
15855 (insert "[" c "] " tg (make-string
15856 (- fwidth 4 (length tg)) ?\ ))
15857 (push (cons tg c) ntable)
15858 (when (= (setq cnt (1+ cnt)) ncol)
15859 (insert "\n")
15860 (if ingroup (insert " "))
15861 (setq cnt 0)))))
15862 (setq ntable (nreverse ntable))
15863 (insert "\n")
15864 (goto-char (point-min))
15865 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15866 (fit-window-to-buffer))
15867 (setq rtn
15868 (catch 'exit
15869 (while t
15870 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15871 (if groups " [!] no groups" " [!]groups")
15872 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15873 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15874 (cond
15875 ((= c ?\r) (throw 'exit t))
15876 ((= c ?!)
15877 (setq groups (not groups))
15878 (goto-char (point-min))
15879 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15880 ((= c ?\C-c)
15881 (if (not expert)
15882 (org-fast-tag-show-exit
15883 (setq exit-after-next (not exit-after-next)))
15884 (setq expert nil)
15885 (delete-other-windows)
15886 (split-window-vertically)
15887 (org-switch-to-buffer-other-window " *Org tags*")
15888 (and (fboundp 'fit-window-to-buffer)
15889 (fit-window-to-buffer))))
15890 ((or (= c ?\C-g)
15891 (and (= c ?q) (not (rassoc c ntable))))
15892 (org-detach-overlay org-tags-overlay)
15893 (setq quit-flag t))
15894 ((= c ?\ )
15895 (setq current nil)
15896 (if exit-after-next (setq exit-after-next 'now)))
15897 ((= c ?\t)
15898 (condition-case nil
15899 (setq tg (completing-read
15900 "Tag: "
15901 (or buffer-tags
15902 (with-current-buffer buf
15903 (org-get-buffer-tags)))))
15904 (quit (setq tg "")))
15905 (when (string-match "\\S-" tg)
15906 (add-to-list 'buffer-tags (list tg))
15907 (if (member tg current)
15908 (setq current (delete tg current))
15909 (push tg current)))
15910 (if exit-after-next (setq exit-after-next 'now)))
15911 ((setq e (rassoc c todo-table) tg (car e))
15912 (with-current-buffer buf
15913 (save-excursion (org-todo tg)))
15914 (if exit-after-next (setq exit-after-next 'now)))
15915 ((setq e (rassoc c ntable) tg (car e))
15916 (if (member tg current)
15917 (setq current (delete tg current))
15918 (loop for g in groups do
15919 (if (member tg g)
15920 (mapc (lambda (x)
15921 (setq current (delete x current)))
15922 g)))
15923 (push tg current))
15924 (if exit-after-next (setq exit-after-next 'now))))
15926 ;; Create a sorted list
15927 (setq current
15928 (sort current
15929 (lambda (a b)
15930 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15931 (if (eq exit-after-next 'now) (throw 'exit t))
15932 (goto-char (point-min))
15933 (beginning-of-line 2)
15934 (delete-region (point) (point-at-eol))
15935 (org-fast-tag-insert "Current" current c-face)
15936 (org-set-current-tags-overlay current ov-prefix)
15937 (while (re-search-forward
15938 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15939 (setq tg (match-string 1))
15940 (add-text-properties
15941 (match-beginning 1) (match-end 1)
15942 (list 'face
15943 (cond
15944 ((member tg current) c-face)
15945 ((member tg inherited) i-face)
15946 (t (get-text-property (match-beginning 1) 'face))))))
15947 (goto-char (point-min)))))
15948 (org-detach-overlay org-tags-overlay)
15949 (if rtn
15950 (mapconcat 'identity current ":")
15951 nil))))
15953 (defun org-get-tags-string ()
15954 "Get the TAGS string in the current headline."
15955 (unless (org-on-heading-p t)
15956 (error "Not on a heading"))
15957 (save-excursion
15958 (beginning-of-line 1)
15959 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15960 (org-match-string-no-properties 1)
15961 "")))
15963 (defun org-get-tags ()
15964 "Get the list of tags specified in the current headline."
15965 (org-split-string (org-get-tags-string) ":"))
15967 (defun org-get-buffer-tags ()
15968 "Get a table of all tags used in the buffer, for completion."
15969 (let (tags)
15970 (save-excursion
15971 (goto-char (point-min))
15972 (while (re-search-forward
15973 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15974 (when (equal (char-after (point-at-bol 0)) ?*)
15975 (mapc (lambda (x) (add-to-list 'tags x))
15976 (org-split-string (org-match-string-no-properties 1) ":")))))
15977 (mapcar 'list tags)))
15980 ;;;; Properties
15982 ;;; Setting and retrieving properties
15984 (defconst org-special-properties
15985 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15986 "TIMESTAMP" "TIMESTAMP_IA")
15987 "The special properties valid in Org-mode.
15989 These are properties that are not defined in the property drawer,
15990 but in some other way.")
15992 (defconst org-default-properties
15993 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15994 "LOCATION" "LOGGING" "COLUMNS")
15995 "Some properties that are used by Org-mode for various purposes.
15996 Being in this list makes sure that they are offered for completion.")
15998 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15999 "Regular expression matching the first line of a property drawer.")
16001 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16002 "Regular expression matching the first line of a property drawer.")
16004 (defun org-property-action ()
16005 "Do an action on properties."
16006 (interactive)
16007 (let (c)
16008 (org-at-property-p)
16009 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16010 (setq c (read-char-exclusive))
16011 (cond
16012 ((equal c ?s)
16013 (call-interactively 'org-set-property))
16014 ((equal c ?d)
16015 (call-interactively 'org-delete-property))
16016 ((equal c ?D)
16017 (call-interactively 'org-delete-property-globally))
16018 ((equal c ?c)
16019 (call-interactively 'org-compute-property-at-point))
16020 (t (error "No such property action %c" c)))))
16022 (defun org-at-property-p ()
16023 "Is the cursor in a property line?"
16024 ;; FIXME: Does not check if we are actually in the drawer.
16025 ;; FIXME: also returns true on any drawers.....
16026 ;; This is used by C-c C-c for property action.
16027 (save-excursion
16028 (beginning-of-line 1)
16029 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16031 (defmacro org-with-point-at (pom &rest body)
16032 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16033 (declare (indent 1) (debug t))
16034 `(save-excursion
16035 (if (markerp pom) (set-buffer (marker-buffer pom)))
16036 (save-excursion
16037 (goto-char (or pom (point)))
16038 ,@body)))
16040 (defun org-get-property-block (&optional beg end force)
16041 "Return the (beg . end) range of the body of the property drawer.
16042 BEG and END can be beginning and end of subtree, if not given
16043 they will be found.
16044 If the drawer does not exist and FORCE is non-nil, create the drawer."
16045 (catch 'exit
16046 (save-excursion
16047 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16048 (end (or end (progn (outline-next-heading) (point)))))
16049 (goto-char beg)
16050 (if (re-search-forward org-property-start-re end t)
16051 (setq beg (1+ (match-end 0)))
16052 (if force
16053 (save-excursion
16054 (org-insert-property-drawer)
16055 (setq end (progn (outline-next-heading) (point))))
16056 (throw 'exit nil))
16057 (goto-char beg)
16058 (if (re-search-forward org-property-start-re end t)
16059 (setq beg (1+ (match-end 0)))))
16060 (if (re-search-forward org-property-end-re end t)
16061 (setq end (match-beginning 0))
16062 (or force (throw 'exit nil))
16063 (goto-char beg)
16064 (setq end beg)
16065 (org-indent-line-function)
16066 (insert ":END:\n"))
16067 (cons beg end)))))
16069 (defun org-entry-properties (&optional pom which)
16070 "Get all properties of the entry at point-or-marker POM.
16071 This includes the TODO keyword, the tags, time strings for deadline,
16072 scheduled, and clocking, and any additional properties defined in the
16073 entry. The return value is an alist, keys may occur multiple times
16074 if the property key was used several times.
16075 POM may also be nil, in which case the current entry is used.
16076 If WHICH is nil or `all', get all properties. If WHICH is
16077 `special' or `standard', only get that subclass."
16078 (setq which (or which 'all))
16079 (org-with-point-at pom
16080 (let ((clockstr (substring org-clock-string 0 -1))
16081 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16082 beg end range props sum-props key value string clocksum)
16083 (save-excursion
16084 (when (condition-case nil (org-back-to-heading t) (error nil))
16085 (setq beg (point))
16086 (setq sum-props (get-text-property (point) 'org-summaries))
16087 (setq clocksum (get-text-property (point) :org-clock-minutes))
16088 (outline-next-heading)
16089 (setq end (point))
16090 (when (memq which '(all special))
16091 ;; Get the special properties, like TODO and tags
16092 (goto-char beg)
16093 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16094 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16095 (when (looking-at org-priority-regexp)
16096 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16097 (when (and (setq value (org-get-tags-string))
16098 (string-match "\\S-" value))
16099 (push (cons "TAGS" value) props))
16100 (when (setq value (org-get-tags-at))
16101 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16102 props))
16103 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16104 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16105 string (if (equal key clockstr)
16106 (org-no-properties
16107 (org-trim
16108 (buffer-substring
16109 (match-beginning 3) (goto-char (point-at-eol)))))
16110 (substring (org-match-string-no-properties 3) 1 -1)))
16111 (unless key
16112 (if (= (char-after (match-beginning 3)) ?\[)
16113 (setq key "TIMESTAMP_IA")
16114 (setq key "TIMESTAMP")))
16115 (when (or (equal key clockstr) (not (assoc key props)))
16116 (push (cons key string) props)))
16120 (when (memq which '(all standard))
16121 ;; Get the standard properties, like :PORP: ...
16122 (setq range (org-get-property-block beg end))
16123 (when range
16124 (goto-char (car range))
16125 (while (re-search-forward
16126 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16127 (cdr range) t)
16128 (setq key (org-match-string-no-properties 1)
16129 value (org-trim (or (org-match-string-no-properties 2) "")))
16130 (unless (member key excluded)
16131 (push (cons key (or value "")) props)))))
16132 (if clocksum
16133 (push (cons "CLOCKSUM"
16134 (org-column-number-to-string (/ (float clocksum) 60.)
16135 'add_times))
16136 props))
16137 (append sum-props (nreverse props)))))))
16139 (defun org-entry-get (pom property &optional inherit)
16140 "Get value of PROPERTY for entry at point-or-marker POM.
16141 If INHERIT is non-nil and the entry does not have the property,
16142 then also check higher levels of the hierarchy.
16143 If the property is present but empty, the return value is the empty string.
16144 If the property is not present at all, nil is returned."
16145 (org-with-point-at pom
16146 (if inherit
16147 (org-entry-get-with-inheritance property)
16148 (if (member property org-special-properties)
16149 ;; We need a special property. Use brute force, get all properties.
16150 (cdr (assoc property (org-entry-properties nil 'special)))
16151 (let ((range (org-get-property-block)))
16152 (if (and range
16153 (goto-char (car range))
16154 (re-search-forward
16155 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16156 (cdr range) t))
16157 ;; Found the property, return it.
16158 (if (match-end 1)
16159 (org-match-string-no-properties 1)
16160 "")))))))
16162 (defun org-entry-delete (pom property)
16163 "Delete the property PROPERTY from entry at point-or-marker POM."
16164 (org-with-point-at pom
16165 (if (member property org-special-properties)
16166 nil ; cannot delete these properties.
16167 (let ((range (org-get-property-block)))
16168 (if (and range
16169 (goto-char (car range))
16170 (re-search-forward
16171 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16172 (cdr range) t))
16173 (progn
16174 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16176 nil)))))
16178 ;; Multi-values properties are properties that contain multiple values
16179 ;; These values are assumed to be single words, separated by whitespace.
16180 (defun org-entry-add-to-multivalued-property (pom property value)
16181 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16182 (let* ((old (org-entry-get pom property))
16183 (values (and old (org-split-string old "[ \t]"))))
16184 (unless (member value values)
16185 (setq values (cons value values))
16186 (org-entry-put pom property
16187 (mapconcat 'identity values " ")))))
16189 (defun org-entry-remove-from-multivalued-property (pom property value)
16190 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16191 (let* ((old (org-entry-get pom property))
16192 (values (and old (org-split-string old "[ \t]"))))
16193 (when (member value values)
16194 (setq values (delete value values))
16195 (org-entry-put pom property
16196 (mapconcat 'identity values " ")))))
16198 (defun org-entry-member-in-multivalued-property (pom property value)
16199 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16200 (let* ((old (org-entry-get pom property))
16201 (values (and old (org-split-string old "[ \t]"))))
16202 (member value values)))
16204 (defvar org-entry-property-inherited-from (make-marker))
16206 (defun org-entry-get-with-inheritance (property)
16207 "Get entry property, and search higher levels if not present."
16208 (let (tmp)
16209 (save-excursion
16210 (save-restriction
16211 (widen)
16212 (catch 'ex
16213 (while t
16214 (when (setq tmp (org-entry-get nil property))
16215 (org-back-to-heading t)
16216 (move-marker org-entry-property-inherited-from (point))
16217 (throw 'ex tmp))
16218 (or (org-up-heading-safe) (throw 'ex nil)))))
16219 (or tmp (cdr (assoc property org-local-properties))
16220 (cdr (assoc property org-global-properties))))))
16222 (defun org-entry-put (pom property value)
16223 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16224 (org-with-point-at pom
16225 (org-back-to-heading t)
16226 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16227 range)
16228 (cond
16229 ((equal property "TODO")
16230 (when (and (stringp value) (string-match "\\S-" value)
16231 (not (member value org-todo-keywords-1)))
16232 (error "\"%s\" is not a valid TODO state" value))
16233 (if (or (not value)
16234 (not (string-match "\\S-" value)))
16235 (setq value 'none))
16236 (org-todo value)
16237 (org-set-tags nil 'align))
16238 ((equal property "PRIORITY")
16239 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16240 (string-to-char value) ?\ ))
16241 (org-set-tags nil 'align))
16242 ((equal property "SCHEDULED")
16243 (if (re-search-forward org-scheduled-time-regexp end t)
16244 (cond
16245 ((eq value 'earlier) (org-timestamp-change -1 'day))
16246 ((eq value 'later) (org-timestamp-change 1 'day))
16247 (t (call-interactively 'org-schedule)))
16248 (call-interactively 'org-schedule)))
16249 ((equal property "DEADLINE")
16250 (if (re-search-forward org-deadline-time-regexp end t)
16251 (cond
16252 ((eq value 'earlier) (org-timestamp-change -1 'day))
16253 ((eq value 'later) (org-timestamp-change 1 'day))
16254 (t (call-interactively 'org-deadline)))
16255 (call-interactively 'org-deadline)))
16256 ((member property org-special-properties)
16257 (error "The %s property can not yet be set with `org-entry-put'"
16258 property))
16259 (t ; a non-special property
16260 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16261 (setq range (org-get-property-block beg end 'force))
16262 (goto-char (car range))
16263 (if (re-search-forward
16264 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16265 (progn
16266 (delete-region (match-beginning 1) (match-end 1))
16267 (goto-char (match-beginning 1)))
16268 (goto-char (cdr range))
16269 (insert "\n")
16270 (backward-char 1)
16271 (org-indent-line-function)
16272 (insert ":" property ":"))
16273 (and value (insert " " value))
16274 (org-indent-line-function)))))))
16276 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16277 "Get all property keys in the current buffer.
16278 With INCLUDE-SPECIALS, also list the special properties that relect things
16279 like tags and TODO state.
16280 With INCLUDE-DEFAULTS, also include properties that has special meaning
16281 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16282 With INCLUDE-COLUMNS, also include property names given in COLUMN
16283 formats in the current buffer."
16284 (let (rtn range cfmt cols s p)
16285 (save-excursion
16286 (save-restriction
16287 (widen)
16288 (goto-char (point-min))
16289 (while (re-search-forward org-property-start-re nil t)
16290 (setq range (org-get-property-block))
16291 (goto-char (car range))
16292 (while (re-search-forward
16293 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16294 (cdr range) t)
16295 (add-to-list 'rtn (org-match-string-no-properties 1)))
16296 (outline-next-heading))))
16298 (when include-specials
16299 (setq rtn (append org-special-properties rtn)))
16301 (when include-defaults
16302 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16304 (when include-columns
16305 (save-excursion
16306 (save-restriction
16307 (widen)
16308 (goto-char (point-min))
16309 (while (re-search-forward
16310 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16311 nil t)
16312 (setq cfmt (match-string 2) s 0)
16313 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16314 cfmt s)
16315 (setq s (match-end 0)
16316 p (match-string 1 cfmt))
16317 (unless (or (equal p "ITEM")
16318 (member p org-special-properties))
16319 (add-to-list 'rtn (match-string 1 cfmt))))))))
16321 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16323 (defun org-property-values (key)
16324 "Return a list of all values of property KEY."
16325 (save-excursion
16326 (save-restriction
16327 (widen)
16328 (goto-char (point-min))
16329 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16330 values)
16331 (while (re-search-forward re nil t)
16332 (add-to-list 'values (org-trim (match-string 1))))
16333 (delete "" values)))))
16335 (defun org-insert-property-drawer ()
16336 "Insert a property drawer into the current entry."
16337 (interactive)
16338 (org-back-to-heading t)
16339 (looking-at outline-regexp)
16340 (let ((indent (- (match-end 0)(match-beginning 0)))
16341 (beg (point))
16342 (re (concat "^[ \t]*" org-keyword-time-regexp))
16343 end hiddenp)
16344 (outline-next-heading)
16345 (setq end (point))
16346 (goto-char beg)
16347 (while (re-search-forward re end t))
16348 (setq hiddenp (org-invisible-p))
16349 (end-of-line 1)
16350 (and (equal (char-after) ?\n) (forward-char 1))
16351 (org-skip-over-state-notes)
16352 (skip-chars-backward " \t\n\r")
16353 (if (eq (char-before) ?*) (forward-char 1))
16354 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16355 (beginning-of-line 0)
16356 (indent-to-column indent)
16357 (beginning-of-line 2)
16358 (indent-to-column indent)
16359 (beginning-of-line 0)
16360 (if hiddenp
16361 (save-excursion
16362 (org-back-to-heading t)
16363 (hide-entry))
16364 (org-flag-drawer t))))
16366 (defun org-set-property (property value)
16367 "In the current entry, set PROPERTY to VALUE.
16368 When called interactively, this will prompt for a property name, offering
16369 completion on existing and default properties. And then it will prompt
16370 for a value, offering competion either on allowed values (via an inherited
16371 xxx_ALL property) or on existing values in other instances of this property
16372 in the current file."
16373 (interactive
16374 (let* ((prop (completing-read
16375 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16376 (cur (org-entry-get nil prop))
16377 (allowed (org-property-get-allowed-values nil prop 'table))
16378 (existing (mapcar 'list (org-property-values prop)))
16379 (val (if allowed
16380 (completing-read "Value: " allowed nil 'req-match)
16381 (completing-read
16382 (concat "Value" (if (and cur (string-match "\\S-" cur))
16383 (concat "[" cur "]") "")
16384 ": ")
16385 existing nil nil "" nil cur))))
16386 (list prop (if (equal val "") cur val))))
16387 (unless (equal (org-entry-get nil property) value)
16388 (org-entry-put nil property value)))
16390 (defun org-delete-property (property)
16391 "In the current entry, delete PROPERTY."
16392 (interactive
16393 (let* ((prop (completing-read
16394 "Property: " (org-entry-properties nil 'standard))))
16395 (list prop)))
16396 (message "Property %s %s" property
16397 (if (org-entry-delete nil property)
16398 "deleted"
16399 "was not present in the entry")))
16401 (defun org-delete-property-globally (property)
16402 "Remove PROPERTY globally, from all entries."
16403 (interactive
16404 (let* ((prop (completing-read
16405 "Globally remove property: "
16406 (mapcar 'list (org-buffer-property-keys)))))
16407 (list prop)))
16408 (save-excursion
16409 (save-restriction
16410 (widen)
16411 (goto-char (point-min))
16412 (let ((cnt 0))
16413 (while (re-search-forward
16414 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16415 nil t)
16416 (setq cnt (1+ cnt))
16417 (replace-match ""))
16418 (message "Property \"%s\" removed from %d entries" property cnt)))))
16420 (defvar org-columns-current-fmt-compiled) ; defined below
16422 (defun org-compute-property-at-point ()
16423 "Compute the property at point.
16424 This looks for an enclosing column format, extracts the operator and
16425 then applies it to the proerty in the column format's scope."
16426 (interactive)
16427 (unless (org-at-property-p)
16428 (error "Not at a property"))
16429 (let ((prop (org-match-string-no-properties 2)))
16430 (org-columns-get-format-and-top-level)
16431 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16432 (error "No operator defined for property %s" prop))
16433 (org-columns-compute prop)))
16435 (defun org-property-get-allowed-values (pom property &optional table)
16436 "Get allowed values for the property PROPERTY.
16437 When TABLE is non-nil, return an alist that can directly be used for
16438 completion."
16439 (let (vals)
16440 (cond
16441 ((equal property "TODO")
16442 (setq vals (org-with-point-at pom
16443 (append org-todo-keywords-1 '("")))))
16444 ((equal property "PRIORITY")
16445 (let ((n org-lowest-priority))
16446 (while (>= n org-highest-priority)
16447 (push (char-to-string n) vals)
16448 (setq n (1- n)))))
16449 ((member property org-special-properties))
16451 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16453 (when (and vals (string-match "\\S-" vals))
16454 (setq vals (car (read-from-string (concat "(" vals ")"))))
16455 (setq vals (mapcar (lambda (x)
16456 (cond ((stringp x) x)
16457 ((numberp x) (number-to-string x))
16458 ((symbolp x) (symbol-name x))
16459 (t "???")))
16460 vals)))))
16461 (if table (mapcar 'list vals) vals)))
16463 (defun org-property-previous-allowed-value (&optional previous)
16464 "Switch to the next allowed value for this property."
16465 (interactive)
16466 (org-property-next-allowed-value t))
16468 (defun org-property-next-allowed-value (&optional previous)
16469 "Switch to the next allowed value for this property."
16470 (interactive)
16471 (unless (org-at-property-p)
16472 (error "Not at a property"))
16473 (let* ((key (match-string 2))
16474 (value (match-string 3))
16475 (allowed (or (org-property-get-allowed-values (point) key)
16476 (and (member value '("[ ]" "[-]" "[X]"))
16477 '("[ ]" "[X]"))))
16478 nval)
16479 (unless allowed
16480 (error "Allowed values for this property have not been defined"))
16481 (if previous (setq allowed (reverse allowed)))
16482 (if (member value allowed)
16483 (setq nval (car (cdr (member value allowed)))))
16484 (setq nval (or nval (car allowed)))
16485 (if (equal nval value)
16486 (error "Only one allowed value for this property"))
16487 (org-at-property-p)
16488 (replace-match (concat " :" key ": " nval) t t)
16489 (org-indent-line-function)
16490 (beginning-of-line 1)
16491 (skip-chars-forward " \t")))
16493 (defun org-find-entry-with-id (ident)
16494 "Locate the entry that contains the ID property with exact value IDENT.
16495 IDENT can be a string, a symbol or a number, this function will search for
16496 the string representation of it.
16497 Return the position where this entry starts, or nil if there is no such entry."
16498 (let ((id (cond
16499 ((stringp ident) ident)
16500 ((symbol-name ident) (symbol-name ident))
16501 ((numberp ident) (number-to-string ident))
16502 (t (error "IDENT %s must be a string, symbol or number" ident))))
16503 (case-fold-search nil))
16504 (save-excursion
16505 (save-restriction
16506 (widen)
16507 (goto-char (point-min))
16508 (when (re-search-forward
16509 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16510 nil t)
16511 (org-back-to-heading)
16512 (point))))))
16514 ;;; Column View
16516 (defvar org-columns-overlays nil
16517 "Holds the list of current column overlays.")
16519 (defvar org-columns-current-fmt nil
16520 "Local variable, holds the currently active column format.")
16521 (defvar org-columns-current-fmt-compiled nil
16522 "Local variable, holds the currently active column format.
16523 This is the compiled version of the format.")
16524 (defvar org-columns-current-widths nil
16525 "Loval variable, holds the currently widths of fields.")
16526 (defvar org-columns-current-maxwidths nil
16527 "Loval variable, holds the currently active maximum column widths.")
16528 (defvar org-columns-begin-marker (make-marker)
16529 "Points to the position where last a column creation command was called.")
16530 (defvar org-columns-top-level-marker (make-marker)
16531 "Points to the position where current columns region starts.")
16533 (defvar org-columns-map (make-sparse-keymap)
16534 "The keymap valid in column display.")
16536 (defun org-columns-content ()
16537 "Switch to contents view while in columns view."
16538 (interactive)
16539 (org-overview)
16540 (org-content))
16542 (org-defkey org-columns-map "c" 'org-columns-content)
16543 (org-defkey org-columns-map "o" 'org-overview)
16544 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16545 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16546 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16547 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16548 (org-defkey org-columns-map "v" 'org-columns-show-value)
16549 (org-defkey org-columns-map "q" 'org-columns-quit)
16550 (org-defkey org-columns-map "r" 'org-columns-redo)
16551 (org-defkey org-columns-map "g" 'org-columns-redo)
16552 (org-defkey org-columns-map [left] 'backward-char)
16553 (org-defkey org-columns-map "\M-b" 'backward-char)
16554 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16555 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16556 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16557 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16558 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16559 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16560 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16561 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16562 (org-defkey org-columns-map "<" 'org-columns-narrow)
16563 (org-defkey org-columns-map ">" 'org-columns-widen)
16564 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16565 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16566 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16567 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16569 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16570 '("Column"
16571 ["Edit property" org-columns-edit-value t]
16572 ["Next allowed value" org-columns-next-allowed-value t]
16573 ["Previous allowed value" org-columns-previous-allowed-value t]
16574 ["Show full value" org-columns-show-value t]
16575 ["Edit allowed values" org-columns-edit-allowed t]
16576 "--"
16577 ["Edit column attributes" org-columns-edit-attributes t]
16578 ["Increase column width" org-columns-widen t]
16579 ["Decrease column width" org-columns-narrow t]
16580 "--"
16581 ["Move column right" org-columns-move-right t]
16582 ["Move column left" org-columns-move-left t]
16583 ["Add column" org-columns-new t]
16584 ["Delete column" org-columns-delete t]
16585 "--"
16586 ["CONTENTS" org-columns-content t]
16587 ["OVERVIEW" org-overview t]
16588 ["Refresh columns display" org-columns-redo t]
16589 "--"
16590 ["Open link" org-columns-open-link t]
16591 "--"
16592 ["Quit" org-columns-quit t]))
16594 (defun org-columns-new-overlay (beg end &optional string face)
16595 "Create a new column overlay and add it to the list."
16596 (let ((ov (org-make-overlay beg end)))
16597 (org-overlay-put ov 'face (or face 'secondary-selection))
16598 (org-overlay-display ov string face)
16599 (push ov org-columns-overlays)
16600 ov))
16602 (defun org-columns-display-here (&optional props)
16603 "Overlay the current line with column display."
16604 (interactive)
16605 (let* ((fmt org-columns-current-fmt-compiled)
16606 (beg (point-at-bol))
16607 (level-face (save-excursion
16608 (beginning-of-line 1)
16609 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16610 (org-get-level-face 2))))
16611 (color (list :foreground
16612 (face-attribute (or level-face 'default) :foreground)))
16613 props pom property ass width f string ov column val modval)
16614 ;; Check if the entry is in another buffer.
16615 (unless props
16616 (if (eq major-mode 'org-agenda-mode)
16617 (setq pom (or (get-text-property (point) 'org-hd-marker)
16618 (get-text-property (point) 'org-marker))
16619 props (if pom (org-entry-properties pom) nil))
16620 (setq props (org-entry-properties nil))))
16621 ;; Walk the format
16622 (while (setq column (pop fmt))
16623 (setq property (car column)
16624 ass (if (equal property "ITEM")
16625 (cons "ITEM"
16626 (save-match-data
16627 (org-no-properties
16628 (org-remove-tabs
16629 (buffer-substring-no-properties
16630 (point-at-bol) (point-at-eol))))))
16631 (assoc property props))
16632 width (or (cdr (assoc property org-columns-current-maxwidths))
16633 (nth 2 column)
16634 (length property))
16635 f (format "%%-%d.%ds | " width width)
16636 val (or (cdr ass) "")
16637 modval (if (equal property "ITEM")
16638 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16639 string (format f (or modval val)))
16640 ;; Create the overlay
16641 (org-unmodified
16642 (setq ov (org-columns-new-overlay
16643 beg (setq beg (1+ beg)) string
16644 (list color 'org-column)))
16645 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16646 (org-overlay-put ov 'keymap org-columns-map)
16647 (org-overlay-put ov 'org-columns-key property)
16648 (org-overlay-put ov 'org-columns-value (cdr ass))
16649 (org-overlay-put ov 'org-columns-value-modified modval)
16650 (org-overlay-put ov 'org-columns-pom pom)
16651 (org-overlay-put ov 'org-columns-format f))
16652 (if (or (not (char-after beg))
16653 (equal (char-after beg) ?\n))
16654 (let ((inhibit-read-only t))
16655 (save-excursion
16656 (goto-char beg)
16657 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16658 ;; Make the rest of the line disappear.
16659 (org-unmodified
16660 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16661 (org-overlay-put ov 'invisible t)
16662 (org-overlay-put ov 'keymap org-columns-map)
16663 (org-overlay-put ov 'intangible t)
16664 (push ov org-columns-overlays)
16665 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16666 (org-overlay-put ov 'keymap org-columns-map)
16667 (push ov org-columns-overlays)
16668 (let ((inhibit-read-only t))
16669 (put-text-property (max (point-min) (1- (point-at-bol)))
16670 (min (point-max) (1+ (point-at-eol)))
16671 'read-only "Type `e' to edit property")))))
16673 (defvar org-previous-header-line-format nil
16674 "The header line format before column view was turned on.")
16675 (defvar org-columns-inhibit-recalculation nil
16676 "Inhibit recomputing of columns on column view startup.")
16679 (defvar header-line-format)
16680 (defun org-columns-display-here-title ()
16681 "Overlay the newline before the current line with the table title."
16682 (interactive)
16683 (let ((fmt org-columns-current-fmt-compiled)
16684 string (title "")
16685 property width f column str widths)
16686 (while (setq column (pop fmt))
16687 (setq property (car column)
16688 str (or (nth 1 column) property)
16689 width (or (cdr (assoc property org-columns-current-maxwidths))
16690 (nth 2 column)
16691 (length str))
16692 widths (push width widths)
16693 f (format "%%-%d.%ds | " width width)
16694 string (format f str)
16695 title (concat title string)))
16696 (setq title (concat
16697 (org-add-props " " nil 'display '(space :align-to 0))
16698 (org-add-props title nil 'face '(:weight bold :underline t))))
16699 (org-set-local 'org-previous-header-line-format header-line-format)
16700 (org-set-local 'org-columns-current-widths (nreverse widths))
16701 (setq header-line-format title)))
16703 (defun org-columns-remove-overlays ()
16704 "Remove all currently active column overlays."
16705 (interactive)
16706 (when (marker-buffer org-columns-begin-marker)
16707 (with-current-buffer (marker-buffer org-columns-begin-marker)
16708 (when (local-variable-p 'org-previous-header-line-format)
16709 (setq header-line-format org-previous-header-line-format)
16710 (kill-local-variable 'org-previous-header-line-format))
16711 (move-marker org-columns-begin-marker nil)
16712 (move-marker org-columns-top-level-marker nil)
16713 (org-unmodified
16714 (mapc 'org-delete-overlay org-columns-overlays)
16715 (setq org-columns-overlays nil)
16716 (let ((inhibit-read-only t))
16717 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16719 (defun org-columns-cleanup-item (item fmt)
16720 "Remove from ITEM what is a column in the format FMT."
16721 (if (not org-complex-heading-regexp)
16722 item
16723 (when (string-match org-complex-heading-regexp item)
16724 (concat
16725 (org-add-props (concat (match-string 1 item) " ") nil
16726 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16727 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16728 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16729 " " (match-string 4 item)
16730 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16732 (defun org-columns-show-value ()
16733 "Show the full value of the property."
16734 (interactive)
16735 (let ((value (get-char-property (point) 'org-columns-value)))
16736 (message "Value is: %s" (or value ""))))
16738 (defun org-columns-quit ()
16739 "Remove the column overlays and in this way exit column editing."
16740 (interactive)
16741 (org-unmodified
16742 (org-columns-remove-overlays)
16743 (let ((inhibit-read-only t))
16744 (remove-text-properties (point-min) (point-max) '(read-only t))))
16745 (when (eq major-mode 'org-agenda-mode)
16746 (message
16747 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16749 (defun org-columns-check-computed ()
16750 "Check if this column value is computed.
16751 If yes, throw an error indicating that changing it does not make sense."
16752 (let ((val (get-char-property (point) 'org-columns-value)))
16753 (when (and (stringp val)
16754 (get-char-property 0 'org-computed val))
16755 (error "This value is computed from the entry's children"))))
16757 (defun org-columns-todo (&optional arg)
16758 "Change the TODO state during column view."
16759 (interactive "P")
16760 (org-columns-edit-value "TODO"))
16762 (defun org-columns-set-tags-or-toggle (&optional arg)
16763 "Toggle checkbox at point, or set tags for current headline."
16764 (interactive "P")
16765 (if (string-match "\\`\\[[ xX-]\\]\\'"
16766 (get-char-property (point) 'org-columns-value))
16767 (org-columns-next-allowed-value)
16768 (org-columns-edit-value "TAGS")))
16770 (defun org-columns-edit-value (&optional key)
16771 "Edit the value of the property at point in column view.
16772 Where possible, use the standard interface for changing this line."
16773 (interactive)
16774 (org-columns-check-computed)
16775 (let* ((external-key key)
16776 (col (current-column))
16777 (key (or key (get-char-property (point) 'org-columns-key)))
16778 (value (get-char-property (point) 'org-columns-value))
16779 (bol (point-at-bol)) (eol (point-at-eol))
16780 (pom (or (get-text-property bol 'org-hd-marker)
16781 (point))) ; keep despite of compiler waring
16782 (line-overlays
16783 (delq nil (mapcar (lambda (x)
16784 (and (eq (overlay-buffer x) (current-buffer))
16785 (>= (overlay-start x) bol)
16786 (<= (overlay-start x) eol)
16788 org-columns-overlays)))
16789 nval eval allowed)
16790 (cond
16791 ((equal key "CLOCKSUM")
16792 (error "This special column cannot be edited"))
16793 ((equal key "ITEM")
16794 (setq eval '(org-with-point-at pom
16795 (org-edit-headline))))
16796 ((equal key "TODO")
16797 (setq eval '(org-with-point-at pom
16798 (let ((current-prefix-arg
16799 (if external-key current-prefix-arg '(4))))
16800 (call-interactively 'org-todo)))))
16801 ((equal key "PRIORITY")
16802 (setq eval '(org-with-point-at pom
16803 (call-interactively 'org-priority))))
16804 ((equal key "TAGS")
16805 (setq eval '(org-with-point-at pom
16806 (let ((org-fast-tag-selection-single-key
16807 (if (eq org-fast-tag-selection-single-key 'expert)
16808 t org-fast-tag-selection-single-key)))
16809 (call-interactively 'org-set-tags)))))
16810 ((equal key "DEADLINE")
16811 (setq eval '(org-with-point-at pom
16812 (call-interactively 'org-deadline))))
16813 ((equal key "SCHEDULED")
16814 (setq eval '(org-with-point-at pom
16815 (call-interactively 'org-schedule))))
16817 (setq allowed (org-property-get-allowed-values pom key 'table))
16818 (if allowed
16819 (setq nval (completing-read "Value: " allowed nil t))
16820 (setq nval (read-string "Edit: " value)))
16821 (setq nval (org-trim nval))
16822 (when (not (equal nval value))
16823 (setq eval '(org-entry-put pom key nval)))))
16824 (when eval
16825 (let ((inhibit-read-only t))
16826 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16827 (unwind-protect
16828 (progn
16829 (setq org-columns-overlays
16830 (org-delete-all line-overlays org-columns-overlays))
16831 (mapc 'org-delete-overlay line-overlays)
16832 (org-columns-eval eval))
16833 (org-columns-display-here))))
16834 (move-to-column col)
16835 (if (and (org-mode-p)
16836 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16837 (org-columns-update key))))
16839 (defun org-edit-headline () ; FIXME: this is not columns specific
16840 "Edit the current headline, the part without TODO keyword, TAGS."
16841 (org-back-to-heading)
16842 (when (looking-at org-todo-line-regexp)
16843 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16844 (txt (match-string 3))
16845 (post "")
16846 txt2)
16847 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16848 (setq post (match-string 0 txt)
16849 txt (substring txt 0 (match-beginning 0))))
16850 (setq txt2 (read-string "Edit: " txt))
16851 (when (not (equal txt txt2))
16852 (beginning-of-line 1)
16853 (insert pre txt2 post)
16854 (delete-region (point) (point-at-eol))
16855 (org-set-tags nil t)))))
16857 (defun org-columns-edit-allowed ()
16858 "Edit the list of allowed values for the current property."
16859 (interactive)
16860 (let* ((key (get-char-property (point) 'org-columns-key))
16861 (key1 (concat key "_ALL"))
16862 (allowed (org-entry-get (point) key1 t))
16863 nval)
16864 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16865 (setq nval (read-string "Allowed: " allowed))
16866 (org-entry-put
16867 (cond ((marker-position org-entry-property-inherited-from)
16868 org-entry-property-inherited-from)
16869 ((marker-position org-columns-top-level-marker)
16870 org-columns-top-level-marker))
16871 key1 nval)))
16873 (defmacro org-no-warnings (&rest body)
16874 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16876 (defun org-columns-eval (form)
16877 (let (hidep)
16878 (save-excursion
16879 (beginning-of-line 1)
16880 ;; `next-line' is needed here, because it skips invisible line.
16881 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16882 (setq hidep (org-on-heading-p 1)))
16883 (eval form)
16884 (and hidep (hide-entry))))
16886 (defun org-columns-previous-allowed-value ()
16887 "Switch to the previous allowed value for this column."
16888 (interactive)
16889 (org-columns-next-allowed-value t))
16891 (defun org-columns-next-allowed-value (&optional previous)
16892 "Switch to the next allowed value for this column."
16893 (interactive)
16894 (org-columns-check-computed)
16895 (let* ((col (current-column))
16896 (key (get-char-property (point) 'org-columns-key))
16897 (value (get-char-property (point) 'org-columns-value))
16898 (bol (point-at-bol)) (eol (point-at-eol))
16899 (pom (or (get-text-property bol 'org-hd-marker)
16900 (point))) ; keep despite of compiler waring
16901 (line-overlays
16902 (delq nil (mapcar (lambda (x)
16903 (and (eq (overlay-buffer x) (current-buffer))
16904 (>= (overlay-start x) bol)
16905 (<= (overlay-start x) eol)
16907 org-columns-overlays)))
16908 (allowed (or (org-property-get-allowed-values pom key)
16909 (and (memq
16910 (nth 4 (assoc key org-columns-current-fmt-compiled))
16911 '(checkbox checkbox-n-of-m checkbox-percent))
16912 '("[ ]" "[X]"))))
16913 nval)
16914 (when (equal key "ITEM")
16915 (error "Cannot edit item headline from here"))
16916 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16917 (error "Allowed values for this property have not been defined"))
16918 (if (member key '("SCHEDULED" "DEADLINE"))
16919 (setq nval (if previous 'earlier 'later))
16920 (if previous (setq allowed (reverse allowed)))
16921 (if (member value allowed)
16922 (setq nval (car (cdr (member value allowed)))))
16923 (setq nval (or nval (car allowed)))
16924 (if (equal nval value)
16925 (error "Only one allowed value for this property")))
16926 (let ((inhibit-read-only t))
16927 (remove-text-properties (1- bol) eol '(read-only t))
16928 (unwind-protect
16929 (progn
16930 (setq org-columns-overlays
16931 (org-delete-all line-overlays org-columns-overlays))
16932 (mapc 'org-delete-overlay line-overlays)
16933 (org-columns-eval '(org-entry-put pom key nval)))
16934 (org-columns-display-here)))
16935 (move-to-column col)
16936 (if (and (org-mode-p)
16937 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16938 (org-columns-update key))))
16940 (defun org-verify-version (task)
16941 (cond
16942 ((eq task 'columns)
16943 (if (or (featurep 'xemacs)
16944 (< emacs-major-version 22))
16945 (error "Emacs 22 is required for the columns feature")))))
16947 (defun org-columns-open-link (&optional arg)
16948 (interactive "P")
16949 (let ((value (get-char-property (point) 'org-columns-value)))
16950 (org-open-link-from-string value arg)))
16952 (defun org-open-link-from-string (s &optional arg)
16953 "Open a link in the string S, as if it was in Org-mode."
16954 (interactive)
16955 (with-temp-buffer
16956 (let ((org-inhibit-startup t))
16957 (org-mode)
16958 (insert s)
16959 (goto-char (point-min))
16960 (org-open-at-point arg))))
16962 (defun org-columns-get-format-and-top-level ()
16963 (let (fmt)
16964 (when (condition-case nil (org-back-to-heading) (error nil))
16965 (move-marker org-entry-property-inherited-from nil)
16966 (setq fmt (org-entry-get nil "COLUMNS" t)))
16967 (setq fmt (or fmt org-columns-default-format))
16968 (org-set-local 'org-columns-current-fmt fmt)
16969 (org-columns-compile-format fmt)
16970 (if (marker-position org-entry-property-inherited-from)
16971 (move-marker org-columns-top-level-marker
16972 org-entry-property-inherited-from)
16973 (move-marker org-columns-top-level-marker (point)))
16974 fmt))
16976 (defun org-columns ()
16977 "Turn on column view on an org-mode file."
16978 (interactive)
16979 (org-verify-version 'columns)
16980 (org-columns-remove-overlays)
16981 (move-marker org-columns-begin-marker (point))
16982 (let (beg end fmt cache maxwidths)
16983 (setq fmt (org-columns-get-format-and-top-level))
16984 (save-excursion
16985 (goto-char org-columns-top-level-marker)
16986 (setq beg (point))
16987 (unless org-columns-inhibit-recalculation
16988 (org-columns-compute-all))
16989 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16990 (point-max)))
16991 ;; Get and cache the properties
16992 (goto-char beg)
16993 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16994 (save-excursion
16995 (save-restriction
16996 (narrow-to-region beg end)
16997 (org-clock-sum))))
16998 (while (re-search-forward (concat "^" outline-regexp) end t)
16999 (push (cons (org-current-line) (org-entry-properties)) cache))
17000 (when cache
17001 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17002 (org-set-local 'org-columns-current-maxwidths maxwidths)
17003 (org-columns-display-here-title)
17004 (mapc (lambda (x)
17005 (goto-line (car x))
17006 (org-columns-display-here (cdr x)))
17007 cache)))))
17009 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17010 "Insert a new column, to the leeft o the current column."
17011 (interactive)
17012 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17013 cell)
17014 (setq prop (completing-read
17015 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17016 nil nil prop))
17017 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17018 (setq width (read-string "Column width: " (if width (number-to-string width))))
17019 (if (string-match "\\S-" width)
17020 (setq width (string-to-number width))
17021 (setq width nil))
17022 (setq fmt (completing-read "Summary [none]: "
17023 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17024 nil t))
17025 (if (string-match "\\S-" fmt)
17026 (setq fmt (intern fmt))
17027 (setq fmt nil))
17028 (if (eq fmt 'none) (setq fmt nil))
17029 (if editp
17030 (progn
17031 (setcar editp prop)
17032 (setcdr editp (list title width nil fmt)))
17033 (setq cell (nthcdr (1- (current-column))
17034 org-columns-current-fmt-compiled))
17035 (setcdr cell (cons (list prop title width nil fmt)
17036 (cdr cell))))
17037 (org-columns-store-format)
17038 (org-columns-redo)))
17040 (defun org-columns-delete ()
17041 "Delete the column at point from columns view."
17042 (interactive)
17043 (let* ((n (current-column))
17044 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17045 (when (y-or-n-p
17046 (format "Are you sure you want to remove column \"%s\"? " title))
17047 (setq org-columns-current-fmt-compiled
17048 (delq (nth n org-columns-current-fmt-compiled)
17049 org-columns-current-fmt-compiled))
17050 (org-columns-store-format)
17051 (org-columns-redo)
17052 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17053 (backward-char 1)))))
17055 (defun org-columns-edit-attributes ()
17056 "Edit the attributes of the current column."
17057 (interactive)
17058 (let* ((n (current-column))
17059 (info (nth n org-columns-current-fmt-compiled)))
17060 (apply 'org-columns-new info)))
17062 (defun org-columns-widen (arg)
17063 "Make the column wider by ARG characters."
17064 (interactive "p")
17065 (let* ((n (current-column))
17066 (entry (nth n org-columns-current-fmt-compiled))
17067 (width (or (nth 2 entry)
17068 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17069 (setq width (max 1 (+ width arg)))
17070 (setcar (nthcdr 2 entry) width)
17071 (org-columns-store-format)
17072 (org-columns-redo)))
17074 (defun org-columns-narrow (arg)
17075 "Make the column nrrower by ARG characters."
17076 (interactive "p")
17077 (org-columns-widen (- arg)))
17079 (defun org-columns-move-right ()
17080 "Swap this column with the one to the right."
17081 (interactive)
17082 (let* ((n (current-column))
17083 (cell (nthcdr n org-columns-current-fmt-compiled))
17085 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17086 (error "Cannot shift this column further to the right"))
17087 (setq e (car cell))
17088 (setcar cell (car (cdr cell)))
17089 (setcdr cell (cons e (cdr (cdr cell))))
17090 (org-columns-store-format)
17091 (org-columns-redo)
17092 (forward-char 1)))
17094 (defun org-columns-move-left ()
17095 "Swap this column with the one to the left."
17096 (interactive)
17097 (let* ((n (current-column)))
17098 (when (= n 0)
17099 (error "Cannot shift this column further to the left"))
17100 (backward-char 1)
17101 (org-columns-move-right)
17102 (backward-char 1)))
17104 (defun org-columns-store-format ()
17105 "Store the text version of the current columns format in appropriate place.
17106 This is either in the COLUMNS property of the node starting the current column
17107 display, or in the #+COLUMNS line of the current buffer."
17108 (let (fmt (cnt 0))
17109 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17110 (org-set-local 'org-columns-current-fmt fmt)
17111 (if (marker-position org-columns-top-level-marker)
17112 (save-excursion
17113 (goto-char org-columns-top-level-marker)
17114 (if (and (org-at-heading-p)
17115 (org-entry-get nil "COLUMNS"))
17116 (org-entry-put nil "COLUMNS" fmt)
17117 (goto-char (point-min))
17118 ;; Overwrite all #+COLUMNS lines....
17119 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17120 (setq cnt (1+ cnt))
17121 (replace-match (concat "#+COLUMNS: " fmt) t t))
17122 (unless (> cnt 0)
17123 (goto-char (point-min))
17124 (or (org-on-heading-p t) (outline-next-heading))
17125 (let ((inhibit-read-only t))
17126 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17127 (org-set-local 'org-columns-default-format fmt))))))
17129 (defvar org-overriding-columns-format nil
17130 "When set, overrides any other definition.")
17131 (defvar org-agenda-view-columns-initially nil
17132 "When set, switch to columns view immediately after creating the agenda.")
17134 (defun org-agenda-columns ()
17135 "Turn on column view in the agenda."
17136 (interactive)
17137 (org-verify-version 'columns)
17138 (org-columns-remove-overlays)
17139 (move-marker org-columns-begin-marker (point))
17140 (let (fmt cache maxwidths m)
17141 (cond
17142 ((and (local-variable-p 'org-overriding-columns-format)
17143 org-overriding-columns-format)
17144 (setq fmt org-overriding-columns-format))
17145 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17146 (setq fmt (org-entry-get m "COLUMNS" t)))
17147 ((and (boundp 'org-columns-current-fmt)
17148 (local-variable-p 'org-columns-current-fmt)
17149 org-columns-current-fmt)
17150 (setq fmt org-columns-current-fmt))
17151 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17152 (setq m (get-text-property m 'org-hd-marker))
17153 (setq fmt (org-entry-get m "COLUMNS" t))))
17154 (setq fmt (or fmt org-columns-default-format))
17155 (org-set-local 'org-columns-current-fmt fmt)
17156 (org-columns-compile-format fmt)
17157 (save-excursion
17158 ;; Get and cache the properties
17159 (goto-char (point-min))
17160 (while (not (eobp))
17161 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17162 (get-text-property (point) 'org-marker)))
17163 (push (cons (org-current-line) (org-entry-properties m)) cache))
17164 (beginning-of-line 2))
17165 (when cache
17166 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17167 (org-set-local 'org-columns-current-maxwidths maxwidths)
17168 (org-columns-display-here-title)
17169 (mapc (lambda (x)
17170 (goto-line (car x))
17171 (org-columns-display-here (cdr x)))
17172 cache)))))
17174 (defun org-columns-get-autowidth-alist (s cache)
17175 "Derive the maximum column widths from the format and the cache."
17176 (let ((start 0) rtn)
17177 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17178 (push (cons (match-string 1 s) 1) rtn)
17179 (setq start (match-end 0)))
17180 (mapc (lambda (x)
17181 (setcdr x (apply 'max
17182 (mapcar
17183 (lambda (y)
17184 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17185 cache))))
17186 rtn)
17187 rtn))
17189 (defun org-columns-compute-all ()
17190 "Compute all columns that have operators defined."
17191 (org-unmodified
17192 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17193 (let ((columns org-columns-current-fmt-compiled) col)
17194 (while (setq col (pop columns))
17195 (when (nth 3 col)
17196 (save-excursion
17197 (org-columns-compute (car col)))))))
17199 (defun org-columns-update (property)
17200 "Recompute PROPERTY, and update the columns display for it."
17201 (org-columns-compute property)
17202 (let (fmt val pos)
17203 (save-excursion
17204 (mapc (lambda (ov)
17205 (when (equal (org-overlay-get ov 'org-columns-key) property)
17206 (setq pos (org-overlay-start ov))
17207 (goto-char pos)
17208 (when (setq val (cdr (assoc property
17209 (get-text-property
17210 (point-at-bol) 'org-summaries))))
17211 (setq fmt (org-overlay-get ov 'org-columns-format))
17212 (org-overlay-put ov 'org-columns-value val)
17213 (org-overlay-put ov 'display (format fmt val)))))
17214 org-columns-overlays))))
17216 (defun org-columns-compute (property)
17217 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17218 (interactive)
17219 (let* ((re (concat "^" outline-regexp))
17220 (lmax 30) ; Does anyone use deeper levels???
17221 (lsum (make-vector lmax 0))
17222 (lflag (make-vector lmax nil))
17223 (level 0)
17224 (ass (assoc property org-columns-current-fmt-compiled))
17225 (format (nth 4 ass))
17226 (printf (nth 5 ass))
17227 (beg org-columns-top-level-marker)
17228 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17229 (save-excursion
17230 ;; Find the region to compute
17231 (goto-char beg)
17232 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17233 (goto-char end)
17234 ;; Walk the tree from the back and do the computations
17235 (while (re-search-backward re beg t)
17236 (setq sumpos (match-beginning 0)
17237 last-level level
17238 level (org-outline-level)
17239 val (org-entry-get nil property)
17240 valflag (and val (string-match "\\S-" val)))
17241 (cond
17242 ((< level last-level)
17243 ;; put the sum of lower levels here as a property
17244 (setq sum (aref lsum last-level) ; current sum
17245 flag (aref lflag last-level) ; any valid entries from children?
17246 str (org-column-number-to-string sum format printf)
17247 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17248 useval (if flag str1 (if valflag val ""))
17249 sum-alist (get-text-property sumpos 'org-summaries))
17250 (if (assoc property sum-alist)
17251 (setcdr (assoc property sum-alist) useval)
17252 (push (cons property useval) sum-alist)
17253 (org-unmodified
17254 (add-text-properties sumpos (1+ sumpos)
17255 (list 'org-summaries sum-alist))))
17256 (when val
17257 (org-entry-put nil property (if flag str val)))
17258 ;; add current to current level accumulator
17259 (when (or flag valflag)
17260 (aset lsum level (+ (aref lsum level)
17261 (if flag sum (org-column-string-to-number
17262 (if flag str val) format))))
17263 (aset lflag level t))
17264 ;; clear accumulators for deeper levels
17265 (loop for l from (1+ level) to (1- lmax) do
17266 (aset lsum l 0)
17267 (aset lflag l nil)))
17268 ((>= level last-level)
17269 ;; add what we have here to the accumulator for this level
17270 (aset lsum level (+ (aref lsum level)
17271 (org-column-string-to-number (or val "0") format)))
17272 (and valflag (aset lflag level t)))
17273 (t (error "This should not happen")))))))
17275 (defun org-columns-redo ()
17276 "Construct the column display again."
17277 (interactive)
17278 (message "Recomputing columns...")
17279 (save-excursion
17280 (if (marker-position org-columns-begin-marker)
17281 (goto-char org-columns-begin-marker))
17282 (org-columns-remove-overlays)
17283 (if (org-mode-p)
17284 (call-interactively 'org-columns)
17285 (call-interactively 'org-agenda-columns)))
17286 (message "Recomputing columns...done"))
17288 (defun org-columns-not-in-agenda ()
17289 (if (eq major-mode 'org-agenda-mode)
17290 (error "This command is only allowed in Org-mode buffers")))
17293 (defun org-string-to-number (s)
17294 "Convert string to number, and interpret hh:mm:ss."
17295 (if (not (string-match ":" s))
17296 (string-to-number s)
17297 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17298 (while l
17299 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17300 sum)))
17302 (defun org-column-number-to-string (n fmt &optional printf)
17303 "Convert a computed column number to a string value, according to FMT."
17304 (cond
17305 ((eq fmt 'add_times)
17306 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17307 (format "%d:%02d" h m)))
17308 ((eq fmt 'checkbox)
17309 (cond ((= n (floor n)) "[X]")
17310 ((> n 1.) "[-]")
17311 (t "[ ]")))
17312 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17313 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17314 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17315 (printf (format printf n))
17316 ((eq fmt 'currency)
17317 (format "%.2f" n))
17318 (t (number-to-string n))))
17320 (defun org-nofm-to-completion (n m &optional percent)
17321 (if (not percent)
17322 (format "[%d/%d]" n m)
17323 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17325 (defun org-column-string-to-number (s fmt)
17326 "Convert a column value to a number that can be used for column computing."
17327 (cond
17328 ((string-match ":" s)
17329 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17330 (while l
17331 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17332 sum))
17333 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17334 (if (equal s "[X]") 1. 0.000001))
17335 (t (string-to-number s))))
17337 (defun org-columns-uncompile-format (cfmt)
17338 "Turn the compiled columns format back into a string representation."
17339 (let ((rtn "") e s prop title op width fmt printf)
17340 (while (setq e (pop cfmt))
17341 (setq prop (car e)
17342 title (nth 1 e)
17343 width (nth 2 e)
17344 op (nth 3 e)
17345 fmt (nth 4 e)
17346 printf (nth 5 e))
17347 (cond
17348 ((eq fmt 'add_times) (setq op ":"))
17349 ((eq fmt 'checkbox) (setq op "X"))
17350 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17351 ((eq fmt 'checkbox-percent) (setq op "X%"))
17352 ((eq fmt 'add_numbers) (setq op "+"))
17353 ((eq fmt 'currency) (setq op "$")))
17354 (if (and op printf) (setq op (concat op ";" printf)))
17355 (if (equal title prop) (setq title nil))
17356 (setq s (concat "%" (if width (number-to-string width))
17357 prop
17358 (if title (concat "(" title ")"))
17359 (if op (concat "{" op "}"))))
17360 (setq rtn (concat rtn " " s)))
17361 (org-trim rtn)))
17363 (defun org-columns-compile-format (fmt)
17364 "Turn a column format string into an alist of specifications.
17365 The alist has one entry for each column in the format. The elements of
17366 that list are:
17367 property the property
17368 title the title field for the columns
17369 width the column width in characters, can be nil for automatic
17370 operator the operator if any
17371 format the output format for computed results, derived from operator
17372 printf a printf format for computed values"
17373 (let ((start 0) width prop title op f printf)
17374 (setq org-columns-current-fmt-compiled nil)
17375 (while (string-match
17376 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17377 fmt start)
17378 (setq start (match-end 0)
17379 width (match-string 1 fmt)
17380 prop (match-string 2 fmt)
17381 title (or (match-string 3 fmt) prop)
17382 op (match-string 4 fmt)
17383 f nil
17384 printf nil)
17385 (if width (setq width (string-to-number width)))
17386 (when (and op (string-match ";" op))
17387 (setq printf (substring op (match-end 0))
17388 op (substring op 0 (match-beginning 0))))
17389 (cond
17390 ((equal op "+") (setq f 'add_numbers))
17391 ((equal op "$") (setq f 'currency))
17392 ((equal op ":") (setq f 'add_times))
17393 ((equal op "X") (setq f 'checkbox))
17394 ((equal op "X/") (setq f 'checkbox-n-of-m))
17395 ((equal op "X%") (setq f 'checkbox-percent))
17397 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17398 (setq org-columns-current-fmt-compiled
17399 (nreverse org-columns-current-fmt-compiled))))
17402 ;;; Dynamic block for Column view
17404 (defun org-columns-capture-view ()
17405 "Get the column view of the current buffer and return it as a list.
17406 The list will contains the title row and all other rows. Each row is
17407 a list of fields."
17408 (save-excursion
17409 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17410 (n (length title)) row tbl)
17411 (goto-char (point-min))
17412 (while (re-search-forward "^\\*+ " nil t)
17413 (when (get-char-property (match-beginning 0) 'org-columns-key)
17414 (setq row nil)
17415 (loop for i from 0 to (1- n) do
17416 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17417 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17419 row))
17420 (setq row (nreverse row))
17421 (push row tbl)))
17422 (append (list title 'hline) (nreverse tbl)))))
17424 (defun org-dblock-write:columnview (params)
17425 "Write the column view table.
17426 PARAMS is a property list of parameters:
17428 :width enforce same column widths with <N> specifiers.
17429 :id the :ID: property of the entry where the columns view
17430 should be built, as a string. When `local', call locally.
17431 When `global' call column view with the cursor at the beginning
17432 of the buffer (usually this means that the whole buffer switches
17433 to column view).
17434 :hlines When t, insert a hline before each item. When a number, insert
17435 a hline before each level <= that number.
17436 :vlines When t, make each column a colgroup to enforce vertical lines."
17437 (let ((pos (move-marker (make-marker) (point)))
17438 (hlines (plist-get params :hlines))
17439 (vlines (plist-get params :vlines))
17440 tbl id idpos nfields tmp)
17441 (save-excursion
17442 (save-restriction
17443 (when (setq id (plist-get params :id))
17444 (cond ((not id) nil)
17445 ((eq id 'global) (goto-char (point-min)))
17446 ((eq id 'local) nil)
17447 ((setq idpos (org-find-entry-with-id id))
17448 (goto-char idpos))
17449 (t (error "Cannot find entry with :ID: %s" id))))
17450 (org-columns)
17451 (setq tbl (org-columns-capture-view))
17452 (setq nfields (length (car tbl)))
17453 (org-columns-quit)))
17454 (goto-char pos)
17455 (move-marker pos nil)
17456 (when tbl
17457 (when (plist-get params :hlines)
17458 (setq tmp nil)
17459 (while tbl
17460 (if (eq (car tbl) 'hline)
17461 (push (pop tbl) tmp)
17462 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17463 (if (and (not (eq (car tmp) 'hline))
17464 (or (eq hlines t)
17465 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17466 (push 'hline tmp)))
17467 (push (pop tbl) tmp)))
17468 (setq tbl (nreverse tmp)))
17469 (when vlines
17470 (setq tbl (mapcar (lambda (x)
17471 (if (eq 'hline x) x (cons "" x)))
17472 tbl))
17473 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17474 (setq pos (point))
17475 (insert (org-listtable-to-string tbl))
17476 (when (plist-get params :width)
17477 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17478 org-columns-current-widths "|")))
17479 (goto-char pos)
17480 (org-table-align))))
17482 (defun org-listtable-to-string (tbl)
17483 "Convert a listtable TBL to a string that contains the Org-mode table.
17484 The table still need to be alligned. The resulting string has no leading
17485 and tailing newline characters."
17486 (mapconcat
17487 (lambda (x)
17488 (cond
17489 ((listp x)
17490 (concat "|" (mapconcat 'identity x "|") "|"))
17491 ((eq x 'hline) "|-|")
17492 (t (error "Garbage in listtable: %s" x))))
17493 tbl "\n"))
17495 (defun org-insert-columns-dblock ()
17496 "Create a dynamic block capturing a column view table."
17497 (interactive)
17498 (let ((defaults '(:name "columnview" :hlines 1))
17499 (id (completing-read
17500 "Capture columns (local, global, entry with :ID: property) [local]: "
17501 (append '(("global") ("local"))
17502 (mapcar 'list (org-property-values "ID"))))))
17503 (if (equal id "") (setq id 'local))
17504 (if (equal id "global") (setq id 'global))
17505 (setq defaults (append defaults (list :id id)))
17506 (org-create-dblock defaults)
17507 (org-update-dblock)))
17509 ;;;; Timestamps
17511 (defvar org-last-changed-timestamp nil)
17512 (defvar org-time-was-given) ; dynamically scoped parameter
17513 (defvar org-end-time-was-given) ; dynamically scoped parameter
17514 (defvar org-ts-what) ; dynamically scoped parameter
17516 (defun org-time-stamp (arg)
17517 "Prompt for a date/time and insert a time stamp.
17518 If the user specifies a time like HH:MM, or if this command is called
17519 with a prefix argument, the time stamp will contain date and time.
17520 Otherwise, only the date will be included. All parts of a date not
17521 specified by the user will be filled in from the current date/time.
17522 So if you press just return without typing anything, the time stamp
17523 will represent the current date/time. If there is already a timestamp
17524 at the cursor, it will be modified."
17525 (interactive "P")
17526 (let* ((ts nil)
17527 (default-time
17528 ;; Default time is either today, or, when entering a range,
17529 ;; the range start.
17530 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17531 (save-excursion
17532 (re-search-backward
17533 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17534 (- (point) 20) t)))
17535 (apply 'encode-time (org-parse-time-string (match-string 1)))
17536 (current-time)))
17537 (default-input (and ts (org-get-compact-tod ts)))
17538 org-time-was-given org-end-time-was-given time)
17539 (cond
17540 ((and (org-at-timestamp-p)
17541 (eq last-command 'org-time-stamp)
17542 (eq this-command 'org-time-stamp))
17543 (insert "--")
17544 (setq time (let ((this-command this-command))
17545 (org-read-date arg 'totime nil nil default-time default-input)))
17546 (org-insert-time-stamp time (or org-time-was-given arg)))
17547 ((org-at-timestamp-p)
17548 (setq time (let ((this-command this-command))
17549 (org-read-date arg 'totime nil nil default-time default-input)))
17550 (when (org-at-timestamp-p) ; just to get the match data
17551 (replace-match "")
17552 (setq org-last-changed-timestamp
17553 (org-insert-time-stamp
17554 time (or org-time-was-given arg)
17555 nil nil nil (list org-end-time-was-given))))
17556 (message "Timestamp updated"))
17558 (setq time (let ((this-command this-command))
17559 (org-read-date arg 'totime nil nil default-time default-input)))
17560 (org-insert-time-stamp time (or org-time-was-given arg)
17561 nil nil nil (list org-end-time-was-given))))))
17563 ;; FIXME: can we use this for something else????
17564 ;; like computing time differences?????
17565 (defun org-get-compact-tod (s)
17566 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17567 (let* ((t1 (match-string 1 s))
17568 (h1 (string-to-number (match-string 2 s)))
17569 (m1 (string-to-number (match-string 3 s)))
17570 (t2 (and (match-end 4) (match-string 5 s)))
17571 (h2 (and t2 (string-to-number (match-string 6 s))))
17572 (m2 (and t2 (string-to-number (match-string 7 s))))
17573 dh dm)
17574 (if (not t2)
17576 (setq dh (- h2 h1) dm (- m2 m1))
17577 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17578 (concat t1 "+" (number-to-string dh)
17579 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17581 (defun org-time-stamp-inactive (&optional arg)
17582 "Insert an inactive time stamp.
17583 An inactive time stamp is enclosed in square brackets instead of angle
17584 brackets. It is inactive in the sense that it does not trigger agenda entries,
17585 does not link to the calendar and cannot be changed with the S-cursor keys.
17586 So these are more for recording a certain time/date."
17587 (interactive "P")
17588 (let (org-time-was-given org-end-time-was-given time)
17589 (setq time (org-read-date arg 'totime))
17590 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17591 nil nil (list org-end-time-was-given))))
17593 (defvar org-date-ovl (org-make-overlay 1 1))
17594 (org-overlay-put org-date-ovl 'face 'org-warning)
17595 (org-detach-overlay org-date-ovl)
17597 (defvar org-ans1) ; dynamically scoped parameter
17598 (defvar org-ans2) ; dynamically scoped parameter
17600 (defvar org-plain-time-of-day-regexp) ; defined below
17602 (defvar org-read-date-overlay nil)
17603 (defvar org-dcst nil) ; dynamically scoped
17605 (defun org-read-date (&optional with-time to-time from-string prompt
17606 default-time default-input)
17607 "Read a date, possibly a time, and make things smooth for the user.
17608 The prompt will suggest to enter an ISO date, but you can also enter anything
17609 which will at least partially be understood by `parse-time-string'.
17610 Unrecognized parts of the date will default to the current day, month, year,
17611 hour and minute. If this command is called to replace a timestamp at point,
17612 of to enter the second timestamp of a range, the default time is taken from the
17613 existing stamp. For example,
17614 3-2-5 --> 2003-02-05
17615 feb 15 --> currentyear-02-15
17616 sep 12 9 --> 2009-09-12
17617 12:45 --> today 12:45
17618 22 sept 0:34 --> currentyear-09-22 0:34
17619 12 --> currentyear-currentmonth-12
17620 Fri --> nearest Friday (today or later)
17621 etc.
17623 Furthermore you can specify a relative date by giving, as the *first* thing
17624 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17625 change in days weeks, months, years.
17626 With a single plus or minus, the date is relative to today. With a double
17627 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17628 +4d --> four days from today
17629 +4 --> same as above
17630 +2w --> two weeks from today
17631 ++5 --> five days from default date
17633 The function understands only English month and weekday abbreviations,
17634 but this can be configured with the variables `parse-time-months' and
17635 `parse-time-weekdays'.
17637 While prompting, a calendar is popped up - you can also select the
17638 date with the mouse (button 1). The calendar shows a period of three
17639 months. To scroll it to other months, use the keys `>' and `<'.
17640 If you don't like the calendar, turn it off with
17641 \(setq org-read-date-popup-calendar nil)
17643 With optional argument TO-TIME, the date will immediately be converted
17644 to an internal time.
17645 With an optional argument WITH-TIME, the prompt will suggest to also
17646 insert a time. Note that when WITH-TIME is not set, you can still
17647 enter a time, and this function will inform the calling routine about
17648 this change. The calling routine may then choose to change the format
17649 used to insert the time stamp into the buffer to include the time.
17650 With optional argument FROM-STRING, read from this string instead from
17651 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17652 the time/date that is used for everything that is not specified by the
17653 user."
17654 (require 'parse-time)
17655 (let* ((org-time-stamp-rounding-minutes
17656 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17657 (org-dcst org-display-custom-times)
17658 (ct (org-current-time))
17659 (def (or default-time ct))
17660 (defdecode (decode-time def))
17661 (dummy (progn
17662 (when (< (nth 2 defdecode) org-extend-today-until)
17663 (setcar (nthcdr 2 defdecode) -1)
17664 (setcar (nthcdr 1 defdecode) 59)
17665 (setq def (apply 'encode-time defdecode)
17666 defdecode (decode-time def)))))
17667 (calendar-move-hook nil)
17668 (view-diary-entries-initially nil)
17669 (view-calendar-holidays-initially nil)
17670 (timestr (format-time-string
17671 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17672 (prompt (concat (if prompt (concat prompt " ") "")
17673 (format "Date+time [%s]: " timestr)))
17674 ans (org-ans0 "") org-ans1 org-ans2 final)
17676 (cond
17677 (from-string (setq ans from-string))
17678 (org-read-date-popup-calendar
17679 (save-excursion
17680 (save-window-excursion
17681 (calendar)
17682 (calendar-forward-day (- (time-to-days def)
17683 (calendar-absolute-from-gregorian
17684 (calendar-current-date))))
17685 (org-eval-in-calendar nil t)
17686 (let* ((old-map (current-local-map))
17687 (map (copy-keymap calendar-mode-map))
17688 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17689 (org-defkey map (kbd "RET") 'org-calendar-select)
17690 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17691 'org-calendar-select-mouse)
17692 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17693 'org-calendar-select-mouse)
17694 (org-defkey minibuffer-local-map [(meta shift left)]
17695 (lambda () (interactive)
17696 (org-eval-in-calendar '(calendar-backward-month 1))))
17697 (org-defkey minibuffer-local-map [(meta shift right)]
17698 (lambda () (interactive)
17699 (org-eval-in-calendar '(calendar-forward-month 1))))
17700 (org-defkey minibuffer-local-map [(meta shift up)]
17701 (lambda () (interactive)
17702 (org-eval-in-calendar '(calendar-backward-year 1))))
17703 (org-defkey minibuffer-local-map [(meta shift down)]
17704 (lambda () (interactive)
17705 (org-eval-in-calendar '(calendar-forward-year 1))))
17706 (org-defkey minibuffer-local-map [(shift up)]
17707 (lambda () (interactive)
17708 (org-eval-in-calendar '(calendar-backward-week 1))))
17709 (org-defkey minibuffer-local-map [(shift down)]
17710 (lambda () (interactive)
17711 (org-eval-in-calendar '(calendar-forward-week 1))))
17712 (org-defkey minibuffer-local-map [(shift left)]
17713 (lambda () (interactive)
17714 (org-eval-in-calendar '(calendar-backward-day 1))))
17715 (org-defkey minibuffer-local-map [(shift right)]
17716 (lambda () (interactive)
17717 (org-eval-in-calendar '(calendar-forward-day 1))))
17718 (org-defkey minibuffer-local-map ">"
17719 (lambda () (interactive)
17720 (org-eval-in-calendar '(scroll-calendar-left 1))))
17721 (org-defkey minibuffer-local-map "<"
17722 (lambda () (interactive)
17723 (org-eval-in-calendar '(scroll-calendar-right 1))))
17724 (unwind-protect
17725 (progn
17726 (use-local-map map)
17727 (add-hook 'post-command-hook 'org-read-date-display)
17728 (setq org-ans0 (read-string prompt default-input nil nil))
17729 ;; org-ans0: from prompt
17730 ;; org-ans1: from mouse click
17731 ;; org-ans2: from calendar motion
17732 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17733 (remove-hook 'post-command-hook 'org-read-date-display)
17734 (use-local-map old-map)
17735 (when org-read-date-overlay
17736 (org-delete-overlay org-read-date-overlay)
17737 (setq org-read-date-overlay nil)))))))
17739 (t ; Naked prompt only
17740 (unwind-protect
17741 (setq ans (read-string prompt default-input nil timestr))
17742 (when org-read-date-overlay
17743 (org-delete-overlay org-read-date-overlay)
17744 (setq org-read-date-overlay nil)))))
17746 (setq final (org-read-date-analyze ans def defdecode))
17748 (if to-time
17749 (apply 'encode-time final)
17750 (if (and (boundp 'org-time-was-given) org-time-was-given)
17751 (format "%04d-%02d-%02d %02d:%02d"
17752 (nth 5 final) (nth 4 final) (nth 3 final)
17753 (nth 2 final) (nth 1 final))
17754 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17755 (defvar def)
17756 (defvar defdecode)
17757 (defvar with-time)
17758 (defun org-read-date-display ()
17759 "Display the currrent date prompt interpretation in the minibuffer."
17760 (when org-read-date-display-live
17761 (when org-read-date-overlay
17762 (org-delete-overlay org-read-date-overlay))
17763 (let ((p (point)))
17764 (end-of-line 1)
17765 (while (not (equal (buffer-substring
17766 (max (point-min) (- (point) 4)) (point))
17767 " "))
17768 (insert " "))
17769 (goto-char p))
17770 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17771 " " (or org-ans1 org-ans2)))
17772 (org-end-time-was-given nil)
17773 (f (org-read-date-analyze ans def defdecode))
17774 (fmts (if org-dcst
17775 org-time-stamp-custom-formats
17776 org-time-stamp-formats))
17777 (fmt (if (or with-time
17778 (and (boundp 'org-time-was-given) org-time-was-given))
17779 (cdr fmts)
17780 (car fmts)))
17781 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17782 (when (and org-end-time-was-given
17783 (string-match org-plain-time-of-day-regexp txt))
17784 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17785 org-end-time-was-given
17786 (substring txt (match-end 0)))))
17787 (setq org-read-date-overlay
17788 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17789 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17791 (defun org-read-date-analyze (ans def defdecode)
17792 "Analyze the combined answer of the date prompt."
17793 ;; FIXME: cleanup and comment
17794 (let (delta deltan deltaw deltadef year month day
17795 hour minute second wday pm h2 m2 tl wday1)
17797 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17798 (setq ans (replace-match "" t t ans)
17799 deltan (car delta)
17800 deltaw (nth 1 delta)
17801 deltadef (nth 2 delta)))
17803 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17804 (when (string-match
17805 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17806 (setq year (if (match-end 2)
17807 (string-to-number (match-string 2 ans))
17808 (string-to-number (format-time-string "%Y")))
17809 month (string-to-number (match-string 3 ans))
17810 day (string-to-number (match-string 4 ans)))
17811 (if (< year 100) (setq year (+ 2000 year)))
17812 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17813 t nil ans)))
17814 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17815 ;; If there is a time with am/pm, and *no* time without it, we convert
17816 ;; so that matching will be successful.
17817 (loop for i from 1 to 2 do ; twice, for end time as well
17818 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17819 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17820 (setq hour (string-to-number (match-string 1 ans))
17821 minute (if (match-end 3)
17822 (string-to-number (match-string 3 ans))
17824 pm (equal ?p
17825 (string-to-char (downcase (match-string 4 ans)))))
17826 (if (and (= hour 12) (not pm))
17827 (setq hour 0)
17828 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17829 (setq ans (replace-match (format "%02d:%02d" hour minute)
17830 t t ans))))
17832 ;; Check if a time range is given as a duration
17833 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17834 (setq hour (string-to-number (match-string 1 ans))
17835 h2 (+ hour (string-to-number (match-string 3 ans)))
17836 minute (string-to-number (match-string 2 ans))
17837 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17838 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17839 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17841 ;; Check if there is a time range
17842 (when (boundp 'org-end-time-was-given)
17843 (setq org-time-was-given nil)
17844 (when (and (string-match org-plain-time-of-day-regexp ans)
17845 (match-end 8))
17846 (setq org-end-time-was-given (match-string 8 ans))
17847 (setq ans (concat (substring ans 0 (match-beginning 7))
17848 (substring ans (match-end 7))))))
17850 (setq tl (parse-time-string ans)
17851 day (or (nth 3 tl) (nth 3 defdecode))
17852 month (or (nth 4 tl)
17853 (if (and org-read-date-prefer-future
17854 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17855 (1+ (nth 4 defdecode))
17856 (nth 4 defdecode)))
17857 year (or (nth 5 tl)
17858 (if (and org-read-date-prefer-future
17859 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17860 (1+ (nth 5 defdecode))
17861 (nth 5 defdecode)))
17862 hour (or (nth 2 tl) (nth 2 defdecode))
17863 minute (or (nth 1 tl) (nth 1 defdecode))
17864 second (or (nth 0 tl) 0)
17865 wday (nth 6 tl))
17866 (when deltan
17867 (unless deltadef
17868 (let ((now (decode-time (current-time))))
17869 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17870 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17871 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17872 ((equal deltaw "m") (setq month (+ month deltan)))
17873 ((equal deltaw "y") (setq year (+ year deltan)))))
17874 (when (and wday (not (nth 3 tl)))
17875 ;; Weekday was given, but no day, so pick that day in the week
17876 ;; on or after the derived date.
17877 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17878 (unless (equal wday wday1)
17879 (setq day (+ day (% (- wday wday1 -7) 7)))))
17880 (if (and (boundp 'org-time-was-given)
17881 (nth 2 tl))
17882 (setq org-time-was-given t))
17883 (if (< year 100) (setq year (+ 2000 year)))
17884 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17885 (list second minute hour day month year)))
17887 (defvar parse-time-weekdays)
17889 (defun org-read-date-get-relative (s today default)
17890 "Check string S for special relative date string.
17891 TODAY and DEFAULT are internal times, for today and for a default.
17892 Return shift list (N what def-flag)
17893 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17894 N is the number of WHATs to shift.
17895 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17896 the DEFAULT date rather than TODAY."
17897 (when (string-match
17898 (concat
17899 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17900 "\\([0-9]+\\)?"
17901 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17902 "\\([ \t]\\|$\\)") s)
17903 (let* ((dir (if (match-end 1)
17904 (string-to-char (substring (match-string 1 s) -1))
17905 ?+))
17906 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17907 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17908 (what (if (match-end 3) (match-string 3 s) "d"))
17909 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17910 (date (if rel default today))
17911 (wday (nth 6 (decode-time date)))
17912 delta)
17913 (if wday1
17914 (progn
17915 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17916 (if (= dir ?-) (setq delta (- delta 7)))
17917 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17918 (list delta "d" rel))
17919 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17921 (defun org-eval-in-calendar (form &optional keepdate)
17922 "Eval FORM in the calendar window and return to current window.
17923 Also, store the cursor date in variable org-ans2."
17924 (let ((sw (selected-window)))
17925 (select-window (get-buffer-window "*Calendar*"))
17926 (eval form)
17927 (when (and (not keepdate) (calendar-cursor-to-date))
17928 (let* ((date (calendar-cursor-to-date))
17929 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17930 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17931 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17932 (select-window sw)))
17934 ; ;; Update the prompt to show new default date
17935 ; (save-excursion
17936 ; (goto-char (point-min))
17937 ; (when (and org-ans2
17938 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17939 ; (get-text-property (match-end 0) 'field))
17940 ; (let ((inhibit-read-only t))
17941 ; (replace-match (concat "[" org-ans2 "]") t t)
17942 ; (add-text-properties (point-min) (1+ (match-end 0))
17943 ; (text-properties-at (1+ (point-min)))))))))
17945 (defun org-calendar-select ()
17946 "Return to `org-read-date' with the date currently selected.
17947 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17948 (interactive)
17949 (when (calendar-cursor-to-date)
17950 (let* ((date (calendar-cursor-to-date))
17951 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17952 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17953 (if (active-minibuffer-window) (exit-minibuffer))))
17955 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17956 "Insert a date stamp for the date given by the internal TIME.
17957 WITH-HM means, use the stamp format that includes the time of the day.
17958 INACTIVE means use square brackets instead of angular ones, so that the
17959 stamp will not contribute to the agenda.
17960 PRE and POST are optional strings to be inserted before and after the
17961 stamp.
17962 The command returns the inserted time stamp."
17963 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17964 stamp)
17965 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17966 (insert-before-markers (or pre ""))
17967 (insert-before-markers (setq stamp (format-time-string fmt time)))
17968 (when (listp extra)
17969 (setq extra (car extra))
17970 (if (and (stringp extra)
17971 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17972 (setq extra (format "-%02d:%02d"
17973 (string-to-number (match-string 1 extra))
17974 (string-to-number (match-string 2 extra))))
17975 (setq extra nil)))
17976 (when extra
17977 (backward-char 1)
17978 (insert-before-markers extra)
17979 (forward-char 1))
17980 (insert-before-markers (or post ""))
17981 stamp))
17983 (defun org-toggle-time-stamp-overlays ()
17984 "Toggle the use of custom time stamp formats."
17985 (interactive)
17986 (setq org-display-custom-times (not org-display-custom-times))
17987 (unless org-display-custom-times
17988 (let ((p (point-min)) (bmp (buffer-modified-p)))
17989 (while (setq p (next-single-property-change p 'display))
17990 (if (and (get-text-property p 'display)
17991 (eq (get-text-property p 'face) 'org-date))
17992 (remove-text-properties
17993 p (setq p (next-single-property-change p 'display))
17994 '(display t))))
17995 (set-buffer-modified-p bmp)))
17996 (if (featurep 'xemacs)
17997 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17998 (org-restart-font-lock)
17999 (setq org-table-may-need-update t)
18000 (if org-display-custom-times
18001 (message "Time stamps are overlayed with custom format")
18002 (message "Time stamp overlays removed")))
18004 (defun org-display-custom-time (beg end)
18005 "Overlay modified time stamp format over timestamp between BED and END."
18006 (let* ((ts (buffer-substring beg end))
18007 t1 w1 with-hm tf time str w2 (off 0))
18008 (save-match-data
18009 (setq t1 (org-parse-time-string ts t))
18010 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18011 (setq off (- (match-end 0) (match-beginning 0)))))
18012 (setq end (- end off))
18013 (setq w1 (- end beg)
18014 with-hm (and (nth 1 t1) (nth 2 t1))
18015 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18016 time (org-fix-decoded-time t1)
18017 str (org-add-props
18018 (format-time-string
18019 (substring tf 1 -1) (apply 'encode-time time))
18020 nil 'mouse-face 'highlight)
18021 w2 (length str))
18022 (if (not (= w2 w1))
18023 (add-text-properties (1+ beg) (+ 2 beg)
18024 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18025 (if (featurep 'xemacs)
18026 (progn
18027 (put-text-property beg end 'invisible t)
18028 (put-text-property beg end 'end-glyph (make-glyph str)))
18029 (put-text-property beg end 'display str))))
18031 (defun org-translate-time (string)
18032 "Translate all timestamps in STRING to custom format.
18033 But do this only if the variable `org-display-custom-times' is set."
18034 (when org-display-custom-times
18035 (save-match-data
18036 (let* ((start 0)
18037 (re org-ts-regexp-both)
18038 t1 with-hm inactive tf time str beg end)
18039 (while (setq start (string-match re string start))
18040 (setq beg (match-beginning 0)
18041 end (match-end 0)
18042 t1 (save-match-data
18043 (org-parse-time-string (substring string beg end) t))
18044 with-hm (and (nth 1 t1) (nth 2 t1))
18045 inactive (equal (substring string beg (1+ beg)) "[")
18046 tf (funcall (if with-hm 'cdr 'car)
18047 org-time-stamp-custom-formats)
18048 time (org-fix-decoded-time t1)
18049 str (format-time-string
18050 (concat
18051 (if inactive "[" "<") (substring tf 1 -1)
18052 (if inactive "]" ">"))
18053 (apply 'encode-time time))
18054 string (replace-match str t t string)
18055 start (+ start (length str)))))))
18056 string)
18058 (defun org-fix-decoded-time (time)
18059 "Set 0 instead of nil for the first 6 elements of time.
18060 Don't touch the rest."
18061 (let ((n 0))
18062 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18064 (defun org-days-to-time (timestamp-string)
18065 "Difference between TIMESTAMP-STRING and now in days."
18066 (- (time-to-days (org-time-string-to-time timestamp-string))
18067 (time-to-days (current-time))))
18069 (defun org-deadline-close (timestamp-string &optional ndays)
18070 "Is the time in TIMESTAMP-STRING close to the current date?"
18071 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18072 (and (< (org-days-to-time timestamp-string) ndays)
18073 (not (org-entry-is-done-p))))
18075 (defun org-get-wdays (ts)
18076 "Get the deadline lead time appropriate for timestring TS."
18077 (cond
18078 ((<= org-deadline-warning-days 0)
18079 ;; 0 or negative, enforce this value no matter what
18080 (- org-deadline-warning-days))
18081 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18082 ;; lead time is specified.
18083 (floor (* (string-to-number (match-string 1 ts))
18084 (cdr (assoc (match-string 2 ts)
18085 '(("d" . 1) ("w" . 7)
18086 ("m" . 30.4) ("y" . 365.25)))))))
18087 ;; go for the default.
18088 (t org-deadline-warning-days)))
18090 (defun org-calendar-select-mouse (ev)
18091 "Return to `org-read-date' with the date currently selected.
18092 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18093 (interactive "e")
18094 (mouse-set-point ev)
18095 (when (calendar-cursor-to-date)
18096 (let* ((date (calendar-cursor-to-date))
18097 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18098 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18099 (if (active-minibuffer-window) (exit-minibuffer))))
18101 (defun org-check-deadlines (ndays)
18102 "Check if there are any deadlines due or past due.
18103 A deadline is considered due if it happens within `org-deadline-warning-days'
18104 days from today's date. If the deadline appears in an entry marked DONE,
18105 it is not shown. The prefix arg NDAYS can be used to test that many
18106 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18107 (interactive "P")
18108 (let* ((org-warn-days
18109 (cond
18110 ((equal ndays '(4)) 100000)
18111 (ndays (prefix-numeric-value ndays))
18112 (t (abs org-deadline-warning-days))))
18113 (case-fold-search nil)
18114 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18115 (callback
18116 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18118 (message "%d deadlines past-due or due within %d days"
18119 (org-occur regexp nil callback)
18120 org-warn-days)))
18122 (defun org-check-before-date (date)
18123 "Check if there are deadlines or scheduled entries before DATE."
18124 (interactive (list (org-read-date)))
18125 (let ((case-fold-search nil)
18126 (regexp (concat "\\<\\(" org-deadline-string
18127 "\\|" org-scheduled-string
18128 "\\) *<\\([^>]+\\)>"))
18129 (callback
18130 (lambda () (time-less-p
18131 (org-time-string-to-time (match-string 2))
18132 (org-time-string-to-time date)))))
18133 (message "%d entries before %s"
18134 (org-occur regexp nil callback) date)))
18136 (defun org-evaluate-time-range (&optional to-buffer)
18137 "Evaluate a time range by computing the difference between start and end.
18138 Normally the result is just printed in the echo area, but with prefix arg
18139 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18140 If the time range is actually in a table, the result is inserted into the
18141 next column.
18142 For time difference computation, a year is assumed to be exactly 365
18143 days in order to avoid rounding problems."
18144 (interactive "P")
18146 (org-clock-update-time-maybe)
18147 (save-excursion
18148 (unless (org-at-date-range-p t)
18149 (goto-char (point-at-bol))
18150 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18151 (if (not (org-at-date-range-p t))
18152 (error "Not at a time-stamp range, and none found in current line")))
18153 (let* ((ts1 (match-string 1))
18154 (ts2 (match-string 2))
18155 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18156 (match-end (match-end 0))
18157 (time1 (org-time-string-to-time ts1))
18158 (time2 (org-time-string-to-time ts2))
18159 (t1 (time-to-seconds time1))
18160 (t2 (time-to-seconds time2))
18161 (diff (abs (- t2 t1)))
18162 (negative (< (- t2 t1) 0))
18163 ;; (ys (floor (* 365 24 60 60)))
18164 (ds (* 24 60 60))
18165 (hs (* 60 60))
18166 (fy "%dy %dd %02d:%02d")
18167 (fy1 "%dy %dd")
18168 (fd "%dd %02d:%02d")
18169 (fd1 "%dd")
18170 (fh "%02d:%02d")
18171 y d h m align)
18172 (if havetime
18173 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18175 d (floor (/ diff ds)) diff (mod diff ds)
18176 h (floor (/ diff hs)) diff (mod diff hs)
18177 m (floor (/ diff 60)))
18178 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18180 d (floor (+ (/ diff ds) 0.5))
18181 h 0 m 0))
18182 (if (not to-buffer)
18183 (message "%s" (org-make-tdiff-string y d h m))
18184 (if (org-at-table-p)
18185 (progn
18186 (goto-char match-end)
18187 (setq align t)
18188 (and (looking-at " *|") (goto-char (match-end 0))))
18189 (goto-char match-end))
18190 (if (looking-at
18191 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18192 (replace-match ""))
18193 (if negative (insert " -"))
18194 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18195 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18196 (insert " " (format fh h m))))
18197 (if align (org-table-align))
18198 (message "Time difference inserted")))))
18200 (defun org-make-tdiff-string (y d h m)
18201 (let ((fmt "")
18202 (l nil))
18203 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18204 l (push y l)))
18205 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18206 l (push d l)))
18207 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18208 l (push h l)))
18209 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18210 l (push m l)))
18211 (apply 'format fmt (nreverse l))))
18213 (defun org-time-string-to-time (s)
18214 (apply 'encode-time (org-parse-time-string s)))
18216 (defun org-time-string-to-absolute (s &optional daynr prefer)
18217 "Convert a time stamp to an absolute day number.
18218 If there is a specifyer for a cyclic time stamp, get the closest date to
18219 DAYNR."
18220 (cond
18221 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18222 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18223 daynr
18224 (+ daynr 1000)))
18225 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18226 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18227 (time-to-days (current-time))) (match-string 0 s)
18228 prefer))
18229 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18231 (defun org-time-from-absolute (d)
18232 "Return the time corresponding to date D.
18233 D may be an absolute day number, or a calendar-type list (month day year)."
18234 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18235 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18237 (defun org-calendar-holiday ()
18238 "List of holidays, for Diary display in Org-mode."
18239 (require 'holidays)
18240 (let ((hl (funcall
18241 (if (fboundp 'calendar-check-holidays)
18242 'calendar-check-holidays 'check-calendar-holidays) date)))
18243 (if hl (mapconcat 'identity hl "; "))))
18245 (defun org-diary-sexp-entry (sexp entry date)
18246 "Process a SEXP diary ENTRY for DATE."
18247 (require 'diary-lib)
18248 (let ((result (if calendar-debug-sexp
18249 (let ((stack-trace-on-error t))
18250 (eval (car (read-from-string sexp))))
18251 (condition-case nil
18252 (eval (car (read-from-string sexp)))
18253 (error
18254 (beep)
18255 (message "Bad sexp at line %d in %s: %s"
18256 (org-current-line)
18257 (buffer-file-name) sexp)
18258 (sleep-for 2))))))
18259 (cond ((stringp result) result)
18260 ((and (consp result)
18261 (stringp (cdr result))) (cdr result))
18262 (result entry)
18263 (t nil))))
18265 (defun org-diary-to-ical-string (frombuf)
18266 "Get iCalendar entries from diary entries in buffer FROMBUF.
18267 This uses the icalendar.el library."
18268 (let* ((tmpdir (if (featurep 'xemacs)
18269 (temp-directory)
18270 temporary-file-directory))
18271 (tmpfile (make-temp-name
18272 (expand-file-name "orgics" tmpdir)))
18273 buf rtn b e)
18274 (save-excursion
18275 (set-buffer frombuf)
18276 (icalendar-export-region (point-min) (point-max) tmpfile)
18277 (setq buf (find-buffer-visiting tmpfile))
18278 (set-buffer buf)
18279 (goto-char (point-min))
18280 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18281 (setq b (match-beginning 0)))
18282 (goto-char (point-max))
18283 (if (re-search-backward "^END:VEVENT" nil t)
18284 (setq e (match-end 0)))
18285 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18286 (kill-buffer buf)
18287 (kill-buffer frombuf)
18288 (delete-file tmpfile)
18289 rtn))
18291 (defun org-closest-date (start current change prefer)
18292 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18293 When PREFER is `past' return a date that is either CURRENT or past.
18294 When PREFER is `future', return a date that is either CURRENT or future."
18295 ;; Make the proper lists from the dates
18296 (catch 'exit
18297 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18298 dn dw sday cday n1 n2
18299 d m y y1 y2 date1 date2 nmonths nm ny m2)
18301 (setq start (org-date-to-gregorian start)
18302 current (org-date-to-gregorian
18303 (if org-agenda-repeating-timestamp-show-all
18304 current
18305 (time-to-days (current-time))))
18306 sday (calendar-absolute-from-gregorian start)
18307 cday (calendar-absolute-from-gregorian current))
18309 (if (<= cday sday) (throw 'exit sday))
18311 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18312 (setq dn (string-to-number (match-string 1 change))
18313 dw (cdr (assoc (match-string 2 change) a1)))
18314 (error "Invalid change specifyer: %s" change))
18315 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18316 (cond
18317 ((eq dw 'day)
18318 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18319 n2 (+ n1 dn)))
18320 ((eq dw 'year)
18321 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18322 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18323 (setq date1 (list m d y1)
18324 n1 (calendar-absolute-from-gregorian date1)
18325 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18326 n2 (calendar-absolute-from-gregorian date2)))
18327 ((eq dw 'month)
18328 ;; approx number of month between the tow dates
18329 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18330 ;; How often does dn fit in there?
18331 (setq d (nth 1 start) m (car start) y (nth 2 start)
18332 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18333 m (+ m nm)
18334 ny (floor (/ m 12))
18335 y (+ y ny)
18336 m (- m (* ny 12)))
18337 (while (> m 12) (setq m (- m 12) y (1+ y)))
18338 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18339 (setq m2 (+ m dn) y2 y)
18340 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18341 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18342 (while (< n2 cday)
18343 (setq n1 n2 m m2 y y2)
18344 (setq m2 (+ m dn) y2 y)
18345 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18346 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18348 (if org-agenda-repeating-timestamp-show-all
18349 (cond
18350 ((eq prefer 'past) n1)
18351 ((eq prefer 'future) (if (= cday n1) n1 n2))
18352 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18353 (cond
18354 ((eq prefer 'past) n1)
18355 ((eq prefer 'future) (if (= cday n1) n1 n2))
18356 (t (if (= cday n1) n1 n2)))))))
18358 (defun org-date-to-gregorian (date)
18359 "Turn any specification of DATE into a gregorian date for the calendar."
18360 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18361 ((and (listp date) (= (length date) 3)) date)
18362 ((stringp date)
18363 (setq date (org-parse-time-string date))
18364 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18365 ((listp date)
18366 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18368 (defun org-parse-time-string (s &optional nodefault)
18369 "Parse the standard Org-mode time string.
18370 This should be a lot faster than the normal `parse-time-string'.
18371 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18372 hour and minute fields will be nil if not given."
18373 (if (string-match org-ts-regexp0 s)
18374 (list 0
18375 (if (or (match-beginning 8) (not nodefault))
18376 (string-to-number (or (match-string 8 s) "0")))
18377 (if (or (match-beginning 7) (not nodefault))
18378 (string-to-number (or (match-string 7 s) "0")))
18379 (string-to-number (match-string 4 s))
18380 (string-to-number (match-string 3 s))
18381 (string-to-number (match-string 2 s))
18382 nil nil nil)
18383 (make-list 9 0)))
18385 (defun org-timestamp-up (&optional arg)
18386 "Increase the date item at the cursor by one.
18387 If the cursor is on the year, change the year. If it is on the month or
18388 the day, change that.
18389 With prefix ARG, change by that many units."
18390 (interactive "p")
18391 (org-timestamp-change (prefix-numeric-value arg)))
18393 (defun org-timestamp-down (&optional arg)
18394 "Decrease the date item at the cursor by one.
18395 If the cursor is on the year, change the year. If it is on the month or
18396 the day, change that.
18397 With prefix ARG, change by that many units."
18398 (interactive "p")
18399 (org-timestamp-change (- (prefix-numeric-value arg))))
18401 (defun org-timestamp-up-day (&optional arg)
18402 "Increase the date in the time stamp by one day.
18403 With prefix ARG, change that many days."
18404 (interactive "p")
18405 (if (and (not (org-at-timestamp-p t))
18406 (org-on-heading-p))
18407 (org-todo 'up)
18408 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18410 (defun org-timestamp-down-day (&optional arg)
18411 "Decrease the date in the time stamp by one day.
18412 With prefix ARG, change that many days."
18413 (interactive "p")
18414 (if (and (not (org-at-timestamp-p t))
18415 (org-on-heading-p))
18416 (org-todo 'down)
18417 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18419 (defsubst org-pos-in-match-range (pos n)
18420 (and (match-beginning n)
18421 (<= (match-beginning n) pos)
18422 (>= (match-end n) pos)))
18424 (defun org-at-timestamp-p (&optional inactive-ok)
18425 "Determine if the cursor is in or at a timestamp."
18426 (interactive)
18427 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18428 (pos (point))
18429 (ans (or (looking-at tsr)
18430 (save-excursion
18431 (skip-chars-backward "^[<\n\r\t")
18432 (if (> (point) (point-min)) (backward-char 1))
18433 (and (looking-at tsr)
18434 (> (- (match-end 0) pos) -1))))))
18435 (and ans
18436 (boundp 'org-ts-what)
18437 (setq org-ts-what
18438 (cond
18439 ((= pos (match-beginning 0)) 'bracket)
18440 ((= pos (1- (match-end 0))) 'bracket)
18441 ((org-pos-in-match-range pos 2) 'year)
18442 ((org-pos-in-match-range pos 3) 'month)
18443 ((org-pos-in-match-range pos 7) 'hour)
18444 ((org-pos-in-match-range pos 8) 'minute)
18445 ((or (org-pos-in-match-range pos 4)
18446 (org-pos-in-match-range pos 5)) 'day)
18447 ((and (> pos (or (match-end 8) (match-end 5)))
18448 (< pos (match-end 0)))
18449 (- pos (or (match-end 8) (match-end 5))))
18450 (t 'day))))
18451 ans))
18453 (defun org-toggle-timestamp-type ()
18455 (interactive)
18456 (when (org-at-timestamp-p t)
18457 (save-excursion
18458 (goto-char (match-beginning 0))
18459 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18460 (goto-char (1- (match-end 0)))
18461 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18462 (message "Timestamp is now %sactive"
18463 (if (equal (char-before) ?>) "in" ""))))
18465 (defun org-timestamp-change (n &optional what)
18466 "Change the date in the time stamp at point.
18467 The date will be changed by N times WHAT. WHAT can be `day', `month',
18468 `year', `minute', `second'. If WHAT is not given, the cursor position
18469 in the timestamp determines what will be changed."
18470 (let ((pos (point))
18471 with-hm inactive
18472 org-ts-what
18473 extra
18474 ts time time0)
18475 (if (not (org-at-timestamp-p t))
18476 (error "Not at a timestamp"))
18477 (if (and (not what) (eq org-ts-what 'bracket))
18478 (org-toggle-timestamp-type)
18479 (if (and (not what) (not (eq org-ts-what 'day))
18480 org-display-custom-times
18481 (get-text-property (point) 'display)
18482 (not (get-text-property (1- (point)) 'display)))
18483 (setq org-ts-what 'day))
18484 (setq org-ts-what (or what org-ts-what)
18485 inactive (= (char-after (match-beginning 0)) ?\[)
18486 ts (match-string 0))
18487 (replace-match "")
18488 (if (string-match
18489 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18491 (setq extra (match-string 1 ts)))
18492 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18493 (setq with-hm t))
18494 (setq time0 (org-parse-time-string ts))
18495 (setq time
18496 (encode-time (or (car time0) 0)
18497 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18498 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18499 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18500 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18501 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18502 (nthcdr 6 time0)))
18503 (when (integerp org-ts-what)
18504 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18505 (if (eq what 'calendar)
18506 (let ((cal-date (org-get-date-from-calendar)))
18507 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18508 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18509 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18510 (setcar time0 (or (car time0) 0))
18511 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18512 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18513 (setq time (apply 'encode-time time0))))
18514 (setq org-last-changed-timestamp
18515 (org-insert-time-stamp time with-hm inactive nil nil extra))
18516 (org-clock-update-time-maybe)
18517 (goto-char pos)
18518 ;; Try to recenter the calendar window, if any
18519 (if (and org-calendar-follow-timestamp-change
18520 (get-buffer-window "*Calendar*" t)
18521 (memq org-ts-what '(day month year)))
18522 (org-recenter-calendar (time-to-days time))))))
18524 ;; FIXME: does not yet work for lead times
18525 (defun org-modify-ts-extra (s pos n)
18526 "Change the different parts of the lead-time and repeat fields in timestamp."
18527 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18528 ng h m new)
18529 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18530 (cond
18531 ((or (org-pos-in-match-range pos 2)
18532 (org-pos-in-match-range pos 3))
18533 (setq m (string-to-number (match-string 3 s))
18534 h (string-to-number (match-string 2 s)))
18535 (if (org-pos-in-match-range pos 2)
18536 (setq h (+ h n))
18537 (setq m (+ m n)))
18538 (if (< m 0) (setq m (+ m 60) h (1- h)))
18539 (if (> m 59) (setq m (- m 60) h (1+ h)))
18540 (setq h (min 24 (max 0 h)))
18541 (setq ng 1 new (format "-%02d:%02d" h m)))
18542 ((org-pos-in-match-range pos 6)
18543 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18544 ((org-pos-in-match-range pos 5)
18545 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18547 (when ng
18548 (setq s (concat
18549 (substring s 0 (match-beginning ng))
18551 (substring s (match-end ng))))))
18554 (defun org-recenter-calendar (date)
18555 "If the calendar is visible, recenter it to DATE."
18556 (let* ((win (selected-window))
18557 (cwin (get-buffer-window "*Calendar*" t))
18558 (calendar-move-hook nil))
18559 (when cwin
18560 (select-window cwin)
18561 (calendar-goto-date (if (listp date) date
18562 (calendar-gregorian-from-absolute date)))
18563 (select-window win))))
18565 (defun org-goto-calendar (&optional arg)
18566 "Go to the Emacs calendar at the current date.
18567 If there is a time stamp in the current line, go to that date.
18568 A prefix ARG can be used to force the current date."
18569 (interactive "P")
18570 (let ((tsr org-ts-regexp) diff
18571 (calendar-move-hook nil)
18572 (view-calendar-holidays-initially nil)
18573 (view-diary-entries-initially nil))
18574 (if (or (org-at-timestamp-p)
18575 (save-excursion
18576 (beginning-of-line 1)
18577 (looking-at (concat ".*" tsr))))
18578 (let ((d1 (time-to-days (current-time)))
18579 (d2 (time-to-days
18580 (org-time-string-to-time (match-string 1)))))
18581 (setq diff (- d2 d1))))
18582 (calendar)
18583 (calendar-goto-today)
18584 (if (and diff (not arg)) (calendar-forward-day diff))))
18586 (defun org-get-date-from-calendar ()
18587 "Return a list (month day year) of date at point in calendar."
18588 (with-current-buffer "*Calendar*"
18589 (save-match-data
18590 (calendar-cursor-to-date))))
18592 (defun org-date-from-calendar ()
18593 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18594 If there is already a time stamp at the cursor position, update it."
18595 (interactive)
18596 (if (org-at-timestamp-p t)
18597 (org-timestamp-change 0 'calendar)
18598 (let ((cal-date (org-get-date-from-calendar)))
18599 (org-insert-time-stamp
18600 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18602 (defvar appt-time-msg-list)
18604 ;;;###autoload
18605 (defun org-agenda-to-appt (&optional refresh filter)
18606 "Activate appointments found in `org-agenda-files'.
18607 With a \\[universal-argument] prefix, refresh the list of
18608 appointements.
18610 If FILTER is t, interactively prompt the user for a regular
18611 expression, and filter out entries that don't match it.
18613 If FILTER is a string, use this string as a regular expression
18614 for filtering entries out.
18616 FILTER can also be an alist with the car of each cell being
18617 either 'headline or 'category. For example:
18619 '((headline \"IMPORTANT\")
18620 (category \"Work\"))
18622 will only add headlines containing IMPORTANT or headlines
18623 belonging to the \"Work\" category."
18624 (interactive "P")
18625 (require 'calendar)
18626 (if refresh (setq appt-time-msg-list nil))
18627 (if (eq filter t)
18628 (setq filter (read-from-minibuffer "Regexp filter: ")))
18629 (let* ((cnt 0) ; count added events
18630 (org-agenda-new-buffers nil)
18631 (org-deadline-warning-days 0)
18632 (today (org-date-to-gregorian
18633 (time-to-days (current-time))))
18634 (files (org-agenda-files)) entries file)
18635 ;; Get all entries which may contain an appt
18636 (while (setq file (pop files))
18637 (setq entries
18638 (append entries
18639 (org-agenda-get-day-entries
18640 file today :timestamp :scheduled :deadline))))
18641 (setq entries (delq nil entries))
18642 ;; Map thru entries and find if we should filter them out
18643 (mapc
18644 (lambda(x)
18645 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18646 (cat (get-text-property 1 'org-category x))
18647 (tod (get-text-property 1 'time-of-day x))
18648 (ok (or (null filter)
18649 (and (stringp filter) (string-match filter evt))
18650 (and (listp filter)
18651 (or (string-match
18652 (cadr (assoc 'category filter)) cat)
18653 (string-match
18654 (cadr (assoc 'headline filter)) evt))))))
18655 ;; FIXME: Shall we remove text-properties for the appt text?
18656 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18657 (when (and ok tod)
18658 (setq tod (number-to-string tod)
18659 tod (when (string-match
18660 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18661 (concat (match-string 1 tod) ":"
18662 (match-string 2 tod))))
18663 (appt-add tod evt)
18664 (setq cnt (1+ cnt))))) entries)
18665 (org-release-buffers org-agenda-new-buffers)
18666 (if (eq cnt 0)
18667 (message "No event to add")
18668 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18670 ;;; The clock for measuring work time.
18672 (defvar org-mode-line-string "")
18673 (put 'org-mode-line-string 'risky-local-variable t)
18675 (defvar org-mode-line-timer nil)
18676 (defvar org-clock-heading "")
18677 (defvar org-clock-start-time "")
18679 (defun org-update-mode-line ()
18680 (let* ((delta (- (time-to-seconds (current-time))
18681 (time-to-seconds org-clock-start-time)))
18682 (h (floor delta 3600))
18683 (m (floor (- delta (* 3600 h)) 60)))
18684 (setq org-mode-line-string
18685 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18686 'help-echo "Org-mode clock is running"))
18687 (force-mode-line-update)))
18689 (defvar org-clock-marker (make-marker)
18690 "Marker recording the last clock-in.")
18691 (defvar org-clock-mode-line-entry nil
18692 "Information for the modeline about the running clock.")
18694 (defun org-clock-in ()
18695 "Start the clock on the current item.
18696 If necessary, clock-out of the currently active clock."
18697 (interactive)
18698 (org-clock-out t)
18699 (let (ts)
18700 (save-excursion
18701 (org-back-to-heading t)
18702 (when (and org-clock-in-switch-to-state
18703 (not (looking-at (concat outline-regexp "[ \t]*"
18704 org-clock-in-switch-to-state
18705 "\\>"))))
18706 (org-todo org-clock-in-switch-to-state))
18707 (if (and org-clock-heading-function
18708 (functionp org-clock-heading-function))
18709 (setq org-clock-heading (funcall org-clock-heading-function))
18710 (if (looking-at org-complex-heading-regexp)
18711 (setq org-clock-heading (match-string 4))
18712 (setq org-clock-heading "???")))
18713 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18714 (org-clock-find-position)
18716 (insert "\n") (backward-char 1)
18717 (indent-relative)
18718 (insert org-clock-string " ")
18719 (setq org-clock-start-time (current-time))
18720 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18721 (move-marker org-clock-marker (point) (buffer-base-buffer))
18722 (or global-mode-string (setq global-mode-string '("")))
18723 (or (memq 'org-mode-line-string global-mode-string)
18724 (setq global-mode-string
18725 (append global-mode-string '(org-mode-line-string))))
18726 (org-update-mode-line)
18727 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18728 (message "Clock started at %s" ts))))
18730 (defun org-clock-find-position ()
18731 "Find the location where the next clock line should be inserted."
18732 (org-back-to-heading t)
18733 (catch 'exit
18734 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18735 (re (concat "^[ \t]*" org-clock-string))
18736 (cnt 0)
18737 first last)
18738 (goto-char beg)
18739 (when (eobp) (newline) (setq end (max (point) end)))
18740 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18741 ;; we seem to have a CLOCK drawer, so go there.
18742 (beginning-of-line 2)
18743 (throw 'exit t))
18744 ;; Lets count the CLOCK lines
18745 (goto-char beg)
18746 (while (re-search-forward re end t)
18747 (setq first (or first (match-beginning 0))
18748 last (match-beginning 0)
18749 cnt (1+ cnt)))
18750 (when (and (integerp org-clock-into-drawer)
18751 (>= (1+ cnt) org-clock-into-drawer))
18752 ;; Wrap current entries into a new drawer
18753 (goto-char last)
18754 (beginning-of-line 2)
18755 (if (org-at-item-p) (org-end-of-item))
18756 (insert ":END:\n")
18757 (beginning-of-line 0)
18758 (org-indent-line-function)
18759 (goto-char first)
18760 (insert ":CLOCK:\n")
18761 (beginning-of-line 0)
18762 (org-indent-line-function)
18763 (org-flag-drawer t)
18764 (beginning-of-line 2)
18765 (throw 'exit nil))
18767 (goto-char beg)
18768 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18769 (not (equal (match-string 1) org-clock-string)))
18770 ;; Planning info, skip to after it
18771 (beginning-of-line 2)
18772 (or (bolp) (newline)))
18773 (when (eq t org-clock-into-drawer)
18774 (insert ":CLOCK:\n:END:\n")
18775 (beginning-of-line -1)
18776 (org-indent-line-function)
18777 (org-flag-drawer t)
18778 (beginning-of-line 2)
18779 (org-indent-line-function)))))
18781 (defun org-clock-out (&optional fail-quietly)
18782 "Stop the currently running clock.
18783 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18784 (interactive)
18785 (catch 'exit
18786 (if (not (marker-buffer org-clock-marker))
18787 (if fail-quietly (throw 'exit t) (error "No active clock")))
18788 (let (ts te s h m)
18789 (save-excursion
18790 (set-buffer (marker-buffer org-clock-marker))
18791 (goto-char org-clock-marker)
18792 (beginning-of-line 1)
18793 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18794 (equal (match-string 1) org-clock-string))
18795 (setq ts (match-string 2))
18796 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18797 (goto-char (match-end 0))
18798 (delete-region (point) (point-at-eol))
18799 (insert "--")
18800 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18801 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18802 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18803 h (floor (/ s 3600))
18804 s (- s (* 3600 h))
18805 m (floor (/ s 60))
18806 s (- s (* 60 s)))
18807 (insert " => " (format "%2d:%02d" h m))
18808 (move-marker org-clock-marker nil)
18809 (when org-log-note-clock-out
18810 (org-add-log-maybe 'clock-out))
18811 (when org-mode-line-timer
18812 (cancel-timer org-mode-line-timer)
18813 (setq org-mode-line-timer nil))
18814 (setq global-mode-string
18815 (delq 'org-mode-line-string global-mode-string))
18816 (force-mode-line-update)
18817 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18819 (defun org-clock-cancel ()
18820 "Cancel the running clock be removing the start timestamp."
18821 (interactive)
18822 (if (not (marker-buffer org-clock-marker))
18823 (error "No active clock"))
18824 (save-excursion
18825 (set-buffer (marker-buffer org-clock-marker))
18826 (goto-char org-clock-marker)
18827 (delete-region (1- (point-at-bol)) (point-at-eol)))
18828 (setq global-mode-string
18829 (delq 'org-mode-line-string global-mode-string))
18830 (force-mode-line-update)
18831 (message "Clock canceled"))
18833 (defun org-clock-goto (&optional delete-windows)
18834 "Go to the currently clocked-in entry."
18835 (interactive "P")
18836 (if (not (marker-buffer org-clock-marker))
18837 (error "No active clock"))
18838 (switch-to-buffer-other-window
18839 (marker-buffer org-clock-marker))
18840 (if delete-windows (delete-other-windows))
18841 (goto-char org-clock-marker)
18842 (org-show-entry)
18843 (org-back-to-heading)
18844 (recenter))
18846 (defvar org-clock-file-total-minutes nil
18847 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18848 (make-variable-buffer-local 'org-clock-file-total-minutes)
18850 (defun org-clock-sum (&optional tstart tend)
18851 "Sum the times for each subtree.
18852 Puts the resulting times in minutes as a text property on each headline."
18853 (interactive)
18854 (let* ((bmp (buffer-modified-p))
18855 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18856 org-clock-string
18857 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18858 (lmax 30)
18859 (ltimes (make-vector lmax 0))
18860 (t1 0)
18861 (level 0)
18862 ts te dt
18863 time)
18864 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18865 (save-excursion
18866 (goto-char (point-max))
18867 (while (re-search-backward re nil t)
18868 (cond
18869 ((match-end 2)
18870 ;; Two time stamps
18871 (setq ts (match-string 2)
18872 te (match-string 3)
18873 ts (time-to-seconds
18874 (apply 'encode-time (org-parse-time-string ts)))
18875 te (time-to-seconds
18876 (apply 'encode-time (org-parse-time-string te)))
18877 ts (if tstart (max ts tstart) ts)
18878 te (if tend (min te tend) te)
18879 dt (- te ts)
18880 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18881 ((match-end 4)
18882 ;; A naket time
18883 (setq t1 (+ t1 (string-to-number (match-string 5))
18884 (* 60 (string-to-number (match-string 4))))))
18885 (t ;; A headline
18886 (setq level (- (match-end 1) (match-beginning 1)))
18887 (when (or (> t1 0) (> (aref ltimes level) 0))
18888 (loop for l from 0 to level do
18889 (aset ltimes l (+ (aref ltimes l) t1)))
18890 (setq t1 0 time (aref ltimes level))
18891 (loop for l from level to (1- lmax) do
18892 (aset ltimes l 0))
18893 (goto-char (match-beginning 0))
18894 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18895 (setq org-clock-file-total-minutes (aref ltimes 0)))
18896 (set-buffer-modified-p bmp)))
18898 (defun org-clock-display (&optional total-only)
18899 "Show subtree times in the entire buffer.
18900 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18901 in the echo area."
18902 (interactive)
18903 (org-remove-clock-overlays)
18904 (let (time h m p)
18905 (org-clock-sum)
18906 (unless total-only
18907 (save-excursion
18908 (goto-char (point-min))
18909 (while (or (and (equal (setq p (point)) (point-min))
18910 (get-text-property p :org-clock-minutes))
18911 (setq p (next-single-property-change
18912 (point) :org-clock-minutes)))
18913 (goto-char p)
18914 (when (setq time (get-text-property p :org-clock-minutes))
18915 (org-put-clock-overlay time (funcall outline-level))))
18916 (setq h (/ org-clock-file-total-minutes 60)
18917 m (- org-clock-file-total-minutes (* 60 h)))
18918 ;; Arrange to remove the overlays upon next change.
18919 (when org-remove-highlights-with-change
18920 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18921 nil 'local))))
18922 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18924 (defvar org-clock-overlays nil)
18925 (make-variable-buffer-local 'org-clock-overlays)
18927 (defun org-put-clock-overlay (time &optional level)
18928 "Put an overlays on the current line, displaying TIME.
18929 If LEVEL is given, prefix time with a corresponding number of stars.
18930 This creates a new overlay and stores it in `org-clock-overlays', so that it
18931 will be easy to remove."
18932 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18933 (l (if level (org-get-legal-level level 0) 0))
18934 (off 0)
18935 ov tx)
18936 (move-to-column c)
18937 (unless (eolp) (skip-chars-backward "^ \t"))
18938 (skip-chars-backward " \t")
18939 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18940 tx (concat (buffer-substring (1- (point)) (point))
18941 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18942 (org-add-props (format "%s %2d:%02d%s"
18943 (make-string l ?*) h m
18944 (make-string (- 16 l) ?\ ))
18945 '(face secondary-selection))
18946 ""))
18947 (if (not (featurep 'xemacs))
18948 (org-overlay-put ov 'display tx)
18949 (org-overlay-put ov 'invisible t)
18950 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18951 (push ov org-clock-overlays)))
18953 (defun org-remove-clock-overlays (&optional beg end noremove)
18954 "Remove the occur highlights from the buffer.
18955 BEG and END are ignored. If NOREMOVE is nil, remove this function
18956 from the `before-change-functions' in the current buffer."
18957 (interactive)
18958 (unless org-inhibit-highlight-removal
18959 (mapc 'org-delete-overlay org-clock-overlays)
18960 (setq org-clock-overlays nil)
18961 (unless noremove
18962 (remove-hook 'before-change-functions
18963 'org-remove-clock-overlays 'local))))
18965 (defun org-clock-out-if-current ()
18966 "Clock out if the current entry contains the running clock.
18967 This is used to stop the clock after a TODO entry is marked DONE,
18968 and is only done if the variable `org-clock-out-when-done' is not nil."
18969 (when (and org-clock-out-when-done
18970 (member state org-done-keywords)
18971 (equal (marker-buffer org-clock-marker) (current-buffer))
18972 (< (point) org-clock-marker)
18973 (> (save-excursion (outline-next-heading) (point))
18974 org-clock-marker))
18975 ;; Clock out, but don't accept a logging message for this.
18976 (let ((org-log-note-clock-out nil))
18977 (org-clock-out))))
18979 (add-hook 'org-after-todo-state-change-hook
18980 'org-clock-out-if-current)
18982 (defun org-check-running-clock ()
18983 "Check if the current buffer contains the running clock.
18984 If yes, offer to stop it and to save the buffer with the changes."
18985 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18986 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18987 (buffer-name))))
18988 (org-clock-out)
18989 (when (y-or-n-p "Save changed buffer?")
18990 (save-buffer))))
18992 (defun org-clock-report (&optional arg)
18993 "Create a table containing a report about clocked time.
18994 If the cursor is inside an existing clocktable block, then the table
18995 will be updated. If not, a new clocktable will be inserted.
18996 When called with a prefix argument, move to the first clock table in the
18997 buffer and update it."
18998 (interactive "P")
18999 (org-remove-clock-overlays)
19000 (when arg
19001 (org-find-dblock "clocktable")
19002 (org-show-entry))
19003 (if (org-in-clocktable-p)
19004 (goto-char (org-in-clocktable-p))
19005 (org-create-dblock (list :name "clocktable"
19006 :maxlevel 2 :scope 'file)))
19007 (org-update-dblock))
19009 (defun org-in-clocktable-p ()
19010 "Check if the cursor is in a clocktable."
19011 (let ((pos (point)) start)
19012 (save-excursion
19013 (end-of-line 1)
19014 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19015 (setq start (match-beginning 0))
19016 (re-search-forward "^#\\+END:.*" nil t)
19017 (>= (match-end 0) pos)
19018 start))))
19020 (defun org-clock-update-time-maybe ()
19021 "If this is a CLOCK line, update it and return t.
19022 Otherwise, return nil."
19023 (interactive)
19024 (save-excursion
19025 (beginning-of-line 1)
19026 (skip-chars-forward " \t")
19027 (when (looking-at org-clock-string)
19028 (let ((re (concat "[ \t]*" org-clock-string
19029 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19030 "\\([ \t]*=>.*\\)?"))
19031 ts te h m s)
19032 (if (not (looking-at re))
19034 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19035 (end-of-line 1)
19036 (setq ts (match-string 1)
19037 te (match-string 2))
19038 (setq s (- (time-to-seconds
19039 (apply 'encode-time (org-parse-time-string te)))
19040 (time-to-seconds
19041 (apply 'encode-time (org-parse-time-string ts))))
19042 h (floor (/ s 3600))
19043 s (- s (* 3600 h))
19044 m (floor (/ s 60))
19045 s (- s (* 60 s)))
19046 (insert " => " (format "%2d:%02d" h m))
19047 t)))))
19049 (defun org-clock-special-range (key &optional time as-strings)
19050 "Return two times bordering a special time range.
19051 Key is a symbol specifying the range and can be one of `today', `yesterday',
19052 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19053 A week starts Monday 0:00 and ends Sunday 24:00.
19054 The range is determined relative to TIME. TIME defaults to the current time.
19055 The return value is a cons cell with two internal times like the ones
19056 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19057 the returned times will be formatted strings."
19058 (let* ((tm (decode-time (or time (current-time))))
19059 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19060 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19061 (dow (nth 6 tm))
19062 s1 m1 h1 d1 month1 y1 diff ts te fm)
19063 (cond
19064 ((eq key 'today)
19065 (setq h 0 m 0 h1 24 m1 0))
19066 ((eq key 'yesterday)
19067 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19068 ((eq key 'thisweek)
19069 (setq diff (if (= dow 0) 6 (1- dow))
19070 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19071 ((eq key 'lastweek)
19072 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19073 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19074 ((eq key 'thismonth)
19075 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19076 ((eq key 'lastmonth)
19077 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19078 ((eq key 'thisyear)
19079 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19080 ((eq key 'lastyear)
19081 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19082 (t (error "No such time block %s" key)))
19083 (setq ts (encode-time s m h d month y)
19084 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19085 (or d1 d) (or month1 month) (or y1 y)))
19086 (setq fm (cdr org-time-stamp-formats))
19087 (if as-strings
19088 (cons (format-time-string fm ts) (format-time-string fm te))
19089 (cons ts te))))
19091 (defun org-dblock-write:clocktable (params)
19092 "Write the standard clocktable."
19093 (catch 'exit
19094 (let* ((hlchars '((1 . "*") (2 . "/")))
19095 (ins (make-marker))
19096 (total-time nil)
19097 (scope (plist-get params :scope))
19098 (tostring (plist-get params :tostring))
19099 (multifile (plist-get params :multifile))
19100 (header (plist-get params :header))
19101 (maxlevel (or (plist-get params :maxlevel) 3))
19102 (step (plist-get params :step))
19103 (emph (plist-get params :emphasize))
19104 (ts (plist-get params :tstart))
19105 (te (plist-get params :tend))
19106 (block (plist-get params :block))
19107 ipos time h m p level hlc hdl
19108 cc beg end pos tbl)
19109 (when step
19110 (org-clocktable-steps params)
19111 (throw 'exit nil))
19112 (when block
19113 (setq cc (org-clock-special-range block nil t)
19114 ts (car cc) te (cdr cc)))
19115 (if ts (setq ts (time-to-seconds
19116 (apply 'encode-time (org-parse-time-string ts)))))
19117 (if te (setq te (time-to-seconds
19118 (apply 'encode-time (org-parse-time-string te)))))
19119 (move-marker ins (point))
19120 (setq ipos (point))
19122 ;; Get the right scope
19123 (setq pos (point))
19124 (save-restriction
19125 (cond
19126 ((not scope))
19127 ((eq scope 'file) (widen))
19128 ((eq scope 'subtree) (org-narrow-to-subtree))
19129 ((eq scope 'tree)
19130 (while (org-up-heading-safe))
19131 (org-narrow-to-subtree))
19132 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19133 (symbol-name scope)))
19134 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19135 (catch 'exit
19136 (while (org-up-heading-safe)
19137 (looking-at outline-regexp)
19138 (if (<= (org-reduced-level (funcall outline-level)) level)
19139 (throw 'exit nil))))
19140 (org-narrow-to-subtree))
19141 ((or (listp scope) (eq scope 'agenda))
19142 (let* ((files (if (listp scope) scope (org-agenda-files)))
19143 (scope 'agenda)
19144 (p1 (copy-sequence params))
19145 file)
19146 (plist-put p1 :tostring t)
19147 (plist-put p1 :multifile t)
19148 (plist-put p1 :scope 'file)
19149 (org-prepare-agenda-buffers files)
19150 (while (setq file (pop files))
19151 (with-current-buffer (find-buffer-visiting file)
19152 (push (org-clocktable-add-file
19153 file (org-dblock-write:clocktable p1)) tbl)
19154 (setq total-time (+ (or total-time 0)
19155 org-clock-file-total-minutes)))))))
19156 (goto-char pos)
19158 (unless (eq scope 'agenda)
19159 (org-clock-sum ts te)
19160 (goto-char (point-min))
19161 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19162 (goto-char p)
19163 (when (setq time (get-text-property p :org-clock-minutes))
19164 (save-excursion
19165 (beginning-of-line 1)
19166 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19167 (setq level (org-reduced-level
19168 (- (match-end 1) (match-beginning 1))))
19169 (<= level maxlevel))
19170 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19171 hdl (match-string 2)
19172 h (/ time 60)
19173 m (- time (* 60 h)))
19174 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19175 (push (concat
19176 "| " (int-to-string level) "|" hlc hdl hlc " |"
19177 (make-string (1- level) ?|)
19178 hlc (format "%d:%02d" h m) hlc
19179 " |") tbl))))))
19180 (setq tbl (nreverse tbl))
19181 (if tostring
19182 (if tbl (mapconcat 'identity tbl "\n") nil)
19183 (goto-char ins)
19184 (insert-before-markers
19185 (or header
19186 (concat
19187 "Clock summary at ["
19188 (substring
19189 (format-time-string (cdr org-time-stamp-formats))
19190 1 -1)
19191 "]."
19192 (if block
19193 (format " Considered range is /%s/." block)
19195 "\n\n"))
19196 (if (eq scope 'agenda) "|File" "")
19197 "|L|Headline|Time|\n")
19198 (setq total-time (or total-time org-clock-file-total-minutes)
19199 h (/ total-time 60)
19200 m (- total-time (* 60 h)))
19201 (insert-before-markers
19202 "|-\n|"
19203 (if (eq scope 'agenda) "|" "")
19205 "*Total time*| "
19206 (format "*%d:%02d*" h m)
19207 "|\n|-\n")
19208 (setq tbl (delq nil tbl))
19209 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19210 (equal (substring (car tbl) 0 2) "|-"))
19211 (pop tbl))
19212 (insert-before-markers (mapconcat
19213 'identity (delq nil tbl)
19214 (if (eq scope 'agenda) "\n|-\n" "\n")))
19215 (backward-delete-char 1)
19216 (goto-char ipos)
19217 (skip-chars-forward "^|")
19218 (org-table-align))))))
19220 (defun org-clocktable-steps (params)
19221 (let* ((p1 (copy-sequence params))
19222 (ts (plist-get p1 :tstart))
19223 (te (plist-get p1 :tend))
19224 (step0 (plist-get p1 :step))
19225 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19226 (block (plist-get p1 :block))
19228 (when block
19229 (setq cc (org-clock-special-range block nil t)
19230 ts (car cc) te (cdr cc)))
19231 (if ts (setq ts (time-to-seconds
19232 (apply 'encode-time (org-parse-time-string ts)))))
19233 (if te (setq te (time-to-seconds
19234 (apply 'encode-time (org-parse-time-string te)))))
19235 (plist-put p1 :header "")
19236 (plist-put p1 :step nil)
19237 (plist-put p1 :block nil)
19238 (while (< ts te)
19239 (or (bolp) (insert "\n"))
19240 (plist-put p1 :tstart (format-time-string
19241 (car org-time-stamp-formats)
19242 (seconds-to-time ts)))
19243 (plist-put p1 :tend (format-time-string
19244 (car org-time-stamp-formats)
19245 (seconds-to-time (setq ts (+ ts step)))))
19246 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19247 (plist-get p1 :tstart) "\n")
19248 (org-dblock-write:clocktable p1)
19249 (re-search-forward "#\\+END:")
19250 (end-of-line 0))))
19253 (defun org-clocktable-add-file (file table)
19254 (if table
19255 (let ((lines (org-split-string table "\n"))
19256 (ff (file-name-nondirectory file)))
19257 (mapconcat 'identity
19258 (mapcar (lambda (x)
19259 (if (string-match org-table-dataline-regexp x)
19260 (concat "|" ff x)
19262 lines)
19263 "\n"))))
19265 ;; FIXME: I don't think anybody uses this, ask David
19266 (defun org-collect-clock-time-entries ()
19267 "Return an internal list with clocking information.
19268 This list has one entry for each CLOCK interval.
19269 FIXME: describe the elements."
19270 (interactive)
19271 (let ((re (concat "^[ \t]*" org-clock-string
19272 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19273 rtn beg end next cont level title total closedp leafp
19274 clockpos titlepos h m donep)
19275 (save-excursion
19276 (org-clock-sum)
19277 (goto-char (point-min))
19278 (while (re-search-forward re nil t)
19279 (setq clockpos (match-beginning 0)
19280 beg (match-string 1) end (match-string 2)
19281 cont (match-end 0))
19282 (setq beg (apply 'encode-time (org-parse-time-string beg))
19283 end (apply 'encode-time (org-parse-time-string end)))
19284 (org-back-to-heading t)
19285 (setq donep (org-entry-is-done-p))
19286 (setq titlepos (point)
19287 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19288 h (/ total 60) m (- total (* 60 h))
19289 total (cons h m))
19290 (looking-at "\\(\\*+\\) +\\(.*\\)")
19291 (setq level (- (match-end 1) (match-beginning 1))
19292 title (org-match-string-no-properties 2))
19293 (save-excursion (outline-next-heading) (setq next (point)))
19294 (setq closedp (re-search-forward org-closed-time-regexp next t))
19295 (goto-char next)
19296 (setq leafp (and (looking-at "^\\*+ ")
19297 (<= (- (match-end 0) (point)) level)))
19298 (push (list beg end clockpos closedp donep
19299 total title titlepos level leafp)
19300 rtn)
19301 (goto-char cont)))
19302 (nreverse rtn)))
19304 ;;;; Agenda, and Diary Integration
19306 ;;; Define the Org-agenda-mode
19308 (defvar org-agenda-mode-map (make-sparse-keymap)
19309 "Keymap for `org-agenda-mode'.")
19311 (defvar org-agenda-menu) ; defined later in this file.
19312 (defvar org-agenda-follow-mode nil)
19313 (defvar org-agenda-show-log nil)
19314 (defvar org-agenda-redo-command nil)
19315 (defvar org-agenda-mode-hook nil)
19316 (defvar org-agenda-type nil)
19317 (defvar org-agenda-force-single-file nil)
19319 (defun org-agenda-mode ()
19320 "Mode for time-sorted view on action items in Org-mode files.
19322 The following commands are available:
19324 \\{org-agenda-mode-map}"
19325 (interactive)
19326 (kill-all-local-variables)
19327 (setq org-agenda-undo-list nil
19328 org-agenda-pending-undo-list nil)
19329 (setq major-mode 'org-agenda-mode)
19330 ;; Keep global-font-lock-mode from turning on font-lock-mode
19331 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19332 (setq mode-name "Org-Agenda")
19333 (use-local-map org-agenda-mode-map)
19334 (easy-menu-add org-agenda-menu)
19335 (if org-startup-truncated (setq truncate-lines t))
19336 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19337 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19338 ;; Make sure properties are removed when copying text
19339 (when (boundp 'buffer-substring-filters)
19340 (org-set-local 'buffer-substring-filters
19341 (cons (lambda (x)
19342 (set-text-properties 0 (length x) nil x) x)
19343 buffer-substring-filters)))
19344 (unless org-agenda-keep-modes
19345 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19346 org-agenda-show-log nil))
19347 (easy-menu-change
19348 '("Agenda") "Agenda Files"
19349 (append
19350 (list
19351 (vector
19352 (if (get 'org-agenda-files 'org-restrict)
19353 "Restricted to single file"
19354 "Edit File List")
19355 '(org-edit-agenda-file-list)
19356 (not (get 'org-agenda-files 'org-restrict)))
19357 "--")
19358 (mapcar 'org-file-menu-entry (org-agenda-files))))
19359 (org-agenda-set-mode-name)
19360 (apply
19361 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19362 (list 'org-agenda-mode-hook)))
19364 (substitute-key-definition 'undo 'org-agenda-undo
19365 org-agenda-mode-map global-map)
19366 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19367 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19368 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19369 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19370 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19371 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19372 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19373 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19374 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19375 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19376 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19377 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19378 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19379 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19380 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19381 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19382 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19383 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19384 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19385 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19386 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19387 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19388 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19389 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19390 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19391 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19392 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19393 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19394 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19396 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19397 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19398 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19399 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19400 (while l (org-defkey org-agenda-mode-map
19401 (int-to-string (pop l)) 'digit-argument)))
19403 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19404 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19405 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19406 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19407 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19408 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19409 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19410 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19411 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19412 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19413 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19414 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19415 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19416 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19417 (org-defkey org-agenda-mode-map "n" 'next-line)
19418 (org-defkey org-agenda-mode-map "p" 'previous-line)
19419 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19420 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19421 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19422 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19423 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19424 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19425 (eval-after-load "calendar"
19426 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19427 'org-calendar-goto-agenda))
19428 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19429 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19430 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19431 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19432 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19433 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19434 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19435 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19436 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19437 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19438 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19439 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19440 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19441 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19442 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19443 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19444 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19445 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19446 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19447 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19448 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19449 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19451 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19452 "Local keymap for agenda entries from Org-mode.")
19454 (org-defkey org-agenda-keymap
19455 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19456 (org-defkey org-agenda-keymap
19457 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19458 (when org-agenda-mouse-1-follows-link
19459 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19460 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19461 '("Agenda"
19462 ("Agenda Files")
19463 "--"
19464 ["Show" org-agenda-show t]
19465 ["Go To (other window)" org-agenda-goto t]
19466 ["Go To (this window)" org-agenda-switch-to t]
19467 ["Follow Mode" org-agenda-follow-mode
19468 :style toggle :selected org-agenda-follow-mode :active t]
19469 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19470 "--"
19471 ["Cycle TODO" org-agenda-todo t]
19472 ["Archive subtree" org-agenda-archive t]
19473 ["Delete subtree" org-agenda-kill t]
19474 "--"
19475 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19476 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19477 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19478 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19479 "--"
19480 ("Tags and Properties"
19481 ["Show all Tags" org-agenda-show-tags t]
19482 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19483 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19484 "--"
19485 ["Column View" org-columns t])
19486 ("Date/Schedule"
19487 ["Schedule" org-agenda-schedule t]
19488 ["Set Deadline" org-agenda-deadline t]
19489 "--"
19490 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19491 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19492 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19493 ("Clock"
19494 ["Clock in" org-agenda-clock-in t]
19495 ["Clock out" org-agenda-clock-out t]
19496 ["Clock cancel" org-agenda-clock-cancel t]
19497 ["Goto running clock" org-clock-goto t])
19498 ("Priority"
19499 ["Set Priority" org-agenda-priority t]
19500 ["Increase Priority" org-agenda-priority-up t]
19501 ["Decrease Priority" org-agenda-priority-down t]
19502 ["Show Priority" org-agenda-show-priority t])
19503 ("Calendar/Diary"
19504 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19505 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19506 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19507 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19508 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19509 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19510 "--"
19511 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19512 "--"
19513 ("View"
19514 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19515 :style radio :selected (equal org-agenda-ndays 1)]
19516 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19517 :style radio :selected (equal org-agenda-ndays 7)]
19518 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19519 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19520 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19521 :style radio :selected (member org-agenda-ndays '(365 366))]
19522 "--"
19523 ["Show Logbook entries" org-agenda-log-mode
19524 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19525 ["Include Diary" org-agenda-toggle-diary
19526 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19527 ["Use Time Grid" org-agenda-toggle-time-grid
19528 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19529 ["Write view to file" org-write-agenda t]
19530 ["Rebuild buffer" org-agenda-redo t]
19531 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19532 "--"
19533 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19534 "--"
19535 ["Quit" org-agenda-quit t]
19536 ["Exit and Release Buffers" org-agenda-exit t]
19539 ;;; Agenda undo
19541 (defvar org-agenda-allow-remote-undo t
19542 "Non-nil means, allow remote undo from the agenda buffer.")
19543 (defvar org-agenda-undo-list nil
19544 "List of undoable operations in the agenda since last refresh.")
19545 (defvar org-agenda-undo-has-started-in nil
19546 "Buffers that have already seen `undo-start' in the current undo sequence.")
19547 (defvar org-agenda-pending-undo-list nil
19548 "In a series of undo commands, this is the list of remaning undo items.")
19550 (defmacro org-if-unprotected (&rest body)
19551 "Execute BODY if there is no `org-protected' text property at point."
19552 (declare (debug t))
19553 `(unless (get-text-property (point) 'org-protected)
19554 ,@body))
19556 (defmacro org-with-remote-undo (_buffer &rest _body)
19557 "Execute BODY while recording undo information in two buffers."
19558 (declare (indent 1) (debug t))
19559 `(let ((_cline (org-current-line))
19560 (_cmd this-command)
19561 (_buf1 (current-buffer))
19562 (_buf2 ,_buffer)
19563 (_undo1 buffer-undo-list)
19564 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19565 _c1 _c2)
19566 ,@_body
19567 (when org-agenda-allow-remote-undo
19568 (setq _c1 (org-verify-change-for-undo
19569 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19570 _c2 (org-verify-change-for-undo
19571 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19572 (when (or _c1 _c2)
19573 ;; make sure there are undo boundaries
19574 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19575 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19576 ;; remember which buffer to undo
19577 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19578 org-agenda-undo-list)))))
19580 (defun org-agenda-undo ()
19581 "Undo a remote editing step in the agenda.
19582 This undoes changes both in the agenda buffer and in the remote buffer
19583 that have been changed along."
19584 (interactive)
19585 (or org-agenda-allow-remote-undo
19586 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19587 (if (not (eq this-command last-command))
19588 (setq org-agenda-undo-has-started-in nil
19589 org-agenda-pending-undo-list org-agenda-undo-list))
19590 (if (not org-agenda-pending-undo-list)
19591 (error "No further undo information"))
19592 (let* ((entry (pop org-agenda-pending-undo-list))
19593 buf line cmd rembuf)
19594 (setq cmd (pop entry) line (pop entry))
19595 (setq rembuf (nth 2 entry))
19596 (org-with-remote-undo rembuf
19597 (while (bufferp (setq buf (pop entry)))
19598 (if (pop entry)
19599 (with-current-buffer buf
19600 (let ((last-undo-buffer buf)
19601 (inhibit-read-only t))
19602 (unless (memq buf org-agenda-undo-has-started-in)
19603 (push buf org-agenda-undo-has-started-in)
19604 (make-local-variable 'pending-undo-list)
19605 (undo-start))
19606 (while (and pending-undo-list
19607 (listp pending-undo-list)
19608 (not (car pending-undo-list)))
19609 (pop pending-undo-list))
19610 (undo-more 1))))))
19611 (goto-line line)
19612 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19614 (defun org-verify-change-for-undo (l1 l2)
19615 "Verify that a real change occurred between the undo lists L1 and L2."
19616 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19617 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19618 (not (eq l1 l2)))
19620 ;;; Agenda dispatch
19622 (defvar org-agenda-restrict nil)
19623 (defvar org-agenda-restrict-begin (make-marker))
19624 (defvar org-agenda-restrict-end (make-marker))
19625 (defvar org-agenda-last-dispatch-buffer nil)
19626 (defvar org-agenda-overriding-restriction nil)
19628 ;;;###autoload
19629 (defun org-agenda (arg &optional keys restriction)
19630 "Dispatch agenda commands to collect entries to the agenda buffer.
19631 Prompts for a command to execute. Any prefix arg will be passed
19632 on to the selected command. The default selections are:
19634 a Call `org-agenda-list' to display the agenda for current day or week.
19635 t Call `org-todo-list' to display the global todo list.
19636 T Call `org-todo-list' to display the global todo list, select only
19637 entries with a specific TODO keyword (the user gets a prompt).
19638 m Call `org-tags-view' to display headlines with tags matching
19639 a condition (the user is prompted for the condition).
19640 M Like `m', but select only TODO entries, no ordinary headlines.
19641 L Create a timeline for the current buffer.
19642 e Export views to associated files.
19644 More commands can be added by configuring the variable
19645 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19646 searches can be pre-defined in this way.
19648 If the current buffer is in Org-mode and visiting a file, you can also
19649 first press `<' once to indicate that the agenda should be temporarily
19650 \(until the next use of \\[org-agenda]) restricted to the current file.
19651 Pressing `<' twice means to restrict to the current subtree or region
19652 \(if active)."
19653 (interactive "P")
19654 (catch 'exit
19655 (let* ((prefix-descriptions nil)
19656 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19657 (org-agenda-custom-commands
19658 ;; normalize different versions
19659 (delq nil
19660 (mapcar
19661 (lambda (x)
19662 (cond ((stringp (cdr x))
19663 (push x prefix-descriptions)
19664 nil)
19665 ((stringp (nth 1 x)) x)
19666 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19667 (t (cons (car x) (cons "" (cdr x))))))
19668 org-agenda-custom-commands)))
19669 (buf (current-buffer))
19670 (bfn (buffer-file-name (buffer-base-buffer)))
19671 entry key type match lprops ans)
19672 ;; Turn off restriction unless there is an overriding one
19673 (unless org-agenda-overriding-restriction
19674 (put 'org-agenda-files 'org-restrict nil)
19675 (setq org-agenda-restrict nil)
19676 (move-marker org-agenda-restrict-begin nil)
19677 (move-marker org-agenda-restrict-end nil))
19678 ;; Delete old local properties
19679 (put 'org-agenda-redo-command 'org-lprops nil)
19680 ;; Remember where this call originated
19681 (setq org-agenda-last-dispatch-buffer (current-buffer))
19682 (unless keys
19683 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19684 keys (car ans)
19685 restriction (cdr ans)))
19686 ;; Estabish the restriction, if any
19687 (when (and (not org-agenda-overriding-restriction) restriction)
19688 (put 'org-agenda-files 'org-restrict (list bfn))
19689 (cond
19690 ((eq restriction 'region)
19691 (setq org-agenda-restrict t)
19692 (move-marker org-agenda-restrict-begin (region-beginning))
19693 (move-marker org-agenda-restrict-end (region-end)))
19694 ((eq restriction 'subtree)
19695 (save-excursion
19696 (setq org-agenda-restrict t)
19697 (org-back-to-heading t)
19698 (move-marker org-agenda-restrict-begin (point))
19699 (move-marker org-agenda-restrict-end
19700 (progn (org-end-of-subtree t)))))))
19702 (require 'calendar) ; FIXME: can we avoid this for some commands?
19703 ;; For example the todo list should not need it (but does...)
19704 (cond
19705 ((setq entry (assoc keys org-agenda-custom-commands))
19706 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19707 (progn
19708 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19709 (put 'org-agenda-redo-command 'org-lprops lprops)
19710 (cond
19711 ((eq type 'agenda)
19712 (org-let lprops '(org-agenda-list current-prefix-arg)))
19713 ((eq type 'alltodo)
19714 (org-let lprops '(org-todo-list current-prefix-arg)))
19715 ((eq type 'stuck)
19716 (org-let lprops '(org-agenda-list-stuck-projects
19717 current-prefix-arg)))
19718 ((eq type 'tags)
19719 (org-let lprops '(org-tags-view current-prefix-arg match)))
19720 ((eq type 'tags-todo)
19721 (org-let lprops '(org-tags-view '(4) match)))
19722 ((eq type 'todo)
19723 (org-let lprops '(org-todo-list match)))
19724 ((eq type 'tags-tree)
19725 (org-check-for-org-mode)
19726 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19727 ((eq type 'todo-tree)
19728 (org-check-for-org-mode)
19729 (org-let lprops
19730 '(org-occur (concat "^" outline-regexp "[ \t]*"
19731 (regexp-quote match) "\\>"))))
19732 ((eq type 'occur-tree)
19733 (org-check-for-org-mode)
19734 (org-let lprops '(org-occur match)))
19735 ((functionp type)
19736 (org-let lprops '(funcall type match)))
19737 ((fboundp type)
19738 (org-let lprops '(funcall type match)))
19739 (t (error "Invalid custom agenda command type %s" type))))
19740 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19741 ((equal keys "C")
19742 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19743 (customize-variable 'org-agenda-custom-commands))
19744 ((equal keys "a") (call-interactively 'org-agenda-list))
19745 ((equal keys "t") (call-interactively 'org-todo-list))
19746 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19747 ((equal keys "m") (call-interactively 'org-tags-view))
19748 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19749 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19750 ((equal keys "L")
19751 (unless (org-mode-p)
19752 (error "This is not an Org-mode file"))
19753 (unless restriction
19754 (put 'org-agenda-files 'org-restrict (list bfn))
19755 (org-call-with-arg 'org-timeline arg)))
19756 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19757 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19758 ((equal keys "!") (customize-variable 'org-stuck-projects))
19759 (t (error "Invalid agenda key"))))))
19761 (defun org-agenda-normalize-custom-commands (cmds)
19762 (delq nil
19763 (mapcar
19764 (lambda (x)
19765 (cond ((stringp (cdr x)) nil)
19766 ((stringp (nth 1 x)) x)
19767 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19768 (t (cons (car x) (cons "" (cdr x))))))
19769 cmds)))
19771 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19772 "The user interface for selecting an agenda command."
19773 (catch 'exit
19774 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19775 (restrict-ok (and bfn (org-mode-p)))
19776 (region-p (org-region-active-p))
19777 (custom org-agenda-custom-commands)
19778 (selstring "")
19779 restriction second-time
19780 c entry key type match prefixes rmheader header-end custom1 desc)
19781 (save-window-excursion
19782 (delete-other-windows)
19783 (org-switch-to-buffer-other-window " *Agenda Commands*")
19784 (erase-buffer)
19785 (insert (eval-when-compile
19786 (let ((header
19788 Press key for an agenda command: < Buffer,subtree/region restriction
19789 -------------------------------- > Remove restriction
19790 a Agenda for current week or day e Export agenda views
19791 t List of all TODO entries T Entries with special TODO kwd
19792 m Match a TAGS query M Like m, but only TODO entries
19793 L Timeline for current buffer # List stuck projects (!=configure)
19794 / Multi-occur C Configure custom agenda commands
19796 (start 0))
19797 (while (string-match
19798 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19799 header start)
19800 (setq start (match-end 0))
19801 (add-text-properties (match-beginning 2) (match-end 2)
19802 '(face bold) header))
19803 header)))
19804 (setq header-end (move-marker (make-marker) (point)))
19805 (while t
19806 (setq custom1 custom)
19807 (when (eq rmheader t)
19808 (goto-line 1)
19809 (re-search-forward ":" nil t)
19810 (delete-region (match-end 0) (point-at-eol))
19811 (forward-char 1)
19812 (looking-at "-+")
19813 (delete-region (match-end 0) (point-at-eol))
19814 (move-marker header-end (match-end 0)))
19815 (goto-char header-end)
19816 (delete-region (point) (point-max))
19817 (while (setq entry (pop custom1))
19818 (setq key (car entry) desc (nth 1 entry)
19819 type (nth 2 entry) match (nth 3 entry))
19820 (if (> (length key) 1)
19821 (add-to-list 'prefixes (string-to-char key))
19822 (insert
19823 (format
19824 "\n%-4s%-14s: %s"
19825 (org-add-props (copy-sequence key)
19826 '(face bold))
19827 (cond
19828 ((string-match "\\S-" desc) desc)
19829 ((eq type 'agenda) "Agenda for current week or day")
19830 ((eq type 'alltodo) "List of all TODO entries")
19831 ((eq type 'stuck) "List of stuck projects")
19832 ((eq type 'todo) "TODO keyword")
19833 ((eq type 'tags) "Tags query")
19834 ((eq type 'tags-todo) "Tags (TODO)")
19835 ((eq type 'tags-tree) "Tags tree")
19836 ((eq type 'todo-tree) "TODO kwd tree")
19837 ((eq type 'occur-tree) "Occur tree")
19838 ((functionp type) (if (symbolp type)
19839 (symbol-name type)
19840 "Lambda expression"))
19841 (t "???"))
19842 (cond
19843 ((stringp match)
19844 (org-add-props match nil 'face 'org-warning))
19845 (match
19846 (format "set of %d commands" (length match)))
19847 (t ""))))))
19848 (when prefixes
19849 (mapc (lambda (x)
19850 (insert
19851 (format "\n%s %s"
19852 (org-add-props (char-to-string x)
19853 nil 'face 'bold)
19854 (or (cdr (assoc (concat selstring (char-to-string x))
19855 prefix-descriptions))
19856 "Prefix key"))))
19857 prefixes))
19858 (goto-char (point-min))
19859 (when (fboundp 'fit-window-to-buffer)
19860 (if second-time
19861 (if (not (pos-visible-in-window-p (point-max)))
19862 (fit-window-to-buffer))
19863 (setq second-time t)
19864 (fit-window-to-buffer)))
19865 (message "Press key for agenda command%s:"
19866 (if (or restrict-ok org-agenda-overriding-restriction)
19867 (if org-agenda-overriding-restriction
19868 " (restriction lock active)"
19869 (if restriction
19870 (format " (restricted to %s)" restriction)
19871 " (unrestricted)"))
19872 ""))
19873 (setq c (read-char-exclusive))
19874 (message "")
19875 (cond
19876 ((assoc (char-to-string c) custom)
19877 (setq selstring (concat selstring (char-to-string c)))
19878 (throw 'exit (cons selstring restriction)))
19879 ((memq c prefixes)
19880 (setq selstring (concat selstring (char-to-string c))
19881 prefixes nil
19882 rmheader (or rmheader t)
19883 custom (delq nil (mapcar
19884 (lambda (x)
19885 (if (or (= (length (car x)) 1)
19886 (/= (string-to-char (car x)) c))
19888 (cons (substring (car x) 1) (cdr x))))
19889 custom))))
19890 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19891 (message "Restriction is only possible in Org-mode buffers")
19892 (ding) (sit-for 1))
19893 ((eq c ?1)
19894 (org-agenda-remove-restriction-lock 'noupdate)
19895 (setq restriction 'buffer))
19896 ((eq c ?0)
19897 (org-agenda-remove-restriction-lock 'noupdate)
19898 (setq restriction (if region-p 'region 'subtree)))
19899 ((eq c ?<)
19900 (org-agenda-remove-restriction-lock 'noupdate)
19901 (setq restriction
19902 (cond
19903 ((eq restriction 'buffer)
19904 (if region-p 'region 'subtree))
19905 ((memq restriction '(subtree region))
19906 nil)
19907 (t 'buffer))))
19908 ((eq c ?>)
19909 (org-agenda-remove-restriction-lock 'noupdate)
19910 (setq restriction nil))
19911 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19912 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19913 ((and (> (length selstring) 0) (eq c ?\d))
19914 (delete-window)
19915 (org-agenda-get-restriction-and-command prefix-descriptions))
19917 ((equal c ?q) (error "Abort"))
19918 (t (error "Invalid key %c" c))))))))
19920 (defun org-run-agenda-series (name series)
19921 (org-prepare-agenda name)
19922 (let* ((org-agenda-multi t)
19923 (redo (list 'org-run-agenda-series name (list 'quote series)))
19924 (cmds (car series))
19925 (gprops (nth 1 series))
19926 match ;; The byte compiler incorrectly complains about this. Keep it!
19927 cmd type lprops)
19928 (while (setq cmd (pop cmds))
19929 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19930 (cond
19931 ((eq type 'agenda)
19932 (org-let2 gprops lprops
19933 '(call-interactively 'org-agenda-list)))
19934 ((eq type 'alltodo)
19935 (org-let2 gprops lprops
19936 '(call-interactively 'org-todo-list)))
19937 ((eq type 'stuck)
19938 (org-let2 gprops lprops
19939 '(call-interactively 'org-agenda-list-stuck-projects)))
19940 ((eq type 'tags)
19941 (org-let2 gprops lprops
19942 '(org-tags-view current-prefix-arg match)))
19943 ((eq type 'tags-todo)
19944 (org-let2 gprops lprops
19945 '(org-tags-view '(4) match)))
19946 ((eq type 'todo)
19947 (org-let2 gprops lprops
19948 '(org-todo-list match)))
19949 ((fboundp type)
19950 (org-let2 gprops lprops
19951 '(funcall type match)))
19952 (t (error "Invalid type in command series"))))
19953 (widen)
19954 (setq org-agenda-redo-command redo)
19955 (goto-char (point-min)))
19956 (org-finalize-agenda))
19958 ;;;###autoload
19959 (defmacro org-batch-agenda (cmd-key &rest parameters)
19960 "Run an agenda command in batch mode and send the result to STDOUT.
19961 If CMD-KEY is a string of length 1, it is used as a key in
19962 `org-agenda-custom-commands' and triggers this command. If it is a
19963 longer string it is used as a tags/todo match string.
19964 Paramters are alternating variable names and values that will be bound
19965 before running the agenda command."
19966 (let (pars)
19967 (while parameters
19968 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19969 (if (> (length cmd-key) 2)
19970 (eval (list 'let (nreverse pars)
19971 (list 'org-tags-view nil cmd-key)))
19972 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19973 (set-buffer org-agenda-buffer-name)
19974 (princ (org-encode-for-stdout (buffer-string)))))
19976 (defun org-encode-for-stdout (string)
19977 (if (fboundp 'encode-coding-string)
19978 (encode-coding-string string buffer-file-coding-system)
19979 string))
19981 (defvar org-agenda-info nil)
19983 ;;;###autoload
19984 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19985 "Run an agenda command in batch mode and send the result to STDOUT.
19986 If CMD-KEY is a string of length 1, it is used as a key in
19987 `org-agenda-custom-commands' and triggers this command. If it is a
19988 longer string it is used as a tags/todo match string.
19989 Paramters are alternating variable names and values that will be bound
19990 before running the agenda command.
19992 The output gives a line for each selected agenda item. Each
19993 item is a list of comma-separated values, like this:
19995 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19997 category The category of the item
19998 head The headline, without TODO kwd, TAGS and PRIORITY
19999 type The type of the agenda entry, can be
20000 todo selected in TODO match
20001 tagsmatch selected in tags match
20002 diary imported from diary
20003 deadline a deadline on given date
20004 scheduled scheduled on given date
20005 timestamp entry has timestamp on given date
20006 closed entry was closed on given date
20007 upcoming-deadline warning about deadline
20008 past-scheduled forwarded scheduled item
20009 block entry has date block including g. date
20010 todo The todo keyword, if any
20011 tags All tags including inherited ones, separated by colons
20012 date The relevant date, like 2007-2-14
20013 time The time, like 15:00-16:50
20014 extra Sting with extra planning info
20015 priority-l The priority letter if any was given
20016 priority-n The computed numerical priority
20017 agenda-day The day in the agenda where this is listed"
20019 (let (pars)
20020 (while parameters
20021 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20022 (push (list 'org-agenda-remove-tags t) pars)
20023 (if (> (length cmd-key) 2)
20024 (eval (list 'let (nreverse pars)
20025 (list 'org-tags-view nil cmd-key)))
20026 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20027 (set-buffer org-agenda-buffer-name)
20028 (let* ((lines (org-split-string (buffer-string) "\n"))
20029 line)
20030 (while (setq line (pop lines))
20031 (catch 'next
20032 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20033 (setq org-agenda-info
20034 (org-fix-agenda-info (text-properties-at 0 line)))
20035 (princ
20036 (org-encode-for-stdout
20037 (mapconcat 'org-agenda-export-csv-mapper
20038 '(org-category txt type todo tags date time-of-day extra
20039 priority-letter priority agenda-day)
20040 ",")))
20041 (princ "\n"))))))
20043 (defun org-fix-agenda-info (props)
20044 "Make sure all properties on an agenda item have a canonical form,
20045 so the export commands can easily use it."
20046 (let (tmp re)
20047 (when (setq tmp (plist-get props 'tags))
20048 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20049 (when (setq tmp (plist-get props 'date))
20050 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20051 (let ((calendar-date-display-form '(year "-" month "-" day)))
20052 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20054 (setq tmp (calendar-date-string tmp)))
20055 (setq props (plist-put props 'date tmp)))
20056 (when (setq tmp (plist-get props 'day))
20057 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20058 (let ((calendar-date-display-form '(year "-" month "-" day)))
20059 (setq tmp (calendar-date-string tmp)))
20060 (setq props (plist-put props 'day tmp))
20061 (setq props (plist-put props 'agenda-day tmp)))
20062 (when (setq tmp (plist-get props 'txt))
20063 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20064 (plist-put props 'priority-letter (match-string 1 tmp))
20065 (setq tmp (replace-match "" t t tmp)))
20066 (when (and (setq re (plist-get props 'org-todo-regexp))
20067 (setq re (concat "\\`\\.*" re " ?"))
20068 (string-match re tmp))
20069 (plist-put props 'todo (match-string 1 tmp))
20070 (setq tmp (replace-match "" t t tmp)))
20071 (plist-put props 'txt tmp)))
20072 props)
20074 (defun org-agenda-export-csv-mapper (prop)
20075 (let ((res (plist-get org-agenda-info prop)))
20076 (setq res
20077 (cond
20078 ((not res) "")
20079 ((stringp res) res)
20080 (t (prin1-to-string res))))
20081 (while (string-match "," res)
20082 (setq res (replace-match ";" t t res)))
20083 (org-trim res)))
20086 ;;;###autoload
20087 (defun org-store-agenda-views (&rest parameters)
20088 (interactive)
20089 (eval (list 'org-batch-store-agenda-views)))
20091 ;; FIXME, why is this a macro?????
20092 ;;;###autoload
20093 (defmacro org-batch-store-agenda-views (&rest parameters)
20094 "Run all custom agenda commands that have a file argument."
20095 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20096 (pop-up-frames nil)
20097 (dir default-directory)
20098 pars cmd thiscmdkey files opts)
20099 (while parameters
20100 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20101 (setq pars (reverse pars))
20102 (save-window-excursion
20103 (while cmds
20104 (setq cmd (pop cmds)
20105 thiscmdkey (car cmd)
20106 opts (nth 4 cmd)
20107 files (nth 5 cmd))
20108 (if (stringp files) (setq files (list files)))
20109 (when files
20110 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20111 (list 'org-agenda nil thiscmdkey)))
20112 (set-buffer org-agenda-buffer-name)
20113 (while files
20114 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20115 (list 'org-write-agenda
20116 (expand-file-name (pop files) dir) t))))
20117 (and (get-buffer org-agenda-buffer-name)
20118 (kill-buffer org-agenda-buffer-name)))))))
20120 (defun org-write-agenda (file &optional nosettings)
20121 "Write the current buffer (an agenda view) as a file.
20122 Depending on the extension of the file name, plain text (.txt),
20123 HTML (.html or .htm) or Postscript (.ps) is produced.
20124 If NOSETTINGS is given, do not scope the settings of
20125 `org-agenda-exporter-settings' into the export commands. This is used when
20126 the settings have already been scoped and we do not wish to overrule other,
20127 higher priority settings."
20128 (interactive "FWrite agenda to file: ")
20129 (if (not (file-writable-p file))
20130 (error "Cannot write agenda to file %s" file))
20131 (cond
20132 ((string-match "\\.html?\\'" file) (require 'htmlize))
20133 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20134 (org-let (if nosettings nil org-agenda-exporter-settings)
20135 '(save-excursion
20136 (save-window-excursion
20137 (cond
20138 ((string-match "\\.html?\\'" file)
20139 (set-buffer (htmlize-buffer (current-buffer)))
20141 (when (and org-agenda-export-html-style
20142 (string-match "<style>" org-agenda-export-html-style))
20143 ;; replace <style> section with org-agenda-export-html-style
20144 (goto-char (point-min))
20145 (kill-region (- (search-forward "<style") 6)
20146 (search-forward "</style>"))
20147 (insert org-agenda-export-html-style))
20148 (write-file file)
20149 (kill-buffer (current-buffer))
20150 (message "HTML written to %s" file))
20151 ((string-match "\\.ps\\'" file)
20152 (ps-print-buffer-with-faces file)
20153 (message "Postscript written to %s" file))
20155 (let ((bs (buffer-string)))
20156 (find-file file)
20157 (insert bs)
20158 (save-buffer 0)
20159 (kill-buffer (current-buffer))
20160 (message "Plain text written to %s" file))))))
20161 (set-buffer org-agenda-buffer-name)))
20163 (defmacro org-no-read-only (&rest body)
20164 "Inhibit read-only for BODY."
20165 `(let ((inhibit-read-only t)) ,@body))
20167 (defun org-check-for-org-mode ()
20168 "Make sure current buffer is in org-mode. Error if not."
20169 (or (org-mode-p)
20170 (error "Cannot execute org-mode agenda command on buffer in %s."
20171 major-mode)))
20173 (defun org-fit-agenda-window ()
20174 "Fit the window to the buffer size."
20175 (and (memq org-agenda-window-setup '(reorganize-frame))
20176 (fboundp 'fit-window-to-buffer)
20177 (fit-window-to-buffer
20179 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20180 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20182 ;;; Agenda file list
20184 (defun org-agenda-files (&optional unrestricted)
20185 "Get the list of agenda files.
20186 Optional UNRESTRICTED means return the full list even if a restriction
20187 is currently in place."
20188 (let ((files
20189 (cond
20190 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20191 ((stringp org-agenda-files) (org-read-agenda-file-list))
20192 ((listp org-agenda-files) org-agenda-files)
20193 (t (error "Invalid value of `org-agenda-files'")))))
20194 (setq files (apply 'append
20195 (mapcar (lambda (f)
20196 (if (file-directory-p f)
20197 (directory-files f t
20198 org-agenda-file-regexp)
20199 (list f)))
20200 files)))
20201 (if org-agenda-skip-unavailable-files
20202 (delq nil
20203 (mapcar (function
20204 (lambda (file)
20205 (and (file-readable-p file) file)))
20206 files))
20207 files))) ; `org-check-agenda-file' will remove them from the list
20209 (defun org-edit-agenda-file-list ()
20210 "Edit the list of agenda files.
20211 Depending on setup, this either uses customize to edit the variable
20212 `org-agenda-files', or it visits the file that is holding the list. In the
20213 latter case, the buffer is set up in a way that saving it automatically kills
20214 the buffer and restores the previous window configuration."
20215 (interactive)
20216 (if (stringp org-agenda-files)
20217 (let ((cw (current-window-configuration)))
20218 (find-file org-agenda-files)
20219 (org-set-local 'org-window-configuration cw)
20220 (org-add-hook 'after-save-hook
20221 (lambda ()
20222 (set-window-configuration
20223 (prog1 org-window-configuration
20224 (kill-buffer (current-buffer))))
20225 (org-install-agenda-files-menu)
20226 (message "New agenda file list installed"))
20227 nil 'local)
20228 (message "%s" (substitute-command-keys
20229 "Edit list and finish with \\[save-buffer]")))
20230 (customize-variable 'org-agenda-files)))
20232 (defun org-store-new-agenda-file-list (list)
20233 "Set new value for the agenda file list and save it correcly."
20234 (if (stringp org-agenda-files)
20235 (let ((f org-agenda-files) b)
20236 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20237 (with-temp-file f
20238 (insert (mapconcat 'identity list "\n") "\n")))
20239 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20240 (setq org-agenda-files list)
20241 (customize-save-variable 'org-agenda-files org-agenda-files))))
20243 (defun org-read-agenda-file-list ()
20244 "Read the list of agenda files from a file."
20245 (when (stringp org-agenda-files)
20246 (with-temp-buffer
20247 (insert-file-contents org-agenda-files)
20248 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20251 ;;;###autoload
20252 (defun org-cycle-agenda-files ()
20253 "Cycle through the files in `org-agenda-files'.
20254 If the current buffer visits an agenda file, find the next one in the list.
20255 If the current buffer does not, find the first agenda file."
20256 (interactive)
20257 (let* ((fs (org-agenda-files t))
20258 (files (append fs (list (car fs))))
20259 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20260 file)
20261 (unless files (error "No agenda files"))
20262 (catch 'exit
20263 (while (setq file (pop files))
20264 (if (equal (file-truename file) tcf)
20265 (when (car files)
20266 (find-file (car files))
20267 (throw 'exit t))))
20268 (find-file (car fs)))
20269 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20271 (defun org-agenda-file-to-front (&optional to-end)
20272 "Move/add the current file to the top of the agenda file list.
20273 If the file is not present in the list, it is added to the front. If it is
20274 present, it is moved there. With optional argument TO-END, add/move to the
20275 end of the list."
20276 (interactive "P")
20277 (let ((org-agenda-skip-unavailable-files nil)
20278 (file-alist (mapcar (lambda (x)
20279 (cons (file-truename x) x))
20280 (org-agenda-files t)))
20281 (ctf (file-truename buffer-file-name))
20282 x had)
20283 (setq x (assoc ctf file-alist) had x)
20285 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20286 (if to-end
20287 (setq file-alist (append (delq x file-alist) (list x)))
20288 (setq file-alist (cons x (delq x file-alist))))
20289 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20290 (org-install-agenda-files-menu)
20291 (message "File %s to %s of agenda file list"
20292 (if had "moved" "added") (if to-end "end" "front"))))
20294 (defun org-remove-file (&optional file)
20295 "Remove current file from the list of files in variable `org-agenda-files'.
20296 These are the files which are being checked for agenda entries.
20297 Optional argument FILE means, use this file instead of the current."
20298 (interactive)
20299 (let* ((org-agenda-skip-unavailable-files nil)
20300 (file (or file buffer-file-name))
20301 (true-file (file-truename file))
20302 (afile (abbreviate-file-name file))
20303 (files (delq nil (mapcar
20304 (lambda (x)
20305 (if (equal true-file
20306 (file-truename x))
20307 nil x))
20308 (org-agenda-files t)))))
20309 (if (not (= (length files) (length (org-agenda-files t))))
20310 (progn
20311 (org-store-new-agenda-file-list files)
20312 (org-install-agenda-files-menu)
20313 (message "Removed file: %s" afile))
20314 (message "File was not in list: %s (not removed)" afile))))
20316 (defun org-file-menu-entry (file)
20317 (vector file (list 'find-file file) t))
20319 (defun org-check-agenda-file (file)
20320 "Make sure FILE exists. If not, ask user what to do."
20321 (when (not (file-exists-p file))
20322 (message "non-existent file %s. [R]emove from list or [A]bort?"
20323 (abbreviate-file-name file))
20324 (let ((r (downcase (read-char-exclusive))))
20325 (cond
20326 ((equal r ?r)
20327 (org-remove-file file)
20328 (throw 'nextfile t))
20329 (t (error "Abort"))))))
20331 ;;; Agenda prepare and finalize
20333 (defvar org-agenda-multi nil) ; dynammically scoped
20334 (defvar org-agenda-buffer-name "*Org Agenda*")
20335 (defvar org-pre-agenda-window-conf nil)
20336 (defvar org-agenda-name nil)
20337 (defun org-prepare-agenda (&optional name)
20338 (setq org-todo-keywords-for-agenda nil)
20339 (setq org-done-keywords-for-agenda nil)
20340 (if org-agenda-multi
20341 (progn
20342 (setq buffer-read-only nil)
20343 (goto-char (point-max))
20344 (unless (or (bobp) org-agenda-compact-blocks)
20345 (insert "\n" (make-string (window-width) ?=) "\n"))
20346 (narrow-to-region (point) (point-max)))
20347 (org-agenda-reset-markers)
20348 (org-prepare-agenda-buffers (org-agenda-files))
20349 (setq org-todo-keywords-for-agenda
20350 (org-uniquify org-todo-keywords-for-agenda))
20351 (setq org-done-keywords-for-agenda
20352 (org-uniquify org-done-keywords-for-agenda))
20353 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20354 (awin (get-buffer-window abuf)))
20355 (cond
20356 ((equal (current-buffer) abuf) nil)
20357 (awin (select-window awin))
20358 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20359 ((equal org-agenda-window-setup 'current-window)
20360 (switch-to-buffer abuf))
20361 ((equal org-agenda-window-setup 'other-window)
20362 (org-switch-to-buffer-other-window abuf))
20363 ((equal org-agenda-window-setup 'other-frame)
20364 (switch-to-buffer-other-frame abuf))
20365 ((equal org-agenda-window-setup 'reorganize-frame)
20366 (delete-other-windows)
20367 (org-switch-to-buffer-other-window abuf))))
20368 (setq buffer-read-only nil)
20369 (erase-buffer)
20370 (org-agenda-mode)
20371 (and name (not org-agenda-name)
20372 (org-set-local 'org-agenda-name name)))
20373 (setq buffer-read-only nil))
20375 (defun org-finalize-agenda ()
20376 "Finishing touch for the agenda buffer, called just before displaying it."
20377 (unless org-agenda-multi
20378 (save-excursion
20379 (let ((inhibit-read-only t))
20380 (goto-char (point-min))
20381 (while (org-activate-bracket-links (point-max))
20382 (add-text-properties (match-beginning 0) (match-end 0)
20383 '(face org-link)))
20384 (org-agenda-align-tags)
20385 (unless org-agenda-with-colors
20386 (remove-text-properties (point-min) (point-max) '(face nil))))
20387 (if (and (boundp 'org-overriding-columns-format)
20388 org-overriding-columns-format)
20389 (org-set-local 'org-overriding-columns-format
20390 org-overriding-columns-format))
20391 (if (and (boundp 'org-agenda-view-columns-initially)
20392 org-agenda-view-columns-initially)
20393 (org-agenda-columns))
20394 (when org-agenda-fontify-priorities
20395 (org-fontify-priorities))
20396 (run-hooks 'org-finalize-agenda-hook)
20397 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20400 (defun org-fontify-priorities ()
20401 "Make highest priority lines bold, and lowest italic."
20402 (interactive)
20403 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20404 (org-delete-overlay o)))
20405 (org-overlays-in (point-min) (point-max)))
20406 (save-excursion
20407 (let ((inhibit-read-only t)
20408 b e p ov h l)
20409 (goto-char (point-min))
20410 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20411 (setq h (or (get-char-property (point) 'org-highest-priority)
20412 org-highest-priority)
20413 l (or (get-char-property (point) 'org-lowest-priority)
20414 org-lowest-priority)
20415 p (string-to-char (match-string 1))
20416 b (match-beginning 0) e (point-at-eol)
20417 ov (org-make-overlay b e))
20418 (org-overlay-put
20419 ov 'face
20420 (cond ((listp org-agenda-fontify-priorities)
20421 (cdr (assoc p org-agenda-fontify-priorities)))
20422 ((equal p l) 'italic)
20423 ((equal p h) 'bold)))
20424 (org-overlay-put ov 'org-type 'org-priority)))))
20426 (defun org-prepare-agenda-buffers (files)
20427 "Create buffers for all agenda files, protect archived trees and comments."
20428 (interactive)
20429 (let ((pa '(:org-archived t))
20430 (pc '(:org-comment t))
20431 (pall '(:org-archived t :org-comment t))
20432 (inhibit-read-only t)
20433 (rea (concat ":" org-archive-tag ":"))
20434 bmp file re)
20435 (save-excursion
20436 (save-restriction
20437 (while (setq file (pop files))
20438 (if (bufferp file)
20439 (set-buffer file)
20440 (org-check-agenda-file file)
20441 (set-buffer (org-get-agenda-file-buffer file)))
20442 (widen)
20443 (setq bmp (buffer-modified-p))
20444 (org-refresh-category-properties)
20445 (setq org-todo-keywords-for-agenda
20446 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20447 (setq org-done-keywords-for-agenda
20448 (append org-done-keywords-for-agenda org-done-keywords))
20449 (save-excursion
20450 (remove-text-properties (point-min) (point-max) pall)
20451 (when org-agenda-skip-archived-trees
20452 (goto-char (point-min))
20453 (while (re-search-forward rea nil t)
20454 (if (org-on-heading-p t)
20455 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20456 (goto-char (point-min))
20457 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20458 (while (re-search-forward re nil t)
20459 (add-text-properties
20460 (match-beginning 0) (org-end-of-subtree t) pc)))
20461 (set-buffer-modified-p bmp))))))
20463 (defvar org-agenda-skip-function nil
20464 "Function to be called at each match during agenda construction.
20465 If this function returns nil, the current match should not be skipped.
20466 Otherwise, the function must return a position from where the search
20467 should be continued.
20468 This may also be a Lisp form, it will be evaluated.
20469 Never set this variable using `setq' or so, because then it will apply
20470 to all future agenda commands. Instead, bind it with `let' to scope
20471 it dynamically into the agenda-constructing command. A good way to set
20472 it is through options in org-agenda-custom-commands.")
20474 (defun org-agenda-skip ()
20475 "Throw to `:skip' in places that should be skipped.
20476 Also moves point to the end of the skipped region, so that search can
20477 continue from there."
20478 (let ((p (point-at-bol)) to fp)
20479 (and org-agenda-skip-archived-trees
20480 (get-text-property p :org-archived)
20481 (org-end-of-subtree t)
20482 (throw :skip t))
20483 (and (get-text-property p :org-comment)
20484 (org-end-of-subtree t)
20485 (throw :skip t))
20486 (if (equal (char-after p) ?#) (throw :skip t))
20487 (when (and (or (setq fp (functionp org-agenda-skip-function))
20488 (consp org-agenda-skip-function))
20489 (setq to (save-excursion
20490 (save-match-data
20491 (if fp
20492 (funcall org-agenda-skip-function)
20493 (eval org-agenda-skip-function))))))
20494 (goto-char to)
20495 (throw :skip t))))
20497 (defvar org-agenda-markers nil
20498 "List of all currently active markers created by `org-agenda'.")
20499 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20500 "Creation time of the last agenda marker.")
20502 (defun org-agenda-new-marker (&optional pos)
20503 "Return a new agenda marker.
20504 Org-mode keeps a list of these markers and resets them when they are
20505 no longer in use."
20506 (let ((m (copy-marker (or pos (point)))))
20507 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20508 (push m org-agenda-markers)
20511 (defun org-agenda-reset-markers ()
20512 "Reset markers created by `org-agenda'."
20513 (while org-agenda-markers
20514 (move-marker (pop org-agenda-markers) nil)))
20516 (defun org-get-agenda-file-buffer (file)
20517 "Get a buffer visiting FILE. If the buffer needs to be created, add
20518 it to the list of buffers which might be released later."
20519 (let ((buf (org-find-base-buffer-visiting file)))
20520 (if buf
20521 buf ; just return it
20522 ;; Make a new buffer and remember it
20523 (setq buf (find-file-noselect file))
20524 (if buf (push buf org-agenda-new-buffers))
20525 buf)))
20527 (defun org-release-buffers (blist)
20528 "Release all buffers in list, asking the user for confirmation when needed.
20529 When a buffer is unmodified, it is just killed. When modified, it is saved
20530 \(if the user agrees) and then killed."
20531 (let (buf file)
20532 (while (setq buf (pop blist))
20533 (setq file (buffer-file-name buf))
20534 (when (and (buffer-modified-p buf)
20535 file
20536 (y-or-n-p (format "Save file %s? " file)))
20537 (with-current-buffer buf (save-buffer)))
20538 (kill-buffer buf))))
20540 (defun org-get-category (&optional pos)
20541 "Get the category applying to position POS."
20542 (get-text-property (or pos (point)) 'org-category))
20544 ;;; Agenda timeline
20546 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20548 (defun org-timeline (&optional include-all)
20549 "Show a time-sorted view of the entries in the current org file.
20550 Only entries with a time stamp of today or later will be listed. With
20551 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20552 under the current date.
20553 If the buffer contains an active region, only check the region for
20554 dates."
20555 (interactive "P")
20556 (require 'calendar)
20557 (org-compile-prefix-format 'timeline)
20558 (org-set-sorting-strategy 'timeline)
20559 (let* ((dopast t)
20560 (dotodo include-all)
20561 (doclosed org-agenda-show-log)
20562 (entry buffer-file-name)
20563 (date (calendar-current-date))
20564 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20565 (end (if (org-region-active-p) (region-end) (point-max)))
20566 (day-numbers (org-get-all-dates beg end 'no-ranges
20567 t doclosed ; always include today
20568 org-timeline-show-empty-dates))
20569 (org-deadline-warning-days 0)
20570 (org-agenda-only-exact-dates t)
20571 (today (time-to-days (current-time)))
20572 (past t)
20573 args
20574 s e rtn d emptyp)
20575 (setq org-agenda-redo-command
20576 (list 'progn
20577 (list 'org-switch-to-buffer-other-window (current-buffer))
20578 (list 'org-timeline (list 'quote include-all))))
20579 (if (not dopast)
20580 ;; Remove past dates from the list of dates.
20581 (setq day-numbers (delq nil (mapcar (lambda(x)
20582 (if (>= x today) x nil))
20583 day-numbers))))
20584 (org-prepare-agenda (concat "Timeline "
20585 (file-name-nondirectory buffer-file-name)))
20586 (if doclosed (push :closed args))
20587 (push :timestamp args)
20588 (push :deadline args)
20589 (push :scheduled args)
20590 (push :sexp args)
20591 (if dotodo (push :todo args))
20592 (while (setq d (pop day-numbers))
20593 (if (and (listp d) (eq (car d) :omitted))
20594 (progn
20595 (setq s (point))
20596 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20597 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20598 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20599 (if (and (>= d today)
20600 dopast
20601 past)
20602 (progn
20603 (setq past nil)
20604 (insert (make-string 79 ?-) "\n")))
20605 (setq date (calendar-gregorian-from-absolute d))
20606 (setq s (point))
20607 (setq rtn (and (not emptyp)
20608 (apply 'org-agenda-get-day-entries entry
20609 date args)))
20610 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20611 (progn
20612 (insert
20613 (if (stringp org-agenda-format-date)
20614 (format-time-string org-agenda-format-date
20615 (org-time-from-absolute date))
20616 (funcall org-agenda-format-date date))
20617 "\n")
20618 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20619 (put-text-property s (1- (point)) 'org-date-line t)
20620 (if (equal d today)
20621 (put-text-property s (1- (point)) 'org-today t))
20622 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20623 (put-text-property s (1- (point)) 'day d)))))
20624 (goto-char (point-min))
20625 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20626 (point-min)))
20627 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20628 (org-finalize-agenda)
20629 (setq buffer-read-only t)))
20631 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20632 "Return a list of all relevant day numbers from BEG to END buffer positions.
20633 If NO-RANGES is non-nil, include only the start and end dates of a range,
20634 not every single day in the range. If FORCE-TODAY is non-nil, make
20635 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20636 inactive time stamps (those in square brackets) are included.
20637 When EMPTY is non-nil, also include days without any entries."
20638 (let ((re (concat
20639 (if pre-re pre-re "")
20640 (if inactive org-ts-regexp-both org-ts-regexp)))
20641 dates dates1 date day day1 day2 ts1 ts2)
20642 (if force-today
20643 (setq dates (list (time-to-days (current-time)))))
20644 (save-excursion
20645 (goto-char beg)
20646 (while (re-search-forward re end t)
20647 (setq day (time-to-days (org-time-string-to-time
20648 (substring (match-string 1) 0 10))))
20649 (or (memq day dates) (push day dates)))
20650 (unless no-ranges
20651 (goto-char beg)
20652 (while (re-search-forward org-tr-regexp end t)
20653 (setq ts1 (substring (match-string 1) 0 10)
20654 ts2 (substring (match-string 2) 0 10)
20655 day1 (time-to-days (org-time-string-to-time ts1))
20656 day2 (time-to-days (org-time-string-to-time ts2)))
20657 (while (< (setq day1 (1+ day1)) day2)
20658 (or (memq day1 dates) (push day1 dates)))))
20659 (setq dates (sort dates '<))
20660 (when empty
20661 (while (setq day (pop dates))
20662 (setq day2 (car dates))
20663 (push day dates1)
20664 (when (and day2 empty)
20665 (if (or (eq empty t)
20666 (and (numberp empty) (<= (- day2 day) empty)))
20667 (while (< (setq day (1+ day)) day2)
20668 (push (list day) dates1))
20669 (push (cons :omitted (- day2 day)) dates1))))
20670 (setq dates (nreverse dates1)))
20671 dates)))
20673 ;;; Agenda Daily/Weekly
20675 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20676 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20677 (defvar org-agenda-last-arguments nil
20678 "The arguments of the previous call to org-agenda")
20679 (defvar org-starting-day nil) ; local variable in the agenda buffer
20680 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20681 (defvar org-include-all-loc nil) ; local variable
20682 (defvar org-agenda-remove-date nil) ; dynamically scoped
20684 ;;;###autoload
20685 (defun org-agenda-list (&optional include-all start-day ndays)
20686 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20687 The view will be for the current day or week, but from the overview buffer
20688 you will be able to go to other days/weeks.
20690 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20691 all unfinished TODO items will also be shown, before the agenda.
20692 This feature is considered obsolete, please use the TODO list or a block
20693 agenda instead.
20695 With a numeric prefix argument in an interactive call, the agenda will
20696 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20697 the number of days. NDAYS defaults to `org-agenda-ndays'.
20699 START-DAY defaults to TODAY, or to the most recent match for the weekday
20700 given in `org-agenda-start-on-weekday'."
20701 (interactive "P")
20702 (if (and (integerp include-all) (> include-all 0))
20703 (setq ndays include-all include-all nil))
20704 (setq ndays (or ndays org-agenda-ndays)
20705 start-day (or start-day org-agenda-start-day))
20706 (if org-agenda-overriding-arguments
20707 (setq include-all (car org-agenda-overriding-arguments)
20708 start-day (nth 1 org-agenda-overriding-arguments)
20709 ndays (nth 2 org-agenda-overriding-arguments)))
20710 (if (stringp start-day)
20711 ;; Convert to an absolute day number
20712 (setq start-day (time-to-days (org-read-date nil t start-day))))
20713 (setq org-agenda-last-arguments (list include-all start-day ndays))
20714 (org-compile-prefix-format 'agenda)
20715 (org-set-sorting-strategy 'agenda)
20716 (require 'calendar)
20717 (let* ((org-agenda-start-on-weekday
20718 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20719 org-agenda-start-on-weekday nil))
20720 (thefiles (org-agenda-files))
20721 (files thefiles)
20722 (today (time-to-days
20723 (time-subtract (current-time)
20724 (list 0 (* 3600 org-extend-today-until) 0))))
20725 (sd (or start-day today))
20726 (start (if (or (null org-agenda-start-on-weekday)
20727 (< org-agenda-ndays 7))
20729 (let* ((nt (calendar-day-of-week
20730 (calendar-gregorian-from-absolute sd)))
20731 (n1 org-agenda-start-on-weekday)
20732 (d (- nt n1)))
20733 (- sd (+ (if (< d 0) 7 0) d)))))
20734 (day-numbers (list start))
20735 (day-cnt 0)
20736 (inhibit-redisplay (not debug-on-error))
20737 s e rtn rtnall file date d start-pos end-pos todayp nd)
20738 (setq org-agenda-redo-command
20739 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20740 ;; Make the list of days
20741 (setq ndays (or ndays org-agenda-ndays)
20742 nd ndays)
20743 (while (> ndays 1)
20744 (push (1+ (car day-numbers)) day-numbers)
20745 (setq ndays (1- ndays)))
20746 (setq day-numbers (nreverse day-numbers))
20747 (org-prepare-agenda "Day/Week")
20748 (org-set-local 'org-starting-day (car day-numbers))
20749 (org-set-local 'org-include-all-loc include-all)
20750 (org-set-local 'org-agenda-span
20751 (org-agenda-ndays-to-span nd))
20752 (when (and (or include-all org-agenda-include-all-todo)
20753 (member today day-numbers))
20754 (setq files thefiles
20755 rtnall nil)
20756 (while (setq file (pop files))
20757 (catch 'nextfile
20758 (org-check-agenda-file file)
20759 (setq date (calendar-gregorian-from-absolute today)
20760 rtn (org-agenda-get-day-entries
20761 file date :todo))
20762 (setq rtnall (append rtnall rtn))))
20763 (when rtnall
20764 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20765 (add-text-properties (point-min) (1- (point))
20766 (list 'face 'org-agenda-structure))
20767 (insert (org-finalize-agenda-entries rtnall) "\n")))
20768 (unless org-agenda-compact-blocks
20769 (setq s (point))
20770 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20771 "-agenda:\n")
20772 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20773 'org-date-line t)))
20774 (while (setq d (pop day-numbers))
20775 (setq date (calendar-gregorian-from-absolute d)
20776 s (point))
20777 (if (or (setq todayp (= d today))
20778 (and (not start-pos) (= d sd)))
20779 (setq start-pos (point))
20780 (if (and start-pos (not end-pos))
20781 (setq end-pos (point))))
20782 (setq files thefiles
20783 rtnall nil)
20784 (while (setq file (pop files))
20785 (catch 'nextfile
20786 (org-check-agenda-file file)
20787 (if org-agenda-show-log
20788 (setq rtn (org-agenda-get-day-entries
20789 file date
20790 :deadline :scheduled :timestamp :sexp :closed))
20791 (setq rtn (org-agenda-get-day-entries
20792 file date
20793 :deadline :scheduled :sexp :timestamp)))
20794 (setq rtnall (append rtnall rtn))))
20795 (if org-agenda-include-diary
20796 (progn
20797 (require 'diary-lib)
20798 (setq rtn (org-get-entries-from-diary date))
20799 (setq rtnall (append rtnall rtn))))
20800 (if (or rtnall org-agenda-show-all-dates)
20801 (progn
20802 (setq day-cnt (1+ day-cnt))
20803 (insert
20804 (if (stringp org-agenda-format-date)
20805 (format-time-string org-agenda-format-date
20806 (org-time-from-absolute date))
20807 (funcall org-agenda-format-date date))
20808 "\n")
20809 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20810 (put-text-property s (1- (point)) 'org-date-line t)
20811 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20812 (if todayp (put-text-property s (1- (point)) 'org-today t))
20813 (if rtnall (insert
20814 (org-finalize-agenda-entries
20815 (org-agenda-add-time-grid-maybe
20816 rtnall nd todayp))
20817 "\n"))
20818 (put-text-property s (1- (point)) 'day d)
20819 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20820 (goto-char (point-min))
20821 (org-fit-agenda-window)
20822 (unless (and (pos-visible-in-window-p (point-min))
20823 (pos-visible-in-window-p (point-max)))
20824 (goto-char (1- (point-max)))
20825 (recenter -1)
20826 (if (not (pos-visible-in-window-p (or start-pos 1)))
20827 (progn
20828 (goto-char (or start-pos 1))
20829 (recenter 1))))
20830 (goto-char (or start-pos 1))
20831 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20832 (org-finalize-agenda)
20833 (setq buffer-read-only t)
20834 (message "")))
20836 (defun org-agenda-ndays-to-span (n)
20837 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20839 ;;; Agenda TODO list
20841 (defvar org-select-this-todo-keyword nil)
20842 (defvar org-last-arg nil)
20844 ;;;###autoload
20845 (defun org-todo-list (arg)
20846 "Show all TODO entries from all agenda file in a single list.
20847 The prefix arg can be used to select a specific TODO keyword and limit
20848 the list to these. When using \\[universal-argument], you will be prompted
20849 for a keyword. A numeric prefix directly selects the Nth keyword in
20850 `org-todo-keywords-1'."
20851 (interactive "P")
20852 (require 'calendar)
20853 (org-compile-prefix-format 'todo)
20854 (org-set-sorting-strategy 'todo)
20855 (org-prepare-agenda "TODO")
20856 (let* ((today (time-to-days (current-time)))
20857 (date (calendar-gregorian-from-absolute today))
20858 (kwds org-todo-keywords-for-agenda)
20859 (completion-ignore-case t)
20860 (org-select-this-todo-keyword
20861 (if (stringp arg) arg
20862 (and arg (integerp arg) (> arg 0)
20863 (nth (1- arg) kwds))))
20864 rtn rtnall files file pos)
20865 (when (equal arg '(4))
20866 (setq org-select-this-todo-keyword
20867 (completing-read "Keyword (or KWD1|K2D2|...): "
20868 (mapcar 'list kwds) nil nil)))
20869 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20870 (org-set-local 'org-last-arg arg)
20871 (setq org-agenda-redo-command
20872 '(org-todo-list (or current-prefix-arg org-last-arg)))
20873 (setq files (org-agenda-files)
20874 rtnall nil)
20875 (while (setq file (pop files))
20876 (catch 'nextfile
20877 (org-check-agenda-file file)
20878 (setq rtn (org-agenda-get-day-entries file date :todo))
20879 (setq rtnall (append rtnall rtn))))
20880 (if org-agenda-overriding-header
20881 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20882 nil 'face 'org-agenda-structure) "\n")
20883 (insert "Global list of TODO items of type: ")
20884 (add-text-properties (point-min) (1- (point))
20885 (list 'face 'org-agenda-structure))
20886 (setq pos (point))
20887 (insert (or org-select-this-todo-keyword "ALL") "\n")
20888 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20889 (setq pos (point))
20890 (unless org-agenda-multi
20891 (insert "Available with `N r': (0)ALL")
20892 (let ((n 0) s)
20893 (mapc (lambda (x)
20894 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20895 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20896 (insert "\n "))
20897 (insert " " s))
20898 kwds))
20899 (insert "\n"))
20900 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20901 (when rtnall
20902 (insert (org-finalize-agenda-entries rtnall) "\n"))
20903 (goto-char (point-min))
20904 (org-fit-agenda-window)
20905 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20906 (org-finalize-agenda)
20907 (setq buffer-read-only t)))
20909 ;;; Agenda tags match
20911 ;;;###autoload
20912 (defun org-tags-view (&optional todo-only match)
20913 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20914 The prefix arg TODO-ONLY limits the search to TODO entries."
20915 (interactive "P")
20916 (org-compile-prefix-format 'tags)
20917 (org-set-sorting-strategy 'tags)
20918 (let* ((org-tags-match-list-sublevels
20919 (if todo-only t org-tags-match-list-sublevels))
20920 (completion-ignore-case t)
20921 rtn rtnall files file pos matcher
20922 buffer)
20923 (setq matcher (org-make-tags-matcher match)
20924 match (car matcher) matcher (cdr matcher))
20925 (org-prepare-agenda (concat "TAGS " match))
20926 (setq org-agenda-redo-command
20927 (list 'org-tags-view (list 'quote todo-only)
20928 (list 'if 'current-prefix-arg nil match)))
20929 (setq files (org-agenda-files)
20930 rtnall nil)
20931 (while (setq file (pop files))
20932 (catch 'nextfile
20933 (org-check-agenda-file file)
20934 (setq buffer (if (file-exists-p file)
20935 (org-get-agenda-file-buffer file)
20936 (error "No such file %s" file)))
20937 (if (not buffer)
20938 ;; If file does not exist, merror message to agenda
20939 (setq rtn (list
20940 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20941 rtnall (append rtnall rtn))
20942 (with-current-buffer buffer
20943 (unless (org-mode-p)
20944 (error "Agenda file %s is not in `org-mode'" file))
20945 (save-excursion
20946 (save-restriction
20947 (if org-agenda-restrict
20948 (narrow-to-region org-agenda-restrict-begin
20949 org-agenda-restrict-end)
20950 (widen))
20951 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20952 (setq rtnall (append rtnall rtn))))))))
20953 (if org-agenda-overriding-header
20954 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20955 nil 'face 'org-agenda-structure) "\n")
20956 (insert "Headlines with TAGS match: ")
20957 (add-text-properties (point-min) (1- (point))
20958 (list 'face 'org-agenda-structure))
20959 (setq pos (point))
20960 (insert match "\n")
20961 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20962 (setq pos (point))
20963 (unless org-agenda-multi
20964 (insert "Press `C-u r' to search again with new search string\n"))
20965 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20966 (when rtnall
20967 (insert (org-finalize-agenda-entries rtnall) "\n"))
20968 (goto-char (point-min))
20969 (org-fit-agenda-window)
20970 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20971 (org-finalize-agenda)
20972 (setq buffer-read-only t)))
20974 ;;; Agenda Finding stuck projects
20976 (defvar org-agenda-skip-regexp nil
20977 "Regular expression used in skipping subtrees for the agenda.
20978 This is basically a temporary global variable that can be set and then
20979 used by user-defined selections using `org-agenda-skip-function'.")
20981 (defvar org-agenda-overriding-header nil
20982 "When this is set during todo and tags searches, will replace header.")
20984 (defun org-agenda-skip-subtree-when-regexp-matches ()
20985 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20986 If yes, it returns the end position of this tree, causing agenda commands
20987 to skip this subtree. This is a function that can be put into
20988 `org-agenda-skip-function' for the duration of a command."
20989 (let ((end (save-excursion (org-end-of-subtree t)))
20990 skip)
20991 (save-excursion
20992 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20993 (and skip end)))
20995 (defun org-agenda-skip-entry-if (&rest conditions)
20996 "Skip entry if any of CONDITIONS is true.
20997 See `org-agenda-skip-if' for details."
20998 (org-agenda-skip-if nil conditions))
21000 (defun org-agenda-skip-subtree-if (&rest conditions)
21001 "Skip entry if any of CONDITIONS is true.
21002 See `org-agenda-skip-if' for details."
21003 (org-agenda-skip-if t conditions))
21005 (defun org-agenda-skip-if (subtree conditions)
21006 "Checks current entity for CONDITIONS.
21007 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21008 the entry, i.e. the text before the next heading is checked.
21010 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21011 from different tests. Valid conditions are:
21013 scheduled Check if there is a scheduled cookie
21014 notscheduled Check if there is no scheduled cookie
21015 deadline Check if there is a deadline
21016 notdeadline Check if there is no deadline
21017 regexp Check if regexp matches
21018 notregexp Check if regexp does not match.
21020 The regexp is taken from the conditions list, it must come right after
21021 the `regexp' or `notregexp' element.
21023 If any of these conditions is met, this function returns the end point of
21024 the entity, causing the search to continue from there. This is a function
21025 that can be put into `org-agenda-skip-function' for the duration of a command."
21026 (let (beg end m)
21027 (org-back-to-heading t)
21028 (setq beg (point)
21029 end (if subtree
21030 (progn (org-end-of-subtree t) (point))
21031 (progn (outline-next-heading) (1- (point)))))
21032 (goto-char beg)
21033 (and
21035 (and (memq 'scheduled conditions)
21036 (re-search-forward org-scheduled-time-regexp end t))
21037 (and (memq 'notscheduled conditions)
21038 (not (re-search-forward org-scheduled-time-regexp end t)))
21039 (and (memq 'deadline conditions)
21040 (re-search-forward org-deadline-time-regexp end t))
21041 (and (memq 'notdeadline conditions)
21042 (not (re-search-forward org-deadline-time-regexp end t)))
21043 (and (setq m (memq 'regexp conditions))
21044 (stringp (nth 1 m))
21045 (re-search-forward (nth 1 m) end t))
21046 (and (setq m (memq 'notregexp conditions))
21047 (stringp (nth 1 m))
21048 (not (re-search-forward (nth 1 m) end t))))
21049 end)))
21051 ;;;###autoload
21052 (defun org-agenda-list-stuck-projects (&rest ignore)
21053 "Create agenda view for projects that are stuck.
21054 Stuck projects are project that have no next actions. For the definitions
21055 of what a project is and how to check if it stuck, customize the variable
21056 `org-stuck-projects'.
21057 MATCH is being ignored."
21058 (interactive)
21059 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21060 ;; FIXME: we could have used org-agenda-skip-if here.
21061 (org-agenda-overriding-header "List of stuck projects: ")
21062 (matcher (nth 0 org-stuck-projects))
21063 (todo (nth 1 org-stuck-projects))
21064 (todo-wds (if (member "*" todo)
21065 (progn
21066 (org-prepare-agenda-buffers (org-agenda-files))
21067 (org-delete-all
21068 org-done-keywords-for-agenda
21069 (copy-sequence org-todo-keywords-for-agenda)))
21070 todo))
21071 (todo-re (concat "^\\*+[ \t]+\\("
21072 (mapconcat 'identity todo-wds "\\|")
21073 "\\)\\>"))
21074 (tags (nth 2 org-stuck-projects))
21075 (tags-re (if (member "*" tags)
21076 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21077 (concat "^\\*+ .*:\\("
21078 (mapconcat 'identity tags "\\|")
21079 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21080 (gen-re (nth 3 org-stuck-projects))
21081 (re-list
21082 (delq nil
21083 (list
21084 (if todo todo-re)
21085 (if tags tags-re)
21086 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21087 gen-re)))))
21088 (setq org-agenda-skip-regexp
21089 (if re-list
21090 (mapconcat 'identity re-list "\\|")
21091 (error "No information how to identify unstuck projects")))
21092 (org-tags-view nil matcher)
21093 (with-current-buffer org-agenda-buffer-name
21094 (setq org-agenda-redo-command
21095 '(org-agenda-list-stuck-projects
21096 (or current-prefix-arg org-last-arg))))))
21098 ;;; Diary integration
21100 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21102 (defun org-get-entries-from-diary (date)
21103 "Get the (Emacs Calendar) diary entries for DATE."
21104 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21105 (diary-display-hook '(fancy-diary-display))
21106 (pop-up-frames nil)
21107 (list-diary-entries-hook
21108 (cons 'org-diary-default-entry list-diary-entries-hook))
21109 (diary-file-name-prefix-function nil) ; turn this feature off
21110 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21111 entries
21112 (org-disable-agenda-to-diary t))
21113 (save-excursion
21114 (save-window-excursion
21115 (funcall (if (fboundp 'diary-list-entries)
21116 'diary-list-entries 'list-diary-entries)
21117 date 1)))
21118 (if (not (get-buffer fancy-diary-buffer))
21119 (setq entries nil)
21120 (with-current-buffer fancy-diary-buffer
21121 (setq buffer-read-only nil)
21122 (if (zerop (buffer-size))
21123 ;; No entries
21124 (setq entries nil)
21125 ;; Omit the date and other unnecessary stuff
21126 (org-agenda-cleanup-fancy-diary)
21127 ;; Add prefix to each line and extend the text properties
21128 (if (zerop (buffer-size))
21129 (setq entries nil)
21130 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21131 (set-buffer-modified-p nil)
21132 (kill-buffer fancy-diary-buffer)))
21133 (when entries
21134 (setq entries (org-split-string entries "\n"))
21135 (setq entries
21136 (mapcar
21137 (lambda (x)
21138 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21139 ;; Extend the text properties to the beginning of the line
21140 (org-add-props x (text-properties-at (1- (length x)) x)
21141 'type "diary" 'date date))
21142 entries)))))
21144 (defun org-agenda-cleanup-fancy-diary ()
21145 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21146 This gets rid of the date, the underline under the date, and
21147 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21148 date. It also removes lines that contain only whitespace."
21149 (goto-char (point-min))
21150 (if (looking-at ".*?:[ \t]*")
21151 (progn
21152 (replace-match "")
21153 (re-search-forward "\n=+$" nil t)
21154 (replace-match "")
21155 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21156 (re-search-forward "\n=+$" nil t)
21157 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21158 (goto-char (point-min))
21159 (while (re-search-forward "^ +\n" nil t)
21160 (replace-match ""))
21161 (goto-char (point-min))
21162 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21163 (replace-match "")))
21165 ;; Make sure entries from the diary have the right text properties.
21166 (eval-after-load "diary-lib"
21167 '(if (boundp 'diary-modify-entry-list-string-function)
21168 ;; We can rely on the hook, nothing to do
21170 ;; Hook not avaiable, must use advice to make this work
21171 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21172 "Make the position visible."
21173 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21174 (stringp string)
21175 buffer-file-name)
21176 (setq string (org-modify-diary-entry-string string))))))
21178 (defun org-modify-diary-entry-string (string)
21179 "Add text properties to string, allowing org-mode to act on it."
21180 (org-add-props string nil
21181 'mouse-face 'highlight
21182 'keymap org-agenda-keymap
21183 'help-echo (if buffer-file-name
21184 (format "mouse-2 or RET jump to diary file %s"
21185 (abbreviate-file-name buffer-file-name))
21187 'org-agenda-diary-link t
21188 'org-marker (org-agenda-new-marker (point-at-bol))))
21190 (defun org-diary-default-entry ()
21191 "Add a dummy entry to the diary.
21192 Needed to avoid empty dates which mess up holiday display."
21193 ;; Catch the error if dealing with the new add-to-diary-alist
21194 (when org-disable-agenda-to-diary
21195 (condition-case nil
21196 (add-to-diary-list original-date "Org-mode dummy" "")
21197 (error
21198 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21200 ;;;###autoload
21201 (defun org-diary (&rest args)
21202 "Return diary information from org-files.
21203 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21204 It accesses org files and extracts information from those files to be
21205 listed in the diary. The function accepts arguments specifying what
21206 items should be listed. The following arguments are allowed:
21208 :timestamp List the headlines of items containing a date stamp or
21209 date range matching the selected date. Deadlines will
21210 also be listed, on the expiration day.
21212 :sexp List entries resulting from diary-like sexps.
21214 :deadline List any deadlines past due, or due within
21215 `org-deadline-warning-days'. The listing occurs only
21216 in the diary for *today*, not at any other date. If
21217 an entry is marked DONE, it is no longer listed.
21219 :scheduled List all items which are scheduled for the given date.
21220 The diary for *today* also contains items which were
21221 scheduled earlier and are not yet marked DONE.
21223 :todo List all TODO items from the org-file. This may be a
21224 long list - so this is not turned on by default.
21225 Like deadlines, these entries only show up in the
21226 diary for *today*, not at any other date.
21228 The call in the diary file should look like this:
21230 &%%(org-diary) ~/path/to/some/orgfile.org
21232 Use a separate line for each org file to check. Or, if you omit the file name,
21233 all files listed in `org-agenda-files' will be checked automatically:
21235 &%%(org-diary)
21237 If you don't give any arguments (as in the example above), the default
21238 arguments (:deadline :scheduled :timestamp :sexp) are used.
21239 So the example above may also be written as
21241 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21243 The function expects the lisp variables `entry' and `date' to be provided
21244 by the caller, because this is how the calendar works. Don't use this
21245 function from a program - use `org-agenda-get-day-entries' instead."
21246 (when (> (- (time-to-seconds (current-time))
21247 org-agenda-last-marker-time)
21249 (org-agenda-reset-markers))
21250 (org-compile-prefix-format 'agenda)
21251 (org-set-sorting-strategy 'agenda)
21252 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21253 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21254 (list entry)
21255 (org-agenda-files t)))
21256 file rtn results)
21257 (org-prepare-agenda-buffers files)
21258 ;; If this is called during org-agenda, don't return any entries to
21259 ;; the calendar. Org Agenda will list these entries itself.
21260 (if org-disable-agenda-to-diary (setq files nil))
21261 (while (setq file (pop files))
21262 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21263 (setq results (append results rtn)))
21264 (if results
21265 (concat (org-finalize-agenda-entries results) "\n"))))
21267 ;;; Agenda entry finders
21269 (defun org-agenda-get-day-entries (file date &rest args)
21270 "Does the work for `org-diary' and `org-agenda'.
21271 FILE is the path to a file to be checked for entries. DATE is date like
21272 the one returned by `calendar-current-date'. ARGS are symbols indicating
21273 which kind of entries should be extracted. For details about these, see
21274 the documentation of `org-diary'."
21275 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21276 (let* ((org-startup-folded nil)
21277 (org-startup-align-all-tables nil)
21278 (buffer (if (file-exists-p file)
21279 (org-get-agenda-file-buffer file)
21280 (error "No such file %s" file)))
21281 arg results rtn)
21282 (if (not buffer)
21283 ;; If file does not exist, make sure an error message ends up in diary
21284 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21285 (with-current-buffer buffer
21286 (unless (org-mode-p)
21287 (error "Agenda file %s is not in `org-mode'" file))
21288 (let ((case-fold-search nil))
21289 (save-excursion
21290 (save-restriction
21291 (if org-agenda-restrict
21292 (narrow-to-region org-agenda-restrict-begin
21293 org-agenda-restrict-end)
21294 (widen))
21295 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21296 (while (setq arg (pop args))
21297 (cond
21298 ((and (eq arg :todo)
21299 (equal date (calendar-current-date)))
21300 (setq rtn (org-agenda-get-todos))
21301 (setq results (append results rtn)))
21302 ((eq arg :timestamp)
21303 (setq rtn (org-agenda-get-blocks))
21304 (setq results (append results rtn))
21305 (setq rtn (org-agenda-get-timestamps))
21306 (setq results (append results rtn)))
21307 ((eq arg :sexp)
21308 (setq rtn (org-agenda-get-sexps))
21309 (setq results (append results rtn)))
21310 ((eq arg :scheduled)
21311 (setq rtn (org-agenda-get-scheduled))
21312 (setq results (append results rtn)))
21313 ((eq arg :closed)
21314 (setq rtn (org-agenda-get-closed))
21315 (setq results (append results rtn)))
21316 ((eq arg :deadline)
21317 (setq rtn (org-agenda-get-deadlines))
21318 (setq results (append results rtn))))))))
21319 results))))
21321 (defun org-entry-is-todo-p ()
21322 (member (org-get-todo-state) org-not-done-keywords))
21324 (defun org-entry-is-done-p ()
21325 (member (org-get-todo-state) org-done-keywords))
21327 (defun org-get-todo-state ()
21328 (save-excursion
21329 (org-back-to-heading t)
21330 (and (looking-at org-todo-line-regexp)
21331 (match-end 2)
21332 (match-string 2))))
21334 (defun org-at-date-range-p (&optional inactive-ok)
21335 "Is the cursor inside a date range?"
21336 (interactive)
21337 (save-excursion
21338 (catch 'exit
21339 (let ((pos (point)))
21340 (skip-chars-backward "^[<\r\n")
21341 (skip-chars-backward "<[")
21342 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21343 (>= (match-end 0) pos)
21344 (throw 'exit t))
21345 (skip-chars-backward "^<[\r\n")
21346 (skip-chars-backward "<[")
21347 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21348 (>= (match-end 0) pos)
21349 (throw 'exit t)))
21350 nil)))
21352 (defun org-agenda-get-todos ()
21353 "Return the TODO information for agenda display."
21354 (let* ((props (list 'face nil
21355 'done-face 'org-done
21356 'org-not-done-regexp org-not-done-regexp
21357 'org-todo-regexp org-todo-regexp
21358 'mouse-face 'highlight
21359 'keymap org-agenda-keymap
21360 'help-echo
21361 (format "mouse-2 or RET jump to org file %s"
21362 (abbreviate-file-name buffer-file-name))))
21363 ;; FIXME: get rid of the \n at some point but watch out
21364 (regexp (concat "^\\*+[ \t]+\\("
21365 (if org-select-this-todo-keyword
21366 (if (equal org-select-this-todo-keyword "*")
21367 org-todo-regexp
21368 (concat "\\<\\("
21369 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21370 "\\)\\>"))
21371 org-not-done-regexp)
21372 "[^\n\r]*\\)"))
21373 marker priority category tags
21374 ee txt beg end)
21375 (goto-char (point-min))
21376 (while (re-search-forward regexp nil t)
21377 (catch :skip
21378 (save-match-data
21379 (beginning-of-line)
21380 (setq beg (point) end (progn (outline-next-heading) (point)))
21381 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21382 (re-search-forward org-ts-regexp end t))
21383 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21384 (re-search-forward org-scheduled-time-regexp end t))
21385 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21386 (re-search-forward org-deadline-time-regexp end t)
21387 (org-deadline-close (match-string 1))))
21388 (goto-char (1+ beg))
21389 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21390 (throw :skip nil)))
21391 (goto-char beg)
21392 (org-agenda-skip)
21393 (goto-char (match-beginning 1))
21394 (setq marker (org-agenda-new-marker (match-beginning 0))
21395 category (org-get-category)
21396 tags (org-get-tags-at (point))
21397 txt (org-format-agenda-item "" (match-string 1) category tags)
21398 priority (1+ (org-get-priority txt)))
21399 (org-add-props txt props
21400 'org-marker marker 'org-hd-marker marker
21401 'priority priority 'org-category category
21402 'type "todo")
21403 (push txt ee)
21404 (if org-agenda-todo-list-sublevels
21405 (goto-char (match-end 1))
21406 (org-end-of-subtree 'invisible))))
21407 (nreverse ee)))
21409 (defconst org-agenda-no-heading-message
21410 "No heading for this item in buffer or region.")
21412 (defun org-agenda-get-timestamps ()
21413 "Return the date stamp information for agenda display."
21414 (let* ((props (list 'face nil
21415 'org-not-done-regexp org-not-done-regexp
21416 'org-todo-regexp org-todo-regexp
21417 'mouse-face 'highlight
21418 'keymap org-agenda-keymap
21419 'help-echo
21420 (format "mouse-2 or RET jump to org file %s"
21421 (abbreviate-file-name buffer-file-name))))
21422 (d1 (calendar-absolute-from-gregorian date))
21423 (remove-re
21424 (concat
21425 (regexp-quote
21426 (format-time-string
21427 "<%Y-%m-%d"
21428 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21429 ".*?>"))
21430 (regexp
21431 (concat
21432 (regexp-quote
21433 (substring
21434 (format-time-string
21435 (car org-time-stamp-formats)
21436 (apply 'encode-time ; DATE bound by calendar
21437 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21438 0 11))
21439 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21440 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21441 marker hdmarker deadlinep scheduledp donep tmp priority category
21442 ee txt timestr tags b0 b3 e3 head)
21443 (goto-char (point-min))
21444 (while (re-search-forward regexp nil t)
21445 (setq b0 (match-beginning 0)
21446 b3 (match-beginning 3) e3 (match-end 3))
21447 (catch :skip
21448 (and (org-at-date-range-p) (throw :skip nil))
21449 (org-agenda-skip)
21450 (if (and (match-end 1)
21451 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21452 (throw :skip nil))
21453 (if (and e3
21454 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21455 (throw :skip nil))
21456 (setq marker (org-agenda-new-marker b0)
21457 category (org-get-category b0)
21458 tmp (buffer-substring (max (point-min)
21459 (- b0 org-ds-keyword-length))
21461 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21462 deadlinep (string-match org-deadline-regexp tmp)
21463 scheduledp (string-match org-scheduled-regexp tmp)
21464 donep (org-entry-is-done-p))
21465 (if (or scheduledp deadlinep) (throw :skip t))
21466 (if (string-match ">" timestr)
21467 ;; substring should only run to end of time stamp
21468 (setq timestr (substring timestr 0 (match-end 0))))
21469 (save-excursion
21470 (if (re-search-backward "^\\*+ " nil t)
21471 (progn
21472 (goto-char (match-beginning 0))
21473 (setq hdmarker (org-agenda-new-marker)
21474 tags (org-get-tags-at))
21475 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21476 (setq head (match-string 1))
21477 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21478 (setq txt (org-format-agenda-item
21479 nil head category tags timestr nil
21480 remove-re)))
21481 (setq txt org-agenda-no-heading-message))
21482 (setq priority (org-get-priority txt))
21483 (org-add-props txt props
21484 'org-marker marker 'org-hd-marker hdmarker)
21485 (org-add-props txt nil 'priority priority
21486 'org-category category 'date date
21487 'type "timestamp")
21488 (push txt ee))
21489 (outline-next-heading)))
21490 (nreverse ee)))
21492 (defun org-agenda-get-sexps ()
21493 "Return the sexp information for agenda display."
21494 (require 'diary-lib)
21495 (let* ((props (list 'face nil
21496 'mouse-face 'highlight
21497 'keymap org-agenda-keymap
21498 'help-echo
21499 (format "mouse-2 or RET jump to org file %s"
21500 (abbreviate-file-name buffer-file-name))))
21501 (regexp "^&?%%(")
21502 marker category ee txt tags entry result beg b sexp sexp-entry)
21503 (goto-char (point-min))
21504 (while (re-search-forward regexp nil t)
21505 (catch :skip
21506 (org-agenda-skip)
21507 (setq beg (match-beginning 0))
21508 (goto-char (1- (match-end 0)))
21509 (setq b (point))
21510 (forward-sexp 1)
21511 (setq sexp (buffer-substring b (point)))
21512 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21513 (org-trim (match-string 1))
21514 ""))
21515 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21516 (when result
21517 (setq marker (org-agenda-new-marker beg)
21518 category (org-get-category beg))
21520 (if (string-match "\\S-" result)
21521 (setq txt result)
21522 (setq txt "SEXP entry returned empty string"))
21524 (setq txt (org-format-agenda-item
21525 "" txt category tags 'time))
21526 (org-add-props txt props 'org-marker marker)
21527 (org-add-props txt nil
21528 'org-category category 'date date
21529 'type "sexp")
21530 (push txt ee))))
21531 (nreverse ee)))
21533 (defun org-agenda-get-closed ()
21534 "Return the logged TODO entries for agenda display."
21535 (let* ((props (list 'mouse-face 'highlight
21536 'org-not-done-regexp org-not-done-regexp
21537 'org-todo-regexp org-todo-regexp
21538 'keymap org-agenda-keymap
21539 'help-echo
21540 (format "mouse-2 or RET jump to org file %s"
21541 (abbreviate-file-name buffer-file-name))))
21542 (regexp (concat
21543 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21544 (regexp-quote
21545 (substring
21546 (format-time-string
21547 (car org-time-stamp-formats)
21548 (apply 'encode-time ; DATE bound by calendar
21549 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21550 1 11))))
21551 marker hdmarker priority category tags closedp
21552 ee txt timestr)
21553 (goto-char (point-min))
21554 (while (re-search-forward regexp nil t)
21555 (catch :skip
21556 (org-agenda-skip)
21557 (setq marker (org-agenda-new-marker (match-beginning 0))
21558 closedp (equal (match-string 1) org-closed-string)
21559 category (org-get-category (match-beginning 0))
21560 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21561 ;; donep (org-entry-is-done-p)
21563 (if (string-match "\\]" timestr)
21564 ;; substring should only run to end of time stamp
21565 (setq timestr (substring timestr 0 (match-end 0))))
21566 (save-excursion
21567 (if (re-search-backward "^\\*+ " nil t)
21568 (progn
21569 (goto-char (match-beginning 0))
21570 (setq hdmarker (org-agenda-new-marker)
21571 tags (org-get-tags-at))
21572 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21573 (setq txt (org-format-agenda-item
21574 (if closedp "Closed: " "Clocked: ")
21575 (match-string 1) category tags timestr)))
21576 (setq txt org-agenda-no-heading-message))
21577 (setq priority 100000)
21578 (org-add-props txt props
21579 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21580 'priority priority 'org-category category
21581 'type "closed" 'date date
21582 'undone-face 'org-warning 'done-face 'org-done)
21583 (push txt ee))
21584 (goto-char (point-at-eol))))
21585 (nreverse ee)))
21587 (defun org-agenda-get-deadlines ()
21588 "Return the deadline information for agenda display."
21589 (let* ((props (list 'mouse-face 'highlight
21590 'org-not-done-regexp org-not-done-regexp
21591 'org-todo-regexp org-todo-regexp
21592 'keymap org-agenda-keymap
21593 'help-echo
21594 (format "mouse-2 or RET jump to org file %s"
21595 (abbreviate-file-name buffer-file-name))))
21596 (regexp org-deadline-time-regexp)
21597 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21598 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21599 d2 diff dfrac wdays pos pos1 category tags
21600 ee txt head face s upcomingp donep timestr)
21601 (goto-char (point-min))
21602 (while (re-search-forward regexp nil t)
21603 (catch :skip
21604 (org-agenda-skip)
21605 (setq s (match-string 1)
21606 pos (1- (match-beginning 1))
21607 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21608 diff (- d2 d1)
21609 wdays (org-get-wdays s)
21610 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21611 upcomingp (and todayp (> diff 0)))
21612 ;; When to show a deadline in the calendar:
21613 ;; If the expiration is within wdays warning time.
21614 ;; Past-due deadlines are only shown on the current date
21615 (if (or (and (<= diff wdays)
21616 (and todayp (not org-agenda-only-exact-dates)))
21617 (= diff 0))
21618 (save-excursion
21619 (setq category (org-get-category))
21620 (if (re-search-backward "^\\*+[ \t]+" nil t)
21621 (progn
21622 (goto-char (match-end 0))
21623 (setq pos1 (match-beginning 0))
21624 (setq tags (org-get-tags-at pos1))
21625 (setq head (buffer-substring-no-properties
21626 (point)
21627 (progn (skip-chars-forward "^\r\n")
21628 (point))))
21629 (setq donep (string-match org-looking-at-done-regexp head))
21630 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21631 (setq timestr
21632 (concat (substring s (match-beginning 1)) " "))
21633 (setq timestr 'time))
21634 (if (and donep
21635 (or org-agenda-skip-deadline-if-done
21636 (not (= diff 0))))
21637 (setq txt nil)
21638 (setq txt (org-format-agenda-item
21639 (if (= diff 0)
21640 (car org-agenda-deadline-leaders)
21641 (format (nth 1 org-agenda-deadline-leaders)
21642 diff))
21643 head category tags timestr))))
21644 (setq txt org-agenda-no-heading-message))
21645 (when txt
21646 (setq face (org-agenda-deadline-face dfrac))
21647 (org-add-props txt props
21648 'org-marker (org-agenda-new-marker pos)
21649 'org-hd-marker (org-agenda-new-marker pos1)
21650 'priority (+ (- diff)
21651 (org-get-priority txt))
21652 'org-category category
21653 'type (if upcomingp "upcoming-deadline" "deadline")
21654 'date (if upcomingp date d2)
21655 'face (if donep 'org-done face)
21656 'undone-face face 'done-face 'org-done)
21657 (push txt ee))))))
21658 (nreverse ee)))
21660 (defun org-agenda-deadline-face (fraction)
21661 "Return the face to displaying a deadline item.
21662 FRACTION is what fraction of the head-warning time has passed."
21663 (let ((faces org-agenda-deadline-faces) f)
21664 (catch 'exit
21665 (while (setq f (pop faces))
21666 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21668 (defun org-agenda-get-scheduled ()
21669 "Return the scheduled information for agenda display."
21670 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21671 'org-todo-regexp org-todo-regexp
21672 'done-face 'org-done
21673 'mouse-face 'highlight
21674 'keymap org-agenda-keymap
21675 'help-echo
21676 (format "mouse-2 or RET jump to org file %s"
21677 (abbreviate-file-name buffer-file-name))))
21678 (regexp org-scheduled-time-regexp)
21679 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21680 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21681 d2 diff pos pos1 category tags
21682 ee txt head pastschedp donep face timestr s)
21683 (goto-char (point-min))
21684 (while (re-search-forward regexp nil t)
21685 (catch :skip
21686 (org-agenda-skip)
21687 (setq s (match-string 1)
21688 pos (1- (match-beginning 1))
21689 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21690 ;;; is this right?
21691 ;;; do we need to do this for deadleine too????
21692 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21693 diff (- d2 d1))
21694 (setq pastschedp (and todayp (< diff 0)))
21695 ;; When to show a scheduled item in the calendar:
21696 ;; If it is on or past the date.
21697 (if (or (and (< diff 0)
21698 (and todayp (not org-agenda-only-exact-dates)))
21699 (= diff 0))
21700 (save-excursion
21701 (setq category (org-get-category))
21702 (if (re-search-backward "^\\*+[ \t]+" nil t)
21703 (progn
21704 (goto-char (match-end 0))
21705 (setq pos1 (match-beginning 0))
21706 (setq tags (org-get-tags-at))
21707 (setq head (buffer-substring-no-properties
21708 (point)
21709 (progn (skip-chars-forward "^\r\n") (point))))
21710 (setq donep (string-match org-looking-at-done-regexp head))
21711 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21712 (setq timestr
21713 (concat (substring s (match-beginning 1)) " "))
21714 (setq timestr 'time))
21715 (if (and donep
21716 (or org-agenda-skip-scheduled-if-done
21717 (not (= diff 0))))
21718 (setq txt nil)
21719 (setq txt (org-format-agenda-item
21720 (if (= diff 0)
21721 (car org-agenda-scheduled-leaders)
21722 (format (nth 1 org-agenda-scheduled-leaders)
21723 (- 1 diff)))
21724 head category tags timestr))))
21725 (setq txt org-agenda-no-heading-message))
21726 (when txt
21727 (setq face (if pastschedp
21728 'org-scheduled-previously
21729 'org-scheduled-today))
21730 (org-add-props txt props
21731 'undone-face face
21732 'face (if donep 'org-done face)
21733 'org-marker (org-agenda-new-marker pos)
21734 'org-hd-marker (org-agenda-new-marker pos1)
21735 'type (if pastschedp "past-scheduled" "scheduled")
21736 'date (if pastschedp d2 date)
21737 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21738 'org-category category)
21739 (push txt ee))))))
21740 (nreverse ee)))
21742 (defun org-agenda-get-blocks ()
21743 "Return the date-range information for agenda display."
21744 (let* ((props (list 'face nil
21745 'org-not-done-regexp org-not-done-regexp
21746 'org-todo-regexp org-todo-regexp
21747 'mouse-face 'highlight
21748 'keymap org-agenda-keymap
21749 'help-echo
21750 (format "mouse-2 or RET jump to org file %s"
21751 (abbreviate-file-name buffer-file-name))))
21752 (regexp org-tr-regexp)
21753 (d0 (calendar-absolute-from-gregorian date))
21754 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21755 donep head)
21756 (goto-char (point-min))
21757 (while (re-search-forward regexp nil t)
21758 (catch :skip
21759 (org-agenda-skip)
21760 (setq pos (point))
21761 (setq timestr (match-string 0)
21762 s1 (match-string 1)
21763 s2 (match-string 2)
21764 d1 (time-to-days (org-time-string-to-time s1))
21765 d2 (time-to-days (org-time-string-to-time s2)))
21766 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21767 ;; Only allow days between the limits, because the normal
21768 ;; date stamps will catch the limits.
21769 (save-excursion
21770 (setq marker (org-agenda-new-marker (point)))
21771 (setq category (org-get-category))
21772 (if (re-search-backward "^\\*+ " nil t)
21773 (progn
21774 (goto-char (match-beginning 0))
21775 (setq hdmarker (org-agenda-new-marker (point)))
21776 (setq tags (org-get-tags-at))
21777 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21778 (setq head (match-string 1))
21779 (and org-agenda-skip-timestamp-if-done
21780 (org-entry-is-done-p)
21781 (throw :skip t))
21782 (setq txt (org-format-agenda-item
21783 (format (if (= d1 d2) "" "(%d/%d): ")
21784 (1+ (- d0 d1)) (1+ (- d2 d1)))
21785 head category tags
21786 (if (= d0 d1) timestr))))
21787 (setq txt org-agenda-no-heading-message))
21788 (org-add-props txt props
21789 'org-marker marker 'org-hd-marker hdmarker
21790 'type "block" 'date date
21791 'priority (org-get-priority txt) 'org-category category)
21792 (push txt ee)))
21793 (goto-char pos)))
21794 ;; Sort the entries by expiration date.
21795 (nreverse ee)))
21797 ;;; Agenda presentation and sorting
21799 (defconst org-plain-time-of-day-regexp
21800 (concat
21801 "\\(\\<[012]?[0-9]"
21802 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21803 "\\(--?"
21804 "\\(\\<[012]?[0-9]"
21805 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21806 "\\)?")
21807 "Regular expression to match a plain time or time range.
21808 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21809 groups carry important information:
21810 0 the full match
21811 1 the first time, range or not
21812 8 the second time, if it is a range.")
21814 (defconst org-plain-time-extension-regexp
21815 (concat
21816 "\\(\\<[012]?[0-9]"
21817 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21818 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21819 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21820 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21821 groups carry important information:
21822 0 the full match
21823 7 hours of duration
21824 9 minutes of duration")
21826 (defconst org-stamp-time-of-day-regexp
21827 (concat
21828 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21829 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21830 "\\(--?"
21831 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21832 "Regular expression to match a timestamp time or time range.
21833 After a match, the following groups carry important information:
21834 0 the full match
21835 1 date plus weekday, for backreferencing to make sure both times on same day
21836 2 the first time, range or not
21837 4 the second time, if it is a range.")
21839 (defvar org-prefix-has-time nil
21840 "A flag, set by `org-compile-prefix-format'.
21841 The flag is set if the currently compiled format contains a `%t'.")
21842 (defvar org-prefix-has-tag nil
21843 "A flag, set by `org-compile-prefix-format'.
21844 The flag is set if the currently compiled format contains a `%T'.")
21846 (defun org-format-agenda-item (extra txt &optional category tags dotime
21847 noprefix remove-re)
21848 "Format TXT to be inserted into the agenda buffer.
21849 In particular, it adds the prefix and corresponding text properties. EXTRA
21850 must be a string and replaces the `%s' specifier in the prefix format.
21851 CATEGORY (string, symbol or nil) may be used to overrule the default
21852 category taken from local variable or file name. It will replace the `%c'
21853 specifier in the format. DOTIME, when non-nil, indicates that a
21854 time-of-day should be extracted from TXT for sorting of this entry, and for
21855 the `%t' specifier in the format. When DOTIME is a string, this string is
21856 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21857 only the correctly processes TXT should be returned - this is used by
21858 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21859 Any match of REMOVE-RE will be removed from TXT."
21860 (save-match-data
21861 ;; Diary entries sometimes have extra whitespace at the beginning
21862 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21863 (let* ((category (or category
21864 org-category
21865 (if buffer-file-name
21866 (file-name-sans-extension
21867 (file-name-nondirectory buffer-file-name))
21868 "")))
21869 (tag (if tags (nth (1- (length tags)) tags) ""))
21870 time ; time and tag are needed for the eval of the prefix format
21871 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21872 (time-of-day (and dotime (org-get-time-of-day ts)))
21873 stamp plain s0 s1 s2 rtn srp)
21874 (when (and dotime time-of-day org-prefix-has-time)
21875 ;; Extract starting and ending time and move them to prefix
21876 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21877 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21878 (setq s0 (match-string 0 ts)
21879 srp (and stamp (match-end 3))
21880 s1 (match-string (if plain 1 2) ts)
21881 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21883 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21884 ;; them, we might want to remove them there to avoid duplication.
21885 ;; The user can turn this off with a variable.
21886 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21887 (string-match (concat (regexp-quote s0) " *") txt)
21888 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21889 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21890 (= (match-beginning 0) 0)
21892 (setq txt (replace-match "" nil nil txt))))
21893 ;; Normalize the time(s) to 24 hour
21894 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21895 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21897 (when (and s1 (not s2) org-agenda-default-appointment-duration
21898 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21899 (let ((m (+ (string-to-number (match-string 2 s1))
21900 (* 60 (string-to-number (match-string 1 s1)))
21901 org-agenda-default-appointment-duration))
21903 (setq h (/ m 60) m (- m (* h 60)))
21904 (setq s2 (format "%02d:%02d" h m))))
21906 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21907 txt)
21908 ;; Tags are in the string
21909 (if (or (eq org-agenda-remove-tags t)
21910 (and org-agenda-remove-tags
21911 org-prefix-has-tag))
21912 (setq txt (replace-match "" t t txt))
21913 (setq txt (replace-match
21914 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21915 (match-string 2 txt))
21916 t t txt))))
21918 (when remove-re
21919 (while (string-match remove-re txt)
21920 (setq txt (replace-match "" t t txt))))
21922 ;; Create the final string
21923 (if noprefix
21924 (setq rtn txt)
21925 ;; Prepare the variables needed in the eval of the compiled format
21926 (setq time (cond (s2 (concat s1 "-" s2))
21927 (s1 (concat s1 "......"))
21928 (t ""))
21929 extra (or extra "")
21930 category (if (symbolp category) (symbol-name category) category))
21931 ;; Evaluate the compiled format
21932 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21934 ;; And finally add the text properties
21935 (org-add-props rtn nil
21936 'org-category (downcase category) 'tags tags
21937 'org-highest-priority org-highest-priority
21938 'org-lowest-priority org-lowest-priority
21939 'prefix-length (- (length rtn) (length txt))
21940 'time-of-day time-of-day
21941 'txt txt
21942 'time time
21943 'extra extra
21944 'dotime dotime))))
21946 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21947 (defvar org-agenda-sorting-strategy-selected nil)
21949 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21950 (catch 'exit
21951 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21952 ((and todayp (member 'today (car org-agenda-time-grid))))
21953 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21954 ((member 'weekly (car org-agenda-time-grid)))
21955 (t (throw 'exit list)))
21956 (let* ((have (delq nil (mapcar
21957 (lambda (x) (get-text-property 1 'time-of-day x))
21958 list)))
21959 (string (nth 1 org-agenda-time-grid))
21960 (gridtimes (nth 2 org-agenda-time-grid))
21961 (req (car org-agenda-time-grid))
21962 (remove (member 'remove-match req))
21963 new time)
21964 (if (and (member 'require-timed req) (not have))
21965 ;; don't show empty grid
21966 (throw 'exit list))
21967 (while (setq time (pop gridtimes))
21968 (unless (and remove (member time have))
21969 (setq time (int-to-string time))
21970 (push (org-format-agenda-item
21971 nil string "" nil
21972 (concat (substring time 0 -2) ":" (substring time -2)))
21973 new)
21974 (put-text-property
21975 1 (length (car new)) 'face 'org-time-grid (car new))))
21976 (if (member 'time-up org-agenda-sorting-strategy-selected)
21977 (append new list)
21978 (append list new)))))
21980 (defun org-compile-prefix-format (key)
21981 "Compile the prefix format into a Lisp form that can be evaluated.
21982 The resulting form is returned and stored in the variable
21983 `org-prefix-format-compiled'."
21984 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21985 (let ((s (cond
21986 ((stringp org-agenda-prefix-format)
21987 org-agenda-prefix-format)
21988 ((assq key org-agenda-prefix-format)
21989 (cdr (assq key org-agenda-prefix-format)))
21990 (t " %-12:c%?-12t% s")))
21991 (start 0)
21992 varform vars var e c f opt)
21993 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21994 s start)
21995 (setq var (cdr (assoc (match-string 4 s)
21996 '(("c" . category) ("t" . time) ("s" . extra)
21997 ("T" . tag))))
21998 c (or (match-string 3 s) "")
21999 opt (match-beginning 1)
22000 start (1+ (match-beginning 0)))
22001 (if (equal var 'time) (setq org-prefix-has-time t))
22002 (if (equal var 'tag) (setq org-prefix-has-tag t))
22003 (setq f (concat "%" (match-string 2 s) "s"))
22004 (if opt
22005 (setq varform
22006 `(if (equal "" ,var)
22008 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22009 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22010 (setq s (replace-match "%s" t nil s))
22011 (push varform vars))
22012 (setq vars (nreverse vars))
22013 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22015 (defun org-set-sorting-strategy (key)
22016 (if (symbolp (car org-agenda-sorting-strategy))
22017 ;; the old format
22018 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22019 (setq org-agenda-sorting-strategy-selected
22020 (or (cdr (assq key org-agenda-sorting-strategy))
22021 (cdr (assq 'agenda org-agenda-sorting-strategy))
22022 '(time-up category-keep priority-down)))))
22024 (defun org-get-time-of-day (s &optional string mod24)
22025 "Check string S for a time of day.
22026 If found, return it as a military time number between 0 and 2400.
22027 If not found, return nil.
22028 The optional STRING argument forces conversion into a 5 character wide string
22029 HH:MM."
22030 (save-match-data
22031 (when
22032 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22033 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22034 (let* ((h (string-to-number (match-string 1 s)))
22035 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22036 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22037 (am-p (equal ampm "am"))
22038 (h1 (cond ((not ampm) h)
22039 ((= h 12) (if am-p 0 12))
22040 (t (+ h (if am-p 0 12)))))
22041 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22042 (mod h1 24) h1))
22043 (t0 (+ (* 100 h2) m))
22044 (t1 (concat (if (>= h1 24) "+" " ")
22045 (if (< t0 100) "0" "")
22046 (if (< t0 10) "0" "")
22047 (int-to-string t0))))
22048 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22050 (defun org-finalize-agenda-entries (list &optional nosort)
22051 "Sort and concatenate the agenda items."
22052 (setq list (mapcar 'org-agenda-highlight-todo list))
22053 (if nosort
22054 list
22055 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22057 (defun org-agenda-highlight-todo (x)
22058 (let (re pl)
22059 (if (eq x 'line)
22060 (save-excursion
22061 (beginning-of-line 1)
22062 (setq re (get-text-property (point) 'org-todo-regexp))
22063 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22064 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22065 (add-text-properties (match-beginning 0) (match-end 0)
22066 (list 'face (org-get-todo-face 0)))
22067 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22068 (delete-region (match-beginning 1) (1- (match-end 0)))
22069 (goto-char (match-beginning 1))
22070 (insert (format org-agenda-todo-keyword-format s)))))
22071 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22072 pl (get-text-property 0 'prefix-length x))
22073 (when (and re
22074 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22075 x (or pl 0)) pl))
22076 (add-text-properties
22077 (or (match-end 1) (match-end 0)) (match-end 0)
22078 (list 'face (org-get-todo-face (match-string 2 x)))
22080 (setq x (concat (substring x 0 (match-end 1))
22081 (format org-agenda-todo-keyword-format
22082 (match-string 2 x))
22084 (substring x (match-end 3)))))
22085 x)))
22087 (defsubst org-cmp-priority (a b)
22088 "Compare the priorities of string A and B."
22089 (let ((pa (or (get-text-property 1 'priority a) 0))
22090 (pb (or (get-text-property 1 'priority b) 0)))
22091 (cond ((> pa pb) +1)
22092 ((< pa pb) -1)
22093 (t nil))))
22095 (defsubst org-cmp-category (a b)
22096 "Compare the string values of categories of strings A and B."
22097 (let ((ca (or (get-text-property 1 'org-category a) ""))
22098 (cb (or (get-text-property 1 'org-category b) "")))
22099 (cond ((string-lessp ca cb) -1)
22100 ((string-lessp cb ca) +1)
22101 (t nil))))
22103 (defsubst org-cmp-tag (a b)
22104 "Compare the string values of categories of strings A and B."
22105 (let ((ta (car (last (get-text-property 1 'tags a))))
22106 (tb (car (last (get-text-property 1 'tags b)))))
22107 (cond ((not ta) +1)
22108 ((not tb) -1)
22109 ((string-lessp ta tb) -1)
22110 ((string-lessp tb ta) +1)
22111 (t nil))))
22113 (defsubst org-cmp-time (a b)
22114 "Compare the time-of-day values of strings A and B."
22115 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22116 (ta (or (get-text-property 1 'time-of-day a) def))
22117 (tb (or (get-text-property 1 'time-of-day b) def)))
22118 (cond ((< ta tb) -1)
22119 ((< tb ta) +1)
22120 (t nil))))
22122 (defun org-entries-lessp (a b)
22123 "Predicate for sorting agenda entries."
22124 ;; The following variables will be used when the form is evaluated.
22125 ;; So even though the compiler complains, keep them.
22126 (let* ((time-up (org-cmp-time a b))
22127 (time-down (if time-up (- time-up) nil))
22128 (priority-up (org-cmp-priority a b))
22129 (priority-down (if priority-up (- priority-up) nil))
22130 (category-up (org-cmp-category a b))
22131 (category-down (if category-up (- category-up) nil))
22132 (category-keep (if category-up +1 nil))
22133 (tag-up (org-cmp-tag a b))
22134 (tag-down (if tag-up (- tag-up) nil)))
22135 (cdr (assoc
22136 (eval (cons 'or org-agenda-sorting-strategy-selected))
22137 '((-1 . t) (1 . nil) (nil . nil))))))
22139 ;;; Agenda restriction lock
22141 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22142 "Overlay to mark the headline to which arenda commands are restricted.")
22143 (org-overlay-put org-agenda-restriction-lock-overlay
22144 'face 'org-agenda-restriction-lock)
22145 (org-overlay-put org-agenda-restriction-lock-overlay
22146 'help-echo "Agendas are currently limited to this subtree.")
22147 (org-detach-overlay org-agenda-restriction-lock-overlay)
22148 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22149 "Overlay marking the agenda restriction line in speedbar.")
22150 (org-overlay-put org-speedbar-restriction-lock-overlay
22151 'face 'org-agenda-restriction-lock)
22152 (org-overlay-put org-speedbar-restriction-lock-overlay
22153 'help-echo "Agendas are currently limited to this item.")
22154 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22156 (defun org-agenda-set-restriction-lock (&optional type)
22157 "Set restriction lock for agenda, to current subtree or file.
22158 Restriction will be the file if TYPE is `file', or if type is the
22159 universal prefix '(4), or if the cursor is before the first headline
22160 in the file. Otherwise, restriction will be to the current subtree."
22161 (interactive "P")
22162 (and (equal type '(4)) (setq type 'file))
22163 (setq type (cond
22164 (type type)
22165 ((org-at-heading-p) 'subtree)
22166 ((condition-case nil (org-back-to-heading t) (error nil))
22167 'subtree)
22168 (t 'file)))
22169 (if (eq type 'subtree)
22170 (progn
22171 (setq org-agenda-restrict t)
22172 (setq org-agenda-overriding-restriction 'subtree)
22173 (put 'org-agenda-files 'org-restrict
22174 (list (buffer-file-name (buffer-base-buffer))))
22175 (org-back-to-heading t)
22176 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22177 (move-marker org-agenda-restrict-begin (point))
22178 (move-marker org-agenda-restrict-end
22179 (save-excursion (org-end-of-subtree t)))
22180 (message "Locking agenda restriction to subtree"))
22181 (put 'org-agenda-files 'org-restrict
22182 (list (buffer-file-name (buffer-base-buffer))))
22183 (setq org-agenda-restrict nil)
22184 (setq org-agenda-overriding-restriction 'file)
22185 (move-marker org-agenda-restrict-begin nil)
22186 (move-marker org-agenda-restrict-end nil)
22187 (message "Locking agenda restriction to file"))
22188 (setq current-prefix-arg nil)
22189 (org-agenda-maybe-redo))
22191 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22192 "Remove the agenda restriction lock."
22193 (interactive "P")
22194 (org-detach-overlay org-agenda-restriction-lock-overlay)
22195 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22196 (setq org-agenda-overriding-restriction nil)
22197 (setq org-agenda-restrict nil)
22198 (put 'org-agenda-files 'org-restrict nil)
22199 (move-marker org-agenda-restrict-begin nil)
22200 (move-marker org-agenda-restrict-end nil)
22201 (setq current-prefix-arg nil)
22202 (message "Agenda restriction lock removed")
22203 (or noupdate (org-agenda-maybe-redo)))
22205 (defun org-agenda-maybe-redo ()
22206 "If there is any window showing the agenda view, update it."
22207 (let ((w (get-buffer-window org-agenda-buffer-name t))
22208 (w0 (selected-window)))
22209 (when w
22210 (select-window w)
22211 (org-agenda-redo)
22212 (select-window w0)
22213 (if org-agenda-overriding-restriction
22214 (message "Agenda view shifted to new %s restriction"
22215 org-agenda-overriding-restriction)
22216 (message "Agenda restriction lock removed")))))
22218 ;;; Agenda commands
22220 (defun org-agenda-check-type (error &rest types)
22221 "Check if agenda buffer is of allowed type.
22222 If ERROR is non-nil, throw an error, otherwise just return nil."
22223 (if (memq org-agenda-type types)
22225 (if error
22226 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22227 nil)))
22229 (defun org-agenda-quit ()
22230 "Exit agenda by removing the window or the buffer."
22231 (interactive)
22232 (let ((buf (current-buffer)))
22233 (if (not (one-window-p)) (delete-window))
22234 (kill-buffer buf)
22235 (org-agenda-reset-markers)
22236 (org-columns-remove-overlays))
22237 ;; Maybe restore the pre-agenda window configuration.
22238 (and org-agenda-restore-windows-after-quit
22239 (not (eq org-agenda-window-setup 'other-frame))
22240 org-pre-agenda-window-conf
22241 (set-window-configuration org-pre-agenda-window-conf)))
22243 (defun org-agenda-exit ()
22244 "Exit agenda by removing the window or the buffer.
22245 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22246 Org-mode buffers visited directly by the user will not be touched."
22247 (interactive)
22248 (org-release-buffers org-agenda-new-buffers)
22249 (setq org-agenda-new-buffers nil)
22250 (org-agenda-quit))
22252 (defun org-agenda-execute (arg)
22253 "Execute another agenda command, keeping same window.\\<global-map>
22254 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22255 (interactive "P")
22256 (let ((org-agenda-window-setup 'current-window))
22257 (org-agenda arg)))
22259 (defun org-save-all-org-buffers ()
22260 "Save all Org-mode buffers without user confirmation."
22261 (interactive)
22262 (message "Saving all Org-mode buffers...")
22263 (save-some-buffers t 'org-mode-p)
22264 (message "Saving all Org-mode buffers... done"))
22266 (defun org-agenda-redo ()
22267 "Rebuild Agenda.
22268 When this is the global TODO list, a prefix argument will be interpreted."
22269 (interactive)
22270 (let* ((org-agenda-keep-modes t)
22271 (line (org-current-line))
22272 (window-line (- line (org-current-line (window-start))))
22273 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22274 (message "Rebuilding agenda buffer...")
22275 (org-let lprops '(eval org-agenda-redo-command))
22276 (setq org-agenda-undo-list nil
22277 org-agenda-pending-undo-list nil)
22278 (message "Rebuilding agenda buffer...done")
22279 (goto-line line)
22280 (recenter window-line)))
22282 (defun org-agenda-goto-date (date)
22283 "Jump to DATE in agenda."
22284 (interactive (list (org-read-date)))
22285 (org-agenda-list nil date))
22287 (defun org-agenda-goto-today ()
22288 "Go to today."
22289 (interactive)
22290 (org-agenda-check-type t 'timeline 'agenda)
22291 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22292 (cond
22293 (tdpos (goto-char tdpos))
22294 ((eq org-agenda-type 'agenda)
22295 (let* ((sd (time-to-days
22296 (time-subtract (current-time)
22297 (list 0 (* 3600 org-extend-today-until) 0))))
22298 (comp (org-agenda-compute-time-span sd org-agenda-span))
22299 (org-agenda-overriding-arguments org-agenda-last-arguments))
22300 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22301 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22302 (org-agenda-redo)
22303 (org-agenda-find-same-or-today-or-agenda)))
22304 (t (error "Cannot find today")))))
22306 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22307 (goto-char
22308 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22309 (text-property-any (point-min) (point-max) 'org-today t)
22310 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22311 (point-min))))
22313 (defun org-agenda-later (arg)
22314 "Go forward in time by thee current span.
22315 With prefix ARG, go forward that many times the current span."
22316 (interactive "p")
22317 (org-agenda-check-type t 'agenda)
22318 (let* ((span org-agenda-span)
22319 (sd org-starting-day)
22320 (greg (calendar-gregorian-from-absolute sd))
22321 (cnt (get-text-property (point) 'org-day-cnt))
22322 greg2 nd)
22323 (cond
22324 ((eq span 'day)
22325 (setq sd (+ arg sd) nd 1))
22326 ((eq span 'week)
22327 (setq sd (+ (* 7 arg) sd) nd 7))
22328 ((eq span 'month)
22329 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22330 sd (calendar-absolute-from-gregorian greg2))
22331 (setcar greg2 (1+ (car greg2)))
22332 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22333 ((eq span 'year)
22334 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22335 sd (calendar-absolute-from-gregorian greg2))
22336 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22337 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22338 (let ((org-agenda-overriding-arguments
22339 (list (car org-agenda-last-arguments) sd nd t)))
22340 (org-agenda-redo)
22341 (org-agenda-find-same-or-today-or-agenda cnt))))
22343 (defun org-agenda-earlier (arg)
22344 "Go backward in time by the current span.
22345 With prefix ARG, go backward that many times the current span."
22346 (interactive "p")
22347 (org-agenda-later (- arg)))
22349 (defun org-agenda-day-view ()
22350 "Switch to daily view for agenda."
22351 (interactive)
22352 (setq org-agenda-ndays 1)
22353 (org-agenda-change-time-span 'day))
22354 (defun org-agenda-week-view ()
22355 "Switch to daily view for agenda."
22356 (interactive)
22357 (setq org-agenda-ndays 7)
22358 (org-agenda-change-time-span 'week))
22359 (defun org-agenda-month-view ()
22360 "Switch to daily view for agenda."
22361 (interactive)
22362 (org-agenda-change-time-span 'month))
22363 (defun org-agenda-year-view ()
22364 "Switch to daily view for agenda."
22365 (interactive)
22366 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22367 (org-agenda-change-time-span 'year)
22368 (error "Abort")))
22370 (defun org-agenda-change-time-span (span)
22371 "Change the agenda view to SPAN.
22372 SPAN may be `day', `week', `month', `year'."
22373 (org-agenda-check-type t 'agenda)
22374 (if (equal org-agenda-span span)
22375 (error "Viewing span is already \"%s\"" span))
22376 (let* ((sd (or (get-text-property (point) 'day)
22377 org-starting-day))
22378 (computed (org-agenda-compute-time-span sd span))
22379 (org-agenda-overriding-arguments
22380 (list (car org-agenda-last-arguments)
22381 (car computed) (cdr computed) t)))
22382 (org-agenda-redo)
22383 (org-agenda-find-same-or-today-or-agenda))
22384 (org-agenda-set-mode-name)
22385 (message "Switched to %s view" span))
22387 (defun org-agenda-compute-time-span (sd span)
22388 "Compute starting date and number of days for agenda.
22389 SPAN may be `day', `week', `month', `year'. The return value
22390 is a cons cell with the starting date and the number of days,
22391 so that the date SD will be in that range."
22392 (let* ((greg (calendar-gregorian-from-absolute sd))
22394 (cond
22395 ((eq span 'day)
22396 (setq nd 1))
22397 ((eq span 'week)
22398 (let* ((nt (calendar-day-of-week
22399 (calendar-gregorian-from-absolute sd)))
22400 (d (if org-agenda-start-on-weekday
22401 (- nt org-agenda-start-on-weekday)
22402 0)))
22403 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22404 (setq nd 7)))
22405 ((eq span 'month)
22406 (setq sd (calendar-absolute-from-gregorian
22407 (list (car greg) 1 (nth 2 greg)))
22408 nd (- (calendar-absolute-from-gregorian
22409 (list (1+ (car greg)) 1 (nth 2 greg)))
22410 sd)))
22411 ((eq span 'year)
22412 (setq sd (calendar-absolute-from-gregorian
22413 (list 1 1 (nth 2 greg)))
22414 nd (- (calendar-absolute-from-gregorian
22415 (list 1 1 (1+ (nth 2 greg))))
22416 sd))))
22417 (cons sd nd)))
22419 ;; FIXME: does not work if user makes date format that starts with a blank
22420 (defun org-agenda-next-date-line (&optional arg)
22421 "Jump to the next line indicating a date in agenda buffer."
22422 (interactive "p")
22423 (org-agenda-check-type t 'agenda 'timeline)
22424 (beginning-of-line 1)
22425 (if (looking-at "^\\S-") (forward-char 1))
22426 (if (not (re-search-forward "^\\S-" nil t arg))
22427 (progn
22428 (backward-char 1)
22429 (error "No next date after this line in this buffer")))
22430 (goto-char (match-beginning 0)))
22432 (defun org-agenda-previous-date-line (&optional arg)
22433 "Jump to the previous line indicating a date in agenda buffer."
22434 (interactive "p")
22435 (org-agenda-check-type t 'agenda 'timeline)
22436 (beginning-of-line 1)
22437 (if (not (re-search-backward "^\\S-" nil t arg))
22438 (error "No previous date before this line in this buffer")))
22440 ;; Initialize the highlight
22441 (defvar org-hl (org-make-overlay 1 1))
22442 (org-overlay-put org-hl 'face 'highlight)
22444 (defun org-highlight (begin end &optional buffer)
22445 "Highlight a region with overlay."
22446 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22447 org-hl begin end (or buffer (current-buffer))))
22449 (defun org-unhighlight ()
22450 "Detach overlay INDEX."
22451 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22453 ;; FIXME this is currently not used.
22454 (defun org-highlight-until-next-command (beg end &optional buffer)
22455 (org-highlight beg end buffer)
22456 (add-hook 'pre-command-hook 'org-unhighlight-once))
22457 (defun org-unhighlight-once ()
22458 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22459 (org-unhighlight))
22461 (defun org-agenda-follow-mode ()
22462 "Toggle follow mode in an agenda buffer."
22463 (interactive)
22464 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22465 (org-agenda-set-mode-name)
22466 (message "Follow mode is %s"
22467 (if org-agenda-follow-mode "on" "off")))
22469 (defun org-agenda-log-mode ()
22470 "Toggle log mode in an agenda buffer."
22471 (interactive)
22472 (org-agenda-check-type t 'agenda 'timeline)
22473 (setq org-agenda-show-log (not org-agenda-show-log))
22474 (org-agenda-set-mode-name)
22475 (org-agenda-redo)
22476 (message "Log mode is %s"
22477 (if org-agenda-show-log "on" "off")))
22479 (defun org-agenda-toggle-diary ()
22480 "Toggle diary inclusion in an agenda buffer."
22481 (interactive)
22482 (org-agenda-check-type t 'agenda)
22483 (setq org-agenda-include-diary (not org-agenda-include-diary))
22484 (org-agenda-redo)
22485 (org-agenda-set-mode-name)
22486 (message "Diary inclusion turned %s"
22487 (if org-agenda-include-diary "on" "off")))
22489 (defun org-agenda-toggle-time-grid ()
22490 "Toggle time grid in an agenda buffer."
22491 (interactive)
22492 (org-agenda-check-type t 'agenda)
22493 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22494 (org-agenda-redo)
22495 (org-agenda-set-mode-name)
22496 (message "Time-grid turned %s"
22497 (if org-agenda-use-time-grid "on" "off")))
22499 (defun org-agenda-set-mode-name ()
22500 "Set the mode name to indicate all the small mode settings."
22501 (setq mode-name
22502 (concat "Org-Agenda"
22503 (if (equal org-agenda-ndays 1) " Day" "")
22504 (if (equal org-agenda-ndays 7) " Week" "")
22505 (if org-agenda-follow-mode " Follow" "")
22506 (if org-agenda-include-diary " Diary" "")
22507 (if org-agenda-use-time-grid " Grid" "")
22508 (if org-agenda-show-log " Log" "")))
22509 (force-mode-line-update))
22511 (defun org-agenda-post-command-hook ()
22512 (and (eolp) (not (bolp)) (backward-char 1))
22513 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22514 (if (and org-agenda-follow-mode
22515 (get-text-property (point) 'org-marker))
22516 (org-agenda-show)))
22518 (defun org-agenda-show-priority ()
22519 "Show the priority of the current item.
22520 This priority is composed of the main priority given with the [#A] cookies,
22521 and by additional input from the age of a schedules or deadline entry."
22522 (interactive)
22523 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22524 (message "Priority is %d" (if pri pri -1000))))
22526 (defun org-agenda-show-tags ()
22527 "Show the tags applicable to the current item."
22528 (interactive)
22529 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22530 (if tags
22531 (message "Tags are :%s:"
22532 (org-no-properties (mapconcat 'identity tags ":")))
22533 (message "No tags associated with this line"))))
22535 (defun org-agenda-goto (&optional highlight)
22536 "Go to the Org-mode file which contains the item at point."
22537 (interactive)
22538 (let* ((marker (or (get-text-property (point) 'org-marker)
22539 (org-agenda-error)))
22540 (buffer (marker-buffer marker))
22541 (pos (marker-position marker)))
22542 (switch-to-buffer-other-window buffer)
22543 (widen)
22544 (goto-char pos)
22545 (when (org-mode-p)
22546 (org-show-context 'agenda)
22547 (save-excursion
22548 (and (outline-next-heading)
22549 (org-flag-heading nil)))) ; show the next heading
22550 (recenter (/ (window-height) 2))
22551 (run-hooks 'org-agenda-after-show-hook)
22552 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22554 (defvar org-agenda-after-show-hook nil
22555 "Normal hook run after an item has been shown from the agenda.
22556 Point is in the buffer where the item originated.")
22558 (defun org-agenda-kill ()
22559 "Kill the entry or subtree belonging to the current agenda entry."
22560 (interactive)
22561 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22562 (let* ((marker (or (get-text-property (point) 'org-marker)
22563 (org-agenda-error)))
22564 (buffer (marker-buffer marker))
22565 (pos (marker-position marker))
22566 (type (get-text-property (point) 'type))
22567 dbeg dend (n 0) conf)
22568 (org-with-remote-undo buffer
22569 (with-current-buffer buffer
22570 (save-excursion
22571 (goto-char pos)
22572 (if (and (org-mode-p) (not (member type '("sexp"))))
22573 (setq dbeg (progn (org-back-to-heading t) (point))
22574 dend (org-end-of-subtree t t))
22575 (setq dbeg (point-at-bol)
22576 dend (min (point-max) (1+ (point-at-eol)))))
22577 (goto-char dbeg)
22578 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22579 (setq conf (or (eq t org-agenda-confirm-kill)
22580 (and (numberp org-agenda-confirm-kill)
22581 (> n org-agenda-confirm-kill))))
22582 (and conf
22583 (not (y-or-n-p
22584 (format "Delete entry with %d lines in buffer \"%s\"? "
22585 n (buffer-name buffer))))
22586 (error "Abort"))
22587 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22588 (with-current-buffer buffer (delete-region dbeg dend))
22589 (message "Agenda item and source killed"))))
22591 (defun org-agenda-archive ()
22592 "Kill the entry or subtree belonging to the current agenda entry."
22593 (interactive)
22594 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22595 (let* ((marker (or (get-text-property (point) 'org-marker)
22596 (org-agenda-error)))
22597 (buffer (marker-buffer marker))
22598 (pos (marker-position marker)))
22599 (org-with-remote-undo buffer
22600 (with-current-buffer buffer
22601 (if (org-mode-p)
22602 (save-excursion
22603 (goto-char pos)
22604 (org-remove-subtree-entries-from-agenda)
22605 (org-back-to-heading t)
22606 (org-archive-subtree))
22607 (error "Archiving works only in Org-mode files"))))))
22609 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22610 "Remove all lines in the agenda that correspond to a given subtree.
22611 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22612 If this information is not given, the function uses the tree at point."
22613 (let ((buf (or buf (current-buffer))) m p)
22614 (save-excursion
22615 (unless (and beg end)
22616 (org-back-to-heading t)
22617 (setq beg (point))
22618 (org-end-of-subtree t)
22619 (setq end (point)))
22620 (set-buffer (get-buffer org-agenda-buffer-name))
22621 (save-excursion
22622 (goto-char (point-max))
22623 (beginning-of-line 1)
22624 (while (not (bobp))
22625 (when (and (setq m (get-text-property (point) 'org-marker))
22626 (equal buf (marker-buffer m))
22627 (setq p (marker-position m))
22628 (>= p beg)
22629 (<= p end))
22630 (let ((inhibit-read-only t))
22631 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22632 (beginning-of-line 0))))))
22634 (defun org-agenda-open-link ()
22635 "Follow the link in the current line, if any."
22636 (interactive)
22637 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22638 (save-excursion
22639 (save-restriction
22640 (narrow-to-region (point-at-bol) (point-at-eol))
22641 (org-open-at-point))))
22643 (defun org-agenda-copy-local-variable (var)
22644 "Get a variable from a referenced buffer and install it here."
22645 (let ((m (get-text-property (point) 'org-marker)))
22646 (when (and m (buffer-live-p (marker-buffer m)))
22647 (org-set-local var (with-current-buffer (marker-buffer m)
22648 (symbol-value var))))))
22650 (defun org-agenda-switch-to (&optional delete-other-windows)
22651 "Go to the Org-mode file which contains the item at point."
22652 (interactive)
22653 (let* ((marker (or (get-text-property (point) 'org-marker)
22654 (org-agenda-error)))
22655 (buffer (marker-buffer marker))
22656 (pos (marker-position marker)))
22657 (switch-to-buffer buffer)
22658 (and delete-other-windows (delete-other-windows))
22659 (widen)
22660 (goto-char pos)
22661 (when (org-mode-p)
22662 (org-show-context 'agenda)
22663 (save-excursion
22664 (and (outline-next-heading)
22665 (org-flag-heading nil)))))) ; show the next heading
22667 (defun org-agenda-goto-mouse (ev)
22668 "Go to the Org-mode file which contains the item at the mouse click."
22669 (interactive "e")
22670 (mouse-set-point ev)
22671 (org-agenda-goto))
22673 (defun org-agenda-show ()
22674 "Display the Org-mode file which contains the item at point."
22675 (interactive)
22676 (let ((win (selected-window)))
22677 (org-agenda-goto t)
22678 (select-window win)))
22680 (defun org-agenda-recenter (arg)
22681 "Display the Org-mode file which contains the item at point and recenter."
22682 (interactive "P")
22683 (let ((win (selected-window)))
22684 (org-agenda-goto t)
22685 (recenter arg)
22686 (select-window win)))
22688 (defun org-agenda-show-mouse (ev)
22689 "Display the Org-mode file which contains the item at the mouse click."
22690 (interactive "e")
22691 (mouse-set-point ev)
22692 (org-agenda-show))
22694 (defun org-agenda-check-no-diary ()
22695 "Check if the entry is a diary link and abort if yes."
22696 (if (get-text-property (point) 'org-agenda-diary-link)
22697 (org-agenda-error)))
22699 (defun org-agenda-error ()
22700 (error "Command not allowed in this line"))
22702 (defun org-agenda-tree-to-indirect-buffer ()
22703 "Show the subtree corresponding to the current entry in an indirect buffer.
22704 This calls the command `org-tree-to-indirect-buffer' from the original
22705 Org-mode buffer.
22706 With numerical prefix arg ARG, go up to this level and then take that tree.
22707 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22708 dedicated frame)."
22709 (interactive)
22710 (org-agenda-check-no-diary)
22711 (let* ((marker (or (get-text-property (point) 'org-marker)
22712 (org-agenda-error)))
22713 (buffer (marker-buffer marker))
22714 (pos (marker-position marker)))
22715 (with-current-buffer buffer
22716 (save-excursion
22717 (goto-char pos)
22718 (call-interactively 'org-tree-to-indirect-buffer)))))
22720 (defvar org-last-heading-marker (make-marker)
22721 "Marker pointing to the headline that last changed its TODO state
22722 by a remote command from the agenda.")
22724 (defun org-agenda-todo-nextset ()
22725 "Switch TODO entry to next sequence."
22726 (interactive)
22727 (org-agenda-todo 'nextset))
22729 (defun org-agenda-todo-previousset ()
22730 "Switch TODO entry to previous sequence."
22731 (interactive)
22732 (org-agenda-todo 'previousset))
22734 (defun org-agenda-todo (&optional arg)
22735 "Cycle TODO state of line at point, also in Org-mode file.
22736 This changes the line at point, all other lines in the agenda referring to
22737 the same tree node, and the headline of the tree node in the Org-mode file."
22738 (interactive "P")
22739 (org-agenda-check-no-diary)
22740 (let* ((col (current-column))
22741 (marker (or (get-text-property (point) 'org-marker)
22742 (org-agenda-error)))
22743 (buffer (marker-buffer marker))
22744 (pos (marker-position marker))
22745 (hdmarker (get-text-property (point) 'org-hd-marker))
22746 (inhibit-read-only t)
22747 newhead)
22748 (org-with-remote-undo buffer
22749 (with-current-buffer buffer
22750 (widen)
22751 (goto-char pos)
22752 (org-show-context 'agenda)
22753 (save-excursion
22754 (and (outline-next-heading)
22755 (org-flag-heading nil))) ; show the next heading
22756 (org-todo arg)
22757 (and (bolp) (forward-char 1))
22758 (setq newhead (org-get-heading))
22759 (save-excursion
22760 (org-back-to-heading)
22761 (move-marker org-last-heading-marker (point))))
22762 (beginning-of-line 1)
22763 (save-excursion
22764 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22765 (move-to-column col))))
22767 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22768 "Change all lines in the agenda buffer which match HDMARKER.
22769 The new content of the line will be NEWHEAD (as modified by
22770 `org-format-agenda-item'). HDMARKER is checked with
22771 `equal' against all `org-hd-marker' text properties in the file.
22772 If FIXFACE is non-nil, the face of each item is modified acording to
22773 the new TODO state."
22774 (let* ((inhibit-read-only t)
22775 props m pl undone-face done-face finish new dotime cat tags)
22776 (save-excursion
22777 (goto-char (point-max))
22778 (beginning-of-line 1)
22779 (while (not finish)
22780 (setq finish (bobp))
22781 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22782 (equal m hdmarker))
22783 (setq props (text-properties-at (point))
22784 dotime (get-text-property (point) 'dotime)
22785 cat (get-text-property (point) 'org-category)
22786 tags (get-text-property (point) 'tags)
22787 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22788 pl (get-text-property (point) 'prefix-length)
22789 undone-face (get-text-property (point) 'undone-face)
22790 done-face (get-text-property (point) 'done-face))
22791 (move-to-column pl)
22792 (cond
22793 ((equal new "")
22794 (beginning-of-line 1)
22795 (and (looking-at ".*\n?") (replace-match "")))
22796 ((looking-at ".*")
22797 (replace-match new t t)
22798 (beginning-of-line 1)
22799 (add-text-properties (point-at-bol) (point-at-eol) props)
22800 (when fixface
22801 (add-text-properties
22802 (point-at-bol) (point-at-eol)
22803 (list 'face
22804 (if org-last-todo-state-is-todo
22805 undone-face done-face))))
22806 (org-agenda-highlight-todo 'line)
22807 (beginning-of-line 1))
22808 (t (error "Line update did not work"))))
22809 (beginning-of-line 0)))
22810 (org-finalize-agenda)))
22812 (defun org-agenda-align-tags (&optional line)
22813 "Align all tags in agenda items to `org-agenda-tags-column'."
22814 (let ((inhibit-read-only t) l c)
22815 (save-excursion
22816 (goto-char (if line (point-at-bol) (point-min)))
22817 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22818 (if line (point-at-eol) nil) t)
22819 (add-text-properties
22820 (match-beginning 2) (match-end 2)
22821 (list 'face (list 'org-tag (get-text-property
22822 (match-beginning 2) 'face))))
22823 (setq l (- (match-end 2) (match-beginning 2))
22824 c (if (< org-agenda-tags-column 0)
22825 (- (abs org-agenda-tags-column) l)
22826 org-agenda-tags-column))
22827 (delete-region (match-beginning 1) (match-end 1))
22828 (goto-char (match-beginning 1))
22829 (insert (org-add-props
22830 (make-string (max 1 (- c (current-column))) ?\ )
22831 (text-properties-at (point))))))))
22833 (defun org-agenda-priority-up ()
22834 "Increase the priority of line at point, also in Org-mode file."
22835 (interactive)
22836 (org-agenda-priority 'up))
22838 (defun org-agenda-priority-down ()
22839 "Decrease the priority of line at point, also in Org-mode file."
22840 (interactive)
22841 (org-agenda-priority 'down))
22843 (defun org-agenda-priority (&optional force-direction)
22844 "Set the priority of line at point, also in Org-mode file.
22845 This changes the line at point, all other lines in the agenda referring to
22846 the same tree node, and the headline of the tree node in the Org-mode file."
22847 (interactive)
22848 (org-agenda-check-no-diary)
22849 (let* ((marker (or (get-text-property (point) 'org-marker)
22850 (org-agenda-error)))
22851 (hdmarker (get-text-property (point) 'org-hd-marker))
22852 (buffer (marker-buffer hdmarker))
22853 (pos (marker-position hdmarker))
22854 (inhibit-read-only t)
22855 newhead)
22856 (org-with-remote-undo buffer
22857 (with-current-buffer buffer
22858 (widen)
22859 (goto-char pos)
22860 (org-show-context 'agenda)
22861 (save-excursion
22862 (and (outline-next-heading)
22863 (org-flag-heading nil))) ; show the next heading
22864 (funcall 'org-priority force-direction)
22865 (end-of-line 1)
22866 (setq newhead (org-get-heading)))
22867 (org-agenda-change-all-lines newhead hdmarker)
22868 (beginning-of-line 1))))
22870 (defun org-get-tags-at (&optional pos)
22871 "Get a list of all headline tags applicable at POS.
22872 POS defaults to point. If tags are inherited, the list contains
22873 the targets in the same sequence as the headlines appear, i.e.
22874 the tags of the current headline come last."
22875 (interactive)
22876 (let (tags lastpos)
22877 (save-excursion
22878 (save-restriction
22879 (widen)
22880 (goto-char (or pos (point)))
22881 (save-match-data
22882 (org-back-to-heading t)
22883 (condition-case nil
22884 (while (not (equal lastpos (point)))
22885 (setq lastpos (point))
22886 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22887 (setq tags (append (org-split-string
22888 (org-match-string-no-properties 1) ":")
22889 tags)))
22890 (or org-use-tag-inheritance (error ""))
22891 (org-up-heading-all 1))
22892 (error nil))))
22893 tags)))
22895 ;; FIXME: should fix the tags property of the agenda line.
22896 (defun org-agenda-set-tags ()
22897 "Set tags for the current headline."
22898 (interactive)
22899 (org-agenda-check-no-diary)
22900 (if (and (org-region-active-p) (interactive-p))
22901 (call-interactively 'org-change-tag-in-region)
22902 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22903 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22904 (org-agenda-error)))
22905 (buffer (marker-buffer hdmarker))
22906 (pos (marker-position hdmarker))
22907 (inhibit-read-only t)
22908 newhead)
22909 (org-with-remote-undo buffer
22910 (with-current-buffer buffer
22911 (widen)
22912 (goto-char pos)
22913 (save-excursion
22914 (org-show-context 'agenda))
22915 (save-excursion
22916 (and (outline-next-heading)
22917 (org-flag-heading nil))) ; show the next heading
22918 (goto-char pos)
22919 (call-interactively 'org-set-tags)
22920 (end-of-line 1)
22921 (setq newhead (org-get-heading)))
22922 (org-agenda-change-all-lines newhead hdmarker)
22923 (beginning-of-line 1)))))
22925 (defun org-agenda-toggle-archive-tag ()
22926 "Toggle the archive tag for the current entry."
22927 (interactive)
22928 (org-agenda-check-no-diary)
22929 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22930 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22931 (org-agenda-error)))
22932 (buffer (marker-buffer hdmarker))
22933 (pos (marker-position hdmarker))
22934 (inhibit-read-only t)
22935 newhead)
22936 (org-with-remote-undo buffer
22937 (with-current-buffer buffer
22938 (widen)
22939 (goto-char pos)
22940 (org-show-context 'agenda)
22941 (save-excursion
22942 (and (outline-next-heading)
22943 (org-flag-heading nil))) ; show the next heading
22944 (call-interactively 'org-toggle-archive-tag)
22945 (end-of-line 1)
22946 (setq newhead (org-get-heading)))
22947 (org-agenda-change-all-lines newhead hdmarker)
22948 (beginning-of-line 1))))
22950 (defun org-agenda-date-later (arg &optional what)
22951 "Change the date of this item to one day later."
22952 (interactive "p")
22953 (org-agenda-check-type t 'agenda 'timeline)
22954 (org-agenda-check-no-diary)
22955 (let* ((marker (or (get-text-property (point) 'org-marker)
22956 (org-agenda-error)))
22957 (buffer (marker-buffer marker))
22958 (pos (marker-position marker)))
22959 (org-with-remote-undo buffer
22960 (with-current-buffer buffer
22961 (widen)
22962 (goto-char pos)
22963 (if (not (org-at-timestamp-p))
22964 (error "Cannot find time stamp"))
22965 (org-timestamp-change arg (or what 'day)))
22966 (org-agenda-show-new-time marker org-last-changed-timestamp))
22967 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22969 (defun org-agenda-date-earlier (arg &optional what)
22970 "Change the date of this item to one day earlier."
22971 (interactive "p")
22972 (org-agenda-date-later (- arg) what))
22974 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22975 "Show new date stamp via text properties."
22976 ;; We use text properties to make this undoable
22977 (let ((inhibit-read-only t))
22978 (setq stamp (concat " " prefix " => " stamp))
22979 (save-excursion
22980 (goto-char (point-max))
22981 (while (not (bobp))
22982 (when (equal marker (get-text-property (point) 'org-marker))
22983 (move-to-column (- (window-width) (length stamp)) t)
22984 (if (featurep 'xemacs)
22985 ;; Use `duplicable' property to trigger undo recording
22986 (let ((ex (make-extent nil nil))
22987 (gl (make-glyph stamp)))
22988 (set-glyph-face gl 'secondary-selection)
22989 (set-extent-properties
22990 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22991 (insert-extent ex (1- (point)) (point-at-eol)))
22992 (add-text-properties
22993 (1- (point)) (point-at-eol)
22994 (list 'display (org-add-props stamp nil
22995 'face 'secondary-selection))))
22996 (beginning-of-line 1))
22997 (beginning-of-line 0)))))
22999 (defun org-agenda-date-prompt (arg)
23000 "Change the date of this item. Date is prompted for, with default today.
23001 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23002 be used to request time specification in the time stamp."
23003 (interactive "P")
23004 (org-agenda-check-type t 'agenda 'timeline)
23005 (org-agenda-check-no-diary)
23006 (let* ((marker (or (get-text-property (point) 'org-marker)
23007 (org-agenda-error)))
23008 (buffer (marker-buffer marker))
23009 (pos (marker-position marker)))
23010 (org-with-remote-undo buffer
23011 (with-current-buffer buffer
23012 (widen)
23013 (goto-char pos)
23014 (if (not (org-at-timestamp-p))
23015 (error "Cannot find time stamp"))
23016 (org-time-stamp arg)
23017 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23019 (defun org-agenda-schedule (arg)
23020 "Schedule the item at point."
23021 (interactive "P")
23022 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23023 (org-agenda-check-no-diary)
23024 (let* ((marker (or (get-text-property (point) 'org-marker)
23025 (org-agenda-error)))
23026 (buffer (marker-buffer marker))
23027 (pos (marker-position marker))
23028 (org-insert-labeled-timestamps-at-point nil)
23030 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23031 (set-marker-insertion-type marker t)
23032 (org-with-remote-undo buffer
23033 (with-current-buffer buffer
23034 (widen)
23035 (goto-char pos)
23036 (setq ts (org-schedule arg)))
23037 (org-agenda-show-new-time marker ts "S"))
23038 (message "Item scheduled for %s" ts)))
23040 (defun org-agenda-deadline (arg)
23041 "Schedule the item at point."
23042 (interactive "P")
23043 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23044 (org-agenda-check-no-diary)
23045 (let* ((marker (or (get-text-property (point) 'org-marker)
23046 (org-agenda-error)))
23047 (buffer (marker-buffer marker))
23048 (pos (marker-position marker))
23049 (org-insert-labeled-timestamps-at-point nil)
23051 (org-with-remote-undo buffer
23052 (with-current-buffer buffer
23053 (widen)
23054 (goto-char pos)
23055 (setq ts (org-deadline arg)))
23056 (org-agenda-show-new-time marker ts "S"))
23057 (message "Deadline for this item set to %s" ts)))
23059 (defun org-get-heading (&optional no-tags)
23060 "Return the heading of the current entry, without the stars."
23061 (save-excursion
23062 (org-back-to-heading t)
23063 (if (looking-at
23064 (if no-tags
23065 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23066 "\\*+[ \t]+\\([^\r\n]*\\)"))
23067 (match-string 1) "")))
23069 (defun org-agenda-clock-in (&optional arg)
23070 "Start the clock on the currently selected item."
23071 (interactive "P")
23072 (org-agenda-check-no-diary)
23073 (let* ((marker (or (get-text-property (point) 'org-marker)
23074 (org-agenda-error)))
23075 (pos (marker-position marker)))
23076 (org-with-remote-undo (marker-buffer marker)
23077 (with-current-buffer (marker-buffer marker)
23078 (widen)
23079 (goto-char pos)
23080 (org-clock-in)))))
23082 (defun org-agenda-clock-out (&optional arg)
23083 "Stop the currently running clock."
23084 (interactive "P")
23085 (unless (marker-buffer org-clock-marker)
23086 (error "No running clock"))
23087 (org-with-remote-undo (marker-buffer org-clock-marker)
23088 (org-clock-out)))
23090 (defun org-agenda-clock-cancel (&optional arg)
23091 "Cancel the currently running clock."
23092 (interactive "P")
23093 (unless (marker-buffer org-clock-marker)
23094 (error "No running clock"))
23095 (org-with-remote-undo (marker-buffer org-clock-marker)
23096 (org-clock-cancel)))
23098 (defun org-agenda-diary-entry ()
23099 "Make a diary entry, like the `i' command from the calendar.
23100 All the standard commands work: block, weekly etc."
23101 (interactive)
23102 (org-agenda-check-type t 'agenda 'timeline)
23103 (require 'diary-lib)
23104 (let* ((char (progn
23105 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23106 (read-char-exclusive)))
23107 (cmd (cdr (assoc char
23108 '((?d . insert-diary-entry)
23109 (?w . insert-weekly-diary-entry)
23110 (?m . insert-monthly-diary-entry)
23111 (?y . insert-yearly-diary-entry)
23112 (?a . insert-anniversary-diary-entry)
23113 (?b . insert-block-diary-entry)
23114 (?c . insert-cyclic-diary-entry)))))
23115 (oldf (symbol-function 'calendar-cursor-to-date))
23116 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23117 (point (point))
23118 (mark (or (mark t) (point))))
23119 (unless cmd
23120 (error "No command associated with <%c>" char))
23121 (unless (and (get-text-property point 'day)
23122 (or (not (equal ?b char))
23123 (get-text-property mark 'day)))
23124 (error "Don't know which date to use for diary entry"))
23125 ;; We implement this by hacking the `calendar-cursor-to-date' function
23126 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23127 (let ((calendar-mark-ring
23128 (list (calendar-gregorian-from-absolute
23129 (or (get-text-property mark 'day)
23130 (get-text-property point 'day))))))
23131 (unwind-protect
23132 (progn
23133 (fset 'calendar-cursor-to-date
23134 (lambda (&optional error)
23135 (calendar-gregorian-from-absolute
23136 (get-text-property point 'day))))
23137 (call-interactively cmd))
23138 (fset 'calendar-cursor-to-date oldf)))))
23141 (defun org-agenda-execute-calendar-command (cmd)
23142 "Execute a calendar command from the agenda, with the date associated to
23143 the cursor position."
23144 (org-agenda-check-type t 'agenda 'timeline)
23145 (require 'diary-lib)
23146 (unless (get-text-property (point) 'day)
23147 (error "Don't know which date to use for calendar command"))
23148 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23149 (point (point))
23150 (date (calendar-gregorian-from-absolute
23151 (get-text-property point 'day)))
23152 ;; the following 3 vars are needed in the calendar
23153 (displayed-day (extract-calendar-day date))
23154 (displayed-month (extract-calendar-month date))
23155 (displayed-year (extract-calendar-year date)))
23156 (unwind-protect
23157 (progn
23158 (fset 'calendar-cursor-to-date
23159 (lambda (&optional error)
23160 (calendar-gregorian-from-absolute
23161 (get-text-property point 'day))))
23162 (call-interactively cmd))
23163 (fset 'calendar-cursor-to-date oldf))))
23165 (defun org-agenda-phases-of-moon ()
23166 "Display the phases of the moon for the 3 months around the cursor date."
23167 (interactive)
23168 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23170 (defun org-agenda-holidays ()
23171 "Display the holidays for the 3 months around the cursor date."
23172 (interactive)
23173 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23175 (defun org-agenda-sunrise-sunset (arg)
23176 "Display sunrise and sunset for the cursor date.
23177 Latitude and longitude can be specified with the variables
23178 `calendar-latitude' and `calendar-longitude'. When called with prefix
23179 argument, latitude and longitude will be prompted for."
23180 (interactive "P")
23181 (let ((calendar-longitude (if arg nil calendar-longitude))
23182 (calendar-latitude (if arg nil calendar-latitude))
23183 (calendar-location-name
23184 (if arg "the given coordinates" calendar-location-name)))
23185 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23187 (defun org-agenda-goto-calendar ()
23188 "Open the Emacs calendar with the date at the cursor."
23189 (interactive)
23190 (org-agenda-check-type t 'agenda 'timeline)
23191 (let* ((day (or (get-text-property (point) 'day)
23192 (error "Don't know which date to open in calendar")))
23193 (date (calendar-gregorian-from-absolute day))
23194 (calendar-move-hook nil)
23195 (view-calendar-holidays-initially nil)
23196 (view-diary-entries-initially nil))
23197 (calendar)
23198 (calendar-goto-date date)))
23200 (defun org-calendar-goto-agenda ()
23201 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23202 This is a command that has to be installed in `calendar-mode-map'."
23203 (interactive)
23204 (org-agenda-list nil (calendar-absolute-from-gregorian
23205 (calendar-cursor-to-date))
23206 nil))
23208 (defun org-agenda-convert-date ()
23209 (interactive)
23210 (org-agenda-check-type t 'agenda 'timeline)
23211 (let ((day (get-text-property (point) 'day))
23212 date s)
23213 (unless day
23214 (error "Don't know which date to convert"))
23215 (setq date (calendar-gregorian-from-absolute day))
23216 (setq s (concat
23217 "Gregorian: " (calendar-date-string date) "\n"
23218 "ISO: " (calendar-iso-date-string date) "\n"
23219 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23220 "Julian: " (calendar-julian-date-string date) "\n"
23221 "Astron. JD: " (calendar-astro-date-string date)
23222 " (Julian date number at noon UTC)\n"
23223 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23224 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23225 "French: " (calendar-french-date-string date) "\n"
23226 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23227 "Mayan: " (calendar-mayan-date-string date) "\n"
23228 "Coptic: " (calendar-coptic-date-string date) "\n"
23229 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23230 "Persian: " (calendar-persian-date-string date) "\n"
23231 "Chinese: " (calendar-chinese-date-string date) "\n"))
23232 (with-output-to-temp-buffer "*Dates*"
23233 (princ s))
23234 (if (fboundp 'fit-window-to-buffer)
23235 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23238 ;;;; Embedded LaTeX
23240 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23241 "Keymap for the minor `org-cdlatex-mode'.")
23243 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23244 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23245 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23246 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23247 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23249 (defvar org-cdlatex-texmathp-advice-is-done nil
23250 "Flag remembering if we have applied the advice to texmathp already.")
23252 (define-minor-mode org-cdlatex-mode
23253 "Toggle the minor `org-cdlatex-mode'.
23254 This mode supports entering LaTeX environment and math in LaTeX fragments
23255 in Org-mode.
23256 \\{org-cdlatex-mode-map}"
23257 nil " OCDL" nil
23258 (when org-cdlatex-mode (require 'cdlatex))
23259 (unless org-cdlatex-texmathp-advice-is-done
23260 (setq org-cdlatex-texmathp-advice-is-done t)
23261 (defadvice texmathp (around org-math-always-on activate)
23262 "Always return t in org-mode buffers.
23263 This is because we want to insert math symbols without dollars even outside
23264 the LaTeX math segments. If Orgmode thinks that point is actually inside
23265 en embedded LaTeX fragement, let texmathp do its job.
23266 \\[org-cdlatex-mode-map]"
23267 (interactive)
23268 (let (p)
23269 (cond
23270 ((not (org-mode-p)) ad-do-it)
23271 ((eq this-command 'cdlatex-math-symbol)
23272 (setq ad-return-value t
23273 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23275 (let ((p (org-inside-LaTeX-fragment-p)))
23276 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23277 (setq ad-return-value t
23278 texmathp-why '("Org-mode embedded math" . 0))
23279 (if p ad-do-it)))))))))
23281 (defun turn-on-org-cdlatex ()
23282 "Unconditionally turn on `org-cdlatex-mode'."
23283 (org-cdlatex-mode 1))
23285 (defun org-inside-LaTeX-fragment-p ()
23286 "Test if point is inside a LaTeX fragment.
23287 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23288 sequence appearing also before point.
23289 Even though the matchers for math are configurable, this function assumes
23290 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23291 delimiters are skipped when they have been removed by customization.
23292 The return value is nil, or a cons cell with the delimiter and
23293 and the position of this delimiter.
23295 This function does a reasonably good job, but can locally be fooled by
23296 for example currency specifications. For example it will assume being in
23297 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23298 fragments that are properly closed, but during editing, we have to live
23299 with the uncertainty caused by missing closing delimiters. This function
23300 looks only before point, not after."
23301 (catch 'exit
23302 (let ((pos (point))
23303 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23304 (lim (progn
23305 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23306 (point)))
23307 dd-on str (start 0) m re)
23308 (goto-char pos)
23309 (when dodollar
23310 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23311 re (nth 1 (assoc "$" org-latex-regexps)))
23312 (while (string-match re str start)
23313 (cond
23314 ((= (match-end 0) (length str))
23315 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23316 ((= (match-end 0) (- (length str) 5))
23317 (throw 'exit nil))
23318 (t (setq start (match-end 0))))))
23319 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23320 (goto-char pos)
23321 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23322 (and (match-beginning 2) (throw 'exit nil))
23323 ;; count $$
23324 (while (re-search-backward "\\$\\$" lim t)
23325 (setq dd-on (not dd-on)))
23326 (goto-char pos)
23327 (if dd-on (cons "$$" m))))))
23330 (defun org-try-cdlatex-tab ()
23331 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23332 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23333 - inside a LaTeX fragment, or
23334 - after the first word in a line, where an abbreviation expansion could
23335 insert a LaTeX environment."
23336 (when org-cdlatex-mode
23337 (cond
23338 ((save-excursion
23339 (skip-chars-backward "a-zA-Z0-9*")
23340 (skip-chars-backward " \t")
23341 (bolp))
23342 (cdlatex-tab) t)
23343 ((org-inside-LaTeX-fragment-p)
23344 (cdlatex-tab) t)
23345 (t nil))))
23347 (defun org-cdlatex-underscore-caret (&optional arg)
23348 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23349 Revert to the normal definition outside of these fragments."
23350 (interactive "P")
23351 (if (org-inside-LaTeX-fragment-p)
23352 (call-interactively 'cdlatex-sub-superscript)
23353 (let (org-cdlatex-mode)
23354 (call-interactively (key-binding (vector last-input-event))))))
23356 (defun org-cdlatex-math-modify (&optional arg)
23357 "Execute `cdlatex-math-modify' in LaTeX fragments.
23358 Revert to the normal definition outside of these fragments."
23359 (interactive "P")
23360 (if (org-inside-LaTeX-fragment-p)
23361 (call-interactively 'cdlatex-math-modify)
23362 (let (org-cdlatex-mode)
23363 (call-interactively (key-binding (vector last-input-event))))))
23365 (defvar org-latex-fragment-image-overlays nil
23366 "List of overlays carrying the images of latex fragments.")
23367 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23369 (defun org-remove-latex-fragment-image-overlays ()
23370 "Remove all overlays with LaTeX fragment images in current buffer."
23371 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23372 (setq org-latex-fragment-image-overlays nil))
23374 (defun org-preview-latex-fragment (&optional subtree)
23375 "Preview the LaTeX fragment at point, or all locally or globally.
23376 If the cursor is in a LaTeX fragment, create the image and overlay
23377 it over the source code. If there is no fragment at point, display
23378 all fragments in the current text, from one headline to the next. With
23379 prefix SUBTREE, display all fragments in the current subtree. With a
23380 double prefix `C-u C-u', or when the cursor is before the first headline,
23381 display all fragments in the buffer.
23382 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23383 (interactive "P")
23384 (org-remove-latex-fragment-image-overlays)
23385 (save-excursion
23386 (save-restriction
23387 (let (beg end at msg)
23388 (cond
23389 ((or (equal subtree '(16))
23390 (not (save-excursion
23391 (re-search-backward (concat "^" outline-regexp) nil t))))
23392 (setq beg (point-min) end (point-max)
23393 msg "Creating images for buffer...%s"))
23394 ((equal subtree '(4))
23395 (org-back-to-heading)
23396 (setq beg (point) end (org-end-of-subtree t)
23397 msg "Creating images for subtree...%s"))
23399 (if (setq at (org-inside-LaTeX-fragment-p))
23400 (goto-char (max (point-min) (- (cdr at) 2)))
23401 (org-back-to-heading))
23402 (setq beg (point) end (progn (outline-next-heading) (point))
23403 msg (if at "Creating image...%s"
23404 "Creating images for entry...%s"))))
23405 (message msg "")
23406 (narrow-to-region beg end)
23407 (goto-char beg)
23408 (org-format-latex
23409 (concat "ltxpng/" (file-name-sans-extension
23410 (file-name-nondirectory
23411 buffer-file-name)))
23412 default-directory 'overlays msg at 'forbuffer)
23413 (message msg "done. Use `C-c C-c' to remove images.")))))
23415 (defvar org-latex-regexps
23416 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23417 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23418 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23419 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23420 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23421 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23422 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23423 "Regular expressions for matching embedded LaTeX.")
23425 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23426 "Replace LaTeX fragments with links to an image, and produce images."
23427 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23428 (let* ((prefixnodir (file-name-nondirectory prefix))
23429 (absprefix (expand-file-name prefix dir))
23430 (todir (file-name-directory absprefix))
23431 (opt org-format-latex-options)
23432 (matchers (plist-get opt :matchers))
23433 (re-list org-latex-regexps)
23434 (cnt 0) txt link beg end re e checkdir
23435 m n block linkfile movefile ov)
23436 ;; Check if there are old images files with this prefix, and remove them
23437 (when (file-directory-p todir)
23438 (mapc 'delete-file
23439 (directory-files
23440 todir 'full
23441 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23442 ;; Check the different regular expressions
23443 (while (setq e (pop re-list))
23444 (setq m (car e) re (nth 1 e) n (nth 2 e)
23445 block (if (nth 3 e) "\n\n" ""))
23446 (when (member m matchers)
23447 (goto-char (point-min))
23448 (while (re-search-forward re nil t)
23449 (when (or (not at) (equal (cdr at) (match-beginning n)))
23450 (setq txt (match-string n)
23451 beg (match-beginning n) end (match-end n)
23452 cnt (1+ cnt)
23453 linkfile (format "%s_%04d.png" prefix cnt)
23454 movefile (format "%s_%04d.png" absprefix cnt)
23455 link (concat block "[[file:" linkfile "]]" block))
23456 (if msg (message msg cnt))
23457 (goto-char beg)
23458 (unless checkdir ; make sure the directory exists
23459 (setq checkdir t)
23460 (or (file-directory-p todir) (make-directory todir)))
23461 (org-create-formula-image
23462 txt movefile opt forbuffer)
23463 (if overlays
23464 (progn
23465 (setq ov (org-make-overlay beg end))
23466 (if (featurep 'xemacs)
23467 (progn
23468 (org-overlay-put ov 'invisible t)
23469 (org-overlay-put
23470 ov 'end-glyph
23471 (make-glyph (vector 'png :file movefile))))
23472 (org-overlay-put
23473 ov 'display
23474 (list 'image :type 'png :file movefile :ascent 'center)))
23475 (push ov org-latex-fragment-image-overlays)
23476 (goto-char end))
23477 (delete-region beg end)
23478 (insert link))))))))
23480 ;; This function borrows from Ganesh Swami's latex2png.el
23481 (defun org-create-formula-image (string tofile options buffer)
23482 (let* ((tmpdir (if (featurep 'xemacs)
23483 (temp-directory)
23484 temporary-file-directory))
23485 (texfilebase (make-temp-name
23486 (expand-file-name "orgtex" tmpdir)))
23487 (texfile (concat texfilebase ".tex"))
23488 (dvifile (concat texfilebase ".dvi"))
23489 (pngfile (concat texfilebase ".png"))
23490 (fnh (face-attribute 'default :height nil))
23491 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23492 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23493 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23494 "Black"))
23495 (bg (or (plist-get options (if buffer :background :html-background))
23496 "Transparent")))
23497 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23498 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23499 (with-temp-file texfile
23500 (insert org-format-latex-header
23501 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23502 (let ((dir default-directory))
23503 (condition-case nil
23504 (progn
23505 (cd tmpdir)
23506 (call-process "latex" nil nil nil texfile))
23507 (error nil))
23508 (cd dir))
23509 (if (not (file-exists-p dvifile))
23510 (progn (message "Failed to create dvi file from %s" texfile) nil)
23511 (call-process "dvipng" nil nil nil
23512 "-E" "-fg" fg "-bg" bg
23513 "-D" dpi
23514 ;;"-x" scale "-y" scale
23515 "-T" "tight"
23516 "-o" pngfile
23517 dvifile)
23518 (if (not (file-exists-p pngfile))
23519 (progn (message "Failed to create png file from %s" texfile) nil)
23520 ;; Use the requested file name and clean up
23521 (copy-file pngfile tofile 'replace)
23522 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23523 (delete-file (concat texfilebase e)))
23524 pngfile))))
23526 (defun org-dvipng-color (attr)
23527 "Return an rgb color specification for dvipng."
23528 (apply 'format "rgb %s %s %s"
23529 (mapcar 'org-normalize-color
23530 (color-values (face-attribute 'default attr nil)))))
23532 (defun org-normalize-color (value)
23533 "Return string to be used as color value for an RGB component."
23534 (format "%g" (/ value 65535.0)))
23536 ;;;; Exporting
23538 ;;; Variables, constants, and parameter plists
23540 (defconst org-level-max 20)
23542 (defvar org-export-html-preamble nil
23543 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23544 (defvar org-export-html-postamble nil
23545 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23546 (defvar org-export-html-auto-preamble t
23547 "Should default preamble be inserted? Set by publishing functions.")
23548 (defvar org-export-html-auto-postamble t
23549 "Should default postamble be inserted? Set by publishing functions.")
23550 (defvar org-current-export-file nil) ; dynamically scoped parameter
23551 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23554 (defconst org-export-plist-vars
23555 '((:language . org-export-default-language)
23556 (:customtime . org-display-custom-times)
23557 (:headline-levels . org-export-headline-levels)
23558 (:section-numbers . org-export-with-section-numbers)
23559 (:table-of-contents . org-export-with-toc)
23560 (:preserve-breaks . org-export-preserve-breaks)
23561 (:archived-trees . org-export-with-archived-trees)
23562 (:emphasize . org-export-with-emphasize)
23563 (:sub-superscript . org-export-with-sub-superscripts)
23564 (:special-strings . org-export-with-special-strings)
23565 (:footnotes . org-export-with-footnotes)
23566 (:drawers . org-export-with-drawers)
23567 (:tags . org-export-with-tags)
23568 (:TeX-macros . org-export-with-TeX-macros)
23569 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23570 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23571 (:fixed-width . org-export-with-fixed-width)
23572 (:timestamps . org-export-with-timestamps)
23573 (:author-info . org-export-author-info)
23574 (:time-stamp-file . org-export-time-stamp-file)
23575 (:tables . org-export-with-tables)
23576 (:table-auto-headline . org-export-highlight-first-table-line)
23577 (:style . org-export-html-style)
23578 (:agenda-style . org-agenda-export-html-style)
23579 (:convert-org-links . org-export-html-link-org-files-as-html)
23580 (:inline-images . org-export-html-inline-images)
23581 (:html-extension . org-export-html-extension)
23582 (:html-table-tag . org-export-html-table-tag)
23583 (:expand-quoted-html . org-export-html-expand)
23584 (:timestamp . org-export-html-with-timestamp)
23585 (:publishing-directory . org-export-publishing-directory)
23586 (:preamble . org-export-html-preamble)
23587 (:postamble . org-export-html-postamble)
23588 (:auto-preamble . org-export-html-auto-preamble)
23589 (:auto-postamble . org-export-html-auto-postamble)
23590 (:author . user-full-name)
23591 (:email . user-mail-address)))
23593 (defun org-default-export-plist ()
23594 "Return the property list with default settings for the export variables."
23595 (let ((l org-export-plist-vars) rtn e)
23596 (while (setq e (pop l))
23597 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23598 rtn))
23600 (defun org-infile-export-plist ()
23601 "Return the property list with file-local settings for export."
23602 (save-excursion
23603 (save-restriction
23604 (widen)
23605 (goto-char 0)
23606 (let ((re (org-make-options-regexp
23607 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23608 p key val text options)
23609 (while (re-search-forward re nil t)
23610 (setq key (org-match-string-no-properties 1)
23611 val (org-match-string-no-properties 2))
23612 (cond
23613 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23614 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23615 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23616 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23617 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23618 ((string-equal key "TEXT")
23619 (setq text (if text (concat text "\n" val) val)))
23620 ((string-equal key "OPTIONS") (setq options val))))
23621 (setq p (plist-put p :text text))
23622 (when options
23623 (let ((op '(("H" . :headline-levels)
23624 ("num" . :section-numbers)
23625 ("toc" . :table-of-contents)
23626 ("\\n" . :preserve-breaks)
23627 ("@" . :expand-quoted-html)
23628 (":" . :fixed-width)
23629 ("|" . :tables)
23630 ("^" . :sub-superscript)
23631 ("-" . :special-strings)
23632 ("f" . :footnotes)
23633 ("d" . :drawers)
23634 ("tags" . :tags)
23635 ("*" . :emphasize)
23636 ("TeX" . :TeX-macros)
23637 ("LaTeX" . :LaTeX-fragments)
23638 ("skip" . :skip-before-1st-heading)
23639 ("author" . :author-info)
23640 ("timestamp" . :time-stamp-file)))
23642 (while (setq o (pop op))
23643 (if (string-match (concat (regexp-quote (car o))
23644 ":\\([^ \t\n\r;,.]*\\)")
23645 options)
23646 (setq p (plist-put p (cdr o)
23647 (car (read-from-string
23648 (match-string 1 options)))))))))
23649 p))))
23651 (defun org-export-directory (type plist)
23652 (let* ((val (plist-get plist :publishing-directory))
23653 (dir (if (listp val)
23654 (or (cdr (assoc type val)) ".")
23655 val)))
23656 dir))
23658 (defun org-skip-comments (lines)
23659 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23660 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23661 (re2 "^\\(\\*+\\)[ \t\n\r]")
23662 (case-fold-search nil)
23663 rtn line level)
23664 (while (setq line (pop lines))
23665 (cond
23666 ((and (string-match re1 line)
23667 (setq level (- (match-end 1) (match-beginning 1))))
23668 ;; Beginning of a COMMENT subtree. Skip it.
23669 (while (and (setq line (pop lines))
23670 (or (not (string-match re2 line))
23671 (> (- (match-end 1) (match-beginning 1)) level))))
23672 (setq lines (cons line lines)))
23673 ((string-match "^#" line)
23674 ;; an ordinary comment line
23676 ((and org-export-table-remove-special-lines
23677 (string-match "^[ \t]*|" line)
23678 (or (string-match "^[ \t]*| *[!_^] *|" line)
23679 (and (string-match "| *<[0-9]+> *|" line)
23680 (not (string-match "| *[^ <|]" line)))))
23681 ;; a special table line that should be removed
23683 (t (setq rtn (cons line rtn)))))
23684 (nreverse rtn)))
23686 (defun org-export (&optional arg)
23687 (interactive)
23688 (let ((help "[t] insert the export option template
23689 \[v] limit export to visible part of outline tree
23691 \[a] export as ASCII
23693 \[h] export as HTML
23694 \[H] export as HTML to temporary buffer
23695 \[R] export region as HTML
23696 \[b] export as HTML and browse immediately
23697 \[x] export as XOXO
23699 \[l] export as LaTeX
23700 \[L] export as LaTeX to temporary buffer
23702 \[i] export current file as iCalendar file
23703 \[I] export all agenda files as iCalendar files
23704 \[c] export agenda files into combined iCalendar file
23706 \[F] publish current file
23707 \[P] publish current project
23708 \[X] publish... (project will be prompted for)
23709 \[A] publish all projects")
23710 (cmds
23711 '((?t . org-insert-export-options-template)
23712 (?v . org-export-visible)
23713 (?a . org-export-as-ascii)
23714 (?h . org-export-as-html)
23715 (?b . org-export-as-html-and-open)
23716 (?H . org-export-as-html-to-buffer)
23717 (?R . org-export-region-as-html)
23718 (?x . org-export-as-xoxo)
23719 (?l . org-export-as-latex)
23720 (?L . org-export-as-latex-to-buffer)
23721 (?i . org-export-icalendar-this-file)
23722 (?I . org-export-icalendar-all-agenda-files)
23723 (?c . org-export-icalendar-combine-agenda-files)
23724 (?F . org-publish-current-file)
23725 (?P . org-publish-current-project)
23726 (?X . org-publish)
23727 (?A . org-publish-all)))
23728 r1 r2 ass)
23729 (save-window-excursion
23730 (delete-other-windows)
23731 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23732 (princ help))
23733 (message "Select command: ")
23734 (setq r1 (read-char-exclusive)))
23735 (setq r2 (if (< r1 27) (+ r1 96) r1))
23736 (if (setq ass (assq r2 cmds))
23737 (call-interactively (cdr ass))
23738 (error "No command associated with key %c" r1))))
23740 (defconst org-html-entities
23741 '(("nbsp")
23742 ("iexcl")
23743 ("cent")
23744 ("pound")
23745 ("curren")
23746 ("yen")
23747 ("brvbar")
23748 ("vert" . "&#124;")
23749 ("sect")
23750 ("uml")
23751 ("copy")
23752 ("ordf")
23753 ("laquo")
23754 ("not")
23755 ("shy")
23756 ("reg")
23757 ("macr")
23758 ("deg")
23759 ("plusmn")
23760 ("sup2")
23761 ("sup3")
23762 ("acute")
23763 ("micro")
23764 ("para")
23765 ("middot")
23766 ("odot"."o")
23767 ("star"."*")
23768 ("cedil")
23769 ("sup1")
23770 ("ordm")
23771 ("raquo")
23772 ("frac14")
23773 ("frac12")
23774 ("frac34")
23775 ("iquest")
23776 ("Agrave")
23777 ("Aacute")
23778 ("Acirc")
23779 ("Atilde")
23780 ("Auml")
23781 ("Aring") ("AA"."&Aring;")
23782 ("AElig")
23783 ("Ccedil")
23784 ("Egrave")
23785 ("Eacute")
23786 ("Ecirc")
23787 ("Euml")
23788 ("Igrave")
23789 ("Iacute")
23790 ("Icirc")
23791 ("Iuml")
23792 ("ETH")
23793 ("Ntilde")
23794 ("Ograve")
23795 ("Oacute")
23796 ("Ocirc")
23797 ("Otilde")
23798 ("Ouml")
23799 ("times")
23800 ("Oslash")
23801 ("Ugrave")
23802 ("Uacute")
23803 ("Ucirc")
23804 ("Uuml")
23805 ("Yacute")
23806 ("THORN")
23807 ("szlig")
23808 ("agrave")
23809 ("aacute")
23810 ("acirc")
23811 ("atilde")
23812 ("auml")
23813 ("aring")
23814 ("aelig")
23815 ("ccedil")
23816 ("egrave")
23817 ("eacute")
23818 ("ecirc")
23819 ("euml")
23820 ("igrave")
23821 ("iacute")
23822 ("icirc")
23823 ("iuml")
23824 ("eth")
23825 ("ntilde")
23826 ("ograve")
23827 ("oacute")
23828 ("ocirc")
23829 ("otilde")
23830 ("ouml")
23831 ("divide")
23832 ("oslash")
23833 ("ugrave")
23834 ("uacute")
23835 ("ucirc")
23836 ("uuml")
23837 ("yacute")
23838 ("thorn")
23839 ("yuml")
23840 ("fnof")
23841 ("Alpha")
23842 ("Beta")
23843 ("Gamma")
23844 ("Delta")
23845 ("Epsilon")
23846 ("Zeta")
23847 ("Eta")
23848 ("Theta")
23849 ("Iota")
23850 ("Kappa")
23851 ("Lambda")
23852 ("Mu")
23853 ("Nu")
23854 ("Xi")
23855 ("Omicron")
23856 ("Pi")
23857 ("Rho")
23858 ("Sigma")
23859 ("Tau")
23860 ("Upsilon")
23861 ("Phi")
23862 ("Chi")
23863 ("Psi")
23864 ("Omega")
23865 ("alpha")
23866 ("beta")
23867 ("gamma")
23868 ("delta")
23869 ("epsilon")
23870 ("varepsilon"."&epsilon;")
23871 ("zeta")
23872 ("eta")
23873 ("theta")
23874 ("iota")
23875 ("kappa")
23876 ("lambda")
23877 ("mu")
23878 ("nu")
23879 ("xi")
23880 ("omicron")
23881 ("pi")
23882 ("rho")
23883 ("sigmaf") ("varsigma"."&sigmaf;")
23884 ("sigma")
23885 ("tau")
23886 ("upsilon")
23887 ("phi")
23888 ("chi")
23889 ("psi")
23890 ("omega")
23891 ("thetasym") ("vartheta"."&thetasym;")
23892 ("upsih")
23893 ("piv")
23894 ("bull") ("bullet"."&bull;")
23895 ("hellip") ("dots"."&hellip;")
23896 ("prime")
23897 ("Prime")
23898 ("oline")
23899 ("frasl")
23900 ("weierp")
23901 ("image")
23902 ("real")
23903 ("trade")
23904 ("alefsym")
23905 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23906 ("uarr") ("uparrow"."&uarr;")
23907 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23908 ("darr")("downarrow"."&darr;")
23909 ("harr") ("leftrightarrow"."&harr;")
23910 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23911 ("lArr") ("Leftarrow"."&lArr;")
23912 ("uArr") ("Uparrow"."&uArr;")
23913 ("rArr") ("Rightarrow"."&rArr;")
23914 ("dArr") ("Downarrow"."&dArr;")
23915 ("hArr") ("Leftrightarrow"."&hArr;")
23916 ("forall")
23917 ("part") ("partial"."&part;")
23918 ("exist") ("exists"."&exist;")
23919 ("empty") ("emptyset"."&empty;")
23920 ("nabla")
23921 ("isin") ("in"."&isin;")
23922 ("notin")
23923 ("ni")
23924 ("prod")
23925 ("sum")
23926 ("minus")
23927 ("lowast") ("ast"."&lowast;")
23928 ("radic")
23929 ("prop") ("proptp"."&prop;")
23930 ("infin") ("infty"."&infin;")
23931 ("ang") ("angle"."&ang;")
23932 ("and") ("wedge"."&and;")
23933 ("or") ("vee"."&or;")
23934 ("cap")
23935 ("cup")
23936 ("int")
23937 ("there4")
23938 ("sim")
23939 ("cong") ("simeq"."&cong;")
23940 ("asymp")("approx"."&asymp;")
23941 ("ne") ("neq"."&ne;")
23942 ("equiv")
23943 ("le")
23944 ("ge")
23945 ("sub") ("subset"."&sub;")
23946 ("sup") ("supset"."&sup;")
23947 ("nsub")
23948 ("sube")
23949 ("supe")
23950 ("oplus")
23951 ("otimes")
23952 ("perp")
23953 ("sdot") ("cdot"."&sdot;")
23954 ("lceil")
23955 ("rceil")
23956 ("lfloor")
23957 ("rfloor")
23958 ("lang")
23959 ("rang")
23960 ("loz") ("Diamond"."&loz;")
23961 ("spades") ("spadesuit"."&spades;")
23962 ("clubs") ("clubsuit"."&clubs;")
23963 ("hearts") ("diamondsuit"."&hearts;")
23964 ("diams") ("diamondsuit"."&diams;")
23965 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23966 ("quot")
23967 ("amp")
23968 ("lt")
23969 ("gt")
23970 ("OElig")
23971 ("oelig")
23972 ("Scaron")
23973 ("scaron")
23974 ("Yuml")
23975 ("circ")
23976 ("tilde")
23977 ("ensp")
23978 ("emsp")
23979 ("thinsp")
23980 ("zwnj")
23981 ("zwj")
23982 ("lrm")
23983 ("rlm")
23984 ("ndash")
23985 ("mdash")
23986 ("lsquo")
23987 ("rsquo")
23988 ("sbquo")
23989 ("ldquo")
23990 ("rdquo")
23991 ("bdquo")
23992 ("dagger")
23993 ("Dagger")
23994 ("permil")
23995 ("lsaquo")
23996 ("rsaquo")
23997 ("euro")
23999 ("arccos"."arccos")
24000 ("arcsin"."arcsin")
24001 ("arctan"."arctan")
24002 ("arg"."arg")
24003 ("cos"."cos")
24004 ("cosh"."cosh")
24005 ("cot"."cot")
24006 ("coth"."coth")
24007 ("csc"."csc")
24008 ("deg"."deg")
24009 ("det"."det")
24010 ("dim"."dim")
24011 ("exp"."exp")
24012 ("gcd"."gcd")
24013 ("hom"."hom")
24014 ("inf"."inf")
24015 ("ker"."ker")
24016 ("lg"."lg")
24017 ("lim"."lim")
24018 ("liminf"."liminf")
24019 ("limsup"."limsup")
24020 ("ln"."ln")
24021 ("log"."log")
24022 ("max"."max")
24023 ("min"."min")
24024 ("Pr"."Pr")
24025 ("sec"."sec")
24026 ("sin"."sin")
24027 ("sinh"."sinh")
24028 ("sup"."sup")
24029 ("tan"."tan")
24030 ("tanh"."tanh")
24032 "Entities for TeX->HTML translation.
24033 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24034 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24035 In that case, \"\\ent\" will be translated to \"&other;\".
24036 The list contains HTML entities for Latin-1, Greek and other symbols.
24037 It is supplemented by a number of commonly used TeX macros with appropriate
24038 translations. There is currently no way for users to extend this.")
24040 ;;; General functions for all backends
24042 (defun org-cleaned-string-for-export (string &rest parameters)
24043 "Cleanup a buffer STRING so that links can be created safely."
24044 (interactive)
24045 (let* ((re-radio (and org-target-link-regexp
24046 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24047 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24048 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24049 (re-archive (concat ":" org-archive-tag ":"))
24050 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24051 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24052 (htmlp (plist-get parameters :for-html))
24053 (asciip (plist-get parameters :for-ascii))
24054 (latexp (plist-get parameters :for-LaTeX))
24055 (commentsp (plist-get parameters :comments))
24056 (archived-trees (plist-get parameters :archived-trees))
24057 (inhibit-read-only t)
24058 (drawers org-drawers)
24059 (exp-drawers (plist-get parameters :drawers))
24060 (outline-regexp "\\*+ ")
24061 a b xx
24062 rtn p)
24063 (with-current-buffer (get-buffer-create " org-mode-tmp")
24064 (erase-buffer)
24065 (insert string)
24066 ;; Remove license-to-kill stuff
24067 (while (setq p (text-property-any (point-min) (point-max)
24068 :org-license-to-kill t))
24069 (delete-region p (next-single-property-change p :org-license-to-kill)))
24071 (let ((org-inhibit-startup t)) (org-mode))
24072 (untabify (point-min) (point-max))
24074 ;; Get rid of drawers
24075 (unless (eq t exp-drawers)
24076 (goto-char (point-min))
24077 (let ((re (concat "^[ \t]*:\\("
24078 (mapconcat
24079 'identity
24080 (org-delete-all exp-drawers
24081 (copy-sequence drawers))
24082 "\\|")
24083 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24084 (while (re-search-forward re nil t)
24085 (replace-match ""))))
24087 ;; Get the correct stuff before the first headline
24088 (when (plist-get parameters :skip-before-1st-heading)
24089 (goto-char (point-min))
24090 (when (re-search-forward "^\\*+[ \t]" nil t)
24091 (delete-region (point-min) (match-beginning 0))
24092 (goto-char (point-min))
24093 (insert "\n")))
24094 (when (plist-get parameters :add-text)
24095 (goto-char (point-min))
24096 (insert (plist-get parameters :add-text) "\n"))
24098 ;; Get rid of archived trees
24099 (when (not (eq archived-trees t))
24100 (goto-char (point-min))
24101 (while (re-search-forward re-archive nil t)
24102 (if (not (org-on-heading-p t))
24103 (org-end-of-subtree t)
24104 (beginning-of-line 1)
24105 (setq a (if archived-trees
24106 (1+ (point-at-eol)) (point))
24107 b (org-end-of-subtree t))
24108 (if (> b a) (delete-region a b)))))
24110 ;; Find targets in comments and move them out of comments,
24111 ;; but mark them as targets that should be invisible
24112 (goto-char (point-min))
24113 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24114 (replace-match "\\1(INVISIBLE)"))
24116 ;; Protect backend specific stuff, throw away the others.
24117 (let ((formatters
24118 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24119 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24120 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24121 fmt)
24122 (goto-char (point-min))
24123 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24124 (goto-char (match-end 0))
24125 (while (not (looking-at "#\\+END_EXAMPLE"))
24126 (insert ": ")
24127 (beginning-of-line 2)))
24128 (goto-char (point-min))
24129 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24130 (add-text-properties (match-beginning 0) (match-end 0)
24131 '(org-protected t)))
24132 (while formatters
24133 (setq fmt (pop formatters))
24134 (when (car fmt)
24135 (goto-char (point-min))
24136 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24137 ":[ \t]*\\(.*\\)") nil t)
24138 (replace-match "\\1" t)
24139 (add-text-properties
24140 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24141 '(org-protected t))))
24142 (goto-char (point-min))
24143 (while (re-search-forward
24144 (concat "^#\\+"
24145 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24146 (cadddr fmt) "\\>.*\n?") nil t)
24147 (if (car fmt)
24148 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24149 '(org-protected t))
24150 (delete-region (match-beginning 0) (match-end 0))))))
24152 ;; Protect quoted subtrees
24153 (goto-char (point-min))
24154 (while (re-search-forward re-quote nil t)
24155 (goto-char (match-beginning 0))
24156 (end-of-line 1)
24157 (add-text-properties (point) (org-end-of-subtree t)
24158 '(org-protected t)))
24160 ;; Protect verbatim elements
24161 (goto-char (point-min))
24162 (while (re-search-forward org-verbatim-re nil t)
24163 (add-text-properties (match-beginning 4) (match-end 4)
24164 '(org-protected t))
24165 (goto-char (1+ (match-end 4))))
24167 ;; Remove subtrees that are commented
24168 (goto-char (point-min))
24169 (while (re-search-forward re-commented nil t)
24170 (goto-char (match-beginning 0))
24171 (delete-region (point) (org-end-of-subtree t)))
24173 ;; Remove special table lines
24174 (when org-export-table-remove-special-lines
24175 (goto-char (point-min))
24176 (while (re-search-forward "^[ \t]*|" nil t)
24177 (beginning-of-line 1)
24178 (if (or (looking-at "[ \t]*| *[!_^] *|")
24179 (and (looking-at ".*?| *<[0-9]+> *|")
24180 (not (looking-at ".*?| *[^ <|]"))))
24181 (delete-region (max (point-min) (1- (point-at-bol)))
24182 (point-at-eol))
24183 (end-of-line 1))))
24185 ;; Specific LaTeX stuff
24186 (when latexp
24187 (require 'org-export-latex nil)
24188 (org-export-latex-cleaned-string))
24190 (when asciip
24191 (org-export-ascii-clean-string))
24193 ;; Specific HTML stuff
24194 (when htmlp
24195 ;; Convert LaTeX fragments to images
24196 (when (plist-get parameters :LaTeX-fragments)
24197 (org-format-latex
24198 (concat "ltxpng/" (file-name-sans-extension
24199 (file-name-nondirectory
24200 org-current-export-file)))
24201 org-current-export-dir nil "Creating LaTeX image %s"))
24202 (message "Exporting..."))
24204 ;; Remove or replace comments
24205 (goto-char (point-min))
24206 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24207 (if commentsp
24208 (progn (add-text-properties
24209 (match-beginning 0) (match-end 0) '(org-protected t))
24210 (replace-match (format commentsp (match-string 1)) t t))
24211 (replace-match "")))
24213 ;; Find matches for radio targets and turn them into internal links
24214 (goto-char (point-min))
24215 (when re-radio
24216 (while (re-search-forward re-radio nil t)
24217 (org-if-unprotected
24218 (replace-match "\\1[[\\2]]"))))
24220 ;; Find all links that contain a newline and put them into a single line
24221 (goto-char (point-min))
24222 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24223 (org-if-unprotected
24224 (replace-match "\\1 \\3")
24225 (goto-char (match-beginning 0))))
24228 ;; Normalize links: Convert angle and plain links into bracket links
24229 ;; Expand link abbreviations
24230 (goto-char (point-min))
24231 (while (re-search-forward re-plain-link nil t)
24232 (goto-char (1- (match-end 0)))
24233 (org-if-unprotected
24234 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24235 ":" (match-string 3) "]]")))
24236 ;; added 'org-link face to links
24237 (put-text-property 0 (length s) 'face 'org-link s)
24238 (replace-match s t t))))
24239 (goto-char (point-min))
24240 (while (re-search-forward re-angle-link nil t)
24241 (goto-char (1- (match-end 0)))
24242 (org-if-unprotected
24243 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24244 ":" (match-string 3) "]]")))
24245 (put-text-property 0 (length s) 'face 'org-link s)
24246 (replace-match s t t))))
24247 (goto-char (point-min))
24248 (while (re-search-forward org-bracket-link-regexp nil t)
24249 (org-if-unprotected
24250 (let* ((s (concat "[[" (setq xx (save-match-data
24251 (org-link-expand-abbrev (match-string 1))))
24253 (if (match-end 3)
24254 (match-string 2)
24255 (concat "[" xx "]"))
24256 "]")))
24257 (put-text-property 0 (length s) 'face 'org-link s)
24258 (replace-match s t t))))
24260 ;; Find multiline emphasis and put them into single line
24261 (when (plist-get parameters :emph-multiline)
24262 (goto-char (point-min))
24263 (while (re-search-forward org-emph-re nil t)
24264 (if (not (= (char-after (match-beginning 3))
24265 (char-after (match-beginning 4))))
24266 (org-if-unprotected
24267 (subst-char-in-region (match-beginning 0) (match-end 0)
24268 ?\n ?\ t)
24269 (goto-char (1- (match-end 0))))
24270 (goto-char (1+ (match-beginning 0))))))
24272 (setq rtn (buffer-string)))
24273 (kill-buffer " org-mode-tmp")
24274 rtn))
24276 (defun org-export-grab-title-from-buffer ()
24277 "Get a title for the current document, from looking at the buffer."
24278 (let ((inhibit-read-only t))
24279 (save-excursion
24280 (goto-char (point-min))
24281 (let ((end (save-excursion (outline-next-heading) (point))))
24282 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24283 ;; Mark the line so that it will not be exported as normal text.
24284 (org-unmodified
24285 (add-text-properties (match-beginning 0) (match-end 0)
24286 (list :org-license-to-kill t)))
24287 ;; Return the title string
24288 (org-trim (match-string 0)))))))
24290 (defun org-export-get-title-from-subtree ()
24291 "Return subtree title and exclude it from export."
24292 (let (title (m (mark)))
24293 (save-excursion
24294 (goto-char (region-beginning))
24295 (when (and (org-at-heading-p)
24296 (>= (org-end-of-subtree t t) (region-end)))
24297 ;; This is a subtree, we take the title from the first heading
24298 (goto-char (region-beginning))
24299 (looking-at org-todo-line-regexp)
24300 (setq title (match-string 3))
24301 (org-unmodified
24302 (add-text-properties (point) (1+ (point-at-eol))
24303 (list :org-license-to-kill t)))))
24304 title))
24306 (defun org-solidify-link-text (s &optional alist)
24307 "Take link text and make a safe target out of it."
24308 (save-match-data
24309 (let* ((rtn
24310 (mapconcat
24311 'identity
24312 (org-split-string s "[ \t\r\n]+") "--"))
24313 (a (assoc rtn alist)))
24314 (or (cdr a) rtn))))
24316 (defun org-get-min-level (lines)
24317 "Get the minimum level in LINES."
24318 (let ((re "^\\(\\*+\\) ") l min)
24319 (catch 'exit
24320 (while (setq l (pop lines))
24321 (if (string-match re l)
24322 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24323 1)))
24325 ;; Variable holding the vector with section numbers
24326 (defvar org-section-numbers (make-vector org-level-max 0))
24328 (defun org-init-section-numbers ()
24329 "Initialize the vector for the section numbers."
24330 (let* ((level -1)
24331 (numbers (nreverse (org-split-string "" "\\.")))
24332 (depth (1- (length org-section-numbers)))
24333 (i depth) number-string)
24334 (while (>= i 0)
24335 (if (> i level)
24336 (aset org-section-numbers i 0)
24337 (setq number-string (or (car numbers) "0"))
24338 (if (string-match "\\`[A-Z]\\'" number-string)
24339 (aset org-section-numbers i
24340 (- (string-to-char number-string) ?A -1))
24341 (aset org-section-numbers i (string-to-number number-string)))
24342 (pop numbers))
24343 (setq i (1- i)))))
24345 (defun org-section-number (&optional level)
24346 "Return a string with the current section number.
24347 When LEVEL is non-nil, increase section numbers on that level."
24348 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24349 (when level
24350 (when (> level -1)
24351 (aset org-section-numbers
24352 level (1+ (aref org-section-numbers level))))
24353 (setq idx (1+ level))
24354 (while (<= idx depth)
24355 (if (not (= idx 1))
24356 (aset org-section-numbers idx 0))
24357 (setq idx (1+ idx))))
24358 (setq idx 0)
24359 (while (<= idx depth)
24360 (setq n (aref org-section-numbers idx))
24361 (setq string (concat string (if (not (string= string "")) "." "")
24362 (int-to-string n)))
24363 (setq idx (1+ idx)))
24364 (save-match-data
24365 (if (string-match "\\`\\([@0]\\.\\)+" string)
24366 (setq string (replace-match "" t nil string)))
24367 (if (string-match "\\(\\.0\\)+\\'" string)
24368 (setq string (replace-match "" t nil string))))
24369 string))
24371 ;;; ASCII export
24373 (defvar org-last-level nil) ; dynamically scoped variable
24374 (defvar org-min-level nil) ; dynamically scoped variable
24375 (defvar org-levels-open nil) ; dynamically scoped parameter
24376 (defvar org-ascii-current-indentation nil) ; For communication
24378 (defun org-export-as-ascii (arg)
24379 "Export the outline as a pretty ASCII file.
24380 If there is an active region, export only the region.
24381 The prefix ARG specifies how many levels of the outline should become
24382 underlined headlines. The default is 3."
24383 (interactive "P")
24384 (setq-default org-todo-line-regexp org-todo-line-regexp)
24385 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24386 (org-infile-export-plist)))
24387 (region-p (org-region-active-p))
24388 (subtree-p
24389 (when region-p
24390 (save-excursion
24391 (goto-char (region-beginning))
24392 (and (org-at-heading-p)
24393 (>= (org-end-of-subtree t t) (region-end))))))
24394 (custom-times org-display-custom-times)
24395 (org-ascii-current-indentation '(0 . 0))
24396 (level 0) line txt
24397 (umax nil)
24398 (umax-toc nil)
24399 (case-fold-search nil)
24400 (filename (concat (file-name-as-directory
24401 (org-export-directory :ascii opt-plist))
24402 (file-name-sans-extension
24403 (or (and subtree-p
24404 (org-entry-get (region-beginning)
24405 "EXPORT_FILE_NAME" t))
24406 (file-name-nondirectory buffer-file-name)))
24407 ".txt"))
24408 (filename (if (equal (file-truename filename)
24409 (file-truename buffer-file-name))
24410 (concat filename ".txt")
24411 filename))
24412 (buffer (find-file-noselect filename))
24413 (org-levels-open (make-vector org-level-max nil))
24414 (odd org-odd-levels-only)
24415 (date (plist-get opt-plist :date))
24416 (author (plist-get opt-plist :author))
24417 (title (or (and subtree-p (org-export-get-title-from-subtree))
24418 (plist-get opt-plist :title)
24419 (and (not
24420 (plist-get opt-plist :skip-before-1st-heading))
24421 (org-export-grab-title-from-buffer))
24422 (file-name-sans-extension
24423 (file-name-nondirectory buffer-file-name))))
24424 (email (plist-get opt-plist :email))
24425 (language (plist-get opt-plist :language))
24426 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24427 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24428 (todo nil)
24429 (lang-words nil)
24430 (region
24431 (buffer-substring
24432 (if (org-region-active-p) (region-beginning) (point-min))
24433 (if (org-region-active-p) (region-end) (point-max))))
24434 (lines (org-split-string
24435 (org-cleaned-string-for-export
24436 region
24437 :for-ascii t
24438 :skip-before-1st-heading
24439 (plist-get opt-plist :skip-before-1st-heading)
24440 :drawers (plist-get opt-plist :drawers)
24441 :verbatim-multiline t
24442 :archived-trees
24443 (plist-get opt-plist :archived-trees)
24444 :add-text (plist-get opt-plist :text))
24445 "\n"))
24446 thetoc have-headings first-heading-pos
24447 table-open table-buffer)
24449 (let ((inhibit-read-only t))
24450 (org-unmodified
24451 (remove-text-properties (point-min) (point-max)
24452 '(:org-license-to-kill t))))
24454 (setq org-min-level (org-get-min-level lines))
24455 (setq org-last-level org-min-level)
24456 (org-init-section-numbers)
24458 (find-file-noselect filename)
24460 (setq lang-words (or (assoc language org-export-language-setup)
24461 (assoc "en" org-export-language-setup)))
24462 (switch-to-buffer-other-window buffer)
24463 (erase-buffer)
24464 (fundamental-mode)
24465 ;; create local variables for all options, to make sure all called
24466 ;; functions get the correct information
24467 (mapc (lambda (x)
24468 (set (make-local-variable (cdr x))
24469 (plist-get opt-plist (car x))))
24470 org-export-plist-vars)
24471 (org-set-local 'org-odd-levels-only odd)
24472 (setq umax (if arg (prefix-numeric-value arg)
24473 org-export-headline-levels))
24474 (setq umax-toc (if (integerp org-export-with-toc)
24475 (min org-export-with-toc umax)
24476 umax))
24478 ;; File header
24479 (if title (org-insert-centered title ?=))
24480 (insert "\n")
24481 (if (and (or author email)
24482 org-export-author-info)
24483 (insert (concat (nth 1 lang-words) ": " (or author "")
24484 (if email (concat " <" email ">") "")
24485 "\n")))
24487 (cond
24488 ((and date (string-match "%" date))
24489 (setq date (format-time-string date (current-time))))
24490 (date)
24491 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24493 (if (and date org-export-time-stamp-file)
24494 (insert (concat (nth 2 lang-words) ": " date"\n")))
24496 (insert "\n\n")
24498 (if org-export-with-toc
24499 (progn
24500 (push (concat (nth 3 lang-words) "\n") thetoc)
24501 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24502 (mapc '(lambda (line)
24503 (if (string-match org-todo-line-regexp
24504 line)
24505 ;; This is a headline
24506 (progn
24507 (setq have-headings t)
24508 (setq level (- (match-end 1) (match-beginning 1))
24509 level (org-tr-level level)
24510 txt (match-string 3 line)
24511 todo
24512 (or (and org-export-mark-todo-in-toc
24513 (match-beginning 2)
24514 (not (member (match-string 2 line)
24515 org-done-keywords)))
24516 ; TODO, not DONE
24517 (and org-export-mark-todo-in-toc
24518 (= level umax-toc)
24519 (org-search-todo-below
24520 line lines level))))
24521 (setq txt (org-html-expand-for-ascii txt))
24523 (while (string-match org-bracket-link-regexp txt)
24524 (setq txt
24525 (replace-match
24526 (match-string (if (match-end 2) 3 1) txt)
24527 t t txt)))
24529 (if (and (memq org-export-with-tags '(not-in-toc nil))
24530 (string-match
24531 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24532 txt))
24533 (setq txt (replace-match "" t t txt)))
24534 (if (string-match quote-re0 txt)
24535 (setq txt (replace-match "" t t txt)))
24537 (if org-export-with-section-numbers
24538 (setq txt (concat (org-section-number level)
24539 " " txt)))
24540 (if (<= level umax-toc)
24541 (progn
24542 (push
24543 (concat
24544 (make-string
24545 (* (max 0 (- level org-min-level)) 4) ?\ )
24546 (format (if todo "%s (*)\n" "%s\n") txt))
24547 thetoc)
24548 (setq org-last-level level))
24549 ))))
24550 lines)
24551 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24553 (org-init-section-numbers)
24554 (while (setq line (pop lines))
24555 ;; Remove the quoted HTML tags.
24556 (setq line (org-html-expand-for-ascii line))
24557 ;; Remove targets
24558 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24559 (setq line (replace-match "" t t line)))
24560 ;; Replace internal links
24561 (while (string-match org-bracket-link-regexp line)
24562 (setq line (replace-match
24563 (if (match-end 3) "[\\3]" "[\\1]")
24564 t nil line)))
24565 (when custom-times
24566 (setq line (org-translate-time line)))
24567 (cond
24568 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24569 ;; a Headline
24570 (setq first-heading-pos (or first-heading-pos (point)))
24571 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24572 txt (match-string 2 line))
24573 (org-ascii-level-start level txt umax lines))
24575 ((and org-export-with-tables
24576 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24577 (if (not table-open)
24578 ;; New table starts
24579 (setq table-open t table-buffer nil))
24580 ;; Accumulate lines
24581 (setq table-buffer (cons line table-buffer))
24582 (when (or (not lines)
24583 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24584 (car lines))))
24585 (setq table-open nil
24586 table-buffer (nreverse table-buffer))
24587 (insert (mapconcat
24588 (lambda (x)
24589 (org-fix-indentation x org-ascii-current-indentation))
24590 (org-format-table-ascii table-buffer)
24591 "\n") "\n")))
24593 (setq line (org-fix-indentation line org-ascii-current-indentation))
24594 (if (and org-export-with-fixed-width
24595 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24596 (setq line (replace-match "\\1" nil nil line)))
24597 (insert line "\n"))))
24599 (normal-mode)
24601 ;; insert the table of contents
24602 (when thetoc
24603 (goto-char (point-min))
24604 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24605 (progn
24606 (goto-char (match-beginning 0))
24607 (replace-match ""))
24608 (goto-char first-heading-pos))
24609 (mapc 'insert thetoc)
24610 (or (looking-at "[ \t]*\n[ \t]*\n")
24611 (insert "\n\n")))
24613 ;; Convert whitespace place holders
24614 (goto-char (point-min))
24615 (let (beg end)
24616 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24617 (setq end (next-single-property-change beg 'org-whitespace))
24618 (goto-char beg)
24619 (delete-region beg end)
24620 (insert (make-string (- end beg) ?\ ))))
24622 (save-buffer)
24623 ;; remove display and invisible chars
24624 (let (beg end)
24625 (goto-char (point-min))
24626 (while (setq beg (next-single-property-change (point) 'display))
24627 (setq end (next-single-property-change beg 'display))
24628 (delete-region beg end)
24629 (goto-char beg)
24630 (insert "=>"))
24631 (goto-char (point-min))
24632 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24633 (setq end (next-single-property-change beg 'org-cwidth))
24634 (delete-region beg end)
24635 (goto-char beg)))
24636 (goto-char (point-min))))
24638 (defun org-export-ascii-clean-string ()
24639 "Do extra work for ASCII export"
24640 (goto-char (point-min))
24641 (while (re-search-forward org-verbatim-re nil t)
24642 (goto-char (match-end 2))
24643 (backward-delete-char 1) (insert "'")
24644 (goto-char (match-beginning 2))
24645 (delete-char 1) (insert "`")
24646 (goto-char (match-end 2))))
24648 (defun org-search-todo-below (line lines level)
24649 "Search the subtree below LINE for any TODO entries."
24650 (let ((rest (cdr (memq line lines)))
24651 (re org-todo-line-regexp)
24652 line lv todo)
24653 (catch 'exit
24654 (while (setq line (pop rest))
24655 (if (string-match re line)
24656 (progn
24657 (setq lv (- (match-end 1) (match-beginning 1))
24658 todo (and (match-beginning 2)
24659 (not (member (match-string 2 line)
24660 org-done-keywords))))
24661 ; TODO, not DONE
24662 (if (<= lv level) (throw 'exit nil))
24663 (if todo (throw 'exit t))))))))
24665 (defun org-html-expand-for-ascii (line)
24666 "Handle quoted HTML for ASCII export."
24667 (if org-export-html-expand
24668 (while (string-match "@<[^<>\n]*>" line)
24669 ;; We just remove the tags for now.
24670 (setq line (replace-match "" nil nil line))))
24671 line)
24673 (defun org-insert-centered (s &optional underline)
24674 "Insert the string S centered and underline it with character UNDERLINE."
24675 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24676 (insert (make-string ind ?\ ) s "\n")
24677 (if underline
24678 (insert (make-string ind ?\ )
24679 (make-string (string-width s) underline)
24680 "\n"))))
24682 (defun org-ascii-level-start (level title umax &optional lines)
24683 "Insert a new level in ASCII export."
24684 (let (char (n (- level umax 1)) (ind 0))
24685 (if (> level umax)
24686 (progn
24687 (insert (make-string (* 2 n) ?\ )
24688 (char-to-string (nth (% n (length org-export-ascii-bullets))
24689 org-export-ascii-bullets))
24690 " " title "\n")
24691 ;; find the indentation of the next non-empty line
24692 (catch 'stop
24693 (while lines
24694 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24695 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24696 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24697 (pop lines)))
24698 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24699 (if (or (not (equal (char-before) ?\n))
24700 (not (equal (char-before (1- (point))) ?\n)))
24701 (insert "\n"))
24702 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24703 (unless org-export-with-tags
24704 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24705 (setq title (replace-match "" t t title))))
24706 (if org-export-with-section-numbers
24707 (setq title (concat (org-section-number level) " " title)))
24708 (insert title "\n" (make-string (string-width title) char) "\n")
24709 (setq org-ascii-current-indentation '(0 . 0)))))
24711 (defun org-export-visible (type arg)
24712 "Create a copy of the visible part of the current buffer, and export it.
24713 The copy is created in a temporary buffer and removed after use.
24714 TYPE is the final key (as a string) that also select the export command in
24715 the `C-c C-e' export dispatcher.
24716 As a special case, if the you type SPC at the prompt, the temporary
24717 org-mode file will not be removed but presented to you so that you can
24718 continue to use it. The prefix arg ARG is passed through to the exporting
24719 command."
24720 (interactive
24721 (list (progn
24722 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24723 (read-char-exclusive))
24724 current-prefix-arg))
24725 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24726 (error "Invalid export key"))
24727 (let* ((binding (cdr (assoc type
24728 '((?a . org-export-as-ascii)
24729 (?\C-a . org-export-as-ascii)
24730 (?b . org-export-as-html-and-open)
24731 (?\C-b . org-export-as-html-and-open)
24732 (?h . org-export-as-html)
24733 (?H . org-export-as-html-to-buffer)
24734 (?R . org-export-region-as-html)
24735 (?x . org-export-as-xoxo)))))
24736 (keepp (equal type ?\ ))
24737 (file buffer-file-name)
24738 (buffer (get-buffer-create "*Org Export Visible*"))
24739 s e)
24740 ;; Need to hack the drawers here.
24741 (save-excursion
24742 (goto-char (point-min))
24743 (while (re-search-forward org-drawer-regexp nil t)
24744 (goto-char (match-beginning 1))
24745 (or (org-invisible-p) (org-flag-drawer nil))))
24746 (with-current-buffer buffer (erase-buffer))
24747 (save-excursion
24748 (setq s (goto-char (point-min)))
24749 (while (not (= (point) (point-max)))
24750 (goto-char (org-find-invisible))
24751 (append-to-buffer buffer s (point))
24752 (setq s (goto-char (org-find-visible))))
24753 (org-cycle-hide-drawers 'all)
24754 (goto-char (point-min))
24755 (unless keepp
24756 ;; Copy all comment lines to the end, to make sure #+ settings are
24757 ;; still available for the second export step. Kind of a hack, but
24758 ;; does do the trick.
24759 (if (looking-at "#[^\r\n]*")
24760 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24761 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24762 (append-to-buffer buffer (1+ (match-beginning 0))
24763 (min (point-max) (1+ (match-end 0))))))
24764 (set-buffer buffer)
24765 (let ((buffer-file-name file)
24766 (org-inhibit-startup t))
24767 (org-mode)
24768 (show-all)
24769 (unless keepp (funcall binding arg))))
24770 (if (not keepp)
24771 (kill-buffer buffer)
24772 (switch-to-buffer-other-window buffer)
24773 (goto-char (point-min)))))
24775 (defun org-find-visible ()
24776 (let ((s (point)))
24777 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24778 (get-char-property s 'invisible)))
24780 (defun org-find-invisible ()
24781 (let ((s (point)))
24782 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24783 (not (get-char-property s 'invisible))))
24786 ;;; HTML export
24788 (defun org-get-current-options ()
24789 "Return a string with current options as keyword options.
24790 Does include HTML export options as well as TODO and CATEGORY stuff."
24791 (format
24792 "#+TITLE: %s
24793 #+AUTHOR: %s
24794 #+EMAIL: %s
24795 #+LANGUAGE: %s
24796 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24797 #+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
24798 #+CATEGORY: %s
24799 #+SEQ_TODO: %s
24800 #+TYP_TODO: %s
24801 #+PRIORITIES: %c %c %c
24802 #+DRAWERS: %s
24803 #+STARTUP: %s %s %s %s %s
24804 #+TAGS: %s
24805 #+ARCHIVE: %s
24806 #+LINK: %s
24808 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24809 org-export-headline-levels
24810 org-export-with-section-numbers
24811 org-export-with-toc
24812 org-export-preserve-breaks
24813 org-export-html-expand
24814 org-export-with-fixed-width
24815 org-export-with-tables
24816 org-export-with-sub-superscripts
24817 org-export-with-special-strings
24818 org-export-with-footnotes
24819 org-export-with-emphasize
24820 org-export-with-TeX-macros
24821 org-export-with-LaTeX-fragments
24822 org-export-skip-text-before-1st-heading
24823 org-export-with-drawers
24824 org-export-with-tags
24825 (file-name-nondirectory buffer-file-name)
24826 "TODO FEEDBACK VERIFY DONE"
24827 "Me Jason Marie DONE"
24828 org-highest-priority org-lowest-priority org-default-priority
24829 (mapconcat 'identity org-drawers " ")
24830 (cdr (assoc org-startup-folded
24831 '((nil . "showall") (t . "overview") (content . "content"))))
24832 (if org-odd-levels-only "odd" "oddeven")
24833 (if org-hide-leading-stars "hidestars" "showstars")
24834 (if org-startup-align-all-tables "align" "noalign")
24835 (cond ((eq org-log-done t) "logdone")
24836 ((equal org-log-done 'note) "lognotedone")
24837 ((not org-log-done) "nologdone"))
24838 (or (mapconcat (lambda (x)
24839 (cond
24840 ((equal '(:startgroup) x) "{")
24841 ((equal '(:endgroup) x) "}")
24842 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24843 (t (car x))))
24844 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24845 org-archive-location
24846 "org file:~/org/%s.org"
24849 (defun org-insert-export-options-template ()
24850 "Insert into the buffer a template with information for exporting."
24851 (interactive)
24852 (if (not (bolp)) (newline))
24853 (let ((s (org-get-current-options)))
24854 (and (string-match "#\\+CATEGORY" s)
24855 (setq s (substring s 0 (match-beginning 0))))
24856 (insert s)))
24858 (defun org-toggle-fixed-width-section (arg)
24859 "Toggle the fixed-width export.
24860 If there is no active region, the QUOTE keyword at the current headline is
24861 inserted or removed. When present, it causes the text between this headline
24862 and the next to be exported as fixed-width text, and unmodified.
24863 If there is an active region, this command adds or removes a colon as the
24864 first character of this line. If the first character of a line is a colon,
24865 this line is also exported in fixed-width font."
24866 (interactive "P")
24867 (let* ((cc 0)
24868 (regionp (org-region-active-p))
24869 (beg (if regionp (region-beginning) (point)))
24870 (end (if regionp (region-end)))
24871 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24872 (case-fold-search nil)
24873 (re "[ \t]*\\(:\\)")
24874 off)
24875 (if regionp
24876 (save-excursion
24877 (goto-char beg)
24878 (setq cc (current-column))
24879 (beginning-of-line 1)
24880 (setq off (looking-at re))
24881 (while (> nlines 0)
24882 (setq nlines (1- nlines))
24883 (beginning-of-line 1)
24884 (cond
24885 (arg
24886 (move-to-column cc t)
24887 (insert ":\n")
24888 (forward-line -1))
24889 ((and off (looking-at re))
24890 (replace-match "" t t nil 1))
24891 ((not off) (move-to-column cc t) (insert ":")))
24892 (forward-line 1)))
24893 (save-excursion
24894 (org-back-to-heading)
24895 (if (looking-at (concat outline-regexp
24896 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24897 (replace-match "" t t nil 1)
24898 (if (looking-at outline-regexp)
24899 (progn
24900 (goto-char (match-end 0))
24901 (insert org-quote-string " "))))))))
24903 (defun org-export-as-html-and-open (arg)
24904 "Export the outline as HTML and immediately open it with a browser.
24905 If there is an active region, export only the region.
24906 The prefix ARG specifies how many levels of the outline should become
24907 headlines. The default is 3. Lower levels will become bulleted lists."
24908 (interactive "P")
24909 (org-export-as-html arg 'hidden)
24910 (org-open-file buffer-file-name))
24912 (defun org-export-as-html-batch ()
24913 "Call `org-export-as-html', may be used in batch processing as
24914 emacs --batch
24915 --load=$HOME/lib/emacs/org.el
24916 --eval \"(setq org-export-headline-levels 2)\"
24917 --visit=MyFile --funcall org-export-as-html-batch"
24918 (org-export-as-html org-export-headline-levels 'hidden))
24920 (defun org-export-as-html-to-buffer (arg)
24921 "Call `org-exort-as-html` with output to a temporary buffer.
24922 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24923 (interactive "P")
24924 (org-export-as-html arg nil nil "*Org HTML Export*")
24925 (switch-to-buffer-other-window "*Org HTML Export*"))
24927 (defun org-replace-region-by-html (beg end)
24928 "Assume the current region has org-mode syntax, and convert it to HTML.
24929 This can be used in any buffer. For example, you could write an
24930 itemized list in org-mode syntax in an HTML buffer and then use this
24931 command to convert it."
24932 (interactive "r")
24933 (let (reg html buf pop-up-frames)
24934 (save-window-excursion
24935 (if (org-mode-p)
24936 (setq html (org-export-region-as-html
24937 beg end t 'string))
24938 (setq reg (buffer-substring beg end)
24939 buf (get-buffer-create "*Org tmp*"))
24940 (with-current-buffer buf
24941 (erase-buffer)
24942 (insert reg)
24943 (org-mode)
24944 (setq html (org-export-region-as-html
24945 (point-min) (point-max) t 'string)))
24946 (kill-buffer buf)))
24947 (delete-region beg end)
24948 (insert html)))
24950 (defun org-export-region-as-html (beg end &optional body-only buffer)
24951 "Convert region from BEG to END in org-mode buffer to HTML.
24952 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24953 contents, and only produce the region of converted text, useful for
24954 cut-and-paste operations.
24955 If BUFFER is a buffer or a string, use/create that buffer as a target
24956 of the converted HTML. If BUFFER is the symbol `string', return the
24957 produced HTML as a string and leave not buffer behind. For example,
24958 a Lisp program could call this function in the following way:
24960 (setq html (org-export-region-as-html beg end t 'string))
24962 When called interactively, the output buffer is selected, and shown
24963 in a window. A non-interactive call will only retunr the buffer."
24964 (interactive "r\nP")
24965 (when (interactive-p)
24966 (setq buffer "*Org HTML Export*"))
24967 (let ((transient-mark-mode t) (zmacs-regions t)
24968 rtn)
24969 (goto-char end)
24970 (set-mark (point)) ;; to activate the region
24971 (goto-char beg)
24972 (setq rtn (org-export-as-html
24973 nil nil nil
24974 buffer body-only))
24975 (if (fboundp 'deactivate-mark) (deactivate-mark))
24976 (if (and (interactive-p) (bufferp rtn))
24977 (switch-to-buffer-other-window rtn)
24978 rtn)))
24980 (defvar html-table-tag nil) ; dynamically scoped into this.
24981 (defun org-export-as-html (arg &optional hidden ext-plist
24982 to-buffer body-only)
24983 "Export the outline as a pretty HTML file.
24984 If there is an active region, export only the region. The prefix
24985 ARG specifies how many levels of the outline should become
24986 headlines. The default is 3. Lower levels will become bulleted
24987 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24988 EXT-PLIST is a property list with external parameters overriding
24989 org-mode's default settings, but still inferior to file-local
24990 settings. When TO-BUFFER is non-nil, create a buffer with that
24991 name and export to that buffer. If TO-BUFFER is the symbol `string',
24992 don't leave any buffer behind but just return the resulting HTML as
24993 a string. When BODY-ONLY is set, don't produce the file header and footer,
24994 simply return the content of <body>...</body>, without even
24995 the body tags themselves."
24996 (interactive "P")
24998 ;; Make sure we have a file name when we need it.
24999 (when (and (not (or to-buffer body-only))
25000 (not buffer-file-name))
25001 (if (buffer-base-buffer)
25002 (org-set-local 'buffer-file-name
25003 (with-current-buffer (buffer-base-buffer)
25004 buffer-file-name))
25005 (error "Need a file name to be able to export.")))
25007 (message "Exporting...")
25008 (setq-default org-todo-line-regexp org-todo-line-regexp)
25009 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25010 (setq-default org-done-keywords org-done-keywords)
25011 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25012 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25013 ext-plist
25014 (org-infile-export-plist)))
25016 (style (plist-get opt-plist :style))
25017 (html-extension (plist-get opt-plist :html-extension))
25018 (link-validate (plist-get opt-plist :link-validation-function))
25019 valid thetoc have-headings first-heading-pos
25020 (odd org-odd-levels-only)
25021 (region-p (org-region-active-p))
25022 (subtree-p
25023 (when region-p
25024 (save-excursion
25025 (goto-char (region-beginning))
25026 (and (org-at-heading-p)
25027 (>= (org-end-of-subtree t t) (region-end))))))
25028 ;; The following two are dynamically scoped into other
25029 ;; routines below.
25030 (org-current-export-dir (org-export-directory :html opt-plist))
25031 (org-current-export-file buffer-file-name)
25032 (level 0) (line "") (origline "") txt todo
25033 (umax nil)
25034 (umax-toc nil)
25035 (filename (if to-buffer nil
25036 (expand-file-name
25037 (concat
25038 (file-name-sans-extension
25039 (or (and subtree-p
25040 (org-entry-get (region-beginning)
25041 "EXPORT_FILE_NAME" t))
25042 (file-name-nondirectory buffer-file-name)))
25043 "." html-extension)
25044 (file-name-as-directory
25045 (org-export-directory :html opt-plist)))))
25046 (current-dir (if buffer-file-name
25047 (file-name-directory buffer-file-name)
25048 default-directory))
25049 (buffer (if to-buffer
25050 (cond
25051 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25052 (t (get-buffer-create to-buffer)))
25053 (find-file-noselect filename)))
25054 (org-levels-open (make-vector org-level-max nil))
25055 (date (plist-get opt-plist :date))
25056 (author (plist-get opt-plist :author))
25057 (title (or (and subtree-p (org-export-get-title-from-subtree))
25058 (plist-get opt-plist :title)
25059 (and (not
25060 (plist-get opt-plist :skip-before-1st-heading))
25061 (org-export-grab-title-from-buffer))
25062 (and buffer-file-name
25063 (file-name-sans-extension
25064 (file-name-nondirectory buffer-file-name)))
25065 "UNTITLED"))
25066 (html-table-tag (plist-get opt-plist :html-table-tag))
25067 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25068 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25069 (inquote nil)
25070 (infixed nil)
25071 (in-local-list nil)
25072 (local-list-num nil)
25073 (local-list-indent nil)
25074 (llt org-plain-list-ordered-item-terminator)
25075 (email (plist-get opt-plist :email))
25076 (language (plist-get opt-plist :language))
25077 (lang-words nil)
25078 (target-alist nil) tg
25079 (head-count 0) cnt
25080 (start 0)
25081 (coding-system (and (boundp 'buffer-file-coding-system)
25082 buffer-file-coding-system))
25083 (coding-system-for-write (or org-export-html-coding-system
25084 coding-system))
25085 (save-buffer-coding-system (or org-export-html-coding-system
25086 coding-system))
25087 (charset (and coding-system-for-write
25088 (fboundp 'coding-system-get)
25089 (coding-system-get coding-system-for-write
25090 'mime-charset)))
25091 (region
25092 (buffer-substring
25093 (if region-p (region-beginning) (point-min))
25094 (if region-p (region-end) (point-max))))
25095 (lines
25096 (org-split-string
25097 (org-cleaned-string-for-export
25098 region
25099 :emph-multiline t
25100 :for-html t
25101 :skip-before-1st-heading
25102 (plist-get opt-plist :skip-before-1st-heading)
25103 :drawers (plist-get opt-plist :drawers)
25104 :archived-trees
25105 (plist-get opt-plist :archived-trees)
25106 :add-text
25107 (plist-get opt-plist :text)
25108 :LaTeX-fragments
25109 (plist-get opt-plist :LaTeX-fragments))
25110 "[\r\n]"))
25111 table-open type
25112 table-buffer table-orig-buffer
25113 ind start-is-num starter didclose
25114 rpl path desc descp desc1 desc2 link
25117 (let ((inhibit-read-only t))
25118 (org-unmodified
25119 (remove-text-properties (point-min) (point-max)
25120 '(:org-license-to-kill t))))
25122 (message "Exporting...")
25124 (setq org-min-level (org-get-min-level lines))
25125 (setq org-last-level org-min-level)
25126 (org-init-section-numbers)
25128 (cond
25129 ((and date (string-match "%" date))
25130 (setq date (format-time-string date (current-time))))
25131 (date)
25132 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25134 ;; Get the language-dependent settings
25135 (setq lang-words (or (assoc language org-export-language-setup)
25136 (assoc "en" org-export-language-setup)))
25138 ;; Switch to the output buffer
25139 (set-buffer buffer)
25140 (let ((inhibit-read-only t)) (erase-buffer))
25141 (fundamental-mode)
25143 (and (fboundp 'set-buffer-file-coding-system)
25144 (set-buffer-file-coding-system coding-system-for-write))
25146 (let ((case-fold-search nil)
25147 (org-odd-levels-only odd))
25148 ;; create local variables for all options, to make sure all called
25149 ;; functions get the correct information
25150 (mapc (lambda (x)
25151 (set (make-local-variable (cdr x))
25152 (plist-get opt-plist (car x))))
25153 org-export-plist-vars)
25154 (setq umax (if arg (prefix-numeric-value arg)
25155 org-export-headline-levels))
25156 (setq umax-toc (if (integerp org-export-with-toc)
25157 (min org-export-with-toc umax)
25158 umax))
25159 (unless body-only
25160 ;; File header
25161 (insert (format
25162 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25163 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25164 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25165 lang=\"%s\" xml:lang=\"%s\">
25166 <head>
25167 <title>%s</title>
25168 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25169 <meta name=\"generator\" content=\"Org-mode\"/>
25170 <meta name=\"generated\" content=\"%s\"/>
25171 <meta name=\"author\" content=\"%s\"/>
25173 </head><body>
25175 language language (org-html-expand title)
25176 (or charset "iso-8859-1") date author style))
25178 (insert (or (plist-get opt-plist :preamble) ""))
25180 (when (plist-get opt-plist :auto-preamble)
25181 (if title (insert (format org-export-html-title-format
25182 (org-html-expand title))))))
25184 (if (and org-export-with-toc (not body-only))
25185 (progn
25186 (push (format "<h%d>%s</h%d>\n"
25187 org-export-html-toplevel-hlevel
25188 (nth 3 lang-words)
25189 org-export-html-toplevel-hlevel)
25190 thetoc)
25191 (push "<ul>\n<li>" thetoc)
25192 (setq lines
25193 (mapcar '(lambda (line)
25194 (if (string-match org-todo-line-regexp line)
25195 ;; This is a headline
25196 (progn
25197 (setq have-headings t)
25198 (setq level (- (match-end 1) (match-beginning 1))
25199 level (org-tr-level level)
25200 txt (save-match-data
25201 (org-html-expand
25202 (org-export-cleanup-toc-line
25203 (match-string 3 line))))
25204 todo
25205 (or (and org-export-mark-todo-in-toc
25206 (match-beginning 2)
25207 (not (member (match-string 2 line)
25208 org-done-keywords)))
25209 ; TODO, not DONE
25210 (and org-export-mark-todo-in-toc
25211 (= level umax-toc)
25212 (org-search-todo-below
25213 line lines level))))
25214 (if (string-match
25215 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25216 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25217 (if (string-match quote-re0 txt)
25218 (setq txt (replace-match "" t t txt)))
25219 (if org-export-with-section-numbers
25220 (setq txt (concat (org-section-number level)
25221 " " txt)))
25222 (if (<= level (max umax umax-toc))
25223 (setq head-count (+ head-count 1)))
25224 (if (<= level umax-toc)
25225 (progn
25226 (if (> level org-last-level)
25227 (progn
25228 (setq cnt (- level org-last-level))
25229 (while (>= (setq cnt (1- cnt)) 0)
25230 (push "\n<ul>\n<li>" thetoc))
25231 (push "\n" thetoc)))
25232 (if (< level org-last-level)
25233 (progn
25234 (setq cnt (- org-last-level level))
25235 (while (>= (setq cnt (1- cnt)) 0)
25236 (push "</li>\n</ul>" thetoc))
25237 (push "\n" thetoc)))
25238 ;; Check for targets
25239 (while (string-match org-target-regexp line)
25240 (setq tg (match-string 1 line)
25241 line (replace-match
25242 (concat "@<span class=\"target\">" tg "@</span> ")
25243 t t line))
25244 (push (cons (org-solidify-link-text tg)
25245 (format "sec-%d" head-count))
25246 target-alist))
25247 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25248 (setq txt (replace-match "" t t txt)))
25249 (push
25250 (format
25251 (if todo
25252 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25253 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25254 head-count txt) thetoc)
25256 (setq org-last-level level))
25258 line)
25259 lines))
25260 (while (> org-last-level (1- org-min-level))
25261 (setq org-last-level (1- org-last-level))
25262 (push "</li>\n</ul>\n" thetoc))
25263 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25265 (setq head-count 0)
25266 (org-init-section-numbers)
25268 (while (setq line (pop lines) origline line)
25269 (catch 'nextline
25271 ;; end of quote section?
25272 (when (and inquote (string-match "^\\*+ " line))
25273 (insert "</pre>\n")
25274 (setq inquote nil))
25275 ;; inside a quote section?
25276 (when inquote
25277 (insert (org-html-protect line) "\n")
25278 (throw 'nextline nil))
25280 ;; verbatim lines
25281 (when (and org-export-with-fixed-width
25282 (string-match "^[ \t]*:\\(.*\\)" line))
25283 (when (not infixed)
25284 (setq infixed t)
25285 (insert "<pre>\n"))
25286 (insert (org-html-protect (match-string 1 line)) "\n")
25287 (when (and lines
25288 (not (string-match "^[ \t]*\\(:.*\\)"
25289 (car lines))))
25290 (setq infixed nil)
25291 (insert "</pre>\n"))
25292 (throw 'nextline nil))
25294 ;; Protected HTML
25295 (when (get-text-property 0 'org-protected line)
25296 (let (par)
25297 (when (re-search-backward
25298 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25299 (setq par (match-string 1))
25300 (replace-match "\\2\n"))
25301 (insert line "\n")
25302 (while (and lines
25303 (or (= (length (car lines)) 0)
25304 (get-text-property 0 'org-protected (car lines))))
25305 (insert (pop lines) "\n"))
25306 (and par (insert "<p>\n")))
25307 (throw 'nextline nil))
25309 ;; Horizontal line
25310 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25311 (insert "\n<hr/>\n")
25312 (throw 'nextline nil))
25314 ;; make targets to anchors
25315 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25316 (cond
25317 ((match-end 2)
25318 (setq line (replace-match
25319 (concat "@<a name=\""
25320 (org-solidify-link-text (match-string 1 line))
25321 "\">\\nbsp@</a>")
25322 t t line)))
25323 ((and org-export-with-toc (equal (string-to-char line) ?*))
25324 (setq line (replace-match
25325 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25326 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25327 t t line)))
25329 (setq line (replace-match
25330 (concat "@<a name=\""
25331 (org-solidify-link-text (match-string 1 line))
25332 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25333 t t line)))))
25335 (setq line (org-html-handle-time-stamps line))
25337 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25338 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25339 ;; Also handle sub_superscripts and checkboxes
25340 (or (string-match org-table-hline-regexp line)
25341 (setq line (org-html-expand line)))
25343 ;; Format the links
25344 (setq start 0)
25345 (while (string-match org-bracket-link-analytic-regexp line start)
25346 (setq start (match-beginning 0))
25347 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25348 (setq path (match-string 3 line))
25349 (setq desc1 (if (match-end 5) (match-string 5 line))
25350 desc2 (if (match-end 2) (concat type ":" path) path)
25351 descp (and desc1 (not (equal desc1 desc2)))
25352 desc (or desc1 desc2))
25353 ;; Make an image out of the description if that is so wanted
25354 (when (and descp (org-file-image-p desc))
25355 (save-match-data
25356 (if (string-match "^file:" desc)
25357 (setq desc (substring desc (match-end 0)))))
25358 (setq desc (concat "<img src=\"" desc "\"/>")))
25359 ;; FIXME: do we need to unescape here somewhere?
25360 (cond
25361 ((equal type "internal")
25362 (setq rpl
25363 (concat
25364 "<a href=\"#"
25365 (org-solidify-link-text
25366 (save-match-data (org-link-unescape path)) target-alist)
25367 "\">" desc "</a>")))
25368 ((member type '("http" "https"))
25369 ;; standard URL, just check if we need to inline an image
25370 (if (and (or (eq t org-export-html-inline-images)
25371 (and org-export-html-inline-images (not descp)))
25372 (org-file-image-p path))
25373 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25374 (setq link (concat type ":" path))
25375 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25376 ((member type '("ftp" "mailto" "news"))
25377 ;; standard URL
25378 (setq link (concat type ":" path))
25379 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25380 ((string= type "file")
25381 ;; FILE link
25382 (let* ((filename path)
25383 (abs-p (file-name-absolute-p filename))
25384 thefile file-is-image-p search)
25385 (save-match-data
25386 (if (string-match "::\\(.*\\)" filename)
25387 (setq search (match-string 1 filename)
25388 filename (replace-match "" t nil filename)))
25389 (setq valid
25390 (if (functionp link-validate)
25391 (funcall link-validate filename current-dir)
25393 (setq file-is-image-p (org-file-image-p filename))
25394 (setq thefile (if abs-p (expand-file-name filename) filename))
25395 (when (and org-export-html-link-org-files-as-html
25396 (string-match "\\.org$" thefile))
25397 (setq thefile (concat (substring thefile 0
25398 (match-beginning 0))
25399 "." html-extension))
25400 (if (and search
25401 ;; make sure this is can be used as target search
25402 (not (string-match "^[0-9]*$" search))
25403 (not (string-match "^\\*" search))
25404 (not (string-match "^/.*/$" search)))
25405 (setq thefile (concat thefile "#"
25406 (org-solidify-link-text
25407 (org-link-unescape search)))))
25408 (when (string-match "^file:" desc)
25409 (setq desc (replace-match "" t t desc))
25410 (if (string-match "\\.org$" desc)
25411 (setq desc (replace-match "" t t desc))))))
25412 (setq rpl (if (and file-is-image-p
25413 (or (eq t org-export-html-inline-images)
25414 (and org-export-html-inline-images
25415 (not descp))))
25416 (concat "<img src=\"" thefile "\"/>")
25417 (concat "<a href=\"" thefile "\">" desc "</a>")))
25418 (if (not valid) (setq rpl desc))))
25419 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25420 (setq rpl (concat "<i>&lt;" type ":"
25421 (save-match-data (org-link-unescape path))
25422 "&gt;</i>"))))
25423 (setq line (replace-match rpl t t line)
25424 start (+ start (length rpl))))
25426 ;; TODO items
25427 (if (and (string-match org-todo-line-regexp line)
25428 (match-beginning 2))
25430 (setq line
25431 (concat (substring line 0 (match-beginning 2))
25432 "<span class=\""
25433 (if (member (match-string 2 line)
25434 org-done-keywords)
25435 "done" "todo")
25436 "\">" (match-string 2 line)
25437 "</span>" (substring line (match-end 2)))))
25439 ;; Does this contain a reference to a footnote?
25440 (when org-export-with-footnotes
25441 (setq start 0)
25442 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25443 (if (get-text-property (match-beginning 2) 'org-protected line)
25444 (setq start (match-end 2))
25445 (let ((n (match-string 2 line)))
25446 (setq line
25447 (replace-match
25448 (format
25449 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25450 (match-string 1 line) n n n)
25451 t t line))))))
25453 (cond
25454 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25455 ;; This is a headline
25456 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25457 txt (match-string 2 line))
25458 (if (string-match quote-re0 txt)
25459 (setq txt (replace-match "" t t txt)))
25460 (if (<= level (max umax umax-toc))
25461 (setq head-count (+ head-count 1)))
25462 (when in-local-list
25463 ;; Close any local lists before inserting a new header line
25464 (while local-list-num
25465 (org-close-li)
25466 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25467 (pop local-list-num))
25468 (setq local-list-indent nil
25469 in-local-list nil))
25470 (setq first-heading-pos (or first-heading-pos (point)))
25471 (org-html-level-start level txt umax
25472 (and org-export-with-toc (<= level umax))
25473 head-count)
25474 ;; QUOTES
25475 (when (string-match quote-re line)
25476 (insert "<pre>")
25477 (setq inquote t)))
25479 ((and org-export-with-tables
25480 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25481 (if (not table-open)
25482 ;; New table starts
25483 (setq table-open t table-buffer nil table-orig-buffer nil))
25484 ;; Accumulate lines
25485 (setq table-buffer (cons line table-buffer)
25486 table-orig-buffer (cons origline table-orig-buffer))
25487 (when (or (not lines)
25488 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25489 (car lines))))
25490 (setq table-open nil
25491 table-buffer (nreverse table-buffer)
25492 table-orig-buffer (nreverse table-orig-buffer))
25493 (org-close-par-maybe)
25494 (insert (org-format-table-html table-buffer table-orig-buffer))))
25496 ;; Normal lines
25497 (when (string-match
25498 (cond
25499 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25500 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25501 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25502 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25503 line)
25504 (setq ind (org-get-string-indentation line)
25505 start-is-num (match-beginning 4)
25506 starter (if (match-beginning 2)
25507 (substring (match-string 2 line) 0 -1))
25508 line (substring line (match-beginning 5)))
25509 (unless (string-match "[^ \t]" line)
25510 ;; empty line. Pretend indentation is large.
25511 (setq ind (if org-empty-line-terminates-plain-lists
25513 (1+ (or (car local-list-indent) 1)))))
25514 (setq didclose nil)
25515 (while (and in-local-list
25516 (or (and (= ind (car local-list-indent))
25517 (not starter))
25518 (< ind (car local-list-indent))))
25519 (setq didclose t)
25520 (org-close-li)
25521 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25522 (pop local-list-num) (pop local-list-indent)
25523 (setq in-local-list local-list-indent))
25524 (cond
25525 ((and starter
25526 (or (not in-local-list)
25527 (> ind (car local-list-indent))))
25528 ;; Start new (level of) list
25529 (org-close-par-maybe)
25530 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25531 (push start-is-num local-list-num)
25532 (push ind local-list-indent)
25533 (setq in-local-list t))
25534 (starter
25535 ;; continue current list
25536 (org-close-li)
25537 (insert "<li>\n"))
25538 (didclose
25539 ;; we did close a list, normal text follows: need <p>
25540 (org-open-par)))
25541 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25542 (setq line
25543 (replace-match
25544 (if (equal (match-string 1 line) "X")
25545 "<b>[X]</b>"
25546 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25547 t t line))))
25549 ;; Empty lines start a new paragraph. If hand-formatted lists
25550 ;; are not fully interpreted, lines starting with "-", "+", "*"
25551 ;; also start a new paragraph.
25552 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25554 ;; Is this the start of a footnote?
25555 (when org-export-with-footnotes
25556 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25557 (org-close-par-maybe)
25558 (let ((n (match-string 1 line)))
25559 (setq line (replace-match
25560 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25562 ;; Check if the line break needs to be conserved
25563 (cond
25564 ((string-match "\\\\\\\\[ \t]*$" line)
25565 (setq line (replace-match "<br/>" t t line)))
25566 (org-export-preserve-breaks
25567 (setq line (concat line "<br/>"))))
25569 (insert line "\n")))))
25571 ;; Properly close all local lists and other lists
25572 (when inquote (insert "</pre>\n"))
25573 (when in-local-list
25574 ;; Close any local lists before inserting a new header line
25575 (while local-list-num
25576 (org-close-li)
25577 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25578 (pop local-list-num))
25579 (setq local-list-indent nil
25580 in-local-list nil))
25581 (org-html-level-start 1 nil umax
25582 (and org-export-with-toc (<= level umax))
25583 head-count)
25585 (unless body-only
25586 (when (plist-get opt-plist :auto-postamble)
25587 (insert "<div id=\"postamble\">")
25588 (when (and org-export-author-info author)
25589 (insert "<p class=\"author\"> "
25590 (nth 1 lang-words) ": " author "\n")
25591 (when email
25592 (if (listp (split-string email ",+ *"))
25593 (mapc (lambda(e)
25594 (insert "<a href=\"mailto:" e "\">&lt;"
25595 e "&gt;</a>\n"))
25596 (split-string email ",+ *"))
25597 (insert "<a href=\"mailto:" email "\">&lt;"
25598 email "&gt;</a>\n")))
25599 (insert "</p>\n"))
25600 (when (and date org-export-time-stamp-file)
25601 (insert "<p class=\"date\"> "
25602 (nth 2 lang-words) ": "
25603 date "</p>\n"))
25604 (insert "</div>"))
25606 (if org-export-html-with-timestamp
25607 (insert org-export-html-html-helper-timestamp))
25608 (insert (or (plist-get opt-plist :postamble) ""))
25609 (insert "</body>\n</html>\n"))
25611 (normal-mode)
25612 (if (eq major-mode default-major-mode) (html-mode))
25614 ;; insert the table of contents
25615 (goto-char (point-min))
25616 (when thetoc
25617 (if (or (re-search-forward
25618 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25619 (re-search-forward
25620 "\\[TABLE-OF-CONTENTS\\]" nil t))
25621 (progn
25622 (goto-char (match-beginning 0))
25623 (replace-match ""))
25624 (goto-char first-heading-pos)
25625 (when (looking-at "\\s-*</p>")
25626 (goto-char (match-end 0))
25627 (insert "\n")))
25628 (insert "<div id=\"table-of-contents\">\n")
25629 (mapc 'insert thetoc)
25630 (insert "</div>\n"))
25631 ;; remove empty paragraphs and lists
25632 (goto-char (point-min))
25633 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25634 (replace-match ""))
25635 (goto-char (point-min))
25636 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25637 (replace-match ""))
25638 (goto-char (point-min))
25639 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25640 (replace-match ""))
25641 ;; Convert whitespace place holders
25642 (goto-char (point-min))
25643 (let (beg end n)
25644 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25645 (setq n (get-text-property beg 'org-whitespace)
25646 end (next-single-property-change beg 'org-whitespace))
25647 (goto-char beg)
25648 (delete-region beg end)
25649 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25650 (make-string n ?x)))))
25652 (or to-buffer (save-buffer))
25653 (goto-char (point-min))
25654 (message "Exporting... done")
25655 (if (eq to-buffer 'string)
25656 (prog1 (buffer-substring (point-min) (point-max))
25657 (kill-buffer (current-buffer)))
25658 (current-buffer)))))
25660 (defvar org-table-colgroup-info nil)
25661 (defun org-format-table-ascii (lines)
25662 "Format a table for ascii export."
25663 (if (stringp lines)
25664 (setq lines (org-split-string lines "\n")))
25665 (if (not (string-match "^[ \t]*|" (car lines)))
25666 ;; Table made by table.el - test for spanning
25667 lines
25669 ;; A normal org table
25670 ;; Get rid of hlines at beginning and end
25671 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25672 (setq lines (nreverse lines))
25673 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25674 (setq lines (nreverse lines))
25675 (when org-export-table-remove-special-lines
25676 ;; Check if the table has a marking column. If yes remove the
25677 ;; column and the special lines
25678 (setq lines (org-table-clean-before-export lines)))
25679 ;; Get rid of the vertical lines except for grouping
25680 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25681 rtn line vl1 start)
25682 (while (setq line (pop lines))
25683 (if (string-match org-table-hline-regexp line)
25684 (and (string-match "|\\(.*\\)|" line)
25685 (setq line (replace-match " \\1" t nil line)))
25686 (setq start 0 vl1 vl)
25687 (while (string-match "|" line start)
25688 (setq start (match-end 0))
25689 (or (pop vl1) (setq line (replace-match " " t t line)))))
25690 (push line rtn))
25691 (nreverse rtn))))
25693 (defun org-colgroup-info-to-vline-list (info)
25694 (let (vl new last)
25695 (while info
25696 (setq last new new (pop info))
25697 (if (or (memq last '(:end :startend))
25698 (memq new '(:start :startend)))
25699 (push t vl)
25700 (push nil vl)))
25701 (setq vl (nreverse vl))
25702 (and vl (setcar vl nil))
25703 vl))
25705 (defun org-format-table-html (lines olines)
25706 "Find out which HTML converter to use and return the HTML code."
25707 (if (stringp lines)
25708 (setq lines (org-split-string lines "\n")))
25709 (if (string-match "^[ \t]*|" (car lines))
25710 ;; A normal org table
25711 (org-format-org-table-html lines)
25712 ;; Table made by table.el - test for spanning
25713 (let* ((hlines (delq nil (mapcar
25714 (lambda (x)
25715 (if (string-match "^[ \t]*\\+-" x) x
25716 nil))
25717 lines)))
25718 (first (car hlines))
25719 (ll (and (string-match "\\S-+" first)
25720 (match-string 0 first)))
25721 (re (concat "^[ \t]*" (regexp-quote ll)))
25722 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25723 hlines))))
25724 (if (and (not spanning)
25725 (not org-export-prefer-native-exporter-for-tables))
25726 ;; We can use my own converter with HTML conversions
25727 (org-format-table-table-html lines)
25728 ;; Need to use the code generator in table.el, with the original text.
25729 (org-format-table-table-html-using-table-generate-source olines)))))
25731 (defun org-format-org-table-html (lines &optional splice)
25732 "Format a table into HTML."
25733 ;; Get rid of hlines at beginning and end
25734 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25735 (setq lines (nreverse lines))
25736 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25737 (setq lines (nreverse lines))
25738 (when org-export-table-remove-special-lines
25739 ;; Check if the table has a marking column. If yes remove the
25740 ;; column and the special lines
25741 (setq lines (org-table-clean-before-export lines)))
25743 (let ((head (and org-export-highlight-first-table-line
25744 (delq nil (mapcar
25745 (lambda (x) (string-match "^[ \t]*|-" x))
25746 (cdr lines)))))
25747 (nlines 0) fnum i
25748 tbopen line fields html gr colgropen)
25749 (if splice (setq head nil))
25750 (unless splice (push (if head "<thead>" "<tbody>") html))
25751 (setq tbopen t)
25752 (while (setq line (pop lines))
25753 (catch 'next-line
25754 (if (string-match "^[ \t]*|-" line)
25755 (progn
25756 (unless splice
25757 (push (if head "</thead>" "</tbody>") html)
25758 (if lines (push "<tbody>" html) (setq tbopen nil)))
25759 (setq head nil) ;; head ends here, first time around
25760 ;; ignore this line
25761 (throw 'next-line t)))
25762 ;; Break the line into fields
25763 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25764 (unless fnum (setq fnum (make-vector (length fields) 0)))
25765 (setq nlines (1+ nlines) i -1)
25766 (push (concat "<tr>"
25767 (mapconcat
25768 (lambda (x)
25769 (setq i (1+ i))
25770 (if (and (< i nlines)
25771 (string-match org-table-number-regexp x))
25772 (incf (aref fnum i)))
25773 (if head
25774 (concat (car org-export-table-header-tags) x
25775 (cdr org-export-table-header-tags))
25776 (concat (car org-export-table-data-tags) x
25777 (cdr org-export-table-data-tags))))
25778 fields "")
25779 "</tr>")
25780 html)))
25781 (unless splice (if tbopen (push "</tbody>" html)))
25782 (unless splice (push "</table>\n" html))
25783 (setq html (nreverse html))
25784 (unless splice
25785 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25786 (push (mapconcat
25787 (lambda (x)
25788 (setq gr (pop org-table-colgroup-info))
25789 (format "%s<col align=\"%s\"></col>%s"
25790 (if (memq gr '(:start :startend))
25791 (prog1
25792 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25793 (setq colgropen t))
25795 (if (> (/ (float x) nlines) org-table-number-fraction)
25796 "right" "left")
25797 (if (memq gr '(:end :startend))
25798 (progn (setq colgropen nil) "</colgroup>")
25799 "")))
25800 fnum "")
25801 html)
25802 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25803 (push html-table-tag html))
25804 (concat (mapconcat 'identity html "\n") "\n")))
25806 (defun org-table-clean-before-export (lines)
25807 "Check if the table has a marking column.
25808 If yes remove the column and the special lines."
25809 (setq org-table-colgroup-info nil)
25810 (if (memq nil
25811 (mapcar
25812 (lambda (x) (or (string-match "^[ \t]*|-" x)
25813 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25814 lines))
25815 (progn
25816 (setq org-table-clean-did-remove-column nil)
25817 (delq nil
25818 (mapcar
25819 (lambda (x)
25820 (cond
25821 ((string-match "^[ \t]*| */ *|" x)
25822 (setq org-table-colgroup-info
25823 (mapcar (lambda (x)
25824 (cond ((member x '("<" "&lt;")) :start)
25825 ((member x '(">" "&gt;")) :end)
25826 ((member x '("<>" "&lt;&gt;")) :startend)
25827 (t nil)))
25828 (org-split-string x "[ \t]*|[ \t]*")))
25829 nil)
25830 (t x)))
25831 lines)))
25832 (setq org-table-clean-did-remove-column t)
25833 (delq nil
25834 (mapcar
25835 (lambda (x)
25836 (cond
25837 ((string-match "^[ \t]*| */ *|" x)
25838 (setq org-table-colgroup-info
25839 (mapcar (lambda (x)
25840 (cond ((member x '("<" "&lt;")) :start)
25841 ((member x '(">" "&gt;")) :end)
25842 ((member x '("<>" "&lt;&gt;")) :startend)
25843 (t nil)))
25844 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25845 nil)
25846 ((string-match "^[ \t]*| *[!_^/] *|" x)
25847 nil) ; ignore this line
25848 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25849 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25850 ;; remove the first column
25851 (replace-match "\\1|" t nil x))))
25852 lines))))
25854 (defun org-format-table-table-html (lines)
25855 "Format a table generated by table.el into HTML.
25856 This conversion does *not* use `table-generate-source' from table.el.
25857 This has the advantage that Org-mode's HTML conversions can be used.
25858 But it has the disadvantage, that no cell- or row-spanning is allowed."
25859 (let (line field-buffer
25860 (head org-export-highlight-first-table-line)
25861 fields html empty)
25862 (setq html (concat html-table-tag "\n"))
25863 (while (setq line (pop lines))
25864 (setq empty "&nbsp;")
25865 (catch 'next-line
25866 (if (string-match "^[ \t]*\\+-" line)
25867 (progn
25868 (if field-buffer
25869 (progn
25870 (setq
25871 html
25872 (concat
25873 html
25874 "<tr>"
25875 (mapconcat
25876 (lambda (x)
25877 (if (equal x "") (setq x empty))
25878 (if head
25879 (concat (car org-export-table-header-tags) x
25880 (cdr org-export-table-header-tags))
25881 (concat (car org-export-table-data-tags) x
25882 (cdr org-export-table-data-tags))))
25883 field-buffer "\n")
25884 "</tr>\n"))
25885 (setq head nil)
25886 (setq field-buffer nil)))
25887 ;; Ignore this line
25888 (throw 'next-line t)))
25889 ;; Break the line into fields and store the fields
25890 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25891 (if field-buffer
25892 (setq field-buffer (mapcar
25893 (lambda (x)
25894 (concat x "<br/>" (pop fields)))
25895 field-buffer))
25896 (setq field-buffer fields))))
25897 (setq html (concat html "</table>\n"))
25898 html))
25900 (defun org-format-table-table-html-using-table-generate-source (lines)
25901 "Format a table into html, using `table-generate-source' from table.el.
25902 This has the advantage that cell- or row-spanning is allowed.
25903 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25904 (require 'table)
25905 (with-current-buffer (get-buffer-create " org-tmp1 ")
25906 (erase-buffer)
25907 (insert (mapconcat 'identity lines "\n"))
25908 (goto-char (point-min))
25909 (if (not (re-search-forward "|[^+]" nil t))
25910 (error "Error processing table"))
25911 (table-recognize-table)
25912 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25913 (table-generate-source 'html " org-tmp2 ")
25914 (set-buffer " org-tmp2 ")
25915 (buffer-substring (point-min) (point-max))))
25917 (defun org-html-handle-time-stamps (s)
25918 "Format time stamps in string S, or remove them."
25919 (catch 'exit
25920 (let (r b)
25921 (while (string-match org-maybe-keyword-time-regexp s)
25922 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25923 ;; never export CLOCK
25924 (throw 'exit ""))
25925 (or b (setq b (substring s 0 (match-beginning 0))))
25926 (if (not org-export-with-timestamps)
25927 (setq r (concat r (substring s 0 (match-beginning 0)))
25928 s (substring s (match-end 0)))
25929 (setq r (concat
25930 r (substring s 0 (match-beginning 0))
25931 (if (match-end 1)
25932 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25933 (match-string 1 s)))
25934 (format " @<span class=\"timestamp\">%s@</span>"
25935 (substring
25936 (org-translate-time (match-string 3 s)) 1 -1)))
25937 s (substring s (match-end 0)))))
25938 ;; Line break if line started and ended with time stamp stuff
25939 (if (not r)
25941 (setq r (concat r s))
25942 (unless (string-match "\\S-" (concat b s))
25943 (setq r (concat r "@<br/>")))
25944 r))))
25946 (defun org-html-protect (s)
25947 ;; convert & to &amp;, < to &lt; and > to &gt;
25948 (let ((start 0))
25949 (while (string-match "&" s start)
25950 (setq s (replace-match "&amp;" t t s)
25951 start (1+ (match-beginning 0))))
25952 (while (string-match "<" s)
25953 (setq s (replace-match "&lt;" t t s)))
25954 (while (string-match ">" s)
25955 (setq s (replace-match "&gt;" t t s))))
25958 (defun org-export-cleanup-toc-line (s)
25959 "Remove tags and time staps from lines going into the toc."
25960 (when (memq org-export-with-tags '(not-in-toc nil))
25961 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25962 (setq s (replace-match "" t t s))))
25963 (when org-export-remove-timestamps-from-toc
25964 (while (string-match org-maybe-keyword-time-regexp s)
25965 (setq s (replace-match "" t t s))))
25966 (while (string-match org-bracket-link-regexp s)
25967 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25968 t t s)))
25971 (defun org-html-expand (string)
25972 "Prepare STRING for HTML export. Applies all active conversions.
25973 If there are links in the string, don't modify these."
25974 (let* ((re (concat org-bracket-link-regexp "\\|"
25975 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25976 m s l res)
25977 (while (setq m (string-match re string))
25978 (setq s (substring string 0 m)
25979 l (match-string 0 string)
25980 string (substring string (match-end 0)))
25981 (push (org-html-do-expand s) res)
25982 (push l res))
25983 (push (org-html-do-expand string) res)
25984 (apply 'concat (nreverse res))))
25986 (defun org-html-do-expand (s)
25987 "Apply all active conversions to translate special ASCII to HTML."
25988 (setq s (org-html-protect s))
25989 (if org-export-html-expand
25990 (let ((start 0))
25991 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25992 (setq s (replace-match "<\\1>" t nil s)))))
25993 (if org-export-with-emphasize
25994 (setq s (org-export-html-convert-emphasize s)))
25995 (if org-export-with-special-strings
25996 (setq s (org-export-html-convert-special-strings s)))
25997 (if org-export-with-sub-superscripts
25998 (setq s (org-export-html-convert-sub-super s)))
25999 (if org-export-with-TeX-macros
26000 (let ((start 0) wd ass)
26001 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26002 (if (get-text-property (match-beginning 0) 'org-protected s)
26003 (setq start (match-end 0))
26004 (setq wd (match-string 1 s))
26005 (if (setq ass (assoc wd org-html-entities))
26006 (setq s (replace-match (or (cdr ass)
26007 (concat "&" (car ass) ";"))
26008 t t s))
26009 (setq start (+ start (length wd))))))))
26012 (defun org-create-multibrace-regexp (left right n)
26013 "Create a regular expression which will match a balanced sexp.
26014 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26015 as single character strings.
26016 The regexp returned will match the entire expression including the
26017 delimiters. It will also define a single group which contains the
26018 match except for the outermost delimiters. The maximum depth of
26019 stacked delimiters is N. Escaping delimiters is not possible."
26020 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26021 (or "\\|")
26022 (re nothing)
26023 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26024 (while (> n 1)
26025 (setq n (1- n)
26026 re (concat re or next)
26027 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26028 (concat left "\\(" re "\\)" right)))
26030 (defvar org-match-substring-regexp
26031 (concat
26032 "\\([^\\]\\)\\([_^]\\)\\("
26033 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26034 "\\|"
26035 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26036 "\\|"
26037 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26038 "The regular expression matching a sub- or superscript.")
26040 (defvar org-match-substring-with-braces-regexp
26041 (concat
26042 "\\([^\\]\\)\\([_^]\\)\\("
26043 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26044 "\\)")
26045 "The regular expression matching a sub- or superscript, forcing braces.")
26047 (defconst org-export-html-special-string-regexps
26048 '(("\\\\-" . "&shy;")
26049 ("---\\([^-]\\)" . "&mdash;\\1")
26050 ("--\\([^-]\\)" . "&ndash;\\1")
26051 ("\\.\\.\\." . "&hellip;"))
26052 "Regular expressions for special string conversion.")
26054 (defun org-export-html-convert-special-strings (string)
26055 "Convert special characters in STRING to HTML."
26056 (let ((all org-export-html-special-string-regexps)
26057 e a re rpl start)
26058 (while (setq a (pop all))
26059 (setq re (car a) rpl (cdr a) start 0)
26060 (while (string-match re string start)
26061 (if (get-text-property (match-beginning 0) 'org-protected string)
26062 (setq start (match-end 0))
26063 (setq string (replace-match rpl t nil string)))))
26064 string))
26066 (defun org-export-html-convert-sub-super (string)
26067 "Convert sub- and superscripts in STRING to HTML."
26068 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26069 (while (string-match org-match-substring-regexp string s)
26070 (cond
26071 ((and requireb (match-end 8)) (setq s (match-end 2)))
26072 ((get-text-property (match-beginning 2) 'org-protected string)
26073 (setq s (match-end 2)))
26075 (setq s (match-end 1)
26076 key (if (string= (match-string 2 string) "_") "sub" "sup")
26077 c (or (match-string 8 string)
26078 (match-string 6 string)
26079 (match-string 5 string))
26080 string (replace-match
26081 (concat (match-string 1 string)
26082 "<" key ">" c "</" key ">")
26083 t t string)))))
26084 (while (string-match "\\\\\\([_^]\\)" string)
26085 (setq string (replace-match (match-string 1 string) t t string)))
26086 string))
26088 (defun org-export-html-convert-emphasize (string)
26089 "Apply emphasis."
26090 (let ((s 0) rpl)
26091 (while (string-match org-emph-re string s)
26092 (if (not (equal
26093 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26094 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26095 (setq s (match-beginning 0)
26097 (concat
26098 (match-string 1 string)
26099 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26100 (match-string 4 string)
26101 (nth 3 (assoc (match-string 3 string)
26102 org-emphasis-alist))
26103 (match-string 5 string))
26104 string (replace-match rpl t t string)
26105 s (+ s (- (length rpl) 2)))
26106 (setq s (1+ s))))
26107 string))
26109 (defvar org-par-open nil)
26110 (defun org-open-par ()
26111 "Insert <p>, but first close previous paragraph if any."
26112 (org-close-par-maybe)
26113 (insert "\n<p>")
26114 (setq org-par-open t))
26115 (defun org-close-par-maybe ()
26116 "Close paragraph if there is one open."
26117 (when org-par-open
26118 (insert "</p>")
26119 (setq org-par-open nil)))
26120 (defun org-close-li ()
26121 "Close <li> if necessary."
26122 (org-close-par-maybe)
26123 (insert "</li>\n"))
26125 (defvar body-only) ; dynamically scoped into this.
26126 (defun org-html-level-start (level title umax with-toc head-count)
26127 "Insert a new level in HTML export.
26128 When TITLE is nil, just close all open levels."
26129 (org-close-par-maybe)
26130 (let ((l org-level-max))
26131 (while (>= l level)
26132 (if (aref org-levels-open (1- l))
26133 (progn
26134 (org-html-level-close l umax)
26135 (aset org-levels-open (1- l) nil)))
26136 (setq l (1- l)))
26137 (when title
26138 ;; If title is nil, this means this function is called to close
26139 ;; all levels, so the rest is done only if title is given
26140 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26141 (setq title (replace-match
26142 (if org-export-with-tags
26143 (save-match-data
26144 (concat
26145 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26146 (mapconcat 'identity (org-split-string
26147 (match-string 1 title) ":")
26148 "&nbsp;")
26149 "</span>"))
26151 t t title)))
26152 (if (> level umax)
26153 (progn
26154 (if (aref org-levels-open (1- level))
26155 (progn
26156 (org-close-li)
26157 (insert "<li>" title "<br/>\n"))
26158 (aset org-levels-open (1- level) t)
26159 (org-close-par-maybe)
26160 (insert "<ul>\n<li>" title "<br/>\n")))
26161 (aset org-levels-open (1- level) t)
26162 (if (and org-export-with-section-numbers (not body-only))
26163 (setq title (concat (org-section-number level) " " title)))
26164 (setq level (+ level org-export-html-toplevel-hlevel -1))
26165 (if with-toc
26166 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26167 level level head-count title level))
26168 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26169 (org-open-par)))))
26171 (defun org-html-level-close (level max-outline-level)
26172 "Terminate one level in HTML export."
26173 (if (<= level max-outline-level)
26174 (insert "</div>\n")
26175 (org-close-li)
26176 (insert "</ul>\n")))
26178 ;;; iCalendar export
26180 ;;;###autoload
26181 (defun org-export-icalendar-this-file ()
26182 "Export current file as an iCalendar file.
26183 The iCalendar file will be located in the same directory as the Org-mode
26184 file, but with extension `.ics'."
26185 (interactive)
26186 (org-export-icalendar nil buffer-file-name))
26188 ;;;###autoload
26189 (defun org-export-icalendar-all-agenda-files ()
26190 "Export all files in `org-agenda-files' to iCalendar .ics files.
26191 Each iCalendar file will be located in the same directory as the Org-mode
26192 file, but with extension `.ics'."
26193 (interactive)
26194 (apply 'org-export-icalendar nil (org-agenda-files t)))
26196 ;;;###autoload
26197 (defun org-export-icalendar-combine-agenda-files ()
26198 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26199 The file is stored under the name `org-combined-agenda-icalendar-file'."
26200 (interactive)
26201 (apply 'org-export-icalendar t (org-agenda-files t)))
26203 (defun org-export-icalendar (combine &rest files)
26204 "Create iCalendar files for all elements of FILES.
26205 If COMBINE is non-nil, combine all calendar entries into a single large
26206 file and store it under the name `org-combined-agenda-icalendar-file'."
26207 (save-excursion
26208 (org-prepare-agenda-buffers files)
26209 (let* ((dir (org-export-directory
26210 :ical (list :publishing-directory
26211 org-export-publishing-directory)))
26212 file ical-file ical-buffer category started org-agenda-new-buffers)
26214 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26215 (when combine
26216 (setq ical-file
26217 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26218 org-combined-agenda-icalendar-file
26219 (expand-file-name org-combined-agenda-icalendar-file dir))
26220 ical-buffer (org-get-agenda-file-buffer ical-file))
26221 (set-buffer ical-buffer) (erase-buffer))
26222 (while (setq file (pop files))
26223 (catch 'nextfile
26224 (org-check-agenda-file file)
26225 (set-buffer (org-get-agenda-file-buffer file))
26226 (unless combine
26227 (setq ical-file (concat (file-name-as-directory dir)
26228 (file-name-sans-extension
26229 (file-name-nondirectory buffer-file-name))
26230 ".ics"))
26231 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26232 (with-current-buffer ical-buffer (erase-buffer)))
26233 (setq category (or org-category
26234 (file-name-sans-extension
26235 (file-name-nondirectory buffer-file-name))))
26236 (if (symbolp category) (setq category (symbol-name category)))
26237 (let ((standard-output ical-buffer))
26238 (if combine
26239 (and (not started) (setq started t)
26240 (org-start-icalendar-file org-icalendar-combined-name))
26241 (org-start-icalendar-file category))
26242 (org-print-icalendar-entries combine)
26243 (when (or (and combine (not files)) (not combine))
26244 (org-finish-icalendar-file)
26245 (set-buffer ical-buffer)
26246 (save-buffer)
26247 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26248 (org-release-buffers org-agenda-new-buffers))))
26250 (defvar org-after-save-iCalendar-file-hook nil
26251 "Hook run after an iCalendar file has been saved.
26252 The iCalendar buffer is still current when this hook is run.
26253 A good way to use this is to tell a desktop calenndar application to re-read
26254 the iCalendar file.")
26256 (defun org-print-icalendar-entries (&optional combine)
26257 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26258 When COMBINE is non nil, add the category to each line."
26259 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26260 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26261 (dts (org-ical-ts-to-string
26262 (format-time-string (cdr org-time-stamp-formats) (current-time))
26263 "DTSTART"))
26264 hd ts ts2 state status (inc t) pos b sexp rrule
26265 scheduledp deadlinep tmp pri category entry location summary desc
26266 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26267 (org-refresh-category-properties)
26268 (save-excursion
26269 (goto-char (point-min))
26270 (while (re-search-forward re1 nil t)
26271 (catch :skip
26272 (org-agenda-skip)
26273 (setq pos (match-beginning 0)
26274 ts (match-string 0)
26275 inc t
26276 hd (org-get-heading)
26277 summary (org-icalendar-cleanup-string
26278 (org-entry-get nil "SUMMARY"))
26279 desc (org-icalendar-cleanup-string
26280 (or (org-entry-get nil "DESCRIPTION")
26281 (and org-icalendar-include-body (org-get-entry)))
26282 t org-icalendar-include-body)
26283 location (org-icalendar-cleanup-string
26284 (org-entry-get nil "LOCATION"))
26285 category (org-get-category))
26286 (if (looking-at re2)
26287 (progn
26288 (goto-char (match-end 0))
26289 (setq ts2 (match-string 1) inc nil))
26290 (setq tmp (buffer-substring (max (point-min)
26291 (- pos org-ds-keyword-length))
26292 pos)
26293 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26294 (progn
26295 (setq inc nil)
26296 (replace-match "\\1" t nil ts))
26298 deadlinep (string-match org-deadline-regexp tmp)
26299 scheduledp (string-match org-scheduled-regexp tmp)
26300 ;; donep (org-entry-is-done-p)
26302 (if (or (string-match org-tr-regexp hd)
26303 (string-match org-ts-regexp hd))
26304 (setq hd (replace-match "" t t hd)))
26305 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26306 (setq rrule
26307 (concat "\nRRULE:FREQ="
26308 (cdr (assoc
26309 (match-string 2 ts)
26310 '(("d" . "DAILY")("w" . "WEEKLY")
26311 ("m" . "MONTHLY")("y" . "YEARLY"))))
26312 ";INTERVAL=" (match-string 1 ts)))
26313 (setq rrule ""))
26314 (setq summary (or summary hd))
26315 (if (string-match org-bracket-link-regexp summary)
26316 (setq summary
26317 (replace-match (if (match-end 3)
26318 (match-string 3 summary)
26319 (match-string 1 summary))
26320 t t summary)))
26321 (if deadlinep (setq summary (concat "DL: " summary)))
26322 (if scheduledp (setq summary (concat "S: " summary)))
26323 (if (string-match "\\`<%%" ts)
26324 (with-current-buffer sexp-buffer
26325 (insert (substring ts 1 -1) " " summary "\n"))
26326 (princ (format "BEGIN:VEVENT
26328 %s%s
26329 SUMMARY:%s%s%s
26330 CATEGORIES:%s
26331 END:VEVENT\n"
26332 (org-ical-ts-to-string ts "DTSTART")
26333 (org-ical-ts-to-string ts2 "DTEND" inc)
26334 rrule summary
26335 (if (and desc (string-match "\\S-" desc))
26336 (concat "\nDESCRIPTION: " desc) "")
26337 (if (and location (string-match "\\S-" location))
26338 (concat "\nLOCATION: " location) "")
26339 category)))))
26341 (when (and org-icalendar-include-sexps
26342 (condition-case nil (require 'icalendar) (error nil))
26343 (fboundp 'icalendar-export-region))
26344 ;; Get all the literal sexps
26345 (goto-char (point-min))
26346 (while (re-search-forward "^&?%%(" nil t)
26347 (catch :skip
26348 (org-agenda-skip)
26349 (setq b (match-beginning 0))
26350 (goto-char (1- (match-end 0)))
26351 (forward-sexp 1)
26352 (end-of-line 1)
26353 (setq sexp (buffer-substring b (point)))
26354 (with-current-buffer sexp-buffer
26355 (insert sexp "\n"))
26356 (princ (org-diary-to-ical-string sexp-buffer)))))
26358 (when org-icalendar-include-todo
26359 (goto-char (point-min))
26360 (while (re-search-forward org-todo-line-regexp nil t)
26361 (catch :skip
26362 (org-agenda-skip)
26363 (setq state (match-string 2))
26364 (setq status (if (member state org-done-keywords)
26365 "COMPLETED" "NEEDS-ACTION"))
26366 (when (and state
26367 (or (not (member state org-done-keywords))
26368 (eq org-icalendar-include-todo 'all))
26369 (not (member org-archive-tag (org-get-tags-at)))
26371 (setq hd (match-string 3)
26372 summary (org-icalendar-cleanup-string
26373 (org-entry-get nil "SUMMARY"))
26374 desc (org-icalendar-cleanup-string
26375 (or (org-entry-get nil "DESCRIPTION")
26376 (and org-icalendar-include-body (org-get-entry)))
26377 t org-icalendar-include-body)
26378 location (org-icalendar-cleanup-string
26379 (org-entry-get nil "LOCATION")))
26380 (if (string-match org-bracket-link-regexp hd)
26381 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26382 (match-string 1 hd))
26383 t t hd)))
26384 (if (string-match org-priority-regexp hd)
26385 (setq pri (string-to-char (match-string 2 hd))
26386 hd (concat (substring hd 0 (match-beginning 1))
26387 (substring hd (match-end 1))))
26388 (setq pri org-default-priority))
26389 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26390 (- org-lowest-priority org-highest-priority))))))
26392 (princ (format "BEGIN:VTODO
26394 SUMMARY:%s%s%s
26395 CATEGORIES:%s
26396 SEQUENCE:1
26397 PRIORITY:%d
26398 STATUS:%s
26399 END:VTODO\n"
26401 (or summary hd)
26402 (if (and location (string-match "\\S-" location))
26403 (concat "\nLOCATION: " location) "")
26404 (if (and desc (string-match "\\S-" desc))
26405 (concat "\nDESCRIPTION: " desc) "")
26406 category pri status)))))))))
26408 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26409 "Take out stuff and quote what needs to be quoted.
26410 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26411 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26412 characters."
26413 (if (not s)
26415 (when is-body
26416 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26417 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26418 (while (string-match re s) (setq s (replace-match "" t t s)))
26419 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26420 (let ((start 0))
26421 (while (string-match "\\([,;\\]\\)" s start)
26422 (setq start (+ (match-beginning 0) 2)
26423 s (replace-match "\\\\\\1" nil nil s))))
26424 (when is-body
26425 (while (string-match "[ \t]*\n[ \t]*" s)
26426 (setq s (replace-match "\\n" t t s))))
26427 (setq s (org-trim s))
26428 (if is-body
26429 (if maxlength
26430 (if (and (numberp maxlength)
26431 (> (length s) maxlength))
26432 (setq s (substring s 0 maxlength)))))
26435 (defun org-get-entry ()
26436 "Clean-up description string."
26437 (save-excursion
26438 (org-back-to-heading t)
26439 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26441 (defun org-start-icalendar-file (name)
26442 "Start an iCalendar file by inserting the header."
26443 (let ((user user-full-name)
26444 (name (or name "unknown"))
26445 (timezone (cadr (current-time-zone))))
26446 (princ
26447 (format "BEGIN:VCALENDAR
26448 VERSION:2.0
26449 X-WR-CALNAME:%s
26450 PRODID:-//%s//Emacs with Org-mode//EN
26451 X-WR-TIMEZONE:%s
26452 CALSCALE:GREGORIAN\n" name user timezone))))
26454 (defun org-finish-icalendar-file ()
26455 "Finish an iCalendar file by inserting the END statement."
26456 (princ "END:VCALENDAR\n"))
26458 (defun org-ical-ts-to-string (s keyword &optional inc)
26459 "Take a time string S and convert it to iCalendar format.
26460 KEYWORD is added in front, to make a complete line like DTSTART....
26461 When INC is non-nil, increase the hour by two (if time string contains
26462 a time), or the day by one (if it does not contain a time)."
26463 (let ((t1 (org-parse-time-string s 'nodefault))
26464 t2 fmt have-time time)
26465 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26466 (setq t2 t1 have-time t)
26467 (setq t2 (org-parse-time-string s)))
26468 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26469 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26470 (when inc
26471 (if have-time
26472 (if org-agenda-default-appointment-duration
26473 (setq mi (+ org-agenda-default-appointment-duration mi))
26474 (setq h (+ 2 h)))
26475 (setq d (1+ d))))
26476 (setq time (encode-time s mi h d m y)))
26477 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26478 (concat keyword (format-time-string fmt time))))
26480 ;;; XOXO export
26482 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26483 (with-current-buffer buffer
26484 (apply 'insert output)))
26485 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26487 (defun org-export-as-xoxo (&optional buffer)
26488 "Export the org buffer as XOXO.
26489 The XOXO buffer is named *xoxo-<source buffer name>*"
26490 (interactive (list (current-buffer)))
26491 ;; A quickie abstraction
26493 ;; Output everything as XOXO
26494 (with-current-buffer (get-buffer buffer)
26495 (let* ((pos (point))
26496 (opt-plist (org-combine-plists (org-default-export-plist)
26497 (org-infile-export-plist)))
26498 (filename (concat (file-name-as-directory
26499 (org-export-directory :xoxo opt-plist))
26500 (file-name-sans-extension
26501 (file-name-nondirectory buffer-file-name))
26502 ".html"))
26503 (out (find-file-noselect filename))
26504 (last-level 1)
26505 (hanging-li nil))
26506 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26507 ;; Check the output buffer is empty.
26508 (with-current-buffer out (erase-buffer))
26509 ;; Kick off the output
26510 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26511 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26512 (let* ((hd (match-string-no-properties 1))
26513 (level (length hd))
26514 (text (concat
26515 (match-string-no-properties 2)
26516 (save-excursion
26517 (goto-char (match-end 0))
26518 (let ((str ""))
26519 (catch 'loop
26520 (while 't
26521 (forward-line)
26522 (if (looking-at "^[ \t]\\(.*\\)")
26523 (setq str (concat str (match-string-no-properties 1)))
26524 (throw 'loop str)))))))))
26526 ;; Handle level rendering
26527 (cond
26528 ((> level last-level)
26529 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26531 ((< level last-level)
26532 (dotimes (- (- last-level level) 1)
26533 (if hanging-li
26534 (org-export-as-xoxo-insert-into out "</li>\n"))
26535 (org-export-as-xoxo-insert-into out "</ol>\n"))
26536 (when hanging-li
26537 (org-export-as-xoxo-insert-into out "</li>\n")
26538 (setq hanging-li nil)))
26540 ((equal level last-level)
26541 (if hanging-li
26542 (org-export-as-xoxo-insert-into out "</li>\n")))
26545 (setq last-level level)
26547 ;; And output the new li
26548 (setq hanging-li 't)
26549 (if (equal ?+ (elt text 0))
26550 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26551 (org-export-as-xoxo-insert-into out "<li>" text))))
26553 ;; Finally finish off the ol
26554 (dotimes (- last-level 1)
26555 (if hanging-li
26556 (org-export-as-xoxo-insert-into out "</li>\n"))
26557 (org-export-as-xoxo-insert-into out "</ol>\n"))
26559 (goto-char pos)
26560 ;; Finish the buffer off and clean it up.
26561 (switch-to-buffer-other-window out)
26562 (indent-region (point-min) (point-max) nil)
26563 (save-buffer)
26564 (goto-char (point-min))
26568 ;;;; Key bindings
26570 ;; Make `C-c C-x' a prefix key
26571 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26573 ;; TAB key with modifiers
26574 (org-defkey org-mode-map "\C-i" 'org-cycle)
26575 (org-defkey org-mode-map [(tab)] 'org-cycle)
26576 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26577 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26578 (org-defkey org-mode-map "\M-\t" 'org-complete)
26579 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26580 ;; The following line is necessary under Suse GNU/Linux
26581 (unless (featurep 'xemacs)
26582 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26583 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26584 (define-key org-mode-map [backtab] 'org-shifttab)
26586 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26587 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26588 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26590 ;; Cursor keys with modifiers
26591 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26592 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26593 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26594 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26596 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26597 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26598 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26599 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26601 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26602 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26603 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26604 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26606 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26607 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26609 ;;; Extra keys for tty access.
26610 ;; We only set them when really needed because otherwise the
26611 ;; menus don't show the simple keys
26613 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26614 (not window-system))
26615 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26616 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26617 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26618 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26619 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26620 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26621 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26622 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26623 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26624 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26625 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26626 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26627 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26628 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26629 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26630 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26631 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26632 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26633 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26634 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26635 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26636 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26638 ;; All the other keys
26640 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26641 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26642 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26643 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26644 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26645 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26646 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26647 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26648 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26649 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26650 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26651 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26652 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26653 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26654 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26655 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26656 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26657 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26658 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26659 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26660 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26661 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26662 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26663 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26664 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26665 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26666 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26667 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26668 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26669 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26670 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26671 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26672 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26673 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26674 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26675 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26676 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26677 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26678 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26679 (org-defkey org-mode-map "\C-c^" 'org-sort)
26680 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26681 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26682 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26683 (org-defkey org-mode-map "\C-m" 'org-return)
26684 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26685 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26686 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26687 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26688 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26689 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26690 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26691 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26692 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26693 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26694 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26695 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26696 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26697 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26698 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26699 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26700 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26702 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26703 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26704 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26705 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26707 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26708 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26709 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26710 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26711 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26712 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26713 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26714 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26715 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26716 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26717 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26718 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26720 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26722 (when (featurep 'xemacs)
26723 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26725 (defsubst org-table-p () (org-at-table-p))
26727 (defun org-self-insert-command (N)
26728 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26729 If the cursor is in a table looking at whitespace, the whitespace is
26730 overwritten, and the table is not marked as requiring realignment."
26731 (interactive "p")
26732 (if (and (org-table-p)
26733 (progn
26734 ;; check if we blank the field, and if that triggers align
26735 (and org-table-auto-blank-field
26736 (member last-command
26737 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26738 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26739 ;; got extra space, this field does not determine column width
26740 (let (org-table-may-need-update) (org-table-blank-field))
26741 ;; no extra space, this field may determine column width
26742 (org-table-blank-field)))
26744 (eq N 1)
26745 (looking-at "[^|\n]* |"))
26746 (let (org-table-may-need-update)
26747 (goto-char (1- (match-end 0)))
26748 (delete-backward-char 1)
26749 (goto-char (match-beginning 0))
26750 (self-insert-command N))
26751 (setq org-table-may-need-update t)
26752 (self-insert-command N)
26753 (org-fix-tags-on-the-fly)))
26755 (defun org-fix-tags-on-the-fly ()
26756 (when (and (equal (char-after (point-at-bol)) ?*)
26757 (org-on-heading-p))
26758 (org-align-tags-here org-tags-column)))
26760 (defun org-delete-backward-char (N)
26761 "Like `delete-backward-char', insert whitespace at field end in tables.
26762 When deleting backwards, in tables this function will insert whitespace in
26763 front of the next \"|\" separator, to keep the table aligned. The table will
26764 still be marked for re-alignment if the field did fill the entire column,
26765 because, in this case the deletion might narrow the column."
26766 (interactive "p")
26767 (if (and (org-table-p)
26768 (eq N 1)
26769 (string-match "|" (buffer-substring (point-at-bol) (point)))
26770 (looking-at ".*?|"))
26771 (let ((pos (point))
26772 (noalign (looking-at "[^|\n\r]* |"))
26773 (c org-table-may-need-update))
26774 (backward-delete-char N)
26775 (skip-chars-forward "^|")
26776 (insert " ")
26777 (goto-char (1- pos))
26778 ;; noalign: if there were two spaces at the end, this field
26779 ;; does not determine the width of the column.
26780 (if noalign (setq org-table-may-need-update c)))
26781 (backward-delete-char N)
26782 (org-fix-tags-on-the-fly)))
26784 (defun org-delete-char (N)
26785 "Like `delete-char', but insert whitespace at field end in tables.
26786 When deleting characters, in tables this function will insert whitespace in
26787 front of the next \"|\" separator, to keep the table aligned. The table will
26788 still be marked for re-alignment if the field did fill the entire column,
26789 because, in this case the deletion might narrow the column."
26790 (interactive "p")
26791 (if (and (org-table-p)
26792 (not (bolp))
26793 (not (= (char-after) ?|))
26794 (eq N 1))
26795 (if (looking-at ".*?|")
26796 (let ((pos (point))
26797 (noalign (looking-at "[^|\n\r]* |"))
26798 (c org-table-may-need-update))
26799 (replace-match (concat
26800 (substring (match-string 0) 1 -1)
26801 " |"))
26802 (goto-char pos)
26803 ;; noalign: if there were two spaces at the end, this field
26804 ;; does not determine the width of the column.
26805 (if noalign (setq org-table-may-need-update c)))
26806 (delete-char N))
26807 (delete-char N)
26808 (org-fix-tags-on-the-fly)))
26810 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26811 (put 'org-self-insert-command 'delete-selection t)
26812 (put 'orgtbl-self-insert-command 'delete-selection t)
26813 (put 'org-delete-char 'delete-selection 'supersede)
26814 (put 'org-delete-backward-char 'delete-selection 'supersede)
26816 ;; Make `flyspell-mode' delay after some commands
26817 (put 'org-self-insert-command 'flyspell-delayed t)
26818 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26819 (put 'org-delete-char 'flyspell-delayed t)
26820 (put 'org-delete-backward-char 'flyspell-delayed t)
26822 ;; Make pabbrev-mode expand after org-mode commands
26823 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26824 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26826 ;; How to do this: Measure non-white length of current string
26827 ;; If equal to column width, we should realign.
26829 (defun org-remap (map &rest commands)
26830 "In MAP, remap the functions given in COMMANDS.
26831 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26832 (let (new old)
26833 (while commands
26834 (setq old (pop commands) new (pop commands))
26835 (if (fboundp 'command-remapping)
26836 (org-defkey map (vector 'remap old) new)
26837 (substitute-key-definition old new map global-map)))))
26839 (when (eq org-enable-table-editor 'optimized)
26840 ;; If the user wants maximum table support, we need to hijack
26841 ;; some standard editing functions
26842 (org-remap org-mode-map
26843 'self-insert-command 'org-self-insert-command
26844 'delete-char 'org-delete-char
26845 'delete-backward-char 'org-delete-backward-char)
26846 (org-defkey org-mode-map "|" 'org-force-self-insert))
26848 (defun org-shiftcursor-error ()
26849 "Throw an error because Shift-Cursor command was applied in wrong context."
26850 (error "This command is active in special context like tables, headlines or timestamps"))
26852 (defun org-shifttab (&optional arg)
26853 "Global visibility cycling or move to previous table field.
26854 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26855 on context.
26856 See the individual commands for more information."
26857 (interactive "P")
26858 (cond
26859 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26860 (arg (message "Content view to level: ")
26861 (org-content (prefix-numeric-value arg))
26862 (setq org-cycle-global-status 'overview))
26863 (t (call-interactively 'org-global-cycle))))
26865 (defun org-shiftmetaleft ()
26866 "Promote subtree or delete table column.
26867 Calls `org-promote-subtree', `org-outdent-item',
26868 or `org-table-delete-column', depending on context.
26869 See the individual commands for more information."
26870 (interactive)
26871 (cond
26872 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26873 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26874 ((org-at-item-p) (call-interactively 'org-outdent-item))
26875 (t (org-shiftcursor-error))))
26877 (defun org-shiftmetaright ()
26878 "Demote subtree or insert table column.
26879 Calls `org-demote-subtree', `org-indent-item',
26880 or `org-table-insert-column', depending on context.
26881 See the individual commands for more information."
26882 (interactive)
26883 (cond
26884 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26885 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26886 ((org-at-item-p) (call-interactively 'org-indent-item))
26887 (t (org-shiftcursor-error))))
26889 (defun org-shiftmetaup (&optional arg)
26890 "Move subtree up or kill table row.
26891 Calls `org-move-subtree-up' or `org-table-kill-row' or
26892 `org-move-item-up' depending on context. See the individual commands
26893 for more information."
26894 (interactive "P")
26895 (cond
26896 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26897 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26898 ((org-at-item-p) (call-interactively 'org-move-item-up))
26899 (t (org-shiftcursor-error))))
26900 (defun org-shiftmetadown (&optional arg)
26901 "Move subtree down or insert table row.
26902 Calls `org-move-subtree-down' or `org-table-insert-row' or
26903 `org-move-item-down', depending on context. See the individual
26904 commands for more information."
26905 (interactive "P")
26906 (cond
26907 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26908 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26909 ((org-at-item-p) (call-interactively 'org-move-item-down))
26910 (t (org-shiftcursor-error))))
26912 (defun org-metaleft (&optional arg)
26913 "Promote heading or move table column to left.
26914 Calls `org-do-promote' or `org-table-move-column', depending on context.
26915 With no specific context, calls the Emacs default `backward-word'.
26916 See the individual commands for more information."
26917 (interactive "P")
26918 (cond
26919 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26920 ((or (org-on-heading-p) (org-region-active-p))
26921 (call-interactively 'org-do-promote))
26922 ((org-at-item-p) (call-interactively 'org-outdent-item))
26923 (t (call-interactively 'backward-word))))
26925 (defun org-metaright (&optional arg)
26926 "Demote subtree or move table column to right.
26927 Calls `org-do-demote' or `org-table-move-column', depending on context.
26928 With no specific context, calls the Emacs default `forward-word'.
26929 See the individual commands for more information."
26930 (interactive "P")
26931 (cond
26932 ((org-at-table-p) (call-interactively 'org-table-move-column))
26933 ((or (org-on-heading-p) (org-region-active-p))
26934 (call-interactively 'org-do-demote))
26935 ((org-at-item-p) (call-interactively 'org-indent-item))
26936 (t (call-interactively 'forward-word))))
26938 (defun org-metaup (&optional arg)
26939 "Move subtree up or move table row up.
26940 Calls `org-move-subtree-up' or `org-table-move-row' or
26941 `org-move-item-up', depending on context. See the individual commands
26942 for more information."
26943 (interactive "P")
26944 (cond
26945 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26946 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26947 ((org-at-item-p) (call-interactively 'org-move-item-up))
26948 (t (transpose-lines 1) (beginning-of-line -1))))
26950 (defun org-metadown (&optional arg)
26951 "Move subtree down or move table row down.
26952 Calls `org-move-subtree-down' or `org-table-move-row' or
26953 `org-move-item-down', depending on context. See the individual
26954 commands for more information."
26955 (interactive "P")
26956 (cond
26957 ((org-at-table-p) (call-interactively 'org-table-move-row))
26958 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26959 ((org-at-item-p) (call-interactively 'org-move-item-down))
26960 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26962 (defun org-shiftup (&optional arg)
26963 "Increase item in timestamp or increase priority of current headline.
26964 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26965 depending on context. See the individual commands for more information."
26966 (interactive "P")
26967 (cond
26968 ((org-at-timestamp-p t)
26969 (call-interactively (if org-edit-timestamp-down-means-later
26970 'org-timestamp-down 'org-timestamp-up)))
26971 ((org-on-heading-p) (call-interactively 'org-priority-up))
26972 ((org-at-item-p) (call-interactively 'org-previous-item))
26973 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26975 (defun org-shiftdown (&optional arg)
26976 "Decrease item in timestamp or decrease priority of current headline.
26977 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26978 depending on context. See the individual commands for more information."
26979 (interactive "P")
26980 (cond
26981 ((org-at-timestamp-p t)
26982 (call-interactively (if org-edit-timestamp-down-means-later
26983 'org-timestamp-up 'org-timestamp-down)))
26984 ((org-on-heading-p) (call-interactively 'org-priority-down))
26985 (t (call-interactively 'org-next-item))))
26987 (defun org-shiftright ()
26988 "Next TODO keyword or timestamp one day later, depending on context."
26989 (interactive)
26990 (cond
26991 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26992 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26993 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26994 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26995 (t (org-shiftcursor-error))))
26997 (defun org-shiftleft ()
26998 "Previous TODO keyword or timestamp one day earlier, depending on context."
26999 (interactive)
27000 (cond
27001 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27002 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27003 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27004 ((org-at-property-p)
27005 (call-interactively 'org-property-previous-allowed-value))
27006 (t (org-shiftcursor-error))))
27008 (defun org-shiftcontrolright ()
27009 "Switch to next TODO set."
27010 (interactive)
27011 (cond
27012 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27013 (t (org-shiftcursor-error))))
27015 (defun org-shiftcontrolleft ()
27016 "Switch to previous TODO set."
27017 (interactive)
27018 (cond
27019 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27020 (t (org-shiftcursor-error))))
27022 (defun org-ctrl-c-ret ()
27023 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27024 (interactive)
27025 (cond
27026 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27027 (t (call-interactively 'org-insert-heading))))
27029 (defun org-copy-special ()
27030 "Copy region in table or copy current subtree.
27031 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27032 See the individual commands for more information."
27033 (interactive)
27034 (call-interactively
27035 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27037 (defun org-cut-special ()
27038 "Cut region in table or cut current subtree.
27039 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27040 See the individual commands for more information."
27041 (interactive)
27042 (call-interactively
27043 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27045 (defun org-paste-special (arg)
27046 "Paste rectangular region into table, or past subtree relative to level.
27047 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27048 See the individual commands for more information."
27049 (interactive "P")
27050 (if (org-at-table-p)
27051 (org-table-paste-rectangle)
27052 (org-paste-subtree arg)))
27054 (defun org-ctrl-c-ctrl-c (&optional arg)
27055 "Set tags in headline, or update according to changed information at point.
27057 This command does many different things, depending on context:
27059 - If the cursor is in a headline, prompt for tags and insert them
27060 into the current line, aligned to `org-tags-column'. When called
27061 with prefix arg, realign all tags in the current buffer.
27063 - If the cursor is in one of the special #+KEYWORD lines, this
27064 triggers scanning the buffer for these lines and updating the
27065 information.
27067 - If the cursor is inside a table, realign the table. This command
27068 works even if the automatic table editor has been turned off.
27070 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27071 the entire table.
27073 - If the cursor is a the beginning of a dynamic block, update it.
27075 - If the cursor is inside a table created by the table.el package,
27076 activate that table.
27078 - If the current buffer is a remember buffer, close note and file it.
27079 with a prefix argument, file it without further interaction to the default
27080 location.
27082 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27083 links in this buffer.
27085 - If the cursor is on a numbered item in a plain list, renumber the
27086 ordered list.
27088 - If the cursor is on a checkbox, toggle it."
27089 (interactive "P")
27090 (let ((org-enable-table-editor t))
27091 (cond
27092 ((or org-clock-overlays
27093 org-occur-highlights
27094 org-latex-fragment-image-overlays)
27095 (org-remove-clock-overlays)
27096 (org-remove-occur-highlights)
27097 (org-remove-latex-fragment-image-overlays)
27098 (message "Temporary highlights/overlays removed from current buffer"))
27099 ((and (local-variable-p 'org-finish-function (current-buffer))
27100 (fboundp org-finish-function))
27101 (funcall org-finish-function))
27102 ((org-at-property-p)
27103 (call-interactively 'org-property-action))
27104 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27105 ((org-on-heading-p) (call-interactively 'org-set-tags))
27106 ((org-at-table.el-p)
27107 (require 'table)
27108 (beginning-of-line 1)
27109 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27110 (call-interactively 'table-recognize-table))
27111 ((org-at-table-p)
27112 (org-table-maybe-eval-formula)
27113 (if arg
27114 (call-interactively 'org-table-recalculate)
27115 (org-table-maybe-recalculate-line))
27116 (call-interactively 'org-table-align))
27117 ((org-at-item-checkbox-p)
27118 (call-interactively 'org-toggle-checkbox))
27119 ((org-at-item-p)
27120 (call-interactively 'org-maybe-renumber-ordered-list))
27121 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27122 ;; Dynamic block
27123 (beginning-of-line 1)
27124 (org-update-dblock))
27125 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27126 (cond
27127 ((equal (match-string 1) "TBLFM")
27128 ;; Recalculate the table before this line
27129 (save-excursion
27130 (beginning-of-line 1)
27131 (skip-chars-backward " \r\n\t")
27132 (if (org-at-table-p)
27133 (org-call-with-arg 'org-table-recalculate t))))
27135 (call-interactively 'org-mode-restart))))
27136 (t (error "C-c C-c can do nothing useful at this location.")))))
27138 (defun org-mode-restart ()
27139 "Restart Org-mode, to scan again for special lines.
27140 Also updates the keyword regular expressions."
27141 (interactive)
27142 (let ((org-inhibit-startup t)) (org-mode))
27143 (message "Org-mode restarted to refresh keyword and special line setup"))
27145 (defun org-kill-note-or-show-branches ()
27146 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27147 (interactive)
27148 (if (not org-finish-function)
27149 (call-interactively 'show-branches)
27150 (let ((org-note-abort t))
27151 (funcall org-finish-function))))
27153 (defun org-return (&optional indent)
27154 "Goto next table row or insert a newline.
27155 Calls `org-table-next-row' or `newline', depending on context.
27156 See the individual commands for more information."
27157 (interactive)
27158 (cond
27159 ((bobp) (if indent (newline-and-indent) (newline)))
27160 ((and (org-at-heading-p)
27161 (looking-at
27162 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27163 (org-show-entry)
27164 (end-of-line 1)
27165 (newline))
27166 ((org-at-table-p)
27167 (org-table-justify-field-maybe)
27168 (call-interactively 'org-table-next-row))
27169 (t (if indent (newline-and-indent) (newline)))))
27171 (defun org-return-indent ()
27172 (interactive)
27173 "Goto next table row or insert a newline and indent.
27174 Calls `org-table-next-row' or `newline-and-indent', depending on
27175 context. See the individual commands for more information."
27176 (org-return t))
27178 (defun org-ctrl-c-minus ()
27179 "Insert separator line in table or modify bullet type in list.
27180 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27181 depending on context."
27182 (interactive)
27183 (cond
27184 ((org-at-table-p)
27185 (call-interactively 'org-table-insert-hline))
27186 ((org-on-heading-p)
27187 ;; Convert to item
27188 (save-excursion
27189 (beginning-of-line 1)
27190 (if (looking-at "\\*+ ")
27191 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27192 ((org-in-item-p)
27193 (call-interactively 'org-cycle-list-bullet))
27194 (t (error "`C-c -' does have no function here."))))
27196 (defun org-meta-return (&optional arg)
27197 "Insert a new heading or wrap a region in a table.
27198 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27199 See the individual commands for more information."
27200 (interactive "P")
27201 (cond
27202 ((org-at-table-p)
27203 (call-interactively 'org-table-wrap-region))
27204 (t (call-interactively 'org-insert-heading))))
27206 ;;; Menu entries
27208 ;; Define the Org-mode menus
27209 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27210 '("Tbl"
27211 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27212 ["Next Field" org-cycle (org-at-table-p)]
27213 ["Previous Field" org-shifttab (org-at-table-p)]
27214 ["Next Row" org-return (org-at-table-p)]
27215 "--"
27216 ["Blank Field" org-table-blank-field (org-at-table-p)]
27217 ["Edit Field" org-table-edit-field (org-at-table-p)]
27218 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27219 "--"
27220 ("Column"
27221 ["Move Column Left" org-metaleft (org-at-table-p)]
27222 ["Move Column Right" org-metaright (org-at-table-p)]
27223 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27224 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27225 ("Row"
27226 ["Move Row Up" org-metaup (org-at-table-p)]
27227 ["Move Row Down" org-metadown (org-at-table-p)]
27228 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27229 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27230 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27231 "--"
27232 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27233 ("Rectangle"
27234 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27235 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27236 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27237 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27238 "--"
27239 ("Calculate"
27240 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27241 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27242 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27243 "--"
27244 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27245 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27246 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27247 "--"
27248 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27249 "--"
27250 ["Sum Column/Rectangle" org-table-sum
27251 (or (org-at-table-p) (org-region-active-p))]
27252 ["Which Column?" org-table-current-column (org-at-table-p)])
27253 ["Debug Formulas"
27254 org-table-toggle-formula-debugger
27255 :style toggle :selected org-table-formula-debug]
27256 ["Show Col/Row Numbers"
27257 org-table-toggle-coordinate-overlays
27258 :style toggle :selected org-table-overlay-coordinates]
27259 "--"
27260 ["Create" org-table-create (and (not (org-at-table-p))
27261 org-enable-table-editor)]
27262 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27263 ["Import from File" org-table-import (not (org-at-table-p))]
27264 ["Export to File" org-table-export (org-at-table-p)]
27265 "--"
27266 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27268 (easy-menu-define org-org-menu org-mode-map "Org menu"
27269 '("Org"
27270 ("Show/Hide"
27271 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27272 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27273 ["Sparse Tree" org-occur t]
27274 ["Reveal Context" org-reveal t]
27275 ["Show All" show-all t]
27276 "--"
27277 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27278 "--"
27279 ["New Heading" org-insert-heading t]
27280 ("Navigate Headings"
27281 ["Up" outline-up-heading t]
27282 ["Next" outline-next-visible-heading t]
27283 ["Previous" outline-previous-visible-heading t]
27284 ["Next Same Level" outline-forward-same-level t]
27285 ["Previous Same Level" outline-backward-same-level t]
27286 "--"
27287 ["Jump" org-goto t])
27288 ("Edit Structure"
27289 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27290 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27291 "--"
27292 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27293 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27294 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27295 "--"
27296 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27297 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27298 ["Demote Heading" org-metaright (not (org-at-table-p))]
27299 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27300 "--"
27301 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27302 "--"
27303 ["Convert to odd levels" org-convert-to-odd-levels t]
27304 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27305 ("Editing"
27306 ["Emphasis..." org-emphasize t])
27307 ("Archive"
27308 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27309 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27310 ; :active t :keys "C-u C-c C-x C-a"]
27311 ["Sparse trees open ARCHIVE trees"
27312 (setq org-sparse-tree-open-archived-trees
27313 (not org-sparse-tree-open-archived-trees))
27314 :style toggle :selected org-sparse-tree-open-archived-trees]
27315 ["Cycling opens ARCHIVE trees"
27316 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27317 :style toggle :selected org-cycle-open-archived-trees]
27318 ["Agenda includes ARCHIVE trees"
27319 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27320 :style toggle :selected (not org-agenda-skip-archived-trees)]
27321 "--"
27322 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27323 ; ["Check and Move Children" (org-archive-subtree '(4))
27324 ; :active t :keys "C-u C-c C-x C-s"]
27326 "--"
27327 ("TODO Lists"
27328 ["TODO/DONE/-" org-todo t]
27329 ("Select keyword"
27330 ["Next keyword" org-shiftright (org-on-heading-p)]
27331 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27332 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27333 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27334 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27335 ["Show TODO Tree" org-show-todo-tree t]
27336 ["Global TODO list" org-todo-list t]
27337 "--"
27338 ["Set Priority" org-priority t]
27339 ["Priority Up" org-shiftup t]
27340 ["Priority Down" org-shiftdown t])
27341 ("TAGS and Properties"
27342 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27343 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27344 "--"
27345 ["Set property" 'org-set-property t]
27346 ["Column view of properties" org-columns t]
27347 ["Insert Column View DBlock" org-insert-columns-dblock t])
27348 ("Dates and Scheduling"
27349 ["Timestamp" org-time-stamp t]
27350 ["Timestamp (inactive)" org-time-stamp-inactive t]
27351 ("Change Date"
27352 ["1 Day Later" org-shiftright t]
27353 ["1 Day Earlier" org-shiftleft t]
27354 ["1 ... Later" org-shiftup t]
27355 ["1 ... Earlier" org-shiftdown t])
27356 ["Compute Time Range" org-evaluate-time-range t]
27357 ["Schedule Item" org-schedule t]
27358 ["Deadline" org-deadline t]
27359 "--"
27360 ["Custom time format" org-toggle-time-stamp-overlays
27361 :style radio :selected org-display-custom-times]
27362 "--"
27363 ["Goto Calendar" org-goto-calendar t]
27364 ["Date from Calendar" org-date-from-calendar t])
27365 ("Logging work"
27366 ["Clock in" org-clock-in t]
27367 ["Clock out" org-clock-out t]
27368 ["Clock cancel" org-clock-cancel t]
27369 ["Goto running clock" org-clock-goto t]
27370 ["Display times" org-clock-display t]
27371 ["Create clock table" org-clock-report t]
27372 "--"
27373 ["Record DONE time"
27374 (progn (setq org-log-done (not org-log-done))
27375 (message "Switching to %s will %s record a timestamp"
27376 (car org-done-keywords)
27377 (if org-log-done "automatically" "not")))
27378 :style toggle :selected org-log-done])
27379 "--"
27380 ["Agenda Command..." org-agenda t]
27381 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27382 ("File List for Agenda")
27383 ("Special views current file"
27384 ["TODO Tree" org-show-todo-tree t]
27385 ["Check Deadlines" org-check-deadlines t]
27386 ["Timeline" org-timeline t]
27387 ["Tags Tree" org-tags-sparse-tree t])
27388 "--"
27389 ("Hyperlinks"
27390 ["Store Link (Global)" org-store-link t]
27391 ["Insert Link" org-insert-link t]
27392 ["Follow Link" org-open-at-point t]
27393 "--"
27394 ["Next link" org-next-link t]
27395 ["Previous link" org-previous-link t]
27396 "--"
27397 ["Descriptive Links"
27398 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27399 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27400 ["Literal Links"
27401 (progn
27402 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27403 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27404 "--"
27405 ["Export/Publish..." org-export t]
27406 ("LaTeX"
27407 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27408 :selected org-cdlatex-mode]
27409 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27410 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27411 ["Modify math symbol" org-cdlatex-math-modify
27412 (org-inside-LaTeX-fragment-p)]
27413 ["Export LaTeX fragments as images"
27414 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27415 :style toggle :selected org-export-with-LaTeX-fragments])
27416 "--"
27417 ("Documentation"
27418 ["Show Version" org-version t]
27419 ["Info Documentation" org-info t])
27420 ("Customize"
27421 ["Browse Org Group" org-customize t]
27422 "--"
27423 ["Expand This Menu" org-create-customize-menu
27424 (fboundp 'customize-menu-create)])
27425 "--"
27426 ["Refresh setup" org-mode-restart t]
27429 (defun org-info (&optional node)
27430 "Read documentation for Org-mode in the info system.
27431 With optional NODE, go directly to that node."
27432 (interactive)
27433 (require 'info)
27434 (info (format "(org)%s" (or node ""))))
27436 (defun org-install-agenda-files-menu ()
27437 (let ((bl (buffer-list)))
27438 (save-excursion
27439 (while bl
27440 (set-buffer (pop bl))
27441 (if (org-mode-p) (setq bl nil)))
27442 (when (org-mode-p)
27443 (easy-menu-change
27444 '("Org") "File List for Agenda"
27445 (append
27446 (list
27447 ["Edit File List" (org-edit-agenda-file-list) t]
27448 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27449 ["Remove Current File from List" org-remove-file t]
27450 ["Cycle through agenda files" org-cycle-agenda-files t]
27451 ["Occur in all agenda files" org-occur-in-agenda-files t]
27452 "--")
27453 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27455 ;;;; Documentation
27457 (defun org-customize ()
27458 "Call the customize function with org as argument."
27459 (interactive)
27460 (customize-browse 'org))
27462 (defun org-create-customize-menu ()
27463 "Create a full customization menu for Org-mode, insert it into the menu."
27464 (interactive)
27465 (if (fboundp 'customize-menu-create)
27466 (progn
27467 (easy-menu-change
27468 '("Org") "Customize"
27469 `(["Browse Org group" org-customize t]
27470 "--"
27471 ,(customize-menu-create 'org)
27472 ["Set" Custom-set t]
27473 ["Save" Custom-save t]
27474 ["Reset to Current" Custom-reset-current t]
27475 ["Reset to Saved" Custom-reset-saved t]
27476 ["Reset to Standard Settings" Custom-reset-standard t]))
27477 (message "\"Org\"-menu now contains full customization menu"))
27478 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27480 ;;;; Miscellaneous stuff
27483 ;;; Generally useful functions
27485 (defun org-context ()
27486 "Return a list of contexts of the current cursor position.
27487 If several contexts apply, all are returned.
27488 Each context entry is a list with a symbol naming the context, and
27489 two positions indicating start and end of the context. Possible
27490 contexts are:
27492 :headline anywhere in a headline
27493 :headline-stars on the leading stars in a headline
27494 :todo-keyword on a TODO keyword (including DONE) in a headline
27495 :tags on the TAGS in a headline
27496 :priority on the priority cookie in a headline
27497 :item on the first line of a plain list item
27498 :item-bullet on the bullet/number of a plain list item
27499 :checkbox on the checkbox in a plain list item
27500 :table in an org-mode table
27501 :table-special on a special filed in a table
27502 :table-table in a table.el table
27503 :link on a hyperlink
27504 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27505 :target on a <<target>>
27506 :radio-target on a <<<radio-target>>>
27507 :latex-fragment on a LaTeX fragment
27508 :latex-preview on a LaTeX fragment with overlayed preview image
27510 This function expects the position to be visible because it uses font-lock
27511 faces as a help to recognize the following contexts: :table-special, :link,
27512 and :keyword."
27513 (let* ((f (get-text-property (point) 'face))
27514 (faces (if (listp f) f (list f)))
27515 (p (point)) clist o)
27516 ;; First the large context
27517 (cond
27518 ((org-on-heading-p t)
27519 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27520 (when (progn
27521 (beginning-of-line 1)
27522 (looking-at org-todo-line-tags-regexp))
27523 (push (org-point-in-group p 1 :headline-stars) clist)
27524 (push (org-point-in-group p 2 :todo-keyword) clist)
27525 (push (org-point-in-group p 4 :tags) clist))
27526 (goto-char p)
27527 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27528 (if (looking-at "\\[#[A-Z0-9]\\]")
27529 (push (org-point-in-group p 0 :priority) clist)))
27531 ((org-at-item-p)
27532 (push (org-point-in-group p 2 :item-bullet) clist)
27533 (push (list :item (point-at-bol)
27534 (save-excursion (org-end-of-item) (point)))
27535 clist)
27536 (and (org-at-item-checkbox-p)
27537 (push (org-point-in-group p 0 :checkbox) clist)))
27539 ((org-at-table-p)
27540 (push (list :table (org-table-begin) (org-table-end)) clist)
27541 (if (memq 'org-formula faces)
27542 (push (list :table-special
27543 (previous-single-property-change p 'face)
27544 (next-single-property-change p 'face)) clist)))
27545 ((org-at-table-p 'any)
27546 (push (list :table-table) clist)))
27547 (goto-char p)
27549 ;; Now the small context
27550 (cond
27551 ((org-at-timestamp-p)
27552 (push (org-point-in-group p 0 :timestamp) clist))
27553 ((memq 'org-link faces)
27554 (push (list :link
27555 (previous-single-property-change p 'face)
27556 (next-single-property-change p 'face)) clist))
27557 ((memq 'org-special-keyword faces)
27558 (push (list :keyword
27559 (previous-single-property-change p 'face)
27560 (next-single-property-change p 'face)) clist))
27561 ((org-on-target-p)
27562 (push (org-point-in-group p 0 :target) clist)
27563 (goto-char (1- (match-beginning 0)))
27564 (if (looking-at org-radio-target-regexp)
27565 (push (org-point-in-group p 0 :radio-target) clist))
27566 (goto-char p))
27567 ((setq o (car (delq nil
27568 (mapcar
27569 (lambda (x)
27570 (if (memq x org-latex-fragment-image-overlays) x))
27571 (org-overlays-at (point))))))
27572 (push (list :latex-fragment
27573 (org-overlay-start o) (org-overlay-end o)) clist)
27574 (push (list :latex-preview
27575 (org-overlay-start o) (org-overlay-end o)) clist))
27576 ((org-inside-LaTeX-fragment-p)
27577 ;; FIXME: positions wrong.
27578 (push (list :latex-fragment (point) (point)) clist)))
27580 (setq clist (nreverse (delq nil clist)))
27581 clist))
27583 ;; FIXME: Compare with at-regexp-p Do we need both?
27584 (defun org-in-regexp (re &optional nlines visually)
27585 "Check if point is inside a match of regexp.
27586 Normally only the current line is checked, but you can include NLINES extra
27587 lines both before and after point into the search.
27588 If VISUALLY is set, require that the cursor is not after the match but
27589 really on, so that the block visually is on the match."
27590 (catch 'exit
27591 (let ((pos (point))
27592 (eol (point-at-eol (+ 1 (or nlines 0))))
27593 (inc (if visually 1 0)))
27594 (save-excursion
27595 (beginning-of-line (- 1 (or nlines 0)))
27596 (while (re-search-forward re eol t)
27597 (if (and (<= (match-beginning 0) pos)
27598 (>= (+ inc (match-end 0)) pos))
27599 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27601 (defun org-at-regexp-p (regexp)
27602 "Is point inside a match of REGEXP in the current line?"
27603 (catch 'exit
27604 (save-excursion
27605 (let ((pos (point)) (end (point-at-eol)))
27606 (beginning-of-line 1)
27607 (while (re-search-forward regexp end t)
27608 (if (and (<= (match-beginning 0) pos)
27609 (>= (match-end 0) pos))
27610 (throw 'exit t)))
27611 nil))))
27613 (defun org-occur-in-agenda-files (regexp &optional nlines)
27614 "Call `multi-occur' with buffers for all agenda files."
27615 (interactive "sOrg-files matching: \np")
27616 (let* ((files (org-agenda-files))
27617 (tnames (mapcar 'file-truename files))
27618 (extra org-agenda-multi-occur-extra-files)
27620 (while (setq f (pop extra))
27621 (unless (member (file-truename f) tnames)
27622 (add-to-list 'files f 'append)
27623 (add-to-list 'tnames (file-truename f) 'append)))
27624 (multi-occur
27625 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27626 regexp)))
27628 (if (boundp 'occur-mode-find-occurrence-hook)
27629 ;; Emacs 23
27630 (add-hook 'occur-mode-find-occurrence-hook
27631 (lambda ()
27632 (when (org-mode-p)
27633 (org-reveal))))
27634 ;; Emacs 22
27635 (defadvice occur-mode-goto-occurrence
27636 (after org-occur-reveal activate)
27637 (and (org-mode-p) (org-reveal)))
27638 (defadvice occur-mode-goto-occurrence-other-window
27639 (after org-occur-reveal activate)
27640 (and (org-mode-p) (org-reveal)))
27641 (defadvice occur-mode-display-occurrence
27642 (after org-occur-reveal activate)
27643 (when (org-mode-p)
27644 (let ((pos (occur-mode-find-occurrence)))
27645 (with-current-buffer (marker-buffer pos)
27646 (save-excursion
27647 (goto-char pos)
27648 (org-reveal)))))))
27650 (defun org-uniquify (list)
27651 "Remove duplicate elements from LIST."
27652 (let (res)
27653 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27654 res))
27656 (defun org-delete-all (elts list)
27657 "Remove all elements in ELTS from LIST."
27658 (while elts
27659 (setq list (delete (pop elts) list)))
27660 list)
27662 (defun org-back-over-empty-lines ()
27663 "Move backwards over witespace, to the beginning of the first empty line.
27664 Returns the number o empty lines passed."
27665 (let ((pos (point)))
27666 (skip-chars-backward " \t\n\r")
27667 (beginning-of-line 2)
27668 (goto-char (min (point) pos))
27669 (count-lines (point) pos)))
27671 (defun org-skip-whitespace ()
27672 (skip-chars-forward " \t\n\r"))
27674 (defun org-point-in-group (point group &optional context)
27675 "Check if POINT is in match-group GROUP.
27676 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27677 match. If the match group does ot exist or point is not inside it,
27678 return nil."
27679 (and (match-beginning group)
27680 (>= point (match-beginning group))
27681 (<= point (match-end group))
27682 (if context
27683 (list context (match-beginning group) (match-end group))
27684 t)))
27686 (defun org-switch-to-buffer-other-window (&rest args)
27687 "Switch to buffer in a second window on the current frame.
27688 In particular, do not allow pop-up frames."
27689 (let (pop-up-frames special-display-buffer-names special-display-regexps
27690 special-display-function)
27691 (apply 'switch-to-buffer-other-window args)))
27693 (defun org-combine-plists (&rest plists)
27694 "Create a single property list from all plists in PLISTS.
27695 The process starts by copying the first list, and then setting properties
27696 from the other lists. Settings in the last list are the most significant
27697 ones and overrule settings in the other lists."
27698 (let ((rtn (copy-sequence (pop plists)))
27699 p v ls)
27700 (while plists
27701 (setq ls (pop plists))
27702 (while ls
27703 (setq p (pop ls) v (pop ls))
27704 (setq rtn (plist-put rtn p v))))
27705 rtn))
27707 (defun org-move-line-down (arg)
27708 "Move the current line down. With prefix argument, move it past ARG lines."
27709 (interactive "p")
27710 (let ((col (current-column))
27711 beg end pos)
27712 (beginning-of-line 1) (setq beg (point))
27713 (beginning-of-line 2) (setq end (point))
27714 (beginning-of-line (+ 1 arg))
27715 (setq pos (move-marker (make-marker) (point)))
27716 (insert (delete-and-extract-region beg end))
27717 (goto-char pos)
27718 (move-to-column col)))
27720 (defun org-move-line-up (arg)
27721 "Move the current line up. With prefix argument, move it past ARG lines."
27722 (interactive "p")
27723 (let ((col (current-column))
27724 beg end pos)
27725 (beginning-of-line 1) (setq beg (point))
27726 (beginning-of-line 2) (setq end (point))
27727 (beginning-of-line (- arg))
27728 (setq pos (move-marker (make-marker) (point)))
27729 (insert (delete-and-extract-region beg end))
27730 (goto-char pos)
27731 (move-to-column col)))
27733 (defun org-replace-escapes (string table)
27734 "Replace %-escapes in STRING with values in TABLE.
27735 TABLE is an association list with keys like \"%a\" and string values.
27736 The sequences in STRING may contain normal field width and padding information,
27737 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27738 so values can contain further %-escapes if they are define later in TABLE."
27739 (let ((case-fold-search nil)
27740 e re rpl)
27741 (while (setq e (pop table))
27742 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27743 (while (string-match re string)
27744 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27745 (cdr e)))
27746 (setq string (replace-match rpl t t string))))
27747 string))
27750 (defun org-sublist (list start end)
27751 "Return a section of LIST, from START to END.
27752 Counting starts at 1."
27753 (let (rtn (c start))
27754 (setq list (nthcdr (1- start) list))
27755 (while (and list (<= c end))
27756 (push (pop list) rtn)
27757 (setq c (1+ c)))
27758 (nreverse rtn)))
27760 (defun org-find-base-buffer-visiting (file)
27761 "Like `find-buffer-visiting' but alway return the base buffer and
27762 not an indirect buffer"
27763 (let ((buf (find-buffer-visiting file)))
27764 (if buf
27765 (or (buffer-base-buffer buf) buf)
27766 nil)))
27768 (defun org-image-file-name-regexp ()
27769 "Return regexp matching the file names of images."
27770 (if (fboundp 'image-file-name-regexp)
27771 (image-file-name-regexp)
27772 (let ((image-file-name-extensions
27773 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27774 "xbm" "xpm" "pbm" "pgm" "ppm")))
27775 (concat "\\."
27776 (regexp-opt (nconc (mapcar 'upcase
27777 image-file-name-extensions)
27778 image-file-name-extensions)
27780 "\\'"))))
27782 (defun org-file-image-p (file)
27783 "Return non-nil if FILE is an image."
27784 (save-match-data
27785 (string-match (org-image-file-name-regexp) file)))
27787 ;;; Paragraph filling stuff.
27788 ;; We want this to be just right, so use the full arsenal.
27790 (defun org-indent-line-function ()
27791 "Indent line like previous, but further if previous was headline or item."
27792 (interactive)
27793 (let* ((pos (point))
27794 (itemp (org-at-item-p))
27795 column bpos bcol tpos tcol bullet btype bullet-type)
27796 ;; Find the previous relevant line
27797 (beginning-of-line 1)
27798 (cond
27799 ((looking-at "#") (setq column 0))
27800 ((looking-at "\\*+ ") (setq column 0))
27802 (beginning-of-line 0)
27803 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27804 (beginning-of-line 0))
27805 (cond
27806 ((looking-at "\\*+[ \t]+")
27807 (goto-char (match-end 0))
27808 (setq column (current-column)))
27809 ((org-in-item-p)
27810 (org-beginning-of-item)
27811 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27812 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27813 (setq bpos (match-beginning 1) tpos (match-end 0)
27814 bcol (progn (goto-char bpos) (current-column))
27815 tcol (progn (goto-char tpos) (current-column))
27816 bullet (match-string 1)
27817 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27818 (if (not itemp)
27819 (setq column tcol)
27820 (goto-char pos)
27821 (beginning-of-line 1)
27822 (if (looking-at "\\S-")
27823 (progn
27824 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27825 (setq bullet (match-string 1)
27826 btype (if (string-match "[0-9]" bullet) "n" bullet))
27827 (setq column (if (equal btype bullet-type) bcol tcol)))
27828 (setq column (org-get-indentation)))))
27829 (t (setq column (org-get-indentation))))))
27830 (goto-char pos)
27831 (if (<= (current-column) (current-indentation))
27832 (indent-line-to column)
27833 (save-excursion (indent-line-to column)))
27834 (setq column (current-column))
27835 (beginning-of-line 1)
27836 (if (looking-at
27837 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27838 (replace-match (concat "\\1" (format org-property-format
27839 (match-string 2) (match-string 3)))
27840 t nil))
27841 (move-to-column column)))
27843 (defun org-set-autofill-regexps ()
27844 (interactive)
27845 ;; In the paragraph separator we include headlines, because filling
27846 ;; text in a line directly attached to a headline would otherwise
27847 ;; fill the headline as well.
27848 (org-set-local 'comment-start-skip "^#+[ \t]*")
27849 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27850 ;; The paragraph starter includes hand-formatted lists.
27851 (org-set-local 'paragraph-start
27852 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27853 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27854 ;; But only if the user has not turned off tables or fixed-width regions
27855 (org-set-local
27856 'auto-fill-inhibit-regexp
27857 (concat "\\*+ \\|#\\+"
27858 "\\|[ \t]*" org-keyword-time-regexp
27859 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27860 (concat
27861 "\\|[ \t]*["
27862 (if org-enable-table-editor "|" "")
27863 (if org-enable-fixed-width-editor ":" "")
27864 "]"))))
27865 ;; We use our own fill-paragraph function, to make sure that tables
27866 ;; and fixed-width regions are not wrapped. That function will pass
27867 ;; through to `fill-paragraph' when appropriate.
27868 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27869 ; Adaptive filling: To get full control, first make sure that
27870 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27871 (org-set-local 'adaptive-fill-regexp "\000")
27872 (org-set-local 'adaptive-fill-function
27873 'org-adaptive-fill-function)
27874 (org-set-local
27875 'align-mode-rules-list
27876 '((org-in-buffer-settings
27877 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27878 (modes . '(org-mode))))))
27880 (defun org-fill-paragraph (&optional justify)
27881 "Re-align a table, pass through to fill-paragraph if no table."
27882 (let ((table-p (org-at-table-p))
27883 (table.el-p (org-at-table.el-p)))
27884 (cond ((and (equal (char-after (point-at-bol)) ?*)
27885 (save-excursion (goto-char (point-at-bol))
27886 (looking-at outline-regexp)))
27887 t) ; skip headlines
27888 (table.el-p t) ; skip table.el tables
27889 (table-p (org-table-align) t) ; align org-mode tables
27890 (t nil)))) ; call paragraph-fill
27892 ;; For reference, this is the default value of adaptive-fill-regexp
27893 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27895 (defun org-adaptive-fill-function ()
27896 "Return a fill prefix for org-mode files.
27897 In particular, this makes sure hanging paragraphs for hand-formatted lists
27898 work correctly."
27899 (cond ((looking-at "#[ \t]+")
27900 (match-string 0))
27901 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27902 (save-excursion
27903 (goto-char (match-end 0))
27904 (make-string (current-column) ?\ )))
27905 (t nil)))
27907 ;;;; Functions extending outline functionality
27910 (defun org-beginning-of-line (&optional arg)
27911 "Go to the beginning of the current line. If that is invisible, continue
27912 to a visible line beginning. This makes the function of C-a more intuitive.
27913 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27914 first attempt, and only move to after the tags when the cursor is already
27915 beyond the end of the headline."
27916 (interactive "P")
27917 (let ((pos (point)))
27918 (beginning-of-line 1)
27919 (if (bobp)
27921 (backward-char 1)
27922 (if (org-invisible-p)
27923 (while (and (not (bobp)) (org-invisible-p))
27924 (backward-char 1)
27925 (beginning-of-line 1))
27926 (forward-char 1)))
27927 (when org-special-ctrl-a/e
27928 (cond
27929 ((and (looking-at org-todo-line-regexp)
27930 (= (char-after (match-end 1)) ?\ ))
27931 (goto-char
27932 (if (eq org-special-ctrl-a/e t)
27933 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27934 ((= pos (point)) (match-beginning 3))
27935 (t (point)))
27936 (cond ((> pos (point)) (point))
27937 ((not (eq last-command this-command)) (point))
27938 (t (match-beginning 3))))))
27939 ((org-at-item-p)
27940 (goto-char
27941 (if (eq org-special-ctrl-a/e t)
27942 (cond ((> pos (match-end 4)) (match-end 4))
27943 ((= pos (point)) (match-end 4))
27944 (t (point)))
27945 (cond ((> pos (point)) (point))
27946 ((not (eq last-command this-command)) (point))
27947 (t (match-end 4))))))))))
27949 (defun org-end-of-line (&optional arg)
27950 "Go to the end of the line.
27951 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27952 first attempt, and only move to after the tags when the cursor is already
27953 beyond the end of the headline."
27954 (interactive "P")
27955 (if (or (not org-special-ctrl-a/e)
27956 (not (org-on-heading-p)))
27957 (end-of-line arg)
27958 (let ((pos (point)))
27959 (beginning-of-line 1)
27960 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27961 (if (eq org-special-ctrl-a/e t)
27962 (if (or (< pos (match-beginning 1))
27963 (= pos (match-end 0)))
27964 (goto-char (match-beginning 1))
27965 (goto-char (match-end 0)))
27966 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27967 (goto-char (match-end 0))
27968 (goto-char (match-beginning 1))))
27969 (end-of-line arg)))))
27971 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27972 (define-key org-mode-map "\C-e" 'org-end-of-line)
27974 (defun org-kill-line (&optional arg)
27975 "Kill line, to tags or end of line."
27976 (interactive "P")
27977 (cond
27978 ((or (not org-special-ctrl-k)
27979 (bolp)
27980 (not (org-on-heading-p)))
27981 (call-interactively 'kill-line))
27982 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27983 (kill-region (point) (match-beginning 1))
27984 (org-set-tags nil t))
27985 (t (kill-region (point) (point-at-eol)))))
27987 (define-key org-mode-map "\C-k" 'org-kill-line)
27989 (defun org-invisible-p ()
27990 "Check if point is at a character currently not visible."
27991 ;; Early versions of noutline don't have `outline-invisible-p'.
27992 (if (fboundp 'outline-invisible-p)
27993 (outline-invisible-p)
27994 (get-char-property (point) 'invisible)))
27996 (defun org-invisible-p2 ()
27997 "Check if point is at a character currently not visible."
27998 (save-excursion
27999 (if (and (eolp) (not (bobp))) (backward-char 1))
28000 ;; Early versions of noutline don't have `outline-invisible-p'.
28001 (if (fboundp 'outline-invisible-p)
28002 (outline-invisible-p)
28003 (get-char-property (point) 'invisible))))
28005 (defalias 'org-back-to-heading 'outline-back-to-heading)
28006 (defalias 'org-on-heading-p 'outline-on-heading-p)
28007 (defalias 'org-at-heading-p 'outline-on-heading-p)
28008 (defun org-at-heading-or-item-p ()
28009 (or (org-on-heading-p) (org-at-item-p)))
28011 (defun org-on-target-p ()
28012 (or (org-in-regexp org-radio-target-regexp)
28013 (org-in-regexp org-target-regexp)))
28015 (defun org-up-heading-all (arg)
28016 "Move to the heading line of which the present line is a subheading.
28017 This function considers both visible and invisible heading lines.
28018 With argument, move up ARG levels."
28019 (if (fboundp 'outline-up-heading-all)
28020 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28021 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28023 (defun org-up-heading-safe ()
28024 "Move to the heading line of which the present line is a subheading.
28025 This version will not throw an error. It will return the level of the
28026 headline found, or nil if no higher level is found."
28027 (let ((pos (point)) start-level level
28028 (re (concat "^" outline-regexp)))
28029 (catch 'exit
28030 (outline-back-to-heading t)
28031 (setq start-level (funcall outline-level))
28032 (if (equal start-level 1) (throw 'exit nil))
28033 (while (re-search-backward re nil t)
28034 (setq level (funcall outline-level))
28035 (if (< level start-level) (throw 'exit level)))
28036 nil)))
28038 (defun org-first-sibling-p ()
28039 "Is this heading the first child of its parents?"
28040 (interactive)
28041 (let ((re (concat "^" outline-regexp))
28042 level l)
28043 (unless (org-at-heading-p t)
28044 (error "Not at a heading"))
28045 (setq level (funcall outline-level))
28046 (save-excursion
28047 (if (not (re-search-backward re nil t))
28049 (setq l (funcall outline-level))
28050 (< l level)))))
28052 (defun org-goto-sibling (&optional previous)
28053 "Goto the next sibling, even if it is invisible.
28054 When PREVIOUS is set, go to the previous sibling instead. Returns t
28055 when a sibling was found. When none is found, return nil and don't
28056 move point."
28057 (let ((fun (if previous 're-search-backward 're-search-forward))
28058 (pos (point))
28059 (re (concat "^" outline-regexp))
28060 level l)
28061 (when (condition-case nil (org-back-to-heading t) (error nil))
28062 (setq level (funcall outline-level))
28063 (catch 'exit
28064 (or previous (forward-char 1))
28065 (while (funcall fun re nil t)
28066 (setq l (funcall outline-level))
28067 (when (< l level) (goto-char pos) (throw 'exit nil))
28068 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28069 (goto-char pos)
28070 nil))))
28072 (defun org-show-siblings ()
28073 "Show all siblings of the current headline."
28074 (save-excursion
28075 (while (org-goto-sibling) (org-flag-heading nil)))
28076 (save-excursion
28077 (while (org-goto-sibling 'previous)
28078 (org-flag-heading nil))))
28080 (defun org-show-hidden-entry ()
28081 "Show an entry where even the heading is hidden."
28082 (save-excursion
28083 (org-show-entry)))
28085 (defun org-flag-heading (flag &optional entry)
28086 "Flag the current heading. FLAG non-nil means make invisible.
28087 When ENTRY is non-nil, show the entire entry."
28088 (save-excursion
28089 (org-back-to-heading t)
28090 ;; Check if we should show the entire entry
28091 (if entry
28092 (progn
28093 (org-show-entry)
28094 (save-excursion
28095 (and (outline-next-heading)
28096 (org-flag-heading nil))))
28097 (outline-flag-region (max (point-min) (1- (point)))
28098 (save-excursion (outline-end-of-heading) (point))
28099 flag))))
28101 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28102 ;; This is an exact copy of the original function, but it uses
28103 ;; `org-back-to-heading', to make it work also in invisible
28104 ;; trees. And is uses an invisible-OK argument.
28105 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28106 (org-back-to-heading invisible-OK)
28107 (let ((first t)
28108 (level (funcall outline-level)))
28109 (while (and (not (eobp))
28110 (or first (> (funcall outline-level) level)))
28111 (setq first nil)
28112 (outline-next-heading))
28113 (unless to-heading
28114 (if (memq (preceding-char) '(?\n ?\^M))
28115 (progn
28116 ;; Go to end of line before heading
28117 (forward-char -1)
28118 (if (memq (preceding-char) '(?\n ?\^M))
28119 ;; leave blank line before heading
28120 (forward-char -1))))))
28121 (point))
28123 (defun org-show-subtree ()
28124 "Show everything after this heading at deeper levels."
28125 (outline-flag-region
28126 (point)
28127 (save-excursion
28128 (outline-end-of-subtree) (outline-next-heading) (point))
28129 nil))
28131 (defun org-show-entry ()
28132 "Show the body directly following this heading.
28133 Show the heading too, if it is currently invisible."
28134 (interactive)
28135 (save-excursion
28136 (condition-case nil
28137 (progn
28138 (org-back-to-heading t)
28139 (outline-flag-region
28140 (max (point-min) (1- (point)))
28141 (save-excursion
28142 (re-search-forward
28143 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28144 (or (match-beginning 1) (point-max)))
28145 nil))
28146 (error nil))))
28148 (defun org-make-options-regexp (kwds)
28149 "Make a regular expression for keyword lines."
28150 (concat
28152 "#?[ \t]*\\+\\("
28153 (mapconcat 'regexp-quote kwds "\\|")
28154 "\\):[ \t]*"
28155 "\\(.+\\)"))
28157 ;; Make isearch reveal the necessary context
28158 (defun org-isearch-end ()
28159 "Reveal context after isearch exits."
28160 (when isearch-success ; only if search was successful
28161 (if (featurep 'xemacs)
28162 ;; Under XEmacs, the hook is run in the correct place,
28163 ;; we directly show the context.
28164 (org-show-context 'isearch)
28165 ;; In Emacs the hook runs *before* restoring the overlays.
28166 ;; So we have to use a one-time post-command-hook to do this.
28167 ;; (Emacs 22 has a special variable, see function `org-mode')
28168 (unless (and (boundp 'isearch-mode-end-hook-quit)
28169 isearch-mode-end-hook-quit)
28170 ;; Only when the isearch was not quitted.
28171 (org-add-hook 'post-command-hook 'org-isearch-post-command
28172 'append 'local)))))
28174 (defun org-isearch-post-command ()
28175 "Remove self from hook, and show context."
28176 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28177 (org-show-context 'isearch))
28180 ;;;; Integration with and fixes for other packages
28182 ;;; Imenu support
28184 (defvar org-imenu-markers nil
28185 "All markers currently used by Imenu.")
28186 (make-variable-buffer-local 'org-imenu-markers)
28188 (defun org-imenu-new-marker (&optional pos)
28189 "Return a new marker for use by Imenu, and remember the marker."
28190 (let ((m (make-marker)))
28191 (move-marker m (or pos (point)))
28192 (push m org-imenu-markers)
28195 (defun org-imenu-get-tree ()
28196 "Produce the index for Imenu."
28197 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28198 (setq org-imenu-markers nil)
28199 (let* ((n org-imenu-depth)
28200 (re (concat "^" outline-regexp))
28201 (subs (make-vector (1+ n) nil))
28202 (last-level 0)
28203 m tree level head)
28204 (save-excursion
28205 (save-restriction
28206 (widen)
28207 (goto-char (point-max))
28208 (while (re-search-backward re nil t)
28209 (setq level (org-reduced-level (funcall outline-level)))
28210 (when (<= level n)
28211 (looking-at org-complex-heading-regexp)
28212 (setq head (org-match-string-no-properties 4)
28213 m (org-imenu-new-marker))
28214 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28215 (if (>= level last-level)
28216 (push (cons head m) (aref subs level))
28217 (push (cons head (aref subs (1+ level))) (aref subs level))
28218 (loop for i from (1+ level) to n do (aset subs i nil)))
28219 (setq last-level level)))))
28220 (aref subs 1)))
28222 (eval-after-load "imenu"
28223 '(progn
28224 (add-hook 'imenu-after-jump-hook
28225 (lambda () (org-show-context 'org-goto)))))
28227 ;; Speedbar support
28229 (defun org-speedbar-set-agenda-restriction ()
28230 "Restrict future agenda commands to the location at point in speedbar.
28231 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28232 (interactive)
28233 (let (p m tp np dir txt w)
28234 (cond
28235 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28236 'org-imenu t))
28237 (setq m (get-text-property p 'org-imenu-marker))
28238 (save-excursion
28239 (save-restriction
28240 (set-buffer (marker-buffer m))
28241 (goto-char m)
28242 (org-agenda-set-restriction-lock 'subtree))))
28243 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28244 'speedbar-function 'speedbar-find-file))
28245 (setq tp (previous-single-property-change
28246 (1+ p) 'speedbar-function)
28247 np (next-single-property-change
28248 tp 'speedbar-function)
28249 dir (speedbar-line-directory)
28250 txt (buffer-substring-no-properties (or tp (point-min))
28251 (or np (point-max))))
28252 (save-excursion
28253 (save-restriction
28254 (set-buffer (find-file-noselect
28255 (let ((default-directory dir))
28256 (expand-file-name txt))))
28257 (unless (org-mode-p)
28258 (error "Cannot restrict to non-Org-mode file"))
28259 (org-agenda-set-restriction-lock 'file))))
28260 (t (error "Don't know how to restrict Org-mode's agenda")))
28261 (org-move-overlay org-speedbar-restriction-lock-overlay
28262 (point-at-bol) (point-at-eol))
28263 (setq current-prefix-arg nil)
28264 (org-agenda-maybe-redo)))
28266 (eval-after-load "speedbar"
28267 '(progn
28268 (speedbar-add-supported-extension ".org")
28269 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28270 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28271 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28272 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28273 (add-hook 'speedbar-visiting-tag-hook
28274 (lambda () (org-show-context 'org-goto)))))
28277 ;;; Fixes and Hacks
28279 ;; Make flyspell not check words in links, to not mess up our keymap
28280 (defun org-mode-flyspell-verify ()
28281 "Don't let flyspell put overlays at active buttons."
28282 (not (get-text-property (point) 'keymap)))
28284 ;; Make `bookmark-jump' show the jump location if it was hidden.
28285 (eval-after-load "bookmark"
28286 '(if (boundp 'bookmark-after-jump-hook)
28287 ;; We can use the hook
28288 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28289 ;; Hook not available, use advice
28290 (defadvice bookmark-jump (after org-make-visible activate)
28291 "Make the position visible."
28292 (org-bookmark-jump-unhide))))
28294 (defun org-bookmark-jump-unhide ()
28295 "Unhide the current position, to show the bookmark location."
28296 (and (org-mode-p)
28297 (or (org-invisible-p)
28298 (save-excursion (goto-char (max (point-min) (1- (point))))
28299 (org-invisible-p)))
28300 (org-show-context 'bookmark-jump)))
28302 ;; Fix a bug in htmlize where there are text properties (face nil)
28303 (eval-after-load "htmlize"
28304 '(progn
28305 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28306 "Make sure there are no nil faces"
28307 (setq ad-return-value (delq nil ad-return-value)))))
28309 ;; Make session.el ignore our circular variable
28310 (eval-after-load "session"
28311 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28313 ;;;; Experimental code
28315 (defun org-closed-in-range ()
28316 "Sparse tree of items closed in a certain time range.
28317 Still experimental, may disappear in the future."
28318 (interactive)
28319 ;; Get the time interval from the user.
28320 (let* ((time1 (time-to-seconds
28321 (org-read-date nil 'to-time nil "Starting date: ")))
28322 (time2 (time-to-seconds
28323 (org-read-date nil 'to-time nil "End date:")))
28324 ;; callback function
28325 (callback (lambda ()
28326 (let ((time
28327 (time-to-seconds
28328 (apply 'encode-time
28329 (org-parse-time-string
28330 (match-string 1))))))
28331 ;; check if time in interval
28332 (and (>= time time1) (<= time time2))))))
28333 ;; make tree, check each match with the callback
28334 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28336 ;;;; Finish up
28338 (provide 'org)
28340 (run-hooks 'org-load-hook)
28342 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28343 ;;; org.el ends here