Merge branch 'master' of git+ssh://repo.or.cz/srv/git/org-mode
[org-mode.git] / org.el
blob08ee515778c0635029a4a5543b8d55349a7898d3
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 ;; FIXME: Needs a separate group...
155 (defcustom org-completion-fallback-command 'hippie-expand
156 "The expansion command called by \\[org-complete] in normal context.
157 Normal means, no org-mode-specific context."
158 :group 'org
159 :type 'function)
161 (defgroup org-startup nil
162 "Options concerning startup of Org-mode."
163 :tag "Org Startup"
164 :group 'org)
166 (defcustom org-startup-folded t
167 "Non-nil means, entering Org-mode will switch to OVERVIEW.
168 This can also be configured on a per-file basis by adding one of
169 the following lines anywhere in the buffer:
171 #+STARTUP: fold
172 #+STARTUP: nofold
173 #+STARTUP: content"
174 :group 'org-startup
175 :type '(choice
176 (const :tag "nofold: show all" nil)
177 (const :tag "fold: overview" t)
178 (const :tag "content: all headlines" content)))
180 (defcustom org-startup-truncated t
181 "Non-nil means, entering Org-mode will set `truncate-lines'.
182 This is useful since some lines containing links can be very long and
183 uninteresting. Also tables look terrible when wrapped."
184 :group 'org-startup
185 :type 'boolean)
187 (defcustom org-startup-align-all-tables nil
188 "Non-nil means, align all tables when visiting a file.
189 This is useful when the column width in tables is forced with <N> cookies
190 in table fields. Such tables will look correct only after the first re-align.
191 This can also be configured on a per-file basis by adding one of
192 the following lines anywhere in the buffer:
193 #+STARTUP: align
194 #+STARTUP: noalign"
195 :group 'org-startup
196 :type 'boolean)
198 (defcustom org-insert-mode-line-in-empty-file nil
199 "Non-nil means insert the first line setting Org-mode in empty files.
200 When the function `org-mode' is called interactively in an empty file, this
201 normally means that the file name does not automatically trigger Org-mode.
202 To ensure that the file will always be in Org-mode in the future, a
203 line enforcing Org-mode will be inserted into the buffer, if this option
204 has been set."
205 :group 'org-startup
206 :type 'boolean)
208 (defcustom org-replace-disputed-keys nil
209 "Non-nil means use alternative key bindings for some keys.
210 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
211 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
212 If you want to use Org-mode together with one of these other modes,
213 or more generally if you would like to move some Org-mode commands to
214 other keys, set this variable and configure the keys with the variable
215 `org-disputed-keys'.
217 This option is only relevant at load-time of Org-mode, and must be set
218 *before* org.el is loaded. Changing it requires a restart of Emacs to
219 become effective."
220 :group 'org-startup
221 :type 'boolean)
223 (if (fboundp 'defvaralias)
224 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
226 (defcustom org-disputed-keys
227 '(([(shift up)] . [(meta p)])
228 ([(shift down)] . [(meta n)])
229 ([(shift left)] . [(meta -)])
230 ([(shift right)] . [(meta +)])
231 ([(control shift right)] . [(meta shift +)])
232 ([(control shift left)] . [(meta shift -)]))
233 "Keys for which Org-mode and other modes compete.
234 This is an alist, cars are the default keys, second element specifies
235 the alternative to use when `org-replace-disputed-keys' is t.
237 Keys can be specified in any syntax supported by `define-key'.
238 The value of this option takes effect only at Org-mode's startup,
239 therefore you'll have to restart Emacs to apply it after changing."
240 :group 'org-startup
241 :type 'alist)
243 (defun org-key (key)
244 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
245 Or return the original if not disputed."
246 (if org-replace-disputed-keys
247 (let* ((nkey (key-description key))
248 (x (org-find-if (lambda (x)
249 (equal (key-description (car x)) nkey))
250 org-disputed-keys)))
251 (if x (cdr x) key))
252 key))
254 (defun org-find-if (predicate seq)
255 (catch 'exit
256 (while seq
257 (if (funcall predicate (car seq))
258 (throw 'exit (car seq))
259 (pop seq)))))
261 (defun org-defkey (keymap key def)
262 "Define a key, possibly translated, as returned by `org-key'."
263 (define-key keymap (org-key key) def))
265 (defcustom org-ellipsis nil
266 "The ellipsis to use in the Org-mode outline.
267 When nil, just use the standard three dots. When a string, use that instead,
268 When a face, use the standart 3 dots, but with the specified face.
269 The change affects only Org-mode (which will then use its own display table).
270 Changing this requires executing `M-x org-mode' in a buffer to become
271 effective."
272 :group 'org-startup
273 :type '(choice (const :tag "Default" nil)
274 (face :tag "Face" :value org-warning)
275 (string :tag "String" :value "...#")))
277 (defvar org-display-table nil
278 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
280 (defgroup org-keywords nil
281 "Keywords in Org-mode."
282 :tag "Org Keywords"
283 :group 'org)
285 (defcustom org-deadline-string "DEADLINE:"
286 "String to mark deadline entries.
287 A deadline is this string, followed by a time stamp. Should be a word,
288 terminated by a colon. You can insert a schedule keyword and
289 a timestamp with \\[org-deadline].
290 Changes become only effective after restarting Emacs."
291 :group 'org-keywords
292 :type 'string)
294 (defcustom org-scheduled-string "SCHEDULED:"
295 "String to mark scheduled TODO entries.
296 A schedule is this string, followed by a time stamp. Should be a word,
297 terminated by a colon. You can insert a schedule keyword and
298 a timestamp with \\[org-schedule].
299 Changes become only effective after restarting Emacs."
300 :group 'org-keywords
301 :type 'string)
303 (defcustom org-closed-string "CLOSED:"
304 "String used as the prefix for timestamps logging closing a TODO entry."
305 :group 'org-keywords
306 :type 'string)
308 (defcustom org-clock-string "CLOCK:"
309 "String used as prefix for timestamps clocking work hours on an item."
310 :group 'org-keywords
311 :type 'string)
313 (defcustom org-comment-string "COMMENT"
314 "Entries starting with this keyword will never be exported.
315 An entry can be toggled between COMMENT and normal with
316 \\[org-toggle-comment].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
321 (defcustom org-quote-string "QUOTE"
322 "Entries starting with this keyword will be exported in fixed-width font.
323 Quoting applies only to the text in the entry following the headline, and does
324 not extend beyond the next headline, even if that is lower level.
325 An entry can be toggled between QUOTE and normal with
326 \\[org-toggle-fixed-width-section]."
327 :group 'org-keywords
328 :type 'string)
330 (defconst org-repeat-re
331 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
332 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
333 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
334 "Regular expression for specifying repeated events.
335 After a match, group 1 contains the repeat expression.")
337 (defgroup org-structure nil
338 "Options concerning the general structure of Org-mode files."
339 :tag "Org Structure"
340 :group 'org)
342 (defgroup org-reveal-location nil
343 "Options about how to make context of a location visible."
344 :tag "Org Reveal Location"
345 :group 'org-structure)
347 (defconst org-context-choice
348 '(choice
349 (const :tag "Always" t)
350 (const :tag "Never" nil)
351 (repeat :greedy t :tag "Individual contexts"
352 (cons
353 (choice :tag "Context"
354 (const agenda)
355 (const org-goto)
356 (const occur-tree)
357 (const tags-tree)
358 (const link-search)
359 (const mark-goto)
360 (const bookmark-jump)
361 (const isearch)
362 (const default))
363 (boolean))))
364 "Contexts for the reveal options.")
366 (defcustom org-show-hierarchy-above '((default . t))
367 "Non-nil means, show full hierarchy when revealing a location.
368 Org-mode often shows locations in an org-mode file which might have
369 been invisible before. When this is set, the hierarchy of headings
370 above the exposed location is shown.
371 Turning this off for example for sparse trees makes them very compact.
372 Instead of t, this can also be an alist specifying this option for different
373 contexts. Valid contexts are
374 agenda when exposing an entry from the agenda
375 org-goto when using the command `org-goto' on key C-c C-j
376 occur-tree when using the command `org-occur' on key C-c /
377 tags-tree when constructing a sparse tree based on tags matches
378 link-search when exposing search matches associated with a link
379 mark-goto when exposing the jump goal of a mark
380 bookmark-jump when exposing a bookmark location
381 isearch when exiting from an incremental search
382 default default for all contexts not set explicitly"
383 :group 'org-reveal-location
384 :type org-context-choice)
386 (defcustom org-show-following-heading '((default . nil))
387 "Non-nil means, show following heading when revealing a location.
388 Org-mode often shows locations in an org-mode file which might have
389 been invisible before. When this is set, the heading following the
390 match is shown.
391 Turning this off for example for sparse trees makes them very compact,
392 but makes it harder to edit the location of the match. In such a case,
393 use the command \\[org-reveal] to show more context.
394 Instead of t, this can also be an alist specifying this option for different
395 contexts. See `org-show-hierarchy-above' for valid contexts."
396 :group 'org-reveal-location
397 :type org-context-choice)
399 (defcustom org-show-siblings '((default . nil) (isearch t))
400 "Non-nil means, show all sibling heading when revealing a location.
401 Org-mode often shows locations in an org-mode file which might have
402 been invisible before. When this is set, the sibling of the current entry
403 heading are all made visible. If `org-show-hierarchy-above' is t,
404 the same happens on each level of the hierarchy above the current entry.
406 By default this is on for the isearch context, off for all other contexts.
407 Turning this off for example for sparse trees makes them very compact,
408 but makes it harder to edit the location of the match. In such a case,
409 use the command \\[org-reveal] to show more context.
410 Instead of t, this can also be an alist specifying this option for different
411 contexts. See `org-show-hierarchy-above' for valid contexts."
412 :group 'org-reveal-location
413 :type org-context-choice)
415 (defcustom org-show-entry-below '((default . nil))
416 "Non-nil means, show the entry below a headline when revealing a location.
417 Org-mode often shows locations in an org-mode file which might have
418 been invisible before. When this is set, the text below the headline that is
419 exposed is also shown.
421 By default this is off for all contexts.
422 Instead of t, this can also be an alist specifying this option for different
423 contexts. See `org-show-hierarchy-above' for valid contexts."
424 :group 'org-reveal-location
425 :type org-context-choice)
427 (defgroup org-cycle nil
428 "Options concerning visibility cycling in Org-mode."
429 :tag "Org Cycle"
430 :group 'org-structure)
432 (defcustom org-drawers '("PROPERTIES" "CLOCK")
433 "Names of drawers. Drawers are not opened by cycling on the headline above.
434 Drawers only open with a TAB on the drawer line itself. A drawer looks like
435 this:
436 :DRAWERNAME:
437 .....
438 :END:
439 The drawer \"PROPERTIES\" is special for capturing properties through
440 the property API.
442 Drawers can be defined on the per-file basis with a line like:
444 #+DRAWERS: HIDDEN STATE PROPERTIES"
445 :group 'org-structure
446 :type '(repeat (string :tag "Drawer Name")))
448 (defcustom org-cycle-global-at-bob nil
449 "Cycle globally if cursor is at beginning of buffer and not at a headline.
450 This makes it possible to do global cycling without having to use S-TAB or
451 C-u TAB. For this special case to work, the first line of the buffer
452 must not be a headline - it may be empty ot some other text. When used in
453 this way, `org-cycle-hook' is disables temporarily, to make sure the
454 cursor stays at the beginning of the buffer.
455 When this option is nil, don't do anything special at the beginning
456 of the buffer."
457 :group 'org-cycle
458 :type 'boolean)
460 (defcustom org-cycle-emulate-tab t
461 "Where should `org-cycle' emulate TAB.
462 nil Never
463 white Only in completely white lines
464 whitestart Only at the beginning of lines, before the first non-white char
465 t Everywhere except in headlines
466 exc-hl-bol Everywhere except at the start of a headline
467 If TAB is used in a place where it does not emulate TAB, the current subtree
468 visibility is cycled."
469 :group 'org-cycle
470 :type '(choice (const :tag "Never" nil)
471 (const :tag "Only in completely white lines" white)
472 (const :tag "Before first char in a line" whitestart)
473 (const :tag "Everywhere except in headlines" t)
474 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
477 (defcustom org-cycle-separator-lines 2
478 "Number of empty lines needed to keep an empty line between collapsed trees.
479 If you leave an empty line between the end of a subtree and the following
480 headline, this empty line is hidden when the subtree is folded.
481 Org-mode will leave (exactly) one empty line visible if the number of
482 empty lines is equal or larger to the number given in this variable.
483 So the default 2 means, at least 2 empty lines after the end of a subtree
484 are needed to produce free space between a collapsed subtree and the
485 following headline.
487 Special case: when 0, never leave empty lines in collapsed view."
488 :group 'org-cycle
489 :type 'integer)
491 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
492 org-cycle-hide-drawers
493 org-cycle-show-empty-lines
494 org-optimize-window-after-visibility-change)
495 "Hook that is run after `org-cycle' has changed the buffer visibility.
496 The function(s) in this hook must accept a single argument which indicates
497 the new state that was set by the most recent `org-cycle' command. The
498 argument is a symbol. After a global state change, it can have the values
499 `overview', `content', or `all'. After a local state change, it can have
500 the values `folded', `children', or `subtree'."
501 :group 'org-cycle
502 :type 'hook)
504 (defgroup org-edit-structure nil
505 "Options concerning structure editing in Org-mode."
506 :tag "Org Edit Structure"
507 :group 'org-structure)
509 (defcustom org-special-ctrl-a/e nil
510 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
511 When t, `C-a' will bring back the cursor to the beginning of the
512 headline text, i.e. after the stars and after a possible TODO keyword.
513 In an item, this will be the position after the bullet.
514 When the cursor is already at that position, another `C-a' will bring
515 it to the beginning of the line.
516 `C-e' will jump to the end of the headline, ignoring the presence of tags
517 in the headline. A second `C-e' will then jump to the true end of the
518 line, after any tags.
519 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
520 and only a directly following, identical keypress will bring the cursor
521 to the special positions."
522 :group 'org-edit-structure
523 :type '(choice
524 (const :tag "off" nil)
525 (const :tag "after bullet first" t)
526 (const :tag "border first" reversed)))
528 (if (fboundp 'defvaralias)
529 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
531 (defcustom org-special-ctrl-k nil
532 "Non-nil means `C-k' will behave specially in headlines.
533 When nil, `C-k' will call the default `kill-line' command.
534 When t, the following will happen while the cursor is in the headline:
536 - When the cursor is at the beginning of a headline, kill the entire
537 line and possible the folded subtree below the line.
538 - When in the middle of the headline text, kill the headline up to the tags.
539 - When after the headline text, kill the tags."
540 :group 'org-edit-structure
541 :type 'boolean)
543 (defcustom org-odd-levels-only nil
544 "Non-nil means, skip even levels and only use odd levels for the outline.
545 This has the effect that two stars are being added/taken away in
546 promotion/demotion commands. It also influences how levels are
547 handled by the exporters.
548 Changing it requires restart of `font-lock-mode' to become effective
549 for fontification also in regions already fontified.
550 You may also set this on a per-file basis by adding one of the following
551 lines to the buffer:
553 #+STARTUP: odd
554 #+STARTUP: oddeven"
555 :group 'org-edit-structure
556 :group 'org-font-lock
557 :type 'boolean)
559 (defcustom org-adapt-indentation t
560 "Non-nil means, adapt indentation when promoting and demoting.
561 When this is set and the *entire* text in an entry is indented, the
562 indentation is increased by one space in a demotion command, and
563 decreased by one in a promotion command. If any line in the entry
564 body starts at column 0, indentation is not changed at all."
565 :group 'org-edit-structure
566 :type 'boolean)
568 (defcustom org-blank-before-new-entry '((heading . nil)
569 (plain-list-item . nil))
570 "Should `org-insert-heading' leave a blank line before new heading/item?
571 The value is an alist, with `heading' and `plain-list-item' as car,
572 and a boolean flag as cdr."
573 :group 'org-edit-structure
574 :type '(list
575 (cons (const heading) (boolean))
576 (cons (const plain-list-item) (boolean))))
578 (defcustom org-insert-heading-hook nil
579 "Hook being run after inserting a new heading."
580 :group 'org-edit-structure
581 :type 'hook)
583 (defcustom org-enable-fixed-width-editor t
584 "Non-nil means, lines starting with \":\" are treated as fixed-width.
585 This currently only means, they are never auto-wrapped.
586 When nil, such lines will be treated like ordinary lines.
587 See also the QUOTE keyword."
588 :group 'org-edit-structure
589 :type 'boolean)
591 (defcustom org-goto-auto-isearch t
592 "Non-nil means, typing characters in org-goto starts incremental search."
593 :group 'org-edit-structure
594 :type 'boolean)
596 (defgroup org-sparse-trees nil
597 "Options concerning sparse trees in Org-mode."
598 :tag "Org Sparse Trees"
599 :group 'org-structure)
601 (defcustom org-highlight-sparse-tree-matches t
602 "Non-nil means, highlight all matches that define a sparse tree.
603 The highlights will automatically disappear the next time the buffer is
604 changed by an edit command."
605 :group 'org-sparse-trees
606 :type 'boolean)
608 (defcustom org-remove-highlights-with-change t
609 "Non-nil means, any change to the buffer will remove temporary highlights.
610 Such highlights are created by `org-occur' and `org-clock-display'.
611 When nil, `C-c C-c needs to be used to get rid of the highlights.
612 The highlights created by `org-preview-latex-fragment' always need
613 `C-c C-c' to be removed."
614 :group 'org-sparse-trees
615 :group 'org-time
616 :type 'boolean)
619 (defcustom org-occur-hook '(org-first-headline-recenter)
620 "Hook that is run after `org-occur' has constructed a sparse tree.
621 This can be used to recenter the window to show as much of the structure
622 as possible."
623 :group 'org-sparse-trees
624 :type 'hook)
626 (defgroup org-plain-lists nil
627 "Options concerning plain lists in Org-mode."
628 :tag "Org Plain lists"
629 :group 'org-structure)
631 (defcustom org-cycle-include-plain-lists nil
632 "Non-nil means, include plain lists into visibility cycling.
633 This means that during cycling, plain list items will *temporarily* be
634 interpreted as outline headlines with a level given by 1000+i where i is the
635 indentation of the bullet. In all other operations, plain list items are
636 not seen as headlines. For example, you cannot assign a TODO keyword to
637 such an item."
638 :group 'org-plain-lists
639 :type 'boolean)
641 (defcustom org-plain-list-ordered-item-terminator t
642 "The character that makes a line with leading number an ordered list item.
643 Valid values are ?. and ?\). To get both terminators, use t. While
644 ?. may look nicer, it creates the danger that a line with leading
645 number may be incorrectly interpreted as an item. ?\) therefore is
646 the safe choice."
647 :group 'org-plain-lists
648 :type '(choice (const :tag "dot like in \"2.\"" ?.)
649 (const :tag "paren like in \"2)\"" ?\))
650 (const :tab "both" t)))
652 (defcustom org-auto-renumber-ordered-lists t
653 "Non-nil means, automatically renumber ordered plain lists.
654 Renumbering happens when the sequence have been changed with
655 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
656 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
657 :group 'org-plain-lists
658 :type 'boolean)
660 (defcustom org-provide-checkbox-statistics t
661 "Non-nil means, update checkbox statistics after insert and toggle.
662 When this is set, checkbox statistics is updated each time you either insert
663 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
664 with \\[org-ctrl-c-ctrl-c\\]."
665 :group 'org-plain-lists
666 :type 'boolean)
668 (defgroup org-archive nil
669 "Options concerning archiving in Org-mode."
670 :tag "Org Archive"
671 :group 'org-structure)
673 (defcustom org-archive-tag "ARCHIVE"
674 "The tag that marks a subtree as archived.
675 An archived subtree does not open during visibility cycling, and does
676 not contribute to the agenda listings.
677 After changing this, font-lock must be restarted in the relevant buffers to
678 get the proper fontification."
679 :group 'org-archive
680 :group 'org-keywords
681 :type 'string)
683 (defcustom org-agenda-skip-archived-trees t
684 "Non-nil means, the agenda will skip any items located in archived trees.
685 An archived tree is a tree marked with the tag ARCHIVE."
686 :group 'org-archive
687 :group 'org-agenda-skip
688 :type 'boolean)
690 (defcustom org-cycle-open-archived-trees nil
691 "Non-nil means, `org-cycle' will open archived trees.
692 An archived tree is a tree marked with the tag ARCHIVE.
693 When nil, archived trees will stay folded. You can still open them with
694 normal outline commands like `show-all', but not with the cycling commands."
695 :group 'org-archive
696 :group 'org-cycle
697 :type 'boolean)
699 (defcustom org-sparse-tree-open-archived-trees nil
700 "Non-nil means sparse tree construction shows matches in archived trees.
701 When nil, matches in these trees are highlighted, but the trees are kept in
702 collapsed state."
703 :group 'org-archive
704 :group 'org-sparse-trees
705 :type 'boolean)
707 (defcustom org-archive-location "%s_archive::"
708 "The location where subtrees should be archived.
709 This string consists of two parts, separated by a double-colon.
711 The first part is a file name - when omitted, archiving happens in the same
712 file. %s will be replaced by the current file name (without directory part).
713 Archiving to a different file is useful to keep archived entries from
714 contributing to the Org-mode Agenda.
716 The part after the double colon is a headline. The archived entries will be
717 filed under that headline. When omitted, the subtrees are simply filed away
718 at the end of the file, as top-level entries.
720 Here are a few examples:
721 \"%s_archive::\"
722 If the current file is Projects.org, archive in file
723 Projects.org_archive, as top-level trees. This is the default.
725 \"::* Archived Tasks\"
726 Archive in the current file, under the top-level headline
727 \"* Archived Tasks\".
729 \"~/org/archive.org::\"
730 Archive in file ~/org/archive.org (absolute path), as top-level trees.
732 \"basement::** Finished Tasks\"
733 Archive in file ./basement (relative path), as level 3 trees
734 below the level 2 heading \"** Finished Tasks\".
736 You may set this option on a per-file basis by adding to the buffer a
737 line like
739 #+ARCHIVE: basement::** Finished Tasks"
740 :group 'org-archive
741 :type 'string)
743 (defcustom org-archive-mark-done t
744 "Non-nil means, mark entries as DONE when they are moved to the archive file.
745 This can be a string to set the keyword to use. When t, Org-mode will
746 use the first keyword in its list that means done."
747 :group 'org-archive
748 :type '(choice
749 (const :tag "No" nil)
750 (const :tag "Yes" t)
751 (string :tag "Use this keyword")))
753 (defcustom org-archive-stamp-time t
754 "Non-nil means, add a time stamp to entries moved to an archive file.
755 This variable is obsolete and has no effect anymore, instead add ot remove
756 `time' from the variablle `org-archive-save-context-info'."
757 :group 'org-archive
758 :type 'boolean)
760 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
761 "Parts of context info that should be stored as properties when archiving.
762 When a subtree is moved to an archive file, it looses information given by
763 context, like inherited tags, the category, and possibly also the TODO
764 state (depending on the variable `org-archive-mark-done').
765 This variable can be a list of any of the following symbols:
767 time The time of archiving.
768 file The file where the entry originates.
769 itags The local tags, in the headline of the subtree.
770 ltags The tags the subtree inherits from further up the hierarchy.
771 todo The pre-archive TODO state.
772 category The category, taken from file name or #+CATEGORY lines.
773 olpath The outline path to the item. These are all headlines above
774 the current item, separated by /, like a file path.
776 For each symbol present in the list, a property will be created in
777 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
778 information."
779 :group 'org-archive
780 :type '(set :greedy t
781 (const :tag "Time" time)
782 (const :tag "File" file)
783 (const :tag "Category" category)
784 (const :tag "TODO state" todo)
785 (const :tag "TODO state" priority)
786 (const :tag "Inherited tags" itags)
787 (const :tag "Outline path" olpath)
788 (const :tag "Local tags" ltags)))
790 (defgroup org-imenu-and-speedbar nil
791 "Options concerning imenu and speedbar in Org-mode."
792 :tag "Org Imenu and Speedbar"
793 :group 'org-structure)
795 (defcustom org-imenu-depth 2
796 "The maximum level for Imenu access to Org-mode headlines.
797 This also applied for speedbar access."
798 :group 'org-imenu-and-speedbar
799 :type 'number)
801 (defgroup org-table nil
802 "Options concerning tables in Org-mode."
803 :tag "Org Table"
804 :group 'org)
806 (defcustom org-enable-table-editor 'optimized
807 "Non-nil means, lines starting with \"|\" are handled by the table editor.
808 When nil, such lines will be treated like ordinary lines.
810 When equal to the symbol `optimized', the table editor will be optimized to
811 do the following:
812 - Automatic overwrite mode in front of whitespace in table fields.
813 This makes the structure of the table stay in tact as long as the edited
814 field does not exceed the column width.
815 - Minimize the number of realigns. Normally, the table is aligned each time
816 TAB or RET are pressed to move to another field. With optimization this
817 happens only if changes to a field might have changed the column width.
818 Optimization requires replacing the functions `self-insert-command',
819 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
820 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
821 very good at guessing when a re-align will be necessary, but you can always
822 force one with \\[org-ctrl-c-ctrl-c].
824 If you would like to use the optimized version in Org-mode, but the
825 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
827 This variable can be used to turn on and off the table editor during a session,
828 but in order to toggle optimization, a restart is required.
830 See also the variable `org-table-auto-blank-field'."
831 :group 'org-table
832 :type '(choice
833 (const :tag "off" nil)
834 (const :tag "on" t)
835 (const :tag "on, optimized" optimized)))
837 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
838 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
839 In the optimized version, the table editor takes over all simple keys that
840 normally just insert a character. In tables, the characters are inserted
841 in a way to minimize disturbing the table structure (i.e. in overwrite mode
842 for empty fields). Outside tables, the correct binding of the keys is
843 restored.
845 The default for this option is t if the optimized version is also used in
846 Org-mode. See the variable `org-enable-table-editor' for details. Changing
847 this variable requires a restart of Emacs to become effective."
848 :group 'org-table
849 :type 'boolean)
851 (defcustom orgtbl-radio-table-templates
852 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
853 % END RECEIVE ORGTBL %n
854 \\begin{comment}
855 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
856 | | |
857 \\end{comment}\n")
858 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
859 @c END RECEIVE ORGTBL %n
860 @ignore
861 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
862 | | |
863 @end ignore\n")
864 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
865 <!-- END RECEIVE ORGTBL %n -->
866 <!--
867 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
868 | | |
869 -->\n"))
870 "Templates for radio tables in different major modes.
871 All occurrences of %n in a template will be replaced with the name of the
872 table, obtained by prompting the user."
873 :group 'org-table
874 :type '(repeat
875 (list (symbol :tag "Major mode")
876 (string :tag "Format"))))
878 (defgroup org-table-settings nil
879 "Settings for tables in Org-mode."
880 :tag "Org Table Settings"
881 :group 'org-table)
883 (defcustom org-table-default-size "5x2"
884 "The default size for newly created tables, Columns x Rows."
885 :group 'org-table-settings
886 :type 'string)
888 (defcustom org-table-number-regexp
889 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
890 "Regular expression for recognizing numbers in table columns.
891 If a table column contains mostly numbers, it will be aligned to the
892 right. If not, it will be aligned to the left.
894 The default value of this option is a regular expression which allows
895 anything which looks remotely like a number as used in scientific
896 context. For example, all of the following will be considered a
897 number:
898 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
900 Other options offered by the customize interface are more restrictive."
901 :group 'org-table-settings
902 :type '(choice
903 (const :tag "Positive Integers"
904 "^[0-9]+$")
905 (const :tag "Integers"
906 "^[-+]?[0-9]+$")
907 (const :tag "Floating Point Numbers"
908 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
909 (const :tag "Floating Point Number or Integer"
910 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
911 (const :tag "Exponential, Floating point, Integer"
912 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
913 (const :tag "Very General Number-Like, including hex"
914 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
915 (string :tag "Regexp:")))
917 (defcustom org-table-number-fraction 0.5
918 "Fraction of numbers in a column required to make the column align right.
919 In a column all non-white fields are considered. If at least this
920 fraction of fields is matched by `org-table-number-fraction',
921 alignment to the right border applies."
922 :group 'org-table-settings
923 :type 'number)
925 (defgroup org-table-editing nil
926 "Behavior of tables during editing in Org-mode."
927 :tag "Org Table Editing"
928 :group 'org-table)
930 (defcustom org-table-automatic-realign t
931 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
932 When nil, aligning is only done with \\[org-table-align], or after column
933 removal/insertion."
934 :group 'org-table-editing
935 :type 'boolean)
937 (defcustom org-table-auto-blank-field t
938 "Non-nil means, automatically blank table field when starting to type into it.
939 This only happens when typing immediately after a field motion
940 command (TAB, S-TAB or RET).
941 Only relevant when `org-enable-table-editor' is equal to `optimized'."
942 :group 'org-table-editing
943 :type 'boolean)
945 (defcustom org-table-tab-jumps-over-hlines t
946 "Non-nil means, tab in the last column of a table with jump over a hline.
947 If a horizontal separator line is following the current line,
948 `org-table-next-field' can either create a new row before that line, or jump
949 over the line. When this option is nil, a new line will be created before
950 this line."
951 :group 'org-table-editing
952 :type 'boolean)
954 (defcustom org-table-tab-recognizes-table.el t
955 "Non-nil means, TAB will automatically notice a table.el table.
956 When it sees such a table, it moves point into it and - if necessary -
957 calls `table-recognize-table'."
958 :group 'org-table-editing
959 :type 'boolean)
961 (defgroup org-table-calculation nil
962 "Options concerning tables in Org-mode."
963 :tag "Org Table Calculation"
964 :group 'org-table)
966 (defcustom org-table-use-standard-references t
967 "Should org-mode work with table refrences like B3 instead of @3$2?
968 Possible values are:
969 nil never use them
970 from accept as input, do not present for editing
971 t: accept as input and present for editing"
972 :group 'org-table-calculation
973 :type '(choice
974 (const :tag "Never, don't even check unser input for them" nil)
975 (const :tag "Always, both as user input, and when editing" t)
976 (const :tag "Convert user input, don't offer during editing" 'from)))
978 (defcustom org-table-copy-increment t
979 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
980 :group 'org-table-calculation
981 :type 'boolean)
983 (defcustom org-calc-default-modes
984 '(calc-internal-prec 12
985 calc-float-format (float 5)
986 calc-angle-mode deg
987 calc-prefer-frac nil
988 calc-symbolic-mode nil
989 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
990 calc-display-working-message t
992 "List with Calc mode settings for use in calc-eval for table formulas.
993 The list must contain alternating symbols (Calc modes variables and values).
994 Don't remove any of the default settings, just change the values. Org-mode
995 relies on the variables to be present in the list."
996 :group 'org-table-calculation
997 :type 'plist)
999 (defcustom org-table-formula-evaluate-inline t
1000 "Non-nil means, TAB and RET evaluate a formula in current table field.
1001 If the current field starts with an equal sign, it is assumed to be a formula
1002 which should be evaluated as described in the manual and in the documentation
1003 string of the command `org-table-eval-formula'. This feature requires the
1004 Emacs calc package.
1005 When this variable is nil, formula calculation is only available through
1006 the command \\[org-table-eval-formula]."
1007 :group 'org-table-calculation
1008 :type 'boolean)
1010 (defcustom org-table-formula-use-constants t
1011 "Non-nil means, interpret constants in formulas in tables.
1012 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1013 by the value given in `org-table-formula-constants', or by a value obtained
1014 from the `constants.el' package."
1015 :group 'org-table-calculation
1016 :type 'boolean)
1018 (defcustom org-table-formula-constants nil
1019 "Alist with constant names and values, for use in table formulas.
1020 The car of each element is a name of a constant, without the `$' before it.
1021 The cdr is the value as a string. For example, if you'd like to use the
1022 speed of light in a formula, you would configure
1024 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1026 and then use it in an equation like `$1*$c'.
1028 Constants can also be defined on a per-file basis using a line like
1030 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1031 :group 'org-table-calculation
1032 :type '(repeat
1033 (cons (string :tag "name")
1034 (string :tag "value"))))
1036 (defvar org-table-formula-constants-local nil
1037 "Local version of `org-table-formula-constants'.")
1038 (make-variable-buffer-local 'org-table-formula-constants-local)
1040 (defcustom org-table-allow-automatic-line-recalculation t
1041 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1042 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1043 :group 'org-table-calculation
1044 :type 'boolean)
1046 (defgroup org-link nil
1047 "Options concerning links in Org-mode."
1048 :tag "Org Link"
1049 :group 'org)
1051 (defvar org-link-abbrev-alist-local nil
1052 "Buffer-local version of `org-link-abbrev-alist', which see.
1053 The value of this is taken from the #+LINK lines.")
1054 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1056 (defcustom org-link-abbrev-alist nil
1057 "Alist of link abbreviations.
1058 The car of each element is a string, to be replaced at the start of a link.
1059 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1060 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1062 [[linkkey:tag][description]]
1064 If REPLACE is a string, the tag will simply be appended to create the link.
1065 If the string contains \"%s\", the tag will be inserted there.
1067 REPLACE may also be a function that will be called with the tag as the
1068 only argument to create the link, which should be returned as a string.
1070 See the manual for examples."
1071 :group 'org-link
1072 :type 'alist)
1074 (defcustom org-descriptive-links t
1075 "Non-nil means, hide link part and only show description of bracket links.
1076 Bracket links are like [[link][descritpion]]. This variable sets the initial
1077 state in new org-mode buffers. The setting can then be toggled on a
1078 per-buffer basis from the Org->Hyperlinks menu."
1079 :group 'org-link
1080 :type 'boolean)
1082 (defcustom org-link-file-path-type 'adaptive
1083 "How the path name in file links should be stored.
1084 Valid values are:
1086 relative Relative to the current directory, i.e. the directory of the file
1087 into which the link is being inserted.
1088 absolute Absolute path, if possible with ~ for home directory.
1089 noabbrev Absolute path, no abbreviation of home directory.
1090 adaptive Use relative path for files in the current directory and sub-
1091 directories of it. For other files, use an absolute path."
1092 :group 'org-link
1093 :type '(choice
1094 (const relative)
1095 (const absolute)
1096 (const noabbrev)
1097 (const adaptive)))
1099 (defcustom org-activate-links '(bracket angle plain radio tag date)
1100 "Types of links that should be activated in Org-mode files.
1101 This is a list of symbols, each leading to the activation of a certain link
1102 type. In principle, it does not hurt to turn on most link types - there may
1103 be a small gain when turning off unused link types. The types are:
1105 bracket The recommended [[link][description]] or [[link]] links with hiding.
1106 angular Links in angular brackes that may contain whitespace like
1107 <bbdb:Carsten Dominik>.
1108 plain Plain links in normal text, no whitespace, like http://google.com.
1109 radio Text that is matched by a radio target, see manual for details.
1110 tag Tag settings in a headline (link to tag search).
1111 date Time stamps (link to calendar).
1113 Changing this variable requires a restart of Emacs to become effective."
1114 :group 'org-link
1115 :type '(set (const :tag "Double bracket links (new style)" bracket)
1116 (const :tag "Angular bracket links (old style)" angular)
1117 (const :tag "plain text links" plain)
1118 (const :tag "Radio target matches" radio)
1119 (const :tag "Tags" tag)
1120 (const :tag "Tags" target)
1121 (const :tag "Timestamps" date)))
1123 (defgroup org-link-store nil
1124 "Options concerning storing links in Org-mode"
1125 :tag "Org Store Link"
1126 :group 'org-link)
1128 (defcustom org-email-link-description-format "Email %c: %.30s"
1129 "Format of the description part of a link to an email or usenet message.
1130 The following %-excapes will be replaced by corresponding information:
1132 %F full \"From\" field
1133 %f name, taken from \"From\" field, address if no name
1134 %T full \"To\" field
1135 %t first name in \"To\" field, address if no name
1136 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1137 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1138 %s subject
1139 %m message-id.
1141 You may use normal field width specification between the % and the letter.
1142 This is for example useful to limit the length of the subject.
1144 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1145 :group 'org-link-store
1146 :type 'string)
1148 (defcustom org-from-is-user-regexp
1149 (let (r1 r2)
1150 (when (and user-mail-address (not (string= user-mail-address "")))
1151 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1152 (when (and user-full-name (not (string= user-full-name "")))
1153 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1154 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1155 "Regexp mached against the \"From:\" header of an email or usenet message.
1156 It should match if the message is from the user him/herself."
1157 :group 'org-link-store
1158 :type 'regexp)
1160 (defcustom org-context-in-file-links t
1161 "Non-nil means, file links from `org-store-link' contain context.
1162 A search string will be added to the file name with :: as separator and
1163 used to find the context when the link is activated by the command
1164 `org-open-at-point'.
1165 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1166 negates this setting for the duration of the command."
1167 :group 'org-link-store
1168 :type 'boolean)
1170 (defcustom org-keep-stored-link-after-insertion nil
1171 "Non-nil means, keep link in list for entire session.
1173 The command `org-store-link' adds a link pointing to the current
1174 location to an internal list. These links accumulate during a session.
1175 The command `org-insert-link' can be used to insert links into any
1176 Org-mode file (offering completion for all stored links). When this
1177 option is nil, every link which has been inserted once using \\[org-insert-link]
1178 will be removed from the list, to make completing the unused links
1179 more efficient."
1180 :group 'org-link-store
1181 :type 'boolean)
1183 (defcustom org-usenet-links-prefer-google nil
1184 "Non-nil means, `org-store-link' will create web links to Google groups.
1185 When nil, Gnus will be used for such links.
1186 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1187 negates this setting for the duration of the command."
1188 :group 'org-link-store
1189 :type 'boolean)
1191 (defgroup org-link-follow nil
1192 "Options concerning following links in Org-mode"
1193 :tag "Org Follow Link"
1194 :group 'org-link)
1196 (defcustom org-tab-follows-link nil
1197 "Non-nil means, on links TAB will follow the link.
1198 Needs to be set before org.el is loaded."
1199 :group 'org-link-follow
1200 :type 'boolean)
1202 (defcustom org-return-follows-link nil
1203 "Non-nil means, on links RET will follow the link.
1204 Needs to be set before org.el is loaded."
1205 :group 'org-link-follow
1206 :type 'boolean)
1208 (defcustom org-mouse-1-follows-link t
1209 "Non-nil means, mouse-1 on a link will follow the link.
1210 A longer mouse click will still set point. Does not wortk on XEmacs.
1211 Needs to be set before org.el is loaded."
1212 :group 'org-link-follow
1213 :type 'boolean)
1215 (defcustom org-mark-ring-length 4
1216 "Number of different positions to be recorded in the ring
1217 Changing this requires a restart of Emacs to work correctly."
1218 :group 'org-link-follow
1219 :type 'interger)
1221 (defcustom org-link-frame-setup
1222 '((vm . vm-visit-folder-other-frame)
1223 (gnus . gnus-other-frame)
1224 (file . find-file-other-window))
1225 "Setup the frame configuration for following links.
1226 When following a link with Emacs, it may often be useful to display
1227 this link in another window or frame. This variable can be used to
1228 set this up for the different types of links.
1229 For VM, use any of
1230 `vm-visit-folder'
1231 `vm-visit-folder-other-frame'
1232 For Gnus, use any of
1233 `gnus'
1234 `gnus-other-frame'
1235 For FILE, use any of
1236 `find-file'
1237 `find-file-other-window'
1238 `find-file-other-frame'
1239 For the calendar, use the variable `calendar-setup'.
1240 For BBDB, it is currently only possible to display the matches in
1241 another window."
1242 :group 'org-link-follow
1243 :type '(list
1244 (cons (const vm)
1245 (choice
1246 (const vm-visit-folder)
1247 (const vm-visit-folder-other-window)
1248 (const vm-visit-folder-other-frame)))
1249 (cons (const gnus)
1250 (choice
1251 (const gnus)
1252 (const gnus-other-frame)))
1253 (cons (const file)
1254 (choice
1255 (const find-file)
1256 (const find-file-other-window)
1257 (const find-file-other-frame)))))
1259 (defcustom org-display-internal-link-with-indirect-buffer nil
1260 "Non-nil means, use indirect buffer to display infile links.
1261 Activating internal links (from one location in a file to another location
1262 in the same file) normally just jumps to the location. When the link is
1263 activated with a C-u prefix (or with mouse-3), the link is displayed in
1264 another window. When this option is set, the other window actually displays
1265 an indirect buffer clone of the current buffer, to avoid any visibility
1266 changes to the current buffer."
1267 :group 'org-link-follow
1268 :type 'boolean)
1270 (defcustom org-open-non-existing-files nil
1271 "Non-nil means, `org-open-file' will open non-existing files.
1272 When nil, an error will be generated."
1273 :group 'org-link-follow
1274 :type 'boolean)
1276 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1277 "Function and arguments to call for following mailto links.
1278 This is a list with the first element being a lisp function, and the
1279 remaining elements being arguments to the function. In string arguments,
1280 %a will be replaced by the address, and %s will be replaced by the subject
1281 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1282 :group 'org-link-follow
1283 :type '(choice
1284 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1285 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1286 (const :tag "message-mail" (message-mail "%a" "%s"))
1287 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1289 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1290 "Non-nil means, ask for confirmation before executing shell links.
1291 Shell links can be dangerous: just think about a link
1293 [[shell:rm -rf ~/*][Google Search]]
1295 This link would show up in your Org-mode document as \"Google Search\",
1296 but really it would remove your entire home directory.
1297 Therefore we advise against setting this variable to nil.
1298 Just change it to `y-or-n-p' of you want to confirm with a
1299 single keystroke rather than having to type \"yes\"."
1300 :group 'org-link-follow
1301 :type '(choice
1302 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1303 (const :tag "with y-or-n (faster)" y-or-n-p)
1304 (const :tag "no confirmation (dangerous)" nil)))
1306 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1307 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1308 Elisp links can be dangerous: just think about a link
1310 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1312 This link would show up in your Org-mode document as \"Google Search\",
1313 but really it would remove your entire home directory.
1314 Therefore we advise against setting this variable to nil.
1315 Just change it to `y-or-n-p' of you want to confirm with a
1316 single keystroke rather than having to type \"yes\"."
1317 :group 'org-link-follow
1318 :type '(choice
1319 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1320 (const :tag "with y-or-n (faster)" y-or-n-p)
1321 (const :tag "no confirmation (dangerous)" nil)))
1323 (defconst org-file-apps-defaults-gnu
1324 '((remote . emacs)
1325 (t . mailcap))
1326 "Default file applications on a UNIX or GNU/Linux system.
1327 See `org-file-apps'.")
1329 (defconst org-file-apps-defaults-macosx
1330 '((remote . emacs)
1331 (t . "open %s")
1332 ("ps" . "gv %s")
1333 ("ps.gz" . "gv %s")
1334 ("eps" . "gv %s")
1335 ("eps.gz" . "gv %s")
1336 ("dvi" . "xdvi %s")
1337 ("fig" . "xfig %s"))
1338 "Default file applications on a MacOS X system.
1339 The system \"open\" is known as a default, but we use X11 applications
1340 for some files for which the OS does not have a good default.
1341 See `org-file-apps'.")
1343 (defconst org-file-apps-defaults-windowsnt
1344 (list
1345 '(remote . emacs)
1346 (cons t
1347 (list (if (featurep 'xemacs)
1348 'mswindows-shell-execute
1349 'w32-shell-execute)
1350 "open" 'file)))
1351 "Default file applications on a Windows NT system.
1352 The system \"open\" is used for most files.
1353 See `org-file-apps'.")
1355 (defcustom org-file-apps
1357 ("txt" . emacs)
1358 ("tex" . emacs)
1359 ("ltx" . emacs)
1360 ("org" . emacs)
1361 ("el" . emacs)
1362 ("bib" . emacs)
1364 "External applications for opening `file:path' items in a document.
1365 Org-mode uses system defaults for different file types, but
1366 you can use this variable to set the application for a given file
1367 extension. The entries in this list are cons cells where the car identifies
1368 files and the cdr the corresponding command. Possible values for the
1369 file identifier are
1370 \"ext\" A string identifying an extension
1371 `directory' Matches a directory
1372 `remote' Matches a remote file, accessible through tramp or efs.
1373 Remote files most likely should be visited through Emacs
1374 because external applications cannot handle such paths.
1375 t Default for all remaining files
1377 Possible values for the command are:
1378 `emacs' The file will be visited by the current Emacs process.
1379 `default' Use the default application for this file type.
1380 string A command to be executed by a shell; %s will be replaced
1381 by the path to the file.
1382 sexp A Lisp form which will be evaluated. The file path will
1383 be available in the Lisp variable `file'.
1384 For more examples, see the system specific constants
1385 `org-file-apps-defaults-macosx'
1386 `org-file-apps-defaults-windowsnt'
1387 `org-file-apps-defaults-gnu'."
1388 :group 'org-link-follow
1389 :type '(repeat
1390 (cons (choice :value ""
1391 (string :tag "Extension")
1392 (const :tag "Default for unrecognized files" t)
1393 (const :tag "Remote file" remote)
1394 (const :tag "Links to a directory" directory))
1395 (choice :value ""
1396 (const :tag "Visit with Emacs" emacs)
1397 (const :tag "Use system default" default)
1398 (string :tag "Command")
1399 (sexp :tag "Lisp form")))))
1401 (defcustom org-mhe-search-all-folders nil
1402 "Non-nil means, that the search for the mh-message will be extended to
1403 all folders if the message cannot be found in the folder given in the link.
1404 Searching all folders is very efficient with one of the search engines
1405 supported by MH-E, but will be slow with pick."
1406 :group 'org-link-follow
1407 :type 'boolean)
1409 (defgroup org-remember nil
1410 "Options concerning interaction with remember.el."
1411 :tag "Org Remember"
1412 :group 'org)
1414 (defcustom org-directory "~/org"
1415 "Directory with org files.
1416 This directory will be used as default to prompt for org files.
1417 Used by the hooks for remember.el."
1418 :group 'org-remember
1419 :type 'directory)
1421 (defcustom org-default-notes-file "~/.notes"
1422 "Default target for storing notes.
1423 Used by the hooks for remember.el. This can be a string, or nil to mean
1424 the value of `remember-data-file'.
1425 You can set this on a per-template basis with the variable
1426 `org-remember-templates'."
1427 :group 'org-remember
1428 :type '(choice
1429 (const :tag "Default from remember-data-file" nil)
1430 file))
1432 (defcustom org-remember-store-without-prompt t
1433 "Non-nil means, `C-c C-c' stores remember note without further promts.
1434 In this case, you need `C-u C-c C-c' to get the prompts for
1435 note file and headline.
1436 When this variable is nil, `C-c C-c' give you the prompts, and
1437 `C-u C-c C-c' trigger the fasttrack."
1438 :group 'org-remember
1439 :type 'boolean)
1441 (defcustom org-remember-interactive-interface 'refile
1442 "The interface to be used for interactive filing of remember notes.
1443 This is only used when the interactive mode for selecting a filing
1444 location is used (see the variable `org-remember-store-without-prompt').
1445 Allowed vaues are:
1446 outline The interface shows an outline of the relevant file
1447 and the correct heading is found by moving through
1448 the outline or by searching with incremental search.
1449 outline-path-completion Headlines in the current buffer are offered via
1450 completion.
1451 refile Use the refile interface, and offer headlines,
1452 possibly from different buffers."
1453 :group 'org-remember
1454 :type '(choice
1455 (const :tag "Refile" refile)
1456 (const :tag "Outline" outline)
1457 (const :tag "Outline-path-completion" outline-path-completion)))
1459 (defcustom org-goto-interface 'outline
1460 "The default interface to be used for `org-goto'.
1461 Allowed vaues are:
1462 outline The interface shows an outline of the relevant file
1463 and the correct heading is found by moving through
1464 the outline or by searching with incremental search.
1465 outline-path-completion Headlines in the current buffer are offered via
1466 completion."
1467 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1468 :type '(choice
1469 (const :tag "Outline" outline)
1470 (const :tag "Outline-path-completion" outline-path-completion)))
1472 (defcustom org-remember-default-headline ""
1473 "The headline that should be the default location in the notes file.
1474 When filing remember notes, the cursor will start at that position.
1475 You can set this on a per-template basis with the variable
1476 `org-remember-templates'."
1477 :group 'org-remember
1478 :type 'string)
1480 (defcustom org-remember-templates nil
1481 "Templates for the creation of remember buffers.
1482 When nil, just let remember make the buffer.
1483 When not nil, this is a list of 5-element lists. In each entry, the first
1484 element is the name of the template, which should be a single short word.
1485 The second element is a character, a unique key to select this template.
1486 The third element is the template. The fourth element is optional and can
1487 specify a destination file for remember items created with this template.
1488 The default file is given by `org-default-notes-file'. An optional fifth
1489 element can specify the headline in that file that should be offered
1490 first when the user is asked to file the entry. The default headline is
1491 given in the variable `org-remember-default-headline'.
1493 The template specifies the structure of the remember buffer. It should have
1494 a first line starting with a star, to act as the org-mode headline.
1495 Furthermore, the following %-escapes will be replaced with content:
1497 %^{prompt} Prompt the user for a string and replace this sequence with it.
1498 A default value and a completion table ca be specified like this:
1499 %^{prompt|default|completion2|completion3|...}
1500 %t time stamp, date only
1501 %T time stamp with date and time
1502 %u, %U like the above, but inactive time stamps
1503 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1504 You may define a prompt like %^{Please specify birthday}t
1505 %n user name (taken from `user-full-name')
1506 %a annotation, normally the link created with org-store-link
1507 %i initial content, the region active. If %i is indented,
1508 the entire inserted text will be indented as well.
1509 %c content of the clipboard, or current kill ring head
1510 %^g prompt for tags, with completion on tags in target file
1511 %^G prompt for tags, with completion all tags in all agenda files
1512 %:keyword specific information for certain link types, see below
1513 %[pathname] insert the contents of the file given by `pathname'
1514 %(sexp) evaluate elisp `(sexp)' and replace with the result
1515 %! Store this note immediately after filling the template
1517 %? After completing the template, position cursor here.
1519 Apart from these general escapes, you can access information specific to the
1520 link type that is created. For example, calling `remember' in emails or gnus
1521 will record the author and the subject of the message, which you can access
1522 with %:author and %:subject, respectively. Here is a complete list of what
1523 is recorded for each link type.
1525 Link type | Available information
1526 -------------------+------------------------------------------------------
1527 bbdb | %:type %:name %:company
1528 vm, wl, mh, rmail | %:type %:subject %:message-id
1529 | %:from %:fromname %:fromaddress
1530 | %:to %:toname %:toaddress
1531 | %:fromto (either \"to NAME\" or \"from NAME\")
1532 gnus | %:group, for messages also all email fields
1533 w3, w3m | %:type %:url
1534 info | %:type %:file %:node
1535 calendar | %:type %:date"
1536 :group 'org-remember
1537 :get (lambda (var) ; Make sure all entries have 5 elements
1538 (mapcar (lambda (x)
1539 (if (not (stringp (car x))) (setq x (cons "" x)))
1540 (cond ((= (length x) 4) (append x '("")))
1541 ((= (length x) 3) (append x '("" "")))
1542 (t x)))
1543 (default-value var)))
1544 :type '(repeat
1545 :tag "enabled"
1546 (list :value ("" ?a "\n" nil nil)
1547 (string :tag "Name")
1548 (character :tag "Selection Key")
1549 (string :tag "Template")
1550 (choice
1551 (file :tag "Destination file")
1552 (const :tag "Prompt for file" nil))
1553 (choice
1554 (string :tag "Destination headline")
1555 (const :tag "Selection interface for heading")))))
1557 (defcustom org-reverse-note-order nil
1558 "Non-nil means, store new notes at the beginning of a file or entry.
1559 When nil, new notes will be filed to the end of a file or entry.
1560 This can also be a list with cons cells of regular expressions that
1561 are matched against file names, and values."
1562 :group 'org-remember
1563 :type '(choice
1564 (const :tag "Reverse always" t)
1565 (const :tag "Reverse never" nil)
1566 (repeat :tag "By file name regexp"
1567 (cons regexp boolean))))
1569 (defcustom org-refile-targets nil
1570 "Targets for refiling entries with \\[org-refile].
1571 This is list of cons cells. Each cell contains:
1572 - a specification of the files to be considered, either a list of files,
1573 or a symbol whose function or value fields will be used to retrieve
1574 a file name or a list of file names. Nil means, refile to a different
1575 heading in the current buffer.
1576 - A specification of how to find candidate refile targets. This may be
1577 any of
1578 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1579 This tag has to be present in all target headlines, inheritance will
1580 not be considered.
1581 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1582 todo keyword.
1583 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1584 headlines that are refiling targets.
1585 - a cons cell (:level . N). Any headline of level N is considered a target.
1586 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1587 ;; FIXME: what if there are a var and func with same name???
1588 :group 'org-remember
1589 :type '(repeat
1590 (cons
1591 (choice :value org-agenda-files
1592 (const :tag "All agenda files" org-agenda-files)
1593 (const :tag "Current buffer" nil)
1594 (function) (variable) (file))
1595 (choice :tag "Identify target headline by"
1596 (cons :tag "Specific tag" (const :tag) (string))
1597 (cons :tag "TODO keyword" (const :todo) (string))
1598 (cons :tag "Regular expression" (const :regexp) (regexp))
1599 (cons :tag "Level number" (const :level) (integer))
1600 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1602 (defcustom org-refile-use-outline-path nil
1603 "Non-nil means, provide refile targets as paths.
1604 So a level 3 headline will be available as level1/level2/level3.
1605 When the value is `file', also include the file name (without directory)
1606 into the path. When `full-file-path', include the full file path."
1607 :group 'org-remember
1608 :type '(choice
1609 (const :tag "Not" nil)
1610 (const :tag "Yes" t)
1611 (const :tag "Start with file name" file)
1612 (const :tag "Start with full file path" full-file-path)))
1614 (defgroup org-todo nil
1615 "Options concerning TODO items in Org-mode."
1616 :tag "Org TODO"
1617 :group 'org)
1619 (defgroup org-progress nil
1620 "Options concerning Progress logging in Org-mode."
1621 :tag "Org Progress"
1622 :group 'org-time)
1624 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1625 "List of TODO entry keyword sequences and their interpretation.
1626 \\<org-mode-map>This is a list of sequences.
1628 Each sequence starts with a symbol, either `sequence' or `type',
1629 indicating if the keywords should be interpreted as a sequence of
1630 action steps, or as different types of TODO items. The first
1631 keywords are states requiring action - these states will select a headline
1632 for inclusion into the global TODO list Org-mode produces. If one of
1633 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1634 signify that no further action is necessary. If \"|\" is not found,
1635 the last keyword is treated as the only DONE state of the sequence.
1637 The command \\[org-todo] cycles an entry through these states, and one
1638 additional state where no keyword is present. For details about this
1639 cycling, see the manual.
1641 TODO keywords and interpretation can also be set on a per-file basis with
1642 the special #+SEQ_TODO and #+TYP_TODO lines.
1644 Each keyword can optionally specify a character for fast state selection
1645 \(in combination with the variable `org-use-fast-todo-selection')
1646 and specifiers for state change logging, using the same syntax
1647 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1648 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1649 indicates to record a time stamp each time this state is selected.
1650 \"WAIT(w@)\" says that the user should in addition be prompted for a
1651 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1652 entering and when leaving this state.
1654 For backward compatibility, this variable may also be just a list
1655 of keywords - in this case the interptetation (sequence or type) will be
1656 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1657 :group 'org-todo
1658 :group 'org-keywords
1659 :type '(choice
1660 (repeat :tag "Old syntax, just keywords"
1661 (string :tag "Keyword"))
1662 (repeat :tag "New syntax"
1663 (cons
1664 (choice
1665 :tag "Interpretation"
1666 (const :tag "Sequence (cycling hits every state)" sequence)
1667 (const :tag "Type (cycling directly to DONE)" type))
1668 (repeat
1669 (string :tag "Keyword"))))))
1671 (defvar org-todo-keywords-1 nil
1672 "All TODO and DONE keywords active in a buffer.")
1673 (make-variable-buffer-local 'org-todo-keywords-1)
1674 (defvar org-todo-keywords-for-agenda nil)
1675 (defvar org-done-keywords-for-agenda nil)
1676 (defvar org-not-done-keywords nil)
1677 (make-variable-buffer-local 'org-not-done-keywords)
1678 (defvar org-done-keywords nil)
1679 (make-variable-buffer-local 'org-done-keywords)
1680 (defvar org-todo-heads nil)
1681 (make-variable-buffer-local 'org-todo-heads)
1682 (defvar org-todo-sets nil)
1683 (make-variable-buffer-local 'org-todo-sets)
1684 (defvar org-todo-log-states nil)
1685 (make-variable-buffer-local 'org-todo-log-states)
1686 (defvar org-todo-kwd-alist nil)
1687 (make-variable-buffer-local 'org-todo-kwd-alist)
1688 (defvar org-todo-key-alist nil)
1689 (make-variable-buffer-local 'org-todo-key-alist)
1690 (defvar org-todo-key-trigger nil)
1691 (make-variable-buffer-local 'org-todo-key-trigger)
1693 (defcustom org-todo-interpretation 'sequence
1694 "Controls how TODO keywords are interpreted.
1695 This variable is in principle obsolete and is only used for
1696 backward compatibility, if the interpretation of todo keywords is
1697 not given already in `org-todo-keywords'. See that variable for
1698 more information."
1699 :group 'org-todo
1700 :group 'org-keywords
1701 :type '(choice (const sequence)
1702 (const type)))
1704 (defcustom org-use-fast-todo-selection 'prefix
1705 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1706 This variable describes if and under what circumstances the cycling
1707 mechanism for TODO keywords will be replaced by a single-key, direct
1708 selection scheme.
1710 When nil, fast selection is never used.
1712 When the symbol `prefix', it will be used when `org-todo' is called with
1713 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1714 in an agenda buffer.
1716 When t, fast selection is used by default. In this case, the prefix
1717 argument forces cycling instead.
1719 In all cases, the special interface is only used if access keys have actually
1720 been assigned by the user, i.e. if keywords in the configuration are followed
1721 by a letter in parenthesis, like TODO(t)."
1722 :group 'org-todo
1723 :type '(choice
1724 (const :tag "Never" nil)
1725 (const :tag "By default" t)
1726 (const :tag "Only with C-u C-c C-t" prefix)))
1728 (defcustom org-after-todo-state-change-hook nil
1729 "Hook which is run after the state of a TODO item was changed.
1730 The new state (a string with a TODO keyword, or nil) is available in the
1731 Lisp variable `state'."
1732 :group 'org-todo
1733 :type 'hook)
1735 (defcustom org-log-done nil
1736 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1737 When equal to the list (done), also prompt for a closing note.
1738 This can also be configured on a per-file basis by adding one of
1739 the following lines anywhere in the buffer:
1741 #+STARTUP: logdone
1742 #+STARTUP: lognotedone
1743 #+STARTUP: nologdone"
1744 :group 'org-todo
1745 :group 'org-progress
1746 :type '(choice
1747 (const :tag "No logging" nil)
1748 (const :tag "Record CLOSED timestamp" time)
1749 (const :tag "Record CLOSED timestamp with closing note." note)))
1751 ;; Normalize old uses of org-log-done.
1752 (cond
1753 ((eq org-log-done t) (setq org-log-done 'time))
1754 ((and (listp org-log-done) (memq 'done org-log-done))
1755 (setq org-log-done 'note)))
1757 ;; FIXME: document
1758 (defcustom org-log-note-clock-out nil
1759 "Non-nil means, recored a note when clocking out of an item.
1760 This can also be configured on a per-file basis by adding one of
1761 the following lines anywhere in the buffer:
1763 #+STARTUP: lognoteclock-out
1764 #+STARTUP: nolognoteclock-out"
1765 :group 'org-todo
1766 :group 'org-progress
1767 :type 'boolean)
1769 (defcustom org-log-done-with-time t
1770 "Non-nil means, the CLOSED time stamp will contain date and time.
1771 When nil, only the date will be recorded."
1772 :group 'org-progress
1773 :type 'boolean)
1775 (defcustom org-log-note-headings
1776 '((done . "CLOSING NOTE %t")
1777 (state . "State %-12s %t")
1778 (clock-out . ""))
1779 "Headings for notes added when clocking out or closing TODO items.
1780 The value is an alist, with the car being a symbol indicating the note
1781 context, and the cdr is the heading to be used. The heading may also be the
1782 empty string.
1783 %t in the heading will be replaced by a time stamp.
1784 %s will be replaced by the new TODO state, in double quotes.
1785 %u will be replaced by the user name.
1786 %U will be replaced by the full user name."
1787 :group 'org-todo
1788 :group 'org-progress
1789 :type '(list :greedy t
1790 (cons (const :tag "Heading when closing an item" done) string)
1791 (cons (const :tag
1792 "Heading when changing todo state (todo sequence only)"
1793 state) string)
1794 (cons (const :tag "Heading when clocking out" clock-out) string)))
1796 (defcustom org-log-states-order-reversed t
1797 "Non-nil means, the latest state change note will be directly after heading.
1798 When nil, the notes will be orderer according to time."
1799 :group 'org-todo
1800 :group 'org-progress
1801 :type 'boolean)
1803 (defcustom org-log-repeat 'time
1804 "Non-nil means, record moving through the DONE state when triggering repeat.
1805 An auto-repeating tasks is immediately switched back to TODO when marked
1806 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1807 the TODO keyword definition, or recording a cloing note by setting
1808 `org-log-done', there will be no record of the task moving trhough DONE.
1809 This variable forces taking a note anyway. Possible values are:
1811 nil Don't force a record
1812 time Record a time stamp
1813 note Record a note
1815 This option can also be set with on a per-file-basis with
1817 #+STARTUP: logrepeat
1818 #+STARTUP: lognoterepeat
1819 #+STARTUP: nologrepeat
1821 You can have local logging settings for a subtree by setting the LOGGING
1822 property to one or more of these keywords."
1823 :group 'org-todo
1824 :group 'org-progress
1825 :type '(choice
1826 (const :tag "Don't force a record" nil)
1827 (const :tag "Force recording the DONE state" time)
1828 (const :tag "Force recording a note with the DONE state" note)))
1830 (defcustom org-clock-into-drawer 2
1831 "Should clocking info be wrapped into a drawer?
1832 When t, clocking info will always be inserted into a :CLOCK: drawer.
1833 If necessary, the drawer will be created.
1834 When nil, the drawer will not be created, but used when present.
1835 When an integer and the number of clocking entries in an item
1836 reaches or exceeds this number, a drawer will be created."
1837 :group 'org-todo
1838 :group 'org-progress
1839 :type '(choice
1840 (const :tag "Always" t)
1841 (const :tag "Only when drawer exists" nil)
1842 (integer :tag "When at least N clock entries")))
1844 (defcustom org-clock-out-when-done t
1845 "When t, the clock will be stopped when the relevant entry is marked DONE.
1846 Nil means, clock will keep running until stopped explicitly with
1847 `C-c C-x C-o', or until the clock is started in a different item."
1848 :group 'org-progress
1849 :type 'boolean)
1851 (defcustom org-clock-in-switch-to-state nil
1852 "Set task to a special todo state while clocking it.
1853 The value should be the state to which the entry should be switched."
1854 :group 'org-progress
1855 :group 'org-todo
1856 :type '(choice
1857 (const :tag "Don't force a state" nil)
1858 (string :tag "State")))
1860 (defgroup org-priorities nil
1861 "Priorities in Org-mode."
1862 :tag "Org Priorities"
1863 :group 'org-todo)
1865 (defcustom org-highest-priority ?A
1866 "The highest priority of TODO items. A character like ?A, ?B etc.
1867 Must have a smaller ASCII number than `org-lowest-priority'."
1868 :group 'org-priorities
1869 :type 'character)
1871 (defcustom org-lowest-priority ?C
1872 "The lowest priority of TODO items. A character like ?A, ?B etc.
1873 Must have a larger ASCII number than `org-highest-priority'."
1874 :group 'org-priorities
1875 :type 'character)
1877 (defcustom org-default-priority ?B
1878 "The default priority of TODO items.
1879 This is the priority an item get if no explicit priority is given."
1880 :group 'org-priorities
1881 :type 'character)
1883 (defcustom org-priority-start-cycle-with-default t
1884 "Non-nil means, start with default priority when starting to cycle.
1885 When this is nil, the first step in the cycle will be (depending on the
1886 command used) one higher or lower that the default priority."
1887 :group 'org-priorities
1888 :type 'boolean)
1890 (defgroup org-time nil
1891 "Options concerning time stamps and deadlines in Org-mode."
1892 :tag "Org Time"
1893 :group 'org)
1895 (defcustom org-insert-labeled-timestamps-at-point nil
1896 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1897 When nil, these labeled time stamps are forces into the second line of an
1898 entry, just after the headline. When scheduling from the global TODO list,
1899 the time stamp will always be forced into the second line."
1900 :group 'org-time
1901 :type 'boolean)
1903 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1904 "Formats for `format-time-string' which are used for time stamps.
1905 It is not recommended to change this constant.")
1907 (defcustom org-time-stamp-rounding-minutes 0
1908 "Number of minutes to round time stamps to upon insertion.
1909 When zero, insert the time unmodified. Useful rounding numbers
1910 should be factors of 60, so for example 5, 10, 15.
1911 When this is not zero, you can still force an exact time-stamp by using
1912 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1913 :group 'org-time
1914 :type 'integer)
1916 (defcustom org-display-custom-times nil
1917 "Non-nil means, overlay custom formats over all time stamps.
1918 The formats are defined through the variable `org-time-stamp-custom-formats'.
1919 To turn this on on a per-file basis, insert anywhere in the file:
1920 #+STARTUP: customtime"
1921 :group 'org-time
1922 :set 'set-default
1923 :type 'sexp)
1924 (make-variable-buffer-local 'org-display-custom-times)
1926 (defcustom org-time-stamp-custom-formats
1927 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1928 "Custom formats for time stamps. See `format-time-string' for the syntax.
1929 These are overlayed over the default ISO format if the variable
1930 `org-display-custom-times' is set. Time like %H:%M should be at the
1931 end of the second format."
1932 :group 'org-time
1933 :type 'sexp)
1935 (defun org-time-stamp-format (&optional long inactive)
1936 "Get the right format for a time string."
1937 (let ((f (if long (cdr org-time-stamp-formats)
1938 (car org-time-stamp-formats))))
1939 (if inactive
1940 (concat "[" (substring f 1 -1) "]")
1941 f)))
1943 (defcustom org-read-date-prefer-future t
1944 "Non-nil means, assume future for incomplete date input from user.
1945 This affects the following situations:
1946 1. The user gives a day, but no month.
1947 For example, if today is the 15th, and you enter \"3\", Org-mode will
1948 read this as the third of *next* month. However, if you enter \"17\",
1949 it will be considered as *this* month.
1950 2. The user gives a month but not a year.
1951 For example, if it is april and you enter \"feb 2\", this will be read
1952 as feb 2, *next* year. \"May 5\", however, will be this year.
1954 When this option is nil, the current month and year will always be used
1955 as defaults."
1956 :group 'org-time
1957 :type 'boolean)
1959 (defcustom org-read-date-display-live t
1960 "Non-nil means, display current interpretation of date prompt live.
1961 This display will be in an overlay, in the minibuffer."
1962 :group 'org-time
1963 :type 'boolean)
1965 (defcustom org-read-date-popup-calendar t
1966 "Non-nil means, pop up a calendar when prompting for a date.
1967 In the calendar, the date can be selected with mouse-1. However, the
1968 minibuffer will also be active, and you can simply enter the date as well.
1969 When nil, only the minibuffer will be available."
1970 :group 'org-time
1971 :type 'boolean)
1972 (if (fboundp 'defvaralias)
1973 (defvaralias 'org-popup-calendar-for-date-prompt
1974 'org-read-date-popup-calendar))
1976 (defcustom org-extend-today-until 0
1977 "The hour when your day really ends.
1978 This has influence for the following applications:
1979 - When switching the agenda to \"today\". It it is still earlier than
1980 the time given here, the day recognized as TODAY is actually yesterday.
1981 - When a date is read from the user and it is still before the time given
1982 here, the current date and time will be assumed to be yesterday, 23:59.
1984 FIXME:
1985 IMPORTANT: This is still a very experimental feature, it may disappear
1986 again or it may be extended to mean more things."
1987 :group 'org-time
1988 :type 'number)
1990 (defcustom org-edit-timestamp-down-means-later nil
1991 "Non-nil means, S-down will increase the time in a time stamp.
1992 When nil, S-up will increase."
1993 :group 'org-time
1994 :type 'boolean)
1996 (defcustom org-calendar-follow-timestamp-change t
1997 "Non-nil means, make the calendar window follow timestamp changes.
1998 When a timestamp is modified and the calendar window is visible, it will be
1999 moved to the new date."
2000 :group 'org-time
2001 :type 'boolean)
2003 (defcustom org-clock-heading-function nil
2004 "When non-nil, should be a function to create `org-clock-heading'.
2005 This is the string shown in the mode line when a clock is running.
2006 The function is called with point at the beginning of the headline."
2007 :group 'org-time ; FIXME: Should we have a separate group????
2008 :type 'function)
2010 (defgroup org-tags nil
2011 "Options concerning tags in Org-mode."
2012 :tag "Org Tags"
2013 :group 'org)
2015 (defcustom org-tag-alist nil
2016 "List of tags allowed in Org-mode files.
2017 When this list is nil, Org-mode will base TAG input on what is already in the
2018 buffer.
2019 The value of this variable is an alist, the car of each entry must be a
2020 keyword as a string, the cdr may be a character that is used to select
2021 that tag through the fast-tag-selection interface.
2022 See the manual for details."
2023 :group 'org-tags
2024 :type '(repeat
2025 (choice
2026 (cons (string :tag "Tag name")
2027 (character :tag "Access char"))
2028 (const :tag "Start radio group" (:startgroup))
2029 (const :tag "End radio group" (:endgroup)))))
2031 (defcustom org-use-fast-tag-selection 'auto
2032 "Non-nil means, use fast tag selection scheme.
2033 This is a special interface to select and deselect tags with single keys.
2034 When nil, fast selection is never used.
2035 When the symbol `auto', fast selection is used if and only if selection
2036 characters for tags have been configured, either through the variable
2037 `org-tag-alist' or through a #+TAGS line in the buffer.
2038 When t, fast selection is always used and selection keys are assigned
2039 automatically if necessary."
2040 :group 'org-tags
2041 :type '(choice
2042 (const :tag "Always" t)
2043 (const :tag "Never" nil)
2044 (const :tag "When selection characters are configured" 'auto)))
2046 (defcustom org-fast-tag-selection-single-key nil
2047 "Non-nil means, fast tag selection exits after first change.
2048 When nil, you have to press RET to exit it.
2049 During fast tag selection, you can toggle this flag with `C-c'.
2050 This variable can also have the value `expert'. In this case, the window
2051 displaying the tags menu is not even shown, until you press C-c again."
2052 :group 'org-tags
2053 :type '(choice
2054 (const :tag "No" nil)
2055 (const :tag "Yes" t)
2056 (const :tag "Expert" expert)))
2058 (defvar org-fast-tag-selection-include-todo nil
2059 "Non-nil means, fast tags selection interface will also offer TODO states.
2060 This is an undocumented feature, you should not rely on it.")
2062 (defcustom org-tags-column -80
2063 "The column to which tags should be indented in a headline.
2064 If this number is positive, it specifies the column. If it is negative,
2065 it means that the tags should be flushright to that column. For example,
2066 -80 works well for a normal 80 character screen."
2067 :group 'org-tags
2068 :type 'integer)
2070 (defcustom org-auto-align-tags t
2071 "Non-nil means, realign tags after pro/demotion of TODO state change.
2072 These operations change the length of a headline and therefore shift
2073 the tags around. With this options turned on, after each such operation
2074 the tags are again aligned to `org-tags-column'."
2075 :group 'org-tags
2076 :type 'boolean)
2078 (defcustom org-use-tag-inheritance t
2079 "Non-nil means, tags in levels apply also for sublevels.
2080 When nil, only the tags directly given in a specific line apply there.
2081 If you turn off this option, you very likely want to turn on the
2082 companion option `org-tags-match-list-sublevels'."
2083 :group 'org-tags
2084 :type 'boolean)
2086 (defcustom org-tags-match-list-sublevels nil
2087 "Non-nil means list also sublevels of headlines matching tag search.
2088 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2089 the sublevels of a headline matching a tag search often also match
2090 the same search. Listing all of them can create very long lists.
2091 Setting this variable to nil causes subtrees of a match to be skipped.
2092 This option is off by default, because inheritance in on. If you turn
2093 inheritance off, you very likely want to turn this option on.
2095 As a special case, if the tag search is restricted to TODO items, the
2096 value of this variable is ignored and sublevels are always checked, to
2097 make sure all corresponding TODO items find their way into the list."
2098 :group 'org-tags
2099 :type 'boolean)
2101 (defvar org-tags-history nil
2102 "History of minibuffer reads for tags.")
2103 (defvar org-last-tags-completion-table nil
2104 "The last used completion table for tags.")
2105 (defvar org-after-tags-change-hook nil
2106 "Hook that is run after the tags in a line have changed.")
2108 (defgroup org-properties nil
2109 "Options concerning properties in Org-mode."
2110 :tag "Org Properties"
2111 :group 'org)
2113 (defcustom org-property-format "%-10s %s"
2114 "How property key/value pairs should be formatted by `indent-line'.
2115 When `indent-line' hits a property definition, it will format the line
2116 according to this format, mainly to make sure that the values are
2117 lined-up with respect to each other."
2118 :group 'org-properties
2119 :type 'string)
2121 (defcustom org-use-property-inheritance nil
2122 "Non-nil means, properties apply also for sublevels.
2123 This setting is only relevant during property searches, not when querying
2124 an entry with `org-entry-get'. To retrieve a property with inheritance,
2125 you need to call `org-entry-get' with the inheritance flag.
2126 Turning this on can cause significant overhead when doing a search, so
2127 this is turned off by default.
2128 When nil, only the properties directly given in the current entry count.
2129 The value may also be a list of properties that shouldhave inheritance.
2131 However, note that some special properties use inheritance under special
2132 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2133 and the properties ending in \"_ALL\" when they are used as descriptor
2134 for valid values of a property."
2135 :group 'org-properties
2136 :type '(choice
2137 (const :tag "Not" nil)
2138 (const :tag "Always" nil)
2139 (repeat :tag "Specific properties" (string :tag "Property"))))
2141 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2142 "The default column format, if no other format has been defined.
2143 This variable can be set on the per-file basis by inserting a line
2145 #+COLUMNS: %25ITEM ....."
2146 :group 'org-properties
2147 :type 'string)
2149 (defcustom org-global-properties nil
2150 "List of property/value pairs that can be inherited by any entry.
2151 You can set buffer-local values for this by adding lines like
2153 #+PROPERTY: NAME VALUE"
2154 :group 'org-properties
2155 :type '(repeat
2156 (cons (string :tag "Property")
2157 (string :tag "Value"))))
2159 (defvar org-local-properties nil
2160 "List of property/value pairs that can be inherited by any entry.
2161 Valid for the current buffer.
2162 This variable is populated from #+PROPERTY lines.")
2164 (defgroup org-agenda nil
2165 "Options concerning agenda views in Org-mode."
2166 :tag "Org Agenda"
2167 :group 'org)
2169 (defvar org-category nil
2170 "Variable used by org files to set a category for agenda display.
2171 Such files should use a file variable to set it, for example
2173 # -*- mode: org; org-category: \"ELisp\"
2175 or contain a special line
2177 #+CATEGORY: ELisp
2179 If the file does not specify a category, then file's base name
2180 is used instead.")
2181 (make-variable-buffer-local 'org-category)
2183 (defcustom org-agenda-files nil
2184 "The files to be used for agenda display.
2185 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2186 \\[org-remove-file]. You can also use customize to edit the list.
2188 If an entry is a directory, all files in that directory that are matched by
2189 `org-agenda-file-regexp' will be part of the file list.
2191 If the value of the variable is not a list but a single file name, then
2192 the list of agenda files is actually stored and maintained in that file, one
2193 agenda file per line."
2194 :group 'org-agenda
2195 :type '(choice
2196 (repeat :tag "List of files and directories" file)
2197 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2199 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2200 "Regular expression to match files for `org-agenda-files'.
2201 If any element in the list in that variable contains a directory instead
2202 of a normal file, all files in that directory that are matched by this
2203 regular expression will be included."
2204 :group 'org-agenda
2205 :type 'regexp)
2207 (defcustom org-agenda-skip-unavailable-files nil
2208 "t means to just skip non-reachable files in `org-agenda-files'.
2209 Nil means to remove them, after a query, from the list."
2210 :group 'org-agenda
2211 :type 'boolean)
2213 (defcustom org-agenda-multi-occur-extra-files nil
2214 "List of extra files to be searched by `org-occur-in-agenda-files'.
2215 The files in `org-agenda-files' are always searched."
2216 :group 'org-agenda
2217 :type '(repeat file))
2219 (defcustom org-agenda-confirm-kill 1
2220 "When set, remote killing from the agenda buffer needs confirmation.
2221 When t, a confirmation is always needed. When a number N, confirmation is
2222 only needed when the text to be killed contains more than N non-white lines."
2223 :group 'org-agenda
2224 :type '(choice
2225 (const :tag "Never" nil)
2226 (const :tag "Always" t)
2227 (number :tag "When more than N lines")))
2229 (defcustom org-calendar-to-agenda-key [?c]
2230 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2231 The command `org-calendar-goto-agenda' will be bound to this key. The
2232 default is the character `c' because then `c' can be used to switch back and
2233 forth between agenda and calendar."
2234 :group 'org-agenda
2235 :type 'sexp)
2237 (defcustom org-agenda-compact-blocks nil
2238 "Non-nil means, make the block agenda more compact.
2239 This is done by leaving out unnecessary lines."
2240 :group 'org-agenda
2241 :type nil)
2243 (defgroup org-agenda-export nil
2244 "Options concerning exporting agenda views in Org-mode."
2245 :tag "Org Agenda Export"
2246 :group 'org-agenda)
2248 (defcustom org-agenda-with-colors t
2249 "Non-nil means, use colors in agenda views."
2250 :group 'org-agenda-export
2251 :type 'boolean)
2253 (defcustom org-agenda-exporter-settings nil
2254 "Alist of variable/value pairs that should be active during agenda export.
2255 This is a good place to set uptions for ps-print and for htmlize."
2256 :group 'org-agenda-export
2257 :type '(repeat
2258 (list
2259 (variable)
2260 (sexp :tag "Value"))))
2262 (defcustom org-agenda-export-html-style ""
2263 "The style specification for exported HTML Agenda files.
2264 If this variable contains a string, it will replace the default <style>
2265 section as produced by `htmlize'.
2266 Since there are different ways of setting style information, this variable
2267 needs to contain the full HTML structure to provide a style, including the
2268 surrounding HTML tags. The style specifications should include definitions
2269 the fonts used by the agenda, here is an example:
2271 <style type=\"text/css\">
2272 p { font-weight: normal; color: gray; }
2273 .org-agenda-structure {
2274 font-size: 110%;
2275 color: #003399;
2276 font-weight: 600;
2278 .org-todo {
2279 color: #cc6666;Week-agenda:
2280 font-weight: bold;
2282 .org-done {
2283 color: #339933;
2285 .title { text-align: center; }
2286 .todo, .deadline { color: red; }
2287 .done { color: green; }
2288 </style>
2290 or, if you want to keep the style in a file,
2292 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2294 As the value of this option simply gets inserted into the HTML <head> header,
2295 you can \"misuse\" it to also add other text to the header. However,
2296 <style>...</style> is required, if not present the variable will be ignored."
2297 :group 'org-agenda-export
2298 :group 'org-export-html
2299 :type 'string)
2301 (defgroup org-agenda-custom-commands nil
2302 "Options concerning agenda views in Org-mode."
2303 :tag "Org Agenda Custom Commands"
2304 :group 'org-agenda)
2306 (defcustom org-agenda-custom-commands nil
2307 "Custom commands for the agenda.
2308 These commands will be offered on the splash screen displayed by the
2309 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2311 (key desc type match options files)
2313 key The key (one or more characters as a string) to be associated
2314 with the command.
2315 desc A description of the commend, when omitted or nil, a default
2316 description is built using MATCH.
2317 type The command type, any of the following symbols:
2318 todo Entries with a specific TODO keyword, in all agenda files.
2319 tags Tags match in all agenda files.
2320 tags-todo Tags match in all agenda files, TODO entries only.
2321 todo-tree Sparse tree of specific TODO keyword in *current* file.
2322 tags-tree Sparse tree with all tags matches in *current* file.
2323 occur-tree Occur sparse tree for *current* file.
2324 ... A user-defined function.
2325 match What to search for:
2326 - a single keyword for TODO keyword searches
2327 - a tags match expression for tags searches
2328 - a regular expression for occur searches
2329 options A list of option settings, similar to that in a let form, so like
2330 this: ((opt1 val1) (opt2 val2) ...)
2331 files A list of files file to write the produced agenda buffer to
2332 with the command `org-store-agenda-views'.
2333 If a file name ends in \".html\", an HTML version of the buffer
2334 is written out. If it ends in \".ps\", a postscript version is
2335 produced. Otherwide, only the plain text is written to the file.
2337 You can also define a set of commands, to create a composite agenda buffer.
2338 In this case, an entry looks like this:
2340 (key desc (cmd1 cmd2 ...) general-options file)
2342 where
2344 desc A description string to be displayed in the dispatcher menu.
2345 cmd An agenda command, similar to the above. However, tree commands
2346 are no allowed, but instead you can get agenda and global todo list.
2347 So valid commands for a set are:
2348 (agenda)
2349 (alltodo)
2350 (stuck)
2351 (todo \"match\" options files)
2352 (tags \"match\" options files)
2353 (tags-todo \"match\" options files)
2355 Each command can carry a list of options, and another set of options can be
2356 given for the whole set of commands. Individual command options take
2357 precedence over the general options.
2359 When using several characters as key to a command, the first characters
2360 are prefix commands. For the dispatcher to display useful information, you
2361 should provide a description for the prefix, like
2363 (setq org-agenda-custom-commands
2364 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2365 (\"hl\" tags \"+HOME+Lisa\")
2366 (\"hp\" tags \"+HOME+Peter\")
2367 (\"hk\" tags \"+HOME+Kim\")))"
2368 :group 'org-agenda-custom-commands
2369 :type '(repeat
2370 (choice :value ("a" "" tags "" nil)
2371 (list :tag "Single command"
2372 (string :tag "Access Key(s) ")
2373 (option (string :tag "Description"))
2374 (choice
2375 (const :tag "Agenda" agenda)
2376 (const :tag "TODO list" alltodo)
2377 (const :tag "Stuck projects" stuck)
2378 (const :tag "Tags search (all agenda files)" tags)
2379 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2380 (const :tag "TODO keyword search (all agenda files)" todo)
2381 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2382 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2383 (const :tag "Occur tree (current buffer)" occur-tree)
2384 (sexp :tag "Other, user-defined function"))
2385 (string :tag "Match")
2386 (repeat :tag "Local options"
2387 (list (variable :tag "Option") (sexp :tag "Value")))
2388 (option (repeat :tag "Export" (file :tag "Export to"))))
2389 (list :tag "Command series, all agenda files"
2390 (string :tag "Access Key(s)")
2391 (string :tag "Description ")
2392 (repeat
2393 (choice
2394 (const :tag "Agenda" (agenda))
2395 (const :tag "TODO list" (alltodo))
2396 (const :tag "Stuck projects" (stuck))
2397 (list :tag "Tags search"
2398 (const :format "" tags)
2399 (string :tag "Match")
2400 (repeat :tag "Local options"
2401 (list (variable :tag "Option")
2402 (sexp :tag "Value"))))
2404 (list :tag "Tags search, TODO entries only"
2405 (const :format "" tags-todo)
2406 (string :tag "Match")
2407 (repeat :tag "Local options"
2408 (list (variable :tag "Option")
2409 (sexp :tag "Value"))))
2411 (list :tag "TODO keyword search"
2412 (const :format "" todo)
2413 (string :tag "Match")
2414 (repeat :tag "Local options"
2415 (list (variable :tag "Option")
2416 (sexp :tag "Value"))))
2418 (list :tag "Other, user-defined function"
2419 (symbol :tag "function")
2420 (string :tag "Match")
2421 (repeat :tag "Local options"
2422 (list (variable :tag "Option")
2423 (sexp :tag "Value"))))))
2425 (repeat :tag "General options"
2426 (list (variable :tag "Option")
2427 (sexp :tag "Value")))
2428 (option (repeat :tag "Export" (file :tag "Export to"))))
2429 (cons :tag "Prefix key documentation"
2430 (string :tag "Access Key(s)")
2431 (string :tag "Description ")))))
2433 (defcustom org-stuck-projects
2434 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2435 "How to identify stuck projects.
2436 This is a list of four items:
2437 1. A tags/todo matcher string that is used to identify a project.
2438 The entire tree below a headline matched by this is considered one project.
2439 2. A list of TODO keywords identifying non-stuck projects.
2440 If the project subtree contains any headline with one of these todo
2441 keywords, the project is considered to be not stuck. If you specify
2442 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2443 3. A list of tags identifying non-stuck projects.
2444 If the project subtree contains any headline with one of these tags,
2445 the project is considered to be not stuck. If you specify \"*\" as
2446 a tag, any tag will mark the project unstuck.
2447 4. An arbitrary regular expression matching non-stuck projects.
2449 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2450 or `C-c a #' to produce the list."
2451 :group 'org-agenda-custom-commands
2452 :type '(list
2453 (string :tag "Tags/TODO match to identify a project")
2454 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2455 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2456 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2459 (defgroup org-agenda-skip nil
2460 "Options concerning skipping parts of agenda files."
2461 :tag "Org Agenda Skip"
2462 :group 'org-agenda)
2464 (defcustom org-agenda-todo-list-sublevels t
2465 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2466 When nil, the sublevels of a TODO entry are not checked, resulting in
2467 potentially much shorter TODO lists."
2468 :group 'org-agenda-skip
2469 :group 'org-todo
2470 :type 'boolean)
2472 (defcustom org-agenda-todo-ignore-with-date nil
2473 "Non-nil means, don't show entries with a date in the global todo list.
2474 You can use this if you prefer to mark mere appointments with a TODO keyword,
2475 but don't want them to show up in the TODO list.
2476 When this is set, it also covers deadlines and scheduled items, the settings
2477 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2478 will be ignored."
2479 :group 'org-agenda-skip
2480 :group 'org-todo
2481 :type 'boolean)
2483 (defcustom org-agenda-todo-ignore-scheduled nil
2484 "Non-nil means, don't show scheduled entries in the global todo list.
2485 The idea behind this is that by scheduling it, you have already taken care
2486 of this item.
2487 See also `org-agenda-todo-ignore-with-date'."
2488 :group 'org-agenda-skip
2489 :group 'org-todo
2490 :type 'boolean)
2492 (defcustom org-agenda-todo-ignore-deadlines nil
2493 "Non-nil means, don't show near deadline entries in the global todo list.
2494 Near means closer than `org-deadline-warning-days' days.
2495 The idea behind this is that such items will appear in the agenda anyway.
2496 See also `org-agenda-todo-ignore-with-date'."
2497 :group 'org-agenda-skip
2498 :group 'org-todo
2499 :type 'boolean)
2501 (defcustom org-agenda-skip-scheduled-if-done nil
2502 "Non-nil means don't show scheduled items in agenda when they are done.
2503 This is relevant for the daily/weekly agenda, not for the TODO list. And
2504 it applies only to the actual date of the scheduling. Warnings about
2505 an item with a past scheduling dates are always turned off when the item
2506 is DONE."
2507 :group 'org-agenda-skip
2508 :type 'boolean)
2510 (defcustom org-agenda-skip-deadline-if-done nil
2511 "Non-nil means don't show deadines when the corresponding item is done.
2512 When nil, the deadline is still shown and should give you a happy feeling.
2513 This is relevant for the daily/weekly agenda. And it applied only to the
2514 actualy date of the deadline. Warnings about approching and past-due
2515 deadlines are always turned off when the item is DONE."
2516 :group 'org-agenda-skip
2517 :type 'boolean)
2519 (defcustom org-agenda-skip-timestamp-if-done nil
2520 "Non-nil means don't select item by timestamp or -range if it is DONE."
2521 :group 'org-agenda-skip
2522 :type 'boolean)
2524 (defcustom org-timeline-show-empty-dates 3
2525 "Non-nil means, `org-timeline' also shows dates without an entry.
2526 When nil, only the days which actually have entries are shown.
2527 When t, all days between the first and the last date are shown.
2528 When an integer, show also empty dates, but if there is a gap of more than
2529 N days, just insert a special line indicating the size of the gap."
2530 :group 'org-agenda-skip
2531 :type '(choice
2532 (const :tag "None" nil)
2533 (const :tag "All" t)
2534 (number :tag "at most")))
2537 (defgroup org-agenda-startup nil
2538 "Options concerning initial settings in the Agenda in Org Mode."
2539 :tag "Org Agenda Startup"
2540 :group 'org-agenda)
2542 (defcustom org-finalize-agenda-hook nil
2543 "Hook run just before displaying an agenda buffer."
2544 :group 'org-agenda-startup
2545 :type 'hook)
2547 (defcustom org-agenda-mouse-1-follows-link nil
2548 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2549 A longer mouse click will still set point. Does not wortk on XEmacs.
2550 Needs to be set before org.el is loaded."
2551 :group 'org-agenda-startup
2552 :type 'boolean)
2554 (defcustom org-agenda-start-with-follow-mode nil
2555 "The initial value of follow-mode in a newly created agenda window."
2556 :group 'org-agenda-startup
2557 :type 'boolean)
2559 (defgroup org-agenda-windows nil
2560 "Options concerning the windows used by the Agenda in Org Mode."
2561 :tag "Org Agenda Windows"
2562 :group 'org-agenda)
2564 (defcustom org-agenda-window-setup 'reorganize-frame
2565 "How the agenda buffer should be displayed.
2566 Possible values for this option are:
2568 current-window Show agenda in the current window, keeping all other windows.
2569 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2570 other-window Use `switch-to-buffer-other-window' to display agenda.
2571 reorganize-frame Show only two windows on the current frame, the current
2572 window and the agenda.
2573 See also the variable `org-agenda-restore-windows-after-quit'."
2574 :group 'org-agenda-windows
2575 :type '(choice
2576 (const current-window)
2577 (const other-frame)
2578 (const other-window)
2579 (const reorganize-frame)))
2581 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2582 "The min and max height of the agenda window as a fraction of frame height.
2583 The value of the variable is a cons cell with two numbers between 0 and 1.
2584 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2585 :group 'org-agenda-windows
2586 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2588 (defcustom org-agenda-restore-windows-after-quit nil
2589 "Non-nil means, restore window configuration open exiting agenda.
2590 Before the window configuration is changed for displaying the agenda,
2591 the current status is recorded. When the agenda is exited with
2592 `q' or `x' and this option is set, the old state is restored. If
2593 `org-agenda-window-setup' is `other-frame', the value of this
2594 option will be ignored.."
2595 :group 'org-agenda-windows
2596 :type 'boolean)
2598 (defcustom org-indirect-buffer-display 'other-window
2599 "How should indirect tree buffers be displayed?
2600 This applies to indirect buffers created with the commands
2601 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2602 Valid values are:
2603 current-window Display in the current window
2604 other-window Just display in another window.
2605 dedicated-frame Create one new frame, and re-use it each time.
2606 new-frame Make a new frame each time. Note that in this case
2607 previously-made indirect buffers are kept, and you need to
2608 kill these buffers yourself."
2609 :group 'org-structure
2610 :group 'org-agenda-windows
2611 :type '(choice
2612 (const :tag "In current window" current-window)
2613 (const :tag "In current frame, other window" other-window)
2614 (const :tag "Each time a new frame" new-frame)
2615 (const :tag "One dedicated frame" dedicated-frame)))
2617 (defgroup org-agenda-daily/weekly nil
2618 "Options concerning the daily/weekly agenda."
2619 :tag "Org Agenda Daily/Weekly"
2620 :group 'org-agenda)
2622 (defcustom org-agenda-ndays 7
2623 "Number of days to include in overview display.
2624 Should be 1 or 7."
2625 :group 'org-agenda-daily/weekly
2626 :type 'number)
2628 (defcustom org-agenda-start-on-weekday 1
2629 "Non-nil means, start the overview always on the specified weekday.
2630 0 denotes Sunday, 1 denotes Monday etc.
2631 When nil, always start on the current day."
2632 :group 'org-agenda-daily/weekly
2633 :type '(choice (const :tag "Today" nil)
2634 (number :tag "Weekday No.")))
2636 (defcustom org-agenda-show-all-dates t
2637 "Non-nil means, `org-agenda' shows every day in the selected range.
2638 When nil, only the days which actually have entries are shown."
2639 :group 'org-agenda-daily/weekly
2640 :type 'boolean)
2642 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2643 "Format string for displaying dates in the agenda.
2644 Used by the daily/weekly agenda and by the timeline. This should be
2645 a format string understood by `format-time-string', or a function returning
2646 the formatted date as a string. The function must take a single argument,
2647 a calendar-style date list like (month day year)."
2648 :group 'org-agenda-daily/weekly
2649 :type '(choice
2650 (string :tag "Format string")
2651 (function :tag "Function")))
2653 (defun org-agenda-format-date-aligned (date)
2654 "Format a date string for display in the daily/weekly agenda, or timeline.
2655 This function makes sure that dates are aligned for easy reading."
2656 (format "%-9s %2d %s %4d"
2657 (calendar-day-name date)
2658 (extract-calendar-day date)
2659 (calendar-month-name (extract-calendar-month date))
2660 (extract-calendar-year date)))
2662 (defcustom org-agenda-include-diary nil
2663 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2664 :group 'org-agenda-daily/weekly
2665 :type 'boolean)
2667 (defcustom org-agenda-include-all-todo nil
2668 "Set means weekly/daily agenda will always contain all TODO entries.
2669 The TODO entries will be listed at the top of the agenda, before
2670 the entries for specific days."
2671 :group 'org-agenda-daily/weekly
2672 :type 'boolean)
2674 (defcustom org-agenda-repeating-timestamp-show-all t
2675 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2676 When nil, only one occurence is shown, either today or the
2677 nearest into the future."
2678 :group 'org-agenda-daily/weekly
2679 :type 'boolean)
2681 (defcustom org-deadline-warning-days 14
2682 "No. of days before expiration during which a deadline becomes active.
2683 This variable governs the display in sparse trees and in the agenda.
2684 When negative, it means use this number (the absolute value of it)
2685 even if a deadline has a different individual lead time specified."
2686 :group 'org-time
2687 :group 'org-agenda-daily/weekly
2688 :type 'number)
2690 (defcustom org-scheduled-past-days 10000
2691 "No. of days to continue listing scheduled items that are not marked DONE.
2692 When an item is scheduled on a date, it shows up in the agenda on this
2693 day and will be listed until it is marked done for the number of days
2694 given here."
2695 :group 'org-agenda-daily/weekly
2696 :type 'number)
2698 (defgroup org-agenda-time-grid nil
2699 "Options concerning the time grid in the Org-mode Agenda."
2700 :tag "Org Agenda Time Grid"
2701 :group 'org-agenda)
2703 (defcustom org-agenda-use-time-grid t
2704 "Non-nil means, show a time grid in the agenda schedule.
2705 A time grid is a set of lines for specific times (like every two hours between
2706 8:00 and 20:00). The items scheduled for a day at specific times are
2707 sorted in between these lines.
2708 For details about when the grid will be shown, and what it will look like, see
2709 the variable `org-agenda-time-grid'."
2710 :group 'org-agenda-time-grid
2711 :type 'boolean)
2713 (defcustom org-agenda-time-grid
2714 '((daily today require-timed)
2715 "----------------"
2716 (800 1000 1200 1400 1600 1800 2000))
2718 "The settings for time grid for agenda display.
2719 This is a list of three items. The first item is again a list. It contains
2720 symbols specifying conditions when the grid should be displayed:
2722 daily if the agenda shows a single day
2723 weekly if the agenda shows an entire week
2724 today show grid on current date, independent of daily/weekly display
2725 require-timed show grid only if at least one item has a time specification
2727 The second item is a string which will be places behing the grid time.
2729 The third item is a list of integers, indicating the times that should have
2730 a grid line."
2731 :group 'org-agenda-time-grid
2732 :type
2733 '(list
2734 (set :greedy t :tag "Grid Display Options"
2735 (const :tag "Show grid in single day agenda display" daily)
2736 (const :tag "Show grid in weekly agenda display" weekly)
2737 (const :tag "Always show grid for today" today)
2738 (const :tag "Show grid only if any timed entries are present"
2739 require-timed)
2740 (const :tag "Skip grid times already present in an entry"
2741 remove-match))
2742 (string :tag "Grid String")
2743 (repeat :tag "Grid Times" (integer :tag "Time"))))
2745 (defgroup org-agenda-sorting nil
2746 "Options concerning sorting in the Org-mode Agenda."
2747 :tag "Org Agenda Sorting"
2748 :group 'org-agenda)
2750 (defconst org-sorting-choice
2751 '(choice
2752 (const time-up) (const time-down)
2753 (const category-keep) (const category-up) (const category-down)
2754 (const tag-down) (const tag-up)
2755 (const priority-up) (const priority-down))
2756 "Sorting choices.")
2758 (defcustom org-agenda-sorting-strategy
2759 '((agenda time-up category-keep priority-down)
2760 (todo category-keep priority-down)
2761 (tags category-keep priority-down))
2762 "Sorting structure for the agenda items of a single day.
2763 This is a list of symbols which will be used in sequence to determine
2764 if an entry should be listed before another entry. The following
2765 symbols are recognized:
2767 time-up Put entries with time-of-day indications first, early first
2768 time-down Put entries with time-of-day indications first, late first
2769 category-keep Keep the default order of categories, corresponding to the
2770 sequence in `org-agenda-files'.
2771 category-up Sort alphabetically by category, A-Z.
2772 category-down Sort alphabetically by category, Z-A.
2773 tag-up Sort alphabetically by last tag, A-Z.
2774 tag-down Sort alphabetically by last tag, Z-A.
2775 priority-up Sort numerically by priority, high priority last.
2776 priority-down Sort numerically by priority, high priority first.
2778 The different possibilities will be tried in sequence, and testing stops
2779 if one comparison returns a \"not-equal\". For example, the default
2780 '(time-up category-keep priority-down)
2781 means: Pull out all entries having a specified time of day and sort them,
2782 in order to make a time schedule for the current day the first thing in the
2783 agenda listing for the day. Of the entries without a time indication, keep
2784 the grouped in categories, don't sort the categories, but keep them in
2785 the sequence given in `org-agenda-files'. Within each category sort by
2786 priority.
2788 Leaving out `category-keep' would mean that items will be sorted across
2789 categories by priority.
2791 Instead of a single list, this can also be a set of list for specific
2792 contents, with a context symbol in the car of the list, any of
2793 `agenda', `todo', `tags' for the corresponding agenda views."
2794 :group 'org-agenda-sorting
2795 :type `(choice
2796 (repeat :tag "General" ,org-sorting-choice)
2797 (list :tag "Individually"
2798 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2799 (repeat ,org-sorting-choice))
2800 (cons (const :tag "Strategy for TODO lists" todo)
2801 (repeat ,org-sorting-choice))
2802 (cons (const :tag "Strategy for Tags matches" tags)
2803 (repeat ,org-sorting-choice)))))
2805 (defcustom org-sort-agenda-notime-is-late t
2806 "Non-nil means, items without time are considered late.
2807 This is only relevant for sorting. When t, items which have no explicit
2808 time like 15:30 will be considered as 99:01, i.e. later than any items which
2809 do have a time. When nil, the default time is before 0:00. You can use this
2810 option to decide if the schedule for today should come before or after timeless
2811 agenda entries."
2812 :group 'org-agenda-sorting
2813 :type 'boolean)
2815 (defgroup org-agenda-line-format nil
2816 "Options concerning the entry prefix in the Org-mode agenda display."
2817 :tag "Org Agenda Line Format"
2818 :group 'org-agenda)
2820 (defcustom org-agenda-prefix-format
2821 '((agenda . " %-12:c%?-12t% s")
2822 (timeline . " % s")
2823 (todo . " %-12:c")
2824 (tags . " %-12:c"))
2825 "Format specifications for the prefix of items in the agenda views.
2826 An alist with four entries, for the different agenda types. The keys to the
2827 sublists are `agenda', `timeline', `todo', and `tags'. The values
2828 are format strings.
2829 This format works similar to a printf format, with the following meaning:
2831 %c the category of the item, \"Diary\" for entries from the diary, or
2832 as given by the CATEGORY keyword or derived from the file name.
2833 %T the *last* tag of the item. Last because inherited tags come
2834 first in the list.
2835 %t the time-of-day specification if one applies to the entry, in the
2836 format HH:MM
2837 %s Scheduling/Deadline information, a short string
2839 All specifiers work basically like the standard `%s' of printf, but may
2840 contain two additional characters: A question mark just after the `%' and
2841 a whitespace/punctuation character just before the final letter.
2843 If the first character after `%' is a question mark, the entire field
2844 will only be included if the corresponding value applies to the
2845 current entry. This is useful for fields which should have fixed
2846 width when present, but zero width when absent. For example,
2847 \"%?-12t\" will result in a 12 character time field if a time of the
2848 day is specified, but will completely disappear in entries which do
2849 not contain a time.
2851 If there is punctuation or whitespace character just before the final
2852 format letter, this character will be appended to the field value if
2853 the value is not empty. For example, the format \"%-12:c\" leads to
2854 \"Diary: \" if the category is \"Diary\". If the category were be
2855 empty, no additional colon would be interted.
2857 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2858 - Indent the line with two space characters
2859 - Give the category in a 12 chars wide field, padded with whitespace on
2860 the right (because of `-'). Append a colon if there is a category
2861 (because of `:').
2862 - If there is a time-of-day, put it into a 12 chars wide field. If no
2863 time, don't put in an empty field, just skip it (because of '?').
2864 - Finally, put the scheduling information and append a whitespace.
2866 As another example, if you don't want the time-of-day of entries in
2867 the prefix, you could use:
2869 (setq org-agenda-prefix-format \" %-11:c% s\")
2871 See also the variables `org-agenda-remove-times-when-in-prefix' and
2872 `org-agenda-remove-tags'."
2873 :type '(choice
2874 (string :tag "General format")
2875 (list :greedy t :tag "View dependent"
2876 (cons (const agenda) (string :tag "Format"))
2877 (cons (const timeline) (string :tag "Format"))
2878 (cons (const todo) (string :tag "Format"))
2879 (cons (const tags) (string :tag "Format"))))
2880 :group 'org-agenda-line-format)
2882 (defvar org-prefix-format-compiled nil
2883 "The compiled version of the most recently used prefix format.
2884 See the variable `org-agenda-prefix-format'.")
2886 (defcustom org-agenda-todo-keyword-format "%-1s"
2887 "Format for the TODO keyword in agenda lines.
2888 Set this to something like \"%-12s\" if you want all TODO keywords
2889 to occupy a fixed space in the agenda display."
2890 :group 'org-agenda-line-format
2891 :type 'string)
2893 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2894 "Text preceeding scheduled items in the agenda view.
2895 This is a list with two strings. The first applies when the item is
2896 scheduled on the current day. The second applies when it has been scheduled
2897 previously, it may contain a %d to capture how many days ago the item was
2898 scheduled."
2899 :group 'org-agenda-line-format
2900 :type '(list
2901 (string :tag "Scheduled today ")
2902 (string :tag "Scheduled previously")))
2904 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2905 "Text preceeding deadline items in the agenda view.
2906 This is a list with two strings. The first applies when the item has its
2907 deadline on the current day. The second applies when it is in the past or
2908 in the future, it may contain %d to capture how many days away the deadline
2909 is (was)."
2910 :group 'org-agenda-line-format
2911 :type '(list
2912 (string :tag "Deadline today ")
2913 (string :tag "Deadline relative")))
2915 (defcustom org-agenda-remove-times-when-in-prefix t
2916 "Non-nil means, remove duplicate time specifications in agenda items.
2917 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2918 time-of-day specification in a headline or diary entry is extracted and
2919 placed into the prefix. If this option is non-nil, the original specification
2920 \(a timestamp or -range, or just a plain time(range) specification like
2921 11:30-4pm) will be removed for agenda display. This makes the agenda less
2922 cluttered.
2923 The option can be t or nil. It may also be the symbol `beg', indicating
2924 that the time should only be removed what it is located at the beginning of
2925 the headline/diary entry."
2926 :group 'org-agenda-line-format
2927 :type '(choice
2928 (const :tag "Always" t)
2929 (const :tag "Never" nil)
2930 (const :tag "When at beginning of entry" beg)))
2933 (defcustom org-agenda-default-appointment-duration nil
2934 "Default duration for appointments that only have a starting time.
2935 When nil, no duration is specified in such cases.
2936 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2937 :group 'org-agenda-line-format
2938 :type '(choice
2939 (integer :tag "Minutes")
2940 (const :tag "No default duration")))
2943 (defcustom org-agenda-remove-tags nil
2944 "Non-nil means, remove the tags from the headline copy in the agenda.
2945 When this is the symbol `prefix', only remove tags when
2946 `org-agenda-prefix-format' contains a `%T' specifier."
2947 :group 'org-agenda-line-format
2948 :type '(choice
2949 (const :tag "Always" t)
2950 (const :tag "Never" nil)
2951 (const :tag "When prefix format contains %T" prefix)))
2953 (if (fboundp 'defvaralias)
2954 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2955 'org-agenda-remove-tags))
2957 (defcustom org-agenda-tags-column -80
2958 "Shift tags in agenda items to this column.
2959 If this number is positive, it specifies the column. If it is negative,
2960 it means that the tags should be flushright to that column. For example,
2961 -80 works well for a normal 80 character screen."
2962 :group 'org-agenda-line-format
2963 :type 'integer)
2965 (if (fboundp 'defvaralias)
2966 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2968 (defcustom org-agenda-fontify-priorities t
2969 "Non-nil means, highlight low and high priorities in agenda.
2970 When t, the highest priority entries are bold, lowest priority italic.
2971 This may also be an association list of priority faces. The face may be
2972 a names face, or a list like `(:background \"Red\")'."
2973 :group 'org-agenda-line-format
2974 :type '(choice
2975 (const :tag "Never" nil)
2976 (const :tag "Defaults" t)
2977 (repeat :tag "Specify"
2978 (list (character :tag "Priority" :value ?A)
2979 (sexp :tag "face")))))
2981 (defgroup org-latex nil
2982 "Options for embedding LaTeX code into Org-mode"
2983 :tag "Org LaTeX"
2984 :group 'org)
2986 (defcustom org-format-latex-options
2987 '(:foreground default :background default :scale 1.0
2988 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2989 :matchers ("begin" "$" "$$" "\\(" "\\["))
2990 "Options for creating images from LaTeX fragments.
2991 This is a property list with the following properties:
2992 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2993 `default' means use the forground of the default face.
2994 :background the background color, or \"Transparent\".
2995 `default' means use the background of the default face.
2996 :scale a scaling factor for the size of the images
2997 :html-foreground, :html-background, :html-scale
2998 The same numbers for HTML export.
2999 :matchers a list indicating which matchers should be used to
3000 find LaTeX fragments. Valid members of this list are:
3001 \"begin\" find environments
3002 \"$\" find math expressions surrounded by $...$
3003 \"$$\" find math expressions surrounded by $$....$$
3004 \"\\(\" find math expressions surrounded by \\(...\\)
3005 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3006 :group 'org-latex
3007 :type 'plist)
3009 (defcustom org-format-latex-header "\\documentclass{article}
3010 \\usepackage{fullpage} % do not remove
3011 \\usepackage{amssymb}
3012 \\usepackage[usenames]{color}
3013 \\usepackage{amsmath}
3014 \\usepackage{latexsym}
3015 \\usepackage[mathscr]{eucal}
3016 \\pagestyle{empty} % do not remove"
3017 "The document header used for processing LaTeX fragments."
3018 :group 'org-latex
3019 :type 'string)
3021 (defgroup org-export nil
3022 "Options for exporting org-listings."
3023 :tag "Org Export"
3024 :group 'org)
3026 (defgroup org-export-general nil
3027 "General options for exporting Org-mode files."
3028 :tag "Org Export General"
3029 :group 'org-export)
3031 ;; FIXME
3032 (defvar org-export-publishing-directory nil)
3034 (defcustom org-export-with-special-strings t
3035 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3036 When this option is turned on, these strings will be exported as:
3038 Org HTML LaTeX
3039 -----+----------+--------
3040 \\- &shy; \\-
3041 -- &ndash; --
3042 --- &mdash; ---
3043 ... &hellip; \ldots
3045 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3046 :group 'org-export-translation
3047 :type 'boolean)
3049 (defcustom org-export-language-setup
3050 '(("en" "Author" "Date" "Table of Contents")
3051 ("cs" "Autor" "Datum" "Obsah")
3052 ("da" "Ophavsmand" "Dato" "Indhold")
3053 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3054 ("es" "Autor" "Fecha" "\xcdndice")
3055 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3056 ("it" "Autore" "Data" "Indice")
3057 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3058 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3059 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3060 "Terms used in export text, translated to different languages.
3061 Use the variable `org-export-default-language' to set the language,
3062 or use the +OPTION lines for a per-file setting."
3063 :group 'org-export-general
3064 :type '(repeat
3065 (list
3066 (string :tag "HTML language tag")
3067 (string :tag "Author")
3068 (string :tag "Date")
3069 (string :tag "Table of Contents"))))
3071 (defcustom org-export-default-language "en"
3072 "The default language of HTML export, as a string.
3073 This should have an association in `org-export-language-setup'."
3074 :group 'org-export-general
3075 :type 'string)
3077 (defcustom org-export-skip-text-before-1st-heading t
3078 "Non-nil means, skip all text before the first headline when exporting.
3079 When nil, that text is exported as well."
3080 :group 'org-export-general
3081 :type 'boolean)
3083 (defcustom org-export-headline-levels 3
3084 "The last level which is still exported as a headline.
3085 Inferior levels will produce itemize lists when exported.
3086 Note that a numeric prefix argument to an exporter function overrides
3087 this setting.
3089 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3090 :group 'org-export-general
3091 :type 'number)
3093 (defcustom org-export-with-section-numbers t
3094 "Non-nil means, add section numbers to headlines when exporting.
3096 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3097 :group 'org-export-general
3098 :type 'boolean)
3100 (defcustom org-export-with-toc t
3101 "Non-nil means, create a table of contents in exported files.
3102 The TOC contains headlines with levels up to`org-export-headline-levels'.
3103 When an integer, include levels up to N in the toc, this may then be
3104 different from `org-export-headline-levels', but it will not be allowed
3105 to be larger than the number of headline levels.
3106 When nil, no table of contents is made.
3108 Headlines which contain any TODO items will be marked with \"(*)\" in
3109 ASCII export, and with red color in HTML output, if the option
3110 `org-export-mark-todo-in-toc' is set.
3112 In HTML output, the TOC will be clickable.
3114 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3115 or \"toc:3\"."
3116 :group 'org-export-general
3117 :type '(choice
3118 (const :tag "No Table of Contents" nil)
3119 (const :tag "Full Table of Contents" t)
3120 (integer :tag "TOC to level")))
3122 (defcustom org-export-mark-todo-in-toc nil
3123 "Non-nil means, mark TOC lines that contain any open TODO items."
3124 :group 'org-export-general
3125 :type 'boolean)
3127 (defcustom org-export-preserve-breaks nil
3128 "Non-nil means, preserve all line breaks when exporting.
3129 Normally, in HTML output paragraphs will be reformatted. In ASCII
3130 export, line breaks will always be preserved, regardless of this variable.
3132 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3133 :group 'org-export-general
3134 :type 'boolean)
3136 (defcustom org-export-with-archived-trees 'headline
3137 "Whether subtrees with the ARCHIVE tag should be exported.
3138 This can have three different values
3139 nil Do not export, pretend this tree is not present
3140 t Do export the entire tree
3141 headline Only export the headline, but skip the tree below it."
3142 :group 'org-export-general
3143 :group 'org-archive
3144 :type '(choice
3145 (const :tag "not at all" nil)
3146 (const :tag "headline only" 'headline)
3147 (const :tag "entirely" t)))
3149 (defcustom org-export-author-info t
3150 "Non-nil means, insert author name and email into the exported file.
3152 This option can also be set with the +OPTIONS line,
3153 e.g. \"author-info:nil\"."
3154 :group 'org-export-general
3155 :type 'boolean)
3157 (defcustom org-export-time-stamp-file t
3158 "Non-nil means, insert a time stamp into the exported file.
3159 The time stamp shows when the file was created.
3161 This option can also be set with the +OPTIONS line,
3162 e.g. \"timestamp:nil\"."
3163 :group 'org-export-general
3164 :type 'boolean)
3166 (defcustom org-export-with-timestamps t
3167 "If nil, do not export time stamps and associated keywords."
3168 :group 'org-export-general
3169 :type 'boolean)
3171 (defcustom org-export-remove-timestamps-from-toc t
3172 "If nil, remove timestamps from the table of contents entries."
3173 :group 'org-export-general
3174 :type 'boolean)
3176 (defcustom org-export-with-tags 'not-in-toc
3177 "If nil, do not export tags, just remove them from headlines.
3178 If this is the symbol `not-in-toc', tags will be removed from table of
3179 contents entries, but still be shown in the headlines of the document.
3181 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3182 :group 'org-export-general
3183 :type '(choice
3184 (const :tag "Off" nil)
3185 (const :tag "Not in TOC" not-in-toc)
3186 (const :tag "On" t)))
3188 (defcustom org-export-with-drawers nil
3189 "Non-nil means, export with drawers like the property drawer.
3190 When t, all drawers are exported. This may also be a list of
3191 drawer names to export."
3192 :group 'org-export-general
3193 :type '(choice
3194 (const :tag "All drawers" t)
3195 (const :tag "None" nil)
3196 (repeat :tag "Selected drawers"
3197 (string :tag "Drawer name"))))
3199 (defgroup org-export-translation nil
3200 "Options for translating special ascii sequences for the export backends."
3201 :tag "Org Export Translation"
3202 :group 'org-export)
3204 (defcustom org-export-with-emphasize t
3205 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3206 If the export target supports emphasizing text, the word will be
3207 typeset in bold, italic, or underlined, respectively. Works only for
3208 single words, but you can say: I *really* *mean* *this*.
3209 Not all export backends support this.
3211 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3212 :group 'org-export-translation
3213 :type 'boolean)
3215 (defcustom org-export-with-footnotes t
3216 "If nil, export [1] as a footnote marker.
3217 Lines starting with [1] will be formatted as footnotes.
3219 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3220 :group 'org-export-translation
3221 :type 'boolean)
3223 (defcustom org-export-with-sub-superscripts t
3224 "Non-nil means, interpret \"_\" and \"^\" for export.
3225 When this option is turned on, you can use TeX-like syntax for sub- and
3226 superscripts. Several characters after \"_\" or \"^\" will be
3227 considered as a single item - so grouping with {} is normally not
3228 needed. For example, the following things will be parsed as single
3229 sub- or superscripts.
3231 10^24 or 10^tau several digits will be considered 1 item.
3232 10^-12 or 10^-tau a leading sign with digits or a word
3233 x^2-y^3 will be read as x^2 - y^3, because items are
3234 terminated by almost any nonword/nondigit char.
3235 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3237 Still, ambiguity is possible - so when in doubt use {} to enclose the
3238 sub/superscript. If you set this variable to the symbol `{}',
3239 the braces are *required* in order to trigger interpretations as
3240 sub/superscript. This can be helpful in documents that need \"_\"
3241 frequently in plain text.
3243 Not all export backends support this, but HTML does.
3245 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3246 :group 'org-export-translation
3247 :type '(choice
3248 (const :tag "Always interpret" t)
3249 (const :tag "Only with braces" {})
3250 (const :tag "Never interpret" nil)))
3252 (defcustom org-export-with-special-strings t
3253 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3254 When this option is turned on, these strings will be exported as:
3256 \\- : &shy;
3257 -- : &ndash;
3258 --- : &mdash;
3260 Not all export backends support this, but HTML does.
3262 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3263 :group 'org-export-translation
3264 :type 'boolean)
3266 (defcustom org-export-with-TeX-macros t
3267 "Non-nil means, interpret simple TeX-like macros when exporting.
3268 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3269 No only real TeX macros will work here, but the standard HTML entities
3270 for math can be used as macro names as well. For a list of supported
3271 names in HTML export, see the constant `org-html-entities'.
3272 Not all export backends support this.
3274 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3275 :group 'org-export-translation
3276 :group 'org-export-latex
3277 :type 'boolean)
3279 (defcustom org-export-with-LaTeX-fragments nil
3280 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3281 When set, the exporter will find LaTeX environments if the \\begin line is
3282 the first non-white thing on a line. It will also find the math delimiters
3283 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3284 display math.
3286 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3287 :group 'org-export-translation
3288 :group 'org-export-latex
3289 :type 'boolean)
3291 (defcustom org-export-with-fixed-width t
3292 "Non-nil means, lines starting with \":\" will be in fixed width font.
3293 This can be used to have pre-formatted text, fragments of code etc. For
3294 example:
3295 : ;; Some Lisp examples
3296 : (while (defc cnt)
3297 : (ding))
3298 will be looking just like this in also HTML. See also the QUOTE keyword.
3299 Not all export backends support this.
3301 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3302 :group 'org-export-translation
3303 :type 'boolean)
3305 (defcustom org-match-sexp-depth 3
3306 "Number of stacked braces for sub/superscript matching.
3307 This has to be set before loading org.el to be effective."
3308 :group 'org-export-translation
3309 :type 'integer)
3311 (defgroup org-export-tables nil
3312 "Options for exporting tables in Org-mode."
3313 :tag "Org Export Tables"
3314 :group 'org-export)
3316 (defcustom org-export-with-tables t
3317 "If non-nil, lines starting with \"|\" define a table.
3318 For example:
3320 | Name | Address | Birthday |
3321 |-------------+----------+-----------|
3322 | Arthur Dent | England | 29.2.2100 |
3324 Not all export backends support this.
3326 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3327 :group 'org-export-tables
3328 :type 'boolean)
3330 (defcustom org-export-highlight-first-table-line t
3331 "Non-nil means, highlight the first table line.
3332 In HTML export, this means use <th> instead of <td>.
3333 In tables created with table.el, this applies to the first table line.
3334 In Org-mode tables, all lines before the first horizontal separator
3335 line will be formatted with <th> tags."
3336 :group 'org-export-tables
3337 :type 'boolean)
3339 (defcustom org-export-table-remove-special-lines t
3340 "Remove special lines and marking characters in calculating tables.
3341 This removes the special marking character column from tables that are set
3342 up for spreadsheet calculations. It also removes the entire lines
3343 marked with `!', `_', or `^'. The lines with `$' are kept, because
3344 the values of constants may be useful to have."
3345 :group 'org-export-tables
3346 :type 'boolean)
3348 (defcustom org-export-prefer-native-exporter-for-tables nil
3349 "Non-nil means, always export tables created with table.el natively.
3350 Natively means, use the HTML code generator in table.el.
3351 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3352 the table does not use row- or column-spanning). This has the
3353 advantage, that the automatic HTML conversions for math symbols and
3354 sub/superscripts can be applied. Org-mode's HTML generator is also
3355 much faster."
3356 :group 'org-export-tables
3357 :type 'boolean)
3359 (defgroup org-export-ascii nil
3360 "Options specific for ASCII export of Org-mode files."
3361 :tag "Org Export ASCII"
3362 :group 'org-export)
3364 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3365 "Characters for underlining headings in ASCII export.
3366 In the given sequence, these characters will be used for level 1, 2, ..."
3367 :group 'org-export-ascii
3368 :type '(repeat character))
3370 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3371 "Bullet characters for headlines converted to lists in ASCII export.
3372 The first character is used for the first lest level generated in this
3373 way, and so on. If there are more levels than characters given here,
3374 the list will be repeated.
3375 Note that plain lists will keep the same bullets as the have in the
3376 Org-mode file."
3377 :group 'org-export-ascii
3378 :type '(repeat character))
3380 (defgroup org-export-xml nil
3381 "Options specific for XML export of Org-mode files."
3382 :tag "Org Export XML"
3383 :group 'org-export)
3385 (defgroup org-export-html nil
3386 "Options specific for HTML export of Org-mode files."
3387 :tag "Org Export HTML"
3388 :group 'org-export)
3390 (defcustom org-export-html-coding-system nil
3392 :group 'org-export-html
3393 :type 'coding-system)
3395 (defcustom org-export-html-extension "html"
3396 "The extension for exported HTML files."
3397 :group 'org-export-html
3398 :type 'string)
3400 (defcustom org-export-html-style
3401 "<style type=\"text/css\">
3402 html {
3403 font-family: Times, serif;
3404 font-size: 12pt;
3406 .title { text-align: center; }
3407 .todo { color: red; }
3408 .done { color: green; }
3409 .timestamp { color: grey }
3410 .timestamp-kwd { color: CadetBlue }
3411 .tag { background-color:lightblue; font-weight:normal }
3412 .target { background-color: lavender; }
3413 pre {
3414 border: 1pt solid #AEBDCC;
3415 background-color: #F3F5F7;
3416 padding: 5pt;
3417 font-family: courier, monospace;
3419 table { border-collapse: collapse; }
3420 td, th {
3421 vertical-align: top;
3422 <!--border: 1pt solid #ADB9CC;-->
3424 </style>"
3425 "The default style specification for exported HTML files.
3426 Since there are different ways of setting style information, this variable
3427 needs to contain the full HTML structure to provide a style, including the
3428 surrounding HTML tags. The style specifications should include definitions
3429 for new classes todo, done, title, and deadline. For example, legal values
3430 would be:
3432 <style type=\"text/css\">
3433 p { font-weight: normal; color: gray; }
3434 h1 { color: black; }
3435 .title { text-align: center; }
3436 .todo, .deadline { color: red; }
3437 .done { color: green; }
3438 </style>
3440 or, if you want to keep the style in a file,
3442 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3444 As the value of this option simply gets inserted into the HTML <head> header,
3445 you can \"misuse\" it to add arbitrary text to the header."
3446 :group 'org-export-html
3447 :type 'string)
3450 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3451 "Format for typesetting the document title in HTML export."
3452 :group 'org-export-html
3453 :type 'string)
3455 (defcustom org-export-html-toplevel-hlevel 2
3456 "The <H> level for level 1 headings in HTML export."
3457 :group 'org-export-html
3458 :type 'string)
3460 (defcustom org-export-html-link-org-files-as-html t
3461 "Non-nil means, make file links to `file.org' point to `file.html'.
3462 When org-mode is exporting an org-mode file to HTML, links to
3463 non-html files are directly put into a href tag in HTML.
3464 However, links to other Org-mode files (recognized by the
3465 extension `.org.) should become links to the corresponding html
3466 file, assuming that the linked org-mode file will also be
3467 converted to HTML.
3468 When nil, the links still point to the plain `.org' file."
3469 :group 'org-export-html
3470 :type 'boolean)
3472 (defcustom org-export-html-inline-images 'maybe
3473 "Non-nil means, inline images into exported HTML pages.
3474 This is done using an <img> tag. When nil, an anchor with href is used to
3475 link to the image. If this option is `maybe', then images in links with
3476 an empty description will be inlined, while images with a description will
3477 be linked only."
3478 :group 'org-export-html
3479 :type '(choice (const :tag "Never" nil)
3480 (const :tag "Always" t)
3481 (const :tag "When there is no description" maybe)))
3483 ;; FIXME: rename
3484 (defcustom org-export-html-expand t
3485 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3486 When nil, these tags will be exported as plain text and therefore
3487 not be interpreted by a browser.
3489 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3490 :group 'org-export-html
3491 :type 'boolean)
3493 (defcustom org-export-html-table-tag
3494 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3495 "The HTML tag that is used to start a table.
3496 This must be a <table> tag, but you may change the options like
3497 borders and spacing."
3498 :group 'org-export-html
3499 :type 'string)
3501 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3502 "The opening tag for table header fields.
3503 This is customizable so that alignment options can be specified."
3504 :group 'org-export-tables
3505 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3507 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3508 "The opening tag for table data fields.
3509 This is customizable so that alignment options can be specified."
3510 :group 'org-export-tables
3511 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3513 (defcustom org-export-html-with-timestamp nil
3514 "If non-nil, write `org-export-html-html-helper-timestamp'
3515 into the exported HTML text. Otherwise, the buffer will just be saved
3516 to a file."
3517 :group 'org-export-html
3518 :type 'boolean)
3520 (defcustom org-export-html-html-helper-timestamp
3521 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3522 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3523 :group 'org-export-html
3524 :type 'string)
3526 (defgroup org-export-icalendar nil
3527 "Options specific for iCalendar export of Org-mode files."
3528 :tag "Org Export iCalendar"
3529 :group 'org-export)
3531 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3532 "The file name for the iCalendar file covering all agenda files.
3533 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3534 The file name should be absolute, the file will be overwritten without warning."
3535 :group 'org-export-icalendar
3536 :type 'file)
3538 (defcustom org-icalendar-include-todo nil
3539 "Non-nil means, export to iCalendar files should also cover TODO items."
3540 :group 'org-export-icalendar
3541 :type '(choice
3542 (const :tag "None" nil)
3543 (const :tag "Unfinished" t)
3544 (const :tag "All" all)))
3546 (defcustom org-icalendar-include-sexps t
3547 "Non-nil means, export to iCalendar files should also cover sexp entries.
3548 These are entries like in the diary, but directly in an Org-mode file."
3549 :group 'org-export-icalendar
3550 :type 'boolean)
3552 (defcustom org-icalendar-include-body 100
3553 "Amount of text below headline to be included in iCalendar export.
3554 This is a number of characters that should maximally be included.
3555 Properties, scheduling and clocking lines will always be removed.
3556 The text will be inserted into the DESCRIPTION field."
3557 :group 'org-export-icalendar
3558 :type '(choice
3559 (const :tag "Nothing" nil)
3560 (const :tag "Everything" t)
3561 (integer :tag "Max characters")))
3563 (defcustom org-icalendar-combined-name "OrgMode"
3564 "Calendar name for the combined iCalendar representing all agenda files."
3565 :group 'org-export-icalendar
3566 :type 'string)
3568 (defgroup org-font-lock nil
3569 "Font-lock settings for highlighting in Org-mode."
3570 :tag "Org Font Lock"
3571 :group 'org)
3573 (defcustom org-level-color-stars-only nil
3574 "Non-nil means fontify only the stars in each headline.
3575 When nil, the entire headline is fontified.
3576 Changing it requires restart of `font-lock-mode' to become effective
3577 also in regions already fontified."
3578 :group 'org-font-lock
3579 :type 'boolean)
3581 (defcustom org-hide-leading-stars nil
3582 "Non-nil means, hide the first N-1 stars in a headline.
3583 This works by using the face `org-hide' for these stars. This
3584 face is white for a light background, and black for a dark
3585 background. You may have to customize the face `org-hide' to
3586 make this work.
3587 Changing it requires restart of `font-lock-mode' to become effective
3588 also in regions already fontified.
3589 You may also set this on a per-file basis by adding one of the following
3590 lines to the buffer:
3592 #+STARTUP: hidestars
3593 #+STARTUP: showstars"
3594 :group 'org-font-lock
3595 :type 'boolean)
3597 (defcustom org-fontify-done-headline nil
3598 "Non-nil means, change the face of a headline if it is marked DONE.
3599 Normally, only the TODO/DONE keyword indicates the state of a headline.
3600 When this is non-nil, the headline after the keyword is set to the
3601 `org-headline-done' as an additional indication."
3602 :group 'org-font-lock
3603 :type 'boolean)
3605 (defcustom org-fontify-emphasized-text t
3606 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3607 Changing this variable requires a restart of Emacs to take effect."
3608 :group 'org-font-lock
3609 :type 'boolean)
3611 (defcustom org-highlight-latex-fragments-and-specials nil
3612 "Non-nil means, fontify what is treated specially by the exporters."
3613 :group 'org-font-lock
3614 :type 'boolean)
3616 (defcustom org-hide-emphasis-markers nil
3617 "Non-nil mean font-lock should hide the emphasis marker characters."
3618 :group 'org-font-lock
3619 :type 'boolean)
3621 (defvar org-emph-re nil
3622 "Regular expression for matching emphasis.")
3623 (defvar org-verbatim-re nil
3624 "Regular expression for matching verbatim text.")
3625 (defvar org-emphasis-regexp-components) ; defined just below
3626 (defvar org-emphasis-alist) ; defined just below
3627 (defun org-set-emph-re (var val)
3628 "Set variable and compute the emphasis regular expression."
3629 (set var val)
3630 (when (and (boundp 'org-emphasis-alist)
3631 (boundp 'org-emphasis-regexp-components)
3632 org-emphasis-alist org-emphasis-regexp-components)
3633 (let* ((e org-emphasis-regexp-components)
3634 (pre (car e))
3635 (post (nth 1 e))
3636 (border (nth 2 e))
3637 (body (nth 3 e))
3638 (nl (nth 4 e))
3639 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3640 (body1 (concat body "*?"))
3641 (markers (mapconcat 'car org-emphasis-alist ""))
3642 (vmarkers (mapconcat
3643 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3644 org-emphasis-alist "")))
3645 ;; make sure special characters appear at the right position in the class
3646 (if (string-match "\\^" markers)
3647 (setq markers (concat (replace-match "" t t markers) "^")))
3648 (if (string-match "-" markers)
3649 (setq markers (concat (replace-match "" t t markers) "-")))
3650 (if (string-match "\\^" vmarkers)
3651 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3652 (if (string-match "-" vmarkers)
3653 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3654 (if (> nl 0)
3655 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3656 (int-to-string nl) "\\}")))
3657 ;; Make the regexp
3658 (setq org-emph-re
3659 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3660 "\\("
3661 "\\([" markers "]\\)"
3662 "\\("
3663 "[^" border "]\\|"
3664 "[^" border (if (and nil stacked) markers) "]"
3665 body1
3666 "[^" border (if (and nil stacked) markers) "]"
3667 "\\)"
3668 "\\3\\)"
3669 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3670 (setq org-verbatim-re
3671 (concat "\\([" pre "]\\|^\\)"
3672 "\\("
3673 "\\([" vmarkers "]\\)"
3674 "\\("
3675 "[^" border "]\\|"
3676 "[^" border "]"
3677 body1
3678 "[^" border "]"
3679 "\\)"
3680 "\\3\\)"
3681 "\\([" post "]\\|$\\)")))))
3683 (defcustom org-emphasis-regexp-components
3684 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3685 "Components used to build the regular expression for emphasis.
3686 This is a list with 6 entries. Terminology: In an emphasis string
3687 like \" *strong word* \", we call the initial space PREMATCH, the final
3688 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3689 and \"trong wor\" is the body. The different components in this variable
3690 specify what is allowed/forbidden in each part:
3692 pre Chars allowed as prematch. Beginning of line will be allowed too.
3693 post Chars allowed as postmatch. End of line will be allowed too.
3694 border The chars *forbidden* as border characters.
3695 body-regexp A regexp like \".\" to match a body character. Don't use
3696 non-shy groups here, and don't allow newline here.
3697 newline The maximum number of newlines allowed in an emphasis exp.
3699 Use customize to modify this, or restart Emacs after changing it."
3700 :group 'org-font-lock
3701 :set 'org-set-emph-re
3702 :type '(list
3703 (sexp :tag "Allowed chars in pre ")
3704 (sexp :tag "Allowed chars in post ")
3705 (sexp :tag "Forbidden chars in border ")
3706 (sexp :tag "Regexp for body ")
3707 (integer :tag "number of newlines allowed")
3708 (option (boolean :tag "Stacking (DISABLED) "))))
3710 (defcustom org-emphasis-alist
3711 '(("*" bold "<b>" "</b>")
3712 ("/" italic "<i>" "</i>")
3713 ("_" underline "<u>" "</u>")
3714 ("=" org-code "<code>" "</code>" verbatim)
3715 ("~" org-verbatim "" "" verbatim)
3716 ("+" (:strike-through t) "<del>" "</del>")
3718 "Special syntax for emphasized text.
3719 Text starting and ending with a special character will be emphasized, for
3720 example *bold*, _underlined_ and /italic/. This variable sets the marker
3721 characters, the face to be used by font-lock for highlighting in Org-mode
3722 Emacs buffers, and the HTML tags to be used for this.
3723 Use customize to modify this, or restart Emacs after changing it."
3724 :group 'org-font-lock
3725 :set 'org-set-emph-re
3726 :type '(repeat
3727 (list
3728 (string :tag "Marker character")
3729 (choice
3730 (face :tag "Font-lock-face")
3731 (plist :tag "Face property list"))
3732 (string :tag "HTML start tag")
3733 (string :tag "HTML end tag")
3734 (option (const verbatim)))))
3736 ;;; The faces
3738 (defgroup org-faces nil
3739 "Faces in Org-mode."
3740 :tag "Org Faces"
3741 :group 'org-font-lock)
3743 (defun org-compatible-face (inherits specs)
3744 "Make a compatible face specification.
3745 If INHERITS is an existing face and if the Emacs version supports it,
3746 just inherit the face. If not, use SPECS to define the face.
3747 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3748 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3749 to the top of the list. The `min-colors' attribute will be removed from
3750 any other entries, and any resulting duplicates will be removed entirely."
3751 (cond
3752 ((and inherits (facep inherits)
3753 (not (featurep 'xemacs)) (> emacs-major-version 22))
3754 ;; In Emacs 23, we use inheritance where possible.
3755 ;; We only do this in Emacs 23, because only there the outline
3756 ;; faces have been changed to the original org-mode-level-faces.
3757 (list (list t :inherit inherits)))
3758 ((or (featurep 'xemacs) (< emacs-major-version 22))
3759 ;; These do not understand the `min-colors' attribute.
3760 (let (r e a)
3761 (while (setq e (pop specs))
3762 (cond
3763 ((memq (car e) '(t default)) (push e r))
3764 ((setq a (member '(min-colors 8) (car e)))
3765 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3766 (cdr e)))))
3767 ((setq a (assq 'min-colors (car e)))
3768 (setq e (cons (delq a (car e)) (cdr e)))
3769 (or (assoc (car e) r) (push e r)))
3770 (t (or (assoc (car e) r) (push e r)))))
3771 (nreverse r)))
3772 (t specs)))
3773 (put 'org-compatible-face 'lisp-indent-function 1)
3775 (defface org-hide
3776 '((((background light)) (:foreground "white"))
3777 (((background dark)) (:foreground "black")))
3778 "Face used to hide leading stars in headlines.
3779 The forground color of this face should be equal to the background
3780 color of the frame."
3781 :group 'org-faces)
3783 (defface org-level-1 ;; font-lock-function-name-face
3784 (org-compatible-face 'outline-1
3785 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3786 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3787 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3788 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3789 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3790 (t (:bold t))))
3791 "Face used for level 1 headlines."
3792 :group 'org-faces)
3794 (defface org-level-2 ;; font-lock-variable-name-face
3795 (org-compatible-face 'outline-2
3796 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3797 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3798 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3799 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3800 (t (:bold t))))
3801 "Face used for level 2 headlines."
3802 :group 'org-faces)
3804 (defface org-level-3 ;; font-lock-keyword-face
3805 (org-compatible-face 'outline-3
3806 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3807 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3808 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3809 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3810 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3811 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3812 (t (:bold t))))
3813 "Face used for level 3 headlines."
3814 :group 'org-faces)
3816 (defface org-level-4 ;; font-lock-comment-face
3817 (org-compatible-face 'outline-4
3818 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3819 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3820 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3821 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3822 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3823 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3824 (t (:bold t))))
3825 "Face used for level 4 headlines."
3826 :group 'org-faces)
3828 (defface org-level-5 ;; font-lock-type-face
3829 (org-compatible-face 'outline-5
3830 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3831 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3832 (((class color) (min-colors 8)) (:foreground "green"))))
3833 "Face used for level 5 headlines."
3834 :group 'org-faces)
3836 (defface org-level-6 ;; font-lock-constant-face
3837 (org-compatible-face 'outline-6
3838 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3839 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3840 (((class color) (min-colors 8)) (:foreground "magenta"))))
3841 "Face used for level 6 headlines."
3842 :group 'org-faces)
3844 (defface org-level-7 ;; font-lock-builtin-face
3845 (org-compatible-face 'outline-7
3846 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3847 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3848 (((class color) (min-colors 8)) (:foreground "blue"))))
3849 "Face used for level 7 headlines."
3850 :group 'org-faces)
3852 (defface org-level-8 ;; font-lock-string-face
3853 (org-compatible-face 'outline-8
3854 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3855 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3856 (((class color) (min-colors 8)) (:foreground "green"))))
3857 "Face used for level 8 headlines."
3858 :group 'org-faces)
3860 (defface org-special-keyword ;; font-lock-string-face
3861 (org-compatible-face nil
3862 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3863 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3864 (t (:italic t))))
3865 "Face used for special keywords."
3866 :group 'org-faces)
3868 (defface org-drawer ;; font-lock-function-name-face
3869 (org-compatible-face nil
3870 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3871 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3872 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3873 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3874 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3875 (t (:bold t))))
3876 "Face used for drawers."
3877 :group 'org-faces)
3879 (defface org-property-value nil
3880 "Face used for the value of a property."
3881 :group 'org-faces)
3883 (defface org-column
3884 (org-compatible-face nil
3885 '((((class color) (min-colors 16) (background light))
3886 (:background "grey90"))
3887 (((class color) (min-colors 16) (background dark))
3888 (:background "grey30"))
3889 (((class color) (min-colors 8))
3890 (:background "cyan" :foreground "black"))
3891 (t (:inverse-video t))))
3892 "Face for column display of entry properties."
3893 :group 'org-faces)
3895 (when (fboundp 'set-face-attribute)
3896 ;; Make sure that a fixed-width face is used when we have a column table.
3897 (set-face-attribute 'org-column nil
3898 :height (face-attribute 'default :height)
3899 :family (face-attribute 'default :family)))
3901 (defface org-warning
3902 (org-compatible-face 'font-lock-warning-face
3903 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3904 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3905 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3906 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3907 (t (:bold t))))
3908 "Face for deadlines and TODO keywords."
3909 :group 'org-faces)
3911 (defface org-archived ; similar to shadow
3912 (org-compatible-face 'shadow
3913 '((((class color grayscale) (min-colors 88) (background light))
3914 (:foreground "grey50"))
3915 (((class color grayscale) (min-colors 88) (background dark))
3916 (:foreground "grey70"))
3917 (((class color) (min-colors 8) (background light))
3918 (:foreground "green"))
3919 (((class color) (min-colors 8) (background dark))
3920 (:foreground "yellow"))))
3921 "Face for headline with the ARCHIVE tag."
3922 :group 'org-faces)
3924 (defface org-link
3925 '((((class color) (background light)) (:foreground "Purple" :underline t))
3926 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3927 (t (:underline t)))
3928 "Face for links."
3929 :group 'org-faces)
3931 (defface org-ellipsis
3932 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3933 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3934 (t (:strike-through t)))
3935 "Face for the ellipsis in folded text."
3936 :group 'org-faces)
3938 (defface org-target
3939 '((((class color) (background light)) (:underline t))
3940 (((class color) (background dark)) (:underline t))
3941 (t (:underline t)))
3942 "Face for links."
3943 :group 'org-faces)
3945 (defface org-date
3946 '((((class color) (background light)) (:foreground "Purple" :underline t))
3947 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3948 (t (:underline t)))
3949 "Face for links."
3950 :group 'org-faces)
3952 (defface org-sexp-date
3953 '((((class color) (background light)) (:foreground "Purple"))
3954 (((class color) (background dark)) (:foreground "Cyan"))
3955 (t (:underline t)))
3956 "Face for links."
3957 :group 'org-faces)
3959 (defface org-tag
3960 '((t (:bold t)))
3961 "Face for tags."
3962 :group 'org-faces)
3964 (defface org-todo ; font-lock-warning-face
3965 (org-compatible-face nil
3966 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3967 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3968 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3969 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3970 (t (:inverse-video t :bold t))))
3971 "Face for TODO keywords."
3972 :group 'org-faces)
3974 (defface org-done ;; font-lock-type-face
3975 (org-compatible-face nil
3976 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3977 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3978 (((class color) (min-colors 8)) (:foreground "green"))
3979 (t (:bold t))))
3980 "Face used for todo keywords that indicate DONE items."
3981 :group 'org-faces)
3983 (defface org-headline-done ;; font-lock-string-face
3984 (org-compatible-face nil
3985 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3986 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3987 (((class color) (min-colors 8) (background light)) (:bold nil))))
3988 "Face used to indicate that a headline is DONE.
3989 This face is only used if `org-fontify-done-headline' is set. If applies
3990 to the part of the headline after the DONE keyword."
3991 :group 'org-faces)
3993 (defcustom org-todo-keyword-faces nil
3994 "Faces for specific TODO keywords.
3995 This is a list of cons cells, with TODO keywords in the car
3996 and faces in the cdr. The face can be a symbol, or a property
3997 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3998 :group 'org-faces
3999 :group 'org-todo
4000 :type '(repeat
4001 (cons
4002 (string :tag "keyword")
4003 (sexp :tag "face"))))
4005 (defface org-table ;; font-lock-function-name-face
4006 (org-compatible-face nil
4007 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4008 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4009 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4010 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4011 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4012 (((class color) (min-colors 8) (background dark)))))
4013 "Face used for tables."
4014 :group 'org-faces)
4016 (defface org-formula
4017 (org-compatible-face nil
4018 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4019 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4020 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4021 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4022 (t (:bold t :italic t))))
4023 "Face for formulas."
4024 :group 'org-faces)
4026 (defface org-code
4027 (org-compatible-face nil
4028 '((((class color grayscale) (min-colors 88) (background light))
4029 (:foreground "grey50"))
4030 (((class color grayscale) (min-colors 88) (background dark))
4031 (:foreground "grey70"))
4032 (((class color) (min-colors 8) (background light))
4033 (:foreground "green"))
4034 (((class color) (min-colors 8) (background dark))
4035 (:foreground "yellow"))))
4036 "Face for fixed-with text like code snippets."
4037 :group 'org-faces
4038 :version "22.1")
4040 (defface org-verbatim
4041 (org-compatible-face nil
4042 '((((class color grayscale) (min-colors 88) (background light))
4043 (:foreground "grey50" :underline t))
4044 (((class color grayscale) (min-colors 88) (background dark))
4045 (:foreground "grey70" :underline t))
4046 (((class color) (min-colors 8) (background light))
4047 (:foreground "green" :underline t))
4048 (((class color) (min-colors 8) (background dark))
4049 (:foreground "yellow" :underline t))))
4050 "Face for fixed-with text like code snippets."
4051 :group 'org-faces
4052 :version "22.1")
4054 (defface org-agenda-structure ;; font-lock-function-name-face
4055 (org-compatible-face nil
4056 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4057 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4058 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4059 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4060 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4061 (t (:bold t))))
4062 "Face used in agenda for captions and dates."
4063 :group 'org-faces)
4065 (defface org-scheduled-today
4066 (org-compatible-face nil
4067 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4068 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4069 (((class color) (min-colors 8)) (:foreground "green"))
4070 (t (:bold t :italic t))))
4071 "Face for items scheduled for a certain day."
4072 :group 'org-faces)
4074 (defface org-scheduled-previously
4075 (org-compatible-face nil
4076 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4077 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4078 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4079 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4080 (t (:bold t))))
4081 "Face for items scheduled previously, and not yet done."
4082 :group 'org-faces)
4084 (defface org-upcoming-deadline
4085 (org-compatible-face nil
4086 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4087 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4088 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4089 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4090 (t (:bold t))))
4091 "Face for items scheduled previously, and not yet done."
4092 :group 'org-faces)
4094 (defcustom org-agenda-deadline-faces
4095 '((1.0 . org-warning)
4096 (0.5 . org-upcoming-deadline)
4097 (0.0 . default))
4098 "Faces for showing deadlines in the agenda.
4099 This is a list of cons cells. The cdr of each cell is a face to be used,
4100 and it can also just be like '(:foreground \"yellow\").
4101 Each car is a fraction of the head-warning time that must have passed for
4102 this the face in the cdr to be used for display. The numbers must be
4103 given in descending order. The head-warning time is normally taken
4104 from `org-deadline-warning-days', but can also be specified in the deadline
4105 timestamp itself, like this:
4107 DEADLINE: <2007-08-13 Mon -8d>
4109 You may use d for days, w for weeks, m for months and y for years. Months
4110 and years will only be treated in an approximate fashion (30.4 days for a
4111 month and 365.24 days for a year)."
4112 :group 'org-faces
4113 :group 'org-agenda-daily/weekly
4114 :type '(repeat
4115 (cons
4116 (number :tag "Fraction of head-warning time passed")
4117 (sexp :tag "Face"))))
4119 ;; FIXME: this is not a good face yet.
4120 (defface org-agenda-restriction-lock
4121 (org-compatible-face nil
4122 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4123 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4124 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4125 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4126 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4127 (t (:inverse-video t))))
4128 "Face for showing the agenda restriction lock."
4129 :group 'org-faces)
4131 (defface org-time-grid ;; font-lock-variable-name-face
4132 (org-compatible-face nil
4133 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4134 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4135 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4136 "Face used for time grids."
4137 :group 'org-faces)
4139 (defconst org-level-faces
4140 '(org-level-1 org-level-2 org-level-3 org-level-4
4141 org-level-5 org-level-6 org-level-7 org-level-8
4144 (defcustom org-n-level-faces (length org-level-faces)
4145 "The number different faces to be used for headlines.
4146 Org-mode defines 8 different headline faces, so this can be at most 8.
4147 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4148 :type 'number
4149 :group 'org-faces)
4151 ;;; Functions and variables from ther packages
4152 ;; Declared here to avoid compiler warnings
4154 (eval-and-compile
4155 (unless (fboundp 'declare-function)
4156 (defmacro declare-function (fn file &optional arglist fileonly))))
4158 ;; XEmacs only
4159 (defvar outline-mode-menu-heading)
4160 (defvar outline-mode-menu-show)
4161 (defvar outline-mode-menu-hide)
4162 (defvar zmacs-regions) ; XEmacs regions
4164 ;; Emacs only
4165 (defvar mark-active)
4167 ;; Various packages
4168 ;; FIXME: get the argument lists for the UNKNOWN stuff
4169 (declare-function add-to-diary-list "diary-lib"
4170 (date string specifier &optional marker globcolor literal))
4171 (declare-function table--at-cell-p "table" (position &optional object at-column))
4172 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4173 (declare-function Info-goto-node "info" (nodename &optional fork))
4174 (declare-function bbdb "ext:bbdb-com" (string elidep))
4175 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4176 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4177 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4178 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4179 (declare-function bbdb-record-name "ext:bbdb" (record))
4180 (declare-function bibtex-beginning-of-entry "bibtex" ())
4181 (declare-function bibtex-generate-autokey "bibtex" ())
4182 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4183 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4184 (defvar calc-embedded-close-formula)
4185 (defvar calc-embedded-open-formula)
4186 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4187 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4188 (declare-function calendar-check-holidays "holidays" (date))
4189 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4190 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4191 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4192 (declare-function calendar-forward-day "cal-move" (arg))
4193 (declare-function calendar-french-date-string "cal-french" (&optional date))
4194 (declare-function calendar-goto-date "cal-move" (date))
4195 (declare-function calendar-goto-today "cal-move" ())
4196 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4197 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4198 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4199 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4200 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4201 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4202 (defvar calendar-mode-map)
4203 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4204 (declare-function cdlatex-tab "ext:cdlatex" ())
4205 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4206 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4207 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4208 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4209 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4210 (defvar font-lock-unfontify-region-function)
4211 (declare-function gnus-article-show-summary "gnus-art" ())
4212 (declare-function gnus-summary-last-subject "gnus-sum" ())
4213 (defvar gnus-other-frame-object)
4214 (defvar gnus-group-name)
4215 (defvar gnus-article-current)
4216 (defvar Info-current-file)
4217 (defvar Info-current-node)
4218 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4219 (declare-function mh-find-path "mh-utils" ())
4220 (declare-function mh-get-header-field "mh-utils" (field))
4221 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4222 (declare-function mh-header-display "mh-show" ())
4223 (declare-function mh-index-previous-folder "mh-search" ())
4224 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4225 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4226 (declare-function mh-search-choose "mh-search" (&optional searcher))
4227 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4228 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4229 (declare-function mh-show-header-display "mh-show" t t)
4230 (declare-function mh-show-msg "mh-show" (msg))
4231 (declare-function mh-show-show "mh-show" t t)
4232 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4233 (defvar mh-progs)
4234 (defvar mh-current-folder)
4235 (defvar mh-show-folder-buffer)
4236 (defvar mh-index-folder)
4237 (defvar mh-searcher)
4238 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4239 (declare-function parse-time-string "parse-time" (string))
4240 (declare-function remember "remember" (&optional initial))
4241 (declare-function remember-buffer-desc "remember" ())
4242 (declare-function remember-finalize "remember" ())
4243 (defvar remember-save-after-remembering)
4244 (defvar remember-data-file)
4245 (defvar remember-register)
4246 (defvar remember-buffer)
4247 (defvar remember-handler-functions)
4248 (defvar remember-annotation-functions)
4249 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4250 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4251 (declare-function rmail-what-message "rmail" ())
4252 (defvar rmail-current-message)
4253 (defvar texmathp-why)
4254 (declare-function vm-beginning-of-message "ext:vm-page" ())
4255 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4256 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4257 (declare-function vm-isearch-narrow "ext:vm-search" ())
4258 (declare-function vm-isearch-update "ext:vm-search" ())
4259 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4260 (declare-function vm-su-message-id "ext:vm-summary" (m))
4261 (declare-function vm-su-subject "ext:vm-summary" (m))
4262 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4263 (defvar vm-message-pointer)
4264 (defvar vm-folder-directory)
4265 (defvar w3m-current-url)
4266 (defvar w3m-current-title)
4267 ;; backward compatibility to old version of wl
4268 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4269 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4270 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4271 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4272 (declare-function wl-summary-line-from "ext:wl-summary" ())
4273 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4274 (declare-function wl-summary-message-number "ext:wl-summary" ())
4275 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4276 (defvar wl-summary-buffer-elmo-folder)
4277 (defvar wl-summary-buffer-folder-name)
4278 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4280 (defvar org-latex-regexps)
4281 (defvar constants-unit-system)
4283 ;;; Variables for pre-computed regular expressions, all buffer local
4285 (defvar org-drawer-regexp nil
4286 "Matches first line of a hidden block.")
4287 (make-variable-buffer-local 'org-drawer-regexp)
4288 (defvar org-todo-regexp nil
4289 "Matches any of the TODO state keywords.")
4290 (make-variable-buffer-local 'org-todo-regexp)
4291 (defvar org-not-done-regexp nil
4292 "Matches any of the TODO state keywords except the last one.")
4293 (make-variable-buffer-local 'org-not-done-regexp)
4294 (defvar org-todo-line-regexp nil
4295 "Matches a headline and puts TODO state into group 2 if present.")
4296 (make-variable-buffer-local 'org-todo-line-regexp)
4297 (defvar org-complex-heading-regexp nil
4298 "Matches a headline and puts everything into groups:
4299 group 1: the stars
4300 group 2: The todo keyword, maybe
4301 group 3: Priority cookie
4302 group 4: True headline
4303 group 5: Tags")
4304 (make-variable-buffer-local 'org-complex-heading-regexp)
4305 (defvar org-todo-line-tags-regexp nil
4306 "Matches a headline and puts TODO state into group 2 if present.
4307 Also put tags into group 4 if tags are present.")
4308 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4309 (defvar org-nl-done-regexp nil
4310 "Matches newline followed by a headline with the DONE keyword.")
4311 (make-variable-buffer-local 'org-nl-done-regexp)
4312 (defvar org-looking-at-done-regexp nil
4313 "Matches the DONE keyword a point.")
4314 (make-variable-buffer-local 'org-looking-at-done-regexp)
4315 (defvar org-ds-keyword-length 12
4316 "Maximum length of the Deadline and SCHEDULED keywords.")
4317 (make-variable-buffer-local 'org-ds-keyword-length)
4318 (defvar org-deadline-regexp nil
4319 "Matches the DEADLINE keyword.")
4320 (make-variable-buffer-local 'org-deadline-regexp)
4321 (defvar org-deadline-time-regexp nil
4322 "Matches the DEADLINE keyword together with a time stamp.")
4323 (make-variable-buffer-local 'org-deadline-time-regexp)
4324 (defvar org-deadline-line-regexp nil
4325 "Matches the DEADLINE keyword and the rest of the line.")
4326 (make-variable-buffer-local 'org-deadline-line-regexp)
4327 (defvar org-scheduled-regexp nil
4328 "Matches the SCHEDULED keyword.")
4329 (make-variable-buffer-local 'org-scheduled-regexp)
4330 (defvar org-scheduled-time-regexp nil
4331 "Matches the SCHEDULED keyword together with a time stamp.")
4332 (make-variable-buffer-local 'org-scheduled-time-regexp)
4333 (defvar org-closed-time-regexp nil
4334 "Matches the CLOSED keyword together with a time stamp.")
4335 (make-variable-buffer-local 'org-closed-time-regexp)
4337 (defvar org-keyword-time-regexp nil
4338 "Matches any of the 4 keywords, together with the time stamp.")
4339 (make-variable-buffer-local 'org-keyword-time-regexp)
4340 (defvar org-keyword-time-not-clock-regexp nil
4341 "Matches any of the 3 keywords, together with the time stamp.")
4342 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4343 (defvar org-maybe-keyword-time-regexp nil
4344 "Matches a timestamp, possibly preceeded by a keyword.")
4345 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4346 (defvar org-planning-or-clock-line-re nil
4347 "Matches a line with planning or clock info.")
4348 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4350 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4351 rear-nonsticky t mouse-map t fontified t)
4352 "Properties to remove when a string without properties is wanted.")
4354 (defsubst org-match-string-no-properties (num &optional string)
4355 (if (featurep 'xemacs)
4356 (let ((s (match-string num string)))
4357 (remove-text-properties 0 (length s) org-rm-props s)
4359 (match-string-no-properties num string)))
4361 (defsubst org-no-properties (s)
4362 (if (fboundp 'set-text-properties)
4363 (set-text-properties 0 (length s) nil s)
4364 (remove-text-properties 0 (length s) org-rm-props s))
4367 (defsubst org-get-alist-option (option key)
4368 (cond ((eq key t) t)
4369 ((eq option t) t)
4370 ((assoc key option) (cdr (assoc key option)))
4371 (t (cdr (assq 'default option)))))
4373 (defsubst org-inhibit-invisibility ()
4374 "Modified `buffer-invisibility-spec' for Emacs 21.
4375 Some ops with invisible text do not work correctly on Emacs 21. For these
4376 we turn off invisibility temporarily. Use this in a `let' form."
4377 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4379 (defsubst org-set-local (var value)
4380 "Make VAR local in current buffer and set it to VALUE."
4381 (set (make-variable-buffer-local var) value))
4383 (defsubst org-mode-p ()
4384 "Check if the current buffer is in Org-mode."
4385 (eq major-mode 'org-mode))
4387 (defsubst org-last (list)
4388 "Return the last element of LIST."
4389 (car (last list)))
4391 (defun org-let (list &rest body)
4392 (eval (cons 'let (cons list body))))
4393 (put 'org-let 'lisp-indent-function 1)
4395 (defun org-let2 (list1 list2 &rest body)
4396 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4397 (put 'org-let2 'lisp-indent-function 2)
4398 (defconst org-startup-options
4399 '(("fold" org-startup-folded t)
4400 ("overview" org-startup-folded t)
4401 ("nofold" org-startup-folded nil)
4402 ("showall" org-startup-folded nil)
4403 ("content" org-startup-folded content)
4404 ("hidestars" org-hide-leading-stars t)
4405 ("showstars" org-hide-leading-stars nil)
4406 ("odd" org-odd-levels-only t)
4407 ("oddeven" org-odd-levels-only nil)
4408 ("align" org-startup-align-all-tables t)
4409 ("noalign" org-startup-align-all-tables nil)
4410 ("customtime" org-display-custom-times t)
4411 ("logdone" org-log-done time)
4412 ("lognotedone" org-log-done note)
4413 ("nologdone" org-log-done nil)
4414 ("lognoteclock-out" org-log-note-clock-out t)
4415 ("nolognoteclock-out" org-log-note-clock-out nil)
4416 ("logrepeat" org-log-repeat state)
4417 ("lognoterepeat" org-log-repeat note)
4418 ("nologrepeat" org-log-repeat nil)
4419 ("constcgs" constants-unit-system cgs)
4420 ("constSI" constants-unit-system SI))
4421 "Variable associated with STARTUP options for org-mode.
4422 Each element is a list of three items: The startup options as written
4423 in the #+STARTUP line, the corresponding variable, and the value to
4424 set this variable to if the option is found. An optional forth element PUSH
4425 means to push this value onto the list in the variable.")
4427 (defun org-set-regexps-and-options ()
4428 "Precompute regular expressions for current buffer."
4429 (when (org-mode-p)
4430 (org-set-local 'org-todo-kwd-alist nil)
4431 (org-set-local 'org-todo-key-alist nil)
4432 (org-set-local 'org-todo-key-trigger nil)
4433 (org-set-local 'org-todo-keywords-1 nil)
4434 (org-set-local 'org-done-keywords nil)
4435 (org-set-local 'org-todo-heads nil)
4436 (org-set-local 'org-todo-sets nil)
4437 (org-set-local 'org-todo-log-states nil)
4438 (let ((re (org-make-options-regexp
4439 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4440 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4441 "CONSTANTS" "PROPERTY" "DRAWERS")))
4442 (splitre "[ \t]+")
4443 kwds kws0 kwsa key log value cat arch tags const links hw dws
4444 tail sep kws1 prio props drawers)
4445 (save-excursion
4446 (save-restriction
4447 (widen)
4448 (goto-char (point-min))
4449 (while (re-search-forward re nil t)
4450 (setq key (match-string 1) value (org-match-string-no-properties 2))
4451 (cond
4452 ((equal key "CATEGORY")
4453 (if (string-match "[ \t]+$" value)
4454 (setq value (replace-match "" t t value)))
4455 (setq cat value))
4456 ((member key '("SEQ_TODO" "TODO"))
4457 (push (cons 'sequence (org-split-string value splitre)) kwds))
4458 ((equal key "TYP_TODO")
4459 (push (cons 'type (org-split-string value splitre)) kwds))
4460 ((equal key "TAGS")
4461 (setq tags (append tags (org-split-string value splitre))))
4462 ((equal key "COLUMNS")
4463 (org-set-local 'org-columns-default-format value))
4464 ((equal key "LINK")
4465 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4466 (push (cons (match-string 1 value)
4467 (org-trim (match-string 2 value)))
4468 links)))
4469 ((equal key "PRIORITIES")
4470 (setq prio (org-split-string value " +")))
4471 ((equal key "PROPERTY")
4472 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4473 (push (cons (match-string 1 value) (match-string 2 value))
4474 props)))
4475 ((equal key "DRAWERS")
4476 (setq drawers (org-split-string value splitre)))
4477 ((equal key "CONSTANTS")
4478 (setq const (append const (org-split-string value splitre))))
4479 ((equal key "STARTUP")
4480 (let ((opts (org-split-string value splitre))
4481 l var val)
4482 (while (setq l (pop opts))
4483 (when (setq l (assoc l org-startup-options))
4484 (setq var (nth 1 l) val (nth 2 l))
4485 (if (not (nth 3 l))
4486 (set (make-local-variable var) val)
4487 (if (not (listp (symbol-value var)))
4488 (set (make-local-variable var) nil))
4489 (set (make-local-variable var) (symbol-value var))
4490 (add-to-list var val))))))
4491 ((equal key "ARCHIVE")
4492 (string-match " *$" value)
4493 (setq arch (replace-match "" t t value))
4494 (remove-text-properties 0 (length arch)
4495 '(face t fontified t) arch)))
4497 (when cat
4498 (org-set-local 'org-category (intern cat))
4499 (push (cons "CATEGORY" cat) props))
4500 (when prio
4501 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4502 (setq prio (mapcar 'string-to-char prio))
4503 (org-set-local 'org-highest-priority (nth 0 prio))
4504 (org-set-local 'org-lowest-priority (nth 1 prio))
4505 (org-set-local 'org-default-priority (nth 2 prio)))
4506 (and props (org-set-local 'org-local-properties (nreverse props)))
4507 (and drawers (org-set-local 'org-drawers drawers))
4508 (and arch (org-set-local 'org-archive-location arch))
4509 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4510 ;; Process the TODO keywords
4511 (unless kwds
4512 ;; Use the global values as if they had been given locally.
4513 (setq kwds (default-value 'org-todo-keywords))
4514 (if (stringp (car kwds))
4515 (setq kwds (list (cons org-todo-interpretation
4516 (default-value 'org-todo-keywords)))))
4517 (setq kwds (reverse kwds)))
4518 (setq kwds (nreverse kwds))
4519 (let (inter kws kw)
4520 (while (setq kws (pop kwds))
4521 (setq inter (pop kws) sep (member "|" kws)
4522 kws0 (delete "|" (copy-sequence kws))
4523 kwsa nil
4524 kws1 (mapcar
4525 (lambda (x)
4526 ;; 1 2
4527 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4528 (progn
4529 (setq kw (match-string 1 x)
4530 key (and (match-end 2) (match-string 2 x))
4531 log (org-extract-log-state-settings x))
4532 (push (cons kw (and key (string-to-char key))) kwsa)
4533 (and log (push log org-todo-log-states))
4535 (error "Invalid TODO keyword %s" x)))
4536 kws0)
4537 kwsa (if kwsa (append '((:startgroup))
4538 (nreverse kwsa)
4539 '((:endgroup))))
4540 hw (car kws1)
4541 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4542 tail (list inter hw (car dws) (org-last dws)))
4543 (add-to-list 'org-todo-heads hw 'append)
4544 (push kws1 org-todo-sets)
4545 (setq org-done-keywords (append org-done-keywords dws nil))
4546 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4547 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4548 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4549 (setq org-todo-sets (nreverse org-todo-sets)
4550 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4551 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4552 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4553 ;; Process the constants
4554 (when const
4555 (let (e cst)
4556 (while (setq e (pop const))
4557 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4558 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4559 (setq org-table-formula-constants-local cst)))
4561 ;; Process the tags.
4562 (when tags
4563 (let (e tgs)
4564 (while (setq e (pop tags))
4565 (cond
4566 ((equal e "{") (push '(:startgroup) tgs))
4567 ((equal e "}") (push '(:endgroup) tgs))
4568 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4569 (push (cons (match-string 1 e)
4570 (string-to-char (match-string 2 e)))
4571 tgs))
4572 (t (push (list e) tgs))))
4573 (org-set-local 'org-tag-alist nil)
4574 (while (setq e (pop tgs))
4575 (or (and (stringp (car e))
4576 (assoc (car e) org-tag-alist))
4577 (push e org-tag-alist))))))
4579 ;; Compute the regular expressions and other local variables
4580 (if (not org-done-keywords)
4581 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4582 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4583 (length org-scheduled-string)))
4584 org-drawer-regexp
4585 (concat "^[ \t]*:\\("
4586 (mapconcat 'regexp-quote org-drawers "\\|")
4587 "\\):[ \t]*$")
4588 org-not-done-keywords
4589 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4590 org-todo-regexp
4591 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4592 "\\|") "\\)\\>")
4593 org-not-done-regexp
4594 (concat "\\<\\("
4595 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4596 "\\)\\>")
4597 org-todo-line-regexp
4598 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4599 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4600 "\\)\\>\\)?[ \t]*\\(.*\\)")
4601 org-complex-heading-regexp
4602 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4603 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4604 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4605 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4606 org-nl-done-regexp
4607 (concat "\n\\*+[ \t]+"
4608 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4609 "\\)" "\\>")
4610 org-todo-line-tags-regexp
4611 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4612 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4613 (org-re
4614 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4615 org-looking-at-done-regexp
4616 (concat "^" "\\(?:"
4617 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4618 "\\>")
4619 org-deadline-regexp (concat "\\<" org-deadline-string)
4620 org-deadline-time-regexp
4621 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4622 org-deadline-line-regexp
4623 (concat "\\<\\(" org-deadline-string "\\).*")
4624 org-scheduled-regexp
4625 (concat "\\<" org-scheduled-string)
4626 org-scheduled-time-regexp
4627 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4628 org-closed-time-regexp
4629 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4630 org-keyword-time-regexp
4631 (concat "\\<\\(" org-scheduled-string
4632 "\\|" org-deadline-string
4633 "\\|" org-closed-string
4634 "\\|" org-clock-string "\\)"
4635 " *[[<]\\([^]>]+\\)[]>]")
4636 org-keyword-time-not-clock-regexp
4637 (concat "\\<\\(" org-scheduled-string
4638 "\\|" org-deadline-string
4639 "\\|" org-closed-string
4640 "\\)"
4641 " *[[<]\\([^]>]+\\)[]>]")
4642 org-maybe-keyword-time-regexp
4643 (concat "\\(\\<\\(" org-scheduled-string
4644 "\\|" org-deadline-string
4645 "\\|" org-closed-string
4646 "\\|" org-clock-string "\\)\\)?"
4647 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4648 org-planning-or-clock-line-re
4649 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4650 "\\|" org-deadline-string
4651 "\\|" org-closed-string "\\|" org-clock-string
4652 "\\)\\>\\)")
4654 (org-compute-latex-and-specials-regexp)
4655 (org-set-font-lock-defaults)))
4657 (defun org-extract-log-state-settings (x)
4658 "Extract the log state setting from a TODO keyword string.
4659 This will extract info from a string like \"WAIT(w@/!)\"."
4660 (let (kw key log1 log2)
4661 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4662 (setq kw (match-string 1 x)
4663 key (and (match-end 2) (match-string 2 x))
4664 log1 (and (match-end 3) (match-string 3 x))
4665 log2 (and (match-end 4) (match-string 4 x)))
4666 (and (or log1 log2)
4667 (list kw
4668 (and log1 (if (equal log1 "!") 'time 'note))
4669 (and log2 (if (equal log2 "!") 'time 'note)))))))
4671 (defun org-remove-keyword-keys (list)
4672 (mapcar (lambda (x)
4673 (if (string-match "(..?)$" x)
4674 (substring x 0 (match-beginning 0))
4676 list))
4678 ;; FIXME: this could be done much better, using second characters etc.
4679 (defun org-assign-fast-keys (alist)
4680 "Assign fast keys to a keyword-key alist.
4681 Respect keys that are already there."
4682 (let (new e k c c1 c2 (char ?a))
4683 (while (setq e (pop alist))
4684 (cond
4685 ((equal e '(:startgroup)) (push e new))
4686 ((equal e '(:endgroup)) (push e new))
4688 (setq k (car e) c2 nil)
4689 (if (cdr e)
4690 (setq c (cdr e))
4691 ;; automatically assign a character.
4692 (setq c1 (string-to-char
4693 (downcase (substring
4694 k (if (= (string-to-char k) ?@) 1 0)))))
4695 (if (or (rassoc c1 new) (rassoc c1 alist))
4696 (while (or (rassoc char new) (rassoc char alist))
4697 (setq char (1+ char)))
4698 (setq c2 c1))
4699 (setq c (or c2 char)))
4700 (push (cons k c) new))))
4701 (nreverse new)))
4703 ;;; Some variables ujsed in various places
4705 (defvar org-window-configuration nil
4706 "Used in various places to store a window configuration.")
4707 (defvar org-finish-function nil
4708 "Function to be called when `C-c C-c' is used.
4709 This is for getting out of special buffers like remember.")
4712 ;; FIXME: Occasionally check by commenting these, to make sure
4713 ;; no other functions uses these, forgetting to let-bind them.
4714 (defvar entry)
4715 (defvar state)
4716 (defvar last-state)
4717 (defvar date)
4718 (defvar description)
4720 ;; Defined somewhere in this file, but used before definition.
4721 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4722 (defvar org-agenda-buffer-name)
4723 (defvar org-agenda-undo-list)
4724 (defvar org-agenda-pending-undo-list)
4725 (defvar org-agenda-overriding-header)
4726 (defvar orgtbl-mode)
4727 (defvar org-html-entities)
4728 (defvar org-struct-menu)
4729 (defvar org-org-menu)
4730 (defvar org-tbl-menu)
4731 (defvar org-agenda-keymap)
4733 ;;;; Emacs/XEmacs compatibility
4735 ;; Overlay compatibility functions
4736 (defun org-make-overlay (beg end &optional buffer)
4737 (if (featurep 'xemacs)
4738 (make-extent beg end buffer)
4739 (make-overlay beg end buffer)))
4740 (defun org-delete-overlay (ovl)
4741 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4742 (defun org-detach-overlay (ovl)
4743 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4744 (defun org-move-overlay (ovl beg end &optional buffer)
4745 (if (featurep 'xemacs)
4746 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4747 (move-overlay ovl beg end buffer)))
4748 (defun org-overlay-put (ovl prop value)
4749 (if (featurep 'xemacs)
4750 (set-extent-property ovl prop value)
4751 (overlay-put ovl prop value)))
4752 (defun org-overlay-display (ovl text &optional face evap)
4753 "Make overlay OVL display TEXT with face FACE."
4754 (if (featurep 'xemacs)
4755 (let ((gl (make-glyph text)))
4756 (and face (set-glyph-face gl face))
4757 (set-extent-property ovl 'invisible t)
4758 (set-extent-property ovl 'end-glyph gl))
4759 (overlay-put ovl 'display text)
4760 (if face (overlay-put ovl 'face face))
4761 (if evap (overlay-put ovl 'evaporate t))))
4762 (defun org-overlay-before-string (ovl text &optional face evap)
4763 "Make overlay OVL display TEXT with face FACE."
4764 (if (featurep 'xemacs)
4765 (let ((gl (make-glyph text)))
4766 (and face (set-glyph-face gl face))
4767 (set-extent-property ovl 'begin-glyph gl))
4768 (if face (org-add-props text nil 'face face))
4769 (overlay-put ovl 'before-string text)
4770 (if evap (overlay-put ovl 'evaporate t))))
4771 (defun org-overlay-get (ovl prop)
4772 (if (featurep 'xemacs)
4773 (extent-property ovl prop)
4774 (overlay-get ovl prop)))
4775 (defun org-overlays-at (pos)
4776 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4777 (defun org-overlays-in (&optional start end)
4778 (if (featurep 'xemacs)
4779 (extent-list nil start end)
4780 (overlays-in start end)))
4781 (defun org-overlay-start (o)
4782 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4783 (defun org-overlay-end (o)
4784 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4785 (defun org-find-overlays (prop &optional pos delete)
4786 "Find all overlays specifying PROP at POS or point.
4787 If DELETE is non-nil, delete all those overlays."
4788 (let ((overlays (org-overlays-at (or pos (point))))
4789 ov found)
4790 (while (setq ov (pop overlays))
4791 (if (org-overlay-get ov prop)
4792 (if delete (org-delete-overlay ov) (push ov found))))
4793 found))
4795 ;; Region compatibility
4797 (defun org-add-hook (hook function &optional append local)
4798 "Add-hook, compatible with both Emacsen."
4799 (if (and local (featurep 'xemacs))
4800 (add-local-hook hook function append)
4801 (add-hook hook function append local)))
4803 (defvar org-ignore-region nil
4804 "To temporarily disable the active region.")
4806 (defun org-region-active-p ()
4807 "Is `transient-mark-mode' on and the region active?
4808 Works on both Emacs and XEmacs."
4809 (if org-ignore-region
4811 (if (featurep 'xemacs)
4812 (and zmacs-regions (region-active-p))
4813 (if (fboundp 'use-region-p)
4814 (use-region-p)
4815 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4817 ;; Invisibility compatibility
4819 (defun org-add-to-invisibility-spec (arg)
4820 "Add elements to `buffer-invisibility-spec'.
4821 See documentation for `buffer-invisibility-spec' for the kind of elements
4822 that can be added."
4823 (cond
4824 ((fboundp 'add-to-invisibility-spec)
4825 (add-to-invisibility-spec arg))
4826 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4827 (setq buffer-invisibility-spec (list arg)))
4829 (setq buffer-invisibility-spec
4830 (cons arg buffer-invisibility-spec)))))
4832 (defun org-remove-from-invisibility-spec (arg)
4833 "Remove elements from `buffer-invisibility-spec'."
4834 (if (fboundp 'remove-from-invisibility-spec)
4835 (remove-from-invisibility-spec arg)
4836 (if (consp buffer-invisibility-spec)
4837 (setq buffer-invisibility-spec
4838 (delete arg buffer-invisibility-spec)))))
4840 (defun org-in-invisibility-spec-p (arg)
4841 "Is ARG a member of `buffer-invisibility-spec'?"
4842 (if (consp buffer-invisibility-spec)
4843 (member arg buffer-invisibility-spec)
4844 nil))
4846 ;;;; Define the Org-mode
4848 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4849 (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."))
4852 ;; We use a before-change function to check if a table might need
4853 ;; an update.
4854 (defvar org-table-may-need-update t
4855 "Indicates that a table might need an update.
4856 This variable is set by `org-before-change-function'.
4857 `org-table-align' sets it back to nil.")
4858 (defvar org-mode-map)
4859 (defvar org-mode-hook nil)
4860 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4861 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4862 (defvar org-table-buffer-is-an nil)
4863 (defconst org-outline-regexp "\\*+ ")
4865 ;;;###autoload
4866 (define-derived-mode org-mode outline-mode "Org"
4867 "Outline-based notes management and organizer, alias
4868 \"Carsten's outline-mode for keeping track of everything.\"
4870 Org-mode develops organizational tasks around a NOTES file which
4871 contains information about projects as plain text. Org-mode is
4872 implemented on top of outline-mode, which is ideal to keep the content
4873 of large files well structured. It supports ToDo items, deadlines and
4874 time stamps, which magically appear in the diary listing of the Emacs
4875 calendar. Tables are easily created with a built-in table editor.
4876 Plain text URL-like links connect to websites, emails (VM), Usenet
4877 messages (Gnus), BBDB entries, and any files related to the project.
4878 For printing and sharing of notes, an Org-mode file (or a part of it)
4879 can be exported as a structured ASCII or HTML file.
4881 The following commands are available:
4883 \\{org-mode-map}"
4885 ;; Get rid of Outline menus, they are not needed
4886 ;; Need to do this here because define-derived-mode sets up
4887 ;; the keymap so late. Still, it is a waste to call this each time
4888 ;; we switch another buffer into org-mode.
4889 (if (featurep 'xemacs)
4890 (when (boundp 'outline-mode-menu-heading)
4891 ;; Assume this is Greg's port, it used easymenu
4892 (easy-menu-remove outline-mode-menu-heading)
4893 (easy-menu-remove outline-mode-menu-show)
4894 (easy-menu-remove outline-mode-menu-hide))
4895 (define-key org-mode-map [menu-bar headings] 'undefined)
4896 (define-key org-mode-map [menu-bar hide] 'undefined)
4897 (define-key org-mode-map [menu-bar show] 'undefined))
4899 (easy-menu-add org-org-menu)
4900 (easy-menu-add org-tbl-menu)
4901 (org-install-agenda-files-menu)
4902 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4903 (org-add-to-invisibility-spec '(org-cwidth))
4904 (when (featurep 'xemacs)
4905 (org-set-local 'line-move-ignore-invisible t))
4906 (org-set-local 'outline-regexp org-outline-regexp)
4907 (org-set-local 'outline-level 'org-outline-level)
4908 (when (and org-ellipsis
4909 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4910 (fboundp 'make-glyph-code))
4911 (unless org-display-table
4912 (setq org-display-table (make-display-table)))
4913 (set-display-table-slot
4914 org-display-table 4
4915 (vconcat (mapcar
4916 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4917 org-ellipsis)))
4918 (if (stringp org-ellipsis) org-ellipsis "..."))))
4919 (setq buffer-display-table org-display-table))
4920 (org-set-regexps-and-options)
4921 ;; Calc embedded
4922 (org-set-local 'calc-embedded-open-mode "# ")
4923 (modify-syntax-entry ?# "<")
4924 (modify-syntax-entry ?@ "w")
4925 (if org-startup-truncated (setq truncate-lines t))
4926 (org-set-local 'font-lock-unfontify-region-function
4927 'org-unfontify-region)
4928 ;; Activate before-change-function
4929 (org-set-local 'org-table-may-need-update t)
4930 (org-add-hook 'before-change-functions 'org-before-change-function nil
4931 'local)
4932 ;; Check for running clock before killing a buffer
4933 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4934 ;; Paragraphs and auto-filling
4935 (org-set-autofill-regexps)
4936 (setq indent-line-function 'org-indent-line-function)
4937 (org-update-radio-target-regexp)
4939 ;; Comment characters
4940 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4941 (org-set-local 'comment-padding " ")
4943 ;; Align options lines
4944 (org-set-local
4945 'align-mode-rules-list
4946 '((org-in-buffer-settings
4947 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4948 (modes . '(org-mode)))))
4950 ;; Imenu
4951 (org-set-local 'imenu-create-index-function
4952 'org-imenu-get-tree)
4954 ;; Make isearch reveal context
4955 (if (or (featurep 'xemacs)
4956 (not (boundp 'outline-isearch-open-invisible-function)))
4957 ;; Emacs 21 and XEmacs make use of the hook
4958 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4959 ;; Emacs 22 deals with this through a special variable
4960 (org-set-local 'outline-isearch-open-invisible-function
4961 (lambda (&rest ignore) (org-show-context 'isearch))))
4963 ;; If empty file that did not turn on org-mode automatically, make it to.
4964 (if (and org-insert-mode-line-in-empty-file
4965 (interactive-p)
4966 (= (point-min) (point-max)))
4967 (insert "# -*- mode: org -*-\n\n"))
4969 (unless org-inhibit-startup
4970 (when org-startup-align-all-tables
4971 (let ((bmp (buffer-modified-p)))
4972 (org-table-map-tables 'org-table-align)
4973 (set-buffer-modified-p bmp)))
4974 (org-cycle-hide-drawers 'all)
4975 (cond
4976 ((eq org-startup-folded t)
4977 (org-cycle '(4)))
4978 ((eq org-startup-folded 'content)
4979 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4980 (org-cycle '(4)) (org-cycle '(4)))))))
4982 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4984 (defsubst org-call-with-arg (command arg)
4985 "Call COMMAND interactively, but pretend prefix are was ARG."
4986 (let ((current-prefix-arg arg)) (call-interactively command)))
4988 (defsubst org-current-line (&optional pos)
4989 (save-excursion
4990 (and pos (goto-char pos))
4991 ;; works also in narrowed buffer, because we start at 1, not point-min
4992 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4994 (defun org-current-time ()
4995 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4996 (if (> org-time-stamp-rounding-minutes 0)
4997 (let ((r org-time-stamp-rounding-minutes)
4998 (time (decode-time)))
4999 (apply 'encode-time
5000 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5001 (nthcdr 2 time))))
5002 (current-time)))
5004 (defun org-add-props (string plist &rest props)
5005 "Add text properties to entire string, from beginning to end.
5006 PLIST may be a list of properties, PROPS are individual properties and values
5007 that will be added to PLIST. Returns the string that was modified."
5008 (add-text-properties
5009 0 (length string) (if props (append plist props) plist) string)
5010 string)
5011 (put 'org-add-props 'lisp-indent-function 2)
5014 ;;;; Font-Lock stuff, including the activators
5016 (defvar org-mouse-map (make-sparse-keymap))
5017 (org-defkey org-mouse-map
5018 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5019 (org-defkey org-mouse-map
5020 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5021 (when org-mouse-1-follows-link
5022 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5023 (when org-tab-follows-link
5024 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5025 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5026 (when org-return-follows-link
5027 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5028 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5030 (require 'font-lock)
5032 (defconst org-non-link-chars "]\t\n\r<>")
5033 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5034 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5035 (defvar org-link-re-with-space nil
5036 "Matches a link with spaces, optional angular brackets around it.")
5037 (defvar org-link-re-with-space2 nil
5038 "Matches a link with spaces, optional angular brackets around it.")
5039 (defvar org-angle-link-re nil
5040 "Matches link with angular brackets, spaces are allowed.")
5041 (defvar org-plain-link-re nil
5042 "Matches plain link, without spaces.")
5043 (defvar org-bracket-link-regexp nil
5044 "Matches a link in double brackets.")
5045 (defvar org-bracket-link-analytic-regexp nil
5046 "Regular expression used to analyze links.
5047 Here is what the match groups contain after a match:
5048 1: http:
5049 2: http
5050 3: path
5051 4: [desc]
5052 5: desc")
5053 (defvar org-any-link-re nil
5054 "Regular expression matching any link.")
5056 (defun org-make-link-regexps ()
5057 "Update the link regular expressions.
5058 This should be called after the variable `org-link-types' has changed."
5059 (setq org-link-re-with-space
5060 (concat
5061 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5062 "\\([^" org-non-link-chars " ]"
5063 "[^" org-non-link-chars "]*"
5064 "[^" org-non-link-chars " ]\\)>?")
5065 org-link-re-with-space2
5066 (concat
5067 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5068 "\\([^" org-non-link-chars " ]"
5069 "[^]\t\n\r]*"
5070 "[^" org-non-link-chars " ]\\)>?")
5071 org-angle-link-re
5072 (concat
5073 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5074 "\\([^" org-non-link-chars " ]"
5075 "[^" org-non-link-chars "]*"
5076 "\\)>")
5077 org-plain-link-re
5078 (concat
5079 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5080 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5081 org-bracket-link-regexp
5082 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5083 org-bracket-link-analytic-regexp
5084 (concat
5085 "\\[\\["
5086 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5087 "\\([^]]+\\)"
5088 "\\]"
5089 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5090 "\\]")
5091 org-any-link-re
5092 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5093 org-angle-link-re "\\)\\|\\("
5094 org-plain-link-re "\\)")))
5096 (org-make-link-regexps)
5098 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5099 "Regular expression for fast time stamp matching.")
5100 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5101 "Regular expression for fast time stamp matching.")
5102 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5103 "Regular expression matching time strings for analysis.
5104 This one does not require the space after the date.")
5105 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5106 "Regular expression matching time strings for analysis.")
5107 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5108 "Regular expression matching time stamps, with groups.")
5109 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5110 "Regular expression matching time stamps (also [..]), with groups.")
5111 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5112 "Regular expression matching a time stamp range.")
5113 (defconst org-tr-regexp-both
5114 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5115 "Regular expression matching a time stamp range.")
5116 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5117 org-ts-regexp "\\)?")
5118 "Regular expression matching a time stamp or time stamp range.")
5119 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5120 org-ts-regexp-both "\\)?")
5121 "Regular expression matching a time stamp or time stamp range.
5122 The time stamps may be either active or inactive.")
5124 (defvar org-emph-face nil)
5126 (defun org-do-emphasis-faces (limit)
5127 "Run through the buffer and add overlays to links."
5128 (let (rtn)
5129 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5130 (if (not (= (char-after (match-beginning 3))
5131 (char-after (match-beginning 4))))
5132 (progn
5133 (setq rtn t)
5134 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5135 'face
5136 (nth 1 (assoc (match-string 3)
5137 org-emphasis-alist)))
5138 (add-text-properties (match-beginning 2) (match-end 2)
5139 '(font-lock-multiline t))
5140 (when org-hide-emphasis-markers
5141 (add-text-properties (match-end 4) (match-beginning 5)
5142 '(invisible org-link))
5143 (add-text-properties (match-beginning 3) (match-end 3)
5144 '(invisible org-link)))))
5145 (backward-char 1))
5146 rtn))
5148 (defun org-emphasize (&optional char)
5149 "Insert or change an emphasis, i.e. a font like bold or italic.
5150 If there is an active region, change that region to a new emphasis.
5151 If there is no region, just insert the marker characters and position
5152 the cursor between them.
5153 CHAR should be either the marker character, or the first character of the
5154 HTML tag associated with that emphasis. If CHAR is a space, the means
5155 to remove the emphasis of the selected region.
5156 If char is not given (for example in an interactive call) it
5157 will be prompted for."
5158 (interactive)
5159 (let ((eal org-emphasis-alist) e det
5160 (erc org-emphasis-regexp-components)
5161 (prompt "")
5162 (string "") beg end move tag c s)
5163 (if (org-region-active-p)
5164 (setq beg (region-beginning) end (region-end)
5165 string (buffer-substring beg end))
5166 (setq move t))
5168 (while (setq e (pop eal))
5169 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5170 c (aref tag 0))
5171 (push (cons c (string-to-char (car e))) det)
5172 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5173 (substring tag 1)))))
5174 (unless char
5175 (message "%s" (concat "Emphasis marker or tag:" prompt))
5176 (setq char (read-char-exclusive)))
5177 (setq char (or (cdr (assoc char det)) char))
5178 (if (equal char ?\ )
5179 (setq s "" move nil)
5180 (unless (assoc (char-to-string char) org-emphasis-alist)
5181 (error "No such emphasis marker: \"%c\"" char))
5182 (setq s (char-to-string char)))
5183 (while (and (> (length string) 1)
5184 (equal (substring string 0 1) (substring string -1))
5185 (assoc (substring string 0 1) org-emphasis-alist))
5186 (setq string (substring string 1 -1)))
5187 (setq string (concat s string s))
5188 (if beg (delete-region beg end))
5189 (unless (or (bolp)
5190 (string-match (concat "[" (nth 0 erc) "\n]")
5191 (char-to-string (char-before (point)))))
5192 (insert " "))
5193 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5194 (char-to-string (char-after (point))))
5195 (insert " ") (backward-char 1))
5196 (insert string)
5197 (and move (backward-char 1))))
5199 (defconst org-nonsticky-props
5200 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5203 (defun org-activate-plain-links (limit)
5204 "Run through the buffer and add overlays to links."
5205 (catch 'exit
5206 (let (f)
5207 (while (re-search-forward org-plain-link-re limit t)
5208 (setq f (get-text-property (match-beginning 0) 'face))
5209 (if (or (eq f 'org-tag)
5210 (and (listp f) (memq 'org-tag f)))
5212 (add-text-properties (match-beginning 0) (match-end 0)
5213 (list 'mouse-face 'highlight
5214 'rear-nonsticky org-nonsticky-props
5215 'keymap org-mouse-map
5217 (throw 'exit t))))))
5219 (defun org-activate-code (limit)
5220 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5221 (unless (get-text-property (match-beginning 1) 'face)
5222 (remove-text-properties (match-beginning 0) (match-end 0)
5223 '(display t invisible t intangible t))
5224 t)))
5226 (defun org-activate-angle-links (limit)
5227 "Run through the buffer and add overlays to links."
5228 (if (re-search-forward org-angle-link-re limit t)
5229 (progn
5230 (add-text-properties (match-beginning 0) (match-end 0)
5231 (list 'mouse-face 'highlight
5232 'rear-nonsticky org-nonsticky-props
5233 'keymap org-mouse-map
5235 t)))
5237 (defmacro org-maybe-intangible (props)
5238 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5239 In emacs 21, invisible text is not avoided by the command loop, so the
5240 intangible property is needed to make sure point skips this text.
5241 In Emacs 22, this is not necessary. The intangible text property has
5242 led to problems with flyspell. These problems are fixed in flyspell.el,
5243 but we still avoid setting the property in Emacs 22 and later.
5244 We use a macro so that the test can happen at compilation time."
5245 (if (< emacs-major-version 22)
5246 `(append '(intangible t) ,props)
5247 props))
5249 (defun org-activate-bracket-links (limit)
5250 "Run through the buffer and add overlays to bracketed links."
5251 (if (re-search-forward org-bracket-link-regexp limit t)
5252 (let* ((help (concat "LINK: "
5253 (org-match-string-no-properties 1)))
5254 ;; FIXME: above we should remove the escapes.
5255 ;; but that requires another match, protecting match data,
5256 ;; a lot of overhead for font-lock.
5257 (ip (org-maybe-intangible
5258 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5259 'keymap org-mouse-map 'mouse-face 'highlight
5260 'font-lock-multiline t 'help-echo help)))
5261 (vp (list 'rear-nonsticky org-nonsticky-props
5262 'keymap org-mouse-map 'mouse-face 'highlight
5263 ' font-lock-multiline t 'help-echo help)))
5264 ;; We need to remove the invisible property here. Table narrowing
5265 ;; may have made some of this invisible.
5266 (remove-text-properties (match-beginning 0) (match-end 0)
5267 '(invisible nil))
5268 (if (match-end 3)
5269 (progn
5270 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5271 (add-text-properties (match-beginning 3) (match-end 3) vp)
5272 (add-text-properties (match-end 3) (match-end 0) ip))
5273 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5274 (add-text-properties (match-beginning 1) (match-end 1) vp)
5275 (add-text-properties (match-end 1) (match-end 0) ip))
5276 t)))
5278 (defun org-activate-dates (limit)
5279 "Run through the buffer and add overlays to dates."
5280 (if (re-search-forward org-tsr-regexp-both limit t)
5281 (progn
5282 (add-text-properties (match-beginning 0) (match-end 0)
5283 (list 'mouse-face 'highlight
5284 'rear-nonsticky org-nonsticky-props
5285 'keymap org-mouse-map))
5286 (when org-display-custom-times
5287 (if (match-end 3)
5288 (org-display-custom-time (match-beginning 3) (match-end 3)))
5289 (org-display-custom-time (match-beginning 1) (match-end 1)))
5290 t)))
5292 (defvar org-target-link-regexp nil
5293 "Regular expression matching radio targets in plain text.")
5294 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5295 "Regular expression matching a link target.")
5296 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5297 "Regular expression matching a radio target.")
5298 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5299 "Regular expression matching any target.")
5301 (defun org-activate-target-links (limit)
5302 "Run through the buffer and add overlays to target matches."
5303 (when org-target-link-regexp
5304 (let ((case-fold-search t))
5305 (if (re-search-forward org-target-link-regexp limit t)
5306 (progn
5307 (add-text-properties (match-beginning 0) (match-end 0)
5308 (list 'mouse-face 'highlight
5309 'rear-nonsticky org-nonsticky-props
5310 'keymap org-mouse-map
5311 'help-echo "Radio target link"
5312 'org-linked-text t))
5313 t)))))
5315 (defun org-update-radio-target-regexp ()
5316 "Find all radio targets in this file and update the regular expression."
5317 (interactive)
5318 (when (memq 'radio org-activate-links)
5319 (setq org-target-link-regexp
5320 (org-make-target-link-regexp (org-all-targets 'radio)))
5321 (org-restart-font-lock)))
5323 (defun org-hide-wide-columns (limit)
5324 (let (s e)
5325 (setq s (text-property-any (point) (or limit (point-max))
5326 'org-cwidth t))
5327 (when s
5328 (setq e (next-single-property-change s 'org-cwidth))
5329 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5330 (goto-char e)
5331 t)))
5333 (defvar org-latex-and-specials-regexp nil
5334 "Regular expression for highlighting export special stuff.")
5335 (defvar org-match-substring-regexp)
5336 (defvar org-match-substring-with-braces-regexp)
5337 (defvar org-export-html-special-string-regexps)
5339 (defun org-compute-latex-and-specials-regexp ()
5340 "Compute regular expression for stuff treated specially by exporters."
5341 (if (not org-highlight-latex-fragments-and-specials)
5342 (org-set-local 'org-latex-and-specials-regexp nil)
5343 (let*
5344 ((matchers (plist-get org-format-latex-options :matchers))
5345 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5346 org-latex-regexps)))
5347 (options (org-combine-plists (org-default-export-plist)
5348 (org-infile-export-plist)))
5349 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5350 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5351 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5352 (org-export-html-expand (plist-get options :expand-quoted-html))
5353 (org-export-with-special-strings (plist-get options :special-strings))
5354 (re-sub
5355 (cond
5356 ((equal org-export-with-sub-superscripts '{})
5357 (list org-match-substring-with-braces-regexp))
5358 (org-export-with-sub-superscripts
5359 (list org-match-substring-regexp))
5360 (t nil)))
5361 (re-latex
5362 (if org-export-with-LaTeX-fragments
5363 (mapcar (lambda (x) (nth 1 x)) latexs)))
5364 (re-macros
5365 (if org-export-with-TeX-macros
5366 (list (concat "\\\\"
5367 (regexp-opt
5368 (append (mapcar 'car org-html-entities)
5369 (if (boundp 'org-latex-entities)
5370 org-latex-entities nil))
5371 'words))) ; FIXME
5373 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5374 (re-special (if org-export-with-special-strings
5375 (mapcar (lambda (x) (car x))
5376 org-export-html-special-string-regexps)))
5377 (re-rest
5378 (delq nil
5379 (list
5380 (if org-export-html-expand "@<[^>\n]+>")
5381 ))))
5382 (org-set-local
5383 'org-latex-and-specials-regexp
5384 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5385 re-rest) "\\|")))))
5387 (defface org-latex-and-export-specials
5388 (let ((font (cond ((assq :inherit custom-face-attributes)
5389 '(:inherit underline))
5390 (t '(:underline t)))))
5391 `((((class grayscale) (background light))
5392 (:foreground "DimGray" ,@font))
5393 (((class grayscale) (background dark))
5394 (:foreground "LightGray" ,@font))
5395 (((class color) (background light))
5396 (:foreground "SaddleBrown"))
5397 (((class color) (background dark))
5398 (:foreground "burlywood"))
5399 (t (,@font))))
5400 "Face used to highlight math latex and other special exporter stuff."
5401 :group 'org-faces)
5403 (defun org-do-latex-and-special-faces (limit)
5404 "Run through the buffer and add overlays to links."
5405 (when org-latex-and-specials-regexp
5406 (let (rtn d)
5407 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5408 limit t))
5409 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5410 'face))
5411 '(org-code org-verbatim underline)))
5412 (progn
5413 (setq rtn t
5414 d (cond ((member (char-after (1+ (match-beginning 0)))
5415 '(?_ ?^)) 1)
5416 (t 0)))
5417 (font-lock-prepend-text-property
5418 (+ d (match-beginning 0)) (match-end 0)
5419 'face 'org-latex-and-export-specials)
5420 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5421 '(font-lock-multiline t)))))
5422 rtn)))
5424 (defun org-restart-font-lock ()
5425 "Restart font-lock-mode, to force refontification."
5426 (when (and (boundp 'font-lock-mode) font-lock-mode)
5427 (font-lock-mode -1)
5428 (font-lock-mode 1)))
5430 (defun org-all-targets (&optional radio)
5431 "Return a list of all targets in this file.
5432 With optional argument RADIO, only find radio targets."
5433 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5434 rtn)
5435 (save-excursion
5436 (goto-char (point-min))
5437 (while (re-search-forward re nil t)
5438 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5439 rtn)))
5441 (defun org-make-target-link-regexp (targets)
5442 "Make regular expression matching all strings in TARGETS.
5443 The regular expression finds the targets also if there is a line break
5444 between words."
5445 (and targets
5446 (concat
5447 "\\<\\("
5448 (mapconcat
5449 (lambda (x)
5450 (while (string-match " +" x)
5451 (setq x (replace-match "\\s-+" t t x)))
5453 targets
5454 "\\|")
5455 "\\)\\>")))
5457 (defun org-activate-tags (limit)
5458 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5459 (progn
5460 (add-text-properties (match-beginning 1) (match-end 1)
5461 (list 'mouse-face 'highlight
5462 'rear-nonsticky org-nonsticky-props
5463 'keymap org-mouse-map))
5464 t)))
5466 (defun org-outline-level ()
5467 (save-excursion
5468 (looking-at outline-regexp)
5469 (if (match-beginning 1)
5470 (+ (org-get-string-indentation (match-string 1)) 1000)
5471 (1- (- (match-end 0) (match-beginning 0))))))
5473 (defvar org-font-lock-keywords nil)
5475 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5476 "Regular expression matching a property line.")
5478 (defun org-set-font-lock-defaults ()
5479 (let* ((em org-fontify-emphasized-text)
5480 (lk org-activate-links)
5481 (org-font-lock-extra-keywords
5482 (list
5483 ;; Headlines
5484 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5485 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5486 ;; Table lines
5487 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5488 (1 'org-table t))
5489 ;; Table internals
5490 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5491 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5492 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5493 ;; Drawers
5494 (list org-drawer-regexp '(0 'org-special-keyword t))
5495 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5496 ;; Properties
5497 (list org-property-re
5498 '(1 'org-special-keyword t)
5499 '(3 'org-property-value t))
5500 (if org-format-transports-properties-p
5501 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5502 ;; Links
5503 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5504 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5505 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5506 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5507 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5508 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5509 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5510 '(org-hide-wide-columns (0 nil append))
5511 ;; TODO lines
5512 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5513 '(1 (org-get-todo-face 1) t))
5514 ;; DONE
5515 (if org-fontify-done-headline
5516 (list (concat "^[*]+ +\\<\\("
5517 (mapconcat 'regexp-quote org-done-keywords "\\|")
5518 "\\)\\(.*\\)")
5519 '(2 'org-headline-done t))
5520 nil)
5521 ;; Priorities
5522 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5523 ;; Special keywords
5524 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5525 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5526 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5527 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5528 ;; Emphasis
5529 (if em
5530 (if (featurep 'xemacs)
5531 '(org-do-emphasis-faces (0 nil append))
5532 '(org-do-emphasis-faces)))
5533 ;; Checkboxes
5534 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5535 2 'bold prepend)
5536 (if org-provide-checkbox-statistics
5537 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5538 (0 (org-get-checkbox-statistics-face) t)))
5539 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5540 '(1 'org-archived prepend))
5541 ;; Specials
5542 '(org-do-latex-and-special-faces)
5543 ;; Code
5544 '(org-activate-code (1 'org-code t))
5545 ;; COMMENT
5546 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5547 "\\|" org-quote-string "\\)\\>")
5548 '(1 'org-special-keyword t))
5549 '("^#.*" (0 'font-lock-comment-face t))
5551 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5552 ;; Now set the full font-lock-keywords
5553 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5554 (org-set-local 'font-lock-defaults
5555 '(org-font-lock-keywords t nil nil backward-paragraph))
5556 (kill-local-variable 'font-lock-keywords) nil))
5558 (defvar org-m nil)
5559 (defvar org-l nil)
5560 (defvar org-f nil)
5561 (defun org-get-level-face (n)
5562 "Get the right face for match N in font-lock matching of healdines."
5563 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5564 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5565 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5566 (cond
5567 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5568 ((eq n 2) org-f)
5569 (t (if org-level-color-stars-only nil org-f))))
5571 (defun org-get-todo-face (kwd)
5572 "Get the right face for a TODO keyword KWD.
5573 If KWD is a number, get the corresponding match group."
5574 (if (numberp kwd) (setq kwd (match-string kwd)))
5575 (or (cdr (assoc kwd org-todo-keyword-faces))
5576 (and (member kwd org-done-keywords) 'org-done)
5577 'org-todo))
5579 (defun org-unfontify-region (beg end &optional maybe_loudly)
5580 "Remove fontification and activation overlays from links."
5581 (font-lock-default-unfontify-region beg end)
5582 (let* ((buffer-undo-list t)
5583 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5584 (inhibit-modification-hooks t)
5585 deactivate-mark buffer-file-name buffer-file-truename)
5586 (remove-text-properties beg end
5587 '(mouse-face t keymap t org-linked-text t
5588 invisible t intangible t))))
5590 ;;;; Visibility cycling, including org-goto and indirect buffer
5592 ;;; Cycling
5594 (defvar org-cycle-global-status nil)
5595 (make-variable-buffer-local 'org-cycle-global-status)
5596 (defvar org-cycle-subtree-status nil)
5597 (make-variable-buffer-local 'org-cycle-subtree-status)
5599 ;;;###autoload
5600 (defun org-cycle (&optional arg)
5601 "Visibility cycling for Org-mode.
5603 - When this function is called with a prefix argument, rotate the entire
5604 buffer through 3 states (global cycling)
5605 1. OVERVIEW: Show only top-level headlines.
5606 2. CONTENTS: Show all headlines of all levels, but no body text.
5607 3. SHOW ALL: Show everything.
5609 - When point is at the beginning of a headline, rotate the subtree started
5610 by this line through 3 different states (local cycling)
5611 1. FOLDED: Only the main headline is shown.
5612 2. CHILDREN: The main headline and the direct children are shown.
5613 From this state, you can move to one of the children
5614 and zoom in further.
5615 3. SUBTREE: Show the entire subtree, including body text.
5617 - When there is a numeric prefix, go up to a heading with level ARG, do
5618 a `show-subtree' and return to the previous cursor position. If ARG
5619 is negative, go up that many levels.
5621 - When point is not at the beginning of a headline, execute
5622 `indent-relative', like TAB normally does. See the option
5623 `org-cycle-emulate-tab' for details.
5625 - Special case: if point is at the beginning of the buffer and there is
5626 no headline in line 1, this function will act as if called with prefix arg.
5627 But only if also the variable `org-cycle-global-at-bob' is t."
5628 (interactive "P")
5629 (let* ((outline-regexp
5630 (if (and (org-mode-p) org-cycle-include-plain-lists)
5631 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5632 outline-regexp))
5633 (bob-special (and org-cycle-global-at-bob (bobp)
5634 (not (looking-at outline-regexp))))
5635 (org-cycle-hook
5636 (if bob-special
5637 (delq 'org-optimize-window-after-visibility-change
5638 (copy-sequence org-cycle-hook))
5639 org-cycle-hook))
5640 (pos (point)))
5642 (if (or bob-special (equal arg '(4)))
5643 ;; special case: use global cycling
5644 (setq arg t))
5646 (cond
5648 ((org-at-table-p 'any)
5649 ;; Enter the table or move to the next field in the table
5650 (or (org-table-recognize-table.el)
5651 (progn
5652 (if arg (org-table-edit-field t)
5653 (org-table-justify-field-maybe)
5654 (call-interactively 'org-table-next-field)))))
5656 ((eq arg t) ;; Global cycling
5658 (cond
5659 ((and (eq last-command this-command)
5660 (eq org-cycle-global-status 'overview))
5661 ;; We just created the overview - now do table of contents
5662 ;; This can be slow in very large buffers, so indicate action
5663 (message "CONTENTS...")
5664 (org-content)
5665 (message "CONTENTS...done")
5666 (setq org-cycle-global-status 'contents)
5667 (run-hook-with-args 'org-cycle-hook 'contents))
5669 ((and (eq last-command this-command)
5670 (eq org-cycle-global-status 'contents))
5671 ;; We just showed the table of contents - now show everything
5672 (show-all)
5673 (message "SHOW ALL")
5674 (setq org-cycle-global-status 'all)
5675 (run-hook-with-args 'org-cycle-hook 'all))
5678 ;; Default action: go to overview
5679 (org-overview)
5680 (message "OVERVIEW")
5681 (setq org-cycle-global-status 'overview)
5682 (run-hook-with-args 'org-cycle-hook 'overview))))
5684 ((and org-drawers org-drawer-regexp
5685 (save-excursion
5686 (beginning-of-line 1)
5687 (looking-at org-drawer-regexp)))
5688 ;; Toggle block visibility
5689 (org-flag-drawer
5690 (not (get-char-property (match-end 0) 'invisible))))
5692 ((integerp arg)
5693 ;; Show-subtree, ARG levels up from here.
5694 (save-excursion
5695 (org-back-to-heading)
5696 (outline-up-heading (if (< arg 0) (- arg)
5697 (- (funcall outline-level) arg)))
5698 (org-show-subtree)))
5700 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5701 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5702 ;; At a heading: rotate between three different views
5703 (org-back-to-heading)
5704 (let ((goal-column 0) eoh eol eos)
5705 ;; First, some boundaries
5706 (save-excursion
5707 (org-back-to-heading)
5708 (save-excursion
5709 (beginning-of-line 2)
5710 (while (and (not (eobp)) ;; this is like `next-line'
5711 (get-char-property (1- (point)) 'invisible))
5712 (beginning-of-line 2)) (setq eol (point)))
5713 (outline-end-of-heading) (setq eoh (point))
5714 (org-end-of-subtree t)
5715 (unless (eobp)
5716 (skip-chars-forward " \t\n")
5717 (beginning-of-line 1) ; in case this is an item
5719 (setq eos (1- (point))))
5720 ;; Find out what to do next and set `this-command'
5721 (cond
5722 ((= eos eoh)
5723 ;; Nothing is hidden behind this heading
5724 (message "EMPTY ENTRY")
5725 (setq org-cycle-subtree-status nil)
5726 (save-excursion
5727 (goto-char eos)
5728 (outline-next-heading)
5729 (if (org-invisible-p) (org-flag-heading nil))))
5730 ((or (>= eol eos)
5731 (not (string-match "\\S-" (buffer-substring eol eos))))
5732 ;; Entire subtree is hidden in one line: open it
5733 (org-show-entry)
5734 (show-children)
5735 (message "CHILDREN")
5736 (save-excursion
5737 (goto-char eos)
5738 (outline-next-heading)
5739 (if (org-invisible-p) (org-flag-heading nil)))
5740 (setq org-cycle-subtree-status 'children)
5741 (run-hook-with-args 'org-cycle-hook 'children))
5742 ((and (eq last-command this-command)
5743 (eq org-cycle-subtree-status 'children))
5744 ;; We just showed the children, now show everything.
5745 (org-show-subtree)
5746 (message "SUBTREE")
5747 (setq org-cycle-subtree-status 'subtree)
5748 (run-hook-with-args 'org-cycle-hook 'subtree))
5750 ;; Default action: hide the subtree.
5751 (hide-subtree)
5752 (message "FOLDED")
5753 (setq org-cycle-subtree-status 'folded)
5754 (run-hook-with-args 'org-cycle-hook 'folded)))))
5756 ;; TAB emulation
5757 (buffer-read-only (org-back-to-heading))
5759 ((org-try-cdlatex-tab))
5761 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5762 (or (not (bolp))
5763 (not (looking-at outline-regexp))))
5764 (call-interactively (global-key-binding "\t")))
5766 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5767 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5768 (or (and (eq org-cycle-emulate-tab 'white)
5769 (= (match-end 0) (point-at-eol)))
5770 (and (eq org-cycle-emulate-tab 'whitestart)
5771 (>= (match-end 0) pos))))
5773 (eq org-cycle-emulate-tab t))
5774 ; (if (and (looking-at "[ \n\r\t]")
5775 ; (string-match "^[ \t]*$" (buffer-substring
5776 ; (point-at-bol) (point))))
5777 ; (progn
5778 ; (beginning-of-line 1)
5779 ; (and (looking-at "[ \t]+") (replace-match ""))))
5780 (call-interactively (global-key-binding "\t")))
5782 (t (save-excursion
5783 (org-back-to-heading)
5784 (org-cycle))))))
5786 ;;;###autoload
5787 (defun org-global-cycle (&optional arg)
5788 "Cycle the global visibility. For details see `org-cycle'."
5789 (interactive "P")
5790 (let ((org-cycle-include-plain-lists
5791 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5792 (if (integerp arg)
5793 (progn
5794 (show-all)
5795 (hide-sublevels arg)
5796 (setq org-cycle-global-status 'contents))
5797 (org-cycle '(4)))))
5799 (defun org-overview ()
5800 "Switch to overview mode, shoing only top-level headlines.
5801 Really, this shows all headlines with level equal or greater than the level
5802 of the first headline in the buffer. This is important, because if the
5803 first headline is not level one, then (hide-sublevels 1) gives confusing
5804 results."
5805 (interactive)
5806 (let ((level (save-excursion
5807 (goto-char (point-min))
5808 (if (re-search-forward (concat "^" outline-regexp) nil t)
5809 (progn
5810 (goto-char (match-beginning 0))
5811 (funcall outline-level))))))
5812 (and level (hide-sublevels level))))
5814 (defun org-content (&optional arg)
5815 "Show all headlines in the buffer, like a table of contents.
5816 With numerical argument N, show content up to level N."
5817 (interactive "P")
5818 (save-excursion
5819 ;; Visit all headings and show their offspring
5820 (and (integerp arg) (org-overview))
5821 (goto-char (point-max))
5822 (catch 'exit
5823 (while (and (progn (condition-case nil
5824 (outline-previous-visible-heading 1)
5825 (error (goto-char (point-min))))
5827 (looking-at outline-regexp))
5828 (if (integerp arg)
5829 (show-children (1- arg))
5830 (show-branches))
5831 (if (bobp) (throw 'exit nil))))))
5834 (defun org-optimize-window-after-visibility-change (state)
5835 "Adjust the window after a change in outline visibility.
5836 This function is the default value of the hook `org-cycle-hook'."
5837 (when (get-buffer-window (current-buffer))
5838 (cond
5839 ; ((eq state 'overview) (org-first-headline-recenter 1))
5840 ; ((eq state 'overview) (org-beginning-of-line))
5841 ((eq state 'content) nil)
5842 ((eq state 'all) nil)
5843 ((eq state 'folded) nil)
5844 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5845 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5847 (defun org-compact-display-after-subtree-move ()
5848 (let (beg end)
5849 (save-excursion
5850 (if (org-up-heading-safe)
5851 (progn
5852 (hide-subtree)
5853 (show-entry)
5854 (show-children)
5855 (org-cycle-show-empty-lines 'children)
5856 (org-cycle-hide-drawers 'children))
5857 (org-overview)))))
5859 (defun org-cycle-show-empty-lines (state)
5860 "Show empty lines above all visible headlines.
5861 The region to be covered depends on STATE when called through
5862 `org-cycle-hook'. Lisp program can use t for STATE to get the
5863 entire buffer covered. Note that an empty line is only shown if there
5864 are at least `org-cycle-separator-lines' empty lines before the headeline."
5865 (when (> org-cycle-separator-lines 0)
5866 (save-excursion
5867 (let* ((n org-cycle-separator-lines)
5868 (re (cond
5869 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5870 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5871 (t (let ((ns (number-to-string (- n 2))))
5872 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5873 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5874 beg end)
5875 (cond
5876 ((memq state '(overview contents t))
5877 (setq beg (point-min) end (point-max)))
5878 ((memq state '(children folded))
5879 (setq beg (point) end (progn (org-end-of-subtree t t)
5880 (beginning-of-line 2)
5881 (point)))))
5882 (when beg
5883 (goto-char beg)
5884 (while (re-search-forward re end t)
5885 (if (not (get-char-property (match-end 1) 'invisible))
5886 (outline-flag-region
5887 (match-beginning 1) (match-end 1) nil)))))))
5888 ;; Never hide empty lines at the end of the file.
5889 (save-excursion
5890 (goto-char (point-max))
5891 (outline-previous-heading)
5892 (outline-end-of-heading)
5893 (if (and (looking-at "[ \t\n]+")
5894 (= (match-end 0) (point-max)))
5895 (outline-flag-region (point) (match-end 0) nil))))
5897 (defun org-subtree-end-visible-p ()
5898 "Is the end of the current subtree visible?"
5899 (pos-visible-in-window-p
5900 (save-excursion (org-end-of-subtree t) (point))))
5902 (defun org-first-headline-recenter (&optional N)
5903 "Move cursor to the first headline and recenter the headline.
5904 Optional argument N means, put the headline into the Nth line of the window."
5905 (goto-char (point-min))
5906 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5907 (beginning-of-line)
5908 (recenter (prefix-numeric-value N))))
5910 ;;; Org-goto
5912 (defvar org-goto-window-configuration nil)
5913 (defvar org-goto-marker nil)
5914 (defvar org-goto-map
5915 (let ((map (make-sparse-keymap)))
5916 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5917 (while (setq cmd (pop cmds))
5918 (substitute-key-definition cmd cmd map global-map)))
5919 (suppress-keymap map)
5920 (org-defkey map "\C-m" 'org-goto-ret)
5921 (org-defkey map [(return)] 'org-goto-ret)
5922 (org-defkey map [(left)] 'org-goto-left)
5923 (org-defkey map [(right)] 'org-goto-right)
5924 (org-defkey map [(control ?g)] 'org-goto-quit)
5925 (org-defkey map "\C-i" 'org-cycle)
5926 (org-defkey map [(tab)] 'org-cycle)
5927 (org-defkey map [(down)] 'outline-next-visible-heading)
5928 (org-defkey map [(up)] 'outline-previous-visible-heading)
5929 (if org-goto-auto-isearch
5930 (if (fboundp 'define-key-after)
5931 (define-key-after map [t] 'org-goto-local-auto-isearch)
5932 nil)
5933 (org-defkey map "q" 'org-goto-quit)
5934 (org-defkey map "n" 'outline-next-visible-heading)
5935 (org-defkey map "p" 'outline-previous-visible-heading)
5936 (org-defkey map "f" 'outline-forward-same-level)
5937 (org-defkey map "b" 'outline-backward-same-level)
5938 (org-defkey map "u" 'outline-up-heading))
5939 (org-defkey map "/" 'org-occur)
5940 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5941 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5942 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5943 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5944 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5945 map))
5947 (defconst org-goto-help
5948 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5949 RET=jump to location [Q]uit and return to previous location
5950 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5952 (defvar org-goto-start-pos) ; dynamically scoped parameter
5954 (defun org-goto (&optional alternative-interface)
5955 "Look up a different location in the current file, keeping current visibility.
5957 When you want look-up or go to a different location in a document, the
5958 fastest way is often to fold the entire buffer and then dive into the tree.
5959 This method has the disadvantage, that the previous location will be folded,
5960 which may not be what you want.
5962 This command works around this by showing a copy of the current buffer
5963 in an indirect buffer, in overview mode. You can dive into the tree in
5964 that copy, use org-occur and incremental search to find a location.
5965 When pressing RET or `Q', the command returns to the original buffer in
5966 which the visibility is still unchanged. After RET is will also jump to
5967 the location selected in the indirect buffer and expose the
5968 the headline hierarchy above."
5969 (interactive "P")
5970 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
5971 (org-refile-use-outline-path t)
5972 (interface
5973 (if (not alternative-interface)
5974 org-goto-interface
5975 (if (eq org-goto-interface 'outline)
5976 'outline-path-completion
5977 'outline)))
5978 (org-goto-start-pos (point))
5979 (selected-point
5980 (if (eq interface 'outline)
5981 (car (org-get-location (current-buffer) org-goto-help))
5982 (nth 3 (org-refile-get-location "Goto: ")))))
5983 (if selected-point
5984 (progn
5985 (org-mark-ring-push org-goto-start-pos)
5986 (goto-char selected-point)
5987 (if (or (org-invisible-p) (org-invisible-p2))
5988 (org-show-context 'org-goto)))
5989 (message "Quit"))))
5991 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5992 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5993 (defvar org-goto-local-auto-isearch-map) ; defined below
5995 (defun org-get-location (buf help)
5996 "Let the user select a location in the Org-mode buffer BUF.
5997 This function uses a recursive edit. It returns the selected position
5998 or nil."
5999 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6000 (isearch-hide-immediately nil)
6001 (isearch-search-fun-function
6002 (lambda () 'org-goto-local-search-forward-headings))
6003 (org-goto-selected-point org-goto-exit-command))
6004 (save-excursion
6005 (save-window-excursion
6006 (delete-other-windows)
6007 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6008 (switch-to-buffer
6009 (condition-case nil
6010 (make-indirect-buffer (current-buffer) "*org-goto*")
6011 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6012 (with-output-to-temp-buffer "*Help*"
6013 (princ help))
6014 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6015 (setq buffer-read-only nil)
6016 (let ((org-startup-truncated t)
6017 (org-startup-folded nil)
6018 (org-startup-align-all-tables nil))
6019 (org-mode)
6020 (org-overview))
6021 (setq buffer-read-only t)
6022 (if (and (boundp 'org-goto-start-pos)
6023 (integer-or-marker-p org-goto-start-pos))
6024 (let ((org-show-hierarchy-above t)
6025 (org-show-siblings t)
6026 (org-show-following-heading t))
6027 (goto-char org-goto-start-pos)
6028 (and (org-invisible-p) (org-show-context)))
6029 (goto-char (point-min)))
6030 (org-beginning-of-line)
6031 (message "Select location and press RET")
6032 (use-local-map org-goto-map)
6033 (recursive-edit)
6035 (kill-buffer "*org-goto*")
6036 (cons org-goto-selected-point org-goto-exit-command)))
6038 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6039 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6040 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6041 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6043 (defun org-goto-local-search-forward-headings (string bound noerror)
6044 "Search and make sure that anu matches are in headlines."
6045 (catch 'return
6046 (while (search-forward string bound noerror)
6047 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6048 (and (member :headline context)
6049 (not (member :tags context))))
6050 (throw 'return (point))))))
6052 (defun org-goto-local-auto-isearch ()
6053 "Start isearch."
6054 (interactive)
6055 (goto-char (point-min))
6056 (let ((keys (this-command-keys)))
6057 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6058 (isearch-mode t)
6059 (isearch-process-search-char (string-to-char keys)))))
6061 (defun org-goto-ret (&optional arg)
6062 "Finish `org-goto' by going to the new location."
6063 (interactive "P")
6064 (setq org-goto-selected-point (point)
6065 org-goto-exit-command 'return)
6066 (throw 'exit nil))
6068 (defun org-goto-left ()
6069 "Finish `org-goto' by going to the new location."
6070 (interactive)
6071 (if (org-on-heading-p)
6072 (progn
6073 (beginning-of-line 1)
6074 (setq org-goto-selected-point (point)
6075 org-goto-exit-command 'left)
6076 (throw 'exit nil))
6077 (error "Not on a heading")))
6079 (defun org-goto-right ()
6080 "Finish `org-goto' by going to the new location."
6081 (interactive)
6082 (if (org-on-heading-p)
6083 (progn
6084 (setq org-goto-selected-point (point)
6085 org-goto-exit-command 'right)
6086 (throw 'exit nil))
6087 (error "Not on a heading")))
6089 (defun org-goto-quit ()
6090 "Finish `org-goto' without cursor motion."
6091 (interactive)
6092 (setq org-goto-selected-point nil)
6093 (setq org-goto-exit-command 'quit)
6094 (throw 'exit nil))
6096 ;;; Indirect buffer display of subtrees
6098 (defvar org-indirect-dedicated-frame nil
6099 "This is the frame being used for indirect tree display.")
6100 (defvar org-last-indirect-buffer nil)
6102 (defun org-tree-to-indirect-buffer (&optional arg)
6103 "Create indirect buffer and narrow it to current subtree.
6104 With numerical prefix ARG, go up to this level and then take that tree.
6105 If ARG is negative, go up that many levels.
6106 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6107 indirect buffer previously made with this command, to avoid proliferation of
6108 indirect buffers. However, when you call the command with a `C-u' prefix, or
6109 when `org-indirect-buffer-display' is `new-frame', the last buffer
6110 is kept so that you can work with several indirect buffers at the same time.
6111 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6112 requests that a new frame be made for the new buffer, so that the dedicated
6113 frame is not changed."
6114 (interactive "P")
6115 (let ((cbuf (current-buffer))
6116 (cwin (selected-window))
6117 (pos (point))
6118 beg end level heading ibuf)
6119 (save-excursion
6120 (org-back-to-heading t)
6121 (when (numberp arg)
6122 (setq level (org-outline-level))
6123 (if (< arg 0) (setq arg (+ level arg)))
6124 (while (> (setq level (org-outline-level)) arg)
6125 (outline-up-heading 1 t)))
6126 (setq beg (point)
6127 heading (org-get-heading))
6128 (org-end-of-subtree t) (setq end (point)))
6129 (if (and (buffer-live-p org-last-indirect-buffer)
6130 (not (eq org-indirect-buffer-display 'new-frame))
6131 (not arg))
6132 (kill-buffer org-last-indirect-buffer))
6133 (setq ibuf (org-get-indirect-buffer cbuf)
6134 org-last-indirect-buffer ibuf)
6135 (cond
6136 ((or (eq org-indirect-buffer-display 'new-frame)
6137 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6138 (select-frame (make-frame))
6139 (delete-other-windows)
6140 (switch-to-buffer ibuf)
6141 (org-set-frame-title heading))
6142 ((eq org-indirect-buffer-display 'dedicated-frame)
6143 (raise-frame
6144 (select-frame (or (and org-indirect-dedicated-frame
6145 (frame-live-p org-indirect-dedicated-frame)
6146 org-indirect-dedicated-frame)
6147 (setq org-indirect-dedicated-frame (make-frame)))))
6148 (delete-other-windows)
6149 (switch-to-buffer ibuf)
6150 (org-set-frame-title (concat "Indirect: " heading)))
6151 ((eq org-indirect-buffer-display 'current-window)
6152 (switch-to-buffer ibuf))
6153 ((eq org-indirect-buffer-display 'other-window)
6154 (pop-to-buffer ibuf))
6155 (t (error "Invalid value.")))
6156 (if (featurep 'xemacs)
6157 (save-excursion (org-mode) (turn-on-font-lock)))
6158 (narrow-to-region beg end)
6159 (show-all)
6160 (goto-char pos)
6161 (and (window-live-p cwin) (select-window cwin))))
6163 (defun org-get-indirect-buffer (&optional buffer)
6164 (setq buffer (or buffer (current-buffer)))
6165 (let ((n 1) (base (buffer-name buffer)) bname)
6166 (while (buffer-live-p
6167 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6168 (setq n (1+ n)))
6169 (condition-case nil
6170 (make-indirect-buffer buffer bname 'clone)
6171 (error (make-indirect-buffer buffer bname)))))
6173 (defun org-set-frame-title (title)
6174 "Set the title of the current frame to the string TITLE."
6175 ;; FIXME: how to name a single frame in XEmacs???
6176 (unless (featurep 'xemacs)
6177 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6179 ;;;; Structure editing
6181 ;;; Inserting headlines
6183 (defun org-insert-heading (&optional force-heading)
6184 "Insert a new heading or item with same depth at point.
6185 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6186 If point is at the beginning of a headline, insert a sibling before the
6187 current headline. If point is not at the beginning, do not split the line,
6188 but create the new hedline after the current line."
6189 (interactive "P")
6190 (if (= (buffer-size) 0)
6191 (insert "\n* ")
6192 (when (or force-heading (not (org-insert-item)))
6193 (let* ((head (save-excursion
6194 (condition-case nil
6195 (progn
6196 (org-back-to-heading)
6197 (match-string 0))
6198 (error "*"))))
6199 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6200 pos)
6201 (cond
6202 ((and (org-on-heading-p) (bolp)
6203 (or (bobp)
6204 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6205 ;; insert before the current line
6206 (open-line (if blank 2 1)))
6207 ((and (bolp)
6208 (or (bobp)
6209 (save-excursion
6210 (backward-char 1) (not (org-invisible-p)))))
6211 ;; insert right here
6212 nil)
6214 ;; in the middle of the line
6215 (org-show-entry)
6216 (if (and (org-on-heading-p)
6217 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6218 ;; protect the tags
6219 (let ((tags (match-string 2)) pos)
6220 (delete-region (match-beginning 1) (match-end 1))
6221 (setq pos (point-at-bol))
6222 (newline (if blank 2 1))
6223 (save-excursion
6224 (goto-char pos)
6225 (end-of-line 1)
6226 (insert " " tags)
6227 (org-set-tags nil 'align)))
6228 (newline (if blank 2 1)))))
6229 (insert head) (just-one-space)
6230 (setq pos (point))
6231 (end-of-line 1)
6232 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6233 (run-hooks 'org-insert-heading-hook)))))
6235 (defun org-insert-heading-after-current ()
6236 "Insert a new heading with same level as current, after current subtree."
6237 (interactive)
6238 (org-back-to-heading)
6239 (org-insert-heading)
6240 (org-move-subtree-down)
6241 (end-of-line 1))
6243 (defun org-insert-todo-heading (arg)
6244 "Insert a new heading with the same level and TODO state as current heading.
6245 If the heading has no TODO state, or if the state is DONE, use the first
6246 state (TODO by default). Also with prefix arg, force first state."
6247 (interactive "P")
6248 (when (not (org-insert-item 'checkbox))
6249 (org-insert-heading)
6250 (save-excursion
6251 (org-back-to-heading)
6252 (outline-previous-heading)
6253 (looking-at org-todo-line-regexp))
6254 (if (or arg
6255 (not (match-beginning 2))
6256 (member (match-string 2) org-done-keywords))
6257 (insert (car org-todo-keywords-1) " ")
6258 (insert (match-string 2) " "))))
6260 (defun org-insert-subheading (arg)
6261 "Insert a new subheading and demote it.
6262 Works for outline headings and for plain lists alike."
6263 (interactive "P")
6264 (org-insert-heading arg)
6265 (cond
6266 ((org-on-heading-p) (org-do-demote))
6267 ((org-at-item-p) (org-indent-item 1))))
6269 (defun org-insert-todo-subheading (arg)
6270 "Insert a new subheading with TODO keyword or checkbox and demote it.
6271 Works for outline headings and for plain lists alike."
6272 (interactive "P")
6273 (org-insert-todo-heading arg)
6274 (cond
6275 ((org-on-heading-p) (org-do-demote))
6276 ((org-at-item-p) (org-indent-item 1))))
6278 ;;; Promotion and Demotion
6280 (defun org-promote-subtree ()
6281 "Promote the entire subtree.
6282 See also `org-promote'."
6283 (interactive)
6284 (save-excursion
6285 (org-map-tree 'org-promote))
6286 (org-fix-position-after-promote))
6288 (defun org-demote-subtree ()
6289 "Demote the entire subtree. See `org-demote'.
6290 See also `org-promote'."
6291 (interactive)
6292 (save-excursion
6293 (org-map-tree 'org-demote))
6294 (org-fix-position-after-promote))
6297 (defun org-do-promote ()
6298 "Promote the current heading higher up the tree.
6299 If the region is active in `transient-mark-mode', promote all headings
6300 in the region."
6301 (interactive)
6302 (save-excursion
6303 (if (org-region-active-p)
6304 (org-map-region 'org-promote (region-beginning) (region-end))
6305 (org-promote)))
6306 (org-fix-position-after-promote))
6308 (defun org-do-demote ()
6309 "Demote the current heading lower down the tree.
6310 If the region is active in `transient-mark-mode', demote all headings
6311 in the region."
6312 (interactive)
6313 (save-excursion
6314 (if (org-region-active-p)
6315 (org-map-region 'org-demote (region-beginning) (region-end))
6316 (org-demote)))
6317 (org-fix-position-after-promote))
6319 (defun org-fix-position-after-promote ()
6320 "Make sure that after pro/demotion cursor position is right."
6321 (let ((pos (point)))
6322 (when (save-excursion
6323 (beginning-of-line 1)
6324 (looking-at org-todo-line-regexp)
6325 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6326 (cond ((eobp) (insert " "))
6327 ((eolp) (insert " "))
6328 ((equal (char-after) ?\ ) (forward-char 1))))))
6330 (defun org-reduced-level (l)
6331 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6333 (defun org-get-legal-level (level &optional change)
6334 "Rectify a level change under the influence of `org-odd-levels-only'
6335 LEVEL is a current level, CHANGE is by how much the level should be
6336 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6337 even level numbers will become the next higher odd number."
6338 (if org-odd-levels-only
6339 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6340 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6341 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6342 (max 1 (+ level change))))
6344 (defun org-promote ()
6345 "Promote the current heading higher up the tree.
6346 If the region is active in `transient-mark-mode', promote all headings
6347 in the region."
6348 (org-back-to-heading t)
6349 (let* ((level (save-match-data (funcall outline-level)))
6350 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6351 (diff (abs (- level (length up-head) -1))))
6352 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6353 (replace-match up-head nil t)
6354 ;; Fixup tag positioning
6355 (and org-auto-align-tags (org-set-tags nil t))
6356 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6358 (defun org-demote ()
6359 "Demote the current heading lower down the tree.
6360 If the region is active in `transient-mark-mode', demote all headings
6361 in the region."
6362 (org-back-to-heading t)
6363 (let* ((level (save-match-data (funcall outline-level)))
6364 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6365 (diff (abs (- level (length down-head) -1))))
6366 (replace-match down-head nil t)
6367 ;; Fixup tag positioning
6368 (and org-auto-align-tags (org-set-tags nil t))
6369 (if org-adapt-indentation (org-fixup-indentation diff))))
6371 (defun org-map-tree (fun)
6372 "Call FUN for every heading underneath the current one."
6373 (org-back-to-heading)
6374 (let ((level (funcall outline-level)))
6375 (save-excursion
6376 (funcall fun)
6377 (while (and (progn
6378 (outline-next-heading)
6379 (> (funcall outline-level) level))
6380 (not (eobp)))
6381 (funcall fun)))))
6383 (defun org-map-region (fun beg end)
6384 "Call FUN for every heading between BEG and END."
6385 (let ((org-ignore-region t))
6386 (save-excursion
6387 (setq end (copy-marker end))
6388 (goto-char beg)
6389 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6390 (< (point) end))
6391 (funcall fun))
6392 (while (and (progn
6393 (outline-next-heading)
6394 (< (point) end))
6395 (not (eobp)))
6396 (funcall fun)))))
6398 (defun org-fixup-indentation (diff)
6399 "Change the indentation in the current entry by DIFF
6400 However, if any line in the current entry has no indentation, or if it
6401 would end up with no indentation after the change, nothing at all is done."
6402 (save-excursion
6403 (let ((end (save-excursion (outline-next-heading)
6404 (point-marker)))
6405 (prohibit (if (> diff 0)
6406 "^\\S-"
6407 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6408 col)
6409 (unless (save-excursion (end-of-line 1)
6410 (re-search-forward prohibit end t))
6411 (while (and (< (point) end)
6412 (re-search-forward "^[ \t]+" end t))
6413 (goto-char (match-end 0))
6414 (setq col (current-column))
6415 (if (< diff 0) (replace-match ""))
6416 (indent-to (+ diff col))))
6417 (move-marker end nil))))
6419 (defun org-convert-to-odd-levels ()
6420 "Convert an org-mode file with all levels allowed to one with odd levels.
6421 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6422 level 5 etc."
6423 (interactive)
6424 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6425 (let ((org-odd-levels-only nil) n)
6426 (save-excursion
6427 (goto-char (point-min))
6428 (while (re-search-forward "^\\*\\*+ " nil t)
6429 (setq n (- (length (match-string 0)) 2))
6430 (while (>= (setq n (1- n)) 0)
6431 (org-demote))
6432 (end-of-line 1))))))
6435 (defun org-convert-to-oddeven-levels ()
6436 "Convert an org-mode file with only odd levels to one with odd and even levels.
6437 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6438 section with an even level, conversion would destroy the structure of the file. An error
6439 is signaled in this case."
6440 (interactive)
6441 (goto-char (point-min))
6442 ;; First check if there are no even levels
6443 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6444 (org-show-context t)
6445 (error "Not all levels are odd in this file. Conversion not possible."))
6446 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6447 (let ((org-odd-levels-only nil) n)
6448 (save-excursion
6449 (goto-char (point-min))
6450 (while (re-search-forward "^\\*\\*+ " nil t)
6451 (setq n (/ (1- (length (match-string 0))) 2))
6452 (while (>= (setq n (1- n)) 0)
6453 (org-promote))
6454 (end-of-line 1))))))
6456 (defun org-tr-level (n)
6457 "Make N odd if required."
6458 (if org-odd-levels-only (1+ (/ n 2)) n))
6460 ;;; Vertical tree motion, cutting and pasting of subtrees
6462 (defun org-move-subtree-up (&optional arg)
6463 "Move the current subtree up past ARG headlines of the same level."
6464 (interactive "p")
6465 (org-move-subtree-down (- (prefix-numeric-value arg))))
6467 (defun org-move-subtree-down (&optional arg)
6468 "Move the current subtree down past ARG headlines of the same level."
6469 (interactive "p")
6470 (setq arg (prefix-numeric-value arg))
6471 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6472 'outline-get-last-sibling))
6473 (ins-point (make-marker))
6474 (cnt (abs arg))
6475 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6476 ;; Select the tree
6477 (org-back-to-heading)
6478 (setq beg0 (point))
6479 (save-excursion
6480 (setq ne-beg (org-back-over-empty-lines))
6481 (setq beg (point)))
6482 (save-match-data
6483 (save-excursion (outline-end-of-heading)
6484 (setq folded (org-invisible-p)))
6485 (outline-end-of-subtree))
6486 (outline-next-heading)
6487 (setq ne-end (org-back-over-empty-lines))
6488 (setq end (point))
6489 (goto-char beg0)
6490 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6491 ;; include less whitespace
6492 (save-excursion
6493 (goto-char beg)
6494 (forward-line (- ne-beg ne-end))
6495 (setq beg (point))))
6496 ;; Find insertion point, with error handling
6497 (while (> cnt 0)
6498 (or (and (funcall movfunc) (looking-at outline-regexp))
6499 (progn (goto-char beg0)
6500 (error "Cannot move past superior level or buffer limit")))
6501 (setq cnt (1- cnt)))
6502 (if (> arg 0)
6503 ;; Moving forward - still need to move over subtree
6504 (progn (org-end-of-subtree t t)
6505 (save-excursion
6506 (org-back-over-empty-lines)
6507 (or (bolp) (newline)))))
6508 (setq ne-ins (org-back-over-empty-lines))
6509 (move-marker ins-point (point))
6510 (setq txt (buffer-substring beg end))
6511 (delete-region beg end)
6512 (outline-flag-region (1- beg) beg nil)
6513 (outline-flag-region (1- (point)) (point) nil)
6514 (insert txt)
6515 (or (bolp) (insert "\n"))
6516 (setq ins-end (point))
6517 (goto-char ins-point)
6518 (org-skip-whitespace)
6519 (when (and (< arg 0)
6520 (org-first-sibling-p)
6521 (> ne-ins ne-beg))
6522 ;; Move whitespace back to beginning
6523 (save-excursion
6524 (goto-char ins-end)
6525 (let ((kill-whole-line t))
6526 (kill-line (- ne-ins ne-beg)) (point)))
6527 (insert (make-string (- ne-ins ne-beg) ?\n)))
6528 (move-marker ins-point nil)
6529 (org-compact-display-after-subtree-move)
6530 (unless folded
6531 (org-show-entry)
6532 (show-children)
6533 (org-cycle-hide-drawers 'children))))
6535 (defvar org-subtree-clip ""
6536 "Clipboard for cut and paste of subtrees.
6537 This is actually only a copy of the kill, because we use the normal kill
6538 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6540 (defvar org-subtree-clip-folded nil
6541 "Was the last copied subtree folded?
6542 This is used to fold the tree back after pasting.")
6544 (defun org-cut-subtree (&optional n)
6545 "Cut the current subtree into the clipboard.
6546 With prefix arg N, cut this many sequential subtrees.
6547 This is a short-hand for marking the subtree and then cutting it."
6548 (interactive "p")
6549 (org-copy-subtree n 'cut))
6551 (defun org-copy-subtree (&optional n cut)
6552 "Cut the current subtree into the clipboard.
6553 With prefix arg N, cut this many sequential subtrees.
6554 This is a short-hand for marking the subtree and then copying it.
6555 If CUT is non-nil, actually cut the subtree."
6556 (interactive "p")
6557 (let (beg end folded (beg0 (point)))
6558 (if (interactive-p)
6559 (org-back-to-heading nil) ; take what looks like a subtree
6560 (org-back-to-heading t)) ; take what is really there
6561 (org-back-over-empty-lines)
6562 (setq beg (point))
6563 (skip-chars-forward " \t\r\n")
6564 (save-match-data
6565 (save-excursion (outline-end-of-heading)
6566 (setq folded (org-invisible-p)))
6567 (condition-case nil
6568 (outline-forward-same-level (1- n))
6569 (error nil))
6570 (org-end-of-subtree t t))
6571 (org-back-over-empty-lines)
6572 (setq end (point))
6573 (goto-char beg0)
6574 (when (> end beg)
6575 (setq org-subtree-clip-folded folded)
6576 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6577 (setq org-subtree-clip (current-kill 0))
6578 (message "%s: Subtree(s) with %d characters"
6579 (if cut "Cut" "Copied")
6580 (length org-subtree-clip)))))
6582 (defun org-paste-subtree (&optional level tree)
6583 "Paste the clipboard as a subtree, with modification of headline level.
6584 The entire subtree is promoted or demoted in order to match a new headline
6585 level. By default, the new level is derived from the visible headings
6586 before and after the insertion point, and taken to be the inferior headline
6587 level of the two. So if the previous visible heading is level 3 and the
6588 next is level 4 (or vice versa), level 4 will be used for insertion.
6589 This makes sure that the subtree remains an independent subtree and does
6590 not swallow low level entries.
6592 You can also force a different level, either by using a numeric prefix
6593 argument, or by inserting the heading marker by hand. For example, if the
6594 cursor is after \"*****\", then the tree will be shifted to level 5.
6596 If you want to insert the tree as is, just use \\[yank].
6598 If optional TREE is given, use this text instead of the kill ring."
6599 (interactive "P")
6600 (unless (org-kill-is-subtree-p tree)
6601 (error "%s"
6602 (substitute-command-keys
6603 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6604 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6605 (^re (concat "^\\(" outline-regexp "\\)"))
6606 (re (concat "\\(" outline-regexp "\\)"))
6607 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6609 (old-level (if (string-match ^re txt)
6610 (- (match-end 0) (match-beginning 0) 1)
6611 -1))
6612 (force-level (cond (level (prefix-numeric-value level))
6613 ((string-match
6614 ^re_ (buffer-substring (point-at-bol) (point)))
6615 (- (match-end 1) (match-beginning 1)))
6616 (t nil)))
6617 (previous-level (save-excursion
6618 (condition-case nil
6619 (progn
6620 (outline-previous-visible-heading 1)
6621 (if (looking-at re)
6622 (- (match-end 0) (match-beginning 0) 1)
6624 (error 1))))
6625 (next-level (save-excursion
6626 (condition-case nil
6627 (progn
6628 (or (looking-at outline-regexp)
6629 (outline-next-visible-heading 1))
6630 (if (looking-at re)
6631 (- (match-end 0) (match-beginning 0) 1)
6633 (error 1))))
6634 (new-level (or force-level (max previous-level next-level)))
6635 (shift (if (or (= old-level -1)
6636 (= new-level -1)
6637 (= old-level new-level))
6639 (- new-level old-level)))
6640 (delta (if (> shift 0) -1 1))
6641 (func (if (> shift 0) 'org-demote 'org-promote))
6642 (org-odd-levels-only nil)
6643 beg end)
6644 ;; Remove the forced level indicator
6645 (if force-level
6646 (delete-region (point-at-bol) (point)))
6647 ;; Paste
6648 (beginning-of-line 1)
6649 (org-back-over-empty-lines) ;; FIXME: correct fix????
6650 (setq beg (point))
6651 (insert-before-markers txt) ;; FIXME: correct fix????
6652 (unless (string-match "\n\\'" txt) (insert "\n"))
6653 (setq end (point))
6654 (goto-char beg)
6655 (skip-chars-forward " \t\n\r")
6656 (setq beg (point))
6657 ;; Shift if necessary
6658 (unless (= shift 0)
6659 (save-restriction
6660 (narrow-to-region beg end)
6661 (while (not (= shift 0))
6662 (org-map-region func (point-min) (point-max))
6663 (setq shift (+ delta shift)))
6664 (goto-char (point-min))))
6665 (when (interactive-p)
6666 (message "Clipboard pasted as level %d subtree" new-level))
6667 (if (and kill-ring
6668 (eq org-subtree-clip (current-kill 0))
6669 org-subtree-clip-folded)
6670 ;; The tree was folded before it was killed/copied
6671 (hide-subtree))))
6673 (defun org-kill-is-subtree-p (&optional txt)
6674 "Check if the current kill is an outline subtree, or a set of trees.
6675 Returns nil if kill does not start with a headline, or if the first
6676 headline level is not the largest headline level in the tree.
6677 So this will actually accept several entries of equal levels as well,
6678 which is OK for `org-paste-subtree'.
6679 If optional TXT is given, check this string instead of the current kill."
6680 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6681 (start-level (and kill
6682 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6683 org-outline-regexp "\\)")
6684 kill)
6685 (- (match-end 2) (match-beginning 2) 1)))
6686 (re (concat "^" org-outline-regexp))
6687 (start (1+ (match-beginning 2))))
6688 (if (not start-level)
6689 (progn
6690 nil) ;; does not even start with a heading
6691 (catch 'exit
6692 (while (setq start (string-match re kill (1+ start)))
6693 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6694 (throw 'exit nil)))
6695 t))))
6697 (defun org-narrow-to-subtree ()
6698 "Narrow buffer to the current subtree."
6699 (interactive)
6700 (save-excursion
6701 (save-match-data
6702 (narrow-to-region
6703 (progn (org-back-to-heading) (point))
6704 (progn (org-end-of-subtree t t) (point))))))
6707 ;;; Outline Sorting
6709 (defun org-sort (with-case)
6710 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6711 Optional argument WITH-CASE means sort case-sensitively."
6712 (interactive "P")
6713 (if (org-at-table-p)
6714 (org-call-with-arg 'org-table-sort-lines with-case)
6715 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6717 (defvar org-priority-regexp) ; defined later in the file
6719 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6720 "Sort entries on a certain level of an outline tree.
6721 If there is an active region, the entries in the region are sorted.
6722 Else, if the cursor is before the first entry, sort the top-level items.
6723 Else, the children of the entry at point are sorted.
6725 Sorting can be alphabetically, numerically, and by date/time as given by
6726 the first time stamp in the entry. The command prompts for the sorting
6727 type unless it has been given to the function through the SORTING-TYPE
6728 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6729 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6730 called with point at the beginning of the record. It must return either
6731 a string or a number that should serve as the sorting key for that record.
6733 Comparing entries ignores case by default. However, with an optional argument
6734 WITH-CASE, the sorting considers case as well."
6735 (interactive "P")
6736 (let ((case-func (if with-case 'identity 'downcase))
6737 start beg end stars re re2
6738 txt what tmp plain-list-p)
6739 ;; Find beginning and end of region to sort
6740 (cond
6741 ((org-region-active-p)
6742 ;; we will sort the region
6743 (setq end (region-end)
6744 what "region")
6745 (goto-char (region-beginning))
6746 (if (not (org-on-heading-p)) (outline-next-heading))
6747 (setq start (point)))
6748 ((org-at-item-p)
6749 ;; we will sort this plain list
6750 (org-beginning-of-item-list) (setq start (point))
6751 (org-end-of-item-list) (setq end (point))
6752 (goto-char start)
6753 (setq plain-list-p t
6754 what "plain list"))
6755 ((or (org-on-heading-p)
6756 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6757 ;; we will sort the children of the current headline
6758 (org-back-to-heading)
6759 (setq start (point)
6760 end (progn (org-end-of-subtree t t)
6761 (org-back-over-empty-lines)
6762 (point))
6763 what "children")
6764 (goto-char start)
6765 (show-subtree)
6766 (outline-next-heading))
6768 ;; we will sort the top-level entries in this file
6769 (goto-char (point-min))
6770 (or (org-on-heading-p) (outline-next-heading))
6771 (setq start (point) end (point-max) what "top-level")
6772 (goto-char start)
6773 (show-all)))
6775 (setq beg (point))
6776 (if (>= beg end) (error "Nothing to sort"))
6778 (unless plain-list-p
6779 (looking-at "\\(\\*+\\)")
6780 (setq stars (match-string 1)
6781 re (concat "^" (regexp-quote stars) " +")
6782 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6783 txt (buffer-substring beg end))
6784 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6785 (if (and (not (equal stars "*")) (string-match re2 txt))
6786 (error "Region to sort contains a level above the first entry")))
6788 (unless sorting-type
6789 (message
6790 (if plain-list-p
6791 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6792 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6793 what)
6794 (setq sorting-type (read-char-exclusive))
6796 (and (= (downcase sorting-type) ?f)
6797 (setq getkey-func
6798 (completing-read "Sort using function: "
6799 obarray 'fboundp t nil nil))
6800 (setq getkey-func (intern getkey-func)))
6802 (and (= (downcase sorting-type) ?r)
6803 (setq property
6804 (completing-read "Property: "
6805 (mapcar 'list (org-buffer-property-keys t))
6806 nil t))))
6808 (message "Sorting entries...")
6810 (save-restriction
6811 (narrow-to-region start end)
6813 (let ((dcst (downcase sorting-type))
6814 (now (current-time)))
6815 (sort-subr
6816 (/= dcst sorting-type)
6817 ;; This function moves to the beginning character of the "record" to
6818 ;; be sorted.
6819 (if plain-list-p
6820 (lambda nil
6821 (if (org-at-item-p) t (goto-char (point-max))))
6822 (lambda nil
6823 (if (re-search-forward re nil t)
6824 (goto-char (match-beginning 0))
6825 (goto-char (point-max)))))
6826 ;; This function moves to the last character of the "record" being
6827 ;; sorted.
6828 (if plain-list-p
6829 'org-end-of-item
6830 (lambda nil
6831 (save-match-data
6832 (condition-case nil
6833 (outline-forward-same-level 1)
6834 (error
6835 (goto-char (point-max)))))))
6837 ;; This function returns the value that gets sorted against.
6838 (if plain-list-p
6839 (lambda nil
6840 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6841 (cond
6842 ((= dcst ?n)
6843 (string-to-number (buffer-substring (match-end 0)
6844 (point-at-eol))))
6845 ((= dcst ?a)
6846 (buffer-substring (match-end 0) (point-at-eol)))
6847 ((= dcst ?t)
6848 (if (re-search-forward org-ts-regexp
6849 (point-at-eol) t)
6850 (org-time-string-to-time (match-string 0))
6851 now))
6852 ((= dcst ?f)
6853 (if getkey-func
6854 (progn
6855 (setq tmp (funcall getkey-func))
6856 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6857 tmp)
6858 (error "Invalid key function `%s'" getkey-func)))
6859 (t (error "Invalid sorting type `%c'" sorting-type)))))
6860 (lambda nil
6861 (cond
6862 ((= dcst ?n)
6863 (if (looking-at outline-regexp)
6864 (string-to-number (buffer-substring (match-end 0)
6865 (point-at-eol)))
6866 nil))
6867 ((= dcst ?a)
6868 (funcall case-func (buffer-substring (point-at-bol)
6869 (point-at-eol))))
6870 ((= dcst ?t)
6871 (if (re-search-forward org-ts-regexp
6872 (save-excursion
6873 (forward-line 2)
6874 (point)) t)
6875 (org-time-string-to-time (match-string 0))
6876 now))
6877 ((= dcst ?p)
6878 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6879 (string-to-char (match-string 2))
6880 org-default-priority))
6881 ((= dcst ?r)
6882 (or (org-entry-get nil property) ""))
6883 ((= dcst ?f)
6884 (if getkey-func
6885 (progn
6886 (setq tmp (funcall getkey-func))
6887 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6888 tmp)
6889 (error "Invalid key function `%s'" getkey-func)))
6890 (t (error "Invalid sorting type `%c'" sorting-type)))))
6892 (cond
6893 ((= dcst ?a) 'string<)
6894 ((= dcst ?t) 'time-less-p)
6895 (t nil)))))
6896 (message "Sorting entries...done")))
6898 (defun org-do-sort (table what &optional with-case sorting-type)
6899 "Sort TABLE of WHAT according to SORTING-TYPE.
6900 The user will be prompted for the SORTING-TYPE if the call to this
6901 function does not specify it. WHAT is only for the prompt, to indicate
6902 what is being sorted. The sorting key will be extracted from
6903 the car of the elements of the table.
6904 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6905 (unless sorting-type
6906 (message
6907 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6908 what)
6909 (setq sorting-type (read-char-exclusive)))
6910 (let ((dcst (downcase sorting-type))
6911 extractfun comparefun)
6912 ;; Define the appropriate functions
6913 (cond
6914 ((= dcst ?n)
6915 (setq extractfun 'string-to-number
6916 comparefun (if (= dcst sorting-type) '< '>)))
6917 ((= dcst ?a)
6918 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6919 (lambda(x) (downcase (org-sort-remove-invisible x))))
6920 comparefun (if (= dcst sorting-type)
6921 'string<
6922 (lambda (a b) (and (not (string< a b))
6923 (not (string= a b)))))))
6924 ((= dcst ?t)
6925 (setq extractfun
6926 (lambda (x)
6927 (if (string-match org-ts-regexp x)
6928 (time-to-seconds
6929 (org-time-string-to-time (match-string 0 x)))
6931 comparefun (if (= dcst sorting-type) '< '>)))
6932 (t (error "Invalid sorting type `%c'" sorting-type)))
6934 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6935 table)
6936 (lambda (a b) (funcall comparefun (car a) (car b))))))
6938 ;;;; Plain list items, including checkboxes
6940 ;;; Plain list items
6942 (defun org-at-item-p ()
6943 "Is point in a line starting a hand-formatted item?"
6944 (let ((llt org-plain-list-ordered-item-terminator))
6945 (save-excursion
6946 (goto-char (point-at-bol))
6947 (looking-at
6948 (cond
6949 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6950 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6951 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6952 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6954 (defun org-in-item-p ()
6955 "It the cursor inside a plain list item.
6956 Does not have to be the first line."
6957 (save-excursion
6958 (condition-case nil
6959 (progn
6960 (org-beginning-of-item)
6961 (org-at-item-p)
6963 (error nil))))
6965 (defun org-insert-item (&optional checkbox)
6966 "Insert a new item at the current level.
6967 Return t when things worked, nil when we are not in an item."
6968 (when (save-excursion
6969 (condition-case nil
6970 (progn
6971 (org-beginning-of-item)
6972 (org-at-item-p)
6973 (if (org-invisible-p) (error "Invisible item"))
6975 (error nil)))
6976 (let* ((bul (match-string 0))
6977 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6978 (match-end 0)))
6979 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6980 pos)
6981 (cond
6982 ((and (org-at-item-p) (<= (point) eow))
6983 ;; before the bullet
6984 (beginning-of-line 1)
6985 (open-line (if blank 2 1)))
6986 ((<= (point) eow)
6987 (beginning-of-line 1))
6988 (t (newline (if blank 2 1))))
6989 (insert bul (if checkbox "[ ]" ""))
6990 (just-one-space)
6991 (setq pos (point))
6992 (end-of-line 1)
6993 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6994 (org-maybe-renumber-ordered-list)
6995 (and checkbox (org-update-checkbox-count-maybe))
6998 ;;; Checkboxes
7000 (defun org-at-item-checkbox-p ()
7001 "Is point at a line starting a plain-list item with a checklet?"
7002 (and (org-at-item-p)
7003 (save-excursion
7004 (goto-char (match-end 0))
7005 (skip-chars-forward " \t")
7006 (looking-at "\\[[- X]\\]"))))
7008 (defun org-toggle-checkbox (&optional arg)
7009 "Toggle the checkbox in the current line."
7010 (interactive "P")
7011 (catch 'exit
7012 (let (beg end status (firstnew 'unknown))
7013 (cond
7014 ((org-region-active-p)
7015 (setq beg (region-beginning) end (region-end)))
7016 ((org-on-heading-p)
7017 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7018 ((org-at-item-checkbox-p)
7019 (let ((pos (point)))
7020 (replace-match
7021 (cond (arg "[-]")
7022 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7023 (t "[ ]"))
7024 t t)
7025 (goto-char pos))
7026 (throw 'exit t))
7027 (t (error "Not at a checkbox or heading, and no active region")))
7028 (save-excursion
7029 (goto-char beg)
7030 (while (< (point) end)
7031 (when (org-at-item-checkbox-p)
7032 (setq status (equal (match-string 0) "[X]"))
7033 (when (eq firstnew 'unknown)
7034 (setq firstnew (not status)))
7035 (replace-match
7036 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7037 (beginning-of-line 2)))))
7038 (org-update-checkbox-count-maybe))
7040 (defun org-update-checkbox-count-maybe ()
7041 "Update checkbox statistics unless turned off by user."
7042 (when org-provide-checkbox-statistics
7043 (org-update-checkbox-count)))
7045 (defun org-update-checkbox-count (&optional all)
7046 "Update the checkbox statistics in the current section.
7047 This will find all statistic cookies like [57%] and [6/12] and update them
7048 with the current numbers. With optional prefix argument ALL, do this for
7049 the whole buffer."
7050 (interactive "P")
7051 (save-excursion
7052 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7053 (beg (condition-case nil
7054 (progn (outline-back-to-heading) (point))
7055 (error (point-min))))
7056 (end (move-marker (make-marker)
7057 (progn (outline-next-heading) (point))))
7058 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7059 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7060 (re-find (concat re "\\|" re-box))
7061 beg-cookie end-cookie is-percent c-on c-off lim
7062 eline curr-ind next-ind continue-from startsearch
7063 (cstat 0)
7065 (when all
7066 (goto-char (point-min))
7067 (outline-next-heading)
7068 (setq beg (point) end (point-max)))
7069 (goto-char end)
7070 ;; find each statistic cookie
7071 (while (re-search-backward re-find beg t)
7072 (setq beg-cookie (match-beginning 1)
7073 end-cookie (match-end 1)
7074 cstat (+ cstat (if end-cookie 1 0))
7075 startsearch (point-at-eol)
7076 continue-from (point-at-bol)
7077 is-percent (match-beginning 2)
7078 lim (cond
7079 ((org-on-heading-p) (outline-next-heading) (point))
7080 ((org-at-item-p) (org-end-of-item) (point))
7081 (t nil))
7082 c-on 0
7083 c-off 0)
7084 (when lim
7085 ;; find first checkbox for this cookie and gather
7086 ;; statistics from all that are at this indentation level
7087 (goto-char startsearch)
7088 (if (re-search-forward re-box lim t)
7089 (progn
7090 (org-beginning-of-item)
7091 (setq curr-ind (org-get-indentation))
7092 (setq next-ind curr-ind)
7093 (while (= curr-ind next-ind)
7094 (save-excursion (end-of-line) (setq eline (point)))
7095 (if (re-search-forward re-box eline t)
7096 (if (member (match-string 2) '("[ ]" "[-]"))
7097 (setq c-off (1+ c-off))
7098 (setq c-on (1+ c-on))
7101 (org-end-of-item)
7102 (setq next-ind (org-get-indentation))
7104 (goto-char continue-from)
7105 ;; update cookie
7106 (when end-cookie
7107 (delete-region beg-cookie end-cookie)
7108 (goto-char beg-cookie)
7109 (insert
7110 (if is-percent
7111 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7112 (format "[%d/%d]" c-on (+ c-on c-off)))))
7113 ;; update items checkbox if it has one
7114 (when (org-at-item-p)
7115 (org-beginning-of-item)
7116 (when (and (> (+ c-on c-off) 0)
7117 (re-search-forward re-box (point-at-eol) t))
7118 (setq beg-cookie (match-beginning 2)
7119 end-cookie (match-end 2))
7120 (delete-region beg-cookie end-cookie)
7121 (goto-char beg-cookie)
7122 (cond ((= c-off 0) (insert "[X]"))
7123 ((= c-on 0) (insert "[ ]"))
7124 (t (insert "[-]")))
7126 (goto-char continue-from))
7127 (when (interactive-p)
7128 (message "Checkbox satistics updated %s (%d places)"
7129 (if all "in entire file" "in current outline entry") cstat)))))
7131 (defun org-get-checkbox-statistics-face ()
7132 "Select the face for checkbox statistics.
7133 The face will be `org-done' when all relevant boxes are checked. Otherwise
7134 it will be `org-todo'."
7135 (if (match-end 1)
7136 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7137 (if (and (> (match-end 2) (match-beginning 2))
7138 (equal (match-string 2) (match-string 3)))
7139 'org-done
7140 'org-todo)))
7142 (defun org-get-indentation (&optional line)
7143 "Get the indentation of the current line, interpreting tabs.
7144 When LINE is given, assume it represents a line and compute its indentation."
7145 (if line
7146 (if (string-match "^ *" (org-remove-tabs line))
7147 (match-end 0))
7148 (save-excursion
7149 (beginning-of-line 1)
7150 (skip-chars-forward " \t")
7151 (current-column))))
7153 (defun org-remove-tabs (s &optional width)
7154 "Replace tabulators in S with spaces.
7155 Assumes that s is a single line, starting in column 0."
7156 (setq width (or width tab-width))
7157 (while (string-match "\t" s)
7158 (setq s (replace-match
7159 (make-string
7160 (- (* width (/ (+ (match-beginning 0) width) width))
7161 (match-beginning 0)) ?\ )
7162 t t s)))
7165 (defun org-fix-indentation (line ind)
7166 "Fix indentation in LINE.
7167 IND is a cons cell with target and minimum indentation.
7168 If the current indenation in LINE is smaller than the minimum,
7169 leave it alone. If it is larger than ind, set it to the target."
7170 (let* ((l (org-remove-tabs line))
7171 (i (org-get-indentation l))
7172 (i1 (car ind)) (i2 (cdr ind)))
7173 (if (>= i i2) (setq l (substring line i2)))
7174 (if (> i1 0)
7175 (concat (make-string i1 ?\ ) l)
7176 l)))
7178 (defcustom org-empty-line-terminates-plain-lists nil
7179 "Non-nil means, an empty line ends all plain list levels.
7180 When nil, empty lines are part of the preceeding item."
7181 :group 'org-plain-lists
7182 :type 'boolean)
7184 (defun org-beginning-of-item ()
7185 "Go to the beginning of the current hand-formatted item.
7186 If the cursor is not in an item, throw an error."
7187 (interactive)
7188 (let ((pos (point))
7189 (limit (save-excursion
7190 (condition-case nil
7191 (progn
7192 (org-back-to-heading)
7193 (beginning-of-line 2) (point))
7194 (error (point-min)))))
7195 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7196 ind ind1)
7197 (if (org-at-item-p)
7198 (beginning-of-line 1)
7199 (beginning-of-line 1)
7200 (skip-chars-forward " \t")
7201 (setq ind (current-column))
7202 (if (catch 'exit
7203 (while t
7204 (beginning-of-line 0)
7205 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7207 (if (looking-at "[ \t]*$")
7208 (setq ind1 ind-empty)
7209 (skip-chars-forward " \t")
7210 (setq ind1 (current-column)))
7211 (if (< ind1 ind)
7212 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7214 (goto-char pos)
7215 (error "Not in an item")))))
7217 (defun org-end-of-item ()
7218 "Go to the end of the current hand-formatted item.
7219 If the cursor is not in an item, throw an error."
7220 (interactive)
7221 (let* ((pos (point))
7222 ind1
7223 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7224 (limit (save-excursion (outline-next-heading) (point)))
7225 (ind (save-excursion
7226 (org-beginning-of-item)
7227 (skip-chars-forward " \t")
7228 (current-column)))
7229 (end (catch 'exit
7230 (while t
7231 (beginning-of-line 2)
7232 (if (eobp) (throw 'exit (point)))
7233 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7234 (if (looking-at "[ \t]*$")
7235 (setq ind1 ind-empty)
7236 (skip-chars-forward " \t")
7237 (setq ind1 (current-column)))
7238 (if (<= ind1 ind)
7239 (throw 'exit (point-at-bol)))))))
7240 (if end
7241 (goto-char end)
7242 (goto-char pos)
7243 (error "Not in an item"))))
7245 (defun org-next-item ()
7246 "Move to the beginning of the next item in the current plain list.
7247 Error if not at a plain list, or if this is the last item in the list."
7248 (interactive)
7249 (let (ind ind1 (pos (point)))
7250 (org-beginning-of-item)
7251 (setq ind (org-get-indentation))
7252 (org-end-of-item)
7253 (setq ind1 (org-get-indentation))
7254 (unless (and (org-at-item-p) (= ind ind1))
7255 (goto-char pos)
7256 (error "On last item"))))
7258 (defun org-previous-item ()
7259 "Move to the beginning of the previous item in the current plain list.
7260 Error if not at a plain list, or if this is the first item in the list."
7261 (interactive)
7262 (let (beg ind ind1 (pos (point)))
7263 (org-beginning-of-item)
7264 (setq beg (point))
7265 (setq ind (org-get-indentation))
7266 (goto-char beg)
7267 (catch 'exit
7268 (while t
7269 (beginning-of-line 0)
7270 (if (looking-at "[ \t]*$")
7272 (if (<= (setq ind1 (org-get-indentation)) ind)
7273 (throw 'exit t)))))
7274 (condition-case nil
7275 (if (or (not (org-at-item-p))
7276 (< ind1 (1- ind)))
7277 (error "")
7278 (org-beginning-of-item))
7279 (error (goto-char pos)
7280 (error "On first item")))))
7282 (defun org-first-list-item-p ()
7283 "Is this heading the item in a plain list?"
7284 (unless (org-at-item-p)
7285 (error "Not at a plain list item"))
7286 (org-beginning-of-item)
7287 (= (point) (save-excursion (org-beginning-of-item-list))))
7289 (defun org-move-item-down ()
7290 "Move the plain list item at point down, i.e. swap with following item.
7291 Subitems (items with larger indentation) are considered part of the item,
7292 so this really moves item trees."
7293 (interactive)
7294 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7295 (org-beginning-of-item)
7296 (setq beg0 (point))
7297 (save-excursion
7298 (setq ne-beg (org-back-over-empty-lines))
7299 (setq beg (point)))
7300 (goto-char beg0)
7301 (setq ind (org-get-indentation))
7302 (org-end-of-item)
7303 (setq end0 (point))
7304 (setq ind1 (org-get-indentation))
7305 (setq ne-end (org-back-over-empty-lines))
7306 (setq end (point))
7307 (goto-char beg0)
7308 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7309 ;; include less whitespace
7310 (save-excursion
7311 (goto-char beg)
7312 (forward-line (- ne-beg ne-end))
7313 (setq beg (point))))
7314 (goto-char end0)
7315 (if (and (org-at-item-p) (= ind ind1))
7316 (progn
7317 (org-end-of-item)
7318 (org-back-over-empty-lines)
7319 (setq txt (buffer-substring beg end))
7320 (save-excursion
7321 (delete-region beg end))
7322 (setq pos (point))
7323 (insert txt)
7324 (goto-char pos) (org-skip-whitespace)
7325 (org-maybe-renumber-ordered-list))
7326 (goto-char pos)
7327 (error "Cannot move this item further down"))))
7329 (defun org-move-item-up (arg)
7330 "Move the plain list item at point up, i.e. swap with previous item.
7331 Subitems (items with larger indentation) are considered part of the item,
7332 so this really moves item trees."
7333 (interactive "p")
7334 (let (beg beg0 end ind ind1 (pos (point)) txt
7335 ne-beg ne-ins ins-end)
7336 (org-beginning-of-item)
7337 (setq beg0 (point))
7338 (setq ind (org-get-indentation))
7339 (save-excursion
7340 (setq ne-beg (org-back-over-empty-lines))
7341 (setq beg (point)))
7342 (goto-char beg0)
7343 (org-end-of-item)
7344 (setq end (point))
7345 (goto-char beg0)
7346 (catch 'exit
7347 (while t
7348 (beginning-of-line 0)
7349 (if (looking-at "[ \t]*$")
7350 (if org-empty-line-terminates-plain-lists
7351 (progn
7352 (goto-char pos)
7353 (error "Cannot move this item further up"))
7354 nil)
7355 (if (<= (setq ind1 (org-get-indentation)) ind)
7356 (throw 'exit t)))))
7357 (condition-case nil
7358 (org-beginning-of-item)
7359 (error (goto-char beg)
7360 (error "Cannot move this item further up")))
7361 (setq ind1 (org-get-indentation))
7362 (if (and (org-at-item-p) (= ind ind1))
7363 (progn
7364 (setq ne-ins (org-back-over-empty-lines))
7365 (setq txt (buffer-substring beg end))
7366 (save-excursion
7367 (delete-region beg end))
7368 (setq pos (point))
7369 (insert txt)
7370 (setq ins-end (point))
7371 (goto-char pos) (org-skip-whitespace)
7373 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7374 ;; Move whitespace back to beginning
7375 (save-excursion
7376 (goto-char ins-end)
7377 (let ((kill-whole-line t))
7378 (kill-line (- ne-ins ne-beg)) (point)))
7379 (insert (make-string (- ne-ins ne-beg) ?\n)))
7381 (org-maybe-renumber-ordered-list))
7382 (goto-char pos)
7383 (error "Cannot move this item further up"))))
7385 (defun org-maybe-renumber-ordered-list ()
7386 "Renumber the ordered list at point if setup allows it.
7387 This tests the user option `org-auto-renumber-ordered-lists' before
7388 doing the renumbering."
7389 (interactive)
7390 (when (and org-auto-renumber-ordered-lists
7391 (org-at-item-p))
7392 (if (match-beginning 3)
7393 (org-renumber-ordered-list 1)
7394 (org-fix-bullet-type))))
7396 (defun org-maybe-renumber-ordered-list-safe ()
7397 (condition-case nil
7398 (save-excursion
7399 (org-maybe-renumber-ordered-list))
7400 (error nil)))
7402 (defun org-cycle-list-bullet (&optional which)
7403 "Cycle through the different itemize/enumerate bullets.
7404 This cycle the entire list level through the sequence:
7406 `-' -> `+' -> `*' -> `1.' -> `1)'
7408 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7409 0 meand `-', 1 means `+' etc."
7410 (interactive "P")
7411 (org-preserve-lc
7412 (org-beginning-of-item-list)
7413 (org-at-item-p)
7414 (beginning-of-line 1)
7415 (let ((current (match-string 0))
7416 (prevp (eq which 'previous))
7417 new)
7418 (setq new (cond
7419 ((and (numberp which)
7420 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7421 ((string-match "-" current) (if prevp "1)" "+"))
7422 ((string-match "\\+" current)
7423 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7424 ((string-match "\\*" current) (if prevp "+" "1."))
7425 ((string-match "\\." current) (if prevp "*" "1)"))
7426 ((string-match ")" current) (if prevp "1." "-"))
7427 (t (error "This should not happen"))))
7428 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7429 (org-fix-bullet-type)
7430 (org-maybe-renumber-ordered-list))))
7432 (defun org-get-string-indentation (s)
7433 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7434 (let ((n -1) (i 0) (w tab-width) c)
7435 (catch 'exit
7436 (while (< (setq n (1+ n)) (length s))
7437 (setq c (aref s n))
7438 (cond ((= c ?\ ) (setq i (1+ i)))
7439 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7440 (t (throw 'exit t)))))
7443 (defun org-renumber-ordered-list (arg)
7444 "Renumber an ordered plain list.
7445 Cursor needs to be in the first line of an item, the line that starts
7446 with something like \"1.\" or \"2)\"."
7447 (interactive "p")
7448 (unless (and (org-at-item-p)
7449 (match-beginning 3))
7450 (error "This is not an ordered list"))
7451 (let ((line (org-current-line))
7452 (col (current-column))
7453 (ind (org-get-string-indentation
7454 (buffer-substring (point-at-bol) (match-beginning 3))))
7455 ;; (term (substring (match-string 3) -1))
7456 ind1 (n (1- arg))
7457 fmt)
7458 ;; find where this list begins
7459 (org-beginning-of-item-list)
7460 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7461 (setq fmt (concat "%d" (match-string 1)))
7462 (beginning-of-line 0)
7463 ;; walk forward and replace these numbers
7464 (catch 'exit
7465 (while t
7466 (catch 'next
7467 (beginning-of-line 2)
7468 (if (eobp) (throw 'exit nil))
7469 (if (looking-at "[ \t]*$") (throw 'next nil))
7470 (skip-chars-forward " \t") (setq ind1 (current-column))
7471 (if (> ind1 ind) (throw 'next t))
7472 (if (< ind1 ind) (throw 'exit t))
7473 (if (not (org-at-item-p)) (throw 'exit nil))
7474 (delete-region (match-beginning 2) (match-end 2))
7475 (goto-char (match-beginning 2))
7476 (insert (format fmt (setq n (1+ n)))))))
7477 (goto-line line)
7478 (move-to-column col)))
7480 (defun org-fix-bullet-type ()
7481 "Make sure all items in this list have the same bullet as the firsst item."
7482 (interactive)
7483 (unless (org-at-item-p) (error "This is not a list"))
7484 (let ((line (org-current-line))
7485 (col (current-column))
7486 (ind (current-indentation))
7487 ind1 bullet)
7488 ;; find where this list begins
7489 (org-beginning-of-item-list)
7490 (beginning-of-line 1)
7491 ;; find out what the bullet type is
7492 (looking-at "[ \t]*\\(\\S-+\\)")
7493 (setq bullet (match-string 1))
7494 ;; walk forward and replace these numbers
7495 (beginning-of-line 0)
7496 (catch 'exit
7497 (while t
7498 (catch 'next
7499 (beginning-of-line 2)
7500 (if (eobp) (throw 'exit nil))
7501 (if (looking-at "[ \t]*$") (throw 'next nil))
7502 (skip-chars-forward " \t") (setq ind1 (current-column))
7503 (if (> ind1 ind) (throw 'next t))
7504 (if (< ind1 ind) (throw 'exit t))
7505 (if (not (org-at-item-p)) (throw 'exit nil))
7506 (skip-chars-forward " \t")
7507 (looking-at "\\S-+")
7508 (replace-match bullet))))
7509 (goto-line line)
7510 (move-to-column col)
7511 (if (string-match "[0-9]" bullet)
7512 (org-renumber-ordered-list 1))))
7514 (defun org-beginning-of-item-list ()
7515 "Go to the beginning of the current item list.
7516 I.e. to the first item in this list."
7517 (interactive)
7518 (org-beginning-of-item)
7519 (let ((pos (point-at-bol))
7520 (ind (org-get-indentation))
7521 ind1)
7522 ;; find where this list begins
7523 (catch 'exit
7524 (while t
7525 (catch 'next
7526 (beginning-of-line 0)
7527 (if (looking-at "[ \t]*$")
7528 (throw (if (bobp) 'exit 'next) t))
7529 (skip-chars-forward " \t") (setq ind1 (current-column))
7530 (if (or (< ind1 ind)
7531 (and (= ind1 ind)
7532 (not (org-at-item-p)))
7533 (bobp))
7534 (throw 'exit t)
7535 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7536 (goto-char pos)))
7539 (defun org-end-of-item-list ()
7540 "Go to the end of the current item list.
7541 I.e. to the text after the last item."
7542 (interactive)
7543 (org-beginning-of-item)
7544 (let ((pos (point-at-bol))
7545 (ind (org-get-indentation))
7546 ind1)
7547 ;; find where this list begins
7548 (catch 'exit
7549 (while t
7550 (catch 'next
7551 (beginning-of-line 2)
7552 (if (looking-at "[ \t]*$")
7553 (throw (if (eobp) 'exit 'next) t))
7554 (skip-chars-forward " \t") (setq ind1 (current-column))
7555 (if (or (< ind1 ind)
7556 (and (= ind1 ind)
7557 (not (org-at-item-p)))
7558 (eobp))
7559 (progn
7560 (setq pos (point-at-bol))
7561 (throw 'exit t))))))
7562 (goto-char pos)))
7565 (defvar org-last-indent-begin-marker (make-marker))
7566 (defvar org-last-indent-end-marker (make-marker))
7568 (defun org-outdent-item (arg)
7569 "Outdent a local list item."
7570 (interactive "p")
7571 (org-indent-item (- arg)))
7573 (defun org-indent-item (arg)
7574 "Indent a local list item."
7575 (interactive "p")
7576 (unless (org-at-item-p)
7577 (error "Not on an item"))
7578 (save-excursion
7579 (let (beg end ind ind1 tmp delta ind-down ind-up)
7580 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7581 (setq beg org-last-indent-begin-marker
7582 end org-last-indent-end-marker)
7583 (org-beginning-of-item)
7584 (setq beg (move-marker org-last-indent-begin-marker (point)))
7585 (org-end-of-item)
7586 (setq end (move-marker org-last-indent-end-marker (point))))
7587 (goto-char beg)
7588 (setq tmp (org-item-indent-positions)
7589 ind (car tmp)
7590 ind-down (nth 2 tmp)
7591 ind-up (nth 1 tmp)
7592 delta (if (> arg 0)
7593 (if ind-down (- ind-down ind) 2)
7594 (if ind-up (- ind-up ind) -2)))
7595 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7596 (while (< (point) end)
7597 (beginning-of-line 1)
7598 (skip-chars-forward " \t") (setq ind1 (current-column))
7599 (delete-region (point-at-bol) (point))
7600 (or (eolp) (indent-to-column (+ ind1 delta)))
7601 (beginning-of-line 2))))
7602 (org-fix-bullet-type)
7603 (org-maybe-renumber-ordered-list-safe)
7604 (save-excursion
7605 (beginning-of-line 0)
7606 (condition-case nil (org-beginning-of-item) (error nil))
7607 (org-maybe-renumber-ordered-list-safe)))
7609 (defun org-item-indent-positions ()
7610 "Return indentation for plain list items.
7611 This returns a list with three values: The current indentation, the
7612 parent indentation and the indentation a child should habe.
7613 Assumes cursor in item line."
7614 (let* ((bolpos (point-at-bol))
7615 (ind (org-get-indentation))
7616 ind-down ind-up pos)
7617 (save-excursion
7618 (org-beginning-of-item-list)
7619 (skip-chars-backward "\n\r \t")
7620 (when (org-in-item-p)
7621 (org-beginning-of-item)
7622 (setq ind-up (org-get-indentation))))
7623 (setq pos (point))
7624 (save-excursion
7625 (cond
7626 ((and (condition-case nil (progn (org-previous-item) t)
7627 (error nil))
7628 (or (forward-char 1) t)
7629 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7630 (setq ind-down (org-get-indentation)))
7631 ((and (goto-char pos)
7632 (org-at-item-p))
7633 (goto-char (match-end 0))
7634 (skip-chars-forward " \t")
7635 (setq ind-down (current-column)))))
7636 (list ind ind-up ind-down)))
7638 ;;; The orgstruct minor mode
7640 ;; Define a minor mode which can be used in other modes in order to
7641 ;; integrate the org-mode structure editing commands.
7643 ;; This is really a hack, because the org-mode structure commands use
7644 ;; keys which normally belong to the major mode. Here is how it
7645 ;; works: The minor mode defines all the keys necessary to operate the
7646 ;; structure commands, but wraps the commands into a function which
7647 ;; tests if the cursor is currently at a headline or a plain list
7648 ;; item. If that is the case, the structure command is used,
7649 ;; temporarily setting many Org-mode variables like regular
7650 ;; expressions for filling etc. However, when any of those keys is
7651 ;; used at a different location, function uses `key-binding' to look
7652 ;; up if the key has an associated command in another currently active
7653 ;; keymap (minor modes, major mode, global), and executes that
7654 ;; command. There might be problems if any of the keys is otherwise
7655 ;; used as a prefix key.
7657 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7658 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7659 ;; addresses this by checking explicitly for both bindings.
7661 (defvar orgstruct-mode-map (make-sparse-keymap)
7662 "Keymap for the minor `orgstruct-mode'.")
7664 (defvar org-local-vars nil
7665 "List of local variables, for use by `orgstruct-mode'")
7667 ;;;###autoload
7668 (define-minor-mode orgstruct-mode
7669 "Toggle the minor more `orgstruct-mode'.
7670 This mode is for using Org-mode structure commands in other modes.
7671 The following key behave as if Org-mode was active, if the cursor
7672 is on a headline, or on a plain list item (both in the definition
7673 of Org-mode).
7675 M-up Move entry/item up
7676 M-down Move entry/item down
7677 M-left Promote
7678 M-right Demote
7679 M-S-up Move entry/item up
7680 M-S-down Move entry/item down
7681 M-S-left Promote subtree
7682 M-S-right Demote subtree
7683 M-q Fill paragraph and items like in Org-mode
7684 C-c ^ Sort entries
7685 C-c - Cycle list bullet
7686 TAB Cycle item visibility
7687 M-RET Insert new heading/item
7688 S-M-RET Insert new TODO heading / Chekbox item
7689 C-c C-c Set tags / toggle checkbox"
7690 nil " OrgStruct" nil
7691 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7693 ;;;###autoload
7694 (defun turn-on-orgstruct ()
7695 "Unconditionally turn on `orgstruct-mode'."
7696 (orgstruct-mode 1))
7698 ;;;###autoload
7699 (defun turn-on-orgstruct++ ()
7700 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7701 In addition to setting orgstruct-mode, this also exports all indentation and
7702 autofilling variables from org-mode into the buffer. Note that turning
7703 off orgstruct-mode will *not* remove these additional settings."
7704 (orgstruct-mode 1)
7705 (let (var val)
7706 (mapc
7707 (lambda (x)
7708 (when (string-match
7709 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7710 (symbol-name (car x)))
7711 (setq var (car x) val (nth 1 x))
7712 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7713 org-local-vars)))
7715 (defun orgstruct-error ()
7716 "Error when there is no default binding for a structure key."
7717 (interactive)
7718 (error "This key has no function outside structure elements"))
7720 (defun orgstruct-setup ()
7721 "Setup orgstruct keymaps."
7722 (let ((nfunc 0)
7723 (bindings
7724 (list
7725 '([(meta up)] org-metaup)
7726 '([(meta down)] org-metadown)
7727 '([(meta left)] org-metaleft)
7728 '([(meta right)] org-metaright)
7729 '([(meta shift up)] org-shiftmetaup)
7730 '([(meta shift down)] org-shiftmetadown)
7731 '([(meta shift left)] org-shiftmetaleft)
7732 '([(meta shift right)] org-shiftmetaright)
7733 '([(shift up)] org-shiftup)
7734 '([(shift down)] org-shiftdown)
7735 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7736 '("\M-q" fill-paragraph)
7737 '("\C-c^" org-sort)
7738 '("\C-c-" org-cycle-list-bullet)))
7739 elt key fun cmd)
7740 (while (setq elt (pop bindings))
7741 (setq nfunc (1+ nfunc))
7742 (setq key (org-key (car elt))
7743 fun (nth 1 elt)
7744 cmd (orgstruct-make-binding fun nfunc key))
7745 (org-defkey orgstruct-mode-map key cmd))
7747 ;; Special treatment needed for TAB and RET
7748 (org-defkey orgstruct-mode-map [(tab)]
7749 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7750 (org-defkey orgstruct-mode-map "\C-i"
7751 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7753 (org-defkey orgstruct-mode-map "\M-\C-m"
7754 (orgstruct-make-binding 'org-insert-heading 105
7755 "\M-\C-m" [(meta return)]))
7756 (org-defkey orgstruct-mode-map [(meta return)]
7757 (orgstruct-make-binding 'org-insert-heading 106
7758 [(meta return)] "\M-\C-m"))
7760 (org-defkey orgstruct-mode-map [(shift meta return)]
7761 (orgstruct-make-binding 'org-insert-todo-heading 107
7762 [(meta return)] "\M-\C-m"))
7764 (unless org-local-vars
7765 (setq org-local-vars (org-get-local-variables)))
7769 (defun orgstruct-make-binding (fun n &rest keys)
7770 "Create a function for binding in the structure minor mode.
7771 FUN is the command to call inside a table. N is used to create a unique
7772 command name. KEYS are keys that should be checked in for a command
7773 to execute outside of tables."
7774 (eval
7775 (list 'defun
7776 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7777 '(arg)
7778 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7779 "Outside of structure, run the binding of `"
7780 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7781 "'.")
7782 '(interactive "p")
7783 (list 'if
7784 '(org-context-p 'headline 'item)
7785 (list 'org-run-like-in-org-mode (list 'quote fun))
7786 (list 'let '(orgstruct-mode)
7787 (list 'call-interactively
7788 (append '(or)
7789 (mapcar (lambda (k)
7790 (list 'key-binding k))
7791 keys)
7792 '('orgstruct-error))))))))
7794 (defun org-context-p (&rest contexts)
7795 "Check if local context is and of CONTEXTS.
7796 Possible values in the list of contexts are `table', `headline', and `item'."
7797 (let ((pos (point)))
7798 (goto-char (point-at-bol))
7799 (prog1 (or (and (memq 'table contexts)
7800 (looking-at "[ \t]*|"))
7801 (and (memq 'headline contexts)
7802 (looking-at "\\*+"))
7803 (and (memq 'item contexts)
7804 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7805 (goto-char pos))))
7807 (defun org-get-local-variables ()
7808 "Return a list of all local variables in an org-mode buffer."
7809 (let (varlist)
7810 (with-current-buffer (get-buffer-create "*Org tmp*")
7811 (erase-buffer)
7812 (org-mode)
7813 (setq varlist (buffer-local-variables)))
7814 (kill-buffer "*Org tmp*")
7815 (delq nil
7816 (mapcar
7817 (lambda (x)
7818 (setq x
7819 (if (symbolp x)
7820 (list x)
7821 (list (car x) (list 'quote (cdr x)))))
7822 (if (string-match
7823 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7824 (symbol-name (car x)))
7825 x nil))
7826 varlist))))
7828 ;;;###autoload
7829 (defun org-run-like-in-org-mode (cmd)
7830 (unless org-local-vars
7831 (setq org-local-vars (org-get-local-variables)))
7832 (eval (list 'let org-local-vars
7833 (list 'call-interactively (list 'quote cmd)))))
7835 ;;;; Archiving
7837 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7839 (defun org-archive-subtree (&optional find-done)
7840 "Move the current subtree to the archive.
7841 The archive can be a certain top-level heading in the current file, or in
7842 a different file. The tree will be moved to that location, the subtree
7843 heading be marked DONE, and the current time will be added.
7845 When called with prefix argument FIND-DONE, find whole trees without any
7846 open TODO items and archive them (after getting confirmation from the user).
7847 If the cursor is not at a headline when this comand is called, try all level
7848 1 trees. If the cursor is on a headline, only try the direct children of
7849 this heading."
7850 (interactive "P")
7851 (if find-done
7852 (org-archive-all-done)
7853 ;; Save all relevant TODO keyword-relatex variables
7855 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7856 (tr-org-todo-keywords-1 org-todo-keywords-1)
7857 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7858 (tr-org-done-keywords org-done-keywords)
7859 (tr-org-todo-regexp org-todo-regexp)
7860 (tr-org-todo-line-regexp org-todo-line-regexp)
7861 (tr-org-odd-levels-only org-odd-levels-only)
7862 (this-buffer (current-buffer))
7863 (org-archive-location org-archive-location)
7864 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7865 ;; start of variables that will be used for saving context
7866 ;; The compiler complains about them - keep them anyway!
7867 (file (abbreviate-file-name (buffer-file-name)))
7868 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7869 (time (format-time-string
7870 (substring (cdr org-time-stamp-formats) 1 -1)
7871 (current-time)))
7872 afile heading buffer level newfile-p
7873 category todo priority
7874 ;; start of variables that will be used for savind context
7875 ltags itags prop)
7877 ;; Try to find a local archive location
7878 (save-excursion
7879 (save-restriction
7880 (widen)
7881 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7882 (if (and prop (string-match "\\S-" prop))
7883 (setq org-archive-location prop)
7884 (if (or (re-search-backward re nil t)
7885 (re-search-forward re nil t))
7886 (setq org-archive-location (match-string 1))))))
7888 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7889 (progn
7890 (setq afile (format (match-string 1 org-archive-location)
7891 (file-name-nondirectory buffer-file-name))
7892 heading (match-string 2 org-archive-location)))
7893 (error "Invalid `org-archive-location'"))
7894 (if (> (length afile) 0)
7895 (setq newfile-p (not (file-exists-p afile))
7896 buffer (find-file-noselect afile))
7897 (setq buffer (current-buffer)))
7898 (unless buffer
7899 (error "Cannot access file \"%s\"" afile))
7900 (if (and (> (length heading) 0)
7901 (string-match "^\\*+" heading))
7902 (setq level (match-end 0))
7903 (setq heading nil level 0))
7904 (save-excursion
7905 (org-back-to-heading t)
7906 ;; Get context information that will be lost by moving the tree
7907 (org-refresh-category-properties)
7908 (setq category (org-get-category)
7909 todo (and (looking-at org-todo-line-regexp)
7910 (match-string 2))
7911 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7912 ltags (org-get-tags)
7913 itags (org-delete-all ltags (org-get-tags-at)))
7914 (setq ltags (mapconcat 'identity ltags " ")
7915 itags (mapconcat 'identity itags " "))
7916 ;; We first only copy, in case something goes wrong
7917 ;; we need to protect this-command, to avoid kill-region sets it,
7918 ;; which would lead to duplication of subtrees
7919 (let (this-command) (org-copy-subtree))
7920 (set-buffer buffer)
7921 ;; Enforce org-mode for the archive buffer
7922 (if (not (org-mode-p))
7923 ;; Force the mode for future visits.
7924 (let ((org-insert-mode-line-in-empty-file t)
7925 (org-inhibit-startup t))
7926 (call-interactively 'org-mode)))
7927 (when newfile-p
7928 (goto-char (point-max))
7929 (insert (format "\nArchived entries from file %s\n\n"
7930 (buffer-file-name this-buffer))))
7931 ;; Force the TODO keywords of the original buffer
7932 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7933 (org-todo-keywords-1 tr-org-todo-keywords-1)
7934 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7935 (org-done-keywords tr-org-done-keywords)
7936 (org-todo-regexp tr-org-todo-regexp)
7937 (org-todo-line-regexp tr-org-todo-line-regexp)
7938 (org-odd-levels-only
7939 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7940 org-odd-levels-only
7941 tr-org-odd-levels-only)))
7942 (goto-char (point-min))
7943 (if heading
7944 (progn
7945 (if (re-search-forward
7946 (concat "^" (regexp-quote heading)
7947 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7948 nil t)
7949 (goto-char (match-end 0))
7950 ;; Heading not found, just insert it at the end
7951 (goto-char (point-max))
7952 (or (bolp) (insert "\n"))
7953 (insert "\n" heading "\n")
7954 (end-of-line 0))
7955 ;; Make the subtree visible
7956 (show-subtree)
7957 (org-end-of-subtree t)
7958 (skip-chars-backward " \t\r\n")
7959 (and (looking-at "[ \t\r\n]*")
7960 (replace-match "\n\n")))
7961 ;; No specific heading, just go to end of file.
7962 (goto-char (point-max)) (insert "\n"))
7963 ;; Paste
7964 (org-paste-subtree (org-get-legal-level level 1))
7966 ;; Mark the entry as done
7967 (when (and org-archive-mark-done
7968 (looking-at org-todo-line-regexp)
7969 (or (not (match-end 2))
7970 (not (member (match-string 2) org-done-keywords))))
7971 (let (org-log-done org-todo-log-states)
7972 (org-todo
7973 (car (or (member org-archive-mark-done org-done-keywords)
7974 org-done-keywords)))))
7976 ;; Add the context info
7977 (when org-archive-save-context-info
7978 (let ((l org-archive-save-context-info) e n v)
7979 (while (setq e (pop l))
7980 (when (and (setq v (symbol-value e))
7981 (stringp v) (string-match "\\S-" v))
7982 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7983 (org-entry-put (point) n v)))))
7985 ;; Save the buffer, if it is not the same buffer.
7986 (if (not (eq this-buffer buffer)) (save-buffer))))
7987 ;; Here we are back in the original buffer. Everything seems to have
7988 ;; worked. So now cut the tree and finish up.
7989 (let (this-command) (org-cut-subtree))
7990 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7991 (message "Subtree archived %s"
7992 (if (eq this-buffer buffer)
7993 (concat "under heading: " heading)
7994 (concat "in file: " (abbreviate-file-name afile)))))))
7996 (defun org-refresh-category-properties ()
7997 "Refresh category text properties in teh buffer."
7998 (let ((def-cat (cond
7999 ((null org-category)
8000 (if buffer-file-name
8001 (file-name-sans-extension
8002 (file-name-nondirectory buffer-file-name))
8003 "???"))
8004 ((symbolp org-category) (symbol-name org-category))
8005 (t org-category)))
8006 beg end cat pos optionp)
8007 (org-unmodified
8008 (save-excursion
8009 (save-restriction
8010 (widen)
8011 (goto-char (point-min))
8012 (put-text-property (point) (point-max) 'org-category def-cat)
8013 (while (re-search-forward
8014 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8015 (setq pos (match-end 0)
8016 optionp (equal (char-after (match-beginning 0)) ?#)
8017 cat (org-trim (match-string 2)))
8018 (if optionp
8019 (setq beg (point-at-bol) end (point-max))
8020 (org-back-to-heading t)
8021 (setq beg (point) end (org-end-of-subtree t t)))
8022 (put-text-property beg end 'org-category cat)
8023 (goto-char pos)))))))
8025 (defun org-archive-all-done (&optional tag)
8026 "Archive sublevels of the current tree without open TODO items.
8027 If the cursor is not on a headline, try all level 1 trees. If
8028 it is on a headline, try all direct children.
8029 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8030 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8031 (rea (concat ".*:" org-archive-tag ":"))
8032 (begm (make-marker))
8033 (endm (make-marker))
8034 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8035 "Move subtree to archive (no open TODO items)? "))
8036 beg end (cntarch 0))
8037 (if (org-on-heading-p)
8038 (progn
8039 (setq re1 (concat "^" (regexp-quote
8040 (make-string
8041 (1+ (- (match-end 0) (match-beginning 0) 1))
8042 ?*))
8043 " "))
8044 (move-marker begm (point))
8045 (move-marker endm (org-end-of-subtree t)))
8046 (setq re1 "^* ")
8047 (move-marker begm (point-min))
8048 (move-marker endm (point-max)))
8049 (save-excursion
8050 (goto-char begm)
8051 (while (re-search-forward re1 endm t)
8052 (setq beg (match-beginning 0)
8053 end (save-excursion (org-end-of-subtree t) (point)))
8054 (goto-char beg)
8055 (if (re-search-forward re end t)
8056 (goto-char end)
8057 (goto-char beg)
8058 (if (and (or (not tag) (not (looking-at rea)))
8059 (y-or-n-p question))
8060 (progn
8061 (if tag
8062 (org-toggle-tag org-archive-tag 'on)
8063 (org-archive-subtree))
8064 (setq cntarch (1+ cntarch)))
8065 (goto-char end)))))
8066 (message "%d trees archived" cntarch)))
8068 (defun org-cycle-hide-drawers (state)
8069 "Re-hide all drawers after a visibility state change."
8070 (when (and (org-mode-p)
8071 (not (memq state '(overview folded))))
8072 (save-excursion
8073 (let* ((globalp (memq state '(contents all)))
8074 (beg (if globalp (point-min) (point)))
8075 (end (if globalp (point-max) (org-end-of-subtree t))))
8076 (goto-char beg)
8077 (while (re-search-forward org-drawer-regexp end t)
8078 (org-flag-drawer t))))))
8080 (defun org-flag-drawer (flag)
8081 (save-excursion
8082 (beginning-of-line 1)
8083 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8084 (let ((b (match-end 0))
8085 (outline-regexp org-outline-regexp))
8086 (if (re-search-forward
8087 "^[ \t]*:END:"
8088 (save-excursion (outline-next-heading) (point)) t)
8089 (outline-flag-region b (point-at-eol) flag)
8090 (error ":END: line missing"))))))
8092 (defun org-cycle-hide-archived-subtrees (state)
8093 "Re-hide all archived subtrees after a visibility state change."
8094 (when (and (not org-cycle-open-archived-trees)
8095 (not (memq state '(overview folded))))
8096 (save-excursion
8097 (let* ((globalp (memq state '(contents all)))
8098 (beg (if globalp (point-min) (point)))
8099 (end (if globalp (point-max) (org-end-of-subtree t))))
8100 (org-hide-archived-subtrees beg end)
8101 (goto-char beg)
8102 (if (looking-at (concat ".*:" org-archive-tag ":"))
8103 (message "%s" (substitute-command-keys
8104 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8106 (defun org-force-cycle-archived ()
8107 "Cycle subtree even if it is archived."
8108 (interactive)
8109 (setq this-command 'org-cycle)
8110 (let ((org-cycle-open-archived-trees t))
8111 (call-interactively 'org-cycle)))
8113 (defun org-hide-archived-subtrees (beg end)
8114 "Re-hide all archived subtrees after a visibility state change."
8115 (save-excursion
8116 (let* ((re (concat ":" org-archive-tag ":")))
8117 (goto-char beg)
8118 (while (re-search-forward re end t)
8119 (and (org-on-heading-p) (hide-subtree))
8120 (org-end-of-subtree t)))))
8122 (defun org-toggle-tag (tag &optional onoff)
8123 "Toggle the tag TAG for the current line.
8124 If ONOFF is `on' or `off', don't toggle but set to this state."
8125 (unless (org-on-heading-p t) (error "Not on headling"))
8126 (let (res current)
8127 (save-excursion
8128 (beginning-of-line)
8129 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8130 (point-at-eol) t)
8131 (progn
8132 (setq current (match-string 1))
8133 (replace-match ""))
8134 (setq current ""))
8135 (setq current (nreverse (org-split-string current ":")))
8136 (cond
8137 ((eq onoff 'on)
8138 (setq res t)
8139 (or (member tag current) (push tag current)))
8140 ((eq onoff 'off)
8141 (or (not (member tag current)) (setq current (delete tag current))))
8142 (t (if (member tag current)
8143 (setq current (delete tag current))
8144 (setq res t)
8145 (push tag current))))
8146 (end-of-line 1)
8147 (if current
8148 (progn
8149 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8150 (org-set-tags nil t))
8151 (delete-horizontal-space))
8152 (run-hooks 'org-after-tags-change-hook))
8153 res))
8155 (defun org-toggle-archive-tag (&optional arg)
8156 "Toggle the archive tag for the current headline.
8157 With prefix ARG, check all children of current headline and offer tagging
8158 the children that do not contain any open TODO items."
8159 (interactive "P")
8160 (if arg
8161 (org-archive-all-done 'tag)
8162 (let (set)
8163 (save-excursion
8164 (org-back-to-heading t)
8165 (setq set (org-toggle-tag org-archive-tag))
8166 (when set (hide-subtree)))
8167 (and set (beginning-of-line 1))
8168 (message "Subtree %s" (if set "archived" "unarchived")))))
8171 ;;;; Tables
8173 ;;; The table editor
8175 ;; Watch out: Here we are talking about two different kind of tables.
8176 ;; Most of the code is for the tables created with the Org-mode table editor.
8177 ;; Sometimes, we talk about tables created and edited with the table.el
8178 ;; Emacs package. We call the former org-type tables, and the latter
8179 ;; table.el-type tables.
8181 (defun org-before-change-function (beg end)
8182 "Every change indicates that a table might need an update."
8183 (setq org-table-may-need-update t))
8185 (defconst org-table-line-regexp "^[ \t]*|"
8186 "Detects an org-type table line.")
8187 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8188 "Detects an org-type table line.")
8189 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8190 "Detects a table line marked for automatic recalculation.")
8191 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8192 "Detects a table line marked for automatic recalculation.")
8193 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8194 "Detects a table line marked for automatic recalculation.")
8195 (defconst org-table-hline-regexp "^[ \t]*|-"
8196 "Detects an org-type table hline.")
8197 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8198 "Detects a table-type table hline.")
8199 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8200 "Detects an org-type or table-type table.")
8201 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8202 "Searching from within a table (any type) this finds the first line
8203 outside the table.")
8204 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8205 "Searching from within a table (any type) this finds the first line
8206 outside the table.")
8208 (defvar org-table-last-highlighted-reference nil)
8209 (defvar org-table-formula-history nil)
8211 (defvar org-table-column-names nil
8212 "Alist with column names, derived from the `!' line.")
8213 (defvar org-table-column-name-regexp nil
8214 "Regular expression matching the current column names.")
8215 (defvar org-table-local-parameters nil
8216 "Alist with parameter names, derived from the `$' line.")
8217 (defvar org-table-named-field-locations nil
8218 "Alist with locations of named fields.")
8220 (defvar org-table-current-line-types nil
8221 "Table row types, non-nil only for the duration of a comand.")
8222 (defvar org-table-current-begin-line nil
8223 "Table begin line, non-nil only for the duration of a comand.")
8224 (defvar org-table-current-begin-pos nil
8225 "Table begin position, non-nil only for the duration of a comand.")
8226 (defvar org-table-dlines nil
8227 "Vector of data line line numbers in the current table.")
8228 (defvar org-table-hlines nil
8229 "Vector of hline line numbers in the current table.")
8231 (defconst org-table-range-regexp
8232 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8233 ;; 1 2 3 4 5
8234 "Regular expression for matching ranges in formulas.")
8236 (defconst org-table-range-regexp2
8237 (concat
8238 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8239 "\\.\\."
8240 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8241 "Match a range for reference display.")
8243 (defconst org-table-translate-regexp
8244 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8245 "Match a reference that needs translation, for reference display.")
8247 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8249 (defun org-table-create-with-table.el ()
8250 "Use the table.el package to insert a new table.
8251 If there is already a table at point, convert between Org-mode tables
8252 and table.el tables."
8253 (interactive)
8254 (require 'table)
8255 (cond
8256 ((org-at-table.el-p)
8257 (if (y-or-n-p "Convert table to Org-mode table? ")
8258 (org-table-convert)))
8259 ((org-at-table-p)
8260 (if (y-or-n-p "Convert table to table.el table? ")
8261 (org-table-convert)))
8262 (t (call-interactively 'table-insert))))
8264 (defun org-table-create-or-convert-from-region (arg)
8265 "Convert region to table, or create an empty table.
8266 If there is an active region, convert it to a table, using the function
8267 `org-table-convert-region'. See the documentation of that function
8268 to learn how the prefix argument is interpreted to determine the field
8269 separator.
8270 If there is no such region, create an empty table with `org-table-create'."
8271 (interactive "P")
8272 (if (org-region-active-p)
8273 (org-table-convert-region (region-beginning) (region-end) arg)
8274 (org-table-create arg)))
8276 (defun org-table-create (&optional size)
8277 "Query for a size and insert a table skeleton.
8278 SIZE is a string Columns x Rows like for example \"3x2\"."
8279 (interactive "P")
8280 (unless size
8281 (setq size (read-string
8282 (concat "Table size Columns x Rows [e.g. "
8283 org-table-default-size "]: ")
8284 "" nil org-table-default-size)))
8286 (let* ((pos (point))
8287 (indent (make-string (current-column) ?\ ))
8288 (split (org-split-string size " *x *"))
8289 (rows (string-to-number (nth 1 split)))
8290 (columns (string-to-number (car split)))
8291 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8292 "\n")))
8293 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8294 (point-at-bol) (point)))
8295 (beginning-of-line 1)
8296 (newline))
8297 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8298 (dotimes (i rows) (insert line))
8299 (goto-char pos)
8300 (if (> rows 1)
8301 ;; Insert a hline after the first row.
8302 (progn
8303 (end-of-line 1)
8304 (insert "\n|-")
8305 (goto-char pos)))
8306 (org-table-align)))
8308 (defun org-table-convert-region (beg0 end0 &optional separator)
8309 "Convert region to a table.
8310 The region goes from BEG0 to END0, but these borders will be moved
8311 slightly, to make sure a beginning of line in the first line is included.
8313 SEPARATOR specifies the field separator in the lines. It can have the
8314 following values:
8316 '(4) Use the comma as a field separator
8317 '(16) Use a TAB as field separator
8318 integer When a number, use that many spaces as field separator
8319 nil When nil, the command tries to be smart and figure out the
8320 separator in the following way:
8321 - when each line contains a TAB, assume TAB-separated material
8322 - when each line contains a comme, assume CSV material
8323 - else, assume one or more SPACE charcters as separator."
8324 (interactive "rP")
8325 (let* ((beg (min beg0 end0))
8326 (end (max beg0 end0))
8328 (goto-char beg)
8329 (beginning-of-line 1)
8330 (setq beg (move-marker (make-marker) (point)))
8331 (goto-char end)
8332 (if (bolp) (backward-char 1) (end-of-line 1))
8333 (setq end (move-marker (make-marker) (point)))
8334 ;; Get the right field separator
8335 (unless separator
8336 (goto-char beg)
8337 (setq separator
8338 (cond
8339 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8340 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8341 (t 1))))
8342 (setq re (cond
8343 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8344 ((equal separator '(16)) "^\\|\t")
8345 ((integerp separator)
8346 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8347 (t (error "This should not happen"))))
8348 (goto-char beg)
8349 (while (re-search-forward re end t)
8350 (replace-match "| " t t))
8351 (goto-char beg)
8352 (insert " ")
8353 (org-table-align)))
8355 (defun org-table-import (file arg)
8356 "Import FILE as a table.
8357 The file is assumed to be tab-separated. Such files can be produced by most
8358 spreadsheet and database applications. If no tabs (at least one per line)
8359 are found, lines will be split on whitespace into fields."
8360 (interactive "f\nP")
8361 (or (bolp) (newline))
8362 (let ((beg (point))
8363 (pm (point-max)))
8364 (insert-file-contents file)
8365 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8367 (defun org-table-export ()
8368 "Export table as a tab-separated file.
8369 Such a file can be imported into a spreadsheet program like Excel."
8370 (interactive)
8371 (let* ((beg (org-table-begin))
8372 (end (org-table-end))
8373 (table (buffer-substring beg end))
8374 (file (read-file-name "Export table to: "))
8375 buf)
8376 (unless (or (not (file-exists-p file))
8377 (y-or-n-p (format "Overwrite file %s? " file)))
8378 (error "Abort"))
8379 (with-current-buffer (find-file-noselect file)
8380 (setq buf (current-buffer))
8381 (erase-buffer)
8382 (fundamental-mode)
8383 (insert table)
8384 (goto-char (point-min))
8385 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8386 (replace-match "" t t)
8387 (end-of-line 1))
8388 (goto-char (point-min))
8389 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8390 (replace-match "" t t)
8391 (goto-char (min (1+ (point)) (point-max))))
8392 (goto-char (point-min))
8393 (while (re-search-forward "^-[-+]*$" nil t)
8394 (replace-match "")
8395 (if (looking-at "\n")
8396 (delete-char 1)))
8397 (goto-char (point-min))
8398 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8399 (replace-match "\t" t t))
8400 (save-buffer))
8401 (kill-buffer buf)))
8403 (defvar org-table-aligned-begin-marker (make-marker)
8404 "Marker at the beginning of the table last aligned.
8405 Used to check if cursor still is in that table, to minimize realignment.")
8406 (defvar org-table-aligned-end-marker (make-marker)
8407 "Marker at the end of the table last aligned.
8408 Used to check if cursor still is in that table, to minimize realignment.")
8409 (defvar org-table-last-alignment nil
8410 "List of flags for flushright alignment, from the last re-alignment.
8411 This is being used to correctly align a single field after TAB or RET.")
8412 (defvar org-table-last-column-widths nil
8413 "List of max width of fields in each column.
8414 This is being used to correctly align a single field after TAB or RET.")
8415 (defvar org-table-overlay-coordinates nil
8416 "Overlay coordinates after each align of a table.")
8417 (make-variable-buffer-local 'org-table-overlay-coordinates)
8419 (defvar org-last-recalc-line nil)
8420 (defconst org-narrow-column-arrow "=>"
8421 "Used as display property in narrowed table columns.")
8423 (defun org-table-align ()
8424 "Align the table at point by aligning all vertical bars."
8425 (interactive)
8426 (let* (
8427 ;; Limits of table
8428 (beg (org-table-begin))
8429 (end (org-table-end))
8430 ;; Current cursor position
8431 (linepos (org-current-line))
8432 (colpos (org-table-current-column))
8433 (winstart (window-start))
8434 (winstartline (org-current-line (min winstart (1- (point-max)))))
8435 lines (new "") lengths l typenums ty fields maxfields i
8436 column
8437 (indent "") cnt frac
8438 rfmt hfmt
8439 (spaces '(1 . 1))
8440 (sp1 (car spaces))
8441 (sp2 (cdr spaces))
8442 (rfmt1 (concat
8443 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8444 (hfmt1 (concat
8445 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8446 emptystrings links dates emph narrow fmax f1 len c e)
8447 (untabify beg end)
8448 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8449 ;; Check if we have links or dates
8450 (goto-char beg)
8451 (setq links (re-search-forward org-bracket-link-regexp end t))
8452 (goto-char beg)
8453 (setq emph (and org-hide-emphasis-markers
8454 (re-search-forward org-emph-re end t)))
8455 (goto-char beg)
8456 (setq dates (and org-display-custom-times
8457 (re-search-forward org-ts-regexp-both end t)))
8458 ;; Make sure the link properties are right
8459 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8460 ;; Make sure the date properties are right
8461 (when dates (goto-char beg) (while (org-activate-dates end)))
8462 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8464 ;; Check if we are narrowing any columns
8465 (goto-char beg)
8466 (setq narrow (and org-format-transports-properties-p
8467 (re-search-forward "<[0-9]+>" end t)))
8468 ;; Get the rows
8469 (setq lines (org-split-string
8470 (buffer-substring beg end) "\n"))
8471 ;; Store the indentation of the first line
8472 (if (string-match "^ *" (car lines))
8473 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8474 ;; Mark the hlines by setting the corresponding element to nil
8475 ;; At the same time, we remove trailing space.
8476 (setq lines (mapcar (lambda (l)
8477 (if (string-match "^ *|-" l)
8479 (if (string-match "[ \t]+$" l)
8480 (substring l 0 (match-beginning 0))
8481 l)))
8482 lines))
8483 ;; Get the data fields by splitting the lines.
8484 (setq fields (mapcar
8485 (lambda (l)
8486 (org-split-string l " *| *"))
8487 (delq nil (copy-sequence lines))))
8488 ;; How many fields in the longest line?
8489 (condition-case nil
8490 (setq maxfields (apply 'max (mapcar 'length fields)))
8491 (error
8492 (kill-region beg end)
8493 (org-table-create org-table-default-size)
8494 (error "Empty table - created default table")))
8495 ;; A list of empty strings to fill any short rows on output
8496 (setq emptystrings (make-list maxfields ""))
8497 ;; Check for special formatting.
8498 (setq i -1)
8499 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8500 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8501 ;; Check if there is an explicit width specified
8502 (when narrow
8503 (setq c column fmax nil)
8504 (while c
8505 (setq e (pop c))
8506 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8507 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8508 ;; Find fields that are wider than fmax, and shorten them
8509 (when fmax
8510 (loop for xx in column do
8511 (when (and (stringp xx)
8512 (> (org-string-width xx) fmax))
8513 (org-add-props xx nil
8514 'help-echo
8515 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8516 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8517 (unless (> f1 1)
8518 (error "Cannot narrow field starting with wide link \"%s\""
8519 (match-string 0 xx)))
8520 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8521 (add-text-properties (- f1 2) f1
8522 (list 'display org-narrow-column-arrow)
8523 xx)))))
8524 ;; Get the maximum width for each column
8525 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8526 ;; Get the fraction of numbers, to decide about alignment of the column
8527 (setq cnt 0 frac 0.0)
8528 (loop for x in column do
8529 (if (equal x "")
8531 (setq frac ( / (+ (* frac cnt)
8532 (if (string-match org-table-number-regexp x) 1 0))
8533 (setq cnt (1+ cnt))))))
8534 (push (>= frac org-table-number-fraction) typenums))
8535 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8537 ;; Store the alignment of this table, for later editing of single fields
8538 (setq org-table-last-alignment typenums
8539 org-table-last-column-widths lengths)
8541 ;; With invisible characters, `format' does not get the field width right
8542 ;; So we need to make these fields wide by hand.
8543 (when (or links emph)
8544 (loop for i from 0 upto (1- maxfields) do
8545 (setq len (nth i lengths))
8546 (loop for j from 0 upto (1- (length fields)) do
8547 (setq c (nthcdr i (car (nthcdr j fields))))
8548 (if (and (stringp (car c))
8549 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8550 ; (string-match org-bracket-link-regexp (car c))
8551 (< (org-string-width (car c)) len))
8552 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8554 ;; Compute the formats needed for output of the table
8555 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8556 (while (setq l (pop lengths))
8557 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8558 (setq rfmt (concat rfmt (format rfmt1 ty l))
8559 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8560 (setq rfmt (concat rfmt "\n")
8561 hfmt (concat (substring hfmt 0 -1) "|\n"))
8563 (setq new (mapconcat
8564 (lambda (l)
8565 (if l (apply 'format rfmt
8566 (append (pop fields) emptystrings))
8567 hfmt))
8568 lines ""))
8569 ;; Replace the old one
8570 (delete-region beg end)
8571 (move-marker end nil)
8572 (move-marker org-table-aligned-begin-marker (point))
8573 (insert new)
8574 (move-marker org-table-aligned-end-marker (point))
8575 (when (and orgtbl-mode (not (org-mode-p)))
8576 (goto-char org-table-aligned-begin-marker)
8577 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8578 ;; Try to move to the old location
8579 (goto-line winstartline)
8580 (setq winstart (point-at-bol))
8581 (goto-line linepos)
8582 (set-window-start (selected-window) winstart 'noforce)
8583 (org-table-goto-column colpos)
8584 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8585 (setq org-table-may-need-update nil)
8588 (defun org-string-width (s)
8589 "Compute width of string, ignoring invisible characters.
8590 This ignores character with invisibility property `org-link', and also
8591 characters with property `org-cwidth', because these will become invisible
8592 upon the next fontification round."
8593 (let (b l)
8594 (when (or (eq t buffer-invisibility-spec)
8595 (assq 'org-link buffer-invisibility-spec))
8596 (while (setq b (text-property-any 0 (length s)
8597 'invisible 'org-link s))
8598 (setq s (concat (substring s 0 b)
8599 (substring s (or (next-single-property-change
8600 b 'invisible s) (length s)))))))
8601 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8602 (setq s (concat (substring s 0 b)
8603 (substring s (or (next-single-property-change
8604 b 'org-cwidth s) (length s))))))
8605 (setq l (string-width s) b -1)
8606 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8607 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8610 (defun org-table-begin (&optional table-type)
8611 "Find the beginning of the table and return its position.
8612 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8613 (save-excursion
8614 (if (not (re-search-backward
8615 (if table-type org-table-any-border-regexp
8616 org-table-border-regexp)
8617 nil t))
8618 (progn (goto-char (point-min)) (point))
8619 (goto-char (match-beginning 0))
8620 (beginning-of-line 2)
8621 (point))))
8623 (defun org-table-end (&optional table-type)
8624 "Find the end of the table and return its position.
8625 With argument TABLE-TYPE, go to the end of a table.el-type table."
8626 (save-excursion
8627 (if (not (re-search-forward
8628 (if table-type org-table-any-border-regexp
8629 org-table-border-regexp)
8630 nil t))
8631 (goto-char (point-max))
8632 (goto-char (match-beginning 0)))
8633 (point-marker)))
8635 (defun org-table-justify-field-maybe (&optional new)
8636 "Justify the current field, text to left, number to right.
8637 Optional argument NEW may specify text to replace the current field content."
8638 (cond
8639 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8640 ((org-at-table-hline-p))
8641 ((and (not new)
8642 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8643 (current-buffer)))
8644 (< (point) org-table-aligned-begin-marker)
8645 (>= (point) org-table-aligned-end-marker)))
8646 ;; This is not the same table, force a full re-align
8647 (setq org-table-may-need-update t))
8648 (t ;; realign the current field, based on previous full realign
8649 (let* ((pos (point)) s
8650 (col (org-table-current-column))
8651 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8652 l f n o e)
8653 (when (> col 0)
8654 (skip-chars-backward "^|\n")
8655 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8656 (progn
8657 (setq s (match-string 1)
8658 o (match-string 0)
8659 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8660 e (not (= (match-beginning 2) (match-end 2))))
8661 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8662 l (if e "|" (setq org-table-may-need-update t) ""))
8663 n (format f s))
8664 (if new
8665 (if (<= (length new) l) ;; FIXME: length -> str-width?
8666 (setq n (format f new))
8667 (setq n (concat new "|") org-table-may-need-update t)))
8668 (or (equal n o)
8669 (let (org-table-may-need-update)
8670 (replace-match n t t))))
8671 (setq org-table-may-need-update t))
8672 (goto-char pos))))))
8674 (defun org-table-next-field ()
8675 "Go to the next field in the current table, creating new lines as needed.
8676 Before doing so, re-align the table if necessary."
8677 (interactive)
8678 (org-table-maybe-eval-formula)
8679 (org-table-maybe-recalculate-line)
8680 (if (and org-table-automatic-realign
8681 org-table-may-need-update)
8682 (org-table-align))
8683 (let ((end (org-table-end)))
8684 (if (org-at-table-hline-p)
8685 (end-of-line 1))
8686 (condition-case nil
8687 (progn
8688 (re-search-forward "|" end)
8689 (if (looking-at "[ \t]*$")
8690 (re-search-forward "|" end))
8691 (if (and (looking-at "-")
8692 org-table-tab-jumps-over-hlines
8693 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8694 (goto-char (match-beginning 1)))
8695 (if (looking-at "-")
8696 (progn
8697 (beginning-of-line 0)
8698 (org-table-insert-row 'below))
8699 (if (looking-at " ") (forward-char 1))))
8700 (error
8701 (org-table-insert-row 'below)))))
8703 (defun org-table-previous-field ()
8704 "Go to the previous field in the table.
8705 Before doing so, re-align the table if necessary."
8706 (interactive)
8707 (org-table-justify-field-maybe)
8708 (org-table-maybe-recalculate-line)
8709 (if (and org-table-automatic-realign
8710 org-table-may-need-update)
8711 (org-table-align))
8712 (if (org-at-table-hline-p)
8713 (end-of-line 1))
8714 (re-search-backward "|" (org-table-begin))
8715 (re-search-backward "|" (org-table-begin))
8716 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8717 (re-search-backward "|" (org-table-begin)))
8718 (if (looking-at "| ?")
8719 (goto-char (match-end 0))))
8721 (defun org-table-next-row ()
8722 "Go to the next row (same column) in the current table.
8723 Before doing so, re-align the table if necessary."
8724 (interactive)
8725 (org-table-maybe-eval-formula)
8726 (org-table-maybe-recalculate-line)
8727 (if (or (looking-at "[ \t]*$")
8728 (save-excursion (skip-chars-backward " \t") (bolp)))
8729 (newline)
8730 (if (and org-table-automatic-realign
8731 org-table-may-need-update)
8732 (org-table-align))
8733 (let ((col (org-table-current-column)))
8734 (beginning-of-line 2)
8735 (if (or (not (org-at-table-p))
8736 (org-at-table-hline-p))
8737 (progn
8738 (beginning-of-line 0)
8739 (org-table-insert-row 'below)))
8740 (org-table-goto-column col)
8741 (skip-chars-backward "^|\n\r")
8742 (if (looking-at " ") (forward-char 1)))))
8744 (defun org-table-copy-down (n)
8745 "Copy a field down in the current column.
8746 If the field at the cursor is empty, copy into it the content of the nearest
8747 non-empty field above. With argument N, use the Nth non-empty field.
8748 If the current field is not empty, it is copied down to the next row, and
8749 the cursor is moved with it. Therefore, repeating this command causes the
8750 column to be filled row-by-row.
8751 If the variable `org-table-copy-increment' is non-nil and the field is an
8752 integer or a timestamp, it will be incremented while copying. In the case of
8753 a timestamp, if the cursor is on the year, change the year. If it is on the
8754 month or the day, change that. Point will stay on the current date field
8755 in order to easily repeat the interval."
8756 (interactive "p")
8757 (let* ((colpos (org-table-current-column))
8758 (col (current-column))
8759 (field (org-table-get-field))
8760 (non-empty (string-match "[^ \t]" field))
8761 (beg (org-table-begin))
8762 txt)
8763 (org-table-check-inside-data-field)
8764 (if non-empty
8765 (progn
8766 (setq txt (org-trim field))
8767 (org-table-next-row)
8768 (org-table-blank-field))
8769 (save-excursion
8770 (setq txt
8771 (catch 'exit
8772 (while (progn (beginning-of-line 1)
8773 (re-search-backward org-table-dataline-regexp
8774 beg t))
8775 (org-table-goto-column colpos t)
8776 (if (and (looking-at
8777 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8778 (= (setq n (1- n)) 0))
8779 (throw 'exit (match-string 1))))))))
8780 (if txt
8781 (progn
8782 (if (and org-table-copy-increment
8783 (string-match "^[0-9]+$" txt))
8784 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8785 (insert txt)
8786 (move-to-column col)
8787 (if (and org-table-copy-increment (org-at-timestamp-p t))
8788 (org-timestamp-up 1)
8789 (org-table-maybe-recalculate-line))
8790 (org-table-align)
8791 (move-to-column col))
8792 (error "No non-empty field found"))))
8794 (defun org-table-check-inside-data-field ()
8795 "Is point inside a table data field?
8796 I.e. not on a hline or before the first or after the last column?
8797 This actually throws an error, so it aborts the current command."
8798 (if (or (not (org-at-table-p))
8799 (= (org-table-current-column) 0)
8800 (org-at-table-hline-p)
8801 (looking-at "[ \t]*$"))
8802 (error "Not in table data field")))
8804 (defvar org-table-clip nil
8805 "Clipboard for table regions.")
8807 (defun org-table-blank-field ()
8808 "Blank the current table field or active region."
8809 (interactive)
8810 (org-table-check-inside-data-field)
8811 (if (and (interactive-p) (org-region-active-p))
8812 (let (org-table-clip)
8813 (org-table-cut-region (region-beginning) (region-end)))
8814 (skip-chars-backward "^|")
8815 (backward-char 1)
8816 (if (looking-at "|[^|\n]+")
8817 (let* ((pos (match-beginning 0))
8818 (match (match-string 0))
8819 (len (org-string-width match)))
8820 (replace-match (concat "|" (make-string (1- len) ?\ )))
8821 (goto-char (+ 2 pos))
8822 (substring match 1)))))
8824 (defun org-table-get-field (&optional n replace)
8825 "Return the value of the field in column N of current row.
8826 N defaults to current field.
8827 If REPLACE is a string, replace field with this value. The return value
8828 is always the old value."
8829 (and n (org-table-goto-column n))
8830 (skip-chars-backward "^|\n")
8831 (backward-char 1)
8832 (if (looking-at "|[^|\r\n]*")
8833 (let* ((pos (match-beginning 0))
8834 (val (buffer-substring (1+ pos) (match-end 0))))
8835 (if replace
8836 (replace-match (concat "|" replace) t t))
8837 (goto-char (min (point-at-eol) (+ 2 pos)))
8838 val)
8839 (forward-char 1) ""))
8841 (defun org-table-field-info (arg)
8842 "Show info about the current field, and highlight any reference at point."
8843 (interactive "P")
8844 (org-table-get-specials)
8845 (save-excursion
8846 (let* ((pos (point))
8847 (col (org-table-current-column))
8848 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8849 (name (car (rassoc (list (org-current-line) col)
8850 org-table-named-field-locations)))
8851 (eql (org-table-get-stored-formulas))
8852 (dline (org-table-current-dline))
8853 (ref (format "@%d$%d" dline col))
8854 (ref1 (org-table-convert-refs-to-an ref))
8855 (fequation (or (assoc name eql) (assoc ref eql)))
8856 (cequation (assoc (int-to-string col) eql))
8857 (eqn (or fequation cequation)))
8858 (goto-char pos)
8859 (condition-case nil
8860 (org-table-show-reference 'local)
8861 (error nil))
8862 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8863 dline col
8864 (if cname (concat " or $" cname) "")
8865 dline col ref1
8866 (if name (concat " or $" name) "")
8867 ;; FIXME: formula info not correct if special table line
8868 (if eqn
8869 (concat ", formula: "
8870 (org-table-formula-to-user
8871 (concat
8872 (if (string-match "^[$@]"(car eqn)) "" "$")
8873 (car eqn) "=" (cdr eqn))))
8874 "")))))
8876 (defun org-table-current-column ()
8877 "Find out which column we are in.
8878 When called interactively, column is also displayed in echo area."
8879 (interactive)
8880 (if (interactive-p) (org-table-check-inside-data-field))
8881 (save-excursion
8882 (let ((cnt 0) (pos (point)))
8883 (beginning-of-line 1)
8884 (while (search-forward "|" pos t)
8885 (setq cnt (1+ cnt)))
8886 (if (interactive-p) (message "This is table column %d" cnt))
8887 cnt)))
8889 (defun org-table-current-dline ()
8890 "Find out what table data line we are in.
8891 Only datalins count for this."
8892 (interactive)
8893 (if (interactive-p) (org-table-check-inside-data-field))
8894 (save-excursion
8895 (let ((cnt 0) (pos (point)))
8896 (goto-char (org-table-begin))
8897 (while (<= (point) pos)
8898 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8899 (beginning-of-line 2))
8900 (if (interactive-p) (message "This is table line %d" cnt))
8901 cnt)))
8903 (defun org-table-goto-column (n &optional on-delim force)
8904 "Move the cursor to the Nth column in the current table line.
8905 With optional argument ON-DELIM, stop with point before the left delimiter
8906 of the field.
8907 If there are less than N fields, just go to after the last delimiter.
8908 However, when FORCE is non-nil, create new columns if necessary."
8909 (interactive "p")
8910 (let ((pos (point-at-eol)))
8911 (beginning-of-line 1)
8912 (when (> n 0)
8913 (while (and (> (setq n (1- n)) -1)
8914 (or (search-forward "|" pos t)
8915 (and force
8916 (progn (end-of-line 1)
8917 (skip-chars-backward "^|")
8918 (insert " | "))))))
8919 ; (backward-char 2) t)))))
8920 (when (and force (not (looking-at ".*|")))
8921 (save-excursion (end-of-line 1) (insert " | ")))
8922 (if on-delim
8923 (backward-char 1)
8924 (if (looking-at " ") (forward-char 1))))))
8926 (defun org-at-table-p (&optional table-type)
8927 "Return t if the cursor is inside an org-type table.
8928 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8929 (if org-enable-table-editor
8930 (save-excursion
8931 (beginning-of-line 1)
8932 (looking-at (if table-type org-table-any-line-regexp
8933 org-table-line-regexp)))
8934 nil))
8936 (defun org-at-table.el-p ()
8937 "Return t if and only if we are at a table.el table."
8938 (and (org-at-table-p 'any)
8939 (save-excursion
8940 (goto-char (org-table-begin 'any))
8941 (looking-at org-table1-hline-regexp))))
8943 (defun org-table-recognize-table.el ()
8944 "If there is a table.el table nearby, recognize it and move into it."
8945 (if org-table-tab-recognizes-table.el
8946 (if (org-at-table.el-p)
8947 (progn
8948 (beginning-of-line 1)
8949 (if (looking-at org-table-dataline-regexp)
8951 (if (looking-at org-table1-hline-regexp)
8952 (progn
8953 (beginning-of-line 2)
8954 (if (looking-at org-table-any-border-regexp)
8955 (beginning-of-line -1)))))
8956 (if (re-search-forward "|" (org-table-end t) t)
8957 (progn
8958 (require 'table)
8959 (if (table--at-cell-p (point))
8961 (message "recognizing table.el table...")
8962 (table-recognize-table)
8963 (message "recognizing table.el table...done")))
8964 (error "This should not happen..."))
8966 nil)
8967 nil))
8969 (defun org-at-table-hline-p ()
8970 "Return t if the cursor is inside a hline in a table."
8971 (if org-enable-table-editor
8972 (save-excursion
8973 (beginning-of-line 1)
8974 (looking-at org-table-hline-regexp))
8975 nil))
8977 (defun org-table-insert-column ()
8978 "Insert a new column into the table."
8979 (interactive)
8980 (if (not (org-at-table-p))
8981 (error "Not at a table"))
8982 (org-table-find-dataline)
8983 (let* ((col (max 1 (org-table-current-column)))
8984 (beg (org-table-begin))
8985 (end (org-table-end))
8986 ;; Current cursor position
8987 (linepos (org-current-line))
8988 (colpos col))
8989 (goto-char beg)
8990 (while (< (point) end)
8991 (if (org-at-table-hline-p)
8993 (org-table-goto-column col t)
8994 (insert "| "))
8995 (beginning-of-line 2))
8996 (move-marker end nil)
8997 (goto-line linepos)
8998 (org-table-goto-column colpos)
8999 (org-table-align)
9000 (org-table-fix-formulas "$" nil (1- col) 1)))
9002 (defun org-table-find-dataline ()
9003 "Find a dataline in the current table, which is needed for column commands."
9004 (if (and (org-at-table-p)
9005 (not (org-at-table-hline-p)))
9007 (let ((col (current-column))
9008 (end (org-table-end)))
9009 (move-to-column col)
9010 (while (and (< (point) end)
9011 (or (not (= (current-column) col))
9012 (org-at-table-hline-p)))
9013 (beginning-of-line 2)
9014 (move-to-column col))
9015 (if (and (org-at-table-p)
9016 (not (org-at-table-hline-p)))
9018 (error
9019 "Please position cursor in a data line for column operations")))))
9021 (defun org-table-delete-column ()
9022 "Delete a column from the table."
9023 (interactive)
9024 (if (not (org-at-table-p))
9025 (error "Not at a table"))
9026 (org-table-find-dataline)
9027 (org-table-check-inside-data-field)
9028 (let* ((col (org-table-current-column))
9029 (beg (org-table-begin))
9030 (end (org-table-end))
9031 ;; Current cursor position
9032 (linepos (org-current-line))
9033 (colpos col))
9034 (goto-char beg)
9035 (while (< (point) end)
9036 (if (org-at-table-hline-p)
9038 (org-table-goto-column col t)
9039 (and (looking-at "|[^|\n]+|")
9040 (replace-match "|")))
9041 (beginning-of-line 2))
9042 (move-marker end nil)
9043 (goto-line linepos)
9044 (org-table-goto-column colpos)
9045 (org-table-align)
9046 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9047 col -1 col)))
9049 (defun org-table-move-column-right ()
9050 "Move column to the right."
9051 (interactive)
9052 (org-table-move-column nil))
9053 (defun org-table-move-column-left ()
9054 "Move column to the left."
9055 (interactive)
9056 (org-table-move-column 'left))
9058 (defun org-table-move-column (&optional left)
9059 "Move the current column to the right. With arg LEFT, move to the left."
9060 (interactive "P")
9061 (if (not (org-at-table-p))
9062 (error "Not at a table"))
9063 (org-table-find-dataline)
9064 (org-table-check-inside-data-field)
9065 (let* ((col (org-table-current-column))
9066 (col1 (if left (1- col) col))
9067 (beg (org-table-begin))
9068 (end (org-table-end))
9069 ;; Current cursor position
9070 (linepos (org-current-line))
9071 (colpos (if left (1- col) (1+ col))))
9072 (if (and left (= col 1))
9073 (error "Cannot move column further left"))
9074 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9075 (error "Cannot move column further right"))
9076 (goto-char beg)
9077 (while (< (point) end)
9078 (if (org-at-table-hline-p)
9080 (org-table-goto-column col1 t)
9081 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9082 (replace-match "|\\2|\\1|")))
9083 (beginning-of-line 2))
9084 (move-marker end nil)
9085 (goto-line linepos)
9086 (org-table-goto-column colpos)
9087 (org-table-align)
9088 (org-table-fix-formulas
9089 "$" (list (cons (number-to-string col) (number-to-string colpos))
9090 (cons (number-to-string colpos) (number-to-string col))))))
9092 (defun org-table-move-row-down ()
9093 "Move table row down."
9094 (interactive)
9095 (org-table-move-row nil))
9096 (defun org-table-move-row-up ()
9097 "Move table row up."
9098 (interactive)
9099 (org-table-move-row 'up))
9101 (defun org-table-move-row (&optional up)
9102 "Move the current table line down. With arg UP, move it up."
9103 (interactive "P")
9104 (let* ((col (current-column))
9105 (pos (point))
9106 (hline1p (save-excursion (beginning-of-line 1)
9107 (looking-at org-table-hline-regexp)))
9108 (dline1 (org-table-current-dline))
9109 (dline2 (+ dline1 (if up -1 1)))
9110 (tonew (if up 0 2))
9111 txt hline2p)
9112 (beginning-of-line tonew)
9113 (unless (org-at-table-p)
9114 (goto-char pos)
9115 (error "Cannot move row further"))
9116 (setq hline2p (looking-at org-table-hline-regexp))
9117 (goto-char pos)
9118 (beginning-of-line 1)
9119 (setq pos (point))
9120 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9121 (delete-region (point) (1+ (point-at-eol)))
9122 (beginning-of-line tonew)
9123 (insert txt)
9124 (beginning-of-line 0)
9125 (move-to-column col)
9126 (unless (or hline1p hline2p)
9127 (org-table-fix-formulas
9128 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9129 (cons (number-to-string dline2) (number-to-string dline1)))))))
9131 (defun org-table-insert-row (&optional arg)
9132 "Insert a new row above the current line into the table.
9133 With prefix ARG, insert below the current line."
9134 (interactive "P")
9135 (if (not (org-at-table-p))
9136 (error "Not at a table"))
9137 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9138 (new (org-table-clean-line line)))
9139 ;; Fix the first field if necessary
9140 (if (string-match "^[ \t]*| *[#$] *|" line)
9141 (setq new (replace-match (match-string 0 line) t t new)))
9142 (beginning-of-line (if arg 2 1))
9143 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9144 (beginning-of-line 0)
9145 (re-search-forward "| ?" (point-at-eol) t)
9146 (and (or org-table-may-need-update org-table-overlay-coordinates)
9147 (org-table-align))
9148 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9150 (defun org-table-insert-hline (&optional above)
9151 "Insert a horizontal-line below the current line into the table.
9152 With prefix ABOVE, insert above the current line."
9153 (interactive "P")
9154 (if (not (org-at-table-p))
9155 (error "Not at a table"))
9156 (let ((line (org-table-clean-line
9157 (buffer-substring (point-at-bol) (point-at-eol))))
9158 (col (current-column)))
9159 (while (string-match "|\\( +\\)|" line)
9160 (setq line (replace-match
9161 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9162 ?-) "|") t t line)))
9163 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9164 (beginning-of-line (if above 1 2))
9165 (insert line "\n")
9166 (beginning-of-line (if above 1 -1))
9167 (move-to-column col)
9168 (and org-table-overlay-coordinates (org-table-align))))
9170 (defun org-table-hline-and-move (&optional same-column)
9171 "Insert a hline and move to the row below that line."
9172 (interactive "P")
9173 (let ((col (org-table-current-column)))
9174 (org-table-maybe-eval-formula)
9175 (org-table-maybe-recalculate-line)
9176 (org-table-insert-hline)
9177 (end-of-line 2)
9178 (if (looking-at "\n[ \t]*|-")
9179 (progn (insert "\n|") (org-table-align))
9180 (org-table-next-field))
9181 (if same-column (org-table-goto-column col))))
9183 (defun org-table-clean-line (s)
9184 "Convert a table line S into a string with only \"|\" and space.
9185 In particular, this does handle wide and invisible characters."
9186 (if (string-match "^[ \t]*|-" s)
9187 ;; It's a hline, just map the characters
9188 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9189 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9190 (setq s (replace-match
9191 (concat "|" (make-string (org-string-width (match-string 1 s))
9192 ?\ ) "|")
9193 t t s)))
9196 (defun org-table-kill-row ()
9197 "Delete the current row or horizontal line from the table."
9198 (interactive)
9199 (if (not (org-at-table-p))
9200 (error "Not at a table"))
9201 (let ((col (current-column))
9202 (dline (org-table-current-dline)))
9203 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9204 (if (not (org-at-table-p)) (beginning-of-line 0))
9205 (move-to-column col)
9206 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9207 dline -1 dline)))
9209 (defun org-table-sort-lines (with-case &optional sorting-type)
9210 "Sort table lines according to the column at point.
9212 The position of point indicates the column to be used for
9213 sorting, and the range of lines is the range between the nearest
9214 horizontal separator lines, or the entire table of no such lines
9215 exist. If point is before the first column, you will be prompted
9216 for the sorting column. If there is an active region, the mark
9217 specifies the first line and the sorting column, while point
9218 should be in the last line to be included into the sorting.
9220 The command then prompts for the sorting type which can be
9221 alphabetically, numerically, or by time (as given in a time stamp
9222 in the field). Sorting in reverse order is also possible.
9224 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9226 If SORTING-TYPE is specified when this function is called from a Lisp
9227 program, no prompting will take place. SORTING-TYPE must be a character,
9228 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9229 should be done in reverse order."
9230 (interactive "P")
9231 (let* ((thisline (org-current-line))
9232 (thiscol (org-table-current-column))
9233 beg end bcol ecol tend tbeg column lns pos)
9234 (when (equal thiscol 0)
9235 (if (interactive-p)
9236 (setq thiscol
9237 (string-to-number
9238 (read-string "Use column N for sorting: ")))
9239 (setq thiscol 1))
9240 (org-table-goto-column thiscol))
9241 (org-table-check-inside-data-field)
9242 (if (org-region-active-p)
9243 (progn
9244 (setq beg (region-beginning) end (region-end))
9245 (goto-char beg)
9246 (setq column (org-table-current-column)
9247 beg (point-at-bol))
9248 (goto-char end)
9249 (setq end (point-at-bol 2)))
9250 (setq column (org-table-current-column)
9251 pos (point)
9252 tbeg (org-table-begin)
9253 tend (org-table-end))
9254 (if (re-search-backward org-table-hline-regexp tbeg t)
9255 (setq beg (point-at-bol 2))
9256 (goto-char tbeg)
9257 (setq beg (point-at-bol 1)))
9258 (goto-char pos)
9259 (if (re-search-forward org-table-hline-regexp tend t)
9260 (setq end (point-at-bol 1))
9261 (goto-char tend)
9262 (setq end (point-at-bol))))
9263 (setq beg (move-marker (make-marker) beg)
9264 end (move-marker (make-marker) end))
9265 (untabify beg end)
9266 (goto-char beg)
9267 (org-table-goto-column column)
9268 (skip-chars-backward "^|")
9269 (setq bcol (current-column))
9270 (org-table-goto-column (1+ column))
9271 (skip-chars-backward "^|")
9272 (setq ecol (1- (current-column)))
9273 (org-table-goto-column column)
9274 (setq lns (mapcar (lambda(x) (cons
9275 (org-sort-remove-invisible
9276 (nth (1- column)
9277 (org-split-string x "[ \t]*|[ \t]*")))
9279 (org-split-string (buffer-substring beg end) "\n")))
9280 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9281 (delete-region beg end)
9282 (move-marker beg nil)
9283 (move-marker end nil)
9284 (insert (mapconcat 'cdr lns "\n") "\n")
9285 (goto-line thisline)
9286 (org-table-goto-column thiscol)
9287 (message "%d lines sorted, based on column %d" (length lns) column)))
9289 ;; FIXME: maybe we will not need this? Table sorting is broken....
9290 (defun org-sort-remove-invisible (s)
9291 (remove-text-properties 0 (length s) org-rm-props s)
9292 (while (string-match org-bracket-link-regexp s)
9293 (setq s (replace-match (if (match-end 2)
9294 (match-string 3 s)
9295 (match-string 1 s)) t t s)))
9298 (defun org-table-cut-region (beg end)
9299 "Copy region in table to the clipboard and blank all relevant fields."
9300 (interactive "r")
9301 (org-table-copy-region beg end 'cut))
9303 (defun org-table-copy-region (beg end &optional cut)
9304 "Copy rectangular region in table to clipboard.
9305 A special clipboard is used which can only be accessed
9306 with `org-table-paste-rectangle'."
9307 (interactive "rP")
9308 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9309 region cols
9310 (rpl (if cut " " nil)))
9311 (goto-char beg)
9312 (org-table-check-inside-data-field)
9313 (setq l01 (org-current-line)
9314 c01 (org-table-current-column))
9315 (goto-char end)
9316 (org-table-check-inside-data-field)
9317 (setq l02 (org-current-line)
9318 c02 (org-table-current-column))
9319 (setq l1 (min l01 l02) l2 (max l01 l02)
9320 c1 (min c01 c02) c2 (max c01 c02))
9321 (catch 'exit
9322 (while t
9323 (catch 'nextline
9324 (if (> l1 l2) (throw 'exit t))
9325 (goto-line l1)
9326 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9327 (setq cols nil ic1 c1 ic2 c2)
9328 (while (< ic1 (1+ ic2))
9329 (push (org-table-get-field ic1 rpl) cols)
9330 (setq ic1 (1+ ic1)))
9331 (push (nreverse cols) region)
9332 (setq l1 (1+ l1)))))
9333 (setq org-table-clip (nreverse region))
9334 (if cut (org-table-align))
9335 org-table-clip))
9337 (defun org-table-paste-rectangle ()
9338 "Paste a rectangular region into a table.
9339 The upper right corner ends up in the current field. All involved fields
9340 will be overwritten. If the rectangle does not fit into the present table,
9341 the table is enlarged as needed. The process ignores horizontal separator
9342 lines."
9343 (interactive)
9344 (unless (and org-table-clip (listp org-table-clip))
9345 (error "First cut/copy a region to paste!"))
9346 (org-table-check-inside-data-field)
9347 (let* ((clip org-table-clip)
9348 (line (org-current-line))
9349 (col (org-table-current-column))
9350 (org-enable-table-editor t)
9351 (org-table-automatic-realign nil)
9352 c cols field)
9353 (while (setq cols (pop clip))
9354 (while (org-at-table-hline-p) (beginning-of-line 2))
9355 (if (not (org-at-table-p))
9356 (progn (end-of-line 0) (org-table-next-field)))
9357 (setq c col)
9358 (while (setq field (pop cols))
9359 (org-table-goto-column c nil 'force)
9360 (org-table-get-field nil field)
9361 (setq c (1+ c)))
9362 (beginning-of-line 2))
9363 (goto-line line)
9364 (org-table-goto-column col)
9365 (org-table-align)))
9367 (defun org-table-convert ()
9368 "Convert from `org-mode' table to table.el and back.
9369 Obviously, this only works within limits. When an Org-mode table is
9370 converted to table.el, all horizontal separator lines get lost, because
9371 table.el uses these as cell boundaries and has no notion of horizontal lines.
9372 A table.el table can be converted to an Org-mode table only if it does not
9373 do row or column spanning. Multiline cells will become multiple cells.
9374 Beware, Org-mode does not test if the table can be successfully converted - it
9375 blindly applies a recipe that works for simple tables."
9376 (interactive)
9377 (require 'table)
9378 (if (org-at-table.el-p)
9379 ;; convert to Org-mode table
9380 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9381 (end (move-marker (make-marker) (org-table-end t))))
9382 (table-unrecognize-region beg end)
9383 (goto-char beg)
9384 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9385 (replace-match ""))
9386 (goto-char beg))
9387 (if (org-at-table-p)
9388 ;; convert to table.el table
9389 (let ((beg (move-marker (make-marker) (org-table-begin)))
9390 (end (move-marker (make-marker) (org-table-end))))
9391 ;; first, get rid of all horizontal lines
9392 (goto-char beg)
9393 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9394 (replace-match ""))
9395 ;; insert a hline before first
9396 (goto-char beg)
9397 (org-table-insert-hline 'above)
9398 (beginning-of-line -1)
9399 ;; insert a hline after each line
9400 (while (progn (beginning-of-line 3) (< (point) end))
9401 (org-table-insert-hline))
9402 (goto-char beg)
9403 (setq end (move-marker end (org-table-end)))
9404 ;; replace "+" at beginning and ending of hlines
9405 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9406 (replace-match "\\1+-"))
9407 (goto-char beg)
9408 (while (re-search-forward "-|[ \t]*$" end t)
9409 (replace-match "-+"))
9410 (goto-char beg)))))
9412 (defun org-table-wrap-region (arg)
9413 "Wrap several fields in a column like a paragraph.
9414 This is useful if you'd like to spread the contents of a field over several
9415 lines, in order to keep the table compact.
9417 If there is an active region, and both point and mark are in the same column,
9418 the text in the column is wrapped to minimum width for the given number of
9419 lines. Generally, this makes the table more compact. A prefix ARG may be
9420 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9421 formats the selected text to two lines. If the region was longer than two
9422 lines, the remaining lines remain empty. A negative prefix argument reduces
9423 the current number of lines by that amount. The wrapped text is pasted back
9424 into the table. If you formatted it to more lines than it was before, fields
9425 further down in the table get overwritten - so you might need to make space in
9426 the table first.
9428 If there is no region, the current field is split at the cursor position and
9429 the text fragment to the right of the cursor is prepended to the field one
9430 line down.
9432 If there is no region, but you specify a prefix ARG, the current field gets
9433 blank, and the content is appended to the field above."
9434 (interactive "P")
9435 (org-table-check-inside-data-field)
9436 (if (org-region-active-p)
9437 ;; There is a region: fill as a paragraph
9438 (let* ((beg (region-beginning))
9439 (cline (save-excursion (goto-char beg) (org-current-line)))
9440 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9441 nlines)
9442 (org-table-cut-region (region-beginning) (region-end))
9443 (if (> (length (car org-table-clip)) 1)
9444 (error "Region must be limited to single column"))
9445 (setq nlines (if arg
9446 (if (< arg 1)
9447 (+ (length org-table-clip) arg)
9448 arg)
9449 (length org-table-clip)))
9450 (setq org-table-clip
9451 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9452 nil nlines)))
9453 (goto-line cline)
9454 (org-table-goto-column ccol)
9455 (org-table-paste-rectangle))
9456 ;; No region, split the current field at point
9457 (if arg
9458 ;; combine with field above
9459 (let ((s (org-table-blank-field))
9460 (col (org-table-current-column)))
9461 (beginning-of-line 0)
9462 (while (org-at-table-hline-p) (beginning-of-line 0))
9463 (org-table-goto-column col)
9464 (skip-chars-forward "^|")
9465 (skip-chars-backward " ")
9466 (insert " " (org-trim s))
9467 (org-table-align))
9468 ;; split field
9469 (when (looking-at "\\([^|]+\\)+|")
9470 (let ((s (match-string 1)))
9471 (replace-match " |")
9472 (goto-char (match-beginning 0))
9473 (org-table-next-row)
9474 (insert (org-trim s) " ")
9475 (org-table-align))))))
9477 (defvar org-field-marker nil)
9479 (defun org-table-edit-field (arg)
9480 "Edit table field in a different window.
9481 This is mainly useful for fields that contain hidden parts.
9482 When called with a \\[universal-argument] prefix, just make the full field visible so that
9483 it can be edited in place."
9484 (interactive "P")
9485 (if arg
9486 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9487 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9488 (remove-text-properties b e '(org-cwidth t invisible t
9489 display t intangible t))
9490 (if (and (boundp 'font-lock-mode) font-lock-mode)
9491 (font-lock-fontify-block)))
9492 (let ((pos (move-marker (make-marker) (point)))
9493 (field (org-table-get-field))
9494 (cw (current-window-configuration))
9496 (org-switch-to-buffer-other-window "*Org tmp*")
9497 (erase-buffer)
9498 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9499 (let ((org-inhibit-startup t)) (org-mode))
9500 (goto-char (setq p (point-max)))
9501 (insert (org-trim field))
9502 (remove-text-properties p (point-max)
9503 '(invisible t org-cwidth t display t
9504 intangible t))
9505 (goto-char p)
9506 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9507 (org-set-local 'org-window-configuration cw)
9508 (org-set-local 'org-field-marker pos)
9509 (message "Edit and finish with C-c C-c"))))
9511 (defun org-table-finish-edit-field ()
9512 "Finish editing a table data field.
9513 Remove all newline characters, insert the result into the table, realign
9514 the table and kill the editing buffer."
9515 (let ((pos org-field-marker)
9516 (cw org-window-configuration)
9517 (cb (current-buffer))
9518 text)
9519 (goto-char (point-min))
9520 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9521 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9522 (replace-match " "))
9523 (setq text (org-trim (buffer-string)))
9524 (set-window-configuration cw)
9525 (kill-buffer cb)
9526 (select-window (get-buffer-window (marker-buffer pos)))
9527 (goto-char pos)
9528 (move-marker pos nil)
9529 (org-table-check-inside-data-field)
9530 (org-table-get-field nil text)
9531 (org-table-align)
9532 (message "New field value inserted")))
9534 (defun org-trim (s)
9535 "Remove whitespace at beginning and end of string."
9536 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9537 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9540 (defun org-wrap (string &optional width lines)
9541 "Wrap string to either a number of lines, or a width in characters.
9542 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9543 that costs. If there is a word longer than WIDTH, the text is actually
9544 wrapped to the length of that word.
9545 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9546 many lines, whatever width that takes.
9547 The return value is a list of lines, without newlines at the end."
9548 (let* ((words (org-split-string string "[ \t\n]+"))
9549 (maxword (apply 'max (mapcar 'org-string-width words)))
9550 w ll)
9551 (cond (width
9552 (org-do-wrap words (max maxword width)))
9553 (lines
9554 (setq w maxword)
9555 (setq ll (org-do-wrap words maxword))
9556 (if (<= (length ll) lines)
9558 (setq ll words)
9559 (while (> (length ll) lines)
9560 (setq w (1+ w))
9561 (setq ll (org-do-wrap words w)))
9562 ll))
9563 (t (error "Cannot wrap this")))))
9566 (defun org-do-wrap (words width)
9567 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9568 (let (lines line)
9569 (while words
9570 (setq line (pop words))
9571 (while (and words (< (+ (length line) (length (car words))) width))
9572 (setq line (concat line " " (pop words))))
9573 (setq lines (push line lines)))
9574 (nreverse lines)))
9576 (defun org-split-string (string &optional separators)
9577 "Splits STRING into substrings at SEPARATORS.
9578 No empty strings are returned if there are matches at the beginning
9579 and end of string."
9580 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9581 (start 0)
9582 notfirst
9583 (list nil))
9584 (while (and (string-match rexp string
9585 (if (and notfirst
9586 (= start (match-beginning 0))
9587 (< start (length string)))
9588 (1+ start) start))
9589 (< (match-beginning 0) (length string)))
9590 (setq notfirst t)
9591 (or (eq (match-beginning 0) 0)
9592 (and (eq (match-beginning 0) (match-end 0))
9593 (eq (match-beginning 0) start))
9594 (setq list
9595 (cons (substring string start (match-beginning 0))
9596 list)))
9597 (setq start (match-end 0)))
9598 (or (eq start (length string))
9599 (setq list
9600 (cons (substring string start)
9601 list)))
9602 (nreverse list)))
9604 (defun org-table-map-tables (function)
9605 "Apply FUNCTION to the start of all tables in the buffer."
9606 (save-excursion
9607 (save-restriction
9608 (widen)
9609 (goto-char (point-min))
9610 (while (re-search-forward org-table-any-line-regexp nil t)
9611 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9612 (beginning-of-line 1)
9613 (if (looking-at org-table-line-regexp)
9614 (save-excursion (funcall function)))
9615 (re-search-forward org-table-any-border-regexp nil 1))))
9616 (message "Mapping tables: done"))
9618 (defvar org-timecnt) ; dynamically scoped parameter
9620 (defun org-table-sum (&optional beg end nlast)
9621 "Sum numbers in region of current table column.
9622 The result will be displayed in the echo area, and will be available
9623 as kill to be inserted with \\[yank].
9625 If there is an active region, it is interpreted as a rectangle and all
9626 numbers in that rectangle will be summed. If there is no active
9627 region and point is located in a table column, sum all numbers in that
9628 column.
9630 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9631 numbers are assumed to be times as well (in decimal hours) and the
9632 numbers are added as such.
9634 If NLAST is a number, only the NLAST fields will actually be summed."
9635 (interactive)
9636 (save-excursion
9637 (let (col (org-timecnt 0) diff h m s org-table-clip)
9638 (cond
9639 ((and beg end)) ; beg and end given explicitly
9640 ((org-region-active-p)
9641 (setq beg (region-beginning) end (region-end)))
9643 (setq col (org-table-current-column))
9644 (goto-char (org-table-begin))
9645 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9646 (error "No table data"))
9647 (org-table-goto-column col)
9648 (setq beg (point))
9649 (goto-char (org-table-end))
9650 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9651 (error "No table data"))
9652 (org-table-goto-column col)
9653 (setq end (point))))
9654 (let* ((items (apply 'append (org-table-copy-region beg end)))
9655 (items1 (cond ((not nlast) items)
9656 ((>= nlast (length items)) items)
9657 (t (setq items (reverse items))
9658 (setcdr (nthcdr (1- nlast) items) nil)
9659 (nreverse items))))
9660 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9661 items1)))
9662 (res (apply '+ numbers))
9663 (sres (if (= org-timecnt 0)
9664 (format "%g" res)
9665 (setq diff (* 3600 res)
9666 h (floor (/ diff 3600)) diff (mod diff 3600)
9667 m (floor (/ diff 60)) diff (mod diff 60)
9668 s diff)
9669 (format "%d:%02d:%02d" h m s))))
9670 (kill-new sres)
9671 (if (interactive-p)
9672 (message "%s"
9673 (substitute-command-keys
9674 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9675 (length numbers) sres))))
9676 sres))))
9678 (defun org-table-get-number-for-summing (s)
9679 (let (n)
9680 (if (string-match "^ *|? *" s)
9681 (setq s (replace-match "" nil nil s)))
9682 (if (string-match " *|? *$" s)
9683 (setq s (replace-match "" nil nil s)))
9684 (setq n (string-to-number s))
9685 (cond
9686 ((and (string-match "0" s)
9687 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9688 ((string-match "\\`[ \t]+\\'" s) nil)
9689 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9690 (let ((h (string-to-number (or (match-string 1 s) "0")))
9691 (m (string-to-number (or (match-string 2 s) "0")))
9692 (s (string-to-number (or (match-string 4 s) "0"))))
9693 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9694 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9695 ((equal n 0) nil)
9696 (t n))))
9698 (defun org-table-current-field-formula (&optional key noerror)
9699 "Return the formula active for the current field.
9700 Assumes that specials are in place.
9701 If KEY is given, return the key to this formula.
9702 Otherwise return the formula preceeded with \"=\" or \":=\"."
9703 (let* ((name (car (rassoc (list (org-current-line)
9704 (org-table-current-column))
9705 org-table-named-field-locations)))
9706 (col (org-table-current-column))
9707 (scol (int-to-string col))
9708 (ref (format "@%d$%d" (org-table-current-dline) col))
9709 (stored-list (org-table-get-stored-formulas noerror))
9710 (ass (or (assoc name stored-list)
9711 (assoc ref stored-list)
9712 (assoc scol stored-list))))
9713 (if key
9714 (car ass)
9715 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9716 (cdr ass))))))
9718 (defun org-table-get-formula (&optional equation named)
9719 "Read a formula from the minibuffer, offer stored formula as default.
9720 When NAMED is non-nil, look for a named equation."
9721 (let* ((stored-list (org-table-get-stored-formulas))
9722 (name (car (rassoc (list (org-current-line)
9723 (org-table-current-column))
9724 org-table-named-field-locations)))
9725 (ref (format "@%d$%d" (org-table-current-dline)
9726 (org-table-current-column)))
9727 (refass (assoc ref stored-list))
9728 (scol (if named
9729 (if name name ref)
9730 (int-to-string (org-table-current-column))))
9731 (dummy (and (or name refass) (not named)
9732 (not (y-or-n-p "Replace field formula with column formula? " ))
9733 (error "Abort")))
9734 (name (or name ref))
9735 (org-table-may-need-update nil)
9736 (stored (cdr (assoc scol stored-list)))
9737 (eq (cond
9738 ((and stored equation (string-match "^ *=? *$" equation))
9739 stored)
9740 ((stringp equation)
9741 equation)
9742 (t (org-table-formula-from-user
9743 (read-string
9744 (org-table-formula-to-user
9745 (format "%s formula %s%s="
9746 (if named "Field" "Column")
9747 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9748 scol))
9749 (if stored (org-table-formula-to-user stored) "")
9750 'org-table-formula-history
9751 )))))
9752 mustsave)
9753 (when (not (string-match "\\S-" eq))
9754 ;; remove formula
9755 (setq stored-list (delq (assoc scol stored-list) stored-list))
9756 (org-table-store-formulas stored-list)
9757 (error "Formula removed"))
9758 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9759 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9760 (if (and name (not named))
9761 ;; We set the column equation, delete the named one.
9762 (setq stored-list (delq (assoc name stored-list) stored-list)
9763 mustsave t))
9764 (if stored
9765 (setcdr (assoc scol stored-list) eq)
9766 (setq stored-list (cons (cons scol eq) stored-list)))
9767 (if (or mustsave (not (equal stored eq)))
9768 (org-table-store-formulas stored-list))
9769 eq))
9771 (defun org-table-store-formulas (alist)
9772 "Store the list of formulas below the current table."
9773 (setq alist (sort alist 'org-table-formula-less-p))
9774 (save-excursion
9775 (goto-char (org-table-end))
9776 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9777 (progn
9778 ;; don't overwrite TBLFM, we might use text properties to store stuff
9779 (goto-char (match-beginning 2))
9780 (delete-region (match-beginning 2) (match-end 0)))
9781 (insert "#+TBLFM:"))
9782 (insert " "
9783 (mapconcat (lambda (x)
9784 (concat
9785 (if (equal (string-to-char (car x)) ?@) "" "$")
9786 (car x) "=" (cdr x)))
9787 alist "::")
9788 "\n")))
9790 (defsubst org-table-formula-make-cmp-string (a)
9791 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9792 (concat
9793 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9794 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9795 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9797 (defun org-table-formula-less-p (a b)
9798 "Compare two formulas for sorting."
9799 (let ((as (org-table-formula-make-cmp-string (car a)))
9800 (bs (org-table-formula-make-cmp-string (car b))))
9801 (and as bs (string< as bs))))
9803 (defun org-table-get-stored-formulas (&optional noerror)
9804 "Return an alist with the stored formulas directly after current table."
9805 (interactive)
9806 (let (scol eq eq-alist strings string seen)
9807 (save-excursion
9808 (goto-char (org-table-end))
9809 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9810 (setq strings (org-split-string (match-string 2) " *:: *"))
9811 (while (setq string (pop strings))
9812 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9813 (setq scol (if (match-end 2)
9814 (match-string 2 string)
9815 (match-string 1 string))
9816 eq (match-string 3 string)
9817 eq-alist (cons (cons scol eq) eq-alist))
9818 (if (member scol seen)
9819 (if noerror
9820 (progn
9821 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9822 (ding)
9823 (sit-for 2))
9824 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9825 (push scol seen))))))
9826 (nreverse eq-alist)))
9828 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9829 "Modify the equations after the table structure has been edited.
9830 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9831 For all numbers larger than LIMIT, shift them by DELTA."
9832 (save-excursion
9833 (goto-char (org-table-end))
9834 (when (looking-at "#\\+TBLFM:")
9835 (let ((re (concat key "\\([0-9]+\\)"))
9836 (re2
9837 (when remove
9838 (if (equal key "$")
9839 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9840 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9841 s n a)
9842 (when remove
9843 (while (re-search-forward re2 (point-at-eol) t)
9844 (replace-match "")))
9845 (while (re-search-forward re (point-at-eol) t)
9846 (setq s (match-string 1) n (string-to-number s))
9847 (cond
9848 ((setq a (assoc s replace))
9849 (replace-match (concat key (cdr a)) t t))
9850 ((and limit (> n limit))
9851 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9853 (defun org-table-get-specials ()
9854 "Get the column names and local parameters for this table."
9855 (save-excursion
9856 (let ((beg (org-table-begin)) (end (org-table-end))
9857 names name fields fields1 field cnt
9858 c v l line col types dlines hlines)
9859 (setq org-table-column-names nil
9860 org-table-local-parameters nil
9861 org-table-named-field-locations nil
9862 org-table-current-begin-line nil
9863 org-table-current-begin-pos nil
9864 org-table-current-line-types nil)
9865 (goto-char beg)
9866 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9867 (setq names (org-split-string (match-string 1) " *| *")
9868 cnt 1)
9869 (while (setq name (pop names))
9870 (setq cnt (1+ cnt))
9871 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9872 (push (cons name (int-to-string cnt)) org-table-column-names))))
9873 (setq org-table-column-names (nreverse org-table-column-names))
9874 (setq org-table-column-name-regexp
9875 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9876 (goto-char beg)
9877 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9878 (setq fields (org-split-string (match-string 1) " *| *"))
9879 (while (setq field (pop fields))
9880 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9881 (push (cons (match-string 1 field) (match-string 2 field))
9882 org-table-local-parameters))))
9883 (goto-char beg)
9884 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9885 (setq c (match-string 1)
9886 fields (org-split-string (match-string 2) " *| *"))
9887 (save-excursion
9888 (beginning-of-line (if (equal c "_") 2 0))
9889 (setq line (org-current-line) col 1)
9890 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9891 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9892 (while (and fields1 (setq field (pop fields)))
9893 (setq v (pop fields1) col (1+ col))
9894 (when (and (stringp field) (stringp v)
9895 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9896 (push (cons field v) org-table-local-parameters)
9897 (push (list field line col) org-table-named-field-locations))))
9898 ;; Analyse the line types
9899 (goto-char beg)
9900 (setq org-table-current-begin-line (org-current-line)
9901 org-table-current-begin-pos (point)
9902 l org-table-current-begin-line)
9903 (while (looking-at "[ \t]*|\\(-\\)?")
9904 (push (if (match-end 1) 'hline 'dline) types)
9905 (if (match-end 1) (push l hlines) (push l dlines))
9906 (beginning-of-line 2)
9907 (setq l (1+ l)))
9908 (setq org-table-current-line-types (apply 'vector (nreverse types))
9909 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9910 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9912 (defun org-table-maybe-eval-formula ()
9913 "Check if the current field starts with \"=\" or \":=\".
9914 If yes, store the formula and apply it."
9915 ;; We already know we are in a table. Get field will only return a formula
9916 ;; when appropriate. It might return a separator line, but no problem.
9917 (when org-table-formula-evaluate-inline
9918 (let* ((field (org-trim (or (org-table-get-field) "")))
9919 named eq)
9920 (when (string-match "^:?=\\(.*\\)" field)
9921 (setq named (equal (string-to-char field) ?:)
9922 eq (match-string 1 field))
9923 (if (or (fboundp 'calc-eval)
9924 (equal (substring eq 0 (min 2 (length eq))) "'("))
9925 (org-table-eval-formula (if named '(4) nil)
9926 (org-table-formula-from-user eq))
9927 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9929 (defvar org-recalc-commands nil
9930 "List of commands triggering the recalculation of a line.
9931 Will be filled automatically during use.")
9933 (defvar org-recalc-marks
9934 '((" " . "Unmarked: no special line, no automatic recalculation")
9935 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9936 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9937 ("!" . "Column name definition line. Reference in formula as $name.")
9938 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9939 ("_" . "Names for values in row below this one.")
9940 ("^" . "Names for values in row above this one.")))
9942 (defun org-table-rotate-recalc-marks (&optional newchar)
9943 "Rotate the recalculation mark in the first column.
9944 If in any row, the first field is not consistent with a mark,
9945 insert a new column for the markers.
9946 When there is an active region, change all the lines in the region,
9947 after prompting for the marking character.
9948 After each change, a message will be displayed indicating the meaning
9949 of the new mark."
9950 (interactive)
9951 (unless (org-at-table-p) (error "Not at a table"))
9952 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9953 (beg (org-table-begin))
9954 (end (org-table-end))
9955 (l (org-current-line))
9956 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9957 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9958 (have-col
9959 (save-excursion
9960 (goto-char beg)
9961 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9962 (col (org-table-current-column))
9963 (forcenew (car (assoc newchar org-recalc-marks)))
9964 epos new)
9965 (when l1
9966 (message "Change region to what mark? Type # * ! $ or SPC: ")
9967 (setq newchar (char-to-string (read-char-exclusive))
9968 forcenew (car (assoc newchar org-recalc-marks))))
9969 (if (and newchar (not forcenew))
9970 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9971 newchar))
9972 (if l1 (goto-line l1))
9973 (save-excursion
9974 (beginning-of-line 1)
9975 (unless (looking-at org-table-dataline-regexp)
9976 (error "Not at a table data line")))
9977 (unless have-col
9978 (org-table-goto-column 1)
9979 (org-table-insert-column)
9980 (org-table-goto-column (1+ col)))
9981 (setq epos (point-at-eol))
9982 (save-excursion
9983 (beginning-of-line 1)
9984 (org-table-get-field
9985 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9986 (concat " "
9987 (setq new (or forcenew
9988 (cadr (member (match-string 1) marks))))
9989 " ")
9990 " # ")))
9991 (if (and l1 l2)
9992 (progn
9993 (goto-line l1)
9994 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9995 (and (looking-at org-table-dataline-regexp)
9996 (org-table-get-field 1 (concat " " new " "))))
9997 (goto-line l1)))
9998 (if (not (= epos (point-at-eol))) (org-table-align))
9999 (goto-line l)
10000 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10002 (defun org-table-maybe-recalculate-line ()
10003 "Recompute the current line if marked for it, and if we haven't just done it."
10004 (interactive)
10005 (and org-table-allow-automatic-line-recalculation
10006 (not (and (memq last-command org-recalc-commands)
10007 (equal org-last-recalc-line (org-current-line))))
10008 (save-excursion (beginning-of-line 1)
10009 (looking-at org-table-auto-recalculate-regexp))
10010 (org-table-recalculate) t))
10012 (defvar org-table-formula-debug nil
10013 "Non-nil means, debug table formulas.
10014 When nil, simply write \"#ERROR\" in corrupted fields.")
10015 (make-variable-buffer-local 'org-table-formula-debug)
10017 (defvar modes)
10018 (defsubst org-set-calc-mode (var &optional value)
10019 (if (stringp var)
10020 (setq var (assoc var '(("D" calc-angle-mode deg)
10021 ("R" calc-angle-mode rad)
10022 ("F" calc-prefer-frac t)
10023 ("S" calc-symbolic-mode t)))
10024 value (nth 2 var) var (nth 1 var)))
10025 (if (memq var modes)
10026 (setcar (cdr (memq var modes)) value)
10027 (cons var (cons value modes)))
10028 modes)
10030 (defun org-table-eval-formula (&optional arg equation
10031 suppress-align suppress-const
10032 suppress-store suppress-analysis)
10033 "Replace the table field value at the cursor by the result of a calculation.
10035 This function makes use of Dave Gillespie's Calc package, in my view the
10036 most exciting program ever written for GNU Emacs. So you need to have Calc
10037 installed in order to use this function.
10039 In a table, this command replaces the value in the current field with the
10040 result of a formula. It also installs the formula as the \"current\" column
10041 formula, by storing it in a special line below the table. When called
10042 with a `C-u' prefix, the current field must ba a named field, and the
10043 formula is installed as valid in only this specific field.
10045 When called with two `C-u' prefixes, insert the active equation
10046 for the field back into the current field, so that it can be
10047 edited there. This is useful in order to use \\[org-table-show-reference]
10048 to check the referenced fields.
10050 When called, the command first prompts for a formula, which is read in
10051 the minibuffer. Previously entered formulas are available through the
10052 history list, and the last used formula is offered as a default.
10053 These stored formulas are adapted correctly when moving, inserting, or
10054 deleting columns with the corresponding commands.
10056 The formula can be any algebraic expression understood by the Calc package.
10057 For details, see the Org-mode manual.
10059 This function can also be called from Lisp programs and offers
10060 additional arguments: EQUATION can be the formula to apply. If this
10061 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10062 used to speed-up recursive calls by by-passing unnecessary aligns.
10063 SUPPRESS-CONST suppresses the interpretation of constants in the
10064 formula, assuming that this has been done already outside the function.
10065 SUPPRESS-STORE means the formula should not be stored, either because
10066 it is already stored, or because it is a modified equation that should
10067 not overwrite the stored one."
10068 (interactive "P")
10069 (org-table-check-inside-data-field)
10070 (or suppress-analysis (org-table-get-specials))
10071 (if (equal arg '(16))
10072 (let ((eq (org-table-current-field-formula)))
10073 (or eq (error "No equation active for current field"))
10074 (org-table-get-field nil eq)
10075 (org-table-align)
10076 (setq org-table-may-need-update t))
10077 (let* (fields
10078 (ndown (if (integerp arg) arg 1))
10079 (org-table-automatic-realign nil)
10080 (case-fold-search nil)
10081 (down (> ndown 1))
10082 (formula (if (and equation suppress-store)
10083 equation
10084 (org-table-get-formula equation (equal arg '(4)))))
10085 (n0 (org-table-current-column))
10086 (modes (copy-sequence org-calc-default-modes))
10087 (numbers nil) ; was a variable, now fixed default
10088 (keep-empty nil)
10089 n form form0 bw fmt x ev orig c lispp literal)
10090 ;; Parse the format string. Since we have a lot of modes, this is
10091 ;; a lot of work. However, I think calc still uses most of the time.
10092 (if (string-match ";" formula)
10093 (let ((tmp (org-split-string formula ";")))
10094 (setq formula (car tmp)
10095 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10096 (nth 1 tmp)))
10097 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10098 (setq c (string-to-char (match-string 1 fmt))
10099 n (string-to-number (match-string 2 fmt)))
10100 (if (= c ?p)
10101 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10102 (setq modes (org-set-calc-mode
10103 'calc-float-format
10104 (list (cdr (assoc c '((?n . float) (?f . fix)
10105 (?s . sci) (?e . eng))))
10106 n))))
10107 (setq fmt (replace-match "" t t fmt)))
10108 (if (string-match "[NT]" fmt)
10109 (setq numbers (equal (match-string 0 fmt) "N")
10110 fmt (replace-match "" t t fmt)))
10111 (if (string-match "L" fmt)
10112 (setq literal t
10113 fmt (replace-match "" t t fmt)))
10114 (if (string-match "E" fmt)
10115 (setq keep-empty t
10116 fmt (replace-match "" t t fmt)))
10117 (while (string-match "[DRFS]" fmt)
10118 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10119 (setq fmt (replace-match "" t t fmt)))
10120 (unless (string-match "\\S-" fmt)
10121 (setq fmt nil))))
10122 (if (and (not suppress-const) org-table-formula-use-constants)
10123 (setq formula (org-table-formula-substitute-names formula)))
10124 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10125 (while (> ndown 0)
10126 (setq fields (org-split-string
10127 (org-no-properties
10128 (buffer-substring (point-at-bol) (point-at-eol)))
10129 " *| *"))
10130 (if (eq numbers t)
10131 (setq fields (mapcar
10132 (lambda (x) (number-to-string (string-to-number x)))
10133 fields)))
10134 (setq ndown (1- ndown))
10135 (setq form (copy-sequence formula)
10136 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10137 (if (and lispp literal) (setq lispp 'literal))
10138 ;; Check for old vertical references
10139 (setq form (org-rewrite-old-row-references form))
10140 ;; Insert complex ranges
10141 (while (string-match org-table-range-regexp form)
10142 (setq form
10143 (replace-match
10144 (save-match-data
10145 (org-table-make-reference
10146 (org-table-get-range (match-string 0 form) nil n0)
10147 keep-empty numbers lispp))
10148 t t form)))
10149 ;; Insert simple ranges
10150 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10151 (setq form
10152 (replace-match
10153 (save-match-data
10154 (org-table-make-reference
10155 (org-sublist
10156 fields (string-to-number (match-string 1 form))
10157 (string-to-number (match-string 2 form)))
10158 keep-empty numbers lispp))
10159 t t form)))
10160 (setq form0 form)
10161 ;; Insert the references to fields in same row
10162 (while (string-match "\\$\\([0-9]+\\)" form)
10163 (setq n (string-to-number (match-string 1 form))
10164 x (nth (1- (if (= n 0) n0 n)) fields))
10165 (unless x (error "Invalid field specifier \"%s\""
10166 (match-string 0 form)))
10167 (setq form (replace-match
10168 (save-match-data
10169 (org-table-make-reference x nil numbers lispp))
10170 t t form)))
10172 (if lispp
10173 (setq ev (condition-case nil
10174 (eval (eval (read form)))
10175 (error "#ERROR"))
10176 ev (if (numberp ev) (number-to-string ev) ev))
10177 (or (fboundp 'calc-eval)
10178 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10179 (setq ev (calc-eval (cons form modes)
10180 (if numbers 'num))))
10182 (when org-table-formula-debug
10183 (with-output-to-temp-buffer "*Substitution History*"
10184 (princ (format "Substitution history of formula
10185 Orig: %s
10186 $xyz-> %s
10187 @r$c-> %s
10188 $1-> %s\n" orig formula form0 form))
10189 (if (listp ev)
10190 (princ (format " %s^\nError: %s"
10191 (make-string (car ev) ?\-) (nth 1 ev)))
10192 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10193 ev (or fmt "NONE")
10194 (if fmt (format fmt (string-to-number ev)) ev)))))
10195 (setq bw (get-buffer-window "*Substitution History*"))
10196 (shrink-window-if-larger-than-buffer bw)
10197 (unless (and (interactive-p) (not ndown))
10198 (unless (let (inhibit-redisplay)
10199 (y-or-n-p "Debugging Formula. Continue to next? "))
10200 (org-table-align)
10201 (error "Abort"))
10202 (delete-window bw)
10203 (message "")))
10204 (if (listp ev) (setq fmt nil ev "#ERROR"))
10205 (org-table-justify-field-maybe
10206 (if fmt (format fmt (string-to-number ev)) ev))
10207 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10208 (call-interactively 'org-return)
10209 (setq ndown 0)))
10210 (and down (org-table-maybe-recalculate-line))
10211 (or suppress-align (and org-table-may-need-update
10212 (org-table-align))))))
10214 (defun org-table-put-field-property (prop value)
10215 (save-excursion
10216 (put-text-property (progn (skip-chars-backward "^|") (point))
10217 (progn (skip-chars-forward "^|") (point))
10218 prop value)))
10220 (defun org-table-get-range (desc &optional tbeg col highlight)
10221 "Get a calc vector from a column, accorting to descriptor DESC.
10222 Optional arguments TBEG and COL can give the beginning of the table and
10223 the current column, to avoid unnecessary parsing.
10224 HIGHLIGHT means, just highlight the range."
10225 (if (not (equal (string-to-char desc) ?@))
10226 (setq desc (concat "@" desc)))
10227 (save-excursion
10228 (or tbeg (setq tbeg (org-table-begin)))
10229 (or col (setq col (org-table-current-column)))
10230 (let ((thisline (org-current-line))
10231 beg end c1 c2 r1 r2 rangep tmp)
10232 (unless (string-match org-table-range-regexp desc)
10233 (error "Invalid table range specifier `%s'" desc))
10234 (setq rangep (match-end 3)
10235 r1 (and (match-end 1) (match-string 1 desc))
10236 r2 (and (match-end 4) (match-string 4 desc))
10237 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10238 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10240 (and c1 (setq c1 (+ (string-to-number c1)
10241 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10242 (and c2 (setq c2 (+ (string-to-number c2)
10243 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10244 (if (equal r1 "") (setq r1 nil))
10245 (if (equal r2 "") (setq r2 nil))
10246 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10247 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10248 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10249 (if (not r1) (setq r1 thisline))
10250 (if (not r2) (setq r2 thisline))
10251 (if (not c1) (setq c1 col))
10252 (if (not c2) (setq c2 col))
10253 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10254 ;; just one field
10255 (progn
10256 (goto-line r1)
10257 (while (not (looking-at org-table-dataline-regexp))
10258 (beginning-of-line 2))
10259 (prog1 (org-trim (org-table-get-field c1))
10260 (if highlight (org-table-highlight-rectangle (point) (point)))))
10261 ;; A range, return a vector
10262 ;; First sort the numbers to get a regular ractangle
10263 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10264 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10265 (goto-line r1)
10266 (while (not (looking-at org-table-dataline-regexp))
10267 (beginning-of-line 2))
10268 (org-table-goto-column c1)
10269 (setq beg (point))
10270 (goto-line r2)
10271 (while (not (looking-at org-table-dataline-regexp))
10272 (beginning-of-line 0))
10273 (org-table-goto-column c2)
10274 (setq end (point))
10275 (if highlight
10276 (org-table-highlight-rectangle
10277 beg (progn (skip-chars-forward "^|\n") (point))))
10278 ;; return string representation of calc vector
10279 (mapcar 'org-trim
10280 (apply 'append (org-table-copy-region beg end)))))))
10282 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10283 "Analyze descriptor DESC and retrieve the corresponding line number.
10284 The cursor is currently in line CLINE, the table begins in line BLINE,
10285 and TABLE is a vector with line types."
10286 (if (string-match "^[0-9]+$" desc)
10287 (aref org-table-dlines (string-to-number desc))
10288 (setq cline (or cline (org-current-line))
10289 bline (or bline org-table-current-begin-line)
10290 table (or table org-table-current-line-types))
10291 (if (or
10292 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10293 ;; 1 2 3 4 5 6
10294 (and (not (match-end 3)) (not (match-end 6)))
10295 (and (match-end 3) (match-end 6) (not (match-end 5))))
10296 (error "invalid row descriptor `%s'" desc))
10297 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10298 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10299 (odir (and (match-end 5) (match-string 5 desc)))
10300 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10301 (i (- cline bline))
10302 (rel (and (match-end 6)
10303 (or (and (match-end 1) (not (match-end 3)))
10304 (match-end 5)))))
10305 (if (and hn (not hdir))
10306 (progn
10307 (setq i 0 hdir "+")
10308 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10309 (if (and (not hn) on (not odir))
10310 (error "should never happen");;(aref org-table-dlines on)
10311 (if (and hn (> hn 0))
10312 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10313 (if on
10314 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10315 (+ bline i)))))
10317 (defun org-find-row-type (table i type backwards relative n)
10318 (let ((l (length table)))
10319 (while (> n 0)
10320 (while (and (setq i (+ i (if backwards -1 1)))
10321 (>= i 0) (< i l)
10322 (not (eq (aref table i) type))
10323 (if (and relative (eq (aref table i) 'hline))
10324 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10325 t)))
10326 (setq n (1- n)))
10327 (if (or (< i 0) (>= i l))
10328 (error "Row descriptior leads outside table")
10329 i)))
10331 (defun org-rewrite-old-row-references (s)
10332 (if (string-match "&[-+0-9I]" s)
10333 (error "Formula contains old &row reference, please rewrite using @-syntax")
10336 (defun org-table-make-reference (elements keep-empty numbers lispp)
10337 "Convert list ELEMENTS to something appropriate to insert into formula.
10338 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10339 NUMBERS indicates that everything should be converted to numbers.
10340 LISPP means to return something appropriate for a Lisp list."
10341 (if (stringp elements) ; just a single val
10342 (if lispp
10343 (if (eq lispp 'literal)
10344 elements
10345 (prin1-to-string (if numbers (string-to-number elements) elements)))
10346 (if (equal elements "") (setq elements "0"))
10347 (if numbers (number-to-string (string-to-number elements)) elements))
10348 (unless keep-empty
10349 (setq elements
10350 (delq nil
10351 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10352 elements))))
10353 (setq elements (or elements '("0")))
10354 (if lispp
10355 (mapconcat
10356 (lambda (x)
10357 (if (eq lispp 'literal)
10359 (prin1-to-string (if numbers (string-to-number x) x))))
10360 elements " ")
10361 (concat "[" (mapconcat
10362 (lambda (x)
10363 (if numbers (number-to-string (string-to-number x)) x))
10364 elements
10365 ",") "]"))))
10367 (defun org-table-recalculate (&optional all noalign)
10368 "Recalculate the current table line by applying all stored formulas.
10369 With prefix arg ALL, do this for all lines in the table."
10370 (interactive "P")
10371 (or (memq this-command org-recalc-commands)
10372 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10373 (unless (org-at-table-p) (error "Not at a table"))
10374 (if (equal all '(16))
10375 (org-table-iterate)
10376 (org-table-get-specials)
10377 (let* ((eqlist (sort (org-table-get-stored-formulas)
10378 (lambda (a b) (string< (car a) (car b)))))
10379 (inhibit-redisplay (not debug-on-error))
10380 (line-re org-table-dataline-regexp)
10381 (thisline (org-current-line))
10382 (thiscol (org-table-current-column))
10383 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10384 ;; Insert constants in all formulas
10385 (setq eqlist
10386 (mapcar (lambda (x)
10387 (setcdr x (org-table-formula-substitute-names (cdr x)))
10389 eqlist))
10390 ;; Split the equation list
10391 (while (setq eq (pop eqlist))
10392 (if (<= (string-to-char (car eq)) ?9)
10393 (push eq eqlnum)
10394 (push eq eqlname)))
10395 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10396 (if all
10397 (progn
10398 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10399 (goto-char (setq beg (org-table-begin)))
10400 (if (re-search-forward org-table-calculate-mark-regexp end t)
10401 ;; This is a table with marked lines, compute selected lines
10402 (setq line-re org-table-recalculate-regexp)
10403 ;; Move forward to the first non-header line
10404 (if (and (re-search-forward org-table-dataline-regexp end t)
10405 (re-search-forward org-table-hline-regexp end t)
10406 (re-search-forward org-table-dataline-regexp end t))
10407 (setq beg (match-beginning 0))
10408 nil))) ;; just leave beg where it is
10409 (setq beg (point-at-bol)
10410 end (move-marker (make-marker) (1+ (point-at-eol)))))
10411 (goto-char beg)
10412 (and all (message "Re-applying formulas to full table..."))
10414 ;; First find the named fields, and mark them untouchanble
10415 (remove-text-properties beg end '(org-untouchable t))
10416 (while (setq eq (pop eqlname))
10417 (setq name (car eq)
10418 a (assoc name org-table-named-field-locations))
10419 (and (not a)
10420 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10421 (setq a (list name
10422 (aref org-table-dlines
10423 (string-to-number (match-string 1 name)))
10424 (string-to-number (match-string 2 name)))))
10425 (when (and a (or all (equal (nth 1 a) thisline)))
10426 (message "Re-applying formula to field: %s" name)
10427 (goto-line (nth 1 a))
10428 (org-table-goto-column (nth 2 a))
10429 (push (append a (list (cdr eq))) eqlname1)
10430 (org-table-put-field-property :org-untouchable t)))
10432 ;; Now evauluate the column formulas, but skip fields covered by
10433 ;; field formulas
10434 (goto-char beg)
10435 (while (re-search-forward line-re end t)
10436 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10437 ;; Unprotected line, recalculate
10438 (and all (message "Re-applying formulas to full table...(line %d)"
10439 (setq cnt (1+ cnt))))
10440 (setq org-last-recalc-line (org-current-line))
10441 (setq eql eqlnum)
10442 (while (setq entry (pop eql))
10443 (goto-line org-last-recalc-line)
10444 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10445 (unless (get-text-property (point) :org-untouchable)
10446 (org-table-eval-formula nil (cdr entry)
10447 'noalign 'nocst 'nostore 'noanalysis)))))
10449 ;; Now evaluate the field formulas
10450 (while (setq eq (pop eqlname1))
10451 (message "Re-applying formula to field: %s" (car eq))
10452 (goto-line (nth 1 eq))
10453 (org-table-goto-column (nth 2 eq))
10454 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10455 'nostore 'noanalysis))
10457 (goto-line thisline)
10458 (org-table-goto-column thiscol)
10459 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10460 (or noalign (and org-table-may-need-update (org-table-align))
10461 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10463 ;; back to initial position
10464 (message "Re-applying formulas...done")
10465 (goto-line thisline)
10466 (org-table-goto-column thiscol)
10467 (or noalign (and org-table-may-need-update (org-table-align))
10468 (and all (message "Re-applying formulas...done"))))))
10470 (defun org-table-iterate (&optional arg)
10471 "Recalculate the table until it does not change anymore."
10472 (interactive "P")
10473 (let ((imax (if arg (prefix-numeric-value arg) 10))
10474 (i 0)
10475 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10476 thistbl)
10477 (catch 'exit
10478 (while (< i imax)
10479 (setq i (1+ i))
10480 (org-table-recalculate 'all)
10481 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10482 (if (not (string= lasttbl thistbl))
10483 (setq lasttbl thistbl)
10484 (if (> i 1)
10485 (message "Convergence after %d iterations" i)
10486 (message "Table was already stable"))
10487 (throw 'exit t)))
10488 (error "No convergence after %d iterations" i))))
10490 (defun org-table-formula-substitute-names (f)
10491 "Replace $const with values in string F."
10492 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10493 ;; First, check for column names
10494 (while (setq start (string-match org-table-column-name-regexp f start))
10495 (setq start (1+ start))
10496 (setq a (assoc (match-string 1 f) org-table-column-names))
10497 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10498 ;; Parameters and constants
10499 (setq start 0)
10500 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10501 (setq start (1+ start))
10502 (if (setq a (save-match-data
10503 (org-table-get-constant (match-string 1 f))))
10504 (setq f (replace-match
10505 (concat (if pp "(") a (if pp ")")) t t f))))
10506 (if org-table-formula-debug
10507 (put-text-property 0 (length f) :orig-formula f1 f))
10510 (defun org-table-get-constant (const)
10511 "Find the value for a parameter or constant in a formula.
10512 Parameters get priority."
10513 (or (cdr (assoc const org-table-local-parameters))
10514 (cdr (assoc const org-table-formula-constants-local))
10515 (cdr (assoc const org-table-formula-constants))
10516 (and (fboundp 'constants-get) (constants-get const))
10517 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10518 (org-entry-get nil (substring const 5) 'inherit))
10519 "#UNDEFINED_NAME"))
10521 (defvar org-table-fedit-map
10522 (let ((map (make-sparse-keymap)))
10523 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10524 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10525 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10526 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10527 (org-defkey map "\C-c?" 'org-table-show-reference)
10528 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10529 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10530 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10531 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10532 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10533 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10534 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10535 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10536 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10537 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10538 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10539 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10540 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10541 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10542 map))
10544 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10545 '("Edit-Formulas"
10546 ["Finish and Install" org-table-fedit-finish t]
10547 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10548 ["Abort" org-table-fedit-abort t]
10549 "--"
10550 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10551 ["Complete Lisp Symbol" lisp-complete-symbol t]
10552 "--"
10553 "Shift Reference at Point"
10554 ["Up" org-table-fedit-ref-up t]
10555 ["Down" org-table-fedit-ref-down t]
10556 ["Left" org-table-fedit-ref-left t]
10557 ["Right" org-table-fedit-ref-right t]
10559 "Change Test Row for Column Formulas"
10560 ["Up" org-table-fedit-line-up t]
10561 ["Down" org-table-fedit-line-down t]
10562 "--"
10563 ["Scroll Table Window" org-table-fedit-scroll t]
10564 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10565 ["Show Table Grid" org-table-fedit-toggle-coordinates
10566 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10567 org-table-overlay-coordinates)]
10568 "--"
10569 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10570 :style toggle :selected org-table-buffer-is-an]))
10572 (defvar org-pos)
10574 (defun org-table-edit-formulas ()
10575 "Edit the formulas of the current table in a separate buffer."
10576 (interactive)
10577 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10578 (beginning-of-line 0))
10579 (unless (org-at-table-p) (error "Not at a table"))
10580 (org-table-get-specials)
10581 (let ((key (org-table-current-field-formula 'key 'noerror))
10582 (eql (sort (org-table-get-stored-formulas 'noerror)
10583 'org-table-formula-less-p))
10584 (pos (move-marker (make-marker) (point)))
10585 (startline 1)
10586 (wc (current-window-configuration))
10587 (titles '((column . "# Column Formulas\n")
10588 (field . "# Field Formulas\n")
10589 (named . "# Named Field Formulas\n")))
10590 entry s type title)
10591 (org-switch-to-buffer-other-window "*Edit Formulas*")
10592 (erase-buffer)
10593 ;; Keep global-font-lock-mode from turning on font-lock-mode
10594 (let ((font-lock-global-modes '(not fundamental-mode)))
10595 (fundamental-mode))
10596 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10597 (org-set-local 'org-pos pos)
10598 (org-set-local 'org-window-configuration wc)
10599 (use-local-map org-table-fedit-map)
10600 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10601 (easy-menu-add org-table-fedit-menu)
10602 (setq startline (org-current-line))
10603 (while (setq entry (pop eql))
10604 (setq type (cond
10605 ((equal (string-to-char (car entry)) ?@) 'field)
10606 ((string-match "^[0-9]" (car entry)) 'column)
10607 (t 'named)))
10608 (when (setq title (assq type titles))
10609 (or (bobp) (insert "\n"))
10610 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10611 (setq titles (delq title titles)))
10612 (if (equal key (car entry)) (setq startline (org-current-line)))
10613 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10614 (car entry) " = " (cdr entry) "\n"))
10615 (remove-text-properties 0 (length s) '(face nil) s)
10616 (insert s))
10617 (if (eq org-table-use-standard-references t)
10618 (org-table-fedit-toggle-ref-type))
10619 (goto-line startline)
10620 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10622 (defun org-table-fedit-post-command ()
10623 (when (not (memq this-command '(lisp-complete-symbol)))
10624 (let ((win (selected-window)))
10625 (save-excursion
10626 (condition-case nil
10627 (org-table-show-reference)
10628 (error nil))
10629 (select-window win)))))
10631 (defun org-table-formula-to-user (s)
10632 "Convert a formula from internal to user representation."
10633 (if (eq org-table-use-standard-references t)
10634 (org-table-convert-refs-to-an s)
10637 (defun org-table-formula-from-user (s)
10638 "Convert a formula from user to internal representation."
10639 (if org-table-use-standard-references
10640 (org-table-convert-refs-to-rc s)
10643 (defun org-table-convert-refs-to-rc (s)
10644 "Convert spreadsheet references from AB7 to @7$28.
10645 Works for single references, but also for entire formulas and even the
10646 full TBLFM line."
10647 (let ((start 0))
10648 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10649 (cond
10650 ((match-end 3)
10651 ;; format match, just advance
10652 (setq start (match-end 0)))
10653 ((and (> (match-beginning 0) 0)
10654 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10655 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10656 ;; 3.e5 or something like this.
10657 (setq start (match-end 0)))
10659 (setq start (match-beginning 0)
10660 s (replace-match
10661 (if (equal (match-string 2 s) "&")
10662 (format "$%d" (org-letters-to-number (match-string 1 s)))
10663 (format "@%d$%d"
10664 (string-to-number (match-string 2 s))
10665 (org-letters-to-number (match-string 1 s))))
10666 t t s)))))
10669 (defun org-table-convert-refs-to-an (s)
10670 "Convert spreadsheet references from to @7$28 to AB7.
10671 Works for single references, but also for entire formulas and even the
10672 full TBLFM line."
10673 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10674 (setq s (replace-match
10675 (format "%s%d"
10676 (org-number-to-letters
10677 (string-to-number (match-string 2 s)))
10678 (string-to-number (match-string 1 s)))
10679 t t s)))
10680 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10681 (setq s (replace-match (concat "\\1"
10682 (org-number-to-letters
10683 (string-to-number (match-string 2 s))) "&")
10684 t nil s)))
10687 (defun org-letters-to-number (s)
10688 "Convert a base 26 number represented by letters into an integer.
10689 For example: AB -> 28."
10690 (let ((n 0))
10691 (setq s (upcase s))
10692 (while (> (length s) 0)
10693 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10694 s (substring s 1)))
10697 (defun org-number-to-letters (n)
10698 "Convert an integer into a base 26 number represented by letters.
10699 For example: 28 -> AB."
10700 (let ((s ""))
10701 (while (> n 0)
10702 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10703 n (/ (1- n) 26)))
10706 (defun org-table-fedit-convert-buffer (function)
10707 "Convert all references in this buffer, using FUNTION."
10708 (let ((line (org-current-line)))
10709 (goto-char (point-min))
10710 (while (not (eobp))
10711 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10712 (delete-region (point) (point-at-eol))
10713 (or (eobp) (forward-char 1)))
10714 (goto-line line)))
10716 (defun org-table-fedit-toggle-ref-type ()
10717 "Convert all references in the buffer from B3 to @3$2 and back."
10718 (interactive)
10719 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10720 (org-table-fedit-convert-buffer
10721 (if org-table-buffer-is-an
10722 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10723 (message "Reference type switched to %s"
10724 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10726 (defun org-table-fedit-ref-up ()
10727 "Shift the reference at point one row/hline up."
10728 (interactive)
10729 (org-table-fedit-shift-reference 'up))
10730 (defun org-table-fedit-ref-down ()
10731 "Shift the reference at point one row/hline down."
10732 (interactive)
10733 (org-table-fedit-shift-reference 'down))
10734 (defun org-table-fedit-ref-left ()
10735 "Shift the reference at point one field to the left."
10736 (interactive)
10737 (org-table-fedit-shift-reference 'left))
10738 (defun org-table-fedit-ref-right ()
10739 "Shift the reference at point one field to the right."
10740 (interactive)
10741 (org-table-fedit-shift-reference 'right))
10743 (defun org-table-fedit-shift-reference (dir)
10744 (cond
10745 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10746 (if (memq dir '(left right))
10747 (org-rematch-and-replace 1 (eq dir 'left))
10748 (error "Cannot shift reference in this direction")))
10749 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10750 ;; A B3-like reference
10751 (if (memq dir '(up down))
10752 (org-rematch-and-replace 2 (eq dir 'up))
10753 (org-rematch-and-replace 1 (eq dir 'left))))
10754 ((org-at-regexp-p
10755 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10756 ;; An internal reference
10757 (if (memq dir '(up down))
10758 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10759 (org-rematch-and-replace 5 (eq dir 'left))))))
10761 (defun org-rematch-and-replace (n &optional decr hline)
10762 "Re-match the group N, and replace it with the shifted refrence."
10763 (or (match-end n) (error "Cannot shift reference in this direction"))
10764 (goto-char (match-beginning n))
10765 (and (looking-at (regexp-quote (match-string n)))
10766 (replace-match (org-shift-refpart (match-string 0) decr hline)
10767 t t)))
10769 (defun org-shift-refpart (ref &optional decr hline)
10770 "Shift a refrence part REF.
10771 If DECR is set, decrease the references row/column, else increase.
10772 If HLINE is set, this may be a hline reference, it certainly is not
10773 a translation reference."
10774 (save-match-data
10775 (let* ((sign (string-match "^[-+]" ref)) n)
10777 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10778 (cond
10779 ((and hline (string-match "^I+" ref))
10780 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10781 (setq n (+ n (if decr -1 1)))
10782 (if (= n 0) (setq n (+ n (if decr -1 1))))
10783 (if sign
10784 (setq sign (if (< n 0) "-" "+") n (abs n))
10785 (setq n (max 1 n)))
10786 (concat sign (make-string n ?I)))
10788 ((string-match "^[0-9]+" ref)
10789 (setq n (string-to-number (concat sign ref)))
10790 (setq n (+ n (if decr -1 1)))
10791 (if sign
10792 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10793 (number-to-string (max 1 n))))
10795 ((string-match "^[a-zA-Z]+" ref)
10796 (org-number-to-letters
10797 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10799 (t (error "Cannot shift reference"))))))
10801 (defun org-table-fedit-toggle-coordinates ()
10802 "Toggle the display of coordinates in the refrenced table."
10803 (interactive)
10804 (let ((pos (marker-position org-pos)))
10805 (with-current-buffer (marker-buffer org-pos)
10806 (save-excursion
10807 (goto-char pos)
10808 (org-table-toggle-coordinate-overlays)))))
10810 (defun org-table-fedit-finish (&optional arg)
10811 "Parse the buffer for formula definitions and install them.
10812 With prefix ARG, apply the new formulas to the table."
10813 (interactive "P")
10814 (org-table-remove-rectangle-highlight)
10815 (if org-table-use-standard-references
10816 (progn
10817 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10818 (setq org-table-buffer-is-an nil)))
10819 (let ((pos org-pos) eql var form)
10820 (goto-char (point-min))
10821 (while (re-search-forward
10822 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10823 nil t)
10824 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10825 form (match-string 3))
10826 (setq form (org-trim form))
10827 (when (not (equal form ""))
10828 (while (string-match "[ \t]*\n[ \t]*" form)
10829 (setq form (replace-match " " t t form)))
10830 (when (assoc var eql)
10831 (error "Double formulas for %s" var))
10832 (push (cons var form) eql)))
10833 (setq org-pos nil)
10834 (set-window-configuration org-window-configuration)
10835 (select-window (get-buffer-window (marker-buffer pos)))
10836 (goto-char pos)
10837 (unless (org-at-table-p)
10838 (error "Lost table position - cannot install formulae"))
10839 (org-table-store-formulas eql)
10840 (move-marker pos nil)
10841 (kill-buffer "*Edit Formulas*")
10842 (if arg
10843 (org-table-recalculate 'all)
10844 (message "New formulas installed - press C-u C-c C-c to apply."))))
10846 (defun org-table-fedit-abort ()
10847 "Abort editing formulas, without installing the changes."
10848 (interactive)
10849 (org-table-remove-rectangle-highlight)
10850 (let ((pos org-pos))
10851 (set-window-configuration org-window-configuration)
10852 (select-window (get-buffer-window (marker-buffer pos)))
10853 (goto-char pos)
10854 (move-marker pos nil)
10855 (message "Formula editing aborted without installing changes")))
10857 (defun org-table-fedit-lisp-indent ()
10858 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10859 (interactive)
10860 (let ((pos (point)) beg end ind)
10861 (beginning-of-line 1)
10862 (cond
10863 ((looking-at "[ \t]")
10864 (goto-char pos)
10865 (call-interactively 'lisp-indent-line))
10866 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10867 ((not (fboundp 'pp-buffer))
10868 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10869 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10870 (goto-char (- (match-end 0) 2))
10871 (setq beg (point))
10872 (setq ind (make-string (current-column) ?\ ))
10873 (condition-case nil (forward-sexp 1)
10874 (error
10875 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10876 (setq end (point))
10877 (save-restriction
10878 (narrow-to-region beg end)
10879 (if (eq last-command this-command)
10880 (progn
10881 (goto-char (point-min))
10882 (setq this-command nil)
10883 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10884 (replace-match " ")))
10885 (pp-buffer)
10886 (untabify (point-min) (point-max))
10887 (goto-char (1+ (point-min)))
10888 (while (re-search-forward "^." nil t)
10889 (beginning-of-line 1)
10890 (insert ind))
10891 (goto-char (point-max))
10892 (backward-delete-char 1)))
10893 (goto-char beg))
10894 (t nil))))
10896 (defvar org-show-positions nil)
10898 (defun org-table-show-reference (&optional local)
10899 "Show the location/value of the $ expression at point."
10900 (interactive)
10901 (org-table-remove-rectangle-highlight)
10902 (catch 'exit
10903 (let ((pos (if local (point) org-pos))
10904 (face2 'highlight)
10905 (org-inhibit-highlight-removal t)
10906 (win (selected-window))
10907 (org-show-positions nil)
10908 var name e what match dest)
10909 (if local (org-table-get-specials))
10910 (setq what (cond
10911 ((or (org-at-regexp-p org-table-range-regexp2)
10912 (org-at-regexp-p org-table-translate-regexp)
10913 (org-at-regexp-p org-table-range-regexp))
10914 (setq match
10915 (save-match-data
10916 (org-table-convert-refs-to-rc (match-string 0))))
10917 'range)
10918 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10919 ((org-at-regexp-p "\\$[0-9]+") 'column)
10920 ((not local) nil)
10921 (t (error "No reference at point")))
10922 match (and what (or match (match-string 0))))
10923 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10924 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10925 'secondary-selection))
10926 (org-add-hook 'before-change-functions
10927 'org-table-remove-rectangle-highlight)
10928 (if (eq what 'name) (setq var (substring match 1)))
10929 (when (eq what 'range)
10930 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10931 (setq match (org-table-formula-substitute-names match)))
10932 (unless local
10933 (save-excursion
10934 (end-of-line 1)
10935 (re-search-backward "^\\S-" nil t)
10936 (beginning-of-line 1)
10937 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10938 (setq dest
10939 (save-match-data
10940 (org-table-convert-refs-to-rc (match-string 1))))
10941 (org-table-add-rectangle-overlay
10942 (match-beginning 1) (match-end 1) face2))))
10943 (if (and (markerp pos) (marker-buffer pos))
10944 (if (get-buffer-window (marker-buffer pos))
10945 (select-window (get-buffer-window (marker-buffer pos)))
10946 (org-switch-to-buffer-other-window (get-buffer-window
10947 (marker-buffer pos)))))
10948 (goto-char pos)
10949 (org-table-force-dataline)
10950 (when dest
10951 (setq name (substring dest 1))
10952 (cond
10953 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10954 (setq e (assoc name org-table-named-field-locations))
10955 (goto-line (nth 1 e))
10956 (org-table-goto-column (nth 2 e)))
10957 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10958 (let ((l (string-to-number (match-string 1 dest)))
10959 (c (string-to-number (match-string 2 dest))))
10960 (goto-line (aref org-table-dlines l))
10961 (org-table-goto-column c)))
10962 (t (org-table-goto-column (string-to-number name))))
10963 (move-marker pos (point))
10964 (org-table-highlight-rectangle nil nil face2))
10965 (cond
10966 ((equal dest match))
10967 ((not match))
10968 ((eq what 'range)
10969 (condition-case nil
10970 (save-excursion
10971 (org-table-get-range match nil nil 'highlight))
10972 (error nil)))
10973 ((setq e (assoc var org-table-named-field-locations))
10974 (goto-line (nth 1 e))
10975 (org-table-goto-column (nth 2 e))
10976 (org-table-highlight-rectangle (point) (point))
10977 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10978 ((setq e (assoc var org-table-column-names))
10979 (org-table-goto-column (string-to-number (cdr e)))
10980 (org-table-highlight-rectangle (point) (point))
10981 (goto-char (org-table-begin))
10982 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10983 (org-table-end) t)
10984 (progn
10985 (goto-char (match-beginning 1))
10986 (org-table-highlight-rectangle)
10987 (message "Named column (column %s)" (cdr e)))
10988 (error "Column name not found")))
10989 ((eq what 'column)
10990 ;; column number
10991 (org-table-goto-column (string-to-number (substring match 1)))
10992 (org-table-highlight-rectangle (point) (point))
10993 (message "Column %s" (substring match 1)))
10994 ((setq e (assoc var org-table-local-parameters))
10995 (goto-char (org-table-begin))
10996 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10997 (progn
10998 (goto-char (match-beginning 1))
10999 (org-table-highlight-rectangle)
11000 (message "Local parameter."))
11001 (error "Parameter not found")))
11003 (cond
11004 ((not var) (error "No reference at point"))
11005 ((setq e (assoc var org-table-formula-constants-local))
11006 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11007 var (cdr e)))
11008 ((setq e (assoc var org-table-formula-constants))
11009 (message "Constant: $%s=%s in `org-table-formula-constants'."
11010 var (cdr e)))
11011 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11012 (message "Constant: $%s=%s, from `constants.el'%s."
11013 var e (format " (%s units)" constants-unit-system)))
11014 (t (error "Undefined name $%s" var)))))
11015 (goto-char pos)
11016 (when (and org-show-positions
11017 (not (memq this-command '(org-table-fedit-scroll
11018 org-table-fedit-scroll-down))))
11019 (push pos org-show-positions)
11020 (push org-table-current-begin-pos org-show-positions)
11021 (let ((min (apply 'min org-show-positions))
11022 (max (apply 'max org-show-positions)))
11023 (goto-char min) (recenter 0)
11024 (goto-char max)
11025 (or (pos-visible-in-window-p max) (recenter -1))))
11026 (select-window win))))
11028 (defun org-table-force-dataline ()
11029 "Make sure the cursor is in a dataline in a table."
11030 (unless (save-excursion
11031 (beginning-of-line 1)
11032 (looking-at org-table-dataline-regexp))
11033 (let* ((re org-table-dataline-regexp)
11034 (p1 (save-excursion (re-search-forward re nil 'move)))
11035 (p2 (save-excursion (re-search-backward re nil 'move))))
11036 (cond ((and p1 p2)
11037 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11038 p1 p2)))
11039 ((or p1 p2) (goto-char (or p1 p2)))
11040 (t (error "No table dataline around here"))))))
11042 (defun org-table-fedit-line-up ()
11043 "Move cursor one line up in the window showing the table."
11044 (interactive)
11045 (org-table-fedit-move 'previous-line))
11047 (defun org-table-fedit-line-down ()
11048 "Move cursor one line down in the window showing the table."
11049 (interactive)
11050 (org-table-fedit-move 'next-line))
11052 (defun org-table-fedit-move (command)
11053 "Move the cursor in the window shoinw the table.
11054 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11055 (let ((org-table-allow-automatic-line-recalculation nil)
11056 (pos org-pos) (win (selected-window)) p)
11057 (select-window (get-buffer-window (marker-buffer org-pos)))
11058 (setq p (point))
11059 (call-interactively command)
11060 (while (and (org-at-table-p)
11061 (org-at-table-hline-p))
11062 (call-interactively command))
11063 (or (org-at-table-p) (goto-char p))
11064 (move-marker pos (point))
11065 (select-window win)))
11067 (defun org-table-fedit-scroll (N)
11068 (interactive "p")
11069 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11070 (scroll-other-window N)))
11072 (defun org-table-fedit-scroll-down (N)
11073 (interactive "p")
11074 (org-table-fedit-scroll (- N)))
11076 (defvar org-table-rectangle-overlays nil)
11078 (defun org-table-add-rectangle-overlay (beg end &optional face)
11079 "Add a new overlay."
11080 (let ((ov (org-make-overlay beg end)))
11081 (org-overlay-put ov 'face (or face 'secondary-selection))
11082 (push ov org-table-rectangle-overlays)))
11084 (defun org-table-highlight-rectangle (&optional beg end face)
11085 "Highlight rectangular region in a table."
11086 (setq beg (or beg (point)) end (or end (point)))
11087 (let ((b (min beg end))
11088 (e (max beg end))
11089 l1 c1 l2 c2 tmp)
11090 (and (boundp 'org-show-positions)
11091 (setq org-show-positions (cons b (cons e org-show-positions))))
11092 (goto-char (min beg end))
11093 (setq l1 (org-current-line)
11094 c1 (org-table-current-column))
11095 (goto-char (max beg end))
11096 (setq l2 (org-current-line)
11097 c2 (org-table-current-column))
11098 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11099 (goto-line l1)
11100 (beginning-of-line 1)
11101 (loop for line from l1 to l2 do
11102 (when (looking-at org-table-dataline-regexp)
11103 (org-table-goto-column c1)
11104 (skip-chars-backward "^|\n") (setq beg (point))
11105 (org-table-goto-column c2)
11106 (skip-chars-forward "^|\n") (setq end (point))
11107 (org-table-add-rectangle-overlay beg end face))
11108 (beginning-of-line 2))
11109 (goto-char b))
11110 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11112 (defun org-table-remove-rectangle-highlight (&rest ignore)
11113 "Remove the rectangle overlays."
11114 (unless org-inhibit-highlight-removal
11115 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11116 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11117 (setq org-table-rectangle-overlays nil)))
11119 (defvar org-table-coordinate-overlays nil
11120 "Collects the cooordinate grid overlays, so that they can be removed.")
11121 (make-variable-buffer-local 'org-table-coordinate-overlays)
11123 (defun org-table-overlay-coordinates ()
11124 "Add overlays to the table at point, to show row/column coordinates."
11125 (interactive)
11126 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11127 (setq org-table-coordinate-overlays nil)
11128 (save-excursion
11129 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11130 (goto-char (org-table-begin))
11131 (while (org-at-table-p)
11132 (setq eol (point-at-eol))
11133 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11134 (push ov org-table-coordinate-overlays)
11135 (setq hline (looking-at org-table-hline-regexp))
11136 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11137 (format "%4d" (setq id (1+ id)))))
11138 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11139 (when hline
11140 (setq ic 0)
11141 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11142 (setq beg (1+ (match-beginning 0))
11143 ic (1+ ic)
11144 s1 (concat "$" (int-to-string ic))
11145 s2 (org-number-to-letters ic)
11146 str (if (eq org-table-use-standard-references t) s2 s1))
11147 (setq ov (org-make-overlay beg (+ beg (length str))))
11148 (push ov org-table-coordinate-overlays)
11149 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11150 (beginning-of-line 2)))))
11152 (defun org-table-toggle-coordinate-overlays ()
11153 "Toggle the display of Row/Column numbers in tables."
11154 (interactive)
11155 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11156 (message "Row/Column number display turned %s"
11157 (if org-table-overlay-coordinates "on" "off"))
11158 (if (and (org-at-table-p) org-table-overlay-coordinates)
11159 (org-table-align))
11160 (unless org-table-overlay-coordinates
11161 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11162 (setq org-table-coordinate-overlays nil)))
11164 (defun org-table-toggle-formula-debugger ()
11165 "Toggle the formula debugger in tables."
11166 (interactive)
11167 (setq org-table-formula-debug (not org-table-formula-debug))
11168 (message "Formula debugging has been turned %s"
11169 (if org-table-formula-debug "on" "off")))
11171 ;;; The orgtbl minor mode
11173 ;; Define a minor mode which can be used in other modes in order to
11174 ;; integrate the org-mode table editor.
11176 ;; This is really a hack, because the org-mode table editor uses several
11177 ;; keys which normally belong to the major mode, for example the TAB and
11178 ;; RET keys. Here is how it works: The minor mode defines all the keys
11179 ;; necessary to operate the table editor, but wraps the commands into a
11180 ;; function which tests if the cursor is currently inside a table. If that
11181 ;; is the case, the table editor command is executed. However, when any of
11182 ;; those keys is used outside a table, the function uses `key-binding' to
11183 ;; look up if the key has an associated command in another currently active
11184 ;; keymap (minor modes, major mode, global), and executes that command.
11185 ;; There might be problems if any of the keys used by the table editor is
11186 ;; otherwise used as a prefix key.
11188 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11189 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11190 ;; addresses this by checking explicitly for both bindings.
11192 ;; The optimized version (see variable `orgtbl-optimized') takes over
11193 ;; all keys which are bound to `self-insert-command' in the *global map*.
11194 ;; Some modes bind other commands to simple characters, for example
11195 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11196 ;; active, this binding is ignored inside tables and replaced with a
11197 ;; modified self-insert.
11199 (defvar orgtbl-mode nil
11200 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11201 table editor in arbitrary modes.")
11202 (make-variable-buffer-local 'orgtbl-mode)
11204 (defvar orgtbl-mode-map (make-keymap)
11205 "Keymap for `orgtbl-mode'.")
11207 ;;;###autoload
11208 (defun turn-on-orgtbl ()
11209 "Unconditionally turn on `orgtbl-mode'."
11210 (orgtbl-mode 1))
11212 (defvar org-old-auto-fill-inhibit-regexp nil
11213 "Local variable used by `orgtbl-mode'")
11215 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11216 "Matches a line belonging to an orgtbl.")
11218 (defconst orgtbl-extra-font-lock-keywords
11219 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11220 0 (quote 'org-table) 'prepend))
11221 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11223 ;;;###autoload
11224 (defun orgtbl-mode (&optional arg)
11225 "The `org-mode' table editor as a minor mode for use in other modes."
11226 (interactive)
11227 (if (org-mode-p)
11228 ;; Exit without error, in case some hook functions calls this
11229 ;; by accident in org-mode.
11230 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11231 (setq orgtbl-mode
11232 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11233 (if orgtbl-mode
11234 (progn
11235 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11236 ;; Make sure we are first in minor-mode-map-alist
11237 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11238 (and c (setq minor-mode-map-alist
11239 (cons c (delq c minor-mode-map-alist)))))
11240 (org-set-local (quote org-table-may-need-update) t)
11241 (org-add-hook 'before-change-functions 'org-before-change-function
11242 nil 'local)
11243 (org-set-local 'org-old-auto-fill-inhibit-regexp
11244 auto-fill-inhibit-regexp)
11245 (org-set-local 'auto-fill-inhibit-regexp
11246 (if auto-fill-inhibit-regexp
11247 (concat orgtbl-line-start-regexp "\\|"
11248 auto-fill-inhibit-regexp)
11249 orgtbl-line-start-regexp))
11250 (org-add-to-invisibility-spec '(org-cwidth))
11251 (when (fboundp 'font-lock-add-keywords)
11252 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11253 (org-restart-font-lock))
11254 (easy-menu-add orgtbl-mode-menu)
11255 (run-hooks 'orgtbl-mode-hook))
11256 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11257 (org-cleanup-narrow-column-properties)
11258 (org-remove-from-invisibility-spec '(org-cwidth))
11259 (remove-hook 'before-change-functions 'org-before-change-function t)
11260 (when (fboundp 'font-lock-remove-keywords)
11261 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11262 (org-restart-font-lock))
11263 (easy-menu-remove orgtbl-mode-menu)
11264 (force-mode-line-update 'all))))
11266 (defun org-cleanup-narrow-column-properties ()
11267 "Remove all properties related to narrow-column invisibility."
11268 (let ((s 1))
11269 (while (setq s (text-property-any s (point-max)
11270 'display org-narrow-column-arrow))
11271 (remove-text-properties s (1+ s) '(display t)))
11272 (setq s 1)
11273 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11274 (remove-text-properties s (1+ s) '(org-cwidth t)))
11275 (setq s 1)
11276 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11277 (remove-text-properties s (1+ s) '(invisible t)))))
11279 ;; Install it as a minor mode.
11280 (put 'orgtbl-mode :included t)
11281 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11282 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11284 (defun orgtbl-make-binding (fun n &rest keys)
11285 "Create a function for binding in the table minor mode.
11286 FUN is the command to call inside a table. N is used to create a unique
11287 command name. KEYS are keys that should be checked in for a command
11288 to execute outside of tables."
11289 (eval
11290 (list 'defun
11291 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11292 '(arg)
11293 (concat "In tables, run `" (symbol-name fun) "'.\n"
11294 "Outside of tables, run the binding of `"
11295 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11296 "'.")
11297 '(interactive "p")
11298 (list 'if
11299 '(org-at-table-p)
11300 (list 'call-interactively (list 'quote fun))
11301 (list 'let '(orgtbl-mode)
11302 (list 'call-interactively
11303 (append '(or)
11304 (mapcar (lambda (k)
11305 (list 'key-binding k))
11306 keys)
11307 '('orgtbl-error))))))))
11309 (defun orgtbl-error ()
11310 "Error when there is no default binding for a table key."
11311 (interactive)
11312 (error "This key has no function outside tables"))
11314 (defun orgtbl-setup ()
11315 "Setup orgtbl keymaps."
11316 (let ((nfunc 0)
11317 (bindings
11318 (list
11319 '([(meta shift left)] org-table-delete-column)
11320 '([(meta left)] org-table-move-column-left)
11321 '([(meta right)] org-table-move-column-right)
11322 '([(meta shift right)] org-table-insert-column)
11323 '([(meta shift up)] org-table-kill-row)
11324 '([(meta shift down)] org-table-insert-row)
11325 '([(meta up)] org-table-move-row-up)
11326 '([(meta down)] org-table-move-row-down)
11327 '("\C-c\C-w" org-table-cut-region)
11328 '("\C-c\M-w" org-table-copy-region)
11329 '("\C-c\C-y" org-table-paste-rectangle)
11330 '("\C-c-" org-table-insert-hline)
11331 '("\C-c}" org-table-toggle-coordinate-overlays)
11332 '("\C-c{" org-table-toggle-formula-debugger)
11333 '("\C-m" org-table-next-row)
11334 '([(shift return)] org-table-copy-down)
11335 '("\C-c\C-q" org-table-wrap-region)
11336 '("\C-c?" org-table-field-info)
11337 '("\C-c " org-table-blank-field)
11338 '("\C-c+" org-table-sum)
11339 '("\C-c=" org-table-eval-formula)
11340 '("\C-c'" org-table-edit-formulas)
11341 '("\C-c`" org-table-edit-field)
11342 '("\C-c*" org-table-recalculate)
11343 '("\C-c|" org-table-create-or-convert-from-region)
11344 '("\C-c^" org-table-sort-lines)
11345 '([(control ?#)] org-table-rotate-recalc-marks)))
11346 elt key fun cmd)
11347 (while (setq elt (pop bindings))
11348 (setq nfunc (1+ nfunc))
11349 (setq key (org-key (car elt))
11350 fun (nth 1 elt)
11351 cmd (orgtbl-make-binding fun nfunc key))
11352 (org-defkey orgtbl-mode-map key cmd))
11354 ;; Special treatment needed for TAB and RET
11355 (org-defkey orgtbl-mode-map [(return)]
11356 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11357 (org-defkey orgtbl-mode-map "\C-m"
11358 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11360 (org-defkey orgtbl-mode-map [(tab)]
11361 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11362 (org-defkey orgtbl-mode-map "\C-i"
11363 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11365 (org-defkey orgtbl-mode-map [(shift tab)]
11366 (orgtbl-make-binding 'org-table-previous-field 104
11367 [(shift tab)] [(tab)] "\C-i"))
11369 (org-defkey orgtbl-mode-map "\M-\C-m"
11370 (orgtbl-make-binding 'org-table-wrap-region 105
11371 "\M-\C-m" [(meta return)]))
11372 (org-defkey orgtbl-mode-map [(meta return)]
11373 (orgtbl-make-binding 'org-table-wrap-region 106
11374 [(meta return)] "\M-\C-m"))
11376 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11377 (when orgtbl-optimized
11378 ;; If the user wants maximum table support, we need to hijack
11379 ;; some standard editing functions
11380 (org-remap orgtbl-mode-map
11381 'self-insert-command 'orgtbl-self-insert-command
11382 'delete-char 'org-delete-char
11383 'delete-backward-char 'org-delete-backward-char)
11384 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11385 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11386 '("OrgTbl"
11387 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11388 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11389 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11390 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11391 "--"
11392 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11393 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11394 ["Copy Field from Above"
11395 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11396 "--"
11397 ("Column"
11398 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11399 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11400 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11401 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11402 ("Row"
11403 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11404 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11405 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11406 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11407 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11408 "--"
11409 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11410 ("Rectangle"
11411 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11412 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11413 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11414 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11415 "--"
11416 ("Radio tables"
11417 ["Insert table template" orgtbl-insert-radio-table
11418 (assq major-mode orgtbl-radio-table-templates)]
11419 ["Comment/uncomment table" orgtbl-toggle-comment t])
11420 "--"
11421 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11422 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11423 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11424 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11425 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11426 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11427 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11428 ["Sum Column/Rectangle" org-table-sum
11429 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11430 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11431 ["Debug Formulas"
11432 org-table-toggle-formula-debugger :active (org-at-table-p)
11433 :keys "C-c {"
11434 :style toggle :selected org-table-formula-debug]
11435 ["Show Col/Row Numbers"
11436 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11437 :keys "C-c }"
11438 :style toggle :selected org-table-overlay-coordinates]
11442 (defun orgtbl-ctrl-c-ctrl-c (arg)
11443 "If the cursor is inside a table, realign the table.
11444 It it is a table to be sent away to a receiver, do it.
11445 With prefix arg, also recompute table."
11446 (interactive "P")
11447 (let ((pos (point)) action)
11448 (save-excursion
11449 (beginning-of-line 1)
11450 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11451 ((looking-at "[ \t]*|") pos)
11452 ((looking-at "#\\+TBLFM:") 'recalc))))
11453 (cond
11454 ((integerp action)
11455 (goto-char action)
11456 (org-table-maybe-eval-formula)
11457 (if arg
11458 (call-interactively 'org-table-recalculate)
11459 (org-table-maybe-recalculate-line))
11460 (call-interactively 'org-table-align)
11461 (orgtbl-send-table 'maybe))
11462 ((eq action 'recalc)
11463 (save-excursion
11464 (beginning-of-line 1)
11465 (skip-chars-backward " \r\n\t")
11466 (if (org-at-table-p)
11467 (org-call-with-arg 'org-table-recalculate t))))
11468 (t (let (orgtbl-mode)
11469 (call-interactively (key-binding "\C-c\C-c")))))))
11471 (defun orgtbl-tab (arg)
11472 "Justification and field motion for `orgtbl-mode'."
11473 (interactive "P")
11474 (if arg (org-table-edit-field t)
11475 (org-table-justify-field-maybe)
11476 (org-table-next-field)))
11478 (defun orgtbl-ret ()
11479 "Justification and field motion for `orgtbl-mode'."
11480 (interactive)
11481 (org-table-justify-field-maybe)
11482 (org-table-next-row))
11484 (defun orgtbl-self-insert-command (N)
11485 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11486 If the cursor is in a table looking at whitespace, the whitespace is
11487 overwritten, and the table is not marked as requiring realignment."
11488 (interactive "p")
11489 (if (and (org-at-table-p)
11491 (and org-table-auto-blank-field
11492 (member last-command
11493 '(orgtbl-hijacker-command-100
11494 orgtbl-hijacker-command-101
11495 orgtbl-hijacker-command-102
11496 orgtbl-hijacker-command-103
11497 orgtbl-hijacker-command-104
11498 orgtbl-hijacker-command-105))
11499 (org-table-blank-field))
11501 (eq N 1)
11502 (looking-at "[^|\n]* +|"))
11503 (let (org-table-may-need-update)
11504 (goto-char (1- (match-end 0)))
11505 (delete-backward-char 1)
11506 (goto-char (match-beginning 0))
11507 (self-insert-command N))
11508 (setq org-table-may-need-update t)
11509 (let (orgtbl-mode)
11510 (call-interactively (key-binding (vector last-input-event))))))
11512 (defun org-force-self-insert (N)
11513 "Needed to enforce self-insert under remapping."
11514 (interactive "p")
11515 (self-insert-command N))
11517 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11518 "Regula expression matching exponentials as produced by calc.")
11520 (defvar org-table-clean-did-remove-column nil)
11522 (defun orgtbl-export (table target)
11523 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11524 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11525 org-table-last-alignment org-table-last-column-widths
11526 maxcol column)
11527 (if (not (fboundp func))
11528 (error "Cannot export orgtbl table to %s" target))
11529 (setq lines (org-table-clean-before-export lines))
11530 (setq table
11531 (mapcar
11532 (lambda (x)
11533 (if (string-match org-table-hline-regexp x)
11534 'hline
11535 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11536 lines))
11537 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11538 table)))
11539 (loop for i from (1- maxcol) downto 0 do
11540 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11541 (setq column (delq nil column))
11542 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11543 (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))
11544 (funcall func table nil)))
11546 (defun orgtbl-send-table (&optional maybe)
11547 "Send a tranformed version of this table to the receiver position.
11548 With argument MAYBE, fail quietly if no transformation is defined for
11549 this table."
11550 (interactive)
11551 (catch 'exit
11552 (unless (org-at-table-p) (error "Not at a table"))
11553 ;; when non-interactive, we assume align has just happened.
11554 (when (interactive-p) (org-table-align))
11555 (save-excursion
11556 (goto-char (org-table-begin))
11557 (beginning-of-line 0)
11558 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11559 (if maybe
11560 (throw 'exit nil)
11561 (error "Don't know how to transform this table."))))
11562 (let* ((name (match-string 1))
11564 (transform (intern (match-string 2)))
11565 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11566 (skip (plist-get params :skip))
11567 (skipcols (plist-get params :skipcols))
11568 (txt (buffer-substring-no-properties
11569 (org-table-begin) (org-table-end)))
11570 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11571 (lines (org-table-clean-before-export lines))
11572 (i0 (if org-table-clean-did-remove-column 2 1))
11573 (table (mapcar
11574 (lambda (x)
11575 (if (string-match org-table-hline-regexp x)
11576 'hline
11577 (org-remove-by-index
11578 (org-split-string (org-trim x) "\\s-*|\\s-*")
11579 skipcols i0)))
11580 lines))
11581 (fun (if (= i0 2) 'cdr 'identity))
11582 (org-table-last-alignment
11583 (org-remove-by-index (funcall fun org-table-last-alignment)
11584 skipcols i0))
11585 (org-table-last-column-widths
11586 (org-remove-by-index (funcall fun org-table-last-column-widths)
11587 skipcols i0)))
11589 (unless (fboundp transform)
11590 (error "No such transformation function %s" transform))
11591 (setq txt (funcall transform table params))
11592 ;; Find the insertion place
11593 (save-excursion
11594 (goto-char (point-min))
11595 (unless (re-search-forward
11596 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11597 (error "Don't know where to insert translated table"))
11598 (goto-char (match-beginning 0))
11599 (beginning-of-line 2)
11600 (setq beg (point))
11601 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11602 (error "Cannot find end of insertion region"))
11603 (beginning-of-line 1)
11604 (delete-region beg (point))
11605 (goto-char beg)
11606 (insert txt "\n"))
11607 (message "Table converted and installed at receiver location"))))
11609 (defun org-remove-by-index (list indices &optional i0)
11610 "Remove the elements in LIST with indices in INDICES.
11611 First element has index 0, or I0 if given."
11612 (if (not indices)
11613 list
11614 (if (integerp indices) (setq indices (list indices)))
11615 (setq i0 (1- (or i0 0)))
11616 (delq :rm (mapcar (lambda (x)
11617 (setq i0 (1+ i0))
11618 (if (memq i0 indices) :rm x))
11619 list))))
11621 (defun orgtbl-toggle-comment ()
11622 "Comment or uncomment the orgtbl at point."
11623 (interactive)
11624 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11625 (re2 (concat "^" orgtbl-line-start-regexp))
11626 (commented (save-excursion (beginning-of-line 1)
11627 (cond ((looking-at re1) t)
11628 ((looking-at re2) nil)
11629 (t (error "Not at an org table")))))
11630 (re (if commented re1 re2))
11631 beg end)
11632 (save-excursion
11633 (beginning-of-line 1)
11634 (while (looking-at re) (beginning-of-line 0))
11635 (beginning-of-line 2)
11636 (setq beg (point))
11637 (while (looking-at re) (beginning-of-line 2))
11638 (setq end (point)))
11639 (comment-region beg end (if commented '(4) nil))))
11641 (defun orgtbl-insert-radio-table ()
11642 "Insert a radio table template appropriate for this major mode."
11643 (interactive)
11644 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11645 (txt (nth 1 e))
11646 name pos)
11647 (unless e (error "No radio table setup defined for %s" major-mode))
11648 (setq name (read-string "Table name: "))
11649 (while (string-match "%n" txt)
11650 (setq txt (replace-match name t t txt)))
11651 (or (bolp) (insert "\n"))
11652 (setq pos (point))
11653 (insert txt)
11654 (goto-char pos)))
11656 (defun org-get-param (params header i sym &optional hsym)
11657 "Get parameter value for symbol SYM.
11658 If this is a header line, actually get the value for the symbol with an
11659 additional \"h\" inserted after the colon.
11660 If the value is a protperty list, get the element for the current column.
11661 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11662 (let ((val (plist-get params sym)))
11663 (and hsym header (setq val (or (plist-get params hsym) val)))
11664 (if (consp val) (plist-get val i) val)))
11666 (defun orgtbl-to-generic (table params)
11667 "Convert the orgtbl-mode TABLE to some other format.
11668 This generic routine can be used for many standard cases.
11669 TABLE is a list, each entry either the symbol `hline' for a horizontal
11670 separator line, or a list of fields for that line.
11671 PARAMS is a property list of parameters that can influence the conversion.
11672 For the generic converter, some parameters are obligatory: You need to
11673 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11674 :splice, you must have :tstart and :tend.
11676 Valid parameters are
11678 :tstart String to start the table. Ignored when :splice is t.
11679 :tend String to end the table. Ignored when :splice is t.
11681 :splice When set to t, return only table body lines, don't wrap
11682 them into :tstart and :tend. Default is nil.
11684 :hline String to be inserted on horizontal separation lines.
11685 May be nil to ignore hlines.
11687 :lstart String to start a new table line.
11688 :lend String to end a table line
11689 :sep Separator between two fields
11690 :lfmt Format for entire line, with enough %s to capture all fields.
11691 If this is present, :lstart, :lend, and :sep are ignored.
11692 :fmt A format to be used to wrap the field, should contain
11693 %s for the original field value. For example, to wrap
11694 everything in dollars, you could use :fmt \"$%s$\".
11695 This may also be a property list with column numbers and
11696 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11698 :hlstart :hlend :hlsep :hlfmt :hfmt
11699 Same as above, specific for the header lines in the table.
11700 All lines before the first hline are treated as header.
11701 If any of these is not present, the data line value is used.
11703 :efmt Use this format to print numbers with exponentials.
11704 The format should have %s twice for inserting mantissa
11705 and exponent, for example \"%s\\\\times10^{%s}\". This
11706 may also be a property list with column numbers and
11707 formats. :fmt will still be applied after :efmt.
11709 In addition to this, the parameters :skip and :skipcols are always handled
11710 directly by `orgtbl-send-table'. See manual."
11711 (interactive)
11712 (let* ((p params)
11713 (splicep (plist-get p :splice))
11714 (hline (plist-get p :hline))
11715 rtn line i fm efm lfmt h)
11717 ;; Do we have a header?
11718 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11719 (setq h t))
11721 ;; Put header
11722 (unless splicep
11723 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11725 ;; Now loop over all lines
11726 (while (setq line (pop table))
11727 (if (eq line 'hline)
11728 ;; A horizontal separator line
11729 (progn (if hline (push hline rtn))
11730 (setq h nil)) ; no longer in header
11731 ;; A normal line. Convert the fields, push line onto the result list
11732 (setq i 0)
11733 (setq line
11734 (mapcar
11735 (lambda (f)
11736 (setq i (1+ i)
11737 fm (org-get-param p h i :fmt :hfmt)
11738 efm (org-get-param p h i :efmt))
11739 (if (and efm (string-match orgtbl-exp-regexp f))
11740 (setq f (format
11741 efm (match-string 1 f) (match-string 2 f))))
11742 (if fm (setq f (format fm f)))
11744 line))
11745 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11746 (push (apply 'format lfmt line) rtn)
11747 (push (concat
11748 (org-get-param p h i :lstart :hlstart)
11749 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11750 (org-get-param p h i :lend :hlend))
11751 rtn))))
11753 (unless splicep
11754 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11756 (mapconcat 'identity (nreverse rtn) "\n")))
11758 (defun orgtbl-to-latex (table params)
11759 "Convert the orgtbl-mode TABLE to LaTeX.
11760 TABLE is a list, each entry either the symbol `hline' for a horizontal
11761 separator line, or a list of fields for that line.
11762 PARAMS is a property list of parameters that can influence the conversion.
11763 Supports all parameters from `orgtbl-to-generic'. Most important for
11764 LaTeX are:
11766 :splice When set to t, return only table body lines, don't wrap
11767 them into a tabular environment. Default is nil.
11769 :fmt A format to be used to wrap the field, should contain %s for the
11770 original field value. For example, to wrap everything in dollars,
11771 use :fmt \"$%s$\". This may also be a property list with column
11772 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11774 :efmt Format for transforming numbers with exponentials. The format
11775 should have %s twice for inserting mantissa and exponent, for
11776 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11777 This may also be a property list with column numbers and formats.
11779 The general parameters :skip and :skipcols have already been applied when
11780 this function is called."
11781 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11782 org-table-last-alignment ""))
11783 (params2
11784 (list
11785 :tstart (concat "\\begin{tabular}{" alignment "}")
11786 :tend "\\end{tabular}"
11787 :lstart "" :lend " \\\\" :sep " & "
11788 :efmt "%s\\,(%s)" :hline "\\hline")))
11789 (orgtbl-to-generic table (org-combine-plists params2 params))))
11791 (defun orgtbl-to-html (table params)
11792 "Convert the orgtbl-mode TABLE to LaTeX.
11793 TABLE is a list, each entry either the symbol `hline' for a horizontal
11794 separator line, or a list of fields for that line.
11795 PARAMS is a property list of parameters that can influence the conversion.
11796 Currently this function recognizes the following parameters:
11798 :splice When set to t, return only table body lines, don't wrap
11799 them into a <table> environment. Default is nil.
11801 The general parameters :skip and :skipcols have already been applied when
11802 this function is called. The function does *not* use `orgtbl-to-generic',
11803 so you cannot specify parameters for it."
11804 (let* ((splicep (plist-get params :splice))
11805 html)
11806 ;; Just call the formatter we already have
11807 ;; We need to make text lines for it, so put the fields back together.
11808 (setq html (org-format-org-table-html
11809 (mapcar
11810 (lambda (x)
11811 (if (eq x 'hline)
11812 "|----+----|"
11813 (concat "| " (mapconcat 'identity x " | ") " |")))
11814 table)
11815 splicep))
11816 (if (string-match "\n+\\'" html)
11817 (setq html (replace-match "" t t html)))
11818 html))
11820 (defun orgtbl-to-texinfo (table params)
11821 "Convert the orgtbl-mode TABLE to TeXInfo.
11822 TABLE is a list, each entry either the symbol `hline' for a horizontal
11823 separator line, or a list of fields for that line.
11824 PARAMS is a property list of parameters that can influence the conversion.
11825 Supports all parameters from `orgtbl-to-generic'. Most important for
11826 TeXInfo are:
11828 :splice nil/t When set to t, return only table body lines, don't wrap
11829 them into a multitable environment. Default is nil.
11831 :fmt fmt A format to be used to wrap the field, should contain
11832 %s for the original field value. For example, to wrap
11833 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11834 This may also be a property list with column numbers and
11835 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11837 :cf \"f1 f2..\" The column fractions for the table. By default these
11838 are computed automatically from the width of the columns
11839 under org-mode.
11841 The general parameters :skip and :skipcols have already been applied when
11842 this function is called."
11843 (let* ((total (float (apply '+ org-table-last-column-widths)))
11844 (colfrac (or (plist-get params :cf)
11845 (mapconcat
11846 (lambda (x) (format "%.3f" (/ (float x) total)))
11847 org-table-last-column-widths " ")))
11848 (params2
11849 (list
11850 :tstart (concat "@multitable @columnfractions " colfrac)
11851 :tend "@end multitable"
11852 :lstart "@item " :lend "" :sep " @tab "
11853 :hlstart "@headitem ")))
11854 (orgtbl-to-generic table (org-combine-plists params2 params))))
11856 ;;;; Link Stuff
11858 ;;; Link abbreviations
11860 (defun org-link-expand-abbrev (link)
11861 "Apply replacements as defined in `org-link-abbrev-alist."
11862 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11863 (let* ((key (match-string 1 link))
11864 (as (or (assoc key org-link-abbrev-alist-local)
11865 (assoc key org-link-abbrev-alist)))
11866 (tag (and (match-end 2) (match-string 3 link)))
11867 rpl)
11868 (if (not as)
11869 link
11870 (setq rpl (cdr as))
11871 (cond
11872 ((symbolp rpl) (funcall rpl tag))
11873 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11874 (t (concat rpl tag)))))
11875 link))
11877 ;;; Storing and inserting links
11879 (defvar org-insert-link-history nil
11880 "Minibuffer history for links inserted with `org-insert-link'.")
11882 (defvar org-stored-links nil
11883 "Contains the links stored with `org-store-link'.")
11885 (defvar org-store-link-plist nil
11886 "Plist with info about the most recently link created with `org-store-link'.")
11888 (defvar org-link-protocols nil
11889 "Link protocols added to Org-mode using `org-add-link-type'.")
11891 (defvar org-store-link-functions nil
11892 "List of functions that are called to create and store a link.
11893 Each function will be called in turn until one returns a non-nil
11894 value. Each function should check if it is responsible for creating
11895 this link (for example by looking at the major mode).
11896 If not, it must exit and return nil.
11897 If yes, it should return a non-nil value after a calling
11898 `org-store-link-props' with a list of properties and values.
11899 Special properties are:
11901 :type The link prefix. like \"http\". This must be given.
11902 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11903 This is obligatory as well.
11904 :description Optional default description for the second pair
11905 of brackets in an Org-mode link. The user can still change
11906 this when inserting this link into an Org-mode buffer.
11908 In addition to these, any additional properties can be specified
11909 and then used in remember templates.")
11911 (defun org-add-link-type (type &optional follow publish)
11912 "Add TYPE to the list of `org-link-types'.
11913 Re-compute all regular expressions depending on `org-link-types'
11914 FOLLOW and PUBLISH are two functions. Both take the link path as
11915 an argument.
11916 FOLLOW should do whatever is necessary to follow the link, for example
11917 to find a file or display a mail message.
11919 PUBLISH takes the path and retuns the string that should be used when
11920 this document is published. FIMXE: This is actually not yet implemented."
11921 (add-to-list 'org-link-types type t)
11922 (org-make-link-regexps)
11923 (add-to-list 'org-link-protocols
11924 (list type follow publish)))
11926 (defun org-add-agenda-custom-command (entry)
11927 "Replace or add a command in `org-agenda-custom-commands'.
11928 This is mostly for hacking and trying a new command - once the command
11929 works you probably want to add it to `org-agenda-custom-commands' for good."
11930 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11931 (if ass
11932 (setcdr ass (cdr entry))
11933 (push entry org-agenda-custom-commands))))
11935 ;;;###autoload
11936 (defun org-store-link (arg)
11937 "\\<org-mode-map>Store an org-link to the current location.
11938 This link is added to `org-stored-links' and can later be inserted
11939 into an org-buffer with \\[org-insert-link].
11941 For some link types, a prefix arg is interpreted:
11942 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11943 For file links, arg negates `org-context-in-file-links'."
11944 (interactive "P")
11945 (setq org-store-link-plist nil) ; reset
11946 (require 'org-irc)
11947 (let (link cpltxt desc description search txt)
11948 (cond
11950 ((run-hook-with-args-until-success 'org-store-link-functions)
11951 (setq link (plist-get org-store-link-plist :link)
11952 desc (or (plist-get org-store-link-plist :description) link)))
11954 ((eq major-mode 'bbdb-mode)
11955 (let ((name (bbdb-record-name (bbdb-current-record)))
11956 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11957 (setq cpltxt (concat "bbdb:" (or name company))
11958 link (org-make-link cpltxt))
11959 (org-store-link-props :type "bbdb" :name name :company company)))
11961 ((eq major-mode 'Info-mode)
11962 (setq link (org-make-link "info:"
11963 (file-name-nondirectory Info-current-file)
11964 ":" Info-current-node))
11965 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11966 ":" Info-current-node))
11967 (org-store-link-props :type "info" :file Info-current-file
11968 :node Info-current-node))
11970 ((eq major-mode 'calendar-mode)
11971 (let ((cd (calendar-cursor-to-date)))
11972 (setq link
11973 (format-time-string
11974 (car org-time-stamp-formats)
11975 (apply 'encode-time
11976 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11977 nil nil nil))))
11978 (org-store-link-props :type "calendar" :date cd)))
11980 ((or (eq major-mode 'vm-summary-mode)
11981 (eq major-mode 'vm-presentation-mode))
11982 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11983 (vm-follow-summary-cursor)
11984 (save-excursion
11985 (vm-select-folder-buffer)
11986 (let* ((message (car vm-message-pointer))
11987 (folder buffer-file-name)
11988 (subject (vm-su-subject message))
11989 (to (vm-get-header-contents message "To"))
11990 (from (vm-get-header-contents message "From"))
11991 (message-id (vm-su-message-id message)))
11992 (org-store-link-props :type "vm" :from from :to to :subject subject
11993 :message-id message-id)
11994 (setq message-id (org-remove-angle-brackets message-id))
11995 (setq folder (abbreviate-file-name folder))
11996 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11997 folder)
11998 (setq folder (replace-match "" t t folder)))
11999 (setq cpltxt (org-email-link-description))
12000 (setq link (org-make-link "vm:" folder "#" message-id)))))
12002 ((eq major-mode 'wl-summary-mode)
12003 (let* ((msgnum (wl-summary-message-number))
12004 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12005 msgnum 'message-id))
12006 (wl-message-entity
12007 (if (fboundp 'elmo-message-entity)
12008 (elmo-message-entity
12009 wl-summary-buffer-elmo-folder msgnum)
12010 (elmo-msgdb-overview-get-entity
12011 msgnum (wl-summary-buffer-msgdb))))
12012 (from (wl-summary-line-from))
12013 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12014 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12015 (wl-summary-line-subject))))
12016 (org-store-link-props :type "wl" :from from :to to
12017 :subject subject :message-id message-id)
12018 (setq message-id (org-remove-angle-brackets message-id))
12019 (setq cpltxt (org-email-link-description))
12020 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12021 "#" message-id))))
12023 ((or (equal major-mode 'mh-folder-mode)
12024 (equal major-mode 'mh-show-mode))
12025 (let ((from (org-mhe-get-header "From:"))
12026 (to (org-mhe-get-header "To:"))
12027 (message-id (org-mhe-get-header "Message-Id:"))
12028 (subject (org-mhe-get-header "Subject:")))
12029 (org-store-link-props :type "mh" :from from :to to
12030 :subject subject :message-id message-id)
12031 (setq cpltxt (org-email-link-description))
12032 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12033 (org-remove-angle-brackets message-id)))))
12035 ((or (eq major-mode 'rmail-mode)
12036 (eq major-mode 'rmail-summary-mode))
12037 (save-window-excursion
12038 (save-restriction
12039 (when (eq major-mode 'rmail-summary-mode)
12040 (rmail-show-message rmail-current-message))
12041 (rmail-narrow-to-non-pruned-header)
12042 (let ((folder buffer-file-name)
12043 (message-id (mail-fetch-field "message-id"))
12044 (from (mail-fetch-field "from"))
12045 (to (mail-fetch-field "to"))
12046 (subject (mail-fetch-field "subject")))
12047 (org-store-link-props
12048 :type "rmail" :from from :to to
12049 :subject subject :message-id message-id)
12050 (setq message-id (org-remove-angle-brackets message-id))
12051 (setq cpltxt (org-email-link-description))
12052 (setq link (org-make-link "rmail:" folder "#" message-id)))
12053 (rmail-show-message rmail-current-message))))
12055 ((eq major-mode 'gnus-group-mode)
12056 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12057 (gnus-group-group-name)) ; version
12058 ((fboundp 'gnus-group-name)
12059 (gnus-group-name))
12060 (t "???"))))
12061 (unless group (error "Not on a group"))
12062 (org-store-link-props :type "gnus" :group group)
12063 (setq cpltxt (concat
12064 (if (org-xor arg org-usenet-links-prefer-google)
12065 "http://groups.google.com/groups?group="
12066 "gnus:")
12067 group)
12068 link (org-make-link cpltxt))))
12070 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12071 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12072 (let* ((group gnus-newsgroup-name)
12073 (article (gnus-summary-article-number))
12074 (header (gnus-summary-article-header article))
12075 (from (mail-header-from header))
12076 (message-id (mail-header-id header))
12077 (date (mail-header-date header))
12078 (subject (gnus-summary-subject-string)))
12079 (org-store-link-props :type "gnus" :from from :subject subject
12080 :message-id message-id :group group)
12081 (setq cpltxt (org-email-link-description))
12082 (if (org-xor arg org-usenet-links-prefer-google)
12083 (setq link
12084 (concat
12085 cpltxt "\n "
12086 (format "http://groups.google.com/groups?as_umsgid=%s"
12087 (org-fixup-message-id-for-http message-id))))
12088 (setq link (org-make-link "gnus:" group
12089 "#" (number-to-string article))))))
12091 ((eq major-mode 'w3-mode)
12092 (setq cpltxt (url-view-url t)
12093 link (org-make-link cpltxt))
12094 (org-store-link-props :type "w3" :url (url-view-url t)))
12096 ((eq major-mode 'w3m-mode)
12097 (setq cpltxt (or w3m-current-title w3m-current-url)
12098 link (org-make-link w3m-current-url))
12099 (org-store-link-props :type "w3m" :url (url-view-url t)))
12101 ((setq search (run-hook-with-args-until-success
12102 'org-create-file-search-functions))
12103 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12104 "::" search))
12105 (setq cpltxt (or description link)))
12107 ((eq major-mode 'image-mode)
12108 (setq cpltxt (concat "file:"
12109 (abbreviate-file-name buffer-file-name))
12110 link (org-make-link cpltxt))
12111 (org-store-link-props :type "image" :file buffer-file-name))
12113 ((eq major-mode 'dired-mode)
12114 ;; link to the file in the current line
12115 (setq cpltxt (concat "file:"
12116 (abbreviate-file-name
12117 (expand-file-name
12118 (dired-get-filename nil t))))
12119 link (org-make-link cpltxt)))
12121 ((and buffer-file-name (org-mode-p))
12122 ;; Just link to current headline
12123 (setq cpltxt (concat "file:"
12124 (abbreviate-file-name buffer-file-name)))
12125 ;; Add a context search string
12126 (when (org-xor org-context-in-file-links arg)
12127 ;; Check if we are on a target
12128 (if (org-in-regexp "<<\\(.*?\\)>>")
12129 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12130 (setq txt (cond
12131 ((org-on-heading-p) nil)
12132 ((org-region-active-p)
12133 (buffer-substring (region-beginning) (region-end)))
12134 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12135 (when (or (null txt) (string-match "\\S-" txt))
12136 (setq cpltxt
12137 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12138 desc "NONE"))))
12139 (if (string-match "::\\'" cpltxt)
12140 (setq cpltxt (substring cpltxt 0 -2)))
12141 (setq link (org-make-link cpltxt)))
12143 ((buffer-file-name (buffer-base-buffer))
12144 ;; Just link to this file here.
12145 (setq cpltxt (concat "file:"
12146 (abbreviate-file-name
12147 (buffer-file-name (buffer-base-buffer)))))
12148 ;; Add a context string
12149 (when (org-xor org-context-in-file-links arg)
12150 (setq txt (if (org-region-active-p)
12151 (buffer-substring (region-beginning) (region-end))
12152 (buffer-substring (point-at-bol) (point-at-eol))))
12153 ;; Only use search option if there is some text.
12154 (when (string-match "\\S-" txt)
12155 (setq cpltxt
12156 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12157 desc "NONE")))
12158 (setq link (org-make-link cpltxt)))
12160 ((interactive-p)
12161 (error "Cannot link to a buffer which is not visiting a file"))
12163 (t (setq link nil)))
12165 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12166 (setq link (or link cpltxt)
12167 desc (or desc cpltxt))
12168 (if (equal desc "NONE") (setq desc nil))
12170 (if (and (interactive-p) link)
12171 (progn
12172 (setq org-stored-links
12173 (cons (list link desc) org-stored-links))
12174 (message "Stored: %s" (or desc link)))
12175 (and link (org-make-link-string link desc)))))
12177 (defun org-store-link-props (&rest plist)
12178 "Store link properties, extract names and addresses."
12179 (let (x adr)
12180 (when (setq x (plist-get plist :from))
12181 (setq adr (mail-extract-address-components x))
12182 (plist-put plist :fromname (car adr))
12183 (plist-put plist :fromaddress (nth 1 adr)))
12184 (when (setq x (plist-get plist :to))
12185 (setq adr (mail-extract-address-components x))
12186 (plist-put plist :toname (car adr))
12187 (plist-put plist :toaddress (nth 1 adr))))
12188 (let ((from (plist-get plist :from))
12189 (to (plist-get plist :to)))
12190 (when (and from to org-from-is-user-regexp)
12191 (plist-put plist :fromto
12192 (if (string-match org-from-is-user-regexp from)
12193 (concat "to %t")
12194 (concat "from %f")))))
12195 (setq org-store-link-plist plist))
12197 (defun org-email-link-description (&optional fmt)
12198 "Return the description part of an email link.
12199 This takes information from `org-store-link-plist' and formats it
12200 according to FMT (default from `org-email-link-description-format')."
12201 (setq fmt (or fmt org-email-link-description-format))
12202 (let* ((p org-store-link-plist)
12203 (to (plist-get p :toaddress))
12204 (from (plist-get p :fromaddress))
12205 (table
12206 (list
12207 (cons "%c" (plist-get p :fromto))
12208 (cons "%F" (plist-get p :from))
12209 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12210 (cons "%T" (plist-get p :to))
12211 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12212 (cons "%s" (plist-get p :subject))
12213 (cons "%m" (plist-get p :message-id)))))
12214 (when (string-match "%c" fmt)
12215 ;; Check if the user wrote this message
12216 (if (and org-from-is-user-regexp from to
12217 (save-match-data (string-match org-from-is-user-regexp from)))
12218 (setq fmt (replace-match "to %t" t t fmt))
12219 (setq fmt (replace-match "from %f" t t fmt))))
12220 (org-replace-escapes fmt table)))
12222 (defun org-make-org-heading-search-string (&optional string heading)
12223 "Make search string for STRING or current headline."
12224 (interactive)
12225 (let ((s (or string (org-get-heading))))
12226 (unless (and string (not heading))
12227 ;; We are using a headline, clean up garbage in there.
12228 (if (string-match org-todo-regexp s)
12229 (setq s (replace-match "" t t s)))
12230 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12231 (setq s (replace-match "" t t s)))
12232 (setq s (org-trim s))
12233 (if (string-match (concat "^\\(" org-quote-string "\\|"
12234 org-comment-string "\\)") s)
12235 (setq s (replace-match "" t t s)))
12236 (while (string-match org-ts-regexp s)
12237 (setq s (replace-match "" t t s))))
12238 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12239 (setq s (replace-match " " t t s)))
12240 (or string (setq s (concat "*" s))) ; Add * for headlines
12241 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12243 (defun org-make-link (&rest strings)
12244 "Concatenate STRINGS."
12245 (apply 'concat strings))
12247 (defun org-make-link-string (link &optional description)
12248 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12249 (unless (string-match "\\S-" link)
12250 (error "Empty link"))
12251 (when (stringp description)
12252 ;; Remove brackets from the description, they are fatal.
12253 (while (string-match "\\[" description)
12254 (setq description (replace-match "{" t t description)))
12255 (while (string-match "\\]" description)
12256 (setq description (replace-match "}" t t description))))
12257 (when (equal (org-link-escape link) description)
12258 ;; No description needed, it is identical
12259 (setq description nil))
12260 (when (and (not description)
12261 (not (equal link (org-link-escape link))))
12262 (setq description link))
12263 (concat "[[" (org-link-escape link) "]"
12264 (if description (concat "[" description "]") "")
12265 "]"))
12267 (defconst org-link-escape-chars
12268 '((?\ . "%20")
12269 (?\[ . "%5B")
12270 (?\] . "%5D")
12271 (?\340 . "%E0") ; `a
12272 (?\342 . "%E2") ; ^a
12273 (?\347 . "%E7") ; ,c
12274 (?\350 . "%E8") ; `e
12275 (?\351 . "%E9") ; 'e
12276 (?\352 . "%EA") ; ^e
12277 (?\356 . "%EE") ; ^i
12278 (?\364 . "%F4") ; ^o
12279 (?\371 . "%F9") ; `u
12280 (?\373 . "%FB") ; ^u
12281 (?\; . "%3B")
12282 (?? . "%3F")
12283 (?= . "%3D")
12284 (?+ . "%2B")
12286 "Association list of escapes for some characters problematic in links.
12287 This is the list that is used for internal purposes.")
12289 (defconst org-link-escape-chars-browser
12290 '((?\ . "%20")) ; 32 for the SPC char
12291 "Association list of escapes for some characters problematic in links.
12292 This is the list that is used before handing over to the browser.")
12294 (defun org-link-escape (text &optional table)
12295 "Escape charaters in TEXT that are problematic for links."
12296 (setq table (or table org-link-escape-chars))
12297 (when text
12298 (let ((re (mapconcat (lambda (x) (regexp-quote
12299 (char-to-string (car x))))
12300 table "\\|")))
12301 (while (string-match re text)
12302 (setq text
12303 (replace-match
12304 (cdr (assoc (string-to-char (match-string 0 text))
12305 table))
12306 t t text)))
12307 text)))
12309 (defun org-link-unescape (text &optional table)
12310 "Reverse the action of `org-link-escape'."
12311 (setq table (or table org-link-escape-chars))
12312 (when text
12313 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12314 table "\\|")))
12315 (while (string-match re text)
12316 (setq text
12317 (replace-match
12318 (char-to-string (car (rassoc (match-string 0 text) table)))
12319 t t text)))
12320 text)))
12322 (defun org-xor (a b)
12323 "Exclusive or."
12324 (if a (not b) b))
12326 (defun org-get-header (header)
12327 "Find a header field in the current buffer."
12328 (save-excursion
12329 (goto-char (point-min))
12330 (let ((case-fold-search t) s)
12331 (cond
12332 ((eq header 'from)
12333 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12334 (setq s (match-string 1)))
12335 (while (string-match "\"" s)
12336 (setq s (replace-match "" t t s)))
12337 (if (string-match "[<(].*" s)
12338 (setq s (replace-match "" t t s))))
12339 ((eq header 'message-id)
12340 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12341 (setq s (match-string 1))))
12342 ((eq header 'subject)
12343 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12344 (setq s (match-string 1)))))
12345 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12346 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12347 s)))
12350 (defun org-fixup-message-id-for-http (s)
12351 "Replace special characters in a message id, so it can be used in an http query."
12352 (while (string-match "<" s)
12353 (setq s (replace-match "%3C" t t s)))
12354 (while (string-match ">" s)
12355 (setq s (replace-match "%3E" t t s)))
12356 (while (string-match "@" s)
12357 (setq s (replace-match "%40" t t s)))
12360 ;;;###autoload
12361 (defun org-insert-link-global ()
12362 "Insert a link like Org-mode does.
12363 This command can be called in any mode to insert a link in Org-mode syntax."
12364 (interactive)
12365 (org-run-like-in-org-mode 'org-insert-link))
12367 (defun org-insert-link (&optional complete-file)
12368 "Insert a link. At the prompt, enter the link.
12370 Completion can be used to select a link previously stored with
12371 `org-store-link'. When the empty string is entered (i.e. if you just
12372 press RET at the prompt), the link defaults to the most recently
12373 stored link. As SPC triggers completion in the minibuffer, you need to
12374 use M-SPC or C-q SPC to force the insertion of a space character.
12376 You will also be prompted for a description, and if one is given, it will
12377 be displayed in the buffer instead of the link.
12379 If there is already a link at point, this command will allow you to edit link
12380 and description parts.
12382 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12383 selected using completion. The path to the file will be relative to
12384 the current directory if the file is in the current directory or a
12385 subdirectory. Otherwise, the link will be the absolute path as
12386 completed in the minibuffer (i.e. normally ~/path/to/file).
12388 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12389 is in the current directory or below.
12390 With three \\[universal-argument] prefixes, negate the meaning of
12391 `org-keep-stored-link-after-insertion'."
12392 (interactive "P")
12393 (let* ((wcf (current-window-configuration))
12394 (region (if (org-region-active-p)
12395 (buffer-substring (region-beginning) (region-end))))
12396 (remove (and region (list (region-beginning) (region-end))))
12397 (desc region)
12398 tmphist ; byte-compile incorrectly complains about this
12399 link entry file)
12400 (cond
12401 ((org-in-regexp org-bracket-link-regexp 1)
12402 ;; We do have a link at point, and we are going to edit it.
12403 (setq remove (list (match-beginning 0) (match-end 0)))
12404 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12405 (setq link (read-string "Link: "
12406 (org-link-unescape
12407 (org-match-string-no-properties 1)))))
12408 ((or (org-in-regexp org-angle-link-re)
12409 (org-in-regexp org-plain-link-re))
12410 ;; Convert to bracket link
12411 (setq remove (list (match-beginning 0) (match-end 0))
12412 link (read-string "Link: "
12413 (org-remove-angle-brackets (match-string 0)))))
12414 ((equal complete-file '(4))
12415 ;; Completing read for file names.
12416 (setq file (read-file-name "File: "))
12417 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12418 (pwd1 (file-name-as-directory (abbreviate-file-name
12419 (expand-file-name ".")))))
12420 (cond
12421 ((equal complete-file '(16))
12422 (setq link (org-make-link
12423 "file:"
12424 (abbreviate-file-name (expand-file-name file)))))
12425 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12426 (setq link (org-make-link "file:" (match-string 1 file))))
12427 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12428 (expand-file-name file))
12429 (setq link (org-make-link
12430 "file:" (match-string 1 (expand-file-name file)))))
12431 (t (setq link (org-make-link "file:" file))))))
12433 ;; Read link, with completion for stored links.
12434 (with-output-to-temp-buffer "*Org Links*"
12435 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12436 (when org-stored-links
12437 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12438 (princ (mapconcat
12439 (lambda (x)
12440 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12441 (reverse org-stored-links) "\n"))))
12442 (let ((cw (selected-window)))
12443 (select-window (get-buffer-window "*Org Links*"))
12444 (shrink-window-if-larger-than-buffer)
12445 (setq truncate-lines t)
12446 (select-window cw))
12447 ;; Fake a link history, containing the stored links.
12448 (setq tmphist (append (mapcar 'car org-stored-links)
12449 org-insert-link-history))
12450 (unwind-protect
12451 (setq link (org-completing-read
12452 "Link: "
12453 (append
12454 (mapcar (lambda (x) (list (concat (car x) ":")))
12455 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12456 (mapcar (lambda (x) (list (concat x ":")))
12457 org-link-types))
12458 nil nil nil
12459 'tmphist
12460 (or (car (car org-stored-links)))))
12461 (set-window-configuration wcf)
12462 (kill-buffer "*Org Links*"))
12463 (setq entry (assoc link org-stored-links))
12464 (or entry (push link org-insert-link-history))
12465 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12466 (not org-keep-stored-link-after-insertion))
12467 (setq org-stored-links (delq (assoc link org-stored-links)
12468 org-stored-links)))
12469 (setq desc (or desc (nth 1 entry)))))
12471 (if (string-match org-plain-link-re link)
12472 ;; URL-like link, normalize the use of angular brackets.
12473 (setq link (org-make-link (org-remove-angle-brackets link))))
12475 ;; Check if we are linking to the current file with a search option
12476 ;; If yes, simplify the link by using only the search option.
12477 (when (and buffer-file-name
12478 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12479 (let* ((path (match-string 1 link))
12480 (case-fold-search nil)
12481 (search (match-string 2 link)))
12482 (save-match-data
12483 (if (equal (file-truename buffer-file-name) (file-truename path))
12484 ;; We are linking to this same file, with a search option
12485 (setq link search)))))
12487 ;; Check if we can/should use a relative path. If yes, simplify the link
12488 (when (string-match "\\<file:\\(.*\\)" link)
12489 (let* ((path (match-string 1 link))
12490 (origpath path)
12491 (case-fold-search nil))
12492 (cond
12493 ((eq org-link-file-path-type 'absolute)
12494 (setq path (abbreviate-file-name (expand-file-name path))))
12495 ((eq org-link-file-path-type 'noabbrev)
12496 (setq path (expand-file-name path)))
12497 ((eq org-link-file-path-type 'relative)
12498 (setq path (file-relative-name path)))
12500 (save-match-data
12501 (if (string-match (concat "^" (regexp-quote
12502 (file-name-as-directory
12503 (expand-file-name "."))))
12504 (expand-file-name path))
12505 ;; We are linking a file with relative path name.
12506 (setq path (substring (expand-file-name path)
12507 (match-end 0)))))))
12508 (setq link (concat "file:" path))
12509 (if (equal desc origpath)
12510 (setq desc path))))
12512 (setq desc (read-string "Description: " desc))
12513 (unless (string-match "\\S-" desc) (setq desc nil))
12514 (if remove (apply 'delete-region remove))
12515 (insert (org-make-link-string link desc))))
12517 (defun org-completing-read (&rest args)
12518 (let ((minibuffer-local-completion-map
12519 (copy-keymap minibuffer-local-completion-map)))
12520 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12521 (apply 'completing-read args)))
12523 ;;; Opening/following a link
12524 (defvar org-link-search-failed nil)
12526 (defun org-next-link ()
12527 "Move forward to the next link.
12528 If the link is in hidden text, expose it."
12529 (interactive)
12530 (when (and org-link-search-failed (eq this-command last-command))
12531 (goto-char (point-min))
12532 (message "Link search wrapped back to beginning of buffer"))
12533 (setq org-link-search-failed nil)
12534 (let* ((pos (point))
12535 (ct (org-context))
12536 (a (assoc :link ct)))
12537 (if a (goto-char (nth 2 a)))
12538 (if (re-search-forward org-any-link-re nil t)
12539 (progn
12540 (goto-char (match-beginning 0))
12541 (if (org-invisible-p) (org-show-context)))
12542 (goto-char pos)
12543 (setq org-link-search-failed t)
12544 (error "No further link found"))))
12546 (defun org-previous-link ()
12547 "Move backward to the previous link.
12548 If the link is in hidden text, expose it."
12549 (interactive)
12550 (when (and org-link-search-failed (eq this-command last-command))
12551 (goto-char (point-max))
12552 (message "Link search wrapped back to end of buffer"))
12553 (setq org-link-search-failed nil)
12554 (let* ((pos (point))
12555 (ct (org-context))
12556 (a (assoc :link ct)))
12557 (if a (goto-char (nth 1 a)))
12558 (if (re-search-backward org-any-link-re nil t)
12559 (progn
12560 (goto-char (match-beginning 0))
12561 (if (org-invisible-p) (org-show-context)))
12562 (goto-char pos)
12563 (setq org-link-search-failed t)
12564 (error "No further link found"))))
12566 (defun org-find-file-at-mouse (ev)
12567 "Open file link or URL at mouse."
12568 (interactive "e")
12569 (mouse-set-point ev)
12570 (org-open-at-point 'in-emacs))
12572 (defun org-open-at-mouse (ev)
12573 "Open file link or URL at mouse."
12574 (interactive "e")
12575 (mouse-set-point ev)
12576 (org-open-at-point))
12578 (defvar org-window-config-before-follow-link nil
12579 "The window configuration before following a link.
12580 This is saved in case the need arises to restore it.")
12582 (defvar org-open-link-marker (make-marker)
12583 "Marker pointing to the location where `org-open-at-point; was called.")
12585 ;;;###autoload
12586 (defun org-open-at-point-global ()
12587 "Follow a link like Org-mode does.
12588 This command can be called in any mode to follow a link that has
12589 Org-mode syntax."
12590 (interactive)
12591 (org-run-like-in-org-mode 'org-open-at-point))
12593 (defun org-open-at-point (&optional in-emacs)
12594 "Open link at or after point.
12595 If there is no link at point, this function will search forward up to
12596 the end of the current subtree.
12597 Normally, files will be opened by an appropriate application. If the
12598 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12599 (interactive "P")
12600 (catch 'abort
12601 (move-marker org-open-link-marker (point))
12602 (setq org-window-config-before-follow-link (current-window-configuration))
12603 (org-remove-occur-highlights nil nil t)
12604 (if (org-at-timestamp-p t)
12605 (org-follow-timestamp-link)
12606 (let (type path link line search (pos (point)))
12607 (catch 'match
12608 (save-excursion
12609 (skip-chars-forward "^]\n\r")
12610 (when (org-in-regexp org-bracket-link-regexp)
12611 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12612 (while (string-match " *\n *" link)
12613 (setq link (replace-match " " t t link)))
12614 (setq link (org-link-expand-abbrev link))
12615 (if (string-match org-link-re-with-space2 link)
12616 (setq type (match-string 1 link) path (match-string 2 link))
12617 (setq type "thisfile" path link))
12618 (throw 'match t)))
12620 (when (get-text-property (point) 'org-linked-text)
12621 (setq type "thisfile"
12622 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12623 (1+ (point)) (point))
12624 path (buffer-substring
12625 (previous-single-property-change pos 'org-linked-text)
12626 (next-single-property-change pos 'org-linked-text)))
12627 (throw 'match t))
12629 (save-excursion
12630 (when (or (org-in-regexp org-angle-link-re)
12631 (org-in-regexp org-plain-link-re))
12632 (setq type (match-string 1) path (match-string 2))
12633 (throw 'match t)))
12634 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12635 (setq type "tree-match"
12636 path (match-string 1))
12637 (throw 'match t))
12638 (save-excursion
12639 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12640 (setq type "tags"
12641 path (match-string 1))
12642 (while (string-match ":" path)
12643 (setq path (replace-match "+" t t path)))
12644 (throw 'match t))))
12645 (unless path
12646 (error "No link found"))
12647 ;; Remove any trailing spaces in path
12648 (if (string-match " +\\'" path)
12649 (setq path (replace-match "" t t path)))
12651 (cond
12653 ((assoc type org-link-protocols)
12654 (funcall (nth 1 (assoc type org-link-protocols)) path))
12656 ((equal type "mailto")
12657 (let ((cmd (car org-link-mailto-program))
12658 (args (cdr org-link-mailto-program)) args1
12659 (address path) (subject "") a)
12660 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12661 (setq address (match-string 1 path)
12662 subject (org-link-escape (match-string 2 path))))
12663 (while args
12664 (cond
12665 ((not (stringp (car args))) (push (pop args) args1))
12666 (t (setq a (pop args))
12667 (if (string-match "%a" a)
12668 (setq a (replace-match address t t a)))
12669 (if (string-match "%s" a)
12670 (setq a (replace-match subject t t a)))
12671 (push a args1))))
12672 (apply cmd (nreverse args1))))
12674 ((member type '("http" "https" "ftp" "news"))
12675 (browse-url (concat type ":" (org-link-escape
12676 path org-link-escape-chars-browser))))
12678 ((member type '("message"))
12679 (browse-url (concat type ":" path)))
12681 ((string= type "tags")
12682 (org-tags-view in-emacs path))
12683 ((string= type "thisfile")
12684 (if in-emacs
12685 (switch-to-buffer-other-window
12686 (org-get-buffer-for-internal-link (current-buffer)))
12687 (org-mark-ring-push))
12688 (let ((cmd `(org-link-search
12689 ,path
12690 ,(cond ((equal in-emacs '(4)) 'occur)
12691 ((equal in-emacs '(16)) 'org-occur)
12692 (t nil))
12693 ,pos)))
12694 (condition-case nil (eval cmd)
12695 (error (progn (widen) (eval cmd))))))
12697 ((string= type "tree-match")
12698 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12700 ((string= type "file")
12701 (if (string-match "::\\([0-9]+\\)\\'" path)
12702 (setq line (string-to-number (match-string 1 path))
12703 path (substring path 0 (match-beginning 0)))
12704 (if (string-match "::\\(.+\\)\\'" path)
12705 (setq search (match-string 1 path)
12706 path (substring path 0 (match-beginning 0)))))
12707 (if (string-match "[*?{]" (file-name-nondirectory path))
12708 (dired path)
12709 (org-open-file path in-emacs line search)))
12711 ((string= type "news")
12712 (org-follow-gnus-link path))
12714 ((string= type "bbdb")
12715 (org-follow-bbdb-link path))
12717 ((string= type "info")
12718 (org-follow-info-link path))
12720 ((string= type "gnus")
12721 (let (group article)
12722 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12723 (error "Error in Gnus link"))
12724 (setq group (match-string 1 path)
12725 article (match-string 3 path))
12726 (org-follow-gnus-link group article)))
12728 ((string= type "vm")
12729 (let (folder article)
12730 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12731 (error "Error in VM link"))
12732 (setq folder (match-string 1 path)
12733 article (match-string 3 path))
12734 ;; in-emacs is the prefix arg, will be interpreted as read-only
12735 (org-follow-vm-link folder article in-emacs)))
12737 ((string= type "wl")
12738 (let (folder article)
12739 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12740 (error "Error in Wanderlust link"))
12741 (setq folder (match-string 1 path)
12742 article (match-string 3 path))
12743 (org-follow-wl-link folder article)))
12745 ((string= type "mhe")
12746 (let (folder article)
12747 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12748 (error "Error in MHE link"))
12749 (setq folder (match-string 1 path)
12750 article (match-string 3 path))
12751 (org-follow-mhe-link folder article)))
12753 ((string= type "rmail")
12754 (let (folder article)
12755 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12756 (error "Error in RMAIL link"))
12757 (setq folder (match-string 1 path)
12758 article (match-string 3 path))
12759 (org-follow-rmail-link folder article)))
12761 ((string= type "shell")
12762 (let ((cmd path))
12763 (if (or (not org-confirm-shell-link-function)
12764 (funcall org-confirm-shell-link-function
12765 (format "Execute \"%s\" in shell? "
12766 (org-add-props cmd nil
12767 'face 'org-warning))))
12768 (progn
12769 (message "Executing %s" cmd)
12770 (shell-command cmd))
12771 (error "Abort"))))
12773 ((string= type "elisp")
12774 (let ((cmd path))
12775 (if (or (not org-confirm-elisp-link-function)
12776 (funcall org-confirm-elisp-link-function
12777 (format "Execute \"%s\" as elisp? "
12778 (org-add-props cmd nil
12779 'face 'org-warning))))
12780 (message "%s => %s" cmd (eval (read cmd)))
12781 (error "Abort"))))
12784 (browse-url-at-point)))))
12785 (move-marker org-open-link-marker nil)))
12787 ;;; File search
12789 (defvar org-create-file-search-functions nil
12790 "List of functions to construct the right search string for a file link.
12791 These functions are called in turn with point at the location to
12792 which the link should point.
12794 A function in the hook should first test if it would like to
12795 handle this file type, for example by checking the major-mode or
12796 the file extension. If it decides not to handle this file, it
12797 should just return nil to give other functions a chance. If it
12798 does handle the file, it must return the search string to be used
12799 when following the link. The search string will be part of the
12800 file link, given after a double colon, and `org-open-at-point'
12801 will automatically search for it. If special measures must be
12802 taken to make the search successful, another function should be
12803 added to the companion hook `org-execute-file-search-functions',
12804 which see.
12806 A function in this hook may also use `setq' to set the variable
12807 `description' to provide a suggestion for the descriptive text to
12808 be used for this link when it gets inserted into an Org-mode
12809 buffer with \\[org-insert-link].")
12811 (defvar org-execute-file-search-functions nil
12812 "List of functions to execute a file search triggered by a link.
12814 Functions added to this hook must accept a single argument, the
12815 search string that was part of the file link, the part after the
12816 double colon. The function must first check if it would like to
12817 handle this search, for example by checking the major-mode or the
12818 file extension. If it decides not to handle this search, it
12819 should just return nil to give other functions a chance. If it
12820 does handle the search, it must return a non-nil value to keep
12821 other functions from trying.
12823 Each function can access the current prefix argument through the
12824 variable `current-prefix-argument'. Note that a single prefix is
12825 used to force opening a link in Emacs, so it may be good to only
12826 use a numeric or double prefix to guide the search function.
12828 In case this is needed, a function in this hook can also restore
12829 the window configuration before `org-open-at-point' was called using:
12831 (set-window-configuration org-window-config-before-follow-link)")
12833 (defun org-link-search (s &optional type avoid-pos)
12834 "Search for a link search option.
12835 If S is surrounded by forward slashes, it is interpreted as a
12836 regular expression. In org-mode files, this will create an `org-occur'
12837 sparse tree. In ordinary files, `occur' will be used to list matches.
12838 If the current buffer is in `dired-mode', grep will be used to search
12839 in all files. If AVOID-POS is given, ignore matches near that position."
12840 (let ((case-fold-search t)
12841 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12842 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12843 (append '(("") (" ") ("\t") ("\n"))
12844 org-emphasis-alist)
12845 "\\|") "\\)"))
12846 (pos (point))
12847 (pre "") (post "")
12848 words re0 re1 re2 re3 re4 re5 re2a reall)
12849 (cond
12850 ;; First check if there are any special
12851 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12852 ;; Now try the builtin stuff
12853 ((save-excursion
12854 (goto-char (point-min))
12855 (and
12856 (re-search-forward
12857 (concat "<<" (regexp-quote s0) ">>") nil t)
12858 (setq pos (match-beginning 0))))
12859 ;; There is an exact target for this
12860 (goto-char pos))
12861 ((string-match "^/\\(.*\\)/$" s)
12862 ;; A regular expression
12863 (cond
12864 ((org-mode-p)
12865 (org-occur (match-string 1 s)))
12866 ;;((eq major-mode 'dired-mode)
12867 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12868 (t (org-do-occur (match-string 1 s)))))
12870 ;; A normal search strings
12871 (when (equal (string-to-char s) ?*)
12872 ;; Anchor on headlines, post may include tags.
12873 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12874 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12875 s (substring s 1)))
12876 (remove-text-properties
12877 0 (length s)
12878 '(face nil mouse-face nil keymap nil fontified nil) s)
12879 ;; Make a series of regular expressions to find a match
12880 (setq words (org-split-string s "[ \n\r\t]+")
12881 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12882 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12883 "\\)" markers)
12884 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12885 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12886 re1 (concat pre re2 post)
12887 re3 (concat pre re4 post)
12888 re5 (concat pre ".*" re4)
12889 re2 (concat pre re2)
12890 re2a (concat pre re2a)
12891 re4 (concat pre re4)
12892 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12893 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12894 re5 "\\)"
12896 (cond
12897 ((eq type 'org-occur) (org-occur reall))
12898 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12899 (t (goto-char (point-min))
12900 (if (or (org-search-not-self 1 re0 nil t)
12901 (org-search-not-self 1 re1 nil t)
12902 (org-search-not-self 1 re2 nil t)
12903 (org-search-not-self 1 re2a nil t)
12904 (org-search-not-self 1 re3 nil t)
12905 (org-search-not-self 1 re4 nil t)
12906 (org-search-not-self 1 re5 nil t)
12908 (goto-char (match-beginning 1))
12909 (goto-char pos)
12910 (error "No match")))))
12912 ;; Normal string-search
12913 (goto-char (point-min))
12914 (if (search-forward s nil t)
12915 (goto-char (match-beginning 0))
12916 (error "No match"))))
12917 (and (org-mode-p) (org-show-context 'link-search))))
12919 (defun org-search-not-self (group &rest args)
12920 "Execute `re-search-forward', but only accept matches that do not
12921 enclose the position of `org-open-link-marker'."
12922 (let ((m org-open-link-marker))
12923 (catch 'exit
12924 (while (apply 're-search-forward args)
12925 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12926 (goto-char (match-end group))
12927 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12928 (> (match-beginning 0) (marker-position m))
12929 (< (match-end 0) (marker-position m)))
12930 (save-match-data
12931 (or (not (org-in-regexp
12932 org-bracket-link-analytic-regexp 1))
12933 (not (match-end 4)) ; no description
12934 (and (<= (match-beginning 4) (point))
12935 (>= (match-end 4) (point))))))
12936 (throw 'exit (point))))))))
12938 (defun org-get-buffer-for-internal-link (buffer)
12939 "Return a buffer to be used for displaying the link target of internal links."
12940 (cond
12941 ((not org-display-internal-link-with-indirect-buffer)
12942 buffer)
12943 ((string-match "(Clone)$" (buffer-name buffer))
12944 (message "Buffer is already a clone, not making another one")
12945 ;; we also do not modify visibility in this case
12946 buffer)
12947 (t ; make a new indirect buffer for displaying the link
12948 (let* ((bn (buffer-name buffer))
12949 (ibn (concat bn "(Clone)"))
12950 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12951 (with-current-buffer ib (org-overview))
12952 ib))))
12954 (defun org-do-occur (regexp &optional cleanup)
12955 "Call the Emacs command `occur'.
12956 If CLEANUP is non-nil, remove the printout of the regular expression
12957 in the *Occur* buffer. This is useful if the regex is long and not useful
12958 to read."
12959 (occur regexp)
12960 (when cleanup
12961 (let ((cwin (selected-window)) win beg end)
12962 (when (setq win (get-buffer-window "*Occur*"))
12963 (select-window win))
12964 (goto-char (point-min))
12965 (when (re-search-forward "match[a-z]+" nil t)
12966 (setq beg (match-end 0))
12967 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12968 (setq end (1- (match-beginning 0)))))
12969 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12970 (goto-char (point-min))
12971 (select-window cwin))))
12973 ;;; The mark ring for links jumps
12975 (defvar org-mark-ring nil
12976 "Mark ring for positions before jumps in Org-mode.")
12977 (defvar org-mark-ring-last-goto nil
12978 "Last position in the mark ring used to go back.")
12979 ;; Fill and close the ring
12980 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12981 (loop for i from 1 to org-mark-ring-length do
12982 (push (make-marker) org-mark-ring))
12983 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12984 org-mark-ring)
12986 (defun org-mark-ring-push (&optional pos buffer)
12987 "Put the current position or POS into the mark ring and rotate it."
12988 (interactive)
12989 (setq pos (or pos (point)))
12990 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12991 (move-marker (car org-mark-ring)
12992 (or pos (point))
12993 (or buffer (current-buffer)))
12994 (message "%s"
12995 (substitute-command-keys
12996 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12998 (defun org-mark-ring-goto (&optional n)
12999 "Jump to the previous position in the mark ring.
13000 With prefix arg N, jump back that many stored positions. When
13001 called several times in succession, walk through the entire ring.
13002 Org-mode commands jumping to a different position in the current file,
13003 or to another Org-mode file, automatically push the old position
13004 onto the ring."
13005 (interactive "p")
13006 (let (p m)
13007 (if (eq last-command this-command)
13008 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13009 (setq p org-mark-ring))
13010 (setq org-mark-ring-last-goto p)
13011 (setq m (car p))
13012 (switch-to-buffer (marker-buffer m))
13013 (goto-char m)
13014 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13016 (defun org-remove-angle-brackets (s)
13017 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13018 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13020 (defun org-add-angle-brackets (s)
13021 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13022 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13025 ;;; Following specific links
13027 (defun org-follow-timestamp-link ()
13028 (cond
13029 ((org-at-date-range-p t)
13030 (let ((org-agenda-start-on-weekday)
13031 (t1 (match-string 1))
13032 (t2 (match-string 2)))
13033 (setq t1 (time-to-days (org-time-string-to-time t1))
13034 t2 (time-to-days (org-time-string-to-time t2)))
13035 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13036 ((org-at-timestamp-p t)
13037 (org-agenda-list nil (time-to-days (org-time-string-to-time
13038 (substring (match-string 1) 0 10)))
13040 (t (error "This should not happen"))))
13043 (defun org-follow-bbdb-link (name)
13044 "Follow a BBDB link to NAME."
13045 (require 'bbdb)
13046 (let ((inhibit-redisplay (not debug-on-error))
13047 (bbdb-electric-p nil))
13048 (catch 'exit
13049 ;; Exact match on name
13050 (bbdb-name (concat "\\`" name "\\'") nil)
13051 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13052 ;; Exact match on name
13053 (bbdb-company (concat "\\`" name "\\'") nil)
13054 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13055 ;; Partial match on name
13056 (bbdb-name name nil)
13057 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13058 ;; Partial match on company
13059 (bbdb-company name nil)
13060 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13061 ;; General match including network address and notes
13062 (bbdb name nil)
13063 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13064 (delete-window (get-buffer-window "*BBDB*"))
13065 (error "No matching BBDB record")))))
13067 (defun org-follow-info-link (name)
13068 "Follow an info file & node link to NAME."
13069 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13070 (string-match "\\(.*\\)" name))
13071 (progn
13072 (require 'info)
13073 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13074 (Info-find-node (match-string 1 name) (match-string 2 name))
13075 (Info-find-node (match-string 1 name) "Top")))
13076 (message "Could not open: %s" name)))
13078 (defun org-follow-gnus-link (&optional group article)
13079 "Follow a Gnus link to GROUP and ARTICLE."
13080 (require 'gnus)
13081 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13082 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13083 (cond ((and group article)
13084 (gnus-group-read-group 1 nil group)
13085 (gnus-summary-goto-article (string-to-number article) nil t))
13086 (group (gnus-group-jump-to-group group))))
13088 (defun org-follow-vm-link (&optional folder article readonly)
13089 "Follow a VM link to FOLDER and ARTICLE."
13090 (require 'vm)
13091 (setq article (org-add-angle-brackets article))
13092 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13093 ;; ange-ftp or efs or tramp access
13094 (let ((user (or (match-string 1 folder) (user-login-name)))
13095 (host (match-string 2 folder))
13096 (file (match-string 3 folder)))
13097 (cond
13098 ((featurep 'tramp)
13099 ;; use tramp to access the file
13100 (if (featurep 'xemacs)
13101 (setq folder (format "[%s@%s]%s" user host file))
13102 (setq folder (format "/%s@%s:%s" user host file))))
13104 ;; use ange-ftp or efs
13105 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13106 (setq folder (format "/%s@%s:%s" user host file))))))
13107 (when folder
13108 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13109 (sit-for 0.1)
13110 (when article
13111 (vm-select-folder-buffer)
13112 (widen)
13113 (let ((case-fold-search t))
13114 (goto-char (point-min))
13115 (if (not (re-search-forward
13116 (concat "^" "message-id: *" (regexp-quote article))))
13117 (error "Could not find the specified message in this folder"))
13118 (vm-isearch-update)
13119 (vm-isearch-narrow)
13120 (vm-beginning-of-message)
13121 (vm-summarize)))))
13123 (defun org-follow-wl-link (folder article)
13124 "Follow a Wanderlust link to FOLDER and ARTICLE."
13125 (if (and (string= folder "%")
13126 article
13127 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13128 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13129 ;; Thus, we recompose folder and article ids.
13130 (setq folder (format "%s#%s" folder (match-string 1 article))
13131 article (match-string 3 article)))
13132 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13133 (error "No such folder: %s" folder))
13134 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13135 (and article
13136 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13137 (wl-summary-redisplay)))
13139 (defun org-follow-rmail-link (folder article)
13140 "Follow an RMAIL link to FOLDER and ARTICLE."
13141 (setq article (org-add-angle-brackets article))
13142 (let (message-number)
13143 (save-excursion
13144 (save-window-excursion
13145 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13146 (setq message-number
13147 (save-restriction
13148 (widen)
13149 (goto-char (point-max))
13150 (if (re-search-backward
13151 (concat "^Message-ID:\\s-+" (regexp-quote
13152 (or article "")))
13153 nil t)
13154 (rmail-what-message))))))
13155 (if message-number
13156 (progn
13157 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13158 (rmail-show-message message-number)
13159 message-number)
13160 (error "Message not found"))))
13162 ;;; mh-e integration based on planner-mode
13163 (defun org-mhe-get-message-real-folder ()
13164 "Return the name of the current message real folder, so if you use
13165 sequences, it will now work."
13166 (save-excursion
13167 (let* ((folder
13168 (if (equal major-mode 'mh-folder-mode)
13169 mh-current-folder
13170 ;; Refer to the show buffer
13171 mh-show-folder-buffer))
13172 (end-index
13173 (if (boundp 'mh-index-folder)
13174 (min (length mh-index-folder) (length folder))))
13176 ;; a simple test on mh-index-data does not work, because
13177 ;; mh-index-data is always nil in a show buffer.
13178 (if (and (boundp 'mh-index-folder)
13179 (string= mh-index-folder (substring folder 0 end-index)))
13180 (if (equal major-mode 'mh-show-mode)
13181 (save-window-excursion
13182 (let (pop-up-frames)
13183 (when (buffer-live-p (get-buffer folder))
13184 (progn
13185 (pop-to-buffer folder)
13186 (org-mhe-get-message-folder-from-index)
13189 (org-mhe-get-message-folder-from-index)
13191 folder
13195 (defun org-mhe-get-message-folder-from-index ()
13196 "Returns the name of the message folder in a index folder buffer."
13197 (save-excursion
13198 (mh-index-previous-folder)
13199 (re-search-forward "^\\(+.*\\)$" nil t)
13200 (message "%s" (match-string 1))))
13202 (defun org-mhe-get-message-folder ()
13203 "Return the name of the current message folder. Be careful if you
13204 use sequences."
13205 (save-excursion
13206 (if (equal major-mode 'mh-folder-mode)
13207 mh-current-folder
13208 ;; Refer to the show buffer
13209 mh-show-folder-buffer)))
13211 (defun org-mhe-get-message-num ()
13212 "Return the number of the current message. Be careful if you
13213 use sequences."
13214 (save-excursion
13215 (if (equal major-mode 'mh-folder-mode)
13216 (mh-get-msg-num nil)
13217 ;; Refer to the show buffer
13218 (mh-show-buffer-message-number))))
13220 (defun org-mhe-get-header (header)
13221 "Return a header of the message in folder mode. This will create a
13222 show buffer for the corresponding message. If you have a more clever
13223 idea..."
13224 (let* ((folder (org-mhe-get-message-folder))
13225 (num (org-mhe-get-message-num))
13226 (buffer (get-buffer-create (concat "show-" folder)))
13227 (header-field))
13228 (with-current-buffer buffer
13229 (mh-display-msg num folder)
13230 (if (equal major-mode 'mh-folder-mode)
13231 (mh-header-display)
13232 (mh-show-header-display))
13233 (set-buffer buffer)
13234 (setq header-field (mh-get-header-field header))
13235 (if (equal major-mode 'mh-folder-mode)
13236 (mh-show)
13237 (mh-show-show))
13238 header-field)))
13240 (defun org-follow-mhe-link (folder article)
13241 "Follow an MHE link to FOLDER and ARTICLE.
13242 If ARTICLE is nil FOLDER is shown. If the configuration variable
13243 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13244 ARTICLE is searched in all folders. Indexed searches (swish++,
13245 namazu, and others supported by MH-E) will always search in all
13246 folders."
13247 (require 'mh-e)
13248 (require 'mh-search)
13249 (require 'mh-utils)
13250 (mh-find-path)
13251 (if (not article)
13252 (mh-visit-folder (mh-normalize-folder-name folder))
13253 (setq article (org-add-angle-brackets article))
13254 (mh-search-choose)
13255 (if (equal mh-searcher 'pick)
13256 (progn
13257 (mh-search folder (list "--message-id" article))
13258 (when (and org-mhe-search-all-folders
13259 (not (org-mhe-get-message-real-folder)))
13260 (kill-this-buffer)
13261 (mh-search "+" (list "--message-id" article))))
13262 (mh-search "+" article))
13263 (if (org-mhe-get-message-real-folder)
13264 (mh-show-msg 1)
13265 (kill-this-buffer)
13266 (error "Message not found"))))
13268 ;;; BibTeX links
13270 ;; Use the custom search meachnism to construct and use search strings for
13271 ;; file links to BibTeX database entries.
13273 (defun org-create-file-search-in-bibtex ()
13274 "Create the search string and description for a BibTeX database entry."
13275 (when (eq major-mode 'bibtex-mode)
13276 ;; yes, we want to construct this search string.
13277 ;; Make a good description for this entry, using names, year and the title
13278 ;; Put it into the `description' variable which is dynamically scoped.
13279 (let ((bibtex-autokey-names 1)
13280 (bibtex-autokey-names-stretch 1)
13281 (bibtex-autokey-name-case-convert-function 'identity)
13282 (bibtex-autokey-name-separator " & ")
13283 (bibtex-autokey-additional-names " et al.")
13284 (bibtex-autokey-year-length 4)
13285 (bibtex-autokey-name-year-separator " ")
13286 (bibtex-autokey-titlewords 3)
13287 (bibtex-autokey-titleword-separator " ")
13288 (bibtex-autokey-titleword-case-convert-function 'identity)
13289 (bibtex-autokey-titleword-length 'infty)
13290 (bibtex-autokey-year-title-separator ": "))
13291 (setq description (bibtex-generate-autokey)))
13292 ;; Now parse the entry, get the key and return it.
13293 (save-excursion
13294 (bibtex-beginning-of-entry)
13295 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13297 (defun org-execute-file-search-in-bibtex (s)
13298 "Find the link search string S as a key for a database entry."
13299 (when (eq major-mode 'bibtex-mode)
13300 ;; Yes, we want to do the search in this file.
13301 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13302 (goto-char (point-min))
13303 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13304 (regexp-quote s) "[ \t\n]*,") nil t)
13305 (goto-char (match-beginning 0)))
13306 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13307 ;; Use double prefix to indicate that any web link should be browsed
13308 (let ((b (current-buffer)) (p (point)))
13309 ;; Restore the window configuration because we just use the web link
13310 (set-window-configuration org-window-config-before-follow-link)
13311 (save-excursion (set-buffer b) (goto-char p)
13312 (bibtex-url)))
13313 (recenter 0)) ; Move entry start to beginning of window
13314 ;; return t to indicate that the search is done.
13317 ;; Finally add the functions to the right hooks.
13318 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13319 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13321 ;; end of Bibtex link setup
13323 ;;; Following file links
13325 (defun org-open-file (path &optional in-emacs line search)
13326 "Open the file at PATH.
13327 First, this expands any special file name abbreviations. Then the
13328 configuration variable `org-file-apps' is checked if it contains an
13329 entry for this file type, and if yes, the corresponding command is launched.
13330 If no application is found, Emacs simply visits the file.
13331 With optional argument IN-EMACS, Emacs will visit the file.
13332 Optional LINE specifies a line to go to, optional SEARCH a string to
13333 search for. If LINE or SEARCH is given, the file will always be
13334 opened in Emacs.
13335 If the file does not exist, an error is thrown."
13336 (setq in-emacs (or in-emacs line search))
13337 (let* ((file (if (equal path "")
13338 buffer-file-name
13339 (substitute-in-file-name (expand-file-name path))))
13340 (apps (append org-file-apps (org-default-apps)))
13341 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13342 (dirp (if remp nil (file-directory-p file)))
13343 (dfile (downcase file))
13344 (old-buffer (current-buffer))
13345 (old-pos (point))
13346 (old-mode major-mode)
13347 ext cmd)
13348 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13349 (setq ext (match-string 1 dfile))
13350 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13351 (setq ext (match-string 1 dfile))))
13352 (if in-emacs
13353 (setq cmd 'emacs)
13354 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13355 (and dirp (cdr (assoc 'directory apps)))
13356 (cdr (assoc ext apps))
13357 (cdr (assoc t apps)))))
13358 (when (eq cmd 'mailcap)
13359 (require 'mailcap)
13360 (mailcap-parse-mailcaps)
13361 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13362 (command (mailcap-mime-info mime-type)))
13363 (if (stringp command)
13364 (setq cmd command)
13365 (setq cmd 'emacs))))
13366 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13367 (not (file-exists-p file))
13368 (not org-open-non-existing-files))
13369 (error "No such file: %s" file))
13370 (cond
13371 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13372 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13373 (while (string-match "['\"]%s['\"]" cmd)
13374 (setq cmd (replace-match "%s" t t cmd)))
13375 (while (string-match "%s" cmd)
13376 (setq cmd (replace-match
13377 (save-match-data (shell-quote-argument file))
13378 t t cmd)))
13379 (save-window-excursion
13380 (start-process-shell-command cmd nil cmd)))
13381 ((or (stringp cmd)
13382 (eq cmd 'emacs))
13383 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13384 (widen)
13385 (if line (goto-line line)
13386 (if search (org-link-search search))))
13387 ((consp cmd)
13388 (eval cmd))
13389 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13390 (and (org-mode-p) (eq old-mode 'org-mode)
13391 (or (not (equal old-buffer (current-buffer)))
13392 (not (equal old-pos (point))))
13393 (org-mark-ring-push old-pos old-buffer))))
13395 (defun org-default-apps ()
13396 "Return the default applications for this operating system."
13397 (cond
13398 ((eq system-type 'darwin)
13399 org-file-apps-defaults-macosx)
13400 ((eq system-type 'windows-nt)
13401 org-file-apps-defaults-windowsnt)
13402 (t org-file-apps-defaults-gnu)))
13404 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13405 (defun org-file-remote-p (file)
13406 "Test whether FILE specifies a location on a remote system.
13407 Return non-nil if the location is indeed remote.
13409 For example, the filename \"/user@host:/foo\" specifies a location
13410 on the system \"/user@host:\"."
13411 (cond ((fboundp 'file-remote-p)
13412 (file-remote-p file))
13413 ((fboundp 'tramp-handle-file-remote-p)
13414 (tramp-handle-file-remote-p file))
13415 ((and (boundp 'ange-ftp-name-format)
13416 (string-match (car ange-ftp-name-format) file))
13418 (t nil)))
13421 ;;;; Hooks for remember.el, and refiling
13423 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13424 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13426 ;;;###autoload
13427 (defun org-remember-insinuate ()
13428 "Setup remember.el for use wiht Org-mode."
13429 (require 'remember)
13430 (setq remember-annotation-functions '(org-remember-annotation))
13431 (setq remember-handler-functions '(org-remember-handler))
13432 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13434 ;;;###autoload
13435 (defun org-remember-annotation ()
13436 "Return a link to the current location as an annotation for remember.el.
13437 If you are using Org-mode files as target for data storage with
13438 remember.el, then the annotations should include a link compatible with the
13439 conventions in Org-mode. This function returns such a link."
13440 (org-store-link nil))
13442 (defconst org-remember-help
13443 "Select a destination location for the note.
13444 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13445 RET on headline -> Store as sublevel entry to current headline
13446 RET at beg-of-buf -> Append to file as level 2 headline
13447 <left>/<right> -> before/after current headline, same headings level")
13449 (defvar org-remember-previous-location nil)
13450 (defvar org-force-remember-template-char) ;; dynamically scoped
13452 (defun org-select-remember-template (&optional use-char)
13453 (when org-remember-templates
13454 (let* ((templates (mapcar (lambda (x)
13455 (if (stringp (car x))
13456 (append (list (nth 1 x) (car x)) (cddr x))
13457 (append (list (car x) "") (cdr x))))
13458 org-remember-templates))
13459 (char (or use-char
13460 (cond
13461 ((= (length templates) 1)
13462 (caar templates))
13463 ((and (boundp 'org-force-remember-template-char)
13464 org-force-remember-template-char)
13465 (if (stringp org-force-remember-template-char)
13466 (string-to-char org-force-remember-template-char)
13467 org-force-remember-template-char))
13469 (message "Select template: %s"
13470 (mapconcat
13471 (lambda (x)
13472 (cond
13473 ((not (string-match "\\S-" (nth 1 x)))
13474 (format "[%c]" (car x)))
13475 ((equal (downcase (car x))
13476 (downcase (aref (nth 1 x) 0)))
13477 (format "[%c]%s" (car x)
13478 (substring (nth 1 x) 1)))
13479 (t (format "[%c]%s" (car x) (nth 1 x)))))
13480 templates " "))
13481 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13482 (when (equal char0 ?\C-g)
13483 (jump-to-register remember-register)
13484 (kill-buffer remember-buffer))
13485 char0))))))
13486 (cddr (assoc char templates)))))
13488 (defvar x-last-selected-text)
13489 (defvar x-last-selected-text-primary)
13491 ;;;###autoload
13492 (defun org-remember-apply-template (&optional use-char skip-interactive)
13493 "Initialize *remember* buffer with template, invoke `org-mode'.
13494 This function should be placed into `remember-mode-hook' and in fact requires
13495 to be run from that hook to function properly."
13496 (if org-remember-templates
13497 (let* ((entry (org-select-remember-template use-char))
13498 (tpl (car entry))
13499 (plist-p (if org-store-link-plist t nil))
13500 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13501 (string-match "\\S-" (nth 1 entry)))
13502 (nth 1 entry)
13503 org-default-notes-file))
13504 (headline (nth 2 entry))
13505 (v-c (or (and (eq window-system 'x)
13506 (fboundp 'x-cut-buffer-or-selection-value)
13507 (x-cut-buffer-or-selection-value))
13508 (org-bound-and-true-p x-last-selected-text)
13509 (org-bound-and-true-p x-last-selected-text-primary)
13510 (and (> (length kill-ring) 0) (current-kill 0))))
13511 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13512 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13513 (v-u (concat "[" (substring v-t 1 -1) "]"))
13514 (v-U (concat "[" (substring v-T 1 -1) "]"))
13515 ;; `initial' and `annotation' are bound in `remember'
13516 (v-i (if (boundp 'initial) initial))
13517 (v-a (if (and (boundp 'annotation) annotation)
13518 (if (equal annotation "[[]]") "" annotation)
13519 ""))
13520 (v-A (if (and v-a
13521 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13522 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13523 v-a))
13524 (v-n user-full-name)
13525 (org-startup-folded nil)
13526 org-time-was-given org-end-time-was-given x
13527 prompt completions char time pos default histvar)
13528 (setq org-store-link-plist
13529 (append (list :annotation v-a :initial v-i)
13530 org-store-link-plist))
13531 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13532 (erase-buffer)
13533 (insert (substitute-command-keys
13534 (format
13535 "## Filing location: Select interactively, default, or last used:
13536 ## %s to select file and header location interactively.
13537 ## %s \"%s\" -> \"* %s\"
13538 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13539 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13540 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13541 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13542 (abbreviate-file-name (or file org-default-notes-file))
13543 (or headline "")
13544 (or (car org-remember-previous-location) "???")
13545 (or (cdr org-remember-previous-location) "???"))))
13546 (insert tpl) (goto-char (point-min))
13547 ;; Simple %-escapes
13548 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13549 (when (and initial (equal (match-string 0) "%i"))
13550 (save-match-data
13551 (let* ((lead (buffer-substring
13552 (point-at-bol) (match-beginning 0))))
13553 (setq v-i (mapconcat 'identity
13554 (org-split-string initial "\n")
13555 (concat "\n" lead))))))
13556 (replace-match
13557 (or (eval (intern (concat "v-" (match-string 1)))) "")
13558 t t))
13560 ;; %[] Insert contents of a file.
13561 (goto-char (point-min))
13562 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13563 (let ((start (match-beginning 0))
13564 (end (match-end 0))
13565 (filename (expand-file-name (match-string 1))))
13566 (goto-char start)
13567 (delete-region start end)
13568 (condition-case error
13569 (insert-file-contents filename)
13570 (error (insert (format "%%![Couldn't insert %s: %s]"
13571 filename error))))))
13572 ;; %() embedded elisp
13573 (goto-char (point-min))
13574 (while (re-search-forward "%\\((.+)\\)" nil t)
13575 (goto-char (match-beginning 0))
13576 (let ((template-start (point)))
13577 (forward-char 1)
13578 (let ((result
13579 (condition-case error
13580 (eval (read (current-buffer)))
13581 (error (format "%%![Error: %s]" error)))))
13582 (delete-region template-start (point))
13583 (insert result))))
13585 ;; From the property list
13586 (when plist-p
13587 (goto-char (point-min))
13588 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13589 (and (setq x (or (plist-get org-store-link-plist
13590 (intern (match-string 1))) ""))
13591 (replace-match x t t))))
13593 ;; Turn on org-mode in the remember buffer, set local variables
13594 (org-mode)
13595 (org-set-local 'org-finish-function 'org-remember-finalize)
13596 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13597 (org-set-local 'org-default-notes-file file))
13598 (if (and headline (stringp headline) (string-match "\\S-" headline))
13599 (org-set-local 'org-remember-default-headline headline))
13600 ;; Interactive template entries
13601 (goto-char (point-min))
13602 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13603 (setq char (if (match-end 3) (match-string 3))
13604 prompt (if (match-end 2) (match-string 2)))
13605 (goto-char (match-beginning 0))
13606 (replace-match "")
13607 (setq completions nil default nil)
13608 (when prompt
13609 (setq completions (org-split-string prompt "|")
13610 prompt (pop completions)
13611 default (car completions)
13612 histvar (intern (concat
13613 "org-remember-template-prompt-history::"
13614 (or prompt "")))
13615 completions (mapcar 'list completions)))
13616 (cond
13617 ((member char '("G" "g"))
13618 (let* ((org-last-tags-completion-table
13619 (org-global-tags-completion-table
13620 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13621 (org-add-colon-after-tag-completion t)
13622 (ins (completing-read
13623 (if prompt (concat prompt ": ") "Tags: ")
13624 'org-tags-completion-function nil nil nil
13625 'org-tags-history)))
13626 (setq ins (mapconcat 'identity
13627 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13628 ":"))
13629 (when (string-match "\\S-" ins)
13630 (or (equal (char-before) ?:) (insert ":"))
13631 (insert ins)
13632 (or (equal (char-after) ?:) (insert ":")))))
13633 (char
13634 (setq org-time-was-given (equal (upcase char) char))
13635 (setq time (org-read-date (equal (upcase char) "U") t nil
13636 prompt))
13637 (org-insert-time-stamp time org-time-was-given
13638 (member char '("u" "U"))
13639 nil nil (list org-end-time-was-given)))
13641 (insert (org-completing-read
13642 (concat (if prompt prompt "Enter string")
13643 (if default (concat " [" default "]"))
13644 ": ")
13645 completions nil nil nil histvar default)))))
13646 (goto-char (point-min))
13647 (if (re-search-forward "%\\?" nil t)
13648 (replace-match "")
13649 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13650 (org-mode)
13651 (org-set-local 'org-finish-function 'org-remember-finalize))
13652 (when (save-excursion
13653 (goto-char (point-min))
13654 (re-search-forward "%!" nil t))
13655 (replace-match "")
13656 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13658 (defun org-remember-finish-immediately ()
13659 "File remember note immediately.
13660 This should be run in `post-command-hook' and will remove itself
13661 from that hook."
13662 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13663 (when org-finish-function
13664 (funcall org-finish-function)))
13666 (defvar org-clock-marker) ; Defined below
13667 (defun org-remember-finalize ()
13668 "Finalize the remember process."
13669 (unless (fboundp 'remember-finalize)
13670 (defalias 'remember-finalize 'remember-buffer))
13671 (when (and org-clock-marker
13672 (equal (marker-buffer org-clock-marker) (current-buffer)))
13673 ;; FIXME: test this, this is w/o notetaking!
13674 (let (org-log-note-clock-out) (org-clock-out)))
13675 (when buffer-file-name
13676 (save-buffer)
13677 (setq buffer-file-name nil))
13678 (remember-finalize))
13680 ;;;###autoload
13681 (defun org-remember (&optional goto org-force-remember-template-char)
13682 "Call `remember'. If this is already a remember buffer, re-apply template.
13683 If there is an active region, make sure remember uses it as initial content
13684 of the remember buffer.
13686 When called interactively with a `C-u' prefix argument GOTO, don't remember
13687 anything, just go to the file/headline where the selected template usually
13688 stores its notes. With a double prefix arg `C-u C-u', go to the last
13689 note stored by remember.
13691 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13692 associated with a template in `org-remember-templates'."
13693 (interactive "P")
13694 (cond
13695 ((equal goto '(4)) (org-go-to-remember-target))
13696 ((equal goto '(16)) (org-remember-goto-last-stored))
13698 (if (memq org-finish-function '(remember-buffer remember-finalize))
13699 (progn
13700 (when (< (length org-remember-templates) 2)
13701 (error "No other template available"))
13702 (erase-buffer)
13703 (let ((annotation (plist-get org-store-link-plist :annotation))
13704 (initial (plist-get org-store-link-plist :initial)))
13705 (org-remember-apply-template))
13706 (message "Press C-c C-c to remember data"))
13707 (if (org-region-active-p)
13708 (remember (buffer-substring (point) (mark)))
13709 (call-interactively 'remember))))))
13711 (defun org-remember-goto-last-stored ()
13712 "Go to the location where the last remember note was stored."
13713 (interactive)
13714 (bookmark-jump "org-remember-last-stored")
13715 (message "This is the last note stored by remember"))
13717 (defun org-go-to-remember-target (&optional template-key)
13718 "Go to the target location of a remember template.
13719 The user is queried for the template."
13720 (interactive)
13721 (let* ((entry (org-select-remember-template template-key))
13722 (file (nth 1 entry))
13723 (heading (nth 2 entry))
13724 visiting)
13725 (unless (and file (stringp file) (string-match "\\S-" file))
13726 (setq file org-default-notes-file))
13727 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13728 (setq heading org-remember-default-headline))
13729 (setq visiting (org-find-base-buffer-visiting file))
13730 (if (not visiting) (find-file-noselect file))
13731 (switch-to-buffer (or visiting (get-file-buffer file)))
13732 (widen)
13733 (goto-char (point-min))
13734 (if (re-search-forward
13735 (concat "^\\*+[ \t]+" (regexp-quote heading)
13736 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13737 nil t)
13738 (goto-char (match-beginning 0))
13739 (error "Target headline not found: %s" heading))))
13741 (defvar org-note-abort nil) ; dynamically scoped
13743 ;;;###autoload
13744 (defun org-remember-handler ()
13745 "Store stuff from remember.el into an org file.
13746 First prompts for an org file. If the user just presses return, the value
13747 of `org-default-notes-file' is used.
13748 Then the command offers the headings tree of the selected file in order to
13749 file the text at a specific location.
13750 You can either immediately press RET to get the note appended to the
13751 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13752 find a better place. Then press RET or <left> or <right> in insert the note.
13754 Key Cursor position Note gets inserted
13755 -----------------------------------------------------------------------------
13756 RET buffer-start as level 1 heading at end of file
13757 RET on headline as sublevel of the heading at cursor
13758 RET no heading at cursor position, level taken from context.
13759 Or use prefix arg to specify level manually.
13760 <left> on headline as same level, before current heading
13761 <right> on headline as same level, after current heading
13763 So the fastest way to store the note is to press RET RET to append it to
13764 the default file. This way your current train of thought is not
13765 interrupted, in accordance with the principles of remember.el.
13766 You can also get the fast execution without prompting by using
13767 C-u C-c C-c to exit the remember buffer. See also the variable
13768 `org-remember-store-without-prompt'.
13770 Before being stored away, the function ensures that the text has a
13771 headline, i.e. a first line that starts with a \"*\". If not, a headline
13772 is constructed from the current date and some additional data.
13774 If the variable `org-adapt-indentation' is non-nil, the entire text is
13775 also indented so that it starts in the same column as the headline
13776 \(i.e. after the stars).
13778 See also the variable `org-reverse-note-order'."
13779 (goto-char (point-min))
13780 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13781 (replace-match ""))
13782 (goto-char (point-max))
13783 (beginning-of-line 1)
13784 (while (looking-at "[ \t]*$\\|##.*")
13785 (delete-region (1- (point)) (point-max))
13786 (beginning-of-line 1))
13787 (catch 'quit
13788 (if org-note-abort (throw 'quit nil))
13789 (let* ((txt (buffer-substring (point-min) (point-max)))
13790 (fastp (org-xor (equal current-prefix-arg '(4))
13791 org-remember-store-without-prompt))
13792 (file (cond
13793 (fastp org-default-notes-file)
13794 ((and (eq org-remember-interactive-interface 'refile)
13795 org-refile-targets)
13796 org-default-notes-file)
13797 ((not (and (equal current-prefix-arg '(16))
13798 org-remember-previous-location))
13799 (org-get-org-file))))
13800 (heading org-remember-default-headline)
13801 (visiting (and file (org-find-base-buffer-visiting file)))
13802 (org-startup-folded nil)
13803 (org-startup-align-all-tables nil)
13804 (org-goto-start-pos 1)
13805 spos exitcmd level indent reversed)
13806 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13807 (setq file (car org-remember-previous-location)
13808 heading (cdr org-remember-previous-location)
13809 fastp t))
13810 (setq current-prefix-arg nil)
13811 (if (string-match "[ \t\n]+\\'" txt)
13812 (setq txt (replace-match "" t t txt)))
13813 ;; Modify text so that it becomes a nice subtree which can be inserted
13814 ;; into an org tree.
13815 (let* ((lines (split-string txt "\n"))
13816 first)
13817 (setq first (car lines) lines (cdr lines))
13818 (if (string-match "^\\*+ " first)
13819 ;; Is already a headline
13820 (setq indent nil)
13821 ;; We need to add a headline: Use time and first buffer line
13822 (setq lines (cons first lines)
13823 first (concat "* " (current-time-string)
13824 " (" (remember-buffer-desc) ")")
13825 indent " "))
13826 (if (and org-adapt-indentation indent)
13827 (setq lines (mapcar
13828 (lambda (x)
13829 (if (string-match "\\S-" x)
13830 (concat indent x) x))
13831 lines)))
13832 (setq txt (concat first "\n"
13833 (mapconcat 'identity lines "\n"))))
13834 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13835 (setq txt (replace-match "\n\n" t t txt))
13836 (if (string-match "[ \t\n]*\\'" txt)
13837 (setq txt (replace-match "\n" t t txt))))
13838 ;; Put the modified text back into the remember buffer, for refile.
13839 (erase-buffer)
13840 (insert txt)
13841 (goto-char (point-min))
13842 (when (and (eq org-remember-interactive-interface 'refile)
13843 (not fastp))
13844 (org-refile nil (or visiting (find-file-noselect file)))
13845 (throw 'quit t))
13846 ;; Find the file
13847 (if (not visiting) (find-file-noselect file))
13848 (with-current-buffer (or visiting (get-file-buffer file))
13849 (unless (org-mode-p)
13850 (error "Target files for remember notes must be in Org-mode"))
13851 (save-excursion
13852 (save-restriction
13853 (widen)
13854 (and (goto-char (point-min))
13855 (not (re-search-forward "^\\* " nil t))
13856 (insert "\n* " (or heading "Notes") "\n"))
13857 (setq reversed (org-notes-order-reversed-p))
13859 ;; Find the default location
13860 (when (and heading (stringp heading) (string-match "\\S-" heading))
13861 (goto-char (point-min))
13862 (if (re-search-forward
13863 (concat "^\\*+[ \t]+" (regexp-quote heading)
13864 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13865 nil t)
13866 (setq org-goto-start-pos (match-beginning 0))
13867 (when fastp
13868 (goto-char (point-max))
13869 (unless (bolp) (newline))
13870 (insert "* " heading "\n")
13871 (setq org-goto-start-pos (point-at-bol 0)))))
13873 ;; Ask the User for a location, using the appropriate interface
13874 (cond
13875 (fastp (setq spos org-goto-start-pos
13876 exitcmd 'return))
13877 ((eq org-remember-interactive-interface 'outline)
13878 (setq spos (org-get-location (current-buffer)
13879 org-remember-help)
13880 exitcmd (cdr spos)
13881 spos (car spos)))
13882 ((eq org-remember-interactive-interface 'outline-path-completion)
13883 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13884 (org-refile-use-outline-path t))
13885 (setq spos (org-refile-get-location "Heading: ")
13886 exitcmd 'return
13887 spos (nth 3 spos))))
13888 (t (error "this should not hapen")))
13889 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13890 ; not handle this note
13891 (goto-char spos)
13892 (cond ((org-on-heading-p t)
13893 (org-back-to-heading t)
13894 (setq level (funcall outline-level))
13895 (cond
13896 ((eq exitcmd 'return)
13897 ;; sublevel of current
13898 (setq org-remember-previous-location
13899 (cons (abbreviate-file-name file)
13900 (org-get-heading 'notags)))
13901 (if reversed
13902 (outline-next-heading)
13903 (org-end-of-subtree t)
13904 (if (not (bolp))
13905 (if (looking-at "[ \t]*\n")
13906 (beginning-of-line 2)
13907 (end-of-line 1)
13908 (insert "\n"))))
13909 (bookmark-set "org-remember-last-stored")
13910 (org-paste-subtree (org-get-legal-level level 1) txt))
13911 ((eq exitcmd 'left)
13912 ;; before current
13913 (bookmark-set "org-remember-last-stored")
13914 (org-paste-subtree level txt))
13915 ((eq exitcmd 'right)
13916 ;; after current
13917 (org-end-of-subtree t)
13918 (bookmark-set "org-remember-last-stored")
13919 (org-paste-subtree level txt))
13920 (t (error "This should not happen"))))
13922 ((and (bobp) (not reversed))
13923 ;; Put it at the end, one level below level 1
13924 (save-restriction
13925 (widen)
13926 (goto-char (point-max))
13927 (if (not (bolp)) (newline))
13928 (bookmark-set "org-remember-last-stored")
13929 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13931 ((and (bobp) reversed)
13932 ;; Put it at the start, as level 1
13933 (save-restriction
13934 (widen)
13935 (goto-char (point-min))
13936 (re-search-forward "^\\*+ " nil t)
13937 (beginning-of-line 1)
13938 (bookmark-set "org-remember-last-stored")
13939 (org-paste-subtree 1 txt)))
13941 ;; Put it right there, with automatic level determined by
13942 ;; org-paste-subtree or from prefix arg
13943 (bookmark-set "org-remember-last-stored")
13944 (org-paste-subtree
13945 (if (numberp current-prefix-arg) current-prefix-arg)
13946 txt)))
13947 (when remember-save-after-remembering
13948 (save-buffer)
13949 (if (not visiting) (kill-buffer (current-buffer)))))))))
13951 t) ;; return t to indicate that we took care of this note.
13953 (defun org-get-org-file ()
13954 "Read a filename, with default directory `org-directory'."
13955 (let ((default (or org-default-notes-file remember-data-file)))
13956 (read-file-name (format "File name [%s]: " default)
13957 (file-name-as-directory org-directory)
13958 default)))
13960 (defun org-notes-order-reversed-p ()
13961 "Check if the current file should receive notes in reversed order."
13962 (cond
13963 ((not org-reverse-note-order) nil)
13964 ((eq t org-reverse-note-order) t)
13965 ((not (listp org-reverse-note-order)) nil)
13966 (t (catch 'exit
13967 (let ((all org-reverse-note-order)
13968 entry)
13969 (while (setq entry (pop all))
13970 (if (string-match (car entry) buffer-file-name)
13971 (throw 'exit (cdr entry))))
13972 nil)))))
13974 ;;; Refiling
13976 (defvar org-refile-target-table nil
13977 "The list of refile targets, created by `org-refile'.")
13979 (defvar org-agenda-new-buffers nil
13980 "Buffers created to visit agenda files.")
13982 (defun org-get-refile-targets (&optional default-buffer)
13983 "Produce a table with refile targets."
13984 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13985 targets txt re files f desc descre)
13986 (with-current-buffer (or default-buffer (current-buffer))
13987 (while (setq entry (pop entries))
13988 (setq files (car entry) desc (cdr entry))
13989 (cond
13990 ((null files) (setq files (list (current-buffer))))
13991 ((eq files 'org-agenda-files)
13992 (setq files (org-agenda-files 'unrestricted)))
13993 ((and (symbolp files) (fboundp files))
13994 (setq files (funcall files)))
13995 ((and (symbolp files) (boundp files))
13996 (setq files (symbol-value files))))
13997 (if (stringp files) (setq files (list files)))
13998 (cond
13999 ((eq (car desc) :tag)
14000 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14001 ((eq (car desc) :todo)
14002 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14003 ((eq (car desc) :regexp)
14004 (setq descre (cdr desc)))
14005 ((eq (car desc) :level)
14006 (setq descre (concat "^\\*\\{" (number-to-string
14007 (if org-odd-levels-only
14008 (1- (* 2 (cdr desc)))
14009 (cdr desc)))
14010 "\\}[ \t]")))
14011 ((eq (car desc) :maxlevel)
14012 (setq descre (concat "^\\*\\{1," (number-to-string
14013 (if org-odd-levels-only
14014 (1- (* 2 (cdr desc)))
14015 (cdr desc)))
14016 "\\}[ \t]")))
14017 (t (error "Bad refiling target description %s" desc)))
14018 (while (setq f (pop files))
14019 (save-excursion
14020 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14021 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14022 (save-excursion
14023 (save-restriction
14024 (widen)
14025 (goto-char (point-min))
14026 (while (re-search-forward descre nil t)
14027 (goto-char (point-at-bol))
14028 (when (looking-at org-complex-heading-regexp)
14029 (setq txt (match-string 4)
14030 re (concat "^" (regexp-quote
14031 (buffer-substring (match-beginning 1)
14032 (match-end 4)))))
14033 (if (match-end 5) (setq re (concat re "[ \t]+"
14034 (regexp-quote
14035 (match-string 5)))))
14036 (setq re (concat re "[ \t]*$"))
14037 (when org-refile-use-outline-path
14038 (setq txt (mapconcat 'identity
14039 (append
14040 (if (eq org-refile-use-outline-path 'file)
14041 (list (file-name-nondirectory
14042 (buffer-file-name (buffer-base-buffer))))
14043 (if (eq org-refile-use-outline-path 'full-file-path)
14044 (list (buffer-file-name (buffer-base-buffer)))))
14045 (org-get-outline-path)
14046 (list txt))
14047 "/")))
14048 (push (list txt f re (point)) targets))
14049 (goto-char (point-at-eol))))))))
14050 (nreverse targets))))
14052 (defun org-get-outline-path ()
14053 "Return the outline path to the current entry, as a list."
14054 (let (rtn)
14055 (save-excursion
14056 (while (org-up-heading-safe)
14057 (when (looking-at org-complex-heading-regexp)
14058 (push (org-match-string-no-properties 4) rtn)))
14059 rtn)))
14061 (defvar org-refile-history nil
14062 "History for refiling operations.")
14064 (defun org-refile (&optional goto default-buffer)
14065 "Move the entry at point to another heading.
14066 The list of target headings is compiled using the information in
14067 `org-refile-targets', which see. This list is created upon first use, and
14068 you can update it by calling this command with a double prefix (`C-u C-u').
14069 FIXME: Can we find a better way of updating?
14071 At the target location, the entry is filed as a subitem of the target heading.
14072 Depending on `org-reverse-note-order', the new subitem will either be the
14073 first of the last subitem.
14075 With prefix arg GOTO, the command will only visit the target location,
14076 not actually move anything.
14077 With a double prefix `C-c C-c', go to the location where the last refiling
14078 operation has put the subtree.
14080 With a double prefix argument, the command can be used to jump to any
14081 heading in the current buffer."
14082 (interactive "P")
14083 (let* ((cbuf (current-buffer))
14084 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14085 pos it nbuf file re level reversed)
14086 (if (equal goto '(16))
14087 (org-refile-goto-last-stored)
14088 (when (setq it (org-refile-get-location
14089 (if goto "Goto: " "Refile to: ") default-buffer))
14090 (setq file (nth 1 it)
14091 re (nth 2 it)
14092 pos (nth 3 it))
14093 (setq nbuf (or (find-buffer-visiting file)
14094 (find-file-noselect file)))
14095 (if goto
14096 (progn
14097 (switch-to-buffer nbuf)
14098 (goto-char pos)
14099 (org-show-context 'org-goto))
14100 (org-copy-special)
14101 (save-excursion
14102 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14103 (find-file-noselect file))))
14104 (setq reversed (org-notes-order-reversed-p))
14105 (save-excursion
14106 (save-restriction
14107 (widen)
14108 (goto-char pos)
14109 (looking-at outline-regexp)
14110 (setq level (org-get-legal-level (funcall outline-level) 1))
14111 (goto-char
14112 (if reversed
14113 (outline-next-heading)
14114 (or (save-excursion (outline-get-next-sibling))
14115 (org-end-of-subtree t t)
14116 (point-max))))
14117 (bookmark-set "org-refile-last-stored")
14118 (org-paste-subtree level))))
14119 (org-cut-special)
14120 (message "Entry refiled to \"%s\"" (car it)))))))
14122 (defun org-refile-goto-last-stored ()
14123 "Go to the location where the last refile was stored."
14124 (interactive)
14125 (bookmark-jump "org-refile-last-stored")
14126 (message "This is the location of the last refile"))
14128 (defun org-refile-get-location (&optional prompt default-buffer)
14129 "Prompt the user for a refile location, using PROMPT."
14130 (let ((org-refile-targets org-refile-targets)
14131 (org-refile-use-outline-path org-refile-use-outline-path))
14132 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14133 (unless org-refile-target-table
14134 (error "No refile targets"))
14135 (let* ((cbuf (current-buffer))
14136 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14137 (fname (and filename (file-truename filename)))
14138 (tbl (mapcar
14139 (lambda (x)
14140 (if (not (equal fname (file-truename (nth 1 x))))
14141 (cons (concat (car x) " (" (file-name-nondirectory
14142 (nth 1 x)) ")")
14143 (cdr x))
14145 org-refile-target-table))
14146 (completion-ignore-case t))
14147 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14148 tbl)))
14150 ;;;; Dynamic blocks
14152 (defun org-find-dblock (name)
14153 "Find the first dynamic block with name NAME in the buffer.
14154 If not found, stay at current position and return nil."
14155 (let (pos)
14156 (save-excursion
14157 (goto-char (point-min))
14158 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14159 nil t)
14160 (match-beginning 0))))
14161 (if pos (goto-char pos))
14162 pos))
14164 (defconst org-dblock-start-re
14165 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14166 "Matches the startline of a dynamic block, with parameters.")
14168 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14169 "Matches the end of a dyhamic block.")
14171 (defun org-create-dblock (plist)
14172 "Create a dynamic block section, with parameters taken from PLIST.
14173 PLIST must containe a :name entry which is used as name of the block."
14174 (unless (bolp) (newline))
14175 (let ((name (plist-get plist :name)))
14176 (insert "#+BEGIN: " name)
14177 (while plist
14178 (if (eq (car plist) :name)
14179 (setq plist (cddr plist))
14180 (insert " " (prin1-to-string (pop plist)))))
14181 (insert "\n\n#+END:\n")
14182 (beginning-of-line -2)))
14184 (defun org-prepare-dblock ()
14185 "Prepare dynamic block for refresh.
14186 This empties the block, puts the cursor at the insert position and returns
14187 the property list including an extra property :name with the block name."
14188 (unless (looking-at org-dblock-start-re)
14189 (error "Not at a dynamic block"))
14190 (let* ((begdel (1+ (match-end 0)))
14191 (name (org-no-properties (match-string 1)))
14192 (params (append (list :name name)
14193 (read (concat "(" (match-string 3) ")")))))
14194 (unless (re-search-forward org-dblock-end-re nil t)
14195 (error "Dynamic block not terminated"))
14196 (delete-region begdel (match-beginning 0))
14197 (goto-char begdel)
14198 (open-line 1)
14199 params))
14201 (defun org-map-dblocks (&optional command)
14202 "Apply COMMAND to all dynamic blocks in the current buffer.
14203 If COMMAND is not given, use `org-update-dblock'."
14204 (let ((cmd (or command 'org-update-dblock))
14205 pos)
14206 (save-excursion
14207 (goto-char (point-min))
14208 (while (re-search-forward org-dblock-start-re nil t)
14209 (goto-char (setq pos (match-beginning 0)))
14210 (condition-case nil
14211 (funcall cmd)
14212 (error (message "Error during update of dynamic block")))
14213 (goto-char pos)
14214 (unless (re-search-forward org-dblock-end-re nil t)
14215 (error "Dynamic block not terminated"))))))
14217 (defun org-dblock-update (&optional arg)
14218 "User command for updating dynamic blocks.
14219 Update the dynamic block at point. With prefix ARG, update all dynamic
14220 blocks in the buffer."
14221 (interactive "P")
14222 (if arg
14223 (org-update-all-dblocks)
14224 (or (looking-at org-dblock-start-re)
14225 (org-beginning-of-dblock))
14226 (org-update-dblock)))
14228 (defun org-update-dblock ()
14229 "Update the dynamic block at point
14230 This means to empty the block, parse for parameters and then call
14231 the correct writing function."
14232 (save-window-excursion
14233 (let* ((pos (point))
14234 (line (org-current-line))
14235 (params (org-prepare-dblock))
14236 (name (plist-get params :name))
14237 (cmd (intern (concat "org-dblock-write:" name))))
14238 (message "Updating dynamic block `%s' at line %d..." name line)
14239 (funcall cmd params)
14240 (message "Updating dynamic block `%s' at line %d...done" name line)
14241 (goto-char pos))))
14243 (defun org-beginning-of-dblock ()
14244 "Find the beginning of the dynamic block at point.
14245 Error if there is no scuh block at point."
14246 (let ((pos (point))
14247 beg)
14248 (end-of-line 1)
14249 (if (and (re-search-backward org-dblock-start-re nil t)
14250 (setq beg (match-beginning 0))
14251 (re-search-forward org-dblock-end-re nil t)
14252 (> (match-end 0) pos))
14253 (goto-char beg)
14254 (goto-char pos)
14255 (error "Not in a dynamic block"))))
14257 (defun org-update-all-dblocks ()
14258 "Update all dynamic blocks in the buffer.
14259 This function can be used in a hook."
14260 (when (org-mode-p)
14261 (org-map-dblocks 'org-update-dblock)))
14264 ;;;; Completion
14266 (defconst org-additional-option-like-keywords
14267 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14268 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14269 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14271 (defun org-complete (&optional arg)
14272 "Perform completion on word at point.
14273 At the beginning of a headline, this completes TODO keywords as given in
14274 `org-todo-keywords'.
14275 If the current word is preceded by a backslash, completes the TeX symbols
14276 that are supported for HTML support.
14277 If the current word is preceded by \"#+\", completes special words for
14278 setting file options.
14279 In the line after \"#+STARTUP:, complete valid keywords.\"
14280 At all other locations, this simply calls the value of
14281 `org-completion-fallback-command'."
14282 (interactive "P")
14283 (org-without-partial-completion
14284 (catch 'exit
14285 (let* ((end (point))
14286 (beg1 (save-excursion
14287 (skip-chars-backward (org-re "[:alnum:]_@"))
14288 (point)))
14289 (beg (save-excursion
14290 (skip-chars-backward "a-zA-Z0-9_:$")
14291 (point)))
14292 (confirm (lambda (x) (stringp (car x))))
14293 (searchhead (equal (char-before beg) ?*))
14294 (tag (and (equal (char-before beg1) ?:)
14295 (equal (char-after (point-at-bol)) ?*)))
14296 (prop (and (equal (char-before beg1) ?:)
14297 (not (equal (char-after (point-at-bol)) ?*))))
14298 (texp (equal (char-before beg) ?\\))
14299 (link (equal (char-before beg) ?\[))
14300 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14301 beg)
14302 "#+"))
14303 (startup (string-match "^#\\+STARTUP:.*"
14304 (buffer-substring (point-at-bol) (point))))
14305 (completion-ignore-case opt)
14306 (type nil)
14307 (tbl nil)
14308 (table (cond
14309 (opt
14310 (setq type :opt)
14311 (append
14312 (mapcar
14313 (lambda (x)
14314 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14315 (cons (match-string 2 x) (match-string 1 x)))
14316 (org-split-string (org-get-current-options) "\n"))
14317 (mapcar 'list org-additional-option-like-keywords)))
14318 (startup
14319 (setq type :startup)
14320 org-startup-options)
14321 (link (append org-link-abbrev-alist-local
14322 org-link-abbrev-alist))
14323 (texp
14324 (setq type :tex)
14325 org-html-entities)
14326 ((string-match "\\`\\*+[ \t]+\\'"
14327 (buffer-substring (point-at-bol) beg))
14328 (setq type :todo)
14329 (mapcar 'list org-todo-keywords-1))
14330 (searchhead
14331 (setq type :searchhead)
14332 (save-excursion
14333 (goto-char (point-min))
14334 (while (re-search-forward org-todo-line-regexp nil t)
14335 (push (list
14336 (org-make-org-heading-search-string
14337 (match-string 3) t))
14338 tbl)))
14339 tbl)
14340 (tag (setq type :tag beg beg1)
14341 (or org-tag-alist (org-get-buffer-tags)))
14342 (prop (setq type :prop beg beg1)
14343 (mapcar 'list (org-buffer-property-keys nil t t)))
14344 (t (progn
14345 (call-interactively org-completion-fallback-command)
14346 (throw 'exit nil)))))
14347 (pattern (buffer-substring-no-properties beg end))
14348 (completion (try-completion pattern table confirm)))
14349 (cond ((eq completion t)
14350 (if (not (assoc (upcase pattern) table))
14351 (message "Already complete")
14352 (if (equal type :opt)
14353 (insert (substring (cdr (assoc (upcase pattern) table))
14354 (length pattern)))
14355 (if (memq type '(:tag :prop)) (insert ":")))))
14356 ((null completion)
14357 (message "Can't find completion for \"%s\"" pattern)
14358 (ding))
14359 ((not (string= pattern completion))
14360 (delete-region beg end)
14361 (if (string-match " +$" completion)
14362 (setq completion (replace-match "" t t completion)))
14363 (insert completion)
14364 (if (get-buffer-window "*Completions*")
14365 (delete-window (get-buffer-window "*Completions*")))
14366 (if (assoc completion table)
14367 (if (eq type :todo) (insert " ")
14368 (if (memq type '(:tag :prop)) (insert ":"))))
14369 (if (and (equal type :opt) (assoc completion table))
14370 (message "%s" (substitute-command-keys
14371 "Press \\[org-complete] again to insert example settings"))))
14373 (message "Making completion list...")
14374 (let ((list (sort (all-completions pattern table confirm)
14375 'string<)))
14376 (with-output-to-temp-buffer "*Completions*"
14377 (condition-case nil
14378 ;; Protection needed for XEmacs and emacs 21
14379 (display-completion-list list pattern)
14380 (error (display-completion-list list)))))
14381 (message "Making completion list...%s" "done")))))))
14383 ;;;; TODO, DEADLINE, Comments
14385 (defun org-toggle-comment ()
14386 "Change the COMMENT state of an entry."
14387 (interactive)
14388 (save-excursion
14389 (org-back-to-heading)
14390 (let (case-fold-search)
14391 (if (looking-at (concat outline-regexp
14392 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14393 (replace-match "" t t nil 1)
14394 (if (looking-at outline-regexp)
14395 (progn
14396 (goto-char (match-end 0))
14397 (insert org-comment-string " ")))))))
14399 (defvar org-last-todo-state-is-todo nil
14400 "This is non-nil when the last TODO state change led to a TODO state.
14401 If the last change removed the TODO tag or switched to DONE, then
14402 this is nil.")
14404 (defvar org-setting-tags nil) ; dynamically skiped
14406 ;; FIXME: better place
14407 (defun org-property-or-variable-value (var &optional inherit)
14408 "Check if there is a property fixing the value of VAR.
14409 If yes, return this value. If not, return the current value of the variable."
14410 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14411 (if (and prop (stringp prop) (string-match "\\S-" prop))
14412 (read prop)
14413 (symbol-value var))))
14415 (defun org-parse-local-options (string var)
14416 "Parse STRING for startup setting relevant for variable VAR."
14417 (let ((rtn (symbol-value var))
14418 e opts)
14419 (save-match-data
14420 (if (or (not string) (not (string-match "\\S-" string)))
14422 (setq opts (delq nil (mapcar (lambda (x)
14423 (setq e (assoc x org-startup-options))
14424 (if (eq (nth 1 e) var) e nil))
14425 (org-split-string string "[ \t]+"))))
14426 (if (not opts)
14428 (setq rtn nil)
14429 (while (setq e (pop opts))
14430 (if (not (nth 3 e))
14431 (setq rtn (nth 2 e))
14432 (if (not (listp rtn)) (setq rtn nil))
14433 (push (nth 2 e) rtn)))
14434 rtn)))))
14436 (defvar org-blocker-hook nil
14437 "Hook for functions that are allowed to block a state change.
14439 Each function gets as its single argument a property list, see
14440 `org-trigger-hook' for more information about this list.
14442 If any of the functions in this hook returns nil, the state change
14443 is blocked.")
14445 (defvar org-trigger-hook nil
14446 "Hook for functions that are triggered by a state change.
14448 Each function gets as its single argument a property list with at least
14449 the following elements:
14451 (:type type-of-change :position pos-at-entry-start
14452 :from old-state :to new-state)
14454 Depending on the type, more properties may be present.
14456 This mechanism is currently implemented for:
14458 TODO state changes
14459 ------------------
14460 :type todo-state-change
14461 :from previous state (keyword as a string), or nil
14462 :to new state (keyword as a string), or nil")
14465 (defun org-todo (&optional arg)
14466 "Change the TODO state of an item.
14467 The state of an item is given by a keyword at the start of the heading,
14468 like
14469 *** TODO Write paper
14470 *** DONE Call mom
14472 The different keywords are specified in the variable `org-todo-keywords'.
14473 By default the available states are \"TODO\" and \"DONE\".
14474 So for this example: when the item starts with TODO, it is changed to DONE.
14475 When it starts with DONE, the DONE is removed. And when neither TODO nor
14476 DONE are present, add TODO at the beginning of the heading.
14478 With C-u prefix arg, use completion to determine the new state.
14479 With numeric prefix arg, switch to that state.
14481 For calling through lisp, arg is also interpreted in the following way:
14482 'none -> empty state
14483 \"\"(empty string) -> switch to empty state
14484 'done -> switch to DONE
14485 'nextset -> switch to the next set of keywords
14486 'previousset -> switch to the previous set of keywords
14487 \"WAITING\" -> switch to the specified keyword, but only if it
14488 really is a member of `org-todo-keywords'."
14489 (interactive "P")
14490 (save-excursion
14491 (catch 'exit
14492 (org-back-to-heading)
14493 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14494 (or (looking-at (concat " +" org-todo-regexp " *"))
14495 (looking-at " *"))
14496 (let* ((match-data (match-data))
14497 (startpos (point-at-bol))
14498 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14499 (org-log-done org-log-done)
14500 (org-log-repeat org-log-repeat)
14501 (org-todo-log-states org-todo-log-states)
14502 (this (match-string 1))
14503 (hl-pos (match-beginning 0))
14504 (head (org-get-todo-sequence-head this))
14505 (ass (assoc head org-todo-kwd-alist))
14506 (interpret (nth 1 ass))
14507 (done-word (nth 3 ass))
14508 (final-done-word (nth 4 ass))
14509 (last-state (or this ""))
14510 (completion-ignore-case t)
14511 (member (member this org-todo-keywords-1))
14512 (tail (cdr member))
14513 (state (cond
14514 ((and org-todo-key-trigger
14515 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14516 (and (not arg) org-use-fast-todo-selection
14517 (not (eq org-use-fast-todo-selection 'prefix)))))
14518 ;; Use fast selection
14519 (org-fast-todo-selection))
14520 ((and (equal arg '(4))
14521 (or (not org-use-fast-todo-selection)
14522 (not org-todo-key-trigger)))
14523 ;; Read a state with completion
14524 (completing-read "State: " (mapcar (lambda(x) (list x))
14525 org-todo-keywords-1)
14526 nil t))
14527 ((eq arg 'right)
14528 (if this
14529 (if tail (car tail) nil)
14530 (car org-todo-keywords-1)))
14531 ((eq arg 'left)
14532 (if (equal member org-todo-keywords-1)
14534 (if this
14535 (nth (- (length org-todo-keywords-1) (length tail) 2)
14536 org-todo-keywords-1)
14537 (org-last org-todo-keywords-1))))
14538 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14539 (setq arg nil))) ; hack to fall back to cycling
14540 (arg
14541 ;; user or caller requests a specific state
14542 (cond
14543 ((equal arg "") nil)
14544 ((eq arg 'none) nil)
14545 ((eq arg 'done) (or done-word (car org-done-keywords)))
14546 ((eq arg 'nextset)
14547 (or (car (cdr (member head org-todo-heads)))
14548 (car org-todo-heads)))
14549 ((eq arg 'previousset)
14550 (let ((org-todo-heads (reverse org-todo-heads)))
14551 (or (car (cdr (member head org-todo-heads)))
14552 (car org-todo-heads))))
14553 ((car (member arg org-todo-keywords-1)))
14554 ((nth (1- (prefix-numeric-value arg))
14555 org-todo-keywords-1))))
14556 ((null member) (or head (car org-todo-keywords-1)))
14557 ((equal this final-done-word) nil) ;; -> make empty
14558 ((null tail) nil) ;; -> first entry
14559 ((eq interpret 'sequence)
14560 (car tail))
14561 ((memq interpret '(type priority))
14562 (if (eq this-command last-command)
14563 (car tail)
14564 (if (> (length tail) 0)
14565 (or done-word (car org-done-keywords))
14566 nil)))
14567 (t nil)))
14568 (next (if state (concat " " state " ") " "))
14569 (change-plist (list :type 'todo-state-change :from this :to state
14570 :position startpos))
14571 dolog now-done-p)
14572 (when org-blocker-hook
14573 (unless (save-excursion
14574 (save-match-data
14575 (run-hook-with-args-until-failure
14576 'org-blocker-hook change-plist)))
14577 (if (interactive-p)
14578 (error "TODO state change from %s to %s blocked" this state)
14579 ;; fail silently
14580 (message "TODO state change from %s to %s blocked" this state)
14581 (throw 'exit nil))))
14582 (store-match-data match-data)
14583 (replace-match next t t)
14584 (unless (pos-visible-in-window-p hl-pos)
14585 (message "TODO state changed to %s" (org-trim next)))
14586 (unless head
14587 (setq head (org-get-todo-sequence-head state)
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 (when (memq arg '(nextset previousset))
14593 (message "Keyword-Set %d/%d: %s"
14594 (- (length org-todo-sets) -1
14595 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14596 (length org-todo-sets)
14597 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14598 (setq org-last-todo-state-is-todo
14599 (not (member state org-done-keywords)))
14600 (setq now-done-p (and (member state org-done-keywords)
14601 (not (member this org-done-keywords))))
14602 (and logging (org-local-logging logging))
14603 (when (and (or org-todo-log-states org-log-done)
14604 (not (memq arg '(nextset previousset))))
14605 ;; we need to look at recording a time and note
14606 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14607 (nth 2 (assoc this org-todo-log-states))))
14608 (when (and state
14609 (member state org-not-done-keywords)
14610 (not (member this org-not-done-keywords)))
14611 ;; This is now a todo state and was not one before
14612 ;; If there was a CLOSED time stamp, get rid of it.
14613 (org-add-planning-info nil nil 'closed))
14614 (when (and now-done-p org-log-done)
14615 ;; It is now done, and it was not done before
14616 (org-add-planning-info 'closed (org-current-time))
14617 (if (and (not dolog) (eq 'note org-log-done))
14618 (org-add-log-maybe 'done state 'findpos 'note)))
14619 (when (and state dolog)
14620 ;; This is a non-nil state, and we need to log it
14621 (org-add-log-maybe 'state state 'findpos dolog)))
14622 ;; Fixup tag positioning
14623 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14624 (run-hooks 'org-after-todo-state-change-hook)
14625 (if (and arg (not (member state org-done-keywords)))
14626 (setq head (org-get-todo-sequence-head state)))
14627 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14628 ;; Do we need to trigger a repeat?
14629 (when now-done-p (org-auto-repeat-maybe state))
14630 ;; Fixup cursor location if close to the keyword
14631 (if (and (outline-on-heading-p)
14632 (not (bolp))
14633 (save-excursion (beginning-of-line 1)
14634 (looking-at org-todo-line-regexp))
14635 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14636 (progn
14637 (goto-char (or (match-end 2) (match-end 1)))
14638 (just-one-space)))
14639 (when org-trigger-hook
14640 (save-excursion
14641 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14643 (defun org-local-logging (value)
14644 "Get logging settings from a property VALUE."
14645 (let* (words w a)
14646 ;; directly set the variables, they are already local.
14647 (setq org-log-done nil
14648 org-log-repeat nil
14649 org-todo-log-states nil)
14650 (setq words (org-split-string value))
14651 (while (setq w (pop words))
14652 (cond
14653 ((setq a (assoc w org-startup-options))
14654 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14655 (set (nth 1 a) (nth 2 a))))
14656 ((setq a (org-extract-log-state-settings w))
14657 (and (member (car a) org-todo-keywords-1)
14658 (push a org-todo-log-states)))))))
14660 (defun org-get-todo-sequence-head (kwd)
14661 "Return the head of the TODO sequence to which KWD belongs.
14662 If KWD is not set, check if there is a text property remembering the
14663 right sequence."
14664 (let (p)
14665 (cond
14666 ((not kwd)
14667 (or (get-text-property (point-at-bol) 'org-todo-head)
14668 (progn
14669 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14670 nil (point-at-eol)))
14671 (get-text-property p 'org-todo-head))))
14672 ((not (member kwd org-todo-keywords-1))
14673 (car org-todo-keywords-1))
14674 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14676 (defun org-fast-todo-selection ()
14677 "Fast TODO keyword selection with single keys.
14678 Returns the new TODO keyword, or nil if no state change should occur."
14679 (let* ((fulltable org-todo-key-alist)
14680 (done-keywords org-done-keywords) ;; needed for the faces.
14681 (maxlen (apply 'max (mapcar
14682 (lambda (x)
14683 (if (stringp (car x)) (string-width (car x)) 0))
14684 fulltable)))
14685 (expert nil)
14686 (fwidth (+ maxlen 3 1 3))
14687 (ncol (/ (- (window-width) 4) fwidth))
14688 tg cnt e c tbl
14689 groups ingroup)
14690 (save-window-excursion
14691 (if expert
14692 (set-buffer (get-buffer-create " *Org todo*"))
14693 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14694 (erase-buffer)
14695 (org-set-local 'org-done-keywords done-keywords)
14696 (setq tbl fulltable cnt 0)
14697 (while (setq e (pop tbl))
14698 (cond
14699 ((equal e '(:startgroup))
14700 (push '() groups) (setq ingroup t)
14701 (when (not (= cnt 0))
14702 (setq cnt 0)
14703 (insert "\n"))
14704 (insert "{ "))
14705 ((equal e '(:endgroup))
14706 (setq ingroup nil cnt 0)
14707 (insert "}\n"))
14709 (setq tg (car e) c (cdr e))
14710 (if ingroup (push tg (car groups)))
14711 (setq tg (org-add-props tg nil 'face
14712 (org-get-todo-face tg)))
14713 (if (and (= cnt 0) (not ingroup)) (insert " "))
14714 (insert "[" c "] " tg (make-string
14715 (- fwidth 4 (length tg)) ?\ ))
14716 (when (= (setq cnt (1+ cnt)) ncol)
14717 (insert "\n")
14718 (if ingroup (insert " "))
14719 (setq cnt 0)))))
14720 (insert "\n")
14721 (goto-char (point-min))
14722 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14723 (fit-window-to-buffer))
14724 (message "[a-z..]:Set [SPC]:clear")
14725 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14726 (cond
14727 ((or (= c ?\C-g)
14728 (and (= c ?q) (not (rassoc c fulltable))))
14729 (setq quit-flag t))
14730 ((= c ?\ ) nil)
14731 ((setq e (rassoc c fulltable) tg (car e))
14733 (t (setq quit-flag t))))))
14735 (defun org-get-repeat ()
14736 "Check if tere is a deadline/schedule with repeater in this entry."
14737 (save-match-data
14738 (save-excursion
14739 (org-back-to-heading t)
14740 (if (re-search-forward
14741 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14742 (match-string 1)))))
14744 (defvar org-last-changed-timestamp)
14745 (defvar org-log-post-message)
14746 (defvar org-log-note-purpose)
14747 (defun org-auto-repeat-maybe (done-word)
14748 "Check if the current headline contains a repeated deadline/schedule.
14749 If yes, set TODO state back to what it was and change the base date
14750 of repeating deadline/scheduled time stamps to new date.
14751 This function should be run in the `org-after-todo-state-change-hook'."
14752 ;; last-state is dynamically scoped into this function
14753 (let* ((repeat (org-get-repeat))
14754 (aa (assoc last-state org-todo-kwd-alist))
14755 (interpret (nth 1 aa))
14756 (head (nth 2 aa))
14757 (whata '(("d" . day) ("m" . month) ("y" . year)))
14758 (msg "Entry repeats: ")
14759 (org-log-done nil)
14760 re type n what ts)
14761 (when repeat
14762 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14763 (org-todo (if (eq interpret 'type) last-state head))
14764 (when (and org-log-repeat
14765 (or (not (memq 'org-add-log-note
14766 (default-value 'post-command-hook)))
14767 (eq org-log-note-purpose 'done)))
14768 ;; Make sure a note is taken;
14769 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14770 'findpos org-log-repeat))
14771 (org-back-to-heading t)
14772 (org-add-planning-info nil nil 'closed)
14773 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14774 org-deadline-time-regexp "\\)\\|\\("
14775 org-ts-regexp "\\)"))
14776 (while (re-search-forward
14777 re (save-excursion (outline-next-heading) (point)) t)
14778 (setq type (if (match-end 1) org-scheduled-string
14779 (if (match-end 3) org-deadline-string "Plain:"))
14780 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14781 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14782 (setq n (string-to-number (match-string 1 ts))
14783 what (match-string 2 ts))
14784 (if (equal what "w") (setq n (* n 7) what "d"))
14785 (org-timestamp-change n (cdr (assoc what whata)))
14786 (setq msg (concat msg type org-last-changed-timestamp " "))))
14787 (setq org-log-post-message msg)
14788 (message "%s" msg))))
14790 (defun org-show-todo-tree (arg)
14791 "Make a compact tree which shows all headlines marked with TODO.
14792 The tree will show the lines where the regexp matches, and all higher
14793 headlines above the match.
14794 With \\[universal-argument] prefix, also show the DONE entries.
14795 With a numeric prefix N, construct a sparse tree for the Nth element
14796 of `org-todo-keywords-1'."
14797 (interactive "P")
14798 (let ((case-fold-search nil)
14799 (kwd-re
14800 (cond ((null arg) org-not-done-regexp)
14801 ((equal arg '(4))
14802 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14803 (mapcar 'list org-todo-keywords-1))))
14804 (concat "\\("
14805 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14806 "\\)\\>")))
14807 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14808 (regexp-quote (nth (1- (prefix-numeric-value arg))
14809 org-todo-keywords-1)))
14810 (t (error "Invalid prefix argument: %s" arg)))))
14811 (message "%d TODO entries found"
14812 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14814 (defun org-deadline (&optional remove)
14815 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14816 With argument REMOVE, remove any deadline from the item."
14817 (interactive "P")
14818 (if remove
14819 (progn
14820 (org-remove-timestamp-with-keyword org-deadline-string)
14821 (message "Item no longer has a deadline."))
14822 (org-add-planning-info 'deadline nil 'closed)))
14824 (defun org-schedule (&optional remove)
14825 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14826 With argument REMOVE, remove any scheduling date from the item."
14827 (interactive "P")
14828 (if remove
14829 (progn
14830 (org-remove-timestamp-with-keyword org-scheduled-string)
14831 (message "Item is no longer scheduled."))
14832 (org-add-planning-info 'scheduled nil 'closed)))
14834 (defun org-remove-timestamp-with-keyword (keyword)
14835 "Remove all time stamps with KEYWORD in the current entry."
14836 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14837 beg)
14838 (save-excursion
14839 (org-back-to-heading t)
14840 (setq beg (point))
14841 (org-end-of-subtree t t)
14842 (while (re-search-backward re beg t)
14843 (replace-match "")
14844 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14845 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14847 (defun org-add-planning-info (what &optional time &rest remove)
14848 "Insert new timestamp with keyword in the line directly after the headline.
14849 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14850 If non is given, the user is prompted for a date.
14851 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14852 be removed."
14853 (interactive)
14854 (let (org-time-was-given org-end-time-was-given)
14855 (when what (setq time (or time (org-read-date nil 'to-time))))
14856 (when (and org-insert-labeled-timestamps-at-point
14857 (member what '(scheduled deadline)))
14858 (insert
14859 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14860 (org-insert-time-stamp time org-time-was-given
14861 nil nil nil (list org-end-time-was-given))
14862 (setq what nil))
14863 (save-excursion
14864 (save-restriction
14865 (let (col list elt ts buffer-invisibility-spec)
14866 (org-back-to-heading t)
14867 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14868 (goto-char (match-end 1))
14869 (setq col (current-column))
14870 (goto-char (match-end 0))
14871 (if (eobp) (insert "\n") (forward-char 1))
14872 (if (and (not (looking-at outline-regexp))
14873 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14874 "[^\r\n]*"))
14875 (not (equal (match-string 1) org-clock-string)))
14876 (narrow-to-region (match-beginning 0) (match-end 0))
14877 (insert-before-markers "\n")
14878 (backward-char 1)
14879 (narrow-to-region (point) (point))
14880 (indent-to-column col))
14881 ;; Check if we have to remove something.
14882 (setq list (cons what remove))
14883 (while list
14884 (setq elt (pop list))
14885 (goto-char (point-min))
14886 (when (or (and (eq elt 'scheduled)
14887 (re-search-forward org-scheduled-time-regexp nil t))
14888 (and (eq elt 'deadline)
14889 (re-search-forward org-deadline-time-regexp nil t))
14890 (and (eq elt 'closed)
14891 (re-search-forward org-closed-time-regexp nil t)))
14892 (replace-match "")
14893 (if (looking-at "--+<[^>]+>") (replace-match ""))
14894 (if (looking-at " +") (replace-match ""))))
14895 (goto-char (point-max))
14896 (when what
14897 (insert
14898 (if (not (equal (char-before) ?\ )) " " "")
14899 (cond ((eq what 'scheduled) org-scheduled-string)
14900 ((eq what 'deadline) org-deadline-string)
14901 ((eq what 'closed) org-closed-string))
14902 " ")
14903 (setq ts (org-insert-time-stamp
14904 time
14905 (or org-time-was-given
14906 (and (eq what 'closed) org-log-done-with-time))
14907 (eq what 'closed)
14908 nil nil (list org-end-time-was-given)))
14909 (end-of-line 1))
14910 (goto-char (point-min))
14911 (widen)
14912 (if (looking-at "[ \t]+\r?\n")
14913 (replace-match ""))
14914 ts)))))
14916 (defvar org-log-note-marker (make-marker))
14917 (defvar org-log-note-purpose nil)
14918 (defvar org-log-note-state nil)
14919 (defvar org-log-note-how nil)
14920 (defvar org-log-note-window-configuration nil)
14921 (defvar org-log-note-return-to (make-marker))
14922 (defvar org-log-post-message nil
14923 "Message to be displayed after a log note has been stored.
14924 The auto-repeater uses this.")
14926 (defun org-add-log-maybe (&optional purpose state findpos how)
14927 "Set up the post command hook to take a note.
14928 If this is about to TODO state change, the new state is expected in STATE.
14929 When FINDPOS is non-nil, find the correct position for the note in
14930 the current entry. If not, assume that it can be inserted at point."
14931 (save-excursion
14932 (when findpos
14933 (org-back-to-heading t)
14934 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14935 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14936 "[^\r\n]*\\)?"))
14937 (goto-char (match-end 0))
14938 (unless org-log-states-order-reversed
14939 (and (= (char-after) ?\n) (forward-char 1))
14940 (org-skip-over-state-notes)
14941 (skip-chars-backward " \t\n\r")))
14942 (move-marker org-log-note-marker (point))
14943 (setq org-log-note-purpose purpose
14944 org-log-note-state state
14945 org-log-note-how how)
14946 (add-hook 'post-command-hook 'org-add-log-note 'append)))
14948 (defun org-skip-over-state-notes ()
14949 "Skip past the list of State notes in an entry."
14950 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14951 (while (looking-at "[ \t]*- State")
14952 (condition-case nil
14953 (org-next-item)
14954 (error (org-end-of-item)))))
14956 (defun org-add-log-note (&optional purpose)
14957 "Pop up a window for taking a note, and add this note later at point."
14958 (remove-hook 'post-command-hook 'org-add-log-note)
14959 (setq org-log-note-window-configuration (current-window-configuration))
14960 (delete-other-windows)
14961 (move-marker org-log-note-return-to (point))
14962 (switch-to-buffer (marker-buffer org-log-note-marker))
14963 (goto-char org-log-note-marker)
14964 (org-switch-to-buffer-other-window "*Org Note*")
14965 (erase-buffer)
14966 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
14967 (org-store-log-note)
14968 (let ((org-inhibit-startup t)) (org-mode))
14969 (insert (format "# Insert note for %s.
14970 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14971 (cond
14972 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14973 ((eq org-log-note-purpose 'done) "closed todo item")
14974 ((eq org-log-note-purpose 'state)
14975 (format "state change to \"%s\"" org-log-note-state))
14976 (t (error "This should not happen")))))
14977 (org-set-local 'org-finish-function 'org-store-log-note)))
14979 (defun org-store-log-note ()
14980 "Finish taking a log note, and insert it to where it belongs."
14981 (let ((txt (buffer-string))
14982 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14983 lines ind)
14984 (kill-buffer (current-buffer))
14985 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14986 (setq txt (replace-match "" t t txt)))
14987 (if (string-match "\\s-+\\'" txt)
14988 (setq txt (replace-match "" t t txt)))
14989 (setq lines (org-split-string txt "\n"))
14990 (when (and note (string-match "\\S-" note))
14991 (setq note
14992 (org-replace-escapes
14993 note
14994 (list (cons "%u" (user-login-name))
14995 (cons "%U" user-full-name)
14996 (cons "%t" (format-time-string
14997 (org-time-stamp-format 'long 'inactive)
14998 (current-time)))
14999 (cons "%s" (if org-log-note-state
15000 (concat "\"" org-log-note-state "\"")
15001 "")))))
15002 (if lines (setq note (concat note " \\\\")))
15003 (push note lines))
15004 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15005 (when lines
15006 (save-excursion
15007 (set-buffer (marker-buffer org-log-note-marker))
15008 (save-excursion
15009 (goto-char org-log-note-marker)
15010 (move-marker org-log-note-marker nil)
15011 (end-of-line 1)
15012 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15013 (indent-relative nil)
15014 (insert "- " (pop lines))
15015 (org-indent-line-function)
15016 (beginning-of-line 1)
15017 (looking-at "[ \t]*")
15018 (setq ind (concat (match-string 0) " "))
15019 (end-of-line 1)
15020 (while lines (insert "\n" ind (pop lines)))))))
15021 (set-window-configuration org-log-note-window-configuration)
15022 (with-current-buffer (marker-buffer org-log-note-return-to)
15023 (goto-char org-log-note-return-to))
15024 (move-marker org-log-note-return-to nil)
15025 (and org-log-post-message (message "%s" org-log-post-message)))
15027 ;; FIXME: what else would be useful?
15028 ;; - priority
15029 ;; - date
15031 (defun org-sparse-tree (&optional arg)
15032 "Create a sparse tree, prompt for the details.
15033 This command can create sparse trees. You first need to select the type
15034 of match used to create the tree:
15036 t Show entries with a specific TODO keyword.
15037 T Show entries selected by a tags match.
15038 p Enter a property name and its value (both with completion on existing
15039 names/values) and show entries with that property.
15040 r Show entries matching a regular expression
15041 d Show deadlines due within `org-deadline-warning-days'."
15042 (interactive "P")
15043 (let (ans kwd value)
15044 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15045 (setq ans (read-char-exclusive))
15046 (cond
15047 ((equal ans ?d)
15048 (call-interactively 'org-check-deadlines))
15049 ((equal ans ?b)
15050 (call-interactively 'org-check-before-date))
15051 ((equal ans ?t)
15052 (org-show-todo-tree '(4)))
15053 ((equal ans ?T)
15054 (call-interactively 'org-tags-sparse-tree))
15055 ((member ans '(?p ?P))
15056 (setq kwd (completing-read "Property: "
15057 (mapcar 'list (org-buffer-property-keys))))
15058 (setq value (completing-read "Value: "
15059 (mapcar 'list (org-property-values kwd))))
15060 (unless (string-match "\\`{.*}\\'" value)
15061 (setq value (concat "\"" value "\"")))
15062 (org-tags-sparse-tree arg (concat kwd "=" value)))
15063 ((member ans '(?r ?R ?/))
15064 (call-interactively 'org-occur))
15065 (t (error "No such sparse tree command \"%c\"" ans)))))
15067 (defvar org-occur-highlights nil)
15068 (make-variable-buffer-local 'org-occur-highlights)
15070 (defun org-occur (regexp &optional keep-previous callback)
15071 "Make a compact tree which shows all matches of REGEXP.
15072 The tree will show the lines where the regexp matches, and all higher
15073 headlines above the match. It will also show the heading after the match,
15074 to make sure editing the matching entry is easy.
15075 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15076 call to `org-occur' will be kept, to allow stacking of calls to this
15077 command.
15078 If CALLBACK is non-nil, it is a function which is called to confirm
15079 that the match should indeed be shown."
15080 (interactive "sRegexp: \nP")
15081 (or keep-previous (org-remove-occur-highlights nil nil t))
15082 (let ((cnt 0))
15083 (save-excursion
15084 (goto-char (point-min))
15085 (if (or (not keep-previous) ; do not want to keep
15086 (not org-occur-highlights)) ; no previous matches
15087 ;; hide everything
15088 (org-overview))
15089 (while (re-search-forward regexp nil t)
15090 (when (or (not callback)
15091 (save-match-data (funcall callback)))
15092 (setq cnt (1+ cnt))
15093 (when org-highlight-sparse-tree-matches
15094 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15095 (org-show-context 'occur-tree))))
15096 (when org-remove-highlights-with-change
15097 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15098 nil 'local))
15099 (unless org-sparse-tree-open-archived-trees
15100 (org-hide-archived-subtrees (point-min) (point-max)))
15101 (run-hooks 'org-occur-hook)
15102 (if (interactive-p)
15103 (message "%d match(es) for regexp %s" cnt regexp))
15104 cnt))
15106 (defun org-show-context (&optional key)
15107 "Make sure point and context and visible.
15108 How much context is shown depends upon the variables
15109 `org-show-hierarchy-above', `org-show-following-heading'. and
15110 `org-show-siblings'."
15111 (let ((heading-p (org-on-heading-p t))
15112 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15113 (following-p (org-get-alist-option org-show-following-heading key))
15114 (entry-p (org-get-alist-option org-show-entry-below key))
15115 (siblings-p (org-get-alist-option org-show-siblings key)))
15116 (catch 'exit
15117 ;; Show heading or entry text
15118 (if (and heading-p (not entry-p))
15119 (org-flag-heading nil) ; only show the heading
15120 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15121 (org-show-hidden-entry))) ; show entire entry
15122 (when following-p
15123 ;; Show next sibling, or heading below text
15124 (save-excursion
15125 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15126 (org-flag-heading nil))))
15127 (when siblings-p (org-show-siblings))
15128 (when hierarchy-p
15129 ;; show all higher headings, possibly with siblings
15130 (save-excursion
15131 (while (and (condition-case nil
15132 (progn (org-up-heading-all 1) t)
15133 (error nil))
15134 (not (bobp)))
15135 (org-flag-heading nil)
15136 (when siblings-p (org-show-siblings))))))))
15138 (defun org-reveal (&optional siblings)
15139 "Show current entry, hierarchy above it, and the following headline.
15140 This can be used to show a consistent set of context around locations
15141 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15142 not t for the search context.
15144 With optional argument SIBLINGS, on each level of the hierarchy all
15145 siblings are shown. This repairs the tree structure to what it would
15146 look like when opened with hierarchical calls to `org-cycle'."
15147 (interactive "P")
15148 (let ((org-show-hierarchy-above t)
15149 (org-show-following-heading t)
15150 (org-show-siblings (if siblings t org-show-siblings)))
15151 (org-show-context nil)))
15153 (defun org-highlight-new-match (beg end)
15154 "Highlight from BEG to END and mark the highlight is an occur headline."
15155 (let ((ov (org-make-overlay beg end)))
15156 (org-overlay-put ov 'face 'secondary-selection)
15157 (push ov org-occur-highlights)))
15159 (defun org-remove-occur-highlights (&optional beg end noremove)
15160 "Remove the occur highlights from the buffer.
15161 BEG and END are ignored. If NOREMOVE is nil, remove this function
15162 from the `before-change-functions' in the current buffer."
15163 (interactive)
15164 (unless org-inhibit-highlight-removal
15165 (mapc 'org-delete-overlay org-occur-highlights)
15166 (setq org-occur-highlights nil)
15167 (unless noremove
15168 (remove-hook 'before-change-functions
15169 'org-remove-occur-highlights 'local))))
15171 ;;;; Priorities
15173 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15174 "Regular expression matching the priority indicator.")
15176 (defvar org-remove-priority-next-time nil)
15178 (defun org-priority-up ()
15179 "Increase the priority of the current item."
15180 (interactive)
15181 (org-priority 'up))
15183 (defun org-priority-down ()
15184 "Decrease the priority of the current item."
15185 (interactive)
15186 (org-priority 'down))
15188 (defun org-priority (&optional action)
15189 "Change the priority of an item by ARG.
15190 ACTION can be `set', `up', `down', or a character."
15191 (interactive)
15192 (setq action (or action 'set))
15193 (let (current new news have remove)
15194 (save-excursion
15195 (org-back-to-heading)
15196 (if (looking-at org-priority-regexp)
15197 (setq current (string-to-char (match-string 2))
15198 have t)
15199 (setq current org-default-priority))
15200 (cond
15201 ((or (eq action 'set) (integerp action))
15202 (if (integerp action)
15203 (setq new action)
15204 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15205 (setq new (read-char-exclusive)))
15206 (if (and (= (upcase org-highest-priority) org-highest-priority)
15207 (= (upcase org-lowest-priority) org-lowest-priority))
15208 (setq new (upcase new)))
15209 (cond ((equal new ?\ ) (setq remove t))
15210 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15211 (error "Priority must be between `%c' and `%c'"
15212 org-highest-priority org-lowest-priority))))
15213 ((eq action 'up)
15214 (if (and (not have) (eq last-command this-command))
15215 (setq new org-lowest-priority)
15216 (setq new (if (and org-priority-start-cycle-with-default (not have))
15217 org-default-priority (1- current)))))
15218 ((eq action 'down)
15219 (if (and (not have) (eq last-command this-command))
15220 (setq new org-highest-priority)
15221 (setq new (if (and org-priority-start-cycle-with-default (not have))
15222 org-default-priority (1+ current)))))
15223 (t (error "Invalid action")))
15224 (if (or (< (upcase new) org-highest-priority)
15225 (> (upcase new) org-lowest-priority))
15226 (setq remove t))
15227 (setq news (format "%c" new))
15228 (if have
15229 (if remove
15230 (replace-match "" t t nil 1)
15231 (replace-match news t t nil 2))
15232 (if remove
15233 (error "No priority cookie found in line")
15234 (looking-at org-todo-line-regexp)
15235 (if (match-end 2)
15236 (progn
15237 (goto-char (match-end 2))
15238 (insert " [#" news "]"))
15239 (goto-char (match-beginning 3))
15240 (insert "[#" news "] ")))))
15241 (org-preserve-lc (org-set-tags nil 'align))
15242 (if remove
15243 (message "Priority removed")
15244 (message "Priority of current item set to %s" news))))
15247 (defun org-get-priority (s)
15248 "Find priority cookie and return priority."
15249 (save-match-data
15250 (if (not (string-match org-priority-regexp s))
15251 (* 1000 (- org-lowest-priority org-default-priority))
15252 (* 1000 (- org-lowest-priority
15253 (string-to-char (match-string 2 s)))))))
15255 ;;;; Tags
15257 (defun org-scan-tags (action matcher &optional todo-only)
15258 "Scan headline tags with inheritance and produce output ACTION.
15259 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15260 evaluated, testing if a given set of tags qualifies a headline for
15261 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15262 are included in the output."
15263 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15264 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15265 (org-re
15266 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15267 (props (list 'face nil
15268 'done-face 'org-done
15269 'undone-face nil
15270 'mouse-face 'highlight
15271 'org-not-done-regexp org-not-done-regexp
15272 'org-todo-regexp org-todo-regexp
15273 'keymap org-agenda-keymap
15274 'help-echo
15275 (format "mouse-2 or RET jump to org file %s"
15276 (abbreviate-file-name
15277 (or (buffer-file-name (buffer-base-buffer))
15278 (buffer-name (buffer-base-buffer)))))))
15279 (case-fold-search nil)
15280 lspos
15281 tags tags-list tags-alist (llast 0) rtn level category i txt
15282 todo marker entry priority)
15283 (save-excursion
15284 (goto-char (point-min))
15285 (when (eq action 'sparse-tree)
15286 (org-overview)
15287 (org-remove-occur-highlights))
15288 (while (re-search-forward re nil t)
15289 (catch :skip
15290 (setq todo (if (match-end 1) (match-string 2))
15291 tags (if (match-end 4) (match-string 4)))
15292 (goto-char (setq lspos (1+ (match-beginning 0))))
15293 (setq level (org-reduced-level (funcall outline-level))
15294 category (org-get-category))
15295 (setq i llast llast level)
15296 ;; remove tag lists from same and sublevels
15297 (while (>= i level)
15298 (when (setq entry (assoc i tags-alist))
15299 (setq tags-alist (delete entry tags-alist)))
15300 (setq i (1- i)))
15301 ;; add the nex tags
15302 (when tags
15303 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15304 tags-alist
15305 (cons (cons level tags) tags-alist)))
15306 ;; compile tags for current headline
15307 (setq tags-list
15308 (if org-use-tag-inheritance
15309 (apply 'append (mapcar 'cdr tags-alist))
15310 tags))
15311 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15312 (eval matcher)
15313 (or (not org-agenda-skip-archived-trees)
15314 (not (member org-archive-tag tags-list))))
15315 (and (eq action 'agenda) (org-agenda-skip))
15316 ;; list this headline
15318 (if (eq action 'sparse-tree)
15319 (progn
15320 (and org-highlight-sparse-tree-matches
15321 (org-get-heading) (match-end 0)
15322 (org-highlight-new-match
15323 (match-beginning 0) (match-beginning 1)))
15324 (org-show-context 'tags-tree))
15325 (setq txt (org-format-agenda-item
15327 (concat
15328 (if org-tags-match-list-sublevels
15329 (make-string (1- level) ?.) "")
15330 (org-get-heading))
15331 category tags-list)
15332 priority (org-get-priority txt))
15333 (goto-char lspos)
15334 (setq marker (org-agenda-new-marker))
15335 (org-add-props txt props
15336 'org-marker marker 'org-hd-marker marker 'org-category category
15337 'priority priority 'type "tagsmatch")
15338 (push txt rtn))
15339 ;; if we are to skip sublevels, jump to end of subtree
15340 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15341 (when (and (eq action 'sparse-tree)
15342 (not org-sparse-tree-open-archived-trees))
15343 (org-hide-archived-subtrees (point-min) (point-max)))
15344 (nreverse rtn)))
15346 (defvar todo-only) ;; dynamically scoped
15348 (defun org-tags-sparse-tree (&optional todo-only match)
15349 "Create a sparse tree according to tags string MATCH.
15350 MATCH can contain positive and negative selection of tags, like
15351 \"+WORK+URGENT-WITHBOSS\".
15352 If optional argument TODO_ONLY is non-nil, only select lines that are
15353 also TODO lines."
15354 (interactive "P")
15355 (org-prepare-agenda-buffers (list (current-buffer)))
15356 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15358 (defvar org-cached-props nil)
15359 (defun org-cached-entry-get (pom property)
15360 (if (or (eq t org-use-property-inheritance)
15361 (member property org-use-property-inheritance))
15362 ;; Caching is not possible, check it directly
15363 (org-entry-get pom property 'inherit)
15364 ;; Get all properties, so that we can do complicated checks easily
15365 (cdr (assoc property (or org-cached-props
15366 (setq org-cached-props
15367 (org-entry-properties pom)))))))
15369 (defun org-global-tags-completion-table (&optional files)
15370 "Return the list of all tags in all agenda buffer/files."
15371 (save-excursion
15372 (org-uniquify
15373 (delq nil
15374 (apply 'append
15375 (mapcar
15376 (lambda (file)
15377 (set-buffer (find-file-noselect file))
15378 (append (org-get-buffer-tags)
15379 (mapcar (lambda (x) (if (stringp (car-safe x))
15380 (list (car-safe x)) nil))
15381 org-tag-alist)))
15382 (if (and files (car files))
15383 files
15384 (org-agenda-files))))))))
15386 (defun org-make-tags-matcher (match)
15387 "Create the TAGS//TODO matcher form for the selection string MATCH."
15388 ;; todo-only is scoped dynamically into this function, and the function
15389 ;; may change it it the matcher asksk for it.
15390 (unless match
15391 ;; Get a new match request, with completion
15392 (let ((org-last-tags-completion-table
15393 (org-global-tags-completion-table)))
15394 (setq match (completing-read
15395 "Match: " 'org-tags-completion-function nil nil nil
15396 'org-tags-history))))
15398 ;; Parse the string and create a lisp form
15399 (let ((match0 match)
15400 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15401 minus tag mm
15402 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15403 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15404 (if (string-match "/+" match)
15405 ;; match contains also a todo-matching request
15406 (progn
15407 (setq tagsmatch (substring match 0 (match-beginning 0))
15408 todomatch (substring match (match-end 0)))
15409 (if (string-match "^!" todomatch)
15410 (setq todo-only t todomatch (substring todomatch 1)))
15411 (if (string-match "^\\s-*$" todomatch)
15412 (setq todomatch nil)))
15413 ;; only matching tags
15414 (setq tagsmatch match todomatch nil))
15416 ;; Make the tags matcher
15417 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15418 (setq tagsmatcher t)
15419 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15420 (while (setq term (pop orterms))
15421 (while (and (equal (substring term -1) "\\") orterms)
15422 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15423 (while (string-match re term)
15424 (setq minus (and (match-end 1)
15425 (equal (match-string 1 term) "-"))
15426 tag (match-string 2 term)
15427 re-p (equal (string-to-char tag) ?{)
15428 level-p (match-end 3)
15429 prop-p (match-end 4)
15430 mm (cond
15431 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15432 (level-p `(= level ,(string-to-number
15433 (match-string 3 term))))
15434 (prop-p
15435 (setq pn (match-string 4 term)
15436 pv (match-string 5 term)
15437 cat-p (equal pn "CATEGORY")
15438 re-p (equal (string-to-char pv) ?{)
15439 pv (substring pv 1 -1))
15440 (if (equal pn "CATEGORY")
15441 (setq gv '(get-text-property (point) 'org-category))
15442 (setq gv `(org-cached-entry-get nil ,pn)))
15443 (if re-p
15444 `(string-match ,pv (or ,gv ""))
15445 `(equal ,pv (or ,gv ""))))
15446 (t `(member ,(downcase tag) tags-list)))
15447 mm (if minus (list 'not mm) mm)
15448 term (substring term (match-end 0)))
15449 (push mm tagsmatcher))
15450 (push (if (> (length tagsmatcher) 1)
15451 (cons 'and tagsmatcher)
15452 (car tagsmatcher))
15453 orlist)
15454 (setq tagsmatcher nil))
15455 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15456 (setq tagsmatcher
15457 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15459 ;; Make the todo matcher
15460 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15461 (setq todomatcher t)
15462 (setq orterms (org-split-string todomatch "|") orlist nil)
15463 (while (setq term (pop orterms))
15464 (while (string-match re term)
15465 (setq minus (and (match-end 1)
15466 (equal (match-string 1 term) "-"))
15467 kwd (match-string 2 term)
15468 re-p (equal (string-to-char kwd) ?{)
15469 term (substring term (match-end 0))
15470 mm (if re-p
15471 `(string-match ,(substring kwd 1 -1) todo)
15472 (list 'equal 'todo kwd))
15473 mm (if minus (list 'not mm) mm))
15474 (push mm todomatcher))
15475 (push (if (> (length todomatcher) 1)
15476 (cons 'and todomatcher)
15477 (car todomatcher))
15478 orlist)
15479 (setq todomatcher nil))
15480 (setq todomatcher (if (> (length orlist) 1)
15481 (cons 'or orlist) (car orlist))))
15483 ;; Return the string and lisp forms of the matcher
15484 (setq matcher (if todomatcher
15485 (list 'and tagsmatcher todomatcher)
15486 tagsmatcher))
15487 (cons match0 matcher)))
15489 (defun org-match-any-p (re list)
15490 "Does re match any element of list?"
15491 (setq list (mapcar (lambda (x) (string-match re x)) list))
15492 (delq nil list))
15494 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15495 (defvar org-tags-overlay (org-make-overlay 1 1))
15496 (org-detach-overlay org-tags-overlay)
15498 (defun org-align-tags-here (to-col)
15499 ;; Assumes that this is a headline
15500 (let ((pos (point)) (col (current-column)) tags)
15501 (beginning-of-line 1)
15502 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15503 (< pos (match-beginning 2)))
15504 (progn
15505 (setq tags (match-string 2))
15506 (goto-char (match-beginning 1))
15507 (insert " ")
15508 (delete-region (point) (1+ (match-end 0)))
15509 (backward-char 1)
15510 (move-to-column
15511 (max (1+ (current-column))
15512 (1+ col)
15513 (if (> to-col 0)
15514 to-col
15515 (- (abs to-col) (length tags))))
15517 (insert tags)
15518 (move-to-column (min (current-column) col) t))
15519 (goto-char pos))))
15521 (defun org-set-tags (&optional arg just-align)
15522 "Set the tags for the current headline.
15523 With prefix ARG, realign all tags in headings in the current buffer."
15524 (interactive "P")
15525 (let* ((re (concat "^" outline-regexp))
15526 (current (org-get-tags-string))
15527 (col (current-column))
15528 (org-setting-tags t)
15529 table current-tags inherited-tags ; computed below when needed
15530 tags p0 c0 c1 rpl)
15531 (if arg
15532 (save-excursion
15533 (goto-char (point-min))
15534 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15535 (while (re-search-forward re nil t)
15536 (org-set-tags nil t)
15537 (end-of-line 1)))
15538 (message "All tags realigned to column %d" org-tags-column))
15539 (if just-align
15540 (setq tags current)
15541 ;; Get a new set of tags from the user
15542 (save-excursion
15543 (setq table (or org-tag-alist (org-get-buffer-tags))
15544 org-last-tags-completion-table table
15545 current-tags (org-split-string current ":")
15546 inherited-tags (nreverse
15547 (nthcdr (length current-tags)
15548 (nreverse (org-get-tags-at))))
15549 tags
15550 (if (or (eq t org-use-fast-tag-selection)
15551 (and org-use-fast-tag-selection
15552 (delq nil (mapcar 'cdr table))))
15553 (org-fast-tag-selection
15554 current-tags inherited-tags table
15555 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15556 (let ((org-add-colon-after-tag-completion t))
15557 (org-trim
15558 (org-without-partial-completion
15559 (completing-read "Tags: " 'org-tags-completion-function
15560 nil nil current 'org-tags-history)))))))
15561 (while (string-match "[-+&]+" tags)
15562 ;; No boolean logic, just a list
15563 (setq tags (replace-match ":" t t tags))))
15565 (if (string-match "\\`[\t ]*\\'" tags)
15566 (setq tags "")
15567 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15568 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15570 ;; Insert new tags at the correct column
15571 (beginning-of-line 1)
15572 (cond
15573 ((and (equal current "") (equal tags "")))
15574 ((re-search-forward
15575 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15576 (point-at-eol) t)
15577 (if (equal tags "")
15578 (setq rpl "")
15579 (goto-char (match-beginning 0))
15580 (setq c0 (current-column) p0 (point)
15581 c1 (max (1+ c0) (if (> org-tags-column 0)
15582 org-tags-column
15583 (- (- org-tags-column) (length tags))))
15584 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15585 (replace-match rpl t t)
15586 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15587 tags)
15588 (t (error "Tags alignment failed")))
15589 (move-to-column col)
15590 (unless just-align
15591 (run-hooks 'org-after-tags-change-hook)))))
15593 (defun org-change-tag-in-region (beg end tag off)
15594 "Add or remove TAG for each entry in the region.
15595 This works in the agenda, and also in an org-mode buffer."
15596 (interactive
15597 (list (region-beginning) (region-end)
15598 (let ((org-last-tags-completion-table
15599 (if (org-mode-p)
15600 (org-get-buffer-tags)
15601 (org-global-tags-completion-table))))
15602 (completing-read
15603 "Tag: " 'org-tags-completion-function nil nil nil
15604 'org-tags-history))
15605 (progn
15606 (message "[s]et or [r]emove? ")
15607 (equal (read-char-exclusive) ?r))))
15608 (if (fboundp 'deactivate-mark) (deactivate-mark))
15609 (let ((agendap (equal major-mode 'org-agenda-mode))
15610 l1 l2 m buf pos newhead (cnt 0))
15611 (goto-char end)
15612 (setq l2 (1- (org-current-line)))
15613 (goto-char beg)
15614 (setq l1 (org-current-line))
15615 (loop for l from l1 to l2 do
15616 (goto-line l)
15617 (setq m (get-text-property (point) 'org-hd-marker))
15618 (when (or (and (org-mode-p) (org-on-heading-p))
15619 (and agendap m))
15620 (setq buf (if agendap (marker-buffer m) (current-buffer))
15621 pos (if agendap m (point)))
15622 (with-current-buffer buf
15623 (save-excursion
15624 (save-restriction
15625 (goto-char pos)
15626 (setq cnt (1+ cnt))
15627 (org-toggle-tag tag (if off 'off 'on))
15628 (setq newhead (org-get-heading)))))
15629 (and agendap (org-agenda-change-all-lines newhead m))))
15630 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15632 (defun org-tags-completion-function (string predicate &optional flag)
15633 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15634 (confirm (lambda (x) (stringp (car x)))))
15635 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15636 (setq s1 (match-string 1 string)
15637 s2 (match-string 2 string))
15638 (setq s1 "" s2 string))
15639 (cond
15640 ((eq flag nil)
15641 ;; try completion
15642 (setq rtn (try-completion s2 ctable confirm))
15643 (if (stringp rtn)
15644 (setq rtn
15645 (concat s1 s2 (substring rtn (length s2))
15646 (if (and org-add-colon-after-tag-completion
15647 (assoc rtn ctable))
15648 ":" ""))))
15649 rtn)
15650 ((eq flag t)
15651 ;; all-completions
15652 (all-completions s2 ctable confirm)
15654 ((eq flag 'lambda)
15655 ;; exact match?
15656 (assoc s2 ctable)))
15659 (defun org-fast-tag-insert (kwd tags face &optional end)
15660 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15661 (insert (format "%-12s" (concat kwd ":"))
15662 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15663 (or end "")))
15665 (defun org-fast-tag-show-exit (flag)
15666 (save-excursion
15667 (goto-line 3)
15668 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15669 (replace-match ""))
15670 (when flag
15671 (end-of-line 1)
15672 (move-to-column (- (window-width) 19) t)
15673 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15675 (defun org-set-current-tags-overlay (current prefix)
15676 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15677 (if (featurep 'xemacs)
15678 (org-overlay-display org-tags-overlay (concat prefix s)
15679 'secondary-selection)
15680 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15681 (org-overlay-display org-tags-overlay (concat prefix s)))))
15683 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15684 "Fast tag selection with single keys.
15685 CURRENT is the current list of tags in the headline, INHERITED is the
15686 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15687 possibly with grouping information. TODO-TABLE is a similar table with
15688 TODO keywords, should these have keys assigned to them.
15689 If the keys are nil, a-z are automatically assigned.
15690 Returns the new tags string, or nil to not change the current settings."
15691 (let* ((fulltable (append table todo-table))
15692 (maxlen (apply 'max (mapcar
15693 (lambda (x)
15694 (if (stringp (car x)) (string-width (car x)) 0))
15695 fulltable)))
15696 (buf (current-buffer))
15697 (expert (eq org-fast-tag-selection-single-key 'expert))
15698 (buffer-tags nil)
15699 (fwidth (+ maxlen 3 1 3))
15700 (ncol (/ (- (window-width) 4) fwidth))
15701 (i-face 'org-done)
15702 (c-face 'org-todo)
15703 tg cnt e c char c1 c2 ntable tbl rtn
15704 ov-start ov-end ov-prefix
15705 (exit-after-next org-fast-tag-selection-single-key)
15706 (done-keywords org-done-keywords)
15707 groups ingroup)
15708 (save-excursion
15709 (beginning-of-line 1)
15710 (if (looking-at
15711 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15712 (setq ov-start (match-beginning 1)
15713 ov-end (match-end 1)
15714 ov-prefix "")
15715 (setq ov-start (1- (point-at-eol))
15716 ov-end (1+ ov-start))
15717 (skip-chars-forward "^\n\r")
15718 (setq ov-prefix
15719 (concat
15720 (buffer-substring (1- (point)) (point))
15721 (if (> (current-column) org-tags-column)
15723 (make-string (- org-tags-column (current-column)) ?\ ))))))
15724 (org-move-overlay org-tags-overlay ov-start ov-end)
15725 (save-window-excursion
15726 (if expert
15727 (set-buffer (get-buffer-create " *Org tags*"))
15728 (delete-other-windows)
15729 (split-window-vertically)
15730 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15731 (erase-buffer)
15732 (org-set-local 'org-done-keywords done-keywords)
15733 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15734 (org-fast-tag-insert "Current" current c-face "\n\n")
15735 (org-fast-tag-show-exit exit-after-next)
15736 (org-set-current-tags-overlay current ov-prefix)
15737 (setq tbl fulltable char ?a cnt 0)
15738 (while (setq e (pop tbl))
15739 (cond
15740 ((equal e '(:startgroup))
15741 (push '() groups) (setq ingroup t)
15742 (when (not (= cnt 0))
15743 (setq cnt 0)
15744 (insert "\n"))
15745 (insert "{ "))
15746 ((equal e '(:endgroup))
15747 (setq ingroup nil cnt 0)
15748 (insert "}\n"))
15750 (setq tg (car e) c2 nil)
15751 (if (cdr e)
15752 (setq c (cdr e))
15753 ;; automatically assign a character.
15754 (setq c1 (string-to-char
15755 (downcase (substring
15756 tg (if (= (string-to-char tg) ?@) 1 0)))))
15757 (if (or (rassoc c1 ntable) (rassoc c1 table))
15758 (while (or (rassoc char ntable) (rassoc char table))
15759 (setq char (1+ char)))
15760 (setq c2 c1))
15761 (setq c (or c2 char)))
15762 (if ingroup (push tg (car groups)))
15763 (setq tg (org-add-props tg nil 'face
15764 (cond
15765 ((not (assoc tg table))
15766 (org-get-todo-face tg))
15767 ((member tg current) c-face)
15768 ((member tg inherited) i-face)
15769 (t nil))))
15770 (if (and (= cnt 0) (not ingroup)) (insert " "))
15771 (insert "[" c "] " tg (make-string
15772 (- fwidth 4 (length tg)) ?\ ))
15773 (push (cons tg c) ntable)
15774 (when (= (setq cnt (1+ cnt)) ncol)
15775 (insert "\n")
15776 (if ingroup (insert " "))
15777 (setq cnt 0)))))
15778 (setq ntable (nreverse ntable))
15779 (insert "\n")
15780 (goto-char (point-min))
15781 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15782 (fit-window-to-buffer))
15783 (setq rtn
15784 (catch 'exit
15785 (while t
15786 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15787 (if groups " [!] no groups" " [!]groups")
15788 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15789 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15790 (cond
15791 ((= c ?\r) (throw 'exit t))
15792 ((= c ?!)
15793 (setq groups (not groups))
15794 (goto-char (point-min))
15795 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15796 ((= c ?\C-c)
15797 (if (not expert)
15798 (org-fast-tag-show-exit
15799 (setq exit-after-next (not exit-after-next)))
15800 (setq expert nil)
15801 (delete-other-windows)
15802 (split-window-vertically)
15803 (org-switch-to-buffer-other-window " *Org tags*")
15804 (and (fboundp 'fit-window-to-buffer)
15805 (fit-window-to-buffer))))
15806 ((or (= c ?\C-g)
15807 (and (= c ?q) (not (rassoc c ntable))))
15808 (org-detach-overlay org-tags-overlay)
15809 (setq quit-flag t))
15810 ((= c ?\ )
15811 (setq current nil)
15812 (if exit-after-next (setq exit-after-next 'now)))
15813 ((= c ?\t)
15814 (condition-case nil
15815 (setq tg (completing-read
15816 "Tag: "
15817 (or buffer-tags
15818 (with-current-buffer buf
15819 (org-get-buffer-tags)))))
15820 (quit (setq tg "")))
15821 (when (string-match "\\S-" tg)
15822 (add-to-list 'buffer-tags (list tg))
15823 (if (member tg current)
15824 (setq current (delete tg current))
15825 (push tg current)))
15826 (if exit-after-next (setq exit-after-next 'now)))
15827 ((setq e (rassoc c todo-table) tg (car e))
15828 (with-current-buffer buf
15829 (save-excursion (org-todo tg)))
15830 (if exit-after-next (setq exit-after-next 'now)))
15831 ((setq e (rassoc c ntable) tg (car e))
15832 (if (member tg current)
15833 (setq current (delete tg current))
15834 (loop for g in groups do
15835 (if (member tg g)
15836 (mapc (lambda (x)
15837 (setq current (delete x current)))
15838 g)))
15839 (push tg current))
15840 (if exit-after-next (setq exit-after-next 'now))))
15842 ;; Create a sorted list
15843 (setq current
15844 (sort current
15845 (lambda (a b)
15846 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15847 (if (eq exit-after-next 'now) (throw 'exit t))
15848 (goto-char (point-min))
15849 (beginning-of-line 2)
15850 (delete-region (point) (point-at-eol))
15851 (org-fast-tag-insert "Current" current c-face)
15852 (org-set-current-tags-overlay current ov-prefix)
15853 (while (re-search-forward
15854 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15855 (setq tg (match-string 1))
15856 (add-text-properties
15857 (match-beginning 1) (match-end 1)
15858 (list 'face
15859 (cond
15860 ((member tg current) c-face)
15861 ((member tg inherited) i-face)
15862 (t (get-text-property (match-beginning 1) 'face))))))
15863 (goto-char (point-min)))))
15864 (org-detach-overlay org-tags-overlay)
15865 (if rtn
15866 (mapconcat 'identity current ":")
15867 nil))))
15869 (defun org-get-tags-string ()
15870 "Get the TAGS string in the current headline."
15871 (unless (org-on-heading-p t)
15872 (error "Not on a heading"))
15873 (save-excursion
15874 (beginning-of-line 1)
15875 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15876 (org-match-string-no-properties 1)
15877 "")))
15879 (defun org-get-tags ()
15880 "Get the list of tags specified in the current headline."
15881 (org-split-string (org-get-tags-string) ":"))
15883 (defun org-get-buffer-tags ()
15884 "Get a table of all tags used in the buffer, for completion."
15885 (let (tags)
15886 (save-excursion
15887 (goto-char (point-min))
15888 (while (re-search-forward
15889 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15890 (when (equal (char-after (point-at-bol 0)) ?*)
15891 (mapc (lambda (x) (add-to-list 'tags x))
15892 (org-split-string (org-match-string-no-properties 1) ":")))))
15893 (mapcar 'list tags)))
15896 ;;;; Properties
15898 ;;; Setting and retrieving properties
15900 (defconst org-special-properties
15901 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15902 "TIMESTAMP" "TIMESTAMP_IA")
15903 "The special properties valid in Org-mode.
15905 These are properties that are not defined in the property drawer,
15906 but in some other way.")
15908 (defconst org-default-properties
15909 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15910 "LOCATION" "LOGGING" "COLUMNS")
15911 "Some properties that are used by Org-mode for various purposes.
15912 Being in this list makes sure that they are offered for completion.")
15914 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15915 "Regular expression matching the first line of a property drawer.")
15917 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15918 "Regular expression matching the first line of a property drawer.")
15920 (defun org-property-action ()
15921 "Do an action on properties."
15922 (interactive)
15923 (let (c)
15924 (org-at-property-p)
15925 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15926 (setq c (read-char-exclusive))
15927 (cond
15928 ((equal c ?s)
15929 (call-interactively 'org-set-property))
15930 ((equal c ?d)
15931 (call-interactively 'org-delete-property))
15932 ((equal c ?D)
15933 (call-interactively 'org-delete-property-globally))
15934 ((equal c ?c)
15935 (call-interactively 'org-compute-property-at-point))
15936 (t (error "No such property action %c" c)))))
15938 (defun org-at-property-p ()
15939 "Is the cursor in a property line?"
15940 ;; FIXME: Does not check if we are actually in the drawer.
15941 ;; FIXME: also returns true on any drawers.....
15942 ;; This is used by C-c C-c for property action.
15943 (save-excursion
15944 (beginning-of-line 1)
15945 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15947 (defmacro org-with-point-at (pom &rest body)
15948 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15949 (declare (indent 1) (debug t))
15950 `(save-excursion
15951 (if (markerp pom) (set-buffer (marker-buffer pom)))
15952 (save-excursion
15953 (goto-char (or pom (point)))
15954 ,@body)))
15956 (defun org-get-property-block (&optional beg end force)
15957 "Return the (beg . end) range of the body of the property drawer.
15958 BEG and END can be beginning and end of subtree, if not given
15959 they will be found.
15960 If the drawer does not exist and FORCE is non-nil, create the drawer."
15961 (catch 'exit
15962 (save-excursion
15963 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15964 (end (or end (progn (outline-next-heading) (point)))))
15965 (goto-char beg)
15966 (if (re-search-forward org-property-start-re end t)
15967 (setq beg (1+ (match-end 0)))
15968 (if force
15969 (save-excursion
15970 (org-insert-property-drawer)
15971 (setq end (progn (outline-next-heading) (point))))
15972 (throw 'exit nil))
15973 (goto-char beg)
15974 (if (re-search-forward org-property-start-re end t)
15975 (setq beg (1+ (match-end 0)))))
15976 (if (re-search-forward org-property-end-re end t)
15977 (setq end (match-beginning 0))
15978 (or force (throw 'exit nil))
15979 (goto-char beg)
15980 (setq end beg)
15981 (org-indent-line-function)
15982 (insert ":END:\n"))
15983 (cons beg end)))))
15985 (defun org-entry-properties (&optional pom which)
15986 "Get all properties of the entry at point-or-marker POM.
15987 This includes the TODO keyword, the tags, time strings for deadline,
15988 scheduled, and clocking, and any additional properties defined in the
15989 entry. The return value is an alist, keys may occur multiple times
15990 if the property key was used several times.
15991 POM may also be nil, in which case the current entry is used.
15992 If WHICH is nil or `all', get all properties. If WHICH is
15993 `special' or `standard', only get that subclass."
15994 (setq which (or which 'all))
15995 (org-with-point-at pom
15996 (let ((clockstr (substring org-clock-string 0 -1))
15997 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15998 beg end range props sum-props key value string clocksum)
15999 (save-excursion
16000 (when (condition-case nil (org-back-to-heading t) (error nil))
16001 (setq beg (point))
16002 (setq sum-props (get-text-property (point) 'org-summaries))
16003 (setq clocksum (get-text-property (point) :org-clock-minutes))
16004 (outline-next-heading)
16005 (setq end (point))
16006 (when (memq which '(all special))
16007 ;; Get the special properties, like TODO and tags
16008 (goto-char beg)
16009 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16010 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16011 (when (looking-at org-priority-regexp)
16012 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16013 (when (and (setq value (org-get-tags-string))
16014 (string-match "\\S-" value))
16015 (push (cons "TAGS" value) props))
16016 (when (setq value (org-get-tags-at))
16017 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16018 props))
16019 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16020 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16021 string (if (equal key clockstr)
16022 (org-no-properties
16023 (org-trim
16024 (buffer-substring
16025 (match-beginning 3) (goto-char (point-at-eol)))))
16026 (substring (org-match-string-no-properties 3) 1 -1)))
16027 (unless key
16028 (if (= (char-after (match-beginning 3)) ?\[)
16029 (setq key "TIMESTAMP_IA")
16030 (setq key "TIMESTAMP")))
16031 (when (or (equal key clockstr) (not (assoc key props)))
16032 (push (cons key string) props)))
16036 (when (memq which '(all standard))
16037 ;; Get the standard properties, like :PORP: ...
16038 (setq range (org-get-property-block beg end))
16039 (when range
16040 (goto-char (car range))
16041 (while (re-search-forward
16042 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16043 (cdr range) t)
16044 (setq key (org-match-string-no-properties 1)
16045 value (org-trim (or (org-match-string-no-properties 2) "")))
16046 (unless (member key excluded)
16047 (push (cons key (or value "")) props)))))
16048 (if clocksum
16049 (push (cons "CLOCKSUM"
16050 (org-column-number-to-string (/ (float clocksum) 60.)
16051 'add_times))
16052 props))
16053 (append sum-props (nreverse props)))))))
16055 (defun org-entry-get (pom property &optional inherit)
16056 "Get value of PROPERTY for entry at point-or-marker POM.
16057 If INHERIT is non-nil and the entry does not have the property,
16058 then also check higher levels of the hierarchy.
16059 If the property is present but empty, the return value is the empty string.
16060 If the property is not present at all, nil is returned."
16061 (org-with-point-at pom
16062 (if inherit
16063 (org-entry-get-with-inheritance property)
16064 (if (member property org-special-properties)
16065 ;; We need a special property. Use brute force, get all properties.
16066 (cdr (assoc property (org-entry-properties nil 'special)))
16067 (let ((range (org-get-property-block)))
16068 (if (and range
16069 (goto-char (car range))
16070 (re-search-forward
16071 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16072 (cdr range) t))
16073 ;; Found the property, return it.
16074 (if (match-end 1)
16075 (org-match-string-no-properties 1)
16076 "")))))))
16078 (defun org-entry-delete (pom property)
16079 "Delete the property PROPERTY from entry at point-or-marker POM."
16080 (org-with-point-at pom
16081 (if (member property org-special-properties)
16082 nil ; cannot delete these properties.
16083 (let ((range (org-get-property-block)))
16084 (if (and range
16085 (goto-char (car range))
16086 (re-search-forward
16087 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16088 (cdr range) t))
16089 (progn
16090 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16092 nil)))))
16094 ;; Multi-values properties are properties that contain multiple values
16095 ;; These values are assumed to be single words, separated by whitespace.
16096 (defun org-entry-add-to-multivalued-property (pom property value)
16097 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16098 (let* ((old (org-entry-get pom property))
16099 (values (and old (org-split-string old "[ \t]"))))
16100 (unless (member value values)
16101 (setq values (cons value values))
16102 (org-entry-put pom property
16103 (mapconcat 'identity values " ")))))
16105 (defun org-entry-remove-from-multivalued-property (pom property value)
16106 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16107 (let* ((old (org-entry-get pom property))
16108 (values (and old (org-split-string old "[ \t]"))))
16109 (when (member value values)
16110 (setq values (delete value values))
16111 (org-entry-put pom property
16112 (mapconcat 'identity values " ")))))
16114 (defun org-entry-member-in-multivalued-property (pom property value)
16115 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16116 (let* ((old (org-entry-get pom property))
16117 (values (and old (org-split-string old "[ \t]"))))
16118 (member value values)))
16120 (defvar org-entry-property-inherited-from (make-marker))
16122 (defun org-entry-get-with-inheritance (property)
16123 "Get entry property, and search higher levels if not present."
16124 (let (tmp)
16125 (save-excursion
16126 (save-restriction
16127 (widen)
16128 (catch 'ex
16129 (while t
16130 (when (setq tmp (org-entry-get nil property))
16131 (org-back-to-heading t)
16132 (move-marker org-entry-property-inherited-from (point))
16133 (throw 'ex tmp))
16134 (or (org-up-heading-safe) (throw 'ex nil)))))
16135 (or tmp (cdr (assoc property org-local-properties))
16136 (cdr (assoc property org-global-properties))))))
16138 (defun org-entry-put (pom property value)
16139 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16140 (org-with-point-at pom
16141 (org-back-to-heading t)
16142 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16143 range)
16144 (cond
16145 ((equal property "TODO")
16146 (when (and (stringp value) (string-match "\\S-" value)
16147 (not (member value org-todo-keywords-1)))
16148 (error "\"%s\" is not a valid TODO state" value))
16149 (if (or (not value)
16150 (not (string-match "\\S-" value)))
16151 (setq value 'none))
16152 (org-todo value)
16153 (org-set-tags nil 'align))
16154 ((equal property "PRIORITY")
16155 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16156 (string-to-char value) ?\ ))
16157 (org-set-tags nil 'align))
16158 ((equal property "SCHEDULED")
16159 (if (re-search-forward org-scheduled-time-regexp end t)
16160 (cond
16161 ((eq value 'earlier) (org-timestamp-change -1 'day))
16162 ((eq value 'later) (org-timestamp-change 1 'day))
16163 (t (call-interactively 'org-schedule)))
16164 (call-interactively 'org-schedule)))
16165 ((equal property "DEADLINE")
16166 (if (re-search-forward org-deadline-time-regexp end t)
16167 (cond
16168 ((eq value 'earlier) (org-timestamp-change -1 'day))
16169 ((eq value 'later) (org-timestamp-change 1 'day))
16170 (t (call-interactively 'org-deadline)))
16171 (call-interactively 'org-deadline)))
16172 ((member property org-special-properties)
16173 (error "The %s property can not yet be set with `org-entry-put'"
16174 property))
16175 (t ; a non-special property
16176 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16177 (setq range (org-get-property-block beg end 'force))
16178 (goto-char (car range))
16179 (if (re-search-forward
16180 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16181 (progn
16182 (delete-region (match-beginning 1) (match-end 1))
16183 (goto-char (match-beginning 1)))
16184 (goto-char (cdr range))
16185 (insert "\n")
16186 (backward-char 1)
16187 (org-indent-line-function)
16188 (insert ":" property ":"))
16189 (and value (insert " " value))
16190 (org-indent-line-function)))))))
16192 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16193 "Get all property keys in the current buffer.
16194 With INCLUDE-SPECIALS, also list the special properties that relect things
16195 like tags and TODO state.
16196 With INCLUDE-DEFAULTS, also include properties that has special meaning
16197 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16198 With INCLUDE-COLUMNS, also include property names given in COLUMN
16199 formats in the current buffer."
16200 (let (rtn range cfmt cols s p)
16201 (save-excursion
16202 (save-restriction
16203 (widen)
16204 (goto-char (point-min))
16205 (while (re-search-forward org-property-start-re nil t)
16206 (setq range (org-get-property-block))
16207 (goto-char (car range))
16208 (while (re-search-forward
16209 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16210 (cdr range) t)
16211 (add-to-list 'rtn (org-match-string-no-properties 1)))
16212 (outline-next-heading))))
16214 (when include-specials
16215 (setq rtn (append org-special-properties rtn)))
16217 (when include-defaults
16218 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16220 (when include-columns
16221 (save-excursion
16222 (save-restriction
16223 (widen)
16224 (goto-char (point-min))
16225 (while (re-search-forward
16226 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16227 nil t)
16228 (setq cfmt (match-string 2) s 0)
16229 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16230 cfmt s)
16231 (setq s (match-end 0)
16232 p (match-string 1 cfmt))
16233 (unless (or (equal p "ITEM")
16234 (member p org-special-properties))
16235 (add-to-list 'rtn (match-string 1 cfmt))))))))
16237 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16239 (defun org-property-values (key)
16240 "Return a list of all values of property KEY."
16241 (save-excursion
16242 (save-restriction
16243 (widen)
16244 (goto-char (point-min))
16245 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16246 values)
16247 (while (re-search-forward re nil t)
16248 (add-to-list 'values (org-trim (match-string 1))))
16249 (delete "" values)))))
16251 (defun org-insert-property-drawer ()
16252 "Insert a property drawer into the current entry."
16253 (interactive)
16254 (org-back-to-heading t)
16255 (looking-at outline-regexp)
16256 (let ((indent (- (match-end 0)(match-beginning 0)))
16257 (beg (point))
16258 (re (concat "^[ \t]*" org-keyword-time-regexp))
16259 end hiddenp)
16260 (outline-next-heading)
16261 (setq end (point))
16262 (goto-char beg)
16263 (while (re-search-forward re end t))
16264 (setq hiddenp (org-invisible-p))
16265 (end-of-line 1)
16266 (and (equal (char-after) ?\n) (forward-char 1))
16267 (org-skip-over-state-notes)
16268 (skip-chars-backward " \t\n\r")
16269 (if (eq (char-before) ?*) (forward-char 1))
16270 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16271 (beginning-of-line 0)
16272 (indent-to-column indent)
16273 (beginning-of-line 2)
16274 (indent-to-column indent)
16275 (beginning-of-line 0)
16276 (if hiddenp
16277 (save-excursion
16278 (org-back-to-heading t)
16279 (hide-entry))
16280 (org-flag-drawer t))))
16282 (defun org-set-property (property value)
16283 "In the current entry, set PROPERTY to VALUE.
16284 When called interactively, this will prompt for a property name, offering
16285 completion on existing and default properties. And then it will prompt
16286 for a value, offering competion either on allowed values (via an inherited
16287 xxx_ALL property) or on existing values in other instances of this property
16288 in the current file."
16289 (interactive
16290 (let* ((prop (completing-read
16291 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16292 (cur (org-entry-get nil prop))
16293 (allowed (org-property-get-allowed-values nil prop 'table))
16294 (existing (mapcar 'list (org-property-values prop)))
16295 (val (if allowed
16296 (completing-read "Value: " allowed nil 'req-match)
16297 (completing-read
16298 (concat "Value" (if (and cur (string-match "\\S-" cur))
16299 (concat "[" cur "]") "")
16300 ": ")
16301 existing nil nil "" nil cur))))
16302 (list prop (if (equal val "") cur val))))
16303 (unless (equal (org-entry-get nil property) value)
16304 (org-entry-put nil property value)))
16306 (defun org-delete-property (property)
16307 "In the current entry, delete PROPERTY."
16308 (interactive
16309 (let* ((prop (completing-read
16310 "Property: " (org-entry-properties nil 'standard))))
16311 (list prop)))
16312 (message "Property %s %s" property
16313 (if (org-entry-delete nil property)
16314 "deleted"
16315 "was not present in the entry")))
16317 (defun org-delete-property-globally (property)
16318 "Remove PROPERTY globally, from all entries."
16319 (interactive
16320 (let* ((prop (completing-read
16321 "Globally remove property: "
16322 (mapcar 'list (org-buffer-property-keys)))))
16323 (list prop)))
16324 (save-excursion
16325 (save-restriction
16326 (widen)
16327 (goto-char (point-min))
16328 (let ((cnt 0))
16329 (while (re-search-forward
16330 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16331 nil t)
16332 (setq cnt (1+ cnt))
16333 (replace-match ""))
16334 (message "Property \"%s\" removed from %d entries" property cnt)))))
16336 (defvar org-columns-current-fmt-compiled) ; defined below
16338 (defun org-compute-property-at-point ()
16339 "Compute the property at point.
16340 This looks for an enclosing column format, extracts the operator and
16341 then applies it to the proerty in the column format's scope."
16342 (interactive)
16343 (unless (org-at-property-p)
16344 (error "Not at a property"))
16345 (let ((prop (org-match-string-no-properties 2)))
16346 (org-columns-get-format-and-top-level)
16347 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16348 (error "No operator defined for property %s" prop))
16349 (org-columns-compute prop)))
16351 (defun org-property-get-allowed-values (pom property &optional table)
16352 "Get allowed values for the property PROPERTY.
16353 When TABLE is non-nil, return an alist that can directly be used for
16354 completion."
16355 (let (vals)
16356 (cond
16357 ((equal property "TODO")
16358 (setq vals (org-with-point-at pom
16359 (append org-todo-keywords-1 '("")))))
16360 ((equal property "PRIORITY")
16361 (let ((n org-lowest-priority))
16362 (while (>= n org-highest-priority)
16363 (push (char-to-string n) vals)
16364 (setq n (1- n)))))
16365 ((member property org-special-properties))
16367 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16369 (when (and vals (string-match "\\S-" vals))
16370 (setq vals (car (read-from-string (concat "(" vals ")"))))
16371 (setq vals (mapcar (lambda (x)
16372 (cond ((stringp x) x)
16373 ((numberp x) (number-to-string x))
16374 ((symbolp x) (symbol-name x))
16375 (t "???")))
16376 vals)))))
16377 (if table (mapcar 'list vals) vals)))
16379 (defun org-property-previous-allowed-value (&optional previous)
16380 "Switch to the next allowed value for this property."
16381 (interactive)
16382 (org-property-next-allowed-value t))
16384 (defun org-property-next-allowed-value (&optional previous)
16385 "Switch to the next allowed value for this property."
16386 (interactive)
16387 (unless (org-at-property-p)
16388 (error "Not at a property"))
16389 (let* ((key (match-string 2))
16390 (value (match-string 3))
16391 (allowed (or (org-property-get-allowed-values (point) key)
16392 (and (member value '("[ ]" "[-]" "[X]"))
16393 '("[ ]" "[X]"))))
16394 nval)
16395 (unless allowed
16396 (error "Allowed values for this property have not been defined"))
16397 (if previous (setq allowed (reverse allowed)))
16398 (if (member value allowed)
16399 (setq nval (car (cdr (member value allowed)))))
16400 (setq nval (or nval (car allowed)))
16401 (if (equal nval value)
16402 (error "Only one allowed value for this property"))
16403 (org-at-property-p)
16404 (replace-match (concat " :" key ": " nval) t t)
16405 (org-indent-line-function)
16406 (beginning-of-line 1)
16407 (skip-chars-forward " \t")))
16409 (defun org-find-entry-with-id (ident)
16410 "Locate the entry that contains the ID property with exact value IDENT.
16411 IDENT can be a string, a symbol or a number, this function will search for
16412 the string representation of it.
16413 Return the position where this entry starts, or nil if there is no such entry."
16414 (let ((id (cond
16415 ((stringp ident) ident)
16416 ((symbol-name ident) (symbol-name ident))
16417 ((numberp ident) (number-to-string ident))
16418 (t (error "IDENT %s must be a string, symbol or number" ident))))
16419 (case-fold-search nil))
16420 (save-excursion
16421 (save-restriction
16422 (goto-char (point-min))
16423 (when (re-search-forward
16424 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16425 nil t)
16426 (org-back-to-heading)
16427 (point))))))
16429 ;;; Column View
16431 (defvar org-columns-overlays nil
16432 "Holds the list of current column overlays.")
16434 (defvar org-columns-current-fmt nil
16435 "Local variable, holds the currently active column format.")
16436 (defvar org-columns-current-fmt-compiled nil
16437 "Local variable, holds the currently active column format.
16438 This is the compiled version of the format.")
16439 (defvar org-columns-current-widths nil
16440 "Loval variable, holds the currently widths of fields.")
16441 (defvar org-columns-current-maxwidths nil
16442 "Loval variable, holds the currently active maximum column widths.")
16443 (defvar org-columns-begin-marker (make-marker)
16444 "Points to the position where last a column creation command was called.")
16445 (defvar org-columns-top-level-marker (make-marker)
16446 "Points to the position where current columns region starts.")
16448 (defvar org-columns-map (make-sparse-keymap)
16449 "The keymap valid in column display.")
16451 (defun org-columns-content ()
16452 "Switch to contents view while in columns view."
16453 (interactive)
16454 (org-overview)
16455 (org-content))
16457 (org-defkey org-columns-map "c" 'org-columns-content)
16458 (org-defkey org-columns-map "o" 'org-overview)
16459 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16460 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16461 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16462 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16463 (org-defkey org-columns-map "v" 'org-columns-show-value)
16464 (org-defkey org-columns-map "q" 'org-columns-quit)
16465 (org-defkey org-columns-map "r" 'org-columns-redo)
16466 (org-defkey org-columns-map "g" 'org-columns-redo)
16467 (org-defkey org-columns-map [left] 'backward-char)
16468 (org-defkey org-columns-map "\M-b" 'backward-char)
16469 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16470 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16471 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16472 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16473 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16474 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16475 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16476 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16477 (org-defkey org-columns-map "<" 'org-columns-narrow)
16478 (org-defkey org-columns-map ">" 'org-columns-widen)
16479 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16480 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16481 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16482 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16484 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16485 '("Column"
16486 ["Edit property" org-columns-edit-value t]
16487 ["Next allowed value" org-columns-next-allowed-value t]
16488 ["Previous allowed value" org-columns-previous-allowed-value t]
16489 ["Show full value" org-columns-show-value t]
16490 ["Edit allowed values" org-columns-edit-allowed t]
16491 "--"
16492 ["Edit column attributes" org-columns-edit-attributes t]
16493 ["Increase column width" org-columns-widen t]
16494 ["Decrease column width" org-columns-narrow t]
16495 "--"
16496 ["Move column right" org-columns-move-right t]
16497 ["Move column left" org-columns-move-left t]
16498 ["Add column" org-columns-new t]
16499 ["Delete column" org-columns-delete t]
16500 "--"
16501 ["CONTENTS" org-columns-content t]
16502 ["OVERVIEW" org-overview t]
16503 ["Refresh columns display" org-columns-redo t]
16504 "--"
16505 ["Open link" org-columns-open-link t]
16506 "--"
16507 ["Quit" org-columns-quit t]))
16509 (defun org-columns-new-overlay (beg end &optional string face)
16510 "Create a new column overlay and add it to the list."
16511 (let ((ov (org-make-overlay beg end)))
16512 (org-overlay-put ov 'face (or face 'secondary-selection))
16513 (org-overlay-display ov string face)
16514 (push ov org-columns-overlays)
16515 ov))
16517 (defun org-columns-display-here (&optional props)
16518 "Overlay the current line with column display."
16519 (interactive)
16520 (let* ((fmt org-columns-current-fmt-compiled)
16521 (beg (point-at-bol))
16522 (level-face (save-excursion
16523 (beginning-of-line 1)
16524 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16525 (org-get-level-face 2))))
16526 (color (list :foreground
16527 (face-attribute (or level-face 'default) :foreground)))
16528 props pom property ass width f string ov column val modval)
16529 ;; Check if the entry is in another buffer.
16530 (unless props
16531 (if (eq major-mode 'org-agenda-mode)
16532 (setq pom (or (get-text-property (point) 'org-hd-marker)
16533 (get-text-property (point) 'org-marker))
16534 props (if pom (org-entry-properties pom) nil))
16535 (setq props (org-entry-properties nil))))
16536 ;; Walk the format
16537 (while (setq column (pop fmt))
16538 (setq property (car column)
16539 ass (if (equal property "ITEM")
16540 (cons "ITEM"
16541 (save-match-data
16542 (org-no-properties
16543 (org-remove-tabs
16544 (buffer-substring-no-properties
16545 (point-at-bol) (point-at-eol))))))
16546 (assoc property props))
16547 width (or (cdr (assoc property org-columns-current-maxwidths))
16548 (nth 2 column)
16549 (length property))
16550 f (format "%%-%d.%ds | " width width)
16551 val (or (cdr ass) "")
16552 modval (if (equal property "ITEM")
16553 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16554 string (format f (or modval val)))
16555 ;; Create the overlay
16556 (org-unmodified
16557 (setq ov (org-columns-new-overlay
16558 beg (setq beg (1+ beg)) string
16559 (list color 'org-column)))
16560 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16561 (org-overlay-put ov 'keymap org-columns-map)
16562 (org-overlay-put ov 'org-columns-key property)
16563 (org-overlay-put ov 'org-columns-value (cdr ass))
16564 (org-overlay-put ov 'org-columns-value-modified modval)
16565 (org-overlay-put ov 'org-columns-pom pom)
16566 (org-overlay-put ov 'org-columns-format f))
16567 (if (or (not (char-after beg))
16568 (equal (char-after beg) ?\n))
16569 (let ((inhibit-read-only t))
16570 (save-excursion
16571 (goto-char beg)
16572 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16573 ;; Make the rest of the line disappear.
16574 (org-unmodified
16575 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16576 (org-overlay-put ov 'invisible t)
16577 (org-overlay-put ov 'keymap org-columns-map)
16578 (org-overlay-put ov 'intangible t)
16579 (push ov org-columns-overlays)
16580 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16581 (org-overlay-put ov 'keymap org-columns-map)
16582 (push ov org-columns-overlays)
16583 (let ((inhibit-read-only t))
16584 (put-text-property (max (point-min) (1- (point-at-bol)))
16585 (min (point-max) (1+ (point-at-eol)))
16586 'read-only "Type `e' to edit property")))))
16588 (defvar org-previous-header-line-format nil
16589 "The header line format before column view was turned on.")
16590 (defvar org-columns-inhibit-recalculation nil
16591 "Inhibit recomputing of columns on column view startup.")
16594 (defvar header-line-format)
16595 (defun org-columns-display-here-title ()
16596 "Overlay the newline before the current line with the table title."
16597 (interactive)
16598 (let ((fmt org-columns-current-fmt-compiled)
16599 string (title "")
16600 property width f column str widths)
16601 (while (setq column (pop fmt))
16602 (setq property (car column)
16603 str (or (nth 1 column) property)
16604 width (or (cdr (assoc property org-columns-current-maxwidths))
16605 (nth 2 column)
16606 (length str))
16607 widths (push width widths)
16608 f (format "%%-%d.%ds | " width width)
16609 string (format f str)
16610 title (concat title string)))
16611 (setq title (concat
16612 (org-add-props " " nil 'display '(space :align-to 0))
16613 (org-add-props title nil 'face '(:weight bold :underline t))))
16614 (org-set-local 'org-previous-header-line-format header-line-format)
16615 (org-set-local 'org-columns-current-widths (nreverse widths))
16616 (setq header-line-format title)))
16618 (defun org-columns-remove-overlays ()
16619 "Remove all currently active column overlays."
16620 (interactive)
16621 (when (marker-buffer org-columns-begin-marker)
16622 (with-current-buffer (marker-buffer org-columns-begin-marker)
16623 (when (local-variable-p 'org-previous-header-line-format)
16624 (setq header-line-format org-previous-header-line-format)
16625 (kill-local-variable 'org-previous-header-line-format))
16626 (move-marker org-columns-begin-marker nil)
16627 (move-marker org-columns-top-level-marker nil)
16628 (org-unmodified
16629 (mapc 'org-delete-overlay org-columns-overlays)
16630 (setq org-columns-overlays nil)
16631 (let ((inhibit-read-only t))
16632 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16634 (defun org-columns-cleanup-item (item fmt)
16635 "Remove from ITEM what is a column in the format FMT."
16636 (if (not org-complex-heading-regexp)
16637 item
16638 (when (string-match org-complex-heading-regexp item)
16639 (concat
16640 (org-add-props (concat (match-string 1 item) " ") nil
16641 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16642 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16643 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16644 " " (match-string 4 item)
16645 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16647 (defun org-columns-show-value ()
16648 "Show the full value of the property."
16649 (interactive)
16650 (let ((value (get-char-property (point) 'org-columns-value)))
16651 (message "Value is: %s" (or value ""))))
16653 (defun org-columns-quit ()
16654 "Remove the column overlays and in this way exit column editing."
16655 (interactive)
16656 (org-unmodified
16657 (org-columns-remove-overlays)
16658 (let ((inhibit-read-only t))
16659 (remove-text-properties (point-min) (point-max) '(read-only t))))
16660 (when (eq major-mode 'org-agenda-mode)
16661 (message
16662 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16664 (defun org-columns-check-computed ()
16665 "Check if this column value is computed.
16666 If yes, throw an error indicating that changing it does not make sense."
16667 (let ((val (get-char-property (point) 'org-columns-value)))
16668 (when (and (stringp val)
16669 (get-char-property 0 'org-computed val))
16670 (error "This value is computed from the entry's children"))))
16672 (defun org-columns-todo (&optional arg)
16673 "Change the TODO state during column view."
16674 (interactive "P")
16675 (org-columns-edit-value "TODO"))
16677 (defun org-columns-set-tags-or-toggle (&optional arg)
16678 "Toggle checkbox at point, or set tags for current headline."
16679 (interactive "P")
16680 (if (string-match "\\`\\[[ xX-]\\]\\'"
16681 (get-char-property (point) 'org-columns-value))
16682 (org-columns-next-allowed-value)
16683 (org-columns-edit-value "TAGS")))
16685 (defun org-columns-edit-value (&optional key)
16686 "Edit the value of the property at point in column view.
16687 Where possible, use the standard interface for changing this line."
16688 (interactive)
16689 (org-columns-check-computed)
16690 (let* ((external-key key)
16691 (col (current-column))
16692 (key (or key (get-char-property (point) 'org-columns-key)))
16693 (value (get-char-property (point) 'org-columns-value))
16694 (bol (point-at-bol)) (eol (point-at-eol))
16695 (pom (or (get-text-property bol 'org-hd-marker)
16696 (point))) ; keep despite of compiler waring
16697 (line-overlays
16698 (delq nil (mapcar (lambda (x)
16699 (and (eq (overlay-buffer x) (current-buffer))
16700 (>= (overlay-start x) bol)
16701 (<= (overlay-start x) eol)
16703 org-columns-overlays)))
16704 nval eval allowed)
16705 (cond
16706 ((equal key "CLOCKSUM")
16707 (error "This special column cannot be edited"))
16708 ((equal key "ITEM")
16709 (setq eval '(org-with-point-at pom
16710 (org-edit-headline))))
16711 ((equal key "TODO")
16712 (setq eval '(org-with-point-at pom
16713 (let ((current-prefix-arg
16714 (if external-key current-prefix-arg '(4))))
16715 (call-interactively 'org-todo)))))
16716 ((equal key "PRIORITY")
16717 (setq eval '(org-with-point-at pom
16718 (call-interactively 'org-priority))))
16719 ((equal key "TAGS")
16720 (setq eval '(org-with-point-at pom
16721 (let ((org-fast-tag-selection-single-key
16722 (if (eq org-fast-tag-selection-single-key 'expert)
16723 t org-fast-tag-selection-single-key)))
16724 (call-interactively 'org-set-tags)))))
16725 ((equal key "DEADLINE")
16726 (setq eval '(org-with-point-at pom
16727 (call-interactively 'org-deadline))))
16728 ((equal key "SCHEDULED")
16729 (setq eval '(org-with-point-at pom
16730 (call-interactively 'org-schedule))))
16732 (setq allowed (org-property-get-allowed-values pom key 'table))
16733 (if allowed
16734 (setq nval (completing-read "Value: " allowed nil t))
16735 (setq nval (read-string "Edit: " value)))
16736 (setq nval (org-trim nval))
16737 (when (not (equal nval value))
16738 (setq eval '(org-entry-put pom key nval)))))
16739 (when eval
16740 (let ((inhibit-read-only t))
16741 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16742 (unwind-protect
16743 (progn
16744 (setq org-columns-overlays
16745 (org-delete-all line-overlays org-columns-overlays))
16746 (mapc 'org-delete-overlay line-overlays)
16747 (org-columns-eval eval))
16748 (org-columns-display-here))))
16749 (move-to-column col)
16750 (if (and (org-mode-p)
16751 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16752 (org-columns-update key))))
16754 (defun org-edit-headline () ; FIXME: this is not columns specific
16755 "Edit the current headline, the part without TODO keyword, TAGS."
16756 (org-back-to-heading)
16757 (when (looking-at org-todo-line-regexp)
16758 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16759 (txt (match-string 3))
16760 (post "")
16761 txt2)
16762 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16763 (setq post (match-string 0 txt)
16764 txt (substring txt 0 (match-beginning 0))))
16765 (setq txt2 (read-string "Edit: " txt))
16766 (when (not (equal txt txt2))
16767 (beginning-of-line 1)
16768 (insert pre txt2 post)
16769 (delete-region (point) (point-at-eol))
16770 (org-set-tags nil t)))))
16772 (defun org-columns-edit-allowed ()
16773 "Edit the list of allowed values for the current property."
16774 (interactive)
16775 (let* ((key (get-char-property (point) 'org-columns-key))
16776 (key1 (concat key "_ALL"))
16777 (allowed (org-entry-get (point) key1 t))
16778 nval)
16779 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16780 (setq nval (read-string "Allowed: " allowed))
16781 (org-entry-put
16782 (cond ((marker-position org-entry-property-inherited-from)
16783 org-entry-property-inherited-from)
16784 ((marker-position org-columns-top-level-marker)
16785 org-columns-top-level-marker))
16786 key1 nval)))
16788 (defmacro org-no-warnings (&rest body)
16789 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16791 (defun org-columns-eval (form)
16792 (let (hidep)
16793 (save-excursion
16794 (beginning-of-line 1)
16795 ;; `next-line' is needed here, because it skips invisible line.
16796 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16797 (setq hidep (org-on-heading-p 1)))
16798 (eval form)
16799 (and hidep (hide-entry))))
16801 (defun org-columns-previous-allowed-value ()
16802 "Switch to the previous allowed value for this column."
16803 (interactive)
16804 (org-columns-next-allowed-value t))
16806 (defun org-columns-next-allowed-value (&optional previous)
16807 "Switch to the next allowed value for this column."
16808 (interactive)
16809 (org-columns-check-computed)
16810 (let* ((col (current-column))
16811 (key (get-char-property (point) 'org-columns-key))
16812 (value (get-char-property (point) 'org-columns-value))
16813 (bol (point-at-bol)) (eol (point-at-eol))
16814 (pom (or (get-text-property bol 'org-hd-marker)
16815 (point))) ; keep despite of compiler waring
16816 (line-overlays
16817 (delq nil (mapcar (lambda (x)
16818 (and (eq (overlay-buffer x) (current-buffer))
16819 (>= (overlay-start x) bol)
16820 (<= (overlay-start x) eol)
16822 org-columns-overlays)))
16823 (allowed (or (org-property-get-allowed-values pom key)
16824 (and (memq
16825 (nth 4 (assoc key org-columns-current-fmt-compiled))
16826 '(checkbox checkbox-n-of-m checkbox-percent))
16827 '("[ ]" "[X]"))))
16828 nval)
16829 (when (equal key "ITEM")
16830 (error "Cannot edit item headline from here"))
16831 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16832 (error "Allowed values for this property have not been defined"))
16833 (if (member key '("SCHEDULED" "DEADLINE"))
16834 (setq nval (if previous 'earlier 'later))
16835 (if previous (setq allowed (reverse allowed)))
16836 (if (member value allowed)
16837 (setq nval (car (cdr (member value allowed)))))
16838 (setq nval (or nval (car allowed)))
16839 (if (equal nval value)
16840 (error "Only one allowed value for this property")))
16841 (let ((inhibit-read-only t))
16842 (remove-text-properties (1- bol) eol '(read-only t))
16843 (unwind-protect
16844 (progn
16845 (setq org-columns-overlays
16846 (org-delete-all line-overlays org-columns-overlays))
16847 (mapc 'org-delete-overlay line-overlays)
16848 (org-columns-eval '(org-entry-put pom key nval)))
16849 (org-columns-display-here)))
16850 (move-to-column col)
16851 (if (and (org-mode-p)
16852 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16853 (org-columns-update key))))
16855 (defun org-verify-version (task)
16856 (cond
16857 ((eq task 'columns)
16858 (if (or (featurep 'xemacs)
16859 (< emacs-major-version 22))
16860 (error "Emacs 22 is required for the columns feature")))))
16862 (defun org-columns-open-link (&optional arg)
16863 (interactive "P")
16864 (let ((value (get-char-property (point) 'org-columns-value)))
16865 (org-open-link-from-string value arg)))
16867 (defun org-open-link-from-string (s &optional arg)
16868 "Open a link in the string S, as if it was in Org-mode."
16869 (interactive)
16870 (with-temp-buffer
16871 (let ((org-inhibit-startup t))
16872 (org-mode)
16873 (insert s)
16874 (goto-char (point-min))
16875 (org-open-at-point arg))))
16877 (defun org-columns-get-format-and-top-level ()
16878 (let (fmt)
16879 (when (condition-case nil (org-back-to-heading) (error nil))
16880 (move-marker org-entry-property-inherited-from nil)
16881 (setq fmt (org-entry-get nil "COLUMNS" t)))
16882 (setq fmt (or fmt org-columns-default-format))
16883 (org-set-local 'org-columns-current-fmt fmt)
16884 (org-columns-compile-format fmt)
16885 (if (marker-position org-entry-property-inherited-from)
16886 (move-marker org-columns-top-level-marker
16887 org-entry-property-inherited-from)
16888 (move-marker org-columns-top-level-marker (point)))
16889 fmt))
16891 (defun org-columns ()
16892 "Turn on column view on an org-mode file."
16893 (interactive)
16894 (org-verify-version 'columns)
16895 (org-columns-remove-overlays)
16896 (move-marker org-columns-begin-marker (point))
16897 (let (beg end fmt cache maxwidths)
16898 (setq fmt (org-columns-get-format-and-top-level))
16899 (save-excursion
16900 (goto-char org-columns-top-level-marker)
16901 (setq beg (point))
16902 (unless org-columns-inhibit-recalculation
16903 (org-columns-compute-all))
16904 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16905 (point-max)))
16906 ;; Get and cache the properties
16907 (goto-char beg)
16908 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16909 (save-excursion
16910 (save-restriction
16911 (narrow-to-region beg end)
16912 (org-clock-sum))))
16913 (while (re-search-forward (concat "^" outline-regexp) end t)
16914 (push (cons (org-current-line) (org-entry-properties)) cache))
16915 (when cache
16916 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16917 (org-set-local 'org-columns-current-maxwidths maxwidths)
16918 (org-columns-display-here-title)
16919 (mapc (lambda (x)
16920 (goto-line (car x))
16921 (org-columns-display-here (cdr x)))
16922 cache)))))
16924 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16925 "Insert a new column, to the leeft o the current column."
16926 (interactive)
16927 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16928 cell)
16929 (setq prop (completing-read
16930 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
16931 nil nil prop))
16932 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16933 (setq width (read-string "Column width: " (if width (number-to-string width))))
16934 (if (string-match "\\S-" width)
16935 (setq width (string-to-number width))
16936 (setq width nil))
16937 (setq fmt (completing-read "Summary [none]: "
16938 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
16939 nil t))
16940 (if (string-match "\\S-" fmt)
16941 (setq fmt (intern fmt))
16942 (setq fmt nil))
16943 (if (eq fmt 'none) (setq fmt nil))
16944 (if editp
16945 (progn
16946 (setcar editp prop)
16947 (setcdr editp (list title width nil fmt)))
16948 (setq cell (nthcdr (1- (current-column))
16949 org-columns-current-fmt-compiled))
16950 (setcdr cell (cons (list prop title width nil fmt)
16951 (cdr cell))))
16952 (org-columns-store-format)
16953 (org-columns-redo)))
16955 (defun org-columns-delete ()
16956 "Delete the column at point from columns view."
16957 (interactive)
16958 (let* ((n (current-column))
16959 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16960 (when (y-or-n-p
16961 (format "Are you sure you want to remove column \"%s\"? " title))
16962 (setq org-columns-current-fmt-compiled
16963 (delq (nth n org-columns-current-fmt-compiled)
16964 org-columns-current-fmt-compiled))
16965 (org-columns-store-format)
16966 (org-columns-redo)
16967 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16968 (backward-char 1)))))
16970 (defun org-columns-edit-attributes ()
16971 "Edit the attributes of the current column."
16972 (interactive)
16973 (let* ((n (current-column))
16974 (info (nth n org-columns-current-fmt-compiled)))
16975 (apply 'org-columns-new info)))
16977 (defun org-columns-widen (arg)
16978 "Make the column wider by ARG characters."
16979 (interactive "p")
16980 (let* ((n (current-column))
16981 (entry (nth n org-columns-current-fmt-compiled))
16982 (width (or (nth 2 entry)
16983 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16984 (setq width (max 1 (+ width arg)))
16985 (setcar (nthcdr 2 entry) width)
16986 (org-columns-store-format)
16987 (org-columns-redo)))
16989 (defun org-columns-narrow (arg)
16990 "Make the column nrrower by ARG characters."
16991 (interactive "p")
16992 (org-columns-widen (- arg)))
16994 (defun org-columns-move-right ()
16995 "Swap this column with the one to the right."
16996 (interactive)
16997 (let* ((n (current-column))
16998 (cell (nthcdr n org-columns-current-fmt-compiled))
17000 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17001 (error "Cannot shift this column further to the right"))
17002 (setq e (car cell))
17003 (setcar cell (car (cdr cell)))
17004 (setcdr cell (cons e (cdr (cdr cell))))
17005 (org-columns-store-format)
17006 (org-columns-redo)
17007 (forward-char 1)))
17009 (defun org-columns-move-left ()
17010 "Swap this column with the one to the left."
17011 (interactive)
17012 (let* ((n (current-column)))
17013 (when (= n 0)
17014 (error "Cannot shift this column further to the left"))
17015 (backward-char 1)
17016 (org-columns-move-right)
17017 (backward-char 1)))
17019 (defun org-columns-store-format ()
17020 "Store the text version of the current columns format in appropriate place.
17021 This is either in the COLUMNS property of the node starting the current column
17022 display, or in the #+COLUMNS line of the current buffer."
17023 (let (fmt (cnt 0))
17024 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17025 (org-set-local 'org-columns-current-fmt fmt)
17026 (if (marker-position org-columns-top-level-marker)
17027 (save-excursion
17028 (goto-char org-columns-top-level-marker)
17029 (if (and (org-at-heading-p)
17030 (org-entry-get nil "COLUMNS"))
17031 (org-entry-put nil "COLUMNS" fmt)
17032 (goto-char (point-min))
17033 ;; Overwrite all #+COLUMNS lines....
17034 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17035 (setq cnt (1+ cnt))
17036 (replace-match (concat "#+COLUMNS: " fmt) t t))
17037 (unless (> cnt 0)
17038 (goto-char (point-min))
17039 (or (org-on-heading-p t) (outline-next-heading))
17040 (let ((inhibit-read-only t))
17041 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17042 (org-set-local 'org-columns-default-format fmt))))))
17044 (defvar org-overriding-columns-format nil
17045 "When set, overrides any other definition.")
17046 (defvar org-agenda-view-columns-initially nil
17047 "When set, switch to columns view immediately after creating the agenda.")
17049 (defun org-agenda-columns ()
17050 "Turn on column view in the agenda."
17051 (interactive)
17052 (org-verify-version 'columns)
17053 (org-columns-remove-overlays)
17054 (move-marker org-columns-begin-marker (point))
17055 (let (fmt cache maxwidths m)
17056 (cond
17057 ((and (local-variable-p 'org-overriding-columns-format)
17058 org-overriding-columns-format)
17059 (setq fmt org-overriding-columns-format))
17060 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17061 (setq fmt (org-entry-get m "COLUMNS" t)))
17062 ((and (boundp 'org-columns-current-fmt)
17063 (local-variable-p 'org-columns-current-fmt)
17064 org-columns-current-fmt)
17065 (setq fmt org-columns-current-fmt))
17066 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17067 (setq m (get-text-property m 'org-hd-marker))
17068 (setq fmt (org-entry-get m "COLUMNS" t))))
17069 (setq fmt (or fmt org-columns-default-format))
17070 (org-set-local 'org-columns-current-fmt fmt)
17071 (org-columns-compile-format fmt)
17072 (save-excursion
17073 ;; Get and cache the properties
17074 (goto-char (point-min))
17075 (while (not (eobp))
17076 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17077 (get-text-property (point) 'org-marker)))
17078 (push (cons (org-current-line) (org-entry-properties m)) cache))
17079 (beginning-of-line 2))
17080 (when cache
17081 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17082 (org-set-local 'org-columns-current-maxwidths maxwidths)
17083 (org-columns-display-here-title)
17084 (mapc (lambda (x)
17085 (goto-line (car x))
17086 (org-columns-display-here (cdr x)))
17087 cache)))))
17089 (defun org-columns-get-autowidth-alist (s cache)
17090 "Derive the maximum column widths from the format and the cache."
17091 (let ((start 0) rtn)
17092 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17093 (push (cons (match-string 1 s) 1) rtn)
17094 (setq start (match-end 0)))
17095 (mapc (lambda (x)
17096 (setcdr x (apply 'max
17097 (mapcar
17098 (lambda (y)
17099 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17100 cache))))
17101 rtn)
17102 rtn))
17104 (defun org-columns-compute-all ()
17105 "Compute all columns that have operators defined."
17106 (org-unmodified
17107 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17108 (let ((columns org-columns-current-fmt-compiled) col)
17109 (while (setq col (pop columns))
17110 (when (nth 3 col)
17111 (save-excursion
17112 (org-columns-compute (car col)))))))
17114 (defun org-columns-update (property)
17115 "Recompute PROPERTY, and update the columns display for it."
17116 (org-columns-compute property)
17117 (let (fmt val pos)
17118 (save-excursion
17119 (mapc (lambda (ov)
17120 (when (equal (org-overlay-get ov 'org-columns-key) property)
17121 (setq pos (org-overlay-start ov))
17122 (goto-char pos)
17123 (when (setq val (cdr (assoc property
17124 (get-text-property
17125 (point-at-bol) 'org-summaries))))
17126 (setq fmt (org-overlay-get ov 'org-columns-format))
17127 (org-overlay-put ov 'org-columns-value val)
17128 (org-overlay-put ov 'display (format fmt val)))))
17129 org-columns-overlays))))
17131 (defun org-columns-compute (property)
17132 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17133 (interactive)
17134 (let* ((re (concat "^" outline-regexp))
17135 (lmax 30) ; Does anyone use deeper levels???
17136 (lsum (make-vector lmax 0))
17137 (lflag (make-vector lmax nil))
17138 (level 0)
17139 (ass (assoc property org-columns-current-fmt-compiled))
17140 (format (nth 4 ass))
17141 (printf (nth 5 ass))
17142 (beg org-columns-top-level-marker)
17143 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17144 (save-excursion
17145 ;; Find the region to compute
17146 (goto-char beg)
17147 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17148 (goto-char end)
17149 ;; Walk the tree from the back and do the computations
17150 (while (re-search-backward re beg t)
17151 (setq sumpos (match-beginning 0)
17152 last-level level
17153 level (org-outline-level)
17154 val (org-entry-get nil property)
17155 valflag (and val (string-match "\\S-" val)))
17156 (cond
17157 ((< level last-level)
17158 ;; put the sum of lower levels here as a property
17159 (setq sum (aref lsum last-level) ; current sum
17160 flag (aref lflag last-level) ; any valid entries from children?
17161 str (org-column-number-to-string sum format printf)
17162 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17163 useval (if flag str1 (if valflag val ""))
17164 sum-alist (get-text-property sumpos 'org-summaries))
17165 (if (assoc property sum-alist)
17166 (setcdr (assoc property sum-alist) useval)
17167 (push (cons property useval) sum-alist)
17168 (org-unmodified
17169 (add-text-properties sumpos (1+ sumpos)
17170 (list 'org-summaries sum-alist))))
17171 (when val
17172 (org-entry-put nil property (if flag str val)))
17173 ;; add current to current level accumulator
17174 (when (or flag valflag)
17175 (aset lsum level (+ (aref lsum level)
17176 (if flag sum (org-column-string-to-number
17177 (if flag str val) format))))
17178 (aset lflag level t))
17179 ;; clear accumulators for deeper levels
17180 (loop for l from (1+ level) to (1- lmax) do
17181 (aset lsum l 0)
17182 (aset lflag l nil)))
17183 ((>= level last-level)
17184 ;; add what we have here to the accumulator for this level
17185 (aset lsum level (+ (aref lsum level)
17186 (org-column-string-to-number (or val "0") format)))
17187 (and valflag (aset lflag level t)))
17188 (t (error "This should not happen")))))))
17190 (defun org-columns-redo ()
17191 "Construct the column display again."
17192 (interactive)
17193 (message "Recomputing columns...")
17194 (save-excursion
17195 (if (marker-position org-columns-begin-marker)
17196 (goto-char org-columns-begin-marker))
17197 (org-columns-remove-overlays)
17198 (if (org-mode-p)
17199 (call-interactively 'org-columns)
17200 (call-interactively 'org-agenda-columns)))
17201 (message "Recomputing columns...done"))
17203 (defun org-columns-not-in-agenda ()
17204 (if (eq major-mode 'org-agenda-mode)
17205 (error "This command is only allowed in Org-mode buffers")))
17208 (defun org-string-to-number (s)
17209 "Convert string to number, and interpret hh:mm:ss."
17210 (if (not (string-match ":" s))
17211 (string-to-number s)
17212 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17213 (while l
17214 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17215 sum)))
17217 (defun org-column-number-to-string (n fmt &optional printf)
17218 "Convert a computed column number to a string value, according to FMT."
17219 (cond
17220 ((eq fmt 'add_times)
17221 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17222 (format "%d:%02d" h m)))
17223 ((eq fmt 'checkbox)
17224 (cond ((= n (floor n)) "[X]")
17225 ((> n 1.) "[-]")
17226 (t "[ ]")))
17227 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17228 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17229 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17230 (printf (format printf n))
17231 ((eq fmt 'currency)
17232 (format "%.2f" n))
17233 (t (number-to-string n))))
17235 (defun org-nofm-to-completion (n m &optional percent)
17236 (if (not percent)
17237 (format "[%d/%d]" n m)
17238 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17240 (defun org-column-string-to-number (s fmt)
17241 "Convert a column value to a number that can be used for column computing."
17242 (cond
17243 ((string-match ":" s)
17244 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17245 (while l
17246 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17247 sum))
17248 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17249 (if (equal s "[X]") 1. 0.000001))
17250 (t (string-to-number s))))
17252 (defun org-columns-uncompile-format (cfmt)
17253 "Turn the compiled columns format back into a string representation."
17254 (let ((rtn "") e s prop title op width fmt printf)
17255 (while (setq e (pop cfmt))
17256 (setq prop (car e)
17257 title (nth 1 e)
17258 width (nth 2 e)
17259 op (nth 3 e)
17260 fmt (nth 4 e)
17261 printf (nth 5 e))
17262 (cond
17263 ((eq fmt 'add_times) (setq op ":"))
17264 ((eq fmt 'checkbox) (setq op "X"))
17265 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17266 ((eq fmt 'checkbox-percent) (setq op "X%"))
17267 ((eq fmt 'add_numbers) (setq op "+"))
17268 ((eq fmt 'currency) (setq op "$")))
17269 (if (and op printf) (setq op (concat op ";" printf)))
17270 (if (equal title prop) (setq title nil))
17271 (setq s (concat "%" (if width (number-to-string width))
17272 prop
17273 (if title (concat "(" title ")"))
17274 (if op (concat "{" op "}"))))
17275 (setq rtn (concat rtn " " s)))
17276 (org-trim rtn)))
17278 (defun org-columns-compile-format (fmt)
17279 "Turn a column format string into an alist of specifications.
17280 The alist has one entry for each column in the format. The elements of
17281 that list are:
17282 property the property
17283 title the title field for the columns
17284 width the column width in characters, can be nil for automatic
17285 operator the operator if any
17286 format the output format for computed results, derived from operator
17287 printf a printf format for computed values"
17288 (let ((start 0) width prop title op f printf)
17289 (setq org-columns-current-fmt-compiled nil)
17290 (while (string-match
17291 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17292 fmt start)
17293 (setq start (match-end 0)
17294 width (match-string 1 fmt)
17295 prop (match-string 2 fmt)
17296 title (or (match-string 3 fmt) prop)
17297 op (match-string 4 fmt)
17298 f nil
17299 printf nil)
17300 (if width (setq width (string-to-number width)))
17301 (when (and op (string-match ";" op))
17302 (setq printf (substring op (match-end 0))
17303 op (substring op 0 (match-beginning 0))))
17304 (cond
17305 ((equal op "+") (setq f 'add_numbers))
17306 ((equal op "$") (setq f 'currency))
17307 ((equal op ":") (setq f 'add_times))
17308 ((equal op "X") (setq f 'checkbox))
17309 ((equal op "X/") (setq f 'checkbox-n-of-m))
17310 ((equal op "X%") (setq f 'checkbox-percent))
17312 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17313 (setq org-columns-current-fmt-compiled
17314 (nreverse org-columns-current-fmt-compiled))))
17317 ;;; Dynamic block for Column view
17319 (defun org-columns-capture-view ()
17320 "Get the column view of the current buffer and return it as a list.
17321 The list will contains the title row and all other rows. Each row is
17322 a list of fields."
17323 (save-excursion
17324 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17325 (n (length title)) row tbl)
17326 (goto-char (point-min))
17327 (while (re-search-forward "^\\*+ " nil t)
17328 (when (get-char-property (match-beginning 0) 'org-columns-key)
17329 (setq row nil)
17330 (loop for i from 0 to (1- n) do
17331 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17332 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17334 row))
17335 (setq row (nreverse row))
17336 (push row tbl)))
17337 (append (list title 'hline) (nreverse tbl)))))
17339 (defun org-dblock-write:columnview (params)
17340 "Write the column view table.
17341 PARAMS is a property list of parameters:
17343 :width enforce same column widths with <N> specifiers.
17344 :id the :ID: property of the entry where the columns view
17345 should be built, as a string. When `local', call locally.
17346 When `global' call column view with the cursor at the beginning
17347 of the buffer (usually this means that the whole buffer switches
17348 to column view).
17349 :hlines When t, insert a hline before each item. When a number, insert
17350 a hline before each level <= that number.
17351 :vlines When t, make each column a colgroup to enforce vertical lines."
17352 (let ((pos (move-marker (make-marker) (point)))
17353 (hlines (plist-get params :hlines))
17354 (vlines (plist-get params :vlines))
17355 tbl id idpos nfields tmp)
17356 (save-excursion
17357 (save-restriction
17358 (when (setq id (plist-get params :id))
17359 (cond ((not id) nil)
17360 ((eq id 'global) (goto-char (point-min)))
17361 ((eq id 'local) nil)
17362 ((setq idpos (org-find-entry-with-id id))
17363 (goto-char idpos))
17364 (t (error "Cannot find entry with :ID: %s" id))))
17365 (org-columns)
17366 (setq tbl (org-columns-capture-view))
17367 (setq nfields (length (car tbl)))
17368 (org-columns-quit)))
17369 (goto-char pos)
17370 (move-marker pos nil)
17371 (when tbl
17372 (when (plist-get params :hlines)
17373 (setq tmp nil)
17374 (while tbl
17375 (if (eq (car tbl) 'hline)
17376 (push (pop tbl) tmp)
17377 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17378 (if (and (not (eq (car tmp) 'hline))
17379 (or (eq hlines t)
17380 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17381 (push 'hline tmp)))
17382 (push (pop tbl) tmp)))
17383 (setq tbl (nreverse tmp)))
17384 (when vlines
17385 (setq tbl (mapcar (lambda (x)
17386 (if (eq 'hline x) x (cons "" x)))
17387 tbl))
17388 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17389 (setq pos (point))
17390 (insert (org-listtable-to-string tbl))
17391 (when (plist-get params :width)
17392 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17393 org-columns-current-widths "|")))
17394 (goto-char pos)
17395 (org-table-align))))
17397 (defun org-listtable-to-string (tbl)
17398 "Convert a listtable TBL to a string that contains the Org-mode table.
17399 The table still need to be alligned. The resulting string has no leading
17400 and tailing newline characters."
17401 (mapconcat
17402 (lambda (x)
17403 (cond
17404 ((listp x)
17405 (concat "|" (mapconcat 'identity x "|") "|"))
17406 ((eq x 'hline) "|-|")
17407 (t (error "Garbage in listtable: %s" x))))
17408 tbl "\n"))
17410 (defun org-insert-columns-dblock ()
17411 "Create a dynamic block capturing a column view table."
17412 (interactive)
17413 (let ((defaults '(:name "columnview" :hlines 1))
17414 (id (completing-read
17415 "Capture columns (local, global, entry with :ID: property) [local]: "
17416 (append '(("global") ("local"))
17417 (mapcar 'list (org-property-values "ID"))))))
17418 (if (equal id "") (setq id 'local))
17419 (if (equal id "global") (setq id 'global))
17420 (setq defaults (append defaults (list :id id)))
17421 (org-create-dblock defaults)
17422 (org-update-dblock)))
17424 ;;;; Timestamps
17426 (defvar org-last-changed-timestamp nil)
17427 (defvar org-time-was-given) ; dynamically scoped parameter
17428 (defvar org-end-time-was-given) ; dynamically scoped parameter
17429 (defvar org-ts-what) ; dynamically scoped parameter
17431 (defun org-time-stamp (arg)
17432 "Prompt for a date/time and insert a time stamp.
17433 If the user specifies a time like HH:MM, or if this command is called
17434 with a prefix argument, the time stamp will contain date and time.
17435 Otherwise, only the date will be included. All parts of a date not
17436 specified by the user will be filled in from the current date/time.
17437 So if you press just return without typing anything, the time stamp
17438 will represent the current date/time. If there is already a timestamp
17439 at the cursor, it will be modified."
17440 (interactive "P")
17441 (let* ((ts nil)
17442 (default-time
17443 ;; Default time is either today, or, when entering a range,
17444 ;; the range start.
17445 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17446 (save-excursion
17447 (re-search-backward
17448 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17449 (- (point) 20) t)))
17450 (apply 'encode-time (org-parse-time-string (match-string 1)))
17451 (current-time)))
17452 (default-input (and ts (org-get-compact-tod ts)))
17453 org-time-was-given org-end-time-was-given time)
17454 (cond
17455 ((and (org-at-timestamp-p)
17456 (eq last-command 'org-time-stamp)
17457 (eq this-command 'org-time-stamp))
17458 (insert "--")
17459 (setq time (let ((this-command this-command))
17460 (org-read-date arg 'totime nil nil default-time default-input)))
17461 (org-insert-time-stamp time (or org-time-was-given arg)))
17462 ((org-at-timestamp-p)
17463 (setq time (let ((this-command this-command))
17464 (org-read-date arg 'totime nil nil default-time default-input)))
17465 (when (org-at-timestamp-p) ; just to get the match data
17466 (replace-match "")
17467 (setq org-last-changed-timestamp
17468 (org-insert-time-stamp
17469 time (or org-time-was-given arg)
17470 nil nil nil (list org-end-time-was-given))))
17471 (message "Timestamp updated"))
17473 (setq time (let ((this-command this-command))
17474 (org-read-date arg 'totime nil nil default-time default-input)))
17475 (org-insert-time-stamp time (or org-time-was-given arg)
17476 nil nil nil (list org-end-time-was-given))))))
17478 ;; FIXME: can we use this for something else????
17479 ;; like computing time differences?????
17480 (defun org-get-compact-tod (s)
17481 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17482 (let* ((t1 (match-string 1 s))
17483 (h1 (string-to-number (match-string 2 s)))
17484 (m1 (string-to-number (match-string 3 s)))
17485 (t2 (and (match-end 4) (match-string 5 s)))
17486 (h2 (and t2 (string-to-number (match-string 6 s))))
17487 (m2 (and t2 (string-to-number (match-string 7 s))))
17488 dh dm)
17489 (if (not t2)
17491 (setq dh (- h2 h1) dm (- m2 m1))
17492 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17493 (concat t1 "+" (number-to-string dh)
17494 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17496 (defun org-time-stamp-inactive (&optional arg)
17497 "Insert an inactive time stamp.
17498 An inactive time stamp is enclosed in square brackets instead of angle
17499 brackets. It is inactive in the sense that it does not trigger agenda entries,
17500 does not link to the calendar and cannot be changed with the S-cursor keys.
17501 So these are more for recording a certain time/date."
17502 (interactive "P")
17503 (let (org-time-was-given org-end-time-was-given time)
17504 (setq time (org-read-date arg 'totime))
17505 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17506 nil nil (list org-end-time-was-given))))
17508 (defvar org-date-ovl (org-make-overlay 1 1))
17509 (org-overlay-put org-date-ovl 'face 'org-warning)
17510 (org-detach-overlay org-date-ovl)
17512 (defvar org-ans1) ; dynamically scoped parameter
17513 (defvar org-ans2) ; dynamically scoped parameter
17515 (defvar org-plain-time-of-day-regexp) ; defined below
17517 (defvar org-read-date-overlay nil)
17518 (defvar org-dcst nil) ; dynamically scoped
17520 (defun org-read-date (&optional with-time to-time from-string prompt
17521 default-time default-input)
17522 "Read a date, possibly a time, and make things smooth for the user.
17523 The prompt will suggest to enter an ISO date, but you can also enter anything
17524 which will at least partially be understood by `parse-time-string'.
17525 Unrecognized parts of the date will default to the current day, month, year,
17526 hour and minute. If this command is called to replace a timestamp at point,
17527 of to enter the second timestamp of a range, the default time is taken from the
17528 existing stamp. For example,
17529 3-2-5 --> 2003-02-05
17530 feb 15 --> currentyear-02-15
17531 sep 12 9 --> 2009-09-12
17532 12:45 --> today 12:45
17533 22 sept 0:34 --> currentyear-09-22 0:34
17534 12 --> currentyear-currentmonth-12
17535 Fri --> nearest Friday (today or later)
17536 etc.
17538 Furthermore you can specify a relative date by giving, as the *first* thing
17539 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17540 change in days weeks, months, years.
17541 With a single plus or minus, the date is relative to today. With a double
17542 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17543 +4d --> four days from today
17544 +4 --> same as above
17545 +2w --> two weeks from today
17546 ++5 --> five days from default date
17548 The function understands only English month and weekday abbreviations,
17549 but this can be configured with the variables `parse-time-months' and
17550 `parse-time-weekdays'.
17552 While prompting, a calendar is popped up - you can also select the
17553 date with the mouse (button 1). The calendar shows a period of three
17554 months. To scroll it to other months, use the keys `>' and `<'.
17555 If you don't like the calendar, turn it off with
17556 \(setq org-read-date-popup-calendar nil)
17558 With optional argument TO-TIME, the date will immediately be converted
17559 to an internal time.
17560 With an optional argument WITH-TIME, the prompt will suggest to also
17561 insert a time. Note that when WITH-TIME is not set, you can still
17562 enter a time, and this function will inform the calling routine about
17563 this change. The calling routine may then choose to change the format
17564 used to insert the time stamp into the buffer to include the time.
17565 With optional argument FROM-STRING, read from this string instead from
17566 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17567 the time/date that is used for everything that is not specified by the
17568 user."
17569 (require 'parse-time)
17570 (let* ((org-time-stamp-rounding-minutes
17571 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17572 (org-dcst org-display-custom-times)
17573 (ct (org-current-time))
17574 (def (or default-time ct))
17575 (defdecode (decode-time def))
17576 (dummy (progn
17577 (when (< (nth 2 defdecode) org-extend-today-until)
17578 (setcar (nthcdr 2 defdecode) -1)
17579 (setcar (nthcdr 1 defdecode) 59)
17580 (setq def (apply 'encode-time defdecode)
17581 defdecode (decode-time def)))))
17582 (calendar-move-hook nil)
17583 (view-diary-entries-initially nil)
17584 (view-calendar-holidays-initially nil)
17585 (timestr (format-time-string
17586 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17587 (prompt (concat (if prompt (concat prompt " ") "")
17588 (format "Date+time [%s]: " timestr)))
17589 ans (org-ans0 "") org-ans1 org-ans2 final)
17591 (cond
17592 (from-string (setq ans from-string))
17593 (org-read-date-popup-calendar
17594 (save-excursion
17595 (save-window-excursion
17596 (calendar)
17597 (calendar-forward-day (- (time-to-days def)
17598 (calendar-absolute-from-gregorian
17599 (calendar-current-date))))
17600 (org-eval-in-calendar nil t)
17601 (let* ((old-map (current-local-map))
17602 (map (copy-keymap calendar-mode-map))
17603 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17604 (org-defkey map (kbd "RET") 'org-calendar-select)
17605 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17606 'org-calendar-select-mouse)
17607 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17608 'org-calendar-select-mouse)
17609 (org-defkey minibuffer-local-map [(meta shift left)]
17610 (lambda () (interactive)
17611 (org-eval-in-calendar '(calendar-backward-month 1))))
17612 (org-defkey minibuffer-local-map [(meta shift right)]
17613 (lambda () (interactive)
17614 (org-eval-in-calendar '(calendar-forward-month 1))))
17615 (org-defkey minibuffer-local-map [(meta shift up)]
17616 (lambda () (interactive)
17617 (org-eval-in-calendar '(calendar-backward-year 1))))
17618 (org-defkey minibuffer-local-map [(meta shift down)]
17619 (lambda () (interactive)
17620 (org-eval-in-calendar '(calendar-forward-year 1))))
17621 (org-defkey minibuffer-local-map [(shift up)]
17622 (lambda () (interactive)
17623 (org-eval-in-calendar '(calendar-backward-week 1))))
17624 (org-defkey minibuffer-local-map [(shift down)]
17625 (lambda () (interactive)
17626 (org-eval-in-calendar '(calendar-forward-week 1))))
17627 (org-defkey minibuffer-local-map [(shift left)]
17628 (lambda () (interactive)
17629 (org-eval-in-calendar '(calendar-backward-day 1))))
17630 (org-defkey minibuffer-local-map [(shift right)]
17631 (lambda () (interactive)
17632 (org-eval-in-calendar '(calendar-forward-day 1))))
17633 (org-defkey minibuffer-local-map ">"
17634 (lambda () (interactive)
17635 (org-eval-in-calendar '(scroll-calendar-left 1))))
17636 (org-defkey minibuffer-local-map "<"
17637 (lambda () (interactive)
17638 (org-eval-in-calendar '(scroll-calendar-right 1))))
17639 (unwind-protect
17640 (progn
17641 (use-local-map map)
17642 (add-hook 'post-command-hook 'org-read-date-display)
17643 (setq org-ans0 (read-string prompt default-input nil nil))
17644 ;; org-ans0: from prompt
17645 ;; org-ans1: from mouse click
17646 ;; org-ans2: from calendar motion
17647 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17648 (remove-hook 'post-command-hook 'org-read-date-display)
17649 (use-local-map old-map)
17650 (when org-read-date-overlay
17651 (org-delete-overlay org-read-date-overlay)
17652 (setq org-read-date-overlay nil)))))))
17654 (t ; Naked prompt only
17655 (unwind-protect
17656 (setq ans (read-string prompt default-input nil timestr))
17657 (when org-read-date-overlay
17658 (org-delete-overlay org-read-date-overlay)
17659 (setq org-read-date-overlay nil)))))
17661 (setq final (org-read-date-analyze ans def defdecode))
17663 (if to-time
17664 (apply 'encode-time final)
17665 (if (and (boundp 'org-time-was-given) org-time-was-given)
17666 (format "%04d-%02d-%02d %02d:%02d"
17667 (nth 5 final) (nth 4 final) (nth 3 final)
17668 (nth 2 final) (nth 1 final))
17669 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17670 (defvar def)
17671 (defvar defdecode)
17672 (defvar with-time)
17673 (defun org-read-date-display ()
17674 "Display the currrent date prompt interpretation in the minibuffer."
17675 (when org-read-date-display-live
17676 (when org-read-date-overlay
17677 (org-delete-overlay org-read-date-overlay))
17678 (let ((p (point)))
17679 (end-of-line 1)
17680 (while (not (equal (buffer-substring
17681 (max (point-min) (- (point) 4)) (point))
17682 " "))
17683 (insert " "))
17684 (goto-char p))
17685 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17686 " " (or org-ans1 org-ans2)))
17687 (org-end-time-was-given nil)
17688 (f (org-read-date-analyze ans def defdecode))
17689 (fmts (if org-dcst
17690 org-time-stamp-custom-formats
17691 org-time-stamp-formats))
17692 (fmt (if (or with-time
17693 (and (boundp 'org-time-was-given) org-time-was-given))
17694 (cdr fmts)
17695 (car fmts)))
17696 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17697 (when (and org-end-time-was-given
17698 (string-match org-plain-time-of-day-regexp txt))
17699 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17700 org-end-time-was-given
17701 (substring txt (match-end 0)))))
17702 (setq org-read-date-overlay
17703 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17704 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17706 (defun org-read-date-analyze (ans def defdecode)
17707 "Analyze the combined answer of the date prompt."
17708 ;; FIXME: cleanup and comment
17709 (let (delta deltan deltaw deltadef year month day
17710 hour minute second wday pm h2 m2 tl wday1)
17712 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17713 (setq ans (replace-match "" t t ans)
17714 deltan (car delta)
17715 deltaw (nth 1 delta)
17716 deltadef (nth 2 delta)))
17718 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17719 (when (string-match
17720 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17721 (setq year (if (match-end 2)
17722 (string-to-number (match-string 2 ans))
17723 (string-to-number (format-time-string "%Y")))
17724 month (string-to-number (match-string 3 ans))
17725 day (string-to-number (match-string 4 ans)))
17726 (if (< year 100) (setq year (+ 2000 year)))
17727 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17728 t nil ans)))
17729 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17730 ;; If there is a time with am/pm, and *no* time without it, we convert
17731 ;; so that matching will be successful.
17732 (loop for i from 1 to 2 do ; twice, for end time as well
17733 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17734 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17735 (setq hour (string-to-number (match-string 1 ans))
17736 minute (if (match-end 3)
17737 (string-to-number (match-string 3 ans))
17739 pm (equal ?p
17740 (string-to-char (downcase (match-string 4 ans)))))
17741 (if (and (= hour 12) (not pm))
17742 (setq hour 0)
17743 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17744 (setq ans (replace-match (format "%02d:%02d" hour minute)
17745 t t ans))))
17747 ;; Check if a time range is given as a duration
17748 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17749 (setq hour (string-to-number (match-string 1 ans))
17750 h2 (+ hour (string-to-number (match-string 3 ans)))
17751 minute (string-to-number (match-string 2 ans))
17752 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17753 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17754 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17756 ;; Check if there is a time range
17757 (when (boundp 'org-end-time-was-given)
17758 (setq org-time-was-given nil)
17759 (when (and (string-match org-plain-time-of-day-regexp ans)
17760 (match-end 8))
17761 (setq org-end-time-was-given (match-string 8 ans))
17762 (setq ans (concat (substring ans 0 (match-beginning 7))
17763 (substring ans (match-end 7))))))
17765 (setq tl (parse-time-string ans)
17766 day (or (nth 3 tl) (nth 3 defdecode))
17767 month (or (nth 4 tl)
17768 (if (and org-read-date-prefer-future
17769 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17770 (1+ (nth 4 defdecode))
17771 (nth 4 defdecode)))
17772 year (or (nth 5 tl)
17773 (if (and org-read-date-prefer-future
17774 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17775 (1+ (nth 5 defdecode))
17776 (nth 5 defdecode)))
17777 hour (or (nth 2 tl) (nth 2 defdecode))
17778 minute (or (nth 1 tl) (nth 1 defdecode))
17779 second (or (nth 0 tl) 0)
17780 wday (nth 6 tl))
17781 (when deltan
17782 (unless deltadef
17783 (let ((now (decode-time (current-time))))
17784 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17785 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17786 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17787 ((equal deltaw "m") (setq month (+ month deltan)))
17788 ((equal deltaw "y") (setq year (+ year deltan)))))
17789 (when (and wday (not (nth 3 tl)))
17790 ;; Weekday was given, but no day, so pick that day in the week
17791 ;; on or after the derived date.
17792 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17793 (unless (equal wday wday1)
17794 (setq day (+ day (% (- wday wday1 -7) 7)))))
17795 (if (and (boundp 'org-time-was-given)
17796 (nth 2 tl))
17797 (setq org-time-was-given t))
17798 (if (< year 100) (setq year (+ 2000 year)))
17799 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17800 (list second minute hour day month year)))
17802 (defvar parse-time-weekdays)
17804 (defun org-read-date-get-relative (s today default)
17805 "Check string S for special relative date string.
17806 TODAY and DEFAULT are internal times, for today and for a default.
17807 Return shift list (N what def-flag)
17808 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17809 N is the number of WHATs to shift.
17810 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17811 the DEFAULT date rather than TODAY."
17812 (when (string-match
17813 (concat
17814 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17815 "\\([0-9]+\\)?"
17816 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17817 "\\([ \t]\\|$\\)") s)
17818 (let* ((dir (if (match-end 1)
17819 (string-to-char (substring (match-string 1 s) -1))
17820 ?+))
17821 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17822 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17823 (what (if (match-end 3) (match-string 3 s) "d"))
17824 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17825 (date (if rel default today))
17826 (wday (nth 6 (decode-time date)))
17827 delta)
17828 (if wday1
17829 (progn
17830 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17831 (if (= dir ?-) (setq delta (- delta 7)))
17832 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17833 (list delta "d" rel))
17834 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17836 (defun org-eval-in-calendar (form &optional keepdate)
17837 "Eval FORM in the calendar window and return to current window.
17838 Also, store the cursor date in variable org-ans2."
17839 (let ((sw (selected-window)))
17840 (select-window (get-buffer-window "*Calendar*"))
17841 (eval form)
17842 (when (and (not keepdate) (calendar-cursor-to-date))
17843 (let* ((date (calendar-cursor-to-date))
17844 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17845 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17846 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17847 (select-window sw)))
17849 ; ;; Update the prompt to show new default date
17850 ; (save-excursion
17851 ; (goto-char (point-min))
17852 ; (when (and org-ans2
17853 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17854 ; (get-text-property (match-end 0) 'field))
17855 ; (let ((inhibit-read-only t))
17856 ; (replace-match (concat "[" org-ans2 "]") t t)
17857 ; (add-text-properties (point-min) (1+ (match-end 0))
17858 ; (text-properties-at (1+ (point-min)))))))))
17860 (defun org-calendar-select ()
17861 "Return to `org-read-date' with the date currently selected.
17862 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17863 (interactive)
17864 (when (calendar-cursor-to-date)
17865 (let* ((date (calendar-cursor-to-date))
17866 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17867 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17868 (if (active-minibuffer-window) (exit-minibuffer))))
17870 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17871 "Insert a date stamp for the date given by the internal TIME.
17872 WITH-HM means, use the stamp format that includes the time of the day.
17873 INACTIVE means use square brackets instead of angular ones, so that the
17874 stamp will not contribute to the agenda.
17875 PRE and POST are optional strings to be inserted before and after the
17876 stamp.
17877 The command returns the inserted time stamp."
17878 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17879 stamp)
17880 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17881 (insert-before-markers (or pre ""))
17882 (insert-before-markers (setq stamp (format-time-string fmt time)))
17883 (when (listp extra)
17884 (setq extra (car extra))
17885 (if (and (stringp extra)
17886 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17887 (setq extra (format "-%02d:%02d"
17888 (string-to-number (match-string 1 extra))
17889 (string-to-number (match-string 2 extra))))
17890 (setq extra nil)))
17891 (when extra
17892 (backward-char 1)
17893 (insert-before-markers extra)
17894 (forward-char 1))
17895 (insert-before-markers (or post ""))
17896 stamp))
17898 (defun org-toggle-time-stamp-overlays ()
17899 "Toggle the use of custom time stamp formats."
17900 (interactive)
17901 (setq org-display-custom-times (not org-display-custom-times))
17902 (unless org-display-custom-times
17903 (let ((p (point-min)) (bmp (buffer-modified-p)))
17904 (while (setq p (next-single-property-change p 'display))
17905 (if (and (get-text-property p 'display)
17906 (eq (get-text-property p 'face) 'org-date))
17907 (remove-text-properties
17908 p (setq p (next-single-property-change p 'display))
17909 '(display t))))
17910 (set-buffer-modified-p bmp)))
17911 (if (featurep 'xemacs)
17912 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17913 (org-restart-font-lock)
17914 (setq org-table-may-need-update t)
17915 (if org-display-custom-times
17916 (message "Time stamps are overlayed with custom format")
17917 (message "Time stamp overlays removed")))
17919 (defun org-display-custom-time (beg end)
17920 "Overlay modified time stamp format over timestamp between BED and END."
17921 (let* ((ts (buffer-substring beg end))
17922 t1 w1 with-hm tf time str w2 (off 0))
17923 (save-match-data
17924 (setq t1 (org-parse-time-string ts t))
17925 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17926 (setq off (- (match-end 0) (match-beginning 0)))))
17927 (setq end (- end off))
17928 (setq w1 (- end beg)
17929 with-hm (and (nth 1 t1) (nth 2 t1))
17930 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17931 time (org-fix-decoded-time t1)
17932 str (org-add-props
17933 (format-time-string
17934 (substring tf 1 -1) (apply 'encode-time time))
17935 nil 'mouse-face 'highlight)
17936 w2 (length str))
17937 (if (not (= w2 w1))
17938 (add-text-properties (1+ beg) (+ 2 beg)
17939 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17940 (if (featurep 'xemacs)
17941 (progn
17942 (put-text-property beg end 'invisible t)
17943 (put-text-property beg end 'end-glyph (make-glyph str)))
17944 (put-text-property beg end 'display str))))
17946 (defun org-translate-time (string)
17947 "Translate all timestamps in STRING to custom format.
17948 But do this only if the variable `org-display-custom-times' is set."
17949 (when org-display-custom-times
17950 (save-match-data
17951 (let* ((start 0)
17952 (re org-ts-regexp-both)
17953 t1 with-hm inactive tf time str beg end)
17954 (while (setq start (string-match re string start))
17955 (setq beg (match-beginning 0)
17956 end (match-end 0)
17957 t1 (save-match-data
17958 (org-parse-time-string (substring string beg end) t))
17959 with-hm (and (nth 1 t1) (nth 2 t1))
17960 inactive (equal (substring string beg (1+ beg)) "[")
17961 tf (funcall (if with-hm 'cdr 'car)
17962 org-time-stamp-custom-formats)
17963 time (org-fix-decoded-time t1)
17964 str (format-time-string
17965 (concat
17966 (if inactive "[" "<") (substring tf 1 -1)
17967 (if inactive "]" ">"))
17968 (apply 'encode-time time))
17969 string (replace-match str t t string)
17970 start (+ start (length str)))))))
17971 string)
17973 (defun org-fix-decoded-time (time)
17974 "Set 0 instead of nil for the first 6 elements of time.
17975 Don't touch the rest."
17976 (let ((n 0))
17977 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17979 (defun org-days-to-time (timestamp-string)
17980 "Difference between TIMESTAMP-STRING and now in days."
17981 (- (time-to-days (org-time-string-to-time timestamp-string))
17982 (time-to-days (current-time))))
17984 (defun org-deadline-close (timestamp-string &optional ndays)
17985 "Is the time in TIMESTAMP-STRING close to the current date?"
17986 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17987 (and (< (org-days-to-time timestamp-string) ndays)
17988 (not (org-entry-is-done-p))))
17990 (defun org-get-wdays (ts)
17991 "Get the deadline lead time appropriate for timestring TS."
17992 (cond
17993 ((<= org-deadline-warning-days 0)
17994 ;; 0 or negative, enforce this value no matter what
17995 (- org-deadline-warning-days))
17996 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17997 ;; lead time is specified.
17998 (floor (* (string-to-number (match-string 1 ts))
17999 (cdr (assoc (match-string 2 ts)
18000 '(("d" . 1) ("w" . 7)
18001 ("m" . 30.4) ("y" . 365.25)))))))
18002 ;; go for the default.
18003 (t org-deadline-warning-days)))
18005 (defun org-calendar-select-mouse (ev)
18006 "Return to `org-read-date' with the date currently selected.
18007 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18008 (interactive "e")
18009 (mouse-set-point ev)
18010 (when (calendar-cursor-to-date)
18011 (let* ((date (calendar-cursor-to-date))
18012 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18013 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18014 (if (active-minibuffer-window) (exit-minibuffer))))
18016 (defun org-check-deadlines (ndays)
18017 "Check if there are any deadlines due or past due.
18018 A deadline is considered due if it happens within `org-deadline-warning-days'
18019 days from today's date. If the deadline appears in an entry marked DONE,
18020 it is not shown. The prefix arg NDAYS can be used to test that many
18021 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18022 (interactive "P")
18023 (let* ((org-warn-days
18024 (cond
18025 ((equal ndays '(4)) 100000)
18026 (ndays (prefix-numeric-value ndays))
18027 (t (abs org-deadline-warning-days))))
18028 (case-fold-search nil)
18029 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18030 (callback
18031 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18033 (message "%d deadlines past-due or due within %d days"
18034 (org-occur regexp nil callback)
18035 org-warn-days)))
18037 (defun org-check-before-date (date)
18038 "Check if there are deadlines or scheduled entries before DATE."
18039 (interactive (list (org-read-date)))
18040 (let ((case-fold-search nil)
18041 (regexp (concat "\\<\\(" org-deadline-string
18042 "\\|" org-scheduled-string
18043 "\\) *<\\([^>]+\\)>"))
18044 (callback
18045 (lambda () (time-less-p
18046 (org-time-string-to-time (match-string 2))
18047 (org-time-string-to-time date)))))
18048 (message "%d entries before %s"
18049 (org-occur regexp nil callback) date)))
18051 (defun org-evaluate-time-range (&optional to-buffer)
18052 "Evaluate a time range by computing the difference between start and end.
18053 Normally the result is just printed in the echo area, but with prefix arg
18054 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18055 If the time range is actually in a table, the result is inserted into the
18056 next column.
18057 For time difference computation, a year is assumed to be exactly 365
18058 days in order to avoid rounding problems."
18059 (interactive "P")
18061 (org-clock-update-time-maybe)
18062 (save-excursion
18063 (unless (org-at-date-range-p t)
18064 (goto-char (point-at-bol))
18065 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18066 (if (not (org-at-date-range-p t))
18067 (error "Not at a time-stamp range, and none found in current line")))
18068 (let* ((ts1 (match-string 1))
18069 (ts2 (match-string 2))
18070 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18071 (match-end (match-end 0))
18072 (time1 (org-time-string-to-time ts1))
18073 (time2 (org-time-string-to-time ts2))
18074 (t1 (time-to-seconds time1))
18075 (t2 (time-to-seconds time2))
18076 (diff (abs (- t2 t1)))
18077 (negative (< (- t2 t1) 0))
18078 ;; (ys (floor (* 365 24 60 60)))
18079 (ds (* 24 60 60))
18080 (hs (* 60 60))
18081 (fy "%dy %dd %02d:%02d")
18082 (fy1 "%dy %dd")
18083 (fd "%dd %02d:%02d")
18084 (fd1 "%dd")
18085 (fh "%02d:%02d")
18086 y d h m align)
18087 (if havetime
18088 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18090 d (floor (/ diff ds)) diff (mod diff ds)
18091 h (floor (/ diff hs)) diff (mod diff hs)
18092 m (floor (/ diff 60)))
18093 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18095 d (floor (+ (/ diff ds) 0.5))
18096 h 0 m 0))
18097 (if (not to-buffer)
18098 (message "%s" (org-make-tdiff-string y d h m))
18099 (if (org-at-table-p)
18100 (progn
18101 (goto-char match-end)
18102 (setq align t)
18103 (and (looking-at " *|") (goto-char (match-end 0))))
18104 (goto-char match-end))
18105 (if (looking-at
18106 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18107 (replace-match ""))
18108 (if negative (insert " -"))
18109 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18110 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18111 (insert " " (format fh h m))))
18112 (if align (org-table-align))
18113 (message "Time difference inserted")))))
18115 (defun org-make-tdiff-string (y d h m)
18116 (let ((fmt "")
18117 (l nil))
18118 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18119 l (push y l)))
18120 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18121 l (push d l)))
18122 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18123 l (push h l)))
18124 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18125 l (push m l)))
18126 (apply 'format fmt (nreverse l))))
18128 (defun org-time-string-to-time (s)
18129 (apply 'encode-time (org-parse-time-string s)))
18131 (defun org-time-string-to-absolute (s &optional daynr prefer)
18132 "Convert a time stamp to an absolute day number.
18133 If there is a specifyer for a cyclic time stamp, get the closest date to
18134 DAYNR."
18135 (cond
18136 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18137 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18138 daynr
18139 (+ daynr 1000)))
18140 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18141 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18142 (time-to-days (current-time))) (match-string 0 s)
18143 prefer))
18144 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18146 (defun org-time-from-absolute (d)
18147 "Return the time corresponding to date D.
18148 D may be an absolute day number, or a calendar-type list (month day year)."
18149 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18150 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18152 (defun org-calendar-holiday ()
18153 "List of holidays, for Diary display in Org-mode."
18154 (require 'holidays)
18155 (let ((hl (funcall
18156 (if (fboundp 'calendar-check-holidays)
18157 'calendar-check-holidays 'check-calendar-holidays) date)))
18158 (if hl (mapconcat 'identity hl "; "))))
18160 (defun org-diary-sexp-entry (sexp entry date)
18161 "Process a SEXP diary ENTRY for DATE."
18162 (require 'diary-lib)
18163 (let ((result (if calendar-debug-sexp
18164 (let ((stack-trace-on-error t))
18165 (eval (car (read-from-string sexp))))
18166 (condition-case nil
18167 (eval (car (read-from-string sexp)))
18168 (error
18169 (beep)
18170 (message "Bad sexp at line %d in %s: %s"
18171 (org-current-line)
18172 (buffer-file-name) sexp)
18173 (sleep-for 2))))))
18174 (cond ((stringp result) result)
18175 ((and (consp result)
18176 (stringp (cdr result))) (cdr result))
18177 (result entry)
18178 (t nil))))
18180 (defun org-diary-to-ical-string (frombuf)
18181 "Get iCalendar entries from diary entries in buffer FROMBUF.
18182 This uses the icalendar.el library."
18183 (let* ((tmpdir (if (featurep 'xemacs)
18184 (temp-directory)
18185 temporary-file-directory))
18186 (tmpfile (make-temp-name
18187 (expand-file-name "orgics" tmpdir)))
18188 buf rtn b e)
18189 (save-excursion
18190 (set-buffer frombuf)
18191 (icalendar-export-region (point-min) (point-max) tmpfile)
18192 (setq buf (find-buffer-visiting tmpfile))
18193 (set-buffer buf)
18194 (goto-char (point-min))
18195 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18196 (setq b (match-beginning 0)))
18197 (goto-char (point-max))
18198 (if (re-search-backward "^END:VEVENT" nil t)
18199 (setq e (match-end 0)))
18200 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18201 (kill-buffer buf)
18202 (kill-buffer frombuf)
18203 (delete-file tmpfile)
18204 rtn))
18206 (defun org-closest-date (start current change prefer)
18207 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18208 When PREFER is `past' return a date that is either CURRENT or past.
18209 When PREFER is `future', return a date that is either CURRENT or future."
18210 ;; Make the proper lists from the dates
18211 (catch 'exit
18212 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18213 dn dw sday cday n1 n2
18214 d m y y1 y2 date1 date2 nmonths nm ny m2)
18216 (setq start (org-date-to-gregorian start)
18217 current (org-date-to-gregorian
18218 (if org-agenda-repeating-timestamp-show-all
18219 current
18220 (time-to-days (current-time))))
18221 sday (calendar-absolute-from-gregorian start)
18222 cday (calendar-absolute-from-gregorian current))
18224 (if (<= cday sday) (throw 'exit sday))
18226 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18227 (setq dn (string-to-number (match-string 1 change))
18228 dw (cdr (assoc (match-string 2 change) a1)))
18229 (error "Invalid change specifyer: %s" change))
18230 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18231 (cond
18232 ((eq dw 'day)
18233 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18234 n2 (+ n1 dn)))
18235 ((eq dw 'year)
18236 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18237 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18238 (setq date1 (list m d y1)
18239 n1 (calendar-absolute-from-gregorian date1)
18240 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18241 n2 (calendar-absolute-from-gregorian date2)))
18242 ((eq dw 'month)
18243 ;; approx number of month between the tow dates
18244 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18245 ;; How often does dn fit in there?
18246 (setq d (nth 1 start) m (car start) y (nth 2 start)
18247 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18248 m (+ m nm)
18249 ny (floor (/ m 12))
18250 y (+ y ny)
18251 m (- m (* ny 12)))
18252 (while (> m 12) (setq m (- m 12) y (1+ y)))
18253 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18254 (setq m2 (+ m dn) y2 y)
18255 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18256 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18257 (while (< n2 cday)
18258 (setq n1 n2 m m2 y y2)
18259 (setq m2 (+ m dn) y2 y)
18260 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18261 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18263 (if org-agenda-repeating-timestamp-show-all
18264 (cond
18265 ((eq prefer 'past) n1)
18266 ((eq prefer 'future) (if (= cday n1) n1 n2))
18267 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18268 (cond
18269 ((eq prefer 'past) n1)
18270 ((eq prefer 'future) (if (= cday n1) n1 n2))
18271 (t (if (= cday n1) n1 n2)))))))
18273 (defun org-date-to-gregorian (date)
18274 "Turn any specification of DATE into a gregorian date for the calendar."
18275 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18276 ((and (listp date) (= (length date) 3)) date)
18277 ((stringp date)
18278 (setq date (org-parse-time-string date))
18279 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18280 ((listp date)
18281 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18283 (defun org-parse-time-string (s &optional nodefault)
18284 "Parse the standard Org-mode time string.
18285 This should be a lot faster than the normal `parse-time-string'.
18286 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18287 hour and minute fields will be nil if not given."
18288 (if (string-match org-ts-regexp0 s)
18289 (list 0
18290 (if (or (match-beginning 8) (not nodefault))
18291 (string-to-number (or (match-string 8 s) "0")))
18292 (if (or (match-beginning 7) (not nodefault))
18293 (string-to-number (or (match-string 7 s) "0")))
18294 (string-to-number (match-string 4 s))
18295 (string-to-number (match-string 3 s))
18296 (string-to-number (match-string 2 s))
18297 nil nil nil)
18298 (make-list 9 0)))
18300 (defun org-timestamp-up (&optional arg)
18301 "Increase the date item at the cursor by one.
18302 If the cursor is on the year, change the year. If it is on the month or
18303 the day, change that.
18304 With prefix ARG, change by that many units."
18305 (interactive "p")
18306 (org-timestamp-change (prefix-numeric-value arg)))
18308 (defun org-timestamp-down (&optional arg)
18309 "Decrease the date item at the cursor by one.
18310 If the cursor is on the year, change the year. If it is on the month or
18311 the day, change that.
18312 With prefix ARG, change by that many units."
18313 (interactive "p")
18314 (org-timestamp-change (- (prefix-numeric-value arg))))
18316 (defun org-timestamp-up-day (&optional arg)
18317 "Increase the date in the time stamp by one day.
18318 With prefix ARG, change that many days."
18319 (interactive "p")
18320 (if (and (not (org-at-timestamp-p t))
18321 (org-on-heading-p))
18322 (org-todo 'up)
18323 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18325 (defun org-timestamp-down-day (&optional arg)
18326 "Decrease the date in the time stamp by one day.
18327 With prefix ARG, change that many days."
18328 (interactive "p")
18329 (if (and (not (org-at-timestamp-p t))
18330 (org-on-heading-p))
18331 (org-todo 'down)
18332 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18334 (defsubst org-pos-in-match-range (pos n)
18335 (and (match-beginning n)
18336 (<= (match-beginning n) pos)
18337 (>= (match-end n) pos)))
18339 (defun org-at-timestamp-p (&optional inactive-ok)
18340 "Determine if the cursor is in or at a timestamp."
18341 (interactive)
18342 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18343 (pos (point))
18344 (ans (or (looking-at tsr)
18345 (save-excursion
18346 (skip-chars-backward "^[<\n\r\t")
18347 (if (> (point) (point-min)) (backward-char 1))
18348 (and (looking-at tsr)
18349 (> (- (match-end 0) pos) -1))))))
18350 (and ans
18351 (boundp 'org-ts-what)
18352 (setq org-ts-what
18353 (cond
18354 ((= pos (match-beginning 0)) 'bracket)
18355 ((= pos (1- (match-end 0))) 'bracket)
18356 ((org-pos-in-match-range pos 2) 'year)
18357 ((org-pos-in-match-range pos 3) 'month)
18358 ((org-pos-in-match-range pos 7) 'hour)
18359 ((org-pos-in-match-range pos 8) 'minute)
18360 ((or (org-pos-in-match-range pos 4)
18361 (org-pos-in-match-range pos 5)) 'day)
18362 ((and (> pos (or (match-end 8) (match-end 5)))
18363 (< pos (match-end 0)))
18364 (- pos (or (match-end 8) (match-end 5))))
18365 (t 'day))))
18366 ans))
18368 (defun org-toggle-timestamp-type ()
18370 (interactive)
18371 (when (org-at-timestamp-p t)
18372 (save-excursion
18373 (goto-char (match-beginning 0))
18374 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18375 (goto-char (1- (match-end 0)))
18376 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18377 (message "Timestamp is now %sactive"
18378 (if (equal (char-before) ?>) "in" ""))))
18380 (defun org-timestamp-change (n &optional what)
18381 "Change the date in the time stamp at point.
18382 The date will be changed by N times WHAT. WHAT can be `day', `month',
18383 `year', `minute', `second'. If WHAT is not given, the cursor position
18384 in the timestamp determines what will be changed."
18385 (let ((pos (point))
18386 with-hm inactive
18387 org-ts-what
18388 extra
18389 ts time time0)
18390 (if (not (org-at-timestamp-p t))
18391 (error "Not at a timestamp"))
18392 (if (and (not what) (eq org-ts-what 'bracket))
18393 (org-toggle-timestamp-type)
18394 (if (and (not what) (not (eq org-ts-what 'day))
18395 org-display-custom-times
18396 (get-text-property (point) 'display)
18397 (not (get-text-property (1- (point)) 'display)))
18398 (setq org-ts-what 'day))
18399 (setq org-ts-what (or what org-ts-what)
18400 inactive (= (char-after (match-beginning 0)) ?\[)
18401 ts (match-string 0))
18402 (replace-match "")
18403 (if (string-match
18404 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18406 (setq extra (match-string 1 ts)))
18407 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18408 (setq with-hm t))
18409 (setq time0 (org-parse-time-string ts))
18410 (setq time
18411 (encode-time (or (car time0) 0)
18412 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18413 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18414 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18415 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18416 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18417 (nthcdr 6 time0)))
18418 (when (integerp org-ts-what)
18419 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18420 (if (eq what 'calendar)
18421 (let ((cal-date (org-get-date-from-calendar)))
18422 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18423 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18424 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18425 (setcar time0 (or (car time0) 0))
18426 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18427 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18428 (setq time (apply 'encode-time time0))))
18429 (setq org-last-changed-timestamp
18430 (org-insert-time-stamp time with-hm inactive nil nil extra))
18431 (org-clock-update-time-maybe)
18432 (goto-char pos)
18433 ;; Try to recenter the calendar window, if any
18434 (if (and org-calendar-follow-timestamp-change
18435 (get-buffer-window "*Calendar*" t)
18436 (memq org-ts-what '(day month year)))
18437 (org-recenter-calendar (time-to-days time))))))
18439 ;; FIXME: does not yet work for lead times
18440 (defun org-modify-ts-extra (s pos n)
18441 "Change the different parts of the lead-time and repeat fields in timestamp."
18442 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18443 ng h m new)
18444 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18445 (cond
18446 ((or (org-pos-in-match-range pos 2)
18447 (org-pos-in-match-range pos 3))
18448 (setq m (string-to-number (match-string 3 s))
18449 h (string-to-number (match-string 2 s)))
18450 (if (org-pos-in-match-range pos 2)
18451 (setq h (+ h n))
18452 (setq m (+ m n)))
18453 (if (< m 0) (setq m (+ m 60) h (1- h)))
18454 (if (> m 59) (setq m (- m 60) h (1+ h)))
18455 (setq h (min 24 (max 0 h)))
18456 (setq ng 1 new (format "-%02d:%02d" h m)))
18457 ((org-pos-in-match-range pos 6)
18458 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18459 ((org-pos-in-match-range pos 5)
18460 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18462 (when ng
18463 (setq s (concat
18464 (substring s 0 (match-beginning ng))
18466 (substring s (match-end ng))))))
18469 (defun org-recenter-calendar (date)
18470 "If the calendar is visible, recenter it to DATE."
18471 (let* ((win (selected-window))
18472 (cwin (get-buffer-window "*Calendar*" t))
18473 (calendar-move-hook nil))
18474 (when cwin
18475 (select-window cwin)
18476 (calendar-goto-date (if (listp date) date
18477 (calendar-gregorian-from-absolute date)))
18478 (select-window win))))
18480 (defun org-goto-calendar (&optional arg)
18481 "Go to the Emacs calendar at the current date.
18482 If there is a time stamp in the current line, go to that date.
18483 A prefix ARG can be used to force the current date."
18484 (interactive "P")
18485 (let ((tsr org-ts-regexp) diff
18486 (calendar-move-hook nil)
18487 (view-calendar-holidays-initially nil)
18488 (view-diary-entries-initially nil))
18489 (if (or (org-at-timestamp-p)
18490 (save-excursion
18491 (beginning-of-line 1)
18492 (looking-at (concat ".*" tsr))))
18493 (let ((d1 (time-to-days (current-time)))
18494 (d2 (time-to-days
18495 (org-time-string-to-time (match-string 1)))))
18496 (setq diff (- d2 d1))))
18497 (calendar)
18498 (calendar-goto-today)
18499 (if (and diff (not arg)) (calendar-forward-day diff))))
18501 (defun org-get-date-from-calendar ()
18502 "Return a list (month day year) of date at point in calendar."
18503 (with-current-buffer "*Calendar*"
18504 (save-match-data
18505 (calendar-cursor-to-date))))
18507 (defun org-date-from-calendar ()
18508 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18509 If there is already a time stamp at the cursor position, update it."
18510 (interactive)
18511 (if (org-at-timestamp-p t)
18512 (org-timestamp-change 0 'calendar)
18513 (let ((cal-date (org-get-date-from-calendar)))
18514 (org-insert-time-stamp
18515 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18517 ;; Make appt aware of appointments from the agenda
18518 ;;;###autoload
18519 (defun org-agenda-to-appt (&optional filter)
18520 "Activate appointments found in `org-agenda-files'.
18521 When prefixed, prompt for a regular expression and use it as a
18522 filter: only add entries if they match this regular expression.
18524 FILTER can be a string. In this case, use this string as a
18525 regular expression to filter results.
18527 FILTER can also be an alist, with the car of each cell being
18528 either 'headline or 'category. For example:
18530 '((headline \"IMPORTANT\")
18531 (category \"Work\"))
18533 will only add headlines containing IMPORTANT or headlines
18534 belonging to the category \"Work\"."
18535 (interactive "P")
18536 (require 'calendar)
18537 (if (equal filter '(4))
18538 (setq filter (read-from-minibuffer "Regexp filter: ")))
18539 (let* ((cnt 0) ; count added events
18540 (org-agenda-new-buffers nil)
18541 (today (org-date-to-gregorian
18542 (time-to-days (current-time))))
18543 (files (org-agenda-files)) entries file)
18544 ;; Get all entries which may contain an appt
18545 (while (setq file (pop files))
18546 (setq entries
18547 (append entries
18548 (org-agenda-get-day-entries
18549 file today
18550 :timestamp :scheduled :deadline))))
18551 (setq entries (delq nil entries))
18552 ;; Map thru entries and find if they pass thru the filter
18553 (mapc
18554 (lambda(x)
18555 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18556 (cat (get-text-property 1 'org-category x))
18557 (tod (get-text-property 1 'time-of-day x))
18558 (ok (or (null filter)
18559 (and (stringp filter) (string-match filter evt))
18560 (and (listp filter)
18561 (or (string-match
18562 (cadr (assoc 'category filter)) cat)
18563 (string-match
18564 (cadr (assoc 'headline filter)) evt))))))
18565 ;; FIXME: Shall we remove text-properties for the appt text?
18566 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18567 (when (and ok tod)
18568 (setq tod (number-to-string tod)
18569 tod (when (string-match
18570 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18571 (concat (match-string 1 tod) ":"
18572 (match-string 2 tod))))
18573 (appt-add tod evt)
18574 (setq cnt (1+ cnt))))) entries)
18575 (org-release-buffers org-agenda-new-buffers)
18576 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
18578 ;;; The clock for measuring work time.
18580 (defvar org-mode-line-string "")
18581 (put 'org-mode-line-string 'risky-local-variable t)
18583 (defvar org-mode-line-timer nil)
18584 (defvar org-clock-heading "")
18585 (defvar org-clock-start-time "")
18587 (defun org-update-mode-line ()
18588 (let* ((delta (- (time-to-seconds (current-time))
18589 (time-to-seconds org-clock-start-time)))
18590 (h (floor delta 3600))
18591 (m (floor (- delta (* 3600 h)) 60)))
18592 (setq org-mode-line-string
18593 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18594 'help-echo "Org-mode clock is running"))
18595 (force-mode-line-update)))
18597 (defvar org-clock-marker (make-marker)
18598 "Marker recording the last clock-in.")
18599 (defvar org-clock-mode-line-entry nil
18600 "Information for the modeline about the running clock.")
18602 (defun org-clock-in ()
18603 "Start the clock on the current item.
18604 If necessary, clock-out of the currently active clock."
18605 (interactive)
18606 (org-clock-out t)
18607 (let (ts)
18608 (save-excursion
18609 (org-back-to-heading t)
18610 (when (and org-clock-in-switch-to-state
18611 (not (looking-at (concat outline-regexp "[ \t]*"
18612 org-clock-in-switch-to-state
18613 "\\>"))))
18614 (org-todo org-clock-in-switch-to-state))
18615 (if (and org-clock-heading-function
18616 (functionp org-clock-heading-function))
18617 (setq org-clock-heading (funcall org-clock-heading-function))
18618 (if (looking-at org-complex-heading-regexp)
18619 (setq org-clock-heading (match-string 4))
18620 (setq org-clock-heading "???")))
18621 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18622 (org-clock-find-position)
18624 (insert "\n") (backward-char 1)
18625 (indent-relative)
18626 (insert org-clock-string " ")
18627 (setq org-clock-start-time (current-time))
18628 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18629 (move-marker org-clock-marker (point) (buffer-base-buffer))
18630 (or global-mode-string (setq global-mode-string '("")))
18631 (or (memq 'org-mode-line-string global-mode-string)
18632 (setq global-mode-string
18633 (append global-mode-string '(org-mode-line-string))))
18634 (org-update-mode-line)
18635 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18636 (message "Clock started at %s" ts))))
18638 (defun org-clock-find-position ()
18639 "Find the location where the next clock line should be inserted."
18640 (org-back-to-heading t)
18641 (catch 'exit
18642 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18643 (re (concat "^[ \t]*" org-clock-string))
18644 (cnt 0)
18645 first last)
18646 (goto-char beg)
18647 (when (eobp) (newline) (setq end (max (point) end)))
18648 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18649 ;; we seem to have a CLOCK drawer, so go there.
18650 (beginning-of-line 2)
18651 (throw 'exit t))
18652 ;; Lets count the CLOCK lines
18653 (goto-char beg)
18654 (while (re-search-forward re end t)
18655 (setq first (or first (match-beginning 0))
18656 last (match-beginning 0)
18657 cnt (1+ cnt)))
18658 (when (and (integerp org-clock-into-drawer)
18659 (>= (1+ cnt) org-clock-into-drawer))
18660 ;; Wrap current entries into a new drawer
18661 (goto-char last)
18662 (beginning-of-line 2)
18663 (if (org-at-item-p) (org-end-of-item))
18664 (insert ":END:\n")
18665 (beginning-of-line 0)
18666 (org-indent-line-function)
18667 (goto-char first)
18668 (insert ":CLOCK:\n")
18669 (beginning-of-line 0)
18670 (org-indent-line-function)
18671 (org-flag-drawer t)
18672 (beginning-of-line 2)
18673 (throw 'exit nil))
18675 (goto-char beg)
18676 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18677 (not (equal (match-string 1) org-clock-string)))
18678 ;; Planning info, skip to after it
18679 (beginning-of-line 2)
18680 (or (bolp) (newline)))
18681 (when (eq t org-clock-into-drawer)
18682 (insert ":CLOCK:\n:END:\n")
18683 (beginning-of-line -1)
18684 (org-indent-line-function)
18685 (org-flag-drawer t)
18686 (beginning-of-line 2)
18687 (org-indent-line-function)))))
18689 (defun org-clock-out (&optional fail-quietly)
18690 "Stop the currently running clock.
18691 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18692 (interactive)
18693 (catch 'exit
18694 (if (not (marker-buffer org-clock-marker))
18695 (if fail-quietly (throw 'exit t) (error "No active clock")))
18696 (let (ts te s h m)
18697 (save-excursion
18698 (set-buffer (marker-buffer org-clock-marker))
18699 (goto-char org-clock-marker)
18700 (beginning-of-line 1)
18701 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18702 (equal (match-string 1) org-clock-string))
18703 (setq ts (match-string 2))
18704 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18705 (goto-char (match-end 0))
18706 (delete-region (point) (point-at-eol))
18707 (insert "--")
18708 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18709 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18710 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18711 h (floor (/ s 3600))
18712 s (- s (* 3600 h))
18713 m (floor (/ s 60))
18714 s (- s (* 60 s)))
18715 (insert " => " (format "%2d:%02d" h m))
18716 (move-marker org-clock-marker nil)
18717 (when org-log-note-clock-out
18718 (org-add-log-maybe 'clock-out))
18719 (when org-mode-line-timer
18720 (cancel-timer org-mode-line-timer)
18721 (setq org-mode-line-timer nil))
18722 (setq global-mode-string
18723 (delq 'org-mode-line-string global-mode-string))
18724 (force-mode-line-update)
18725 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18727 (defun org-clock-cancel ()
18728 "Cancel the running clock be removing the start timestamp."
18729 (interactive)
18730 (if (not (marker-buffer org-clock-marker))
18731 (error "No active clock"))
18732 (save-excursion
18733 (set-buffer (marker-buffer org-clock-marker))
18734 (goto-char org-clock-marker)
18735 (delete-region (1- (point-at-bol)) (point-at-eol)))
18736 (setq global-mode-string
18737 (delq 'org-mode-line-string global-mode-string))
18738 (force-mode-line-update)
18739 (message "Clock canceled"))
18741 (defun org-clock-goto (&optional delete-windows)
18742 "Go to the currently clocked-in entry."
18743 (interactive "P")
18744 (if (not (marker-buffer org-clock-marker))
18745 (error "No active clock"))
18746 (switch-to-buffer-other-window
18747 (marker-buffer org-clock-marker))
18748 (if delete-windows (delete-other-windows))
18749 (goto-char org-clock-marker)
18750 (org-show-entry)
18751 (org-back-to-heading)
18752 (recenter))
18754 (defvar org-clock-file-total-minutes nil
18755 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18756 (make-variable-buffer-local 'org-clock-file-total-minutes)
18758 (defun org-clock-sum (&optional tstart tend)
18759 "Sum the times for each subtree.
18760 Puts the resulting times in minutes as a text property on each headline."
18761 (interactive)
18762 (let* ((bmp (buffer-modified-p))
18763 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18764 org-clock-string
18765 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18766 (lmax 30)
18767 (ltimes (make-vector lmax 0))
18768 (t1 0)
18769 (level 0)
18770 ts te dt
18771 time)
18772 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18773 (save-excursion
18774 (goto-char (point-max))
18775 (while (re-search-backward re nil t)
18776 (cond
18777 ((match-end 2)
18778 ;; Two time stamps
18779 (setq ts (match-string 2)
18780 te (match-string 3)
18781 ts (time-to-seconds
18782 (apply 'encode-time (org-parse-time-string ts)))
18783 te (time-to-seconds
18784 (apply 'encode-time (org-parse-time-string te)))
18785 ts (if tstart (max ts tstart) ts)
18786 te (if tend (min te tend) te)
18787 dt (- te ts)
18788 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18789 ((match-end 4)
18790 ;; A naket time
18791 (setq t1 (+ t1 (string-to-number (match-string 5))
18792 (* 60 (string-to-number (match-string 4))))))
18793 (t ;; A headline
18794 (setq level (- (match-end 1) (match-beginning 1)))
18795 (when (or (> t1 0) (> (aref ltimes level) 0))
18796 (loop for l from 0 to level do
18797 (aset ltimes l (+ (aref ltimes l) t1)))
18798 (setq t1 0 time (aref ltimes level))
18799 (loop for l from level to (1- lmax) do
18800 (aset ltimes l 0))
18801 (goto-char (match-beginning 0))
18802 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18803 (setq org-clock-file-total-minutes (aref ltimes 0)))
18804 (set-buffer-modified-p bmp)))
18806 (defun org-clock-display (&optional total-only)
18807 "Show subtree times in the entire buffer.
18808 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18809 in the echo area."
18810 (interactive)
18811 (org-remove-clock-overlays)
18812 (let (time h m p)
18813 (org-clock-sum)
18814 (unless total-only
18815 (save-excursion
18816 (goto-char (point-min))
18817 (while (or (and (equal (setq p (point)) (point-min))
18818 (get-text-property p :org-clock-minutes))
18819 (setq p (next-single-property-change
18820 (point) :org-clock-minutes)))
18821 (goto-char p)
18822 (when (setq time (get-text-property p :org-clock-minutes))
18823 (org-put-clock-overlay time (funcall outline-level))))
18824 (setq h (/ org-clock-file-total-minutes 60)
18825 m (- org-clock-file-total-minutes (* 60 h)))
18826 ;; Arrange to remove the overlays upon next change.
18827 (when org-remove-highlights-with-change
18828 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18829 nil 'local))))
18830 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18832 (defvar org-clock-overlays nil)
18833 (make-variable-buffer-local 'org-clock-overlays)
18835 (defun org-put-clock-overlay (time &optional level)
18836 "Put an overlays on the current line, displaying TIME.
18837 If LEVEL is given, prefix time with a corresponding number of stars.
18838 This creates a new overlay and stores it in `org-clock-overlays', so that it
18839 will be easy to remove."
18840 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18841 (l (if level (org-get-legal-level level 0) 0))
18842 (off 0)
18843 ov tx)
18844 (move-to-column c)
18845 (unless (eolp) (skip-chars-backward "^ \t"))
18846 (skip-chars-backward " \t")
18847 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18848 tx (concat (buffer-substring (1- (point)) (point))
18849 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18850 (org-add-props (format "%s %2d:%02d%s"
18851 (make-string l ?*) h m
18852 (make-string (- 10 l) ?\ ))
18853 '(face secondary-selection))
18854 ""))
18855 (if (not (featurep 'xemacs))
18856 (org-overlay-put ov 'display tx)
18857 (org-overlay-put ov 'invisible t)
18858 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18859 (push ov org-clock-overlays)))
18861 (defun org-remove-clock-overlays (&optional beg end noremove)
18862 "Remove the occur highlights from the buffer.
18863 BEG and END are ignored. If NOREMOVE is nil, remove this function
18864 from the `before-change-functions' in the current buffer."
18865 (interactive)
18866 (unless org-inhibit-highlight-removal
18867 (mapc 'org-delete-overlay org-clock-overlays)
18868 (setq org-clock-overlays nil)
18869 (unless noremove
18870 (remove-hook 'before-change-functions
18871 'org-remove-clock-overlays 'local))))
18873 (defun org-clock-out-if-current ()
18874 "Clock out if the current entry contains the running clock.
18875 This is used to stop the clock after a TODO entry is marked DONE,
18876 and is only done if the variable `org-clock-out-when-done' is not nil."
18877 (when (and org-clock-out-when-done
18878 (member state org-done-keywords)
18879 (equal (marker-buffer org-clock-marker) (current-buffer))
18880 (< (point) org-clock-marker)
18881 (> (save-excursion (outline-next-heading) (point))
18882 org-clock-marker))
18883 ;; Clock out, but don't accept a logging message for this.
18884 (let ((org-log-note-clock-out nil))
18885 (org-clock-out))))
18887 (add-hook 'org-after-todo-state-change-hook
18888 'org-clock-out-if-current)
18890 (defun org-check-running-clock ()
18891 "Check if the current buffer contains the running clock.
18892 If yes, offer to stop it and to save the buffer with the changes."
18893 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18894 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18895 (buffer-name))))
18896 (org-clock-out)
18897 (when (y-or-n-p "Save changed buffer?")
18898 (save-buffer))))
18900 (defun org-clock-report (&optional arg)
18901 "Create a table containing a report about clocked time.
18902 If the cursor is inside an existing clocktable block, then the table
18903 will be updated. If not, a new clocktable will be inserted.
18904 When called with a prefix argument, move to the first clock table in the
18905 buffer and update it."
18906 (interactive "P")
18907 (org-remove-clock-overlays)
18908 (when arg
18909 (org-find-dblock "clocktable")
18910 (org-show-entry))
18911 (if (org-in-clocktable-p)
18912 (goto-char (org-in-clocktable-p))
18913 (org-create-dblock (list :name "clocktable"
18914 :maxlevel 2 :scope 'file)))
18915 (org-update-dblock))
18917 (defun org-in-clocktable-p ()
18918 "Check if the cursor is in a clocktable."
18919 (let ((pos (point)) start)
18920 (save-excursion
18921 (end-of-line 1)
18922 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18923 (setq start (match-beginning 0))
18924 (re-search-forward "^#\\+END:.*" nil t)
18925 (>= (match-end 0) pos)
18926 start))))
18928 (defun org-clock-update-time-maybe ()
18929 "If this is a CLOCK line, update it and return t.
18930 Otherwise, return nil."
18931 (interactive)
18932 (save-excursion
18933 (beginning-of-line 1)
18934 (skip-chars-forward " \t")
18935 (when (looking-at org-clock-string)
18936 (let ((re (concat "[ \t]*" org-clock-string
18937 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18938 "\\([ \t]*=>.*\\)?"))
18939 ts te h m s)
18940 (if (not (looking-at re))
18942 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18943 (end-of-line 1)
18944 (setq ts (match-string 1)
18945 te (match-string 2))
18946 (setq s (- (time-to-seconds
18947 (apply 'encode-time (org-parse-time-string te)))
18948 (time-to-seconds
18949 (apply 'encode-time (org-parse-time-string ts))))
18950 h (floor (/ s 3600))
18951 s (- s (* 3600 h))
18952 m (floor (/ s 60))
18953 s (- s (* 60 s)))
18954 (insert " => " (format "%2d:%02d" h m))
18955 t)))))
18957 (defun org-clock-special-range (key &optional time as-strings)
18958 "Return two times bordering a special time range.
18959 Key is a symbol specifying the range and can be one of `today', `yesterday',
18960 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18961 A week starts Monday 0:00 and ends Sunday 24:00.
18962 The range is determined relative to TIME. TIME defaults to the current time.
18963 The return value is a cons cell with two internal times like the ones
18964 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18965 the returned times will be formatted strings."
18966 (let* ((tm (decode-time (or time (current-time))))
18967 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18968 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18969 (dow (nth 6 tm))
18970 s1 m1 h1 d1 month1 y1 diff ts te fm)
18971 (cond
18972 ((eq key 'today)
18973 (setq h 0 m 0 h1 24 m1 0))
18974 ((eq key 'yesterday)
18975 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18976 ((eq key 'thisweek)
18977 (setq diff (if (= dow 0) 6 (1- dow))
18978 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18979 ((eq key 'lastweek)
18980 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18981 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18982 ((eq key 'thismonth)
18983 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18984 ((eq key 'lastmonth)
18985 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18986 ((eq key 'thisyear)
18987 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18988 ((eq key 'lastyear)
18989 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18990 (t (error "No such time block %s" key)))
18991 (setq ts (encode-time s m h d month y)
18992 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18993 (or d1 d) (or month1 month) (or y1 y)))
18994 (setq fm (cdr org-time-stamp-formats))
18995 (if as-strings
18996 (cons (format-time-string fm ts) (format-time-string fm te))
18997 (cons ts te))))
18999 (defun org-dblock-write:clocktable (params)
19000 "Write the standard clocktable."
19001 (catch 'exit
19002 (let* ((hlchars '((1 . "*") (2 . "/")))
19003 (ins (make-marker))
19004 (total-time nil)
19005 (scope (plist-get params :scope))
19006 (tostring (plist-get params :tostring))
19007 (multifile (plist-get params :multifile))
19008 (header (plist-get params :header))
19009 (maxlevel (or (plist-get params :maxlevel) 3))
19010 (step (plist-get params :step))
19011 (emph (plist-get params :emphasize))
19012 (ts (plist-get params :tstart))
19013 (te (plist-get params :tend))
19014 (block (plist-get params :block))
19015 ipos time h m p level hlc hdl
19016 cc beg end pos tbl)
19017 (when step
19018 (org-clocktable-steps params)
19019 (throw 'exit nil))
19020 (when block
19021 (setq cc (org-clock-special-range block nil t)
19022 ts (car cc) te (cdr cc)))
19023 (if ts (setq ts (time-to-seconds
19024 (apply 'encode-time (org-parse-time-string ts)))))
19025 (if te (setq te (time-to-seconds
19026 (apply 'encode-time (org-parse-time-string te)))))
19027 (move-marker ins (point))
19028 (setq ipos (point))
19030 ;; Get the right scope
19031 (setq pos (point))
19032 (save-restriction
19033 (cond
19034 ((not scope))
19035 ((eq scope 'file) (widen))
19036 ((eq scope 'subtree) (org-narrow-to-subtree))
19037 ((eq scope 'tree)
19038 (while (org-up-heading-safe))
19039 (org-narrow-to-subtree))
19040 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19041 (symbol-name scope)))
19042 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19043 (catch 'exit
19044 (while (org-up-heading-safe)
19045 (looking-at outline-regexp)
19046 (if (<= (org-reduced-level (funcall outline-level)) level)
19047 (throw 'exit nil))))
19048 (org-narrow-to-subtree))
19049 ((or (listp scope) (eq scope 'agenda))
19050 (let* ((files (if (listp scope) scope (org-agenda-files)))
19051 (scope 'agenda)
19052 (p1 (copy-sequence params))
19053 file)
19054 (plist-put p1 :tostring t)
19055 (plist-put p1 :multifile t)
19056 (plist-put p1 :scope 'file)
19057 (org-prepare-agenda-buffers files)
19058 (while (setq file (pop files))
19059 (with-current-buffer (find-buffer-visiting file)
19060 (push (org-clocktable-add-file
19061 file (org-dblock-write:clocktable p1)) tbl)
19062 (setq total-time (+ (or total-time 0)
19063 org-clock-file-total-minutes)))))))
19064 (goto-char pos)
19066 (unless (eq scope 'agenda)
19067 (org-clock-sum ts te)
19068 (goto-char (point-min))
19069 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19070 (goto-char p)
19071 (when (setq time (get-text-property p :org-clock-minutes))
19072 (save-excursion
19073 (beginning-of-line 1)
19074 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19075 (setq level (org-reduced-level
19076 (- (match-end 1) (match-beginning 1))))
19077 (<= level maxlevel))
19078 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19079 hdl (match-string 2)
19080 h (/ time 60)
19081 m (- time (* 60 h)))
19082 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19083 (push (concat
19084 "| " (int-to-string level) "|" hlc hdl hlc " |"
19085 (make-string (1- level) ?|)
19086 hlc (format "%d:%02d" h m) hlc
19087 " |") tbl))))))
19088 (setq tbl (nreverse tbl))
19089 (if tostring
19090 (if tbl (mapconcat 'identity tbl "\n") nil)
19091 (goto-char ins)
19092 (insert-before-markers
19093 (or header
19094 (concat
19095 "Clock summary at ["
19096 (substring
19097 (format-time-string (cdr org-time-stamp-formats))
19098 1 -1)
19099 "]."
19100 (if block
19101 (format " Considered range is /%s/." block)
19103 "\n\n"))
19104 (if (eq scope 'agenda) "|File" "")
19105 "|L|Headline|Time|\n")
19106 (setq total-time (or total-time org-clock-file-total-minutes)
19107 h (/ total-time 60)
19108 m (- total-time (* 60 h)))
19109 (insert-before-markers
19110 "|-\n|"
19111 (if (eq scope 'agenda) "|" "")
19113 "*Total time*| "
19114 (format "*%d:%02d*" h m)
19115 "|\n|-\n")
19116 (setq tbl (delq nil tbl))
19117 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19118 (equal (substring (car tbl) 0 2) "|-"))
19119 (pop tbl))
19120 (insert-before-markers (mapconcat
19121 'identity (delq nil tbl)
19122 (if (eq scope 'agenda) "\n|-\n" "\n")))
19123 (backward-delete-char 1)
19124 (goto-char ipos)
19125 (skip-chars-forward "^|")
19126 (org-table-align))))))
19128 (defun org-clocktable-steps (params)
19129 (let* ((p1 (copy-sequence params))
19130 (ts (plist-get p1 :tstart))
19131 (te (plist-get p1 :tend))
19132 (step0 (plist-get p1 :step))
19133 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19134 (block (plist-get p1 :block))
19136 (when block
19137 (setq cc (org-clock-special-range block nil t)
19138 ts (car cc) te (cdr cc)))
19139 (if ts (setq ts (time-to-seconds
19140 (apply 'encode-time (org-parse-time-string ts)))))
19141 (if te (setq te (time-to-seconds
19142 (apply 'encode-time (org-parse-time-string te)))))
19143 (plist-put p1 :header "")
19144 (plist-put p1 :step nil)
19145 (plist-put p1 :block nil)
19146 (while (< ts te)
19147 (or (bolp) (insert "\n"))
19148 (plist-put p1 :tstart (format-time-string
19149 (car org-time-stamp-formats)
19150 (seconds-to-time ts)))
19151 (plist-put p1 :tend (format-time-string
19152 (car org-time-stamp-formats)
19153 (seconds-to-time (setq ts (+ ts step)))))
19154 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19155 (plist-get p1 :tstart) "\n")
19156 (org-dblock-write:clocktable p1)
19157 (re-search-forward "#\\+END:")
19158 (end-of-line 0))))
19161 (defun org-clocktable-add-file (file table)
19162 (if table
19163 (let ((lines (org-split-string table "\n"))
19164 (ff (file-name-nondirectory file)))
19165 (mapconcat 'identity
19166 (mapcar (lambda (x)
19167 (if (string-match org-table-dataline-regexp x)
19168 (concat "|" ff x)
19170 lines)
19171 "\n"))))
19173 ;; FIXME: I don't think anybody uses this, ask David
19174 (defun org-collect-clock-time-entries ()
19175 "Return an internal list with clocking information.
19176 This list has one entry for each CLOCK interval.
19177 FIXME: describe the elements."
19178 (interactive)
19179 (let ((re (concat "^[ \t]*" org-clock-string
19180 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19181 rtn beg end next cont level title total closedp leafp
19182 clockpos titlepos h m donep)
19183 (save-excursion
19184 (org-clock-sum)
19185 (goto-char (point-min))
19186 (while (re-search-forward re nil t)
19187 (setq clockpos (match-beginning 0)
19188 beg (match-string 1) end (match-string 2)
19189 cont (match-end 0))
19190 (setq beg (apply 'encode-time (org-parse-time-string beg))
19191 end (apply 'encode-time (org-parse-time-string end)))
19192 (org-back-to-heading t)
19193 (setq donep (org-entry-is-done-p))
19194 (setq titlepos (point)
19195 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19196 h (/ total 60) m (- total (* 60 h))
19197 total (cons h m))
19198 (looking-at "\\(\\*+\\) +\\(.*\\)")
19199 (setq level (- (match-end 1) (match-beginning 1))
19200 title (org-match-string-no-properties 2))
19201 (save-excursion (outline-next-heading) (setq next (point)))
19202 (setq closedp (re-search-forward org-closed-time-regexp next t))
19203 (goto-char next)
19204 (setq leafp (and (looking-at "^\\*+ ")
19205 (<= (- (match-end 0) (point)) level)))
19206 (push (list beg end clockpos closedp donep
19207 total title titlepos level leafp)
19208 rtn)
19209 (goto-char cont)))
19210 (nreverse rtn)))
19212 ;;;; Agenda, and Diary Integration
19214 ;;; Define the Org-agenda-mode
19216 (defvar org-agenda-mode-map (make-sparse-keymap)
19217 "Keymap for `org-agenda-mode'.")
19219 (defvar org-agenda-menu) ; defined later in this file.
19220 (defvar org-agenda-follow-mode nil)
19221 (defvar org-agenda-show-log nil)
19222 (defvar org-agenda-redo-command nil)
19223 (defvar org-agenda-mode-hook nil)
19224 (defvar org-agenda-type nil)
19225 (defvar org-agenda-force-single-file nil)
19227 (defun org-agenda-mode ()
19228 "Mode for time-sorted view on action items in Org-mode files.
19230 The following commands are available:
19232 \\{org-agenda-mode-map}"
19233 (interactive)
19234 (kill-all-local-variables)
19235 (setq org-agenda-undo-list nil
19236 org-agenda-pending-undo-list nil)
19237 (setq major-mode 'org-agenda-mode)
19238 ;; Keep global-font-lock-mode from turning on font-lock-mode
19239 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19240 (setq mode-name "Org-Agenda")
19241 (use-local-map org-agenda-mode-map)
19242 (easy-menu-add org-agenda-menu)
19243 (if org-startup-truncated (setq truncate-lines t))
19244 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19245 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19246 ;; Make sure properties are removed when copying text
19247 (when (boundp 'buffer-substring-filters)
19248 (org-set-local 'buffer-substring-filters
19249 (cons (lambda (x)
19250 (set-text-properties 0 (length x) nil x) x)
19251 buffer-substring-filters)))
19252 (unless org-agenda-keep-modes
19253 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19254 org-agenda-show-log nil))
19255 (easy-menu-change
19256 '("Agenda") "Agenda Files"
19257 (append
19258 (list
19259 (vector
19260 (if (get 'org-agenda-files 'org-restrict)
19261 "Restricted to single file"
19262 "Edit File List")
19263 '(org-edit-agenda-file-list)
19264 (not (get 'org-agenda-files 'org-restrict)))
19265 "--")
19266 (mapcar 'org-file-menu-entry (org-agenda-files))))
19267 (org-agenda-set-mode-name)
19268 (apply
19269 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19270 (list 'org-agenda-mode-hook)))
19272 (substitute-key-definition 'undo 'org-agenda-undo
19273 org-agenda-mode-map global-map)
19274 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19275 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19276 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19277 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19278 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19279 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19280 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19281 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19282 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19283 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19284 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19285 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19286 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19287 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19288 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19289 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19290 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19291 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19292 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19293 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19294 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19295 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19296 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19297 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19298 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19299 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19300 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19301 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19302 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19304 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19305 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19306 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19307 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19308 (while l (org-defkey org-agenda-mode-map
19309 (int-to-string (pop l)) 'digit-argument)))
19311 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19312 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19313 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19314 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19315 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19316 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19317 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19318 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19319 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19320 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19321 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19322 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19323 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19324 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19325 (org-defkey org-agenda-mode-map "n" 'next-line)
19326 (org-defkey org-agenda-mode-map "p" 'previous-line)
19327 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19328 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19329 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19330 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19331 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19332 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19333 (eval-after-load "calendar"
19334 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19335 'org-calendar-goto-agenda))
19336 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19337 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19338 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19339 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19340 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19341 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19342 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19343 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19344 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19345 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19346 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19347 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19348 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19349 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19350 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19351 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19352 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19353 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19354 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19355 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19356 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19357 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19359 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19360 "Local keymap for agenda entries from Org-mode.")
19362 (org-defkey org-agenda-keymap
19363 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19364 (org-defkey org-agenda-keymap
19365 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19366 (when org-agenda-mouse-1-follows-link
19367 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19368 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19369 '("Agenda"
19370 ("Agenda Files")
19371 "--"
19372 ["Show" org-agenda-show t]
19373 ["Go To (other window)" org-agenda-goto t]
19374 ["Go To (this window)" org-agenda-switch-to t]
19375 ["Follow Mode" org-agenda-follow-mode
19376 :style toggle :selected org-agenda-follow-mode :active t]
19377 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19378 "--"
19379 ["Cycle TODO" org-agenda-todo t]
19380 ["Archive subtree" org-agenda-archive t]
19381 ["Delete subtree" org-agenda-kill t]
19382 "--"
19383 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19384 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19385 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19386 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19387 "--"
19388 ("Tags and Properties"
19389 ["Show all Tags" org-agenda-show-tags t]
19390 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19391 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19392 "--"
19393 ["Column View" org-columns t])
19394 ("Date/Schedule"
19395 ["Schedule" org-agenda-schedule t]
19396 ["Set Deadline" org-agenda-deadline t]
19397 "--"
19398 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19399 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19400 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19401 ("Clock"
19402 ["Clock in" org-agenda-clock-in t]
19403 ["Clock out" org-agenda-clock-out t]
19404 ["Clock cancel" org-agenda-clock-cancel t]
19405 ["Goto running clock" org-clock-goto t])
19406 ("Priority"
19407 ["Set Priority" org-agenda-priority t]
19408 ["Increase Priority" org-agenda-priority-up t]
19409 ["Decrease Priority" org-agenda-priority-down t]
19410 ["Show Priority" org-agenda-show-priority t])
19411 ("Calendar/Diary"
19412 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19413 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19414 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19415 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19416 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19417 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19418 "--"
19419 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19420 "--"
19421 ("View"
19422 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19423 :style radio :selected (equal org-agenda-ndays 1)]
19424 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19425 :style radio :selected (equal org-agenda-ndays 7)]
19426 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19427 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19428 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19429 :style radio :selected (member org-agenda-ndays '(365 366))]
19430 "--"
19431 ["Show Logbook entries" org-agenda-log-mode
19432 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19433 ["Include Diary" org-agenda-toggle-diary
19434 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19435 ["Use Time Grid" org-agenda-toggle-time-grid
19436 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19437 ["Write view to file" org-write-agenda t]
19438 ["Rebuild buffer" org-agenda-redo t]
19439 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19440 "--"
19441 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19442 "--"
19443 ["Quit" org-agenda-quit t]
19444 ["Exit and Release Buffers" org-agenda-exit t]
19447 ;;; Agenda undo
19449 (defvar org-agenda-allow-remote-undo t
19450 "Non-nil means, allow remote undo from the agenda buffer.")
19451 (defvar org-agenda-undo-list nil
19452 "List of undoable operations in the agenda since last refresh.")
19453 (defvar org-agenda-undo-has-started-in nil
19454 "Buffers that have already seen `undo-start' in the current undo sequence.")
19455 (defvar org-agenda-pending-undo-list nil
19456 "In a series of undo commands, this is the list of remaning undo items.")
19458 (defmacro org-if-unprotected (&rest body)
19459 "Execute BODY if there is no `org-protected' text property at point."
19460 (declare (debug t))
19461 `(unless (get-text-property (point) 'org-protected)
19462 ,@body))
19464 (defmacro org-with-remote-undo (_buffer &rest _body)
19465 "Execute BODY while recording undo information in two buffers."
19466 (declare (indent 1) (debug t))
19467 `(let ((_cline (org-current-line))
19468 (_cmd this-command)
19469 (_buf1 (current-buffer))
19470 (_buf2 ,_buffer)
19471 (_undo1 buffer-undo-list)
19472 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19473 _c1 _c2)
19474 ,@_body
19475 (when org-agenda-allow-remote-undo
19476 (setq _c1 (org-verify-change-for-undo
19477 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19478 _c2 (org-verify-change-for-undo
19479 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19480 (when (or _c1 _c2)
19481 ;; make sure there are undo boundaries
19482 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19483 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19484 ;; remember which buffer to undo
19485 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19486 org-agenda-undo-list)))))
19488 (defun org-agenda-undo ()
19489 "Undo a remote editing step in the agenda.
19490 This undoes changes both in the agenda buffer and in the remote buffer
19491 that have been changed along."
19492 (interactive)
19493 (or org-agenda-allow-remote-undo
19494 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19495 (if (not (eq this-command last-command))
19496 (setq org-agenda-undo-has-started-in nil
19497 org-agenda-pending-undo-list org-agenda-undo-list))
19498 (if (not org-agenda-pending-undo-list)
19499 (error "No further undo information"))
19500 (let* ((entry (pop org-agenda-pending-undo-list))
19501 buf line cmd rembuf)
19502 (setq cmd (pop entry) line (pop entry))
19503 (setq rembuf (nth 2 entry))
19504 (org-with-remote-undo rembuf
19505 (while (bufferp (setq buf (pop entry)))
19506 (if (pop entry)
19507 (with-current-buffer buf
19508 (let ((last-undo-buffer buf)
19509 (inhibit-read-only t))
19510 (unless (memq buf org-agenda-undo-has-started-in)
19511 (push buf org-agenda-undo-has-started-in)
19512 (make-local-variable 'pending-undo-list)
19513 (undo-start))
19514 (while (and pending-undo-list
19515 (listp pending-undo-list)
19516 (not (car pending-undo-list)))
19517 (pop pending-undo-list))
19518 (undo-more 1))))))
19519 (goto-line line)
19520 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19522 (defun org-verify-change-for-undo (l1 l2)
19523 "Verify that a real change occurred between the undo lists L1 and L2."
19524 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19525 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19526 (not (eq l1 l2)))
19528 ;;; Agenda dispatch
19530 (defvar org-agenda-restrict nil)
19531 (defvar org-agenda-restrict-begin (make-marker))
19532 (defvar org-agenda-restrict-end (make-marker))
19533 (defvar org-agenda-last-dispatch-buffer nil)
19534 (defvar org-agenda-overriding-restriction nil)
19536 ;;;###autoload
19537 (defun org-agenda (arg &optional keys restriction)
19538 "Dispatch agenda commands to collect entries to the agenda buffer.
19539 Prompts for a command to execute. Any prefix arg will be passed
19540 on to the selected command. The default selections are:
19542 a Call `org-agenda-list' to display the agenda for current day or week.
19543 t Call `org-todo-list' to display the global todo list.
19544 T Call `org-todo-list' to display the global todo list, select only
19545 entries with a specific TODO keyword (the user gets a prompt).
19546 m Call `org-tags-view' to display headlines with tags matching
19547 a condition (the user is prompted for the condition).
19548 M Like `m', but select only TODO entries, no ordinary headlines.
19549 L Create a timeline for the current buffer.
19550 e Export views to associated files.
19552 More commands can be added by configuring the variable
19553 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19554 searches can be pre-defined in this way.
19556 If the current buffer is in Org-mode and visiting a file, you can also
19557 first press `<' once to indicate that the agenda should be temporarily
19558 \(until the next use of \\[org-agenda]) restricted to the current file.
19559 Pressing `<' twice means to restrict to the current subtree or region
19560 \(if active)."
19561 (interactive "P")
19562 (catch 'exit
19563 (let* ((prefix-descriptions nil)
19564 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19565 (org-agenda-custom-commands
19566 ;; normalize different versions
19567 (delq nil
19568 (mapcar
19569 (lambda (x)
19570 (cond ((stringp (cdr x))
19571 (push x prefix-descriptions)
19572 nil)
19573 ((stringp (nth 1 x)) x)
19574 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19575 (t (cons (car x) (cons "" (cdr x))))))
19576 org-agenda-custom-commands)))
19577 (buf (current-buffer))
19578 (bfn (buffer-file-name (buffer-base-buffer)))
19579 entry key type match lprops ans)
19580 ;; Turn off restriction unless there is an overriding one
19581 (unless org-agenda-overriding-restriction
19582 (put 'org-agenda-files 'org-restrict nil)
19583 (setq org-agenda-restrict nil)
19584 (move-marker org-agenda-restrict-begin nil)
19585 (move-marker org-agenda-restrict-end nil))
19586 ;; Delete old local properties
19587 (put 'org-agenda-redo-command 'org-lprops nil)
19588 ;; Remember where this call originated
19589 (setq org-agenda-last-dispatch-buffer (current-buffer))
19590 (unless keys
19591 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19592 keys (car ans)
19593 restriction (cdr ans)))
19594 ;; Estabish the restriction, if any
19595 (when (and (not org-agenda-overriding-restriction) restriction)
19596 (put 'org-agenda-files 'org-restrict (list bfn))
19597 (cond
19598 ((eq restriction 'region)
19599 (setq org-agenda-restrict t)
19600 (move-marker org-agenda-restrict-begin (region-beginning))
19601 (move-marker org-agenda-restrict-end (region-end)))
19602 ((eq restriction 'subtree)
19603 (save-excursion
19604 (setq org-agenda-restrict t)
19605 (org-back-to-heading t)
19606 (move-marker org-agenda-restrict-begin (point))
19607 (move-marker org-agenda-restrict-end
19608 (progn (org-end-of-subtree t)))))))
19610 (require 'calendar) ; FIXME: can we avoid this for some commands?
19611 ;; For example the todo list should not need it (but does...)
19612 (cond
19613 ((setq entry (assoc keys org-agenda-custom-commands))
19614 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19615 (progn
19616 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19617 (put 'org-agenda-redo-command 'org-lprops lprops)
19618 (cond
19619 ((eq type 'agenda)
19620 (org-let lprops '(org-agenda-list current-prefix-arg)))
19621 ((eq type 'alltodo)
19622 (org-let lprops '(org-todo-list current-prefix-arg)))
19623 ((eq type 'stuck)
19624 (org-let lprops '(org-agenda-list-stuck-projects
19625 current-prefix-arg)))
19626 ((eq type 'tags)
19627 (org-let lprops '(org-tags-view current-prefix-arg match)))
19628 ((eq type 'tags-todo)
19629 (org-let lprops '(org-tags-view '(4) match)))
19630 ((eq type 'todo)
19631 (org-let lprops '(org-todo-list match)))
19632 ((eq type 'tags-tree)
19633 (org-check-for-org-mode)
19634 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19635 ((eq type 'todo-tree)
19636 (org-check-for-org-mode)
19637 (org-let lprops
19638 '(org-occur (concat "^" outline-regexp "[ \t]*"
19639 (regexp-quote match) "\\>"))))
19640 ((eq type 'occur-tree)
19641 (org-check-for-org-mode)
19642 (org-let lprops '(org-occur match)))
19643 ((functionp type)
19644 (org-let lprops '(funcall type match)))
19645 ((fboundp type)
19646 (org-let lprops '(funcall type match)))
19647 (t (error "Invalid custom agenda command type %s" type))))
19648 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19649 ((equal keys "C")
19650 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19651 (customize-variable 'org-agenda-custom-commands))
19652 ((equal keys "a") (call-interactively 'org-agenda-list))
19653 ((equal keys "t") (call-interactively 'org-todo-list))
19654 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19655 ((equal keys "m") (call-interactively 'org-tags-view))
19656 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19657 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19658 ((equal keys "L")
19659 (unless (org-mode-p)
19660 (error "This is not an Org-mode file"))
19661 (unless restriction
19662 (put 'org-agenda-files 'org-restrict (list bfn))
19663 (org-call-with-arg 'org-timeline arg)))
19664 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19665 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19666 ((equal keys "!") (customize-variable 'org-stuck-projects))
19667 (t (error "Invalid agenda key"))))))
19669 (defun org-agenda-normalize-custom-commands (cmds)
19670 (delq nil
19671 (mapcar
19672 (lambda (x)
19673 (cond ((stringp (cdr x)) nil)
19674 ((stringp (nth 1 x)) x)
19675 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19676 (t (cons (car x) (cons "" (cdr x))))))
19677 cmds)))
19679 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19680 "The user interface for selecting an agenda command."
19681 (catch 'exit
19682 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19683 (restrict-ok (and bfn (org-mode-p)))
19684 (region-p (org-region-active-p))
19685 (custom org-agenda-custom-commands)
19686 (selstring "")
19687 restriction second-time
19688 c entry key type match prefixes rmheader header-end custom1 desc)
19689 (save-window-excursion
19690 (delete-other-windows)
19691 (org-switch-to-buffer-other-window " *Agenda Commands*")
19692 (erase-buffer)
19693 (insert (eval-when-compile
19694 (let ((header
19696 Press key for an agenda command: < Buffer,subtree/region restriction
19697 -------------------------------- > Remove restriction
19698 a Agenda for current week or day e Export agenda views
19699 t List of all TODO entries T Entries with special TODO kwd
19700 m Match a TAGS query M Like m, but only TODO entries
19701 L Timeline for current buffer # List stuck projects (!=configure)
19702 / Multi-occur C Configure custom agenda commands
19704 (start 0))
19705 (while (string-match
19706 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19707 header start)
19708 (setq start (match-end 0))
19709 (add-text-properties (match-beginning 2) (match-end 2)
19710 '(face bold) header))
19711 header)))
19712 (setq header-end (move-marker (make-marker) (point)))
19713 (while t
19714 (setq custom1 custom)
19715 (when (eq rmheader t)
19716 (goto-line 1)
19717 (re-search-forward ":" nil t)
19718 (delete-region (match-end 0) (point-at-eol))
19719 (forward-char 1)
19720 (looking-at "-+")
19721 (delete-region (match-end 0) (point-at-eol))
19722 (move-marker header-end (match-end 0)))
19723 (goto-char header-end)
19724 (delete-region (point) (point-max))
19725 (while (setq entry (pop custom1))
19726 (setq key (car entry) desc (nth 1 entry)
19727 type (nth 2 entry) match (nth 3 entry))
19728 (if (> (length key) 1)
19729 (add-to-list 'prefixes (string-to-char key))
19730 (insert
19731 (format
19732 "\n%-4s%-14s: %s"
19733 (org-add-props (copy-sequence key)
19734 '(face bold))
19735 (cond
19736 ((string-match "\\S-" desc) desc)
19737 ((eq type 'agenda) "Agenda for current week or day")
19738 ((eq type 'alltodo) "List of all TODO entries")
19739 ((eq type 'stuck) "List of stuck projects")
19740 ((eq type 'todo) "TODO keyword")
19741 ((eq type 'tags) "Tags query")
19742 ((eq type 'tags-todo) "Tags (TODO)")
19743 ((eq type 'tags-tree) "Tags tree")
19744 ((eq type 'todo-tree) "TODO kwd tree")
19745 ((eq type 'occur-tree) "Occur tree")
19746 ((functionp type) (if (symbolp type)
19747 (symbol-name type)
19748 "Lambda expression"))
19749 (t "???"))
19750 (cond
19751 ((stringp match)
19752 (org-add-props match nil 'face 'org-warning))
19753 (match
19754 (format "set of %d commands" (length match)))
19755 (t ""))))))
19756 (when prefixes
19757 (mapc (lambda (x)
19758 (insert
19759 (format "\n%s %s"
19760 (org-add-props (char-to-string x)
19761 nil 'face 'bold)
19762 (or (cdr (assoc (concat selstring (char-to-string x))
19763 prefix-descriptions))
19764 "Prefix key"))))
19765 prefixes))
19766 (goto-char (point-min))
19767 (when (fboundp 'fit-window-to-buffer)
19768 (if second-time
19769 (if (not (pos-visible-in-window-p (point-max)))
19770 (fit-window-to-buffer))
19771 (setq second-time t)
19772 (fit-window-to-buffer)))
19773 (message "Press key for agenda command%s:"
19774 (if (or restrict-ok org-agenda-overriding-restriction)
19775 (if org-agenda-overriding-restriction
19776 " (restriction lock active)"
19777 (if restriction
19778 (format " (restricted to %s)" restriction)
19779 " (unrestricted)"))
19780 ""))
19781 (setq c (read-char-exclusive))
19782 (message "")
19783 (cond
19784 ((assoc (char-to-string c) custom)
19785 (setq selstring (concat selstring (char-to-string c)))
19786 (throw 'exit (cons selstring restriction)))
19787 ((memq c prefixes)
19788 (setq selstring (concat selstring (char-to-string c))
19789 prefixes nil
19790 rmheader (or rmheader t)
19791 custom (delq nil (mapcar
19792 (lambda (x)
19793 (if (or (= (length (car x)) 1)
19794 (/= (string-to-char (car x)) c))
19796 (cons (substring (car x) 1) (cdr x))))
19797 custom))))
19798 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19799 (message "Restriction is only possible in Org-mode buffers")
19800 (ding) (sit-for 1))
19801 ((eq c ?1)
19802 (org-agenda-remove-restriction-lock 'noupdate)
19803 (setq restriction 'buffer))
19804 ((eq c ?0)
19805 (org-agenda-remove-restriction-lock 'noupdate)
19806 (setq restriction (if region-p 'region 'subtree)))
19807 ((eq c ?<)
19808 (org-agenda-remove-restriction-lock 'noupdate)
19809 (setq restriction
19810 (cond
19811 ((eq restriction 'buffer)
19812 (if region-p 'region 'subtree))
19813 ((memq restriction '(subtree region))
19814 nil)
19815 (t 'buffer))))
19816 ((eq c ?>)
19817 (org-agenda-remove-restriction-lock 'noupdate)
19818 (setq restriction nil))
19819 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19820 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19821 ((and (> (length selstring) 0) (eq c ?\d))
19822 (delete-window)
19823 (org-agenda-get-restriction-and-command prefix-descriptions))
19825 ((equal c ?q) (error "Abort"))
19826 (t (error "Invalid key %c" c))))))))
19828 (defun org-run-agenda-series (name series)
19829 (org-prepare-agenda name)
19830 (let* ((org-agenda-multi t)
19831 (redo (list 'org-run-agenda-series name (list 'quote series)))
19832 (cmds (car series))
19833 (gprops (nth 1 series))
19834 match ;; The byte compiler incorrectly complains about this. Keep it!
19835 cmd type lprops)
19836 (while (setq cmd (pop cmds))
19837 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19838 (cond
19839 ((eq type 'agenda)
19840 (org-let2 gprops lprops
19841 '(call-interactively 'org-agenda-list)))
19842 ((eq type 'alltodo)
19843 (org-let2 gprops lprops
19844 '(call-interactively 'org-todo-list)))
19845 ((eq type 'stuck)
19846 (org-let2 gprops lprops
19847 '(call-interactively 'org-agenda-list-stuck-projects)))
19848 ((eq type 'tags)
19849 (org-let2 gprops lprops
19850 '(org-tags-view current-prefix-arg match)))
19851 ((eq type 'tags-todo)
19852 (org-let2 gprops lprops
19853 '(org-tags-view '(4) match)))
19854 ((eq type 'todo)
19855 (org-let2 gprops lprops
19856 '(org-todo-list match)))
19857 ((fboundp type)
19858 (org-let2 gprops lprops
19859 '(funcall type match)))
19860 (t (error "Invalid type in command series"))))
19861 (widen)
19862 (setq org-agenda-redo-command redo)
19863 (goto-char (point-min)))
19864 (org-finalize-agenda))
19866 ;;;###autoload
19867 (defmacro org-batch-agenda (cmd-key &rest parameters)
19868 "Run an agenda command in batch mode and send the result to STDOUT.
19869 If CMD-KEY is a string of length 1, it is used as a key in
19870 `org-agenda-custom-commands' and triggers this command. If it is a
19871 longer string it is used as a tags/todo match string.
19872 Paramters are alternating variable names and values that will be bound
19873 before running the agenda command."
19874 (let (pars)
19875 (while parameters
19876 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19877 (if (> (length cmd-key) 2)
19878 (eval (list 'let (nreverse pars)
19879 (list 'org-tags-view nil cmd-key)))
19880 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19881 (set-buffer org-agenda-buffer-name)
19882 (princ (org-encode-for-stdout (buffer-string)))))
19884 (defun org-encode-for-stdout (string)
19885 (if (fboundp 'encode-coding-string)
19886 (encode-coding-string string buffer-file-coding-system)
19887 string))
19889 (defvar org-agenda-info nil)
19891 ;;;###autoload
19892 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19893 "Run an agenda command in batch mode and send the result to STDOUT.
19894 If CMD-KEY is a string of length 1, it is used as a key in
19895 `org-agenda-custom-commands' and triggers this command. If it is a
19896 longer string it is used as a tags/todo match string.
19897 Paramters are alternating variable names and values that will be bound
19898 before running the agenda command.
19900 The output gives a line for each selected agenda item. Each
19901 item is a list of comma-separated values, like this:
19903 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19905 category The category of the item
19906 head The headline, without TODO kwd, TAGS and PRIORITY
19907 type The type of the agenda entry, can be
19908 todo selected in TODO match
19909 tagsmatch selected in tags match
19910 diary imported from diary
19911 deadline a deadline on given date
19912 scheduled scheduled on given date
19913 timestamp entry has timestamp on given date
19914 closed entry was closed on given date
19915 upcoming-deadline warning about deadline
19916 past-scheduled forwarded scheduled item
19917 block entry has date block including g. date
19918 todo The todo keyword, if any
19919 tags All tags including inherited ones, separated by colons
19920 date The relevant date, like 2007-2-14
19921 time The time, like 15:00-16:50
19922 extra Sting with extra planning info
19923 priority-l The priority letter if any was given
19924 priority-n The computed numerical priority
19925 agenda-day The day in the agenda where this is listed"
19927 (let (pars)
19928 (while parameters
19929 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19930 (push (list 'org-agenda-remove-tags t) pars)
19931 (if (> (length cmd-key) 2)
19932 (eval (list 'let (nreverse pars)
19933 (list 'org-tags-view nil cmd-key)))
19934 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19935 (set-buffer org-agenda-buffer-name)
19936 (let* ((lines (org-split-string (buffer-string) "\n"))
19937 line)
19938 (while (setq line (pop lines))
19939 (catch 'next
19940 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19941 (setq org-agenda-info
19942 (org-fix-agenda-info (text-properties-at 0 line)))
19943 (princ
19944 (org-encode-for-stdout
19945 (mapconcat 'org-agenda-export-csv-mapper
19946 '(org-category txt type todo tags date time-of-day extra
19947 priority-letter priority agenda-day)
19948 ",")))
19949 (princ "\n"))))))
19951 (defun org-fix-agenda-info (props)
19952 "Make sure all properties on an agenda item have a canonical form,
19953 so the export commands can easily use it."
19954 (let (tmp re)
19955 (when (setq tmp (plist-get props 'tags))
19956 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19957 (when (setq tmp (plist-get props 'date))
19958 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19959 (let ((calendar-date-display-form '(year "-" month "-" day)))
19960 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19962 (setq tmp (calendar-date-string tmp)))
19963 (setq props (plist-put props 'date tmp)))
19964 (when (setq tmp (plist-get props 'day))
19965 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19966 (let ((calendar-date-display-form '(year "-" month "-" day)))
19967 (setq tmp (calendar-date-string tmp)))
19968 (setq props (plist-put props 'day tmp))
19969 (setq props (plist-put props 'agenda-day tmp)))
19970 (when (setq tmp (plist-get props 'txt))
19971 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19972 (plist-put props 'priority-letter (match-string 1 tmp))
19973 (setq tmp (replace-match "" t t tmp)))
19974 (when (and (setq re (plist-get props 'org-todo-regexp))
19975 (setq re (concat "\\`\\.*" re " ?"))
19976 (string-match re tmp))
19977 (plist-put props 'todo (match-string 1 tmp))
19978 (setq tmp (replace-match "" t t tmp)))
19979 (plist-put props 'txt tmp)))
19980 props)
19982 (defun org-agenda-export-csv-mapper (prop)
19983 (let ((res (plist-get org-agenda-info prop)))
19984 (setq res
19985 (cond
19986 ((not res) "")
19987 ((stringp res) res)
19988 (t (prin1-to-string res))))
19989 (while (string-match "," res)
19990 (setq res (replace-match ";" t t res)))
19991 (org-trim res)))
19994 ;;;###autoload
19995 (defun org-store-agenda-views (&rest parameters)
19996 (interactive)
19997 (eval (list 'org-batch-store-agenda-views)))
19999 ;; FIXME, why is this a macro?????
20000 ;;;###autoload
20001 (defmacro org-batch-store-agenda-views (&rest parameters)
20002 "Run all custom agenda commands that have a file argument."
20003 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20004 (pop-up-frames nil)
20005 (dir default-directory)
20006 pars cmd thiscmdkey files opts)
20007 (while parameters
20008 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20009 (setq pars (reverse pars))
20010 (save-window-excursion
20011 (while cmds
20012 (setq cmd (pop cmds)
20013 thiscmdkey (car cmd)
20014 opts (nth 4 cmd)
20015 files (nth 5 cmd))
20016 (if (stringp files) (setq files (list files)))
20017 (when files
20018 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20019 (list 'org-agenda nil thiscmdkey)))
20020 (set-buffer org-agenda-buffer-name)
20021 (while files
20022 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20023 (list 'org-write-agenda
20024 (expand-file-name (pop files) dir) t))))
20025 (and (get-buffer org-agenda-buffer-name)
20026 (kill-buffer org-agenda-buffer-name)))))))
20028 (defun org-write-agenda (file &optional nosettings)
20029 "Write the current buffer (an agenda view) as a file.
20030 Depending on the extension of the file name, plain text (.txt),
20031 HTML (.html or .htm) or Postscript (.ps) is produced.
20032 If NOSETTINGS is given, do not scope the settings of
20033 `org-agenda-exporter-settings' into the export commands. This is used when
20034 the settings have already been scoped and we do not wish to overrule other,
20035 higher priority settings."
20036 (interactive "FWrite agenda to file: ")
20037 (if (not (file-writable-p file))
20038 (error "Cannot write agenda to file %s" file))
20039 (cond
20040 ((string-match "\\.html?\\'" file) (require 'htmlize))
20041 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20042 (org-let (if nosettings nil org-agenda-exporter-settings)
20043 '(save-excursion
20044 (save-window-excursion
20045 (cond
20046 ((string-match "\\.html?\\'" file)
20047 (set-buffer (htmlize-buffer (current-buffer)))
20049 (when (and org-agenda-export-html-style
20050 (string-match "<style>" org-agenda-export-html-style))
20051 ;; replace <style> section with org-agenda-export-html-style
20052 (goto-char (point-min))
20053 (kill-region (- (search-forward "<style") 6)
20054 (search-forward "</style>"))
20055 (insert org-agenda-export-html-style))
20056 (write-file file)
20057 (kill-buffer (current-buffer))
20058 (message "HTML written to %s" file))
20059 ((string-match "\\.ps\\'" file)
20060 (ps-print-buffer-with-faces file)
20061 (message "Postscript written to %s" file))
20063 (let ((bs (buffer-string)))
20064 (find-file file)
20065 (insert bs)
20066 (save-buffer 0)
20067 (kill-buffer (current-buffer))
20068 (message "Plain text written to %s" file))))))
20069 (set-buffer org-agenda-buffer-name)))
20071 (defmacro org-no-read-only (&rest body)
20072 "Inhibit read-only for BODY."
20073 `(let ((inhibit-read-only t)) ,@body))
20075 (defun org-check-for-org-mode ()
20076 "Make sure current buffer is in org-mode. Error if not."
20077 (or (org-mode-p)
20078 (error "Cannot execute org-mode agenda command on buffer in %s."
20079 major-mode)))
20081 (defun org-fit-agenda-window ()
20082 "Fit the window to the buffer size."
20083 (and (memq org-agenda-window-setup '(reorganize-frame))
20084 (fboundp 'fit-window-to-buffer)
20085 (fit-window-to-buffer
20087 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20088 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20090 ;;; Agenda file list
20092 (defun org-agenda-files (&optional unrestricted)
20093 "Get the list of agenda files.
20094 Optional UNRESTRICTED means return the full list even if a restriction
20095 is currently in place."
20096 (let ((files
20097 (cond
20098 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20099 ((stringp org-agenda-files) (org-read-agenda-file-list))
20100 ((listp org-agenda-files) org-agenda-files)
20101 (t (error "Invalid value of `org-agenda-files'")))))
20102 (setq files (apply 'append
20103 (mapcar (lambda (f)
20104 (if (file-directory-p f)
20105 (directory-files f t
20106 org-agenda-file-regexp)
20107 (list f)))
20108 files)))
20109 (if org-agenda-skip-unavailable-files
20110 (delq nil
20111 (mapcar (function
20112 (lambda (file)
20113 (and (file-readable-p file) file)))
20114 files))
20115 files))) ; `org-check-agenda-file' will remove them from the list
20117 (defun org-edit-agenda-file-list ()
20118 "Edit the list of agenda files.
20119 Depending on setup, this either uses customize to edit the variable
20120 `org-agenda-files', or it visits the file that is holding the list. In the
20121 latter case, the buffer is set up in a way that saving it automatically kills
20122 the buffer and restores the previous window configuration."
20123 (interactive)
20124 (if (stringp org-agenda-files)
20125 (let ((cw (current-window-configuration)))
20126 (find-file org-agenda-files)
20127 (org-set-local 'org-window-configuration cw)
20128 (org-add-hook 'after-save-hook
20129 (lambda ()
20130 (set-window-configuration
20131 (prog1 org-window-configuration
20132 (kill-buffer (current-buffer))))
20133 (org-install-agenda-files-menu)
20134 (message "New agenda file list installed"))
20135 nil 'local)
20136 (message "%s" (substitute-command-keys
20137 "Edit list and finish with \\[save-buffer]")))
20138 (customize-variable 'org-agenda-files)))
20140 (defun org-store-new-agenda-file-list (list)
20141 "Set new value for the agenda file list and save it correcly."
20142 (if (stringp org-agenda-files)
20143 (let ((f org-agenda-files) b)
20144 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20145 (with-temp-file f
20146 (insert (mapconcat 'identity list "\n") "\n")))
20147 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20148 (setq org-agenda-files list)
20149 (customize-save-variable 'org-agenda-files org-agenda-files))))
20151 (defun org-read-agenda-file-list ()
20152 "Read the list of agenda files from a file."
20153 (when (stringp org-agenda-files)
20154 (with-temp-buffer
20155 (insert-file-contents org-agenda-files)
20156 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20159 ;;;###autoload
20160 (defun org-cycle-agenda-files ()
20161 "Cycle through the files in `org-agenda-files'.
20162 If the current buffer visits an agenda file, find the next one in the list.
20163 If the current buffer does not, find the first agenda file."
20164 (interactive)
20165 (let* ((fs (org-agenda-files t))
20166 (files (append fs (list (car fs))))
20167 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20168 file)
20169 (unless files (error "No agenda files"))
20170 (catch 'exit
20171 (while (setq file (pop files))
20172 (if (equal (file-truename file) tcf)
20173 (when (car files)
20174 (find-file (car files))
20175 (throw 'exit t))))
20176 (find-file (car fs)))
20177 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20179 (defun org-agenda-file-to-front (&optional to-end)
20180 "Move/add the current file to the top of the agenda file list.
20181 If the file is not present in the list, it is added to the front. If it is
20182 present, it is moved there. With optional argument TO-END, add/move to the
20183 end of the list."
20184 (interactive "P")
20185 (let ((org-agenda-skip-unavailable-files nil)
20186 (file-alist (mapcar (lambda (x)
20187 (cons (file-truename x) x))
20188 (org-agenda-files t)))
20189 (ctf (file-truename buffer-file-name))
20190 x had)
20191 (setq x (assoc ctf file-alist) had x)
20193 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20194 (if to-end
20195 (setq file-alist (append (delq x file-alist) (list x)))
20196 (setq file-alist (cons x (delq x file-alist))))
20197 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20198 (org-install-agenda-files-menu)
20199 (message "File %s to %s of agenda file list"
20200 (if had "moved" "added") (if to-end "end" "front"))))
20202 (defun org-remove-file (&optional file)
20203 "Remove current file from the list of files in variable `org-agenda-files'.
20204 These are the files which are being checked for agenda entries.
20205 Optional argument FILE means, use this file instead of the current."
20206 (interactive)
20207 (let* ((org-agenda-skip-unavailable-files nil)
20208 (file (or file buffer-file-name))
20209 (true-file (file-truename file))
20210 (afile (abbreviate-file-name file))
20211 (files (delq nil (mapcar
20212 (lambda (x)
20213 (if (equal true-file
20214 (file-truename x))
20215 nil x))
20216 (org-agenda-files t)))))
20217 (if (not (= (length files) (length (org-agenda-files t))))
20218 (progn
20219 (org-store-new-agenda-file-list files)
20220 (org-install-agenda-files-menu)
20221 (message "Removed file: %s" afile))
20222 (message "File was not in list: %s (not removed)" afile))))
20224 (defun org-file-menu-entry (file)
20225 (vector file (list 'find-file file) t))
20227 (defun org-check-agenda-file (file)
20228 "Make sure FILE exists. If not, ask user what to do."
20229 (when (not (file-exists-p file))
20230 (message "non-existent file %s. [R]emove from list or [A]bort?"
20231 (abbreviate-file-name file))
20232 (let ((r (downcase (read-char-exclusive))))
20233 (cond
20234 ((equal r ?r)
20235 (org-remove-file file)
20236 (throw 'nextfile t))
20237 (t (error "Abort"))))))
20239 ;;; Agenda prepare and finalize
20241 (defvar org-agenda-multi nil) ; dynammically scoped
20242 (defvar org-agenda-buffer-name "*Org Agenda*")
20243 (defvar org-pre-agenda-window-conf nil)
20244 (defvar org-agenda-name nil)
20245 (defun org-prepare-agenda (&optional name)
20246 (setq org-todo-keywords-for-agenda nil)
20247 (setq org-done-keywords-for-agenda nil)
20248 (if org-agenda-multi
20249 (progn
20250 (setq buffer-read-only nil)
20251 (goto-char (point-max))
20252 (unless (or (bobp) org-agenda-compact-blocks)
20253 (insert "\n" (make-string (window-width) ?=) "\n"))
20254 (narrow-to-region (point) (point-max)))
20255 (org-agenda-reset-markers)
20256 (org-prepare-agenda-buffers (org-agenda-files))
20257 (setq org-todo-keywords-for-agenda
20258 (org-uniquify org-todo-keywords-for-agenda))
20259 (setq org-done-keywords-for-agenda
20260 (org-uniquify org-done-keywords-for-agenda))
20261 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20262 (awin (get-buffer-window abuf)))
20263 (cond
20264 ((equal (current-buffer) abuf) nil)
20265 (awin (select-window awin))
20266 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20267 ((equal org-agenda-window-setup 'current-window)
20268 (switch-to-buffer abuf))
20269 ((equal org-agenda-window-setup 'other-window)
20270 (org-switch-to-buffer-other-window abuf))
20271 ((equal org-agenda-window-setup 'other-frame)
20272 (switch-to-buffer-other-frame abuf))
20273 ((equal org-agenda-window-setup 'reorganize-frame)
20274 (delete-other-windows)
20275 (org-switch-to-buffer-other-window abuf))))
20276 (setq buffer-read-only nil)
20277 (erase-buffer)
20278 (org-agenda-mode)
20279 (and name (not org-agenda-name)
20280 (org-set-local 'org-agenda-name name)))
20281 (setq buffer-read-only nil))
20283 (defun org-finalize-agenda ()
20284 "Finishing touch for the agenda buffer, called just before displaying it."
20285 (unless org-agenda-multi
20286 (save-excursion
20287 (let ((inhibit-read-only t))
20288 (goto-char (point-min))
20289 (while (org-activate-bracket-links (point-max))
20290 (add-text-properties (match-beginning 0) (match-end 0)
20291 '(face org-link)))
20292 (org-agenda-align-tags)
20293 (unless org-agenda-with-colors
20294 (remove-text-properties (point-min) (point-max) '(face nil))))
20295 (if (and (boundp 'org-overriding-columns-format)
20296 org-overriding-columns-format)
20297 (org-set-local 'org-overriding-columns-format
20298 org-overriding-columns-format))
20299 (if (and (boundp 'org-agenda-view-columns-initially)
20300 org-agenda-view-columns-initially)
20301 (org-agenda-columns))
20302 (when org-agenda-fontify-priorities
20303 (org-fontify-priorities))
20304 (run-hooks 'org-finalize-agenda-hook)
20305 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20308 (defun org-fontify-priorities ()
20309 "Make highest priority lines bold, and lowest italic."
20310 (interactive)
20311 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20312 (org-delete-overlay o)))
20313 (org-overlays-in (point-min) (point-max)))
20314 (save-excursion
20315 (let ((inhibit-read-only t)
20316 b e p ov h l)
20317 (goto-char (point-min))
20318 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20319 (setq h (or (get-char-property (point) 'org-highest-priority)
20320 org-highest-priority)
20321 l (or (get-char-property (point) 'org-lowest-priority)
20322 org-lowest-priority)
20323 p (string-to-char (match-string 1))
20324 b (match-beginning 0) e (point-at-eol)
20325 ov (org-make-overlay b e))
20326 (org-overlay-put
20327 ov 'face
20328 (cond ((listp org-agenda-fontify-priorities)
20329 (cdr (assoc p org-agenda-fontify-priorities)))
20330 ((equal p l) 'italic)
20331 ((equal p h) 'bold)))
20332 (org-overlay-put ov 'org-type 'org-priority)))))
20334 (defun org-prepare-agenda-buffers (files)
20335 "Create buffers for all agenda files, protect archived trees and comments."
20336 (interactive)
20337 (let ((pa '(:org-archived t))
20338 (pc '(:org-comment t))
20339 (pall '(:org-archived t :org-comment t))
20340 (inhibit-read-only t)
20341 (rea (concat ":" org-archive-tag ":"))
20342 bmp file re)
20343 (save-excursion
20344 (save-restriction
20345 (while (setq file (pop files))
20346 (if (bufferp file)
20347 (set-buffer file)
20348 (org-check-agenda-file file)
20349 (set-buffer (org-get-agenda-file-buffer file)))
20350 (widen)
20351 (setq bmp (buffer-modified-p))
20352 (org-refresh-category-properties)
20353 (setq org-todo-keywords-for-agenda
20354 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20355 (setq org-done-keywords-for-agenda
20356 (append org-done-keywords-for-agenda org-done-keywords))
20357 (save-excursion
20358 (remove-text-properties (point-min) (point-max) pall)
20359 (when org-agenda-skip-archived-trees
20360 (goto-char (point-min))
20361 (while (re-search-forward rea nil t)
20362 (if (org-on-heading-p t)
20363 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20364 (goto-char (point-min))
20365 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20366 (while (re-search-forward re nil t)
20367 (add-text-properties
20368 (match-beginning 0) (org-end-of-subtree t) pc)))
20369 (set-buffer-modified-p bmp))))))
20371 (defvar org-agenda-skip-function nil
20372 "Function to be called at each match during agenda construction.
20373 If this function returns nil, the current match should not be skipped.
20374 Otherwise, the function must return a position from where the search
20375 should be continued.
20376 This may also be a Lisp form, it will be evaluated.
20377 Never set this variable using `setq' or so, because then it will apply
20378 to all future agenda commands. Instead, bind it with `let' to scope
20379 it dynamically into the agenda-constructing command. A good way to set
20380 it is through options in org-agenda-custom-commands.")
20382 (defun org-agenda-skip ()
20383 "Throw to `:skip' in places that should be skipped.
20384 Also moves point to the end of the skipped region, so that search can
20385 continue from there."
20386 (let ((p (point-at-bol)) to fp)
20387 (and org-agenda-skip-archived-trees
20388 (get-text-property p :org-archived)
20389 (org-end-of-subtree t)
20390 (throw :skip t))
20391 (and (get-text-property p :org-comment)
20392 (org-end-of-subtree t)
20393 (throw :skip t))
20394 (if (equal (char-after p) ?#) (throw :skip t))
20395 (when (and (or (setq fp (functionp org-agenda-skip-function))
20396 (consp org-agenda-skip-function))
20397 (setq to (save-excursion
20398 (save-match-data
20399 (if fp
20400 (funcall org-agenda-skip-function)
20401 (eval org-agenda-skip-function))))))
20402 (goto-char to)
20403 (throw :skip t))))
20405 (defvar org-agenda-markers nil
20406 "List of all currently active markers created by `org-agenda'.")
20407 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20408 "Creation time of the last agenda marker.")
20410 (defun org-agenda-new-marker (&optional pos)
20411 "Return a new agenda marker.
20412 Org-mode keeps a list of these markers and resets them when they are
20413 no longer in use."
20414 (let ((m (copy-marker (or pos (point)))))
20415 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20416 (push m org-agenda-markers)
20419 (defun org-agenda-reset-markers ()
20420 "Reset markers created by `org-agenda'."
20421 (while org-agenda-markers
20422 (move-marker (pop org-agenda-markers) nil)))
20424 (defun org-get-agenda-file-buffer (file)
20425 "Get a buffer visiting FILE. If the buffer needs to be created, add
20426 it to the list of buffers which might be released later."
20427 (let ((buf (org-find-base-buffer-visiting file)))
20428 (if buf
20429 buf ; just return it
20430 ;; Make a new buffer and remember it
20431 (setq buf (find-file-noselect file))
20432 (if buf (push buf org-agenda-new-buffers))
20433 buf)))
20435 (defun org-release-buffers (blist)
20436 "Release all buffers in list, asking the user for confirmation when needed.
20437 When a buffer is unmodified, it is just killed. When modified, it is saved
20438 \(if the user agrees) and then killed."
20439 (let (buf file)
20440 (while (setq buf (pop blist))
20441 (setq file (buffer-file-name buf))
20442 (when (and (buffer-modified-p buf)
20443 file
20444 (y-or-n-p (format "Save file %s? " file)))
20445 (with-current-buffer buf (save-buffer)))
20446 (kill-buffer buf))))
20448 (defun org-get-category (&optional pos)
20449 "Get the category applying to position POS."
20450 (get-text-property (or pos (point)) 'org-category))
20452 ;;; Agenda timeline
20454 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20456 (defun org-timeline (&optional include-all)
20457 "Show a time-sorted view of the entries in the current org file.
20458 Only entries with a time stamp of today or later will be listed. With
20459 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20460 under the current date.
20461 If the buffer contains an active region, only check the region for
20462 dates."
20463 (interactive "P")
20464 (require 'calendar)
20465 (org-compile-prefix-format 'timeline)
20466 (org-set-sorting-strategy 'timeline)
20467 (let* ((dopast t)
20468 (dotodo include-all)
20469 (doclosed org-agenda-show-log)
20470 (entry buffer-file-name)
20471 (date (calendar-current-date))
20472 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20473 (end (if (org-region-active-p) (region-end) (point-max)))
20474 (day-numbers (org-get-all-dates beg end 'no-ranges
20475 t doclosed ; always include today
20476 org-timeline-show-empty-dates))
20477 (org-deadline-warning-days 0)
20478 (org-agenda-only-exact-dates t)
20479 (today (time-to-days (current-time)))
20480 (past t)
20481 args
20482 s e rtn d emptyp)
20483 (setq org-agenda-redo-command
20484 (list 'progn
20485 (list 'org-switch-to-buffer-other-window (current-buffer))
20486 (list 'org-timeline (list 'quote include-all))))
20487 (if (not dopast)
20488 ;; Remove past dates from the list of dates.
20489 (setq day-numbers (delq nil (mapcar (lambda(x)
20490 (if (>= x today) x nil))
20491 day-numbers))))
20492 (org-prepare-agenda (concat "Timeline "
20493 (file-name-nondirectory buffer-file-name)))
20494 (if doclosed (push :closed args))
20495 (push :timestamp args)
20496 (push :deadline args)
20497 (push :scheduled args)
20498 (push :sexp args)
20499 (if dotodo (push :todo args))
20500 (while (setq d (pop day-numbers))
20501 (if (and (listp d) (eq (car d) :omitted))
20502 (progn
20503 (setq s (point))
20504 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20505 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20506 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20507 (if (and (>= d today)
20508 dopast
20509 past)
20510 (progn
20511 (setq past nil)
20512 (insert (make-string 79 ?-) "\n")))
20513 (setq date (calendar-gregorian-from-absolute d))
20514 (setq s (point))
20515 (setq rtn (and (not emptyp)
20516 (apply 'org-agenda-get-day-entries entry
20517 date args)))
20518 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20519 (progn
20520 (insert
20521 (if (stringp org-agenda-format-date)
20522 (format-time-string org-agenda-format-date
20523 (org-time-from-absolute date))
20524 (funcall org-agenda-format-date date))
20525 "\n")
20526 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20527 (put-text-property s (1- (point)) 'org-date-line t)
20528 (if (equal d today)
20529 (put-text-property s (1- (point)) 'org-today t))
20530 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20531 (put-text-property s (1- (point)) 'day d)))))
20532 (goto-char (point-min))
20533 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20534 (point-min)))
20535 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20536 (org-finalize-agenda)
20537 (setq buffer-read-only t)))
20539 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20540 "Return a list of all relevant day numbers from BEG to END buffer positions.
20541 If NO-RANGES is non-nil, include only the start and end dates of a range,
20542 not every single day in the range. If FORCE-TODAY is non-nil, make
20543 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20544 inactive time stamps (those in square brackets) are included.
20545 When EMPTY is non-nil, also include days without any entries."
20546 (let ((re (concat
20547 (if pre-re pre-re "")
20548 (if inactive org-ts-regexp-both org-ts-regexp)))
20549 dates dates1 date day day1 day2 ts1 ts2)
20550 (if force-today
20551 (setq dates (list (time-to-days (current-time)))))
20552 (save-excursion
20553 (goto-char beg)
20554 (while (re-search-forward re end t)
20555 (setq day (time-to-days (org-time-string-to-time
20556 (substring (match-string 1) 0 10))))
20557 (or (memq day dates) (push day dates)))
20558 (unless no-ranges
20559 (goto-char beg)
20560 (while (re-search-forward org-tr-regexp end t)
20561 (setq ts1 (substring (match-string 1) 0 10)
20562 ts2 (substring (match-string 2) 0 10)
20563 day1 (time-to-days (org-time-string-to-time ts1))
20564 day2 (time-to-days (org-time-string-to-time ts2)))
20565 (while (< (setq day1 (1+ day1)) day2)
20566 (or (memq day1 dates) (push day1 dates)))))
20567 (setq dates (sort dates '<))
20568 (when empty
20569 (while (setq day (pop dates))
20570 (setq day2 (car dates))
20571 (push day dates1)
20572 (when (and day2 empty)
20573 (if (or (eq empty t)
20574 (and (numberp empty) (<= (- day2 day) empty)))
20575 (while (< (setq day (1+ day)) day2)
20576 (push (list day) dates1))
20577 (push (cons :omitted (- day2 day)) dates1))))
20578 (setq dates (nreverse dates1)))
20579 dates)))
20581 ;;; Agenda Daily/Weekly
20583 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20584 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20585 (defvar org-agenda-last-arguments nil
20586 "The arguments of the previous call to org-agenda")
20587 (defvar org-starting-day nil) ; local variable in the agenda buffer
20588 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20589 (defvar org-include-all-loc nil) ; local variable
20590 (defvar org-agenda-remove-date nil) ; dynamically scoped
20592 ;;;###autoload
20593 (defun org-agenda-list (&optional include-all start-day ndays)
20594 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20595 The view will be for the current day or week, but from the overview buffer
20596 you will be able to go to other days/weeks.
20598 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20599 all unfinished TODO items will also be shown, before the agenda.
20600 This feature is considered obsolete, please use the TODO list or a block
20601 agenda instead.
20603 With a numeric prefix argument in an interactive call, the agenda will
20604 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20605 the number of days. NDAYS defaults to `org-agenda-ndays'.
20607 START-DAY defaults to TODAY, or to the most recent match for the weekday
20608 given in `org-agenda-start-on-weekday'."
20609 (interactive "P")
20610 (if (and (integerp include-all) (> include-all 0))
20611 (setq ndays include-all include-all nil))
20612 (setq ndays (or ndays org-agenda-ndays)
20613 start-day (or start-day org-agenda-start-day))
20614 (if org-agenda-overriding-arguments
20615 (setq include-all (car org-agenda-overriding-arguments)
20616 start-day (nth 1 org-agenda-overriding-arguments)
20617 ndays (nth 2 org-agenda-overriding-arguments)))
20618 (if (stringp start-day)
20619 ;; Convert to an absolute day number
20620 (setq start-day (time-to-days (org-read-date nil t start-day))))
20621 (setq org-agenda-last-arguments (list include-all start-day ndays))
20622 (org-compile-prefix-format 'agenda)
20623 (org-set-sorting-strategy 'agenda)
20624 (require 'calendar)
20625 (let* ((org-agenda-start-on-weekday
20626 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20627 org-agenda-start-on-weekday nil))
20628 (thefiles (org-agenda-files))
20629 (files thefiles)
20630 (today (time-to-days
20631 (time-subtract (current-time)
20632 (list 0 (* 3600 org-extend-today-until) 0))))
20633 (sd (or start-day today))
20634 (start (if (or (null org-agenda-start-on-weekday)
20635 (< org-agenda-ndays 7))
20637 (let* ((nt (calendar-day-of-week
20638 (calendar-gregorian-from-absolute sd)))
20639 (n1 org-agenda-start-on-weekday)
20640 (d (- nt n1)))
20641 (- sd (+ (if (< d 0) 7 0) d)))))
20642 (day-numbers (list start))
20643 (day-cnt 0)
20644 (inhibit-redisplay (not debug-on-error))
20645 s e rtn rtnall file date d start-pos end-pos todayp nd)
20646 (setq org-agenda-redo-command
20647 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20648 ;; Make the list of days
20649 (setq ndays (or ndays org-agenda-ndays)
20650 nd ndays)
20651 (while (> ndays 1)
20652 (push (1+ (car day-numbers)) day-numbers)
20653 (setq ndays (1- ndays)))
20654 (setq day-numbers (nreverse day-numbers))
20655 (org-prepare-agenda "Day/Week")
20656 (org-set-local 'org-starting-day (car day-numbers))
20657 (org-set-local 'org-include-all-loc include-all)
20658 (org-set-local 'org-agenda-span
20659 (org-agenda-ndays-to-span nd))
20660 (when (and (or include-all org-agenda-include-all-todo)
20661 (member today day-numbers))
20662 (setq files thefiles
20663 rtnall nil)
20664 (while (setq file (pop files))
20665 (catch 'nextfile
20666 (org-check-agenda-file file)
20667 (setq date (calendar-gregorian-from-absolute today)
20668 rtn (org-agenda-get-day-entries
20669 file date :todo))
20670 (setq rtnall (append rtnall rtn))))
20671 (when rtnall
20672 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20673 (add-text-properties (point-min) (1- (point))
20674 (list 'face 'org-agenda-structure))
20675 (insert (org-finalize-agenda-entries rtnall) "\n")))
20676 (unless org-agenda-compact-blocks
20677 (setq s (point))
20678 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20679 "-agenda:\n")
20680 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20681 'org-date-line t)))
20682 (while (setq d (pop day-numbers))
20683 (setq date (calendar-gregorian-from-absolute d)
20684 s (point))
20685 (if (or (setq todayp (= d today))
20686 (and (not start-pos) (= d sd)))
20687 (setq start-pos (point))
20688 (if (and start-pos (not end-pos))
20689 (setq end-pos (point))))
20690 (setq files thefiles
20691 rtnall nil)
20692 (while (setq file (pop files))
20693 (catch 'nextfile
20694 (org-check-agenda-file file)
20695 (if org-agenda-show-log
20696 (setq rtn (org-agenda-get-day-entries
20697 file date
20698 :deadline :scheduled :timestamp :sexp :closed))
20699 (setq rtn (org-agenda-get-day-entries
20700 file date
20701 :deadline :scheduled :sexp :timestamp)))
20702 (setq rtnall (append rtnall rtn))))
20703 (if org-agenda-include-diary
20704 (progn
20705 (require 'diary-lib)
20706 (setq rtn (org-get-entries-from-diary date))
20707 (setq rtnall (append rtnall rtn))))
20708 (if (or rtnall org-agenda-show-all-dates)
20709 (progn
20710 (setq day-cnt (1+ day-cnt))
20711 (insert
20712 (if (stringp org-agenda-format-date)
20713 (format-time-string org-agenda-format-date
20714 (org-time-from-absolute date))
20715 (funcall org-agenda-format-date date))
20716 "\n")
20717 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20718 (put-text-property s (1- (point)) 'org-date-line t)
20719 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20720 (if todayp (put-text-property s (1- (point)) 'org-today t))
20721 (if rtnall (insert
20722 (org-finalize-agenda-entries
20723 (org-agenda-add-time-grid-maybe
20724 rtnall nd todayp))
20725 "\n"))
20726 (put-text-property s (1- (point)) 'day d)
20727 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20728 (goto-char (point-min))
20729 (org-fit-agenda-window)
20730 (unless (and (pos-visible-in-window-p (point-min))
20731 (pos-visible-in-window-p (point-max)))
20732 (goto-char (1- (point-max)))
20733 (recenter -1)
20734 (if (not (pos-visible-in-window-p (or start-pos 1)))
20735 (progn
20736 (goto-char (or start-pos 1))
20737 (recenter 1))))
20738 (goto-char (or start-pos 1))
20739 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20740 (org-finalize-agenda)
20741 (setq buffer-read-only t)
20742 (message "")))
20744 (defun org-agenda-ndays-to-span (n)
20745 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20747 ;;; Agenda TODO list
20749 (defvar org-select-this-todo-keyword nil)
20750 (defvar org-last-arg nil)
20752 ;;;###autoload
20753 (defun org-todo-list (arg)
20754 "Show all TODO entries from all agenda file in a single list.
20755 The prefix arg can be used to select a specific TODO keyword and limit
20756 the list to these. When using \\[universal-argument], you will be prompted
20757 for a keyword. A numeric prefix directly selects the Nth keyword in
20758 `org-todo-keywords-1'."
20759 (interactive "P")
20760 (require 'calendar)
20761 (org-compile-prefix-format 'todo)
20762 (org-set-sorting-strategy 'todo)
20763 (org-prepare-agenda "TODO")
20764 (let* ((today (time-to-days (current-time)))
20765 (date (calendar-gregorian-from-absolute today))
20766 (kwds org-todo-keywords-for-agenda)
20767 (completion-ignore-case t)
20768 (org-select-this-todo-keyword
20769 (if (stringp arg) arg
20770 (and arg (integerp arg) (> arg 0)
20771 (nth (1- arg) kwds))))
20772 rtn rtnall files file pos)
20773 (when (equal arg '(4))
20774 (setq org-select-this-todo-keyword
20775 (completing-read "Keyword (or KWD1|K2D2|...): "
20776 (mapcar 'list kwds) nil nil)))
20777 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
20778 (org-set-local 'org-last-arg arg)
20779 (setq org-agenda-redo-command
20780 '(org-todo-list (or current-prefix-arg org-last-arg)))
20781 (setq files (org-agenda-files)
20782 rtnall nil)
20783 (while (setq file (pop files))
20784 (catch 'nextfile
20785 (org-check-agenda-file file)
20786 (setq rtn (org-agenda-get-day-entries file date :todo))
20787 (setq rtnall (append rtnall rtn))))
20788 (if org-agenda-overriding-header
20789 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20790 nil 'face 'org-agenda-structure) "\n")
20791 (insert "Global list of TODO items of type: ")
20792 (add-text-properties (point-min) (1- (point))
20793 (list 'face 'org-agenda-structure))
20794 (setq pos (point))
20795 (insert (or org-select-this-todo-keyword "ALL") "\n")
20796 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20797 (setq pos (point))
20798 (unless org-agenda-multi
20799 (insert "Available with `N r': (0)ALL")
20800 (let ((n 0) s)
20801 (mapc (lambda (x)
20802 (setq s (format "(%d)%s" (setq n (1+ n)) x))
20803 (if (> (+ (current-column) (string-width s) 1) (frame-width))
20804 (insert "\n "))
20805 (insert " " s))
20806 kwds))
20807 (insert "\n"))
20808 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20809 (when rtnall
20810 (insert (org-finalize-agenda-entries rtnall) "\n"))
20811 (goto-char (point-min))
20812 (org-fit-agenda-window)
20813 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
20814 (org-finalize-agenda)
20815 (setq buffer-read-only t)))
20817 ;;; Agenda tags match
20819 ;;;###autoload
20820 (defun org-tags-view (&optional todo-only match)
20821 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
20822 The prefix arg TODO-ONLY limits the search to TODO entries."
20823 (interactive "P")
20824 (org-compile-prefix-format 'tags)
20825 (org-set-sorting-strategy 'tags)
20826 (let* ((org-tags-match-list-sublevels
20827 (if todo-only t org-tags-match-list-sublevels))
20828 (completion-ignore-case t)
20829 rtn rtnall files file pos matcher
20830 buffer)
20831 (setq matcher (org-make-tags-matcher match)
20832 match (car matcher) matcher (cdr matcher))
20833 (org-prepare-agenda (concat "TAGS " match))
20834 (setq org-agenda-redo-command
20835 (list 'org-tags-view (list 'quote todo-only)
20836 (list 'if 'current-prefix-arg nil match)))
20837 (setq files (org-agenda-files)
20838 rtnall nil)
20839 (while (setq file (pop files))
20840 (catch 'nextfile
20841 (org-check-agenda-file file)
20842 (setq buffer (if (file-exists-p file)
20843 (org-get-agenda-file-buffer file)
20844 (error "No such file %s" file)))
20845 (if (not buffer)
20846 ;; If file does not exist, merror message to agenda
20847 (setq rtn (list
20848 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20849 rtnall (append rtnall rtn))
20850 (with-current-buffer buffer
20851 (unless (org-mode-p)
20852 (error "Agenda file %s is not in `org-mode'" file))
20853 (save-excursion
20854 (save-restriction
20855 (if org-agenda-restrict
20856 (narrow-to-region org-agenda-restrict-begin
20857 org-agenda-restrict-end)
20858 (widen))
20859 (setq rtn (org-scan-tags 'agenda matcher todo-only))
20860 (setq rtnall (append rtnall rtn))))))))
20861 (if org-agenda-overriding-header
20862 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20863 nil 'face 'org-agenda-structure) "\n")
20864 (insert "Headlines with TAGS match: ")
20865 (add-text-properties (point-min) (1- (point))
20866 (list 'face 'org-agenda-structure))
20867 (setq pos (point))
20868 (insert match "\n")
20869 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20870 (setq pos (point))
20871 (unless org-agenda-multi
20872 (insert "Press `C-u r' to search again with new search string\n"))
20873 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
20874 (when rtnall
20875 (insert (org-finalize-agenda-entries rtnall) "\n"))
20876 (goto-char (point-min))
20877 (org-fit-agenda-window)
20878 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
20879 (org-finalize-agenda)
20880 (setq buffer-read-only t)))
20882 ;;; Agenda Finding stuck projects
20884 (defvar org-agenda-skip-regexp nil
20885 "Regular expression used in skipping subtrees for the agenda.
20886 This is basically a temporary global variable that can be set and then
20887 used by user-defined selections using `org-agenda-skip-function'.")
20889 (defvar org-agenda-overriding-header nil
20890 "When this is set during todo and tags searches, will replace header.")
20892 (defun org-agenda-skip-subtree-when-regexp-matches ()
20893 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
20894 If yes, it returns the end position of this tree, causing agenda commands
20895 to skip this subtree. This is a function that can be put into
20896 `org-agenda-skip-function' for the duration of a command."
20897 (let ((end (save-excursion (org-end-of-subtree t)))
20898 skip)
20899 (save-excursion
20900 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
20901 (and skip end)))
20903 (defun org-agenda-skip-entry-if (&rest conditions)
20904 "Skip entry if any of CONDITIONS is true.
20905 See `org-agenda-skip-if' for details."
20906 (org-agenda-skip-if nil conditions))
20908 (defun org-agenda-skip-subtree-if (&rest conditions)
20909 "Skip entry if any of CONDITIONS is true.
20910 See `org-agenda-skip-if' for details."
20911 (org-agenda-skip-if t conditions))
20913 (defun org-agenda-skip-if (subtree conditions)
20914 "Checks current entity for CONDITIONS.
20915 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
20916 the entry, i.e. the text before the next heading is checked.
20918 CONDITIONS is a list of symbols, boolean OR is used to combine the results
20919 from different tests. Valid conditions are:
20921 scheduled Check if there is a scheduled cookie
20922 notscheduled Check if there is no scheduled cookie
20923 deadline Check if there is a deadline
20924 notdeadline Check if there is no deadline
20925 regexp Check if regexp matches
20926 notregexp Check if regexp does not match.
20928 The regexp is taken from the conditions list, it must come right after
20929 the `regexp' or `notregexp' element.
20931 If any of these conditions is met, this function returns the end point of
20932 the entity, causing the search to continue from there. This is a function
20933 that can be put into `org-agenda-skip-function' for the duration of a command."
20934 (let (beg end m)
20935 (org-back-to-heading t)
20936 (setq beg (point)
20937 end (if subtree
20938 (progn (org-end-of-subtree t) (point))
20939 (progn (outline-next-heading) (1- (point)))))
20940 (goto-char beg)
20941 (and
20943 (and (memq 'scheduled conditions)
20944 (re-search-forward org-scheduled-time-regexp end t))
20945 (and (memq 'notscheduled conditions)
20946 (not (re-search-forward org-scheduled-time-regexp end t)))
20947 (and (memq 'deadline conditions)
20948 (re-search-forward org-deadline-time-regexp end t))
20949 (and (memq 'notdeadline conditions)
20950 (not (re-search-forward org-deadline-time-regexp end t)))
20951 (and (setq m (memq 'regexp conditions))
20952 (stringp (nth 1 m))
20953 (re-search-forward (nth 1 m) end t))
20954 (and (setq m (memq 'notregexp conditions))
20955 (stringp (nth 1 m))
20956 (not (re-search-forward (nth 1 m) end t))))
20957 end)))
20959 ;;;###autoload
20960 (defun org-agenda-list-stuck-projects (&rest ignore)
20961 "Create agenda view for projects that are stuck.
20962 Stuck projects are project that have no next actions. For the definitions
20963 of what a project is and how to check if it stuck, customize the variable
20964 `org-stuck-projects'.
20965 MATCH is being ignored."
20966 (interactive)
20967 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
20968 ;; FIXME: we could have used org-agenda-skip-if here.
20969 (org-agenda-overriding-header "List of stuck projects: ")
20970 (matcher (nth 0 org-stuck-projects))
20971 (todo (nth 1 org-stuck-projects))
20972 (todo-wds (if (member "*" todo)
20973 (progn
20974 (org-prepare-agenda-buffers (org-agenda-files))
20975 (org-delete-all
20976 org-done-keywords-for-agenda
20977 (copy-sequence org-todo-keywords-for-agenda)))
20978 todo))
20979 (todo-re (concat "^\\*+[ \t]+\\("
20980 (mapconcat 'identity todo-wds "\\|")
20981 "\\)\\>"))
20982 (tags (nth 2 org-stuck-projects))
20983 (tags-re (if (member "*" tags)
20984 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
20985 (concat "^\\*+ .*:\\("
20986 (mapconcat 'identity tags "\\|")
20987 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
20988 (gen-re (nth 3 org-stuck-projects))
20989 (re-list
20990 (delq nil
20991 (list
20992 (if todo todo-re)
20993 (if tags tags-re)
20994 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
20995 gen-re)))))
20996 (setq org-agenda-skip-regexp
20997 (if re-list
20998 (mapconcat 'identity re-list "\\|")
20999 (error "No information how to identify unstuck projects")))
21000 (org-tags-view nil matcher)
21001 (with-current-buffer org-agenda-buffer-name
21002 (setq org-agenda-redo-command
21003 '(org-agenda-list-stuck-projects
21004 (or current-prefix-arg org-last-arg))))))
21006 ;;; Diary integration
21008 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21010 (defun org-get-entries-from-diary (date)
21011 "Get the (Emacs Calendar) diary entries for DATE."
21012 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21013 (diary-display-hook '(fancy-diary-display))
21014 (pop-up-frames nil)
21015 (list-diary-entries-hook
21016 (cons 'org-diary-default-entry list-diary-entries-hook))
21017 (diary-file-name-prefix-function nil) ; turn this feature off
21018 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21019 entries
21020 (org-disable-agenda-to-diary t))
21021 (save-excursion
21022 (save-window-excursion
21023 (funcall (if (fboundp 'diary-list-entries)
21024 'diary-list-entries 'list-diary-entries)
21025 date 1)))
21026 (if (not (get-buffer fancy-diary-buffer))
21027 (setq entries nil)
21028 (with-current-buffer fancy-diary-buffer
21029 (setq buffer-read-only nil)
21030 (if (zerop (buffer-size))
21031 ;; No entries
21032 (setq entries nil)
21033 ;; Omit the date and other unnecessary stuff
21034 (org-agenda-cleanup-fancy-diary)
21035 ;; Add prefix to each line and extend the text properties
21036 (if (zerop (buffer-size))
21037 (setq entries nil)
21038 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21039 (set-buffer-modified-p nil)
21040 (kill-buffer fancy-diary-buffer)))
21041 (when entries
21042 (setq entries (org-split-string entries "\n"))
21043 (setq entries
21044 (mapcar
21045 (lambda (x)
21046 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21047 ;; Extend the text properties to the beginning of the line
21048 (org-add-props x (text-properties-at (1- (length x)) x)
21049 'type "diary" 'date date))
21050 entries)))))
21052 (defun org-agenda-cleanup-fancy-diary ()
21053 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21054 This gets rid of the date, the underline under the date, and
21055 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21056 date. It also removes lines that contain only whitespace."
21057 (goto-char (point-min))
21058 (if (looking-at ".*?:[ \t]*")
21059 (progn
21060 (replace-match "")
21061 (re-search-forward "\n=+$" nil t)
21062 (replace-match "")
21063 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21064 (re-search-forward "\n=+$" nil t)
21065 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21066 (goto-char (point-min))
21067 (while (re-search-forward "^ +\n" nil t)
21068 (replace-match ""))
21069 (goto-char (point-min))
21070 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21071 (replace-match "")))
21073 ;; Make sure entries from the diary have the right text properties.
21074 (eval-after-load "diary-lib"
21075 '(if (boundp 'diary-modify-entry-list-string-function)
21076 ;; We can rely on the hook, nothing to do
21078 ;; Hook not avaiable, must use advice to make this work
21079 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21080 "Make the position visible."
21081 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21082 (stringp string)
21083 buffer-file-name)
21084 (setq string (org-modify-diary-entry-string string))))))
21086 (defun org-modify-diary-entry-string (string)
21087 "Add text properties to string, allowing org-mode to act on it."
21088 (org-add-props string nil
21089 'mouse-face 'highlight
21090 'keymap org-agenda-keymap
21091 'help-echo (if buffer-file-name
21092 (format "mouse-2 or RET jump to diary file %s"
21093 (abbreviate-file-name buffer-file-name))
21095 'org-agenda-diary-link t
21096 'org-marker (org-agenda-new-marker (point-at-bol))))
21098 (defun org-diary-default-entry ()
21099 "Add a dummy entry to the diary.
21100 Needed to avoid empty dates which mess up holiday display."
21101 ;; Catch the error if dealing with the new add-to-diary-alist
21102 (when org-disable-agenda-to-diary
21103 (condition-case nil
21104 (add-to-diary-list original-date "Org-mode dummy" "")
21105 (error
21106 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21108 ;;;###autoload
21109 (defun org-diary (&rest args)
21110 "Return diary information from org-files.
21111 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21112 It accesses org files and extracts information from those files to be
21113 listed in the diary. The function accepts arguments specifying what
21114 items should be listed. The following arguments are allowed:
21116 :timestamp List the headlines of items containing a date stamp or
21117 date range matching the selected date. Deadlines will
21118 also be listed, on the expiration day.
21120 :sexp List entries resulting from diary-like sexps.
21122 :deadline List any deadlines past due, or due within
21123 `org-deadline-warning-days'. The listing occurs only
21124 in the diary for *today*, not at any other date. If
21125 an entry is marked DONE, it is no longer listed.
21127 :scheduled List all items which are scheduled for the given date.
21128 The diary for *today* also contains items which were
21129 scheduled earlier and are not yet marked DONE.
21131 :todo List all TODO items from the org-file. This may be a
21132 long list - so this is not turned on by default.
21133 Like deadlines, these entries only show up in the
21134 diary for *today*, not at any other date.
21136 The call in the diary file should look like this:
21138 &%%(org-diary) ~/path/to/some/orgfile.org
21140 Use a separate line for each org file to check. Or, if you omit the file name,
21141 all files listed in `org-agenda-files' will be checked automatically:
21143 &%%(org-diary)
21145 If you don't give any arguments (as in the example above), the default
21146 arguments (:deadline :scheduled :timestamp :sexp) are used.
21147 So the example above may also be written as
21149 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21151 The function expects the lisp variables `entry' and `date' to be provided
21152 by the caller, because this is how the calendar works. Don't use this
21153 function from a program - use `org-agenda-get-day-entries' instead."
21154 (when (> (- (time-to-seconds (current-time))
21155 org-agenda-last-marker-time)
21157 (org-agenda-reset-markers))
21158 (org-compile-prefix-format 'agenda)
21159 (org-set-sorting-strategy 'agenda)
21160 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21161 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21162 (list entry)
21163 (org-agenda-files t)))
21164 file rtn results)
21165 (org-prepare-agenda-buffers files)
21166 ;; If this is called during org-agenda, don't return any entries to
21167 ;; the calendar. Org Agenda will list these entries itself.
21168 (if org-disable-agenda-to-diary (setq files nil))
21169 (while (setq file (pop files))
21170 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21171 (setq results (append results rtn)))
21172 (if results
21173 (concat (org-finalize-agenda-entries results) "\n"))))
21175 ;;; Agenda entry finders
21177 (defun org-agenda-get-day-entries (file date &rest args)
21178 "Does the work for `org-diary' and `org-agenda'.
21179 FILE is the path to a file to be checked for entries. DATE is date like
21180 the one returned by `calendar-current-date'. ARGS are symbols indicating
21181 which kind of entries should be extracted. For details about these, see
21182 the documentation of `org-diary'."
21183 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21184 (let* ((org-startup-folded nil)
21185 (org-startup-align-all-tables nil)
21186 (buffer (if (file-exists-p file)
21187 (org-get-agenda-file-buffer file)
21188 (error "No such file %s" file)))
21189 arg results rtn)
21190 (if (not buffer)
21191 ;; If file does not exist, make sure an error message ends up in diary
21192 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21193 (with-current-buffer buffer
21194 (unless (org-mode-p)
21195 (error "Agenda file %s is not in `org-mode'" file))
21196 (let ((case-fold-search nil))
21197 (save-excursion
21198 (save-restriction
21199 (if org-agenda-restrict
21200 (narrow-to-region org-agenda-restrict-begin
21201 org-agenda-restrict-end)
21202 (widen))
21203 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21204 (while (setq arg (pop args))
21205 (cond
21206 ((and (eq arg :todo)
21207 (equal date (calendar-current-date)))
21208 (setq rtn (org-agenda-get-todos))
21209 (setq results (append results rtn)))
21210 ((eq arg :timestamp)
21211 (setq rtn (org-agenda-get-blocks))
21212 (setq results (append results rtn))
21213 (setq rtn (org-agenda-get-timestamps))
21214 (setq results (append results rtn)))
21215 ((eq arg :sexp)
21216 (setq rtn (org-agenda-get-sexps))
21217 (setq results (append results rtn)))
21218 ((eq arg :scheduled)
21219 (setq rtn (org-agenda-get-scheduled))
21220 (setq results (append results rtn)))
21221 ((eq arg :closed)
21222 (setq rtn (org-agenda-get-closed))
21223 (setq results (append results rtn)))
21224 ((eq arg :deadline)
21225 (setq rtn (org-agenda-get-deadlines))
21226 (setq results (append results rtn))))))))
21227 results))))
21229 (defun org-entry-is-todo-p ()
21230 (member (org-get-todo-state) org-not-done-keywords))
21232 (defun org-entry-is-done-p ()
21233 (member (org-get-todo-state) org-done-keywords))
21235 (defun org-get-todo-state ()
21236 (save-excursion
21237 (org-back-to-heading t)
21238 (and (looking-at org-todo-line-regexp)
21239 (match-end 2)
21240 (match-string 2))))
21242 (defun org-at-date-range-p (&optional inactive-ok)
21243 "Is the cursor inside a date range?"
21244 (interactive)
21245 (save-excursion
21246 (catch 'exit
21247 (let ((pos (point)))
21248 (skip-chars-backward "^[<\r\n")
21249 (skip-chars-backward "<[")
21250 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21251 (>= (match-end 0) pos)
21252 (throw 'exit t))
21253 (skip-chars-backward "^<[\r\n")
21254 (skip-chars-backward "<[")
21255 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21256 (>= (match-end 0) pos)
21257 (throw 'exit t)))
21258 nil)))
21260 (defun org-agenda-get-todos ()
21261 "Return the TODO information for agenda display."
21262 (let* ((props (list 'face nil
21263 'done-face 'org-done
21264 'org-not-done-regexp org-not-done-regexp
21265 'org-todo-regexp org-todo-regexp
21266 'mouse-face 'highlight
21267 'keymap org-agenda-keymap
21268 'help-echo
21269 (format "mouse-2 or RET jump to org file %s"
21270 (abbreviate-file-name buffer-file-name))))
21271 ;; FIXME: get rid of the \n at some point but watch out
21272 (regexp (concat "^\\*+[ \t]+\\("
21273 (if org-select-this-todo-keyword
21274 (if (equal org-select-this-todo-keyword "*")
21275 org-todo-regexp
21276 (concat "\\<\\("
21277 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21278 "\\)\\>"))
21279 org-not-done-regexp)
21280 "[^\n\r]*\\)"))
21281 marker priority category tags
21282 ee txt beg end)
21283 (goto-char (point-min))
21284 (while (re-search-forward regexp nil t)
21285 (catch :skip
21286 (save-match-data
21287 (beginning-of-line)
21288 (setq beg (point) end (progn (outline-next-heading) (point)))
21289 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21290 (re-search-forward org-ts-regexp end t))
21291 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21292 (re-search-forward org-scheduled-time-regexp end t))
21293 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21294 (re-search-forward org-deadline-time-regexp end t)
21295 (org-deadline-close (match-string 1))))
21296 (goto-char (1+ beg))
21297 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21298 (throw :skip nil)))
21299 (goto-char beg)
21300 (org-agenda-skip)
21301 (goto-char (match-beginning 1))
21302 (setq marker (org-agenda-new-marker (match-beginning 0))
21303 category (org-get-category)
21304 tags (org-get-tags-at (point))
21305 txt (org-format-agenda-item "" (match-string 1) category tags)
21306 priority (1+ (org-get-priority txt)))
21307 (org-add-props txt props
21308 'org-marker marker 'org-hd-marker marker
21309 'priority priority 'org-category category
21310 'type "todo")
21311 (push txt ee)
21312 (if org-agenda-todo-list-sublevels
21313 (goto-char (match-end 1))
21314 (org-end-of-subtree 'invisible))))
21315 (nreverse ee)))
21317 (defconst org-agenda-no-heading-message
21318 "No heading for this item in buffer or region.")
21320 (defun org-agenda-get-timestamps ()
21321 "Return the date stamp information for agenda display."
21322 (let* ((props (list 'face nil
21323 'org-not-done-regexp org-not-done-regexp
21324 'org-todo-regexp org-todo-regexp
21325 'mouse-face 'highlight
21326 'keymap org-agenda-keymap
21327 'help-echo
21328 (format "mouse-2 or RET jump to org file %s"
21329 (abbreviate-file-name buffer-file-name))))
21330 (d1 (calendar-absolute-from-gregorian date))
21331 (remove-re
21332 (concat
21333 (regexp-quote
21334 (format-time-string
21335 "<%Y-%m-%d"
21336 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21337 ".*?>"))
21338 (regexp
21339 (concat
21340 (regexp-quote
21341 (substring
21342 (format-time-string
21343 (car org-time-stamp-formats)
21344 (apply 'encode-time ; DATE bound by calendar
21345 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21346 0 11))
21347 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21348 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21349 marker hdmarker deadlinep scheduledp donep tmp priority category
21350 ee txt timestr tags b0 b3 e3 head)
21351 (goto-char (point-min))
21352 (while (re-search-forward regexp nil t)
21353 (setq b0 (match-beginning 0)
21354 b3 (match-beginning 3) e3 (match-end 3))
21355 (catch :skip
21356 (and (org-at-date-range-p) (throw :skip nil))
21357 (org-agenda-skip)
21358 (if (and (match-end 1)
21359 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21360 (throw :skip nil))
21361 (if (and e3
21362 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21363 (throw :skip nil))
21364 (setq marker (org-agenda-new-marker b0)
21365 category (org-get-category b0)
21366 tmp (buffer-substring (max (point-min)
21367 (- b0 org-ds-keyword-length))
21369 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21370 deadlinep (string-match org-deadline-regexp tmp)
21371 scheduledp (string-match org-scheduled-regexp tmp)
21372 donep (org-entry-is-done-p))
21373 (if (or scheduledp deadlinep) (throw :skip t))
21374 (if (string-match ">" timestr)
21375 ;; substring should only run to end of time stamp
21376 (setq timestr (substring timestr 0 (match-end 0))))
21377 (save-excursion
21378 (if (re-search-backward "^\\*+ " nil t)
21379 (progn
21380 (goto-char (match-beginning 0))
21381 (setq hdmarker (org-agenda-new-marker)
21382 tags (org-get-tags-at))
21383 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21384 (setq head (match-string 1))
21385 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21386 (setq txt (org-format-agenda-item
21387 nil head category tags timestr nil
21388 remove-re)))
21389 (setq txt org-agenda-no-heading-message))
21390 (setq priority (org-get-priority txt))
21391 (org-add-props txt props
21392 'org-marker marker 'org-hd-marker hdmarker)
21393 (org-add-props txt nil 'priority priority
21394 'org-category category 'date date
21395 'type "timestamp")
21396 (push txt ee))
21397 (outline-next-heading)))
21398 (nreverse ee)))
21400 (defun org-agenda-get-sexps ()
21401 "Return the sexp information for agenda display."
21402 (require 'diary-lib)
21403 (let* ((props (list 'face nil
21404 'mouse-face 'highlight
21405 'keymap org-agenda-keymap
21406 'help-echo
21407 (format "mouse-2 or RET jump to org file %s"
21408 (abbreviate-file-name buffer-file-name))))
21409 (regexp "^&?%%(")
21410 marker category ee txt tags entry result beg b sexp sexp-entry)
21411 (goto-char (point-min))
21412 (while (re-search-forward regexp nil t)
21413 (catch :skip
21414 (org-agenda-skip)
21415 (setq beg (match-beginning 0))
21416 (goto-char (1- (match-end 0)))
21417 (setq b (point))
21418 (forward-sexp 1)
21419 (setq sexp (buffer-substring b (point)))
21420 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21421 (org-trim (match-string 1))
21422 ""))
21423 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21424 (when result
21425 (setq marker (org-agenda-new-marker beg)
21426 category (org-get-category beg))
21428 (if (string-match "\\S-" result)
21429 (setq txt result)
21430 (setq txt "SEXP entry returned empty string"))
21432 (setq txt (org-format-agenda-item
21433 "" txt category tags 'time))
21434 (org-add-props txt props 'org-marker marker)
21435 (org-add-props txt nil
21436 'org-category category 'date date
21437 'type "sexp")
21438 (push txt ee))))
21439 (nreverse ee)))
21441 (defun org-agenda-get-closed ()
21442 "Return the logged TODO entries for agenda display."
21443 (let* ((props (list 'mouse-face 'highlight
21444 'org-not-done-regexp org-not-done-regexp
21445 'org-todo-regexp org-todo-regexp
21446 'keymap org-agenda-keymap
21447 'help-echo
21448 (format "mouse-2 or RET jump to org file %s"
21449 (abbreviate-file-name buffer-file-name))))
21450 (regexp (concat
21451 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21452 (regexp-quote
21453 (substring
21454 (format-time-string
21455 (car org-time-stamp-formats)
21456 (apply 'encode-time ; DATE bound by calendar
21457 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21458 1 11))))
21459 marker hdmarker priority category tags closedp
21460 ee txt timestr)
21461 (goto-char (point-min))
21462 (while (re-search-forward regexp nil t)
21463 (catch :skip
21464 (org-agenda-skip)
21465 (setq marker (org-agenda-new-marker (match-beginning 0))
21466 closedp (equal (match-string 1) org-closed-string)
21467 category (org-get-category (match-beginning 0))
21468 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21469 ;; donep (org-entry-is-done-p)
21471 (if (string-match "\\]" timestr)
21472 ;; substring should only run to end of time stamp
21473 (setq timestr (substring timestr 0 (match-end 0))))
21474 (save-excursion
21475 (if (re-search-backward "^\\*+ " nil t)
21476 (progn
21477 (goto-char (match-beginning 0))
21478 (setq hdmarker (org-agenda-new-marker)
21479 tags (org-get-tags-at))
21480 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21481 (setq txt (org-format-agenda-item
21482 (if closedp "Closed: " "Clocked: ")
21483 (match-string 1) category tags timestr)))
21484 (setq txt org-agenda-no-heading-message))
21485 (setq priority 100000)
21486 (org-add-props txt props
21487 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21488 'priority priority 'org-category category
21489 'type "closed" 'date date
21490 'undone-face 'org-warning 'done-face 'org-done)
21491 (push txt ee))
21492 (goto-char (point-at-eol))))
21493 (nreverse ee)))
21495 (defun org-agenda-get-deadlines ()
21496 "Return the deadline information for agenda display."
21497 (let* ((props (list 'mouse-face 'highlight
21498 'org-not-done-regexp org-not-done-regexp
21499 'org-todo-regexp org-todo-regexp
21500 'keymap org-agenda-keymap
21501 'help-echo
21502 (format "mouse-2 or RET jump to org file %s"
21503 (abbreviate-file-name buffer-file-name))))
21504 (regexp org-deadline-time-regexp)
21505 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21506 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21507 d2 diff dfrac wdays pos pos1 category tags
21508 ee txt head face s upcomingp donep timestr)
21509 (goto-char (point-min))
21510 (while (re-search-forward regexp nil t)
21511 (catch :skip
21512 (org-agenda-skip)
21513 (setq s (match-string 1)
21514 pos (1- (match-beginning 1))
21515 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21516 diff (- d2 d1)
21517 wdays (org-get-wdays s)
21518 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21519 upcomingp (and todayp (> diff 0)))
21520 ;; When to show a deadline in the calendar:
21521 ;; If the expiration is within wdays warning time.
21522 ;; Past-due deadlines are only shown on the current date
21523 (if (or (and (<= diff wdays)
21524 (and todayp (not org-agenda-only-exact-dates)))
21525 (= diff 0))
21526 (save-excursion
21527 (setq category (org-get-category))
21528 (if (re-search-backward "^\\*+[ \t]+" nil t)
21529 (progn
21530 (goto-char (match-end 0))
21531 (setq pos1 (match-beginning 0))
21532 (setq tags (org-get-tags-at pos1))
21533 (setq head (buffer-substring-no-properties
21534 (point)
21535 (progn (skip-chars-forward "^\r\n")
21536 (point))))
21537 (setq donep (string-match org-looking-at-done-regexp head))
21538 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21539 (setq timestr
21540 (concat (substring s (match-beginning 1)) " "))
21541 (setq timestr 'time))
21542 (if (and donep
21543 (or org-agenda-skip-deadline-if-done
21544 (not (= diff 0))))
21545 (setq txt nil)
21546 (setq txt (org-format-agenda-item
21547 (if (= diff 0)
21548 (car org-agenda-deadline-leaders)
21549 (format (nth 1 org-agenda-deadline-leaders)
21550 diff))
21551 head category tags timestr))))
21552 (setq txt org-agenda-no-heading-message))
21553 (when txt
21554 (setq face (org-agenda-deadline-face dfrac))
21555 (org-add-props txt props
21556 'org-marker (org-agenda-new-marker pos)
21557 'org-hd-marker (org-agenda-new-marker pos1)
21558 'priority (+ (- diff)
21559 (org-get-priority txt))
21560 'org-category category
21561 'type (if upcomingp "upcoming-deadline" "deadline")
21562 'date (if upcomingp date d2)
21563 'face (if donep 'org-done face)
21564 'undone-face face 'done-face 'org-done)
21565 (push txt ee))))))
21566 (nreverse ee)))
21568 (defun org-agenda-deadline-face (fraction)
21569 "Return the face to displaying a deadline item.
21570 FRACTION is what fraction of the head-warning time has passed."
21571 (let ((faces org-agenda-deadline-faces) f)
21572 (catch 'exit
21573 (while (setq f (pop faces))
21574 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21576 (defun org-agenda-get-scheduled ()
21577 "Return the scheduled information for agenda display."
21578 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21579 'org-todo-regexp org-todo-regexp
21580 'done-face 'org-done
21581 'mouse-face 'highlight
21582 'keymap org-agenda-keymap
21583 'help-echo
21584 (format "mouse-2 or RET jump to org file %s"
21585 (abbreviate-file-name buffer-file-name))))
21586 (regexp org-scheduled-time-regexp)
21587 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21588 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21589 d2 diff pos pos1 category tags
21590 ee txt head pastschedp donep face timestr s)
21591 (goto-char (point-min))
21592 (while (re-search-forward regexp nil t)
21593 (catch :skip
21594 (org-agenda-skip)
21595 (setq s (match-string 1)
21596 pos (1- (match-beginning 1))
21597 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21598 ;;; is this right?
21599 ;;; do we need to do this for deadleine too????
21600 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21601 diff (- d2 d1))
21602 (setq pastschedp (and todayp (< diff 0)))
21603 ;; When to show a scheduled item in the calendar:
21604 ;; If it is on or past the date.
21605 (if (or (and (< diff 0)
21606 (and todayp (not org-agenda-only-exact-dates)))
21607 (= diff 0))
21608 (save-excursion
21609 (setq category (org-get-category))
21610 (if (re-search-backward "^\\*+[ \t]+" nil t)
21611 (progn
21612 (goto-char (match-end 0))
21613 (setq pos1 (match-beginning 0))
21614 (setq tags (org-get-tags-at))
21615 (setq head (buffer-substring-no-properties
21616 (point)
21617 (progn (skip-chars-forward "^\r\n") (point))))
21618 (setq donep (string-match org-looking-at-done-regexp head))
21619 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21620 (setq timestr
21621 (concat (substring s (match-beginning 1)) " "))
21622 (setq timestr 'time))
21623 (if (and donep
21624 (or org-agenda-skip-scheduled-if-done
21625 (not (= diff 0))))
21626 (setq txt nil)
21627 (setq txt (org-format-agenda-item
21628 (if (= diff 0)
21629 (car org-agenda-scheduled-leaders)
21630 (format (nth 1 org-agenda-scheduled-leaders)
21631 (- 1 diff)))
21632 head category tags timestr))))
21633 (setq txt org-agenda-no-heading-message))
21634 (when txt
21635 (setq face (if pastschedp
21636 'org-scheduled-previously
21637 'org-scheduled-today))
21638 (org-add-props txt props
21639 'undone-face face
21640 'face (if donep 'org-done face)
21641 'org-marker (org-agenda-new-marker pos)
21642 'org-hd-marker (org-agenda-new-marker pos1)
21643 'type (if pastschedp "past-scheduled" "scheduled")
21644 'date (if pastschedp d2 date)
21645 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21646 'org-category category)
21647 (push txt ee))))))
21648 (nreverse ee)))
21650 (defun org-agenda-get-blocks ()
21651 "Return the date-range information for agenda display."
21652 (let* ((props (list 'face nil
21653 'org-not-done-regexp org-not-done-regexp
21654 'org-todo-regexp org-todo-regexp
21655 'mouse-face 'highlight
21656 'keymap org-agenda-keymap
21657 'help-echo
21658 (format "mouse-2 or RET jump to org file %s"
21659 (abbreviate-file-name buffer-file-name))))
21660 (regexp org-tr-regexp)
21661 (d0 (calendar-absolute-from-gregorian date))
21662 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21663 donep head)
21664 (goto-char (point-min))
21665 (while (re-search-forward regexp nil t)
21666 (catch :skip
21667 (org-agenda-skip)
21668 (setq pos (point))
21669 (setq timestr (match-string 0)
21670 s1 (match-string 1)
21671 s2 (match-string 2)
21672 d1 (time-to-days (org-time-string-to-time s1))
21673 d2 (time-to-days (org-time-string-to-time s2)))
21674 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21675 ;; Only allow days between the limits, because the normal
21676 ;; date stamps will catch the limits.
21677 (save-excursion
21678 (setq marker (org-agenda-new-marker (point)))
21679 (setq category (org-get-category))
21680 (if (re-search-backward "^\\*+ " nil t)
21681 (progn
21682 (goto-char (match-beginning 0))
21683 (setq hdmarker (org-agenda-new-marker (point)))
21684 (setq tags (org-get-tags-at))
21685 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21686 (setq head (match-string 1))
21687 (and org-agenda-skip-timestamp-if-done
21688 (org-entry-is-done-p)
21689 (throw :skip t))
21690 (setq txt (org-format-agenda-item
21691 (format (if (= d1 d2) "" "(%d/%d): ")
21692 (1+ (- d0 d1)) (1+ (- d2 d1)))
21693 head category tags
21694 (if (= d0 d1) timestr))))
21695 (setq txt org-agenda-no-heading-message))
21696 (org-add-props txt props
21697 'org-marker marker 'org-hd-marker hdmarker
21698 'type "block" 'date date
21699 'priority (org-get-priority txt) 'org-category category)
21700 (push txt ee)))
21701 (goto-char pos)))
21702 ;; Sort the entries by expiration date.
21703 (nreverse ee)))
21705 ;;; Agenda presentation and sorting
21707 (defconst org-plain-time-of-day-regexp
21708 (concat
21709 "\\(\\<[012]?[0-9]"
21710 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21711 "\\(--?"
21712 "\\(\\<[012]?[0-9]"
21713 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21714 "\\)?")
21715 "Regular expression to match a plain time or time range.
21716 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21717 groups carry important information:
21718 0 the full match
21719 1 the first time, range or not
21720 8 the second time, if it is a range.")
21722 (defconst org-plain-time-extension-regexp
21723 (concat
21724 "\\(\\<[012]?[0-9]"
21725 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21726 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21727 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21728 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21729 groups carry important information:
21730 0 the full match
21731 7 hours of duration
21732 9 minutes of duration")
21734 (defconst org-stamp-time-of-day-regexp
21735 (concat
21736 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21737 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21738 "\\(--?"
21739 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21740 "Regular expression to match a timestamp time or time range.
21741 After a match, the following groups carry important information:
21742 0 the full match
21743 1 date plus weekday, for backreferencing to make sure both times on same day
21744 2 the first time, range or not
21745 4 the second time, if it is a range.")
21747 (defvar org-prefix-has-time nil
21748 "A flag, set by `org-compile-prefix-format'.
21749 The flag is set if the currently compiled format contains a `%t'.")
21750 (defvar org-prefix-has-tag nil
21751 "A flag, set by `org-compile-prefix-format'.
21752 The flag is set if the currently compiled format contains a `%T'.")
21754 (defun org-format-agenda-item (extra txt &optional category tags dotime
21755 noprefix remove-re)
21756 "Format TXT to be inserted into the agenda buffer.
21757 In particular, it adds the prefix and corresponding text properties. EXTRA
21758 must be a string and replaces the `%s' specifier in the prefix format.
21759 CATEGORY (string, symbol or nil) may be used to overrule the default
21760 category taken from local variable or file name. It will replace the `%c'
21761 specifier in the format. DOTIME, when non-nil, indicates that a
21762 time-of-day should be extracted from TXT for sorting of this entry, and for
21763 the `%t' specifier in the format. When DOTIME is a string, this string is
21764 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21765 only the correctly processes TXT should be returned - this is used by
21766 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21767 Any match of REMOVE-RE will be removed from TXT."
21768 (save-match-data
21769 ;; Diary entries sometimes have extra whitespace at the beginning
21770 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
21771 (let* ((category (or category
21772 org-category
21773 (if buffer-file-name
21774 (file-name-sans-extension
21775 (file-name-nondirectory buffer-file-name))
21776 "")))
21777 (tag (if tags (nth (1- (length tags)) tags) ""))
21778 time ; time and tag are needed for the eval of the prefix format
21779 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
21780 (time-of-day (and dotime (org-get-time-of-day ts)))
21781 stamp plain s0 s1 s2 rtn srp)
21782 (when (and dotime time-of-day org-prefix-has-time)
21783 ;; Extract starting and ending time and move them to prefix
21784 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
21785 (setq plain (string-match org-plain-time-of-day-regexp ts)))
21786 (setq s0 (match-string 0 ts)
21787 srp (and stamp (match-end 3))
21788 s1 (match-string (if plain 1 2) ts)
21789 s2 (match-string (if plain 8 (if srp 4 6)) ts))
21791 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
21792 ;; them, we might want to remove them there to avoid duplication.
21793 ;; The user can turn this off with a variable.
21794 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
21795 (string-match (concat (regexp-quote s0) " *") txt)
21796 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
21797 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
21798 (= (match-beginning 0) 0)
21800 (setq txt (replace-match "" nil nil txt))))
21801 ;; Normalize the time(s) to 24 hour
21802 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
21803 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
21805 (when (and s1 (not s2) org-agenda-default-appointment-duration
21806 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
21807 (let ((m (+ (string-to-number (match-string 2 s1))
21808 (* 60 (string-to-number (match-string 1 s1)))
21809 org-agenda-default-appointment-duration))
21811 (setq h (/ m 60) m (- m (* h 60)))
21812 (setq s2 (format "%02d:%02d" h m))))
21814 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21815 txt)
21816 ;; Tags are in the string
21817 (if (or (eq org-agenda-remove-tags t)
21818 (and org-agenda-remove-tags
21819 org-prefix-has-tag))
21820 (setq txt (replace-match "" t t txt))
21821 (setq txt (replace-match
21822 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
21823 (match-string 2 txt))
21824 t t txt))))
21826 (when remove-re
21827 (while (string-match remove-re txt)
21828 (setq txt (replace-match "" t t txt))))
21830 ;; Create the final string
21831 (if noprefix
21832 (setq rtn txt)
21833 ;; Prepare the variables needed in the eval of the compiled format
21834 (setq time (cond (s2 (concat s1 "-" s2))
21835 (s1 (concat s1 "......"))
21836 (t ""))
21837 extra (or extra "")
21838 category (if (symbolp category) (symbol-name category) category))
21839 ;; Evaluate the compiled format
21840 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
21842 ;; And finally add the text properties
21843 (org-add-props rtn nil
21844 'org-category (downcase category) 'tags tags
21845 'org-highest-priority org-highest-priority
21846 'org-lowest-priority org-lowest-priority
21847 'prefix-length (- (length rtn) (length txt))
21848 'time-of-day time-of-day
21849 'txt txt
21850 'time time
21851 'extra extra
21852 'dotime dotime))))
21854 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
21855 (defvar org-agenda-sorting-strategy-selected nil)
21857 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
21858 (catch 'exit
21859 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
21860 ((and todayp (member 'today (car org-agenda-time-grid))))
21861 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
21862 ((member 'weekly (car org-agenda-time-grid)))
21863 (t (throw 'exit list)))
21864 (let* ((have (delq nil (mapcar
21865 (lambda (x) (get-text-property 1 'time-of-day x))
21866 list)))
21867 (string (nth 1 org-agenda-time-grid))
21868 (gridtimes (nth 2 org-agenda-time-grid))
21869 (req (car org-agenda-time-grid))
21870 (remove (member 'remove-match req))
21871 new time)
21872 (if (and (member 'require-timed req) (not have))
21873 ;; don't show empty grid
21874 (throw 'exit list))
21875 (while (setq time (pop gridtimes))
21876 (unless (and remove (member time have))
21877 (setq time (int-to-string time))
21878 (push (org-format-agenda-item
21879 nil string "" nil
21880 (concat (substring time 0 -2) ":" (substring time -2)))
21881 new)
21882 (put-text-property
21883 1 (length (car new)) 'face 'org-time-grid (car new))))
21884 (if (member 'time-up org-agenda-sorting-strategy-selected)
21885 (append new list)
21886 (append list new)))))
21888 (defun org-compile-prefix-format (key)
21889 "Compile the prefix format into a Lisp form that can be evaluated.
21890 The resulting form is returned and stored in the variable
21891 `org-prefix-format-compiled'."
21892 (setq org-prefix-has-time nil org-prefix-has-tag nil)
21893 (let ((s (cond
21894 ((stringp org-agenda-prefix-format)
21895 org-agenda-prefix-format)
21896 ((assq key org-agenda-prefix-format)
21897 (cdr (assq key org-agenda-prefix-format)))
21898 (t " %-12:c%?-12t% s")))
21899 (start 0)
21900 varform vars var e c f opt)
21901 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
21902 s start)
21903 (setq var (cdr (assoc (match-string 4 s)
21904 '(("c" . category) ("t" . time) ("s" . extra)
21905 ("T" . tag))))
21906 c (or (match-string 3 s) "")
21907 opt (match-beginning 1)
21908 start (1+ (match-beginning 0)))
21909 (if (equal var 'time) (setq org-prefix-has-time t))
21910 (if (equal var 'tag) (setq org-prefix-has-tag t))
21911 (setq f (concat "%" (match-string 2 s) "s"))
21912 (if opt
21913 (setq varform
21914 `(if (equal "" ,var)
21916 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
21917 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
21918 (setq s (replace-match "%s" t nil s))
21919 (push varform vars))
21920 (setq vars (nreverse vars))
21921 (setq org-prefix-format-compiled `(format ,s ,@vars))))
21923 (defun org-set-sorting-strategy (key)
21924 (if (symbolp (car org-agenda-sorting-strategy))
21925 ;; the old format
21926 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
21927 (setq org-agenda-sorting-strategy-selected
21928 (or (cdr (assq key org-agenda-sorting-strategy))
21929 (cdr (assq 'agenda org-agenda-sorting-strategy))
21930 '(time-up category-keep priority-down)))))
21932 (defun org-get-time-of-day (s &optional string mod24)
21933 "Check string S for a time of day.
21934 If found, return it as a military time number between 0 and 2400.
21935 If not found, return nil.
21936 The optional STRING argument forces conversion into a 5 character wide string
21937 HH:MM."
21938 (save-match-data
21939 (when
21940 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
21941 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
21942 (let* ((h (string-to-number (match-string 1 s)))
21943 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
21944 (ampm (if (match-end 4) (downcase (match-string 4 s))))
21945 (am-p (equal ampm "am"))
21946 (h1 (cond ((not ampm) h)
21947 ((= h 12) (if am-p 0 12))
21948 (t (+ h (if am-p 0 12)))))
21949 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
21950 (mod h1 24) h1))
21951 (t0 (+ (* 100 h2) m))
21952 (t1 (concat (if (>= h1 24) "+" " ")
21953 (if (< t0 100) "0" "")
21954 (if (< t0 10) "0" "")
21955 (int-to-string t0))))
21956 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
21958 (defun org-finalize-agenda-entries (list &optional nosort)
21959 "Sort and concatenate the agenda items."
21960 (setq list (mapcar 'org-agenda-highlight-todo list))
21961 (if nosort
21962 list
21963 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
21965 (defun org-agenda-highlight-todo (x)
21966 (let (re pl)
21967 (if (eq x 'line)
21968 (save-excursion
21969 (beginning-of-line 1)
21970 (setq re (get-text-property (point) 'org-todo-regexp))
21971 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
21972 (when (looking-at (concat "[ \t]*\\.*" re " +"))
21973 (add-text-properties (match-beginning 0) (match-end 0)
21974 (list 'face (org-get-todo-face 0)))
21975 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
21976 (delete-region (match-beginning 1) (1- (match-end 0)))
21977 (goto-char (match-beginning 1))
21978 (insert (format org-agenda-todo-keyword-format s)))))
21979 (setq re (concat (get-text-property 0 'org-todo-regexp x))
21980 pl (get-text-property 0 'prefix-length x))
21981 (when (and re
21982 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
21983 x (or pl 0)) pl))
21984 (add-text-properties
21985 (or (match-end 1) (match-end 0)) (match-end 0)
21986 (list 'face (org-get-todo-face (match-string 2 x)))
21988 (setq x (concat (substring x 0 (match-end 1))
21989 (format org-agenda-todo-keyword-format
21990 (match-string 2 x))
21992 (substring x (match-end 3)))))
21993 x)))
21995 (defsubst org-cmp-priority (a b)
21996 "Compare the priorities of string A and B."
21997 (let ((pa (or (get-text-property 1 'priority a) 0))
21998 (pb (or (get-text-property 1 'priority b) 0)))
21999 (cond ((> pa pb) +1)
22000 ((< pa pb) -1)
22001 (t nil))))
22003 (defsubst org-cmp-category (a b)
22004 "Compare the string values of categories of strings A and B."
22005 (let ((ca (or (get-text-property 1 'org-category a) ""))
22006 (cb (or (get-text-property 1 'org-category b) "")))
22007 (cond ((string-lessp ca cb) -1)
22008 ((string-lessp cb ca) +1)
22009 (t nil))))
22011 (defsubst org-cmp-tag (a b)
22012 "Compare the string values of categories of strings A and B."
22013 (let ((ta (car (last (get-text-property 1 'tags a))))
22014 (tb (car (last (get-text-property 1 'tags b)))))
22015 (cond ((not ta) +1)
22016 ((not tb) -1)
22017 ((string-lessp ta tb) -1)
22018 ((string-lessp tb ta) +1)
22019 (t nil))))
22021 (defsubst org-cmp-time (a b)
22022 "Compare the time-of-day values of strings A and B."
22023 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22024 (ta (or (get-text-property 1 'time-of-day a) def))
22025 (tb (or (get-text-property 1 'time-of-day b) def)))
22026 (cond ((< ta tb) -1)
22027 ((< tb ta) +1)
22028 (t nil))))
22030 (defun org-entries-lessp (a b)
22031 "Predicate for sorting agenda entries."
22032 ;; The following variables will be used when the form is evaluated.
22033 ;; So even though the compiler complains, keep them.
22034 (let* ((time-up (org-cmp-time a b))
22035 (time-down (if time-up (- time-up) nil))
22036 (priority-up (org-cmp-priority a b))
22037 (priority-down (if priority-up (- priority-up) nil))
22038 (category-up (org-cmp-category a b))
22039 (category-down (if category-up (- category-up) nil))
22040 (category-keep (if category-up +1 nil))
22041 (tag-up (org-cmp-tag a b))
22042 (tag-down (if tag-up (- tag-up) nil)))
22043 (cdr (assoc
22044 (eval (cons 'or org-agenda-sorting-strategy-selected))
22045 '((-1 . t) (1 . nil) (nil . nil))))))
22047 ;;; Agenda restriction lock
22049 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22050 "Overlay to mark the headline to which arenda commands are restricted.")
22051 (org-overlay-put org-agenda-restriction-lock-overlay
22052 'face 'org-agenda-restriction-lock)
22053 (org-overlay-put org-agenda-restriction-lock-overlay
22054 'help-echo "Agendas are currently limited to this subtree.")
22055 (org-detach-overlay org-agenda-restriction-lock-overlay)
22056 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22057 "Overlay marking the agenda restriction line in speedbar.")
22058 (org-overlay-put org-speedbar-restriction-lock-overlay
22059 'face 'org-agenda-restriction-lock)
22060 (org-overlay-put org-speedbar-restriction-lock-overlay
22061 'help-echo "Agendas are currently limited to this item.")
22062 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22064 (defun org-agenda-set-restriction-lock (&optional type)
22065 "Set restriction lock for agenda, to current subtree or file.
22066 Restriction will be the file if TYPE is `file', or if type is the
22067 universal prefix '(4), or if the cursor is before the first headline
22068 in the file. Otherwise, restriction will be to the current subtree."
22069 (interactive "P")
22070 (and (equal type '(4)) (setq type 'file))
22071 (setq type (cond
22072 (type type)
22073 ((org-at-heading-p) 'subtree)
22074 ((condition-case nil (org-back-to-heading t) (error nil))
22075 'subtree)
22076 (t 'file)))
22077 (if (eq type 'subtree)
22078 (progn
22079 (setq org-agenda-restrict t)
22080 (setq org-agenda-overriding-restriction 'subtree)
22081 (put 'org-agenda-files 'org-restrict
22082 (list (buffer-file-name (buffer-base-buffer))))
22083 (org-back-to-heading t)
22084 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22085 (move-marker org-agenda-restrict-begin (point))
22086 (move-marker org-agenda-restrict-end
22087 (save-excursion (org-end-of-subtree t)))
22088 (message "Locking agenda restriction to subtree"))
22089 (put 'org-agenda-files 'org-restrict
22090 (list (buffer-file-name (buffer-base-buffer))))
22091 (setq org-agenda-restrict nil)
22092 (setq org-agenda-overriding-restriction 'file)
22093 (move-marker org-agenda-restrict-begin nil)
22094 (move-marker org-agenda-restrict-end nil)
22095 (message "Locking agenda restriction to file"))
22096 (setq current-prefix-arg nil)
22097 (org-agenda-maybe-redo))
22099 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22100 "Remove the agenda restriction lock."
22101 (interactive "P")
22102 (org-detach-overlay org-agenda-restriction-lock-overlay)
22103 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22104 (setq org-agenda-overriding-restriction nil)
22105 (setq org-agenda-restrict nil)
22106 (put 'org-agenda-files 'org-restrict nil)
22107 (move-marker org-agenda-restrict-begin nil)
22108 (move-marker org-agenda-restrict-end nil)
22109 (setq current-prefix-arg nil)
22110 (message "Agenda restriction lock removed")
22111 (or noupdate (org-agenda-maybe-redo)))
22113 (defun org-agenda-maybe-redo ()
22114 "If there is any window showing the agenda view, update it."
22115 (let ((w (get-buffer-window org-agenda-buffer-name t))
22116 (w0 (selected-window)))
22117 (when w
22118 (select-window w)
22119 (org-agenda-redo)
22120 (select-window w0)
22121 (if org-agenda-overriding-restriction
22122 (message "Agenda view shifted to new %s restriction"
22123 org-agenda-overriding-restriction)
22124 (message "Agenda restriction lock removed")))))
22126 ;;; Agenda commands
22128 (defun org-agenda-check-type (error &rest types)
22129 "Check if agenda buffer is of allowed type.
22130 If ERROR is non-nil, throw an error, otherwise just return nil."
22131 (if (memq org-agenda-type types)
22133 (if error
22134 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22135 nil)))
22137 (defun org-agenda-quit ()
22138 "Exit agenda by removing the window or the buffer."
22139 (interactive)
22140 (let ((buf (current-buffer)))
22141 (if (not (one-window-p)) (delete-window))
22142 (kill-buffer buf)
22143 (org-agenda-reset-markers)
22144 (org-columns-remove-overlays))
22145 ;; Maybe restore the pre-agenda window configuration.
22146 (and org-agenda-restore-windows-after-quit
22147 (not (eq org-agenda-window-setup 'other-frame))
22148 org-pre-agenda-window-conf
22149 (set-window-configuration org-pre-agenda-window-conf)))
22151 (defun org-agenda-exit ()
22152 "Exit agenda by removing the window or the buffer.
22153 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22154 Org-mode buffers visited directly by the user will not be touched."
22155 (interactive)
22156 (org-release-buffers org-agenda-new-buffers)
22157 (setq org-agenda-new-buffers nil)
22158 (org-agenda-quit))
22160 (defun org-agenda-execute (arg)
22161 "Execute another agenda command, keeping same window.\\<global-map>
22162 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22163 (interactive "P")
22164 (let ((org-agenda-window-setup 'current-window))
22165 (org-agenda arg)))
22167 (defun org-save-all-org-buffers ()
22168 "Save all Org-mode buffers without user confirmation."
22169 (interactive)
22170 (message "Saving all Org-mode buffers...")
22171 (save-some-buffers t 'org-mode-p)
22172 (message "Saving all Org-mode buffers... done"))
22174 (defun org-agenda-redo ()
22175 "Rebuild Agenda.
22176 When this is the global TODO list, a prefix argument will be interpreted."
22177 (interactive)
22178 (let* ((org-agenda-keep-modes t)
22179 (line (org-current-line))
22180 (window-line (- line (org-current-line (window-start))))
22181 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22182 (message "Rebuilding agenda buffer...")
22183 (org-let lprops '(eval org-agenda-redo-command))
22184 (setq org-agenda-undo-list nil
22185 org-agenda-pending-undo-list nil)
22186 (message "Rebuilding agenda buffer...done")
22187 (goto-line line)
22188 (recenter window-line)))
22190 (defun org-agenda-goto-date (date)
22191 "Jump to DATE in agenda."
22192 (interactive (list (org-read-date)))
22193 (org-agenda-list nil date))
22195 (defun org-agenda-goto-today ()
22196 "Go to today."
22197 (interactive)
22198 (org-agenda-check-type t 'timeline 'agenda)
22199 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22200 (cond
22201 (tdpos (goto-char tdpos))
22202 ((eq org-agenda-type 'agenda)
22203 (let* ((sd (time-to-days
22204 (time-subtract (current-time)
22205 (list 0 (* 3600 org-extend-today-until) 0))))
22206 (comp (org-agenda-compute-time-span sd org-agenda-span))
22207 (org-agenda-overriding-arguments org-agenda-last-arguments))
22208 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22209 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22210 (org-agenda-redo)
22211 (org-agenda-find-same-or-today-or-agenda)))
22212 (t (error "Cannot find today")))))
22214 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22215 (goto-char
22216 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22217 (text-property-any (point-min) (point-max) 'org-today t)
22218 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22219 (point-min))))
22221 (defun org-agenda-later (arg)
22222 "Go forward in time by thee current span.
22223 With prefix ARG, go forward that many times the current span."
22224 (interactive "p")
22225 (org-agenda-check-type t 'agenda)
22226 (let* ((span org-agenda-span)
22227 (sd org-starting-day)
22228 (greg (calendar-gregorian-from-absolute sd))
22229 (cnt (get-text-property (point) 'org-day-cnt))
22230 greg2 nd)
22231 (cond
22232 ((eq span 'day)
22233 (setq sd (+ arg sd) nd 1))
22234 ((eq span 'week)
22235 (setq sd (+ (* 7 arg) sd) nd 7))
22236 ((eq span 'month)
22237 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22238 sd (calendar-absolute-from-gregorian greg2))
22239 (setcar greg2 (1+ (car greg2)))
22240 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22241 ((eq span 'year)
22242 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22243 sd (calendar-absolute-from-gregorian greg2))
22244 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22245 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22246 (let ((org-agenda-overriding-arguments
22247 (list (car org-agenda-last-arguments) sd nd t)))
22248 (org-agenda-redo)
22249 (org-agenda-find-same-or-today-or-agenda cnt))))
22251 (defun org-agenda-earlier (arg)
22252 "Go backward in time by the current span.
22253 With prefix ARG, go backward that many times the current span."
22254 (interactive "p")
22255 (org-agenda-later (- arg)))
22257 (defun org-agenda-day-view ()
22258 "Switch to daily view for agenda."
22259 (interactive)
22260 (setq org-agenda-ndays 1)
22261 (org-agenda-change-time-span 'day))
22262 (defun org-agenda-week-view ()
22263 "Switch to daily view for agenda."
22264 (interactive)
22265 (setq org-agenda-ndays 7)
22266 (org-agenda-change-time-span 'week))
22267 (defun org-agenda-month-view ()
22268 "Switch to daily view for agenda."
22269 (interactive)
22270 (org-agenda-change-time-span 'month))
22271 (defun org-agenda-year-view ()
22272 "Switch to daily view for agenda."
22273 (interactive)
22274 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22275 (org-agenda-change-time-span 'year)
22276 (error "Abort")))
22278 (defun org-agenda-change-time-span (span)
22279 "Change the agenda view to SPAN.
22280 SPAN may be `day', `week', `month', `year'."
22281 (org-agenda-check-type t 'agenda)
22282 (if (equal org-agenda-span span)
22283 (error "Viewing span is already \"%s\"" span))
22284 (let* ((sd (or (get-text-property (point) 'day)
22285 org-starting-day))
22286 (computed (org-agenda-compute-time-span sd span))
22287 (org-agenda-overriding-arguments
22288 (list (car org-agenda-last-arguments)
22289 (car computed) (cdr computed) t)))
22290 (org-agenda-redo)
22291 (org-agenda-find-same-or-today-or-agenda))
22292 (org-agenda-set-mode-name)
22293 (message "Switched to %s view" span))
22295 (defun org-agenda-compute-time-span (sd span)
22296 "Compute starting date and number of days for agenda.
22297 SPAN may be `day', `week', `month', `year'. The return value
22298 is a cons cell with the starting date and the number of days,
22299 so that the date SD will be in that range."
22300 (let* ((greg (calendar-gregorian-from-absolute sd))
22302 (cond
22303 ((eq span 'day)
22304 (setq nd 1))
22305 ((eq span 'week)
22306 (let* ((nt (calendar-day-of-week
22307 (calendar-gregorian-from-absolute sd)))
22308 (d (if org-agenda-start-on-weekday
22309 (- nt org-agenda-start-on-weekday)
22310 0)))
22311 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22312 (setq nd 7)))
22313 ((eq span 'month)
22314 (setq sd (calendar-absolute-from-gregorian
22315 (list (car greg) 1 (nth 2 greg)))
22316 nd (- (calendar-absolute-from-gregorian
22317 (list (1+ (car greg)) 1 (nth 2 greg)))
22318 sd)))
22319 ((eq span 'year)
22320 (setq sd (calendar-absolute-from-gregorian
22321 (list 1 1 (nth 2 greg)))
22322 nd (- (calendar-absolute-from-gregorian
22323 (list 1 1 (1+ (nth 2 greg))))
22324 sd))))
22325 (cons sd nd)))
22327 ;; FIXME: does not work if user makes date format that starts with a blank
22328 (defun org-agenda-next-date-line (&optional arg)
22329 "Jump to the next line indicating a date in agenda buffer."
22330 (interactive "p")
22331 (org-agenda-check-type t 'agenda 'timeline)
22332 (beginning-of-line 1)
22333 (if (looking-at "^\\S-") (forward-char 1))
22334 (if (not (re-search-forward "^\\S-" nil t arg))
22335 (progn
22336 (backward-char 1)
22337 (error "No next date after this line in this buffer")))
22338 (goto-char (match-beginning 0)))
22340 (defun org-agenda-previous-date-line (&optional arg)
22341 "Jump to the previous line indicating a date in agenda buffer."
22342 (interactive "p")
22343 (org-agenda-check-type t 'agenda 'timeline)
22344 (beginning-of-line 1)
22345 (if (not (re-search-backward "^\\S-" nil t arg))
22346 (error "No previous date before this line in this buffer")))
22348 ;; Initialize the highlight
22349 (defvar org-hl (org-make-overlay 1 1))
22350 (org-overlay-put org-hl 'face 'highlight)
22352 (defun org-highlight (begin end &optional buffer)
22353 "Highlight a region with overlay."
22354 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22355 org-hl begin end (or buffer (current-buffer))))
22357 (defun org-unhighlight ()
22358 "Detach overlay INDEX."
22359 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22361 ;; FIXME this is currently not used.
22362 (defun org-highlight-until-next-command (beg end &optional buffer)
22363 (org-highlight beg end buffer)
22364 (add-hook 'pre-command-hook 'org-unhighlight-once))
22365 (defun org-unhighlight-once ()
22366 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22367 (org-unhighlight))
22369 (defun org-agenda-follow-mode ()
22370 "Toggle follow mode in an agenda buffer."
22371 (interactive)
22372 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22373 (org-agenda-set-mode-name)
22374 (message "Follow mode is %s"
22375 (if org-agenda-follow-mode "on" "off")))
22377 (defun org-agenda-log-mode ()
22378 "Toggle log mode in an agenda buffer."
22379 (interactive)
22380 (org-agenda-check-type t 'agenda 'timeline)
22381 (setq org-agenda-show-log (not org-agenda-show-log))
22382 (org-agenda-set-mode-name)
22383 (org-agenda-redo)
22384 (message "Log mode is %s"
22385 (if org-agenda-show-log "on" "off")))
22387 (defun org-agenda-toggle-diary ()
22388 "Toggle diary inclusion in an agenda buffer."
22389 (interactive)
22390 (org-agenda-check-type t 'agenda)
22391 (setq org-agenda-include-diary (not org-agenda-include-diary))
22392 (org-agenda-redo)
22393 (org-agenda-set-mode-name)
22394 (message "Diary inclusion turned %s"
22395 (if org-agenda-include-diary "on" "off")))
22397 (defun org-agenda-toggle-time-grid ()
22398 "Toggle time grid in an agenda buffer."
22399 (interactive)
22400 (org-agenda-check-type t 'agenda)
22401 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22402 (org-agenda-redo)
22403 (org-agenda-set-mode-name)
22404 (message "Time-grid turned %s"
22405 (if org-agenda-use-time-grid "on" "off")))
22407 (defun org-agenda-set-mode-name ()
22408 "Set the mode name to indicate all the small mode settings."
22409 (setq mode-name
22410 (concat "Org-Agenda"
22411 (if (equal org-agenda-ndays 1) " Day" "")
22412 (if (equal org-agenda-ndays 7) " Week" "")
22413 (if org-agenda-follow-mode " Follow" "")
22414 (if org-agenda-include-diary " Diary" "")
22415 (if org-agenda-use-time-grid " Grid" "")
22416 (if org-agenda-show-log " Log" "")))
22417 (force-mode-line-update))
22419 (defun org-agenda-post-command-hook ()
22420 (and (eolp) (not (bolp)) (backward-char 1))
22421 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22422 (if (and org-agenda-follow-mode
22423 (get-text-property (point) 'org-marker))
22424 (org-agenda-show)))
22426 (defun org-agenda-show-priority ()
22427 "Show the priority of the current item.
22428 This priority is composed of the main priority given with the [#A] cookies,
22429 and by additional input from the age of a schedules or deadline entry."
22430 (interactive)
22431 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22432 (message "Priority is %d" (if pri pri -1000))))
22434 (defun org-agenda-show-tags ()
22435 "Show the tags applicable to the current item."
22436 (interactive)
22437 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22438 (if tags
22439 (message "Tags are :%s:"
22440 (org-no-properties (mapconcat 'identity tags ":")))
22441 (message "No tags associated with this line"))))
22443 (defun org-agenda-goto (&optional highlight)
22444 "Go to the Org-mode file which contains the item at point."
22445 (interactive)
22446 (let* ((marker (or (get-text-property (point) 'org-marker)
22447 (org-agenda-error)))
22448 (buffer (marker-buffer marker))
22449 (pos (marker-position marker)))
22450 (switch-to-buffer-other-window buffer)
22451 (widen)
22452 (goto-char pos)
22453 (when (org-mode-p)
22454 (org-show-context 'agenda)
22455 (save-excursion
22456 (and (outline-next-heading)
22457 (org-flag-heading nil)))) ; show the next heading
22458 (recenter (/ (window-height) 2))
22459 (run-hooks 'org-agenda-after-show-hook)
22460 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22462 (defvar org-agenda-after-show-hook nil
22463 "Normal hook run after an item has been shown from the agenda.
22464 Point is in the buffer where the item originated.")
22466 (defun org-agenda-kill ()
22467 "Kill the entry or subtree belonging to the current agenda entry."
22468 (interactive)
22469 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22470 (let* ((marker (or (get-text-property (point) 'org-marker)
22471 (org-agenda-error)))
22472 (buffer (marker-buffer marker))
22473 (pos (marker-position marker))
22474 (type (get-text-property (point) 'type))
22475 dbeg dend (n 0) conf)
22476 (org-with-remote-undo buffer
22477 (with-current-buffer buffer
22478 (save-excursion
22479 (goto-char pos)
22480 (if (and (org-mode-p) (not (member type '("sexp"))))
22481 (setq dbeg (progn (org-back-to-heading t) (point))
22482 dend (org-end-of-subtree t t))
22483 (setq dbeg (point-at-bol)
22484 dend (min (point-max) (1+ (point-at-eol)))))
22485 (goto-char dbeg)
22486 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22487 (setq conf (or (eq t org-agenda-confirm-kill)
22488 (and (numberp org-agenda-confirm-kill)
22489 (> n org-agenda-confirm-kill))))
22490 (and conf
22491 (not (y-or-n-p
22492 (format "Delete entry with %d lines in buffer \"%s\"? "
22493 n (buffer-name buffer))))
22494 (error "Abort"))
22495 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22496 (with-current-buffer buffer (delete-region dbeg dend))
22497 (message "Agenda item and source killed"))))
22499 (defun org-agenda-archive ()
22500 "Kill the entry or subtree belonging to the current agenda entry."
22501 (interactive)
22502 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22503 (let* ((marker (or (get-text-property (point) 'org-marker)
22504 (org-agenda-error)))
22505 (buffer (marker-buffer marker))
22506 (pos (marker-position marker)))
22507 (org-with-remote-undo buffer
22508 (with-current-buffer buffer
22509 (if (org-mode-p)
22510 (save-excursion
22511 (goto-char pos)
22512 (org-remove-subtree-entries-from-agenda)
22513 (org-back-to-heading t)
22514 (org-archive-subtree))
22515 (error "Archiving works only in Org-mode files"))))))
22517 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22518 "Remove all lines in the agenda that correspond to a given subtree.
22519 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22520 If this information is not given, the function uses the tree at point."
22521 (let ((buf (or buf (current-buffer))) m p)
22522 (save-excursion
22523 (unless (and beg end)
22524 (org-back-to-heading t)
22525 (setq beg (point))
22526 (org-end-of-subtree t)
22527 (setq end (point)))
22528 (set-buffer (get-buffer org-agenda-buffer-name))
22529 (save-excursion
22530 (goto-char (point-max))
22531 (beginning-of-line 1)
22532 (while (not (bobp))
22533 (when (and (setq m (get-text-property (point) 'org-marker))
22534 (equal buf (marker-buffer m))
22535 (setq p (marker-position m))
22536 (>= p beg)
22537 (<= p end))
22538 (let ((inhibit-read-only t))
22539 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22540 (beginning-of-line 0))))))
22542 (defun org-agenda-open-link ()
22543 "Follow the link in the current line, if any."
22544 (interactive)
22545 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22546 (save-excursion
22547 (save-restriction
22548 (narrow-to-region (point-at-bol) (point-at-eol))
22549 (org-open-at-point))))
22551 (defun org-agenda-copy-local-variable (var)
22552 "Get a variable from a referenced buffer and install it here."
22553 (let ((m (get-text-property (point) 'org-marker)))
22554 (when (and m (buffer-live-p (marker-buffer m)))
22555 (org-set-local var (with-current-buffer (marker-buffer m)
22556 (symbol-value var))))))
22558 (defun org-agenda-switch-to (&optional delete-other-windows)
22559 "Go to the Org-mode file which contains the item at point."
22560 (interactive)
22561 (let* ((marker (or (get-text-property (point) 'org-marker)
22562 (org-agenda-error)))
22563 (buffer (marker-buffer marker))
22564 (pos (marker-position marker)))
22565 (switch-to-buffer buffer)
22566 (and delete-other-windows (delete-other-windows))
22567 (widen)
22568 (goto-char pos)
22569 (when (org-mode-p)
22570 (org-show-context 'agenda)
22571 (save-excursion
22572 (and (outline-next-heading)
22573 (org-flag-heading nil)))))) ; show the next heading
22575 (defun org-agenda-goto-mouse (ev)
22576 "Go to the Org-mode file which contains the item at the mouse click."
22577 (interactive "e")
22578 (mouse-set-point ev)
22579 (org-agenda-goto))
22581 (defun org-agenda-show ()
22582 "Display the Org-mode file which contains the item at point."
22583 (interactive)
22584 (let ((win (selected-window)))
22585 (org-agenda-goto t)
22586 (select-window win)))
22588 (defun org-agenda-recenter (arg)
22589 "Display the Org-mode file which contains the item at point and recenter."
22590 (interactive "P")
22591 (let ((win (selected-window)))
22592 (org-agenda-goto t)
22593 (recenter arg)
22594 (select-window win)))
22596 (defun org-agenda-show-mouse (ev)
22597 "Display the Org-mode file which contains the item at the mouse click."
22598 (interactive "e")
22599 (mouse-set-point ev)
22600 (org-agenda-show))
22602 (defun org-agenda-check-no-diary ()
22603 "Check if the entry is a diary link and abort if yes."
22604 (if (get-text-property (point) 'org-agenda-diary-link)
22605 (org-agenda-error)))
22607 (defun org-agenda-error ()
22608 (error "Command not allowed in this line"))
22610 (defun org-agenda-tree-to-indirect-buffer ()
22611 "Show the subtree corresponding to the current entry in an indirect buffer.
22612 This calls the command `org-tree-to-indirect-buffer' from the original
22613 Org-mode buffer.
22614 With numerical prefix arg ARG, go up to this level and then take that tree.
22615 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22616 dedicated frame)."
22617 (interactive)
22618 (org-agenda-check-no-diary)
22619 (let* ((marker (or (get-text-property (point) 'org-marker)
22620 (org-agenda-error)))
22621 (buffer (marker-buffer marker))
22622 (pos (marker-position marker)))
22623 (with-current-buffer buffer
22624 (save-excursion
22625 (goto-char pos)
22626 (call-interactively 'org-tree-to-indirect-buffer)))))
22628 (defvar org-last-heading-marker (make-marker)
22629 "Marker pointing to the headline that last changed its TODO state
22630 by a remote command from the agenda.")
22632 (defun org-agenda-todo-nextset ()
22633 "Switch TODO entry to next sequence."
22634 (interactive)
22635 (org-agenda-todo 'nextset))
22637 (defun org-agenda-todo-previousset ()
22638 "Switch TODO entry to previous sequence."
22639 (interactive)
22640 (org-agenda-todo 'previousset))
22642 (defun org-agenda-todo (&optional arg)
22643 "Cycle TODO state of line at point, also in Org-mode file.
22644 This changes the line at point, all other lines in the agenda referring to
22645 the same tree node, and the headline of the tree node in the Org-mode file."
22646 (interactive "P")
22647 (org-agenda-check-no-diary)
22648 (let* ((col (current-column))
22649 (marker (or (get-text-property (point) 'org-marker)
22650 (org-agenda-error)))
22651 (buffer (marker-buffer marker))
22652 (pos (marker-position marker))
22653 (hdmarker (get-text-property (point) 'org-hd-marker))
22654 (inhibit-read-only t)
22655 newhead)
22656 (org-with-remote-undo buffer
22657 (with-current-buffer buffer
22658 (widen)
22659 (goto-char pos)
22660 (org-show-context 'agenda)
22661 (save-excursion
22662 (and (outline-next-heading)
22663 (org-flag-heading nil))) ; show the next heading
22664 (org-todo arg)
22665 (and (bolp) (forward-char 1))
22666 (setq newhead (org-get-heading))
22667 (save-excursion
22668 (org-back-to-heading)
22669 (move-marker org-last-heading-marker (point))))
22670 (beginning-of-line 1)
22671 (save-excursion
22672 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22673 (move-to-column col))))
22675 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22676 "Change all lines in the agenda buffer which match HDMARKER.
22677 The new content of the line will be NEWHEAD (as modified by
22678 `org-format-agenda-item'). HDMARKER is checked with
22679 `equal' against all `org-hd-marker' text properties in the file.
22680 If FIXFACE is non-nil, the face of each item is modified acording to
22681 the new TODO state."
22682 (let* ((inhibit-read-only t)
22683 props m pl undone-face done-face finish new dotime cat tags)
22684 (save-excursion
22685 (goto-char (point-max))
22686 (beginning-of-line 1)
22687 (while (not finish)
22688 (setq finish (bobp))
22689 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22690 (equal m hdmarker))
22691 (setq props (text-properties-at (point))
22692 dotime (get-text-property (point) 'dotime)
22693 cat (get-text-property (point) 'org-category)
22694 tags (get-text-property (point) 'tags)
22695 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22696 pl (get-text-property (point) 'prefix-length)
22697 undone-face (get-text-property (point) 'undone-face)
22698 done-face (get-text-property (point) 'done-face))
22699 (move-to-column pl)
22700 (cond
22701 ((equal new "")
22702 (beginning-of-line 1)
22703 (and (looking-at ".*\n?") (replace-match "")))
22704 ((looking-at ".*")
22705 (replace-match new t t)
22706 (beginning-of-line 1)
22707 (add-text-properties (point-at-bol) (point-at-eol) props)
22708 (when fixface
22709 (add-text-properties
22710 (point-at-bol) (point-at-eol)
22711 (list 'face
22712 (if org-last-todo-state-is-todo
22713 undone-face done-face))))
22714 (org-agenda-highlight-todo 'line)
22715 (beginning-of-line 1))
22716 (t (error "Line update did not work"))))
22717 (beginning-of-line 0)))
22718 (org-finalize-agenda)))
22720 (defun org-agenda-align-tags (&optional line)
22721 "Align all tags in agenda items to `org-agenda-tags-column'."
22722 (let ((inhibit-read-only t) l c)
22723 (save-excursion
22724 (goto-char (if line (point-at-bol) (point-min)))
22725 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22726 (if line (point-at-eol) nil) t)
22727 (add-text-properties
22728 (match-beginning 2) (match-end 2)
22729 (list 'face (list 'org-tag (get-text-property
22730 (match-beginning 2) 'face))))
22731 (setq l (- (match-end 2) (match-beginning 2))
22732 c (if (< org-agenda-tags-column 0)
22733 (- (abs org-agenda-tags-column) l)
22734 org-agenda-tags-column))
22735 (delete-region (match-beginning 1) (match-end 1))
22736 (goto-char (match-beginning 1))
22737 (insert (org-add-props
22738 (make-string (max 1 (- c (current-column))) ?\ )
22739 (text-properties-at (point))))))))
22741 (defun org-agenda-priority-up ()
22742 "Increase the priority of line at point, also in Org-mode file."
22743 (interactive)
22744 (org-agenda-priority 'up))
22746 (defun org-agenda-priority-down ()
22747 "Decrease the priority of line at point, also in Org-mode file."
22748 (interactive)
22749 (org-agenda-priority 'down))
22751 (defun org-agenda-priority (&optional force-direction)
22752 "Set the priority of line at point, also in Org-mode file.
22753 This changes the line at point, all other lines in the agenda referring to
22754 the same tree node, and the headline of the tree node in the Org-mode file."
22755 (interactive)
22756 (org-agenda-check-no-diary)
22757 (let* ((marker (or (get-text-property (point) 'org-marker)
22758 (org-agenda-error)))
22759 (hdmarker (get-text-property (point) 'org-hd-marker))
22760 (buffer (marker-buffer hdmarker))
22761 (pos (marker-position hdmarker))
22762 (inhibit-read-only t)
22763 newhead)
22764 (org-with-remote-undo buffer
22765 (with-current-buffer buffer
22766 (widen)
22767 (goto-char pos)
22768 (org-show-context 'agenda)
22769 (save-excursion
22770 (and (outline-next-heading)
22771 (org-flag-heading nil))) ; show the next heading
22772 (funcall 'org-priority force-direction)
22773 (end-of-line 1)
22774 (setq newhead (org-get-heading)))
22775 (org-agenda-change-all-lines newhead hdmarker)
22776 (beginning-of-line 1))))
22778 (defun org-get-tags-at (&optional pos)
22779 "Get a list of all headline tags applicable at POS.
22780 POS defaults to point. If tags are inherited, the list contains
22781 the targets in the same sequence as the headlines appear, i.e.
22782 the tags of the current headline come last."
22783 (interactive)
22784 (let (tags lastpos)
22785 (save-excursion
22786 (save-restriction
22787 (widen)
22788 (goto-char (or pos (point)))
22789 (save-match-data
22790 (org-back-to-heading t)
22791 (condition-case nil
22792 (while (not (equal lastpos (point)))
22793 (setq lastpos (point))
22794 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
22795 (setq tags (append (org-split-string
22796 (org-match-string-no-properties 1) ":")
22797 tags)))
22798 (or org-use-tag-inheritance (error ""))
22799 (org-up-heading-all 1))
22800 (error nil))))
22801 tags)))
22803 ;; FIXME: should fix the tags property of the agenda line.
22804 (defun org-agenda-set-tags ()
22805 "Set tags for the current headline."
22806 (interactive)
22807 (org-agenda-check-no-diary)
22808 (if (and (org-region-active-p) (interactive-p))
22809 (call-interactively 'org-change-tag-in-region)
22810 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22811 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22812 (org-agenda-error)))
22813 (buffer (marker-buffer hdmarker))
22814 (pos (marker-position hdmarker))
22815 (inhibit-read-only t)
22816 newhead)
22817 (org-with-remote-undo buffer
22818 (with-current-buffer buffer
22819 (widen)
22820 (goto-char pos)
22821 (save-excursion
22822 (org-show-context 'agenda))
22823 (save-excursion
22824 (and (outline-next-heading)
22825 (org-flag-heading nil))) ; show the next heading
22826 (goto-char pos)
22827 (call-interactively 'org-set-tags)
22828 (end-of-line 1)
22829 (setq newhead (org-get-heading)))
22830 (org-agenda-change-all-lines newhead hdmarker)
22831 (beginning-of-line 1)))))
22833 (defun org-agenda-toggle-archive-tag ()
22834 "Toggle the archive tag for the current entry."
22835 (interactive)
22836 (org-agenda-check-no-diary)
22837 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
22838 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
22839 (org-agenda-error)))
22840 (buffer (marker-buffer hdmarker))
22841 (pos (marker-position hdmarker))
22842 (inhibit-read-only t)
22843 newhead)
22844 (org-with-remote-undo buffer
22845 (with-current-buffer buffer
22846 (widen)
22847 (goto-char pos)
22848 (org-show-context 'agenda)
22849 (save-excursion
22850 (and (outline-next-heading)
22851 (org-flag-heading nil))) ; show the next heading
22852 (call-interactively 'org-toggle-archive-tag)
22853 (end-of-line 1)
22854 (setq newhead (org-get-heading)))
22855 (org-agenda-change-all-lines newhead hdmarker)
22856 (beginning-of-line 1))))
22858 (defun org-agenda-date-later (arg &optional what)
22859 "Change the date of this item to one day later."
22860 (interactive "p")
22861 (org-agenda-check-type t 'agenda 'timeline)
22862 (org-agenda-check-no-diary)
22863 (let* ((marker (or (get-text-property (point) 'org-marker)
22864 (org-agenda-error)))
22865 (buffer (marker-buffer marker))
22866 (pos (marker-position marker)))
22867 (org-with-remote-undo buffer
22868 (with-current-buffer buffer
22869 (widen)
22870 (goto-char pos)
22871 (if (not (org-at-timestamp-p))
22872 (error "Cannot find time stamp"))
22873 (org-timestamp-change arg (or what 'day)))
22874 (org-agenda-show-new-time marker org-last-changed-timestamp))
22875 (message "Time stamp changed to %s" org-last-changed-timestamp)))
22877 (defun org-agenda-date-earlier (arg &optional what)
22878 "Change the date of this item to one day earlier."
22879 (interactive "p")
22880 (org-agenda-date-later (- arg) what))
22882 (defun org-agenda-show-new-time (marker stamp &optional prefix)
22883 "Show new date stamp via text properties."
22884 ;; We use text properties to make this undoable
22885 (let ((inhibit-read-only t))
22886 (setq stamp (concat " " prefix " => " stamp))
22887 (save-excursion
22888 (goto-char (point-max))
22889 (while (not (bobp))
22890 (when (equal marker (get-text-property (point) 'org-marker))
22891 (move-to-column (- (window-width) (length stamp)) t)
22892 (if (featurep 'xemacs)
22893 ;; Use `duplicable' property to trigger undo recording
22894 (let ((ex (make-extent nil nil))
22895 (gl (make-glyph stamp)))
22896 (set-glyph-face gl 'secondary-selection)
22897 (set-extent-properties
22898 ex (list 'invisible t 'end-glyph gl 'duplicable t))
22899 (insert-extent ex (1- (point)) (point-at-eol)))
22900 (add-text-properties
22901 (1- (point)) (point-at-eol)
22902 (list 'display (org-add-props stamp nil
22903 'face 'secondary-selection))))
22904 (beginning-of-line 1))
22905 (beginning-of-line 0)))))
22907 (defun org-agenda-date-prompt (arg)
22908 "Change the date of this item. Date is prompted for, with default today.
22909 The prefix ARG is passed to the `org-time-stamp' command and can therefore
22910 be used to request time specification in the time stamp."
22911 (interactive "P")
22912 (org-agenda-check-type t 'agenda 'timeline)
22913 (org-agenda-check-no-diary)
22914 (let* ((marker (or (get-text-property (point) 'org-marker)
22915 (org-agenda-error)))
22916 (buffer (marker-buffer marker))
22917 (pos (marker-position marker)))
22918 (org-with-remote-undo buffer
22919 (with-current-buffer buffer
22920 (widen)
22921 (goto-char pos)
22922 (if (not (org-at-timestamp-p))
22923 (error "Cannot find time stamp"))
22924 (org-time-stamp arg)
22925 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
22927 (defun org-agenda-schedule (arg)
22928 "Schedule the item at point."
22929 (interactive "P")
22930 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22931 (org-agenda-check-no-diary)
22932 (let* ((marker (or (get-text-property (point) 'org-marker)
22933 (org-agenda-error)))
22934 (buffer (marker-buffer marker))
22935 (pos (marker-position marker))
22936 (org-insert-labeled-timestamps-at-point nil)
22938 (message "%s" (marker-insertion-type marker)) (sit-for 3)
22939 (set-marker-insertion-type marker t)
22940 (org-with-remote-undo buffer
22941 (with-current-buffer buffer
22942 (widen)
22943 (goto-char pos)
22944 (setq ts (org-schedule arg)))
22945 (org-agenda-show-new-time marker ts "S"))
22946 (message "Item scheduled for %s" ts)))
22948 (defun org-agenda-deadline (arg)
22949 "Schedule the item at point."
22950 (interactive "P")
22951 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
22952 (org-agenda-check-no-diary)
22953 (let* ((marker (or (get-text-property (point) 'org-marker)
22954 (org-agenda-error)))
22955 (buffer (marker-buffer marker))
22956 (pos (marker-position marker))
22957 (org-insert-labeled-timestamps-at-point nil)
22959 (org-with-remote-undo buffer
22960 (with-current-buffer buffer
22961 (widen)
22962 (goto-char pos)
22963 (setq ts (org-deadline arg)))
22964 (org-agenda-show-new-time marker ts "S"))
22965 (message "Deadline for this item set to %s" ts)))
22967 (defun org-get-heading (&optional no-tags)
22968 "Return the heading of the current entry, without the stars."
22969 (save-excursion
22970 (org-back-to-heading t)
22971 (if (looking-at
22972 (if no-tags
22973 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
22974 "\\*+[ \t]+\\([^\r\n]*\\)"))
22975 (match-string 1) "")))
22977 (defun org-agenda-clock-in (&optional arg)
22978 "Start the clock on the currently selected item."
22979 (interactive "P")
22980 (org-agenda-check-no-diary)
22981 (let* ((marker (or (get-text-property (point) 'org-marker)
22982 (org-agenda-error)))
22983 (pos (marker-position marker)))
22984 (org-with-remote-undo (marker-buffer marker)
22985 (with-current-buffer (marker-buffer marker)
22986 (widen)
22987 (goto-char pos)
22988 (org-clock-in)))))
22990 (defun org-agenda-clock-out (&optional arg)
22991 "Stop the currently running clock."
22992 (interactive "P")
22993 (unless (marker-buffer org-clock-marker)
22994 (error "No running clock"))
22995 (org-with-remote-undo (marker-buffer org-clock-marker)
22996 (org-clock-out)))
22998 (defun org-agenda-clock-cancel (&optional arg)
22999 "Cancel the currently running clock."
23000 (interactive "P")
23001 (unless (marker-buffer org-clock-marker)
23002 (error "No running clock"))
23003 (org-with-remote-undo (marker-buffer org-clock-marker)
23004 (org-clock-cancel)))
23006 (defun org-agenda-diary-entry ()
23007 "Make a diary entry, like the `i' command from the calendar.
23008 All the standard commands work: block, weekly etc."
23009 (interactive)
23010 (org-agenda-check-type t 'agenda 'timeline)
23011 (require 'diary-lib)
23012 (let* ((char (progn
23013 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23014 (read-char-exclusive)))
23015 (cmd (cdr (assoc char
23016 '((?d . insert-diary-entry)
23017 (?w . insert-weekly-diary-entry)
23018 (?m . insert-monthly-diary-entry)
23019 (?y . insert-yearly-diary-entry)
23020 (?a . insert-anniversary-diary-entry)
23021 (?b . insert-block-diary-entry)
23022 (?c . insert-cyclic-diary-entry)))))
23023 (oldf (symbol-function 'calendar-cursor-to-date))
23024 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23025 (point (point))
23026 (mark (or (mark t) (point))))
23027 (unless cmd
23028 (error "No command associated with <%c>" char))
23029 (unless (and (get-text-property point 'day)
23030 (or (not (equal ?b char))
23031 (get-text-property mark 'day)))
23032 (error "Don't know which date to use for diary entry"))
23033 ;; We implement this by hacking the `calendar-cursor-to-date' function
23034 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23035 (let ((calendar-mark-ring
23036 (list (calendar-gregorian-from-absolute
23037 (or (get-text-property mark 'day)
23038 (get-text-property point 'day))))))
23039 (unwind-protect
23040 (progn
23041 (fset 'calendar-cursor-to-date
23042 (lambda (&optional error)
23043 (calendar-gregorian-from-absolute
23044 (get-text-property point 'day))))
23045 (call-interactively cmd))
23046 (fset 'calendar-cursor-to-date oldf)))))
23049 (defun org-agenda-execute-calendar-command (cmd)
23050 "Execute a calendar command from the agenda, with the date associated to
23051 the cursor position."
23052 (org-agenda-check-type t 'agenda 'timeline)
23053 (require 'diary-lib)
23054 (unless (get-text-property (point) 'day)
23055 (error "Don't know which date to use for calendar command"))
23056 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23057 (point (point))
23058 (date (calendar-gregorian-from-absolute
23059 (get-text-property point 'day)))
23060 ;; the following 3 vars are needed in the calendar
23061 (displayed-day (extract-calendar-day date))
23062 (displayed-month (extract-calendar-month date))
23063 (displayed-year (extract-calendar-year date)))
23064 (unwind-protect
23065 (progn
23066 (fset 'calendar-cursor-to-date
23067 (lambda (&optional error)
23068 (calendar-gregorian-from-absolute
23069 (get-text-property point 'day))))
23070 (call-interactively cmd))
23071 (fset 'calendar-cursor-to-date oldf))))
23073 (defun org-agenda-phases-of-moon ()
23074 "Display the phases of the moon for the 3 months around the cursor date."
23075 (interactive)
23076 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23078 (defun org-agenda-holidays ()
23079 "Display the holidays for the 3 months around the cursor date."
23080 (interactive)
23081 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23083 (defun org-agenda-sunrise-sunset (arg)
23084 "Display sunrise and sunset for the cursor date.
23085 Latitude and longitude can be specified with the variables
23086 `calendar-latitude' and `calendar-longitude'. When called with prefix
23087 argument, latitude and longitude will be prompted for."
23088 (interactive "P")
23089 (let ((calendar-longitude (if arg nil calendar-longitude))
23090 (calendar-latitude (if arg nil calendar-latitude))
23091 (calendar-location-name
23092 (if arg "the given coordinates" calendar-location-name)))
23093 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23095 (defun org-agenda-goto-calendar ()
23096 "Open the Emacs calendar with the date at the cursor."
23097 (interactive)
23098 (org-agenda-check-type t 'agenda 'timeline)
23099 (let* ((day (or (get-text-property (point) 'day)
23100 (error "Don't know which date to open in calendar")))
23101 (date (calendar-gregorian-from-absolute day))
23102 (calendar-move-hook nil)
23103 (view-calendar-holidays-initially nil)
23104 (view-diary-entries-initially nil))
23105 (calendar)
23106 (calendar-goto-date date)))
23108 (defun org-calendar-goto-agenda ()
23109 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23110 This is a command that has to be installed in `calendar-mode-map'."
23111 (interactive)
23112 (org-agenda-list nil (calendar-absolute-from-gregorian
23113 (calendar-cursor-to-date))
23114 nil))
23116 (defun org-agenda-convert-date ()
23117 (interactive)
23118 (org-agenda-check-type t 'agenda 'timeline)
23119 (let ((day (get-text-property (point) 'day))
23120 date s)
23121 (unless day
23122 (error "Don't know which date to convert"))
23123 (setq date (calendar-gregorian-from-absolute day))
23124 (setq s (concat
23125 "Gregorian: " (calendar-date-string date) "\n"
23126 "ISO: " (calendar-iso-date-string date) "\n"
23127 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23128 "Julian: " (calendar-julian-date-string date) "\n"
23129 "Astron. JD: " (calendar-astro-date-string date)
23130 " (Julian date number at noon UTC)\n"
23131 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23132 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23133 "French: " (calendar-french-date-string date) "\n"
23134 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23135 "Mayan: " (calendar-mayan-date-string date) "\n"
23136 "Coptic: " (calendar-coptic-date-string date) "\n"
23137 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23138 "Persian: " (calendar-persian-date-string date) "\n"
23139 "Chinese: " (calendar-chinese-date-string date) "\n"))
23140 (with-output-to-temp-buffer "*Dates*"
23141 (princ s))
23142 (if (fboundp 'fit-window-to-buffer)
23143 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23146 ;;;; Embedded LaTeX
23148 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23149 "Keymap for the minor `org-cdlatex-mode'.")
23151 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23152 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23153 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23154 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23155 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23157 (defvar org-cdlatex-texmathp-advice-is-done nil
23158 "Flag remembering if we have applied the advice to texmathp already.")
23160 (define-minor-mode org-cdlatex-mode
23161 "Toggle the minor `org-cdlatex-mode'.
23162 This mode supports entering LaTeX environment and math in LaTeX fragments
23163 in Org-mode.
23164 \\{org-cdlatex-mode-map}"
23165 nil " OCDL" nil
23166 (when org-cdlatex-mode (require 'cdlatex))
23167 (unless org-cdlatex-texmathp-advice-is-done
23168 (setq org-cdlatex-texmathp-advice-is-done t)
23169 (defadvice texmathp (around org-math-always-on activate)
23170 "Always return t in org-mode buffers.
23171 This is because we want to insert math symbols without dollars even outside
23172 the LaTeX math segments. If Orgmode thinks that point is actually inside
23173 en embedded LaTeX fragement, let texmathp do its job.
23174 \\[org-cdlatex-mode-map]"
23175 (interactive)
23176 (let (p)
23177 (cond
23178 ((not (org-mode-p)) ad-do-it)
23179 ((eq this-command 'cdlatex-math-symbol)
23180 (setq ad-return-value t
23181 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23183 (let ((p (org-inside-LaTeX-fragment-p)))
23184 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23185 (setq ad-return-value t
23186 texmathp-why '("Org-mode embedded math" . 0))
23187 (if p ad-do-it)))))))))
23189 (defun turn-on-org-cdlatex ()
23190 "Unconditionally turn on `org-cdlatex-mode'."
23191 (org-cdlatex-mode 1))
23193 (defun org-inside-LaTeX-fragment-p ()
23194 "Test if point is inside a LaTeX fragment.
23195 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23196 sequence appearing also before point.
23197 Even though the matchers for math are configurable, this function assumes
23198 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23199 delimiters are skipped when they have been removed by customization.
23200 The return value is nil, or a cons cell with the delimiter and
23201 and the position of this delimiter.
23203 This function does a reasonably good job, but can locally be fooled by
23204 for example currency specifications. For example it will assume being in
23205 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23206 fragments that are properly closed, but during editing, we have to live
23207 with the uncertainty caused by missing closing delimiters. This function
23208 looks only before point, not after."
23209 (catch 'exit
23210 (let ((pos (point))
23211 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23212 (lim (progn
23213 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23214 (point)))
23215 dd-on str (start 0) m re)
23216 (goto-char pos)
23217 (when dodollar
23218 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23219 re (nth 1 (assoc "$" org-latex-regexps)))
23220 (while (string-match re str start)
23221 (cond
23222 ((= (match-end 0) (length str))
23223 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23224 ((= (match-end 0) (- (length str) 5))
23225 (throw 'exit nil))
23226 (t (setq start (match-end 0))))))
23227 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23228 (goto-char pos)
23229 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23230 (and (match-beginning 2) (throw 'exit nil))
23231 ;; count $$
23232 (while (re-search-backward "\\$\\$" lim t)
23233 (setq dd-on (not dd-on)))
23234 (goto-char pos)
23235 (if dd-on (cons "$$" m))))))
23238 (defun org-try-cdlatex-tab ()
23239 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23240 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23241 - inside a LaTeX fragment, or
23242 - after the first word in a line, where an abbreviation expansion could
23243 insert a LaTeX environment."
23244 (when org-cdlatex-mode
23245 (cond
23246 ((save-excursion
23247 (skip-chars-backward "a-zA-Z0-9*")
23248 (skip-chars-backward " \t")
23249 (bolp))
23250 (cdlatex-tab) t)
23251 ((org-inside-LaTeX-fragment-p)
23252 (cdlatex-tab) t)
23253 (t nil))))
23255 (defun org-cdlatex-underscore-caret (&optional arg)
23256 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23257 Revert to the normal definition outside of these fragments."
23258 (interactive "P")
23259 (if (org-inside-LaTeX-fragment-p)
23260 (call-interactively 'cdlatex-sub-superscript)
23261 (let (org-cdlatex-mode)
23262 (call-interactively (key-binding (vector last-input-event))))))
23264 (defun org-cdlatex-math-modify (&optional arg)
23265 "Execute `cdlatex-math-modify' in LaTeX fragments.
23266 Revert to the normal definition outside of these fragments."
23267 (interactive "P")
23268 (if (org-inside-LaTeX-fragment-p)
23269 (call-interactively 'cdlatex-math-modify)
23270 (let (org-cdlatex-mode)
23271 (call-interactively (key-binding (vector last-input-event))))))
23273 (defvar org-latex-fragment-image-overlays nil
23274 "List of overlays carrying the images of latex fragments.")
23275 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23277 (defun org-remove-latex-fragment-image-overlays ()
23278 "Remove all overlays with LaTeX fragment images in current buffer."
23279 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23280 (setq org-latex-fragment-image-overlays nil))
23282 (defun org-preview-latex-fragment (&optional subtree)
23283 "Preview the LaTeX fragment at point, or all locally or globally.
23284 If the cursor is in a LaTeX fragment, create the image and overlay
23285 it over the source code. If there is no fragment at point, display
23286 all fragments in the current text, from one headline to the next. With
23287 prefix SUBTREE, display all fragments in the current subtree. With a
23288 double prefix `C-u C-u', or when the cursor is before the first headline,
23289 display all fragments in the buffer.
23290 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23291 (interactive "P")
23292 (org-remove-latex-fragment-image-overlays)
23293 (save-excursion
23294 (save-restriction
23295 (let (beg end at msg)
23296 (cond
23297 ((or (equal subtree '(16))
23298 (not (save-excursion
23299 (re-search-backward (concat "^" outline-regexp) nil t))))
23300 (setq beg (point-min) end (point-max)
23301 msg "Creating images for buffer...%s"))
23302 ((equal subtree '(4))
23303 (org-back-to-heading)
23304 (setq beg (point) end (org-end-of-subtree t)
23305 msg "Creating images for subtree...%s"))
23307 (if (setq at (org-inside-LaTeX-fragment-p))
23308 (goto-char (max (point-min) (- (cdr at) 2)))
23309 (org-back-to-heading))
23310 (setq beg (point) end (progn (outline-next-heading) (point))
23311 msg (if at "Creating image...%s"
23312 "Creating images for entry...%s"))))
23313 (message msg "")
23314 (narrow-to-region beg end)
23315 (goto-char beg)
23316 (org-format-latex
23317 (concat "ltxpng/" (file-name-sans-extension
23318 (file-name-nondirectory
23319 buffer-file-name)))
23320 default-directory 'overlays msg at 'forbuffer)
23321 (message msg "done. Use `C-c C-c' to remove images.")))))
23323 (defvar org-latex-regexps
23324 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23325 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23326 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23327 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23328 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23329 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23330 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23331 "Regular expressions for matching embedded LaTeX.")
23333 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23334 "Replace LaTeX fragments with links to an image, and produce images."
23335 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23336 (let* ((prefixnodir (file-name-nondirectory prefix))
23337 (absprefix (expand-file-name prefix dir))
23338 (todir (file-name-directory absprefix))
23339 (opt org-format-latex-options)
23340 (matchers (plist-get opt :matchers))
23341 (re-list org-latex-regexps)
23342 (cnt 0) txt link beg end re e checkdir
23343 m n block linkfile movefile ov)
23344 ;; Check if there are old images files with this prefix, and remove them
23345 (when (file-directory-p todir)
23346 (mapc 'delete-file
23347 (directory-files
23348 todir 'full
23349 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23350 ;; Check the different regular expressions
23351 (while (setq e (pop re-list))
23352 (setq m (car e) re (nth 1 e) n (nth 2 e)
23353 block (if (nth 3 e) "\n\n" ""))
23354 (when (member m matchers)
23355 (goto-char (point-min))
23356 (while (re-search-forward re nil t)
23357 (when (or (not at) (equal (cdr at) (match-beginning n)))
23358 (setq txt (match-string n)
23359 beg (match-beginning n) end (match-end n)
23360 cnt (1+ cnt)
23361 linkfile (format "%s_%04d.png" prefix cnt)
23362 movefile (format "%s_%04d.png" absprefix cnt)
23363 link (concat block "[[file:" linkfile "]]" block))
23364 (if msg (message msg cnt))
23365 (goto-char beg)
23366 (unless checkdir ; make sure the directory exists
23367 (setq checkdir t)
23368 (or (file-directory-p todir) (make-directory todir)))
23369 (org-create-formula-image
23370 txt movefile opt forbuffer)
23371 (if overlays
23372 (progn
23373 (setq ov (org-make-overlay beg end))
23374 (if (featurep 'xemacs)
23375 (progn
23376 (org-overlay-put ov 'invisible t)
23377 (org-overlay-put
23378 ov 'end-glyph
23379 (make-glyph (vector 'png :file movefile))))
23380 (org-overlay-put
23381 ov 'display
23382 (list 'image :type 'png :file movefile :ascent 'center)))
23383 (push ov org-latex-fragment-image-overlays)
23384 (goto-char end))
23385 (delete-region beg end)
23386 (insert link))))))))
23388 ;; This function borrows from Ganesh Swami's latex2png.el
23389 (defun org-create-formula-image (string tofile options buffer)
23390 (let* ((tmpdir (if (featurep 'xemacs)
23391 (temp-directory)
23392 temporary-file-directory))
23393 (texfilebase (make-temp-name
23394 (expand-file-name "orgtex" tmpdir)))
23395 (texfile (concat texfilebase ".tex"))
23396 (dvifile (concat texfilebase ".dvi"))
23397 (pngfile (concat texfilebase ".png"))
23398 (fnh (face-attribute 'default :height nil))
23399 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23400 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23401 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23402 "Black"))
23403 (bg (or (plist-get options (if buffer :background :html-background))
23404 "Transparent")))
23405 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23406 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23407 (with-temp-file texfile
23408 (insert org-format-latex-header
23409 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23410 (let ((dir default-directory))
23411 (condition-case nil
23412 (progn
23413 (cd tmpdir)
23414 (call-process "latex" nil nil nil texfile))
23415 (error nil))
23416 (cd dir))
23417 (if (not (file-exists-p dvifile))
23418 (progn (message "Failed to create dvi file from %s" texfile) nil)
23419 (call-process "dvipng" nil nil nil
23420 "-E" "-fg" fg "-bg" bg
23421 "-D" dpi
23422 ;;"-x" scale "-y" scale
23423 "-T" "tight"
23424 "-o" pngfile
23425 dvifile)
23426 (if (not (file-exists-p pngfile))
23427 (progn (message "Failed to create png file from %s" texfile) nil)
23428 ;; Use the requested file name and clean up
23429 (copy-file pngfile tofile 'replace)
23430 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23431 (delete-file (concat texfilebase e)))
23432 pngfile))))
23434 (defun org-dvipng-color (attr)
23435 "Return an rgb color specification for dvipng."
23436 (apply 'format "rgb %s %s %s"
23437 (mapcar 'org-normalize-color
23438 (color-values (face-attribute 'default attr nil)))))
23440 (defun org-normalize-color (value)
23441 "Return string to be used as color value for an RGB component."
23442 (format "%g" (/ value 65535.0)))
23444 ;;;; Exporting
23446 ;;; Variables, constants, and parameter plists
23448 (defconst org-level-max 20)
23450 (defvar org-export-html-preamble nil
23451 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23452 (defvar org-export-html-postamble nil
23453 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23454 (defvar org-export-html-auto-preamble t
23455 "Should default preamble be inserted? Set by publishing functions.")
23456 (defvar org-export-html-auto-postamble t
23457 "Should default postamble be inserted? Set by publishing functions.")
23458 (defvar org-current-export-file nil) ; dynamically scoped parameter
23459 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23462 (defconst org-export-plist-vars
23463 '((:language . org-export-default-language)
23464 (:customtime . org-display-custom-times)
23465 (:headline-levels . org-export-headline-levels)
23466 (:section-numbers . org-export-with-section-numbers)
23467 (:table-of-contents . org-export-with-toc)
23468 (:preserve-breaks . org-export-preserve-breaks)
23469 (:archived-trees . org-export-with-archived-trees)
23470 (:emphasize . org-export-with-emphasize)
23471 (:sub-superscript . org-export-with-sub-superscripts)
23472 (:special-strings . org-export-with-special-strings)
23473 (:footnotes . org-export-with-footnotes)
23474 (:drawers . org-export-with-drawers)
23475 (:tags . org-export-with-tags)
23476 (:TeX-macros . org-export-with-TeX-macros)
23477 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23478 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23479 (:fixed-width . org-export-with-fixed-width)
23480 (:timestamps . org-export-with-timestamps)
23481 (:author-info . org-export-author-info)
23482 (:time-stamp-file . org-export-time-stamp-file)
23483 (:tables . org-export-with-tables)
23484 (:table-auto-headline . org-export-highlight-first-table-line)
23485 (:style . org-export-html-style)
23486 (:agenda-style . org-agenda-export-html-style)
23487 (:convert-org-links . org-export-html-link-org-files-as-html)
23488 (:inline-images . org-export-html-inline-images)
23489 (:html-extension . org-export-html-extension)
23490 (:html-table-tag . org-export-html-table-tag)
23491 (:expand-quoted-html . org-export-html-expand)
23492 (:timestamp . org-export-html-with-timestamp)
23493 (:publishing-directory . org-export-publishing-directory)
23494 (:preamble . org-export-html-preamble)
23495 (:postamble . org-export-html-postamble)
23496 (:auto-preamble . org-export-html-auto-preamble)
23497 (:auto-postamble . org-export-html-auto-postamble)
23498 (:author . user-full-name)
23499 (:email . user-mail-address)))
23501 (defun org-default-export-plist ()
23502 "Return the property list with default settings for the export variables."
23503 (let ((l org-export-plist-vars) rtn e)
23504 (while (setq e (pop l))
23505 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23506 rtn))
23508 (defun org-infile-export-plist ()
23509 "Return the property list with file-local settings for export."
23510 (save-excursion
23511 (save-restriction
23512 (widen)
23513 (goto-char 0)
23514 (let ((re (org-make-options-regexp
23515 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23516 p key val text options)
23517 (while (re-search-forward re nil t)
23518 (setq key (org-match-string-no-properties 1)
23519 val (org-match-string-no-properties 2))
23520 (cond
23521 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23522 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23523 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23524 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23525 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23526 ((string-equal key "TEXT")
23527 (setq text (if text (concat text "\n" val) val)))
23528 ((string-equal key "OPTIONS") (setq options val))))
23529 (setq p (plist-put p :text text))
23530 (when options
23531 (let ((op '(("H" . :headline-levels)
23532 ("num" . :section-numbers)
23533 ("toc" . :table-of-contents)
23534 ("\\n" . :preserve-breaks)
23535 ("@" . :expand-quoted-html)
23536 (":" . :fixed-width)
23537 ("|" . :tables)
23538 ("^" . :sub-superscript)
23539 ("-" . :special-strings)
23540 ("f" . :footnotes)
23541 ("d" . :drawers)
23542 ("tags" . :tags)
23543 ("*" . :emphasize)
23544 ("TeX" . :TeX-macros)
23545 ("LaTeX" . :LaTeX-fragments)
23546 ("skip" . :skip-before-1st-heading)
23547 ("author" . :author-info)
23548 ("timestamp" . :time-stamp-file)))
23550 (while (setq o (pop op))
23551 (if (string-match (concat (regexp-quote (car o))
23552 ":\\([^ \t\n\r;,.]*\\)")
23553 options)
23554 (setq p (plist-put p (cdr o)
23555 (car (read-from-string
23556 (match-string 1 options)))))))))
23557 p))))
23559 (defun org-export-directory (type plist)
23560 (let* ((val (plist-get plist :publishing-directory))
23561 (dir (if (listp val)
23562 (or (cdr (assoc type val)) ".")
23563 val)))
23564 dir))
23566 (defun org-skip-comments (lines)
23567 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23568 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23569 (re2 "^\\(\\*+\\)[ \t\n\r]")
23570 (case-fold-search nil)
23571 rtn line level)
23572 (while (setq line (pop lines))
23573 (cond
23574 ((and (string-match re1 line)
23575 (setq level (- (match-end 1) (match-beginning 1))))
23576 ;; Beginning of a COMMENT subtree. Skip it.
23577 (while (and (setq line (pop lines))
23578 (or (not (string-match re2 line))
23579 (> (- (match-end 1) (match-beginning 1)) level))))
23580 (setq lines (cons line lines)))
23581 ((string-match "^#" line)
23582 ;; an ordinary comment line
23584 ((and org-export-table-remove-special-lines
23585 (string-match "^[ \t]*|" line)
23586 (or (string-match "^[ \t]*| *[!_^] *|" line)
23587 (and (string-match "| *<[0-9]+> *|" line)
23588 (not (string-match "| *[^ <|]" line)))))
23589 ;; a special table line that should be removed
23591 (t (setq rtn (cons line rtn)))))
23592 (nreverse rtn)))
23594 (defun org-export (&optional arg)
23595 (interactive)
23596 (let ((help "[t] insert the export option template
23597 \[v] limit export to visible part of outline tree
23599 \[a] export as ASCII
23601 \[h] export as HTML
23602 \[H] export as HTML to temporary buffer
23603 \[R] export region as HTML
23604 \[b] export as HTML and browse immediately
23605 \[x] export as XOXO
23607 \[l] export as LaTeX
23608 \[L] export as LaTeX to temporary buffer
23610 \[i] export current file as iCalendar file
23611 \[I] export all agenda files as iCalendar files
23612 \[c] export agenda files into combined iCalendar file
23614 \[F] publish current file
23615 \[P] publish current project
23616 \[X] publish... (project will be prompted for)
23617 \[A] publish all projects")
23618 (cmds
23619 '((?t . org-insert-export-options-template)
23620 (?v . org-export-visible)
23621 (?a . org-export-as-ascii)
23622 (?h . org-export-as-html)
23623 (?b . org-export-as-html-and-open)
23624 (?H . org-export-as-html-to-buffer)
23625 (?R . org-export-region-as-html)
23626 (?x . org-export-as-xoxo)
23627 (?l . org-export-as-latex)
23628 (?L . org-export-as-latex-to-buffer)
23629 (?i . org-export-icalendar-this-file)
23630 (?I . org-export-icalendar-all-agenda-files)
23631 (?c . org-export-icalendar-combine-agenda-files)
23632 (?F . org-publish-current-file)
23633 (?P . org-publish-current-project)
23634 (?X . org-publish)
23635 (?A . org-publish-all)))
23636 r1 r2 ass)
23637 (save-window-excursion
23638 (delete-other-windows)
23639 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23640 (princ help))
23641 (message "Select command: ")
23642 (setq r1 (read-char-exclusive)))
23643 (setq r2 (if (< r1 27) (+ r1 96) r1))
23644 (if (setq ass (assq r2 cmds))
23645 (call-interactively (cdr ass))
23646 (error "No command associated with key %c" r1))))
23648 (defconst org-html-entities
23649 '(("nbsp")
23650 ("iexcl")
23651 ("cent")
23652 ("pound")
23653 ("curren")
23654 ("yen")
23655 ("brvbar")
23656 ("vert" . "&#124;")
23657 ("sect")
23658 ("uml")
23659 ("copy")
23660 ("ordf")
23661 ("laquo")
23662 ("not")
23663 ("shy")
23664 ("reg")
23665 ("macr")
23666 ("deg")
23667 ("plusmn")
23668 ("sup2")
23669 ("sup3")
23670 ("acute")
23671 ("micro")
23672 ("para")
23673 ("middot")
23674 ("odot"."o")
23675 ("star"."*")
23676 ("cedil")
23677 ("sup1")
23678 ("ordm")
23679 ("raquo")
23680 ("frac14")
23681 ("frac12")
23682 ("frac34")
23683 ("iquest")
23684 ("Agrave")
23685 ("Aacute")
23686 ("Acirc")
23687 ("Atilde")
23688 ("Auml")
23689 ("Aring") ("AA"."&Aring;")
23690 ("AElig")
23691 ("Ccedil")
23692 ("Egrave")
23693 ("Eacute")
23694 ("Ecirc")
23695 ("Euml")
23696 ("Igrave")
23697 ("Iacute")
23698 ("Icirc")
23699 ("Iuml")
23700 ("ETH")
23701 ("Ntilde")
23702 ("Ograve")
23703 ("Oacute")
23704 ("Ocirc")
23705 ("Otilde")
23706 ("Ouml")
23707 ("times")
23708 ("Oslash")
23709 ("Ugrave")
23710 ("Uacute")
23711 ("Ucirc")
23712 ("Uuml")
23713 ("Yacute")
23714 ("THORN")
23715 ("szlig")
23716 ("agrave")
23717 ("aacute")
23718 ("acirc")
23719 ("atilde")
23720 ("auml")
23721 ("aring")
23722 ("aelig")
23723 ("ccedil")
23724 ("egrave")
23725 ("eacute")
23726 ("ecirc")
23727 ("euml")
23728 ("igrave")
23729 ("iacute")
23730 ("icirc")
23731 ("iuml")
23732 ("eth")
23733 ("ntilde")
23734 ("ograve")
23735 ("oacute")
23736 ("ocirc")
23737 ("otilde")
23738 ("ouml")
23739 ("divide")
23740 ("oslash")
23741 ("ugrave")
23742 ("uacute")
23743 ("ucirc")
23744 ("uuml")
23745 ("yacute")
23746 ("thorn")
23747 ("yuml")
23748 ("fnof")
23749 ("Alpha")
23750 ("Beta")
23751 ("Gamma")
23752 ("Delta")
23753 ("Epsilon")
23754 ("Zeta")
23755 ("Eta")
23756 ("Theta")
23757 ("Iota")
23758 ("Kappa")
23759 ("Lambda")
23760 ("Mu")
23761 ("Nu")
23762 ("Xi")
23763 ("Omicron")
23764 ("Pi")
23765 ("Rho")
23766 ("Sigma")
23767 ("Tau")
23768 ("Upsilon")
23769 ("Phi")
23770 ("Chi")
23771 ("Psi")
23772 ("Omega")
23773 ("alpha")
23774 ("beta")
23775 ("gamma")
23776 ("delta")
23777 ("epsilon")
23778 ("varepsilon"."&epsilon;")
23779 ("zeta")
23780 ("eta")
23781 ("theta")
23782 ("iota")
23783 ("kappa")
23784 ("lambda")
23785 ("mu")
23786 ("nu")
23787 ("xi")
23788 ("omicron")
23789 ("pi")
23790 ("rho")
23791 ("sigmaf") ("varsigma"."&sigmaf;")
23792 ("sigma")
23793 ("tau")
23794 ("upsilon")
23795 ("phi")
23796 ("chi")
23797 ("psi")
23798 ("omega")
23799 ("thetasym") ("vartheta"."&thetasym;")
23800 ("upsih")
23801 ("piv")
23802 ("bull") ("bullet"."&bull;")
23803 ("hellip") ("dots"."&hellip;")
23804 ("prime")
23805 ("Prime")
23806 ("oline")
23807 ("frasl")
23808 ("weierp")
23809 ("image")
23810 ("real")
23811 ("trade")
23812 ("alefsym")
23813 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
23814 ("uarr") ("uparrow"."&uarr;")
23815 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
23816 ("darr")("downarrow"."&darr;")
23817 ("harr") ("leftrightarrow"."&harr;")
23818 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
23819 ("lArr") ("Leftarrow"."&lArr;")
23820 ("uArr") ("Uparrow"."&uArr;")
23821 ("rArr") ("Rightarrow"."&rArr;")
23822 ("dArr") ("Downarrow"."&dArr;")
23823 ("hArr") ("Leftrightarrow"."&hArr;")
23824 ("forall")
23825 ("part") ("partial"."&part;")
23826 ("exist") ("exists"."&exist;")
23827 ("empty") ("emptyset"."&empty;")
23828 ("nabla")
23829 ("isin") ("in"."&isin;")
23830 ("notin")
23831 ("ni")
23832 ("prod")
23833 ("sum")
23834 ("minus")
23835 ("lowast") ("ast"."&lowast;")
23836 ("radic")
23837 ("prop") ("proptp"."&prop;")
23838 ("infin") ("infty"."&infin;")
23839 ("ang") ("angle"."&ang;")
23840 ("and") ("wedge"."&and;")
23841 ("or") ("vee"."&or;")
23842 ("cap")
23843 ("cup")
23844 ("int")
23845 ("there4")
23846 ("sim")
23847 ("cong") ("simeq"."&cong;")
23848 ("asymp")("approx"."&asymp;")
23849 ("ne") ("neq"."&ne;")
23850 ("equiv")
23851 ("le")
23852 ("ge")
23853 ("sub") ("subset"."&sub;")
23854 ("sup") ("supset"."&sup;")
23855 ("nsub")
23856 ("sube")
23857 ("supe")
23858 ("oplus")
23859 ("otimes")
23860 ("perp")
23861 ("sdot") ("cdot"."&sdot;")
23862 ("lceil")
23863 ("rceil")
23864 ("lfloor")
23865 ("rfloor")
23866 ("lang")
23867 ("rang")
23868 ("loz") ("Diamond"."&loz;")
23869 ("spades") ("spadesuit"."&spades;")
23870 ("clubs") ("clubsuit"."&clubs;")
23871 ("hearts") ("diamondsuit"."&hearts;")
23872 ("diams") ("diamondsuit"."&diams;")
23873 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
23874 ("quot")
23875 ("amp")
23876 ("lt")
23877 ("gt")
23878 ("OElig")
23879 ("oelig")
23880 ("Scaron")
23881 ("scaron")
23882 ("Yuml")
23883 ("circ")
23884 ("tilde")
23885 ("ensp")
23886 ("emsp")
23887 ("thinsp")
23888 ("zwnj")
23889 ("zwj")
23890 ("lrm")
23891 ("rlm")
23892 ("ndash")
23893 ("mdash")
23894 ("lsquo")
23895 ("rsquo")
23896 ("sbquo")
23897 ("ldquo")
23898 ("rdquo")
23899 ("bdquo")
23900 ("dagger")
23901 ("Dagger")
23902 ("permil")
23903 ("lsaquo")
23904 ("rsaquo")
23905 ("euro")
23907 ("arccos"."arccos")
23908 ("arcsin"."arcsin")
23909 ("arctan"."arctan")
23910 ("arg"."arg")
23911 ("cos"."cos")
23912 ("cosh"."cosh")
23913 ("cot"."cot")
23914 ("coth"."coth")
23915 ("csc"."csc")
23916 ("deg"."deg")
23917 ("det"."det")
23918 ("dim"."dim")
23919 ("exp"."exp")
23920 ("gcd"."gcd")
23921 ("hom"."hom")
23922 ("inf"."inf")
23923 ("ker"."ker")
23924 ("lg"."lg")
23925 ("lim"."lim")
23926 ("liminf"."liminf")
23927 ("limsup"."limsup")
23928 ("ln"."ln")
23929 ("log"."log")
23930 ("max"."max")
23931 ("min"."min")
23932 ("Pr"."Pr")
23933 ("sec"."sec")
23934 ("sin"."sin")
23935 ("sinh"."sinh")
23936 ("sup"."sup")
23937 ("tan"."tan")
23938 ("tanh"."tanh")
23940 "Entities for TeX->HTML translation.
23941 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
23942 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
23943 In that case, \"\\ent\" will be translated to \"&other;\".
23944 The list contains HTML entities for Latin-1, Greek and other symbols.
23945 It is supplemented by a number of commonly used TeX macros with appropriate
23946 translations. There is currently no way for users to extend this.")
23948 ;;; General functions for all backends
23950 (defun org-cleaned-string-for-export (string &rest parameters)
23951 "Cleanup a buffer STRING so that links can be created safely."
23952 (interactive)
23953 (let* ((re-radio (and org-target-link-regexp
23954 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
23955 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
23956 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
23957 (re-archive (concat ":" org-archive-tag ":"))
23958 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
23959 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
23960 (htmlp (plist-get parameters :for-html))
23961 (asciip (plist-get parameters :for-ascii))
23962 (latexp (plist-get parameters :for-LaTeX))
23963 (commentsp (plist-get parameters :comments))
23964 (archived-trees (plist-get parameters :archived-trees))
23965 (inhibit-read-only t)
23966 (drawers org-drawers)
23967 (exp-drawers (plist-get parameters :drawers))
23968 (outline-regexp "\\*+ ")
23969 a b xx
23970 rtn p)
23971 (with-current-buffer (get-buffer-create " org-mode-tmp")
23972 (erase-buffer)
23973 (insert string)
23974 ;; Remove license-to-kill stuff
23975 (while (setq p (text-property-any (point-min) (point-max)
23976 :org-license-to-kill t))
23977 (delete-region p (next-single-property-change p :org-license-to-kill)))
23979 (let ((org-inhibit-startup t)) (org-mode))
23980 (untabify (point-min) (point-max))
23982 ;; Get rid of drawers
23983 (unless (eq t exp-drawers)
23984 (goto-char (point-min))
23985 (let ((re (concat "^[ \t]*:\\("
23986 (mapconcat
23987 'identity
23988 (org-delete-all exp-drawers
23989 (copy-sequence drawers))
23990 "\\|")
23991 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
23992 (while (re-search-forward re nil t)
23993 (replace-match ""))))
23995 ;; Get the correct stuff before the first headline
23996 (when (plist-get parameters :skip-before-1st-heading)
23997 (goto-char (point-min))
23998 (when (re-search-forward "^\\*+[ \t]" nil t)
23999 (delete-region (point-min) (match-beginning 0))
24000 (goto-char (point-min))
24001 (insert "\n")))
24002 (when (plist-get parameters :add-text)
24003 (goto-char (point-min))
24004 (insert (plist-get parameters :add-text) "\n"))
24006 ;; Get rid of archived trees
24007 (when (not (eq archived-trees t))
24008 (goto-char (point-min))
24009 (while (re-search-forward re-archive nil t)
24010 (if (not (org-on-heading-p t))
24011 (org-end-of-subtree t)
24012 (beginning-of-line 1)
24013 (setq a (if archived-trees
24014 (1+ (point-at-eol)) (point))
24015 b (org-end-of-subtree t))
24016 (if (> b a) (delete-region a b)))))
24018 ;; Find targets in comments and move them out of comments,
24019 ;; but mark them as targets that should be invisible
24020 (goto-char (point-min))
24021 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24022 (replace-match "\\1(INVISIBLE)"))
24024 ;; Protect backend specific stuff, throw away the others.
24025 (let ((formatters
24026 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24027 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24028 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24029 fmt)
24030 (goto-char (point-min))
24031 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24032 (goto-char (match-end 0))
24033 (while (not (looking-at "#\\+END_EXAMPLE"))
24034 (insert ": ")
24035 (beginning-of-line 2)))
24036 (goto-char (point-min))
24037 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24038 (add-text-properties (match-beginning 0) (match-end 0)
24039 '(org-protected t)))
24040 (while formatters
24041 (setq fmt (pop formatters))
24042 (when (car fmt)
24043 (goto-char (point-min))
24044 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24045 ":[ \t]*\\(.*\\)") nil t)
24046 (replace-match "\\1" t)
24047 (add-text-properties
24048 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24049 '(org-protected t))))
24050 (goto-char (point-min))
24051 (while (re-search-forward
24052 (concat "^#\\+"
24053 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24054 (cadddr fmt) "\\>.*\n?") nil t)
24055 (if (car fmt)
24056 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24057 '(org-protected t))
24058 (delete-region (match-beginning 0) (match-end 0))))))
24060 ;; Protect quoted subtrees
24061 (goto-char (point-min))
24062 (while (re-search-forward re-quote nil t)
24063 (goto-char (match-beginning 0))
24064 (end-of-line 1)
24065 (add-text-properties (point) (org-end-of-subtree t)
24066 '(org-protected t)))
24068 ;; Protect verbatim elements
24069 (goto-char (point-min))
24070 (while (re-search-forward org-verbatim-re nil t)
24071 (add-text-properties (match-beginning 4) (match-end 4)
24072 '(org-protected t))
24073 (goto-char (1+ (match-end 4))))
24075 ;; Remove subtrees that are commented
24076 (goto-char (point-min))
24077 (while (re-search-forward re-commented nil t)
24078 (goto-char (match-beginning 0))
24079 (delete-region (point) (org-end-of-subtree t)))
24081 ;; Remove special table lines
24082 (when org-export-table-remove-special-lines
24083 (goto-char (point-min))
24084 (while (re-search-forward "^[ \t]*|" nil t)
24085 (beginning-of-line 1)
24086 (if (or (looking-at "[ \t]*| *[!_^] *|")
24087 (and (looking-at ".*?| *<[0-9]+> *|")
24088 (not (looking-at ".*?| *[^ <|]"))))
24089 (delete-region (max (point-min) (1- (point-at-bol)))
24090 (point-at-eol))
24091 (end-of-line 1))))
24093 ;; Specific LaTeX stuff
24094 (when latexp
24095 (require 'org-export-latex nil)
24096 (org-export-latex-cleaned-string))
24098 (when asciip
24099 (org-export-ascii-clean-string))
24101 ;; Specific HTML stuff
24102 (when htmlp
24103 ;; Convert LaTeX fragments to images
24104 (when (plist-get parameters :LaTeX-fragments)
24105 (org-format-latex
24106 (concat "ltxpng/" (file-name-sans-extension
24107 (file-name-nondirectory
24108 org-current-export-file)))
24109 org-current-export-dir nil "Creating LaTeX image %s"))
24110 (message "Exporting..."))
24112 ;; Remove or replace comments
24113 (goto-char (point-min))
24114 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24115 (if commentsp
24116 (progn (add-text-properties
24117 (match-beginning 0) (match-end 0) '(org-protected t))
24118 (replace-match (format commentsp (match-string 1)) t t))
24119 (replace-match "")))
24121 ;; Find matches for radio targets and turn them into internal links
24122 (goto-char (point-min))
24123 (when re-radio
24124 (while (re-search-forward re-radio nil t)
24125 (org-if-unprotected
24126 (replace-match "\\1[[\\2]]"))))
24128 ;; Find all links that contain a newline and put them into a single line
24129 (goto-char (point-min))
24130 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24131 (org-if-unprotected
24132 (replace-match "\\1 \\3")
24133 (goto-char (match-beginning 0))))
24136 ;; Normalize links: Convert angle and plain links into bracket links
24137 ;; Expand link abbreviations
24138 (goto-char (point-min))
24139 (while (re-search-forward re-plain-link nil t)
24140 (goto-char (1- (match-end 0)))
24141 (org-if-unprotected
24142 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24143 ":" (match-string 3) "]]")))
24144 ;; added 'org-link face to links
24145 (put-text-property 0 (length s) 'face 'org-link s)
24146 (replace-match s t t))))
24147 (goto-char (point-min))
24148 (while (re-search-forward re-angle-link nil t)
24149 (goto-char (1- (match-end 0)))
24150 (org-if-unprotected
24151 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24152 ":" (match-string 3) "]]")))
24153 (put-text-property 0 (length s) 'face 'org-link s)
24154 (replace-match s t t))))
24155 (goto-char (point-min))
24156 (while (re-search-forward org-bracket-link-regexp nil t)
24157 (org-if-unprotected
24158 (let* ((s (concat "[[" (setq xx (save-match-data
24159 (org-link-expand-abbrev (match-string 1))))
24161 (if (match-end 3)
24162 (match-string 2)
24163 (concat "[" xx "]"))
24164 "]")))
24165 (put-text-property 0 (length s) 'face 'org-link s)
24166 (replace-match s t t))))
24168 ;; Find multiline emphasis and put them into single line
24169 (when (plist-get parameters :emph-multiline)
24170 (goto-char (point-min))
24171 (while (re-search-forward org-emph-re nil t)
24172 (if (not (= (char-after (match-beginning 3))
24173 (char-after (match-beginning 4))))
24174 (org-if-unprotected
24175 (subst-char-in-region (match-beginning 0) (match-end 0)
24176 ?\n ?\ t)
24177 (goto-char (1- (match-end 0))))
24178 (goto-char (1+ (match-beginning 0))))))
24180 (setq rtn (buffer-string)))
24181 (kill-buffer " org-mode-tmp")
24182 rtn))
24184 (defun org-export-grab-title-from-buffer ()
24185 "Get a title for the current document, from looking at the buffer."
24186 (let ((inhibit-read-only t))
24187 (save-excursion
24188 (goto-char (point-min))
24189 (let ((end (save-excursion (outline-next-heading) (point))))
24190 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24191 ;; Mark the line so that it will not be exported as normal text.
24192 (org-unmodified
24193 (add-text-properties (match-beginning 0) (match-end 0)
24194 (list :org-license-to-kill t)))
24195 ;; Return the title string
24196 (org-trim (match-string 0)))))))
24198 (defun org-export-get-title-from-subtree ()
24199 "Return subtree title and exclude it from export."
24200 (let (title (m (mark)))
24201 (save-excursion
24202 (goto-char (region-beginning))
24203 (when (and (org-at-heading-p)
24204 (>= (org-end-of-subtree t t) (region-end)))
24205 ;; This is a subtree, we take the title from the first heading
24206 (goto-char (region-beginning))
24207 (looking-at org-todo-line-regexp)
24208 (setq title (match-string 3))
24209 (org-unmodified
24210 (add-text-properties (point) (1+ (point-at-eol))
24211 (list :org-license-to-kill t)))))
24212 title))
24214 (defun org-solidify-link-text (s &optional alist)
24215 "Take link text and make a safe target out of it."
24216 (save-match-data
24217 (let* ((rtn
24218 (mapconcat
24219 'identity
24220 (org-split-string s "[ \t\r\n]+") "--"))
24221 (a (assoc rtn alist)))
24222 (or (cdr a) rtn))))
24224 (defun org-get-min-level (lines)
24225 "Get the minimum level in LINES."
24226 (let ((re "^\\(\\*+\\) ") l min)
24227 (catch 'exit
24228 (while (setq l (pop lines))
24229 (if (string-match re l)
24230 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24231 1)))
24233 ;; Variable holding the vector with section numbers
24234 (defvar org-section-numbers (make-vector org-level-max 0))
24236 (defun org-init-section-numbers ()
24237 "Initialize the vector for the section numbers."
24238 (let* ((level -1)
24239 (numbers (nreverse (org-split-string "" "\\.")))
24240 (depth (1- (length org-section-numbers)))
24241 (i depth) number-string)
24242 (while (>= i 0)
24243 (if (> i level)
24244 (aset org-section-numbers i 0)
24245 (setq number-string (or (car numbers) "0"))
24246 (if (string-match "\\`[A-Z]\\'" number-string)
24247 (aset org-section-numbers i
24248 (- (string-to-char number-string) ?A -1))
24249 (aset org-section-numbers i (string-to-number number-string)))
24250 (pop numbers))
24251 (setq i (1- i)))))
24253 (defun org-section-number (&optional level)
24254 "Return a string with the current section number.
24255 When LEVEL is non-nil, increase section numbers on that level."
24256 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24257 (when level
24258 (when (> level -1)
24259 (aset org-section-numbers
24260 level (1+ (aref org-section-numbers level))))
24261 (setq idx (1+ level))
24262 (while (<= idx depth)
24263 (if (not (= idx 1))
24264 (aset org-section-numbers idx 0))
24265 (setq idx (1+ idx))))
24266 (setq idx 0)
24267 (while (<= idx depth)
24268 (setq n (aref org-section-numbers idx))
24269 (setq string (concat string (if (not (string= string "")) "." "")
24270 (int-to-string n)))
24271 (setq idx (1+ idx)))
24272 (save-match-data
24273 (if (string-match "\\`\\([@0]\\.\\)+" string)
24274 (setq string (replace-match "" t nil string)))
24275 (if (string-match "\\(\\.0\\)+\\'" string)
24276 (setq string (replace-match "" t nil string))))
24277 string))
24279 ;;; ASCII export
24281 (defvar org-last-level nil) ; dynamically scoped variable
24282 (defvar org-min-level nil) ; dynamically scoped variable
24283 (defvar org-levels-open nil) ; dynamically scoped parameter
24284 (defvar org-ascii-current-indentation nil) ; For communication
24286 (defun org-export-as-ascii (arg)
24287 "Export the outline as a pretty ASCII file.
24288 If there is an active region, export only the region.
24289 The prefix ARG specifies how many levels of the outline should become
24290 underlined headlines. The default is 3."
24291 (interactive "P")
24292 (setq-default org-todo-line-regexp org-todo-line-regexp)
24293 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24294 (org-infile-export-plist)))
24295 (region-p (org-region-active-p))
24296 (subtree-p
24297 (when region-p
24298 (save-excursion
24299 (goto-char (region-beginning))
24300 (and (org-at-heading-p)
24301 (>= (org-end-of-subtree t t) (region-end))))))
24302 (custom-times org-display-custom-times)
24303 (org-ascii-current-indentation '(0 . 0))
24304 (level 0) line txt
24305 (umax nil)
24306 (umax-toc nil)
24307 (case-fold-search nil)
24308 (filename (concat (file-name-as-directory
24309 (org-export-directory :ascii opt-plist))
24310 (file-name-sans-extension
24311 (or (and subtree-p
24312 (org-entry-get (region-beginning)
24313 "EXPORT_FILE_NAME" t))
24314 (file-name-nondirectory buffer-file-name)))
24315 ".txt"))
24316 (filename (if (equal (file-truename filename)
24317 (file-truename buffer-file-name))
24318 (concat filename ".txt")
24319 filename))
24320 (buffer (find-file-noselect filename))
24321 (org-levels-open (make-vector org-level-max nil))
24322 (odd org-odd-levels-only)
24323 (date (plist-get opt-plist :date))
24324 (author (plist-get opt-plist :author))
24325 (title (or (and subtree-p (org-export-get-title-from-subtree))
24326 (plist-get opt-plist :title)
24327 (and (not
24328 (plist-get opt-plist :skip-before-1st-heading))
24329 (org-export-grab-title-from-buffer))
24330 (file-name-sans-extension
24331 (file-name-nondirectory buffer-file-name))))
24332 (email (plist-get opt-plist :email))
24333 (language (plist-get opt-plist :language))
24334 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24335 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24336 (todo nil)
24337 (lang-words nil)
24338 (region
24339 (buffer-substring
24340 (if (org-region-active-p) (region-beginning) (point-min))
24341 (if (org-region-active-p) (region-end) (point-max))))
24342 (lines (org-split-string
24343 (org-cleaned-string-for-export
24344 region
24345 :for-ascii t
24346 :skip-before-1st-heading
24347 (plist-get opt-plist :skip-before-1st-heading)
24348 :drawers (plist-get opt-plist :drawers)
24349 :verbatim-multiline t
24350 :archived-trees
24351 (plist-get opt-plist :archived-trees)
24352 :add-text (plist-get opt-plist :text))
24353 "\n"))
24354 thetoc have-headings first-heading-pos
24355 table-open table-buffer)
24357 (let ((inhibit-read-only t))
24358 (org-unmodified
24359 (remove-text-properties (point-min) (point-max)
24360 '(:org-license-to-kill t))))
24362 (setq org-min-level (org-get-min-level lines))
24363 (setq org-last-level org-min-level)
24364 (org-init-section-numbers)
24366 (find-file-noselect filename)
24368 (setq lang-words (or (assoc language org-export-language-setup)
24369 (assoc "en" org-export-language-setup)))
24370 (switch-to-buffer-other-window buffer)
24371 (erase-buffer)
24372 (fundamental-mode)
24373 ;; create local variables for all options, to make sure all called
24374 ;; functions get the correct information
24375 (mapc (lambda (x)
24376 (set (make-local-variable (cdr x))
24377 (plist-get opt-plist (car x))))
24378 org-export-plist-vars)
24379 (org-set-local 'org-odd-levels-only odd)
24380 (setq umax (if arg (prefix-numeric-value arg)
24381 org-export-headline-levels))
24382 (setq umax-toc (if (integerp org-export-with-toc)
24383 (min org-export-with-toc umax)
24384 umax))
24386 ;; File header
24387 (if title (org-insert-centered title ?=))
24388 (insert "\n")
24389 (if (and (or author email)
24390 org-export-author-info)
24391 (insert (concat (nth 1 lang-words) ": " (or author "")
24392 (if email (concat " <" email ">") "")
24393 "\n")))
24395 (cond
24396 ((and date (string-match "%" date))
24397 (setq date (format-time-string date (current-time))))
24398 (date)
24399 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24401 (if (and date org-export-time-stamp-file)
24402 (insert (concat (nth 2 lang-words) ": " date"\n")))
24404 (insert "\n\n")
24406 (if org-export-with-toc
24407 (progn
24408 (push (concat (nth 3 lang-words) "\n") thetoc)
24409 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24410 (mapc '(lambda (line)
24411 (if (string-match org-todo-line-regexp
24412 line)
24413 ;; This is a headline
24414 (progn
24415 (setq have-headings t)
24416 (setq level (- (match-end 1) (match-beginning 1))
24417 level (org-tr-level level)
24418 txt (match-string 3 line)
24419 todo
24420 (or (and org-export-mark-todo-in-toc
24421 (match-beginning 2)
24422 (not (member (match-string 2 line)
24423 org-done-keywords)))
24424 ; TODO, not DONE
24425 (and org-export-mark-todo-in-toc
24426 (= level umax-toc)
24427 (org-search-todo-below
24428 line lines level))))
24429 (setq txt (org-html-expand-for-ascii txt))
24431 (while (string-match org-bracket-link-regexp txt)
24432 (setq txt
24433 (replace-match
24434 (match-string (if (match-end 2) 3 1) txt)
24435 t t txt)))
24437 (if (and (memq org-export-with-tags '(not-in-toc nil))
24438 (string-match
24439 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24440 txt))
24441 (setq txt (replace-match "" t t txt)))
24442 (if (string-match quote-re0 txt)
24443 (setq txt (replace-match "" t t txt)))
24445 (if org-export-with-section-numbers
24446 (setq txt (concat (org-section-number level)
24447 " " txt)))
24448 (if (<= level umax-toc)
24449 (progn
24450 (push
24451 (concat
24452 (make-string
24453 (* (max 0 (- level org-min-level)) 4) ?\ )
24454 (format (if todo "%s (*)\n" "%s\n") txt))
24455 thetoc)
24456 (setq org-last-level level))
24457 ))))
24458 lines)
24459 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24461 (org-init-section-numbers)
24462 (while (setq line (pop lines))
24463 ;; Remove the quoted HTML tags.
24464 (setq line (org-html-expand-for-ascii line))
24465 ;; Remove targets
24466 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24467 (setq line (replace-match "" t t line)))
24468 ;; Replace internal links
24469 (while (string-match org-bracket-link-regexp line)
24470 (setq line (replace-match
24471 (if (match-end 3) "[\\3]" "[\\1]")
24472 t nil line)))
24473 (when custom-times
24474 (setq line (org-translate-time line)))
24475 (cond
24476 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24477 ;; a Headline
24478 (setq first-heading-pos (or first-heading-pos (point)))
24479 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24480 txt (match-string 2 line))
24481 (org-ascii-level-start level txt umax lines))
24483 ((and org-export-with-tables
24484 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24485 (if (not table-open)
24486 ;; New table starts
24487 (setq table-open t table-buffer nil))
24488 ;; Accumulate lines
24489 (setq table-buffer (cons line table-buffer))
24490 (when (or (not lines)
24491 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24492 (car lines))))
24493 (setq table-open nil
24494 table-buffer (nreverse table-buffer))
24495 (insert (mapconcat
24496 (lambda (x)
24497 (org-fix-indentation x org-ascii-current-indentation))
24498 (org-format-table-ascii table-buffer)
24499 "\n") "\n")))
24501 (setq line (org-fix-indentation line org-ascii-current-indentation))
24502 (if (and org-export-with-fixed-width
24503 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24504 (setq line (replace-match "\\1" nil nil line)))
24505 (insert line "\n"))))
24507 (normal-mode)
24509 ;; insert the table of contents
24510 (when thetoc
24511 (goto-char (point-min))
24512 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24513 (progn
24514 (goto-char (match-beginning 0))
24515 (replace-match ""))
24516 (goto-char first-heading-pos))
24517 (mapc 'insert thetoc)
24518 (or (looking-at "[ \t]*\n[ \t]*\n")
24519 (insert "\n\n")))
24521 ;; Convert whitespace place holders
24522 (goto-char (point-min))
24523 (let (beg end)
24524 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24525 (setq end (next-single-property-change beg 'org-whitespace))
24526 (goto-char beg)
24527 (delete-region beg end)
24528 (insert (make-string (- end beg) ?\ ))))
24530 (save-buffer)
24531 ;; remove display and invisible chars
24532 (let (beg end)
24533 (goto-char (point-min))
24534 (while (setq beg (next-single-property-change (point) 'display))
24535 (setq end (next-single-property-change beg 'display))
24536 (delete-region beg end)
24537 (goto-char beg)
24538 (insert "=>"))
24539 (goto-char (point-min))
24540 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24541 (setq end (next-single-property-change beg 'org-cwidth))
24542 (delete-region beg end)
24543 (goto-char beg)))
24544 (goto-char (point-min))))
24546 (defun org-export-ascii-clean-string ()
24547 "Do extra work for ASCII export"
24548 (goto-char (point-min))
24549 (while (re-search-forward org-verbatim-re nil t)
24550 (goto-char (match-end 2))
24551 (backward-delete-char 1) (insert "'")
24552 (goto-char (match-beginning 2))
24553 (delete-char 1) (insert "`")
24554 (goto-char (match-end 2))))
24556 (defun org-search-todo-below (line lines level)
24557 "Search the subtree below LINE for any TODO entries."
24558 (let ((rest (cdr (memq line lines)))
24559 (re org-todo-line-regexp)
24560 line lv todo)
24561 (catch 'exit
24562 (while (setq line (pop rest))
24563 (if (string-match re line)
24564 (progn
24565 (setq lv (- (match-end 1) (match-beginning 1))
24566 todo (and (match-beginning 2)
24567 (not (member (match-string 2 line)
24568 org-done-keywords))))
24569 ; TODO, not DONE
24570 (if (<= lv level) (throw 'exit nil))
24571 (if todo (throw 'exit t))))))))
24573 (defun org-html-expand-for-ascii (line)
24574 "Handle quoted HTML for ASCII export."
24575 (if org-export-html-expand
24576 (while (string-match "@<[^<>\n]*>" line)
24577 ;; We just remove the tags for now.
24578 (setq line (replace-match "" nil nil line))))
24579 line)
24581 (defun org-insert-centered (s &optional underline)
24582 "Insert the string S centered and underline it with character UNDERLINE."
24583 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24584 (insert (make-string ind ?\ ) s "\n")
24585 (if underline
24586 (insert (make-string ind ?\ )
24587 (make-string (string-width s) underline)
24588 "\n"))))
24590 (defun org-ascii-level-start (level title umax &optional lines)
24591 "Insert a new level in ASCII export."
24592 (let (char (n (- level umax 1)) (ind 0))
24593 (if (> level umax)
24594 (progn
24595 (insert (make-string (* 2 n) ?\ )
24596 (char-to-string (nth (% n (length org-export-ascii-bullets))
24597 org-export-ascii-bullets))
24598 " " title "\n")
24599 ;; find the indentation of the next non-empty line
24600 (catch 'stop
24601 (while lines
24602 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24603 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24604 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24605 (pop lines)))
24606 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24607 (if (or (not (equal (char-before) ?\n))
24608 (not (equal (char-before (1- (point))) ?\n)))
24609 (insert "\n"))
24610 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24611 (unless org-export-with-tags
24612 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24613 (setq title (replace-match "" t t title))))
24614 (if org-export-with-section-numbers
24615 (setq title (concat (org-section-number level) " " title)))
24616 (insert title "\n" (make-string (string-width title) char) "\n")
24617 (setq org-ascii-current-indentation '(0 . 0)))))
24619 (defun org-export-visible (type arg)
24620 "Create a copy of the visible part of the current buffer, and export it.
24621 The copy is created in a temporary buffer and removed after use.
24622 TYPE is the final key (as a string) that also select the export command in
24623 the `C-c C-e' export dispatcher.
24624 As a special case, if the you type SPC at the prompt, the temporary
24625 org-mode file will not be removed but presented to you so that you can
24626 continue to use it. The prefix arg ARG is passed through to the exporting
24627 command."
24628 (interactive
24629 (list (progn
24630 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24631 (read-char-exclusive))
24632 current-prefix-arg))
24633 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24634 (error "Invalid export key"))
24635 (let* ((binding (cdr (assoc type
24636 '((?a . org-export-as-ascii)
24637 (?\C-a . org-export-as-ascii)
24638 (?b . org-export-as-html-and-open)
24639 (?\C-b . org-export-as-html-and-open)
24640 (?h . org-export-as-html)
24641 (?H . org-export-as-html-to-buffer)
24642 (?R . org-export-region-as-html)
24643 (?x . org-export-as-xoxo)))))
24644 (keepp (equal type ?\ ))
24645 (file buffer-file-name)
24646 (buffer (get-buffer-create "*Org Export Visible*"))
24647 s e)
24648 ;; Need to hack the drawers here.
24649 (save-excursion
24650 (goto-char (point-min))
24651 (while (re-search-forward org-drawer-regexp nil t)
24652 (goto-char (match-beginning 1))
24653 (or (org-invisible-p) (org-flag-drawer nil))))
24654 (with-current-buffer buffer (erase-buffer))
24655 (save-excursion
24656 (setq s (goto-char (point-min)))
24657 (while (not (= (point) (point-max)))
24658 (goto-char (org-find-invisible))
24659 (append-to-buffer buffer s (point))
24660 (setq s (goto-char (org-find-visible))))
24661 (org-cycle-hide-drawers 'all)
24662 (goto-char (point-min))
24663 (unless keepp
24664 ;; Copy all comment lines to the end, to make sure #+ settings are
24665 ;; still available for the second export step. Kind of a hack, but
24666 ;; does do the trick.
24667 (if (looking-at "#[^\r\n]*")
24668 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24669 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24670 (append-to-buffer buffer (1+ (match-beginning 0))
24671 (min (point-max) (1+ (match-end 0))))))
24672 (set-buffer buffer)
24673 (let ((buffer-file-name file)
24674 (org-inhibit-startup t))
24675 (org-mode)
24676 (show-all)
24677 (unless keepp (funcall binding arg))))
24678 (if (not keepp)
24679 (kill-buffer buffer)
24680 (switch-to-buffer-other-window buffer)
24681 (goto-char (point-min)))))
24683 (defun org-find-visible ()
24684 (let ((s (point)))
24685 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24686 (get-char-property s 'invisible)))
24688 (defun org-find-invisible ()
24689 (let ((s (point)))
24690 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24691 (not (get-char-property s 'invisible))))
24694 ;;; HTML export
24696 (defun org-get-current-options ()
24697 "Return a string with current options as keyword options.
24698 Does include HTML export options as well as TODO and CATEGORY stuff."
24699 (format
24700 "#+TITLE: %s
24701 #+AUTHOR: %s
24702 #+EMAIL: %s
24703 #+LANGUAGE: %s
24704 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24705 #+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
24706 #+CATEGORY: %s
24707 #+SEQ_TODO: %s
24708 #+TYP_TODO: %s
24709 #+PRIORITIES: %c %c %c
24710 #+DRAWERS: %s
24711 #+STARTUP: %s %s %s %s %s
24712 #+TAGS: %s
24713 #+ARCHIVE: %s
24714 #+LINK: %s
24716 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24717 org-export-headline-levels
24718 org-export-with-section-numbers
24719 org-export-with-toc
24720 org-export-preserve-breaks
24721 org-export-html-expand
24722 org-export-with-fixed-width
24723 org-export-with-tables
24724 org-export-with-sub-superscripts
24725 org-export-with-special-strings
24726 org-export-with-footnotes
24727 org-export-with-emphasize
24728 org-export-with-TeX-macros
24729 org-export-with-LaTeX-fragments
24730 org-export-skip-text-before-1st-heading
24731 org-export-with-drawers
24732 org-export-with-tags
24733 (file-name-nondirectory buffer-file-name)
24734 "TODO FEEDBACK VERIFY DONE"
24735 "Me Jason Marie DONE"
24736 org-highest-priority org-lowest-priority org-default-priority
24737 (mapconcat 'identity org-drawers " ")
24738 (cdr (assoc org-startup-folded
24739 '((nil . "showall") (t . "overview") (content . "content"))))
24740 (if org-odd-levels-only "odd" "oddeven")
24741 (if org-hide-leading-stars "hidestars" "showstars")
24742 (if org-startup-align-all-tables "align" "noalign")
24743 (cond ((eq org-log-done t) "logdone")
24744 ((equal org-log-done 'note) "lognotedone")
24745 ((not org-log-done) "nologdone"))
24746 (or (mapconcat (lambda (x)
24747 (cond
24748 ((equal '(:startgroup) x) "{")
24749 ((equal '(:endgroup) x) "}")
24750 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
24751 (t (car x))))
24752 (or org-tag-alist (org-get-buffer-tags)) " ") "")
24753 org-archive-location
24754 "org file:~/org/%s.org"
24757 (defun org-insert-export-options-template ()
24758 "Insert into the buffer a template with information for exporting."
24759 (interactive)
24760 (if (not (bolp)) (newline))
24761 (let ((s (org-get-current-options)))
24762 (and (string-match "#\\+CATEGORY" s)
24763 (setq s (substring s 0 (match-beginning 0))))
24764 (insert s)))
24766 (defun org-toggle-fixed-width-section (arg)
24767 "Toggle the fixed-width export.
24768 If there is no active region, the QUOTE keyword at the current headline is
24769 inserted or removed. When present, it causes the text between this headline
24770 and the next to be exported as fixed-width text, and unmodified.
24771 If there is an active region, this command adds or removes a colon as the
24772 first character of this line. If the first character of a line is a colon,
24773 this line is also exported in fixed-width font."
24774 (interactive "P")
24775 (let* ((cc 0)
24776 (regionp (org-region-active-p))
24777 (beg (if regionp (region-beginning) (point)))
24778 (end (if regionp (region-end)))
24779 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
24780 (case-fold-search nil)
24781 (re "[ \t]*\\(:\\)")
24782 off)
24783 (if regionp
24784 (save-excursion
24785 (goto-char beg)
24786 (setq cc (current-column))
24787 (beginning-of-line 1)
24788 (setq off (looking-at re))
24789 (while (> nlines 0)
24790 (setq nlines (1- nlines))
24791 (beginning-of-line 1)
24792 (cond
24793 (arg
24794 (move-to-column cc t)
24795 (insert ":\n")
24796 (forward-line -1))
24797 ((and off (looking-at re))
24798 (replace-match "" t t nil 1))
24799 ((not off) (move-to-column cc t) (insert ":")))
24800 (forward-line 1)))
24801 (save-excursion
24802 (org-back-to-heading)
24803 (if (looking-at (concat outline-regexp
24804 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
24805 (replace-match "" t t nil 1)
24806 (if (looking-at outline-regexp)
24807 (progn
24808 (goto-char (match-end 0))
24809 (insert org-quote-string " "))))))))
24811 (defun org-export-as-html-and-open (arg)
24812 "Export the outline as HTML and immediately open it with a browser.
24813 If there is an active region, export only the region.
24814 The prefix ARG specifies how many levels of the outline should become
24815 headlines. The default is 3. Lower levels will become bulleted lists."
24816 (interactive "P")
24817 (org-export-as-html arg 'hidden)
24818 (org-open-file buffer-file-name))
24820 (defun org-export-as-html-batch ()
24821 "Call `org-export-as-html', may be used in batch processing as
24822 emacs --batch
24823 --load=$HOME/lib/emacs/org.el
24824 --eval \"(setq org-export-headline-levels 2)\"
24825 --visit=MyFile --funcall org-export-as-html-batch"
24826 (org-export-as-html org-export-headline-levels 'hidden))
24828 (defun org-export-as-html-to-buffer (arg)
24829 "Call `org-exort-as-html` with output to a temporary buffer.
24830 No file is created. The prefix ARG is passed through to `org-export-as-html'."
24831 (interactive "P")
24832 (org-export-as-html arg nil nil "*Org HTML Export*")
24833 (switch-to-buffer-other-window "*Org HTML Export*"))
24835 (defun org-replace-region-by-html (beg end)
24836 "Assume the current region has org-mode syntax, and convert it to HTML.
24837 This can be used in any buffer. For example, you could write an
24838 itemized list in org-mode syntax in an HTML buffer and then use this
24839 command to convert it."
24840 (interactive "r")
24841 (let (reg html buf pop-up-frames)
24842 (save-window-excursion
24843 (if (org-mode-p)
24844 (setq html (org-export-region-as-html
24845 beg end t 'string))
24846 (setq reg (buffer-substring beg end)
24847 buf (get-buffer-create "*Org tmp*"))
24848 (with-current-buffer buf
24849 (erase-buffer)
24850 (insert reg)
24851 (org-mode)
24852 (setq html (org-export-region-as-html
24853 (point-min) (point-max) t 'string)))
24854 (kill-buffer buf)))
24855 (delete-region beg end)
24856 (insert html)))
24858 (defun org-export-region-as-html (beg end &optional body-only buffer)
24859 "Convert region from BEG to END in org-mode buffer to HTML.
24860 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
24861 contents, and only produce the region of converted text, useful for
24862 cut-and-paste operations.
24863 If BUFFER is a buffer or a string, use/create that buffer as a target
24864 of the converted HTML. If BUFFER is the symbol `string', return the
24865 produced HTML as a string and leave not buffer behind. For example,
24866 a Lisp program could call this function in the following way:
24868 (setq html (org-export-region-as-html beg end t 'string))
24870 When called interactively, the output buffer is selected, and shown
24871 in a window. A non-interactive call will only retunr the buffer."
24872 (interactive "r\nP")
24873 (when (interactive-p)
24874 (setq buffer "*Org HTML Export*"))
24875 (let ((transient-mark-mode t) (zmacs-regions t)
24876 rtn)
24877 (goto-char end)
24878 (set-mark (point)) ;; to activate the region
24879 (goto-char beg)
24880 (setq rtn (org-export-as-html
24881 nil nil nil
24882 buffer body-only))
24883 (if (fboundp 'deactivate-mark) (deactivate-mark))
24884 (if (and (interactive-p) (bufferp rtn))
24885 (switch-to-buffer-other-window rtn)
24886 rtn)))
24888 (defvar html-table-tag nil) ; dynamically scoped into this.
24889 (defun org-export-as-html (arg &optional hidden ext-plist
24890 to-buffer body-only)
24891 "Export the outline as a pretty HTML file.
24892 If there is an active region, export only the region. The prefix
24893 ARG specifies how many levels of the outline should become
24894 headlines. The default is 3. Lower levels will become bulleted
24895 lists. When HIDDEN is non-nil, don't display the HTML buffer.
24896 EXT-PLIST is a property list with external parameters overriding
24897 org-mode's default settings, but still inferior to file-local
24898 settings. When TO-BUFFER is non-nil, create a buffer with that
24899 name and export to that buffer. If TO-BUFFER is the symbol `string',
24900 don't leave any buffer behind but just return the resulting HTML as
24901 a string. When BODY-ONLY is set, don't produce the file header and footer,
24902 simply return the content of <body>...</body>, without even
24903 the body tags themselves."
24904 (interactive "P")
24906 ;; Make sure we have a file name when we need it.
24907 (when (and (not (or to-buffer body-only))
24908 (not buffer-file-name))
24909 (if (buffer-base-buffer)
24910 (org-set-local 'buffer-file-name
24911 (with-current-buffer (buffer-base-buffer)
24912 buffer-file-name))
24913 (error "Need a file name to be able to export.")))
24915 (message "Exporting...")
24916 (setq-default org-todo-line-regexp org-todo-line-regexp)
24917 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
24918 (setq-default org-done-keywords org-done-keywords)
24919 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
24920 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24921 ext-plist
24922 (org-infile-export-plist)))
24924 (style (plist-get opt-plist :style))
24925 (html-extension (plist-get opt-plist :html-extension))
24926 (link-validate (plist-get opt-plist :link-validation-function))
24927 valid thetoc have-headings first-heading-pos
24928 (odd org-odd-levels-only)
24929 (region-p (org-region-active-p))
24930 (subtree-p
24931 (when region-p
24932 (save-excursion
24933 (goto-char (region-beginning))
24934 (and (org-at-heading-p)
24935 (>= (org-end-of-subtree t t) (region-end))))))
24936 ;; The following two are dynamically scoped into other
24937 ;; routines below.
24938 (org-current-export-dir (org-export-directory :html opt-plist))
24939 (org-current-export-file buffer-file-name)
24940 (level 0) (line "") (origline "") txt todo
24941 (umax nil)
24942 (umax-toc nil)
24943 (filename (if to-buffer nil
24944 (expand-file-name
24945 (concat
24946 (file-name-sans-extension
24947 (or (and subtree-p
24948 (org-entry-get (region-beginning)
24949 "EXPORT_FILE_NAME" t))
24950 (file-name-nondirectory buffer-file-name)))
24951 "." html-extension)
24952 (file-name-as-directory
24953 (org-export-directory :html opt-plist)))))
24954 (current-dir (if buffer-file-name
24955 (file-name-directory buffer-file-name)
24956 default-directory))
24957 (buffer (if to-buffer
24958 (cond
24959 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
24960 (t (get-buffer-create to-buffer)))
24961 (find-file-noselect filename)))
24962 (org-levels-open (make-vector org-level-max nil))
24963 (date (plist-get opt-plist :date))
24964 (author (plist-get opt-plist :author))
24965 (title (or (and subtree-p (org-export-get-title-from-subtree))
24966 (plist-get opt-plist :title)
24967 (and (not
24968 (plist-get opt-plist :skip-before-1st-heading))
24969 (org-export-grab-title-from-buffer))
24970 (and buffer-file-name
24971 (file-name-sans-extension
24972 (file-name-nondirectory buffer-file-name)))
24973 "UNTITLED"))
24974 (html-table-tag (plist-get opt-plist :html-table-tag))
24975 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24976 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
24977 (inquote nil)
24978 (infixed nil)
24979 (in-local-list nil)
24980 (local-list-num nil)
24981 (local-list-indent nil)
24982 (llt org-plain-list-ordered-item-terminator)
24983 (email (plist-get opt-plist :email))
24984 (language (plist-get opt-plist :language))
24985 (lang-words nil)
24986 (target-alist nil) tg
24987 (head-count 0) cnt
24988 (start 0)
24989 (coding-system (and (boundp 'buffer-file-coding-system)
24990 buffer-file-coding-system))
24991 (coding-system-for-write (or org-export-html-coding-system
24992 coding-system))
24993 (save-buffer-coding-system (or org-export-html-coding-system
24994 coding-system))
24995 (charset (and coding-system-for-write
24996 (fboundp 'coding-system-get)
24997 (coding-system-get coding-system-for-write
24998 'mime-charset)))
24999 (region
25000 (buffer-substring
25001 (if region-p (region-beginning) (point-min))
25002 (if region-p (region-end) (point-max))))
25003 (lines
25004 (org-split-string
25005 (org-cleaned-string-for-export
25006 region
25007 :emph-multiline t
25008 :for-html t
25009 :skip-before-1st-heading
25010 (plist-get opt-plist :skip-before-1st-heading)
25011 :drawers (plist-get opt-plist :drawers)
25012 :archived-trees
25013 (plist-get opt-plist :archived-trees)
25014 :add-text
25015 (plist-get opt-plist :text)
25016 :LaTeX-fragments
25017 (plist-get opt-plist :LaTeX-fragments))
25018 "[\r\n]"))
25019 table-open type
25020 table-buffer table-orig-buffer
25021 ind start-is-num starter didclose
25022 rpl path desc descp desc1 desc2 link
25025 (let ((inhibit-read-only t))
25026 (org-unmodified
25027 (remove-text-properties (point-min) (point-max)
25028 '(:org-license-to-kill t))))
25030 (message "Exporting...")
25032 (setq org-min-level (org-get-min-level lines))
25033 (setq org-last-level org-min-level)
25034 (org-init-section-numbers)
25036 (cond
25037 ((and date (string-match "%" date))
25038 (setq date (format-time-string date (current-time))))
25039 (date)
25040 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25042 ;; Get the language-dependent settings
25043 (setq lang-words (or (assoc language org-export-language-setup)
25044 (assoc "en" org-export-language-setup)))
25046 ;; Switch to the output buffer
25047 (set-buffer buffer)
25048 (let ((inhibit-read-only t)) (erase-buffer))
25049 (fundamental-mode)
25051 (and (fboundp 'set-buffer-file-coding-system)
25052 (set-buffer-file-coding-system coding-system-for-write))
25054 (let ((case-fold-search nil)
25055 (org-odd-levels-only odd))
25056 ;; create local variables for all options, to make sure all called
25057 ;; functions get the correct information
25058 (mapc (lambda (x)
25059 (set (make-local-variable (cdr x))
25060 (plist-get opt-plist (car x))))
25061 org-export-plist-vars)
25062 (setq umax (if arg (prefix-numeric-value arg)
25063 org-export-headline-levels))
25064 (setq umax-toc (if (integerp org-export-with-toc)
25065 (min org-export-with-toc umax)
25066 umax))
25067 (unless body-only
25068 ;; File header
25069 (insert (format
25070 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25071 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25072 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25073 lang=\"%s\" xml:lang=\"%s\">
25074 <head>
25075 <title>%s</title>
25076 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25077 <meta name=\"generator\" content=\"Org-mode\"/>
25078 <meta name=\"generated\" content=\"%s\"/>
25079 <meta name=\"author\" content=\"%s\"/>
25081 </head><body>
25083 language language (org-html-expand title)
25084 (or charset "iso-8859-1") date author style))
25086 (insert (or (plist-get opt-plist :preamble) ""))
25088 (when (plist-get opt-plist :auto-preamble)
25089 (if title (insert (format org-export-html-title-format
25090 (org-html-expand title))))))
25092 (if (and org-export-with-toc (not body-only))
25093 (progn
25094 (push (format "<h%d>%s</h%d>\n"
25095 org-export-html-toplevel-hlevel
25096 (nth 3 lang-words)
25097 org-export-html-toplevel-hlevel)
25098 thetoc)
25099 (push "<ul>\n<li>" thetoc)
25100 (setq lines
25101 (mapcar '(lambda (line)
25102 (if (string-match org-todo-line-regexp line)
25103 ;; This is a headline
25104 (progn
25105 (setq have-headings t)
25106 (setq level (- (match-end 1) (match-beginning 1))
25107 level (org-tr-level level)
25108 txt (save-match-data
25109 (org-html-expand
25110 (org-export-cleanup-toc-line
25111 (match-string 3 line))))
25112 todo
25113 (or (and org-export-mark-todo-in-toc
25114 (match-beginning 2)
25115 (not (member (match-string 2 line)
25116 org-done-keywords)))
25117 ; TODO, not DONE
25118 (and org-export-mark-todo-in-toc
25119 (= level umax-toc)
25120 (org-search-todo-below
25121 line lines level))))
25122 (if (string-match
25123 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25124 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25125 (if (string-match quote-re0 txt)
25126 (setq txt (replace-match "" t t txt)))
25127 (if org-export-with-section-numbers
25128 (setq txt (concat (org-section-number level)
25129 " " txt)))
25130 (if (<= level (max umax umax-toc))
25131 (setq head-count (+ head-count 1)))
25132 (if (<= level umax-toc)
25133 (progn
25134 (if (> level org-last-level)
25135 (progn
25136 (setq cnt (- level org-last-level))
25137 (while (>= (setq cnt (1- cnt)) 0)
25138 (push "\n<ul>\n<li>" thetoc))
25139 (push "\n" thetoc)))
25140 (if (< level org-last-level)
25141 (progn
25142 (setq cnt (- org-last-level level))
25143 (while (>= (setq cnt (1- cnt)) 0)
25144 (push "</li>\n</ul>" thetoc))
25145 (push "\n" thetoc)))
25146 ;; Check for targets
25147 (while (string-match org-target-regexp line)
25148 (setq tg (match-string 1 line)
25149 line (replace-match
25150 (concat "@<span class=\"target\">" tg "@</span> ")
25151 t t line))
25152 (push (cons (org-solidify-link-text tg)
25153 (format "sec-%d" head-count))
25154 target-alist))
25155 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25156 (setq txt (replace-match "" t t txt)))
25157 (push
25158 (format
25159 (if todo
25160 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25161 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25162 head-count txt) thetoc)
25164 (setq org-last-level level))
25166 line)
25167 lines))
25168 (while (> org-last-level (1- org-min-level))
25169 (setq org-last-level (1- org-last-level))
25170 (push "</li>\n</ul>\n" thetoc))
25171 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25173 (setq head-count 0)
25174 (org-init-section-numbers)
25176 (while (setq line (pop lines) origline line)
25177 (catch 'nextline
25179 ;; end of quote section?
25180 (when (and inquote (string-match "^\\*+ " line))
25181 (insert "</pre>\n")
25182 (setq inquote nil))
25183 ;; inside a quote section?
25184 (when inquote
25185 (insert (org-html-protect line) "\n")
25186 (throw 'nextline nil))
25188 ;; verbatim lines
25189 (when (and org-export-with-fixed-width
25190 (string-match "^[ \t]*:\\(.*\\)" line))
25191 (when (not infixed)
25192 (setq infixed t)
25193 (insert "<pre>\n"))
25194 (insert (org-html-protect (match-string 1 line)) "\n")
25195 (when (and lines
25196 (not (string-match "^[ \t]*\\(:.*\\)"
25197 (car lines))))
25198 (setq infixed nil)
25199 (insert "</pre>\n"))
25200 (throw 'nextline nil))
25202 ;; Protected HTML
25203 (when (get-text-property 0 'org-protected line)
25204 (let (par)
25205 (when (re-search-backward
25206 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25207 (setq par (match-string 1))
25208 (replace-match "\\2\n"))
25209 (insert line "\n")
25210 (while (and lines
25211 (or (= (length (car lines)) 0)
25212 (get-text-property 0 'org-protected (car lines))))
25213 (insert (pop lines) "\n"))
25214 (and par (insert "<p>\n")))
25215 (throw 'nextline nil))
25217 ;; Horizontal line
25218 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25219 (insert "\n<hr/>\n")
25220 (throw 'nextline nil))
25222 ;; make targets to anchors
25223 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25224 (cond
25225 ((match-end 2)
25226 (setq line (replace-match
25227 (concat "@<a name=\""
25228 (org-solidify-link-text (match-string 1 line))
25229 "\">\\nbsp@</a>")
25230 t t line)))
25231 ((and org-export-with-toc (equal (string-to-char line) ?*))
25232 (setq line (replace-match
25233 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25234 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25235 t t line)))
25237 (setq line (replace-match
25238 (concat "@<a name=\""
25239 (org-solidify-link-text (match-string 1 line))
25240 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25241 t t line)))))
25243 (setq line (org-html-handle-time-stamps line))
25245 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25246 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25247 ;; Also handle sub_superscripts and checkboxes
25248 (or (string-match org-table-hline-regexp line)
25249 (setq line (org-html-expand line)))
25251 ;; Format the links
25252 (setq start 0)
25253 (while (string-match org-bracket-link-analytic-regexp line start)
25254 (setq start (match-beginning 0))
25255 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25256 (setq path (match-string 3 line))
25257 (setq desc1 (if (match-end 5) (match-string 5 line))
25258 desc2 (if (match-end 2) (concat type ":" path) path)
25259 descp (and desc1 (not (equal desc1 desc2)))
25260 desc (or desc1 desc2))
25261 ;; Make an image out of the description if that is so wanted
25262 (when (and descp (org-file-image-p desc))
25263 (save-match-data
25264 (if (string-match "^file:" desc)
25265 (setq desc (substring desc (match-end 0)))))
25266 (setq desc (concat "<img src=\"" desc "\"/>")))
25267 ;; FIXME: do we need to unescape here somewhere?
25268 (cond
25269 ((equal type "internal")
25270 (setq rpl
25271 (concat
25272 "<a href=\"#"
25273 (org-solidify-link-text
25274 (save-match-data (org-link-unescape path)) target-alist)
25275 "\">" desc "</a>")))
25276 ((member type '("http" "https"))
25277 ;; standard URL, just check if we need to inline an image
25278 (if (and (or (eq t org-export-html-inline-images)
25279 (and org-export-html-inline-images (not descp)))
25280 (org-file-image-p path))
25281 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25282 (setq link (concat type ":" path))
25283 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25284 ((member type '("ftp" "mailto" "news"))
25285 ;; standard URL
25286 (setq link (concat type ":" path))
25287 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25288 ((string= type "file")
25289 ;; FILE link
25290 (let* ((filename path)
25291 (abs-p (file-name-absolute-p filename))
25292 thefile file-is-image-p search)
25293 (save-match-data
25294 (if (string-match "::\\(.*\\)" filename)
25295 (setq search (match-string 1 filename)
25296 filename (replace-match "" t nil filename)))
25297 (setq valid
25298 (if (functionp link-validate)
25299 (funcall link-validate filename current-dir)
25301 (setq file-is-image-p (org-file-image-p filename))
25302 (setq thefile (if abs-p (expand-file-name filename) filename))
25303 (when (and org-export-html-link-org-files-as-html
25304 (string-match "\\.org$" thefile))
25305 (setq thefile (concat (substring thefile 0
25306 (match-beginning 0))
25307 "." html-extension))
25308 (if (and search
25309 ;; make sure this is can be used as target search
25310 (not (string-match "^[0-9]*$" search))
25311 (not (string-match "^\\*" search))
25312 (not (string-match "^/.*/$" search)))
25313 (setq thefile (concat thefile "#"
25314 (org-solidify-link-text
25315 (org-link-unescape search)))))
25316 (when (string-match "^file:" desc)
25317 (setq desc (replace-match "" t t desc))
25318 (if (string-match "\\.org$" desc)
25319 (setq desc (replace-match "" t t desc))))))
25320 (setq rpl (if (and file-is-image-p
25321 (or (eq t org-export-html-inline-images)
25322 (and org-export-html-inline-images
25323 (not descp))))
25324 (concat "<img src=\"" thefile "\"/>")
25325 (concat "<a href=\"" thefile "\">" desc "</a>")))
25326 (if (not valid) (setq rpl desc))))
25327 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25328 (setq rpl (concat "<i>&lt;" type ":"
25329 (save-match-data (org-link-unescape path))
25330 "&gt;</i>"))))
25331 (setq line (replace-match rpl t t line)
25332 start (+ start (length rpl))))
25334 ;; TODO items
25335 (if (and (string-match org-todo-line-regexp line)
25336 (match-beginning 2))
25338 (setq line
25339 (concat (substring line 0 (match-beginning 2))
25340 "<span class=\""
25341 (if (member (match-string 2 line)
25342 org-done-keywords)
25343 "done" "todo")
25344 "\">" (match-string 2 line)
25345 "</span>" (substring line (match-end 2)))))
25347 ;; Does this contain a reference to a footnote?
25348 (when org-export-with-footnotes
25349 (setq start 0)
25350 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25351 (if (get-text-property (match-beginning 2) 'org-protected line)
25352 (setq start (match-end 2))
25353 (let ((n (match-string 2 line)))
25354 (setq line
25355 (replace-match
25356 (format
25357 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25358 (match-string 1 line) n n n)
25359 t t line))))))
25361 (cond
25362 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25363 ;; This is a headline
25364 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25365 txt (match-string 2 line))
25366 (if (string-match quote-re0 txt)
25367 (setq txt (replace-match "" t t txt)))
25368 (if (<= level (max umax umax-toc))
25369 (setq head-count (+ head-count 1)))
25370 (when in-local-list
25371 ;; Close any local lists before inserting a new header line
25372 (while local-list-num
25373 (org-close-li)
25374 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25375 (pop local-list-num))
25376 (setq local-list-indent nil
25377 in-local-list nil))
25378 (setq first-heading-pos (or first-heading-pos (point)))
25379 (org-html-level-start level txt umax
25380 (and org-export-with-toc (<= level umax))
25381 head-count)
25382 ;; QUOTES
25383 (when (string-match quote-re line)
25384 (insert "<pre>")
25385 (setq inquote t)))
25387 ((and org-export-with-tables
25388 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25389 (if (not table-open)
25390 ;; New table starts
25391 (setq table-open t table-buffer nil table-orig-buffer nil))
25392 ;; Accumulate lines
25393 (setq table-buffer (cons line table-buffer)
25394 table-orig-buffer (cons origline table-orig-buffer))
25395 (when (or (not lines)
25396 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25397 (car lines))))
25398 (setq table-open nil
25399 table-buffer (nreverse table-buffer)
25400 table-orig-buffer (nreverse table-orig-buffer))
25401 (org-close-par-maybe)
25402 (insert (org-format-table-html table-buffer table-orig-buffer))))
25404 ;; Normal lines
25405 (when (string-match
25406 (cond
25407 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25408 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25409 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25410 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25411 line)
25412 (setq ind (org-get-string-indentation line)
25413 start-is-num (match-beginning 4)
25414 starter (if (match-beginning 2)
25415 (substring (match-string 2 line) 0 -1))
25416 line (substring line (match-beginning 5)))
25417 (unless (string-match "[^ \t]" line)
25418 ;; empty line. Pretend indentation is large.
25419 (setq ind (if org-empty-line-terminates-plain-lists
25421 (1+ (or (car local-list-indent) 1)))))
25422 (setq didclose nil)
25423 (while (and in-local-list
25424 (or (and (= ind (car local-list-indent))
25425 (not starter))
25426 (< ind (car local-list-indent))))
25427 (setq didclose t)
25428 (org-close-li)
25429 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25430 (pop local-list-num) (pop local-list-indent)
25431 (setq in-local-list local-list-indent))
25432 (cond
25433 ((and starter
25434 (or (not in-local-list)
25435 (> ind (car local-list-indent))))
25436 ;; Start new (level of) list
25437 (org-close-par-maybe)
25438 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25439 (push start-is-num local-list-num)
25440 (push ind local-list-indent)
25441 (setq in-local-list t))
25442 (starter
25443 ;; continue current list
25444 (org-close-li)
25445 (insert "<li>\n"))
25446 (didclose
25447 ;; we did close a list, normal text follows: need <p>
25448 (org-open-par)))
25449 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25450 (setq line
25451 (replace-match
25452 (if (equal (match-string 1 line) "X")
25453 "<b>[X]</b>"
25454 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25455 t t line))))
25457 ;; Empty lines start a new paragraph. If hand-formatted lists
25458 ;; are not fully interpreted, lines starting with "-", "+", "*"
25459 ;; also start a new paragraph.
25460 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25462 ;; Is this the start of a footnote?
25463 (when org-export-with-footnotes
25464 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25465 (org-close-par-maybe)
25466 (let ((n (match-string 1 line)))
25467 (setq line (replace-match
25468 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25470 ;; Check if the line break needs to be conserved
25471 (cond
25472 ((string-match "\\\\\\\\[ \t]*$" line)
25473 (setq line (replace-match "<br/>" t t line)))
25474 (org-export-preserve-breaks
25475 (setq line (concat line "<br/>"))))
25477 (insert line "\n")))))
25479 ;; Properly close all local lists and other lists
25480 (when inquote (insert "</pre>\n"))
25481 (when in-local-list
25482 ;; Close any local lists before inserting a new header line
25483 (while local-list-num
25484 (org-close-li)
25485 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25486 (pop local-list-num))
25487 (setq local-list-indent nil
25488 in-local-list nil))
25489 (org-html-level-start 1 nil umax
25490 (and org-export-with-toc (<= level umax))
25491 head-count)
25493 (unless body-only
25494 (when (plist-get opt-plist :auto-postamble)
25495 (insert "<div id=\"postamble\">")
25496 (when (and org-export-author-info author)
25497 (insert "<p class=\"author\"> "
25498 (nth 1 lang-words) ": " author "\n")
25499 (when email
25500 (if (listp (split-string email ",+ *"))
25501 (mapc (lambda(e)
25502 (insert "<a href=\"mailto:" e "\">&lt;"
25503 e "&gt;</a>\n"))
25504 (split-string email ",+ *"))
25505 (insert "<a href=\"mailto:" email "\">&lt;"
25506 email "&gt;</a>\n")))
25507 (insert "</p>\n"))
25508 (when (and date org-export-time-stamp-file)
25509 (insert "<p class=\"date\"> "
25510 (nth 2 lang-words) ": "
25511 date "</p>\n"))
25512 (insert "</div>"))
25514 (if org-export-html-with-timestamp
25515 (insert org-export-html-html-helper-timestamp))
25516 (insert (or (plist-get opt-plist :postamble) ""))
25517 (insert "</body>\n</html>\n"))
25519 (normal-mode)
25520 (if (eq major-mode default-major-mode) (html-mode))
25522 ;; insert the table of contents
25523 (goto-char (point-min))
25524 (when thetoc
25525 (if (or (re-search-forward
25526 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25527 (re-search-forward
25528 "\\[TABLE-OF-CONTENTS\\]" nil t))
25529 (progn
25530 (goto-char (match-beginning 0))
25531 (replace-match ""))
25532 (goto-char first-heading-pos)
25533 (when (looking-at "\\s-*</p>")
25534 (goto-char (match-end 0))
25535 (insert "\n")))
25536 (insert "<div id=\"table-of-contents\">\n")
25537 (mapc 'insert thetoc)
25538 (insert "</div>\n"))
25539 ;; remove empty paragraphs and lists
25540 (goto-char (point-min))
25541 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25542 (replace-match ""))
25543 (goto-char (point-min))
25544 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25545 (replace-match ""))
25546 (goto-char (point-min))
25547 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25548 (replace-match ""))
25549 ;; Convert whitespace place holders
25550 (goto-char (point-min))
25551 (let (beg end n)
25552 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25553 (setq n (get-text-property beg 'org-whitespace)
25554 end (next-single-property-change beg 'org-whitespace))
25555 (goto-char beg)
25556 (delete-region beg end)
25557 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25558 (make-string n ?x)))))
25560 (or to-buffer (save-buffer))
25561 (goto-char (point-min))
25562 (message "Exporting... done")
25563 (if (eq to-buffer 'string)
25564 (prog1 (buffer-substring (point-min) (point-max))
25565 (kill-buffer (current-buffer)))
25566 (current-buffer)))))
25568 (defvar org-table-colgroup-info nil)
25569 (defun org-format-table-ascii (lines)
25570 "Format a table for ascii export."
25571 (if (stringp lines)
25572 (setq lines (org-split-string lines "\n")))
25573 (if (not (string-match "^[ \t]*|" (car lines)))
25574 ;; Table made by table.el - test for spanning
25575 lines
25577 ;; A normal org table
25578 ;; Get rid of hlines at beginning and end
25579 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25580 (setq lines (nreverse lines))
25581 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25582 (setq lines (nreverse lines))
25583 (when org-export-table-remove-special-lines
25584 ;; Check if the table has a marking column. If yes remove the
25585 ;; column and the special lines
25586 (setq lines (org-table-clean-before-export lines)))
25587 ;; Get rid of the vertical lines except for grouping
25588 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25589 rtn line vl1 start)
25590 (while (setq line (pop lines))
25591 (if (string-match org-table-hline-regexp line)
25592 (and (string-match "|\\(.*\\)|" line)
25593 (setq line (replace-match " \\1" t nil line)))
25594 (setq start 0 vl1 vl)
25595 (while (string-match "|" line start)
25596 (setq start (match-end 0))
25597 (or (pop vl1) (setq line (replace-match " " t t line)))))
25598 (push line rtn))
25599 (nreverse rtn))))
25601 (defun org-colgroup-info-to-vline-list (info)
25602 (let (vl new last)
25603 (while info
25604 (setq last new new (pop info))
25605 (if (or (memq last '(:end :startend))
25606 (memq new '(:start :startend)))
25607 (push t vl)
25608 (push nil vl)))
25609 (setq vl (nreverse vl))
25610 (and vl (setcar vl nil))
25611 vl))
25613 (defun org-format-table-html (lines olines)
25614 "Find out which HTML converter to use and return the HTML code."
25615 (if (stringp lines)
25616 (setq lines (org-split-string lines "\n")))
25617 (if (string-match "^[ \t]*|" (car lines))
25618 ;; A normal org table
25619 (org-format-org-table-html lines)
25620 ;; Table made by table.el - test for spanning
25621 (let* ((hlines (delq nil (mapcar
25622 (lambda (x)
25623 (if (string-match "^[ \t]*\\+-" x) x
25624 nil))
25625 lines)))
25626 (first (car hlines))
25627 (ll (and (string-match "\\S-+" first)
25628 (match-string 0 first)))
25629 (re (concat "^[ \t]*" (regexp-quote ll)))
25630 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25631 hlines))))
25632 (if (and (not spanning)
25633 (not org-export-prefer-native-exporter-for-tables))
25634 ;; We can use my own converter with HTML conversions
25635 (org-format-table-table-html lines)
25636 ;; Need to use the code generator in table.el, with the original text.
25637 (org-format-table-table-html-using-table-generate-source olines)))))
25639 (defun org-format-org-table-html (lines &optional splice)
25640 "Format a table into HTML."
25641 ;; Get rid of hlines at beginning and end
25642 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25643 (setq lines (nreverse lines))
25644 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25645 (setq lines (nreverse lines))
25646 (when org-export-table-remove-special-lines
25647 ;; Check if the table has a marking column. If yes remove the
25648 ;; column and the special lines
25649 (setq lines (org-table-clean-before-export lines)))
25651 (let ((head (and org-export-highlight-first-table-line
25652 (delq nil (mapcar
25653 (lambda (x) (string-match "^[ \t]*|-" x))
25654 (cdr lines)))))
25655 (nlines 0) fnum i
25656 tbopen line fields html gr colgropen)
25657 (if splice (setq head nil))
25658 (unless splice (push (if head "<thead>" "<tbody>") html))
25659 (setq tbopen t)
25660 (while (setq line (pop lines))
25661 (catch 'next-line
25662 (if (string-match "^[ \t]*|-" line)
25663 (progn
25664 (unless splice
25665 (push (if head "</thead>" "</tbody>") html)
25666 (if lines (push "<tbody>" html) (setq tbopen nil)))
25667 (setq head nil) ;; head ends here, first time around
25668 ;; ignore this line
25669 (throw 'next-line t)))
25670 ;; Break the line into fields
25671 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25672 (unless fnum (setq fnum (make-vector (length fields) 0)))
25673 (setq nlines (1+ nlines) i -1)
25674 (push (concat "<tr>"
25675 (mapconcat
25676 (lambda (x)
25677 (setq i (1+ i))
25678 (if (and (< i nlines)
25679 (string-match org-table-number-regexp x))
25680 (incf (aref fnum i)))
25681 (if head
25682 (concat (car org-export-table-header-tags) x
25683 (cdr org-export-table-header-tags))
25684 (concat (car org-export-table-data-tags) x
25685 (cdr org-export-table-data-tags))))
25686 fields "")
25687 "</tr>")
25688 html)))
25689 (unless splice (if tbopen (push "</tbody>" html)))
25690 (unless splice (push "</table>\n" html))
25691 (setq html (nreverse html))
25692 (unless splice
25693 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25694 (push (mapconcat
25695 (lambda (x)
25696 (setq gr (pop org-table-colgroup-info))
25697 (format "%s<col align=\"%s\"></col>%s"
25698 (if (memq gr '(:start :startend))
25699 (prog1
25700 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25701 (setq colgropen t))
25703 (if (> (/ (float x) nlines) org-table-number-fraction)
25704 "right" "left")
25705 (if (memq gr '(:end :startend))
25706 (progn (setq colgropen nil) "</colgroup>")
25707 "")))
25708 fnum "")
25709 html)
25710 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
25711 (push html-table-tag html))
25712 (concat (mapconcat 'identity html "\n") "\n")))
25714 (defun org-table-clean-before-export (lines)
25715 "Check if the table has a marking column.
25716 If yes remove the column and the special lines."
25717 (setq org-table-colgroup-info nil)
25718 (if (memq nil
25719 (mapcar
25720 (lambda (x) (or (string-match "^[ \t]*|-" x)
25721 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
25722 lines))
25723 (progn
25724 (setq org-table-clean-did-remove-column nil)
25725 (delq nil
25726 (mapcar
25727 (lambda (x)
25728 (cond
25729 ((string-match "^[ \t]*| */ *|" x)
25730 (setq org-table-colgroup-info
25731 (mapcar (lambda (x)
25732 (cond ((member x '("<" "&lt;")) :start)
25733 ((member x '(">" "&gt;")) :end)
25734 ((member x '("<>" "&lt;&gt;")) :startend)
25735 (t nil)))
25736 (org-split-string x "[ \t]*|[ \t]*")))
25737 nil)
25738 (t x)))
25739 lines)))
25740 (setq org-table-clean-did-remove-column t)
25741 (delq nil
25742 (mapcar
25743 (lambda (x)
25744 (cond
25745 ((string-match "^[ \t]*| */ *|" x)
25746 (setq org-table-colgroup-info
25747 (mapcar (lambda (x)
25748 (cond ((member x '("<" "&lt;")) :start)
25749 ((member x '(">" "&gt;")) :end)
25750 ((member x '("<>" "&lt;&gt;")) :startend)
25751 (t nil)))
25752 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
25753 nil)
25754 ((string-match "^[ \t]*| *[!_^/] *|" x)
25755 nil) ; ignore this line
25756 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
25757 (string-match "^\\([ \t]*\\)|[^|]*|" x))
25758 ;; remove the first column
25759 (replace-match "\\1|" t nil x))))
25760 lines))))
25762 (defun org-format-table-table-html (lines)
25763 "Format a table generated by table.el into HTML.
25764 This conversion does *not* use `table-generate-source' from table.el.
25765 This has the advantage that Org-mode's HTML conversions can be used.
25766 But it has the disadvantage, that no cell- or row-spanning is allowed."
25767 (let (line field-buffer
25768 (head org-export-highlight-first-table-line)
25769 fields html empty)
25770 (setq html (concat html-table-tag "\n"))
25771 (while (setq line (pop lines))
25772 (setq empty "&nbsp;")
25773 (catch 'next-line
25774 (if (string-match "^[ \t]*\\+-" line)
25775 (progn
25776 (if field-buffer
25777 (progn
25778 (setq
25779 html
25780 (concat
25781 html
25782 "<tr>"
25783 (mapconcat
25784 (lambda (x)
25785 (if (equal x "") (setq x empty))
25786 (if head
25787 (concat (car org-export-table-header-tags) x
25788 (cdr org-export-table-header-tags))
25789 (concat (car org-export-table-data-tags) x
25790 (cdr org-export-table-data-tags))))
25791 field-buffer "\n")
25792 "</tr>\n"))
25793 (setq head nil)
25794 (setq field-buffer nil)))
25795 ;; Ignore this line
25796 (throw 'next-line t)))
25797 ;; Break the line into fields and store the fields
25798 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25799 (if field-buffer
25800 (setq field-buffer (mapcar
25801 (lambda (x)
25802 (concat x "<br/>" (pop fields)))
25803 field-buffer))
25804 (setq field-buffer fields))))
25805 (setq html (concat html "</table>\n"))
25806 html))
25808 (defun org-format-table-table-html-using-table-generate-source (lines)
25809 "Format a table into html, using `table-generate-source' from table.el.
25810 This has the advantage that cell- or row-spanning is allowed.
25811 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
25812 (require 'table)
25813 (with-current-buffer (get-buffer-create " org-tmp1 ")
25814 (erase-buffer)
25815 (insert (mapconcat 'identity lines "\n"))
25816 (goto-char (point-min))
25817 (if (not (re-search-forward "|[^+]" nil t))
25818 (error "Error processing table"))
25819 (table-recognize-table)
25820 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
25821 (table-generate-source 'html " org-tmp2 ")
25822 (set-buffer " org-tmp2 ")
25823 (buffer-substring (point-min) (point-max))))
25825 (defun org-html-handle-time-stamps (s)
25826 "Format time stamps in string S, or remove them."
25827 (catch 'exit
25828 (let (r b)
25829 (while (string-match org-maybe-keyword-time-regexp s)
25830 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
25831 ;; never export CLOCK
25832 (throw 'exit ""))
25833 (or b (setq b (substring s 0 (match-beginning 0))))
25834 (if (not org-export-with-timestamps)
25835 (setq r (concat r (substring s 0 (match-beginning 0)))
25836 s (substring s (match-end 0)))
25837 (setq r (concat
25838 r (substring s 0 (match-beginning 0))
25839 (if (match-end 1)
25840 (format "@<span class=\"timestamp-kwd\">%s @</span>"
25841 (match-string 1 s)))
25842 (format " @<span class=\"timestamp\">%s@</span>"
25843 (substring
25844 (org-translate-time (match-string 3 s)) 1 -1)))
25845 s (substring s (match-end 0)))))
25846 ;; Line break if line started and ended with time stamp stuff
25847 (if (not r)
25849 (setq r (concat r s))
25850 (unless (string-match "\\S-" (concat b s))
25851 (setq r (concat r "@<br/>")))
25852 r))))
25854 (defun org-html-protect (s)
25855 ;; convert & to &amp;, < to &lt; and > to &gt;
25856 (let ((start 0))
25857 (while (string-match "&" s start)
25858 (setq s (replace-match "&amp;" t t s)
25859 start (1+ (match-beginning 0))))
25860 (while (string-match "<" s)
25861 (setq s (replace-match "&lt;" t t s)))
25862 (while (string-match ">" s)
25863 (setq s (replace-match "&gt;" t t s))))
25866 (defun org-export-cleanup-toc-line (s)
25867 "Remove tags and time staps from lines going into the toc."
25868 (when (memq org-export-with-tags '(not-in-toc nil))
25869 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
25870 (setq s (replace-match "" t t s))))
25871 (when org-export-remove-timestamps-from-toc
25872 (while (string-match org-maybe-keyword-time-regexp s)
25873 (setq s (replace-match "" t t s))))
25874 (while (string-match org-bracket-link-regexp s)
25875 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
25876 t t s)))
25879 (defun org-html-expand (string)
25880 "Prepare STRING for HTML export. Applies all active conversions.
25881 If there are links in the string, don't modify these."
25882 (let* ((re (concat org-bracket-link-regexp "\\|"
25883 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
25884 m s l res)
25885 (while (setq m (string-match re string))
25886 (setq s (substring string 0 m)
25887 l (match-string 0 string)
25888 string (substring string (match-end 0)))
25889 (push (org-html-do-expand s) res)
25890 (push l res))
25891 (push (org-html-do-expand string) res)
25892 (apply 'concat (nreverse res))))
25894 (defun org-html-do-expand (s)
25895 "Apply all active conversions to translate special ASCII to HTML."
25896 (setq s (org-html-protect s))
25897 (if org-export-html-expand
25898 (let ((start 0))
25899 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
25900 (setq s (replace-match "<\\1>" t nil s)))))
25901 (if org-export-with-emphasize
25902 (setq s (org-export-html-convert-emphasize s)))
25903 (if org-export-with-special-strings
25904 (setq s (org-export-html-convert-special-strings s)))
25905 (if org-export-with-sub-superscripts
25906 (setq s (org-export-html-convert-sub-super s)))
25907 (if org-export-with-TeX-macros
25908 (let ((start 0) wd ass)
25909 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
25910 (if (get-text-property (match-beginning 0) 'org-protected s)
25911 (setq start (match-end 0))
25912 (setq wd (match-string 1 s))
25913 (if (setq ass (assoc wd org-html-entities))
25914 (setq s (replace-match (or (cdr ass)
25915 (concat "&" (car ass) ";"))
25916 t t s))
25917 (setq start (+ start (length wd))))))))
25920 (defun org-create-multibrace-regexp (left right n)
25921 "Create a regular expression which will match a balanced sexp.
25922 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
25923 as single character strings.
25924 The regexp returned will match the entire expression including the
25925 delimiters. It will also define a single group which contains the
25926 match except for the outermost delimiters. The maximum depth of
25927 stacked delimiters is N. Escaping delimiters is not possible."
25928 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
25929 (or "\\|")
25930 (re nothing)
25931 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
25932 (while (> n 1)
25933 (setq n (1- n)
25934 re (concat re or next)
25935 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
25936 (concat left "\\(" re "\\)" right)))
25938 (defvar org-match-substring-regexp
25939 (concat
25940 "\\([^\\]\\)\\([_^]\\)\\("
25941 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25942 "\\|"
25943 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
25944 "\\|"
25945 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
25946 "The regular expression matching a sub- or superscript.")
25948 (defvar org-match-substring-with-braces-regexp
25949 (concat
25950 "\\([^\\]\\)\\([_^]\\)\\("
25951 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
25952 "\\)")
25953 "The regular expression matching a sub- or superscript, forcing braces.")
25955 (defconst org-export-html-special-string-regexps
25956 '(("\\\\-" . "&shy;")
25957 ("---\\([^-]\\)" . "&mdash;\\1")
25958 ("--\\([^-]\\)" . "&ndash;\\1")
25959 ("\\.\\.\\." . "&hellip;"))
25960 "Regular expressions for special string conversion.")
25962 (defun org-export-html-convert-special-strings (string)
25963 "Convert special characters in STRING to HTML."
25964 (let ((all org-export-html-special-string-regexps)
25965 e a re rpl start)
25966 (while (setq a (pop all))
25967 (setq re (car a) rpl (cdr a) start 0)
25968 (while (string-match re string start)
25969 (if (get-text-property (match-beginning 0) 'org-protected string)
25970 (setq start (match-end 0))
25971 (setq string (replace-match rpl t nil string)))))
25972 string))
25974 (defun org-export-html-convert-sub-super (string)
25975 "Convert sub- and superscripts in STRING to HTML."
25976 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
25977 (while (string-match org-match-substring-regexp string s)
25978 (cond
25979 ((and requireb (match-end 8)) (setq s (match-end 2)))
25980 ((get-text-property (match-beginning 2) 'org-protected string)
25981 (setq s (match-end 2)))
25983 (setq s (match-end 1)
25984 key (if (string= (match-string 2 string) "_") "sub" "sup")
25985 c (or (match-string 8 string)
25986 (match-string 6 string)
25987 (match-string 5 string))
25988 string (replace-match
25989 (concat (match-string 1 string)
25990 "<" key ">" c "</" key ">")
25991 t t string)))))
25992 (while (string-match "\\\\\\([_^]\\)" string)
25993 (setq string (replace-match (match-string 1 string) t t string)))
25994 string))
25996 (defun org-export-html-convert-emphasize (string)
25997 "Apply emphasis."
25998 (let ((s 0) rpl)
25999 (while (string-match org-emph-re string s)
26000 (if (not (equal
26001 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26002 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26003 (setq s (match-beginning 0)
26005 (concat
26006 (match-string 1 string)
26007 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26008 (match-string 4 string)
26009 (nth 3 (assoc (match-string 3 string)
26010 org-emphasis-alist))
26011 (match-string 5 string))
26012 string (replace-match rpl t t string)
26013 s (+ s (- (length rpl) 2)))
26014 (setq s (1+ s))))
26015 string))
26017 (defvar org-par-open nil)
26018 (defun org-open-par ()
26019 "Insert <p>, but first close previous paragraph if any."
26020 (org-close-par-maybe)
26021 (insert "\n<p>")
26022 (setq org-par-open t))
26023 (defun org-close-par-maybe ()
26024 "Close paragraph if there is one open."
26025 (when org-par-open
26026 (insert "</p>")
26027 (setq org-par-open nil)))
26028 (defun org-close-li ()
26029 "Close <li> if necessary."
26030 (org-close-par-maybe)
26031 (insert "</li>\n"))
26033 (defvar body-only) ; dynamically scoped into this.
26034 (defun org-html-level-start (level title umax with-toc head-count)
26035 "Insert a new level in HTML export.
26036 When TITLE is nil, just close all open levels."
26037 (org-close-par-maybe)
26038 (let ((l org-level-max))
26039 (while (>= l level)
26040 (if (aref org-levels-open (1- l))
26041 (progn
26042 (org-html-level-close l umax)
26043 (aset org-levels-open (1- l) nil)))
26044 (setq l (1- l)))
26045 (when title
26046 ;; If title is nil, this means this function is called to close
26047 ;; all levels, so the rest is done only if title is given
26048 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26049 (setq title (replace-match
26050 (if org-export-with-tags
26051 (save-match-data
26052 (concat
26053 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26054 (mapconcat 'identity (org-split-string
26055 (match-string 1 title) ":")
26056 "&nbsp;")
26057 "</span>"))
26059 t t title)))
26060 (if (> level umax)
26061 (progn
26062 (if (aref org-levels-open (1- level))
26063 (progn
26064 (org-close-li)
26065 (insert "<li>" title "<br/>\n"))
26066 (aset org-levels-open (1- level) t)
26067 (org-close-par-maybe)
26068 (insert "<ul>\n<li>" title "<br/>\n")))
26069 (aset org-levels-open (1- level) t)
26070 (if (and org-export-with-section-numbers (not body-only))
26071 (setq title (concat (org-section-number level) " " title)))
26072 (setq level (+ level org-export-html-toplevel-hlevel -1))
26073 (if with-toc
26074 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26075 level level head-count title level))
26076 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26077 (org-open-par)))))
26079 (defun org-html-level-close (level max-outline-level)
26080 "Terminate one level in HTML export."
26081 (if (<= level max-outline-level)
26082 (insert "</div>\n")
26083 (org-close-li)
26084 (insert "</ul>\n")))
26086 ;;; iCalendar export
26088 ;;;###autoload
26089 (defun org-export-icalendar-this-file ()
26090 "Export current file as an iCalendar file.
26091 The iCalendar file will be located in the same directory as the Org-mode
26092 file, but with extension `.ics'."
26093 (interactive)
26094 (org-export-icalendar nil buffer-file-name))
26096 ;;;###autoload
26097 (defun org-export-icalendar-all-agenda-files ()
26098 "Export all files in `org-agenda-files' to iCalendar .ics files.
26099 Each iCalendar file will be located in the same directory as the Org-mode
26100 file, but with extension `.ics'."
26101 (interactive)
26102 (apply 'org-export-icalendar nil (org-agenda-files t)))
26104 ;;;###autoload
26105 (defun org-export-icalendar-combine-agenda-files ()
26106 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26107 The file is stored under the name `org-combined-agenda-icalendar-file'."
26108 (interactive)
26109 (apply 'org-export-icalendar t (org-agenda-files t)))
26111 (defun org-export-icalendar (combine &rest files)
26112 "Create iCalendar files for all elements of FILES.
26113 If COMBINE is non-nil, combine all calendar entries into a single large
26114 file and store it under the name `org-combined-agenda-icalendar-file'."
26115 (save-excursion
26116 (org-prepare-agenda-buffers files)
26117 (let* ((dir (org-export-directory
26118 :ical (list :publishing-directory
26119 org-export-publishing-directory)))
26120 file ical-file ical-buffer category started org-agenda-new-buffers)
26122 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26123 (when combine
26124 (setq ical-file
26125 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26126 org-combined-agenda-icalendar-file
26127 (expand-file-name org-combined-agenda-icalendar-file dir))
26128 ical-buffer (org-get-agenda-file-buffer ical-file))
26129 (set-buffer ical-buffer) (erase-buffer))
26130 (while (setq file (pop files))
26131 (catch 'nextfile
26132 (org-check-agenda-file file)
26133 (set-buffer (org-get-agenda-file-buffer file))
26134 (unless combine
26135 (setq ical-file (concat (file-name-as-directory dir)
26136 (file-name-sans-extension
26137 (file-name-nondirectory buffer-file-name))
26138 ".ics"))
26139 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26140 (with-current-buffer ical-buffer (erase-buffer)))
26141 (setq category (or org-category
26142 (file-name-sans-extension
26143 (file-name-nondirectory buffer-file-name))))
26144 (if (symbolp category) (setq category (symbol-name category)))
26145 (let ((standard-output ical-buffer))
26146 (if combine
26147 (and (not started) (setq started t)
26148 (org-start-icalendar-file org-icalendar-combined-name))
26149 (org-start-icalendar-file category))
26150 (org-print-icalendar-entries combine)
26151 (when (or (and combine (not files)) (not combine))
26152 (org-finish-icalendar-file)
26153 (set-buffer ical-buffer)
26154 (save-buffer)
26155 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26156 (org-release-buffers org-agenda-new-buffers))))
26158 (defvar org-after-save-iCalendar-file-hook nil
26159 "Hook run after an iCalendar file has been saved.
26160 The iCalendar buffer is still current when this hook is run.
26161 A good way to use this is to tell a desktop calenndar application to re-read
26162 the iCalendar file.")
26164 (defun org-print-icalendar-entries (&optional combine)
26165 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26166 When COMBINE is non nil, add the category to each line."
26167 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26168 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26169 (dts (org-ical-ts-to-string
26170 (format-time-string (cdr org-time-stamp-formats) (current-time))
26171 "DTSTART"))
26172 hd ts ts2 state status (inc t) pos b sexp rrule
26173 scheduledp deadlinep tmp pri category entry location summary desc
26174 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26175 (org-refresh-category-properties)
26176 (save-excursion
26177 (goto-char (point-min))
26178 (while (re-search-forward re1 nil t)
26179 (catch :skip
26180 (org-agenda-skip)
26181 (setq pos (match-beginning 0)
26182 ts (match-string 0)
26183 inc t
26184 hd (org-get-heading)
26185 summary (org-icalendar-cleanup-string
26186 (org-entry-get nil "SUMMARY"))
26187 desc (org-icalendar-cleanup-string
26188 (or (org-entry-get nil "DESCRIPTION")
26189 (and org-icalendar-include-body (org-get-entry)))
26190 t org-icalendar-include-body)
26191 location (org-icalendar-cleanup-string
26192 (org-entry-get nil "LOCATION"))
26193 category (org-get-category))
26194 (if (looking-at re2)
26195 (progn
26196 (goto-char (match-end 0))
26197 (setq ts2 (match-string 1) inc nil))
26198 (setq tmp (buffer-substring (max (point-min)
26199 (- pos org-ds-keyword-length))
26200 pos)
26201 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26202 (progn
26203 (setq inc nil)
26204 (replace-match "\\1" t nil ts))
26206 deadlinep (string-match org-deadline-regexp tmp)
26207 scheduledp (string-match org-scheduled-regexp tmp)
26208 ;; donep (org-entry-is-done-p)
26210 (if (or (string-match org-tr-regexp hd)
26211 (string-match org-ts-regexp hd))
26212 (setq hd (replace-match "" t t hd)))
26213 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26214 (setq rrule
26215 (concat "\nRRULE:FREQ="
26216 (cdr (assoc
26217 (match-string 2 ts)
26218 '(("d" . "DAILY")("w" . "WEEKLY")
26219 ("m" . "MONTHLY")("y" . "YEARLY"))))
26220 ";INTERVAL=" (match-string 1 ts)))
26221 (setq rrule ""))
26222 (setq summary (or summary hd))
26223 (if (string-match org-bracket-link-regexp summary)
26224 (setq summary
26225 (replace-match (if (match-end 3)
26226 (match-string 3 summary)
26227 (match-string 1 summary))
26228 t t summary)))
26229 (if deadlinep (setq summary (concat "DL: " summary)))
26230 (if scheduledp (setq summary (concat "S: " summary)))
26231 (if (string-match "\\`<%%" ts)
26232 (with-current-buffer sexp-buffer
26233 (insert (substring ts 1 -1) " " summary "\n"))
26234 (princ (format "BEGIN:VEVENT
26236 %s%s
26237 SUMMARY:%s%s%s
26238 CATEGORIES:%s
26239 END:VEVENT\n"
26240 (org-ical-ts-to-string ts "DTSTART")
26241 (org-ical-ts-to-string ts2 "DTEND" inc)
26242 rrule summary
26243 (if (and desc (string-match "\\S-" desc))
26244 (concat "\nDESCRIPTION: " desc) "")
26245 (if (and location (string-match "\\S-" location))
26246 (concat "\nLOCATION: " location) "")
26247 category)))))
26249 (when (and org-icalendar-include-sexps
26250 (condition-case nil (require 'icalendar) (error nil))
26251 (fboundp 'icalendar-export-region))
26252 ;; Get all the literal sexps
26253 (goto-char (point-min))
26254 (while (re-search-forward "^&?%%(" nil t)
26255 (catch :skip
26256 (org-agenda-skip)
26257 (setq b (match-beginning 0))
26258 (goto-char (1- (match-end 0)))
26259 (forward-sexp 1)
26260 (end-of-line 1)
26261 (setq sexp (buffer-substring b (point)))
26262 (with-current-buffer sexp-buffer
26263 (insert sexp "\n"))
26264 (princ (org-diary-to-ical-string sexp-buffer)))))
26266 (when org-icalendar-include-todo
26267 (goto-char (point-min))
26268 (while (re-search-forward org-todo-line-regexp nil t)
26269 (catch :skip
26270 (org-agenda-skip)
26271 (setq state (match-string 2))
26272 (setq status (if (member state org-done-keywords)
26273 "COMPLETED" "NEEDS-ACTION"))
26274 (when (and state
26275 (or (not (member state org-done-keywords))
26276 (eq org-icalendar-include-todo 'all))
26277 (not (member org-archive-tag (org-get-tags-at)))
26279 (setq hd (match-string 3)
26280 summary (org-icalendar-cleanup-string
26281 (org-entry-get nil "SUMMARY"))
26282 desc (org-icalendar-cleanup-string
26283 (or (org-entry-get nil "DESCRIPTION")
26284 (and org-icalendar-include-body (org-get-entry)))
26285 t org-icalendar-include-body)
26286 location (org-icalendar-cleanup-string
26287 (org-entry-get nil "LOCATION")))
26288 (if (string-match org-bracket-link-regexp hd)
26289 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26290 (match-string 1 hd))
26291 t t hd)))
26292 (if (string-match org-priority-regexp hd)
26293 (setq pri (string-to-char (match-string 2 hd))
26294 hd (concat (substring hd 0 (match-beginning 1))
26295 (substring hd (match-end 1))))
26296 (setq pri org-default-priority))
26297 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26298 (- org-lowest-priority org-highest-priority))))))
26300 (princ (format "BEGIN:VTODO
26302 SUMMARY:%s%s%s
26303 CATEGORIES:%s
26304 SEQUENCE:1
26305 PRIORITY:%d
26306 STATUS:%s
26307 END:VTODO\n"
26309 (or summary hd)
26310 (if (and location (string-match "\\S-" location))
26311 (concat "\nLOCATION: " location) "")
26312 (if (and desc (string-match "\\S-" desc))
26313 (concat "\nDESCRIPTION: " desc) "")
26314 category pri status)))))))))
26316 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26317 "Take out stuff and quote what needs to be quoted.
26318 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26319 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26320 characters."
26321 (if (not s)
26323 (when is-body
26324 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26325 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26326 (while (string-match re s) (setq s (replace-match "" t t s)))
26327 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26328 (let ((start 0))
26329 (while (string-match "\\([,;\\]\\)" s start)
26330 (setq start (+ (match-beginning 0) 2)
26331 s (replace-match "\\\\\\1" nil nil s))))
26332 (when is-body
26333 (while (string-match "[ \t]*\n[ \t]*" s)
26334 (setq s (replace-match "\\n" t t s))))
26335 (setq s (org-trim s))
26336 (if is-body
26337 (if maxlength
26338 (if (and (numberp maxlength)
26339 (> (length s) maxlength))
26340 (setq s (substring s 0 maxlength)))))
26343 (defun org-get-entry ()
26344 "Clean-up description string."
26345 (save-excursion
26346 (org-back-to-heading t)
26347 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26349 (defun org-start-icalendar-file (name)
26350 "Start an iCalendar file by inserting the header."
26351 (let ((user user-full-name)
26352 (name (or name "unknown"))
26353 (timezone (cadr (current-time-zone))))
26354 (princ
26355 (format "BEGIN:VCALENDAR
26356 VERSION:2.0
26357 X-WR-CALNAME:%s
26358 PRODID:-//%s//Emacs with Org-mode//EN
26359 X-WR-TIMEZONE:%s
26360 CALSCALE:GREGORIAN\n" name user timezone))))
26362 (defun org-finish-icalendar-file ()
26363 "Finish an iCalendar file by inserting the END statement."
26364 (princ "END:VCALENDAR\n"))
26366 (defun org-ical-ts-to-string (s keyword &optional inc)
26367 "Take a time string S and convert it to iCalendar format.
26368 KEYWORD is added in front, to make a complete line like DTSTART....
26369 When INC is non-nil, increase the hour by two (if time string contains
26370 a time), or the day by one (if it does not contain a time)."
26371 (let ((t1 (org-parse-time-string s 'nodefault))
26372 t2 fmt have-time time)
26373 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26374 (setq t2 t1 have-time t)
26375 (setq t2 (org-parse-time-string s)))
26376 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26377 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26378 (when inc
26379 (if have-time
26380 (if org-agenda-default-appointment-duration
26381 (setq mi (+ org-agenda-default-appointment-duration mi))
26382 (setq h (+ 2 h)))
26383 (setq d (1+ d))))
26384 (setq time (encode-time s mi h d m y)))
26385 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26386 (concat keyword (format-time-string fmt time))))
26388 ;;; XOXO export
26390 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26391 (with-current-buffer buffer
26392 (apply 'insert output)))
26393 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26395 (defun org-export-as-xoxo (&optional buffer)
26396 "Export the org buffer as XOXO.
26397 The XOXO buffer is named *xoxo-<source buffer name>*"
26398 (interactive (list (current-buffer)))
26399 ;; A quickie abstraction
26401 ;; Output everything as XOXO
26402 (with-current-buffer (get-buffer buffer)
26403 (let* ((pos (point))
26404 (opt-plist (org-combine-plists (org-default-export-plist)
26405 (org-infile-export-plist)))
26406 (filename (concat (file-name-as-directory
26407 (org-export-directory :xoxo opt-plist))
26408 (file-name-sans-extension
26409 (file-name-nondirectory buffer-file-name))
26410 ".html"))
26411 (out (find-file-noselect filename))
26412 (last-level 1)
26413 (hanging-li nil))
26414 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26415 ;; Check the output buffer is empty.
26416 (with-current-buffer out (erase-buffer))
26417 ;; Kick off the output
26418 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26419 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26420 (let* ((hd (match-string-no-properties 1))
26421 (level (length hd))
26422 (text (concat
26423 (match-string-no-properties 2)
26424 (save-excursion
26425 (goto-char (match-end 0))
26426 (let ((str ""))
26427 (catch 'loop
26428 (while 't
26429 (forward-line)
26430 (if (looking-at "^[ \t]\\(.*\\)")
26431 (setq str (concat str (match-string-no-properties 1)))
26432 (throw 'loop str)))))))))
26434 ;; Handle level rendering
26435 (cond
26436 ((> level last-level)
26437 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26439 ((< level last-level)
26440 (dotimes (- (- last-level level) 1)
26441 (if hanging-li
26442 (org-export-as-xoxo-insert-into out "</li>\n"))
26443 (org-export-as-xoxo-insert-into out "</ol>\n"))
26444 (when hanging-li
26445 (org-export-as-xoxo-insert-into out "</li>\n")
26446 (setq hanging-li nil)))
26448 ((equal level last-level)
26449 (if hanging-li
26450 (org-export-as-xoxo-insert-into out "</li>\n")))
26453 (setq last-level level)
26455 ;; And output the new li
26456 (setq hanging-li 't)
26457 (if (equal ?+ (elt text 0))
26458 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26459 (org-export-as-xoxo-insert-into out "<li>" text))))
26461 ;; Finally finish off the ol
26462 (dotimes (- last-level 1)
26463 (if hanging-li
26464 (org-export-as-xoxo-insert-into out "</li>\n"))
26465 (org-export-as-xoxo-insert-into out "</ol>\n"))
26467 (goto-char pos)
26468 ;; Finish the buffer off and clean it up.
26469 (switch-to-buffer-other-window out)
26470 (indent-region (point-min) (point-max) nil)
26471 (save-buffer)
26472 (goto-char (point-min))
26476 ;;;; Key bindings
26478 ;; Make `C-c C-x' a prefix key
26479 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26481 ;; TAB key with modifiers
26482 (org-defkey org-mode-map "\C-i" 'org-cycle)
26483 (org-defkey org-mode-map [(tab)] 'org-cycle)
26484 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26485 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26486 (org-defkey org-mode-map "\M-\t" 'org-complete)
26487 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26488 ;; The following line is necessary under Suse GNU/Linux
26489 (unless (featurep 'xemacs)
26490 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26491 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26492 (define-key org-mode-map [backtab] 'org-shifttab)
26494 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26495 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26496 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26498 ;; Cursor keys with modifiers
26499 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26500 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26501 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26502 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26504 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26505 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26506 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26507 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26509 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26510 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26511 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26512 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26514 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26515 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26517 ;;; Extra keys for tty access.
26518 ;; We only set them when really needed because otherwise the
26519 ;; menus don't show the simple keys
26521 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26522 (not window-system))
26523 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26524 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26525 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26526 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26527 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26528 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26529 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26530 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26531 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26532 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26533 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26534 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26535 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26536 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26537 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26538 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26539 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26540 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26541 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26542 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26543 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26544 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26546 ;; All the other keys
26548 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26549 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26550 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26551 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26552 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26553 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26554 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26555 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26556 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26557 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26558 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26559 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26560 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26561 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26562 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26563 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26564 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26565 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26566 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26567 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26568 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26569 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26570 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26571 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26572 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26573 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26574 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26575 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26576 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26577 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26578 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26579 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26580 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26581 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26582 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26583 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26584 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26585 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26586 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26587 (org-defkey org-mode-map "\C-c^" 'org-sort)
26588 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26589 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26590 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26591 (org-defkey org-mode-map "\C-m" 'org-return)
26592 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26593 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26594 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26595 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26596 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26597 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26598 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26599 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26600 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26601 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26602 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26603 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26604 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26605 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26606 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26607 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26608 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26610 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26611 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26612 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26613 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26615 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26616 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26617 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26618 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26619 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26620 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26621 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26622 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26623 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26624 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26625 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26626 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26628 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26630 (when (featurep 'xemacs)
26631 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26633 (defsubst org-table-p () (org-at-table-p))
26635 (defun org-self-insert-command (N)
26636 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26637 If the cursor is in a table looking at whitespace, the whitespace is
26638 overwritten, and the table is not marked as requiring realignment."
26639 (interactive "p")
26640 (if (and (org-table-p)
26641 (progn
26642 ;; check if we blank the field, and if that triggers align
26643 (and org-table-auto-blank-field
26644 (member last-command
26645 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26646 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26647 ;; got extra space, this field does not determine column width
26648 (let (org-table-may-need-update) (org-table-blank-field))
26649 ;; no extra space, this field may determine column width
26650 (org-table-blank-field)))
26652 (eq N 1)
26653 (looking-at "[^|\n]* |"))
26654 (let (org-table-may-need-update)
26655 (goto-char (1- (match-end 0)))
26656 (delete-backward-char 1)
26657 (goto-char (match-beginning 0))
26658 (self-insert-command N))
26659 (setq org-table-may-need-update t)
26660 (self-insert-command N)
26661 (org-fix-tags-on-the-fly)))
26663 (defun org-fix-tags-on-the-fly ()
26664 (when (and (equal (char-after (point-at-bol)) ?*)
26665 (org-on-heading-p))
26666 (org-align-tags-here org-tags-column)))
26668 (defun org-delete-backward-char (N)
26669 "Like `delete-backward-char', insert whitespace at field end in tables.
26670 When deleting backwards, in tables this function will insert whitespace in
26671 front of the next \"|\" separator, to keep the table aligned. The table will
26672 still be marked for re-alignment if the field did fill the entire column,
26673 because, in this case the deletion might narrow the column."
26674 (interactive "p")
26675 (if (and (org-table-p)
26676 (eq N 1)
26677 (string-match "|" (buffer-substring (point-at-bol) (point)))
26678 (looking-at ".*?|"))
26679 (let ((pos (point))
26680 (noalign (looking-at "[^|\n\r]* |"))
26681 (c org-table-may-need-update))
26682 (backward-delete-char N)
26683 (skip-chars-forward "^|")
26684 (insert " ")
26685 (goto-char (1- pos))
26686 ;; noalign: if there were two spaces at the end, this field
26687 ;; does not determine the width of the column.
26688 (if noalign (setq org-table-may-need-update c)))
26689 (backward-delete-char N)
26690 (org-fix-tags-on-the-fly)))
26692 (defun org-delete-char (N)
26693 "Like `delete-char', but insert whitespace at field end in tables.
26694 When deleting characters, in tables this function will insert whitespace in
26695 front of the next \"|\" separator, to keep the table aligned. The table will
26696 still be marked for re-alignment if the field did fill the entire column,
26697 because, in this case the deletion might narrow the column."
26698 (interactive "p")
26699 (if (and (org-table-p)
26700 (not (bolp))
26701 (not (= (char-after) ?|))
26702 (eq N 1))
26703 (if (looking-at ".*?|")
26704 (let ((pos (point))
26705 (noalign (looking-at "[^|\n\r]* |"))
26706 (c org-table-may-need-update))
26707 (replace-match (concat
26708 (substring (match-string 0) 1 -1)
26709 " |"))
26710 (goto-char pos)
26711 ;; noalign: if there were two spaces at the end, this field
26712 ;; does not determine the width of the column.
26713 (if noalign (setq org-table-may-need-update c)))
26714 (delete-char N))
26715 (delete-char N)
26716 (org-fix-tags-on-the-fly)))
26718 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
26719 (put 'org-self-insert-command 'delete-selection t)
26720 (put 'orgtbl-self-insert-command 'delete-selection t)
26721 (put 'org-delete-char 'delete-selection 'supersede)
26722 (put 'org-delete-backward-char 'delete-selection 'supersede)
26724 ;; Make `flyspell-mode' delay after some commands
26725 (put 'org-self-insert-command 'flyspell-delayed t)
26726 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
26727 (put 'org-delete-char 'flyspell-delayed t)
26728 (put 'org-delete-backward-char 'flyspell-delayed t)
26730 ;; Make pabbrev-mode expand after org-mode commands
26731 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
26732 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
26734 ;; How to do this: Measure non-white length of current string
26735 ;; If equal to column width, we should realign.
26737 (defun org-remap (map &rest commands)
26738 "In MAP, remap the functions given in COMMANDS.
26739 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
26740 (let (new old)
26741 (while commands
26742 (setq old (pop commands) new (pop commands))
26743 (if (fboundp 'command-remapping)
26744 (org-defkey map (vector 'remap old) new)
26745 (substitute-key-definition old new map global-map)))))
26747 (when (eq org-enable-table-editor 'optimized)
26748 ;; If the user wants maximum table support, we need to hijack
26749 ;; some standard editing functions
26750 (org-remap org-mode-map
26751 'self-insert-command 'org-self-insert-command
26752 'delete-char 'org-delete-char
26753 'delete-backward-char 'org-delete-backward-char)
26754 (org-defkey org-mode-map "|" 'org-force-self-insert))
26756 (defun org-shiftcursor-error ()
26757 "Throw an error because Shift-Cursor command was applied in wrong context."
26758 (error "This command is active in special context like tables, headlines or timestamps"))
26760 (defun org-shifttab (&optional arg)
26761 "Global visibility cycling or move to previous table field.
26762 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
26763 on context.
26764 See the individual commands for more information."
26765 (interactive "P")
26766 (cond
26767 ((org-at-table-p) (call-interactively 'org-table-previous-field))
26768 (arg (message "Content view to level: ")
26769 (org-content (prefix-numeric-value arg))
26770 (setq org-cycle-global-status 'overview))
26771 (t (call-interactively 'org-global-cycle))))
26773 (defun org-shiftmetaleft ()
26774 "Promote subtree or delete table column.
26775 Calls `org-promote-subtree', `org-outdent-item',
26776 or `org-table-delete-column', depending on context.
26777 See the individual commands for more information."
26778 (interactive)
26779 (cond
26780 ((org-at-table-p) (call-interactively 'org-table-delete-column))
26781 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
26782 ((org-at-item-p) (call-interactively 'org-outdent-item))
26783 (t (org-shiftcursor-error))))
26785 (defun org-shiftmetaright ()
26786 "Demote subtree or insert table column.
26787 Calls `org-demote-subtree', `org-indent-item',
26788 or `org-table-insert-column', depending on context.
26789 See the individual commands for more information."
26790 (interactive)
26791 (cond
26792 ((org-at-table-p) (call-interactively 'org-table-insert-column))
26793 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
26794 ((org-at-item-p) (call-interactively 'org-indent-item))
26795 (t (org-shiftcursor-error))))
26797 (defun org-shiftmetaup (&optional arg)
26798 "Move subtree up or kill table row.
26799 Calls `org-move-subtree-up' or `org-table-kill-row' or
26800 `org-move-item-up' depending on context. See the individual commands
26801 for more information."
26802 (interactive "P")
26803 (cond
26804 ((org-at-table-p) (call-interactively 'org-table-kill-row))
26805 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26806 ((org-at-item-p) (call-interactively 'org-move-item-up))
26807 (t (org-shiftcursor-error))))
26808 (defun org-shiftmetadown (&optional arg)
26809 "Move subtree down or insert table row.
26810 Calls `org-move-subtree-down' or `org-table-insert-row' or
26811 `org-move-item-down', depending on context. See the individual
26812 commands for more information."
26813 (interactive "P")
26814 (cond
26815 ((org-at-table-p) (call-interactively 'org-table-insert-row))
26816 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26817 ((org-at-item-p) (call-interactively 'org-move-item-down))
26818 (t (org-shiftcursor-error))))
26820 (defun org-metaleft (&optional arg)
26821 "Promote heading or move table column to left.
26822 Calls `org-do-promote' or `org-table-move-column', depending on context.
26823 With no specific context, calls the Emacs default `backward-word'.
26824 See the individual commands for more information."
26825 (interactive "P")
26826 (cond
26827 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
26828 ((or (org-on-heading-p) (org-region-active-p))
26829 (call-interactively 'org-do-promote))
26830 ((org-at-item-p) (call-interactively 'org-outdent-item))
26831 (t (call-interactively 'backward-word))))
26833 (defun org-metaright (&optional arg)
26834 "Demote subtree or move table column to right.
26835 Calls `org-do-demote' or `org-table-move-column', depending on context.
26836 With no specific context, calls the Emacs default `forward-word'.
26837 See the individual commands for more information."
26838 (interactive "P")
26839 (cond
26840 ((org-at-table-p) (call-interactively 'org-table-move-column))
26841 ((or (org-on-heading-p) (org-region-active-p))
26842 (call-interactively 'org-do-demote))
26843 ((org-at-item-p) (call-interactively 'org-indent-item))
26844 (t (call-interactively 'forward-word))))
26846 (defun org-metaup (&optional arg)
26847 "Move subtree up or move table row up.
26848 Calls `org-move-subtree-up' or `org-table-move-row' or
26849 `org-move-item-up', depending on context. See the individual commands
26850 for more information."
26851 (interactive "P")
26852 (cond
26853 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
26854 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
26855 ((org-at-item-p) (call-interactively 'org-move-item-up))
26856 (t (transpose-lines 1) (beginning-of-line -1))))
26858 (defun org-metadown (&optional arg)
26859 "Move subtree down or move table row down.
26860 Calls `org-move-subtree-down' or `org-table-move-row' or
26861 `org-move-item-down', depending on context. See the individual
26862 commands for more information."
26863 (interactive "P")
26864 (cond
26865 ((org-at-table-p) (call-interactively 'org-table-move-row))
26866 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
26867 ((org-at-item-p) (call-interactively 'org-move-item-down))
26868 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
26870 (defun org-shiftup (&optional arg)
26871 "Increase item in timestamp or increase priority of current headline.
26872 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
26873 depending on context. See the individual commands for more information."
26874 (interactive "P")
26875 (cond
26876 ((org-at-timestamp-p t)
26877 (call-interactively (if org-edit-timestamp-down-means-later
26878 'org-timestamp-down 'org-timestamp-up)))
26879 ((org-on-heading-p) (call-interactively 'org-priority-up))
26880 ((org-at-item-p) (call-interactively 'org-previous-item))
26881 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
26883 (defun org-shiftdown (&optional arg)
26884 "Decrease item in timestamp or decrease priority of current headline.
26885 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
26886 depending on context. See the individual commands for more information."
26887 (interactive "P")
26888 (cond
26889 ((org-at-timestamp-p t)
26890 (call-interactively (if org-edit-timestamp-down-means-later
26891 'org-timestamp-up 'org-timestamp-down)))
26892 ((org-on-heading-p) (call-interactively 'org-priority-down))
26893 (t (call-interactively 'org-next-item))))
26895 (defun org-shiftright ()
26896 "Next TODO keyword or timestamp one day later, depending on context."
26897 (interactive)
26898 (cond
26899 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
26900 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
26901 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
26902 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
26903 (t (org-shiftcursor-error))))
26905 (defun org-shiftleft ()
26906 "Previous TODO keyword or timestamp one day earlier, depending on context."
26907 (interactive)
26908 (cond
26909 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
26910 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
26911 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
26912 ((org-at-property-p)
26913 (call-interactively 'org-property-previous-allowed-value))
26914 (t (org-shiftcursor-error))))
26916 (defun org-shiftcontrolright ()
26917 "Switch to next TODO set."
26918 (interactive)
26919 (cond
26920 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
26921 (t (org-shiftcursor-error))))
26923 (defun org-shiftcontrolleft ()
26924 "Switch to previous TODO set."
26925 (interactive)
26926 (cond
26927 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
26928 (t (org-shiftcursor-error))))
26930 (defun org-ctrl-c-ret ()
26931 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
26932 (interactive)
26933 (cond
26934 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
26935 (t (call-interactively 'org-insert-heading))))
26937 (defun org-copy-special ()
26938 "Copy region in table or copy current subtree.
26939 Calls `org-table-copy' or `org-copy-subtree', depending on context.
26940 See the individual commands for more information."
26941 (interactive)
26942 (call-interactively
26943 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
26945 (defun org-cut-special ()
26946 "Cut region in table or cut current subtree.
26947 Calls `org-table-copy' or `org-cut-subtree', depending on context.
26948 See the individual commands for more information."
26949 (interactive)
26950 (call-interactively
26951 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
26953 (defun org-paste-special (arg)
26954 "Paste rectangular region into table, or past subtree relative to level.
26955 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
26956 See the individual commands for more information."
26957 (interactive "P")
26958 (if (org-at-table-p)
26959 (org-table-paste-rectangle)
26960 (org-paste-subtree arg)))
26962 (defun org-ctrl-c-ctrl-c (&optional arg)
26963 "Set tags in headline, or update according to changed information at point.
26965 This command does many different things, depending on context:
26967 - If the cursor is in a headline, prompt for tags and insert them
26968 into the current line, aligned to `org-tags-column'. When called
26969 with prefix arg, realign all tags in the current buffer.
26971 - If the cursor is in one of the special #+KEYWORD lines, this
26972 triggers scanning the buffer for these lines and updating the
26973 information.
26975 - If the cursor is inside a table, realign the table. This command
26976 works even if the automatic table editor has been turned off.
26978 - If the cursor is on a #+TBLFM line, re-apply the formulas to
26979 the entire table.
26981 - If the cursor is a the beginning of a dynamic block, update it.
26983 - If the cursor is inside a table created by the table.el package,
26984 activate that table.
26986 - If the current buffer is a remember buffer, close note and file it.
26987 with a prefix argument, file it without further interaction to the default
26988 location.
26990 - If the cursor is on a <<<target>>>, update radio targets and corresponding
26991 links in this buffer.
26993 - If the cursor is on a numbered item in a plain list, renumber the
26994 ordered list.
26996 - If the cursor is on a checkbox, toggle it."
26997 (interactive "P")
26998 (let ((org-enable-table-editor t))
26999 (cond
27000 ((or org-clock-overlays
27001 org-occur-highlights
27002 org-latex-fragment-image-overlays)
27003 (org-remove-clock-overlays)
27004 (org-remove-occur-highlights)
27005 (org-remove-latex-fragment-image-overlays)
27006 (message "Temporary highlights/overlays removed from current buffer"))
27007 ((and (local-variable-p 'org-finish-function (current-buffer))
27008 (fboundp org-finish-function))
27009 (funcall org-finish-function))
27010 ((org-at-property-p)
27011 (call-interactively 'org-property-action))
27012 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27013 ((org-on-heading-p) (call-interactively 'org-set-tags))
27014 ((org-at-table.el-p)
27015 (require 'table)
27016 (beginning-of-line 1)
27017 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27018 (call-interactively 'table-recognize-table))
27019 ((org-at-table-p)
27020 (org-table-maybe-eval-formula)
27021 (if arg
27022 (call-interactively 'org-table-recalculate)
27023 (org-table-maybe-recalculate-line))
27024 (call-interactively 'org-table-align))
27025 ((org-at-item-checkbox-p)
27026 (call-interactively 'org-toggle-checkbox))
27027 ((org-at-item-p)
27028 (call-interactively 'org-maybe-renumber-ordered-list))
27029 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27030 ;; Dynamic block
27031 (beginning-of-line 1)
27032 (org-update-dblock))
27033 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27034 (cond
27035 ((equal (match-string 1) "TBLFM")
27036 ;; Recalculate the table before this line
27037 (save-excursion
27038 (beginning-of-line 1)
27039 (skip-chars-backward " \r\n\t")
27040 (if (org-at-table-p)
27041 (org-call-with-arg 'org-table-recalculate t))))
27043 (call-interactively 'org-mode-restart))))
27044 (t (error "C-c C-c can do nothing useful at this location.")))))
27046 (defun org-mode-restart ()
27047 "Restart Org-mode, to scan again for special lines.
27048 Also updates the keyword regular expressions."
27049 (interactive)
27050 (let ((org-inhibit-startup t)) (org-mode))
27051 (message "Org-mode restarted to refresh keyword and special line setup"))
27053 (defun org-kill-note-or-show-branches ()
27054 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27055 (interactive)
27056 (if (not org-finish-function)
27057 (call-interactively 'show-branches)
27058 (let ((org-note-abort t))
27059 (funcall org-finish-function))))
27061 (defun org-return (&optional indent)
27062 "Goto next table row or insert a newline.
27063 Calls `org-table-next-row' or `newline', depending on context.
27064 See the individual commands for more information."
27065 (interactive)
27066 (cond
27067 ((bobp) (if indent (newline-and-indent) (newline)))
27068 ((and (org-at-heading-p)
27069 (looking-at
27070 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27071 (org-show-entry)
27072 (end-of-line 1)
27073 (newline))
27074 ((org-at-table-p)
27075 (org-table-justify-field-maybe)
27076 (call-interactively 'org-table-next-row))
27077 (t (if indent (newline-and-indent) (newline)))))
27079 (defun org-return-indent ()
27080 (interactive)
27081 "Goto next table row or insert a newline and indent.
27082 Calls `org-table-next-row' or `newline-and-indent', depending on
27083 context. See the individual commands for more information."
27084 (org-return t))
27086 (defun org-ctrl-c-minus ()
27087 "Insert separator line in table or modify bullet type in list.
27088 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27089 depending on context."
27090 (interactive)
27091 (cond
27092 ((org-at-table-p)
27093 (call-interactively 'org-table-insert-hline))
27094 ((org-on-heading-p)
27095 ;; Convert to item
27096 (save-excursion
27097 (beginning-of-line 1)
27098 (if (looking-at "\\*+ ")
27099 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27100 ((org-in-item-p)
27101 (call-interactively 'org-cycle-list-bullet))
27102 (t (error "`C-c -' does have no function here."))))
27104 (defun org-meta-return (&optional arg)
27105 "Insert a new heading or wrap a region in a table.
27106 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27107 See the individual commands for more information."
27108 (interactive "P")
27109 (cond
27110 ((org-at-table-p)
27111 (call-interactively 'org-table-wrap-region))
27112 (t (call-interactively 'org-insert-heading))))
27114 ;;; Menu entries
27116 ;; Define the Org-mode menus
27117 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27118 '("Tbl"
27119 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27120 ["Next Field" org-cycle (org-at-table-p)]
27121 ["Previous Field" org-shifttab (org-at-table-p)]
27122 ["Next Row" org-return (org-at-table-p)]
27123 "--"
27124 ["Blank Field" org-table-blank-field (org-at-table-p)]
27125 ["Edit Field" org-table-edit-field (org-at-table-p)]
27126 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27127 "--"
27128 ("Column"
27129 ["Move Column Left" org-metaleft (org-at-table-p)]
27130 ["Move Column Right" org-metaright (org-at-table-p)]
27131 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27132 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27133 ("Row"
27134 ["Move Row Up" org-metaup (org-at-table-p)]
27135 ["Move Row Down" org-metadown (org-at-table-p)]
27136 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27137 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27138 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27139 "--"
27140 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27141 ("Rectangle"
27142 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27143 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27144 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27145 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27146 "--"
27147 ("Calculate"
27148 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27149 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27150 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27151 "--"
27152 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27153 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27154 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27155 "--"
27156 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27157 "--"
27158 ["Sum Column/Rectangle" org-table-sum
27159 (or (org-at-table-p) (org-region-active-p))]
27160 ["Which Column?" org-table-current-column (org-at-table-p)])
27161 ["Debug Formulas"
27162 org-table-toggle-formula-debugger
27163 :style toggle :selected org-table-formula-debug]
27164 ["Show Col/Row Numbers"
27165 org-table-toggle-coordinate-overlays
27166 :style toggle :selected org-table-overlay-coordinates]
27167 "--"
27168 ["Create" org-table-create (and (not (org-at-table-p))
27169 org-enable-table-editor)]
27170 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27171 ["Import from File" org-table-import (not (org-at-table-p))]
27172 ["Export to File" org-table-export (org-at-table-p)]
27173 "--"
27174 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27176 (easy-menu-define org-org-menu org-mode-map "Org menu"
27177 '("Org"
27178 ("Show/Hide"
27179 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27180 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27181 ["Sparse Tree" org-occur t]
27182 ["Reveal Context" org-reveal t]
27183 ["Show All" show-all t]
27184 "--"
27185 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27186 "--"
27187 ["New Heading" org-insert-heading t]
27188 ("Navigate Headings"
27189 ["Up" outline-up-heading t]
27190 ["Next" outline-next-visible-heading t]
27191 ["Previous" outline-previous-visible-heading t]
27192 ["Next Same Level" outline-forward-same-level t]
27193 ["Previous Same Level" outline-backward-same-level t]
27194 "--"
27195 ["Jump" org-goto t])
27196 ("Edit Structure"
27197 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27198 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27199 "--"
27200 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27201 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27202 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27203 "--"
27204 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27205 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27206 ["Demote Heading" org-metaright (not (org-at-table-p))]
27207 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27208 "--"
27209 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27210 "--"
27211 ["Convert to odd levels" org-convert-to-odd-levels t]
27212 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27213 ("Editing"
27214 ["Emphasis..." org-emphasize t])
27215 ("Archive"
27216 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27217 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27218 ; :active t :keys "C-u C-c C-x C-a"]
27219 ["Sparse trees open ARCHIVE trees"
27220 (setq org-sparse-tree-open-archived-trees
27221 (not org-sparse-tree-open-archived-trees))
27222 :style toggle :selected org-sparse-tree-open-archived-trees]
27223 ["Cycling opens ARCHIVE trees"
27224 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27225 :style toggle :selected org-cycle-open-archived-trees]
27226 ["Agenda includes ARCHIVE trees"
27227 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27228 :style toggle :selected (not org-agenda-skip-archived-trees)]
27229 "--"
27230 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27231 ; ["Check and Move Children" (org-archive-subtree '(4))
27232 ; :active t :keys "C-u C-c C-x C-s"]
27234 "--"
27235 ("TODO Lists"
27236 ["TODO/DONE/-" org-todo t]
27237 ("Select keyword"
27238 ["Next keyword" org-shiftright (org-on-heading-p)]
27239 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27240 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27241 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27242 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27243 ["Show TODO Tree" org-show-todo-tree t]
27244 ["Global TODO list" org-todo-list t]
27245 "--"
27246 ["Set Priority" org-priority t]
27247 ["Priority Up" org-shiftup t]
27248 ["Priority Down" org-shiftdown t])
27249 ("TAGS and Properties"
27250 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27251 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27252 "--"
27253 ["Set property" 'org-set-property t]
27254 ["Column view of properties" org-columns t]
27255 ["Insert Column View DBlock" org-insert-columns-dblock t])
27256 ("Dates and Scheduling"
27257 ["Timestamp" org-time-stamp t]
27258 ["Timestamp (inactive)" org-time-stamp-inactive t]
27259 ("Change Date"
27260 ["1 Day Later" org-shiftright t]
27261 ["1 Day Earlier" org-shiftleft t]
27262 ["1 ... Later" org-shiftup t]
27263 ["1 ... Earlier" org-shiftdown t])
27264 ["Compute Time Range" org-evaluate-time-range t]
27265 ["Schedule Item" org-schedule t]
27266 ["Deadline" org-deadline t]
27267 "--"
27268 ["Custom time format" org-toggle-time-stamp-overlays
27269 :style radio :selected org-display-custom-times]
27270 "--"
27271 ["Goto Calendar" org-goto-calendar t]
27272 ["Date from Calendar" org-date-from-calendar t])
27273 ("Logging work"
27274 ["Clock in" org-clock-in t]
27275 ["Clock out" org-clock-out t]
27276 ["Clock cancel" org-clock-cancel t]
27277 ["Goto running clock" org-clock-goto t]
27278 ["Display times" org-clock-display t]
27279 ["Create clock table" org-clock-report t]
27280 "--"
27281 ["Record DONE time"
27282 (progn (setq org-log-done (not org-log-done))
27283 (message "Switching to %s will %s record a timestamp"
27284 (car org-done-keywords)
27285 (if org-log-done "automatically" "not")))
27286 :style toggle :selected org-log-done])
27287 "--"
27288 ["Agenda Command..." org-agenda t]
27289 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27290 ("File List for Agenda")
27291 ("Special views current file"
27292 ["TODO Tree" org-show-todo-tree t]
27293 ["Check Deadlines" org-check-deadlines t]
27294 ["Timeline" org-timeline t]
27295 ["Tags Tree" org-tags-sparse-tree t])
27296 "--"
27297 ("Hyperlinks"
27298 ["Store Link (Global)" org-store-link t]
27299 ["Insert Link" org-insert-link t]
27300 ["Follow Link" org-open-at-point t]
27301 "--"
27302 ["Next link" org-next-link t]
27303 ["Previous link" org-previous-link t]
27304 "--"
27305 ["Descriptive Links"
27306 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27307 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27308 ["Literal Links"
27309 (progn
27310 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27311 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27312 "--"
27313 ["Export/Publish..." org-export t]
27314 ("LaTeX"
27315 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27316 :selected org-cdlatex-mode]
27317 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27318 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27319 ["Modify math symbol" org-cdlatex-math-modify
27320 (org-inside-LaTeX-fragment-p)]
27321 ["Export LaTeX fragments as images"
27322 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27323 :style toggle :selected org-export-with-LaTeX-fragments])
27324 "--"
27325 ("Documentation"
27326 ["Show Version" org-version t]
27327 ["Info Documentation" org-info t])
27328 ("Customize"
27329 ["Browse Org Group" org-customize t]
27330 "--"
27331 ["Expand This Menu" org-create-customize-menu
27332 (fboundp 'customize-menu-create)])
27333 "--"
27334 ["Refresh setup" org-mode-restart t]
27337 (defun org-info (&optional node)
27338 "Read documentation for Org-mode in the info system.
27339 With optional NODE, go directly to that node."
27340 (interactive)
27341 (require 'info)
27342 (Info-goto-node (format "(org)%s" (or node ""))))
27344 (defun org-install-agenda-files-menu ()
27345 (let ((bl (buffer-list)))
27346 (save-excursion
27347 (while bl
27348 (set-buffer (pop bl))
27349 (if (org-mode-p) (setq bl nil)))
27350 (when (org-mode-p)
27351 (easy-menu-change
27352 '("Org") "File List for Agenda"
27353 (append
27354 (list
27355 ["Edit File List" (org-edit-agenda-file-list) t]
27356 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27357 ["Remove Current File from List" org-remove-file t]
27358 ["Cycle through agenda files" org-cycle-agenda-files t]
27359 ["Occur in all agenda files" org-occur-in-agenda-files t]
27360 "--")
27361 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27363 ;;;; Documentation
27365 (defun org-customize ()
27366 "Call the customize function with org as argument."
27367 (interactive)
27368 (customize-browse 'org))
27370 (defun org-create-customize-menu ()
27371 "Create a full customization menu for Org-mode, insert it into the menu."
27372 (interactive)
27373 (if (fboundp 'customize-menu-create)
27374 (progn
27375 (easy-menu-change
27376 '("Org") "Customize"
27377 `(["Browse Org group" org-customize t]
27378 "--"
27379 ,(customize-menu-create 'org)
27380 ["Set" Custom-set t]
27381 ["Save" Custom-save t]
27382 ["Reset to Current" Custom-reset-current t]
27383 ["Reset to Saved" Custom-reset-saved t]
27384 ["Reset to Standard Settings" Custom-reset-standard t]))
27385 (message "\"Org\"-menu now contains full customization menu"))
27386 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27388 ;;;; Miscellaneous stuff
27391 ;;; Generally useful functions
27393 (defun org-context ()
27394 "Return a list of contexts of the current cursor position.
27395 If several contexts apply, all are returned.
27396 Each context entry is a list with a symbol naming the context, and
27397 two positions indicating start and end of the context. Possible
27398 contexts are:
27400 :headline anywhere in a headline
27401 :headline-stars on the leading stars in a headline
27402 :todo-keyword on a TODO keyword (including DONE) in a headline
27403 :tags on the TAGS in a headline
27404 :priority on the priority cookie in a headline
27405 :item on the first line of a plain list item
27406 :item-bullet on the bullet/number of a plain list item
27407 :checkbox on the checkbox in a plain list item
27408 :table in an org-mode table
27409 :table-special on a special filed in a table
27410 :table-table in a table.el table
27411 :link on a hyperlink
27412 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27413 :target on a <<target>>
27414 :radio-target on a <<<radio-target>>>
27415 :latex-fragment on a LaTeX fragment
27416 :latex-preview on a LaTeX fragment with overlayed preview image
27418 This function expects the position to be visible because it uses font-lock
27419 faces as a help to recognize the following contexts: :table-special, :link,
27420 and :keyword."
27421 (let* ((f (get-text-property (point) 'face))
27422 (faces (if (listp f) f (list f)))
27423 (p (point)) clist o)
27424 ;; First the large context
27425 (cond
27426 ((org-on-heading-p t)
27427 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27428 (when (progn
27429 (beginning-of-line 1)
27430 (looking-at org-todo-line-tags-regexp))
27431 (push (org-point-in-group p 1 :headline-stars) clist)
27432 (push (org-point-in-group p 2 :todo-keyword) clist)
27433 (push (org-point-in-group p 4 :tags) clist))
27434 (goto-char p)
27435 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27436 (if (looking-at "\\[#[A-Z0-9]\\]")
27437 (push (org-point-in-group p 0 :priority) clist)))
27439 ((org-at-item-p)
27440 (push (org-point-in-group p 2 :item-bullet) clist)
27441 (push (list :item (point-at-bol)
27442 (save-excursion (org-end-of-item) (point)))
27443 clist)
27444 (and (org-at-item-checkbox-p)
27445 (push (org-point-in-group p 0 :checkbox) clist)))
27447 ((org-at-table-p)
27448 (push (list :table (org-table-begin) (org-table-end)) clist)
27449 (if (memq 'org-formula faces)
27450 (push (list :table-special
27451 (previous-single-property-change p 'face)
27452 (next-single-property-change p 'face)) clist)))
27453 ((org-at-table-p 'any)
27454 (push (list :table-table) clist)))
27455 (goto-char p)
27457 ;; Now the small context
27458 (cond
27459 ((org-at-timestamp-p)
27460 (push (org-point-in-group p 0 :timestamp) clist))
27461 ((memq 'org-link faces)
27462 (push (list :link
27463 (previous-single-property-change p 'face)
27464 (next-single-property-change p 'face)) clist))
27465 ((memq 'org-special-keyword faces)
27466 (push (list :keyword
27467 (previous-single-property-change p 'face)
27468 (next-single-property-change p 'face)) clist))
27469 ((org-on-target-p)
27470 (push (org-point-in-group p 0 :target) clist)
27471 (goto-char (1- (match-beginning 0)))
27472 (if (looking-at org-radio-target-regexp)
27473 (push (org-point-in-group p 0 :radio-target) clist))
27474 (goto-char p))
27475 ((setq o (car (delq nil
27476 (mapcar
27477 (lambda (x)
27478 (if (memq x org-latex-fragment-image-overlays) x))
27479 (org-overlays-at (point))))))
27480 (push (list :latex-fragment
27481 (org-overlay-start o) (org-overlay-end o)) clist)
27482 (push (list :latex-preview
27483 (org-overlay-start o) (org-overlay-end o)) clist))
27484 ((org-inside-LaTeX-fragment-p)
27485 ;; FIXME: positions wrong.
27486 (push (list :latex-fragment (point) (point)) clist)))
27488 (setq clist (nreverse (delq nil clist)))
27489 clist))
27491 ;; FIXME: Compare with at-regexp-p Do we need both?
27492 (defun org-in-regexp (re &optional nlines visually)
27493 "Check if point is inside a match of regexp.
27494 Normally only the current line is checked, but you can include NLINES extra
27495 lines both before and after point into the search.
27496 If VISUALLY is set, require that the cursor is not after the match but
27497 really on, so that the block visually is on the match."
27498 (catch 'exit
27499 (let ((pos (point))
27500 (eol (point-at-eol (+ 1 (or nlines 0))))
27501 (inc (if visually 1 0)))
27502 (save-excursion
27503 (beginning-of-line (- 1 (or nlines 0)))
27504 (while (re-search-forward re eol t)
27505 (if (and (<= (match-beginning 0) pos)
27506 (>= (+ inc (match-end 0)) pos))
27507 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27509 (defun org-at-regexp-p (regexp)
27510 "Is point inside a match of REGEXP in the current line?"
27511 (catch 'exit
27512 (save-excursion
27513 (let ((pos (point)) (end (point-at-eol)))
27514 (beginning-of-line 1)
27515 (while (re-search-forward regexp end t)
27516 (if (and (<= (match-beginning 0) pos)
27517 (>= (match-end 0) pos))
27518 (throw 'exit t)))
27519 nil))))
27521 (defun org-occur-in-agenda-files (regexp &optional nlines)
27522 "Call `multi-occur' with buffers for all agenda files."
27523 (interactive "sOrg-files matching: \np")
27524 (let* ((files (org-agenda-files))
27525 (tnames (mapcar 'file-truename files))
27526 (extra org-agenda-multi-occur-extra-files)
27528 (while (setq f (pop extra))
27529 (unless (member (file-truename f) tnames)
27530 (add-to-list 'files f 'append)
27531 (add-to-list 'tnames (file-truename f) 'append)))
27532 (multi-occur
27533 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27534 regexp)))
27536 (if (boundp 'occur-mode-find-occurrence-hook)
27537 ;; Emacs 23
27538 (add-hook 'occur-mode-find-occurrence-hook
27539 (lambda ()
27540 (when (org-mode-p)
27541 (org-reveal))))
27542 ;; Emacs 22
27543 (defadvice occur-mode-goto-occurrence
27544 (after org-occur-reveal activate)
27545 (and (org-mode-p) (org-reveal)))
27546 (defadvice occur-mode-goto-occurrence-other-window
27547 (after org-occur-reveal activate)
27548 (and (org-mode-p) (org-reveal)))
27549 (defadvice occur-mode-display-occurrence
27550 (after org-occur-reveal activate)
27551 (when (org-mode-p)
27552 (let ((pos (occur-mode-find-occurrence)))
27553 (with-current-buffer (marker-buffer pos)
27554 (save-excursion
27555 (goto-char pos)
27556 (org-reveal)))))))
27558 (defun org-uniquify (list)
27559 "Remove duplicate elements from LIST."
27560 (let (res)
27561 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27562 res))
27564 (defun org-delete-all (elts list)
27565 "Remove all elements in ELTS from LIST."
27566 (while elts
27567 (setq list (delete (pop elts) list)))
27568 list)
27570 (defun org-back-over-empty-lines ()
27571 "Move backwards over witespace, to the beginning of the first empty line.
27572 Returns the number o empty lines passed."
27573 (let ((pos (point)))
27574 (skip-chars-backward " \t\n\r")
27575 (beginning-of-line 2)
27576 (goto-char (min (point) pos))
27577 (count-lines (point) pos)))
27579 (defun org-skip-whitespace ()
27580 (skip-chars-forward " \t\n\r"))
27582 (defun org-point-in-group (point group &optional context)
27583 "Check if POINT is in match-group GROUP.
27584 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27585 match. If the match group does ot exist or point is not inside it,
27586 return nil."
27587 (and (match-beginning group)
27588 (>= point (match-beginning group))
27589 (<= point (match-end group))
27590 (if context
27591 (list context (match-beginning group) (match-end group))
27592 t)))
27594 (defun org-switch-to-buffer-other-window (&rest args)
27595 "Switch to buffer in a second window on the current frame.
27596 In particular, do not allow pop-up frames."
27597 (let (pop-up-frames special-display-buffer-names special-display-regexps
27598 special-display-function)
27599 (apply 'switch-to-buffer-other-window args)))
27601 (defun org-combine-plists (&rest plists)
27602 "Create a single property list from all plists in PLISTS.
27603 The process starts by copying the first list, and then setting properties
27604 from the other lists. Settings in the last list are the most significant
27605 ones and overrule settings in the other lists."
27606 (let ((rtn (copy-sequence (pop plists)))
27607 p v ls)
27608 (while plists
27609 (setq ls (pop plists))
27610 (while ls
27611 (setq p (pop ls) v (pop ls))
27612 (setq rtn (plist-put rtn p v))))
27613 rtn))
27615 (defun org-move-line-down (arg)
27616 "Move the current line down. With prefix argument, move it past ARG lines."
27617 (interactive "p")
27618 (let ((col (current-column))
27619 beg end pos)
27620 (beginning-of-line 1) (setq beg (point))
27621 (beginning-of-line 2) (setq end (point))
27622 (beginning-of-line (+ 1 arg))
27623 (setq pos (move-marker (make-marker) (point)))
27624 (insert (delete-and-extract-region beg end))
27625 (goto-char pos)
27626 (move-to-column col)))
27628 (defun org-move-line-up (arg)
27629 "Move the current line up. With prefix argument, move it past ARG lines."
27630 (interactive "p")
27631 (let ((col (current-column))
27632 beg end pos)
27633 (beginning-of-line 1) (setq beg (point))
27634 (beginning-of-line 2) (setq end (point))
27635 (beginning-of-line (- arg))
27636 (setq pos (move-marker (make-marker) (point)))
27637 (insert (delete-and-extract-region beg end))
27638 (goto-char pos)
27639 (move-to-column col)))
27641 (defun org-replace-escapes (string table)
27642 "Replace %-escapes in STRING with values in TABLE.
27643 TABLE is an association list with keys like \"%a\" and string values.
27644 The sequences in STRING may contain normal field width and padding information,
27645 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27646 so values can contain further %-escapes if they are define later in TABLE."
27647 (let ((case-fold-search nil)
27648 e re rpl)
27649 (while (setq e (pop table))
27650 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27651 (while (string-match re string)
27652 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27653 (cdr e)))
27654 (setq string (replace-match rpl t t string))))
27655 string))
27658 (defun org-sublist (list start end)
27659 "Return a section of LIST, from START to END.
27660 Counting starts at 1."
27661 (let (rtn (c start))
27662 (setq list (nthcdr (1- start) list))
27663 (while (and list (<= c end))
27664 (push (pop list) rtn)
27665 (setq c (1+ c)))
27666 (nreverse rtn)))
27668 (defun org-find-base-buffer-visiting (file)
27669 "Like `find-buffer-visiting' but alway return the base buffer and
27670 not an indirect buffer"
27671 (let ((buf (find-buffer-visiting file)))
27672 (if buf
27673 (or (buffer-base-buffer buf) buf)
27674 nil)))
27676 (defun org-image-file-name-regexp ()
27677 "Return regexp matching the file names of images."
27678 (if (fboundp 'image-file-name-regexp)
27679 (image-file-name-regexp)
27680 (let ((image-file-name-extensions
27681 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
27682 "xbm" "xpm" "pbm" "pgm" "ppm")))
27683 (concat "\\."
27684 (regexp-opt (nconc (mapcar 'upcase
27685 image-file-name-extensions)
27686 image-file-name-extensions)
27688 "\\'"))))
27690 (defun org-file-image-p (file)
27691 "Return non-nil if FILE is an image."
27692 (save-match-data
27693 (string-match (org-image-file-name-regexp) file)))
27695 ;;; Paragraph filling stuff.
27696 ;; We want this to be just right, so use the full arsenal.
27698 (defun org-indent-line-function ()
27699 "Indent line like previous, but further if previous was headline or item."
27700 (interactive)
27701 (let* ((pos (point))
27702 (itemp (org-at-item-p))
27703 column bpos bcol tpos tcol bullet btype bullet-type)
27704 ;; Find the previous relevant line
27705 (beginning-of-line 1)
27706 (cond
27707 ((looking-at "#") (setq column 0))
27708 ((looking-at "\\*+ ") (setq column 0))
27710 (beginning-of-line 0)
27711 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
27712 (beginning-of-line 0))
27713 (cond
27714 ((looking-at "\\*+[ \t]+")
27715 (goto-char (match-end 0))
27716 (setq column (current-column)))
27717 ((org-in-item-p)
27718 (org-beginning-of-item)
27719 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27720 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
27721 (setq bpos (match-beginning 1) tpos (match-end 0)
27722 bcol (progn (goto-char bpos) (current-column))
27723 tcol (progn (goto-char tpos) (current-column))
27724 bullet (match-string 1)
27725 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
27726 (if (not itemp)
27727 (setq column tcol)
27728 (goto-char pos)
27729 (beginning-of-line 1)
27730 (if (looking-at "\\S-")
27731 (progn
27732 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
27733 (setq bullet (match-string 1)
27734 btype (if (string-match "[0-9]" bullet) "n" bullet))
27735 (setq column (if (equal btype bullet-type) bcol tcol)))
27736 (setq column (org-get-indentation)))))
27737 (t (setq column (org-get-indentation))))))
27738 (goto-char pos)
27739 (if (<= (current-column) (current-indentation))
27740 (indent-line-to column)
27741 (save-excursion (indent-line-to column)))
27742 (setq column (current-column))
27743 (beginning-of-line 1)
27744 (if (looking-at
27745 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
27746 (replace-match (concat "\\1" (format org-property-format
27747 (match-string 2) (match-string 3)))
27748 t nil))
27749 (move-to-column column)))
27751 (defun org-set-autofill-regexps ()
27752 (interactive)
27753 ;; In the paragraph separator we include headlines, because filling
27754 ;; text in a line directly attached to a headline would otherwise
27755 ;; fill the headline as well.
27756 (org-set-local 'comment-start-skip "^#+[ \t]*")
27757 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
27758 ;; The paragraph starter includes hand-formatted lists.
27759 (org-set-local 'paragraph-start
27760 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
27761 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
27762 ;; But only if the user has not turned off tables or fixed-width regions
27763 (org-set-local
27764 'auto-fill-inhibit-regexp
27765 (concat "\\*+ \\|#\\+"
27766 "\\|[ \t]*" org-keyword-time-regexp
27767 (if (or org-enable-table-editor org-enable-fixed-width-editor)
27768 (concat
27769 "\\|[ \t]*["
27770 (if org-enable-table-editor "|" "")
27771 (if org-enable-fixed-width-editor ":" "")
27772 "]"))))
27773 ;; We use our own fill-paragraph function, to make sure that tables
27774 ;; and fixed-width regions are not wrapped. That function will pass
27775 ;; through to `fill-paragraph' when appropriate.
27776 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
27777 ; Adaptive filling: To get full control, first make sure that
27778 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
27779 (org-set-local 'adaptive-fill-regexp "\000")
27780 (org-set-local 'adaptive-fill-function
27781 'org-adaptive-fill-function)
27782 (org-set-local
27783 'align-mode-rules-list
27784 '((org-in-buffer-settings
27785 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
27786 (modes . '(org-mode))))))
27788 (defun org-fill-paragraph (&optional justify)
27789 "Re-align a table, pass through to fill-paragraph if no table."
27790 (let ((table-p (org-at-table-p))
27791 (table.el-p (org-at-table.el-p)))
27792 (cond ((and (equal (char-after (point-at-bol)) ?*)
27793 (save-excursion (goto-char (point-at-bol))
27794 (looking-at outline-regexp)))
27795 t) ; skip headlines
27796 (table.el-p t) ; skip table.el tables
27797 (table-p (org-table-align) t) ; align org-mode tables
27798 (t nil)))) ; call paragraph-fill
27800 ;; For reference, this is the default value of adaptive-fill-regexp
27801 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
27803 (defun org-adaptive-fill-function ()
27804 "Return a fill prefix for org-mode files.
27805 In particular, this makes sure hanging paragraphs for hand-formatted lists
27806 work correctly."
27807 (cond ((looking-at "#[ \t]+")
27808 (match-string 0))
27809 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
27810 (save-excursion
27811 (goto-char (match-end 0))
27812 (make-string (current-column) ?\ )))
27813 (t nil)))
27815 ;;;; Functions extending outline functionality
27818 (defun org-beginning-of-line (&optional arg)
27819 "Go to the beginning of the current line. If that is invisible, continue
27820 to a visible line beginning. This makes the function of C-a more intuitive.
27821 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27822 first attempt, and only move to after the tags when the cursor is already
27823 beyond the end of the headline."
27824 (interactive "P")
27825 (let ((pos (point)))
27826 (beginning-of-line 1)
27827 (if (bobp)
27829 (backward-char 1)
27830 (if (org-invisible-p)
27831 (while (and (not (bobp)) (org-invisible-p))
27832 (backward-char 1)
27833 (beginning-of-line 1))
27834 (forward-char 1)))
27835 (when org-special-ctrl-a/e
27836 (cond
27837 ((and (looking-at org-todo-line-regexp)
27838 (= (char-after (match-end 1)) ?\ ))
27839 (goto-char
27840 (if (eq org-special-ctrl-a/e t)
27841 (cond ((> pos (match-beginning 3)) (match-beginning 3))
27842 ((= pos (point)) (match-beginning 3))
27843 (t (point)))
27844 (cond ((> pos (point)) (point))
27845 ((not (eq last-command this-command)) (point))
27846 (t (match-beginning 3))))))
27847 ((org-at-item-p)
27848 (goto-char
27849 (if (eq org-special-ctrl-a/e t)
27850 (cond ((> pos (match-end 4)) (match-end 4))
27851 ((= pos (point)) (match-end 4))
27852 (t (point)))
27853 (cond ((> pos (point)) (point))
27854 ((not (eq last-command this-command)) (point))
27855 (t (match-end 4))))))))))
27857 (defun org-end-of-line (&optional arg)
27858 "Go to the end of the line.
27859 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
27860 first attempt, and only move to after the tags when the cursor is already
27861 beyond the end of the headline."
27862 (interactive "P")
27863 (if (or (not org-special-ctrl-a/e)
27864 (not (org-on-heading-p)))
27865 (end-of-line arg)
27866 (let ((pos (point)))
27867 (beginning-of-line 1)
27868 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
27869 (if (eq org-special-ctrl-a/e t)
27870 (if (or (< pos (match-beginning 1))
27871 (= pos (match-end 0)))
27872 (goto-char (match-beginning 1))
27873 (goto-char (match-end 0)))
27874 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
27875 (goto-char (match-end 0))
27876 (goto-char (match-beginning 1))))
27877 (end-of-line arg)))))
27879 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
27880 (define-key org-mode-map "\C-e" 'org-end-of-line)
27882 (defun org-kill-line (&optional arg)
27883 "Kill line, to tags or end of line."
27884 (interactive "P")
27885 (cond
27886 ((or (not org-special-ctrl-k)
27887 (bolp)
27888 (not (org-on-heading-p)))
27889 (call-interactively 'kill-line))
27890 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
27891 (kill-region (point) (match-beginning 1))
27892 (org-set-tags nil t))
27893 (t (kill-region (point) (point-at-eol)))))
27895 (define-key org-mode-map "\C-k" 'org-kill-line)
27897 (defun org-invisible-p ()
27898 "Check if point is at a character currently not visible."
27899 ;; Early versions of noutline don't have `outline-invisible-p'.
27900 (if (fboundp 'outline-invisible-p)
27901 (outline-invisible-p)
27902 (get-char-property (point) 'invisible)))
27904 (defun org-invisible-p2 ()
27905 "Check if point is at a character currently not visible."
27906 (save-excursion
27907 (if (and (eolp) (not (bobp))) (backward-char 1))
27908 ;; Early versions of noutline don't have `outline-invisible-p'.
27909 (if (fboundp 'outline-invisible-p)
27910 (outline-invisible-p)
27911 (get-char-property (point) 'invisible))))
27913 (defalias 'org-back-to-heading 'outline-back-to-heading)
27914 (defalias 'org-on-heading-p 'outline-on-heading-p)
27915 (defalias 'org-at-heading-p 'outline-on-heading-p)
27916 (defun org-at-heading-or-item-p ()
27917 (or (org-on-heading-p) (org-at-item-p)))
27919 (defun org-on-target-p ()
27920 (or (org-in-regexp org-radio-target-regexp)
27921 (org-in-regexp org-target-regexp)))
27923 (defun org-up-heading-all (arg)
27924 "Move to the heading line of which the present line is a subheading.
27925 This function considers both visible and invisible heading lines.
27926 With argument, move up ARG levels."
27927 (if (fboundp 'outline-up-heading-all)
27928 (outline-up-heading-all arg) ; emacs 21 version of outline.el
27929 (outline-up-heading arg t))) ; emacs 22 version of outline.el
27931 (defun org-up-heading-safe ()
27932 "Move to the heading line of which the present line is a subheading.
27933 This version will not throw an error. It will return the level of the
27934 headline found, or nil if no higher level is found."
27935 (let ((pos (point)) start-level level
27936 (re (concat "^" outline-regexp)))
27937 (catch 'exit
27938 (outline-back-to-heading t)
27939 (setq start-level (funcall outline-level))
27940 (if (equal start-level 1) (throw 'exit nil))
27941 (while (re-search-backward re nil t)
27942 (setq level (funcall outline-level))
27943 (if (< level start-level) (throw 'exit level)))
27944 nil)))
27946 (defun org-first-sibling-p ()
27947 "Is this heading the first child of its parents?"
27948 (interactive)
27949 (let ((re (concat "^" outline-regexp))
27950 level l)
27951 (unless (org-at-heading-p t)
27952 (error "Not at a heading"))
27953 (setq level (funcall outline-level))
27954 (save-excursion
27955 (if (not (re-search-backward re nil t))
27957 (setq l (funcall outline-level))
27958 (< l level)))))
27960 (defun org-goto-sibling (&optional previous)
27961 "Goto the next sibling, even if it is invisible.
27962 When PREVIOUS is set, go to the previous sibling instead. Returns t
27963 when a sibling was found. When none is found, return nil and don't
27964 move point."
27965 (let ((fun (if previous 're-search-backward 're-search-forward))
27966 (pos (point))
27967 (re (concat "^" outline-regexp))
27968 level l)
27969 (when (condition-case nil (org-back-to-heading t) (error nil))
27970 (setq level (funcall outline-level))
27971 (catch 'exit
27972 (or previous (forward-char 1))
27973 (while (funcall fun re nil t)
27974 (setq l (funcall outline-level))
27975 (when (< l level) (goto-char pos) (throw 'exit nil))
27976 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
27977 (goto-char pos)
27978 nil))))
27980 (defun org-show-siblings ()
27981 "Show all siblings of the current headline."
27982 (save-excursion
27983 (while (org-goto-sibling) (org-flag-heading nil)))
27984 (save-excursion
27985 (while (org-goto-sibling 'previous)
27986 (org-flag-heading nil))))
27988 (defun org-show-hidden-entry ()
27989 "Show an entry where even the heading is hidden."
27990 (save-excursion
27991 (org-show-entry)))
27993 (defun org-flag-heading (flag &optional entry)
27994 "Flag the current heading. FLAG non-nil means make invisible.
27995 When ENTRY is non-nil, show the entire entry."
27996 (save-excursion
27997 (org-back-to-heading t)
27998 ;; Check if we should show the entire entry
27999 (if entry
28000 (progn
28001 (org-show-entry)
28002 (save-excursion
28003 (and (outline-next-heading)
28004 (org-flag-heading nil))))
28005 (outline-flag-region (max (point-min) (1- (point)))
28006 (save-excursion (outline-end-of-heading) (point))
28007 flag))))
28009 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28010 ;; This is an exact copy of the original function, but it uses
28011 ;; `org-back-to-heading', to make it work also in invisible
28012 ;; trees. And is uses an invisible-OK argument.
28013 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28014 (org-back-to-heading invisible-OK)
28015 (let ((first t)
28016 (level (funcall outline-level)))
28017 (while (and (not (eobp))
28018 (or first (> (funcall outline-level) level)))
28019 (setq first nil)
28020 (outline-next-heading))
28021 (unless to-heading
28022 (if (memq (preceding-char) '(?\n ?\^M))
28023 (progn
28024 ;; Go to end of line before heading
28025 (forward-char -1)
28026 (if (memq (preceding-char) '(?\n ?\^M))
28027 ;; leave blank line before heading
28028 (forward-char -1))))))
28029 (point))
28031 (defun org-show-subtree ()
28032 "Show everything after this heading at deeper levels."
28033 (outline-flag-region
28034 (point)
28035 (save-excursion
28036 (outline-end-of-subtree) (outline-next-heading) (point))
28037 nil))
28039 (defun org-show-entry ()
28040 "Show the body directly following this heading.
28041 Show the heading too, if it is currently invisible."
28042 (interactive)
28043 (save-excursion
28044 (condition-case nil
28045 (progn
28046 (org-back-to-heading t)
28047 (outline-flag-region
28048 (max (point-min) (1- (point)))
28049 (save-excursion
28050 (re-search-forward
28051 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28052 (or (match-beginning 1) (point-max)))
28053 nil))
28054 (error nil))))
28056 (defun org-make-options-regexp (kwds)
28057 "Make a regular expression for keyword lines."
28058 (concat
28060 "#?[ \t]*\\+\\("
28061 (mapconcat 'regexp-quote kwds "\\|")
28062 "\\):[ \t]*"
28063 "\\(.+\\)"))
28065 ;; Make isearch reveal the necessary context
28066 (defun org-isearch-end ()
28067 "Reveal context after isearch exits."
28068 (when isearch-success ; only if search was successful
28069 (if (featurep 'xemacs)
28070 ;; Under XEmacs, the hook is run in the correct place,
28071 ;; we directly show the context.
28072 (org-show-context 'isearch)
28073 ;; In Emacs the hook runs *before* restoring the overlays.
28074 ;; So we have to use a one-time post-command-hook to do this.
28075 ;; (Emacs 22 has a special variable, see function `org-mode')
28076 (unless (and (boundp 'isearch-mode-end-hook-quit)
28077 isearch-mode-end-hook-quit)
28078 ;; Only when the isearch was not quitted.
28079 (org-add-hook 'post-command-hook 'org-isearch-post-command
28080 'append 'local)))))
28082 (defun org-isearch-post-command ()
28083 "Remove self from hook, and show context."
28084 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28085 (org-show-context 'isearch))
28088 ;;;; Integration with and fixes for other packages
28090 ;;; Imenu support
28092 (defvar org-imenu-markers nil
28093 "All markers currently used by Imenu.")
28094 (make-variable-buffer-local 'org-imenu-markers)
28096 (defun org-imenu-new-marker (&optional pos)
28097 "Return a new marker for use by Imenu, and remember the marker."
28098 (let ((m (make-marker)))
28099 (move-marker m (or pos (point)))
28100 (push m org-imenu-markers)
28103 (defun org-imenu-get-tree ()
28104 "Produce the index for Imenu."
28105 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28106 (setq org-imenu-markers nil)
28107 (let* ((n org-imenu-depth)
28108 (re (concat "^" outline-regexp))
28109 (subs (make-vector (1+ n) nil))
28110 (last-level 0)
28111 m tree level head)
28112 (save-excursion
28113 (save-restriction
28114 (widen)
28115 (goto-char (point-max))
28116 (while (re-search-backward re nil t)
28117 (setq level (org-reduced-level (funcall outline-level)))
28118 (when (<= level n)
28119 (looking-at org-complex-heading-regexp)
28120 (setq head (org-match-string-no-properties 4)
28121 m (org-imenu-new-marker))
28122 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28123 (if (>= level last-level)
28124 (push (cons head m) (aref subs level))
28125 (push (cons head (aref subs (1+ level))) (aref subs level))
28126 (loop for i from (1+ level) to n do (aset subs i nil)))
28127 (setq last-level level)))))
28128 (aref subs 1)))
28130 (eval-after-load "imenu"
28131 '(progn
28132 (add-hook 'imenu-after-jump-hook
28133 (lambda () (org-show-context 'org-goto)))))
28135 ;; Speedbar support
28137 (defun org-speedbar-set-agenda-restriction ()
28138 "Restrict future agenda commands to the location at point in speedbar.
28139 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28140 (interactive)
28141 (let (p m tp np dir txt w)
28142 (cond
28143 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28144 'org-imenu t))
28145 (setq m (get-text-property p 'org-imenu-marker))
28146 (save-excursion
28147 (save-restriction
28148 (set-buffer (marker-buffer m))
28149 (goto-char m)
28150 (org-agenda-set-restriction-lock 'subtree))))
28151 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28152 'speedbar-function 'speedbar-find-file))
28153 (setq tp (previous-single-property-change
28154 (1+ p) 'speedbar-function)
28155 np (next-single-property-change
28156 tp 'speedbar-function)
28157 dir (speedbar-line-directory)
28158 txt (buffer-substring-no-properties (or tp (point-min))
28159 (or np (point-max))))
28160 (save-excursion
28161 (save-restriction
28162 (set-buffer (find-file-noselect
28163 (let ((default-directory dir))
28164 (expand-file-name txt))))
28165 (unless (org-mode-p)
28166 (error "Cannot restrict to non-Org-mode file"))
28167 (org-agenda-set-restriction-lock 'file))))
28168 (t (error "Don't know how to restrict Org-mode's agenda")))
28169 (org-move-overlay org-speedbar-restriction-lock-overlay
28170 (point-at-bol) (point-at-eol))
28171 (setq current-prefix-arg nil)
28172 (org-agenda-maybe-redo)))
28174 (eval-after-load "speedbar"
28175 '(progn
28176 (speedbar-add-supported-extension ".org")
28177 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28178 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28179 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28180 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28181 (add-hook 'speedbar-visiting-tag-hook
28182 (lambda () (org-show-context 'org-goto)))))
28185 ;;; Fixes and Hacks
28187 ;; Make flyspell not check words in links, to not mess up our keymap
28188 (defun org-mode-flyspell-verify ()
28189 "Don't let flyspell put overlays at active buttons."
28190 (not (get-text-property (point) 'keymap)))
28192 ;; Make `bookmark-jump' show the jump location if it was hidden.
28193 (eval-after-load "bookmark"
28194 '(if (boundp 'bookmark-after-jump-hook)
28195 ;; We can use the hook
28196 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28197 ;; Hook not available, use advice
28198 (defadvice bookmark-jump (after org-make-visible activate)
28199 "Make the position visible."
28200 (org-bookmark-jump-unhide))))
28202 (defun org-bookmark-jump-unhide ()
28203 "Unhide the current position, to show the bookmark location."
28204 (and (org-mode-p)
28205 (or (org-invisible-p)
28206 (save-excursion (goto-char (max (point-min) (1- (point))))
28207 (org-invisible-p)))
28208 (org-show-context 'bookmark-jump)))
28210 ;; Fix a bug in htmlize where there are text properties (face nil)
28211 (eval-after-load "htmlize"
28212 '(progn
28213 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28214 "Make sure there are no nil faces"
28215 (setq ad-return-value (delq nil ad-return-value)))))
28217 ;; Make session.el ignore our circular variable
28218 (eval-after-load "session"
28219 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28221 ;;;; Experimental code
28223 (defun org-closed-in-range ()
28224 "Sparse tree of items closed in a certain time range.
28225 Still experimental, may disappear in the future."
28226 (interactive)
28227 ;; Get the time interval from the user.
28228 (let* ((time1 (time-to-seconds
28229 (org-read-date nil 'to-time nil "Starting date: ")))
28230 (time2 (time-to-seconds
28231 (org-read-date nil 'to-time nil "End date:")))
28232 ;; callback function
28233 (callback (lambda ()
28234 (let ((time
28235 (time-to-seconds
28236 (apply 'encode-time
28237 (org-parse-time-string
28238 (match-string 1))))))
28239 ;; check if time in interval
28240 (and (>= time time1) (<= time time2))))))
28241 ;; make tree, check each match with the callback
28242 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28244 ;;;; Finish up
28246 (provide 'org)
28248 (run-hooks 'org-load-hook)
28250 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28251 ;;; org.el ends here