Release 4.60
[org-mode.git] / org.el
blobe8cf734cdf9077db476b69a0dd4abcaf7e56cd42
1 ;;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 4.60
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 2, 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://staff.science.uva.nl/~dominik/Tools/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 ;; Recent changes
63 ;; --------------
64 ;; Version 4.60
65 ;; - HTML export: inlining images, clickable images (manual 10.2.4).
66 ;; - Incremental search now shows proper context when exiting.
67 ;; - Tables calculation and Calc package.
68 ;; - Calc is no longer needed when using only elisp formulas.
69 ;; - Proper error messages when calc is needed and not available.
70 ;; - Tracking TODO state changes with time stamps and notes.
71 ;; - Empty entries go full circle.
72 ;; - Links in iCalendar export cleaned up.
73 ;; - Bug fixes.
75 ;; Version 4.59
76 ;; - Cleanup code, bug fixes.
78 ;; Version 4.58
79 ;; - Full undo support in the agenda buffer.
80 ;; - Listing stuck GTD projects (projects without any NEXT ACTIONS).
81 ;; Configure `org-stuck-projects' before using it.
82 ;; - C-c C-x b shows the current subtree in an indirect buffer, in
83 ;; another, dedicated frame.
84 ;; - Custom agenda commands take precedence over builtin commands.
85 ;; - auto-fill for comments works on the Emacs side, XEmacs not yet.
87 ;; Version 4.57
88 ;; - Sorting of outline items on same level.
89 ;; - Sorting tables automatically selects line range between hlines.
90 ;; - Changes in Agenda buffer
91 ;; - `C-c C-o' follows a link in the current line.
92 ;; - `C-c $' archives the subtree corresponding to the line.
93 ;; - Changing dates with S-left and S-right show new date in agenda,
94 ;; but still do not move the entry to the new date.
95 ;; - new option `org-agenda-skip-scheduled-if-done'.
96 ;; - Agenda and sparse tree construction using tag matches can now
97 ;; use regular expressions.
98 ;; - When prompted for a date/time, entering "+7" indicates a date
99 ;; 7 days from now - but only this is the only thing you give.
100 ;; - Custom time formats also apply to exported html and ascii.
101 ;; - Bug fixes.
103 ;; Version 4.56
104 ;; - `C-k' in agenda kills current line and corresponding subtree in file.
105 ;; - XEmacs compatibility issues fixed, in particular tag alignment.
106 ;; - M-left/right now in/outdents plain list items, no Shift needed.
107 ;; - Bug fixes.
109 ;;; Code:
111 ;;;; Require other packages
113 (eval-when-compile
114 (require 'cl)
115 (require 'gnus-sum)
116 (require 'calendar))
117 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
118 ;; the file noutline.el being loaded.
119 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
120 ;; We require noutline, which might be provided in outline.el
121 (require 'outline) (require 'noutline)
122 ;; Other stuff we need.
123 (require 'time-date)
124 (require 'easymenu)
126 ;;;; Customization variables
128 ;;; Version
130 (defvar org-version "4.60"
131 "The version number of the file org.el.")
132 (defun org-version ()
133 (interactive)
134 (message "Org-mode version %s" org-version))
136 ;;; Compatibility constants
137 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
138 (defconst org-format-transports-properties-p
139 (let ((x "a"))
140 (add-text-properties 0 1 '(test t) x)
141 (get-text-property 0 'test (format "%s" x)))
142 "Does format transport text properties?")
144 ;;; The custom variables
146 (defgroup org nil
147 "Outline-based notes management and organizer."
148 :tag "Org"
149 :group 'outlines
150 :group 'hypermedia
151 :group 'calendar)
153 (defgroup org-startup nil
154 "Options concerning startup of Org-mode."
155 :tag "Org Startup"
156 :group 'org)
158 (defcustom org-startup-folded t
159 "Non-nil means, entering Org-mode will switch to OVERVIEW.
160 This can also be configured on a per-file basis by adding one of
161 the following lines anywhere in the buffer:
163 #+STARTUP: fold
164 #+STARTUP: nofold
165 #+STARTUP: content"
166 :group 'org-startup
167 :type '(choice
168 (const :tag "nofold: show all" nil)
169 (const :tag "fold: overview" t)
170 (const :tag "content: all headlines" content)))
172 (defcustom org-startup-truncated t
173 "Non-nil means, entering Org-mode will set `truncate-lines'.
174 This is useful since some lines containing links can be very long and
175 uninteresting. Also tables look terrible when wrapped."
176 :group 'org-startup
177 :type 'boolean)
179 (defcustom org-startup-align-all-tables nil
180 "Non-nil means, align all tables when visiting a file.
181 This is useful when the column width in tables is forced with <N> cookies
182 in table fields. Such tables will look correct only after the first re-align.
183 This can also be configured on a per-file basis by adding one of
184 the following lines anywhere in the buffer:
185 #+STARTUP: align
186 #+STARTUP: noalign"
187 :group 'org-startup
188 :type 'boolean)
190 (defcustom org-startup-with-deadline-check nil
191 "Non-nil means, entering Org-mode will run the deadline check.
192 This means, if you start editing an org file, you will get an
193 immediate reminder of any due deadlines.
194 This can also be configured on a per-file basis by adding one of
195 the following lines anywhere in the buffer:
196 #+STARTUP: dlcheck
197 #+STARTUP: nodlcheck"
198 :group 'org-startup
199 :type 'boolean)
201 (defcustom org-insert-mode-line-in-empty-file nil
202 "Non-nil means insert the first line setting Org-mode in empty files.
203 When the function `org-mode' is called interactively in an empty file, this
204 normally means that the file name does not automatically trigger Org-mode.
205 To ensure that the file will always be in Org-mode in the future, a
206 line enforcing Org-mode will be inserted into the buffer, if this option
207 has been set."
208 :group 'org-startup
209 :type 'boolean)
211 (defcustom org-CUA-compatible nil
212 "Non-nil means use alternative key bindings for S-<cursor movement>.
213 Org-mode used S-<cursor movement> for changing timestamps and priorities.
214 S-<cursor movement> is also used for example by `CUA-mode' to select text.
215 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
216 alternative bindings. Setting this variable to t will replace the following
217 keys both in Org-mode and in the Org-agenda buffer.
219 S-RET -> C-S-RET
220 S-up -> M-p
221 S-down -> M-n
222 S-left -> M--
223 S-right -> M-+
225 If you do not like the alternative keys, take a look at the variable
226 `org-disputed-keys'.
228 This option is only relevant at load-time of Org-mode, and must be set
229 *before* org.el is loaded. Changing it requires a restart of Emacs to
230 become effective."
231 :group 'org-startup
232 :type 'boolean)
234 (defvar org-disputed-keys
235 '((S-up [(shift up)] [(meta ?p)])
236 (S-down [(shift down)] [(meta ?n)])
237 (S-left [(shift left)] [(meta ?-)])
238 (S-right [(shift right)] [(meta ?+)])
239 (S-return [(shift return)] [(control shift return)]))
240 "Keys for which Org-mode and other modes compete.
241 This is an alist, cars are symbols for lookup, 1st element is the default key,
242 second element will be used when `org-CUA-compatible' is t.")
244 (defun org-key (key)
245 "Select a key according to `org-CUA-compatible'."
246 (nth (if org-CUA-compatible 2 1)
247 (or (assq key org-disputed-keys)
248 (error "Invalid Key %s in `org-key'" key))))
250 (defcustom org-ellipsis nil
251 "The ellipsis to use in the Org-mode outline.
252 When nil, just use the standard three dots. When a string, use that instead,
253 and just in Org-mode (which will then use its own display table).
254 Changing this requires executing `M-x org-mode' in a buffer to become
255 effective."
256 :group 'org-startup
257 :type '(choice (const :tag "Default" nil)
258 (string :tag "String" :value "...#")))
260 (defvar org-display-table nil
261 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
263 (defgroup org-keywords nil
264 "Keywords in Org-mode."
265 :tag "Org Keywords"
266 :group 'org)
268 (defcustom org-deadline-string "DEADLINE:"
269 "String to mark deadline entries.
270 A deadline is this string, followed by a time stamp. Should be a word,
271 terminated by a colon. You can insert a schedule keyword and
272 a timestamp with \\[org-deadline].
273 Changes become only effective after restarting Emacs."
274 :group 'org-keywords
275 :type 'string)
277 (defcustom org-scheduled-string "SCHEDULED:"
278 "String to mark scheduled TODO entries.
279 A schedule is this string, followed by a time stamp. Should be a word,
280 terminated by a colon. You can insert a schedule keyword and
281 a timestamp with \\[org-schedule].
282 Changes become only effective after restarting Emacs."
283 :group 'org-keywords
284 :type 'string)
286 (defcustom org-closed-string "CLOSED:"
287 "String used as the prefix for timestamps logging closing a TODO entry."
288 :group 'org-keywords
289 :type 'string)
291 (defcustom org-clock-string "CLOCK:"
292 "String used as prefix for timestamps clocking work hours on an item."
293 :group 'org-keywords
294 :type 'string)
296 (defcustom org-comment-string "COMMENT"
297 "Entries starting with this keyword will never be exported.
298 An entry can be toggled between COMMENT and normal with
299 \\[org-toggle-comment].
300 Changes become only effective after restarting Emacs."
301 :group 'org-keywords
302 :type 'string)
304 (defcustom org-quote-string "QUOTE"
305 "Entries starting with this keyword will be exported in fixed-width font.
306 Quoting applies only to the text in the entry following the headline, and does
307 not extend beyond the next headline, even if that is lower level.
308 An entry can be toggled between QUOTE and normal with
309 \\[org-toggle-fixed-width-section]."
310 :group 'org-keywords
311 :type 'string)
313 (defvar org-repeat-re "\\<REPEAT(\\([-+ 0-9dwmy]+\\))"
314 "Regular expression for specifying repeated events.
315 After a match, group 1 contains the repeat expression.")
317 (defgroup org-structure nil
318 "Options concerning the general structure of Org-mode files."
319 :tag "Org Structure"
320 :group 'org)
322 (defgroup org-reveal-location nil
323 "Options about how to make context of a location visible."
324 :tag "Org Reveal Location"
325 :group 'org-structure)
327 (defcustom org-show-hierarchy-above '((default . t))
328 "Non-nil means, show full hierarchy when revealing a location.
329 Org-mode often shows locations in an org-mode file which might have
330 been invisible before. When this is set, the hierarchy of headings
331 above the exposed location is shown.
332 Turning this off for example for sparse trees makes them very compact.
333 Instead of t, this can also be an alist specifying this option for different
334 contexts. Valid contexts are
335 agenda when exposing an entry from the agenda
336 org-goto when using the command `org-goto' on key C-c C-j
337 occur-tree when using the command `org-occur' on key C-c /
338 tags-tree when constructing a sparse tree based on tags matches
339 link-search when exposing search matches associated with a link
340 mark-goto when exposing the jump goal of a mark
341 bookmark-jump when exposing a bookmark location
342 isearch when exiting from an incremental search
343 default default for all contexts not set explicitly"
344 :group 'org-reveal-location
345 :type '(choice
346 (const :tag "Always" t)
347 (const :tag "Never" nil)
348 (repeat :greedy t :tag "Individual contexts"
349 (cons
350 (choice :tag "Context"
351 (const agenda)
352 (const org-goto)
353 (const occur-tree)
354 (const tags-tree)
355 (const link-search)
356 (const mark-goto)
357 (const bookmark-jump)
358 (const isearch)
359 (const default))
360 (boolean)))))
362 (defcustom org-show-following-heading '((default . t))
363 "Non-nil means, show following heading when revealing a location.
364 Org-mode often shows locations in an org-mode file which might have
365 been invisible before. When this is set, the heading following the
366 match is shown.
367 Turning this off for example for sparse trees makes them very compact,
368 but makes it harder to edit the location of the match. In such a case,
369 use the command \\[org-reveal] to show more context.
370 Instead of t, this can also be an alist specifying this option for different
371 contexts. See `org-show-hierarchy-above' for valid contexts."
372 :group 'org-reveal-location
373 :type '(choice
374 (const :tag "Always" t)
375 (const :tag "Never" nil)
376 (repeat :greedy t :tag "Individual contexts"
377 (cons
378 (choice :tag "Context"
379 (const agenda)
380 (const org-goto)
381 (const occur-tree)
382 (const tags-tree)
383 (const link-search)
384 (const mark-goto)
385 (const bookmark-jump)
386 (const isearch)
387 (const default))
388 (boolean)))))
390 (defcustom org-show-siblings '((default . nil) (isearch t))
391 "Non-nil means, show all sibling heading when revealing a location.
392 Org-mode often shows locations in an org-mode file which might have
393 been invisible before. When this is set, the sibling of the current entry
394 heading are all made visible. If `org-show-hierarchy-above' is t,
395 the same happens on each level of the hierarchy above the current entry.
397 By default this is on for the isearch context, off for all other contexts.
398 Turning this off for example for sparse trees makes them very compact,
399 but makes it harder to edit the location of the match. In such a case,
400 use the command \\[org-reveal] to show more context.
401 Instead of t, this can also be an alist specifying this option for different
402 contexts. See `org-show-hierarchy-above' for valid contexts."
403 :group 'org-reveal-location
404 :type '(choice
405 (const :tag "Always" t)
406 (const :tag "Never" nil)
407 (repeat :greedy t :tag "Individual contexts"
408 (cons
409 (choice :tag "Context"
410 (const agenda)
411 (const org-goto)
412 (const occur-tree)
413 (const tags-tree)
414 (const link-search)
415 (const mark-goto)
416 (const bookmark-jump)
417 (const isearch)
418 (const default))
419 (boolean)))))
421 (defgroup org-cycle nil
422 "Options concerning visibility cycling in Org-mode."
423 :tag "Org Cycle"
424 :group 'org-structure)
426 (defcustom org-cycle-global-at-bob t
427 "Cycle globally if cursor is at beginning of buffer and not at a headline.
428 This makes it possible to do global cycling without having to use S-TAB or
429 C-u TAB. For this special case to work, the first line of the buffer
430 must not be a headline - it may be empty ot some other text. When used in
431 this way, `org-cycle-hook' is disables temporarily, to make sure the
432 cursor stays at the beginning of the buffer.
433 When this option is nil, don't do anything special at the beginning
434 of the buffer."
435 :group 'org-cycle
436 :type 'boolean)
438 (defcustom org-cycle-emulate-tab t
439 "Where should `org-cycle' emulate TAB.
440 nil Never
441 white Only in completely white lines
442 whitestart Only at the beginning of lines, before the first non-white char.
443 t Everywhere except in headlines
444 If TAB is used in a place where it does not emulate TAB, the current subtree
445 visibility is cycled."
446 :group 'org-cycle
447 :type '(choice (const :tag "Never" nil)
448 (const :tag "Only in completely white lines" white)
449 (const :tag "Before first char in a line" whitestart)
450 (const :tag "Everywhere except in headlines" t)
453 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
454 org-optimize-window-after-visibility-change)
455 "Hook that is run after `org-cycle' has changed the buffer visibility.
456 The function(s) in this hook must accept a single argument which indicates
457 the new state that was set by the most recent `org-cycle' command. The
458 argument is a symbol. After a global state change, it can have the values
459 `overview', `content', or `all'. After a local state change, it can have
460 the values `folded', `children', or `subtree'."
461 :group 'org-cycle
462 :type 'hook)
465 (defgroup org-edit-structure nil
466 "Options concerning structure editing in Org-mode."
467 :tag "Org Edit Structure"
468 :group 'org-structure)
470 (defcustom org-odd-levels-only nil
471 "Non-nil means, skip even levels and only use odd levels for the outline.
472 This has the effect that two stars are being added/taken away in
473 promotion/demotion commands. It also influences how levels are
474 handled by the exporters.
475 Changing it requires restart of `font-lock-mode' to become effective
476 for fontification also in regions already fontified.
477 You may also set this on a per-file basis by adding one of the following
478 lines to the buffer:
480 #+STARTUP: odd
481 #+STARTUP: oddeven"
482 :group 'org-edit-structure
483 :group 'org-font-lock
484 :type 'boolean)
486 (defcustom org-adapt-indentation t
487 "Non-nil means, adapt indentation when promoting and demoting.
488 When this is set and the *entire* text in an entry is indented, the
489 indentation is increased by one space in a demotion command, and
490 decreased by one in a promotion command. If any line in the entry
491 body starts at column 0, indentation is not changed at all."
492 :group 'org-edit-structure
493 :type 'boolean)
495 (defcustom org-blank-before-new-entry '((heading . nil)
496 (plain-list-item . nil))
497 "Should `org-insert-heading' leave a blank line before new heading/item?
498 The value is an alist, with `heading' and `plain-list-item' as car,
499 and a boolean flag as cdr."
500 :group 'org-edit-structure
501 :type '(list
502 (cons (const heading) (boolean))
503 (cons (const plain-list-item) (boolean))))
505 (defcustom org-insert-heading-hook nil
506 "Hook being run after inserting a new heading."
507 :group 'org-edit-structure
508 :type 'boolean)
510 (defcustom org-enable-fixed-width-editor t
511 "Non-nil means, lines starting with \":\" are treated as fixed-width.
512 This currently only means, they are never auto-wrapped.
513 When nil, such lines will be treated like ordinary lines.
514 See also the QUOTE keyword."
515 :group 'org-edit-structure
516 :type 'boolean)
518 (defgroup org-sparse-trees nil
519 "Options concerning sparse trees in Org-mode."
520 :tag "Org Sparse Trees"
521 :group 'org-structure)
523 (defcustom org-highlight-sparse-tree-matches t
524 "Non-nil means, highlight all matches that define a sparse tree.
525 The highlights will automatically disappear the next time the buffer is
526 changed by an edit command."
527 :group 'org-sparse-trees
528 :type 'boolean)
530 (defcustom org-remove-highlights-with-change t
531 "Non-nil means, any change to the buffer will remove temporary highlights.
532 Such highlights are created by `org-occur' and `org-clock-display'.
533 When nil, `C-c C-c needs to be used to get rid of the highlights.
534 The highlights created by `org-preview-latex-fragment' always need
535 `C-c C-c' to be removed."
536 :group 'org-sparse-trees
537 :group 'org-time
538 :type 'boolean)
541 (defcustom org-occur-hook '(org-first-headline-recenter)
542 "Hook that is run after `org-occur' has constructed a sparse tree.
543 This can be used to recenter the window to show as much of the structure
544 as possible."
545 :group 'org-sparse-trees
546 :type 'hook)
548 (defgroup org-plain-lists nil
549 "Options concerning plain lists in Org-mode."
550 :tag "Org Plain lists"
551 :group 'org-structure)
553 (defcustom org-cycle-include-plain-lists nil
554 "Non-nil means, include plain lists into visibility cycling.
555 This means that during cycling, plain list items will *temporarily* be
556 interpreted as outline headlines with a level given by 1000+i where i is the
557 indentation of the bullet. In all other operations, plain list items are
558 not seen as headlines. For example, you cannot assign a TODO keyword to
559 such an item."
560 :group 'org-plain-lists
561 :type 'boolean)
563 (defcustom org-plain-list-ordered-item-terminator t
564 "The character that makes a line with leading number an ordered list item.
565 Valid values are ?. and ?\). To get both terminators, use t. While
566 ?. may look nicer, it creates the danger that a line with leading
567 number may be incorrectly interpreted as an item. ?\) therefore is
568 the safe choice."
569 :group 'org-plain-lists
570 :type '(choice (const :tag "dot like in \"2.\"" ?.)
571 (const :tag "paren like in \"2)\"" ?\))
572 (const :tab "both" t)))
574 (defcustom org-auto-renumber-ordered-lists t
575 "Non-nil means, automatically renumber ordered plain lists.
576 Renumbering happens when the sequence have been changed with
577 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
578 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
579 :group 'org-plain-lists
580 :type 'boolean)
582 (defcustom org-provide-checkbox-statistics t
583 "Non-nil means, update checkbox statistics after insert and toggle.
584 When this is set, checkbox statistics is updated each time you either insert
585 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
586 with \\[org-ctrl-c-ctrl-c\\]."
587 :group 'org-plain-lists
588 :type 'boolean)
590 (defgroup org-archive nil
591 "Options concerning archiving in Org-mode."
592 :tag "Org Archive"
593 :group 'org-structure)
595 (defcustom org-archive-tag "ARCHIVE"
596 "The tag that marks a subtree as archived.
597 An archived subtree does not open during visibility cycling, and does
598 not contribute to the agenda listings."
599 :group 'org-archive
600 :group 'org-keywords
601 :type 'string)
603 (defcustom org-agenda-skip-archived-trees t
604 "Non-nil means, the agenda will skip any items located in archived trees.
605 An archived tree is a tree marked with the tag ARCHIVE."
606 :group 'org-archive
607 :group 'org-agenda-skip
608 :type 'boolean)
610 (defcustom org-cycle-open-archived-trees nil
611 "Non-nil means, `org-cycle' will open archived trees.
612 An archived tree is a tree marked with the tag ARCHIVE.
613 When nil, archived trees will stay folded. You can still open them with
614 normal outline commands like `show-all', but not with the cycling commands."
615 :group 'org-archive
616 :group 'org-cycle
617 :type 'boolean)
619 (defcustom org-sparse-tree-open-archived-trees nil
620 "Non-nil means sparse tree construction shows matches in archived trees.
621 When nil, matches in these trees are highlighted, but the trees are kept in
622 collapsed state."
623 :group 'org-archive
624 :group 'org-sparse-trees
625 :type 'boolean)
627 (defcustom org-archive-location "%s_archive::"
628 "The location where subtrees should be archived.
629 This string consists of two parts, separated by a double-colon.
631 The first part is a file name - when omitted, archiving happens in the same
632 file. %s will be replaced by the current file name (without directory part).
633 Archiving to a different file is useful to keep archived entries from
634 contributing to the Org-mode Agenda.
636 The part after the double colon is a headline. The archived entries will be
637 filed under that headline. When omitted, the subtrees are simply filed away
638 at the end of the file, as top-level entries.
640 Here are a few examples:
641 \"%s_archive::\"
642 If the current file is Projects.org, archive in file
643 Projects.org_archive, as top-level trees. This is the default.
645 \"::* Archived Tasks\"
646 Archive in the current file, under the top-level headline
647 \"* Archived Tasks\".
649 \"~/org/archive.org::\"
650 Archive in file ~/org/archive.org (absolute path), as top-level trees.
652 \"basement::** Finished Tasks\"
653 Archive in file ./basement (relative path), as level 3 trees
654 below the level 2 heading \"** Finished Tasks\".
656 You may set this option on a per-file basis by adding to the buffer a
657 line like
659 #+ARCHIVE: basement::** Finished Tasks"
660 :group 'org-archive
661 :type 'string)
663 (defcustom org-archive-mark-done t
664 "Non-nil means, mark entries as DONE when they are moved to the archive file."
665 :group 'org-archive
666 :type 'boolean)
668 (defcustom org-archive-stamp-time t
669 "Non-nil means, add a time stamp to entries moved to an archive file.
670 The time stamp will be added directly after the TODO state keyword in the
671 first line, so it is probably best to use this in combinations with
672 `org-archive-mark-done'."
673 :group 'org-archive
674 :type 'boolean)
676 (defgroup org-table nil
677 "Options concerning tables in Org-mode."
678 :tag "Org Table"
679 :group 'org)
681 (defcustom org-enable-table-editor 'optimized
682 "Non-nil means, lines starting with \"|\" are handled by the table editor.
683 When nil, such lines will be treated like ordinary lines.
685 When equal to the symbol `optimized', the table editor will be optimized to
686 do the following:
687 - Automatic overwrite mode in front of whitespace in table fields.
688 This makes the structure of the table stay in tact as long as the edited
689 field does not exceed the column width.
690 - Minimize the number of realigns. Normally, the table is aligned each time
691 TAB or RET are pressed to move to another field. With optimization this
692 happens only if changes to a field might have changed the column width.
693 Optimization requires replacing the functions `self-insert-command',
694 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
695 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
696 very good at guessing when a re-align will be necessary, but you can always
697 force one with \\[org-ctrl-c-ctrl-c].
699 If you would like to use the optimized version in Org-mode, but the
700 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
702 This variable can be used to turn on and off the table editor during a session,
703 but in order to toggle optimization, a restart is required.
705 See also the variable `org-table-auto-blank-field'."
706 :group 'org-table
707 :type '(choice
708 (const :tag "off" nil)
709 (const :tag "on" t)
710 (const :tag "on, optimized" optimized)))
712 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
713 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
714 In the optimized version, the table editor takes over all simple keys that
715 normally just insert a character. In tables, the characters are inserted
716 in a way to minimize disturbing the table structure (i.e. in overwrite mode
717 for empty fields). Outside tables, the correct binding of the keys is
718 restored.
720 The default for this option is t if the optimized version is also used in
721 Org-mode. See the variable `org-enable-table-editor' for details. Changing
722 this variable requires a restart of Emacs to become effective."
723 :group 'org-table
724 :type 'boolean)
726 (defgroup org-table-settings nil
727 "Settings for tables in Org-mode."
728 :tag "Org Table Settings"
729 :group 'org-table)
731 (defcustom org-table-default-size "5x2"
732 "The default size for newly created tables, Columns x Rows."
733 :group 'org-table-settings
734 :type 'string)
736 (defcustom org-table-number-regexp
737 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$"
738 "Regular expression for recognizing numbers in table columns.
739 If a table column contains mostly numbers, it will be aligned to the
740 right. If not, it will be aligned to the left.
742 The default value of this option is a regular expression which allows
743 anything which looks remotely like a number as used in scientific
744 context. For example, all of the following will be considered a
745 number:
746 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
748 Other options offered by the customize interface are more restrictive."
749 :group 'org-table-settings
750 :type '(choice
751 (const :tag "Positive Integers"
752 "^[0-9]+$")
753 (const :tag "Integers"
754 "^[-+]?[0-9]+$")
755 (const :tag "Floating Point Numbers"
756 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
757 (const :tag "Floating Point Number or Integer"
758 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
759 (const :tag "Exponential, Floating point, Integer"
760 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
761 (const :tag "Very General Number-Like, including hex"
762 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$")
763 (string :tag "Regexp:")))
765 (defcustom org-table-number-fraction 0.5
766 "Fraction of numbers in a column required to make the column align right.
767 In a column all non-white fields are considered. If at least this
768 fraction of fields is matched by `org-table-number-fraction',
769 alignment to the right border applies."
770 :group 'org-table-settings
771 :type 'number)
773 (defgroup org-table-editing nil
774 "Bahavior of tables during editing in Org-mode."
775 :tag "Org Table Editing"
776 :group 'org-table)
778 (defcustom org-table-automatic-realign t
779 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
780 When nil, aligning is only done with \\[org-table-align], or after column
781 removal/insertion."
782 :group 'org-table-editing
783 :type 'boolean)
785 (defcustom org-table-limit-column-width t ;kw
786 "Non-nil means, allow to limit the width of table columns with <N> fields."
787 :group 'org-table-editing
788 :type 'boolean)
790 (defcustom org-table-auto-blank-field t
791 "Non-nil means, automatically blank table field when starting to type into it.
792 This only happens when typing immediately after a field motion
793 command (TAB, S-TAB or RET).
794 Only relevant when `org-enable-table-editor' is equal to `optimized'."
795 :group 'org-table-editing
796 :type 'boolean)
798 (defcustom org-table-tab-jumps-over-hlines t
799 "Non-nil means, tab in the last column of a table with jump over a hline.
800 If a horizontal separator line is following the current line,
801 `org-table-next-field' can either create a new row before that line, or jump
802 over the line. When this option is nil, a new line will be created before
803 this line."
804 :group 'org-table-editing
805 :type 'boolean)
807 (defcustom org-table-tab-recognizes-table.el t
808 "Non-nil means, TAB will automatically notice a table.el table.
809 When it sees such a table, it moves point into it and - if necessary -
810 calls `table-recognize-table'."
811 :group 'org-table-editing
812 :type 'boolean)
814 (defgroup org-table-calculation nil
815 "Options concerning tables in Org-mode."
816 :tag "Org Table Calculation"
817 :group 'org-table)
819 (defcustom org-table-copy-increment t
820 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
821 :group 'org-table-calculation
822 :type 'boolean)
824 (defcustom org-calc-default-modes
825 '(calc-internal-prec 12
826 calc-float-format (float 5)
827 calc-angle-mode deg
828 calc-prefer-frac nil
829 calc-symbolic-mode nil
830 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
831 calc-display-working-message t
833 "List with Calc mode settings for use in calc-eval for table formulas.
834 The list must contain alternating symbols (Calc modes variables and values).
835 Don't remove any of the default settings, just change the values. Org-mode
836 relies on the variables to be present in the list."
837 :group 'org-table-calculation
838 :type 'plist)
840 (defcustom org-table-formula-evaluate-inline t
841 "Non-nil means, TAB and RET evaluate a formula in current table field.
842 If the current field starts with an equal sign, it is assumed to be a formula
843 which should be evaluated as described in the manual and in the documentation
844 string of the command `org-table-eval-formula'. This feature requires the
845 Emacs calc package.
846 When this variable is nil, formula calculation is only available through
847 the command \\[org-table-eval-formula]."
848 :group 'org-table-calculation
849 :type 'boolean)
852 (defcustom org-table-formula-use-constants t
853 "Non-nil means, interpret constants in formulas in tables.
854 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
855 by the value given in `org-table-formula-constants', or by a value obtained
856 from the `constants.el' package."
857 :group 'org-table-calculation
858 :type 'boolean)
860 (defcustom org-table-formula-constants nil
861 "Alist with constant names and values, for use in table formulas.
862 The car of each element is a name of a constant, without the `$' before it.
863 The cdr is the value as a string. For example, if you'd like to use the
864 speed of light in a formula, you would configure
866 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
868 and then use it in an equation like `$1*$c'."
869 :group 'org-table-calculation
870 :type '(repeat
871 (cons (string :tag "name")
872 (string :tag "value"))))
874 (defcustom org-table-formula-numbers-only nil
875 "Non-nil means, calculate only with numbers in table formulas.
876 Then all input fields will be converted to a number, and the result
877 must also be a number. When nil, calc's full potential is available
878 in table calculations, including symbolics etc."
879 :group 'org-table-calculation
880 :type 'boolean)
882 (defcustom org-table-allow-automatic-line-recalculation t
883 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
884 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
885 :group 'org-table-calculation
886 :type 'boolean)
888 (defgroup org-link nil
889 "Options concerning links in Org-mode."
890 :tag "Org Link"
891 :group 'org)
893 (defvar org-link-abbrev-alist-local nil
894 "buffer-local version of `org-link-abbrev-alist', which see.
895 The value of this is taken from the #+LINK lines.")
896 (make-variable-buffer-local 'org-link-abbrev-alist-local)
898 (defcustom org-link-abbrev-alist nil
899 "Alist of link abbreviations.
900 The car of each element is a string, to be replaced at the start of a link.
901 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
902 links in Org-mode buffers can have an optional tag after a double colon, e.g.
904 [[linkkey::tag][description]]
906 If REPLACE is a string, the tag will simply be appended to create the link.
907 If the string contains \"%s\", the tag will be inserted there. REPLACE may
908 also be a function that will be called with the tag as the only argument to
909 create the link. See the manual for examples."
910 :group 'org-link
911 :type 'alist)
913 (defcustom org-descriptive-links t
914 "Non-nil means, hide link part and only show description of bracket links.
915 Bracket links are like [[link][descritpion]]. This variable sets the initial
916 state in new org-mode buffers. The setting can then be toggled on a
917 per-buffer basis from the Org->Hyperlinks menu."
918 :group 'org-link
919 :type 'boolean)
921 (defcustom org-link-style 'bracket
922 "The style of links to be inserted with \\[org-insert-link].
923 Possible values are:
924 bracket [[link][description]]. This is recommended
925 plain Description \\n link. The old way, no longer recommended."
926 :group 'org-link
927 :type '(choice
928 (const :tag "Bracket (recommended)" bracket)
929 (const :tag "Plain (no longer recommended)" plain)))
931 (defcustom org-link-format "%s"
932 "Default format for external, URL-like linkes in the buffer.
933 This is a format string for printf, %s will be replaced by the link text.
934 The recommended value is just \"%s\", since links will be protected by
935 enclosing them in double brackets. If you prefer plain links (see variable
936 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
937 additional URL: prefix, so the format would be \"<URL:%s>\"."
938 :group 'org-link
939 :type '(choice
940 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
941 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
942 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
943 (string :tag "Other" :value "<%s>")))
945 (defcustom org-link-file-path-type 'adaptive
946 "How the path name in file links should be stored.
947 Valid values are:
949 relative relative to the current directory, i.e. the directory of the file
950 into which the link is being inserted.
951 absolute absolute path, if possible with ~ for home directory.
952 noabbrev absolute path, no abbreviation of home directory.
953 adaptive Use relative path for files in the current directory and sub-
954 directories of it. For other files, use an absolute path."
955 :group 'org-link
956 :type '(choice
957 (const relative)
958 (const absolute)
959 (const noabbrev)
960 (const adaptive)))
962 (defcustom org-activate-links '(bracket angle plain radio tag date)
963 "Types of links that should be activated in Org-mode files.
964 This is a list of symbols, each leading to the activation of a certain link
965 type. In principle, it does not hurt to turn on most link types - there may
966 be a small gain when turning off unused link types. The types are:
968 bracket The recommended [[link][description]] or [[link]] links with hiding.
969 angular Links in angular brackes that may contain whitespace like
970 <bbdb:Carsten Dominik>.
971 plain Plain links in normal text, no whitespace, like http://google.com.
972 radio Text that is matched by a radio target, see manual for details.
973 tag Tag settings in a headline (link to tag search).
974 date Time stamps (link to calendar).
975 camel CamelCase words defining text searches.
977 Changing this variable requires a restart of Emacs to become effective."
978 :group 'org-link
979 :type '(set (const :tag "Double bracket links (new style)" bracket)
980 (const :tag "Angular bracket links (old style)" angular)
981 (const :tag "plain text links" plain)
982 (const :tag "Radio target matches" radio)
983 (const :tag "Tags" tag)
984 (const :tag "Timestamps" date)
985 (const :tag "CamelCase words" camel)))
987 (defgroup org-link-store nil
988 "Options concerning storing links in Org-mode"
989 :tag "Org Store Link"
990 :group 'org-link)
992 (defcustom org-context-in-file-links t
993 "Non-nil means, file links from `org-store-link' contain context.
994 A search string will be added to the file name with :: as separator and
995 used to find the context when the link is activated by the command
996 `org-open-at-point'.
997 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
998 negates this setting for the duration of the command."
999 :group 'org-link-store
1000 :type 'boolean)
1002 (defcustom org-file-link-context-use-camel-case nil
1003 "Non-nil means, use CamelCase to store a search context in a file link.
1004 When nil, the search string simply consists of the words of the string.
1005 CamelCase is deprecated, and support for it may be dropped in the future."
1006 :group 'org-link-store
1007 :type 'boolean)
1009 (defcustom org-keep-stored-link-after-insertion nil
1010 "Non-nil means, keep link in list for entire session.
1012 The command `org-store-link' adds a link pointing to the current
1013 location to an internal list. These links accumulate during a session.
1014 The command `org-insert-link' can be used to insert links into any
1015 Org-mode file (offering completion for all stored links). When this
1016 option is nil, every link which has been inserted once using \\[org-insert-link]
1017 will be removed from the list, to make completing the unused links
1018 more efficient."
1019 :group 'org-link-store
1020 :type 'boolean)
1022 (defcustom org-usenet-links-prefer-google nil
1023 "Non-nil means, `org-store-link' will create web links to Google groups.
1024 When nil, Gnus will be used for such links.
1025 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1026 negates this setting for the duration of the command."
1027 :group 'org-link-store
1028 :type 'boolean)
1030 (defgroup org-link-follow nil
1031 "Options concerning following links in Org-mode"
1032 :tag "Org Follow Link"
1033 :group 'org-link)
1035 (defcustom org-tab-follows-link nil
1036 "Non-nil means, on links TAB will follow the link.
1037 Needs to be set before org.el is loaded."
1038 :group 'org-link-follow
1039 :type 'boolean)
1041 (defcustom org-return-follows-link nil
1042 "Non-nil means, on links RET will follow the link.
1043 Needs to be set before org.el is loaded."
1044 :group 'org-link-follow
1045 :type 'boolean)
1047 (defcustom org-mouse-1-follows-link t
1048 "Non-nil means, mouse-1 on a link will follow the link.
1049 A longer mouse click will still set point. Does not wortk on XEmacs.
1050 Needs to be set before org.el is loaded."
1051 :group 'org-link-follow
1052 :type 'boolean)
1054 (defcustom org-mark-ring-length 4
1055 "Number of different positions to be recorded in the ring
1056 Changing this requires a restart of Emacs to work correctly."
1057 :group 'org-link-follow
1058 :type 'interger)
1060 (defcustom org-link-frame-setup
1061 '((vm . vm-visit-folder-other-frame)
1062 (gnus . gnus-other-frame)
1063 (file . find-file-other-window))
1064 "Setup the frame configuration for following links.
1065 When following a link with Emacs, it may often be useful to display
1066 this link in another window or frame. This variable can be used to
1067 set this up for the different types of links.
1068 For VM, use any of
1069 `vm-visit-folder'
1070 `vm-visit-folder-other-frame'
1071 For Gnus, use any of
1072 `gnus'
1073 `gnus-other-frame'
1074 For FILE, use any of
1075 `find-file'
1076 `find-file-other-window'
1077 `find-file-other-frame'
1078 For the calendar, use the variable `calendar-setup'.
1079 For BBDB, it is currently only possible to display the matches in
1080 another window."
1081 :group 'org-link-follow
1082 :type '(list
1083 (cons (const vm)
1084 (choice
1085 (const vm-visit-folder)
1086 (const vm-visit-folder-other-window)
1087 (const vm-visit-folder-other-frame)))
1088 (cons (const gnus)
1089 (choice
1090 (const gnus)
1091 (const gnus-other-frame)))
1092 (cons (const file)
1093 (choice
1094 (const find-file)
1095 (const find-file-other-window)
1096 (const find-file-other-frame)))))
1098 (defcustom org-display-internal-link-with-indirect-buffer nil
1099 "Non-nil means, use indirect buffer to display infile links.
1100 Activating internal links (from one location in a file to another location
1101 in the same file) normally just jumps to the location. When the link is
1102 activated with a C-u prefix (or with mouse-3), the link is displayed in
1103 another window. When this option is set, the other window actually displays
1104 an indirect buffer clone of the current buffer, to avoid any visibility
1105 changes to the current buffer."
1106 :group 'org-link-follow
1107 :type 'boolean)
1110 (defcustom org-open-non-existing-files nil
1111 "Non-nil means, `org-open-file' will open non-existing file.
1112 When nil, an error will be generated."
1113 :group 'org-link-follow
1114 :type 'boolean)
1116 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1117 "Function and arguments to call for following mailto links.
1118 This is a list with the first element being a lisp function, and the
1119 remaining elements being arguments to the function. In string arguments,
1120 %a will be replaced by the address, and %s will be replaced by the subject
1121 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1122 :group 'org-link-follow
1123 :type '(choice
1124 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1125 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1126 (const :tag "message-mail" (message-mail "%a" "%s"))
1127 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1129 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1130 "Non-nil means, ask for confirmation before executing shell links.
1131 Shell links can be dangerous, just thing about a link
1133 [[shell:rm -rf ~/*][Google Search]]
1135 This link would show up in your Org-mode document as \"Google Search\"
1136 but really it would remove your entire home directory.
1137 Therefore I *definitely* advise against setting this variable to nil.
1138 Just change it to `y-or-n-p' of you want to confirm with a single key press
1139 rather than having to type \"yes\"."
1140 :group 'org-link-follow
1141 :type '(choice
1142 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1143 (const :tag "with y-or-n (faster)" y-or-n-p)
1144 (const :tag "no confirmation (dangerous)" nil)))
1146 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1147 "Non-nil means, ask for confirmation before executing elisp links.
1148 Elisp links can be dangerous, just think about a link
1150 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1152 This link would show up in your Org-mode document as \"Google Search\"
1153 but really it would remove your entire home directory.
1154 Therefore I *definitely* advise against setting this variable to nil.
1155 Just change it to `y-or-n-p' of you want to confirm with a single key press
1156 rather than having to type \"yes\"."
1157 :group 'org-link-follow
1158 :type '(choice
1159 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1160 (const :tag "with y-or-n (faster)" y-or-n-p)
1161 (const :tag "no confirmation (dangerous)" nil)))
1163 (defconst org-file-apps-defaults-gnu
1164 '((remote . emacs)
1165 (t . mailcap))
1166 "Default file applications on a UNIX or GNU/Linux system.
1167 See `org-file-apps'.")
1169 (defconst org-file-apps-defaults-macosx
1170 '((remote . emacs)
1171 (t . "open %s")
1172 ("ps" . "gv %s")
1173 ("ps.gz" . "gv %s")
1174 ("eps" . "gv %s")
1175 ("eps.gz" . "gv %s")
1176 ("dvi" . "xdvi %s")
1177 ("fig" . "xfig %s"))
1178 "Default file applications on a MacOS X system.
1179 The system \"open\" is known as a default, but we use X11 applications
1180 for some files for which the OS does not have a good default.
1181 See `org-file-apps'.")
1183 (defconst org-file-apps-defaults-windowsnt
1184 (list
1185 '(remote . emacs)
1186 (cons t
1187 (list (if (featurep 'xemacs)
1188 'mswindows-shell-execute
1189 'w32-shell-execute)
1190 "open" 'file)))
1191 "Default file applications on a Windows NT system.
1192 The system \"open\" is used for most files.
1193 See `org-file-apps'.")
1195 (defcustom org-file-apps
1197 ("txt" . emacs)
1198 ("tex" . emacs)
1199 ("ltx" . emacs)
1200 ("org" . emacs)
1201 ("el" . emacs)
1202 ("bib" . emacs)
1204 "External applications for opening `file:path' items in a document.
1205 Org-mode uses system defaults for different file types, but
1206 you can use this variable to set the application for a given file
1207 extension. The entries in this list are cons cells where the car identifies
1208 files and the cdr the corresponding command. Possible values for the
1209 file identifier are
1210 \"ext\" A string identifying an extension
1211 `directory' Matches a directory
1212 `remote' Matches a remote file, accessible through tramp or efs.
1213 Remote files most likely should be visited through Emacs
1214 because external applications cannot handle such paths.
1215 t Default for all remaining files
1217 Possible values for the command are:
1218 `emacs' The file will be visited by the current Emacs process.
1219 `default' Use the default application for this file type.
1220 string A command to be executed by a shell; %s will be replaced
1221 by the path to the file.
1222 sexp A Lisp form which will be evaluated. The file path will
1223 be available in the Lisp variable `file'.
1224 For more examples, see the system specific constants
1225 `org-file-apps-defaults-macosx'
1226 `org-file-apps-defaults-windowsnt'
1227 `org-file-apps-defaults-gnu'."
1228 :group 'org-link-follow
1229 :type '(repeat
1230 (cons (choice :value ""
1231 (string :tag "Extension")
1232 (const :tag "Default for unrecognized files" t)
1233 (const :tag "Remote file" remote)
1234 (const :tag "Links to a directory" directory))
1235 (choice :value ""
1236 (const :tag "Visit with Emacs" emacs)
1237 (const :tag "Use system default" default)
1238 (string :tag "Command")
1239 (sexp :tag "Lisp form")))))
1241 (defcustom org-mhe-search-all-folders nil
1242 "Non-nil means, that the search for the mh-message will be extended to
1243 all folders if the message cannot be found in the folder given in the link.
1244 Searching all folders is very effective with one of the search engines
1245 supported by MH-E, but will be slow with pick."
1246 :group 'org-link-follow
1247 :type 'boolean)
1249 (defgroup org-remember nil
1250 "Options concerning interaction with remember.el."
1251 :tag "Org Remember"
1252 :group 'org)
1254 (defcustom org-directory "~/org"
1255 "Directory with org files.
1256 This directory will be used as default to prompt for org files.
1257 Used by the hooks for remember.el."
1258 :group 'org-remember
1259 :type 'directory)
1261 (defcustom org-default-notes-file "~/.notes"
1262 "Default target for storing notes.
1263 Used by the hooks for remember.el. This can be a string, or nil to mean
1264 the value of `remember-data-file'."
1265 :group 'org-remember
1266 :type '(choice
1267 (const :tag "Default from remember-data-file" nil)
1268 file))
1270 (defcustom org-remember-templates nil
1271 "Templates for the creation of remember buffers.
1272 When nil, just let remember make the buffer.
1273 When not nil, this is a list of 3-element lists. In each entry, the first
1274 element is a character, a unique key to select this template.
1275 The second element is the template. The third element is optional and can
1276 specify a destination file for remember items created with this template.
1277 The default file is given by `org-default-notes-file'.
1279 The template specifies the structure of the remember buffer. It should have
1280 a first line starting with a star, to act as the org-mode headline.
1281 Furthermore, the following %-escapes will be replaced with content:
1282 %t time stamp, date only
1283 %T time stamp with date and time
1284 %u inactive time stamp, date only
1285 %U inactive time stamp with date and time
1286 %n user name
1287 %a annotation, normally the link created with org-store-link
1288 %i initial content, the region when remember is called with C-u.
1289 If %i is indented, the entire inserted text will be indented as well.
1290 %? This will be removed, and the cursor placed at this position."
1291 :group 'org-remember
1292 :type '(repeat :tag "enabled"
1293 (list :value (?a "\n" nil)
1294 (character :tag "Selection Key")
1295 (string :tag "Template")
1296 (file :tag "Destination file (optional)"))))
1298 (defcustom org-reverse-note-order nil
1299 "Non-nil means, store new notes at the beginning of a file or entry.
1300 When nil, new notes will be filed to the end of a file or entry."
1301 :group 'org-remember
1302 :type '(choice
1303 (const :tag "Reverse always" t)
1304 (const :tag "Reverse never" nil)
1305 (repeat :tag "By file name regexp"
1306 (cons regexp boolean))))
1308 (defgroup org-todo nil
1309 "Options concerning TODO items in Org-mode."
1310 :tag "Org TODO"
1311 :group 'org)
1313 (defgroup org-progress nil
1314 "Options concerning Progress logging in Org-mode."
1315 :tag "Org Progress"
1316 :group 'org-time)
1318 (defcustom org-todo-keywords '("TODO" "DONE")
1319 "List of TODO entry keywords.
1320 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1321 considered to mean that the entry is \"done\". All the other mean that
1322 action is required, and will make the entry show up in todo lists, diaries
1323 etc.
1324 The command \\[org-todo] cycles an entry through these states, and an
1325 additional state where no keyword is present. For details about this
1326 cycling, see also the variable `org-todo-interpretation'
1327 Changes become only effective after restarting Emacs."
1328 :group 'org-todo
1329 :group 'org-keywords
1330 :type '(repeat (string :tag "Keyword")))
1332 (defcustom org-todo-interpretation 'sequence
1333 "Controls how TODO keywords are interpreted.
1334 This variable is only relevant if `org-todo-keywords' contains more than two
1335 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1337 When `sequence', \\[org-todo] will always switch to the next state in the
1338 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1339 to state when executed several times in direct succession. Otherwise, it
1340 switches directly to DONE from any state.
1341 See the manual for more information."
1342 :group 'org-todo
1343 :group 'org-keywords
1344 :type '(choice (const sequence)
1345 (const type)))
1347 (defcustom org-after-todo-state-change-hook nil
1348 "Hook which is run after the state of a TODO item was changed.
1349 The new state (a string with a TODO keyword, or nil) is available in the
1350 Lisp variable `state'."
1351 :group 'org-todo
1352 :type 'hook)
1354 (defcustom org-log-done nil
1355 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1356 When the state of an entry is changed from nothing to TODO, remove a previous
1357 closing date.
1359 This can also be a list of symbols indicating under which conditions
1360 the time stamp recording the action should be annotated with a short note.
1361 Valid members of this list are
1363 done Offer to record a note when marking entries done
1364 state Offer to record a note whenever changing the TODO state
1365 of an item. This is only relevant if TODO keywords are
1366 interpreted as sequence, see variable `org-todo-interpretation'.
1367 When `state' is set, this includes tracking `done'.
1368 clock-out Offer to record a note when clocking out of an item.
1370 A separate window will then pop up and allow you to type a note.
1371 After finishing with C-c C-c, the note will be added directly after the
1372 timestamp, as a plain list item. See also the variable
1373 `org-log-note-headings'.
1375 Logging can also be configured on a per-file basis by adding one of
1376 the following lines anywhere in the buffer:
1378 #+STARTUP: logdone
1379 #+STARTUP: nologging
1380 #+STARTUP: lognotedone
1381 #+STARTUP: lognotestate
1382 #+STARTUP: lognoteclock-out"
1383 :group 'org-todo
1384 :group 'org-progress
1385 :type '(choice
1386 (const :tag "off" nil)
1387 (const :tag "on" t)
1388 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1389 (const :tag "when item is marked DONE" done)
1390 (const :tag "when TODO state changes" state)
1391 (const :tag "when clocking out" clock-out))))
1393 (defcustom org-log-note-headings
1394 '((done . "CLOSING NOTE %t")
1395 (state . "State %-12s %t")
1396 (clock-out . ""))
1397 "Headings for notes added when clocking out or closing TODO items.
1398 The value is an alist, with the car being a sympol indicating the note
1399 context, and the cdr is the heading to be used. The heading may also be the
1400 empty string.
1401 %t in the heading will be replaced by a time stamp.
1402 %s will be replaced by the new TODO state, in double quotes.
1403 %u will be replaced by the user name.
1404 %U will be replaced by the full user name."
1405 :group 'org-todo
1406 :group 'org-progress
1407 :type '(list :greedy t
1408 (cons (const :tag "Heading when closing an item" done) string)
1409 (cons (const :tag
1410 "Heading when changing todo state (todo sequence only)"
1411 state) string)
1412 (cons (const :tag "Heading when clocking out" clock-out) string)))
1414 (defgroup org-priorities nil
1415 "Priorities in Org-mode."
1416 :tag "Org Priorities"
1417 :group 'org-todo)
1419 (defcustom org-default-priority ?B
1420 "The default priority of TODO items.
1421 This is the priority an item get if no explicit priority is given."
1422 :group 'org-priorities
1423 :type 'character)
1425 (defcustom org-lowest-priority ?C
1426 "The lowest priority of TODO items. A character like ?A, ?B etc."
1427 :group 'org-priorities
1428 :type 'character)
1430 (defgroup org-time nil
1431 "Options concerning time stamps and deadlines in Org-mode."
1432 :tag "Org Time"
1433 :group 'org)
1435 (defcustom org-insert-labeled-timestamps-at-point nil
1436 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1437 When nil, these labeled time stamps are forces into the second line of an
1438 entry, just after the headline. When scheduling from the global TODO list,
1439 the time stamp will always be forced into the second line."
1440 :group 'org-time
1441 :type 'boolean)
1443 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1444 "Formats for `format-time-string' which are used for time stamps.
1445 It is not recommended to change this constant.")
1447 (defcustom org-time-stamp-rounding-minutes 0
1448 "Number of minutes to round time stamps to upon insertion.
1449 When zero, insert the time unmodified. Useful rounding numbers
1450 should be factors of 60, so for example 5, 10, 15.
1451 When this is not zero, you can still force an exact time-stamp by using
1452 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1453 :group 'org-time
1454 :type 'integer)
1456 (defcustom org-display-custom-times nil
1457 "Non-nil means, overlay custom formats over all time stamps.
1458 The formats are defined through the variable `org-time-stamp-custom-formats'.
1459 To turn this on on a per-file basis, insert anywhere in the file:
1460 #+STARTUP: customtime"
1461 :group 'org-time
1462 :set 'set-default
1463 :type 'sexp)
1464 (make-variable-buffer-local 'org-display-custom-times)
1466 (defcustom org-time-stamp-custom-formats
1467 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1468 "Custom formats for time stamps. See `format-time-string' for the syntax.
1469 These are overlayed over the default ISO format if the variable
1470 `org-display-custom-times' is set."
1471 :group 'org-time
1472 :type 'sexp)
1474 (defun org-time-stamp-format (&optional long inactive)
1475 "Get the right format for a time string."
1476 (let ((f (if long (cdr org-time-stamp-formats)
1477 (car org-time-stamp-formats))))
1478 (if inactive
1479 (concat "[" (substring f 1 -1) "]")
1480 f)))
1482 (defcustom org-deadline-warning-days 30
1483 "No. of days before expiration during which a deadline becomes active.
1484 This variable governs the display in sparse trees and in the agenda."
1485 :group 'org-time
1486 :type 'number)
1488 (defcustom org-popup-calendar-for-date-prompt t
1489 "Non-nil means, pop up a calendar when prompting for a date.
1490 In the calendar, the date can be selected with mouse-1. However, the
1491 minibuffer will also be active, and you can simply enter the date as well.
1492 When nil, only the minibuffer will be available."
1493 :group 'org-time
1494 :type 'boolean)
1496 (defcustom org-calendar-follow-timestamp-change t
1497 "Non-nil means, make the calendar window follow timestamp changes.
1498 When a timestamp is modified and the calendar window is visible, it will be
1499 moved to the new date."
1500 :group 'org-time
1501 :type 'boolean)
1503 (defgroup org-tags nil
1504 "Options concerning tags in Org-mode."
1505 :tag "Org Tags"
1506 :group 'org)
1508 (defcustom org-tag-alist nil
1509 "List of tags allowed in Org-mode files.
1510 When this list is nil, Org-mode will base TAG input on what is already in the
1511 buffer.
1512 The value of this variable is an alist, the car may be (and should) be a
1513 character that is used to select that tag through the fast-tag-selection
1514 interface. See the manual for details."
1515 :group 'org-tags
1516 :type '(repeat
1517 (choice
1518 (cons (string :tag "Tag name")
1519 (character :tag "Access char"))
1520 (const :tag "Start radio group" (:startgroup))
1521 (const :tag "End radio group" (:endgroup)))))
1523 (defcustom org-use-fast-tag-selection 'auto
1524 "Non-nil means, use fast tag selection scheme.
1525 This is a special interface to select and deselect tags with single keys.
1526 When nil, fast selection is never used.
1527 When the symbol `auto', fast selection is used if and only if selection
1528 characters for tags have been configured, either through the variable
1529 `org-tag-alist' or through a #+TAGS line in the buffer.
1530 When t, fast selection is always used and selection keys are assigned
1531 automatically if necessary."
1532 :group 'org-tags
1533 :type '(choice
1534 (const :tag "Always" t)
1535 (const :tag "Never" nil)
1536 (const :tag "When selection characters are configured" 'auto)))
1538 (defcustom org-fast-tag-selection-single-key nil
1539 "Non-nil means, fast tag selection exits after first change.
1540 When nil, you have to press RET to exit it.
1541 During fast tag selection, you can toggle this flag with `C-c'."
1542 :group 'org-tags
1543 :type 'boolean)
1545 (defcustom org-tags-column 48
1546 "The column to which tags should be indented in a headline.
1547 If this number is positive, it specifies the column. If it is negative,
1548 it means that the tags should be flushright to that column. For example,
1549 -79 works well for a normal 80 character screen."
1550 :group 'org-tags
1551 :type 'integer)
1553 (defcustom org-auto-align-tags t
1554 "Non-nil means, realign tags after pro/demotion of TODO state change.
1555 These operations change the length of a headline and therefore shift
1556 the tags around. With this options turned on, after each such operation
1557 the tags are again aligned to `org-tags-column'."
1558 :group 'org-tags
1559 :type 'boolean)
1561 (defcustom org-use-tag-inheritance t
1562 "Non-nil means, tags in levels apply also for sublevels.
1563 When nil, only the tags directly given in a specific line apply there.
1564 If you turn off this option, you very likely want to turn on the
1565 companion option `org-tags-match-list-sublevels'."
1566 :group 'org-tags
1567 :type 'boolean)
1569 (defcustom org-tags-match-list-sublevels nil
1570 "Non-nil means list also sublevels of headlines matching tag search.
1571 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1572 the sublevels of a headline matching a tag search often also match
1573 the same search. Listing all of them can create very long lists.
1574 Setting this variable to nil causes subtrees of a match to be skipped.
1575 This option is off by default, because inheritance in on. If you turn
1576 inheritance off, you very likely want to turn this option on.
1578 As a special case, if the tag search is restricted to TODO items, the
1579 value of this variable is ignored and sublevels are always checked, to
1580 make sure all corresponding TODO items find their way into the list."
1581 :group 'org-tags
1582 :type 'boolean)
1584 (defvar org-tags-history nil
1585 "History of minibuffer reads for tags.")
1586 (defvar org-last-tags-completion-table nil
1587 "The last used completion table for tags.")
1589 (defgroup org-agenda nil
1590 "Options concerning agenda views in Org-mode."
1591 :tag "Org Agenda"
1592 :group 'org)
1594 (defvar org-category nil
1595 "Variable used by org files to set a category for agenda display.
1596 Such files should use a file variable to set it, for example
1598 -*- mode: org; org-category: \"ELisp\"
1600 or contain a special line
1602 #+CATEGORY: ELisp
1604 If the file does not specify a category, then file's base name
1605 is used instead.")
1606 (make-variable-buffer-local 'org-category)
1608 (defcustom org-agenda-files nil
1609 "The files to be used for agenda display.
1610 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1611 \\[org-remove-file]. You can also use customize to edit the list.
1613 If the value of the variable is not a list but a single file name, then
1614 the list of agenda files is actually stored and maintained in that file, one
1615 agenda file per line."
1616 :group 'org-agenda
1617 :type '(choice
1618 (repeat :tag "List of files" file)
1619 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1622 (defcustom org-agenda-confirm-kill 1
1623 "When set, remote killing from the agenda buffer needs confirmation.
1624 When t, a confirmation is always needed. When a number N, confirmation is
1625 only needed when the text to be killed contains more than N non-white lines."
1626 :group 'org-agenda
1627 :type '(choice
1628 (const :tag "Never" nil)
1629 (const :tag "Always" t)
1630 (number :tag "When more than N lines")))
1632 (defcustom org-calendar-to-agenda-key [?c]
1633 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1634 The command `org-calendar-goto-agenda' will be bound to this key. The
1635 default is the character `c' because then `c' can be used to switch back and
1636 forth between agenda and calendar."
1637 :group 'org-agenda
1638 :type 'sexp)
1640 (defgroup org-agenda-custom-commands nil
1641 "Options concerning agenda views in Org-mode."
1642 :tag "Org Agenda Custom Commands"
1643 :group 'org-agenda)
1645 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1646 "Custom commands for the agenda.
1647 These commands will be offered on the splash screen displayed by the
1648 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1650 (key type match options)
1652 key The key (a single char as a string) to be associated with the command.
1653 type The command type, any of the following symbols:
1654 todo Entries with a specific TODO keyword, in all agenda files.
1655 tags Tags match in all agenda files.
1656 tags-todo Tags match in all agenda files, TODO entries only.
1657 todo-tree Sparse tree of specific TODO keyword in *current* file.
1658 tags-tree Sparse tree with all tags matches in *current* file.
1659 occur-tree Occur sparse tree for *current* file.
1660 match What to search for:
1661 - a single keyword for TODO keyword searches
1662 - a tags match expression for tags searches
1663 - a regular expression for occur searches
1664 options A list of option setttings, similar to that in a let form, so like
1665 this: ((opt1 val1) (opt2 val2) ...)
1667 You can also define a set of commands, to create a composite agenda buffer.
1668 In this case, an entry looks like this:
1670 (key desc (cmd1 cmd2 ...) general-options)
1672 where
1674 desc A description string to be displayed in the dispatcher menu.
1675 cmd An agenda command, similar to the above. However, tree commands
1676 are no allowed, but instead you can get agenda and global todo list.
1677 So valid commands for a set are:
1678 (agenda)
1679 (alltodo)
1680 (todo \"match\" options)
1681 (tags \"match\" options )
1682 (tags-todo \"match\" options)
1684 Each command can carry a list of options, and another set of options can be
1685 given for the whole set of commands. Individual command options take
1686 precedence over the general options."
1687 :group 'org-agenda-custom-commands
1688 :type '(repeat
1689 (choice
1690 (list :tag "Single command"
1691 (string :tag "Key")
1692 (choice
1693 (const :tag "Tags search (all agenda files)" tags)
1694 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1695 (const :tag "TODO keyword search (all agenda files)" todo)
1696 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1697 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1698 (const :tag "Occur tree (current buffer)" occur-tree)
1699 (symbol :tag "Other, user-defined function"))
1700 (string :tag "Match")
1701 (repeat :tag "Local options"
1702 (list (variable :tag "Option") (sexp :tag "Value"))))
1703 (list :tag "Command series, all agenda files"
1704 (string :tag "Key")
1705 (string :tag "Description")
1706 (repeat
1707 (choice
1708 (const :tag "Agenda" (agenda))
1709 (const :tag "TODO list" (alltodo))
1710 (list :tag "Tags search"
1711 (const :format "" tags)
1712 (string :tag "Match")
1713 (repeat :tag "Local options"
1714 (list (variable :tag "Option")
1715 (sexp :tag "Value"))))
1717 (list :tag "Tags search, TODO entries only"
1718 (const :format "" tags-todo)
1719 (string :tag "Match")
1720 (repeat :tag "Local options"
1721 (list (variable :tag "Option")
1722 (sexp :tag "Value"))))
1724 (list :tag "TODO keyword search"
1725 (const :format "" todo)
1726 (string :tag "Match")
1727 (repeat :tag "Local options"
1728 (list (variable :tag "Option")
1729 (sexp :tag "Value"))))
1731 (list :tag "Other, user-defined function"
1732 (symbol :tag "function")
1733 (string :tag "Match")
1734 (repeat :tag "Local options"
1735 (list (variable :tag "Option")
1736 (sexp :tag "Value"))))))
1738 (repeat :tag "General options"
1739 (list (variable :tag "Option")
1740 (sexp :tag "Value")))))))
1742 (defcustom org-stuck-projects
1743 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil)
1744 "How to identify stuck projects.
1745 This is a list of three items:
1746 1. A tags/todo matcher string that is used to identify a project.
1747 The entire tree below a headline matched by this is considered a project.
1748 2. A list of TODO keywords itentifying non-stuck projects.
1749 If the project subtree contains any headline with one of these todo
1750 keywords, the project is consitered to be not stuck.
1751 3. A list of tags identifying non-stuck projects.
1752 If the project subtree contains any headline with one of these tags,
1753 the project is consitered to be not stuck.
1755 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1756 or `C-c a #' to produce the list."
1757 :group 'org-agenda-custom-commands
1758 :type '(list
1759 (string :tag "Tags/TODO match to identify a project")
1760 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1761 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))))
1764 (defgroup org-agenda-skip nil
1765 "Options concerning skipping parts of agenda files."
1766 :tag "Org Agenda Skip"
1767 :group 'org-agenda)
1769 (defcustom org-agenda-todo-list-sublevels t
1770 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1771 When nil, the sublevels of a TODO entry are not checked, resulting in
1772 potentially much shorter TODO lists."
1773 :group 'org-agenda-skip
1774 :group 'org-todo
1775 :type 'boolean)
1777 (defcustom org-agenda-todo-ignore-scheduled nil
1778 "Non-nil means, don't show scheduled entries in the global todo list.
1779 The idea behind this is that by scheduling it, you have already taken care
1780 of this item."
1781 :group 'org-agenda-skip
1782 :group 'org-todo
1783 :type 'boolean)
1785 (defcustom org-agenda-todo-ignore-deadlines nil
1786 "Non-nil means, don't show near deadline entries in the global todo list.
1787 Near means closer than `org-deadline-warning-days' days.
1788 The idea behind this is that such items will appear in the agenda anyway."
1789 :group 'org-agenda-skip
1790 :group 'org-todo
1791 :type 'boolean)
1793 (defcustom org-agenda-skip-scheduled-if-done nil
1794 "Non-nil means don't show scheduled items in agenda when they are done.
1795 This is relevant for the daily/weekly agenda, not for the TODO list."
1796 :group 'org-agenda-skip
1797 :type 'boolean)
1799 (defcustom org-timeline-show-empty-dates 3
1800 "Non-nil means, `org-timeline' also shows dates without an entry.
1801 When nil, only the days which actually have entries are shown.
1802 When t, all days between the first and the last date are shown.
1803 When an integer, show also empty dates, but if there is a gap of more than
1804 N days, just insert a special line indicating the size of the gap."
1805 :group 'org-agenda-skip ; FIXME: not quite the right group...
1806 :type '(choice
1807 (const :tag "None" nil)
1808 (const :tag "All" t)
1809 (number :tag "at most")))
1812 (defgroup org-agenda-startup nil
1813 "Options concerning initial settings in the Agenda in Org Mode."
1814 :tag "Org Agenda Startup"
1815 :group 'org-agenda)
1817 (defcustom org-finalize-agenda-hook nil
1818 "Hook run just before displaying an agenda buffer."
1819 :group 'org-agenda-startup
1820 :type 'hook)
1822 (defcustom org-agenda-mouse-1-follows-link nil
1823 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1824 A longer mouse click will still set point. Does not wortk on XEmacs.
1825 Needs to be set before org.el is loaded."
1826 :group 'org-agenda-startup
1827 :type 'boolean)
1829 (defcustom org-agenda-start-with-follow-mode nil
1830 "The initial value of follwo-mode in a newly created agenda window."
1831 :group 'org-agenda-startup
1832 :type 'boolean)
1834 (defgroup org-agenda-windows nil
1835 "Options concerning the windows used by the Agenda in Org Mode."
1836 :tag "Org Agenda Windows"
1837 :group 'org-agenda)
1839 (defcustom org-agenda-window-setup 'reorganize-frame
1840 "How the agenda buffer should be displayed.
1841 Possible values for this option are:
1843 current-window Show agenda in the current window, keeping all other windows.
1844 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1845 other-window Use `switch-to-buffer-other-window' to display agenda.
1846 reorganize-frame Show only two windows on the current frame, the current
1847 window and the agenda. Also, if the option
1848 `org-fit-agenda-window' is set, resize the agenda window to
1849 try to show as much as possible of the buffer content.
1850 See also the variable `org-agenda-restore-windows-after-quit'."
1851 :group 'org-agenda-windows
1852 :type '(choice
1853 (const current-window)
1854 (const other-frame)
1855 (const other-window)
1856 (const reorganize-frame)))
1858 (defcustom org-agenda-restore-windows-after-quit nil
1859 "Non-nil means, restore window configuration open exiting agenda.
1860 Before the window configuration is changed for displaying the agenda,
1861 the current status is recorded. When the agenda is exited with
1862 `q' or `x' and this option is set, the old state is restored. If
1863 `org-agenda-window-setup' is `other-frame', the value of this
1864 option will be ignored.."
1865 :group 'org-agenda-windows
1866 :type 'boolean)
1868 ;; FIXME: I think this variable could be removed, default set to t
1869 (defcustom org-select-agenda-window t
1870 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1871 When nil, cursor will remain in the current window."
1872 :group 'org-agenda-windows
1873 :type 'boolean)
1875 ;; FIXME: I think this variable could be removed, default set to t
1876 (defcustom org-fit-agenda-window t
1877 "Non-nil means, change window size of agenda to fit content.
1878 This is only effective if `org-agenda-window-setup' is `reorganize-frame'."
1879 :group 'org-agenda-windows
1880 :type 'boolean)
1882 (defcustom org-indirect-buffer-display 'other-window
1883 "How should indirect tree buffers be displayed?
1884 This applies to indirect buffers created with the commands
1885 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1886 Valid values are:
1887 current-window Display in the current window
1888 other-window Just display in another window.
1889 dedicated-frame Create one new frame, and re-use it each time.
1890 new-frame Make a new frame each time."
1891 :group 'org-structure
1892 :group 'org-agenda-windows
1893 :type '(choice
1894 (const :tag "In current window" current-window)
1895 (const :tag "In current frame, other window" other-window)
1896 (const :tag "Each time a new frame" new-frame)
1897 (const :tag "One dedicated frame" dedicated-frame)))
1899 (defgroup org-agenda-daily/weekly nil
1900 "Options concerning the daily/weekly agenda."
1901 :tag "Org Agenda Daily/Weekly"
1902 :group 'org-agenda)
1904 (defcustom org-agenda-ndays 7
1905 "Number of days to include in overview display.
1906 Should be 1 or 7."
1907 :group 'org-agenda-daily/weekly
1908 :type 'number)
1910 (defcustom org-agenda-start-on-weekday 1
1911 "Non-nil means, start the overview always on the specified weekday.
1912 0 denotes Sunday, 1 denotes Monday etc.
1913 When nil, always start on the current day."
1914 :group 'org-agenda-daily/weekly
1915 :type '(choice (const :tag "Today" nil)
1916 (number :tag "Weekday No.")))
1917 (defcustom org-agenda-show-all-dates t
1918 "Non-nil means, `org-agenda' shows every day in the selected range.
1919 When nil, only the days which actually have entries are shown."
1920 :group 'org-agenda-daily/weekly
1921 :type 'boolean)
1923 (defcustom org-agenda-include-diary nil
1924 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1925 :group 'org-agenda-daily/weekly
1926 :type 'boolean)
1928 ;; FIXME: This variable could be removed
1929 (defcustom org-agenda-include-all-todo nil
1930 "Set means weekly/daily agenda will always contain all TODO entries.
1931 The TODO entries will be listed at the top of the agenda, before
1932 the entries for specific days."
1933 :group 'org-agenda-daily/weekly
1934 :type 'boolean)
1936 (defgroup org-agenda-time-grid nil
1937 "Options concerning the time grid in the Org-mode Agenda."
1938 :tag "Org Agenda Time Grid"
1939 :group 'org-agenda)
1941 (defcustom org-agenda-use-time-grid t
1942 "Non-nil means, show a time grid in the agenda schedule.
1943 A time grid is a set of lines for specific times (like every two hours between
1944 8:00 and 20:00). The items scheduled for a day at specific times are
1945 sorted in between these lines.
1946 For details about when the grid will be shown, and what it will look like, see
1947 the variable `org-agenda-time-grid'."
1948 :group 'org-agenda-time-grid
1949 :type 'boolean)
1951 (defcustom org-agenda-time-grid
1952 '((daily today require-timed)
1953 "----------------"
1954 (800 1000 1200 1400 1600 1800 2000))
1956 "The settings for time grid for agenda display.
1957 This is a list of three items. The first item is again a list. It contains
1958 symbols specifying conditions when the grid should be displayed:
1960 daily if the agenda shows a single day
1961 weekly if the agenda shows an entire week
1962 today show grid on current date, independent of daily/weekly display
1963 require-timed show grid only if at least one item has a time specification
1965 The second item is a string which will be places behing the grid time.
1967 The third item is a list of integers, indicating the times that should have
1968 a grid line."
1969 :group 'org-agenda-time-grid
1970 :type
1971 '(list
1972 (set :greedy t :tag "Grid Display Options"
1973 (const :tag "Show grid in single day agenda display" daily)
1974 (const :tag "Show grid in weekly agenda display" weekly)
1975 (const :tag "Always show grid for today" today)
1976 (const :tag "Show grid only if any timed entries are present"
1977 require-timed)
1978 (const :tag "Skip grid times already present in an entry"
1979 remove-match))
1980 (string :tag "Grid String")
1981 (repeat :tag "Grid Times" (integer :tag "Time"))))
1983 (defgroup org-agenda-sorting nil
1984 "Options concerning sorting in the Org-mode Agenda."
1985 :tag "Org Agenda Sorting"
1986 :group 'org-agenda)
1988 (let ((sorting-choice
1989 '(choice
1990 (const time-up) (const time-down)
1991 (const category-keep) (const category-up) (const category-down)
1992 (const tag-down) (const tag-up)
1993 (const priority-up) (const priority-down))))
1995 (defcustom org-agenda-sorting-strategy
1996 '((agenda time-up category-keep priority-down)
1997 (todo category-keep priority-down)
1998 (tags category-keep))
1999 "Sorting structure for the agenda items of a single day.
2000 This is a list of symbols which will be used in sequence to determine
2001 if an entry should be listed before another entry. The following
2002 symbols are recognized:
2004 time-up Put entries with time-of-day indications first, early first
2005 time-down Put entries with time-of-day indications first, late first
2006 category-keep Keep the default order of categories, corresponding to the
2007 sequence in `org-agenda-files'.
2008 category-up Sort alphabetically by category, A-Z.
2009 category-down Sort alphabetically by category, Z-A.
2010 tag-up Sort alphabetically by last tag, A-Z.
2011 tag-down Sort alphabetically by last tag, Z-A.
2012 priority-up Sort numerically by priority, high priority last.
2013 priority-down Sort numerically by priority, high priority first.
2015 The different possibilities will be tried in sequence, and testing stops
2016 if one comparison returns a \"not-equal\". For example, the default
2017 '(time-up category-keep priority-down)
2018 means: Pull out all entries having a specified time of day and sort them,
2019 in order to make a time schedule for the current day the first thing in the
2020 agenda listing for the day. Of the entries without a time indication, keep
2021 the grouped in categories, don't sort the categories, but keep them in
2022 the sequence given in `org-agenda-files'. Within each category sort by
2023 priority.
2025 Leaving out `category-keep' would mean that items will be sorted across
2026 categories by priority."
2027 :group 'org-agenda-sorting
2028 :type `(choice
2029 (repeat :tag "General" ,sorting-choice)
2030 (list :tag "Individually"
2031 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2032 (repeat ,sorting-choice))
2033 (cons (const :tag "Strategy for TODO lists" todo)
2034 (repeat ,sorting-choice))
2035 (cons (const :tag "Strategy for Tags matches" tags)
2036 (repeat ,sorting-choice))))))
2038 (defcustom org-sort-agenda-notime-is-late t
2039 "Non-nil means, items without time are considered late.
2040 This is only relevant for sorting. When t, items which have no explicit
2041 time like 15:30 will be considered as 99:01, i.e. later than any items which
2042 do have a time. When nil, the default time is before 0:00. You can use this
2043 option to decide if the schedule for today should come before or after timeless
2044 agenda entries."
2045 :group 'org-agenda-sorting
2046 :type 'boolean)
2048 (defgroup org-agenda-prefix nil
2049 "Options concerning the entry prefix in the Org-mode agenda display."
2050 :tag "Org Agenda Prefix"
2051 :group 'org-agenda)
2053 (defcustom org-agenda-prefix-format
2054 '((agenda . " %-12:c%?-12t% s")
2055 (timeline . " % s")
2056 (todo . " %-12:c")
2057 (tags . " %-12:c"))
2058 "Format specifications for the prefix of items in the agenda views.
2059 An alist with four entries, for the different agenda types. The keys to the
2060 sublists are `agenda', `timeline', `todo', and `tags'. The values
2061 are format strings.
2062 This format works similar to a printf format, with the following meaning:
2064 %c the category of the item, \"Diary\" for entries from the diary, or
2065 as given by the CATEGORY keyword or derived from the file name.
2066 %T the *last* tag of the item. Last because inherited tags come
2067 first in the list.
2068 %t the time-of-day specification if one applies to the entry, in the
2069 format HH:MM
2070 %s Scheduling/Deadline information, a short string
2072 All specifiers work basically like the standard `%s' of printf, but may
2073 contain two additional characters: A question mark just after the `%' and
2074 a whitespace/punctuation character just before the final letter.
2076 If the first character after `%' is a question mark, the entire field
2077 will only be included if the corresponding value applies to the
2078 current entry. This is useful for fields which should have fixed
2079 width when present, but zero width when absent. For example,
2080 \"%?-12t\" will result in a 12 character time field if a time of the
2081 day is specified, but will completely disappear in entries which do
2082 not contain a time.
2084 If there is punctuation or whitespace character just before the final
2085 format letter, this character will be appended to the field value if
2086 the value is not empty. For example, the format \"%-12:c\" leads to
2087 \"Diary: \" if the category is \"Diary\". If the category were be
2088 empty, no additional colon would be interted.
2090 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2091 - Indent the line with two space characters
2092 - Give the category in a 12 chars wide field, padded with whitespace on
2093 the right (because of `-'). Append a colon if there is a category
2094 (because of `:').
2095 - If there is a time-of-day, put it into a 12 chars wide field. If no
2096 time, don't put in an empty field, just skip it (because of '?').
2097 - Finally, put the scheduling information and append a whitespace.
2099 As another example, if you don't want the time-of-day of entries in
2100 the prefix, you could use:
2102 (setq org-agenda-prefix-format \" %-11:c% s\")
2104 See also the variables `org-agenda-remove-times-when-in-prefix' and
2105 `org-agenda-remove-tags-when-in-prefix'."
2106 :type '(choice
2107 (string :tag "General format")
2108 (list :greedy t :tag "View dependent"
2109 (cons (const agenda) (string :tag "Format"))
2110 (cons (const timeline) (string :tag "Format"))
2111 (cons (const todo) (string :tag "Format"))
2112 (cons (const tags) (string :tag "Format"))))
2113 :group 'org-agenda-prefix)
2115 (defvar org-prefix-format-compiled nil
2116 "The compiled version of the most recently used prefix format.
2117 See the variable `org-agenda-prefix-format'.")
2119 (defcustom org-agenda-remove-times-when-in-prefix t
2120 "Non-nil means, remove duplicate time specifications in agenda items.
2121 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2122 time-of-day specification in a headline or diary entry is extracted and
2123 placed into the prefix. If this option is non-nil, the original specification
2124 \(a timestamp or -range, or just a plain time(range) specification like
2125 11:30-4pm) will be removed for agenda display. This makes the agenda less
2126 cluttered.
2127 The option can be t or nil. It may also be the symbol `beg', indicating
2128 that the time should only be removed what it is located at the beginning of
2129 the headline/diary entry."
2130 :group 'org-agenda-prefix
2131 :type '(choice
2132 (const :tag "Always" t)
2133 (const :tag "Never" nil)
2134 (const :tag "When at beginning of entry" beg)))
2136 (defcustom org-agenda-remove-tags-when-in-prefix nil
2137 "Non-nil means, remove the tags from the headline copy in the agenda.
2138 When this is the symbol `prefix', only remove tags when
2139 `org-agenda-prefix-format' contains a `%T' specifier."
2140 :group 'org-agenda-prefix
2141 :type '(choice
2142 (const :tag "Always" t)
2143 (const :tag "Never" nil)
2144 (const :tag "When prefix format contains %T" prefix)))
2146 (defcustom org-agenda-align-tags-to-column 65
2147 "Shift tags in agenda items to this column."
2148 :group 'org-agenda-prefix
2149 :type 'integer)
2151 (defgroup org-latex nil
2152 "Options for embedding LaTeX code into Org-mode"
2153 :tag "Org LaTeX"
2154 :group 'org)
2156 (defcustom org-format-latex-options
2157 '(:foreground "Black" :background "Transparent" :scale 1.0
2158 :matchers ("begin" "$" "$$" "\\(" "\\["))
2159 "Options for creating images from LaTeX fragments.
2160 This is a property list with the following properties:
2161 :foreground the foreground color, for example \"Black\".
2162 :background the background color, or \"Transparent\".
2163 :scale a scaling factor for the size of the images
2164 :matchers a list indicating which matchers should be used to
2165 find LaTeX fragments. Valid members of this list are:
2166 \"begin\" find environments
2167 \"$\" find math expressions surrounded by $...$
2168 \"$$\" find math expressions surrounded by $$....$$
2169 \"\\(\" find math expressions surrounded by \\(...\\)
2170 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2171 :group 'org-latex
2172 :type 'plist)
2174 (defgroup org-export nil
2175 "Options for exporting org-listings."
2176 :tag "Org Export"
2177 :group 'org)
2179 (defgroup org-export-general nil
2180 "General options for exporting Org-mode files."
2181 :tag "Org Export General"
2182 :group 'org-export)
2184 (defcustom org-export-publishing-directory "."
2185 "Path to the location where exported files should be located.
2186 This path may be relative to the directory where the Org-mode file lives.
2187 The default is to put them into the same directory as the Org-mode file.
2188 The variable may also be an alist with export types `:html', `:ascii',
2189 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2190 is relative, it is interpreted relative to the directory where the exported
2191 Org-mode files lives."
2192 :group 'org-export-general
2193 :type '(choice
2194 (directory)
2195 (repeat
2196 (cons
2197 (choice :tag "Type"
2198 (const :html) (const :ascii) (const :ical) (const :xoxo))
2199 (directory)))))
2201 (defcustom org-export-language-setup
2202 '(("en" "Author" "Date" "Table of Contents")
2203 ("cs" "Autor" "Datum" "Obsah")
2204 ("da" "Ophavsmand" "Dato" "Indhold")
2205 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2206 ("es" "Autor" "Fecha" "\xccndice")
2207 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2208 ("it" "Autore" "Data" "Indice")
2209 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2210 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2211 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2212 "Terms used in export text, translated to different languages.
2213 Use the variable `org-export-default-language' to set the language,
2214 or use the +OPTION lines for a per-file setting."
2215 :group 'org-export-general
2216 :type '(repeat
2217 (list
2218 (string :tag "HTML language tag")
2219 (string :tag "Author")
2220 (string :tag "Date")
2221 (string :tag "Table of Contents"))))
2223 (defcustom org-export-default-language "en"
2224 "The default language of HTML export, as a string.
2225 This should have an association in `org-export-language-setup'."
2226 :group 'org-export-general
2227 :type 'string)
2229 (defcustom org-export-headline-levels 3
2230 "The last level which is still exported as a headline.
2231 Inferior levels will produce itemize lists when exported.
2232 Note that a numeric prefix argument to an exporter function overrides
2233 this setting.
2235 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2236 :group 'org-export-general
2237 :type 'number)
2239 (defcustom org-export-with-section-numbers t
2240 "Non-nil means, add section numbers to headlines when exporting.
2242 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2243 :group 'org-export-general
2244 :type 'boolean)
2246 (defcustom org-export-with-toc t
2247 "Non-nil means, create a table of contents in exported files.
2248 The TOC contains headlines with levels up to`org-export-headline-levels'.
2250 Headlines which contain any TODO items will be marked with \"(*)\" in
2251 ASCII export, and with red color in HTML output.
2253 In HTML output, the TOC will be clickable.
2255 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
2256 :group 'org-export-general
2257 :type 'boolean)
2259 (defcustom org-export-mark-todo-in-toc nil
2260 "Non-nil means, mark TOC lines that contain any open TODO items."
2261 :group 'org-export-general
2262 :type 'boolean)
2264 (defcustom org-export-preserve-breaks nil
2265 "Non-nil means, preserve all line breaks when exporting.
2266 Normally, in HTML output paragraphs will be reformatted. In ASCII
2267 export, line breaks will always be preserved, regardless of this variable.
2269 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2270 :group 'org-export-general
2271 :type 'boolean)
2273 (defcustom org-export-with-archived-trees 'headline
2274 "Whether subtrees with the ARCHIVE tag should be exported.
2275 This can have three different values
2276 nil Do not export, pretend this tree is not present
2277 t Do export the entire tree
2278 headline Only export the headline, but skip the tree below it."
2279 :group 'org-export-general
2280 :group 'org-archive
2281 :type '(choice
2282 (const :tag "not at all" nil)
2283 (const :tag "headline only" 'headline)
2284 (const :tag "entirely" t)))
2286 (defcustom org-export-with-timestamps t
2287 "If nil, do not export time stamps and associated keywords."
2288 :group 'org-export-general
2289 :type 'boolean)
2291 (defcustom org-export-remove-timestamps-from-toc t
2292 "If nil, remove timestamps from the table of contents entries."
2293 :group 'org-export-general
2294 :type 'boolean)
2296 (defcustom org-export-with-tags 'not-in-toc
2297 "If nil, do not export tags, just remove them from headlines.
2298 If this is the symbol `not-in-toc', tags will be removed from table of
2299 contents entries, but still be shown in the headlines of the document."
2300 :group 'org-export-general
2301 :type '(choice
2302 (const :tag "Off" nil)
2303 (const :tag "Not in TOC" not-in-toc)
2304 (const :tag "On" t)))
2306 (defgroup org-export-translation nil
2307 "Options for translating special ascii sequences for the export backends."
2308 :tag "Org Export Translation"
2309 :group 'org-export)
2311 (defcustom org-export-with-emphasize t
2312 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2313 If the export target supports emphasizing text, the word will be
2314 typeset in bold, italic, or underlined, respectively. Works only for
2315 single words, but you can say: I *really* *mean* *this*.
2316 Not all export backends support this.
2318 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2319 :group 'org-export-translation
2320 :type 'boolean)
2322 (defcustom org-export-with-sub-superscripts t
2323 "Non-nil means, interpret \"_\" and \"^\" for export.
2324 When this option is turned on, you can use TeX-like syntax for sub- and
2325 superscripts. Several characters after \"_\" or \"^\" will be
2326 considered as a single item - so grouping with {} is normally not
2327 needed. For example, the following things will be parsed as single
2328 sub- or superscripts.
2330 10^24 or 10^tau several digits will be considered 1 item.
2331 10^-12 or 10^-tau a leading sign with digits or a word
2332 x^2-y^3 will be read as x^2 - y^3, because items are
2333 terminated by almost any nonword/nondigit char.
2334 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2336 Still, ambiguity is possible - so when in doubt use {} to enclose the
2337 sub/superscript.
2338 Not all export backends support this, but HTML does.
2340 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2341 :group 'org-export-translation
2342 :type 'boolean)
2344 (defcustom org-export-with-TeX-macros t
2345 "Non-nil means, interpret simple TeX-like macros when exporting.
2346 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2347 No only real TeX macros will work here, but the standard HTML entities
2348 for math can be used as macro names as well. For a list of supported
2349 names in HTML export, see the constant `org-html-entities'.
2350 Not all export backends support this.
2352 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2353 :group 'org-export-translation
2354 :group 'org-latex
2355 :type 'boolean)
2357 (defcustom org-export-with-LaTeX-fragments nil
2358 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2359 When set, the exporter will find LaTeX environments if the \\begin line is
2360 the first non-white thing on a line. It will also find the math delimiters
2361 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2362 display math.
2364 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2365 :group 'org-export-translation
2366 :group 'org-latex
2367 :type 'boolean)
2369 (defcustom org-export-with-fixed-width t
2370 "Non-nil means, lines starting with \":\" will be in fixed width font.
2371 This can be used to have pre-formatted text, fragments of code etc. For
2372 example:
2373 : ;; Some Lisp examples
2374 : (while (defc cnt)
2375 : (ding))
2376 will be looking just like this in also HTML. See also the QUOTE keyword.
2377 Not all export backends support this.
2379 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2380 :group 'org-export-translation
2381 :type 'boolean)
2383 (defcustom org-match-sexp-depth 3
2384 "Number of stacked braces for sub/superscript matching.
2385 This has to be set before loading org.el to be effective."
2386 :group 'org-export-translation
2387 :type 'integer)
2389 (defgroup org-export-tables nil
2390 "Options for exporting tables in Org-mode."
2391 :tag "Org Export Tables"
2392 :group 'org-export)
2394 (defcustom org-export-with-tables t
2395 "If non-nil, lines starting with \"|\" define a table.
2396 For example:
2398 | Name | Address | Birthday |
2399 |-------------+----------+-----------|
2400 | Arthur Dent | England | 29.2.2100 |
2402 Not all export backends support this.
2404 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2405 :group 'org-export-tables
2406 :type 'boolean)
2408 (defcustom org-export-highlight-first-table-line t
2409 "Non-nil means, highlight the first table line.
2410 In HTML export, this means use <th> instead of <td>.
2411 In tables created with table.el, this applies to the first table line.
2412 In Org-mode tables, all lines before the first horizontal separator
2413 line will be formatted with <th> tags."
2414 :group 'org-export-tables
2415 :type 'boolean)
2417 (defcustom org-export-table-remove-special-lines t
2418 "Remove special lines and marking characters in calculating tables.
2419 This removes the special marking character column from tables that are set
2420 up for spreadsheet calculations. It also removes the entire lines
2421 marked with `!', `_', or `^'. The lines with `$' are kept, because
2422 the values of constants may be useful to have."
2423 :group 'org-export-tables
2424 :type 'boolean)
2426 (defcustom org-export-prefer-native-exporter-for-tables nil
2427 "Non-nil means, always export tables created with table.el natively.
2428 Natively means, use the HTML code generator in table.el.
2429 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2430 the table does not use row- or column-spanning). This has the
2431 advantage, that the automatic HTML conversions for math symbols and
2432 sub/superscripts can be applied. Org-mode's HTML generator is also
2433 much faster."
2434 :group 'org-export-tables
2435 :type 'boolean)
2437 (defgroup org-export-ascii nil
2438 "Options specific for ASCII export of Org-mode files."
2439 :tag "Org Export ASCII"
2440 :group 'org-export)
2442 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2443 "Characters for underlining headings in ASCII export.
2444 In the given sequence, these characters will be used for level 1, 2, ..."
2445 :group 'org-export-ascii
2446 :type '(repeat character))
2448 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2449 "Bullet characters for headlines converted to lists in ASCII export.
2450 The first character is is used for the first lest level generated in this
2451 way, and so on. If there are more levels than characters given here,
2452 the list will be repeated.
2453 Note that plain lists will keep the same bullets as the have in the
2454 Org-mode file."
2455 :group 'org-export-ascii
2456 :type '(repeat character))
2458 (defcustom org-export-ascii-show-new-buffer t
2459 "Non-nil means, popup buffer containing the exported ASCII text.
2460 Otherwise the buffer will just be saved to a file and stay hidden."
2461 :group 'org-export-ascii
2462 :type 'boolean)
2464 (defgroup org-export-xml nil
2465 "Options specific for XML export of Org-mode files."
2466 :tag "Org Export XML"
2467 :group 'org-export)
2469 (defgroup org-export-html nil
2470 "Options specific for HTML export of Org-mode files."
2471 :tag "Org Export HTML"
2472 :group 'org-export)
2474 (defcustom org-export-html-style
2475 "<style type=\"text/css\">
2476 html {
2477 font-family: Times, serif;
2478 font-size: 12pt;
2480 .title { text-align: center; }
2481 .todo { color: red; }
2482 .done { color: green; }
2483 .timestamp { color: grey }
2484 .timestamp-kwd { color: CadetBlue }
2485 .tag { background-color:lightblue; font-weight:normal }
2486 .target { background-color: lavender; }
2487 pre {
2488 border: 1pt solid #AEBDCC;
2489 background-color: #F3F5F7;
2490 padding: 5pt;
2491 font-family: courier, monospace;
2493 table { border-collapse: collapse; }
2494 td, th {
2495 vertical-align: top;
2496 border: 1pt solid #ADB9CC;
2498 </style>"
2499 "The default style specification for exported HTML files.
2500 Since there are different ways of setting style information, this variable
2501 needs to contain the full HTML structure to provide a style, including the
2502 surrounding HTML tags. The style specifications should include definitions
2503 for new classes todo, done, title, and deadline. For example, legal values
2504 would be:
2506 <style type=\"text/css\">
2507 p { font-weight: normal; color: gray; }
2508 h1 { color: black; }
2509 .title { text-align: center; }
2510 .todo, .deadline { color: red; }
2511 .done { color: green; }
2512 </style>
2514 or, if you want to keep the style in a file,
2516 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2518 As the value of this option simply gets inserted into the HTML <head> header,
2519 you can \"misuse\" it to add arbitrary text to the header."
2520 :group 'org-export-html
2521 :type 'string)
2523 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2524 "Format for typesetting the document title in HTML export."
2525 :group 'org-export-html
2526 :type 'string)
2528 (defcustom org-export-html-toplevel-hlevel 2
2529 "The <H> level for level 1 headings in HTML export."
2530 :group 'org-export-html
2531 :type 'string)
2533 (defcustom org-export-html-link-org-files-as-html t
2534 "Non-nil means, make file links to `file.org' point to `file.html'.
2535 When org-mode is exporting an org-mode file to HTML, links to
2536 non-html files are directly put into a href tag in HTML.
2537 However, links to other Org-mode files (recognized by the
2538 extension `.org.) should become links to the corresponding html
2539 file, assuming that the linked org-mode file will also be
2540 converted to HTML.
2541 When nil, the links still point to the plain `.org' file."
2542 :group 'org-export-html
2543 :type 'boolean)
2545 (defcustom org-export-html-inline-images 'maybe
2546 "Non-nil means, inline images into exported HTML pages.
2547 This is done using an <img> tag. When nil, an anchor with href is used to
2548 link to the image. If this option is `maybe', then images in links with
2549 an empty description will be inlined, while images with a description will
2550 be linked only."
2551 :group 'org-export-html
2552 :type '(choice (const :tag "Never" nil)
2553 (const :tag "Always" t)
2554 (const :tag "When there is no description" maybe)))
2556 (defcustom org-export-html-expand t
2557 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2558 When nil, these tags will be exported as plain text and therefore
2559 not be interpreted by a browser.
2561 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2562 :group 'org-export-html
2563 :type 'boolean)
2565 (defcustom org-export-html-table-tag
2566 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2567 "The HTML tag used to start a table.
2568 This must be a <table> tag, but you may change the options like
2569 borders and spacing."
2570 :group 'org-export-html
2571 :type 'string)
2573 (defcustom org-export-html-with-timestamp nil
2574 "If non-nil, write `org-export-html-html-helper-timestamp'
2575 into the exported HTML text. Otherwise, the buffer will just be saved
2576 to a file."
2577 :group 'org-export-html
2578 :type 'boolean)
2580 (defcustom org-export-html-html-helper-timestamp
2581 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2582 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2583 :group 'org-export-html
2584 :type 'string)
2586 (defcustom org-export-html-show-new-buffer nil
2587 "Non-nil means, popup buffer containing the exported html text.
2588 Otherwise, the buffer will just be saved to a file and stay hidden."
2589 :group 'org-export-html
2590 :type 'boolean)
2592 (defgroup org-export-icalendar nil
2593 "Options specific for iCalendar export of Org-mode files."
2594 :tag "Org Export iCalendar"
2595 :group 'org-export)
2597 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2598 "The file name for the iCalendar file covering all agenda files.
2599 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2600 The file name should be absolute."
2601 :group 'org-export-icalendar
2602 :type 'file)
2604 (defcustom org-icalendar-include-todo nil
2605 "Non-nil means, export to iCalendar files should also cover TODO items."
2606 :group 'org-export-icalendar
2607 :type 'boolean)
2609 (defcustom org-icalendar-combined-name "OrgMode"
2610 "Calendar name for the combined iCalendar representing all agenda files."
2611 :group 'org-export-icalendar
2612 :type 'string)
2614 (defgroup org-font-lock nil
2615 "Font-lock settings for highlighting in Org-mode."
2616 :tag "Org Font Lock"
2617 :group 'org)
2619 (defcustom org-level-color-stars-only nil
2620 "Non-nil means fontify only the stars in each headline.
2621 When nil, the entire headline is fontified.
2622 Changing it requires restart of `font-lock-mode' to become effective
2623 also in regions already fontified."
2624 :group 'org-font-lock
2625 :type 'boolean)
2627 (defcustom org-hide-leading-stars nil
2628 "Non-nil means, hide the first N-1 stars in a headline.
2629 This works by using the face `org-hide' for these stars. This
2630 face is white for a light background, and black for a dark
2631 background. You may have to customize the face `org-hide' to
2632 make this work.
2633 Changing it requires restart of `font-lock-mode' to become effective
2634 also in regions already fontified.
2635 You may also set this on a per-file basis by adding one of the following
2636 lines to the buffer:
2638 #+STARTUP: hidestars
2639 #+STARTUP: showstars"
2640 :group 'org-font-lock
2641 :type 'boolean)
2643 (defcustom org-fontify-done-headline nil
2644 "Non-nil means, change the face of a headline if it is marked DONE.
2645 Normally, only the TODO/DONE keyword indicates the state of a headline.
2646 When this is non-nil, the headline after the keyword is set to the
2647 `org-headline-done' as an additional indication."
2648 :group 'org-font-lock
2649 :type 'boolean)
2651 (defcustom org-fontify-emphasized-text t
2652 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2653 Changing this variable requires a restart of Emacs to take effect."
2654 :group 'org-font-lock
2655 :type 'boolean)
2657 (defvar org-emph-re nil
2658 "Regular expression for matching emphasis.")
2659 (defvar org-emphasis-regexp-components) ; defined just below
2660 (defvar org-emphasis-alist) ; defined just below
2661 (defun org-set-emph-re (var val)
2662 "Set variable and compute the emphasis regular expression."
2663 (set var val)
2664 (when (and (boundp 'org-emphasis-alist)
2665 (boundp 'org-emphasis-regexp-components)
2666 org-emphasis-alist org-emphasis-regexp-components)
2667 (let* ((e org-emphasis-regexp-components)
2668 (pre (car e))
2669 (post (nth 1 e))
2670 (border (nth 2 e))
2671 (body (nth 3 e))
2672 (nl (nth 4 e))
2673 (stacked (nth 5 e))
2674 (body1 (concat body "*?"))
2675 (markers (mapconcat 'car org-emphasis-alist "")))
2676 ;; make sure special characters appear at the right position in the class
2677 (if (string-match "\\^" markers)
2678 (setq markers (concat (replace-match "" t t markers) "^")))
2679 (if (string-match "-" markers)
2680 (setq markers (concat (replace-match "" t t markers) "-")))
2681 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2682 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2683 (if (> nl 0)
2684 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2685 (int-to-string nl) "\\}")))
2686 ;; Make the regexp
2687 (setq org-emph-re
2688 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2689 "\\("
2690 "\\([" markers "]\\)"
2691 "\\("
2692 "[^" border markers "]"
2693 body1
2694 "[^" border markers "]"
2695 "\\)"
2696 "\\3\\)"
2697 "\\([" post (if stacked markers) "]\\|$\\)")))))
2699 (defcustom org-emphasis-regexp-components
2700 '(" \t('\"" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2701 "Components used to build the reqular expression for emphasis.
2702 This is a list with 6 entries. Terminology: In an emphasis string
2703 like \" *strong word* \", we call the initial space PREMATCH, the final
2704 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2705 and \"trong wor\" is the body. The different components in this variable
2706 specify what is allowed/forbidden in each part:
2708 pre Chars allowed as prematch. Beginning of line will be allowed too.
2709 post Chars allowed as postmatch. End of line will be allowed too.
2710 border The chars *forbidden* as border characters. In addition to the
2711 characters given here, all marker characters are forbidden too.
2712 body-regexp A regexp like \".\" to match a body character. Don't use
2713 non-shy groups here, and don't allow newline here.
2714 newline The maximum number of newlines allowed in an emphasis exp.
2715 stacked Non-nil means, allow stacked styles. This works only in HTML
2716 export. When this is set, all marker characters (as given in
2717 `org-emphasis-alist') will be allowed as pre/post, aiding
2718 inside-out matching.
2719 Use customize to modify this, or restart Emacs after changing it."
2720 :group 'org-font-lock
2721 :set 'org-set-emph-re
2722 :type '(list
2723 (sexp :tag "Allowed chars in pre ")
2724 (sexp :tag "Allowed chars in post ")
2725 (sexp :tag "Forbidden chars in border ")
2726 (sexp :tag "Regexp for body ")
2727 (integer :tag "number of newlines allowed")
2728 (boolean :tag "Stacking allowed ")))
2730 (defcustom org-emphasis-alist
2731 '(("*" bold "<b>" "</b>")
2732 ("/" italic "<i>" "</i>")
2733 ("_" underline "<u>" "</u>")
2734 ("=" shadow "<code>" "</code>")
2735 ("+" (:strike-through t) "<del>" "</del>")
2737 "Special syntax for emphasized text.
2738 Text starting and ending with a special character will be emphasized, for
2739 example *bold*, _underlined_ and /italic/. This variable sets the marker
2740 characters, the face to bbe used by font-lock for highlighting in Org-mode
2741 Emacs buffers, and the HTML tags to be used for this.
2742 Use customize to modify this, or restart Emacs after changing it."
2743 :group 'org-font-lock
2744 :set 'org-set-emph-re
2745 :type '(repeat
2746 (list
2747 (string :tag "Marker character")
2748 (choice
2749 (face :tag "Font-lock-face")
2750 (plist :tag "Face property list"))
2751 (string :tag "HTML start tag")
2752 (string :tag "HTML end tag"))))
2754 ;;; The faces
2756 (defgroup org-faces nil
2757 "Faces in Org-mode."
2758 :tag "Org Faces"
2759 :group 'org-font-lock)
2761 (defun org-compatible-face (specs)
2762 "Make a compatible face specification.
2763 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2764 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2765 to the top of the list. The `min-colors' attribute will be removed from
2766 any other entries, and any resulting duplicates will be removed entirely."
2767 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2768 (let (r e a)
2769 (while (setq e (pop specs))
2770 (cond
2771 ((memq (car e) '(t default)) (push e r))
2772 ((setq a (member '(min-colors 8) (car e)))
2773 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2774 (cdr e)))))
2775 ((setq a (assq 'min-colors (car e)))
2776 (setq e (cons (delq a (car e)) (cdr e)))
2777 (or (assoc (car e) r) (push e r)))
2778 (t (or (assoc (car e) r) (push e r)))))
2779 (nreverse r))
2780 specs))
2782 (defface org-hide
2783 '((((background light)) (:foreground "white"))
2784 (((background dark)) (:foreground "black")))
2785 "Face used to hide leading stars in headlines.
2786 The forground color of this face should be equal to the background
2787 color of the frame."
2788 :group 'org-faces)
2790 (defface org-level-1 ;; font-lock-function-name-face
2791 (org-compatible-face
2792 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2793 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2794 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2795 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2796 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2797 (t (:bold t))))
2798 "Face used for level 1 headlines."
2799 :group 'org-faces)
2801 (defface org-level-2 ;; font-lock-variable-name-face
2802 (org-compatible-face
2803 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2804 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2805 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2806 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2807 (t (:bold t))))
2808 "Face used for level 2 headlines."
2809 :group 'org-faces)
2811 (defface org-level-3 ;; font-lock-keyword-face
2812 (org-compatible-face
2813 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2814 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2815 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2816 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2817 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2818 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2819 (t (:bold t))))
2820 "Face used for level 3 headlines."
2821 :group 'org-faces)
2823 (defface org-level-4 ;; font-lock-comment-face
2824 (org-compatible-face
2825 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2826 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2827 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2828 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2829 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2830 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2831 (t (:bold t))))
2832 "Face used for level 4 headlines."
2833 :group 'org-faces)
2835 (defface org-level-5 ;; font-lock-type-face
2836 (org-compatible-face
2837 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2838 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2839 (((class color) (min-colors 8)) (:foreground "green"))))
2840 "Face used for level 5 headlines."
2841 :group 'org-faces)
2843 (defface org-level-6 ;; font-lock-constant-face
2844 (org-compatible-face
2845 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2846 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2847 (((class color) (min-colors 8)) (:foreground "magenta"))))
2848 "Face used for level 6 headlines."
2849 :group 'org-faces)
2851 (defface org-level-7 ;; font-lock-builtin-face
2852 (org-compatible-face
2853 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2854 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2855 (((class color) (min-colors 8)) (:foreground "blue"))))
2856 "Face used for level 7 headlines."
2857 :group 'org-faces)
2859 (defface org-level-8 ;; font-lock-string-face
2860 (org-compatible-face
2861 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2862 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2863 (((class color) (min-colors 8)) (:foreground "green"))))
2864 "Face used for level 8 headlines."
2865 :group 'org-faces)
2867 (defface org-special-keyword ;; font-lock-string-face
2868 (org-compatible-face
2869 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2870 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2871 (t (:italic t))))
2872 "Face used for special keywords."
2873 :group 'org-faces)
2875 (defface org-warning ;; font-lock-warning-face
2876 (org-compatible-face
2877 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2878 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2879 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2880 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2881 (t (:bold t))))
2882 "Face for deadlines and TODO keywords."
2883 :group 'org-faces)
2885 (defface org-headline-done ;; font-lock-string-face
2886 (org-compatible-face
2887 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2888 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2889 (((class color) (min-colors 8) (background light)) (:bold nil))))
2890 "Face used to indicate that a headline is DONE.
2891 This face is only used if `org-fontify-done-headline' is set."
2892 :group 'org-faces)
2894 (defface org-archived ; similar to shadow
2895 (org-compatible-face
2896 '((((class color grayscale) (min-colors 88) (background light))
2897 (:foreground "grey50"))
2898 (((class color grayscale) (min-colors 88) (background dark))
2899 (:foreground "grey70"))
2900 (((class color) (min-colors 8) (background light))
2901 (:foreground "green"))
2902 (((class color) (min-colors 8) (background dark))
2903 (:foreground "yellow"))))
2904 "Face for headline with the ARCHIVE tag."
2905 :group 'org-faces)
2907 (defface org-link
2908 '((((class color) (background light)) (:foreground "Purple" :underline t))
2909 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2910 (t (:underline t)))
2911 "Face for links."
2912 :group 'org-faces)
2914 (defface org-date
2915 '((((class color) (background light)) (:foreground "Purple" :underline t))
2916 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2917 (t (:underline t)))
2918 "Face for links."
2919 :group 'org-faces)
2921 (defface org-tag
2922 '((t (:bold t)))
2923 "Face for tags."
2924 :group 'org-faces)
2926 (defface org-todo ;; font-lock-warning-face
2927 (org-compatible-face
2928 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2929 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2930 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2931 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2932 (t (:inverse-video t :bold t))))
2933 "Face for TODO keywords."
2934 :group 'org-faces)
2936 (defface org-done ;; font-lock-type-face
2937 (org-compatible-face
2938 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2939 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2940 (((class color) (min-colors 8)) (:foreground "green"))
2941 (t (:bold t))))
2942 "Face used for DONE."
2943 :group 'org-faces)
2945 (defface org-table ;; font-lock-function-name-face
2946 (org-compatible-face
2947 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2948 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2949 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2950 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2951 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2952 (((class color) (min-colors 8) (background dark)))))
2953 "Face used for tables."
2954 :group 'org-faces)
2956 (defface org-formula
2957 (org-compatible-face
2958 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2959 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2960 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2961 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2962 (t (:bold t :italic t))))
2963 "Face for formulas."
2964 :group 'org-faces)
2966 (defface org-scheduled-today
2967 (org-compatible-face
2968 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2969 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2970 (((class color) (min-colors 8)) (:foreground "green"))
2971 (t (:bold t :italic t))))
2972 "Face for items scheduled for a certain day."
2973 :group 'org-faces)
2975 (defface org-scheduled-previously
2976 (org-compatible-face
2977 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2978 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2979 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2980 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2981 (t (:bold t))))
2982 "Face for items scheduled previously, and not yet done."
2983 :group 'org-faces)
2985 (defface org-upcoming-deadline
2986 (org-compatible-face
2987 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2988 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2989 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2990 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2991 (t (:bold t))))
2992 "Face for items scheduled previously, and not yet done."
2993 :group 'org-faces)
2995 (defface org-time-grid ;; font-lock-variable-name-face
2996 (org-compatible-face
2997 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2998 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2999 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3000 "Face used for time grids."
3001 :group 'org-faces)
3003 (defconst org-level-faces
3004 '(org-level-1 org-level-2 org-level-3 org-level-4
3005 org-level-5 org-level-6 org-level-7 org-level-8
3007 (defconst org-n-levels (length org-level-faces))
3010 ;;; Variables for pre-computed regular expressions, all buffer local
3012 (defvar org-done-string nil
3013 "The last string in `org-todo-keywords', indicating an item is DONE.")
3014 (make-variable-buffer-local 'org-done-string)
3015 (defvar org-todo-regexp nil
3016 "Matches any of the TODO state keywords.")
3017 (make-variable-buffer-local 'org-todo-regexp)
3018 (defvar org-not-done-regexp nil
3019 "Matches any of the TODO state keywords except the last one.")
3020 (make-variable-buffer-local 'org-not-done-regexp)
3021 (defvar org-todo-line-regexp nil
3022 "Matches a headline and puts TODO state into group 2 if present.")
3023 (make-variable-buffer-local 'org-todo-line-regexp)
3024 (defvar org-todo-line-tags-regexp nil
3025 "Matches a headline and puts TODO state into group 2 if present.
3026 Also put tags into group 4 if tags are present.")
3027 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3028 (defvar org-nl-done-regexp nil
3029 "Matches newline followed by a headline with the DONE keyword.")
3030 (make-variable-buffer-local 'org-nl-done-regexp)
3031 (defvar org-looking-at-done-regexp nil
3032 "Matches the DONE keyword a point.")
3033 (make-variable-buffer-local 'org-looking-at-done-regexp)
3034 (defvar org-todo-kwd-priority-p nil
3035 "Do TODO items have priorities?")
3036 (make-variable-buffer-local 'org-todo-kwd-priority-p)
3037 (defvar org-todo-kwd-max-priority nil
3038 "Maximum priority of TODO items.")
3039 (make-variable-buffer-local 'org-todo-kwd-max-priority)
3040 (defvar org-ds-keyword-length 12
3041 "Maximum length of the Deadline and SCHEDULED keywords.")
3042 (make-variable-buffer-local 'org-ds-keyword-length)
3043 (defvar org-deadline-regexp nil
3044 "Matches the DEADLINE keyword.")
3045 (make-variable-buffer-local 'org-deadline-regexp)
3046 (defvar org-deadline-time-regexp nil
3047 "Matches the DEADLINE keyword together with a time stamp.")
3048 (make-variable-buffer-local 'org-deadline-time-regexp)
3049 (defvar org-deadline-line-regexp nil
3050 "Matches the DEADLINE keyword and the rest of the line.")
3051 (make-variable-buffer-local 'org-deadline-line-regexp)
3052 (defvar org-scheduled-regexp nil
3053 "Matches the SCHEDULED keyword.")
3054 (make-variable-buffer-local 'org-scheduled-regexp)
3055 (defvar org-scheduled-time-regexp nil
3056 "Matches the SCHEDULED keyword together with a time stamp.")
3057 (make-variable-buffer-local 'org-scheduled-time-regexp)
3058 (defvar org-closed-time-regexp nil
3059 "Matches the CLOSED keyword together with a time stamp.")
3060 (make-variable-buffer-local 'org-closed-time-regexp)
3062 (defvar org-keyword-time-regexp nil
3063 "Matches any of the 4 keywords, together with the time stamp.")
3064 (make-variable-buffer-local 'org-keyword-time-regexp)
3065 (defvar org-keyword-time-not-clock-regexp nil
3066 "Matches any of the 3 keywords, together with the time stamp.")
3067 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3068 (defvar org-maybe-keyword-time-regexp nil
3069 "Matches a timestamp, possibly preceeded by a keyword.")
3070 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3072 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3073 rear-nonsticky t mouse-map t)
3074 "Properties to remove when a string without properties is wanted.")
3076 (defsubst org-match-string-no-properties (num &optional string)
3077 (if (featurep 'xemacs)
3078 (let ((s (match-string num string)))
3079 (remove-text-properties 0 (length s) org-rm-props s)
3081 (match-string-no-properties num string)))
3083 (defsubst org-no-properties (s)
3084 (remove-text-properties 0 (length s) org-rm-props s)
3087 (defsubst org-get-alist-option (option key)
3088 (cond ((eq key t) t)
3089 ((eq option t) t)
3090 ((assoc key option) (cdr (assoc key option)))
3091 (t (cdr (assq 'default option)))))
3093 (defsubst org-set-local (var value)
3094 "Make VAR local in current buffer and set it to VALUE."
3095 (set (make-variable-buffer-local var) value))
3097 (defsubst org-mode-p ()
3098 "Check if the current buffer is in Org-mode."
3099 (eq major-mode 'org-mode))
3101 (defsubst org-last (list)
3102 "Return the last element of LIST."
3103 (car (last list)))
3105 (defun org-let (list &rest body)
3106 (eval (cons 'let (cons list body))))
3107 (put 'org-let 'lisp-indent-function 1)
3109 (defun org-let2 (list1 list2 &rest body)
3110 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3111 (put 'org-let2 'lisp-indent-function 2)
3112 ;; FIXME: document this, in particular the push argument.
3113 (defconst org-startup-options
3114 '(("fold" org-startup-folded t)
3115 ("overview" org-startup-folded t)
3116 ("nofold" org-startup-folded nil)
3117 ("showall" org-startup-folded nil)
3118 ("content" org-startup-folded content)
3119 ("hidestars" org-hide-leading-stars t)
3120 ("showstars" org-hide-leading-stars nil)
3121 ("odd" org-odd-levels-only t)
3122 ("oddeven" org-odd-levels-only nil)
3123 ("align" org-startup-align-all-tables t)
3124 ("noalign" org-startup-align-all-tables nil)
3125 ("customtime" org-display-custom-times t)
3126 ("logging" org-log-done t)
3127 ("logdone" org-log-done t)
3128 ("nologging" org-log-done nil)
3129 ("lognotedone" org-log-done done push)
3130 ("lognotestate" org-log-done state push)
3131 ("lognoteclock-out" org-log-done clock-out push)
3132 ("dlcheck" org-startup-with-deadline-check t)
3133 ("nodlcheck" org-startup-with-deadline-check nil)))
3135 (defun org-set-regexps-and-options ()
3136 "Precompute regular expressions for current buffer."
3137 (when (org-mode-p)
3138 (let ((re (org-make-options-regexp
3139 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3140 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
3141 (splitre "[ \t]+")
3142 kwds int key value cat arch tags links)
3143 (save-excursion
3144 (save-restriction
3145 (widen)
3146 (goto-char (point-min))
3147 (while (re-search-forward re nil t)
3148 (setq key (match-string 1) value (org-match-string-no-properties 2))
3149 (cond
3150 ((equal key "CATEGORY")
3151 (if (string-match "[ \t]+$" value)
3152 (setq value (replace-match "" t t value)))
3153 (setq cat (intern value)))
3154 ((equal key "SEQ_TODO")
3155 (setq int 'sequence
3156 kwds (append kwds (org-split-string value splitre))))
3157 ((equal key "PRI_TODO")
3158 (setq int 'priority
3159 kwds (append kwds (org-split-string value splitre))))
3160 ((equal key "TYP_TODO")
3161 (setq int 'type
3162 kwds (append kwds (org-split-string value splitre))))
3163 ((equal key "TAGS")
3164 (setq tags (append tags (org-split-string value splitre))))
3165 ((equal key "LINK")
3166 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3167 (push (cons (match-string 1 value)
3168 (org-trim (match-string 2 value)))
3169 links)))
3170 ((equal key "STARTUP")
3171 (let ((opts (org-split-string value splitre))
3172 l var val)
3173 (while (setq l (assoc (pop opts) org-startup-options))
3174 (setq var (nth 1 l) val (nth 2 l))
3175 (if (not (nth 3 l))
3176 (set (make-local-variable var) val)
3177 (if (not (listp (symbol-value var)))
3178 (set (make-local-variable var) nil))
3179 (set (make-local-variable var) (symbol-value var))
3180 (add-to-list var val)))))
3181 ((equal key "ARCHIVE")
3182 (string-match " *$" value)
3183 (setq arch (replace-match "" t t value))
3184 (remove-text-properties 0 (length arch)
3185 '(face t fontified t) arch)))
3187 (and cat (org-set-local 'org-category cat))
3188 (and kwds (org-set-local 'org-todo-keywords kwds))
3189 (and arch (org-set-local 'org-archive-location arch))
3190 (and int (org-set-local 'org-todo-interpretation int))
3191 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3192 (when tags
3193 (let (e tgs)
3194 (while (setq e (pop tags))
3195 (cond
3196 ((equal e "{") (push '(:startgroup) tgs))
3197 ((equal e "}") (push '(:endgroup) tgs))
3198 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3199 (push (cons (match-string 1 e)
3200 (string-to-char (match-string 2 e)))
3201 tgs))
3202 (t (push (list e) tgs))))
3203 (org-set-local 'org-tag-alist nil)
3204 (while (setq e (pop tgs))
3205 (or (and (stringp (car e))
3206 (assoc (car e) org-tag-alist))
3207 (push e org-tag-alist))))))
3209 ;; Compute the regular expressions and other local variables
3210 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3211 org-todo-kwd-max-priority (1- (length org-todo-keywords))
3212 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3213 (length org-scheduled-string)))
3214 org-done-string
3215 (nth (1- (length org-todo-keywords)) org-todo-keywords)
3216 org-todo-regexp
3217 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3218 "\\|") "\\)\\>")
3219 org-not-done-regexp
3220 (concat "\\<\\("
3221 (mapconcat 'regexp-quote
3222 (nreverse (cdr (reverse org-todo-keywords)))
3223 "\\|")
3224 "\\)\\>")
3225 org-todo-line-regexp
3226 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3227 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3228 "\\)\\>\\)? *\\(.*\\)")
3229 org-nl-done-regexp
3230 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3231 org-todo-line-tags-regexp
3232 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3233 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3234 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3235 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3236 org-deadline-regexp (concat "\\<" org-deadline-string)
3237 org-deadline-time-regexp
3238 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3239 org-deadline-line-regexp
3240 (concat "\\<\\(" org-deadline-string "\\).*")
3241 org-scheduled-regexp
3242 (concat "\\<" org-scheduled-string)
3243 org-scheduled-time-regexp
3244 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3245 org-closed-time-regexp
3246 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3247 org-keyword-time-regexp
3248 (concat "\\<\\(" org-scheduled-string
3249 "\\|" org-deadline-string
3250 "\\|" org-closed-string
3251 "\\|" org-clock-string "\\)"
3252 " *[[<]\\([^]>]+\\)[]>]")
3253 org-keyword-time-not-clock-regexp
3254 (concat "\\<\\(" org-scheduled-string
3255 "\\|" org-deadline-string
3256 "\\|" org-closed-string "\\)"
3257 " *[[<]\\([^]>]+\\)[]>]")
3258 org-maybe-keyword-time-regexp
3259 (concat "\\(\\<\\(" org-scheduled-string
3260 "\\|" org-deadline-string
3261 "\\|" org-closed-string
3262 "\\|" org-clock-string "\\)\\)?"
3263 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3265 (org-set-font-lock-defaults)))
3268 ;;; Some variables ujsed in various places
3270 (defvar org-window-configuration nil
3271 "Used in various places to store a window configuration.")
3272 (defvar org-finish-function nil
3273 "Function to be called when `C-c C-c' is used.
3274 This is for getting out of special buffers like remember.")
3276 ;;; Foreign variables, to inform the compiler
3278 ;; XEmacs only
3279 (defvar outline-mode-menu-heading)
3280 (defvar outline-mode-menu-show)
3281 (defvar outline-mode-menu-hide)
3282 (defvar zmacs-regions) ; XEmacs regions
3283 ;; Emacs only
3284 (defvar mark-active)
3286 ;; Packages that org-mode interacts with
3287 (defvar calc-embedded-close-formula)
3288 (defvar calc-embedded-open-formula)
3289 (defvar font-lock-unfontify-region-function)
3290 (defvar org-goto-start-pos)
3291 (defvar vm-message-pointer)
3292 (defvar vm-folder-directory)
3293 (defvar wl-summary-buffer-elmo-folder)
3294 (defvar wl-summary-buffer-folder-name)
3295 (defvar gnus-other-frame-object)
3296 (defvar gnus-group-name)
3297 (defvar gnus-article-current)
3298 (defvar w3m-current-url)
3299 (defvar w3m-current-title)
3300 (defvar mh-progs)
3301 (defvar mh-current-folder)
3302 (defvar mh-show-folder-buffer)
3303 (defvar mh-index-folder)
3304 (defvar mh-searcher)
3305 (defvar calendar-mode-map)
3306 (defvar Info-current-file)
3307 (defvar Info-current-node)
3308 (defvar texmathp-why)
3309 (defvar remember-save-after-remembering)
3310 (defvar remember-data-file)
3311 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3312 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3313 (defvar org-latex-regexps)
3315 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3317 ;; FIXME: Occasionally check by commenting these, to make sure
3318 ;; no other functions uses these, forgetting to let-bind them.
3319 (defvar entry)
3320 (defvar state)
3321 (defvar last-state)
3322 (defvar date)
3323 (defvar description)
3326 ;; Defined somewhere in this file, but used before definition.
3327 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3328 (defvar org-agenda-undo-list)
3329 (defvar org-agenda-pending-undo-list)
3330 (defvar org-agenda-overriding-header)
3331 (defvar orgtbl-mode)
3332 (defvar org-html-entities)
3333 (defvar org-struct-menu)
3334 (defvar org-org-menu)
3335 (defvar org-tbl-menu)
3336 (defvar org-agenda-keymap)
3337 (defvar org-category-table)
3339 ;;;; Emacs/XEmacs compatibility
3341 ;; Overlay compatibility functions
3342 (defun org-make-overlay (beg end &optional buffer)
3343 (if (featurep 'xemacs)
3344 (make-extent beg end buffer)
3345 (make-overlay beg end buffer)))
3346 (defun org-delete-overlay (ovl)
3347 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3348 (defun org-detach-overlay (ovl)
3349 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3350 (defun org-move-overlay (ovl beg end &optional buffer)
3351 (if (featurep 'xemacs)
3352 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3353 (move-overlay ovl beg end buffer)))
3354 (defun org-overlay-put (ovl prop value)
3355 (if (featurep 'xemacs)
3356 (set-extent-property ovl prop value)
3357 (overlay-put ovl prop value)))
3358 (defun org-overlay-display (ovl text &optional face)
3359 "Make overlay OVL display TEXT with face FACE."
3360 (if (featurep 'xemacs)
3361 (let ((gl (make-glyph text)))
3362 (and face (set-glyph-face gl face))
3363 (set-extent-property ovl 'invisible t)
3364 (set-extent-property ovl 'end-glyph gl))
3365 (overlay-put ovl 'display text)
3366 (if face (overlay-put ovl 'face face))))
3367 (defun org-overlay-get (ovl prop)
3368 (if (featurep 'xemacs)
3369 (extent-property ovl prop)
3370 (overlay-get ovl prop)))
3371 (defun org-overlays-at (pos)
3372 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3373 (defun org-overlays-in (&optional start end)
3374 (if (featurep 'xemacs)
3375 (extent-list nil start end)
3376 (overlays-in start end)))
3377 (defun org-overlay-start (o)
3378 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3379 (defun org-overlay-end (o)
3380 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3381 (defun org-find-overlays (prop &optional pos delete)
3382 "Find all overlays specifying PROP at POS or point.
3383 If DELETE is non-nil, delete all those overlays."
3384 (let ((overlays (org-overlays-at (or pos (point))))
3385 ov found)
3386 (while (setq ov (pop overlays))
3387 (if (org-overlay-get ov prop)
3388 (if delete (org-delete-overlay ov) (push ov found))))
3389 found))
3391 ;; Region compatibility
3393 (defun org-add-hook (hook function &optional append local)
3394 "Add-hook, compatible with both Emacsen."
3395 (if (and local (featurep 'xemacs))
3396 (add-local-hook hook function append)
3397 (add-hook hook function append local)))
3399 (defvar org-ignore-region nil
3400 "To temporarily disable the active region.")
3402 (defun org-region-active-p ()
3403 "Is `transient-mark-mode' on and the region active?
3404 Works on both Emacs and XEmacs."
3405 (if org-ignore-region
3407 (if (featurep 'xemacs)
3408 (and zmacs-regions (region-active-p))
3409 (and transient-mark-mode mark-active))))
3411 ;; Invisibility compatibility
3413 (defun org-add-to-invisibility-spec (arg)
3414 "Add elements to `buffer-invisibility-spec'.
3415 See documentation for `buffer-invisibility-spec' for the kind of elements
3416 that can be added."
3417 (cond
3418 ((fboundp 'add-to-invisibility-spec)
3419 (add-to-invisibility-spec arg))
3420 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3421 (setq buffer-invisibility-spec (list arg)))
3423 (setq buffer-invisibility-spec
3424 (cons arg buffer-invisibility-spec)))))
3426 (defun org-remove-from-invisibility-spec (arg)
3427 "Remove elements from `buffer-invisibility-spec'."
3428 (if (fboundp 'remove-from-invisibility-spec)
3429 (remove-from-invisibility-spec arg)
3430 (if (consp buffer-invisibility-spec)
3431 (setq buffer-invisibility-spec
3432 (delete arg buffer-invisibility-spec)))))
3434 (defun org-in-invisibility-spec-p (arg)
3435 "Is ARG a member of `buffer-invisibility-spec'?"
3436 (if (consp buffer-invisibility-spec)
3437 (member arg buffer-invisibility-spec)
3438 nil))
3440 ;;;; Define the Org-mode
3442 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3443 (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."))
3446 ;; We use a before-change function to check if a table might need
3447 ;; an update.
3448 (defvar org-table-may-need-update t
3449 "Indicates that a table might need an update.
3450 This variable is set by `org-before-change-function'.
3451 `org-table-align' sets it back to nil.")
3452 (defvar org-mode-map)
3453 (defvar org-mode-hook nil)
3454 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3455 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3458 ;;;###autoload
3459 (define-derived-mode org-mode outline-mode "Org"
3460 "Outline-based notes management and organizer, alias
3461 \"Carsten's outline-mode for keeping track of everything.\"
3463 Org-mode develops organizational tasks around a NOTES file which
3464 contains information about projects as plain text. Org-mode is
3465 implemented on top of outline-mode, which is ideal to keep the content
3466 of large files well structured. It supports ToDo items, deadlines and
3467 time stamps, which magically appear in the diary listing of the Emacs
3468 calendar. Tables are easily created with a built-in table editor.
3469 Plain text URL-like links connect to websites, emails (VM), Usenet
3470 messages (Gnus), BBDB entries, and any files related to the project.
3471 For printing and sharing of notes, an Org-mode file (or a part of it)
3472 can be exported as a structured ASCII or HTML file.
3474 The following commands are available:
3476 \\{org-mode-map}"
3478 ;; Get rid of Outline menus, they are not needed
3479 ;; Need to do this here because define-derived-mode sets up
3480 ;; the keymap so late. Still, it is a waste to call this each time
3481 ;; we switch another buffer into org-mode.
3482 (if (featurep 'xemacs)
3483 (when (boundp 'outline-mode-menu-heading)
3484 ;; Assume this is Greg's port, it used easymenu
3485 (easy-menu-remove outline-mode-menu-heading)
3486 (easy-menu-remove outline-mode-menu-show)
3487 (easy-menu-remove outline-mode-menu-hide))
3488 (define-key org-mode-map [menu-bar headings] 'undefined)
3489 (define-key org-mode-map [menu-bar hide] 'undefined)
3490 (define-key org-mode-map [menu-bar show] 'undefined))
3492 (easy-menu-add org-org-menu)
3493 (easy-menu-add org-tbl-menu)
3494 (org-install-agenda-files-menu)
3495 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3496 (org-add-to-invisibility-spec '(org-cwidth))
3497 (when (featurep 'xemacs)
3498 (org-set-local 'line-move-ignore-invisible t))
3499 (setq outline-regexp "\\*+")
3500 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
3501 (setq outline-level 'org-outline-level)
3502 (when (and org-ellipsis (stringp org-ellipsis))
3503 (unless org-display-table
3504 (setq org-display-table (make-display-table)))
3505 (set-display-table-slot org-display-table
3506 4 (string-to-vector org-ellipsis))
3507 (setq buffer-display-table org-display-table))
3508 (org-set-regexps-and-options)
3509 ;; Calc embedded
3510 (org-set-local 'calc-embedded-open-mode "# ")
3511 (modify-syntax-entry ?# "<")
3512 (if org-startup-truncated (setq truncate-lines t))
3513 (org-set-local 'font-lock-unfontify-region-function
3514 'org-unfontify-region)
3515 ;; Activate before-change-function
3516 (org-set-local 'org-table-may-need-update t)
3517 (org-add-hook 'before-change-functions 'org-before-change-function nil
3518 'local)
3519 ;; Check for running clock before killing a buffer
3520 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3521 ;; Paragraphs and auto-filling
3522 (org-set-autofill-regexps)
3523 (org-update-radio-target-regexp)
3524 ;; Make isearch reveal context
3525 (if (or (featurep 'xemacs)
3526 (not (boundp 'outline-isearch-open-invisible-function)))
3527 ;; Emacs 21 and XEmacs make use of the hook
3528 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3529 ;; Emacs 22 deals with this through a special variable
3530 (org-set-local 'outline-isearch-open-invisible-function
3531 (lambda (&rest ignore) (org-show-context 'isearch))))
3533 ;; If empty file that did not turn on org-mode automatically, make it to.
3534 (if (and org-insert-mode-line-in-empty-file
3535 (interactive-p)
3536 (= (point-min) (point-max)))
3537 (insert " -*- mode: org -*-\n\n"))
3539 (unless org-inhibit-startup
3540 (when org-startup-align-all-tables
3541 (let ((bmp (buffer-modified-p)))
3542 (org-table-map-tables 'org-table-align)
3543 (set-buffer-modified-p bmp)))
3544 (if org-startup-with-deadline-check
3545 (call-interactively 'org-check-deadlines)
3546 (cond
3547 ((eq org-startup-folded t)
3548 (org-cycle '(4)))
3549 ((eq org-startup-folded 'content)
3550 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3551 (org-cycle '(4)) (org-cycle '(4))))))))
3553 (defsubst org-call-with-arg (command arg)
3554 "Call COMMAND interactively, but pretend prefix are was ARG."
3555 (let ((current-prefix-arg arg)) (call-interactively command)))
3557 (defsubst org-current-line (&optional pos)
3558 (save-excursion
3559 (and pos (goto-char pos))
3560 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
3562 (defun org-current-time ()
3563 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3564 (if (> org-time-stamp-rounding-minutes 0)
3565 (let ((r org-time-stamp-rounding-minutes)
3566 (time (decode-time)))
3567 (apply 'encode-time
3568 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3569 (nthcdr 2 time))))
3570 (current-time)))
3572 (defun org-add-props (string plist &rest props)
3573 "Add text properties to entire string, from beginning to end.
3574 PLIST may be a list of properties, PROPS are individual properties and values
3575 that will be added to PLIST. Returns the string that was modified."
3576 (add-text-properties
3577 0 (length string) (if props (append plist props) plist) string)
3578 string)
3579 (put 'org-add-props 'lisp-indent-function 2)
3582 ;;;; Font-Lock stuff, including the activators
3584 (defvar org-mouse-map (make-sparse-keymap))
3585 (define-key org-mouse-map
3586 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3587 (define-key org-mouse-map
3588 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3589 (when org-mouse-1-follows-link
3590 (define-key org-mouse-map [follow-link] 'mouse-face))
3591 (when org-tab-follows-link
3592 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3593 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3594 (when org-return-follows-link
3595 (define-key org-mouse-map [(return)] 'org-open-at-point)
3596 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3598 (require 'font-lock)
3600 (defconst org-non-link-chars "]\t\n\r<>")
3601 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3602 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3603 (defconst org-link-re-with-space
3604 (concat
3605 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3606 "\\([^" org-non-link-chars " ]"
3607 "[^" org-non-link-chars "]*"
3608 "[^" org-non-link-chars " ]\\)>?")
3609 "Matches a link with spaces, optional angular brackets around it.")
3611 (defconst org-link-re-with-space2
3612 (concat
3613 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3614 "\\([^" org-non-link-chars " ]"
3615 "[^]\t\n\r]*"
3616 "[^" org-non-link-chars " ]\\)>?")
3617 "Matches a link with spaces, optional angular brackets around it.")
3619 (defconst org-angle-link-re
3620 (concat
3621 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3622 "\\([^" org-non-link-chars " ]"
3623 "[^" org-non-link-chars "]*"
3624 "\\)>")
3625 "Matches link with angular brackets, spaces are allowed.")
3626 (defconst org-plain-link-re
3627 (concat
3628 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3629 "\\([^]\t\n\r<>,;() ]+\\)")
3630 "Matches plain link, without spaces.")
3632 (defconst org-bracket-link-regexp
3633 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3634 "Matches a link in double brackets.")
3636 (defconst org-bracket-link-analytic-regexp
3637 (concat
3638 "\\[\\["
3639 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3640 "\\([^]]+\\)"
3641 "\\]"
3642 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3643 "\\]"))
3644 ; 1: http:
3645 ; 2: http
3646 ; 3: path
3647 ; 4: [desc]
3648 ; 5: desc
3650 (defconst org-ts-lengths
3651 (cons (length (format-time-string (car org-time-stamp-formats)))
3652 (length (format-time-string (cdr org-time-stamp-formats))))
3653 "This holds the lengths of the two different time formats.")
3654 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3655 "Regular expression for fast time stamp matching.")
3656 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3657 "Regular expression for fast time stamp matching.")
3658 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3659 "Regular expression matching time strings for analysis.")
3660 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3661 "Regular expression matching time stamps, with groups.")
3662 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3663 "Regular expression matching time stamps (also [..]), with groups.")
3664 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3665 "Regular expression matching a time stamp range.")
3666 (defconst org-tr-regexp-both
3667 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3668 "Regular expression matching a time stamp range.")
3669 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3670 org-ts-regexp "\\)?")
3671 "Regular expression matching a time stamp or time stamp range.")
3672 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3673 org-ts-regexp-both "\\)?")
3674 "Regular expression matching a time stamp or time stamp range.
3675 The time stamps may be either active or inactive.")
3677 (defvar org-emph-face nil)
3679 (defun org-do-emphasis-faces (limit)
3680 "Run through the buffer and add overlays to links."
3681 (if (re-search-forward org-emph-re limit t)
3682 (progn
3683 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3684 'face
3685 (nth 1 (assoc (match-string 3)
3686 org-emphasis-alist)))
3687 (add-text-properties (match-beginning 2) (match-end 2)
3688 '(font-lock-multiline t))
3689 (backward-char 1)
3690 t)))
3692 (defun org-activate-plain-links (limit)
3693 "Run through the buffer and add overlays to links."
3694 (if (re-search-forward org-plain-link-re limit t)
3695 (progn
3696 (add-text-properties (match-beginning 0) (match-end 0)
3697 (list 'mouse-face 'highlight
3698 'rear-nonsticky t
3699 'keymap org-mouse-map
3701 t)))
3703 (defun org-activate-angle-links (limit)
3704 "Run through the buffer and add overlays to links."
3705 (if (re-search-forward org-angle-link-re limit t)
3706 (progn
3707 (add-text-properties (match-beginning 0) (match-end 0)
3708 (list 'mouse-face 'highlight
3709 'rear-nonsticky t
3710 'keymap org-mouse-map
3712 t)))
3714 (defmacro org-maybe-intangible (props)
3715 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3716 In emacs 21, invisible text is not avoided by the command loop, so the
3717 intangible property is needed to make sure point skips this text.
3718 In Emacs 22, this is not necessary. The intangible text property has
3719 led to problems with flyspell. These problems are fixed in flyspell.el,
3720 but we still avoid setting the property in Emacs 22 and later.
3721 We use a macro so that the test can happen at compilation time."
3722 (if (< emacs-major-version 22)
3723 `(append '(intangible t) ,props)
3724 props))
3726 (defun org-activate-bracket-links (limit)
3727 "Run through the buffer and add overlays to bracketed links."
3728 (if (re-search-forward org-bracket-link-regexp limit t)
3729 (let* ((help (concat "LINK: "
3730 (org-match-string-no-properties 1)))
3731 ;; FIXME: above we should remove the escapes.
3732 ;; but that requires another match, protecting match data,
3733 ;; a lot of overhead for font-lock.
3734 (ip (org-maybe-intangible
3735 (list 'invisible 'org-link 'rear-nonsticky t
3736 'keymap org-mouse-map 'mouse-face 'highlight
3737 'help-echo help)))
3738 (vp (list 'rear-nonsticky t
3739 'keymap org-mouse-map 'mouse-face 'highlight
3740 'help-echo help)))
3741 ;; We need to remove the invisible property here. Table narrowing
3742 ;; may have made some of this invisible.
3743 (remove-text-properties (match-beginning 0) (match-end 0)
3744 '(invisible nil))
3745 (if (match-end 3)
3746 (progn
3747 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3748 (add-text-properties (match-beginning 3) (match-end 3) vp)
3749 (add-text-properties (match-end 3) (match-end 0) ip))
3750 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3751 (add-text-properties (match-beginning 1) (match-end 1) vp)
3752 (add-text-properties (match-end 1) (match-end 0) ip))
3753 t)))
3755 (defun org-activate-dates (limit)
3756 "Run through the buffer and add overlays to dates."
3757 (if (re-search-forward org-tsr-regexp-both limit t)
3758 (progn
3759 (add-text-properties (match-beginning 0) (match-end 0)
3760 (list 'mouse-face 'highlight
3761 'rear-nonsticky t
3762 'keymap org-mouse-map))
3763 (when org-display-custom-times
3764 (if (match-end 3)
3765 (org-display-custom-time (match-beginning 3) (match-end 3)))
3766 (org-display-custom-time (match-beginning 1) (match-end 1)))
3767 t)))
3769 (defvar org-target-link-regexp nil
3770 "Regular expression matching radio targets in plain text.")
3771 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3772 "Regular expression matching a link target.")
3773 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3774 "Regular expression matching a link target.")
3776 (defun org-activate-target-links (limit)
3777 "Run through the buffer and add overlays to target matches."
3778 (when org-target-link-regexp
3779 (let ((case-fold-search t))
3780 (if (re-search-forward org-target-link-regexp limit t)
3781 (progn
3782 (add-text-properties (match-beginning 0) (match-end 0)
3783 (list 'mouse-face 'highlight
3784 'rear-nonsticky t
3785 'keymap org-mouse-map
3786 'help-echo "Radio target link"
3787 'org-linked-text t))
3788 t)))))
3790 (defun org-update-radio-target-regexp ()
3791 "Find all radio targets in this file and update the regular expression."
3792 (interactive)
3793 (when (memq 'radio org-activate-links)
3794 (setq org-target-link-regexp
3795 (org-make-target-link-regexp (org-all-targets 'radio)))
3796 (org-restart-font-lock)))
3798 (defun org-hide-wide-columns (limit)
3799 (let (s e)
3800 (setq s (text-property-any (point) (or limit (point-max))
3801 'org-cwidth t))
3802 (when s
3803 (setq e (next-single-property-change s 'org-cwidth))
3804 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3805 (goto-char e)
3806 t)))
3808 (defun org-restart-font-lock ()
3809 "Restart font-lock-mode, to force refontification."
3810 (when (and (boundp 'font-lock-mode) font-lock-mode)
3811 (font-lock-mode -1)
3812 (font-lock-mode 1)))
3814 (defun org-all-targets (&optional radio)
3815 "Return a list of all targets in this file.
3816 With optional argument RADIO, only find radio targets."
3817 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3818 rtn)
3819 (save-excursion
3820 (goto-char (point-min))
3821 (while (re-search-forward re nil t)
3822 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3823 rtn)))
3825 (defun org-make-target-link-regexp (targets)
3826 "Make regular expression matching all strings in TARGETS.
3827 The regular expression finds the targets also if there is a line break
3828 between words."
3829 (and targets
3830 (concat
3831 "\\<\\("
3832 (mapconcat
3833 (lambda (x)
3834 (while (string-match " +" x)
3835 (setq x (replace-match "\\s-+" t t x)))
3837 targets
3838 "\\|")
3839 "\\)\\>")))
3841 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3842 "Matches CamelCase words, possibly with a star before it.")
3844 (defun org-activate-camels (limit)
3845 "Run through the buffer and add overlays to dates."
3846 (if (re-search-forward org-camel-regexp limit t)
3847 (progn
3848 (add-text-properties (match-beginning 0) (match-end 0)
3849 (list 'mouse-face 'highlight
3850 'rear-nonsticky t
3851 'keymap org-mouse-map))
3852 t)))
3854 (defun org-activate-tags (limit)
3855 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3856 (progn
3857 (add-text-properties (match-beginning 1) (match-end 1)
3858 (list 'mouse-face 'highlight
3859 'rear-nonsticky t
3860 'keymap org-mouse-map))
3861 t)))
3863 (defun org-font-lock-level ()
3864 (save-excursion
3865 (org-back-to-heading t)
3866 (- (match-end 0) (match-beginning 0))))
3868 (defun org-outline-level ()
3869 (save-excursion
3870 (looking-at outline-regexp)
3871 (if (match-beginning 1)
3872 (+ (org-get-string-indentation (match-string 1)) 1000)
3873 (- (match-end 0) (match-beginning 0)))))
3875 (defvar org-font-lock-keywords nil)
3877 (defun org-set-font-lock-defaults ()
3878 (let* ((em org-fontify-emphasized-text)
3879 (lk org-activate-links)
3880 (org-font-lock-extra-keywords
3881 ;; Headlines
3882 (list
3883 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3884 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3885 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3886 (1 'org-table))
3887 ;; Links
3888 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3889 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3890 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3891 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3892 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3893 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3894 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3895 (if org-table-limit-column-width
3896 '(org-hide-wide-columns (0 nil append)))
3897 ;; TODO lines
3898 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3899 '(1 'org-todo t))
3900 ;; Priorities
3901 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3902 ;; Special keywords
3903 (list org-repeat-re '(0 'org-special-keyword t))
3904 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3905 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3906 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3907 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3908 ;; Emphasis
3909 (if em
3910 (if (featurep 'xemacs)
3911 '(org-do-emphasis-faces (0 nil append))
3912 '(org-do-emphasis-faces)))
3913 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3914 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3915 2 'bold prepend)
3916 (if org-provide-checkbox-statistics
3917 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3918 (0 (org-get-checkbox-statistics-face) t)))
3919 ;; COMMENT
3920 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3921 "\\|" org-quote-string "\\)\\>")
3922 '(1 'org-special-keyword t))
3923 '("^#.*" (0 'font-lock-comment-face t))
3924 ;; DONE
3925 (if org-fontify-done-headline
3926 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3927 '(1 'org-done t) '(2 'org-headline-done t))
3928 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3929 '(1 'org-done t)))
3930 ;; Table stuff
3931 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3932 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3933 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3934 (if org-format-transports-properties-p
3935 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3936 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3938 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3939 ;; Now set the full font-lock-keywords
3940 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3941 (org-set-local 'font-lock-defaults
3942 '(org-font-lock-keywords t nil nil backward-paragraph))
3943 (kill-local-variable 'font-lock-keywords) nil))
3945 (defvar org-m nil)
3946 (defvar org-l nil)
3947 (defvar org-f nil)
3948 (defun org-get-level-face (n)
3949 "Get the right face for match N in font-lock matching of healdines."
3950 (setq org-l (- (match-end 2) (match-beginning 1)))
3951 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3952 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3953 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3954 (cond
3955 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3956 ((eq n 2) org-f)
3957 (t (if org-level-color-stars-only nil org-f))))
3959 (defun org-unfontify-region (beg end &optional maybe_loudly)
3960 "Remove fontification and activation overlays from links."
3961 (font-lock-default-unfontify-region beg end)
3962 (let* ((buffer-undo-list t)
3963 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3964 (inhibit-modification-hooks t)
3965 deactivate-mark buffer-file-name buffer-file-truename)
3966 (remove-text-properties beg end
3967 '(mouse-face t keymap t org-linked-text t
3968 rear-nonsticky t
3969 invisible t intangible t))))
3971 ;;;; Visibility cycling, including org-goto and indirect buffer
3973 ;;; Cycling
3975 (defvar org-cycle-global-status nil)
3976 (make-variable-buffer-local 'org-cycle-global-status)
3977 (defvar org-cycle-subtree-status nil)
3978 (make-variable-buffer-local 'org-cycle-subtree-status)
3980 ;;;###autoload
3981 (defun org-cycle (&optional arg)
3982 "Visibility cycling for Org-mode.
3984 - When this function is called with a prefix argument, rotate the entire
3985 buffer through 3 states (global cycling)
3986 1. OVERVIEW: Show only top-level headlines.
3987 2. CONTENTS: Show all headlines of all levels, but no body text.
3988 3. SHOW ALL: Show everything.
3990 - When point is at the beginning of a headline, rotate the subtree started
3991 by this line through 3 different states (local cycling)
3992 1. FOLDED: Only the main headline is shown.
3993 2. CHILDREN: The main headline and the direct children are shown.
3994 From this state, you can move to one of the children
3995 and zoom in further.
3996 3. SUBTREE: Show the entire subtree, including body text.
3998 - When there is a numeric prefix, go up to a heading with level ARG, do
3999 a `show-subtree' and return to the previous cursor position. If ARG
4000 is negative, go up that many levels.
4002 - When point is not at the beginning of a headline, execute
4003 `indent-relative', like TAB normally does. See the option
4004 `org-cycle-emulate-tab' for details.
4006 - Special case: if point is the the beginning of the buffer and there is
4007 no headline in line 1, this function will act as if called with prefix arg."
4008 (interactive "P")
4009 (let* ((outline-regexp
4010 (if (and (org-mode-p) org-cycle-include-plain-lists)
4011 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4012 outline-regexp))
4013 (bob-special (and org-cycle-global-at-bob (bobp)
4014 (not (looking-at outline-regexp))))
4015 (org-cycle-hook
4016 (if bob-special
4017 (delq 'org-optimize-window-after-visibility-change
4018 (copy-sequence org-cycle-hook))
4019 org-cycle-hook))
4020 (pos (point)))
4022 (if (or bob-special (equal arg '(4)))
4023 ;; special case: use global cycling
4024 (setq arg t))
4026 (cond
4028 ((org-at-table-p 'any)
4029 ;; Enter the table or move to the next field in the table
4030 (or (org-table-recognize-table.el)
4031 (progn
4032 (if arg (org-table-edit-field t)
4033 (org-table-justify-field-maybe)
4034 (call-interactively 'org-table-next-field)))))
4036 ((eq arg t) ;; Global cycling
4038 (cond
4039 ((and (eq last-command this-command)
4040 (eq org-cycle-global-status 'overview))
4041 ;; We just created the overview - now do table of contents
4042 ;; This can be slow in very large buffers, so indicate action
4043 (message "CONTENTS...")
4044 (org-content)
4045 (message "CONTENTS...done")
4046 (setq org-cycle-global-status 'contents)
4047 (run-hook-with-args 'org-cycle-hook 'contents))
4049 ((and (eq last-command this-command)
4050 (eq org-cycle-global-status 'contents))
4051 ;; We just showed the table of contents - now show everything
4052 (show-all)
4053 (message "SHOW ALL")
4054 (setq org-cycle-global-status 'all)
4055 (run-hook-with-args 'org-cycle-hook 'all))
4058 ;; Default action: go to overview
4059 (org-overview)
4060 (message "OVERVIEW")
4061 (setq org-cycle-global-status 'overview)
4062 (run-hook-with-args 'org-cycle-hook 'overview))))
4064 ((integerp arg)
4065 ;; Show-subtree, ARG levels up from here.
4066 (save-excursion
4067 (org-back-to-heading)
4068 (outline-up-heading (if (< arg 0) (- arg)
4069 (- (funcall outline-level) arg)))
4070 (org-show-subtree)))
4072 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4073 ;; At a heading: rotate between three different views
4074 (org-back-to-heading)
4075 (let ((goal-column 0) eoh eol eos)
4076 ;; First, some boundaries
4077 (save-excursion
4078 (org-back-to-heading)
4079 (save-excursion
4080 (beginning-of-line 2)
4081 (while (and (not (eobp)) ;; this is like `next-line'
4082 (get-char-property (1- (point)) 'invisible))
4083 (beginning-of-line 2)) (setq eol (point)))
4084 (outline-end-of-heading) (setq eoh (point))
4085 (org-end-of-subtree t)
4086 (skip-chars-forward " \t\n")
4087 (setq eos (1- (point))))
4088 ;; Find out what to do next and set `this-command'
4089 (cond
4090 ((= eos eoh)
4091 ;; Nothing is hidden behind this heading
4092 (message "EMPTY ENTRY")
4093 (setq org-cycle-subtree-status nil))
4094 ((>= eol eos)
4095 ;; Entire subtree is hidden in one line: open it
4096 (org-show-entry)
4097 (show-children)
4098 (message "CHILDREN")
4099 (setq org-cycle-subtree-status 'children)
4100 (run-hook-with-args 'org-cycle-hook 'children))
4101 ((and (eq last-command this-command)
4102 (eq org-cycle-subtree-status 'children))
4103 ;; We just showed the children, now show everything.
4104 (org-show-subtree)
4105 (message "SUBTREE")
4106 (setq org-cycle-subtree-status 'subtree)
4107 (run-hook-with-args 'org-cycle-hook 'subtree))
4109 ;; Default action: hide the subtree.
4110 (hide-subtree)
4111 (message "FOLDED")
4112 (setq org-cycle-subtree-status 'folded)
4113 (run-hook-with-args 'org-cycle-hook 'folded)))))
4115 ;; TAB emulation
4116 (buffer-read-only (org-back-to-heading))
4118 ((org-try-cdlatex-tab))
4120 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4121 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4122 (or (and (eq org-cycle-emulate-tab 'white)
4123 (= (match-end 0) (point-at-eol)))
4124 (and (eq org-cycle-emulate-tab 'whitestart)
4125 (>= (match-end 0) pos))))
4127 (eq org-cycle-emulate-tab t))
4128 (if (and (looking-at "[ \n\r\t]")
4129 (string-match "^[ \t]*$" (buffer-substring
4130 (point-at-bol) (point))))
4131 (progn
4132 (beginning-of-line 1)
4133 (and (looking-at "[ \t]+") (replace-match ""))))
4134 (indent-relative))
4136 (t (save-excursion
4137 (org-back-to-heading)
4138 (org-cycle))))))
4140 ;;;###autoload
4141 (defun org-global-cycle (&optional arg)
4142 "Cycle the global visibility. For details see `org-cycle'."
4143 (interactive "P")
4144 (let ((org-cycle-include-plain-lists
4145 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4146 (if (integerp arg)
4147 (progn
4148 (show-all)
4149 (hide-sublevels arg)
4150 (setq org-cycle-global-status 'contents))
4151 (org-cycle '(4)))))
4153 (defun org-overview ()
4154 "Switch to overview mode, shoing only top-level headlines.
4155 Really, this shows all headlines with level equal or greater than the level
4156 of the first headline in the buffer. This is important, because if the
4157 first headline is not level one, then (hide-sublevels 1) gives confusing
4158 results."
4159 (interactive)
4160 (hide-sublevels (save-excursion
4161 (goto-char (point-min))
4162 (if (re-search-forward (concat "^" outline-regexp) nil t)
4163 (progn
4164 (goto-char (match-beginning 0))
4165 (funcall outline-level))
4166 1))))
4168 ;; FIXME: allow an argument to give a limiting level for this.
4169 (defun org-content ()
4170 "Show all headlines in the buffer, like a table of contents"
4171 (interactive)
4172 (save-excursion
4173 ;; Visit all headings and show their offspring
4174 (goto-char (point-max))
4175 (catch 'exit
4176 (while (and (progn (condition-case nil
4177 (outline-previous-visible-heading 1)
4178 (error (goto-char (point-min))))
4180 (looking-at outline-regexp))
4181 (show-branches)
4182 (if (bobp) (throw 'exit nil))))))
4185 (defun org-optimize-window-after-visibility-change (state)
4186 "Adjust the window after a change in outline visibility.
4187 This function is the default value of the hook `org-cycle-hook'."
4188 (when (get-buffer-window (current-buffer))
4189 (cond
4190 ((eq state 'overview) (org-first-headline-recenter 1))
4191 ((eq state 'content) nil)
4192 ((eq state 'all) nil)
4193 ((eq state 'folded) nil)
4194 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4195 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4197 (defun org-subtree-end-visible-p ()
4198 "Is the end of the current subtree visible?"
4199 (pos-visible-in-window-p
4200 (save-excursion (org-end-of-subtree t) (point))))
4202 (defun org-first-headline-recenter (&optional N)
4203 "Move cursor to the first headline and recenter the headline.
4204 Optional argument N means, put the headline into the Nth line of the window."
4205 (goto-char (point-min))
4206 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4207 (beginning-of-line)
4208 (recenter (prefix-numeric-value N))))
4210 ;;; Org-goto
4212 (defvar org-goto-window-configuration nil)
4213 (defvar org-goto-marker nil)
4214 (defvar org-goto-map (make-sparse-keymap))
4215 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4216 (while (setq cmd (pop cmds))
4217 (substitute-key-definition cmd cmd org-goto-map global-map)))
4218 (define-key org-goto-map "\C-m" 'org-goto-ret)
4219 (define-key org-goto-map [(left)] 'org-goto-left)
4220 (define-key org-goto-map [(right)] 'org-goto-right)
4221 (define-key org-goto-map [(?q)] 'org-goto-quit)
4222 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
4223 (define-key org-goto-map "\C-i" 'org-cycle)
4224 (define-key org-goto-map [(tab)] 'org-cycle)
4225 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
4226 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
4227 (define-key org-goto-map "n" 'outline-next-visible-heading)
4228 (define-key org-goto-map "p" 'outline-previous-visible-heading)
4229 (define-key org-goto-map "f" 'outline-forward-same-level)
4230 (define-key org-goto-map "b" 'outline-backward-same-level)
4231 (define-key org-goto-map "u" 'outline-up-heading)
4232 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4233 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4234 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4235 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4236 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
4237 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4238 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
4240 (defconst org-goto-help
4241 "Select a location to jump to, press RET
4242 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4244 (defun org-goto ()
4245 "Go to a different location of the document, keeping current visibility.
4247 When you want to go to a different location in a document, the fastest way
4248 is often to fold the entire buffer and then dive into the tree. This
4249 method has the disadvantage, that the previous location will be folded,
4250 which may not be what you want.
4252 This command works around this by showing a copy of the current buffer in
4253 overview mode. You can dive into the tree in that copy, to find the
4254 location you want to reach. When pressing RET, the command returns to the
4255 original buffer in which the visibility is still unchanged. It then jumps
4256 to the new location, making it and the headline hierarchy above it visible."
4257 (interactive)
4258 (let* ((org-goto-start-pos (point))
4259 (selected-point
4260 (org-get-location (current-buffer) org-goto-help)))
4261 (if selected-point
4262 (progn
4263 (org-mark-ring-push org-goto-start-pos)
4264 (goto-char selected-point)
4265 (if (or (org-invisible-p) (org-invisible-p2))
4266 (org-show-context 'org-goto)))
4267 (error "Quit"))))
4269 (defvar org-selected-point nil) ; dynamically scoped parameter
4271 (defun org-get-location (buf help)
4272 "Let the user select a location in the Org-mode buffer BUF.
4273 This function uses a recursive edit. It returns the selected position
4274 or nil."
4275 (let (org-selected-point)
4276 (save-excursion
4277 (save-window-excursion
4278 (delete-other-windows)
4279 (switch-to-buffer (get-buffer-create "*org-goto*"))
4280 (with-output-to-temp-buffer "*Help*"
4281 (princ help))
4282 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4283 (setq buffer-read-only nil)
4284 (erase-buffer)
4285 (insert-buffer-substring buf)
4286 (let ((org-startup-truncated t)
4287 (org-startup-folded t)
4288 (org-startup-align-all-tables nil)
4289 (org-startup-with-deadline-check nil))
4290 (org-mode))
4291 (setq buffer-read-only t)
4292 (if (boundp 'org-goto-start-pos)
4293 (goto-char org-goto-start-pos)
4294 (goto-char (point-min)))
4295 (org-beginning-of-line)
4296 (message "Select location and press RET")
4297 ;; now we make sure that during selection, ony very few keys work
4298 ;; and that it is impossible to switch to another window.
4299 (let ((gm (current-global-map))
4300 (overriding-local-map org-goto-map))
4301 (unwind-protect
4302 (progn
4303 (use-global-map org-goto-map)
4304 (recursive-edit))
4305 (use-global-map gm)))))
4306 (kill-buffer "*org-goto*")
4307 org-selected-point))
4309 (defun org-goto-ret (&optional arg)
4310 "Finish `org-goto' by going to the new location."
4311 (interactive "P")
4312 (setq org-selected-point (point)
4313 current-prefix-arg arg)
4314 (throw 'exit nil))
4316 (defun org-goto-left ()
4317 "Finish `org-goto' by going to the new location."
4318 (interactive)
4319 (if (org-on-heading-p)
4320 (progn
4321 (beginning-of-line 1)
4322 (setq org-selected-point (point)
4323 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4324 (throw 'exit nil))
4325 (error "Not on a heading")))
4327 (defun org-goto-right ()
4328 "Finish `org-goto' by going to the new location."
4329 (interactive)
4330 (if (org-on-heading-p)
4331 (progn
4332 (outline-end-of-subtree)
4333 (or (eobp) (forward-char 1))
4334 (setq org-selected-point (point)
4335 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4336 (throw 'exit nil))
4337 (error "Not on a heading")))
4339 (defun org-goto-quit ()
4340 "Finish `org-goto' without cursor motion."
4341 (interactive)
4342 (setq org-selected-point nil)
4343 (throw 'exit nil))
4345 ;;; Indirect buffer display of subtrees
4347 (defvar org-indirect-dedicated-frame nil
4348 "This is the frame being used for indirect tree display.")
4349 (defvar org-last-indirect-buffer nil)
4351 (defun org-tree-to-indirect-buffer (&optional arg)
4352 "Create indirect buffer and narrow it to current subtree.
4353 With numerical prefix ARG, go up to this level and then take that tree.
4354 If ARG is negative, go up that many levels.
4355 Normally this command removes the indirect buffer previously made
4356 with this command. However, when called with a C-u prefix, the last buffer
4357 is kept so that you can work with several indirect buffers at the same time.
4358 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4359 requests that a new frame be made for the new buffer, so that the dedicated
4360 frame is not changed."
4361 (interactive "P")
4362 (let ((cbuf (current-buffer))
4363 (cwin (selected-window))
4364 (pos (point))
4365 (bname (buffer-name (current-buffer)))
4366 beg end level heading ibuf)
4367 (save-excursion
4368 (org-back-to-heading t)
4369 (when (numberp arg)
4370 (setq level (org-outline-level))
4371 (if (< arg 0) (setq arg (+ level arg)))
4372 (while (> (setq level (org-outline-level)) arg)
4373 (outline-up-heading 1 t)))
4374 (setq beg (point)
4375 heading (org-get-heading))
4376 (org-end-of-subtree t) (setq end (point)))
4377 (if (and (not arg)
4378 (buffer-live-p org-last-indirect-buffer))
4379 (kill-buffer org-last-indirect-buffer))
4380 (setq ibuf (org-get-indirect-buffer cbuf)
4381 org-last-indirect-buffer ibuf)
4382 (cond
4383 ((or (eq org-indirect-buffer-display 'new-frame)
4384 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4385 (select-frame (make-frame))
4386 (delete-other-windows)
4387 (switch-to-buffer ibuf)
4388 (org-set-frame-title heading))
4389 ((eq org-indirect-buffer-display 'dedicated-frame)
4390 (raise-frame
4391 (select-frame (or (and org-indirect-dedicated-frame
4392 (frame-live-p org-indirect-dedicated-frame)
4393 org-indirect-dedicated-frame)
4394 (setq org-indirect-dedicated-frame (make-frame)))))
4395 (delete-other-windows)
4396 (switch-to-buffer ibuf)
4397 (org-set-frame-title (concat "Indirect: " heading)))
4398 ((eq org-indirect-buffer-display 'current-window)
4399 (switch-to-buffer ibuf))
4400 ((eq org-indirect-buffer-display 'other-window)
4401 (pop-to-buffer ibuf))
4402 (t (error "Invalid value.")))
4403 (if (featurep 'xemacs)
4404 (save-excursion (org-mode) (turn-on-font-lock)))
4405 (narrow-to-region beg end)
4406 (show-all)
4407 (goto-char pos)
4408 (and (window-live-p cwin) (select-window cwin))))
4410 (defun org-get-indirect-buffer (&optional buffer)
4411 (setq buffer (or buffer (current-buffer)))
4412 (let ((n 1) (base (buffer-name buffer)) bname)
4413 (while (buffer-live-p
4414 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4415 (setq n (1+ n)))
4416 (condition-case nil
4417 (make-indirect-buffer buffer bname 'clone)
4418 (error (make-indirect-buffer buffer bname)))))
4420 (defun org-set-frame-title (title)
4421 "Set the title of the current frame to the string TITLE."
4422 ;; FIXME: how to name a single frame in XEmacs???
4423 (unless (featurep 'xemacs)
4424 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4426 ;;;; Structure editing
4428 ;;; Inserting headlines
4430 (defun org-insert-heading (&optional force-heading)
4431 "Insert a new heading or item with same depth at point.
4432 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4433 If point is at the beginning of a headline, insert a sibling before the
4434 current headline. If point is in the middle of a headline, split the headline
4435 at that position and make the rest of the headline part of the sibling below
4436 the current headline."
4437 (interactive "P")
4438 (if (= (buffer-size) 0)
4439 (insert "\n* ")
4440 (when (or force-heading (not (org-insert-item)))
4441 (let* ((head (save-excursion
4442 (condition-case nil
4443 (progn
4444 (org-back-to-heading)
4445 (match-string 0))
4446 (error "*"))))
4447 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4448 pos)
4449 (cond
4450 ((and (org-on-heading-p) (bolp)
4451 (save-excursion (backward-char 1) (not (org-invisible-p))))
4452 (open-line (if blank 2 1)))
4453 ((and (bolp) (save-excursion
4454 (backward-char 1) (not (org-invisible-p))))
4455 nil)
4456 (t (newline (if blank 2 1))))
4457 (insert head) (just-one-space)
4458 (setq pos (point))
4459 (end-of-line 1)
4460 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4461 (run-hooks 'org-insert-heading-hook)))))
4464 (defun org-insert-todo-heading (arg)
4465 "Insert a new heading with the same level and TODO state as current heading.
4466 If the heading has no TODO state, or if the state is DONE, use the first
4467 state (TODO by default). Also with prefix arg, force first state."
4468 (interactive "P")
4469 (when (not (org-insert-item 'checkbox))
4470 (org-insert-heading)
4471 (save-excursion
4472 (org-back-to-heading)
4473 (outline-previous-heading)
4474 (looking-at org-todo-line-regexp))
4475 (if (or arg
4476 (not (match-beginning 2))
4477 (equal (match-string 2) org-done-string))
4478 (insert (car org-todo-keywords) " ")
4479 (insert (match-string 2) " "))))
4481 ;;; Promotion and Demotion
4483 (defun org-promote-subtree ()
4484 "Promote the entire subtree.
4485 See also `org-promote'."
4486 (interactive)
4487 (save-excursion
4488 (org-map-tree 'org-promote))
4489 (org-fix-position-after-promote))
4491 (defun org-demote-subtree ()
4492 "Demote the entire subtree. See `org-demote'.
4493 See also `org-promote'."
4494 (interactive)
4495 (save-excursion
4496 (org-map-tree 'org-demote))
4497 (org-fix-position-after-promote))
4500 (defun org-do-promote ()
4501 "Promote the current heading higher up the tree.
4502 If the region is active in `transient-mark-mode', promote all headings
4503 in the region."
4504 (interactive)
4505 (save-excursion
4506 (if (org-region-active-p)
4507 (org-map-region 'org-promote (region-beginning) (region-end))
4508 (org-promote)))
4509 (org-fix-position-after-promote))
4511 (defun org-do-demote ()
4512 "Demote the current heading lower down the tree.
4513 If the region is active in `transient-mark-mode', demote all headings
4514 in the region."
4515 (interactive)
4516 (save-excursion
4517 (if (org-region-active-p)
4518 (org-map-region 'org-demote (region-beginning) (region-end))
4519 (org-demote)))
4520 (org-fix-position-after-promote))
4522 (defun org-fix-position-after-promote ()
4523 "Make sure that after pro/demotion cursor position is right."
4524 (if (and (or (eobp) (equal (char-after) ?\n))
4525 (save-excursion
4526 (skip-chars-backward "a-zA-Z0-9_@")
4527 (looking-at org-todo-regexp)))
4528 (insert " "))
4529 (and (equal (char-after) ?\ )
4530 (equal (char-before) ?*)
4531 (forward-char 1)))
4533 (defun org-get-legal-level (level &optional change)
4534 "Rectify a level change under the influence of `org-odd-levels-only'
4535 LEVEL is a current level, CHANGE is by how much the level should be
4536 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4537 even level numbers will become the next higher odd number."
4538 (if org-odd-levels-only
4539 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4540 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4541 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4542 (max 1 (+ level change))))
4544 (defun org-promote ()
4545 "Promote the current heading higher up the tree.
4546 If the region is active in `transient-mark-mode', promote all headings
4547 in the region."
4548 (org-back-to-heading t)
4549 (let* ((level (save-match-data (funcall outline-level)))
4550 (up-head (make-string (org-get-legal-level level -1) ?*))
4551 (diff (abs (- level (length up-head)))))
4552 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4553 (replace-match up-head nil t)
4554 ;; Fixup tag positioning
4555 (and org-auto-align-tags (org-set-tags nil t))
4556 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4558 (defun org-demote ()
4559 "Demote the current heading lower down the tree.
4560 If the region is active in `transient-mark-mode', demote all headings
4561 in the region."
4562 (org-back-to-heading t)
4563 (let* ((level (save-match-data (funcall outline-level)))
4564 (down-head (make-string (org-get-legal-level level 1) ?*))
4565 (diff (abs (- level (length down-head)))))
4566 (replace-match down-head nil t)
4567 ;; Fixup tag positioning
4568 (and org-auto-align-tags (org-set-tags nil t))
4569 (if org-adapt-indentation (org-fixup-indentation diff))))
4571 (defun org-map-tree (fun)
4572 "Call FUN for every heading underneath the current one."
4573 (org-back-to-heading)
4574 (let ((level (funcall outline-level)))
4575 (save-excursion
4576 (funcall fun)
4577 (while (and (progn
4578 (outline-next-heading)
4579 (> (funcall outline-level) level))
4580 (not (eobp)))
4581 (funcall fun)))))
4583 (defun org-map-region (fun beg end)
4584 "Call FUN for every heading between BEG and END."
4585 (let ((org-ignore-region t))
4586 (save-excursion
4587 (setq end (copy-marker end))
4588 (goto-char beg)
4589 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4590 (< (point) end))
4591 (funcall fun))
4592 (while (and (progn
4593 (outline-next-heading)
4594 (< (point) end))
4595 (not (eobp)))
4596 (funcall fun)))))
4598 (defun org-fixup-indentation (diff)
4599 "Change the indentation in the current entry by DIFF
4600 However, if any line in the current entry has no indentation, or if it
4601 would end up with no indentation after the change, nothing at all is done."
4602 (save-excursion
4603 (let ((end (save-excursion (outline-next-heading)
4604 (point-marker)))
4605 (prohibit (if (> diff 0)
4606 "^\\S-"
4607 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4608 col)
4609 (unless (save-excursion (re-search-forward prohibit end t))
4610 (while (re-search-forward "^[ \t]+" end t)
4611 (goto-char (match-end 0))
4612 (setq col (current-column))
4613 (if (< diff 0) (replace-match ""))
4614 (indent-to (+ diff col))))
4615 (move-marker end nil))))
4617 (defun org-convert-to-odd-levels ()
4618 "Convert an org-mode file with all levels allowed to one with odd levels.
4619 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4620 level 5 etc."
4621 (interactive)
4622 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4623 (let ((org-odd-levels-only nil) n)
4624 (save-excursion
4625 (goto-char (point-min))
4626 (while (re-search-forward "^\\*\\*+" nil t)
4627 (setq n (1- (length (match-string 0))))
4628 (while (>= (setq n (1- n)) 0)
4629 (org-demote))
4630 (end-of-line 1))))))
4633 (defun org-convert-to-oddeven-levels ()
4634 "Convert an org-mode file with only odd levels to one with odd and even levels.
4635 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4636 section with an even level, conversion would destroy the structure of the file. An error
4637 is signaled in this case."
4638 (interactive)
4639 (goto-char (point-min))
4640 ;; First check if there are no even levels
4641 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
4642 (org-show-context t)
4643 (error "Not all levels are odd in this file. Conversion not possible."))
4644 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4645 (let ((org-odd-levels-only nil) n)
4646 (save-excursion
4647 (goto-char (point-min))
4648 (while (re-search-forward "^\\*\\*+" nil t)
4649 (setq n (/ (length (match-string 0)) 2))
4650 (while (>= (setq n (1- n)) 0)
4651 (org-promote))
4652 (end-of-line 1))))))
4654 (defun org-tr-level (n)
4655 "Make N odd if required."
4656 (if org-odd-levels-only (1+ (/ n 2)) n))
4658 ;;; Vertical tree motion, cutting and pasting of subtrees
4660 (defun org-move-subtree-up (&optional arg)
4661 "Move the current subtree up past ARG headlines of the same level."
4662 (interactive "p")
4663 (org-move-subtree-down (- (prefix-numeric-value arg))))
4665 (defun org-move-subtree-down (&optional arg)
4666 "Move the current subtree down past ARG headlines of the same level."
4667 (interactive "p")
4668 (setq arg (prefix-numeric-value arg))
4669 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4670 'outline-get-last-sibling))
4671 (ins-point (make-marker))
4672 (cnt (abs arg))
4673 beg end txt folded)
4674 ;; Select the tree
4675 (org-back-to-heading)
4676 (setq beg (point))
4677 (save-match-data
4678 (save-excursion (outline-end-of-heading)
4679 (setq folded (org-invisible-p)))
4680 (outline-end-of-subtree))
4681 (outline-next-heading)
4682 (setq end (point))
4683 ;; Find insertion point, with error handling
4684 (goto-char beg)
4685 (while (> cnt 0)
4686 (or (and (funcall movfunc) (looking-at outline-regexp))
4687 (progn (goto-char beg)
4688 (error "Cannot move past superior level or buffer limit")))
4689 (setq cnt (1- cnt)))
4690 (if (> arg 0)
4691 ;; Moving forward - still need to move over subtree
4692 (progn (outline-end-of-subtree)
4693 (outline-next-heading)
4694 (if (not (or (looking-at (concat "^" outline-regexp))
4695 (bolp)))
4696 (newline))))
4697 (move-marker ins-point (point))
4698 (setq txt (buffer-substring beg end))
4699 (delete-region beg end)
4700 (insert txt)
4701 (goto-char ins-point)
4702 (if folded (hide-subtree))
4703 (move-marker ins-point nil)))
4705 (defvar org-subtree-clip ""
4706 "Clipboard for cut and paste of subtrees.
4707 This is actually only a copy of the kill, because we use the normal kill
4708 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4710 (defvar org-subtree-clip-folded nil
4711 "Was the last copied subtree folded?
4712 This is used to fold the tree back after pasting.")
4714 (defun org-cut-subtree ()
4715 "Cut the current subtree into the clipboard.
4716 This is a short-hand for marking the subtree and then cutting it."
4717 (interactive)
4718 (org-copy-subtree 'cut))
4720 (defun org-copy-subtree (&optional cut)
4721 "Cut the current subtree into the clipboard.
4722 This is a short-hand for marking the subtree and then copying it.
4723 If CUT is non-nil, actually cut the subtree."
4724 (interactive)
4725 (let (beg end folded)
4726 (org-back-to-heading)
4727 (setq beg (point))
4728 (save-match-data
4729 (save-excursion (outline-end-of-heading)
4730 (setq folded (org-invisible-p)))
4731 (outline-end-of-subtree))
4732 (if (equal (char-after) ?\n) (forward-char 1))
4733 (setq end (point))
4734 (goto-char beg)
4735 (when (> end beg)
4736 (setq org-subtree-clip-folded folded)
4737 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4738 (setq org-subtree-clip (current-kill 0))
4739 (message "%s: Subtree with %d characters"
4740 (if cut "Cut" "Copied")
4741 (length org-subtree-clip)))))
4743 (defun org-paste-subtree (&optional level tree)
4744 "Paste the clipboard as a subtree, with modification of headline level.
4745 The entire subtree is promoted or demoted in order to match a new headline
4746 level. By default, the new level is derived from the visible headings
4747 before and after the insertion point, and taken to be the inferior headline
4748 level of the two. So if the previous visible heading is level 3 and the
4749 next is level 4 (or vice versa), level 4 will be used for insertion.
4750 This makes sure that the subtree remains an independent subtree and does
4751 not swallow low level entries.
4753 You can also force a different level, either by using a numeric prefix
4754 argument, or by inserting the heading marker by hand. For example, if the
4755 cursor is after \"*****\", then the tree will be shifted to level 5.
4757 If you want to insert the tree as is, just use \\[yank].
4759 If optional TREE is given, use this text instead of the kill ring."
4760 (interactive "P")
4761 (unless (org-kill-is-subtree-p tree)
4762 (error
4763 (substitute-command-keys
4764 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4765 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4766 (^re (concat "^\\(" outline-regexp "\\)"))
4767 (re (concat "\\(" outline-regexp "\\)"))
4768 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4770 (old-level (if (string-match ^re txt)
4771 (- (match-end 0) (match-beginning 0))
4772 -1))
4773 (force-level (cond (level (prefix-numeric-value level))
4774 ((string-match
4775 ^re_ (buffer-substring (point-at-bol) (point)))
4776 (- (match-end 0) (match-beginning 0)))
4777 (t nil)))
4778 (previous-level (save-excursion
4779 (condition-case nil
4780 (progn
4781 (outline-previous-visible-heading 1)
4782 (if (looking-at re)
4783 (- (match-end 0) (match-beginning 0))
4785 (error 1))))
4786 (next-level (save-excursion
4787 (condition-case nil
4788 (progn
4789 (outline-next-visible-heading 1)
4790 (if (looking-at re)
4791 (- (match-end 0) (match-beginning 0))
4793 (error 1))))
4794 (new-level (or force-level (max previous-level next-level)))
4795 (shift (if (or (= old-level -1)
4796 (= new-level -1)
4797 (= old-level new-level))
4799 (- new-level old-level)))
4800 (shift1 shift)
4801 (delta (if (> shift 0) -1 1))
4802 (func (if (> shift 0) 'org-demote 'org-promote))
4803 (org-odd-levels-only nil)
4804 beg end)
4805 ;; Remove the forces level indicator
4806 (if force-level
4807 (delete-region (point-at-bol) (point)))
4808 ;; Make sure we start at the beginning of an empty line
4809 (if (not (bolp)) (insert "\n"))
4810 (if (not (looking-at "[ \t]*$"))
4811 (progn (insert "\n") (backward-char 1)))
4812 ;; Paste
4813 (setq beg (point))
4814 (if (string-match "[ \t\r\n]+\\'" txt)
4815 (setq txt (replace-match "\n" t t txt)))
4816 (insert txt)
4817 (setq end (point))
4818 (if (looking-at "[ \t\r\n]+")
4819 (replace-match "\n"))
4820 (goto-char beg)
4821 ;; Shift if necessary
4822 (if (= shift 0)
4823 (message "Pasted at level %d, without shift" new-level)
4824 (save-restriction
4825 (narrow-to-region beg end)
4826 (while (not (= shift 0))
4827 (org-map-region func (point-min) (point-max))
4828 (setq shift (+ delta shift)))
4829 (goto-char (point-min))
4830 (message "Pasted at level %d, with shift by %d levels"
4831 new-level shift1)))
4832 (if (and kill-ring
4833 (eq org-subtree-clip (current-kill 0))
4834 org-subtree-clip-folded)
4835 ;; The tree was folded before it was killed/copied
4836 (hide-subtree))))
4838 (defun org-kill-is-subtree-p (&optional txt)
4839 "Check if the current kill is an outline subtree, or a set of trees.
4840 Returns nil if kill does not start with a headline, or if the first
4841 headline level is not the largest headline level in the tree.
4842 So this will actually accept several entries of equal levels as well,
4843 which is OK for `org-paste-subtree'.
4844 If optional TXT is given, check this string instead of the current kill."
4845 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4846 (start-level (and kill
4847 (string-match (concat "\\`" outline-regexp) kill)
4848 (- (match-end 0) (match-beginning 0))))
4849 (re (concat "^" outline-regexp))
4850 (start 1))
4851 (if (not start-level)
4852 nil ;; does not even start with a heading
4853 (catch 'exit
4854 (while (setq start (string-match re kill (1+ start)))
4855 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4856 (throw 'exit nil)))
4857 t))))
4859 (defun org-narrow-to-subtree ()
4860 "Narrow buffer to the current subtree."
4861 (interactive)
4862 (save-excursion
4863 (narrow-to-region
4864 (progn (org-back-to-heading) (point))
4865 (progn (org-end-of-subtree t) (point)))))
4868 ;;; Outline Sorting
4870 (defun org-sort (with-case)
4871 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
4872 (interactive "P")
4873 (if (org-at-table-p)
4874 (org-call-with-arg 'org-table-sort-lines with-case)
4875 (org-call-with-arg 'org-sort-entries with-case)))
4877 (defun org-sort-entries (&optional with-case sorting-type)
4878 "Sort entries on a certain level of an outline tree.
4879 If there is an active region, the entries in the region are sorted.
4880 If not, the children of the entry at point are sorted.
4882 Sorting can be alphabetically, numerically, and by date/time as given by
4883 the first time stamp in the entry. The command prompts for the sorting
4884 type unless it has been given to the function through the SORTING-TYPE
4885 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
4887 Comparing entries ignores case by default. However, with an optional argument
4888 WITH-CASE, the sorting considers case as well. With two prefix arguments
4889 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
4890 (interactive "P")
4891 (let ((unique (equal with-case '(16)))
4892 start beg end entries stars re re2 p nentries (nremoved 0) last txt)
4894 ;; Find beginning and end of region to sort
4895 (if (org-region-active-p)
4896 (progn
4897 ;; we will sort the region
4898 (setq end (region-end))
4899 (goto-char (1- (setq start (region-beginning)))))
4900 ;; we will sort the children of the current headline
4901 (setq start (point) end (org-end-of-subtree))
4902 (goto-char start)
4903 (show-subtree))
4904 (outline-next-heading) ; this is the first heading to be included
4905 (setq beg (point))
4906 (if (>= (point) end) (error "Nothing to sort"))
4907 (looking-at "\\(\\*+\\)")
4908 (setq stars (match-string 1)
4909 re (concat "^" (regexp-quote stars) " +")
4910 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4911 txt (buffer-substring beg end))
4912 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4913 (if (string-match re2 txt)
4914 (error "Region to sort contains a level above the first entry"))
4915 ;; Make a list that can be sorted.
4916 ;; The car is the string for comparison, the cdr is the subtree
4917 (message "Sorting entries...")
4918 (setq entries
4919 (mapcar
4920 (lambda (x)
4921 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
4922 (cons (match-string 0 x) x))
4923 (org-split-string txt re)))
4925 ;; Sort the list
4926 (setq entries (org-do-sort
4927 entries
4928 (if (org-region-active-p) "region" "children")
4929 with-case sorting-type))
4931 ;; Delete the old stuff
4932 (goto-char beg)
4933 (kill-region beg end)
4934 (setq nentries (length entries))
4935 ;; Insert the sorted entries, and remove duplicates if this is required
4936 (while (setq p (pop entries))
4937 (if (and unique (equal last (setq last (org-trim (cdr p)))))
4938 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
4939 (insert stars " " (cdr p))))
4940 (goto-char start)
4941 (message "Sorting entries...done (%d entries%s)"
4942 nentries
4943 (if unique (format ", %d duplicates removed" nremoved) ""))))
4945 (defun org-do-sort (table what &optional with-case sorting-type)
4946 "Sort TABLE of WHAT according to SORTING-TYPE.
4947 The user will be prompted for the SORTING-TYPE if the call to this
4948 function does not specify it. WHAT is only for the prompt, to indicate
4949 what is being sorted. The sorting key will be extracted from
4950 the car of the elements of the table.
4951 If WITH-CASE is non-nil, the sorting will be case-sensitive."
4952 (unless sorting-type
4953 (message
4954 "Sort %s:[a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
4955 what)
4956 (setq sorting-type (read-char-exclusive)))
4957 (let ((dcst (downcase sorting-type))
4958 extractfun comparefun)
4959 ;; Define the appropriate functions
4960 (cond
4961 ((= dcst ?n)
4962 (setq extractfun 'string-to-number
4963 comparefun (if (= dcst sorting-type) '< '>)))
4964 ((= dcst ?a)
4965 (setq extractfun (if with-case 'identity 'downcase)
4966 comparefun (if (= dcst sorting-type)
4967 'string<
4968 (lambda (a b) (and (not (string< a b))
4969 (not (string= a b)))))))
4970 ((= dcst ?t)
4971 (setq extractfun
4972 (lambda (x)
4973 (if (string-match org-ts-regexp x)
4974 (time-to-seconds
4975 (org-time-string-to-time (match-string 0 x)))
4977 comparefun (if (= dcst sorting-type) '< '>)))
4978 (t (error "Invalid sorting type `%c'" sorting-type)))
4980 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
4981 table)
4982 (lambda (a b) (funcall comparefun (car a) (car b))))))
4984 ;;;; Plain list items, including checkboxes
4986 ;;; Plain list items
4988 (defun org-at-item-p ()
4989 "Is point in a line starting a hand-formatted item?"
4990 (let ((llt org-plain-list-ordered-item-terminator))
4991 (save-excursion
4992 (goto-char (point-at-bol))
4993 (looking-at
4994 (cond
4995 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4996 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4997 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4998 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5001 (defun org-in-item-p ()
5002 "It the cursor inside a plain list item.
5003 Does not have to be the first line."
5004 (save-excursion
5005 (condition-case nil
5006 (progn
5007 (org-beginning-of-item)
5008 (org-at-item-p)
5010 (error nil))))
5012 (defun org-insert-item (&optional checkbox)
5013 "Insert a new item at the current level.
5014 Return t when things worked, nil when we are not in an item."
5015 (when (save-excursion
5016 (condition-case nil
5017 (progn
5018 (org-beginning-of-item)
5019 (org-at-item-p)
5020 (if (org-invisible-p) (error "Invisible item"))
5022 (error nil)))
5023 (let* ((bul (match-string 0))
5024 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5025 (match-end 0)))
5026 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5027 pos)
5028 (cond
5029 ((and (org-at-item-p) (<= (point) eow))
5030 ;; before the bullet
5031 (beginning-of-line 1)
5032 (open-line (if blank 2 1)))
5033 ((<= (point) eow)
5034 (beginning-of-line 1))
5035 (t (newline (if blank 2 1))))
5036 (insert bul (if checkbox "[ ]" ""))
5037 (just-one-space)
5038 (setq pos (point))
5039 (end-of-line 1)
5040 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5041 (org-maybe-renumber-ordered-list)
5042 (and checkbox (org-update-checkbox-count-maybe))
5045 ;;; Checkboxes
5047 (defun org-at-item-checkbox-p ()
5048 "Is point at a line starting a plain-list item with a checklet?"
5049 (and (org-at-item-p)
5050 (save-excursion
5051 (goto-char (match-end 0))
5052 (skip-chars-forward " \t")
5053 (looking-at "\\[[ X]\\]"))))
5055 (defun org-toggle-checkbox (&optional arg)
5056 "Toggle the checkbox in the current line."
5057 (interactive "P")
5058 (catch 'exit
5059 (let (beg end status (firstnew 'unknown))
5060 (cond
5061 ((org-region-active-p)
5062 (setq beg (region-beginning) end (region-end)))
5063 ((org-on-heading-p)
5064 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5065 ((org-at-item-checkbox-p)
5066 (save-excursion
5067 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
5068 (throw 'exit t))
5069 (t (error "Not at a checkbox or heading, and no active region")))
5070 (save-excursion
5071 (goto-char beg)
5072 (while (< (point) end)
5073 (when (org-at-item-checkbox-p)
5074 (setq status (equal (match-string 0) "[X]"))
5075 (when (eq firstnew 'unknown)
5076 (setq firstnew (not status)))
5077 (replace-match
5078 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5079 (beginning-of-line 2)))))
5080 (org-update-checkbox-count-maybe))
5082 (defun org-update-checkbox-count-maybe ()
5083 "Update checkbox statistics unless turned off by user."
5084 (when org-provide-checkbox-statistics
5085 (org-update-checkbox-count)))
5087 (defun org-update-checkbox-count (&optional all)
5088 "Update the checkbox statistics in the current section.
5089 This will find all statistic cookies like [57%] and [6/12] and update them
5090 with the current numbers. With optional prefix argument ALL, do this for
5091 the whole buffer."
5092 (interactive "P")
5093 (save-excursion
5094 (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
5095 (beg (progn (outline-back-to-heading) (point)))
5096 (end (move-marker (make-marker)
5097 (progn (outline-next-heading) (point))))
5098 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5099 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
5100 b1 e1 f1 c-on c-off lim (cstat 0))
5101 (when all
5102 (goto-char (point-min))
5103 (outline-next-heading)
5104 (setq beg (point) end (point-max)))
5105 (goto-char beg)
5106 (while (re-search-forward re end t)
5107 (setq cstat (1+ cstat)
5108 b1 (match-beginning 0)
5109 e1 (match-end 0)
5110 f1 (match-beginning 1)
5111 lim (cond
5112 ((org-on-heading-p) (outline-next-heading) (point))
5113 ((org-at-item-p) (org-end-of-item) (point))
5114 (t nil))
5115 c-on 0 c-off 0)
5116 (goto-char e1)
5117 (when lim
5118 (while (re-search-forward re-box lim t)
5119 (if (equal (match-string 2) "[ ]")
5120 (setq c-off (1+ c-off))
5121 (setq c-on (1+ c-on))))
5122 (delete-region b1 e1)
5123 (goto-char b1)
5124 (insert (if f1
5125 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5126 (format "[%d/%d]" c-on (+ c-on c-off))))))
5127 (when (interactive-p)
5128 (message "Checkbox satistics updated %s (%d places)"
5129 (if all "in entire file" "in current outline entry") cstat)))))
5131 (defun org-get-checkbox-statistics-face ()
5132 "Select the face for checkbox statistics.
5133 The face will be `org-done' when all relevant boxes are checked. Otherwise
5134 it will be `org-todo'."
5135 (if (match-end 1)
5136 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5137 (if (and (> (match-end 2) (match-beginning 2))
5138 (equal (match-string 2) (match-string 3)))
5139 'org-done
5140 'org-todo)))
5142 (defun org-get-indentation (&optional line)
5143 "Get the indentation of the current line, interpreting tabs.
5144 When LINE is given, assume it represents a line and compute its indentation."
5145 (if line
5146 (if (string-match "^ *" (org-remove-tabs line))
5147 (match-end 0))
5148 (save-excursion
5149 (beginning-of-line 1)
5150 (skip-chars-forward " \t")
5151 (current-column))))
5153 (defun org-remove-tabs (s &optional width)
5154 "Replace tabulators in S with spaces.
5155 Assumes that s is a single line, starting in column 0."
5156 (setq width (or width tab-width))
5157 (while (string-match "\t" s)
5158 (setq s (replace-match
5159 (make-string
5160 (- (* width (/ (+ (match-beginning 0) width) width))
5161 (match-beginning 0)) ?\ )
5162 t t s)))
5165 (defun org-fix-indentation (line ind)
5166 "Fix indentation in LINE.
5167 IND is a cons cell with target and minimum indentation.
5168 If the current indenation in LINE is smaller than the minimum,
5169 leave it alone. If it is larger than ind, set it to the target."
5170 (let* ((l (org-remove-tabs line))
5171 (i (org-get-indentation l))
5172 (i1 (car ind)) (i2 (cdr ind)))
5173 (if (>= i i2) (setq l (substring line i2)))
5174 (if (> i1 0)
5175 (concat (make-string i1 ?\ ) l)
5176 l)))
5178 (defun org-beginning-of-item ()
5179 "Go to the beginning of the current hand-formatted item.
5180 If the cursor is not in an item, throw an error."
5181 (interactive)
5182 (let ((pos (point))
5183 (limit (save-excursion (org-back-to-heading)
5184 (beginning-of-line 2) (point)))
5185 ind ind1)
5186 (if (org-at-item-p)
5187 (beginning-of-line 1)
5188 (beginning-of-line 1)
5189 (skip-chars-forward " \t")
5190 (setq ind (current-column))
5191 (if (catch 'exit
5192 (while t
5193 (beginning-of-line 0)
5194 (if (< (point) limit) (throw 'exit nil))
5195 (unless (looking-at "[ \t]*$")
5196 (skip-chars-forward " \t")
5197 (setq ind1 (current-column))
5198 (if (< ind1 ind)
5199 (throw 'exit (org-at-item-p))))))
5201 (goto-char pos)
5202 (error "Not in an item")))))
5204 (defun org-end-of-item ()
5205 "Go to the end of the current hand-formatted item.
5206 If the cursor is not in an item, throw an error."
5207 (interactive)
5208 (let ((pos (point))
5209 (limit (save-excursion (outline-next-heading) (point)))
5210 (ind (save-excursion
5211 (org-beginning-of-item)
5212 (skip-chars-forward " \t")
5213 (current-column)))
5214 ind1)
5215 (if (catch 'exit
5216 (while t
5217 (beginning-of-line 2)
5218 (if (>= (point) limit) (throw 'exit t))
5219 (unless (looking-at "[ \t]*$")
5220 (skip-chars-forward " \t")
5221 (setq ind1 (current-column))
5222 (if (<= ind1 ind) (throw 'exit t)))))
5223 (beginning-of-line 1)
5224 (goto-char pos)
5225 (error "Not in an item"))))
5227 (defun org-next-item ()
5228 "Move to the beginning of the next item in the current plain list.
5229 Error if not at a plain list, or if this is the last item in the list."
5230 (interactive)
5231 (let (ind ind1 (pos (point)))
5232 (org-beginning-of-item)
5233 (setq ind (org-get-indentation))
5234 (org-end-of-item)
5235 (setq ind1 (org-get-indentation))
5236 (unless (and (org-at-item-p) (= ind ind1))
5237 (goto-char pos)
5238 (error "On last item"))))
5240 (defun org-previous-item ()
5241 "Move to the beginning of the previous item in the current plain list.
5242 Error if not at a plain list, or if this is the last item in the list."
5243 (interactive)
5244 (let (beg ind (pos (point)))
5245 (org-beginning-of-item)
5246 (setq beg (point))
5247 (setq ind (org-get-indentation))
5248 (goto-char beg)
5249 (catch 'exit
5250 (while t
5251 (beginning-of-line 0)
5252 (if (looking-at "[ \t]*$")
5254 (if (<= (org-get-indentation) ind)
5255 (throw 'exit t)))))
5256 (condition-case nil
5257 (org-beginning-of-item)
5258 (error (goto-char pos)
5259 (error "On first item")))))
5261 (defun org-move-item-down ()
5262 "Move the plain list item at point down, i.e. swap with following item.
5263 Subitems (items with larger indentation) are considered part of the item,
5264 so this really moves item trees."
5265 (interactive)
5266 (let (beg end ind ind1 (pos (point)) txt)
5267 (org-beginning-of-item)
5268 (setq beg (point))
5269 (setq ind (org-get-indentation))
5270 (org-end-of-item)
5271 (setq end (point))
5272 (setq ind1 (org-get-indentation))
5273 (if (and (org-at-item-p) (= ind ind1))
5274 (progn
5275 (org-end-of-item)
5276 (setq txt (buffer-substring beg end))
5277 (save-excursion
5278 (delete-region beg end))
5279 (setq pos (point))
5280 (insert txt)
5281 (goto-char pos)
5282 (org-maybe-renumber-ordered-list))
5283 (goto-char pos)
5284 (error "Cannot move this item further down"))))
5286 (defun org-move-item-up (arg)
5287 "Move the plain list item at point up, i.e. swap with previous item.
5288 Subitems (items with larger indentation) are considered part of the item,
5289 so this really moves item trees."
5290 (interactive "p")
5291 (let (beg end ind ind1 (pos (point)) txt)
5292 (org-beginning-of-item)
5293 (setq beg (point))
5294 (setq ind (org-get-indentation))
5295 (org-end-of-item)
5296 (setq end (point))
5297 (goto-char beg)
5298 (catch 'exit
5299 (while t
5300 (beginning-of-line 0)
5301 (if (looking-at "[ \t]*$")
5303 (if (<= (setq ind1 (org-get-indentation)) ind)
5304 (throw 'exit t)))))
5305 (condition-case nil
5306 (org-beginning-of-item)
5307 (error (goto-char beg)
5308 (error "Cannot move this item further up")))
5309 (setq ind1 (org-get-indentation))
5310 (if (and (org-at-item-p) (= ind ind1))
5311 (progn
5312 (setq txt (buffer-substring beg end))
5313 (save-excursion
5314 (delete-region beg end))
5315 (setq pos (point))
5316 (insert txt)
5317 (goto-char pos)
5318 (org-maybe-renumber-ordered-list))
5319 (goto-char pos)
5320 (error "Cannot move this item further up"))))
5322 (defun org-maybe-renumber-ordered-list ()
5323 "Renumber the ordered list at point if setup allows it.
5324 This tests the user option `org-auto-renumber-ordered-lists' before
5325 doing the renumbering."
5326 (and org-auto-renumber-ordered-lists
5327 (org-at-item-p)
5328 (match-beginning 3)
5329 (org-renumber-ordered-list 1)))
5331 (defun org-get-string-indentation (s)
5332 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5333 (let ((n -1) (i 0) (w tab-width) c)
5334 (catch 'exit
5335 (while (< (setq n (1+ n)) (length s))
5336 (setq c (aref s n))
5337 (cond ((= c ?\ ) (setq i (1+ i)))
5338 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5339 (t (throw 'exit t)))))
5342 (defun org-renumber-ordered-list (arg)
5343 "Renumber an ordered plain list.
5344 Cursor needs to be in the first line of an item, the line that starts
5345 with something like \"1.\" or \"2)\"."
5346 (interactive "p")
5347 (unless (and (org-at-item-p)
5348 (match-beginning 3))
5349 (error "This is not an ordered list"))
5350 (let ((line (org-current-line))
5351 (col (current-column))
5352 (ind (org-get-string-indentation
5353 (buffer-substring (point-at-bol) (match-beginning 3))))
5354 ;; (term (substring (match-string 3) -1))
5355 ind1 (n (1- arg)))
5356 ;; find where this list begins
5357 (catch 'exit
5358 (while t
5359 (catch 'next
5360 (beginning-of-line 0)
5361 (if (looking-at "[ \t]*$") (throw 'next t))
5362 (skip-chars-forward " \t") (setq ind1 (current-column))
5363 (if (or (< ind1 ind)
5364 (and (= ind1 ind)
5365 (not (org-at-item-p))))
5366 (throw 'exit t)))))
5367 ;; Walk forward and replace these numbers
5368 (catch 'exit
5369 (while t
5370 (catch 'next
5371 (beginning-of-line 2)
5372 (if (eobp) (throw 'exit nil))
5373 (if (looking-at "[ \t]*$") (throw 'next nil))
5374 (skip-chars-forward " \t") (setq ind1 (current-column))
5375 (if (> ind1 ind) (throw 'next t))
5376 (if (< ind1 ind) (throw 'exit t))
5377 (if (not (org-at-item-p)) (throw 'exit nil))
5378 (if (not (match-beginning 3))
5379 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
5380 (delete-region (match-beginning 3) (1- (match-end 3)))
5381 (goto-char (match-beginning 3))
5382 (insert (format "%d" (setq n (1+ n)))))))
5383 (goto-line line)
5384 (move-to-column col)))
5386 (defvar org-last-indent-begin-marker (make-marker))
5387 (defvar org-last-indent-end-marker (make-marker))
5389 (defun org-outdent-item (arg)
5390 "Outdent a local list item."
5391 (interactive "p")
5392 (org-indent-item (- arg)))
5394 (defun org-indent-item (arg)
5395 "Indent a local list item."
5396 (interactive "p")
5397 (unless (org-at-item-p)
5398 (error "Not on an item"))
5399 (save-excursion
5400 (let (beg end ind ind1)
5401 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5402 (setq beg org-last-indent-begin-marker
5403 end org-last-indent-end-marker)
5404 (org-beginning-of-item)
5405 (setq beg (move-marker org-last-indent-begin-marker (point)))
5406 (org-end-of-item)
5407 (setq end (move-marker org-last-indent-end-marker (point))))
5408 (goto-char beg)
5409 (skip-chars-forward " \t") (setq ind (current-column))
5410 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
5411 (while (< (point) end)
5412 (beginning-of-line 1)
5413 (skip-chars-forward " \t") (setq ind1 (current-column))
5414 (delete-region (point-at-bol) (point))
5415 (indent-to-column (+ ind1 arg))
5416 (beginning-of-line 2)))))
5418 ;;;; Archiving
5420 (defun org-archive-subtree (&optional find-done)
5421 "Move the current subtree to the archive.
5422 The archive can be a certain top-level heading in the current file, or in
5423 a different file. The tree will be moved to that location, the subtree
5424 heading be marked DONE, and the current time will be added.
5426 When called with prefix argument FIND-DONE, find whole trees without any
5427 open TODO items and archive them (after getting confirmation from the user).
5428 If the cursor is not at a headline when this comand is called, try all level
5429 1 trees. If the cursor is on a headline, only try the direct children of
5430 this heading. "
5431 (interactive "P")
5432 (if find-done
5433 (org-archive-all-done)
5434 ;; Save all relevant TODO keyword-relatex variables
5436 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5437 (tr-org-todo-keywords org-todo-keywords)
5438 (tr-org-todo-interpretation org-todo-interpretation)
5439 (tr-org-done-string org-done-string)
5440 (tr-org-todo-regexp org-todo-regexp)
5441 (tr-org-todo-line-regexp org-todo-line-regexp)
5442 (this-buffer (current-buffer))
5443 file heading buffer level newfile-p)
5444 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5445 (progn
5446 (setq file (format (match-string 1 org-archive-location)
5447 (file-name-nondirectory buffer-file-name))
5448 heading (match-string 2 org-archive-location)))
5449 (error "Invalid `org-archive-location'"))
5450 (if (> (length file) 0)
5451 (setq newfile-p (not (file-exists-p file))
5452 buffer (find-file-noselect file))
5453 (setq buffer (current-buffer)))
5454 (unless buffer
5455 (error "Cannot access file \"%s\"" file))
5456 (if (and (> (length heading) 0)
5457 (string-match "^\\*+" heading))
5458 (setq level (match-end 0))
5459 (setq heading nil level 0))
5460 (save-excursion
5461 ;; We first only copy, in case something goes wrong
5462 ;; we need to protect this-command, to avoid kill-region sets it,
5463 ;; which would lead to duplication of subtrees
5464 (let (this-command) (org-copy-subtree))
5465 (set-buffer buffer)
5466 ;; Enforce org-mode for the archive buffer
5467 (if (not (org-mode-p))
5468 ;; Force the mode for future visits.
5469 (let ((org-insert-mode-line-in-empty-file t))
5470 (call-interactively 'org-mode)))
5471 (when newfile-p
5472 (goto-char (point-max))
5473 (insert (format "\nArchived entries from file %s\n\n"
5474 (buffer-file-name this-buffer))))
5475 ;; Force the TODO keywords of the original buffer
5476 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
5477 (org-todo-keywords tr-org-todo-keywords)
5478 (org-todo-interpretation tr-org-todo-interpretation)
5479 (org-done-string tr-org-done-string)
5480 (org-todo-regexp tr-org-todo-regexp)
5481 (org-todo-line-regexp tr-org-todo-line-regexp))
5482 (goto-char (point-min))
5483 (if heading
5484 (progn
5485 (if (re-search-forward
5486 (concat "\\(^\\|\r\\)"
5487 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
5488 nil t)
5489 (goto-char (match-end 0))
5490 ;; Heading not found, just insert it at the end
5491 (goto-char (point-max))
5492 (or (bolp) (insert "\n"))
5493 (insert "\n" heading "\n")
5494 (end-of-line 0))
5495 ;; Make the subtree visible
5496 (show-subtree)
5497 (org-end-of-subtree t)
5498 (skip-chars-backward " \t\r\n")
5499 (and (looking-at "[ \t\r\n]*")
5500 (replace-match "\n\n")))
5501 ;; No specific heading, just go to end of file.
5502 (goto-char (point-max)) (insert "\n"))
5503 ;; Paste
5504 (org-paste-subtree (1+ level))
5505 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
5506 (if org-archive-mark-done
5507 (let (org-log-done)
5508 (org-todo (length org-todo-keywords))))
5509 ;; Move cursor to right after the TODO keyword
5510 (when org-archive-stamp-time
5511 (beginning-of-line 1)
5512 (looking-at org-todo-line-regexp)
5513 (goto-char (or (match-end 2) (match-beginning 3)))
5514 (org-insert-time-stamp (org-current-time) t t "(" ")"))
5515 ;; Save the buffer, if it is not the same buffer.
5516 (if (not (eq this-buffer buffer)) (save-buffer))))
5517 ;; Here we are back in the original buffer. Everything seems to have
5518 ;; worked. So now cut the tree and finish up.
5519 (let (this-command) (org-cut-subtree))
5520 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5521 (message "Subtree archived %s"
5522 (if (eq this-buffer buffer)
5523 (concat "under heading: " heading)
5524 (concat "in file: " (abbreviate-file-name file)))))))
5526 (defun org-archive-all-done (&optional tag)
5527 "Archive sublevels of the current tree without open TODO items.
5528 If the cursor is not on a headline, try all level 1 trees. If
5529 it is on a headline, try all direct children.
5530 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5531 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5532 (rea (concat ".*:" org-archive-tag ":"))
5533 (begm (make-marker))
5534 (endm (make-marker))
5535 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
5536 "Move subtree to archive (no open TODO items)? "))
5537 beg end (cntarch 0))
5538 (if (org-on-heading-p)
5539 (progn
5540 (setq re1 (concat "^" (regexp-quote
5541 (make-string
5542 (1+ (- (match-end 0) (match-beginning 0)))
5543 ?*))
5544 " "))
5545 (move-marker begm (point))
5546 (move-marker endm (org-end-of-subtree t)))
5547 (setq re1 "^* ")
5548 (move-marker begm (point-min))
5549 (move-marker endm (point-max)))
5550 (save-excursion
5551 (goto-char begm)
5552 (while (re-search-forward re1 endm t)
5553 (setq beg (match-beginning 0)
5554 end (save-excursion (org-end-of-subtree t) (point)))
5555 (goto-char beg)
5556 (if (re-search-forward re end t)
5557 (goto-char end)
5558 (goto-char beg)
5559 (if (and (or (not tag) (not (looking-at rea)))
5560 (y-or-n-p question))
5561 (progn
5562 (if tag
5563 (org-toggle-tag org-archive-tag 'on)
5564 (org-archive-subtree))
5565 (setq cntarch (1+ cntarch)))
5566 (goto-char end)))))
5567 (message "%d trees archived" cntarch)))
5569 (defun org-cycle-hide-archived-subtrees (state)
5570 "Re-hide all archived subtrees after a visibility state change."
5571 (when (and (not org-cycle-open-archived-trees)
5572 (not (memq state '(overview folded))))
5573 (save-excursion
5574 (let* ((globalp (memq state '(contents all)))
5575 (beg (if globalp (point-min) (point)))
5576 (end (if globalp (point-max) (org-end-of-subtree t))))
5577 (org-hide-archived-subtrees beg end)
5578 (goto-char beg)
5579 (if (looking-at (concat ".*:" org-archive-tag ":"))
5580 (message (substitute-command-keys
5581 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5583 (defun org-force-cycle-archived ()
5584 "Cycle subtree even if it is archived."
5585 (interactive)
5586 (setq this-command 'org-cycle)
5587 (let ((org-cycle-open-archived-trees t))
5588 (call-interactively 'org-cycle)))
5590 (defun org-hide-archived-subtrees (beg end)
5591 "Re-hide all archived subtrees after a visibility state change."
5592 (save-excursion
5593 (let* ((re (concat ":" org-archive-tag ":")))
5594 (goto-char beg)
5595 (while (re-search-forward re end t)
5596 (and (org-on-heading-p) (hide-subtree))
5597 (org-end-of-subtree t)))))
5599 (defun org-toggle-tag (tag &optional onoff)
5600 "Toggle the tag TAG for the current line.
5601 If ONOFF is `on' or `off', don't toggle but set to this state."
5602 (unless (org-on-heading-p) (error "Not on headling"))
5603 (let (res current)
5604 (save-excursion
5605 (beginning-of-line)
5606 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5607 (point-at-eol) t)
5608 (progn
5609 (setq current (match-string 1))
5610 (replace-match ""))
5611 (setq current ""))
5612 (setq current (nreverse (org-split-string current ":")))
5613 (cond
5614 ((eq onoff 'on)
5615 (setq res t)
5616 (or (member tag current) (push tag current)))
5617 ((eq onoff 'off)
5618 (or (not (member tag current)) (setq current (delete tag current))))
5619 (t (if (member tag current)
5620 (setq current (delete tag current))
5621 (setq res t)
5622 (push tag current))))
5623 (end-of-line 1)
5624 (when current
5625 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5626 (org-set-tags nil t))
5627 res))
5629 (defun org-toggle-archive-tag (&optional arg)
5630 "Toggle the archive tag for the current headline.
5631 With prefix ARG, check all children of current headline and offer tagging
5632 the children that do not contain any open TODO items."
5633 (interactive "P")
5634 (if arg
5635 (org-archive-all-done 'tag)
5636 (let (set)
5637 (save-excursion
5638 (org-back-to-heading t)
5639 (setq set (org-toggle-tag org-archive-tag))
5640 (when set (hide-subtree)))
5641 (and set (beginning-of-line 1))
5642 (message "Subtree %s" (if set "archived" "unarchived")))))
5645 ;;;; Tables
5647 ;;; The table editor
5649 ;; Watch out: Here we are talking about two different kind of tables.
5650 ;; Most of the code is for the tables created with the Org-mode table editor.
5651 ;; Sometimes, we talk about tables created and edited with the table.el
5652 ;; Emacs package. We call the former org-type tables, and the latter
5653 ;; table.el-type tables.
5655 (defun org-before-change-function (beg end)
5656 "Every change indicates that a table might need an update."
5657 (setq org-table-may-need-update t))
5659 (defconst org-table-line-regexp "^[ \t]*|"
5660 "Detects an org-type table line.")
5661 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5662 "Detects an org-type table line.")
5663 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5664 "Detects a table line marked for automatic recalculation.")
5665 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5666 "Detects a table line marked for automatic recalculation.")
5667 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5668 "Detects a table line marked for automatic recalculation.")
5669 (defconst org-table-hline-regexp "^[ \t]*|-"
5670 "Detects an org-type table hline.")
5671 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5672 "Detects a table-type table hline.")
5673 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5674 "Detects an org-type or table-type table.")
5675 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5676 "Searching from within a table (any type) this finds the first line
5677 outside the table.")
5678 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5679 "Searching from within a table (any type) this finds the first line
5680 outside the table.")
5682 (defun org-table-create-with-table.el ()
5683 "Use the table.el package to insert a new table.
5684 If there is already a table at point, convert between Org-mode tables
5685 and table.el tables."
5686 (interactive)
5687 (require 'table)
5688 (cond
5689 ((org-at-table.el-p)
5690 (if (y-or-n-p "Convert table to Org-mode table? ")
5691 (org-table-convert)))
5692 ((org-at-table-p)
5693 (if (y-or-n-p "Convert table to table.el table? ")
5694 (org-table-convert)))
5695 (t (call-interactively 'table-insert))))
5697 (defun org-table-create-or-convert-from-region (arg)
5698 "Convert region to table, or create an empty table.
5699 If there is an active region, convert it to a table. If there is no such
5700 region, create an empty table."
5701 (interactive "P")
5702 (if (org-region-active-p)
5703 (org-table-convert-region (region-beginning) (region-end) arg)
5704 (org-table-create arg)))
5706 (defun org-table-create (&optional size)
5707 "Query for a size and insert a table skeleton.
5708 SIZE is a string Columns x Rows like for example \"3x2\"."
5709 (interactive "P")
5710 (unless size
5711 (setq size (read-string
5712 (concat "Table size Columns x Rows [e.g. "
5713 org-table-default-size "]: ")
5714 "" nil org-table-default-size)))
5716 (let* ((pos (point))
5717 (indent (make-string (current-column) ?\ ))
5718 (split (org-split-string size " *x *"))
5719 (rows (string-to-number (nth 1 split)))
5720 (columns (string-to-number (car split)))
5721 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5722 "\n")))
5723 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5724 (point-at-bol) (point)))
5725 (beginning-of-line 1)
5726 (newline))
5727 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5728 (dotimes (i rows) (insert line))
5729 (goto-char pos)
5730 (if (> rows 1)
5731 ;; Insert a hline after the first row.
5732 (progn
5733 (end-of-line 1)
5734 (insert "\n|-")
5735 (goto-char pos)))
5736 (org-table-align)))
5738 (defun org-table-convert-region (beg0 end0 &optional nspace)
5739 "Convert region to a table.
5740 The region goes from BEG0 to END0, but these borders will be moved
5741 slightly, to make sure a beginning of line in the first line is included.
5742 When NSPACE is non-nil, it indicates the minimum number of spaces that
5743 separate columns (default: just one space)."
5744 (interactive "rP")
5745 (let* ((beg (min beg0 end0))
5746 (end (max beg0 end0))
5747 (tabsep t)
5749 (goto-char beg)
5750 (beginning-of-line 1)
5751 (setq beg (move-marker (make-marker) (point)))
5752 (goto-char end)
5753 (if (bolp) (backward-char 1) (end-of-line 1))
5754 (setq end (move-marker (make-marker) (point)))
5755 ;; Lets see if this is tab-separated material. If every nonempty line
5756 ;; contains a tab, we will assume that it is tab-separated material
5757 (if nspace
5758 (setq tabsep nil)
5759 (goto-char beg)
5760 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5761 (if nspace (setq tabsep nil))
5762 (if tabsep
5763 (setq re "^\\|\t")
5764 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5765 (max 1 (prefix-numeric-value nspace)))))
5766 (goto-char beg)
5767 (while (re-search-forward re end t)
5768 (replace-match "| " t t))
5769 (goto-char beg)
5770 (insert " ")
5771 (org-table-align)))
5773 (defun org-table-import (file arg)
5774 "Import FILE as a table.
5775 The file is assumed to be tab-separated. Such files can be produced by most
5776 spreadsheet and database applications. If no tabs (at least one per line)
5777 are found, lines will be split on whitespace into fields."
5778 (interactive "f\nP")
5779 (or (bolp) (newline))
5780 (let ((beg (point))
5781 (pm (point-max)))
5782 (insert-file-contents file)
5783 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5785 (defun org-table-export ()
5786 "Export table as a tab-separated file.
5787 Such a file can be imported into a spreadsheet program like Excel."
5788 (interactive)
5789 (let* ((beg (org-table-begin))
5790 (end (org-table-end))
5791 (table (buffer-substring beg end))
5792 (file (read-file-name "Export table to: "))
5793 buf)
5794 (unless (or (not (file-exists-p file))
5795 (y-or-n-p (format "Overwrite file %s? " file)))
5796 (error "Abort"))
5797 (with-current-buffer (find-file-noselect file)
5798 (setq buf (current-buffer))
5799 (erase-buffer)
5800 (fundamental-mode)
5801 (insert table)
5802 (goto-char (point-min))
5803 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5804 (replace-match "" t t)
5805 (end-of-line 1))
5806 (goto-char (point-min))
5807 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5808 (replace-match "" t t)
5809 (goto-char (min (1+ (point)) (point-max))))
5810 (goto-char (point-min))
5811 (while (re-search-forward "^-[-+]*$" nil t)
5812 (replace-match "")
5813 (if (looking-at "\n")
5814 (delete-char 1)))
5815 (goto-char (point-min))
5816 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5817 (replace-match "\t" t t))
5818 (save-buffer))
5819 (kill-buffer buf)))
5821 (defvar org-table-aligned-begin-marker (make-marker)
5822 "Marker at the beginning of the table last aligned.
5823 Used to check if cursor still is in that table, to minimize realignment.")
5824 (defvar org-table-aligned-end-marker (make-marker)
5825 "Marker at the end of the table last aligned.
5826 Used to check if cursor still is in that table, to minimize realignment.")
5827 (defvar org-table-last-alignment nil
5828 "List of flags for flushright alignment, from the last re-alignment.
5829 This is being used to correctly align a single field after TAB or RET.")
5830 (defvar org-table-last-column-widths nil
5831 "List of max width of fields in each column.
5832 This is being used to correctly align a single field after TAB or RET.")
5834 (defvar org-last-recalc-line nil)
5835 (defconst org-narrow-column-arrow "=>"
5836 "Used as display property in narrowed table columns.")
5838 (defun org-table-align ()
5839 "Align the table at point by aligning all vertical bars."
5840 (interactive)
5841 (let* (
5842 ;; Limits of table
5843 (beg (org-table-begin))
5844 (end (org-table-end))
5845 ;; Current cursor position
5846 (linepos (org-current-line))
5847 (colpos (org-table-current-column))
5848 (winstart (window-start))
5849 (winstartline (org-current-line (min winstart (1- (point-max)))))
5850 lines (new "") lengths l typenums ty fields maxfields i
5851 column
5852 (indent "") cnt frac
5853 rfmt hfmt
5854 (spaces '(1 . 1))
5855 (sp1 (car spaces))
5856 (sp2 (cdr spaces))
5857 (rfmt1 (concat
5858 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5859 (hfmt1 (concat
5860 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5861 emptystrings links dates narrow fmax f1 len c e)
5862 (untabify beg end)
5863 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
5864 ;; Check if we have links or dates
5865 (goto-char beg)
5866 (setq links (re-search-forward org-bracket-link-regexp end t))
5867 (goto-char beg)
5868 (setq dates (and org-display-custom-times
5869 (re-search-forward org-ts-regexp-both end t)))
5870 ;; Make sure the link properties are right
5871 (when links (goto-char beg) (while (org-activate-bracket-links end)))
5872 ;; Make sure the date properties are right
5873 (when dates (goto-char beg) (while (org-activate-dates end)))
5875 ;; Check if we are narrowing any columns
5876 (goto-char beg)
5877 (setq narrow (and org-format-transports-properties-p
5878 (re-search-forward "<[0-9]+>" end t)))
5879 ;; Get the rows
5880 (setq lines (org-split-string
5881 (buffer-substring beg end) "\n"))
5882 ;; Store the indentation of the first line
5883 (if (string-match "^ *" (car lines))
5884 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
5885 ;; Mark the hlines by setting the corresponding element to nil
5886 ;; At the same time, we remove trailing space.
5887 (setq lines (mapcar (lambda (l)
5888 (if (string-match "^ *|-" l)
5890 (if (string-match "[ \t]+$" l)
5891 (substring l 0 (match-beginning 0))
5892 l)))
5893 lines))
5894 ;; Get the data fields by splitting the lines.
5895 (setq fields (mapcar
5896 (lambda (l)
5897 (org-split-string l " *| *"))
5898 (delq nil (copy-sequence lines))))
5899 ;; How many fields in the longest line?
5900 (condition-case nil
5901 (setq maxfields (apply 'max (mapcar 'length fields)))
5902 (error
5903 (kill-region beg end)
5904 (org-table-create org-table-default-size)
5905 (error "Empty table - created default table")))
5906 ;; A list of empty strings to fill any short rows on output
5907 (setq emptystrings (make-list maxfields ""))
5908 ;; Check for special formatting.
5909 (setq i -1)
5910 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
5911 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
5912 ;; Check if there is an explicit width specified
5913 (when (and org-table-limit-column-width narrow)
5914 (setq c column fmax nil)
5915 (while c
5916 (setq e (pop c))
5917 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
5918 (setq fmax (string-to-number (match-string 1 e)) c nil)))
5919 ;; Find fields that are wider than fmax, and shorten them
5920 (when fmax
5921 (loop for xx in column do
5922 (when (and (stringp xx)
5923 (> (org-string-width xx) fmax))
5924 (org-add-props xx nil
5925 'help-echo
5926 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
5927 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
5928 (unless (> f1 1)
5929 (error "Cannot narrow field starting with wide link \"%s\""
5930 (match-string 0 xx)))
5931 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
5932 (add-text-properties (- f1 2) f1
5933 (list 'display org-narrow-column-arrow)
5934 xx)))))
5935 ;; Get the maximum width for each column
5936 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
5937 ;; Get the fraction of numbers, to decide about alignment of the column
5938 (setq cnt 0 frac 0.0)
5939 (loop for x in column do
5940 (if (equal x "")
5942 (setq frac ( / (+ (* frac cnt)
5943 (if (string-match org-table-number-regexp x) 1 0))
5944 (setq cnt (1+ cnt))))))
5945 (push (>= frac org-table-number-fraction) typenums))
5946 (setq lengths (nreverse lengths) typenums (nreverse typenums))
5948 ;; Store the alignment of this table, for later editing of single fields
5949 (setq org-table-last-alignment typenums
5950 org-table-last-column-widths lengths)
5952 ;; With invisible characters, `format' does not get the field width right
5953 ;; So we need to make these fields wide by hand.
5954 (when links
5955 (loop for i from 0 upto (1- maxfields) do
5956 (setq len (nth i lengths))
5957 (loop for j from 0 upto (1- (length fields)) do
5958 (setq c (nthcdr i (car (nthcdr j fields))))
5959 (if (and (stringp (car c))
5960 (string-match org-bracket-link-regexp (car c))
5961 (< (org-string-width (car c)) len))
5962 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
5964 ;; Compute the formats needed for output of the table
5965 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
5966 (while (setq l (pop lengths))
5967 (setq ty (if (pop typenums) "" "-")) ; number types flushright
5968 (setq rfmt (concat rfmt (format rfmt1 ty l))
5969 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
5970 (setq rfmt (concat rfmt "\n")
5971 hfmt (concat (substring hfmt 0 -1) "|\n"))
5973 (setq new (mapconcat
5974 (lambda (l)
5975 (if l (apply 'format rfmt
5976 (append (pop fields) emptystrings))
5977 hfmt))
5978 lines ""))
5979 ;; Replace the old one
5980 (delete-region beg end)
5981 (move-marker end nil)
5982 (move-marker org-table-aligned-begin-marker (point))
5983 (insert new)
5984 (move-marker org-table-aligned-end-marker (point))
5985 (when (and orgtbl-mode (not (org-mode-p)))
5986 (goto-char org-table-aligned-begin-marker)
5987 (while (org-hide-wide-columns org-table-aligned-end-marker)))
5988 ;; Try to move to the old location
5989 (goto-line winstartline)
5990 (setq winstart (point-at-bol))
5991 (goto-line linepos)
5992 (set-window-start (selected-window) winstart 'noforce)
5993 (org-table-goto-column colpos)
5994 (setq org-table-may-need-update nil)
5997 (defun org-string-width (s)
5998 "Compute width of string, ignoring invisible characters.
5999 This ignores character with invisibility property `org-link', and also
6000 characters with property `org-cwidth', because these will become invisible
6001 upon the next fontification round."
6002 (let (b l)
6003 (when (or (eq t buffer-invisibility-spec)
6004 (assq 'org-link buffer-invisibility-spec))
6005 (while (setq b (text-property-any 0 (length s)
6006 'invisible 'org-link s))
6007 (setq s (concat (substring s 0 b)
6008 (substring s (or (next-single-property-change
6009 b 'invisible s) (length s)))))))
6010 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
6011 (setq s (concat (substring s 0 b)
6012 (substring s (or (next-single-property-change
6013 b 'org-cwidth s) (length s))))))
6014 (setq l (string-width s) b -1)
6015 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
6016 (setq l (- l (get-text-property b 'org-dwidth-n s))))
6019 (defun org-table-begin (&optional table-type)
6020 "Find the beginning of the table and return its position.
6021 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6022 (save-excursion
6023 (if (not (re-search-backward
6024 (if table-type org-table-any-border-regexp
6025 org-table-border-regexp)
6026 nil t))
6027 (progn (goto-char (point-min)) (point))
6028 (goto-char (match-beginning 0))
6029 (beginning-of-line 2)
6030 (point))))
6032 (defun org-table-end (&optional table-type)
6033 "Find the end of the table and return its position.
6034 With argument TABLE-TYPE, go to the end of a table.el-type table."
6035 (save-excursion
6036 (if (not (re-search-forward
6037 (if table-type org-table-any-border-regexp
6038 org-table-border-regexp)
6039 nil t))
6040 (goto-char (point-max))
6041 (goto-char (match-beginning 0)))
6042 (point-marker)))
6044 (defun org-table-justify-field-maybe (&optional new)
6045 "Justify the current field, text to left, number to right.
6046 Optional argument NEW may specify text to replace the current field content."
6047 (cond
6048 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6049 ((org-at-table-hline-p))
6050 ((and (not new)
6051 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6052 (current-buffer)))
6053 (< (point) org-table-aligned-begin-marker)
6054 (>= (point) org-table-aligned-end-marker)))
6055 ;; This is not the same table, force a full re-align
6056 (setq org-table-may-need-update t))
6057 (t ;; realign the current field, based on previous full realign
6058 (let* ((pos (point)) s
6059 (col (org-table-current-column))
6060 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
6061 l f n o e)
6062 (when (> col 0)
6063 (skip-chars-backward "^|\n")
6064 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6065 (progn
6066 (setq s (match-string 1)
6067 o (match-string 0)
6068 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6069 e (not (= (match-beginning 2) (match-end 2))))
6070 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6071 l (if e "|" (setq org-table-may-need-update t) ""))
6072 n (format f s))
6073 (if new
6074 (if (<= (length new) l) ;; FIXME: length -> str-width?
6075 (setq n (format f new))
6076 (setq n (concat new "|") org-table-may-need-update t)))
6077 (or (equal n o)
6078 (let (org-table-may-need-update)
6079 (replace-match n))))
6080 (setq org-table-may-need-update t))
6081 (goto-char pos))))))
6083 (defun org-table-next-field ()
6084 "Go to the next field in the current table, creating new lines as needed.
6085 Before doing so, re-align the table if necessary."
6086 (interactive)
6087 (org-table-maybe-eval-formula)
6088 (org-table-maybe-recalculate-line)
6089 (if (and org-table-automatic-realign
6090 org-table-may-need-update)
6091 (org-table-align))
6092 (let ((end (org-table-end)))
6093 (if (org-at-table-hline-p)
6094 (end-of-line 1))
6095 (condition-case nil
6096 (progn
6097 (re-search-forward "|" end)
6098 (if (looking-at "[ \t]*$")
6099 (re-search-forward "|" end))
6100 (if (and (looking-at "-")
6101 org-table-tab-jumps-over-hlines
6102 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
6103 (goto-char (match-beginning 1)))
6104 (if (looking-at "-")
6105 (progn
6106 (beginning-of-line 0)
6107 (org-table-insert-row 'below))
6108 (if (looking-at " ") (forward-char 1))))
6109 (error
6110 (org-table-insert-row 'below)))))
6112 (defun org-table-previous-field ()
6113 "Go to the previous field in the table.
6114 Before doing so, re-align the table if necessary."
6115 (interactive)
6116 (org-table-justify-field-maybe)
6117 (org-table-maybe-recalculate-line)
6118 (if (and org-table-automatic-realign
6119 org-table-may-need-update)
6120 (org-table-align))
6121 (if (org-at-table-hline-p)
6122 (end-of-line 1))
6123 (re-search-backward "|" (org-table-begin))
6124 (re-search-backward "|" (org-table-begin))
6125 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6126 (re-search-backward "|" (org-table-begin)))
6127 (if (looking-at "| ?")
6128 (goto-char (match-end 0))))
6130 (defun org-table-next-row ()
6131 "Go to the next row (same column) in the current table.
6132 Before doing so, re-align the table if necessary."
6133 (interactive)
6134 (org-table-maybe-eval-formula)
6135 (org-table-maybe-recalculate-line)
6136 (if (or (looking-at "[ \t]*$")
6137 (save-excursion (skip-chars-backward " \t") (bolp)))
6138 (newline)
6139 (if (and org-table-automatic-realign
6140 org-table-may-need-update)
6141 (org-table-align))
6142 (let ((col (org-table-current-column)))
6143 (beginning-of-line 2)
6144 (if (or (not (org-at-table-p))
6145 (org-at-table-hline-p))
6146 (progn
6147 (beginning-of-line 0)
6148 (org-table-insert-row 'below)))
6149 (org-table-goto-column col)
6150 (skip-chars-backward "^|\n\r")
6151 (if (looking-at " ") (forward-char 1)))))
6153 (defun org-table-copy-down (n)
6154 "Copy a field down in the current column.
6155 If the field at the cursor is empty, copy into it the content of the nearest
6156 non-empty field above. With argument N, use the Nth non-empty field.
6157 If the current field is not empty, it is copied down to the next row, and
6158 the cursor is moved with it. Therefore, repeating this command causes the
6159 column to be filled row-by-row.
6160 If the variable `org-table-copy-increment' is non-nil and the field is an
6161 integer, it will be incremented while copying."
6162 (interactive "p")
6163 (let* ((colpos (org-table-current-column))
6164 (field (org-table-get-field))
6165 (non-empty (string-match "[^ \t]" field))
6166 (beg (org-table-begin))
6167 txt)
6168 (org-table-check-inside-data-field)
6169 (if non-empty
6170 (progn
6171 (setq txt (org-trim field))
6172 (org-table-next-row)
6173 (org-table-blank-field))
6174 (save-excursion
6175 (setq txt
6176 (catch 'exit
6177 (while (progn (beginning-of-line 1)
6178 (re-search-backward org-table-dataline-regexp
6179 beg t))
6180 (org-table-goto-column colpos t)
6181 (if (and (looking-at
6182 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6183 (= (setq n (1- n)) 0))
6184 (throw 'exit (match-string 1))))))))
6185 (if txt
6186 (progn
6187 (if (and org-table-copy-increment
6188 (string-match "^[0-9]+$" txt))
6189 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6190 (insert txt)
6191 (org-table-maybe-recalculate-line)
6192 (org-table-align))
6193 (error "No non-empty field found"))))
6195 (defun org-table-check-inside-data-field ()
6196 "Is point inside a table data field?
6197 I.e. not on a hline or before the first or after the last column?
6198 This actually throws an error, so it aborts the current command."
6199 (if (or (not (org-at-table-p))
6200 (= (org-table-current-column) 0)
6201 (org-at-table-hline-p)
6202 (looking-at "[ \t]*$"))
6203 (error "Not in table data field")))
6205 (defvar org-table-clip nil
6206 "Clipboard for table regions.")
6208 (defun org-table-blank-field ()
6209 "Blank the current table field or active region."
6210 (interactive)
6211 (org-table-check-inside-data-field)
6212 (if (and (interactive-p) (org-region-active-p))
6213 (let (org-table-clip)
6214 (org-table-cut-region (region-beginning) (region-end)))
6215 (skip-chars-backward "^|")
6216 (backward-char 1)
6217 (if (looking-at "|[^|\n]+")
6218 (let* ((pos (match-beginning 0))
6219 (match (match-string 0))
6220 (len (org-string-width match)))
6221 (replace-match (concat "|" (make-string (1- len) ?\ )))
6222 (goto-char (+ 2 pos))
6223 (substring match 1)))))
6225 (defun org-table-get-field (&optional n replace)
6226 "Return the value of the field in column N of current row.
6227 N defaults to current field.
6228 If REPLACE is a string, replace field with this value. The return value
6229 is always the old value."
6230 (and n (org-table-goto-column n))
6231 (skip-chars-backward "^|\n")
6232 (backward-char 1)
6233 (if (looking-at "|[^|\r\n]*")
6234 (let* ((pos (match-beginning 0))
6235 (val (buffer-substring (1+ pos) (match-end 0))))
6236 (if replace
6237 (replace-match (concat "|" replace)))
6238 (goto-char (min (point-at-eol) (+ 2 pos)))
6239 val)
6240 (forward-char 1) ""))
6242 (defun org-table-current-column ()
6243 "Find out which column we are in.
6244 When called interactively, column is also displayed in echo area."
6245 (interactive)
6246 (if (interactive-p) (org-table-check-inside-data-field))
6247 (save-excursion
6248 (let ((cnt 0) (pos (point)))
6249 (beginning-of-line 1)
6250 (while (search-forward "|" pos t)
6251 (setq cnt (1+ cnt)))
6252 (if (interactive-p) (message "This is table column %d" cnt))
6253 cnt)))
6255 (defun org-table-goto-column (n &optional on-delim force)
6256 "Move the cursor to the Nth column in the current table line.
6257 With optional argument ON-DELIM, stop with point before the left delimiter
6258 of the field.
6259 If there are less than N fields, just go to after the last delimiter.
6260 However, when FORCE is non-nil, create new columns if necessary."
6261 (interactive "p")
6262 (let ((pos (point-at-eol)))
6263 (beginning-of-line 1)
6264 (when (> n 0)
6265 (while (and (> (setq n (1- n)) -1)
6266 (or (search-forward "|" pos t)
6267 (and force
6268 (progn (end-of-line 1)
6269 (skip-chars-backward "^|")
6270 (insert " | "))))))
6271 ; (backward-char 2) t)))))
6272 (when (and force (not (looking-at ".*|")))
6273 (save-excursion (end-of-line 1) (insert " | ")))
6274 (if on-delim
6275 (backward-char 1)
6276 (if (looking-at " ") (forward-char 1))))))
6278 (defun org-at-table-p (&optional table-type)
6279 "Return t if the cursor is inside an org-type table.
6280 If TABLE-TYPE is non-nil, also check for table.el-type tables."
6281 (if org-enable-table-editor
6282 (save-excursion
6283 (beginning-of-line 1)
6284 (looking-at (if table-type org-table-any-line-regexp
6285 org-table-line-regexp)))
6286 nil))
6288 (defun org-at-table.el-p ()
6289 "Return t if and only if we are at a table.el table."
6290 (and (org-at-table-p 'any)
6291 (save-excursion
6292 (goto-char (org-table-begin 'any))
6293 (looking-at org-table1-hline-regexp))))
6295 (defun org-table-recognize-table.el ()
6296 "If there is a table.el table nearby, recognize it and move into it."
6297 (if org-table-tab-recognizes-table.el
6298 (if (org-at-table.el-p)
6299 (progn
6300 (beginning-of-line 1)
6301 (if (looking-at org-table-dataline-regexp)
6303 (if (looking-at org-table1-hline-regexp)
6304 (progn
6305 (beginning-of-line 2)
6306 (if (looking-at org-table-any-border-regexp)
6307 (beginning-of-line -1)))))
6308 (if (re-search-forward "|" (org-table-end t) t)
6309 (progn
6310 (require 'table)
6311 (if (table--at-cell-p (point))
6313 (message "recognizing table.el table...")
6314 (table-recognize-table)
6315 (message "recognizing table.el table...done")))
6316 (error "This should not happen..."))
6318 nil)
6319 nil))
6321 (defun org-at-table-hline-p ()
6322 "Return t if the cursor is inside a hline in a table."
6323 (if org-enable-table-editor
6324 (save-excursion
6325 (beginning-of-line 1)
6326 (looking-at org-table-hline-regexp))
6327 nil))
6329 (defun org-table-insert-column ()
6330 "Insert a new column into the table."
6331 (interactive)
6332 (if (not (org-at-table-p))
6333 (error "Not at a table"))
6334 (org-table-find-dataline)
6335 (let* ((col (max 1 (org-table-current-column)))
6336 (beg (org-table-begin))
6337 (end (org-table-end))
6338 ;; Current cursor position
6339 (linepos (org-current-line))
6340 (colpos col))
6341 (goto-char beg)
6342 (while (< (point) end)
6343 (if (org-at-table-hline-p)
6345 (org-table-goto-column col t)
6346 (insert "| "))
6347 (beginning-of-line 2))
6348 (move-marker end nil)
6349 (goto-line linepos)
6350 (org-table-goto-column colpos)
6351 (org-table-align)
6352 (org-table-modify-formulas 'insert col)))
6354 (defun org-table-find-dataline ()
6355 "Find a dataline in the current table, which is needed for column commands."
6356 (if (and (org-at-table-p)
6357 (not (org-at-table-hline-p)))
6359 (let ((col (current-column))
6360 (end (org-table-end)))
6361 (move-to-column col)
6362 (while (and (< (point) end)
6363 (or (not (= (current-column) col))
6364 (org-at-table-hline-p)))
6365 (beginning-of-line 2)
6366 (move-to-column col))
6367 (if (and (org-at-table-p)
6368 (not (org-at-table-hline-p)))
6370 (error
6371 "Please position cursor in a data line for column operations")))))
6373 (defun org-table-delete-column ()
6374 "Delete a column from the table."
6375 (interactive)
6376 (if (not (org-at-table-p))
6377 (error "Not at a table"))
6378 (org-table-find-dataline)
6379 (org-table-check-inside-data-field)
6380 (let* ((col (org-table-current-column))
6381 (beg (org-table-begin))
6382 (end (org-table-end))
6383 ;; Current cursor position
6384 (linepos (org-current-line))
6385 (colpos col))
6386 (goto-char beg)
6387 (while (< (point) end)
6388 (if (org-at-table-hline-p)
6390 (org-table-goto-column col t)
6391 (and (looking-at "|[^|\n]+|")
6392 (replace-match "|")))
6393 (beginning-of-line 2))
6394 (move-marker end nil)
6395 (goto-line linepos)
6396 (org-table-goto-column colpos)
6397 (org-table-align)
6398 (org-table-modify-formulas 'remove col)))
6400 (defun org-table-move-column-right ()
6401 "Move column to the right."
6402 (interactive)
6403 (org-table-move-column nil))
6404 (defun org-table-move-column-left ()
6405 "Move column to the left."
6406 (interactive)
6407 (org-table-move-column 'left))
6409 (defun org-table-move-column (&optional left)
6410 "Move the current column to the right. With arg LEFT, move to the left."
6411 (interactive "P")
6412 (if (not (org-at-table-p))
6413 (error "Not at a table"))
6414 (org-table-find-dataline)
6415 (org-table-check-inside-data-field)
6416 (let* ((col (org-table-current-column))
6417 (col1 (if left (1- col) col))
6418 (beg (org-table-begin))
6419 (end (org-table-end))
6420 ;; Current cursor position
6421 (linepos (org-current-line))
6422 (colpos (if left (1- col) (1+ col))))
6423 (if (and left (= col 1))
6424 (error "Cannot move column further left"))
6425 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6426 (error "Cannot move column further right"))
6427 (goto-char beg)
6428 (while (< (point) end)
6429 (if (org-at-table-hline-p)
6431 (org-table-goto-column col1 t)
6432 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6433 (replace-match "|\\2|\\1|")))
6434 (beginning-of-line 2))
6435 (move-marker end nil)
6436 (goto-line linepos)
6437 (org-table-goto-column colpos)
6438 (org-table-align)
6439 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6441 (defun org-table-move-row-down ()
6442 "Move table row down."
6443 (interactive)
6444 (org-table-move-row nil))
6445 (defun org-table-move-row-up ()
6446 "Move table row up."
6447 (interactive)
6448 (org-table-move-row 'up))
6450 (defun org-table-move-row (&optional up)
6451 "Move the current table line down. With arg UP, move it up."
6452 (interactive "P")
6453 (let ((col (current-column))
6454 (pos (point))
6455 (tonew (if up 0 2))
6456 txt)
6457 (beginning-of-line tonew)
6458 (if (not (org-at-table-p))
6459 (progn
6460 (goto-char pos)
6461 (error "Cannot move row further")))
6462 (goto-char pos)
6463 (beginning-of-line 1)
6464 (setq pos (point))
6465 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6466 (delete-region (point) (1+ (point-at-eol)))
6467 (beginning-of-line tonew)
6468 (insert txt)
6469 (beginning-of-line 0)
6470 (move-to-column col)))
6472 (defun org-table-insert-row (&optional arg)
6473 "Insert a new row above the current line into the table.
6474 With prefix ARG, insert below the current line."
6475 (interactive "P")
6476 (if (not (org-at-table-p))
6477 (error "Not at a table"))
6478 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
6479 (new (org-table-clean-line line)))
6480 ;; Fix the first field if necessary
6481 (if (string-match "^[ \t]*| *[#$] *|" line)
6482 (setq new (replace-match (match-string 0 line) t t new)))
6483 (beginning-of-line (if arg 2 1))
6484 (let (org-table-may-need-update) (insert-before-markers new "\n"))
6485 (beginning-of-line 0)
6486 (re-search-forward "| ?" (point-at-eol) t)
6487 (and org-table-may-need-update (org-table-align))))
6489 (defun org-table-insert-hline (&optional arg)
6490 "Insert a horizontal-line below the current line into the table.
6491 With prefix ARG, insert above the current line."
6492 (interactive "P")
6493 (if (not (org-at-table-p))
6494 (error "Not at a table"))
6495 (let ((line (org-table-clean-line
6496 (buffer-substring (point-at-bol) (point-at-eol))))
6497 (col (current-column)))
6498 (while (string-match "|\\( +\\)|" line)
6499 (setq line (replace-match
6500 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
6501 ?-) "|") t t line)))
6502 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
6503 (beginning-of-line (if arg 1 2))
6504 (insert line "\n")
6505 (beginning-of-line (if arg 1 -1))
6506 (move-to-column col)))
6508 (defun org-table-clean-line (s)
6509 "Convert a table line S into a string with only \"|\" and space.
6510 In particular, this does handle wide and invisible characters."
6511 (if (string-match "^[ \t]*|-" s)
6512 ;; It's a hline, just map the characters
6513 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
6514 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
6515 (setq s (replace-match
6516 (concat "|" (make-string (org-string-width (match-string 1 s))
6517 ?\ ) "|")
6518 t t s)))
6521 (defun org-table-kill-row ()
6522 "Delete the current row or horizontal line from the table."
6523 (interactive)
6524 (if (not (org-at-table-p))
6525 (error "Not at a table"))
6526 (let ((col (current-column)))
6527 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6528 (if (not (org-at-table-p)) (beginning-of-line 0))
6529 (move-to-column col)))
6531 (defun org-table-sort-lines (with-case &optional sorting-type)
6532 "Sort table lines according to the column at point.
6534 The position of point indicates the column to be used for
6535 sorting, and the range of lines is the range between the nearest
6536 horizontal separator lines, or the entire table of no such lines
6537 exist. If point is before the first column, you will be prompted
6538 for the sorting column. If there is an active region, the mark
6539 specifies the first line and the sorting column, while point
6540 should be in the last line to be included into the sorting.
6542 The command then prompts for the sorting type which can be
6543 alphabetically, numerically, or by time (as given in a time stamp
6544 in the field). Sorting in reverse order is also possible.
6546 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
6548 If SORTING-TYPE is specified when this function is called from a Lisp
6549 program, no prompting will take place. SORTING-TYPE must be a character,
6550 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
6551 should be done in reverse order."
6552 (interactive "P")
6553 (let* ((thisline (org-current-line))
6554 (thiscol (org-table-current-column))
6555 beg end bcol ecol tend tbeg column lns pos)
6556 (when (equal thiscol 0)
6557 (if (interactive-p)
6558 (setq thiscol
6559 (string-to-number
6560 (read-string "Use column N for sorting: ")))
6561 (setq thiscol 1))
6562 (org-table-goto-column thiscol))
6563 (org-table-check-inside-data-field)
6564 (if (org-region-active-p)
6565 (progn
6566 (setq beg (region-beginning) end (region-end))
6567 (goto-char beg)
6568 (setq column (org-table-current-column)
6569 beg (point-at-bol))
6570 (goto-char end)
6571 (setq end (point-at-bol 2)))
6572 (setq column (org-table-current-column)
6573 pos (point)
6574 tbeg (org-table-begin)
6575 tend (org-table-end))
6576 (if (re-search-backward org-table-hline-regexp tbeg t)
6577 (setq beg (point-at-bol 2))
6578 (goto-char tbeg)
6579 (setq beg (point-at-bol 1)))
6580 (goto-char pos)
6581 (if (re-search-forward org-table-hline-regexp tend t)
6582 (setq beg (point-at-bol 0))
6583 (goto-char tend)
6584 (setq end (point-at-bol))))
6585 (setq beg (move-marker (make-marker) beg)
6586 end (move-marker (make-marker) end))
6587 (untabify beg end)
6588 (goto-char beg)
6589 (org-table-goto-column column)
6590 (skip-chars-backward "^|")
6591 (setq bcol (current-column))
6592 (org-table-goto-column (1+ column))
6593 (skip-chars-backward "^|")
6594 (setq ecol (1- (current-column)))
6595 (org-table-goto-column column)
6596 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
6597 (org-split-string (buffer-substring beg end) "\n")))
6598 (setq lns (org-do-sort lns "Table" with-case sorting-type))
6599 (delete-region beg end)
6600 (move-marker beg nil)
6601 (move-marker end nil)
6602 (insert (mapconcat 'cdr lns "\n") "\n")
6603 (goto-line thisline)
6604 (org-table-goto-column thiscol)
6605 (message "%d lines sorted, based on column %d" (length lns) column)))
6607 (defun org-table-cut-region (beg end)
6608 "Copy region in table to the clipboard and blank all relevant fields."
6609 (interactive "r")
6610 (org-table-copy-region beg end 'cut))
6612 (defun org-table-copy-region (beg end &optional cut)
6613 "Copy rectangular region in table to clipboard.
6614 A special clipboard is used which can only be accessed
6615 with `org-table-paste-rectangle'."
6616 (interactive "rP")
6617 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6618 region cols
6619 (rpl (if cut " " nil)))
6620 (goto-char beg)
6621 (org-table-check-inside-data-field)
6622 (setq l01 (org-current-line)
6623 c01 (org-table-current-column))
6624 (goto-char end)
6625 (org-table-check-inside-data-field)
6626 (setq l02 (org-current-line)
6627 c02 (org-table-current-column))
6628 (setq l1 (min l01 l02) l2 (max l01 l02)
6629 c1 (min c01 c02) c2 (max c01 c02))
6630 (catch 'exit
6631 (while t
6632 (catch 'nextline
6633 (if (> l1 l2) (throw 'exit t))
6634 (goto-line l1)
6635 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6636 (setq cols nil ic1 c1 ic2 c2)
6637 (while (< ic1 (1+ ic2))
6638 (push (org-table-get-field ic1 rpl) cols)
6639 (setq ic1 (1+ ic1)))
6640 (push (nreverse cols) region)
6641 (setq l1 (1+ l1)))))
6642 (setq org-table-clip (nreverse region))
6643 (if cut (org-table-align))
6644 org-table-clip))
6646 (defun org-table-paste-rectangle ()
6647 "Paste a rectangular region into a table.
6648 The upper right corner ends up in the current field. All involved fields
6649 will be overwritten. If the rectangle does not fit into the present table,
6650 the table is enlarged as needed. The process ignores horizontal separator
6651 lines."
6652 (interactive)
6653 (unless (and org-table-clip (listp org-table-clip))
6654 (error "First cut/copy a region to paste!"))
6655 (org-table-check-inside-data-field)
6656 (let* ((clip org-table-clip)
6657 (line (org-current-line))
6658 (col (org-table-current-column))
6659 (org-enable-table-editor t)
6660 (org-table-automatic-realign nil)
6661 c cols field)
6662 (while (setq cols (pop clip))
6663 (while (org-at-table-hline-p) (beginning-of-line 2))
6664 (if (not (org-at-table-p))
6665 (progn (end-of-line 0) (org-table-next-field)))
6666 (setq c col)
6667 (while (setq field (pop cols))
6668 (org-table-goto-column c nil 'force)
6669 (org-table-get-field nil field)
6670 (setq c (1+ c)))
6671 (beginning-of-line 2))
6672 (goto-line line)
6673 (org-table-goto-column col)
6674 (org-table-align)))
6676 (defun org-table-convert ()
6677 "Convert from `org-mode' table to table.el and back.
6678 Obviously, this only works within limits. When an Org-mode table is
6679 converted to table.el, all horizontal separator lines get lost, because
6680 table.el uses these as cell boundaries and has no notion of horizontal lines.
6681 A table.el table can be converted to an Org-mode table only if it does not
6682 do row or column spanning. Multiline cells will become multiple cells.
6683 Beware, Org-mode does not test if the table can be successfully converted - it
6684 blindly applies a recipe that works for simple tables."
6685 (interactive)
6686 (require 'table)
6687 (if (org-at-table.el-p)
6688 ;; convert to Org-mode table
6689 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6690 (end (move-marker (make-marker) (org-table-end t))))
6691 (table-unrecognize-region beg end)
6692 (goto-char beg)
6693 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6694 (replace-match ""))
6695 (goto-char beg))
6696 (if (org-at-table-p)
6697 ;; convert to table.el table
6698 (let ((beg (move-marker (make-marker) (org-table-begin)))
6699 (end (move-marker (make-marker) (org-table-end))))
6700 ;; first, get rid of all horizontal lines
6701 (goto-char beg)
6702 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6703 (replace-match ""))
6704 ;; insert a hline before first
6705 (goto-char beg)
6706 (org-table-insert-hline 'above)
6707 (beginning-of-line -1)
6708 ;; insert a hline after each line
6709 (while (progn (beginning-of-line 3) (< (point) end))
6710 (org-table-insert-hline))
6711 (goto-char beg)
6712 (setq end (move-marker end (org-table-end)))
6713 ;; replace "+" at beginning and ending of hlines
6714 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6715 (replace-match "\\1+-"))
6716 (goto-char beg)
6717 (while (re-search-forward "-|[ \t]*$" end t)
6718 (replace-match "-+"))
6719 (goto-char beg)))))
6721 (defun org-table-wrap-region (arg)
6722 "Wrap several fields in a column like a paragraph.
6723 This is useful if you'd like to spread the contents of a field over several
6724 lines, in order to keep the table compact.
6726 If there is an active region, and both point and mark are in the same column,
6727 the text in the column is wrapped to minimum width for the given number of
6728 lines. Generally, this makes the table more compact. A prefix ARG may be
6729 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6730 formats the selected text to two lines. If the region was longer than two
6731 lines, the remaining lines remain empty. A negative prefix argument reduces
6732 the current number of lines by that amount. The wrapped text is pasted back
6733 into the table. If you formatted it to more lines than it was before, fields
6734 further down in the table get overwritten - so you might need to make space in
6735 the table first.
6737 If there is no region, the current field is split at the cursor position and
6738 the text fragment to the right of the cursor is prepended to the field one
6739 line down.
6741 If there is no region, but you specify a prefix ARG, the current field gets
6742 blank, and the content is appended to the field above."
6743 (interactive "P")
6744 (org-table-check-inside-data-field)
6745 (if (org-region-active-p)
6746 ;; There is a region: fill as a paragraph
6747 (let ((beg (region-beginning))
6748 nlines)
6749 (org-table-cut-region (region-beginning) (region-end))
6750 (if (> (length (car org-table-clip)) 1)
6751 (error "Region must be limited to single column"))
6752 (setq nlines (if arg
6753 (if (< arg 1)
6754 (+ (length org-table-clip) arg)
6755 arg)
6756 (length org-table-clip)))
6757 (setq org-table-clip
6758 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6759 nil nlines)))
6760 (goto-char beg)
6761 (org-table-paste-rectangle))
6762 ;; No region, split the current field at point
6763 (if arg
6764 ;; combine with field above
6765 (let ((s (org-table-blank-field))
6766 (col (org-table-current-column)))
6767 (beginning-of-line 0)
6768 (while (org-at-table-hline-p) (beginning-of-line 0))
6769 (org-table-goto-column col)
6770 (skip-chars-forward "^|")
6771 (skip-chars-backward " ")
6772 (insert " " (org-trim s))
6773 (org-table-align))
6774 ;; split field
6775 (when (looking-at "\\([^|]+\\)+|")
6776 (let ((s (match-string 1)))
6777 (replace-match " |")
6778 (goto-char (match-beginning 0))
6779 (org-table-next-row)
6780 (insert (org-trim s) " ")
6781 (org-table-align))))))
6783 (defvar org-field-marker nil)
6785 (defun org-table-edit-field (arg)
6786 "Edit table field in a different window.
6787 This is mainly useful for fields that contain hidden parts.
6788 When called with a \\[universal-argument] prefix, just make the full field visible so that
6789 it can be edited in place."
6790 (interactive "P")
6791 (if arg
6792 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
6793 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
6794 (remove-text-properties b e '(org-cwidth t invisible t
6795 display t intangible t))
6796 (if (and (boundp 'font-lock-mode) font-lock-mode)
6797 (font-lock-fontify-block)))
6798 (let ((pos (move-marker (make-marker) (point)))
6799 (field (org-table-get-field))
6800 (cw (current-window-configuration))
6802 (switch-to-buffer-other-window "*Org tmp*")
6803 (erase-buffer)
6804 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
6805 (org-mode)
6806 (goto-char (setq p (point-max)))
6807 (insert (org-trim field))
6808 (remove-text-properties p (point-max)
6809 '(invisible t org-cwidth t display t
6810 intangible t))
6811 (goto-char p)
6812 (org-set-local 'org-finish-function
6813 'org-table-finish-edit-field)
6814 (org-set-local 'org-window-configuration cw)
6815 (org-set-local 'org-field-marker pos)
6816 (message "Edit and finish with C-c C-c"))))
6818 (defun org-table-finish-edit-field ()
6819 "Finish editing a table data field.
6820 Remove all newline characters, insert the result into the table, realign
6821 the table and kill the editing buffer."
6822 (let ((pos org-field-marker)
6823 (cw org-window-configuration)
6824 (cb (current-buffer))
6825 text)
6826 (goto-char (point-min))
6827 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
6828 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
6829 (replace-match " "))
6830 (setq text (org-trim (buffer-string)))
6831 (set-window-configuration cw)
6832 (kill-buffer cb)
6833 (select-window (get-buffer-window (marker-buffer pos)))
6834 (goto-char pos)
6835 (move-marker pos nil)
6836 (org-table-check-inside-data-field)
6837 (org-table-get-field nil text)
6838 (org-table-align)
6839 (message "New field value inserted")))
6841 (defun org-trim (s)
6842 "Remove whitespace at beginning and end of string."
6843 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6844 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6847 (defun org-wrap (string &optional width lines)
6848 "Wrap string to either a number of lines, or a width in characters.
6849 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6850 that costs. If there is a word longer than WIDTH, the text is actually
6851 wrapped to the length of that word.
6852 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6853 many lines, whatever width that takes.
6854 The return value is a list of lines, without newlines at the end."
6855 (let* ((words (org-split-string string "[ \t\n]+"))
6856 (maxword (apply 'max (mapcar 'org-string-width words)))
6857 w ll)
6858 (cond (width
6859 (org-do-wrap words (max maxword width)))
6860 (lines
6861 (setq w maxword)
6862 (setq ll (org-do-wrap words maxword))
6863 (if (<= (length ll) lines)
6865 (setq ll words)
6866 (while (> (length ll) lines)
6867 (setq w (1+ w))
6868 (setq ll (org-do-wrap words w)))
6869 ll))
6870 (t (error "Cannot wrap this")))))
6873 (defun org-do-wrap (words width)
6874 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6875 (let (lines line)
6876 (while words
6877 (setq line (pop words))
6878 (while (and words (< (+ (length line) (length (car words))) width))
6879 (setq line (concat line " " (pop words))))
6880 (setq lines (push line lines)))
6881 (nreverse lines)))
6883 (defun org-split-string (string &optional separators)
6884 "Splits STRING into substrings at SEPARATORS.
6885 No empty strings are returned if there are matches at the beginning
6886 and end of string."
6887 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6888 (start 0)
6889 notfirst
6890 (list nil))
6891 (while (and (string-match rexp string
6892 (if (and notfirst
6893 (= start (match-beginning 0))
6894 (< start (length string)))
6895 (1+ start) start))
6896 (< (match-beginning 0) (length string)))
6897 (setq notfirst t)
6898 (or (eq (match-beginning 0) 0)
6899 (and (eq (match-beginning 0) (match-end 0))
6900 (eq (match-beginning 0) start))
6901 (setq list
6902 (cons (substring string start (match-beginning 0))
6903 list)))
6904 (setq start (match-end 0)))
6905 (or (eq start (length string))
6906 (setq list
6907 (cons (substring string start)
6908 list)))
6909 (nreverse list)))
6911 (defun org-table-map-tables (function)
6912 "Apply FUNCTION to the start of all tables in the buffer."
6913 (save-excursion
6914 (save-restriction
6915 (widen)
6916 (goto-char (point-min))
6917 (while (re-search-forward org-table-any-line-regexp nil t)
6918 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6919 (beginning-of-line 1)
6920 (if (looking-at org-table-line-regexp)
6921 (save-excursion (funcall function)))
6922 (re-search-forward org-table-any-border-regexp nil 1))))
6923 (message "Mapping tables: done"))
6925 (defvar org-timecnt) ; dynamically scoped parameter
6927 (defun org-table-sum (&optional beg end nlast)
6928 "Sum numbers in region of current table column.
6929 The result will be displayed in the echo area, and will be available
6930 as kill to be inserted with \\[yank].
6932 If there is an active region, it is interpreted as a rectangle and all
6933 numbers in that rectangle will be summed. If there is no active
6934 region and point is located in a table column, sum all numbers in that
6935 column.
6937 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6938 numbers are assumed to be times as well (in decimal hours) and the
6939 numbers are added as such.
6941 If NLAST is a number, only the NLAST fields will actually be summed."
6942 (interactive)
6943 (save-excursion
6944 (let (col (org-timecnt 0) diff h m s org-table-clip)
6945 (cond
6946 ((and beg end)) ; beg and end given explicitly
6947 ((org-region-active-p)
6948 (setq beg (region-beginning) end (region-end)))
6950 (setq col (org-table-current-column))
6951 (goto-char (org-table-begin))
6952 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6953 (error "No table data"))
6954 (org-table-goto-column col)
6955 ;not needed? (skip-chars-backward "^|")
6956 (setq beg (point))
6957 (goto-char (org-table-end))
6958 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6959 (error "No table data"))
6960 (org-table-goto-column col)
6961 ;not needed? (skip-chars-forward "^|")
6962 (setq end (point))))
6963 (let* ((items (apply 'append (org-table-copy-region beg end)))
6964 (items1 (cond ((not nlast) items)
6965 ((>= nlast (length items)) items)
6966 (t (setq items (reverse items))
6967 (setcdr (nthcdr (1- nlast) items) nil)
6968 (nreverse items))))
6969 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6970 items1)))
6971 (res (apply '+ numbers))
6972 (sres (if (= org-timecnt 0)
6973 (format "%g" res)
6974 (setq diff (* 3600 res)
6975 h (floor (/ diff 3600)) diff (mod diff 3600)
6976 m (floor (/ diff 60)) diff (mod diff 60)
6977 s diff)
6978 (format "%d:%02d:%02d" h m s))))
6979 (kill-new sres)
6980 (if (interactive-p)
6981 (message "%s"
6982 (substitute-command-keys
6983 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6984 (length numbers) sres))))
6985 sres))))
6987 (defun org-table-get-number-for-summing (s)
6988 (let (n)
6989 (if (string-match "^ *|? *" s)
6990 (setq s (replace-match "" nil nil s)))
6991 (if (string-match " *|? *$" s)
6992 (setq s (replace-match "" nil nil s)))
6993 (setq n (string-to-number s))
6994 (cond
6995 ((and (string-match "0" s)
6996 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6997 ((string-match "\\`[ \t]+\\'" s) nil)
6998 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6999 (let ((h (string-to-number (or (match-string 1 s) "0")))
7000 (m (string-to-number (or (match-string 2 s) "0")))
7001 (s (string-to-number (or (match-string 4 s) "0"))))
7002 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
7003 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7004 ((equal n 0) nil)
7005 (t n))))
7007 (defun org-table-get-vertical-vector (desc &optional tbeg col)
7008 "Get a calc vector from a column, accorting to descriptor DESC.
7009 Optional arguments TBEG and COL can give the beginning of the table and
7010 the current column, to avoid unnecessary parsing."
7011 (save-excursion
7012 (or tbeg (setq tbeg (org-table-begin)))
7013 (or col (setq col (org-table-current-column)))
7014 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7015 (cond
7016 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7017 (setq n1 (- (match-end 1) (match-beginning 1)))
7018 (if (match-beginning 3)
7019 (setq n2 (- (match-end 2) (match-beginning 3))))
7020 (setq n (if n2 (max n1 n2) n1))
7021 (setq n1 (if n2 (min n1 n2)))
7022 (setq nn n)
7023 (while (and (> nn 0)
7024 (re-search-backward org-table-hline-regexp tbeg t))
7025 (push (org-current-line) hline-list)
7026 (setq nn (1- nn)))
7027 (setq hline-list (nreverse hline-list))
7028 (goto-line (nth (1- n) hline-list))
7029 (when (re-search-forward org-table-dataline-regexp)
7030 (org-table-goto-column col)
7031 (setq beg (point)))
7032 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7033 (when (re-search-backward org-table-dataline-regexp)
7034 (org-table-goto-column col)
7035 (setq end (point)))
7036 (setq l (apply 'append (org-table-copy-region beg end)))
7037 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7038 (if (equal x "") "0" x))
7039 l ",") "]"))
7040 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7041 (setq n1 (string-to-number (match-string 1 desc))
7042 n2 (string-to-number (match-string 2 desc)))
7043 (beginning-of-line 1)
7044 (save-excursion
7045 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7046 (org-table-goto-column col)
7047 (setq beg (point))))
7048 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7049 (org-table-goto-column col)
7050 (setq end (point)))
7051 (setq l (apply 'append (org-table-copy-region beg end)))
7052 (concat "[" (mapconcat
7053 (lambda (x) (setq x (org-trim x))
7054 (if (equal x "") "0" x))
7055 l ",") "]"))
7056 ((string-match "\\([0-9]+\\)" desc)
7057 (beginning-of-line 1)
7058 (when (re-search-backward org-table-dataline-regexp tbeg t
7059 (string-to-number (match-string 0 desc)))
7060 (org-table-goto-column col)
7061 (org-trim (org-table-get-field))))))))
7063 (defvar org-table-formula-history nil)
7065 (defvar org-table-column-names nil
7066 "Alist with column names, derived from the `!' line.")
7067 (defvar org-table-column-name-regexp nil
7068 "Regular expression matching the current column names.")
7069 (defvar org-table-local-parameters nil
7070 "Alist with parameter names, derived from the `$' line.")
7071 (defvar org-table-named-field-locations nil
7072 "Alist with locations of named fields.")
7074 (defun org-table-get-formula (&optional equation named)
7075 "Read a formula from the minibuffer, offer stored formula as default."
7076 (let* ((name (car (rassoc (list (org-current-line)
7077 (org-table-current-column))
7078 org-table-named-field-locations)))
7079 (scol (if named
7080 (if name name
7081 (error "Not in a named field"))
7082 (int-to-string (org-table-current-column))))
7083 (dummy (and name (not named)
7084 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7085 (error "Abort")))
7086 (org-table-may-need-update nil)
7087 (stored-list (org-table-get-stored-formulas))
7088 (stored (cdr (assoc scol stored-list)))
7089 (eq (cond
7090 ((and stored equation (string-match "^ *=? *$" equation))
7091 stored)
7092 ((stringp equation)
7093 equation)
7094 (t (read-string
7095 (format "%s formula $%s=" (if named "Field" "Column") scol)
7096 (or stored "") 'org-table-formula-history
7097 ;stored
7098 ))))
7099 mustsave)
7100 (when (not (string-match "\\S-" eq))
7101 ;; remove formula
7102 (setq stored-list (delq (assoc scol stored-list) stored-list))
7103 (org-table-store-formulas stored-list)
7104 (error "Formula removed"))
7105 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7106 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7107 (if (and name (not named))
7108 ;; We set the column equation, delete the named one.
7109 (setq stored-list (delq (assoc name stored-list) stored-list)
7110 mustsave t))
7111 (if stored
7112 (setcdr (assoc scol stored-list) eq)
7113 (setq stored-list (cons (cons scol eq) stored-list)))
7114 (if (or mustsave (not (equal stored eq)))
7115 (org-table-store-formulas stored-list))
7116 eq))
7118 (defun org-table-store-formulas (alist)
7119 "Store the list of formulas below the current table."
7120 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7121 (save-excursion
7122 (goto-char (org-table-end))
7123 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7124 (delete-region (point) (match-end 0)))
7125 (insert "#+TBLFM: "
7126 (mapconcat (lambda (x)
7127 (concat "$" (car x) "=" (cdr x)))
7128 alist "::")
7129 "\n")))
7131 (defun org-table-get-stored-formulas ()
7132 "Return an alist with the stored formulas directly after current table."
7133 (interactive)
7134 (let (scol eq eq-alist strings string seen)
7135 (save-excursion
7136 (goto-char (org-table-end))
7137 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7138 (setq strings (org-split-string (match-string 2) " *:: *"))
7139 (while (setq string (pop strings))
7140 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7141 (setq scol (match-string 1 string)
7142 eq (match-string 2 string)
7143 eq-alist (cons (cons scol eq) eq-alist))
7144 (if (member scol seen)
7145 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7146 (push scol seen))))))
7147 (nreverse eq-alist)))
7149 (defun org-table-modify-formulas (action &rest columns)
7150 "Modify the formulas stored below the current table.
7151 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7152 expected, for the other actions only a single column number is needed."
7153 (let ((list (org-table-get-stored-formulas))
7154 (nmax (length (org-split-string
7155 (buffer-substring (point-at-bol) (point-at-eol))
7156 "|")))
7157 col col1 col2 scol si sc1 sc2)
7158 (cond
7159 ((null list)) ; No action needed if there are no stored formulas
7160 ((eq action 'remove)
7161 (setq col (car columns)
7162 scol (int-to-string col))
7163 (org-table-replace-in-formulas list scol "INVALID")
7164 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
7165 (loop for i from (1+ col) upto nmax by 1 do
7166 (setq si (int-to-string i))
7167 (org-table-replace-in-formulas list si (int-to-string (1- i)))
7168 (if (assoc si list) (setcar (assoc si list)
7169 (int-to-string (1- i))))))
7170 ((eq action 'insert)
7171 (setq col (car columns))
7172 (loop for i from nmax downto col by 1 do
7173 (setq si (int-to-string i))
7174 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
7175 (if (assoc si list) (setcar (assoc si list)
7176 (int-to-string (1+ i))))))
7177 ((eq action 'swap)
7178 (setq col1 (car columns) col2 (nth 1 columns)
7179 sc1 (int-to-string col1) sc2 (int-to-string col2))
7180 ;; Hopefully, ZqZtZ will never be a name in a table
7181 (org-table-replace-in-formulas list sc1 "ZqZtZ")
7182 (org-table-replace-in-formulas list sc2 sc1)
7183 (org-table-replace-in-formulas list "ZqZtZ" sc2)
7184 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
7185 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
7186 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
7187 (t (error "Invalid action in `org-table-modify-formulas'")))
7188 (if list (org-table-store-formulas list))))
7190 (defun org-table-replace-in-formulas (list s1 s2)
7191 (let (elt re s)
7192 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7193 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7194 re (concat (regexp-quote s1) "\\>"))
7195 (while (setq elt (pop list))
7196 (setq s (cdr elt))
7197 (while (string-match re s)
7198 (setq s (replace-match s2 t t s)))
7199 (setcdr elt s))))
7201 (defun org-table-get-specials ()
7202 "Get the column names and local parameters for this table."
7203 (save-excursion
7204 (let ((beg (org-table-begin)) (end (org-table-end))
7205 names name fields fields1 field cnt c v line col)
7206 (setq org-table-column-names nil
7207 org-table-local-parameters nil
7208 org-table-named-field-locations nil)
7209 (goto-char beg)
7210 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7211 (setq names (org-split-string (match-string 1) " *| *")
7212 cnt 1)
7213 (while (setq name (pop names))
7214 (setq cnt (1+ cnt))
7215 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7216 (push (cons name (int-to-string cnt)) org-table-column-names))))
7217 (setq org-table-column-names (nreverse org-table-column-names))
7218 (setq org-table-column-name-regexp
7219 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7220 (goto-char beg)
7221 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7222 (setq fields (org-split-string (match-string 1) " *| *"))
7223 (while (setq field (pop fields))
7224 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7225 (push (cons (match-string 1 field) (match-string 2 field))
7226 org-table-local-parameters))))
7227 (goto-char beg)
7228 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7229 (setq c (match-string 1)
7230 fields (org-split-string (match-string 2) " *| *"))
7231 (save-excursion
7232 (beginning-of-line (if (equal c "_") 2 0))
7233 (setq line (org-current-line) col 1)
7234 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7235 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7236 (while (and fields1 (setq field (pop fields)))
7237 (setq v (pop fields1) col (1+ col))
7238 (when (and (stringp field) (stringp v)
7239 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7240 (push (cons field v) org-table-local-parameters)
7241 (push (list field line col) org-table-named-field-locations)))))))
7243 (defun org-this-word ()
7244 ;; Get the current word
7245 (save-excursion
7246 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7247 (end (progn (skip-chars-forward "^ \t\n") (point))))
7248 (buffer-substring-no-properties beg end))))
7250 (defun org-table-maybe-eval-formula ()
7251 "Check if the current field starts with \"=\" or \":=\".
7252 If yes, store the formula and apply it."
7253 ;; We already know we are in a table. Get field will only return a formula
7254 ;; when appropriate. It might return a separator line, but no problem.
7255 (when org-table-formula-evaluate-inline
7256 (let* ((field (org-trim (or (org-table-get-field) "")))
7257 named eq)
7258 (when (string-match "^:?=\\(.*\\)" field)
7259 (setq named (equal (string-to-char field) ?:)
7260 eq (match-string 1 field))
7261 (if (or (fboundp 'calc-eval)
7262 (equal (substring eq 0 (min 2 (length eq))) "'("))
7263 (org-table-eval-formula (if named '(4) nil) eq)
7264 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
7266 (defvar org-recalc-commands nil
7267 "List of commands triggering the recalculation of a line.
7268 Will be filled automatically during use.")
7270 (defvar org-recalc-marks
7271 '((" " . "Unmarked: no special line, no automatic recalculation")
7272 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7273 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7274 ("!" . "Column name definition line. Reference in formula as $name.")
7275 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7276 ("_" . "Names for values in row below this one.")
7277 ("^" . "Names for values in row above this one.")))
7279 (defun org-table-rotate-recalc-marks (&optional newchar)
7280 "Rotate the recalculation mark in the first column.
7281 If in any row, the first field is not consistent with a mark,
7282 insert a new column for the markers.
7283 When there is an active region, change all the lines in the region,
7284 after prompting for the marking character.
7285 After each change, a message will be displayed indicating the meaning
7286 of the new mark."
7287 (interactive)
7288 (unless (org-at-table-p) (error "Not at a table"))
7289 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7290 (beg (org-table-begin))
7291 (end (org-table-end))
7292 (l (org-current-line))
7293 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7294 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7295 (have-col
7296 (save-excursion
7297 (goto-char beg)
7298 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7299 (col (org-table-current-column))
7300 (forcenew (car (assoc newchar org-recalc-marks)))
7301 epos new)
7302 (when l1
7303 (message "Change region to what mark? Type # * ! $ or SPC: ")
7304 (setq newchar (char-to-string (read-char-exclusive))
7305 forcenew (car (assoc newchar org-recalc-marks))))
7306 (if (and newchar (not forcenew))
7307 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7308 newchar))
7309 (if l1 (goto-line l1))
7310 (save-excursion
7311 (beginning-of-line 1)
7312 (unless (looking-at org-table-dataline-regexp)
7313 (error "Not at a table data line")))
7314 (unless have-col
7315 (org-table-goto-column 1)
7316 (org-table-insert-column)
7317 (org-table-goto-column (1+ col)))
7318 (setq epos (point-at-eol))
7319 (save-excursion
7320 (beginning-of-line 1)
7321 (org-table-get-field
7322 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7323 (concat " "
7324 (setq new (or forcenew
7325 (cadr (member (match-string 1) marks))))
7326 " ")
7327 " # ")))
7328 (if (and l1 l2)
7329 (progn
7330 (goto-line l1)
7331 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7332 (and (looking-at org-table-dataline-regexp)
7333 (org-table-get-field 1 (concat " " new " "))))
7334 (goto-line l1)))
7335 (if (not (= epos (point-at-eol))) (org-table-align))
7336 (goto-line l)
7337 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7339 (defun org-table-maybe-recalculate-line ()
7340 "Recompute the current line if marked for it, and if we haven't just done it."
7341 (interactive)
7342 (and org-table-allow-automatic-line-recalculation
7343 (not (and (memq last-command org-recalc-commands)
7344 (equal org-last-recalc-line (org-current-line))))
7345 (save-excursion (beginning-of-line 1)
7346 (looking-at org-table-auto-recalculate-regexp))
7347 ;; (fboundp 'calc-eval) ;; FIXME: correct to remove this?
7348 (org-table-recalculate) t))
7350 (defvar org-table-formula-debug nil
7351 "Non-nil means, debug table formulas.
7352 When nil, simply write \"#ERROR\" in corrupted fields.")
7354 (defvar modes)
7355 (defsubst org-set-calc-mode (var &optional value)
7356 (if (stringp var)
7357 (setq var (assoc var '(("D" calc-angle-mode deg)
7358 ("R" calc-angle-mode rad)
7359 ("F" calc-prefer-frac t)
7360 ("S" calc-symbolic-mode t)))
7361 value (nth 2 var) var (nth 1 var)))
7362 (if (memq var modes)
7363 (setcar (cdr (memq var modes)) value)
7364 (cons var (cons value modes)))
7365 modes)
7367 (defun org-table-eval-formula (&optional arg equation
7368 suppress-align suppress-const
7369 suppress-store)
7370 "Replace the table field value at the cursor by the result of a calculation.
7372 This function makes use of Dave Gillespie's Calc package, in my view the
7373 most exciting program ever written for GNU Emacs. So you need to have Calc
7374 installed in order to use this function.
7376 In a table, this command replaces the value in the current field with the
7377 result of a formula. It also installs the formula as the \"current\" column
7378 formula, by storing it in a special line below the table. When called
7379 with a `C-u' prefix, the current field must ba a named field, and the
7380 formula is installed as valid in only this specific field.
7382 When called, the command first prompts for a formula, which is read in
7383 the minibuffer. Previously entered formulas are available through the
7384 history list, and the last used formula is offered as a default.
7385 These stored formulas are adapted correctly when moving, inserting, or
7386 deleting columns with the corresponding commands.
7388 The formula can be any algebraic expression understood by the Calc package.
7389 For details, see the Org-mode manual.
7391 This function can also be called from Lisp programs and offers
7392 additional arguments: EQUATION can be the formula to apply. If this
7393 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7394 used to speed-up recursive calls by by-passing unnecessary aligns.
7395 SUPPRESS-CONST suppresses the interpretation of constants in the
7396 formula, assuming that this has been done already outside the function.
7397 SUPPRESS-STORE means the formula should not be stored, either because
7398 it is already stored, or because it is a modified equation that should
7399 not overwrite the stored one."
7400 (interactive "P")
7401 (org-table-check-inside-data-field)
7402 (org-table-get-specials)
7403 (let* (fields
7404 (ndown (if (integerp arg) arg 1))
7405 (org-table-automatic-realign nil)
7406 (case-fold-search nil)
7407 (down (> ndown 1))
7408 (formula (if (and equation suppress-store)
7409 equation
7410 (org-table-get-formula equation (equal arg '(4)))))
7411 (n0 (org-table-current-column))
7412 (modes (copy-sequence org-calc-default-modes))
7413 n form fmt x ev orig c lispp)
7414 ;; Parse the format string. Since we have a lot of modes, this is
7415 ;; a lot of work. However, I think calc still uses most of the time.
7416 (if (string-match ";" formula)
7417 (let ((tmp (org-split-string formula ";")))
7418 (setq formula (car tmp)
7419 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7420 (nth 1 tmp)))
7421 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
7422 (setq c (string-to-char (match-string 1 fmt))
7423 n (string-to-number (match-string 2 fmt)))
7424 (if (= c ?p)
7425 (setq modes (org-set-calc-mode 'calc-internal-prec n))
7426 (setq modes (org-set-calc-mode
7427 'calc-float-format
7428 (list (cdr (assoc c '((?n . float) (?f . fix)
7429 (?s . sci) (?e . eng))))
7430 n))))
7431 (setq fmt (replace-match "" t t fmt)))
7432 (while (string-match "[DRFS]" fmt)
7433 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7434 (setq fmt (replace-match "" t t fmt)))
7435 (unless (string-match "\\S-" fmt)
7436 (setq fmt nil))))
7437 (if (and (not suppress-const) org-table-formula-use-constants)
7438 (setq formula (org-table-formula-substitute-names formula)))
7439 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7440 (while (> ndown 0)
7441 (setq fields (org-split-string
7442 (buffer-substring
7443 (point-at-bol) (point-at-eol)) " *| *"))
7444 (if org-table-formula-numbers-only
7445 (setq fields (mapcar
7446 (lambda (x) (number-to-string (string-to-number x)))
7447 fields)))
7448 (setq ndown (1- ndown))
7449 (setq form (copy-sequence formula)
7450 lispp (equal (substring form 0 2) "'("))
7451 ;; Insert the references to fields in same row
7452 (while (string-match "\\$\\([0-9]+\\)?" form)
7453 (setq n (if (match-beginning 1)
7454 (string-to-number (match-string 1 form))
7456 x (nth (1- n) fields))
7457 (unless x (error "Invalid field specifier \"%s\""
7458 (match-string 0 form)))
7459 (if (equal x "") (setq x "0"))
7460 (setq form (replace-match
7461 (if lispp x (concat "(" x ")"))
7462 t t form)))
7463 ;; Insert ranges in current column
7464 (while (string-match "\\&[-I0-9]+" form)
7465 (setq form (replace-match
7466 (save-match-data
7467 (org-table-get-vertical-vector (match-string 0 form)
7468 nil n0))
7469 t t form)))
7470 (if lispp
7471 (setq ev (eval (eval (read form)))
7472 ev (if (numberp ev) (number-to-string ev) ev))
7473 (or (fboundp 'calc-eval)
7474 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
7475 (setq ev (calc-eval (cons form modes)
7476 (if org-table-formula-numbers-only 'num))))
7478 (when org-table-formula-debug
7479 (with-output-to-temp-buffer "*Help*"
7480 (princ (format "Substitution history of formula
7481 Orig: %s
7482 $xyz-> %s
7483 $1-> %s\n" orig formula form))
7484 (if (listp ev)
7485 (princ (format " %s^\nError: %s"
7486 (make-string (car ev) ?\-) (nth 1 ev)))
7487 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7488 ev (or fmt "NONE")
7489 (if fmt (format fmt (string-to-number ev)) ev)))))
7490 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7491 (unless (and (interactive-p) (not ndown))
7492 (unless (let (inhibit-redisplay)
7493 (y-or-n-p "Debugging Formula. Continue to next? "))
7494 (org-table-align)
7495 (error "Abort"))
7496 (delete-window (get-buffer-window "*Help*"))
7497 (message "")))
7498 (if (listp ev) (setq fmt nil ev "#ERROR"))
7499 (org-table-justify-field-maybe
7500 (if fmt (format fmt (string-to-number ev)) ev))
7501 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7502 (call-interactively 'org-return)
7503 (setq ndown 0)))
7504 (and down (org-table-maybe-recalculate-line))
7505 (or suppress-align (and org-table-may-need-update
7506 (org-table-align)))))
7508 (defun org-table-recalculate (&optional all noalign)
7509 "Recalculate the current table line by applying all stored formulas.
7510 With prefix arg ALL, do this for all lines in the table."
7511 (interactive "P")
7512 (or (memq this-command org-recalc-commands)
7513 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7514 (unless (org-at-table-p) (error "Not at a table"))
7515 (org-table-get-specials)
7516 (let* ((eqlist (sort (org-table-get-stored-formulas)
7517 (lambda (a b) (string< (car a) (car b)))))
7518 (inhibit-redisplay t)
7519 (line-re org-table-dataline-regexp)
7520 (thisline (org-current-line))
7521 (thiscol (org-table-current-column))
7522 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7523 ;; Insert constants in all formulas
7524 (setq eqlist
7525 (mapcar (lambda (x)
7526 (setcdr x (org-table-formula-substitute-names (cdr x)))
7528 eqlist))
7529 ;; Split the equation list
7530 (while (setq eq (pop eqlist))
7531 (if (<= (string-to-char (car eq)) ?9)
7532 (push eq eqlnum)
7533 (push eq eqlname)))
7534 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7535 (if all
7536 (progn
7537 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7538 (goto-char (setq beg (org-table-begin)))
7539 (if (re-search-forward org-table-calculate-mark-regexp end t)
7540 ;; This is a table with marked lines, only compute selected lines
7541 (setq line-re org-table-recalculate-regexp)
7542 ;; Move forward to the first non-header line
7543 (if (and (re-search-forward org-table-dataline-regexp end t)
7544 (re-search-forward org-table-hline-regexp end t)
7545 (re-search-forward org-table-dataline-regexp end t))
7546 (setq beg (match-beginning 0))
7547 nil))) ;; just leave beg where it is
7548 (setq beg (point-at-bol)
7549 end (move-marker (make-marker) (1+ (point-at-eol)))))
7550 (goto-char beg)
7551 (and all (message "Re-applying formulas to full table..."))
7552 (while (re-search-forward line-re end t)
7553 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7554 ;; Unprotected line, recalculate
7555 (and all (message "Re-applying formulas to full table...(line %d)"
7556 (setq cnt (1+ cnt))))
7557 (setq org-last-recalc-line (org-current-line))
7558 (setq eql eqlnum)
7559 (while (setq entry (pop eql))
7560 (goto-line org-last-recalc-line)
7561 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7562 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7563 (goto-line thisline)
7564 (org-table-goto-column thiscol)
7565 (or noalign (and org-table-may-need-update (org-table-align))
7566 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7567 ;; Now do the names fields
7568 (while (setq eq (pop eqlname))
7569 (setq name (car eq)
7570 a (assoc name org-table-named-field-locations))
7571 (when a
7572 (message "Re-applying formula to named field: %s" name)
7573 (goto-line (nth 1 a))
7574 (org-table-goto-column (nth 2 a))
7575 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
7576 ;; back to initial position
7577 (goto-line thisline)
7578 (org-table-goto-column thiscol)
7579 (or noalign (and org-table-may-need-update (org-table-align))
7580 (and all (message "Re-applying formulas...done")))))
7582 (defun org-table-formula-substitute-names (f)
7583 "Replace $const with values in string F."
7584 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7585 ;; First, check for column names
7586 (while (setq start (string-match org-table-column-name-regexp f start))
7587 (setq start (1+ start))
7588 (setq a (assoc (match-string 1 f) org-table-column-names))
7589 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7590 ;; Expand ranges to vectors
7591 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7592 (setq n1 (string-to-number (match-string 1 f))
7593 n2 (string-to-number (match-string 2 f))
7594 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7595 s (concat "[($" (number-to-string (1- nn1)) ")"))
7596 (loop for i from nn1 upto nn2 do
7597 (setq s (concat s ",($" (int-to-string i) ")")))
7598 (setq s (concat s "]"))
7599 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7600 (setq f (replace-match s t t f)))
7601 ;; Parameters and constants
7602 (setq start 0)
7603 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7604 (setq start (1+ start))
7605 (if (setq a (save-match-data
7606 (org-table-get-constant (match-string 1 f))))
7607 (setq f (replace-match (concat "(" a ")") t t f))))
7608 (if org-table-formula-debug
7609 (put-text-property 0 (length f) :orig-formula f1 f))
7612 (defun org-table-get-constant (const)
7613 "Find the value for a parameter or constant in a formula.
7614 Parameters get priority."
7615 (or (cdr (assoc const org-table-local-parameters))
7616 (cdr (assoc const org-table-formula-constants))
7617 (and (fboundp 'constants-get) (constants-get const))
7618 "#UNDEFINED_NAME"))
7620 (defvar org-edit-formulas-map (make-sparse-keymap))
7621 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7622 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7623 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
7625 (defvar org-pos)
7627 (defun org-table-edit-formulas ()
7628 "Edit the formulas of the current table in a separate buffer."
7629 (interactive)
7630 (unless (org-at-table-p)
7631 (error "Not at a table"))
7632 (org-table-get-specials)
7633 (let ((eql (org-table-get-stored-formulas))
7634 (pos (move-marker (make-marker) (point)))
7635 (wc (current-window-configuration))
7636 entry loc s)
7637 (switch-to-buffer-other-window "*Edit Formulas*")
7638 (erase-buffer)
7639 (fundamental-mode)
7640 (org-set-local 'org-pos pos)
7641 (org-set-local 'org-window-configuration wc)
7642 (use-local-map org-edit-formulas-map)
7643 (setq s "# Edit formulas and finish with `C-c C-c'.
7644 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
7645 # Use `C-c ?' to get information about $name at point.
7646 # To cancel editing, press `C-c C-q'.\n")
7647 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7648 (insert s)
7649 (while (setq entry (pop eql))
7650 (when (setq loc (assoc (car entry) org-table-named-field-locations))
7651 (setq s (format "# Named formula, referring to column %d in line %d\n"
7652 (nth 2 loc) (nth 1 loc)))
7653 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7654 (insert s))
7655 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
7656 (remove-text-properties 0 (length s) '(face nil) s)
7657 (insert s))
7658 (goto-char (point-min))
7659 (message "Edit formulas and finish with `C-c C-c'.")))
7661 (defun org-show-variable ()
7662 "Show the location/value of the $ expression at point."
7663 (interactive)
7664 (let (var (pos org-pos) (win (selected-window)) e)
7665 (save-excursion
7666 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
7667 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
7668 (setq var (match-string 1))
7669 (error "No variable at point")))
7670 (cond
7671 ((setq e (assoc var org-table-named-field-locations))
7672 (switch-to-buffer-other-window (marker-buffer pos))
7673 (goto-line (nth 1 e))
7674 (org-table-goto-column (nth 2 e))
7675 (select-window win)
7676 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
7677 ((setq e (assoc var org-table-column-names))
7678 (switch-to-buffer-other-window (marker-buffer pos))
7679 (goto-char pos)
7680 (goto-char (org-table-begin))
7681 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
7682 (org-table-end) t)
7683 (progn
7684 (goto-char (match-beginning 1))
7685 (message "Named column (column %s)" (cdr e)))
7686 (error "Column name not found"))
7687 (select-window win))
7688 ((string-match "^[0-9]$" var)
7689 ;; column number
7690 (switch-to-buffer-other-window (marker-buffer pos))
7691 (goto-char pos)
7692 (goto-char (org-table-begin))
7693 (recenter 1)
7694 (if (re-search-forward org-table-dataline-regexp
7695 (org-table-end) t)
7696 (progn
7697 (goto-char (match-beginning 0))
7698 (org-table-goto-column (string-to-number var))
7699 (message "Column %s" var))
7700 (error "Column name not found"))
7701 (select-window win))
7702 ((setq e (assoc var org-table-local-parameters))
7703 (switch-to-buffer-other-window (marker-buffer pos))
7704 (goto-char pos)
7705 (goto-char (org-table-begin))
7706 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
7707 (progn
7708 (goto-char (match-beginning 1))
7709 (message "Local parameter."))
7710 (error "Parameter not found"))
7711 (select-window win))
7713 (cond
7714 ((setq e (assoc var org-table-formula-constants))
7715 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
7716 ((setq e (and (fboundp 'constants-get) (constants-get var)))
7717 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
7718 (t (error "Undefined name $%s" var)))))))
7720 (defun org-finish-edit-formulas (&optional arg)
7721 "Parse the buffer for formula definitions and install them.
7722 With prefix ARG, apply the new formulas to the table."
7723 (interactive "P")
7724 (let ((pos org-pos) eql)
7725 (goto-char (point-min))
7726 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
7727 (push (cons (match-string 1) (match-string 2)) eql))
7728 (set-window-configuration org-window-configuration)
7729 (select-window (get-buffer-window (marker-buffer pos)))
7730 (goto-char pos)
7731 (unless (org-at-table-p)
7732 (error "Lost table position - cannot install formulae"))
7733 (org-table-store-formulas eql)
7734 (move-marker pos nil)
7735 (kill-buffer "*Edit Formulas*")
7736 (if arg
7737 (org-table-recalculate 'all)
7738 (message "New formulas installed - press C-u C-c C-c to apply."))))
7740 (defun org-abort-edit-formulas ()
7741 "Abort editing formulas, without installing the changes."
7742 (interactive)
7743 (let ((pos org-pos))
7744 (set-window-configuration org-window-configuration)
7745 (select-window (get-buffer-window (marker-buffer pos)))
7746 (goto-char pos)
7747 (message "Formula editing aborted without installing changes")))
7749 ;;; The orgtbl minor mode
7751 ;; Define a minor mode which can be used in other modes in order to
7752 ;; integrate the org-mode table editor.
7754 ;; This is really a hack, because the org-mode table editor uses several
7755 ;; keys which normally belong to the major mode, for example the TAB and
7756 ;; RET keys. Here is how it works: The minor mode defines all the keys
7757 ;; necessary to operate the table editor, but wraps the commands into a
7758 ;; function which tests if the cursor is currently inside a table. If that
7759 ;; is the case, the table editor command is executed. However, when any of
7760 ;; those keys is used outside a table, the function uses `key-binding' to
7761 ;; look up if the key has an associated command in another currently active
7762 ;; keymap (minor modes, major mode, global), and executes that command.
7763 ;; There might be problems if any of the keys used by the table editor is
7764 ;; otherwise used as a prefix key.
7766 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7767 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7768 ;; addresses this by checking explicitly for both bindings.
7770 ;; The optimized version (see variable `orgtbl-optimized') takes over
7771 ;; all keys which are bound to `self-insert-command' in the *global map*.
7772 ;; Some modes bind other commands to simple characters, for example
7773 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7774 ;; active, this binding is ignored inside tables and replaced with a
7775 ;; modified self-insert.
7777 (defvar orgtbl-mode nil
7778 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7779 table editor in arbitrary modes.")
7780 (make-variable-buffer-local 'orgtbl-mode)
7782 (defvar orgtbl-mode-map (make-keymap)
7783 "Keymap for `orgtbl-mode'.")
7785 ;;;###autoload
7786 (defun turn-on-orgtbl ()
7787 "Unconditionally turn on `orgtbl-mode'."
7788 (orgtbl-mode 1))
7790 (defvar org-old-auto-fill-inhibit-regexp nil
7791 "Local variable used by `orgtbl-mode'")
7793 ;;;###autoload
7794 (defun orgtbl-mode (&optional arg)
7795 "The `org-mode' table editor as a minor mode for use in other modes."
7796 (interactive)
7797 (if (org-mode-p)
7798 ;; Exit without error, in case some hook functions calls this
7799 ;; by accident in org-mode.
7800 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7801 (setq orgtbl-mode
7802 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7803 (if orgtbl-mode
7804 (progn
7805 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7806 ;; Make sure we are first in minor-mode-map-alist
7807 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7808 (and c (setq minor-mode-map-alist
7809 (cons c (delq c minor-mode-map-alist)))))
7810 (org-set-local (quote org-table-may-need-update) t)
7811 (org-add-hook 'before-change-functions 'org-before-change-function
7812 nil 'local)
7813 (org-set-local 'org-old-auto-fill-inhibit-regexp
7814 auto-fill-inhibit-regexp)
7815 (org-set-local 'auto-fill-inhibit-regexp
7816 (if auto-fill-inhibit-regexp
7817 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7818 "[ \t]*|"))
7819 (org-add-to-invisibility-spec '(org-cwidth))
7820 (easy-menu-add orgtbl-mode-menu)
7821 (run-hooks 'orgtbl-mode-hook))
7822 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7823 (org-cleanup-narrow-column-properties)
7824 (org-remove-from-invisibility-spec '(org-cwidth))
7825 (remove-hook 'before-change-functions 'org-before-change-function t)
7826 (easy-menu-remove orgtbl-mode-menu)
7827 (force-mode-line-update 'all))))
7829 (defun org-cleanup-narrow-column-properties ()
7830 "Remove all properties related to narrow-column invisibility."
7831 (let ((s 1))
7832 (while (setq s (text-property-any s (point-max)
7833 'display org-narrow-column-arrow))
7834 (remove-text-properties s (1+ s) '(display t)))
7835 (setq s 1)
7836 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
7837 (remove-text-properties s (1+ s) '(org-cwidth t)))
7838 (setq s 1)
7839 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
7840 (remove-text-properties s (1+ s) '(invisible t)))))
7842 ;; Install it as a minor mode.
7843 (put 'orgtbl-mode :included t)
7844 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7845 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7847 (defun orgtbl-make-binding (fun n &rest keys)
7848 "Create a function for binding in the table minor mode.
7849 FUN is the command to call inside a table. N is used to create a unique
7850 command name. KEYS are keys that should be checked in for a command
7851 to execute outside of tables."
7852 (eval
7853 (list 'defun
7854 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7855 '(arg)
7856 (concat "In tables, run `" (symbol-name fun) "'.\n"
7857 "Outside of tables, run the binding of `"
7858 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7859 "'.")
7860 '(interactive "p")
7861 (list 'if
7862 '(org-at-table-p)
7863 (list 'call-interactively (list 'quote fun))
7864 (list 'let '(orgtbl-mode)
7865 (list 'call-interactively
7866 (append '(or)
7867 (mapcar (lambda (k)
7868 (list 'key-binding k))
7869 keys)
7870 '('orgtbl-error))))))))
7872 (defun orgtbl-error ()
7873 "Error when there is no default binding for a table key."
7874 (interactive)
7875 (error "This key is has no function outside tables"))
7877 (defun orgtbl-setup ()
7878 "Setup orgtbl keymaps."
7879 (let ((nfunc 0)
7880 (bindings
7881 (list
7882 '([(meta shift left)] org-table-delete-column)
7883 '([(meta left)] org-table-move-column-left)
7884 '([(meta right)] org-table-move-column-right)
7885 '([(meta shift right)] org-table-insert-column)
7886 '([(meta shift up)] org-table-kill-row)
7887 '([(meta shift down)] org-table-insert-row)
7888 '([(meta up)] org-table-move-row-up)
7889 '([(meta down)] org-table-move-row-down)
7890 '("\C-c\C-w" org-table-cut-region)
7891 '("\C-c\M-w" org-table-copy-region)
7892 '("\C-c\C-y" org-table-paste-rectangle)
7893 '("\C-c-" org-table-insert-hline)
7894 ; '([(shift tab)] org-table-previous-field)
7895 '("\C-m" org-table-next-row)
7896 (list (org-key 'S-return) 'org-table-copy-down)
7897 '([(meta return)] org-table-wrap-region)
7898 '("\C-c\C-q" org-table-wrap-region)
7899 '("\C-c?" org-table-current-column)
7900 '("\C-c " org-table-blank-field)
7901 '("\C-c+" org-table-sum)
7902 '("\C-c=" org-table-eval-formula)
7903 '("\C-c'" org-table-edit-formulas)
7904 '("\C-c`" org-table-edit-field)
7905 '("\C-c*" org-table-recalculate)
7906 '("\C-c|" org-table-create-or-convert-from-region)
7907 '("\C-c^" org-table-sort-lines)
7908 '([(control ?#)] org-table-rotate-recalc-marks)))
7909 elt key fun cmd)
7910 (while (setq elt (pop bindings))
7911 (setq nfunc (1+ nfunc))
7912 (setq key (car elt)
7913 fun (nth 1 elt)
7914 cmd (orgtbl-make-binding fun nfunc key))
7915 (define-key orgtbl-mode-map key cmd))
7916 ;; Special treatment needed for TAB and RET
7917 (define-key orgtbl-mode-map [(return)]
7918 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7919 (define-key orgtbl-mode-map "\C-m"
7920 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7921 (define-key orgtbl-mode-map [(tab)]
7922 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7923 (define-key orgtbl-mode-map "\C-i"
7924 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7925 (define-key orgtbl-mode-map "\C-i"
7926 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
7927 (define-key orgtbl-mode-map "\C-c\C-c"
7928 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
7929 (when orgtbl-optimized
7930 ;; If the user wants maximum table support, we need to hijack
7931 ;; some standard editing functions
7932 (org-remap orgtbl-mode-map
7933 'self-insert-command 'orgtbl-self-insert-command
7934 'delete-char 'org-delete-char
7935 'delete-backward-char 'org-delete-backward-char)
7936 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
7937 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
7938 '("OrgTbl"
7939 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
7940 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
7941 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
7942 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
7943 "--"
7944 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
7945 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
7946 ["Copy Field from Above"
7947 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
7948 "--"
7949 ("Column"
7950 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
7951 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
7952 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
7953 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
7954 "--"
7955 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :active (org-at-table-p) :selected org-table-limit-column-width :style toggle])
7956 ("Row"
7957 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
7958 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
7959 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
7960 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
7961 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
7962 "--"
7963 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
7964 ("Rectangle"
7965 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
7966 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
7967 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
7968 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
7969 "--"
7970 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
7971 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
7972 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
7973 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
7974 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
7975 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
7976 ["Sum Column/Rectangle" org-table-sum
7977 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
7978 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
7979 ["Debug Formulas"
7980 (setq org-table-formula-debug (not org-table-formula-debug))
7981 :style toggle :selected org-table-formula-debug]
7985 (defun orgtbl-tab (arg)
7986 "Justification and field motion for `orgtbl-mode'."
7987 (interactive "P")
7988 (if arg (org-table-edit-field t)
7989 (org-table-justify-field-maybe)
7990 (org-table-next-field)))
7992 (defun orgtbl-ret ()
7993 "Justification and field motion for `orgtbl-mode'."
7994 (interactive)
7995 (org-table-justify-field-maybe)
7996 (org-table-next-row))
7998 (defun orgtbl-self-insert-command (N)
7999 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8000 If the cursor is in a table looking at whitespace, the whitespace is
8001 overwritten, and the table is not marked as requiring realignment."
8002 (interactive "p")
8003 (if (and (org-at-table-p)
8005 (and org-table-auto-blank-field
8006 (member last-command
8007 '(orgtbl-hijacker-command-100
8008 orgtbl-hijacker-command-101
8009 orgtbl-hijacker-command-102
8010 orgtbl-hijacker-command-103
8011 orgtbl-hijacker-command-104
8012 orgtbl-hijacker-command-105))
8013 (org-table-blank-field))
8015 (eq N 1)
8016 (looking-at "[^|\n]* +|"))
8017 (let (org-table-may-need-update)
8018 (goto-char (1- (match-end 0)))
8019 (delete-backward-char 1)
8020 (goto-char (match-beginning 0))
8021 (self-insert-command N))
8022 (setq org-table-may-need-update t)
8023 (let (orgtbl-mode)
8024 (call-interactively (key-binding (vector last-input-event))))))
8026 (defun org-force-self-insert (N)
8027 "Needed to enforce self-insert under remapping."
8028 (interactive "p")
8029 (self-insert-command N))
8031 ;;;; Link Stuff
8033 ;;; Link abbreviations
8035 (defun org-link-expand-abbrev (link)
8036 "Apply replacements as defined in `org-link-abbrev-alist."
8037 (if (string-match "^\\([a-zA-Z]+\\)\\(::\\(.*\\)\\)?$" link)
8038 (let* ((key (match-string 1 link))
8039 (as (or (assoc key org-link-abbrev-alist-local)
8040 (assoc key org-link-abbrev-alist)))
8041 (tag (and (match-end 2) (match-string 3 link)))
8042 rpl)
8043 (if (not as)
8044 link
8045 (setq rpl (cdr as))
8046 (cond
8047 ((symbolp rpl) (funcall rpl tag))
8048 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8049 (t (concat rpl tag)))))
8050 link))
8052 ;;; Storing and inserting links
8054 (defvar org-insert-link-history nil
8055 "Minibuffer history for links inserted with `org-insert-link'.")
8057 (defvar org-stored-links nil
8058 "Contains the links stored with `org-store-link'.")
8060 ;;;###autoload
8061 (defun org-store-link (arg)
8062 "\\<org-mode-map>Store an org-link to the current location.
8063 This link can later be inserted into an org-buffer with
8064 \\[org-insert-link].
8065 For some link types, a prefix arg is interpreted:
8066 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
8067 For file links, arg negates `org-context-in-file-links'."
8068 (interactive "P")
8069 (let (link cpltxt desc description search txt (pos (point)))
8070 (cond
8072 ((eq major-mode 'bbdb-mode)
8073 (setq cpltxt (concat
8074 "bbdb:"
8075 (or (bbdb-record-name (bbdb-current-record))
8076 (bbdb-record-company (bbdb-current-record))))
8077 link (org-make-link cpltxt)))
8079 ((eq major-mode 'Info-mode)
8080 (setq link (org-make-link "info:"
8081 (file-name-nondirectory Info-current-file)
8082 ":" Info-current-node))
8083 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
8084 ":" Info-current-node)))
8086 ((eq major-mode 'calendar-mode)
8087 (let ((cd (calendar-cursor-to-date)))
8088 (setq link
8089 (format-time-string
8090 (car org-time-stamp-formats)
8091 (apply 'encode-time
8092 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8093 nil nil nil))))))
8095 ((or (eq major-mode 'vm-summary-mode)
8096 (eq major-mode 'vm-presentation-mode))
8097 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
8098 (vm-follow-summary-cursor)
8099 (save-excursion
8100 (vm-select-folder-buffer)
8101 (let* ((message (car vm-message-pointer))
8102 (folder buffer-file-name)
8103 (subject (vm-su-subject message))
8104 (author (vm-su-full-name message))
8105 (message-id (vm-su-message-id message)))
8106 (setq message-id (org-remove-angle-brackets message-id))
8107 (setq folder (abbreviate-file-name folder))
8108 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
8109 folder)
8110 (setq folder (replace-match "" t t folder)))
8111 (setq cpltxt (concat author " on: " subject))
8112 (setq link (org-make-link "vm:" folder "#" message-id)))))
8114 ((eq major-mode 'wl-summary-mode)
8115 (let* ((msgnum (wl-summary-message-number))
8116 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
8117 msgnum 'message-id))
8118 (wl-message-entity
8119 (if (fboundp 'elmo-message-entity)
8120 (elmo-message-entity
8121 wl-summary-buffer-elmo-folder msgnum)
8122 (elmo-msgdb-overview-get-entity
8123 msgnum (wl-summary-buffer-msgdb))))
8124 ;; FIXME: How to get author and subject in wl???
8125 (author (wl-summary-line-from)) ; ?
8126 (subject "???"))
8127 (setq message-id (org-remove-angle-brackets message-id))
8128 (setq cpltxt (concat author " on: " subject))
8129 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
8130 "#" message-id))))
8132 ((or (equal major-mode 'mh-folder-mode)
8133 (equal major-mode 'mh-show-mode))
8134 (let ((from-header (org-mhe-get-header "From:"))
8135 (to-header (org-mhe-get-header "To:"))
8136 (subject (org-mhe-get-header "Subject:")))
8137 (setq cpltxt (concat from-header " on: " subject))
8138 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
8139 (org-remove-angle-brackets
8140 (org-mhe-get-header "Message-Id:"))))))
8142 ((eq major-mode 'rmail-mode)
8143 (save-excursion
8144 (save-restriction
8145 (rmail-narrow-to-non-pruned-header)
8146 (let ((folder buffer-file-name)
8147 (message-id (mail-fetch-field "message-id"))
8148 (author (mail-fetch-field "from"))
8149 (subject (mail-fetch-field "subject")))
8150 (setq message-id (org-remove-angle-brackets message-id))
8151 (setq cpltxt (concat author " on: " subject))
8152 (setq link (org-make-link "rmail:" folder "#" message-id))))))
8154 ((eq major-mode 'gnus-group-mode)
8155 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
8156 (gnus-group-group-name)) ; version
8157 ((fboundp 'gnus-group-name)
8158 (gnus-group-name))
8159 (t "???"))))
8160 (setq cpltxt (concat
8161 (if (org-xor arg org-usenet-links-prefer-google)
8162 "http://groups.google.com/groups?group="
8163 "gnus:")
8164 group)
8165 link (org-make-link cpltxt))))
8167 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
8168 (require 'gnus-sum) ; FIXME: I don't think this is needed, actually
8169 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
8170 (gnus-summary-beginning-of-article)
8171 (let* ((group (car gnus-article-current))
8172 (article (cdr gnus-article-current))
8173 (header (gnus-summary-article-header article))
8174 (author (mail-header-from header))
8175 (message-id (mail-header-id header))
8176 (date (mail-header-date header))
8177 (subject (gnus-summary-subject-string)))
8178 (setq cpltxt (concat author " on: " subject))
8179 (if (org-xor arg org-usenet-links-prefer-google)
8180 (setq link
8181 (concat
8182 cpltxt "\n "
8183 (format "http://groups.google.com/groups?as_umsgid=%s"
8184 (org-fixup-message-id-for-http message-id))))
8185 (setq link (org-make-link "gnus:" group
8186 "#" (number-to-string article))))))
8188 ((eq major-mode 'w3-mode)
8189 (setq cpltxt (url-view-url t)
8190 link (org-make-link cpltxt)))
8191 ((eq major-mode 'w3m-mode)
8192 (setq cpltxt (or w3m-current-title w3m-current-url)
8193 link (org-make-link w3m-current-url)))
8195 ((setq search (run-hook-with-args-until-success
8196 'org-create-file-search-functions))
8197 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8198 "::" search))
8199 (setq cpltxt (or description link)))
8201 ((eq major-mode 'image-mode)
8202 (setq cpltxt (concat "file:"
8203 (abbreviate-file-name buffer-file-name))
8204 link (org-make-link cpltxt)))
8206 ((eq major-mode 'dired-mode)
8207 ;; link to the file in the current line
8208 (setq cpltxt (concat "file:"
8209 (abbreviate-file-name
8210 (expand-file-name
8211 (dired-get-filename nil t))))
8212 link (org-make-link cpltxt)))
8214 ((and buffer-file-name (org-mode-p))
8215 ;; Just link to current headline
8216 (setq cpltxt (concat "file:"
8217 (abbreviate-file-name buffer-file-name)))
8218 ;; Add a context search string
8219 (when (org-xor org-context-in-file-links arg)
8220 ;; Check if we are on a target
8221 (if (save-excursion
8222 (skip-chars-forward "^>\n\r")
8223 (and (re-search-backward "<<" nil t)
8224 (looking-at "<<\\(.*?\\)>>")
8225 (<= (match-beginning 0) pos)
8226 (>= (match-end 0) pos)))
8227 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8228 (setq txt (cond
8229 ((org-on-heading-p) nil)
8230 ((org-region-active-p)
8231 (buffer-substring (region-beginning) (region-end)))
8232 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8233 (when (or (null txt) (string-match "\\S-" txt))
8234 (setq cpltxt
8235 (concat cpltxt "::"
8236 (if org-file-link-context-use-camel-case
8237 (org-make-org-heading-camel txt)
8238 (org-make-org-heading-search-string txt)))
8239 desc "NONE"))))
8240 (if (string-match "::\\'" cpltxt)
8241 (setq cpltxt (substring cpltxt 0 -2)))
8242 (setq link (org-make-link cpltxt)))
8244 (buffer-file-name
8245 ;; Just link to this file here.
8246 (setq cpltxt (concat "file:"
8247 (abbreviate-file-name buffer-file-name)))
8248 ;; Add a context string
8249 (when (org-xor org-context-in-file-links arg)
8250 (setq txt (if (org-region-active-p)
8251 (buffer-substring (region-beginning) (region-end))
8252 (buffer-substring (point-at-bol) (point-at-eol))))
8253 ;; Only use search option if there is some text.
8254 (when (string-match "\\S-" txt)
8255 (setq cpltxt
8256 (concat cpltxt "::"
8257 (if org-file-link-context-use-camel-case
8258 (org-make-org-heading-camel txt)
8259 (org-make-org-heading-search-string txt)))
8260 desc "NONE")))
8261 (setq link (org-make-link cpltxt)))
8263 ((interactive-p)
8264 (error "Cannot link to a buffer which is not visiting a file"))
8266 (t (setq link nil)))
8268 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8269 (setq link (or link cpltxt)
8270 desc (or desc cpltxt))
8271 (if (equal desc "NONE") (setq desc nil))
8273 (if (and (interactive-p) link)
8274 (progn
8275 (setq org-stored-links
8276 (cons (list cpltxt link desc) org-stored-links))
8277 (message "Stored: %s" (or cpltxt link)))
8278 (org-make-link-string link desc))))
8280 (defun org-make-org-heading-search-string (&optional string heading)
8281 "Make search string for STRING or current headline."
8282 (interactive)
8283 (let ((s (or string (org-get-heading))))
8284 (unless (and string (not heading))
8285 ;; We are using a headline, clean up garbage in there.
8286 (if (string-match org-todo-regexp s)
8287 (setq s (replace-match "" t t s)))
8288 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8289 (setq s (replace-match "" t t s)))
8290 (setq s (org-trim s))
8291 (if (string-match (concat "^\\(" org-quote-string "\\|"
8292 org-comment-string "\\)") s)
8293 (setq s (replace-match "" t t s)))
8294 (while (string-match org-ts-regexp s)
8295 (setq s (replace-match "" t t s))))
8296 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8297 (setq s (replace-match " " t t s)))
8298 (or string (setq s (concat "*" s))) ; Add * for headlines
8299 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8301 (defun org-make-org-heading-camel (&optional string heading)
8302 "Make a CamelCase string for STRING or the current headline."
8303 (interactive)
8304 (let ((s (or string (org-get-heading))))
8305 (unless (and string (not heading))
8306 ;; We are using a headline, clean up garbage in there.
8307 (if (string-match org-todo-regexp s)
8308 (setq s (replace-match "" t t s)))
8309 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8310 (setq s (replace-match "" t t s)))
8311 (setq s (org-trim s))
8312 (if (string-match (concat "^\\(" org-quote-string "\\|"
8313 org-comment-string "\\)") s)
8314 (setq s (replace-match "" t t s)))
8315 (while (string-match org-ts-regexp s)
8316 (setq s (replace-match "" t t s))))
8317 (while (string-match "[^a-zA-Z_ \t]+" s)
8318 (setq s (replace-match " " t t s)))
8319 (or string (setq s (concat "*" s))) ; Add * for headlines
8320 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8322 (defun org-make-link (&rest strings)
8323 "Concatenate STRINGS, format resulting string with `org-link-format'."
8324 (format org-link-format (apply 'concat strings)))
8326 (defun org-make-link-string (link &optional description)
8327 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8328 (if (eq org-link-style 'plain)
8329 (if (equal description link)
8330 link
8331 (concat description "\n" link))
8332 (when (stringp description)
8333 ;; Remove brackets from the description, they are fatal.
8334 (while (string-match "\\[\\|\\]" description)
8335 (setq description (replace-match "" t t description))))
8336 (when (equal (org-link-escape link) description)
8337 ;; No description needed, it is identical
8338 (setq description nil))
8339 (when (and (not description)
8340 (not (equal link (org-link-escape link))))
8341 (setq description link))
8342 (concat "[[" (org-link-escape link) "]"
8343 (if description (concat "[" description "]") "")
8344 "]")))
8346 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8347 "Association list of escapes for some characters problematic in links.")
8349 (defun org-link-escape (text)
8350 "Escape charaters in TEXT that are problematic for links."
8351 (when text
8352 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8353 org-link-escape-chars "\\|")))
8354 (while (string-match re text)
8355 (setq text
8356 (replace-match
8357 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8358 t t text)))
8359 text)))
8361 (defun org-link-unescape (text)
8362 "Reverse the action of `org-link-escape'."
8363 (when text
8364 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8365 org-link-escape-chars "\\|")))
8366 (while (string-match re text)
8367 (setq text
8368 (replace-match
8369 (car (rassoc (match-string 0 text) org-link-escape-chars))
8370 t t text)))
8371 text)))
8373 (defun org-xor (a b)
8374 "Exclusive or."
8375 (if a (not b) b))
8377 (defun org-get-header (header)
8378 "Find a header field in the current buffer."
8379 (save-excursion
8380 (goto-char (point-min))
8381 (let ((case-fold-search t) s)
8382 (cond
8383 ((eq header 'from)
8384 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8385 (setq s (match-string 1)))
8386 (while (string-match "\"" s)
8387 (setq s (replace-match "" t t s)))
8388 (if (string-match "[<(].*" s)
8389 (setq s (replace-match "" t t s))))
8390 ((eq header 'message-id)
8391 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8392 (setq s (match-string 1))))
8393 ((eq header 'subject)
8394 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8395 (setq s (match-string 1)))))
8396 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8397 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8398 s)))
8401 (defun org-fixup-message-id-for-http (s)
8402 "Replace special characters in a message id, so it can be used in an http query."
8403 (while (string-match "<" s)
8404 (setq s (replace-match "%3C" t t s)))
8405 (while (string-match ">" s)
8406 (setq s (replace-match "%3E" t t s)))
8407 (while (string-match "@" s)
8408 (setq s (replace-match "%40" t t s)))
8411 (defun org-insert-link (&optional complete-file)
8412 "Insert a link. At the prompt, enter the link.
8414 Completion can be used to select a link previously stored with
8415 `org-store-link'. When the empty string is entered (i.e. if you just
8416 press RET at the prompt), the link defaults to the most recently
8417 stored link. As SPC triggers completion in the minibuffer, you need to
8418 use M-SPC or C-q SPC to force the insertion of a space character.
8420 You will also be prompted for a description, and if one is given, it will
8421 be displayed in the buffer instead of the link.
8423 If there is already a link at point, this command will allow you to edit link
8424 and description parts.
8426 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8427 selected using completion. The path to the file will be relative to
8428 the current directory if the file is in the current directory or a
8429 subdirectory. Otherwise, the link will be the absolute path as
8430 completed in the minibuffer (i.e. normally ~/path/to/file).
8432 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8433 is in the current directory or below.
8434 With three \\[universal-argument] prefixes, negate the meaning of
8435 `org-keep-stored-link-after-insertion'."
8436 (interactive "P")
8437 (let (link desc entry remove file (pos (point)))
8438 (cond
8439 ((save-excursion
8440 (skip-chars-forward "^]\n\r")
8441 (and (re-search-backward "\\[\\[" nil t)
8442 (looking-at org-bracket-link-regexp)
8443 (<= (match-beginning 0) pos)
8444 (>= (match-end 0) pos)))
8445 ;; We do have a link at point, and we are going to edit it.
8446 (setq remove (list (match-beginning 0) (match-end 0)))
8447 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8448 (setq link (read-string "Link: "
8449 (org-link-unescape
8450 (org-match-string-no-properties 1)))))
8451 ((equal complete-file '(4))
8452 ;; Completing read for file names.
8453 (setq file (read-file-name "File: "))
8454 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8455 (pwd1 (file-name-as-directory (abbreviate-file-name
8456 (expand-file-name ".")))))
8457 (cond
8458 ((equal complete-file '(16))
8459 (setq link (org-make-link
8460 "file:"
8461 (abbreviate-file-name (expand-file-name file)))))
8462 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8463 (setq link (org-make-link "file:" (match-string 1 file))))
8464 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8465 (expand-file-name file))
8466 (setq link (org-make-link
8467 "file:" (match-string 1 (expand-file-name file)))))
8468 (t (setq link (org-make-link "file:" file))))))
8470 ;; Read link, with completion for stored links.
8471 (setq link (org-completing-read
8472 "Link: " org-stored-links nil nil nil
8473 org-insert-link-history
8474 (or (car (car org-stored-links)))))
8475 (setq entry (assoc link org-stored-links))
8476 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8477 (not org-keep-stored-link-after-insertion))
8478 (setq org-stored-links (delq (assoc link org-stored-links)
8479 org-stored-links)))
8480 (setq link (if entry (nth 1 entry) link)
8481 desc (or desc (nth 2 entry)))))
8483 (if (string-match org-plain-link-re link)
8484 ;; URL-like link, normalize the use of angular brackets.
8485 (setq link (org-make-link (org-remove-angle-brackets link))))
8487 ;; Check if we are linking to the current file with a search option
8488 ;; If yes, simplify the link by using only the search option.
8489 (when (and buffer-file-name
8490 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
8491 (let* ((path (match-string 1 link))
8492 (case-fold-search nil)
8493 (search (match-string 2 link)))
8494 (save-match-data
8495 (if (equal (file-truename buffer-file-name) (file-truename path))
8496 ;; We are linking to this same file, with a search option
8497 (setq link search)))))
8499 ;; Check if we can/should use a relative path. If yes, simplify the link
8500 (when (string-match "\\<file:\\(.*\\)" link)
8501 (let* ((path (match-string 1 link))
8502 (case-fold-search nil))
8503 (cond
8504 ((eq org-link-file-path-type 'absolute)
8505 (setq path (abbreviate-file-name (expand-file-name path))))
8506 ((eq org-link-file-path-type 'noabbrev)
8507 (setq path (expand-file-name path)))
8508 ((eq org-link-file-path-type 'relative)
8509 (setq path (file-relative-name path)))
8511 (save-match-data
8512 (if (string-match (concat "^" (regexp-quote
8513 (file-name-as-directory
8514 (expand-file-name "."))))
8515 (expand-file-name path))
8516 ;; We are linking a file with relative path name.
8517 (setq path (substring (expand-file-name path)
8518 (match-end 0)))))))
8519 (setq link (concat "file:" path))))
8521 (setq desc (read-string "Description: " desc))
8522 (unless (string-match "\\S-" desc) (setq desc nil))
8523 (if remove (apply 'delete-region remove))
8524 (insert (org-make-link-string link desc))))
8526 (defun org-completing-read (&rest args)
8527 (let ((minibuffer-local-completion-map
8528 (copy-keymap minibuffer-local-completion-map)))
8529 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8530 (apply 'completing-read args)))
8532 ;;; Opening/following a link
8534 (defun org-find-file-at-mouse (ev)
8535 "Open file link or URL at mouse."
8536 (interactive "e")
8537 (mouse-set-point ev)
8538 (org-open-at-point 'in-emacs))
8540 (defun org-open-at-mouse (ev)
8541 "Open file link or URL at mouse."
8542 (interactive "e")
8543 (mouse-set-point ev)
8544 (org-open-at-point))
8546 (defvar org-window-config-before-follow-link nil
8547 "The window configuration before following a link.
8548 This is saved in case the need arises to restore it.")
8550 ;; FIXME: IN-EMACS is used for many purposes, maybe rename this argument???
8551 (defun org-open-at-point (&optional in-emacs)
8552 "Open link at or after point.
8553 If there is no link at point, this function will search forward up to
8554 the end of the current subtree.
8555 Normally, files will be opened by an appropriate application. If the
8556 optional argument IN-EMACS is non-nil, Emacs will visit the file."
8557 (interactive "P")
8558 (setq org-window-config-before-follow-link (current-window-configuration))
8559 (org-remove-occur-highlights nil nil t)
8560 (if (org-at-timestamp-p t)
8561 (org-follow-timestamp-link)
8562 (let (type path link line search (pos (point)))
8563 (catch 'match
8564 (save-excursion
8565 (skip-chars-forward "^]\n\r")
8566 (when (and (re-search-backward "\\[\\[" nil t)
8567 (looking-at org-bracket-link-regexp)
8568 (<= (match-beginning 0) pos)
8569 (>= (match-end 0) pos))
8570 (setq link (org-link-unescape (org-match-string-no-properties 1)))
8571 (while (string-match " *\n *" link)
8572 (setq link (replace-match " " t t link)))
8573 (setq link (org-link-expand-abbrev link))
8574 (if (string-match org-link-re-with-space2 link)
8575 (setq type (match-string 1 link)
8576 path (match-string 2 link))
8577 (setq type "thisfile"
8578 path link))
8579 (throw 'match t)))
8581 (when (get-text-property (point) 'org-linked-text)
8582 (setq type "thisfile"
8583 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8584 (1+ (point)) (point))
8585 path (buffer-substring
8586 (previous-single-property-change pos 'org-linked-text)
8587 (next-single-property-change pos 'org-linked-text)))
8588 (throw 'match t))
8590 (save-excursion
8591 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
8592 (if (equal (char-before) ?<) (backward-char 1))
8593 (when (or (looking-at org-angle-link-re)
8594 (looking-at org-plain-link-re)
8595 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
8596 (re-search-forward org-plain-link-re (point-at-eol) t))
8597 (<= (match-beginning 0) pos)
8598 (>= (match-end 0) pos)))
8599 (setq type (match-string 1)
8600 path (match-string 2))
8601 (throw 'match t)))
8602 (save-excursion
8603 (skip-chars-backward "^ \t\n\r")
8604 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
8605 (setq type "tags"
8606 path (match-string 1))
8607 (while (string-match ":" path)
8608 (setq path (replace-match "+" t t path)))
8609 (throw 'match t)))
8610 (save-excursion
8611 (skip-chars-backward "a-zA-Z_")
8612 (when (and (memq 'camel org-activate-links)
8613 (looking-at org-camel-regexp))
8614 (setq type "camel" path (match-string 0))
8615 (if (equal (char-before) ?*)
8616 (setq path (concat "*" path))))
8617 (throw 'match t)))
8618 (unless path
8619 (error "No link found"))
8620 ;; Remove any trailing spaces in path
8621 (if (string-match " +\\'" path)
8622 (setq path (replace-match "" t t path)))
8624 (cond
8626 ((equal type "mailto")
8627 (let ((cmd (car org-link-mailto-program))
8628 (args (cdr org-link-mailto-program)) args1
8629 (address path) (subject "") a)
8630 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8631 (setq address (match-string 1 path)
8632 subject (org-link-escape (match-string 2 path))))
8633 (while args
8634 (cond
8635 ((not (stringp (car args))) (push (pop args) args1))
8636 (t (setq a (pop args))
8637 (if (string-match "%a" a)
8638 (setq a (replace-match address t t a)))
8639 (if (string-match "%s" a)
8640 (setq a (replace-match subject t t a)))
8641 (push a args1))))
8642 (apply cmd (nreverse args1))))
8644 ((member type '("http" "https" "ftp" "news"))
8645 (browse-url (concat type ":" path)))
8647 ((string= type "tags")
8648 (org-tags-view in-emacs path))
8649 ((or (string= type "camel")
8650 (string= type "thisfile"))
8651 (if in-emacs
8652 (switch-to-buffer-other-window
8653 (org-get-buffer-for-internal-link (current-buffer)))
8654 (org-mark-ring-push))
8655 (org-link-search
8656 path
8657 (cond ((equal in-emacs '(4)) 'occur)
8658 ((equal in-emacs '(16)) 'org-occur)
8659 (t nil))))
8661 ((string= type "file")
8662 (if (string-match "::\\([0-9]+\\)\\'" path)
8663 (setq line (string-to-number (match-string 1 path))
8664 path (substring path 0 (match-beginning 0)))
8665 (if (string-match "::\\(.+\\)\\'" path)
8666 (setq search (match-string 1 path)
8667 path (substring path 0 (match-beginning 0)))))
8668 (org-open-file path in-emacs line search))
8670 ((string= type "news")
8671 (org-follow-gnus-link path))
8673 ((string= type "bbdb")
8674 (org-follow-bbdb-link path))
8676 ((string= type "info")
8677 (org-follow-info-link path))
8679 ((string= type "gnus")
8680 (let (group article)
8681 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8682 (error "Error in Gnus link"))
8683 (setq group (match-string 1 path)
8684 article (match-string 3 path))
8685 (org-follow-gnus-link group article)))
8687 ((string= type "vm")
8688 (let (folder article)
8689 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8690 (error "Error in VM link"))
8691 (setq folder (match-string 1 path)
8692 article (match-string 3 path))
8693 ;; in-emacs is the prefix arg, will be interpreted as read-only
8694 (org-follow-vm-link folder article in-emacs)))
8696 ((string= type "wl")
8697 (let (folder article)
8698 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8699 (error "Error in Wanderlust link"))
8700 (setq folder (match-string 1 path)
8701 article (match-string 3 path))
8702 (org-follow-wl-link folder article)))
8704 ((string= type "mhe")
8705 (let (folder article)
8706 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8707 (error "Error in MHE link"))
8708 (setq folder (match-string 1 path)
8709 article (match-string 3 path))
8710 (org-follow-mhe-link folder article)))
8712 ((string= type "rmail")
8713 (let (folder article)
8714 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8715 (error "Error in RMAIL link"))
8716 (setq folder (match-string 1 path)
8717 article (match-string 3 path))
8718 (org-follow-rmail-link folder article)))
8720 ((string= type "shell")
8721 (let ((cmd path))
8722 ;; FIXME: the following is only for backward compatibility
8723 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
8724 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
8725 (if (or (not org-confirm-shell-link-function)
8726 (funcall org-confirm-shell-link-function
8727 (format "Execute \"%s\" in shell? "
8728 (org-add-props cmd nil
8729 'face 'org-warning))))
8730 (progn
8731 (message "Executing %s" cmd)
8732 (shell-command cmd))
8733 (error "Abort"))))
8735 ((string= type "elisp")
8736 (let ((cmd path))
8737 (if (or (not org-confirm-elisp-link-function)
8738 (funcall org-confirm-elisp-link-function
8739 (format "Execute \"%s\" as elisp? "
8740 (org-add-props cmd nil
8741 'face 'org-warning))))
8742 (message "%s => %s" cmd (eval (read cmd)))
8743 (error "Abort"))))
8746 (browse-url-at-point))))))
8748 ;;; File search
8750 (defvar org-create-file-search-functions nil
8751 "List of functions to construct the right search string for a file link.
8752 These functions are called in turn with point at the location to
8753 which the link should point.
8755 A function in the hook should first test if it would like to
8756 handle this file type, for example by checking the major-mode or
8757 the file extension. If it decides not to handle this file, it
8758 should just return nil to give other functions a chance. If it
8759 does handle the file, it must return the search string to be used
8760 when following the link. The search string will be part of the
8761 file link, given after a double colon, and `org-open-at-point'
8762 will automatically search for it. If special measures must be
8763 taken to make the search successful, another function should be
8764 added to the companion hook `org-execute-file-search-functions',
8765 which see.
8767 A function in this hook may also use `setq' to set the variable
8768 `description' to provide a suggestion for the descriptive text to
8769 be used for this link when it gets inserted into an Org-mode
8770 buffer with \\[org-insert-link].")
8772 (defvar org-execute-file-search-functions nil
8773 "List of functions to execute a file search triggered by a link.
8775 Functions added to this hook must accept a single argument, the
8776 search string that was part of the file link, the part after the
8777 double colon. The function must first check if it would like to
8778 handle this search, for example by checking the major-mode or the
8779 file extension. If it decides not to handle this search, it
8780 should just return nil to give other functions a chance. If it
8781 does handle the search, it must return a non-nil value to keep
8782 other functions from trying.
8784 Each function can access the current prefix argument through the
8785 variable `current-prefix-argument'. Note that a single prefix is
8786 used to force opening a link in Emacs, so it may be good to only
8787 use a numeric or double prefix to guide the search function.
8789 In case this is needed, a function in this hook can also restore
8790 the window configuration before `org-open-at-point' was called using:
8792 (set-window-configuration org-window-config-before-follow-link)")
8794 (defun org-link-search (s &optional type)
8795 "Search for a link search option.
8796 When S is a CamelCaseWord, search for a target, or for a sentence containing
8797 the words. If S is surrounded by forward slashes, it is interpreted as a
8798 regular expression. In org-mode files, this will create an `org-occur'
8799 sparse tree. In ordinary files, `occur' will be used to list matches.
8800 If the current buffer is in `dired-mode', grep will be used to search
8801 in all files."
8802 (let ((case-fold-search t)
8803 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8804 (pos (point))
8805 (pre "") (post "")
8806 words re0 re1 re2 re3 re4 re5 re2a reall camel)
8807 (cond
8808 ;; First check if there are any special
8809 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8810 ;; Now try the builtin stuff
8811 ((save-excursion
8812 (goto-char (point-min))
8813 (and
8814 (re-search-forward
8815 (concat "<<" (regexp-quote s0) ">>") nil t)
8816 (setq pos (match-beginning 0))))
8817 ;; There is an exact target for this
8818 (goto-char pos))
8819 ((string-match "^/\\(.*\\)/$" s)
8820 ;; A regular expression
8821 (cond
8822 ((org-mode-p)
8823 (org-occur (match-string 1 s)))
8824 ;;((eq major-mode 'dired-mode)
8825 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8826 (t (org-do-occur (match-string 1 s)))))
8827 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
8829 ;; A camel or a normal search string
8830 (when (equal (string-to-char s) ?*)
8831 ;; Anchor on headlines, post may include tags.
8832 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
8833 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
8834 s (substring s 1)))
8835 (remove-text-properties
8836 0 (length s)
8837 '(face nil mouse-face nil keymap nil fontified nil) s)
8838 ;; Make a series of regular expressions to find a match
8839 (setq words
8840 (if camel
8841 (org-camel-to-words s)
8842 (org-split-string s "[ \n\r\t]+"))
8843 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8844 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
8845 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8846 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8847 re1 (concat pre re2 post)
8848 re3 (concat pre re4 post)
8849 re5 (concat pre ".*" re4)
8850 re2 (concat pre re2)
8851 re2a (concat pre re2a)
8852 re4 (concat pre re4)
8853 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8854 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8855 re5 "\\)"
8857 (cond
8858 ((eq type 'org-occur) (org-occur reall))
8859 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8860 (t (goto-char (point-min))
8861 (if (or (org-search-not-link re0 nil t)
8862 (org-search-not-link re1 nil t)
8863 (org-search-not-link re2 nil t)
8864 (org-search-not-link re2a nil t)
8865 (org-search-not-link re3 nil t)
8866 (org-search-not-link re4 nil t)
8867 (org-search-not-link re5 nil t)
8869 (goto-char (match-beginning 1))
8870 (goto-char pos)
8871 (error "No match")))))
8873 ;; Normal string-search
8874 (goto-char (point-min))
8875 (if (search-forward s nil t)
8876 (goto-char (match-beginning 0))
8877 (error "No match"))))
8878 (and (org-mode-p) (org-show-context 'link-search))))
8880 (defun org-search-not-link (&rest args)
8881 "Execute `re-search-forward', but only accept matches that are not a link."
8882 (catch 'exit
8883 (let (p1)
8884 (while (apply 're-search-forward args)
8885 (setq p1 (point))
8886 (if (not (save-match-data
8887 (and (re-search-backward "\\[\\[" nil t)
8888 (looking-at org-bracket-link-regexp)
8889 (<= (match-beginning 0) p1)
8890 (>= (match-end 0) p1))))
8891 (progn (goto-char (match-end 0))
8892 (throw 'exit (point)))
8893 (goto-char (match-end 0)))))))
8895 (defun org-get-buffer-for-internal-link (buffer)
8896 "Return a buffer to be used for displaying the link target of internal links."
8897 (cond
8898 ((not org-display-internal-link-with-indirect-buffer)
8899 buffer)
8900 ((string-match "(Clone)$" (buffer-name buffer))
8901 (message "Buffer is already a clone, not making another one")
8902 ;; we also do not modify visibility in this case
8903 buffer)
8904 (t ; make a new indirect buffer for displaying the link
8905 (let* ((bn (buffer-name buffer))
8906 (ibn (concat bn "(Clone)"))
8907 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8908 (with-current-buffer ib (org-overview))
8909 ib))))
8911 (defun org-do-occur (regexp &optional cleanup)
8912 "Call the Emacs command `occur'.
8913 If CLEANUP is non-nil, remove the printout of the regular expression
8914 in the *Occur* buffer. This is useful if the regex is long and not useful
8915 to read."
8916 (occur regexp)
8917 (when cleanup
8918 (let ((cwin (selected-window)) win beg end)
8919 (when (setq win (get-buffer-window "*Occur*"))
8920 (select-window win))
8921 (goto-char (point-min))
8922 (when (re-search-forward "match[a-z]+" nil t)
8923 (setq beg (match-end 0))
8924 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8925 (setq end (1- (match-beginning 0)))))
8926 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
8927 (goto-char (point-min))
8928 (select-window cwin))))
8930 ;;; The mark ring for links jumps
8932 (defvar org-mark-ring nil
8933 "Mark ring for positions before jumps in Org-mode.")
8934 (defvar org-mark-ring-last-goto nil
8935 "Last position in the mark ring used to go back.")
8936 ;; Fill and close the ring
8937 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8938 (loop for i from 1 to org-mark-ring-length do
8939 (push (make-marker) org-mark-ring))
8940 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8941 org-mark-ring)
8943 (defun org-mark-ring-push (&optional pos buffer)
8944 "Put the current position or POS into the mark ring and rotate it."
8945 (interactive)
8946 (setq pos (or pos (point)))
8947 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8948 (move-marker (car org-mark-ring)
8949 (or pos (point))
8950 (or buffer (current-buffer)))
8951 (message
8952 (substitute-command-keys
8953 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8955 (defun org-mark-ring-goto (&optional n)
8956 "Jump to the previous position in the mark ring.
8957 With prefix arg N, jump back that many stored positions. When
8958 called several times in succession, walk through the entire ring.
8959 Org-mode commands jumping to a different position in the current file,
8960 or to another Org-mode file, automatically push the old position
8961 onto the ring."
8962 (interactive "p")
8963 (let (p m)
8964 (if (eq last-command this-command)
8965 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8966 (setq p org-mark-ring))
8967 (setq org-mark-ring-last-goto p)
8968 (setq m (car p))
8969 (switch-to-buffer (marker-buffer m))
8970 (goto-char m)
8971 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8973 (defun org-camel-to-words (s)
8974 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
8975 (let ((case-fold-search nil)
8976 words)
8977 (while (string-match "[a-z][A-Z]" s)
8978 (push (substring s 0 (1+ (match-beginning 0))) words)
8979 (setq s (substring s (1+ (match-beginning 0)))))
8980 (nreverse (cons s words))))
8982 (defun org-remove-angle-brackets (s)
8983 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8984 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8986 (defun org-add-angle-brackets (s)
8987 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8988 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8991 ;;; Following specific links
8993 (defun org-follow-timestamp-link ()
8994 (cond
8995 ((org-at-date-range-p t)
8996 (let ((org-agenda-start-on-weekday)
8997 (t1 (match-string 1))
8998 (t2 (match-string 2)))
8999 (setq t1 (time-to-days (org-time-string-to-time t1))
9000 t2 (time-to-days (org-time-string-to-time t2)))
9001 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9002 ((org-at-timestamp-p t)
9003 (org-agenda-list nil (time-to-days (org-time-string-to-time
9004 (substring (match-string 1) 0 10)))
9006 (t (error "This should not happen"))))
9009 (defun org-follow-bbdb-link (name)
9010 "Follow a BBDB link to NAME."
9011 (require 'bbdb)
9012 (let ((inhibit-redisplay t)
9013 (bbdb-electric-p nil))
9014 (catch 'exit
9015 ;; Exact match on name
9016 (bbdb-name (concat "\\`" name "\\'") nil)
9017 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9018 ;; Exact match on name
9019 (bbdb-company (concat "\\`" name "\\'") nil)
9020 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9021 ;; Partial match on name
9022 (bbdb-name name nil)
9023 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9024 ;; Partial match on company
9025 (bbdb-company name nil)
9026 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9027 ;; General match including network address and notes
9028 (bbdb name nil)
9029 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9030 (delete-window (get-buffer-window "*BBDB*"))
9031 (error "No matching BBDB record")))))
9033 (defun org-follow-info-link (name)
9034 "Follow an info file & node link to NAME."
9035 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9036 (string-match "\\(.*\\)" name))
9037 (progn
9038 (require 'info)
9039 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9040 (Info-find-node (match-string 1 name) (match-string 2 name))
9041 (Info-find-node (match-string 1 name) "Top")))
9042 (message (concat "Could not open: " name))))
9044 (defun org-follow-gnus-link (&optional group article)
9045 "Follow a Gnus link to GROUP and ARTICLE."
9046 (require 'gnus)
9047 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9048 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
9049 (if group (gnus-fetch-group group))
9050 (if article
9051 (or (gnus-summary-goto-article article nil 'force)
9052 (if (fboundp 'gnus-summary-insert-cached-articles)
9053 (progn
9054 (gnus-summary-insert-cached-articles)
9055 (gnus-summary-goto-article article nil 'force))
9056 (message "Message could not be found.")))))
9058 (defun org-follow-vm-link (&optional folder article readonly)
9059 "Follow a VM link to FOLDER and ARTICLE."
9060 (require 'vm)
9061 (setq article (org-add-angle-brackets article))
9062 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9063 ;; ange-ftp or efs or tramp access
9064 (let ((user (or (match-string 1 folder) (user-login-name)))
9065 (host (match-string 2 folder))
9066 (file (match-string 3 folder)))
9067 (cond
9068 ((featurep 'tramp)
9069 ;; use tramp to access the file
9070 (if (featurep 'xemacs)
9071 (setq folder (format "[%s@%s]%s" user host file))
9072 (setq folder (format "/%s@%s:%s" user host file))))
9074 ;; use ange-ftp or efs
9075 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9076 (setq folder (format "/%s@%s:%s" user host file))))))
9077 (when folder
9078 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9079 (sit-for 0.1)
9080 (when article
9081 (vm-select-folder-buffer)
9082 (widen)
9083 (let ((case-fold-search t))
9084 (goto-char (point-min))
9085 (if (not (re-search-forward
9086 (concat "^" "message-id: *" (regexp-quote article))))
9087 (error "Could not find the specified message in this folder"))
9088 (vm-isearch-update)
9089 (vm-isearch-narrow)
9090 (vm-beginning-of-message)
9091 (vm-summarize)))))
9093 (defun org-follow-wl-link (folder article)
9094 "Follow a Wanderlust link to FOLDER and ARTICLE."
9095 (setq article (org-add-angle-brackets article))
9096 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
9097 (if article (wl-summary-jump-to-msg-by-message-id article))
9098 (wl-summary-redisplay))
9100 (defun org-follow-rmail-link (folder article)
9101 "Follow an RMAIL link to FOLDER and ARTICLE."
9102 (setq article (org-add-angle-brackets article))
9103 (let (message-number)
9104 (save-excursion
9105 (save-window-excursion
9106 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9107 (setq message-number
9108 (save-restriction
9109 (widen)
9110 (goto-char (point-max))
9111 (if (re-search-backward
9112 (concat "^Message-ID:\\s-+" (regexp-quote
9113 (or article "")))
9114 nil t)
9115 (rmail-what-message))))))
9116 (if message-number
9117 (progn
9118 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9119 (rmail-show-message message-number)
9120 message-number)
9121 (error "Message not found"))))
9123 ;;; mh-e integration based on planner-mode
9124 (defun org-mhe-get-message-real-folder ()
9125 "Return the name of the current message real folder, so if you use
9126 sequences, it will now work."
9127 (save-excursion
9128 (let* ((folder
9129 (if (equal major-mode 'mh-folder-mode)
9130 mh-current-folder
9131 ;; Refer to the show buffer
9132 mh-show-folder-buffer))
9133 (end-index
9134 (if (boundp 'mh-index-folder)
9135 (min (length mh-index-folder) (length folder))))
9137 ;; a simple test on mh-index-data does not work, because
9138 ;; mh-index-data is always nil in a show buffer.
9139 (if (and (boundp 'mh-index-folder)
9140 (string= mh-index-folder (substring folder 0 end-index)))
9141 (if (equal major-mode 'mh-show-mode)
9142 (save-window-excursion
9143 (when (buffer-live-p (get-buffer folder))
9144 (progn
9145 (pop-to-buffer folder)
9146 (org-mhe-get-message-folder-from-index)
9149 (org-mhe-get-message-folder-from-index)
9151 folder
9155 (defun org-mhe-get-message-folder-from-index ()
9156 "Returns the name of the message folder in a index folder buffer."
9157 (save-excursion
9158 (mh-index-previous-folder)
9159 (re-search-forward "^\\(+.*\\)$" nil t)
9160 (message (match-string 1))))
9162 (defun org-mhe-get-message-folder ()
9163 "Return the name of the current message folder. Be careful if you
9164 use sequences."
9165 (save-excursion
9166 (if (equal major-mode 'mh-folder-mode)
9167 mh-current-folder
9168 ;; Refer to the show buffer
9169 mh-show-folder-buffer)))
9171 (defun org-mhe-get-message-num ()
9172 "Return the number of the current message. Be careful if you
9173 use sequences."
9174 (save-excursion
9175 (if (equal major-mode 'mh-folder-mode)
9176 (mh-get-msg-num nil)
9177 ;; Refer to the show buffer
9178 (mh-show-buffer-message-number))))
9180 (defun org-mhe-get-header (header)
9181 "Return a header of the message in folder mode. This will create a
9182 show buffer for the corresponding message. If you have a more clever
9183 idea..."
9184 (let* ((folder (org-mhe-get-message-folder))
9185 (num (org-mhe-get-message-num))
9186 (buffer (get-buffer-create (concat "show-" folder)))
9187 (header-field))
9188 (with-current-buffer buffer
9189 (mh-display-msg num folder)
9190 (if (equal major-mode 'mh-folder-mode)
9191 (mh-header-display)
9192 (mh-show-header-display))
9193 (set-buffer buffer)
9194 (setq header-field (mh-get-header-field header))
9195 (if (equal major-mode 'mh-folder-mode)
9196 (mh-show)
9197 (mh-show-show))
9198 header-field)))
9200 (defun org-follow-mhe-link (folder article)
9201 "Follow an MHE link to FOLDER and ARTICLE.
9202 If ARTICLE is nil FOLDER is shown. If the configuration variable
9203 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9204 ARTICLE is searched in all folders. Indexed searches (swish++,
9205 namazu, and others supported by MH-E) will always search in all
9206 folders."
9207 (require 'mh-e)
9208 (require 'mh-search)
9209 (require 'mh-utils)
9210 (mh-find-path)
9211 (if (not article)
9212 (mh-visit-folder (mh-normalize-folder-name folder))
9213 (setq article (org-add-angle-brackets article))
9214 (mh-search-choose)
9215 (if (equal mh-searcher 'pick)
9216 (progn
9217 (mh-search folder (list "--message-id" article))
9218 (when (and org-mhe-search-all-folders
9219 (not (org-mhe-get-message-real-folder)))
9220 (kill-this-buffer)
9221 (mh-search "+" (list "--message-id" article))))
9222 (mh-search "+" article))
9223 (if (org-mhe-get-message-real-folder)
9224 (mh-show-msg 1)
9225 (kill-this-buffer)
9226 (error "Message not found"))))
9228 ;;; BibTeX links
9230 ;; Use the custom search meachnism to construct and use search strings for
9231 ;; file links to BibTeX database entries.
9233 (defun org-create-file-search-in-bibtex ()
9234 "Create the search string and description for a BibTeX database entry."
9235 (when (eq major-mode 'bibtex-mode)
9236 ;; yes, we want to construct this search string.
9237 ;; Make a good description for this entry, using names, year and the title
9238 ;; Put it into the `description' variable which is dynamically scoped.
9239 (let ((bibtex-autokey-names 1)
9240 (bibtex-autokey-names-stretch 1)
9241 (bibtex-autokey-name-case-convert-function 'identity)
9242 (bibtex-autokey-name-separator " & ")
9243 (bibtex-autokey-additional-names " et al.")
9244 (bibtex-autokey-year-length 4)
9245 (bibtex-autokey-name-year-separator " ")
9246 (bibtex-autokey-titlewords 3)
9247 (bibtex-autokey-titleword-separator " ")
9248 (bibtex-autokey-titleword-case-convert-function 'identity)
9249 (bibtex-autokey-titleword-length 'infty)
9250 (bibtex-autokey-year-title-separator ": "))
9251 (setq description (bibtex-generate-autokey)))
9252 ;; Now parse the entry, get the key and return it.
9253 (save-excursion
9254 (bibtex-beginning-of-entry)
9255 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9257 (defun org-execute-file-search-in-bibtex (s)
9258 "Find the link search string S as a key for a database entry."
9259 (when (eq major-mode 'bibtex-mode)
9260 ;; Yes, we want to do the search in this file.
9261 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9262 (goto-char (point-min))
9263 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9264 (regexp-quote s) "[ \t\n]*,") nil t)
9265 (goto-char (match-beginning 0)))
9266 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9267 ;; Use double prefix to indicate that any web link should be browsed
9268 (let ((b (current-buffer)) (p (point)))
9269 ;; Restore the window configuration because we just use the web link
9270 (set-window-configuration org-window-config-before-follow-link)
9271 (save-excursion (set-buffer b) (goto-char p)
9272 (bibtex-url)))
9273 (recenter 0)) ; Move entry start to beginning of window
9274 ;; return t to indicate that the search is done.
9277 ;; Finally add the functions to the right hooks.
9278 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9279 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9281 ;; end of Bibtex link setup
9283 ;;; Following file links
9285 (defun org-open-file (path &optional in-emacs line search)
9286 "Open the file at PATH.
9287 First, this expands any special file name abbreviations. Then the
9288 configuration variable `org-file-apps' is checked if it contains an
9289 entry for this file type, and if yes, the corresponding command is launched.
9290 If no application is found, Emacs simply visits the file.
9291 With optional argument IN-EMACS, Emacs will visit the file.
9292 Optional LINE specifies a line to go to, optional SEARCH a string to
9293 search for. If LINE or SEARCH is given, the file will always be
9294 opened in Emacs.
9295 If the file does not exist, an error is thrown."
9296 (setq in-emacs (or in-emacs line search))
9297 (let* ((file (if (equal path "")
9298 buffer-file-name
9299 (substitute-in-file-name (expand-file-name path))))
9300 (apps (append org-file-apps (org-default-apps)))
9301 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9302 (dirp (if remp nil (file-directory-p file)))
9303 (dfile (downcase file))
9304 (old-buffer (current-buffer))
9305 (old-pos (point))
9306 (old-mode major-mode)
9307 ext cmd)
9308 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9309 (setq ext (match-string 1 dfile))
9310 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9311 (setq ext (match-string 1 dfile))))
9312 (if in-emacs
9313 (setq cmd 'emacs)
9314 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9315 (and dirp (cdr (assoc 'directory apps)))
9316 (cdr (assoc ext apps))
9317 (cdr (assoc t apps)))))
9318 (when (eq cmd 'mailcap)
9319 (require 'mailcap)
9320 (mailcap-parse-mailcaps)
9321 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9322 (command (mailcap-mime-info mime-type)))
9323 (if (stringp command)
9324 (setq cmd command)
9325 (setq cmd 'emacs))))
9326 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9327 (not (file-exists-p file))
9328 (not org-open-non-existing-files))
9329 (error "No such file: %s" file))
9330 (cond
9331 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9332 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9333 (if (string-match "['\"]%s['\"]" cmd)
9334 (setq cmd (replace-match "%s" t t cmd)))
9335 (setq cmd (format cmd (shell-quote-argument file)))
9336 (save-window-excursion
9337 (shell-command (concat cmd " &"))))
9338 ((or (stringp cmd)
9339 (eq cmd 'emacs))
9340 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9341 (if line (goto-line line)
9342 (if search (org-link-search search))))
9343 ((consp cmd)
9344 (eval cmd))
9345 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9346 (and (org-mode-p) (eq old-mode 'org-mode)
9347 (or (not (equal old-buffer (current-buffer)))
9348 (not (equal old-pos (point))))
9349 (org-mark-ring-push old-pos old-buffer))))
9351 (defun org-default-apps ()
9352 "Return the default applications for this operating system."
9353 (cond
9354 ((eq system-type 'darwin)
9355 org-file-apps-defaults-macosx)
9356 ((eq system-type 'windows-nt)
9357 org-file-apps-defaults-windowsnt)
9358 (t org-file-apps-defaults-gnu)))
9360 (defun org-expand-file-name (path)
9361 "Replace special path abbreviations and expand the file name."
9362 (expand-file-name path))
9364 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9365 (defun org-file-remote-p (file)
9366 "Test whether FILE specifies a location on a remote system.
9367 Return non-nil if the location is indeed remote.
9369 For example, the filename \"/user@host:/foo\" specifies a location
9370 on the system \"/user@host:\"."
9371 (cond ((fboundp 'file-remote-p)
9372 (file-remote-p file))
9373 ((fboundp 'tramp-handle-file-remote-p)
9374 (tramp-handle-file-remote-p file))
9375 ((and (boundp 'ange-ftp-name-format)
9376 (string-match (car ange-ftp-name-format) file))
9378 (t nil)))
9381 ;;;; Hooks for remember.el
9383 ;;;###autoload
9384 (defun org-remember-annotation ()
9385 "Return a link to the current location as an annotation for remember.el.
9386 If you are using Org-mode files as target for data storage with
9387 remember.el, then the annotations should include a link compatible with the
9388 conventions in Org-mode. This function returns such a link."
9389 (org-store-link nil))
9391 (defconst org-remember-help
9392 "Select a destination location for the note.
9393 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
9394 RET at beg-of-buf -> Append to file as level 2 headline
9395 RET on headline -> Store as sublevel entry to current headline
9396 <left>/<right> -> before/after current headline, same headings level")
9398 ;;;###autoload
9399 (defun org-remember-apply-template ()
9400 "Initialize *remember* buffer with template, invoke `org-mode'.
9401 This function should be placed into `remember-mode-hook' and in fact requires
9402 to be run from that hook to fucntion properly."
9403 (if org-remember-templates
9405 (let* ((entry (if (= (length org-remember-templates) 1)
9406 (cdar org-remember-templates)
9407 (message "Select template: %s"
9408 (mapconcat
9409 (lambda (x) (char-to-string (car x)))
9410 org-remember-templates " "))
9411 (cdr (assoc (read-char-exclusive) org-remember-templates))))
9412 (tpl (car entry))
9413 (file (if (consp (cdr entry)) (nth 1 entry)))
9414 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
9415 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
9416 (v-u (concat "[" (substring v-t 1 -1) "]"))
9417 (v-U (concat "[" (substring v-T 1 -1) "]"))
9418 (v-a annotation) ; defined in `remember-mode'
9419 (v-i initial) ; defined in `remember-mode'
9420 (v-n user-full-name)
9422 (unless tpl (setq tpl "") (message "No template") (ding))
9423 (insert tpl) (goto-char (point-min))
9424 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
9425 (when (and initial (equal (match-string 0) "%i"))
9426 (save-match-data
9427 (let* ((lead (buffer-substring
9428 (point-at-bol) (match-beginning 0))))
9429 (setq v-i (mapconcat 'identity
9430 (org-split-string initial "\n")
9431 (concat "\n" lead))))))
9432 (replace-match
9433 (or (eval (intern (concat "v-" (match-string 1)))) "")
9434 t t))
9435 (let ((org-startup-folded nil)
9436 (org-startup-with-deadline-check nil))
9437 (org-mode))
9438 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
9439 (org-set-local 'org-default-notes-file file))
9440 (goto-char (point-min))
9441 (if (re-search-forward "%\\?" nil t) (replace-match "")))
9442 (let ((org-startup-folded nil)
9443 (org-startup-with-deadline-check nil))
9444 (org-mode)))
9445 (org-set-local 'org-finish-function 'remember-buffer))
9447 ;;;###autoload
9448 (defun org-remember-handler ()
9449 "Store stuff from remember.el into an org file.
9450 First prompts for an org file. If the user just presses return, the value
9451 of `org-default-notes-file' is used.
9452 Then the command offers the headings tree of the selected file in order to
9453 file the text at a specific location.
9454 You can either immediately press RET to get the note appended to the
9455 file, or you can use vertical cursor motion and visibility cycling (TAB) to
9456 find a better place. Then press RET or <left> or <right> in insert the note.
9458 Key Cursor position Note gets inserted
9459 -----------------------------------------------------------------------------
9460 RET buffer-start as level 2 heading at end of file
9461 RET on headline as sublevel of the heading at cursor
9462 RET no heading at cursor position, level taken from context.
9463 Or use prefix arg to specify level manually.
9464 <left> on headline as same level, before current heading
9465 <right> on headline as same level, after current heading
9467 So the fastest way to store the note is to press RET RET to append it to
9468 the default file. This way your current train of thought is not
9469 interrupted, in accordance with the principles of remember.el. But with
9470 little extra effort, you can push it directly to the correct location.
9472 Before being stored away, the function ensures that the text has a
9473 headline, i.e. a first line that starts with a \"*\". If not, a headline
9474 is constructed from the current date and some additional data.
9476 If the variable `org-adapt-indentation' is non-nil, the entire text is
9477 also indented so that it starts in the same column as the headline
9478 \(i.e. after the stars).
9480 See also the variable `org-reverse-note-order'."
9481 (catch 'quit
9482 (let* ((txt (buffer-substring (point-min) (point-max)))
9483 (fastp current-prefix-arg)
9484 (file (if fastp org-default-notes-file (org-get-org-file)))
9485 (visiting (find-buffer-visiting file))
9486 (org-startup-with-deadline-check nil)
9487 (org-startup-folded nil)
9488 (org-startup-align-all-tables nil)
9489 spos level indent reversed)
9490 ;; Modify text so that it becomes a nice subtree which can be inserted
9491 ;; into an org tree.
9492 (let* ((lines (split-string txt "\n"))
9493 first)
9494 ;; remove empty lines at the beginning
9495 (while (and lines (string-match "^[ \t]*\n" (car lines)))
9496 (setq lines (cdr lines)))
9497 (setq first (car lines) lines (cdr lines))
9498 (if (string-match "^\\*+" first)
9499 ;; Is already a headline
9500 (setq indent nil)
9501 ;; We need to add a headline: Use time and first buffer line
9502 (setq lines (cons first lines)
9503 first (concat "* " (current-time-string)
9504 " (" (remember-buffer-desc) ")")
9505 indent " "))
9506 (if (and org-adapt-indentation indent)
9507 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
9508 (setq txt (concat first "\n"
9509 (mapconcat 'identity lines "\n"))))
9510 ;; Find the file
9511 (if (not visiting)
9512 (find-file-noselect file))
9513 (with-current-buffer (get-file-buffer file)
9514 (save-excursion (and (goto-char (point-min))
9515 (not (re-search-forward "^\\* " nil t))
9516 (insert "\n* Notes\n")))
9517 (setq reversed (org-notes-order-reversed-p))
9518 (save-excursion
9519 (save-restriction
9520 (widen)
9521 ;; Ask the User for a location
9522 (setq spos (if fastp 1 (org-get-location
9523 (current-buffer)
9524 org-remember-help)))
9525 (if (not spos) (throw 'quit nil)) ; return nil to show we did
9526 ; not handle this note
9527 (goto-char spos)
9528 (cond ((and (bobp) (not reversed))
9529 ;; Put it at the end, as level 2
9530 (save-restriction
9531 (widen)
9532 (goto-char (point-max))
9533 (if (not (bolp)) (newline))
9534 (org-paste-subtree 2 txt)))
9535 ((and (bobp) reversed)
9536 ;; Put it at the start, as level 1
9537 (save-restriction
9538 (widen)
9539 (goto-char (point-min))
9540 (re-search-forward "^\\*" nil t)
9541 (beginning-of-line 1)
9542 (org-paste-subtree 1 txt)))
9543 ((and (org-on-heading-p nil) (not current-prefix-arg))
9544 ;; Put it below this entry, at the beg/end of the subtree
9545 (org-back-to-heading)
9546 (setq level (funcall outline-level))
9547 (if reversed
9548 (outline-end-of-heading)
9549 (outline-end-of-subtree))
9550 (if (not (bolp)) (newline))
9551 (beginning-of-line 1)
9552 (org-paste-subtree (org-get-legal-level level 1) txt))
9554 ;; Put it right there, with automatic level determined by
9555 ;; org-paste-subtree or from prefix arg
9556 (org-paste-subtree current-prefix-arg txt)))
9557 (when remember-save-after-remembering
9558 (save-buffer)
9559 (if (not visiting) (kill-buffer (current-buffer)))))))))
9560 t) ;; return t to indicate that we took care of this note.
9562 (defun org-get-org-file ()
9563 "Read a filename, with default directory `org-directory'."
9564 (let ((default (or org-default-notes-file remember-data-file)))
9565 (read-file-name (format "File name [%s]: " default)
9566 (file-name-as-directory org-directory)
9567 default)))
9569 (defun org-notes-order-reversed-p ()
9570 "Check if the current file should receive notes in reversed order."
9571 (cond
9572 ((not org-reverse-note-order) nil)
9573 ((eq t org-reverse-note-order) t)
9574 ((not (listp org-reverse-note-order)) nil)
9575 (t (catch 'exit
9576 (let ((all org-reverse-note-order)
9577 entry)
9578 (while (setq entry (pop all))
9579 (if (string-match (car entry) buffer-file-name)
9580 (throw 'exit (cdr entry))))
9581 nil)))))
9583 ;;;; Dynamic blocks
9585 (defun org-find-dblock (name)
9586 "Find the first dynamic block with name NAME in the buffer.
9587 If not found, stay at current position and return nil."
9588 (let (pos)
9589 (save-excursion
9590 (goto-char (point-min))
9591 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9592 nil t)
9593 (match-beginning 0))))
9594 (if pos (goto-char pos))
9595 pos))
9597 (defconst org-dblock-start-re
9598 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9599 "Matches the startline of a dynamic block, with parameters.")
9601 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
9602 "Matches the end of a dyhamic block.")
9604 (defun org-create-dblock (plist)
9605 "Create a dynamic block section, with parameters taken from PLIST.
9606 PLIST must containe a :name entry which is used as name of the block."
9607 (unless (bolp) (newline))
9608 (let ((name (plist-get plist :name)))
9609 (insert "#+BEGIN: " name)
9610 (while plist
9611 (if (eq (car plist) :name)
9612 (setq plist (cddr plist))
9613 (insert " " (prin1-to-string (pop plist)))))
9614 (insert "\n\n#+END:\n")
9615 (beginning-of-line -2)))
9617 (defun org-prepare-dblock ()
9618 "Prepare dynamic block for refresh.
9619 This empties the block, puts the cursor at the insert position and returns
9620 the property list including an extra property :name with the block name."
9621 (unless (looking-at org-dblock-start-re)
9622 (error "Not at a dynamic block"))
9623 (let* ((begdel (1+ (match-end 0)))
9624 (name (match-string 1))
9625 (params (append (list :name name)
9626 (read (concat "(" (match-string 3) ")")))))
9627 (unless (re-search-forward org-dblock-end-re nil t)
9628 (error "Dynamic block not terminated"))
9629 (delete-region begdel (match-beginning 0))
9630 (goto-char begdel)
9631 (open-line 1)
9632 params))
9634 (defun org-map-dblocks (&optional command)
9635 "Apply COMMAND to all dynamic blocks in the current buffer.
9636 If COMMAND is not given, use `org-update-dblock'."
9637 (let ((cmd (or command 'org-update-dblock))
9638 pos)
9639 (save-excursion
9640 (goto-char (point-min))
9641 (while (re-search-forward org-dblock-start-re nil t)
9642 (goto-char (setq pos (match-beginning 0)))
9643 (condition-case nil
9644 (funcall cmd)
9645 (error (message "Error during update of dynamic block")))
9646 (goto-char pos)
9647 (unless (re-search-forward org-dblock-end-re nil t)
9648 (error "Dynamic block not terminated"))))))
9650 (defun org-dblock-update (&optional arg)
9651 "User command for updating dynamic blocks.
9652 Update the dynamic block at point. With prefix ARG, update all dynamic
9653 blocks in the buffer."
9654 (interactive "P")
9655 (if arg
9656 (org-update-all-dblocks)
9657 (or (looking-at org-dblock-start-re)
9658 (org-beginning-of-dblock))
9659 (org-update-dblock)))
9661 (defun org-update-dblock ()
9662 "Update the dynamic block at point
9663 This means to empty the block, parse for parameters and then call
9664 the correct writing function."
9665 (let* ((pos (point))
9666 (params (org-prepare-dblock))
9667 (name (plist-get params :name))
9668 (cmd (intern (concat "org-dblock-write:" name))))
9669 (funcall cmd params)
9670 (goto-char pos)))
9672 (defun org-beginning-of-dblock ()
9673 "Find the beginning of the dynamic block at point.
9674 Error if there is no scuh block at point."
9675 (let ((pos (point))
9676 beg)
9677 (end-of-line 1)
9678 (if (and (re-search-backward org-dblock-start-re nil t)
9679 (setq beg (match-beginning 0))
9680 (re-search-forward org-dblock-end-re nil t)
9681 (> (match-end 0) pos))
9682 (goto-char beg)
9683 (goto-char pos)
9684 (error "Not in a dynamic block"))))
9686 (defun org-update-all-dblocks ()
9687 "Update all dynamic blocks in the buffer.
9688 This function can be used in a hook."
9689 (when (org-mode-p)
9690 (org-map-dblocks 'org-update-dblock)))
9693 ;;;; Completion
9695 (defun org-complete (&optional arg)
9696 "Perform completion on word at point.
9697 At the beginning of a headline, this completes TODO keywords as given in
9698 `org-todo-keywords'.
9699 If the current word is preceded by a backslash, completes the TeX symbols
9700 that are supported for HTML support.
9701 If the current word is preceded by \"#+\", completes special words for
9702 setting file options.
9703 In the line after \"#+STARTUP:, complete valid keywords.\"
9704 At all other locations, this simply calls `ispell-complete-word'."
9705 (interactive "P")
9706 (catch 'exit
9707 (let* ((end (point))
9708 (beg1 (save-excursion
9709 (skip-chars-backward "a-zA-Z_@0-9")
9710 (point)))
9711 (beg (save-excursion
9712 (skip-chars-backward "a-zA-Z0-9_:$")
9713 (point)))
9714 (confirm (lambda (x) (stringp (car x))))
9715 (camel (equal (char-before beg) ?*))
9716 (tag (equal (char-before beg1) ?:))
9717 (texp (equal (char-before beg) ?\\))
9718 (link (equal (char-before beg) ?\[))
9719 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9720 beg)
9721 "#+"))
9722 (startup (string-match "^#\\+STARTUP:.*"
9723 (buffer-substring (point-at-bol) (point))))
9724 (completion-ignore-case opt)
9725 (type nil)
9726 (tbl nil)
9727 (table (cond
9728 (opt
9729 (setq type :opt)
9730 (mapcar (lambda (x)
9731 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9732 (cons (match-string 2 x) (match-string 1 x)))
9733 (org-split-string (org-get-current-options) "\n")))
9734 (startup
9735 (setq type :startup)
9736 org-startup-options)
9737 (link (append org-link-abbrev-alist-local
9738 org-link-abbrev-alist))
9739 (texp
9740 (setq type :tex)
9741 org-html-entities)
9742 ((string-match "\\`\\*+[ \t]*\\'"
9743 (buffer-substring (point-at-bol) beg))
9744 (setq type :todo)
9745 (mapcar 'list org-todo-keywords))
9746 (camel
9747 (setq type :camel)
9748 (save-excursion
9749 (goto-char (point-min))
9750 (while (re-search-forward org-todo-line-regexp nil t)
9751 (push (list
9752 (if org-file-link-context-use-camel-case
9753 (org-make-org-heading-camel (match-string 3) t)
9754 (org-make-org-heading-search-string
9755 (match-string 3) t)))
9756 tbl)))
9757 tbl)
9758 (tag (setq type :tag beg beg1)
9759 (or org-tag-alist (org-get-buffer-tags)))
9760 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
9761 (pattern (buffer-substring-no-properties beg end))
9762 (completion (try-completion pattern table confirm)))
9763 (cond ((eq completion t)
9764 (if (equal type :opt)
9765 (insert (substring (cdr (assoc (upcase pattern) table))
9766 (length pattern)))
9767 (if (equal type :tag) (insert ":"))))
9768 ((null completion)
9769 (message "Can't find completion for \"%s\"" pattern)
9770 (ding))
9771 ((not (string= pattern completion))
9772 (delete-region beg end)
9773 (if (string-match " +$" completion)
9774 (setq completion (replace-match "" t t completion)))
9775 (insert completion)
9776 (if (get-buffer-window "*Completions*")
9777 (delete-window (get-buffer-window "*Completions*")))
9778 (if (assoc completion table)
9779 (if (eq type :todo) (insert " ")
9780 (if (eq type :tag) (insert ":"))))
9781 (if (and (equal type :opt) (assoc completion table))
9782 (message "%s" (substitute-command-keys
9783 "Press \\[org-complete] again to insert example settings"))))
9785 (message "Making completion list...")
9786 (let ((list (sort (all-completions pattern table confirm)
9787 'string<)))
9788 (with-output-to-temp-buffer "*Completions*"
9789 (condition-case nil
9790 ;; Protection needed for XEmacs and emacs 21
9791 (display-completion-list list pattern)
9792 (error (display-completion-list list)))))
9793 (message "Making completion list...%s" "done"))))))
9795 ;;;; TODO, DEADLINE, Comments
9797 (defun org-toggle-comment ()
9798 "Change the COMMENT state of an entry."
9799 (interactive)
9800 (save-excursion
9801 (org-back-to-heading)
9802 (if (looking-at (concat outline-regexp
9803 "\\( +\\<" org-comment-string "\\>\\)"))
9804 (replace-match "" t t nil 1)
9805 (if (looking-at outline-regexp)
9806 (progn
9807 (goto-char (match-end 0))
9808 (insert " " org-comment-string))))))
9810 (defvar org-last-todo-state-is-todo nil
9811 "This is non-nil when the last TODO state change led to a TODO state.
9812 If the last change removed the TODO tag or switched to DONE, then
9813 this is nil.")
9815 (defun org-todo (&optional arg)
9816 "Change the TODO state of an item.
9817 The state of an item is given by a keyword at the start of the heading,
9818 like
9819 *** TODO Write paper
9820 *** DONE Call mom
9822 The different keywords are specified in the variable `org-todo-keywords'.
9823 By default the available states are \"TODO\" and \"DONE\".
9824 So for this example: when the item starts with TODO, it is changed to DONE.
9825 When it starts with DONE, the DONE is removed. And when neither TODO nor
9826 DONE are present, add TODO at the beginning of the heading.
9828 With C-u prefix arg, use completion to determine the new state.
9829 With numeric prefix arg, switch to that state.
9831 For calling through lisp, arg is also interpreted in the following way:
9832 'none -> empty state
9833 \"\"(empty string) -> switch to empty state
9834 'done -> switch to DONE
9835 \"WAITING\" -> switch to the specified keyword, but only if it
9836 really is a member of `org-todo-keywords'."
9837 (interactive "P")
9838 (save-excursion
9839 (org-back-to-heading)
9840 (if (looking-at outline-regexp) (goto-char (match-end 0)))
9841 (or (looking-at (concat " +" org-todo-regexp " *"))
9842 (looking-at " *"))
9843 (let* ((this (match-string 1))
9844 (last-state (or this ""))
9845 (completion-ignore-case t)
9846 (member (member this org-todo-keywords))
9847 (tail (cdr member))
9848 (state (cond
9849 ((equal arg '(4))
9850 ;; Read a state with completion
9851 (completing-read "State: " (mapcar (lambda(x) (list x))
9852 org-todo-keywords)
9853 nil t))
9854 ((eq arg 'right)
9855 (if this
9856 (if tail (car tail) nil)
9857 (car org-todo-keywords)))
9858 ((eq arg 'left)
9859 (if (equal member org-todo-keywords)
9861 (if this
9862 (nth (- (length org-todo-keywords) (length tail) 2)
9863 org-todo-keywords)
9864 org-done-string)))
9865 (arg
9866 ;; user requests a specific state
9867 (cond
9868 ((equal arg "") nil)
9869 ((eq arg 'none) nil)
9870 ((eq arg 'done) (org-last org-todo-keywords))
9871 ((car (member arg org-todo-keywords)))
9872 ((nth (1- (prefix-numeric-value arg))
9873 org-todo-keywords))))
9874 ((null member) (car org-todo-keywords))
9875 ((null tail) nil) ;; -> first entry
9876 ((eq org-todo-interpretation 'sequence)
9877 (car tail))
9878 ((memq org-todo-interpretation '(type priority))
9879 (if (eq this-command last-command)
9880 (car tail)
9881 (if (> (length tail) 0) org-done-string nil)))
9882 (t nil)))
9883 (next (if state (concat " " state " ") " "))
9884 dostates)
9885 (replace-match next t t)
9886 (setq org-last-todo-state-is-todo
9887 (not (equal state org-done-string)))
9888 (when org-log-done
9889 (setq dostates (and (eq org-todo-interpretation 'sequence)
9890 (listp org-log-done) (memq 'state org-log-done)))
9891 (cond
9892 ((and state (not this))
9893 (org-add-planning-info nil nil 'closed)
9894 (and dostates (org-add-log-maybe 'state state 'findpos)))
9895 ((and state dostates)
9896 (org-add-log-maybe 'state state 'findpos))
9897 ((equal state org-done-string)
9898 ;; Planning info calls the note-setting command.
9899 (org-add-planning-info 'closed (org-current-time)
9900 (if (org-get-repeat) nil 'scheduled))
9901 (org-add-log-maybe 'done state 'findpos))))
9902 ;; Fixup tag positioning
9903 (and org-auto-align-tags (org-set-tags nil t))
9904 (run-hooks 'org-after-todo-state-change-hook)
9905 ;; (and (equal state org-done-string) (org-auto-repeat-maybe))
9907 ;; Fixup cursor location if close to the keyword
9908 (if (and (outline-on-heading-p)
9909 (not (bolp))
9910 (save-excursion (beginning-of-line 1)
9911 (looking-at org-todo-line-regexp))
9912 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9913 (progn
9914 (goto-char (or (match-end 2) (match-end 1)))
9915 (just-one-space))))
9918 (defun org-get-repeat ()
9919 "Return the REPEAT statement of this entry."
9920 (save-match-data
9921 (save-excursion
9922 (org-back-to-heading t)
9923 (if (re-search-forward
9924 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9925 (match-string 1)))))
9927 (defun org-show-todo-tree (arg)
9928 "Make a compact tree which shows all headlines marked with TODO.
9929 The tree will show the lines where the regexp matches, and all higher
9930 headlines above the match.
9931 With \\[universal-argument] prefix, also show the DONE entries.
9932 With a numeric prefix N, construct a sparse tree for the Nth element
9933 of `org-todo-keywords'."
9934 (interactive "P")
9935 (let ((case-fold-search nil)
9936 (kwd-re
9937 (cond ((null arg) org-not-done-regexp)
9938 ((equal arg '(4)) org-todo-regexp)
9939 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
9940 (regexp-quote (nth (1- (prefix-numeric-value arg))
9941 org-todo-keywords)))
9942 (t (error "Invalid prefix argument: %s" arg)))))
9943 (message "%d TODO entries found"
9944 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
9946 (defun org-deadline ()
9947 "Insert the DEADLINE: string to make a deadline.
9948 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
9949 to modify it to the correct date."
9950 (interactive)
9951 (org-add-planning-info 'deadline nil 'closed))
9953 (defun org-schedule ()
9954 "Insert the SCHEDULED: string to schedule a TODO item.
9955 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
9956 to modify it to the correct date."
9957 (interactive)
9958 (org-add-planning-info 'scheduled nil 'closed))
9960 (defun org-add-planning-info (what &optional time &rest remove)
9961 "Insert new timestamp with keyword in the line directly after the headline.
9962 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9963 If non is given, the user is prompted for a date.
9964 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9965 be removed."
9966 (interactive)
9967 (when what (setq time (or time (org-read-date nil 'to-time))))
9968 (when (and org-insert-labeled-timestamps-at-point
9969 (member what '(scheduled deadline)))
9970 (insert
9971 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9972 (org-insert-time-stamp time)
9973 (setq what nil))
9974 (save-excursion
9975 (save-restriction
9976 (let (col list elt ts buffer-invisibility-spec)
9977 (org-back-to-heading t)
9978 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9979 (goto-char (match-end 1))
9980 (setq col (current-column))
9981 (goto-char (1+ (match-end 0)))
9982 (if (and (not (looking-at outline-regexp))
9983 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9984 "[^\r\n]*"))
9985 (not (equal (match-string 1) org-clock-string)))
9986 (narrow-to-region (match-beginning 0) (match-end 0))
9987 (insert "\n")
9988 (backward-char 1)
9989 (narrow-to-region (point) (point))
9990 (indent-to-column col))
9991 ;; Check if we have to remove something.
9992 (setq list (cons what remove))
9993 (while list
9994 (setq elt (pop list))
9995 (goto-char (point-min))
9996 (when (or (and (eq elt 'scheduled)
9997 (re-search-forward org-scheduled-time-regexp nil t))
9998 (and (eq elt 'deadline)
9999 (re-search-forward org-deadline-time-regexp nil t))
10000 (and (eq elt 'closed)
10001 (re-search-forward org-closed-time-regexp nil t)))
10002 (replace-match "")
10003 (if (looking-at "--+<[^>]+>") (replace-match ""))
10004 (if (looking-at " +") (replace-match ""))))
10005 (goto-char (point-max))
10006 (when what
10007 (insert
10008 (if (not (equal (char-before) ?\ )) " " "")
10009 (cond ((eq what 'scheduled) org-scheduled-string)
10010 ((eq what 'deadline) org-deadline-string)
10011 ((eq what 'closed) org-closed-string))
10012 " ")
10013 (org-insert-time-stamp time nil (eq what 'closed))
10014 (end-of-line 1)
10015 ;;FIXME (and (eq what 'closed) (org-add-log-maybe 'done))
10017 (goto-char (point-min))
10018 (widen)
10019 (if (looking-at "[ \t]+\r?\n")
10020 (replace-match ""))
10021 ts))))
10023 (defvar org-log-note-marker (make-marker))
10024 (defvar org-log-note-purpose nil)
10025 (defvar org-log-note-state nil)
10026 (defvar org-log-note-window-configuration nil)
10027 (defvar org-log-note-return-to (make-marker))
10029 (defun org-add-log-maybe (&optional purpose state findpos)
10030 (save-excursion
10031 (when (and (listp org-log-done)
10032 (memq purpose org-log-done))
10033 (when findpos
10034 (org-back-to-heading t)
10035 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10036 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10037 "[^\r\n]*\\)?"))
10038 (goto-char (match-end 0)))
10039 (move-marker org-log-note-marker (point))
10040 (setq org-log-note-purpose purpose)
10041 (setq org-log-note-state state)
10042 (add-hook 'post-command-hook 'org-add-log-note 'append))))
10044 (defun org-add-log-note (&optional purpose)
10045 "Pop up a window for taking a note, and add this note later at point."
10046 (remove-hook 'post-command-hook 'org-add-log-note)
10047 (setq org-log-note-window-configuration (current-window-configuration))
10048 (delete-other-windows)
10049 (move-marker org-log-note-return-to (point))
10050 (switch-to-buffer (marker-buffer org-log-note-marker))
10051 (goto-char org-log-note-marker)
10052 (switch-to-buffer-other-window "*Org Note*")
10053 (erase-buffer)
10054 (org-mode)
10055 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
10056 (cond
10057 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10058 ((eq org-log-note-purpose 'done) "closed todo item")
10059 ((eq org-log-note-purpose 'state) "state change")
10060 (t (error "This should not happen")))))
10061 (org-set-local 'org-finish-function 'org-store-log-note))
10063 (defun org-store-log-note ()
10064 "Finish taking a log note, and insert it to where it belongs."
10065 (let ((txt (buffer-string))
10066 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10067 lines ind)
10068 (kill-buffer (current-buffer))
10069 (if (string-match "^#.*\n[ \t\n]*" txt)
10070 (setq txt (replace-match "" t t txt)))
10071 (if (string-match "\\s-+\\'" txt)
10072 (setq txt (replace-match "" t t txt)))
10073 (setq lines (org-split-string txt "\n"))
10074 (when (and note (string-match "\\S-" note))
10075 (setq note
10076 (org-replace-escapes
10077 note
10078 (list (cons "%u" (user-login-name))
10079 (cons "%U" user-full-name)
10080 (cons "%t" (format-time-string
10081 (org-time-stamp-format 'long 'inactive)
10082 (current-time)))
10083 (cons "%s" (if org-log-note-state
10084 (concat "\"" org-log-note-state "\"")
10085 "")))))
10086 (if lines (setq note (concat note " \\\\")))
10087 (push note lines))
10088 (save-excursion
10089 (set-buffer (marker-buffer org-log-note-marker))
10090 (save-excursion
10091 (goto-char org-log-note-marker)
10092 (end-of-line 1)
10093 (if (not (bolp)) (insert "\n")) (indent-relative nil)
10094 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
10095 (insert " - " (pop lines))
10096 (while lines
10097 (insert "\n" ind (pop lines))))))
10098 (set-window-configuration org-log-note-window-configuration)
10099 (with-current-buffer (marker-buffer org-log-note-return-to)
10100 (goto-char org-log-note-return-to)))
10102 (defvar org-occur-highlights nil)
10103 (make-variable-buffer-local 'org-occur-highlights)
10105 (defun org-occur (regexp &optional keep-previous callback)
10106 "Make a compact tree which shows all matches of REGEXP.
10107 The tree will show the lines where the regexp matches, and all higher
10108 headlines above the match. It will also show the heading after the match,
10109 to make sure editing the matching entry is easy.
10110 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10111 call to `org-occur' will be kept, to allow stacking of calls to this
10112 command.
10113 If CALLBACK is non-nil, it is a function which is called to confirm
10114 that the match should indeed be shown."
10115 (interactive "sRegexp: \nP")
10116 (or keep-previous (org-remove-occur-highlights nil nil t))
10117 (let ((cnt 0))
10118 (save-excursion
10119 (goto-char (point-min))
10120 (if (or (not keep-previous) ; do not want to keep
10121 (not org-occur-highlights)) ; no previous matches
10122 ;; hide everything
10123 (org-overview))
10124 (while (re-search-forward regexp nil t)
10125 (when (or (not callback)
10126 (save-match-data (funcall callback)))
10127 (setq cnt (1+ cnt))
10128 (org-highlight-new-match (match-beginning 0) (match-end 0))
10129 (org-show-context 'occur-tree))))
10130 (when org-remove-highlights-with-change
10131 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10132 nil 'local))
10133 (unless org-sparse-tree-open-archived-trees
10134 (org-hide-archived-subtrees (point-min) (point-max)))
10135 (run-hooks 'org-occur-hook)
10136 (if (interactive-p)
10137 (message "%d match(es) for regexp %s" cnt regexp))
10138 cnt))
10140 ;; FIXME: Remove the siblings argument, or add args for the others too?
10141 (defun org-show-context (&optional key siblings)
10142 "Make sure point and context and visible.
10143 How much context is shown depends upon the variables
10144 `org-show-hierarchy-above' and `org-show-following-heading'.
10145 When SIBLINGS is non-nil, show all siblings on each hierarchy level."
10146 (let ((heading-p (org-on-heading-p t))
10147 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10148 (following-p (org-get-alist-option org-show-following-heading key))
10149 (siblings-p (or siblings (org-get-alist-option org-show-siblings key))))
10150 (catch 'exit
10151 ;; Show heading or entry text
10152 (if heading-p
10153 (org-flag-heading nil) ; only show the heading
10154 (and (or (org-invisible-p) (org-invisible-p2))
10155 (org-show-hidden-entry))) ; show entire entry
10156 (when following-p
10157 ;; Show next sibling, or heading below text
10158 (save-excursion
10159 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10160 (org-flag-heading nil))))
10161 (when siblings-p (org-show-siblings))
10162 (when hierarchy-p
10163 ;; show all higher headings, possibly with siblings
10164 (save-excursion
10165 (while (and (condition-case nil
10166 (progn (org-up-heading-all 1) t)
10167 (error nil))
10168 (not (bobp)))
10169 (org-flag-heading nil)
10170 (when siblings-p (org-show-siblings))))))))
10172 (defun org-reveal (&optional siblings)
10173 "Show current entry, hierarchy above it, and the following headline.
10174 This can be used to show a consistent set of context around locations
10175 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10176 not t for the search context.
10178 With optional argument SIBLINGS, on each level of the hierarchy all
10179 siblings are shown. This repairs the tree structure to what it would
10180 look like when opened with hierarchical calls to `org-cycle'."
10181 (interactive "P")
10182 (let ((org-show-hierarchy-above t)
10183 (org-show-following-heading t))
10184 (org-show-context nil siblings)))
10186 (defun org-highlight-new-match (beg end)
10187 "Highlight from BEG to END and mark the highlight is an occur headline."
10188 (let ((ov (org-make-overlay beg end)))
10189 (org-overlay-put ov 'face 'secondary-selection)
10190 (push ov org-occur-highlights)))
10192 (defvar org-inhibit-highlight-removal nil)
10193 (defun org-remove-occur-highlights (&optional beg end noremove)
10194 "Remove the occur highlights from the buffer.
10195 BEG and END are ignored. If NOREMOVE is nil, remove this function
10196 from the `before-change-functions' in the current buffer."
10197 (interactive)
10198 (unless org-inhibit-highlight-removal
10199 (mapc 'org-delete-overlay org-occur-highlights)
10200 (setq org-occur-highlights nil)
10201 (unless noremove
10202 (remove-hook 'before-change-functions
10203 'org-remove-occur-highlights 'local))))
10205 ;;;; Priorities
10207 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
10208 "Regular expression matching the priority indicator.")
10210 (defvar org-remove-priority-next-time nil)
10212 (defun org-priority-up ()
10213 "Increase the priority of the current item."
10214 (interactive)
10215 (org-priority 'up))
10217 (defun org-priority-down ()
10218 "Decrease the priority of the current item."
10219 (interactive)
10220 (org-priority 'down))
10222 (defun org-priority (&optional action)
10223 "Change the priority of an item by ARG.
10224 ACTION can be set, up, or down."
10225 (interactive)
10226 (setq action (or action 'set))
10227 (let (current new news have remove)
10228 (save-excursion
10229 (org-back-to-heading)
10230 (if (looking-at org-priority-regexp)
10231 (setq current (string-to-char (match-string 2))
10232 have t)
10233 (setq current org-default-priority))
10234 (cond
10235 ((eq action 'set)
10236 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
10237 (setq new (read-char-exclusive))
10238 (cond ((equal new ?\ ) (setq remove t))
10239 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
10240 (error "Priority must be between `%c' and `%c'"
10241 ?A org-lowest-priority))))
10242 ((eq action 'up)
10243 (setq new (1- current)))
10244 ((eq action 'down)
10245 (setq new (1+ current)))
10246 (t (error "Invalid action")))
10247 (setq new (min (max ?A (upcase new)) org-lowest-priority))
10248 (setq news (format "%c" new))
10249 (if have
10250 (if remove
10251 (replace-match "" t t nil 1)
10252 (replace-match news t t nil 2))
10253 (if remove
10254 (error "No priority cookie found in line")
10255 (looking-at org-todo-line-regexp)
10256 (if (match-end 2)
10257 (progn
10258 (goto-char (match-end 2))
10259 (insert " [#" news "]"))
10260 (goto-char (match-beginning 3))
10261 (insert "[#" news "] ")))))
10262 (if remove
10263 (message "Priority removed")
10264 (message "Priority of current item set to %s" news))))
10267 (defun org-get-priority (s)
10268 "Find priority cookie and return priority."
10269 (save-match-data
10270 (if (not (string-match org-priority-regexp s))
10271 (* 1000 (- org-lowest-priority org-default-priority))
10272 (* 1000 (- org-lowest-priority
10273 (string-to-char (match-string 2 s)))))))
10275 ;;;; Tags
10277 (defun org-scan-tags (action matcher &optional todo-only)
10278 "Scan headline tags with inheritance and produce output ACTION.
10279 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
10280 evaluated, testing if a given set of tags qualifies a headline for
10281 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
10282 are included in the output."
10283 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
10284 (mapconcat 'regexp-quote
10285 (nreverse (cdr (reverse org-todo-keywords)))
10286 "\\|")
10287 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
10288 (props (list 'face nil
10289 'done-face 'org-done
10290 'undone-face nil
10291 'mouse-face 'highlight
10292 'org-not-done-regexp org-not-done-regexp
10293 'keymap org-agenda-keymap
10294 'help-echo
10295 (format "mouse-2 or RET jump to org file %s"
10296 (abbreviate-file-name buffer-file-name))))
10297 (case-fold-search nil)
10298 lspos
10299 tags tags-list tags-alist (llast 0) rtn level category i txt
10300 todo marker entry)
10301 (save-excursion
10302 (goto-char (point-min))
10303 (when (eq action 'sparse-tree) (org-overview))
10304 (while (re-search-forward re nil t)
10305 (catch :skip
10306 (and (eq action 'agenda) (org-agenda-skip))
10307 (setq todo (if (match-end 1) (match-string 2))
10308 tags (if (match-end 4) (match-string 4)))
10309 (goto-char (setq lspos (1+ (match-beginning 0))))
10310 (setq level (funcall outline-level)
10311 category (org-get-category))
10312 (setq i llast llast level)
10313 ;; remove tag lists from same and sublevels
10314 (while (>= i level)
10315 (when (setq entry (assoc i tags-alist))
10316 (setq tags-alist (delete entry tags-alist)))
10317 (setq i (1- i)))
10318 ;; add the nex tags
10319 (when tags
10320 (setq tags (mapcar 'downcase (org-split-string tags ":"))
10321 tags-alist
10322 (cons (cons level tags) tags-alist)))
10323 ;; compile tags for current headline
10324 (setq tags-list
10325 (if org-use-tag-inheritance
10326 (apply 'append (mapcar 'cdr tags-alist))
10327 tags))
10328 (when (and (or (not todo-only) todo)
10329 (eval matcher)
10330 (or (not org-agenda-skip-archived-trees)
10331 (not (member org-archive-tag tags-list))))
10332 ;; list this headline
10333 (if (eq action 'sparse-tree)
10334 (progn
10335 (org-show-context 'tags-tree))
10336 (setq txt (org-format-agenda-item
10338 (concat
10339 (if org-tags-match-list-sublevels
10340 (make-string (1- level) ?.) "")
10341 (org-get-heading))
10342 category tags-list))
10343 (goto-char lspos)
10344 (setq marker (org-agenda-new-marker))
10345 (org-add-props txt props
10346 'org-marker marker 'org-hd-marker marker 'category category)
10347 (push txt rtn))
10348 ;; if we are to skip sublevels, jump to end of subtree
10349 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
10350 (when (and (eq action 'sparse-tree)
10351 (not org-sparse-tree-open-archived-trees))
10352 (org-hide-archived-subtrees (point-min) (point-max)))
10353 (nreverse rtn)))
10355 (defvar todo-only) ;; dynamically scoped
10357 (defun org-tags-sparse-tree (&optional todo-only match)
10358 "Create a sparse tree according to tags string MATCH.
10359 MATCH can contain positive and negative selection of tags, like
10360 \"+WORK+URGENT-WITHBOSS\".
10361 If optional argument TODO_ONLY is non-nil, only select lines that are
10362 also TODO lines."
10363 (interactive "P")
10364 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10366 (defun org-make-tags-matcher (match)
10367 "Create the TAGS//TODO matcher form for the selection string MATCH."
10368 ;; todo-only is scoped dynamically into this function, and the function
10369 ;; may change it it the matcher asksk for it.
10370 (unless match
10371 ;; Get a new match request, with completion
10372 (setq org-last-tags-completion-table
10373 (or org-tag-alist
10374 org-last-tags-completion-table))
10375 (setq match (completing-read
10376 "Match: " 'org-tags-completion-function nil nil nil
10377 'org-tags-history))) ; FIXME: Separate history for this?
10379 ;; Parse the string and create a lisp form
10380 (let ((match0 match)
10381 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[A-Za-z_@0-9]+\\)")
10382 minus tag mm
10383 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10384 orterms term orlist re-p level-p)
10385 (if (string-match "/+" match)
10386 ;; match contains also a todo-matching request
10387 (progn
10388 (setq tagsmatch (substring match 0 (match-beginning 0))
10389 todomatch (substring match (match-end 0)))
10390 (if (string-match "^!" todomatch)
10391 (setq todo-only t todomatch (substring todomatch 1)))
10392 (if (string-match "^\\s-*$" todomatch)
10393 (setq todomatch nil)))
10394 ;; only matching tags
10395 (setq tagsmatch match todomatch nil))
10397 ;; Make the tags matcher
10398 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10399 (setq tagsmatcher t)
10400 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10401 (while (setq term (pop orterms))
10402 (while (and (equal (substring term -1) "\\") orterms)
10403 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10404 (while (string-match re term)
10405 (setq minus (and (match-end 1)
10406 (equal (match-string 1 term) "-"))
10407 tag (match-string 2 term)
10408 re-p (equal (string-to-char tag) ?{)
10409 level-p (match-end 3)
10410 mm (cond
10411 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10412 (level-p `(= level ,(string-to-number
10413 (match-string 3 term))))
10414 (t `(member ,(downcase tag) tags-list)))
10415 mm (if minus (list 'not mm) mm)
10416 term (substring term (match-end 0)))
10417 (push mm tagsmatcher))
10418 (push (if (> (length tagsmatcher) 1)
10419 (cons 'and tagsmatcher)
10420 (car tagsmatcher))
10421 orlist)
10422 (setq tagsmatcher nil))
10423 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
10425 ;; Make the todo matcher
10426 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10427 (setq todomatcher t)
10428 (setq orterms (org-split-string todomatch "|") orlist nil)
10429 (while (setq term (pop orterms))
10430 (while (string-match re term)
10431 (setq minus (and (match-end 1)
10432 (equal (match-string 1 term) "-"))
10433 kwd (match-string 2 term)
10434 re-p (equal (string-to-char kwd) ?{)
10435 term (substring term (match-end 0))
10436 mm (if re-p
10437 `(string-match ,(substring kwd 1 -1) todo)
10438 (list 'equal 'todo kwd))
10439 mm (if minus (list 'not mm) mm))
10440 (push mm todomatcher))
10441 (push (if (> (length todomatcher) 1)
10442 (cons 'and todomatcher)
10443 (car todomatcher))
10444 orlist)
10445 (setq todomatcher nil))
10446 (setq todomatcher (if (> (length orlist) 1)
10447 (cons 'or orlist) (car orlist))))
10449 ;; Return the string and lisp forms of the matcher
10450 (setq matcher (if todomatcher
10451 (list 'and tagsmatcher todomatcher)
10452 tagsmatcher))
10453 (cons match0 matcher)))
10455 (defun org-match-any-p (re list)
10456 "Does re match any element of list?"
10457 (setq list (mapcar (lambda (x) (string-match re x)) list))
10458 (delq nil list))
10460 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
10461 (defvar org-tags-overlay (org-make-overlay 1 1))
10462 (org-detach-overlay org-tags-overlay)
10464 (defun org-set-tags (&optional arg just-align)
10465 "Set the tags for the current headline.
10466 With prefix ARG, realign all tags in headings in the current buffer."
10467 (interactive "P")
10468 (let* ((re (concat "^" outline-regexp))
10469 (current (org-get-tags))
10470 table current-tags inherited-tags ; computed below when needed
10471 tags p0 c0 c1 rpl)
10472 (if arg
10473 (save-excursion
10474 (goto-char (point-min))
10475 (let (buffer-invisibility-spec) ; Emacs 21 compatibility
10476 (while (re-search-forward re nil t)
10477 (org-set-tags nil t)
10478 (end-of-line 1)))
10479 (message "All tags realigned to column %d" org-tags-column))
10480 (if just-align
10481 (setq tags current)
10482 ;; Get a new set of tags from the user
10483 (setq table (or org-tag-alist (org-get-buffer-tags))
10484 org-last-tags-completion-table table
10485 current-tags (org-split-string current ":")
10486 inherited-tags (nreverse
10487 (nthcdr (length current-tags)
10488 (nreverse (org-get-tags-at))))
10489 tags
10490 (if (or (eq t org-use-fast-tag-selection)
10491 (and org-use-fast-tag-selection
10492 (delq nil (mapcar 'cdr table))))
10493 (org-fast-tag-selection current-tags inherited-tags table)
10494 (let ((org-add-colon-after-tag-completion t))
10495 (org-trim
10496 (completing-read "Tags: " 'org-tags-completion-function
10497 nil nil current 'org-tags-history)))))
10498 (while (string-match "[-+&]+" tags)
10499 ;; No boolean logic, just a list
10500 (setq tags (replace-match ":" t t tags))))
10501 (if (string-match "\\`[\t ]*\\'" tags)
10502 (setq tags "")
10503 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10504 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10506 ;; Insert new tags at the correct column
10507 (beginning-of-line 1)
10508 (if (re-search-forward
10509 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10510 (point-at-eol) t)
10511 (progn
10512 (if (equal tags "")
10513 (setq rpl "")
10514 (goto-char (match-beginning 0))
10515 (setq c0 (current-column) p0 (point)
10516 c1 (max (1+ c0) (if (> org-tags-column 0)
10517 org-tags-column
10518 (- (- org-tags-column) (length tags))))
10519 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10520 (replace-match rpl)
10521 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
10522 tags)
10523 (error "Tags alignment failed")))))
10525 (defun org-tags-completion-function (string predicate &optional flag)
10526 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10527 (confirm (lambda (x) (stringp (car x)))))
10528 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10529 (setq s1 (match-string 1 string)
10530 s2 (match-string 2 string))
10531 (setq s1 "" s2 string))
10532 (cond
10533 ((eq flag nil)
10534 ;; try completion
10535 (setq rtn (try-completion s2 ctable confirm))
10536 (if (stringp rtn)
10537 (concat s1 s2 (substring rtn (length s2))
10538 (if (and org-add-colon-after-tag-completion
10539 (assoc rtn ctable))
10540 ":" "")))
10542 ((eq flag t)
10543 ;; all-completions
10544 (all-completions s2 ctable confirm)
10546 ((eq flag 'lambda)
10547 ;; exact match?
10548 (assoc s2 ctable)))
10551 (defun org-fast-tag-insert (kwd tags face &optional end)
10552 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
10553 (insert (format "%-12s" (concat kwd ":"))
10554 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10555 (or end "")))
10557 (defun org-fast-tag-show-exit (flag)
10558 (save-excursion
10559 (goto-line 3)
10560 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10561 (replace-match ""))
10562 (when flag
10563 (end-of-line 1)
10564 (move-to-column (- (window-width) 19) t)
10565 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10567 (defun org-set-current-tags-overlay (current prefix)
10568 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10569 (if (featurep 'xemacs)
10570 (org-overlay-display org-tags-overlay (concat prefix s)
10571 'secondary-selection)
10572 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10573 (org-overlay-display org-tags-overlay (concat prefix s)))))
10575 (defun org-fast-tag-selection (current inherited table)
10576 "Fast tag selection with single keys.
10577 CURRENT is the current list of tags in the headline, INHERITED is the
10578 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10579 possibly with grouping information.
10580 If the keys are nil, a-z are automatically assigned.
10581 Returns the new tags string, or nil to not change the current settings."
10582 (let* ((maxlen (apply 'max (mapcar
10583 (lambda (x)
10584 (if (stringp (car x)) (string-width (car x)) 0))
10585 table)))
10586 (buf (current-buffer))
10587 (buffer-tags nil)
10588 (fwidth (+ maxlen 3 1 3))
10589 (ncol (/ (- (window-width) 4) fwidth))
10590 (i-face 'org-done)
10591 (c-face 'org-tag)
10592 tg cnt e c char c1 c2 ntable tbl rtn
10593 ov-start ov-end ov-prefix
10594 (exit-after-next org-fast-tag-selection-single-key)
10595 groups ingroup)
10596 (save-excursion
10597 (beginning-of-line 1)
10598 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
10599 (setq ov-start (match-beginning 1)
10600 ov-end (match-end 1)
10601 ov-prefix "")
10602 (setq ov-start (1- (point-at-eol))
10603 ov-end (1+ ov-start))
10604 (skip-chars-forward "^\n\r")
10605 (setq ov-prefix
10606 (concat
10607 (buffer-substring (1- (point)) (point))
10608 (if (> (current-column) org-tags-column)
10610 (make-string (- org-tags-column (current-column)) ?\ ))))))
10611 (org-move-overlay org-tags-overlay ov-start ov-end)
10612 (save-window-excursion
10613 ;; FIXME: would it be better to keep the other windows?
10614 ;; How about fast tag selection keeping all windows? Expert mode?
10615 (delete-other-windows)
10616 (split-window-vertically)
10617 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
10618 (erase-buffer)
10619 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10620 (org-fast-tag-insert "Current" current c-face "\n\n")
10621 (org-fast-tag-show-exit exit-after-next)
10622 (org-set-current-tags-overlay current ov-prefix)
10623 (setq tbl table char ?a cnt 0)
10624 (while (setq e (pop tbl))
10625 (cond
10626 ((equal e '(:startgroup))
10627 (push '() groups) (setq ingroup t)
10628 (when (not (= cnt 0))
10629 (setq cnt 0)
10630 (insert "\n"))
10631 (insert "{ "))
10632 ((equal e '(:endgroup))
10633 (setq ingroup nil cnt 0)
10634 (insert "}\n"))
10636 (setq tg (car e) c2 nil)
10637 (if (cdr e)
10638 (setq c (cdr e))
10639 ;; automatically assign a character.
10640 (setq c1 (string-to-char
10641 (downcase (substring
10642 tg (if (= (string-to-char tg) ?@) 1 0)))))
10643 (if (or (rassoc c1 ntable) (rassoc c1 table))
10644 (while (or (rassoc char ntable) (rassoc char table))
10645 (setq char (1+ char)))
10646 (setq c2 c1))
10647 (setq c (or c2 char)))
10648 (if ingroup (push tg (car groups)))
10649 (setq tg (org-add-props tg nil 'face
10650 (cond
10651 ((member tg current) c-face)
10652 ((member tg inherited) i-face)
10653 (t nil))))
10654 (if (and (= cnt 0) (not ingroup)) (insert " "))
10655 (insert "[" c "] " tg (make-string
10656 (- fwidth 4 (length tg)) ?\ ))
10657 (push (cons tg c) ntable)
10658 (when (= (setq cnt (1+ cnt)) ncol)
10659 (insert "\n")
10660 (if ingroup (insert " "))
10661 (setq cnt 0)))))
10662 (setq ntable (nreverse ntable))
10663 (insert "\n")
10664 (goto-char (point-min))
10665 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
10666 (setq rtn
10667 (catch 'exit
10668 (while t
10669 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [C-c]: multi%s"
10670 (if groups " [!] no groups" ""))
10671 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10672 (cond
10673 ((= c ?\r) (throw 'exit t))
10674 ((= c ?!)
10675 (setq groups nil)
10676 (goto-char (point-min))
10677 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10678 ((= c ?\C-c)
10679 (org-fast-tag-show-exit
10680 (setq exit-after-next (not exit-after-next))))
10681 ((or (= c ?\C-g)
10682 (and (= c ?q) (not (rassoc c ntable))))
10683 (org-detach-overlay org-tags-overlay)
10684 (setq quit-flag t))
10685 ((= c ?\ )
10686 (setq current nil)
10687 (if exit-after-next (setq exit-after-next 'now)))
10688 ((= c ?\t)
10689 (condition-case nil
10690 (setq tg (completing-read
10691 "Tag: "
10692 (or buffer-tags
10693 (with-current-buffer buf
10694 (org-get-buffer-tags)))))
10695 (quit (setq tg "")))
10696 (when (string-match "\\S-" tg)
10697 (add-to-list 'buffer-tags (list tg))
10698 (if (member tg current)
10699 (setq current (delete tg current))
10700 (push tg current)))
10701 (if exit-after-next (setq exit-after-next 'now)))
10702 ((setq e (rassoc c ntable) tg (car e))
10703 (if (member tg current)
10704 (setq current (delete tg current))
10705 (loop for g in groups do
10706 (if (member tg g)
10707 (mapcar (lambda (x)
10708 (setq current (delete x current)))
10709 g)))
10710 (push tg current))
10711 (if exit-after-next (setq exit-after-next 'now))))
10713 ;; Create a sorted list
10714 (setq current
10715 (sort current
10716 (lambda (a b)
10717 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10718 (if (eq exit-after-next 'now) (throw 'exit t))
10719 (goto-char (point-min))
10720 (beginning-of-line 2)
10721 (delete-region (point) (point-at-eol))
10722 (org-fast-tag-insert "Current" current c-face)
10723 (org-set-current-tags-overlay current ov-prefix)
10724 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
10725 (setq tg (match-string 1))
10726 (add-text-properties (match-beginning 1) (match-end 1)
10727 (list 'face
10728 (cond
10729 ((member tg current) c-face)
10730 ((member tg inherited) i-face)
10731 (t nil)))))
10732 (goto-char (point-min)))))
10733 (org-detach-overlay org-tags-overlay)
10734 (if rtn
10735 (mapconcat 'identity current ":")
10736 nil))))
10738 (defun org-get-tags ()
10739 "Get the TAGS string in the current headline."
10740 (unless (org-on-heading-p t)
10741 (error "Not on a heading"))
10742 (save-excursion
10743 (beginning-of-line 1)
10744 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
10745 (org-match-string-no-properties 1)
10746 "")))
10748 (defun org-get-buffer-tags ()
10749 "Get a table of all tags used in the buffer, for completion."
10750 (let (tags)
10751 (save-excursion
10752 (goto-char (point-min))
10753 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
10754 (mapc (lambda (x) (add-to-list 'tags x))
10755 (org-split-string (org-match-string-no-properties 1) ":"))))
10756 (mapcar 'list tags)))
10758 ;;;; Timestamps
10760 (defvar org-last-changed-timestamp nil)
10761 (defvar org-time-was-given) ; dynamically scoped parameter
10762 (defvar org-ts-what) ; dynamically scoped parameter
10764 (defun org-time-stamp (arg)
10765 "Prompt for a date/time and insert a time stamp.
10766 If the user specifies a time like HH:MM, or if this command is called
10767 with a prefix argument, the time stamp will contain date and time.
10768 Otherwise, only the date will be included. All parts of a date not
10769 specified by the user will be filled in from the current date/time.
10770 So if you press just return without typing anything, the time stamp
10771 will represent the current date/time. If there is already a timestamp
10772 at the cursor, it will be modified."
10773 (interactive "P")
10774 (let (org-time-was-given time)
10775 (cond
10776 ((and (org-at-timestamp-p)
10777 (eq last-command 'org-time-stamp)
10778 (eq this-command 'org-time-stamp))
10779 (insert "--")
10780 (setq time (let ((this-command this-command))
10781 (org-read-date arg 'totime)))
10782 (org-insert-time-stamp time (or org-time-was-given arg)))
10783 ((org-at-timestamp-p)
10784 (setq time (let ((this-command this-command))
10785 (org-read-date arg 'totime)))
10786 (when (org-at-timestamp-p) ; just to get the match data
10787 (replace-match "")
10788 (setq org-last-changed-timestamp
10789 (org-insert-time-stamp time (or org-time-was-given arg))))
10790 (message "Timestamp updated"))
10792 (setq time (let ((this-command this-command))
10793 (org-read-date arg 'totime)))
10794 (org-insert-time-stamp time (or org-time-was-given arg))))))
10796 (defun org-time-stamp-inactive (&optional arg)
10797 "Insert an inactive time stamp.
10798 An inactive time stamp is enclosed in square brackets instead of angle
10799 brackets. It is inactive in the sense that it does not trigger agenda entries,
10800 does not link to the calendar and cannot be changed with the S-cursor keys.
10801 So these are more for recording a certain time/date."
10802 (interactive "P")
10803 (let (org-time-was-given time)
10804 (setq time (org-read-date arg 'totime))
10805 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
10807 (defvar org-date-ovl (org-make-overlay 1 1))
10808 (org-overlay-put org-date-ovl 'face 'org-warning)
10809 (org-detach-overlay org-date-ovl)
10811 (defvar org-ans1) ; dynamically scoped parameter
10812 (defvar org-ans2) ; dynamically scoped parameter
10814 (defun org-read-date (&optional with-time to-time from-string)
10815 "Read a date and make things smooth for the user.
10816 The prompt will suggest to enter an ISO date, but you can also enter anything
10817 which will at least partially be understood by `parse-time-string'.
10818 Unrecognized parts of the date will default to the current day, month, year,
10819 hour and minute. For example,
10820 3-2-5 --> 2003-02-05
10821 feb 15 --> currentyear-02-15
10822 sep 12 9 --> 2009-09-12
10823 12:45 --> today 12:45
10824 22 sept 0:34 --> currentyear-09-22 0:34
10825 12 --> currentyear-currentmonth-12
10826 Fri --> nearest Friday (today or later)
10827 +4 --> four days from today (only if +N is the only thing given)
10828 etc.
10829 The function understands only English month and weekday abbreviations,
10830 but this can be configured with the variables `parse-time-months' and
10831 `parse-time-weekdays'.
10833 While prompting, a calendar is popped up - you can also select the
10834 date with the mouse (button 1). The calendar shows a period of three
10835 months. To scroll it to other months, use the keys `>' and `<'.
10836 If you don't like the calendar, turn it off with
10837 \(setq org-popup-calendar-for-date-prompt nil)
10839 With optional argument TO-TIME, the date will immediately be converted
10840 to an internal time.
10841 With an optional argument WITH-TIME, the prompt will suggest to also
10842 insert a time. Note that when WITH-TIME is not set, you can still
10843 enter a time, and this function will inform the calling routine about
10844 this change. The calling routine may then choose to change the format
10845 used to insert the time stamp into the buffer to include the time."
10846 (require 'parse-time)
10847 (let* ((org-time-stamp-rounding-minutes
10848 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
10849 (ct (org-current-time))
10850 (default-time
10851 ;; Default time is either today, or, when entering a range,
10852 ;; the range start.
10853 (if (save-excursion
10854 (re-search-backward
10855 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10856 (- (point) 20) t))
10857 (apply
10858 'encode-time
10859 (mapcar (lambda(x) (or x 0))
10860 (parse-time-string (match-string 1))))
10861 ct))
10862 (calendar-move-hook nil)
10863 (view-diary-entries-initially nil)
10864 (view-calendar-holidays-initially nil)
10865 (timestr (format-time-string
10866 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
10867 (prompt (format "YYYY-MM-DD [%s]: " timestr))
10868 ans org-ans1 org-ans2 (deltadays 0)
10869 second minute hour day month year tl wday wday1)
10871 (cond
10872 (from-string (setq ans from-string))
10873 (org-popup-calendar-for-date-prompt
10874 (save-excursion
10875 (save-window-excursion
10876 (calendar)
10877 (calendar-forward-day (- (time-to-days default-time)
10878 (calendar-absolute-from-gregorian
10879 (calendar-current-date))))
10880 (org-eval-in-calendar nil)
10881 (let* ((old-map (current-local-map))
10882 (map (copy-keymap calendar-mode-map))
10883 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10884 (define-key map (kbd "RET") 'org-calendar-select)
10885 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
10886 'org-calendar-select-mouse)
10887 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
10888 'org-calendar-select-mouse)
10889 (define-key minibuffer-local-map [(meta shift left)]
10890 (lambda () (interactive)
10891 (org-eval-in-calendar '(calendar-backward-month 1))))
10892 (define-key minibuffer-local-map [(meta shift right)]
10893 (lambda () (interactive)
10894 (org-eval-in-calendar '(calendar-forward-month 1))))
10895 (define-key minibuffer-local-map [(shift up)]
10896 (lambda () (interactive)
10897 (org-eval-in-calendar '(calendar-backward-week 1))))
10898 (define-key minibuffer-local-map [(shift down)]
10899 (lambda () (interactive)
10900 (org-eval-in-calendar '(calendar-forward-week 1))))
10901 (define-key minibuffer-local-map [(shift left)]
10902 (lambda () (interactive)
10903 (org-eval-in-calendar '(calendar-backward-day 1))))
10904 (define-key minibuffer-local-map [(shift right)]
10905 (lambda () (interactive)
10906 (org-eval-in-calendar '(calendar-forward-day 1))))
10907 (define-key minibuffer-local-map ">"
10908 (lambda () (interactive)
10909 (org-eval-in-calendar '(scroll-calendar-left 1))))
10910 (define-key minibuffer-local-map "<"
10911 (lambda () (interactive)
10912 (org-eval-in-calendar '(scroll-calendar-right 1))))
10913 (unwind-protect
10914 (progn
10915 (use-local-map map)
10916 (setq ans (read-string prompt "" nil nil))
10917 (if (not (string-match "\\S-" ans)) (setq ans nil))
10918 (setq ans (or org-ans1 ans org-ans2)))
10919 (use-local-map old-map))))))
10920 (t ; Naked prompt only
10921 (setq ans (read-string prompt "" nil timestr))))
10922 (org-detach-overlay org-date-ovl)
10924 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" ans)
10925 (setq deltadays (string-to-number ans) ans ""))
10927 (if (string-match
10928 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10929 (progn
10930 (setq year (if (match-end 2)
10931 (string-to-number (match-string 2 ans))
10932 (string-to-number (format-time-string "%Y")))
10933 month (string-to-number (match-string 3 ans))
10934 day (string-to-number (match-string 4 ans)))
10935 (if (< year 100) (setq year (+ 2000 year)))
10936 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10937 t nil ans))))
10938 (setq tl (parse-time-string ans)
10939 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
10940 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
10941 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
10942 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
10943 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
10944 second (or (nth 0 tl) 0)
10945 wday (nth 6 tl))
10946 (setq day (+ day deltadays))
10947 (when (and wday (not (nth 3 tl)))
10948 ;; Weekday was given, but no day, so pick that day in the week
10949 ;; on or after the derived date.
10950 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10951 (unless (equal wday wday1)
10952 (setq day (+ day (% (- wday wday1 -7) 7)))))
10953 (if (and (boundp 'org-time-was-given)
10954 (nth 2 tl))
10955 (setq org-time-was-given t))
10956 (if (< year 100) (setq year (+ 2000 year)))
10957 (if to-time
10958 (encode-time second minute hour day month year)
10959 (if (or (nth 1 tl) (nth 2 tl))
10960 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
10961 (format "%04d-%02d-%02d" year month day)))))
10963 (defun org-eval-in-calendar (form)
10964 "Eval FORM in the calendar window and return to current window.
10965 Also, store the cursor date in variable org-ans2."
10966 (let ((sw (selected-window)))
10967 (select-window (get-buffer-window "*Calendar*"))
10968 (eval form)
10969 (when (calendar-cursor-to-date)
10970 (let* ((date (calendar-cursor-to-date))
10971 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10972 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10973 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10974 (select-window sw)))
10976 (defun org-calendar-select ()
10977 "Return to `org-read-date' with the date currently selected.
10978 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10979 (interactive)
10980 (when (calendar-cursor-to-date)
10981 (let* ((date (calendar-cursor-to-date))
10982 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10983 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10984 (if (active-minibuffer-window) (exit-minibuffer))))
10986 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
10987 "Insert a date stamp for the date given by the internal TIME.
10988 WITH-HM means, use the stamp format that includes the time of the day.
10989 INACTIVE means use square brackets instead of angular ones, so that the
10990 stamp will not contribute to the agenda.
10991 PRE and POST are optional strings to be inserted before and after the
10992 stamp.
10993 The command returns the inserted time stamp."
10994 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10995 stamp)
10996 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10997 (insert (or pre ""))
10998 (insert (setq stamp (format-time-string fmt time)))
10999 (insert (or post ""))
11000 stamp))
11002 (defun org-toggle-time-stamp-overlays ()
11003 "Toggle the use of custom time stamp formats."
11004 (interactive)
11005 (setq org-display-custom-times (not org-display-custom-times))
11006 (unless org-display-custom-times
11007 (let ((p (point-min)) (bmp (buffer-modified-p)))
11008 (while (setq p (next-single-property-change p 'display))
11009 (if (and (get-text-property p 'display)
11010 (eq (get-text-property p 'face) 'org-date))
11011 (remove-text-properties
11012 p (setq p (next-single-property-change p 'display))
11013 '(display t))))
11014 (set-buffer-modified-p bmp)))
11015 (if (featurep 'xemacs)
11016 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11017 (org-restart-font-lock)
11018 (setq org-table-may-need-update t)
11019 (if org-display-custom-times
11020 (message "Time stamps are overlayed with custom format")
11021 (message "Time stamp overlays removed")))
11023 (defun org-display-custom-time (beg end)
11024 "Overlay modified time stamp format over timestamp between BED and END."
11025 (let* ((t1 (save-match-data
11026 (org-parse-time-string (buffer-substring beg end) t)))
11027 (w1 (- end beg))
11028 (with-hm (and (nth 1 t1) (nth 2 t1)))
11029 (inactive (= (char-before (1- beg)) ?\[))
11030 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
11031 (time (org-fix-decoded-time t1))
11032 (str (org-add-props
11033 (format-time-string
11034 (substring tf 1 -1) (apply 'encode-time time))
11035 nil 'mouse-face 'highlight))
11036 (w2 (length str)))
11037 (if (not (= w2 w1))
11038 (add-text-properties (1+ beg) (+ 2 beg)
11039 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11040 (if (featurep 'xemacs)
11041 (progn
11042 (put-text-property beg end 'invisible t)
11043 (put-text-property beg end 'end-glyph (make-glyph str)))
11044 (put-text-property beg end 'display str))))
11046 (defun org-translate-time (string)
11047 "Translate all timestamps in STRING to custom format.
11048 But do this only if the variable `org-display-custom-times' is set."
11049 (when org-display-custom-times
11050 (save-match-data
11051 (let* ((start 0)
11052 (re org-ts-regexp-both)
11053 t1 with-hm inactive tf time str beg end)
11054 (while (setq start (string-match re string start))
11055 (setq beg (match-beginning 0)
11056 end (match-end 0)
11057 t1 (save-match-data
11058 (org-parse-time-string (substring string beg end) t))
11059 with-hm (and (nth 1 t1) (nth 2 t1))
11060 inactive (equal (substring string beg (1+ beg)) "[")
11061 tf (funcall (if with-hm 'cdr 'car)
11062 org-time-stamp-custom-formats)
11063 time (org-fix-decoded-time t1)
11064 str (format-time-string
11065 (concat
11066 (if inactive "[" "<") (substring tf 1 -1)
11067 (if inactive "]" ">"))
11068 (apply 'encode-time time))
11069 string (replace-match str t t string)
11070 start (+ start (length str)))))))
11071 string)
11073 (defun org-fix-decoded-time (time)
11074 "Set 0 instead of nil for the first 6 elements of time.
11075 Don't touch the rest."
11076 (let ((n 0))
11077 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11079 (defun org-days-to-time (timestamp-string)
11080 "Difference between TIMESTAMP-STRING and now in days."
11081 (- (time-to-days (org-time-string-to-time timestamp-string))
11082 (time-to-days (current-time))))
11084 (defun org-deadline-close (timestamp-string &optional ndays)
11085 "Is the time in TIMESTAMP-STRING close to the current date?"
11086 (and (< (org-days-to-time timestamp-string)
11087 (or ndays org-deadline-warning-days))
11088 (not (org-entry-is-done-p))))
11090 (defun org-calendar-select-mouse (ev)
11091 "Return to `org-read-date' with the date currently selected.
11092 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11093 (interactive "e")
11094 (mouse-set-point ev)
11095 (when (calendar-cursor-to-date)
11096 (let* ((date (calendar-cursor-to-date))
11097 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11098 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11099 (if (active-minibuffer-window) (exit-minibuffer))))
11101 (defun org-check-deadlines (ndays)
11102 "Check if there are any deadlines due or past due.
11103 A deadline is considered due if it happens within `org-deadline-warning-days'
11104 days from today's date. If the deadline appears in an entry marked DONE,
11105 it is not shown. The prefix arg NDAYS can be used to test that many
11106 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11107 (interactive "P")
11108 (let* ((org-warn-days
11109 (cond
11110 ((equal ndays '(4)) 100000)
11111 (ndays (prefix-numeric-value ndays))
11112 (t org-deadline-warning-days)))
11113 (case-fold-search nil)
11114 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11115 (callback
11116 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11118 (message "%d deadlines past-due or due within %d days"
11119 (org-occur regexp nil callback)
11120 org-warn-days)))
11122 (defun org-evaluate-time-range (&optional to-buffer)
11123 "Evaluate a time range by computing the difference between start and end.
11124 Normally the result is just printed in the echo area, but with prefix arg
11125 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11126 If the time range is actually in a table, the result is inserted into the
11127 next column.
11128 For time difference computation, a year is assumed to be exactly 365
11129 days in order to avoid rounding problems."
11130 (interactive "P")
11132 (org-clock-update-time-maybe)
11133 (save-excursion
11134 (unless (org-at-date-range-p)
11135 (goto-char (point-at-bol))
11136 (re-search-forward org-tr-regexp (point-at-eol) t))
11137 (if (not (org-at-date-range-p))
11138 (error "Not at a time-stamp range, and none found in current line")))
11139 (let* ((ts1 (match-string 1))
11140 (ts2 (match-string 2))
11141 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11142 (match-end (match-end 0))
11143 (time1 (org-time-string-to-time ts1))
11144 (time2 (org-time-string-to-time ts2))
11145 (t1 (time-to-seconds time1))
11146 (t2 (time-to-seconds time2))
11147 (diff (abs (- t2 t1)))
11148 (negative (< (- t2 t1) 0))
11149 ;; (ys (floor (* 365 24 60 60)))
11150 (ds (* 24 60 60))
11151 (hs (* 60 60))
11152 (fy "%dy %dd %02d:%02d")
11153 (fy1 "%dy %dd")
11154 (fd "%dd %02d:%02d")
11155 (fd1 "%dd")
11156 (fh "%02d:%02d")
11157 y d h m align)
11158 (if havetime
11159 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11161 d (floor (/ diff ds)) diff (mod diff ds)
11162 h (floor (/ diff hs)) diff (mod diff hs)
11163 m (floor (/ diff 60)))
11164 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11166 d (floor (+ (/ diff ds) 0.5))
11167 h 0 m 0))
11168 (if (not to-buffer)
11169 (message (org-make-tdiff-string y d h m))
11170 (when (org-at-table-p)
11171 (goto-char match-end)
11172 (setq align t)
11173 (and (looking-at " *|") (goto-char (match-end 0))))
11174 (if (looking-at
11175 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11176 (replace-match ""))
11177 (if negative (insert " -"))
11178 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11179 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11180 (insert " " (format fh h m))))
11181 (if align (org-table-align))
11182 (message "Time difference inserted")))))
11184 (defun org-make-tdiff-string (y d h m)
11185 (let ((fmt "")
11186 (l nil))
11187 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11188 l (push y l)))
11189 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11190 l (push d l)))
11191 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11192 l (push h l)))
11193 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11194 l (push m l)))
11195 (apply 'format fmt (nreverse l))))
11197 (defun org-time-string-to-time (s)
11198 (apply 'encode-time (org-parse-time-string s)))
11200 (defun org-parse-time-string (s &optional nodefault)
11201 "Parse the standard Org-mode time string.
11202 This should be a lot faster than the normal `parse-time-string'.
11203 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11204 hour and minute fields will be nil if not given."
11205 (if (string-match org-ts-regexp1 s)
11206 (list 0
11207 (if (or (match-beginning 8) (not nodefault))
11208 (string-to-number (or (match-string 8 s) "0")))
11209 (if (or (match-beginning 7) (not nodefault))
11210 (string-to-number (or (match-string 7 s) "0")))
11211 (string-to-number (match-string 4 s))
11212 (string-to-number (match-string 3 s))
11213 (string-to-number (match-string 2 s))
11214 nil nil nil)
11215 (make-list 9 0)))
11217 (defun org-timestamp-up (&optional arg)
11218 "Increase the date item at the cursor by one.
11219 If the cursor is on the year, change the year. If it is on the month or
11220 the day, change that.
11221 With prefix ARG, change by that many units."
11222 (interactive "p")
11223 (org-timestamp-change (prefix-numeric-value arg)))
11225 (defun org-timestamp-down (&optional arg)
11226 "Decrease the date item at the cursor by one.
11227 If the cursor is on the year, change the year. If it is on the month or
11228 the day, change that.
11229 With prefix ARG, change by that many units."
11230 (interactive "p")
11231 (org-timestamp-change (- (prefix-numeric-value arg))))
11233 (defun org-timestamp-up-day (&optional arg)
11234 "Increase the date in the time stamp by one day.
11235 With prefix ARG, change that many days."
11236 (interactive "p")
11237 (if (and (not (org-at-timestamp-p t))
11238 (org-on-heading-p))
11239 (org-todo 'up)
11240 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11242 (defun org-timestamp-down-day (&optional arg)
11243 "Decrease the date in the time stamp by one day.
11244 With prefix ARG, change that many days."
11245 (interactive "p")
11246 (if (and (not (org-at-timestamp-p t))
11247 (org-on-heading-p))
11248 (org-todo 'down)
11249 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11251 (defsubst org-pos-in-match-range (pos n)
11252 (and (match-beginning n)
11253 (<= (match-beginning n) pos)
11254 (>= (match-end n) pos)))
11256 (defun org-at-timestamp-p (&optional inactive-ok)
11257 "Determine if the cursor is in or at a timestamp."
11258 (interactive)
11259 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11260 (pos (point))
11261 (ans (or (looking-at tsr)
11262 (save-excursion
11263 (skip-chars-backward "^[<\n\r\t")
11264 (if (> (point) 1) (backward-char 1))
11265 (and (looking-at tsr)
11266 (> (- (match-end 0) pos) -1))))))
11267 (and (boundp 'org-ts-what)
11268 (setq org-ts-what
11269 (cond
11270 ((org-pos-in-match-range pos 2) 'year)
11271 ((org-pos-in-match-range pos 3) 'month)
11272 ((org-pos-in-match-range pos 7) 'hour)
11273 ((org-pos-in-match-range pos 8) 'minute)
11274 ((or (org-pos-in-match-range pos 4)
11275 (org-pos-in-match-range pos 5)) 'day)
11276 (t 'day))))
11277 ans))
11279 (defun org-timestamp-change (n &optional what)
11280 "Change the date in the time stamp at point.
11281 The date will be changed by N times WHAT. WHAT can be `day', `month',
11282 `year', `minute', `second'. If WHAT is not given, the cursor position
11283 in the timestamp determines what will be changed."
11284 (let ((pos (point))
11285 with-hm inactive
11286 org-ts-what
11287 ts time time0)
11288 (if (not (org-at-timestamp-p t))
11289 (error "Not at a timestamp"))
11290 (if (and (not what) (not (eq org-ts-what 'day))
11291 org-display-custom-times
11292 (get-text-property (point) 'display)
11293 (not (get-text-property (1- (point)) 'display)))
11294 (setq org-ts-what 'day))
11295 (setq org-ts-what (or what org-ts-what)
11296 with-hm (<= (abs (- (cdr org-ts-lengths)
11297 (- (match-end 0) (match-beginning 0))))
11299 inactive (= (char-after (match-beginning 0)) ?\[)
11300 ts (match-string 0))
11301 (replace-match "")
11302 (setq time0 (org-parse-time-string ts))
11303 (setq time
11304 (apply 'encode-time
11305 (append
11306 (list (or (car time0) 0))
11307 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
11308 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
11309 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
11310 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
11311 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
11312 (nthcdr 6 time0))))
11313 (if (eq what 'calendar)
11314 (let ((cal-date
11315 (save-excursion
11316 (save-match-data
11317 (set-buffer "*Calendar*")
11318 (calendar-cursor-to-date)))))
11319 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11320 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11321 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11322 (setcar time0 (or (car time0) 0))
11323 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11324 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
11325 (setq time (apply 'encode-time time0))))
11326 (setq org-last-changed-timestamp
11327 (org-insert-time-stamp time with-hm inactive))
11328 (org-clock-update-time-maybe)
11329 (goto-char pos)
11330 ;; Try to recenter the calendar window, if any
11331 (if (and org-calendar-follow-timestamp-change
11332 (get-buffer-window "*Calendar*" t)
11333 (memq org-ts-what '(day month year)))
11334 (org-recenter-calendar (time-to-days time)))))
11336 (defun org-recenter-calendar (date)
11337 "If the calendar is visible, recenter it to DATE."
11338 (let* ((win (selected-window))
11339 (cwin (get-buffer-window "*Calendar*" t))
11340 (calendar-move-hook nil))
11341 (when cwin
11342 (select-window cwin)
11343 (calendar-goto-date (if (listp date) date
11344 (calendar-gregorian-from-absolute date)))
11345 (select-window win))))
11347 (defun org-goto-calendar (&optional arg)
11348 "Go to the Emacs calendar at the current date.
11349 If there is a time stamp in the current line, go to that date.
11350 A prefix ARG can be used to force the current date."
11351 (interactive "P")
11352 (let ((tsr org-ts-regexp) diff
11353 (calendar-move-hook nil)
11354 (view-calendar-holidays-initially nil)
11355 (view-diary-entries-initially nil))
11356 (if (or (org-at-timestamp-p)
11357 (save-excursion
11358 (beginning-of-line 1)
11359 (looking-at (concat ".*" tsr))))
11360 (let ((d1 (time-to-days (current-time)))
11361 (d2 (time-to-days
11362 (org-time-string-to-time (match-string 1)))))
11363 (setq diff (- d2 d1))))
11364 (calendar)
11365 (calendar-goto-today)
11366 (if (and diff (not arg)) (calendar-forward-day diff))))
11368 (defun org-date-from-calendar ()
11369 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11370 If there is already a time stamp at the cursor position, update it."
11371 (interactive)
11372 (org-timestamp-change 0 'calendar))
11374 ;;; The clock for measuring work time.
11376 (defvar org-clock-marker (make-marker)
11377 "Marker recording the last clock-in.")
11379 (defun org-clock-in ()
11380 "Start the clock on the current item.
11381 If necessary, clock-out of the currently active clock."
11382 (interactive)
11383 (org-clock-out t)
11384 (let (ts)
11385 (save-excursion
11386 (org-back-to-heading t)
11387 (beginning-of-line 2)
11388 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
11389 (not (equal (match-string 1) org-clock-string)))
11390 (beginning-of-line 1))
11391 (insert "\n") (backward-char 1)
11392 (indent-relative)
11393 (insert org-clock-string " ")
11394 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
11395 (move-marker org-clock-marker (point) (buffer-base-buffer))
11396 (message "Clock started at %s" ts))))
11398 (defun org-clock-out (&optional fail-quietly)
11399 "Stop the currently running clock.
11400 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
11401 (interactive)
11402 (catch 'exit
11403 (if (not (marker-buffer org-clock-marker))
11404 (if fail-quietly (throw 'exit t) (error "No active clock")))
11405 (let (ts te s h m)
11406 (save-excursion
11407 (set-buffer (marker-buffer org-clock-marker))
11408 (goto-char org-clock-marker)
11409 (beginning-of-line 1)
11410 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
11411 (equal (match-string 1) org-clock-string))
11412 (setq ts (match-string 2))
11413 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
11414 (goto-char org-clock-marker)
11415 (insert "--")
11416 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
11417 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
11418 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
11419 h (floor (/ s 3600))
11420 s (- s (* 3600 h))
11421 m (floor (/ s 60))
11422 s (- s (* 60 s)))
11423 (insert " => " (format "%2d:%02d" h m))
11424 (move-marker org-clock-marker nil)
11425 (org-add-log-maybe 'clock-out)
11426 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
11428 (defun org-clock-cancel ()
11429 "Cancel the running clock be removing the start timestamp."
11430 (interactive)
11431 (if (not (marker-buffer org-clock-marker))
11432 (error "No active clock"))
11433 (save-excursion
11434 (set-buffer (marker-buffer org-clock-marker))
11435 (goto-char org-clock-marker)
11436 (delete-region (1- (point-at-bol)) (point-at-eol)))
11437 (message "Clock canceled"))
11439 (defvar org-clock-file-total-minutes nil
11440 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
11441 (make-variable-buffer-local 'org-clock-file-total-minutes)
11443 (defun org-clock-sum (&optional tstart tend)
11444 "Sum the times for each subtree.
11445 Puts the resulting times in minutes as a text property on each headline."
11446 (interactive)
11447 (let* ((bmp (buffer-modified-p))
11448 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
11449 org-clock-string
11450 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
11451 (lmax 30)
11452 (ltimes (make-vector lmax 0))
11453 (t1 0)
11454 (level 0)
11455 ts te dt
11456 time)
11457 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
11458 (save-excursion
11459 (goto-char (point-max))
11460 (while (re-search-backward re nil t)
11461 (if (match-end 2)
11462 ;; A time
11463 (setq ts (match-string 2)
11464 te (match-string 3)
11465 ts (time-to-seconds
11466 (apply 'encode-time (org-parse-time-string ts)))
11467 te (time-to-seconds
11468 (apply 'encode-time (org-parse-time-string te)))
11469 ts (if tstart (max ts tstart) ts)
11470 te (if tend (min te tend) te)
11471 dt (- te ts)
11472 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
11473 ;; A headline
11474 (setq level (- (match-end 1) (match-beginning 1)))
11475 (when (or (> t1 0) (> (aref ltimes level) 0))
11476 (loop for l from 0 to level do
11477 (aset ltimes l (+ (aref ltimes l) t1)))
11478 (setq t1 0 time (aref ltimes level))
11479 (loop for l from level to (1- lmax) do
11480 (aset ltimes l 0))
11481 (goto-char (match-beginning 0))
11482 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
11483 (setq org-clock-file-total-minutes (aref ltimes 0)))
11484 (set-buffer-modified-p bmp)))
11486 (defun org-clock-display (&optional total-only)
11487 "Show subtree times in the entire buffer.
11488 If TOTAL-ONLY is non-nil, only show the total time for the entire file
11489 in the echo area."
11490 (interactive)
11491 (org-remove-clock-overlays)
11492 (let (time h m p)
11493 (org-clock-sum)
11494 (unless total-only
11495 (save-excursion
11496 (goto-char (point-min))
11497 (while (setq p (next-single-property-change (point) :org-clock-minutes))
11498 (goto-char p)
11499 (when (setq time (get-text-property p :org-clock-minutes))
11500 (org-put-clock-overlay time (funcall outline-level))))
11501 (setq h (/ org-clock-file-total-minutes 60)
11502 m (- org-clock-file-total-minutes (* 60 h)))
11503 ;; Arrange to remove the overlays upon next change.
11504 (when org-remove-highlights-with-change
11505 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
11506 nil 'local))))
11507 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
11509 (defvar org-clock-overlays nil)
11510 (make-variable-buffer-local 'org-clock-overlays)
11512 (defun org-put-clock-overlay (time &optional level)
11513 "Put an overlays on the current line, displaying TIME.
11514 If LEVEL is given, prefix time with a corresponding number of stars.
11515 This creates a new overlay and stores it in `org-clock-overlays', so that it
11516 will be easy to remove."
11517 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
11518 (l (if level (org-get-legal-level level 0) 0))
11519 (off 0)
11520 ov tx)
11521 (move-to-column c)
11522 (unless (eolp) (skip-chars-backward "^ \t"))
11523 (skip-chars-backward " \t")
11524 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
11525 tx (concat (buffer-substring (1- (point)) (point))
11526 (make-string (+ off (max 0 (- c (current-column)))) ?.)
11527 (org-add-props (format "%s %2d:%02d%s"
11528 (make-string l ?*) h m
11529 (make-string (- 10 l) ?\ ))
11530 '(face secondary-selection))
11531 ""))
11532 (if (not (featurep 'xemacs))
11533 (org-overlay-put ov 'display tx)
11534 (org-overlay-put ov 'invisible t)
11535 (org-overlay-put ov 'end-glyph (make-glyph tx)))
11536 (push ov org-clock-overlays)))
11538 (defun org-remove-clock-overlays (&optional beg end noremove)
11539 "Remove the occur highlights from the buffer.
11540 BEG and END are ignored. If NOREMOVE is nil, remove this function
11541 from the `before-change-functions' in the current buffer."
11542 (interactive)
11543 (unless org-inhibit-highlight-removal
11544 (mapc 'org-delete-overlay org-clock-overlays)
11545 (setq org-clock-overlays nil)
11546 (unless noremove
11547 (remove-hook 'before-change-functions
11548 'org-remove-clock-overlays 'local))))
11550 (defun org-clock-out-if-current ()
11551 "Clock out if the current entry contains the running clock.
11552 This is used to stop the clock after a TODO entry is marked DONE."
11553 (when (and (equal state org-done-string)
11554 (equal (marker-buffer org-clock-marker) (current-buffer))
11555 (< (point) org-clock-marker)
11556 (> (save-excursion (outline-next-heading) (point))
11557 org-clock-marker))
11558 ;; Clock out, but don't accept a logging message for this.
11559 (let ((org-log-done (if (and (listp org-log-done)
11560 (member 'clock-out org-log-done))
11561 '(done)
11562 org-log-done)))
11563 (org-clock-out))))
11565 (add-hook 'org-after-todo-state-change-hook
11566 'org-clock-out-if-current)
11568 (defun org-check-running-clock ()
11569 "Check if the current buffer contains the running clock.
11570 If yes, offer to stop it and to save the buffer with the changes."
11571 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
11572 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
11573 (buffer-name))))
11574 (org-clock-out)
11575 (when (y-or-n-p "Save changed buffer?")
11576 (save-buffer))))
11578 (defun org-clock-report ()
11579 "Create a table containing a report about clocked time.
11580 If the buffer contains lines
11581 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
11583 #+END: clocktable
11584 then the table will be inserted between these lines, replacing whatever
11585 is was there before. If these lines are not in the buffer, the table
11586 is inserted at point, surrounded by the special lines.
11587 The BEGIN line can contain parameters. Allowed are:
11588 :maxlevel The maximum level to be included in the table. Default is 3.
11589 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
11590 (interactive)
11591 (org-remove-clock-overlays)
11592 (unless (org-find-dblock "clocktable")
11593 (org-create-dblock (list :name "clocktable"
11594 :maxlevel 2 :emphasize nil)))
11595 (org-update-dblock))
11597 (defun org-clock-update-time-maybe ()
11598 "If this is a CLOCK line, update it and return t.
11599 Otherwise, return nil."
11600 (interactive)
11601 (save-excursion
11602 (beginning-of-line 1)
11603 (skip-chars-forward " \t")
11604 (when (looking-at org-clock-string)
11605 (let ((re (concat "[ \t]*" org-clock-string
11606 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
11607 "\\([ \t]*=>.*\\)?"))
11608 ts te h m s)
11609 (if (not (looking-at re))
11611 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
11612 (end-of-line 1)
11613 (setq ts (match-string 1)
11614 te (match-string 2))
11615 (setq s (- (time-to-seconds
11616 (apply 'encode-time (org-parse-time-string te)))
11617 (time-to-seconds
11618 (apply 'encode-time (org-parse-time-string ts))))
11619 h (floor (/ s 3600))
11620 s (- s (* 3600 h))
11621 m (floor (/ s 60))
11622 s (- s (* 60 s)))
11623 (insert " => " (format "%2d:%02d" h m))
11624 t)))))
11626 (defun org-clock-special-range (key &optional time as-strings)
11627 "Return two times bordering a special time range.
11628 Key is a symbol specifying the range and can be one of `today', `yesterday',
11629 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
11630 A week starts Monday 0:00 and ends Sunday 24:00.
11631 The range is determined relative to TIME. TIME defaults to the current time.
11632 The return value is a cons cell with two internal times like the ones
11633 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
11634 the returned times will be formatted strings."
11635 (let* ((tm (decode-time (or time (current-time))))
11636 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
11637 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
11638 (dow (nth 6 tm))
11639 s1 m1 h1 d1 month1 y1 diff ts te fm)
11640 (cond
11641 ((eq key 'today)
11642 (setq h 0 m 0 h1 24 m1 0))
11643 ((eq key 'yesterday)
11644 (setq d (1- d) h 0 m 0 h1 24 m1 0))
11645 ((eq key 'thisweek)
11646 (setq diff (if (= dow 0) 6 (1- dow))
11647 m 0 h 0 d (- d diff) d1 (+ 7 d)))
11648 ((eq key 'lastweek)
11649 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
11650 m 0 h 0 d (- d diff) d1 (+ 7 d)))
11651 ((eq key 'thismonth)
11652 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
11653 ((eq key 'lastmonth)
11654 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
11655 ((eq key 'thisyear)
11656 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
11657 ((eq key 'lastyear)
11658 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
11659 (t (error "No such time block %s" key)))
11660 (setq ts (encode-time s m h d month y)
11661 te (encode-time (or s1 s) (or m1 m) (or h1 h)
11662 (or d1 d) (or month1 month) (or y1 y)))
11663 (setq fm (cdr org-time-stamp-formats))
11664 (if as-strings
11665 (cons (format-time-string fm ts) (format-time-string fm te))
11666 (cons ts te))))
11668 (defun org-dblock-write:clocktable (params)
11669 "Write the standard clocktable."
11670 (let ((hlchars '((1 . "*") (2 . ?/)))
11671 (emph nil)
11672 (ins (make-marker))
11673 ipos time h m p level hlc hdl maxlevel
11674 ts te cc block)
11675 (setq maxlevel (or (plist-get params :maxlevel) 3)
11676 emph (plist-get params :emphasize)
11677 ts (plist-get params :tstart)
11678 te (plist-get params :tend)
11679 block (plist-get params :block))
11680 (when block
11681 (setq cc (org-clock-special-range block nil t)
11682 ts (car cc) te (cdr cc)))
11683 (if ts (setq ts (time-to-seconds
11684 (apply 'encode-time (org-parse-time-string ts)))))
11685 (if te (setq te (time-to-seconds
11686 (apply 'encode-time (org-parse-time-string te)))))
11687 (move-marker ins (point))
11688 (setq ipos (point))
11689 ;; FIXME: does not yet use org-insert-time-stamp
11690 (insert-before-markers "Clock summary at ["
11691 (substring
11692 (format-time-string (cdr org-time-stamp-formats))
11693 1 -1)
11694 "]."
11695 (if block
11696 (format " Considered range is /%s/." block)
11698 "\n\n|L|Headline|Time|\n")
11699 (org-clock-sum ts te)
11700 (setq h (/ org-clock-file-total-minutes 60)
11701 m (- org-clock-file-total-minutes (* 60 h)))
11702 (insert-before-markers "|-\n|0|" "*Total file time*| "
11703 (format "*%d:%02d*" h m)
11704 "|\n")
11705 (goto-char (point-min))
11706 (while (setq p (next-single-property-change (point) :org-clock-minutes))
11707 (goto-char p)
11708 (when (setq time (get-text-property p :org-clock-minutes))
11709 (save-excursion
11710 (beginning-of-line 1)
11711 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
11712 (setq level (- (match-end 1) (match-beginning 1)))
11713 (<= level maxlevel))
11714 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
11715 hdl (match-string 2)
11716 h (/ time 60)
11717 m (- time (* 60 h)))
11718 (goto-char ins)
11719 (if (= level 1) (insert-before-markers "|-\n"))
11720 (insert-before-markers
11721 "| " (int-to-string level) "|" hlc hdl hlc " |"
11722 (make-string (1- level) ?|)
11724 (format "%d:%02d" h m)
11726 " |\n")))))
11727 (goto-char ins)
11728 (backward-delete-char 1)
11729 (goto-char ipos)
11730 (skip-chars-forward "^|")
11731 (org-table-align)))
11733 (defun org-collect-clock-time-entries ()
11734 "Return an internal list with clocking information.
11735 This list has one entry for each CLOCK interval.
11736 FIXME: describe the elements."
11737 (interactive)
11738 (let ((re (concat "^[ \t]*" org-clock-string
11739 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
11740 rtn beg end next cont level title total closedp leafp
11741 clockpos titlepos h m donep)
11742 (save-excursion
11743 (org-clock-sum)
11744 (goto-char (point-min))
11745 (while (re-search-forward re nil t)
11746 (setq clockpos (match-beginning 0)
11747 beg (match-string 1) end (match-string 2)
11748 cont (match-end 0))
11749 (setq beg (apply 'encode-time (org-parse-time-string beg))
11750 end (apply 'encode-time (org-parse-time-string end)))
11751 (org-back-to-heading t)
11752 (setq donep (org-entry-is-done-p))
11753 (setq titlepos (point)
11754 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
11755 h (/ total 60) m (- total (* 60 h))
11756 total (cons h m))
11757 (looking-at "\\(\\*+\\) +\\(.*\\)")
11758 (setq level (- (match-end 1) (match-beginning 1))
11759 title (org-match-string-no-properties 2))
11760 (save-excursion (outline-next-heading) (setq next (point)))
11761 (setq closedp (re-search-forward org-closed-time-regexp next t))
11762 (goto-char next)
11763 (setq leafp (and (looking-at "^\\*+ ")
11764 (<= (- (match-end 0) (point)) level)))
11765 (push (list beg end clockpos closedp donep
11766 total title titlepos level leafp)
11767 rtn)
11768 (goto-char cont)))
11769 (nreverse rtn)))
11771 ;;;; Agenda, and Diary Integration
11773 ;;; Define the Org-agenda-mode
11775 (defvar org-agenda-mode-map (make-sparse-keymap)
11776 "Keymap for `org-agenda-mode'.")
11778 (defvar org-agenda-menu) ; defined later in this file.
11779 (defvar org-agenda-follow-mode nil)
11780 (defvar org-agenda-show-log nil)
11781 (defvar org-agenda-redo-command nil)
11782 (defvar org-agenda-mode-hook nil)
11783 (defvar org-agenda-type nil)
11784 (defvar org-agenda-force-single-file nil)
11786 (defun org-agenda-mode ()
11787 "Mode for time-sorted view on action items in Org-mode files.
11789 The following commands are available:
11791 \\{org-agenda-mode-map}"
11792 (interactive)
11793 (kill-all-local-variables)
11794 (setq org-agenda-undo-list nil
11795 org-agenda-pending-undo-list nil)
11796 (setq major-mode 'org-agenda-mode)
11797 (setq mode-name "Org-Agenda")
11798 (use-local-map org-agenda-mode-map)
11799 (easy-menu-add org-agenda-menu)
11800 (if org-startup-truncated (setq truncate-lines t))
11801 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
11802 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
11803 (unless org-agenda-keep-modes
11804 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
11805 org-agenda-show-log nil))
11806 (easy-menu-change
11807 '("Agenda") "Agenda Files"
11808 (append
11809 (list
11810 (vector
11811 (if (get 'org-agenda-files 'org-restrict)
11812 "Restricted to single file"
11813 "Edit File List")
11814 '(org-edit-agenda-file-list)
11815 (not (get 'org-agenda-files 'org-restrict)))
11816 "--")
11817 (mapcar 'org-file-menu-entry (org-agenda-files))))
11818 (org-agenda-set-mode-name)
11819 (apply
11820 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
11821 (list 'org-agenda-mode-hook)))
11823 (substitute-key-definition 'undo 'org-agenda-undo
11824 org-agenda-mode-map global-map)
11825 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
11826 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
11827 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
11828 (define-key org-agenda-mode-map "\C-k" 'org-agenda-kill)
11829 (define-key org-agenda-mode-map "\C-c$" 'org-agenda-archive)
11830 (define-key org-agenda-mode-map "$" 'org-agenda-archive)
11831 (define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
11832 (define-key org-agenda-mode-map " " 'org-agenda-show)
11833 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
11834 (define-key org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
11835 (define-key org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
11836 (define-key org-agenda-mode-map "o" 'delete-other-windows)
11837 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
11838 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
11839 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
11840 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
11841 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
11842 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
11843 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
11844 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
11845 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
11846 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
11847 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
11849 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
11850 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
11851 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
11852 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
11853 (while l (define-key org-agenda-mode-map
11854 (int-to-string (pop l)) 'digit-argument)))
11856 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
11857 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
11858 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
11859 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
11860 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
11861 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
11862 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
11863 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
11864 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
11865 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
11866 (define-key org-agenda-mode-map "n" 'next-line)
11867 (define-key org-agenda-mode-map "p" 'previous-line)
11868 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
11869 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
11870 (define-key org-agenda-mode-map "," 'org-agenda-priority)
11871 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
11872 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
11873 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
11874 (eval-after-load "calendar"
11875 '(define-key calendar-mode-map org-calendar-to-agenda-key
11876 'org-calendar-goto-agenda))
11877 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
11878 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
11879 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
11880 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
11881 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
11882 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
11883 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
11884 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
11885 (define-key org-agenda-mode-map "O" 'org-agenda-clock-out)
11886 (define-key org-agenda-mode-map "X" 'org-agenda-clock-cancel)
11887 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
11888 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
11889 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
11890 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
11891 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
11892 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
11893 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
11894 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11895 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
11896 "Local keymap for agenda entries from Org-mode.")
11898 (define-key org-agenda-keymap
11899 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
11900 (define-key org-agenda-keymap
11901 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
11902 (when org-agenda-mouse-1-follows-link
11903 (define-key org-agenda-keymap [follow-link] 'mouse-face))
11904 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
11905 '("Agenda"
11906 ("Agenda Files")
11907 "--"
11908 ["Show" org-agenda-show t]
11909 ["Go To (other window)" org-agenda-goto t]
11910 ["Go To (this window)" org-agenda-switch-to t]
11911 ["Follow Mode" org-agenda-follow-mode
11912 :style toggle :selected org-agenda-follow-mode :active t]
11913 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
11914 "--"
11915 ["Cycle TODO" org-agenda-todo t]
11916 ["Archive subtree" org-agenda-archive t]
11917 ["Delete subtree" org-agenda-kill t]
11918 "--"
11919 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
11920 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
11921 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
11922 "--"
11923 ("Tags"
11924 ["Show all Tags" org-agenda-show-tags t]
11925 ["Set Tags" org-agenda-set-tags t])
11926 ("Date/Schedule"
11927 ["Schedule" org-agenda-schedule t]
11928 ["Set Deadline" org-agenda-deadline t]
11929 "--"
11930 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
11931 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
11932 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
11933 ("Priority"
11934 ["Set Priority" org-agenda-priority t]
11935 ["Increase Priority" org-agenda-priority-up t]
11936 ["Decrease Priority" org-agenda-priority-down t]
11937 ["Show Priority" org-agenda-show-priority t])
11938 ("Calendar/Diary"
11939 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
11940 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
11941 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
11942 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
11943 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
11944 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
11945 "--"
11946 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
11947 "--"
11948 ("View"
11949 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
11950 :style radio :selected (equal org-agenda-ndays 1)]
11951 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
11952 :style radio :selected (equal org-agenda-ndays 7)]
11953 "--"
11954 ["Show Logbook entries" org-agenda-log-mode
11955 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
11956 ["Include Diary" org-agenda-toggle-diary
11957 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
11958 ["Use Time Grid" org-agenda-toggle-time-grid
11959 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
11960 ["Rebuild buffer" org-agenda-redo t]
11961 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
11962 "--"
11963 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
11964 "--"
11965 ["Quit" org-agenda-quit t]
11966 ["Exit and Release Buffers" org-agenda-exit t]
11969 ;;; Agenda undo
11971 (defvar org-agenda-allow-remote-undo t
11972 "Non-nil means, allow remote undo from the agenda buffer.")
11973 (defvar org-agenda-undo-list nil
11974 "List of undoable operations in the agenda since last refresh.")
11975 (defvar org-agenda-undo-has-started-in nil
11976 "Buffers that have already seen `undo-start' in the current undo sequence.")
11977 (defvar org-agenda-pending-undo-list nil
11978 "In a series of undo commands, this is the list of remaning undo items.")
11980 (defmacro org-with-remote-undo (_buffer &rest _body)
11981 "Execute BODY while recording undo information in two buffers."
11982 (declare (indent 1) (debug t))
11983 `(let ((_cline (org-current-line))
11984 (_cmd this-command)
11985 (_buf1 (current-buffer))
11986 (_buf2 ,_buffer)
11987 (_undo1 buffer-undo-list)
11988 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
11989 _c1 _c2)
11990 ,@_body
11991 (when org-agenda-allow-remote-undo
11992 (setq _c1 (org-verify-change-for-undo
11993 _undo1 (with-current-buffer _buf1 buffer-undo-list))
11994 _c2 (org-verify-change-for-undo
11995 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
11996 (when (or _c1 _c2)
11997 ;; make sure there are undo boundaries
11998 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
11999 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
12000 ;; remember which buffer to undo
12001 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
12002 org-agenda-undo-list)))))
12004 (defun org-agenda-undo ()
12005 "Undo a remote editing step in the agenda.
12006 This undoes changes both in the agenda buffer and in the remote buffer
12007 that have been changed along."
12008 (interactive)
12009 (or org-agenda-allow-remote-undo
12010 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
12011 (if (not (eq this-command last-command))
12012 (setq org-agenda-undo-has-started-in nil
12013 org-agenda-pending-undo-list org-agenda-undo-list))
12014 (if (not org-agenda-pending-undo-list)
12015 (error "No further undo information"))
12016 (let* ((entry (pop org-agenda-pending-undo-list))
12017 buf line cmd rembuf)
12018 (setq cmd (pop entry) line (pop entry))
12019 (setq rembuf (nth 2 entry))
12020 (org-with-remote-undo rembuf
12021 (while (bufferp (setq buf (pop entry)))
12022 (if (pop entry)
12023 (with-current-buffer buf
12024 (let ((last-undo-buffer buf)
12025 buffer-read-only)
12026 (unless (memq buf org-agenda-undo-has-started-in)
12027 (push buf org-agenda-undo-has-started-in)
12028 (make-local-variable 'pending-undo-list)
12029 (undo-start))
12030 (while (and pending-undo-list
12031 (listp pending-undo-list)
12032 (not (car pending-undo-list)))
12033 (pop pending-undo-list))
12034 (undo-more 1))))))
12035 (goto-line line)
12036 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
12038 (defun org-verify-change-for-undo (l1 l2)
12039 "Verify that a real change occurred between the undo lists L1 and L2."
12040 (while (and l1 (listp l1) (null (car l1))) (pop l1))
12041 (while (and l2 (listp l2) (null (car l2))) (pop l2))
12042 (not (eq l1 l2)))
12044 ;;; Agenda dispatch
12046 (defvar org-agenda-restrict nil)
12047 (defvar org-agenda-restrict-begin (make-marker))
12048 (defvar org-agenda-restrict-end (make-marker))
12049 (defvar org-agenda-last-dispatch-buffer nil)
12051 ;;;###autoload
12052 (defun org-agenda (arg)
12053 "Dispatch agenda commands to collect entries to the agenda buffer.
12054 Prompts for a character to select a command. Any prefix arg will be passed
12055 on to the selected command. The default selections are:
12057 a Call `org-agenda-list' to display the agenda for current day or week.
12058 t Call `org-todo-list' to display the global todo list.
12059 T Call `org-todo-list' to display the global todo list, select only
12060 entries with a specific TODO keyword (the user gets a prompt).
12061 m Call `org-tags-view' to display headlines with tags matching
12062 a condition (the user is prompted for the condition).
12063 M Like `m', but select only TODO entries, no ordinary headlines.
12064 l Create a timeeline for the current buffer.
12066 More commands can be added by configuring the variable
12067 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
12068 searches can be pre-defined in this way.
12070 If the current buffer is in Org-mode and visiting a file, you can also
12071 first press `1' to indicate that the agenda should be temporarily (until the
12072 next use of \\[org-agenda]) restricted to the current file."
12073 (interactive "P")
12074 (catch 'exit
12075 (let* ((buf (current-buffer))
12076 (bfn (buffer-file-name (buffer-base-buffer)))
12077 (restrict-ok (and bfn (org-mode-p)))
12078 (custom org-agenda-custom-commands)
12079 c entry key type match lprops header)
12080 ;; Turn off restriction
12081 (put 'org-agenda-files 'org-restrict nil)
12082 (setq org-agenda-restrict nil)
12083 (move-marker org-agenda-restrict-begin nil)
12084 (move-marker org-agenda-restrict-end nil)
12085 ;; Remember where this call originated
12086 (setq org-agenda-last-dispatch-buffer (current-buffer))
12087 (save-window-excursion
12088 (delete-other-windows)
12089 (switch-to-buffer-other-window " *Agenda Commands*")
12090 (erase-buffer)
12091 (insert (eval-when-compile
12092 (let ((header
12093 "Press key for an agenda command:
12094 -------------------------------- C Configure custom agenda commands
12095 a Agenda for current week or day
12096 t List of all TODO entries T Entries with special TODO kwd
12097 m Match a TAGS query M Like m, but only TODO entries
12098 L Timeline for current buffer # List stuck projects (!=configure)
12100 (start 0))
12101 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
12102 (setq start (match-end 0))
12103 (add-text-properties (match-beginning 2) (match-end 2)
12104 '(face bold) header))
12105 header)))
12106 (while (setq entry (pop custom))
12107 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
12108 (insert (format "\n%-4s%-14s: %s"
12109 (org-add-props (copy-sequence key)
12110 '(face bold))
12111 (cond
12112 ((stringp type) type)
12113 ((eq type 'tags) "Tags query")
12114 ((eq type 'todo) "TODO keyword")
12115 ((eq type 'tags-tree) "Tags (TODO)")
12116 ((eq type 'tags-tree) "Tags tree")
12117 ((eq type 'todo-tree) "TODO kwd tree")
12118 ((eq type 'occur-tree) "Occur tree")
12119 ((functionp type) (symbol-name type))
12120 (t "???"))
12121 (if (stringp match)
12122 (org-add-props match nil 'face 'org-warning)
12123 (format "set of %d commands" (+ -2 (length entry)))))))
12124 (if restrict-ok
12125 (insert "\n"
12126 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
12128 (goto-char (point-min))
12129 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
12130 (message "Press key for agenda command%s"
12131 (if restrict-ok ", or [1] or [0] to restrict" ""))
12132 (setq c (read-char-exclusive))
12133 (message "")
12134 (when (memq c '(?L ?1 ?0))
12135 (if restrict-ok
12136 (put 'org-agenda-files 'org-restrict (list bfn))
12137 (error "Cannot restrict agenda to current buffer"))
12138 (with-current-buffer " *Agenda Commands*"
12139 (goto-char (point-max))
12140 (delete-region (point-at-bol) (point))
12141 (goto-char (point-min)))
12142 (when (eq c ?0)
12143 (setq org-agenda-restrict t)
12144 (with-current-buffer buf
12145 (if (org-region-active-p)
12146 (progn
12147 (move-marker org-agenda-restrict-begin (region-beginning))
12148 (move-marker org-agenda-restrict-end (region-end)))
12149 (save-excursion
12150 (org-back-to-heading t)
12151 (move-marker org-agenda-restrict-begin (point))
12152 (move-marker org-agenda-restrict-end
12153 (progn (org-end-of-subtree t)))))))
12154 (unless (eq c ?L)
12155 (message "Press key for agenda command%s"
12156 (if restrict-ok " (restricted to current file)" ""))
12157 (setq c (read-char-exclusive)))
12158 (message "")))
12159 (require 'calendar) ; FIXME: can we avoid this for some commands?
12160 ;; For example the todo list should not need it (but does...)
12161 (cond
12162 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
12163 (if (symbolp (nth 1 entry))
12164 (progn
12165 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
12166 lprops (nth 3 entry))
12167 (cond
12168 ((eq type 'tags)
12169 (org-let lprops '(org-tags-view current-prefix-arg match)))
12170 ((eq type 'tags-todo)
12171 (org-let lprops '(org-tags-view '(4) match)))
12172 ((eq type 'todo)
12173 (org-let lprops '(org-todo-list match)))
12174 ((eq type 'tags-tree)
12175 (org-check-for-org-mode)
12176 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
12177 ((eq type 'todo-tree)
12178 (org-check-for-org-mode)
12179 (org-let lprops
12180 '(org-occur (concat "^" outline-regexp "[ \t]*"
12181 (regexp-quote match) "\\>"))))
12182 ((eq type 'occur-tree)
12183 (org-check-for-org-mode)
12184 (org-let lprops '(org-occur match)))
12185 ((fboundp type)
12186 (org-let lprops '(funcall type match)))
12187 (t (error "Invalid custom agenda command type %s" type))))
12188 (org-run-agenda-series (cddr entry))))
12189 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
12190 ((equal c ?a) (call-interactively 'org-agenda-list))
12191 ((equal c ?t) (call-interactively 'org-todo-list))
12192 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
12193 ((equal c ?m) (call-interactively 'org-tags-view))
12194 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
12195 ((equal c ?L)
12196 (unless restrict-ok
12197 (error "This is not an Org-mode file"))
12198 (org-call-with-arg 'org-timeline arg))
12199 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
12200 ((equal c ?!) (customize-variable 'org-stuck-projects))
12201 (t (error "Invalid key"))))))
12203 ;; FIXME: what is the meaning of WINDOW?????
12204 (defun org-run-agenda-series (series &optional window)
12205 (org-prepare-agenda)
12206 (let* ((org-agenda-multi t)
12207 (redo (list 'org-run-agenda-series (list 'quote series)))
12208 (org-select-agenda-window t)
12209 (cmds (car series))
12210 (gprops (nth 1 series))
12211 match ;; The byte compiler incorrectly complains about this. Keep it!
12212 cmd type lprops)
12213 (while (setq cmd (pop cmds))
12214 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
12215 (cond
12216 ((eq type 'agenda)
12217 (call-interactively 'org-agenda-list))
12218 ((eq type 'alltodo)
12219 (call-interactively 'org-todo-list))
12220 ((eq type 'tags)
12221 (org-let2 gprops lprops
12222 '(org-tags-view current-prefix-arg match)))
12223 ((eq type 'tags-todo)
12224 (org-let2 gprops lprops
12225 '(org-tags-view '(4) match)))
12226 ((eq type 'todo)
12227 (org-let2 gprops lprops
12228 '(org-todo-list match)))
12229 ((fboundp type)
12230 (org-let2 gprops lprops
12231 '(funcall type match)))
12232 (t (error "Invalid type in command series"))))
12233 (widen)
12234 (setq org-agenda-redo-command redo)
12235 (goto-char (point-min)))
12236 (org-finalize-agenda))
12238 ;;;###autoload
12239 (defmacro org-batch-agenda (cmd-key &rest parameters)
12240 "Run an agenda command in batch mode, send result to STDOUT.
12241 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
12242 Paramters are alternating variable names and values that will be bound
12243 before running the agenda command."
12244 (let (pars)
12245 (while parameters
12246 (push (list (pop parameters) (if parameters (pop parameters))) pars))
12247 (flet ((read-char-exclusive () (string-to-char cmd-key)))
12248 (eval (list 'let (nreverse pars) '(org-agenda nil))))
12249 (set-buffer "*Org Agenda*")
12250 (princ (buffer-string))))
12252 (defmacro org-no-read-only (&rest body)
12253 "Inhibit read-only for BODY."
12254 `(let ((inhibit-read-only t)) ,@body))
12256 (defun org-check-for-org-mode ()
12257 "Make sure current buffer is in org-mode. Error if not."
12258 (or (org-mode-p)
12259 (error "Cannot execute org-mode agenda command on buffer in %s."
12260 major-mode)))
12262 (defun org-fit-agenda-window ()
12263 "Fit the window to the buffer size."
12264 (and org-fit-agenda-window
12265 (memq org-agenda-window-setup '(reorganize-frame))
12266 (fboundp 'fit-window-to-buffer)
12267 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
12268 (/ (frame-height) 2))))
12270 ;;; Agenda file list
12272 (defun org-agenda-files (&optional unrestricted)
12273 "Get the list of agenda files.
12274 Optional UNRESTRICTED means return the full list even if a restriction
12275 is currently in place."
12276 (cond
12277 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12278 ((stringp org-agenda-files) (org-read-agenda-file-list))
12279 ((listp org-agenda-files) org-agenda-files)
12280 (t (error "Invalid value of `org-agenda-files'"))))
12282 (defun org-edit-agenda-file-list ()
12283 "Edit the list of agenda files.
12284 Depending on setup, this either uses customize to edit the variable
12285 `org-agenda-files', or it visits the file that is holding the list. In the
12286 latter case, the buffer is set up in a way that saving it automatically kills
12287 the buffer and restores the previous window configuration."
12288 (interactive)
12289 (if (stringp org-agenda-files)
12290 (let ((cw (current-window-configuration)))
12291 (find-file org-agenda-files)
12292 (org-set-local 'org-window-configuration cw)
12293 (org-add-hook 'after-save-hook
12294 (lambda ()
12295 (set-window-configuration
12296 (prog1 org-window-configuration
12297 (kill-buffer (current-buffer))))
12298 (org-install-agenda-files-menu)
12299 (message "New agenda file list installed"))
12300 nil 'local)
12301 (message (substitute-command-keys
12302 "Edit list and finish with \\[save-buffer]")))
12303 (customize-variable 'org-agenda-files)))
12305 (defun org-store-new-agenda-file-list (list)
12306 "Set new value for the agenda file list and save it correcly."
12307 (if (stringp org-agenda-files)
12308 (let ((f org-agenda-files) b)
12309 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12310 (with-temp-file f
12311 (insert (mapconcat 'identity list "\n") "\n")))
12312 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12313 (setq org-agenda-files list)
12314 (customize-save-variable 'org-agenda-files org-agenda-files))))
12316 (defun org-read-agenda-file-list ()
12317 "Read the list of agenda files from a file."
12318 (when (stringp org-agenda-files)
12319 (with-temp-buffer
12320 (insert-file-contents org-agenda-files)
12321 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12324 ;;;###autoload
12325 (defun org-cycle-agenda-files ()
12326 "Cycle through the files in `org-agenda-files'.
12327 If the current buffer visits an agenda file, find the next one in the list.
12328 If the current buffer does not, find the first agenda file."
12329 (interactive)
12330 (let* ((fs (org-agenda-files t))
12331 (files (append fs (list (car fs))))
12332 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12333 file)
12334 (unless files (error "No agenda files"))
12335 (catch 'exit
12336 (while (setq file (pop files))
12337 (if (equal (file-truename file) tcf)
12338 (when (car files)
12339 (find-file (car files))
12340 (throw 'exit t))))
12341 (find-file (car fs)))))
12343 (defun org-agenda-file-to-end ()
12344 "Move/add the current file to the end of the agenda file list.
12345 If the file is not present in the list, it is appended to the list. If it is
12346 present, it is moved there."
12347 (interactive)
12348 (org-agenda-file-to-front 'to-end))
12350 (defun org-agenda-file-to-front (&optional to-end)
12351 "Move/add the current file to the top of the agenda file list.
12352 If the file is not present in the list, it is added to the front. If it is
12353 present, it is moved there. With optional argument TO-END, add/move to the
12354 end of the list."
12355 (interactive "P")
12356 (let ((file-alist (mapcar (lambda (x)
12357 (cons (file-truename x) x))
12358 (org-agenda-files t)))
12359 (ctf (file-truename buffer-file-name))
12360 x had)
12361 (setq x (assoc ctf file-alist) had x)
12363 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12364 (if to-end
12365 (setq file-alist (append (delq x file-alist) (list x)))
12366 (setq file-alist (cons x (delq x file-alist))))
12367 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12368 (org-install-agenda-files-menu)
12369 (message "File %s to %s of agenda file list"
12370 (if had "moved" "added") (if to-end "end" "front"))))
12372 (defun org-remove-file (&optional file)
12373 "Remove current file from the list of files in variable `org-agenda-files'.
12374 These are the files which are being checked for agenda entries.
12375 Optional argument FILE means, use this file instead of the current."
12376 (interactive)
12377 (let* ((file (or file buffer-file-name))
12378 (true-file (file-truename file))
12379 (afile (abbreviate-file-name file))
12380 (files (delq nil (mapcar
12381 (lambda (x)
12382 (if (equal true-file
12383 (file-truename x))
12384 nil x))
12385 (org-agenda-files t)))))
12386 (if (not (= (length files) (length (org-agenda-files t))))
12387 (progn
12388 (org-store-new-agenda-file-list files)
12389 (org-install-agenda-files-menu)
12390 (message "Removed file: %s" afile))
12391 (message "File was not in list: %s" afile))))
12393 (defun org-file-menu-entry (file)
12394 (vector file (list 'find-file file) t))
12396 (defun org-check-agenda-file (file)
12397 "Make sure FILE exists. If not, ask user what to do."
12398 (when (not (file-exists-p file))
12399 (message "non-existent file %s. [R]emove from list or [A]bort?"
12400 (abbreviate-file-name file))
12401 (let ((r (downcase (read-char-exclusive))))
12402 (cond
12403 ((equal r ?r)
12404 (org-remove-file file)
12405 (throw 'nextfile t))
12406 (t (error "Abort"))))))
12408 ;;; Agenda prepare and finalize
12410 (defvar org-agenda-multi nil) ; dynammically scoped
12411 (defvar org-agenda-buffer-name "*Org Agenda*")
12412 (defvar org-pre-agenda-window-conf nil)
12413 (defun org-prepare-agenda ()
12414 (if org-agenda-multi
12415 (progn
12416 (setq buffer-read-only nil)
12417 (goto-char (point-max))
12418 (unless (= (point) 1)
12419 (insert "\n" (make-string (window-width) ?=) "\n"))
12420 (narrow-to-region (point) (point-max)))
12421 (org-agenda-maybe-reset-markers 'force)
12422 (org-prepare-agenda-buffers (org-agenda-files))
12423 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
12424 (awin (get-buffer-window abuf)))
12425 (cond
12426 ((equal (current-buffer) abuf) nil)
12427 (awin (select-window awin))
12428 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
12429 ((equal org-agenda-window-setup 'current-window)
12430 (switch-to-buffer abuf))
12431 ((equal org-agenda-window-setup 'other-window)
12432 (switch-to-buffer-other-window abuf))
12433 ((equal org-agenda-window-setup 'other-frame)
12434 (switch-to-buffer-other-frame abuf))
12435 ((equal org-agenda-window-setup 'reorganize-frame)
12436 (delete-other-windows)
12437 (switch-to-buffer-other-window abuf))))
12438 (setq buffer-read-only nil)
12439 (erase-buffer)
12440 (org-agenda-mode))
12441 (setq buffer-read-only nil))
12443 (defun org-finalize-agenda ()
12444 "Finishing touch for the agenda buffer, called just before displaying it."
12445 (unless org-agenda-multi
12446 (org-agenda-align-tags)
12447 (save-excursion
12448 (let ((buffer-read-only))
12449 (goto-char (point-min))
12450 (while (org-activate-bracket-links (point-max))
12451 (add-text-properties (match-beginning 0) (match-end 0)
12452 '(face org-link))))
12453 (run-hooks 'org-finalize-agenda-hook))))
12455 (defun org-prepare-agenda-buffers (files)
12456 "Create buffers for all agenda files, protect archived trees and comments."
12457 (interactive)
12458 (let ((pa '(:org-archived t))
12459 (pc '(:org-comment t))
12460 (pall '(:org-archived t :org-comment t))
12461 (rea (concat ":" org-archive-tag ":"))
12462 bmp file re)
12463 (save-excursion
12464 (while (setq file (pop files))
12465 (org-check-agenda-file file)
12466 (set-buffer (org-get-agenda-file-buffer file))
12467 (widen)
12468 (setq bmp (buffer-modified-p))
12469 (save-excursion
12470 (remove-text-properties (point-min) (point-max) pall)
12471 (when org-agenda-skip-archived-trees
12472 (goto-char (point-min))
12473 (while (re-search-forward rea nil t)
12474 (if (org-on-heading-p)
12475 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12476 (goto-char (point-min))
12477 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12478 (while (re-search-forward re nil t)
12479 (add-text-properties
12480 (match-beginning 0) (org-end-of-subtree t) pc)))
12481 (set-buffer-modified-p bmp)))))
12483 (defvar org-agenda-skip-function nil
12484 "Function to be called at each match during agenda construction.
12485 If this function return nil, the current match should not be skipped.
12486 Otherwise, the function must return a position from where the search
12487 should be continued.
12488 Never set this variable using `setq' or so, because then it will apply
12489 to all future agenda commands. Instead, bind it with `let' to scope
12490 it dynamically into the agenda-constructing command.")
12492 (defun org-agenda-skip ()
12493 "Throw to `:skip' in places that should be skipped."
12494 (let ((p (point-at-bol)) to)
12495 (and org-agenda-skip-archived-trees
12496 (get-text-property p :org-archived)
12497 (org-end-of-subtree t)
12498 (throw :skip t))
12499 (and (get-text-property p :org-comment)
12500 (org-end-of-subtree t)
12501 (throw :skip t))
12502 (if (equal (char-after p) ?#) (throw :skip t))
12503 (when (and (functionp org-agenda-skip-function)
12504 (setq to (save-excursion
12505 (save-match-data
12506 (funcall org-agenda-skip-function)))))
12507 (goto-char to)
12508 (throw :skip t))))
12510 (defvar org-agenda-markers nil
12511 "List of all currently active markers created by `org-agenda'.")
12512 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
12513 "Creation time of the last agenda marker.")
12515 (defun org-agenda-new-marker (&optional pos)
12516 "Return a new agenda marker.
12517 Org-mode keeps a list of these markers and resets them when they are
12518 no longer in use."
12519 (let ((m (copy-marker (or pos (point)))))
12520 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
12521 (push m org-agenda-markers)
12524 (defun org-agenda-maybe-reset-markers (&optional force)
12525 "Reset markers created by `org-agenda'. But only if they are old enough."
12526 (if (or (and force (not org-agenda-multi))
12527 (> (- (time-to-seconds (current-time))
12528 org-agenda-last-marker-time)
12530 (while org-agenda-markers
12531 (move-marker (pop org-agenda-markers) nil))))
12533 (defvar org-agenda-new-buffers nil
12534 "Buffers created to visit agenda files.")
12536 (defun org-get-agenda-file-buffer (file)
12537 "Get a buffer visiting FILE. If the buffer needs to be created, add
12538 it to the list of buffers which might be released later."
12539 (let ((buf (find-buffer-visiting file)))
12540 (if buf
12541 buf ; just return it
12542 ;; Make a new buffer and remember it
12543 (setq buf (find-file-noselect file))
12544 (if buf (push buf org-agenda-new-buffers))
12545 buf)))
12547 (defun org-release-buffers (blist)
12548 "Release all buffers in list, asking the user for confirmation when needed.
12549 When a buffer is unmodified, it is just killed. When modified, it is saved
12550 \(if the user agrees) and then killed."
12551 (let (buf file)
12552 (while (setq buf (pop blist))
12553 (setq file (buffer-file-name buf))
12554 (when (and (buffer-modified-p buf)
12555 file
12556 (y-or-n-p (format "Save file %s? " file)))
12557 (with-current-buffer buf (save-buffer)))
12558 (kill-buffer buf))))
12560 (defvar org-category-table nil)
12561 (defun org-get-category-table ()
12562 "Get the table of categories and positions in current buffer."
12563 (let (tbl)
12564 (save-excursion
12565 (goto-char (point-min))
12566 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
12567 (push (cons (point) (org-trim (match-string 2))) tbl)))
12568 tbl))
12570 (defun org-get-category (&optional pos)
12571 "Get the category applying to position POS."
12572 (if (not org-category-table)
12573 (cond
12574 ((null org-category)
12575 (setq org-category
12576 (if buffer-file-name
12577 (file-name-sans-extension
12578 (file-name-nondirectory buffer-file-name))
12579 "???")))
12580 ((symbolp org-category) (symbol-name org-category))
12581 (t org-category))
12582 (let ((tbl org-category-table)
12583 (pos (or pos (point))))
12584 (while (and tbl (> (caar tbl) pos))
12585 (pop tbl))
12586 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
12587 org-category-table))))))
12588 ;;; Agenda timeline
12590 (defun org-timeline (&optional include-all)
12591 "Show a time-sorted view of the entries in the current org file.
12592 Only entries with a time stamp of today or later will be listed. With
12593 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
12594 under the current date.
12595 If the buffer contains an active region, only check the region for
12596 dates."
12597 (interactive "P")
12598 (require 'calendar)
12599 (org-compile-prefix-format 'timeline)
12600 (org-set-sorting-strategy 'timeline)
12601 (let* ((dopast t)
12602 (dotodo include-all)
12603 (doclosed org-agenda-show-log)
12604 (entry buffer-file-name)
12605 (date (calendar-current-date))
12606 (win (selected-window))
12607 (pos1 (point))
12608 (beg (if (org-region-active-p) (region-beginning) (point-min)))
12609 (end (if (org-region-active-p) (region-end) (point-max)))
12610 (day-numbers (org-get-all-dates beg end 'no-ranges
12611 t doclosed ; always include today
12612 org-timeline-show-empty-dates))
12613 (today (time-to-days (current-time)))
12614 (past t)
12615 args
12616 s e rtn d emptyp)
12617 (setq org-agenda-redo-command
12618 (list 'progn
12619 (list 'switch-to-buffer-other-window (current-buffer))
12620 (list 'org-timeline (list 'quote include-all))))
12621 (if (not dopast)
12622 ;; Remove past dates from the list of dates.
12623 (setq day-numbers (delq nil (mapcar (lambda(x)
12624 (if (>= x today) x nil))
12625 day-numbers))))
12626 (org-prepare-agenda)
12627 (if doclosed (push :closed args))
12628 (push :timestamp args)
12629 (if dotodo (push :todo args))
12630 (while (setq d (pop day-numbers))
12631 (if (and (listp d) (eq (car d) :omitted))
12632 (progn
12633 (setq s (point))
12634 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
12635 (put-text-property s (1- (point)) 'face 'org-level-3))
12636 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
12637 (if (and (>= d today)
12638 dopast
12639 past)
12640 (progn
12641 (setq past nil)
12642 (insert (make-string 79 ?-) "\n")))
12643 (setq date (calendar-gregorian-from-absolute d))
12644 (setq s (point))
12645 (setq rtn (and (not emptyp)
12646 (apply 'org-agenda-get-day-entries
12647 entry date args)))
12648 (if (or rtn (equal d today) org-timeline-show-empty-dates)
12649 (progn
12650 (insert (calendar-day-name date) " "
12651 (number-to-string (extract-calendar-day date)) " "
12652 (calendar-month-name (extract-calendar-month date)) " "
12653 (number-to-string (extract-calendar-year date)) "\n")
12654 (put-text-property s (1- (point)) 'face
12655 'org-level-3)
12656 (if (equal d today)
12657 (put-text-property s (1- (point)) 'org-today t))
12658 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
12659 (put-text-property s (1- (point)) 'day d)))))
12660 (goto-char (point-min))
12661 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
12662 (point-min)))
12663 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
12664 (org-finalize-agenda)
12665 (setq buffer-read-only t)
12666 (when (not org-select-agenda-window)
12667 (select-window win)
12668 (goto-char pos1))))
12669 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
12670 "Return a list of all relevant day numbers from BEG to END buffer positions.
12671 If NO-RANGES is non-nil, include only the start and end dates of a range,
12672 not every single day in the range. If FORCE-TODAY is non-nil, make
12673 sure that TODAY is included in the list. If INACTIVE is non-nil, also
12674 inactive time stamps (those in square brackets) are included.
12675 When EMPTY is non-nil, also include days without any entries."
12676 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
12677 dates dates1 date day day1 day2 ts1 ts2)
12678 (if force-today
12679 (setq dates (list (time-to-days (current-time)))))
12680 (save-excursion
12681 (goto-char beg)
12682 (while (re-search-forward re end t)
12683 (setq day (time-to-days (org-time-string-to-time
12684 (substring (match-string 1) 0 10))))
12685 (or (memq day dates) (push day dates)))
12686 (unless no-ranges
12687 (goto-char beg)
12688 (while (re-search-forward org-tr-regexp end t)
12689 (setq ts1 (substring (match-string 1) 0 10)
12690 ts2 (substring (match-string 2) 0 10)
12691 day1 (time-to-days (org-time-string-to-time ts1))
12692 day2 (time-to-days (org-time-string-to-time ts2)))
12693 (while (< (setq day1 (1+ day1)) day2)
12694 (or (memq day1 dates) (push day1 dates)))))
12695 (setq dates (sort dates '<))
12696 (when empty
12697 (while (setq day (pop dates))
12698 (setq day2 (car dates))
12699 (push day dates1)
12700 (when (and day2 empty)
12701 (if (or (eq empty t)
12702 (and (numberp empty) (<= (- day2 day) empty)))
12703 (while (< (setq day (1+ day)) day2)
12704 (push (list day) dates1))
12705 (push (cons :omitted (- day2 day)) dates1))))
12706 (setq dates (nreverse dates1)))
12707 dates)))
12709 ;;; Agenda Daily/Weekly
12711 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
12712 (defvar org-agenda-last-arguments nil
12713 "The arguments of the previous call to org-agenda")
12714 (defvar org-starting-day nil) ; local variable in the agenda buffer
12715 (defvar org-include-all-loc nil) ; local variable
12718 ;;;###autoload
12719 (defun org-agenda-list (&optional include-all start-day ndays)
12720 "Produce a weekly view from all files in variable `org-agenda-files'.
12721 The view will be for the current week, but from the overview buffer you
12722 will be able to go to other weeks.
12723 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
12724 also be shown, under the current date.
12725 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
12726 on the days are also shown. See the variable `org-log-done' for how
12727 to turn on logging.
12728 START-DAY defaults to TODAY, or to the most recent match for the weekday
12729 given in `org-agenda-start-on-weekday'.
12730 NDAYS defaults to `org-agenda-ndays'."
12731 (interactive "P")
12732 (if org-agenda-overriding-arguments
12733 (setq include-all (car org-agenda-overriding-arguments)
12734 start-day (nth 1 org-agenda-overriding-arguments)
12735 ndays (nth 2 org-agenda-overriding-arguments)))
12736 (setq org-agenda-last-arguments (list include-all start-day ndays))
12737 (org-compile-prefix-format 'agenda)
12738 (org-set-sorting-strategy 'agenda)
12739 (require 'calendar)
12740 (let* ((org-agenda-start-on-weekday
12741 (if (or (equal ndays 1)
12742 (and (null ndays) (equal 1 org-agenda-ndays)))
12743 nil org-agenda-start-on-weekday))
12744 (thefiles (org-agenda-files))
12745 (files thefiles)
12746 (win (selected-window))
12747 (today (time-to-days (current-time)))
12748 (sd (or start-day today))
12749 (start (if (or (null org-agenda-start-on-weekday)
12750 (< org-agenda-ndays 7))
12752 (let* ((nt (calendar-day-of-week
12753 (calendar-gregorian-from-absolute sd)))
12754 (n1 org-agenda-start-on-weekday)
12755 (d (- nt n1)))
12756 (- sd (+ (if (< d 0) 7 0) d)))))
12757 (day-numbers (list start))
12758 (inhibit-redisplay t)
12759 s e rtn rtnall file date d start-pos end-pos todayp nd)
12760 (setq org-agenda-redo-command
12761 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
12762 ;; Make the list of days
12763 (setq ndays (or ndays org-agenda-ndays)
12764 nd ndays)
12765 (while (> ndays 1)
12766 (push (1+ (car day-numbers)) day-numbers)
12767 (setq ndays (1- ndays)))
12768 (setq day-numbers (nreverse day-numbers))
12769 (org-prepare-agenda)
12770 (org-set-local 'org-starting-day (car day-numbers))
12771 (org-set-local 'org-include-all-loc include-all)
12772 (when (and (or include-all org-agenda-include-all-todo)
12773 (member today day-numbers))
12774 (setq files thefiles
12775 rtnall nil)
12776 (while (setq file (pop files))
12777 (catch 'nextfile
12778 (org-check-agenda-file file)
12779 (setq date (calendar-gregorian-from-absolute today)
12780 rtn (org-agenda-get-day-entries
12781 file date :todo))
12782 (setq rtnall (append rtnall rtn))))
12783 (when rtnall
12784 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
12785 (add-text-properties (point-min) (1- (point))
12786 (list 'face 'org-level-3))
12787 (insert (org-finalize-agenda-entries rtnall) "\n")))
12788 (setq s (point))
12789 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
12790 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
12791 (while (setq d (pop day-numbers))
12792 (setq date (calendar-gregorian-from-absolute d)
12793 s (point))
12794 (if (or (setq todayp (= d today))
12795 (and (not start-pos) (= d sd)))
12796 (setq start-pos (point))
12797 (if (and start-pos (not end-pos))
12798 (setq end-pos (point))))
12799 (setq files thefiles
12800 rtnall nil)
12801 (while (setq file (pop files))
12802 (catch 'nextfile
12803 (org-check-agenda-file file)
12804 (if org-agenda-show-log
12805 (setq rtn (org-agenda-get-day-entries
12806 file date
12807 :deadline :scheduled :timestamp :closed))
12808 (setq rtn (org-agenda-get-day-entries
12809 file date
12810 :deadline :scheduled :timestamp)))
12811 (setq rtnall (append rtnall rtn))))
12812 (if org-agenda-include-diary
12813 (progn
12814 (require 'diary-lib)
12815 (setq rtn (org-get-entries-from-diary date))
12816 (setq rtnall (append rtnall rtn))))
12817 (if (or rtnall org-agenda-show-all-dates)
12818 (progn
12819 (insert (format "%-9s %2d %s %4d\n"
12820 (calendar-day-name date)
12821 (extract-calendar-day date)
12822 (calendar-month-name (extract-calendar-month date))
12823 (extract-calendar-year date)))
12824 (put-text-property s (1- (point)) 'face
12825 'org-level-3)
12826 (if todayp (put-text-property s (1- (point)) 'org-today t))
12828 (if rtnall (insert
12829 (org-finalize-agenda-entries
12830 (org-agenda-add-time-grid-maybe
12831 rtnall nd todayp))
12832 "\n"))
12833 (put-text-property s (1- (point)) 'day d))))
12834 (goto-char (point-min))
12835 (org-fit-agenda-window)
12836 (unless (and (pos-visible-in-window-p (point-min))
12837 (pos-visible-in-window-p (point-max)))
12838 (goto-char (1- (point-max)))
12839 (recenter -1)
12840 (if (not (pos-visible-in-window-p (or start-pos 1)))
12841 (progn
12842 (goto-char (or start-pos 1))
12843 (recenter 1))))
12844 (goto-char (or start-pos 1))
12845 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
12846 (org-finalize-agenda)
12847 (setq buffer-read-only t)
12848 (if (not org-select-agenda-window) (select-window win))
12849 (message "")))
12851 ;;; Agenda TODO list
12853 (defvar org-select-this-todo-keyword nil)
12854 (defvar org-last-arg nil)
12856 ;;;###autoload
12857 (defun org-todo-list (arg)
12858 "Show all TODO entries from all agenda file in a single list.
12859 The prefix arg can be used to select a specific TODO keyword and limit
12860 the list to these. When using \\[universal-argument], you will be prompted
12861 for a keyword. A numeric prefix directly selects the Nth keyword in
12862 `org-todo-keywords'."
12863 (interactive "P")
12864 (require 'calendar)
12865 (org-compile-prefix-format 'todo)
12866 (org-set-sorting-strategy 'todo)
12867 (let* ((today (time-to-days (current-time)))
12868 (date (calendar-gregorian-from-absolute today))
12869 (win (selected-window))
12870 (kwds org-todo-keywords)
12871 (completion-ignore-case t)
12872 (org-select-this-todo-keyword
12873 (if (stringp arg) arg
12874 (and arg (integerp arg) (> arg 0)
12875 (nth (1- arg) org-todo-keywords))))
12876 rtn rtnall files file pos)
12877 (when (equal arg '(4))
12878 (setq org-select-this-todo-keyword
12879 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
12880 nil t)))
12881 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
12882 (org-prepare-agenda)
12883 (org-set-local 'org-last-arg arg)
12884 (org-set-local 'org-todo-keywords kwds)
12885 (setq org-agenda-redo-command
12886 '(org-todo-list (or current-prefix-arg org-last-arg)))
12887 (setq files (org-agenda-files)
12888 rtnall nil)
12889 (while (setq file (pop files))
12890 (catch 'nextfile
12891 (org-check-agenda-file file)
12892 (setq rtn (org-agenda-get-day-entries file date :todo))
12893 (setq rtnall (append rtnall rtn))))
12894 (if org-agenda-overriding-header
12895 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
12896 nil 'face 'org-level-3) "\n")
12897 (insert "Global list of TODO items of type: ")
12898 (add-text-properties (point-min) (1- (point))
12899 (list 'face 'org-level-3))
12900 (setq pos (point))
12901 (insert (or org-select-this-todo-keyword "ALL") "\n")
12902 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
12903 (setq pos (point))
12904 (unless org-agenda-multi
12905 (insert
12906 "Available with `N r': (0)ALL "
12907 (let ((n 0))
12908 (mapconcat (lambda (x)
12909 (format "(%d)%s" (setq n (1+ n)) x))
12910 org-todo-keywords " "))
12911 "\n"))
12912 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
12913 (when rtnall
12914 (insert (org-finalize-agenda-entries rtnall) "\n"))
12915 (goto-char (point-min))
12916 (org-fit-agenda-window)
12917 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
12918 (org-finalize-agenda)
12919 (setq buffer-read-only t)
12920 (if (not org-select-agenda-window) (select-window win))))
12922 ;;; Agenda tags match
12924 ;;;###autoload
12925 (defun org-tags-view (&optional todo-only match)
12926 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
12927 The prefix arg TODO-ONLY limits the search to TODO entries."
12928 (interactive "P")
12929 (org-compile-prefix-format 'tags)
12930 (org-set-sorting-strategy 'tags)
12931 (let* ((org-tags-match-list-sublevels
12932 (if todo-only t org-tags-match-list-sublevels))
12933 (win (selected-window))
12934 (completion-ignore-case t)
12935 rtn rtnall files file pos matcher
12936 buffer)
12937 (setq matcher (org-make-tags-matcher match)
12938 match (car matcher) matcher (cdr matcher))
12939 (org-prepare-agenda)
12940 (setq org-agenda-redo-command
12941 (list 'org-tags-view (list 'quote todo-only)
12942 (list 'if 'current-prefix-arg nil match)))
12943 (setq files (org-agenda-files)
12944 rtnall nil)
12945 (while (setq file (pop files))
12946 (catch 'nextfile
12947 (org-check-agenda-file file)
12948 (setq buffer (if (file-exists-p file)
12949 (org-get-agenda-file-buffer file)
12950 (error "No such file %s" file)))
12951 (if (not buffer)
12952 ;; If file does not exist, merror message to agenda
12953 (setq rtn (list
12954 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
12955 rtnall (append rtnall rtn))
12956 (with-current-buffer buffer
12957 (unless (org-mode-p)
12958 (error "Agenda file %s is not in `org-mode'" file))
12959 (setq org-category-table (org-get-category-table))
12960 (save-excursion
12961 (save-restriction
12962 (if org-agenda-restrict
12963 (narrow-to-region org-agenda-restrict-begin
12964 org-agenda-restrict-end)
12965 (widen))
12966 (setq rtn (org-scan-tags 'agenda matcher todo-only))
12967 (setq rtnall (append rtnall rtn))))))))
12968 (if org-agenda-overriding-header
12969 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
12970 nil 'face 'org-level-3) "\n")
12971 (insert "Headlines with TAGS match: ")
12972 (add-text-properties (point-min) (1- (point))
12973 (list 'face 'org-level-3))
12974 (setq pos (point))
12975 (insert match "\n")
12976 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
12977 (setq pos (point))
12978 (unless org-agenda-multi
12979 (insert "Press `C-u r' to search again with new search string\n"))
12980 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
12981 (when rtnall
12982 (insert (org-finalize-agenda-entries rtnall) "\n"))
12983 (goto-char (point-min))
12984 (org-fit-agenda-window)
12985 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
12986 (org-finalize-agenda)
12987 (setq buffer-read-only t)
12988 (if (not org-select-agenda-window) (select-window win))))
12990 ;;; Agenda Finding stuck projects
12992 (defvar org-agenda-skip-regexp nil
12993 "Regular expression used in skipping subtrees for the agenda.
12994 This is basically a temporary global variable that can be set and then
12995 used by user-defined selections using `org-agenda-skip-function'.")
12997 (defvar org-agenda-overriding-header nil
12998 "When this is set during todo and tags searches, will replace header.")
13000 (defun org-agenda-skip-subtree-when-regexp-matches ()
13001 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
13002 If yes, it returns the end position of this tree, causing agenda commands
13003 to skip this subtree. This is a function that can be put into
13004 `org-agenda-skip-function' for the duration of a command."
13005 (save-match-data
13006 (let ((end (save-excursion (org-end-of-subtree t)))
13007 skip)
13008 (save-excursion
13009 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
13010 (and skip end))))
13012 (defun org-agenda-list-stuck-projects (&rest ignore)
13013 "Create agenda view for projects that are stuck.
13014 Stuck projects are project that have no next actions. For the definitions
13015 of what a project is and how to check if it stuck, customize the variable
13016 `org-stuck-projects'.
13017 MATCH is being ignored."
13018 (interactive)
13019 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
13020 (org-agenda-overriding-header "List of stuck projects: ")
13021 (matcher (nth 0 org-stuck-projects))
13022 (todo (nth 1 org-stuck-projects))
13023 (tags (nth 2 org-stuck-projects))
13024 (todo-re (concat "^\\*+[ \t]+\\("
13025 (mapconcat 'identity todo "\\|")
13026 "\\)\\>"))
13027 (tags-re (concat "^\\*+.*:\\("
13028 (mapconcat 'identity tags "\\|")
13029 "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
13031 (setq org-agenda-skip-regexp
13032 (cond
13033 ((and todo tags)
13034 (concat todo-re "\\|" tags-re))
13035 (todo todo-re)
13036 (tags tags-re)
13037 (t (error "No information how to identify unstuck projects"))))
13038 (org-tags-view nil matcher)))
13041 ;;; Diary integration
13043 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
13045 (defun org-get-entries-from-diary (date)
13046 "Get the (Emacs Calendar) diary entries for DATE."
13047 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
13048 (diary-display-hook '(fancy-diary-display))
13049 (list-diary-entries-hook
13050 (cons 'org-diary-default-entry list-diary-entries-hook))
13051 (diary-file-name-prefix-function nil) ; turn this feature off
13052 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
13053 entries
13054 (org-disable-agenda-to-diary t))
13055 (save-excursion
13056 (save-window-excursion
13057 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
13058 (if (not (get-buffer fancy-diary-buffer))
13059 (setq entries nil)
13060 (with-current-buffer fancy-diary-buffer
13061 (setq buffer-read-only nil)
13062 (if (= (point-max) 1)
13063 ;; No entries
13064 (setq entries nil)
13065 ;; Omit the date and other unnecessary stuff
13066 (org-agenda-cleanup-fancy-diary)
13067 ;; Add prefix to each line and extend the text properties
13068 (if (= (point-max) 1)
13069 (setq entries nil)
13070 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
13071 (set-buffer-modified-p nil)
13072 (kill-buffer fancy-diary-buffer)))
13073 (when entries
13074 (setq entries (org-split-string entries "\n"))
13075 (setq entries
13076 (mapcar
13077 (lambda (x)
13078 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
13079 ;; Extend the text properties to the beginning of the line
13080 (org-add-props x (text-properties-at (1- (length x)) x)))
13081 entries)))))
13083 (defun org-agenda-cleanup-fancy-diary ()
13084 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
13085 This gets rid of the date, the underline under the date, and
13086 the dummy entry installed by `org-mode' to ensure non-empty diary for each
13087 date. It also removes lines that contain only whitespace."
13088 (goto-char (point-min))
13089 (if (looking-at ".*?:[ \t]*")
13090 (progn
13091 (replace-match "")
13092 (re-search-forward "\n=+$" nil t)
13093 (replace-match "")
13094 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
13095 (re-search-forward "\n=+$" nil t)
13096 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
13097 (goto-char (point-min))
13098 (while (re-search-forward "^ +\n" nil t)
13099 (replace-match ""))
13100 (goto-char (point-min))
13101 (if (re-search-forward "^Org-mode dummy\n?" nil t)
13102 (replace-match "")))
13104 ;; Make sure entries from the diary have the right text properties.
13105 (eval-after-load "diary-lib"
13106 '(if (boundp 'diary-modify-entry-list-string-function)
13107 ;; We can rely on the hook, nothing to do
13109 ;; Hook not avaiable, must use advice to make this work
13110 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
13111 "Make the position visible."
13112 (if (and org-disable-agenda-to-diary ;; called from org-agenda
13113 (stringp string)
13114 buffer-file-name)
13115 (setq string (org-modify-diary-entry-string string))))))
13117 (defun org-modify-diary-entry-string (string)
13118 "Add text properties to string, allowing org-mode to act on it."
13119 (org-add-props string nil
13120 'mouse-face 'highlight
13121 'keymap org-agenda-keymap
13122 'help-echo (format "mouse-2 or RET jump to diary file %s"
13123 (abbreviate-file-name buffer-file-name))
13124 'org-agenda-diary-link t
13125 'org-marker (org-agenda-new-marker (point-at-bol))))
13127 (defun org-diary-default-entry ()
13128 "Add a dummy entry to the diary.
13129 Needed to avoid empty dates which mess up holiday display."
13130 ;; Catch the error if dealing with the new add-to-diary-alist
13131 (when org-disable-agenda-to-diary
13132 (condition-case nil
13133 (add-to-diary-list original-date "Org-mode dummy" "")
13134 (error
13135 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
13137 ;;;###autoload
13138 (defun org-diary (&rest args)
13139 "Return diary information from org-files.
13140 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
13141 It accesses org files and extracts information from those files to be
13142 listed in the diary. The function accepts arguments specifying what
13143 items should be listed. The following arguments are allowed:
13145 :timestamp List the headlines of items containing a date stamp or
13146 date range matching the selected date. Deadlines will
13147 also be listed, on the expiration day.
13149 :deadline List any deadlines past due, or due within
13150 `org-deadline-warning-days'. The listing occurs only
13151 in the diary for *today*, not at any other date. If
13152 an entry is marked DONE, it is no longer listed.
13154 :scheduled List all items which are scheduled for the given date.
13155 The diary for *today* also contains items which were
13156 scheduled earlier and are not yet marked DONE.
13158 :todo List all TODO items from the org-file. This may be a
13159 long list - so this is not turned on by default.
13160 Like deadlines, these entries only show up in the
13161 diary for *today*, not at any other date.
13163 The call in the diary file should look like this:
13165 &%%(org-diary) ~/path/to/some/orgfile.org
13167 Use a separate line for each org file to check. Or, if you omit the file name,
13168 all files listed in `org-agenda-files' will be checked automatically:
13170 &%%(org-diary)
13172 If you don't give any arguments (as in the example above), the default
13173 arguments (:deadline :scheduled :timestamp) are used. So the example above may
13174 also be written as
13176 &%%(org-diary :deadline :timestamp :scheduled)
13178 The function expects the lisp variables `entry' and `date' to be provided
13179 by the caller, because this is how the calendar works. Don't use this
13180 function from a program - use `org-agenda-get-day-entries' instead."
13181 (org-agenda-maybe-reset-markers)
13182 (org-compile-prefix-format 'agenda)
13183 (org-set-sorting-strategy 'agenda)
13184 (setq args (or args '(:deadline :scheduled :timestamp)))
13185 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
13186 (list entry)
13187 (org-agenda-files t)))
13188 file rtn results)
13189 ;; If this is called during org-agenda, don't return any entries to
13190 ;; the calendar. Org Agenda will list these entries itself.
13191 (if org-disable-agenda-to-diary (setq files nil))
13192 (while (setq file (pop files))
13193 (setq rtn (apply 'org-agenda-get-day-entries file date args))
13194 (setq results (append results rtn)))
13195 (if results
13196 (concat (org-finalize-agenda-entries results) "\n"))))
13198 ;;; Agenda entry finders
13200 (defun org-agenda-get-day-entries (file date &rest args)
13201 "Does the work for `org-diary' and `org-agenda'.
13202 FILE is the path to a file to be checked for entries. DATE is date like
13203 the one returned by `calendar-current-date'. ARGS are symbols indicating
13204 which kind of entries should be extracted. For details about these, see
13205 the documentation of `org-diary'."
13206 (setq args (or args '(:deadline :scheduled :timestamp)))
13207 (let* ((org-startup-with-deadline-check nil)
13208 (org-startup-folded nil)
13209 (org-startup-align-all-tables nil)
13210 (buffer (if (file-exists-p file)
13211 (org-get-agenda-file-buffer file)
13212 (error "No such file %s" file)))
13213 arg results rtn)
13214 (if (not buffer)
13215 ;; If file does not exist, make sure an error message ends up in diary
13216 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
13217 (with-current-buffer buffer
13218 (unless (org-mode-p)
13219 (error "Agenda file %s is not in `org-mode'" file))
13220 (setq org-category-table (org-get-category-table))
13221 (let ((case-fold-search nil))
13222 (save-excursion
13223 (save-restriction
13224 (if org-agenda-restrict
13225 (narrow-to-region org-agenda-restrict-begin
13226 org-agenda-restrict-end)
13227 (widen))
13228 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
13229 (while (setq arg (pop args))
13230 (cond
13231 ((and (eq arg :todo)
13232 (equal date (calendar-current-date)))
13233 (setq rtn (org-agenda-get-todos))
13234 (setq results (append results rtn)))
13235 ((eq arg :timestamp)
13236 (setq rtn (org-agenda-get-blocks))
13237 (setq results (append results rtn))
13238 (setq rtn (org-agenda-get-timestamps))
13239 (setq results (append results rtn)))
13240 ((eq arg :scheduled)
13241 (setq rtn (org-agenda-get-scheduled))
13242 (setq results (append results rtn)))
13243 ((eq arg :closed)
13244 (setq rtn (org-agenda-get-closed))
13245 (setq results (append results rtn)))
13246 ((and (eq arg :deadline)
13247 (equal date (calendar-current-date)))
13248 (setq rtn (org-agenda-get-deadlines))
13249 (setq results (append results rtn))))))))
13250 results))))
13252 (defun org-entry-is-done-p ()
13253 "Is the current entry marked DONE?"
13254 (save-excursion
13255 (and (re-search-backward "[\r\n]\\*" nil t)
13256 (looking-at org-nl-done-regexp))))
13258 (defun org-at-date-range-p (&optional inactive-ok)
13259 "Is the cursor inside a date range?"
13260 (interactive)
13261 (save-excursion
13262 (catch 'exit
13263 (let ((pos (point)))
13264 (skip-chars-backward "^[<\r\n")
13265 (skip-chars-backward "<[")
13266 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13267 (>= (match-end 0) pos)
13268 (throw 'exit t))
13269 (skip-chars-backward "^<[\r\n")
13270 (skip-chars-backward "<[")
13271 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13272 (>= (match-end 0) pos)
13273 (throw 'exit t)))
13274 nil)))
13276 (defun org-agenda-get-todos ()
13277 "Return the TODO information for agenda display."
13278 (let* ((props (list 'face nil
13279 'done-face 'org-done
13280 'org-not-done-regexp org-not-done-regexp
13281 'mouse-face 'highlight
13282 'keymap org-agenda-keymap
13283 'help-echo
13284 (format "mouse-2 or RET jump to org file %s"
13285 (abbreviate-file-name buffer-file-name))))
13286 (regexp (concat "[\n\r]\\*+ *\\("
13287 (if org-select-this-todo-keyword
13288 (concat "\\<\\(" org-select-this-todo-keyword
13289 "\\)\\>")
13290 org-not-done-regexp)
13291 "[^\n\r]*\\)"))
13292 (deadline-re (concat ".*\\(\n[^*].*\\)?" org-deadline-time-regexp))
13293 (sched-re (concat ".*\\(\n[^*].*\\)?" org-scheduled-time-regexp))
13294 marker priority category tags
13295 ee txt)
13296 (goto-char (point-min))
13297 (while (re-search-forward regexp nil t)
13298 (catch :skip
13299 (save-match-data
13300 (beginning-of-line)
13301 (when (or (and org-agenda-todo-ignore-scheduled
13302 (looking-at sched-re))
13303 (and org-agenda-todo-ignore-deadlines
13304 (looking-at deadline-re)
13305 (org-deadline-close (match-string 2))))
13307 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
13308 (throw :skip nil)))
13309 (org-agenda-skip)
13310 (goto-char (match-beginning 1))
13311 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
13312 category (org-get-category)
13313 tags (org-get-tags-at (point))
13314 txt (org-format-agenda-item "" (match-string 1) category tags)
13315 priority
13316 (+ (org-get-priority txt)
13317 (if org-todo-kwd-priority-p
13318 (- org-todo-kwd-max-priority -2
13319 (length
13320 (member (match-string 2) org-todo-keywords)))
13321 1)))
13322 (org-add-props txt props
13323 'org-marker marker 'org-hd-marker marker
13324 'priority priority 'category category)
13325 (push txt ee)
13326 (if org-agenda-todo-list-sublevels
13327 (goto-char (match-end 1))
13328 (org-end-of-subtree 'invisible))))
13329 (nreverse ee)))
13331 (defconst org-agenda-no-heading-message
13332 "No heading for this item in buffer or region.")
13334 (defun org-agenda-get-timestamps ()
13335 "Return the date stamp information for agenda display."
13336 (let* ((props (list 'face nil
13337 'org-not-done-regexp org-not-done-regexp
13338 'mouse-face 'highlight
13339 'keymap org-agenda-keymap
13340 'help-echo
13341 (format "mouse-2 or RET jump to org file %s"
13342 (abbreviate-file-name buffer-file-name))))
13343 (regexp (regexp-quote
13344 (substring
13345 (format-time-string
13346 (car org-time-stamp-formats)
13347 (apply 'encode-time ; DATE bound by calendar
13348 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
13349 0 11)))
13350 marker hdmarker deadlinep scheduledp donep tmp priority category
13351 ee txt timestr tags)
13352 (goto-char (point-min))
13353 (while (re-search-forward regexp nil t)
13354 (catch :skip
13355 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
13356 (org-agenda-skip)
13357 (setq marker (org-agenda-new-marker (match-beginning 0))
13358 category (org-get-category (match-beginning 0))
13359 tmp (buffer-substring (max (point-min)
13360 (- (match-beginning 0)
13361 org-ds-keyword-length))
13362 (match-beginning 0))
13363 timestr (buffer-substring (match-beginning 0) (point-at-eol))
13364 deadlinep (string-match org-deadline-regexp tmp)
13365 scheduledp (string-match org-scheduled-regexp tmp)
13366 donep (org-entry-is-done-p))
13367 (and org-agenda-skip-scheduled-if-done
13368 scheduledp donep
13369 (throw :skip t))
13370 (if (string-match ">" timestr)
13371 ;; substring should only run to end of time stamp
13372 (setq timestr (substring timestr 0 (match-end 0))))
13373 (save-excursion
13374 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
13375 (progn
13376 (goto-char (match-end 1))
13377 (setq hdmarker (org-agenda-new-marker)
13378 tags (org-get-tags-at))
13379 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
13380 (setq txt (org-format-agenda-item
13381 (format "%s%s"
13382 (if deadlinep "Deadline: " "")
13383 (if scheduledp "Scheduled: " ""))
13384 (match-string 1) category tags timestr)))
13385 (setq txt org-agenda-no-heading-message))
13386 (setq priority (org-get-priority txt))
13387 (org-add-props txt props
13388 'org-marker marker 'org-hd-marker hdmarker)
13389 (if deadlinep
13390 (org-add-props txt nil
13391 'face (if donep 'org-done 'org-warning)
13392 'undone-face 'org-warning 'done-face 'org-done
13393 'category category 'priority (+ 100 priority))
13394 (if scheduledp
13395 (org-add-props txt nil
13396 'face 'org-scheduled-today
13397 'undone-face 'org-scheduled-today 'done-face 'org-done
13398 'category category 'priority (+ 99 priority))
13399 (org-add-props txt nil 'priority priority 'category category)))
13400 (push txt ee))
13401 (outline-next-heading)))
13402 (nreverse ee)))
13404 (defun org-agenda-get-closed ()
13405 "Return the logged TODO entries for agenda display."
13406 (let* ((props (list 'mouse-face 'highlight
13407 'org-not-done-regexp org-not-done-regexp
13408 'keymap org-agenda-keymap
13409 'help-echo
13410 (format "mouse-2 or RET jump to org file %s"
13411 (abbreviate-file-name buffer-file-name))))
13412 (regexp (concat
13413 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
13414 (regexp-quote
13415 (substring
13416 (format-time-string
13417 (car org-time-stamp-formats)
13418 (apply 'encode-time ; DATE bound by calendar
13419 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
13420 1 11))))
13421 marker hdmarker priority category tags closedp
13422 ee txt timestr)
13423 (goto-char (point-min))
13424 (while (re-search-forward regexp nil t)
13425 (catch :skip
13426 (org-agenda-skip)
13427 (setq marker (org-agenda-new-marker (match-beginning 0))
13428 closedp (equal (match-string 1) org-closed-string)
13429 category (org-get-category (match-beginning 0))
13430 timestr (buffer-substring (match-beginning 0) (point-at-eol))
13431 ;; donep (org-entry-is-done-p)
13433 (if (string-match "\\]" timestr)
13434 ;; substring should only run to end of time stamp
13435 (setq timestr (substring timestr 0 (match-end 0))))
13436 (save-excursion
13437 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
13438 (progn
13439 (goto-char (match-end 1))
13440 (setq hdmarker (org-agenda-new-marker)
13441 tags (org-get-tags-at))
13442 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
13443 (setq txt (org-format-agenda-item
13444 (if closedp "Closed: " "Clocked: ")
13445 (match-string 1) category tags timestr)))
13446 (setq txt org-agenda-no-heading-message))
13447 (setq priority 100000)
13448 (org-add-props txt props
13449 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
13450 'priority priority 'category category
13451 'undone-face 'org-warning 'done-face 'org-done)
13452 (push txt ee))
13453 (outline-next-heading)))
13454 (nreverse ee)))
13456 (defun org-agenda-get-deadlines ()
13457 "Return the deadline information for agenda display."
13458 (let* ((wdays org-deadline-warning-days)
13459 (props (list 'mouse-face 'highlight
13460 'org-not-done-regexp org-not-done-regexp
13461 'keymap org-agenda-keymap
13462 'help-echo
13463 (format "mouse-2 or RET jump to org file %s"
13464 (abbreviate-file-name buffer-file-name))))
13465 (regexp org-deadline-time-regexp)
13466 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
13467 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
13468 d2 diff pos pos1 category tags
13469 ee txt head face)
13470 (goto-char (point-min))
13471 (while (re-search-forward regexp nil t)
13472 (catch :skip
13473 (org-agenda-skip)
13474 (setq pos (1- (match-beginning 1))
13475 d2 (time-to-days
13476 (org-time-string-to-time (match-string 1)))
13477 diff (- d2 d1))
13478 ;; When to show a deadline in the calendar:
13479 ;; If the expiration is within wdays warning time.
13480 ;; Past-due deadlines are only shown on the current date
13481 (if (and (< diff wdays) todayp (not (= diff 0)))
13482 (save-excursion
13483 (setq category (org-get-category))
13484 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
13485 (progn
13486 (goto-char (match-end 0))
13487 (setq pos1 (match-end 1))
13488 (setq tags (org-get-tags-at pos1))
13489 (setq head (buffer-substring-no-properties
13490 (point)
13491 (progn (skip-chars-forward "^\r\n")
13492 (point))))
13493 (if (string-match org-looking-at-done-regexp head)
13494 (setq txt nil)
13495 (setq txt (org-format-agenda-item
13496 (format "In %3d d.: " diff) head category tags))))
13497 (setq txt org-agenda-no-heading-message))
13498 (when txt
13499 (setq face (cond ((<= diff 0) 'org-warning)
13500 ((<= diff 5) 'org-upcoming-deadline)
13501 (t nil)))
13502 (org-add-props txt props
13503 'org-marker (org-agenda-new-marker pos)
13504 'org-hd-marker (org-agenda-new-marker pos1)
13505 'priority (+ (- 10 diff) (org-get-priority txt))
13506 'category category
13507 'face face 'undone-face face 'done-face 'org-done)
13508 (push txt ee))))))
13509 ee))
13511 (defun org-agenda-get-scheduled ()
13512 "Return the scheduled information for agenda display."
13513 (let* ((props (list 'face 'org-scheduled-previously
13514 'org-not-done-regexp org-not-done-regexp
13515 'undone-face 'org-scheduled-previously
13516 'done-face 'org-done
13517 'mouse-face 'highlight
13518 'keymap org-agenda-keymap
13519 'help-echo
13520 (format "mouse-2 or RET jump to org file %s"
13521 (abbreviate-file-name buffer-file-name))))
13522 (regexp org-scheduled-time-regexp)
13523 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
13524 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
13525 d2 diff pos pos1 category tags donep
13526 ee txt head)
13527 (goto-char (point-min))
13528 (while (re-search-forward regexp nil t)
13529 (catch :skip
13530 (org-agenda-skip)
13531 (setq pos (1- (match-beginning 1))
13532 d2 (time-to-days
13533 (org-time-string-to-time (match-string 1)))
13534 diff (- d2 d1))
13535 ;; When to show a scheduled item in the calendar:
13536 ;; If it is on or past the date.
13537 (if (and (< diff 0) todayp)
13538 (save-excursion
13539 (setq category (org-get-category))
13540 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
13541 (progn
13542 (goto-char (match-end 0))
13543 (setq pos1 (match-end 1))
13544 (setq tags (org-get-tags-at))
13545 (setq head (buffer-substring-no-properties
13546 (point)
13547 (progn (skip-chars-forward "^\r\n") (point))))
13548 (if (string-match org-looking-at-done-regexp head)
13549 (setq txt nil)
13550 (setq txt (org-format-agenda-item
13551 (format "Sched.%2dx: " (- 1 diff)) head
13552 category tags))))
13553 (setq txt org-agenda-no-heading-message))
13554 (when txt
13555 (org-add-props txt props
13556 'org-marker (org-agenda-new-marker pos)
13557 'org-hd-marker (org-agenda-new-marker pos1)
13558 'priority (+ (- 5 diff) (org-get-priority txt))
13559 'category category)
13560 (push txt ee))))))
13561 ee))
13563 (defun org-agenda-get-blocks ()
13564 "Return the date-range information for agenda display."
13565 (let* ((props (list 'face nil
13566 'org-not-done-regexp org-not-done-regexp
13567 'mouse-face 'highlight
13568 'keymap org-agenda-keymap
13569 'help-echo
13570 (format "mouse-2 or RET jump to org file %s"
13571 (abbreviate-file-name buffer-file-name))))
13572 (regexp org-tr-regexp)
13573 (d0 (calendar-absolute-from-gregorian date))
13574 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
13575 (goto-char (point-min))
13576 (while (re-search-forward regexp nil t)
13577 (catch :skip
13578 (org-agenda-skip)
13579 (setq pos (point))
13580 (setq timestr (match-string 0)
13581 s1 (match-string 1)
13582 s2 (match-string 2)
13583 d1 (time-to-days (org-time-string-to-time s1))
13584 d2 (time-to-days (org-time-string-to-time s2)))
13585 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
13586 ;; Only allow days between the limits, because the normal
13587 ;; date stamps will catch the limits.
13588 (save-excursion
13589 (setq marker (org-agenda-new-marker (point)))
13590 (setq category (org-get-category))
13591 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
13592 (progn
13593 (setq hdmarker (org-agenda-new-marker (match-end 1)))
13594 (goto-char (match-end 1))
13595 (setq tags (org-get-tags-at))
13596 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
13597 (setq txt (org-format-agenda-item
13598 (format (if (= d1 d2) "" "(%d/%d): ")
13599 (1+ (- d0 d1)) (1+ (- d2 d1)))
13600 (match-string 1) category tags
13601 (if (= d0 d1) timestr))))
13602 (setq txt org-agenda-no-heading-message))
13603 (org-add-props txt props
13604 'org-marker marker 'org-hd-marker hdmarker
13605 'priority (org-get-priority txt) 'category category)
13606 (push txt ee)))
13607 (goto-char pos)))
13608 ;; Sort the entries by expiration date.
13609 (nreverse ee)))
13611 ;;; Agenda presentation and sorting
13613 ;; FIXME: should I allow spaces around the dash?
13614 (defconst org-plain-time-of-day-regexp
13615 (concat
13616 "\\(\\<[012]?[0-9]"
13617 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
13618 "\\(--?"
13619 "\\(\\<[012]?[0-9]"
13620 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
13621 "\\)?")
13622 "Regular expression to match a plain time or time range.
13623 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
13624 groups carry important information:
13625 0 the full match
13626 1 the first time, range or not
13627 8 the second time, if it is a range.")
13629 (defconst org-stamp-time-of-day-regexp
13630 (concat
13631 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
13632 "\\([012][0-9]:[0-5][0-9]\\)>"
13633 "\\(--?"
13634 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
13635 "Regular expression to match a timestamp time or time range.
13636 After a match, the following groups carry important information:
13637 0 the full match
13638 1 date plus weekday, for backreferencing to make sure both times on same day
13639 2 the first time, range or not
13640 4 the second time, if it is a range.")
13642 (defvar org-prefix-has-time nil
13643 "A flag, set by `org-compile-prefix-format'.
13644 The flag is set if the currently compiled format contains a `%t'.")
13645 (defvar org-prefix-has-tag nil
13646 "A flag, set by `org-compile-prefix-format'.
13647 The flag is set if the currently compiled format contains a `%T'.")
13649 (defun org-format-agenda-item (extra txt &optional category tags dotime
13650 noprefix)
13651 "Format TXT to be inserted into the agenda buffer.
13652 In particular, it adds the prefix and corresponding text properties. EXTRA
13653 must be a string and replaces the `%s' specifier in the prefix format.
13654 CATEGORY (string, symbol or nil) may be used to overrule the default
13655 category taken from local variable or file name. It will replace the `%c'
13656 specifier in the format. DOTIME, when non-nil, indicates that a
13657 time-of-day should be extracted from TXT for sorting of this entry, and for
13658 the `%t' specifier in the format. When DOTIME is a string, this string is
13659 searched for a time before TXT is. NOPREFIX is a flag and indicates that
13660 only the correctly processes TXT should be returned - this is used by
13661 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
13662 (save-match-data
13663 ;; Diary entries sometimes have extra whitespace at the beginning
13664 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
13665 (let* ((category (or category
13666 org-category
13667 (if buffer-file-name
13668 (file-name-sans-extension
13669 (file-name-nondirectory buffer-file-name))
13670 "")))
13671 (tag (if tags (nth (1- (length tags)) tags) ""))
13672 time ;; needed for the eval of the prefix format
13673 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
13674 (time-of-day (and dotime (org-get-time-of-day ts)))
13675 stamp plain s0 s1 s2 rtn)
13676 (when (and dotime time-of-day org-prefix-has-time)
13677 ;; Extract starting and ending time and move them to prefix
13678 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
13679 (setq plain (string-match org-plain-time-of-day-regexp ts)))
13680 (setq s0 (match-string 0 ts)
13681 s1 (match-string (if plain 1 2) ts)
13682 s2 (match-string (if plain 8 4) ts))
13684 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
13685 ;; them, we might want to remove them there to avoid duplication.
13686 ;; The user can turn this off with a variable.
13687 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
13688 (string-match (concat (regexp-quote s0) " *") txt)
13689 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
13690 (= (match-beginning 0) 0)
13692 (setq txt (replace-match "" nil nil txt))))
13693 ;; Normalize the time(s) to 24 hour
13694 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
13695 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
13697 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
13698 ;; Tags are in the string
13699 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
13700 (and org-agenda-remove-tags-when-in-prefix
13701 org-prefix-has-tag))
13702 (setq txt (replace-match "" t t txt))
13703 (setq txt (replace-match
13704 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
13705 (match-string 2 txt))
13706 t t txt))))
13708 ;; Create the final string
13709 (if noprefix
13710 (setq rtn txt)
13711 ;; Prepare the variables needed in the eval of the compiled format
13712 (setq time (cond (s2 (concat s1 "-" s2))
13713 (s1 (concat s1 "......"))
13714 (t ""))
13715 extra (or extra "")
13716 category (if (symbolp category) (symbol-name category) category))
13717 ;; Evaluate the compiled format
13718 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
13720 ;; And finally add the text properties
13721 (org-add-props rtn nil
13722 'category (downcase category) 'tags tags
13723 'prefix-length (- (length rtn) (length txt))
13724 'time-of-day time-of-day
13725 'dotime dotime))))
13727 (defvar org-agenda-sorting-strategy)
13728 (defvar org-agenda-sorting-strategy-selected nil)
13730 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
13731 (catch 'exit
13732 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
13733 ((and todayp (member 'today (car org-agenda-time-grid))))
13734 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
13735 ((member 'weekly (car org-agenda-time-grid)))
13736 (t (throw 'exit list)))
13737 (let* ((have (delq nil (mapcar
13738 (lambda (x) (get-text-property 1 'time-of-day x))
13739 list)))
13740 (string (nth 1 org-agenda-time-grid))
13741 (gridtimes (nth 2 org-agenda-time-grid))
13742 (req (car org-agenda-time-grid))
13743 (remove (member 'remove-match req))
13744 new time)
13745 (if (and (member 'require-timed req) (not have))
13746 ;; don't show empty grid
13747 (throw 'exit list))
13748 (while (setq time (pop gridtimes))
13749 (unless (and remove (member time have))
13750 (setq time (int-to-string time))
13751 (push (org-format-agenda-item
13752 nil string "" nil
13753 (concat (substring time 0 -2) ":" (substring time -2)))
13754 new)
13755 (put-text-property
13756 1 (length (car new)) 'face 'org-time-grid (car new))))
13757 (if (member 'time-up org-agenda-sorting-strategy-selected)
13758 (append new list)
13759 (append list new)))))
13761 (defun org-compile-prefix-format (key)
13762 "Compile the prefix format into a Lisp form that can be evaluated.
13763 The resulting form is returned and stored in the variable
13764 `org-prefix-format-compiled'."
13765 (setq org-prefix-has-time nil org-prefix-has-tag nil)
13766 (let ((s (cond
13767 ((stringp org-agenda-prefix-format)
13768 org-agenda-prefix-format)
13769 ((assq key org-agenda-prefix-format)
13770 (cdr (assq key org-agenda-prefix-format)))
13771 (t " %-12:c%?-12t% s")))
13772 (start 0)
13773 varform vars var e c f opt)
13774 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
13775 s start)
13776 (setq var (cdr (assoc (match-string 4 s)
13777 '(("c" . category) ("t" . time) ("s" . extra)
13778 ("T" . tag))))
13779 c (or (match-string 3 s) "")
13780 opt (match-beginning 1)
13781 start (1+ (match-beginning 0)))
13782 (if (equal var 'time) (setq org-prefix-has-time t))
13783 (if (equal var 'tag) (setq org-prefix-has-tag t))
13784 (setq f (concat "%" (match-string 2 s) "s"))
13785 (if opt
13786 (setq varform
13787 `(if (equal "" ,var)
13789 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
13790 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
13791 (setq s (replace-match "%s" t nil s))
13792 (push varform vars))
13793 (setq vars (nreverse vars))
13794 (setq org-prefix-format-compiled `(format ,s ,@vars))))
13796 (defun org-set-sorting-strategy (key)
13797 (if (symbolp (car org-agenda-sorting-strategy))
13798 ;; the old format
13799 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
13800 (setq org-agenda-sorting-strategy-selected
13801 (or (cdr (assq key org-agenda-sorting-strategy))
13802 (cdr (assq 'agenda org-agenda-sorting-strategy))
13803 '(time-up category-keep priority-down)))))
13805 (defun org-get-time-of-day (s &optional string mod24)
13806 "Check string S for a time of day.
13807 If found, return it as a military time number between 0 and 2400.
13808 If not found, return nil.
13809 The optional STRING argument forces conversion into a 5 character wide string
13810 HH:MM."
13811 (save-match-data
13812 (when
13814 (string-match
13815 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
13816 (string-match
13817 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
13818 (let* ((h (string-to-number (match-string 1 s)))
13819 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
13820 (ampm (if (match-end 4) (downcase (match-string 4 s))))
13821 (am-p (equal ampm "am"))
13822 (h1 (cond ((not ampm) h)
13823 ((= h 12) (if am-p 0 12))
13824 (t (+ h (if am-p 0 12)))))
13825 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
13826 (mod h1 24) h1))
13827 (t0 (+ (* 100 h2) m))
13828 (t1 (concat (if (>= h1 24) "+" " ")
13829 (if (< t0 100) "0" "")
13830 (if (< t0 10) "0" "")
13831 (int-to-string t0))))
13832 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
13834 (defun org-finalize-agenda-entries (list &optional nosort)
13835 "Sort and concatenate the agenda items."
13836 (setq list (mapcar 'org-agenda-highlight-todo list))
13837 (if nosort
13838 list
13839 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
13841 (defun org-agenda-highlight-todo (x)
13842 (let (re pl)
13843 (if (eq x 'line)
13844 (save-excursion
13845 (beginning-of-line 1)
13846 (setq re (get-text-property (point) 'org-not-done-regexp))
13847 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
13848 (and (looking-at (concat "[ \t]*\\.*" re))
13849 (add-text-properties (match-beginning 0) (match-end 0)
13850 '(face org-todo))))
13851 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
13852 pl (get-text-property 0 'prefix-length x))
13853 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
13854 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
13855 '(face org-todo) x))
13856 x)))
13858 (defsubst org-cmp-priority (a b)
13859 "Compare the priorities of string A and B."
13860 (let ((pa (or (get-text-property 1 'priority a) 0))
13861 (pb (or (get-text-property 1 'priority b) 0)))
13862 (cond ((> pa pb) +1)
13863 ((< pa pb) -1)
13864 (t nil))))
13866 (defsubst org-cmp-category (a b)
13867 "Compare the string values of categories of strings A and B."
13868 (let ((ca (or (get-text-property 1 'category a) ""))
13869 (cb (or (get-text-property 1 'category b) "")))
13870 (cond ((string-lessp ca cb) -1)
13871 ((string-lessp cb ca) +1)
13872 (t nil))))
13874 (defsubst org-cmp-tag (a b)
13875 "Compare the string values of categories of strings A and B."
13876 (let ((ta (car (last (get-text-property 1 'tags a))))
13877 (tb (car (last (get-text-property 1 'tags b)))))
13878 (cond ((not ta) +1)
13879 ((not tb) -1)
13880 ((string-lessp ta tb) -1)
13881 ((string-lessp tb ta) +1)
13882 (t nil))))
13884 (defsubst org-cmp-time (a b)
13885 "Compare the time-of-day values of strings A and B."
13886 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
13887 (ta (or (get-text-property 1 'time-of-day a) def))
13888 (tb (or (get-text-property 1 'time-of-day b) def)))
13889 (cond ((< ta tb) -1)
13890 ((< tb ta) +1)
13891 (t nil))))
13893 (defun org-entries-lessp (a b)
13894 "Predicate for sorting agenda entries."
13895 ;; The following variables will be used when the form is evaluated.
13896 (let* ((time-up (org-cmp-time a b))
13897 (time-down (if time-up (- time-up) nil))
13898 (priority-up (org-cmp-priority a b))
13899 (priority-down (if priority-up (- priority-up) nil))
13900 (category-up (org-cmp-category a b))
13901 (category-down (if category-up (- category-up) nil))
13902 (category-keep (if category-up +1 nil))
13903 (tag-up (org-cmp-tag a b))
13904 (tag-down (if tag-up (- tag-up) nil)))
13905 (cdr (assoc
13906 (eval (cons 'or org-agenda-sorting-strategy-selected))
13907 '((-1 . t) (1 . nil) (nil . nil))))))
13909 ;;; Agenda commands
13911 (defun org-agenda-check-type (error &rest types)
13912 "Check if agenda buffer is of allowed type.
13913 If ERROR is non-nil, throw an error, otherwise just return nil."
13914 (if (memq org-agenda-type types)
13916 (if error
13917 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
13918 nil)))
13920 (defun org-agenda-quit ()
13921 "Exit agenda by removing the window or the buffer."
13922 (interactive)
13923 (let ((buf (current-buffer)))
13924 (if (not (one-window-p)) (delete-window))
13925 (kill-buffer buf)
13926 (org-agenda-maybe-reset-markers 'force))
13927 ;; Maybe restore the pre-agenda window configuration.
13928 (and org-agenda-restore-windows-after-quit
13929 (not (eq org-agenda-window-setup 'other-frame))
13930 org-pre-agenda-window-conf
13931 (set-window-configuration org-pre-agenda-window-conf)))
13933 (defun org-agenda-exit ()
13934 "Exit agenda by removing the window or the buffer.
13935 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
13936 Org-mode buffers visited directly by the user will not be touched."
13937 (interactive)
13938 (org-release-buffers org-agenda-new-buffers)
13939 (setq org-agenda-new-buffers nil)
13940 (org-agenda-quit))
13942 (defun org-save-all-org-buffers ()
13943 "Save all Org-mode buffers without user confirmation."
13944 (interactive)
13945 (message "Saving all Org-mode buffers...")
13946 (save-some-buffers t 'org-mode-p)
13947 (message "Saving all Org-mode buffers... done"))
13949 (defun org-agenda-redo ()
13950 "Rebuild Agenda.
13951 When this is the global TODO list, a prefix argument will be interpreted."
13952 (interactive)
13953 (let* ((org-agenda-keep-modes t)
13954 (line (org-current-line))
13955 (window-line (- line (org-current-line (window-start)))))
13956 (message "Rebuilding agenda buffer...")
13957 (eval org-agenda-redo-command)
13958 (setq org-agenda-undo-list nil
13959 org-agenda-pending-undo-list nil)
13960 (message "Rebuilding agenda buffer...done")
13961 (goto-line line)
13962 (recenter window-line)))
13964 (defun org-agenda-goto-today ()
13965 "Go to today."
13966 (interactive)
13967 (org-agenda-check-type t 'timeline 'agenda)
13968 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
13969 (cond
13970 (tdpos (goto-char tdpos))
13971 ((eq org-agenda-type 'agenda)
13972 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
13973 (setf (nth 1 org-agenda-overriding-arguments) nil)
13974 (org-agenda-redo)
13975 (org-agenda-find-today-or-agenda)))
13976 (t (error "Cannot find today")))))
13978 (defun org-agenda-find-today-or-agenda ()
13979 (goto-char
13980 (or (text-property-any (point-min) (point-max) 'org-today t)
13981 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
13982 (point-min))))
13984 (defun org-agenda-later (arg)
13985 "Go forward in time by `org-agenda-ndays' days.
13986 With prefix ARG, go forward that many times `org-agenda-ndays'."
13987 (interactive "p")
13988 (org-agenda-check-type t 'agenda)
13989 (let ((org-agenda-overriding-arguments
13990 (list (car org-agenda-last-arguments)
13991 (+ org-starting-day (* arg org-agenda-ndays))
13992 nil t)))
13993 (org-agenda-redo)
13994 (org-agenda-find-today-or-agenda)))
13996 (defun org-agenda-earlier (arg)
13997 "Go back in time by `org-agenda-ndays' days.
13998 With prefix ARG, go back that many times `org-agenda-ndays'."
13999 (interactive "p")
14000 (org-agenda-check-type t 'agenda)
14001 (let ((org-agenda-overriding-arguments
14002 (list (car org-agenda-last-arguments)
14003 (- org-starting-day (* arg org-agenda-ndays))
14004 nil t)))
14005 (org-agenda-redo)
14006 (org-agenda-find-today-or-agenda)))
14008 (defun org-agenda-week-view ()
14009 "Switch to weekly view for agenda."
14010 (interactive)
14011 (org-agenda-check-type t 'agenda)
14012 (if (= org-agenda-ndays 7)
14013 (error "This is already the week view"))
14014 (setq org-agenda-ndays 7)
14015 (let ((org-agenda-overriding-arguments
14016 (list (car org-agenda-last-arguments)
14017 (or (get-text-property (point) 'day)
14018 org-starting-day)
14019 nil t)))
14020 (org-agenda-redo)
14021 (org-agenda-find-today-or-agenda))
14022 (org-agenda-set-mode-name)
14023 (message "Switched to week view"))
14025 (defun org-agenda-day-view ()
14026 "Switch to daily view for agenda."
14027 (interactive)
14028 (org-agenda-check-type t 'agenda)
14029 (if (= org-agenda-ndays 1)
14030 (error "This is already the day view"))
14031 (setq org-agenda-ndays 1)
14032 (let ((org-agenda-overriding-arguments
14033 (list (car org-agenda-last-arguments)
14034 (or (get-text-property (point) 'day)
14035 org-starting-day)
14036 nil t)))
14037 (org-agenda-redo)
14038 (org-agenda-find-today-or-agenda))
14039 (org-agenda-set-mode-name)
14040 (message "Switched to day view"))
14042 (defun org-agenda-next-date-line (&optional arg)
14043 "Jump to the next line indicating a date in agenda buffer."
14044 (interactive "p")
14045 (org-agenda-check-type t 'agenda 'timeline)
14046 (beginning-of-line 1)
14047 (if (looking-at "^\\S-") (forward-char 1))
14048 (if (not (re-search-forward "^\\S-" nil t arg))
14049 (progn
14050 (backward-char 1)
14051 (error "No next date after this line in this buffer")))
14052 (goto-char (match-beginning 0)))
14054 (defun org-agenda-previous-date-line (&optional arg)
14055 "Jump to the previous line indicating a date in agenda buffer."
14056 (interactive "p")
14057 (org-agenda-check-type t 'agenda 'timeline)
14058 (beginning-of-line 1)
14059 (if (not (re-search-backward "^\\S-" nil t arg))
14060 (error "No previous date before this line in this buffer")))
14062 ;; Initialize the highlight
14063 (defvar org-hl (org-make-overlay 1 1))
14064 (org-overlay-put org-hl 'face 'highlight)
14066 (defun org-highlight (begin end &optional buffer)
14067 "Highlight a region with overlay."
14068 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
14069 org-hl begin end (or buffer (current-buffer))))
14071 (defun org-unhighlight ()
14072 "Detach overlay INDEX."
14073 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
14076 (defun org-agenda-follow-mode ()
14077 "Toggle follow mode in an agenda buffer."
14078 (interactive)
14079 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
14080 (org-agenda-set-mode-name)
14081 (message "Follow mode is %s"
14082 (if org-agenda-follow-mode "on" "off")))
14084 (defun org-agenda-log-mode ()
14085 "Toggle log mode in an agenda buffer."
14086 (interactive)
14087 (org-agenda-check-type t 'agenda 'timeline)
14088 (setq org-agenda-show-log (not org-agenda-show-log))
14089 (org-agenda-set-mode-name)
14090 (org-agenda-redo)
14091 (message "Log mode is %s"
14092 (if org-agenda-show-log "on" "off")))
14094 (defun org-agenda-toggle-diary ()
14095 "Toggle diary inclusion in an agenda buffer."
14096 (interactive)
14097 (org-agenda-check-type t 'agenda)
14098 (setq org-agenda-include-diary (not org-agenda-include-diary))
14099 (org-agenda-redo)
14100 (org-agenda-set-mode-name)
14101 (message "Diary inclusion turned %s"
14102 (if org-agenda-include-diary "on" "off")))
14104 (defun org-agenda-toggle-time-grid ()
14105 "Toggle time grid in an agenda buffer."
14106 (interactive)
14107 (org-agenda-check-type t 'agenda)
14108 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
14109 (org-agenda-redo)
14110 (org-agenda-set-mode-name)
14111 (message "Time-grid turned %s"
14112 (if org-agenda-use-time-grid "on" "off")))
14114 (defun org-agenda-set-mode-name ()
14115 "Set the mode name to indicate all the small mode settings."
14116 (setq mode-name
14117 (concat "Org-Agenda"
14118 (if (equal org-agenda-ndays 1) " Day" "")
14119 (if (equal org-agenda-ndays 7) " Week" "")
14120 (if org-agenda-follow-mode " Follow" "")
14121 (if org-agenda-include-diary " Diary" "")
14122 (if org-agenda-use-time-grid " Grid" "")
14123 (if org-agenda-show-log " Log" "")))
14124 (force-mode-line-update))
14126 (defun org-agenda-post-command-hook ()
14127 (and (eolp) (not (bolp)) (backward-char 1))
14128 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
14129 (if (and org-agenda-follow-mode
14130 (get-text-property (point) 'org-marker))
14131 (org-agenda-show)))
14133 (defun org-agenda-show-priority ()
14134 "Show the priority of the current item.
14135 This priority is composed of the main priority given with the [#A] cookies,
14136 and by additional input from the age of a schedules or deadline entry."
14137 (interactive)
14138 (let* ((pri (get-text-property (point-at-bol) 'priority)))
14139 (message "Priority is %d" (if pri pri -1000))))
14141 (defun org-agenda-show-tags ()
14142 "Show the tags applicable to the current item."
14143 (interactive)
14144 (let* ((tags (get-text-property (point-at-bol) 'tags)))
14145 (if tags
14146 (message "Tags are :%s:"
14147 (org-no-properties (mapconcat 'identity tags ":")))
14148 (message "No tags associated with this line"))))
14150 (defun org-agenda-goto (&optional highlight)
14151 "Go to the Org-mode file which contains the item at point."
14152 (interactive)
14153 (let* ((marker (or (get-text-property (point) 'org-marker)
14154 (org-agenda-error)))
14155 (buffer (marker-buffer marker))
14156 (pos (marker-position marker)))
14157 (switch-to-buffer-other-window buffer)
14158 (widen)
14159 (goto-char pos)
14160 (when (org-mode-p)
14161 (org-show-context 'agenda)
14162 (save-excursion
14163 (and (outline-next-heading)
14164 (org-flag-heading nil)))) ; show the next heading
14165 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
14167 (defun org-agenda-kill ()
14168 "Kill the entry or subtree belonging to the current agenda entry."
14169 (interactive)
14170 (let* ((marker (or (get-text-property (point) 'org-marker)
14171 (org-agenda-error)))
14172 (hdmarker (get-text-property (point) 'org-hd-marker))
14173 (buffer (marker-buffer marker))
14174 (pos (marker-position marker))
14175 dbeg dend (n 0) conf)
14176 (org-with-remote-undo buffer
14177 (with-current-buffer buffer
14178 (save-excursion
14179 (goto-char pos)
14180 (if (org-mode-p)
14181 (setq dbeg (progn (org-back-to-heading t) (point))
14182 dend (org-end-of-subtree t))
14183 (setq dbeg (point-at-bol)
14184 dend (min (point-max) (1+ (point-at-eol)))))
14185 (goto-char dbeg)
14186 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
14187 (setq conf (or (eq t org-agenda-confirm-kill)
14188 (and (numberp org-agenda-confirm-kill)
14189 (> n org-agenda-confirm-kill))))
14190 (and conf
14191 (not (y-or-n-p
14192 (format "Delete entry with %d lines in buffer \"%s\"? "
14193 n (buffer-name buffer))))
14194 (error "Abort"))
14195 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
14196 (with-current-buffer buffer (delete-region dbeg dend))
14197 (message "Agenda item and source killed"))))
14199 (defun org-agenda-archive ()
14200 "Kill the entry or subtree belonging to the current agenda entry."
14201 (interactive)
14202 (let* ((marker (or (get-text-property (point) 'org-marker)
14203 (org-agenda-error)))
14204 (hdmarker (get-text-property (point) 'org-hd-marker))
14205 (buffer (marker-buffer marker))
14206 (pos (marker-position marker))
14207 dbeg dend txt n conf)
14208 (org-with-remote-undo buffer
14209 (with-current-buffer buffer
14210 (if (org-mode-p)
14211 (save-excursion
14212 (goto-char pos)
14213 (org-remove-subtree-entries-from-agenda)
14214 (org-back-to-heading t)
14215 (org-archive-subtree))
14216 (error "Archiving works only in Org-mode files"))))))
14218 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
14219 "Remove all lines in the agenda that correspond to a given subtree.
14220 The subtree is the one in buffer BUF, starting at BEG and ending at END.
14221 If this information is not given, the function uses the tree at point."
14222 (let ((buf (or buf (current-buffer))) m p)
14223 (save-excursion
14224 (unless (and beg end)
14225 (org-back-to-heading t)
14226 (setq beg (point))
14227 (org-end-of-subtree t)
14228 (setq end (point)))
14229 (set-buffer (get-buffer org-agenda-buffer-name))
14230 (save-excursion
14231 (goto-char (point-max))
14232 (beginning-of-line 1)
14233 (while (not (bobp))
14234 (when (and (setq m (get-text-property (point) 'org-marker))
14235 (equal buf (marker-buffer m))
14236 (setq p (marker-position m))
14237 (>= p beg)
14238 (<= p end))
14239 (let (buffer-read-only)
14240 (delete-region (point-at-bol) (1+ (point-at-eol)))))
14241 (beginning-of-line 0))))))
14243 (defun org-agenda-open-link ()
14244 "Follow the link in the current line, if any."
14245 (interactive)
14246 (let ((eol (point-at-eol)))
14247 (save-excursion
14248 (if (or (re-search-forward org-bracket-link-regexp eol t)
14249 (re-search-forward org-angle-link-re eol t)
14250 (re-search-forward org-plain-link-re eol t))
14251 (call-interactively 'org-open-at-point)
14252 (error "No link in current line")))))
14254 (defun org-agenda-switch-to (&optional delete-other-windows)
14255 "Go to the Org-mode file which contains the item at point."
14256 (interactive)
14257 (let* ((marker (or (get-text-property (point) 'org-marker)
14258 (org-agenda-error)))
14259 (buffer (marker-buffer marker))
14260 (pos (marker-position marker)))
14261 (switch-to-buffer buffer)
14262 (and delete-other-windows (delete-other-windows))
14263 (widen)
14264 (goto-char pos)
14265 (when (org-mode-p)
14266 (org-show-context 'agenda)
14267 (save-excursion
14268 (and (outline-next-heading)
14269 (org-flag-heading nil)))))) ; show the next heading
14271 (defun org-agenda-goto-mouse (ev)
14272 "Go to the Org-mode file which contains the item at the mouse click."
14273 (interactive "e")
14274 (mouse-set-point ev)
14275 (org-agenda-goto))
14277 (defun org-agenda-show ()
14278 "Display the Org-mode file which contains the item at point."
14279 (interactive)
14280 (let ((win (selected-window)))
14281 (org-agenda-goto t)
14282 (select-window win)))
14284 (defun org-agenda-recenter (arg)
14285 "Display the Org-mode file which contains the item at point and recenter."
14286 (interactive "P")
14287 (let ((win (selected-window)))
14288 (org-agenda-goto t)
14289 (recenter arg)
14290 (select-window win)))
14292 (defun org-agenda-show-mouse (ev)
14293 "Display the Org-mode file which contains the item at the mouse click."
14294 (interactive "e")
14295 (mouse-set-point ev)
14296 (org-agenda-show))
14298 (defun org-agenda-check-no-diary ()
14299 "Check if the entry is a diary link and abort if yes."
14300 (if (get-text-property (point) 'org-agenda-diary-link)
14301 (org-agenda-error)))
14303 (defun org-agenda-error ()
14304 (error "Command not allowed in this line"))
14306 (defun org-agenda-tree-to-indirect-buffer ()
14307 "Show the subtree corresponding to the current entry in an indirect buffer.
14308 This calls the command `org-tree-to-indirect-buffer' from the original
14309 Org-mode buffer.
14310 With numerical prefix arg ARG, go up to this level and then take that tree.
14311 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
14312 dedicated frame)."
14313 (interactive)
14314 (org-agenda-check-no-diary)
14315 (let* ((marker (or (get-text-property (point) 'org-marker)
14316 (org-agenda-error)))
14317 (buffer (marker-buffer marker))
14318 (pos (marker-position marker)))
14319 (with-current-buffer buffer
14320 (save-excursion
14321 (goto-char pos)
14322 (call-interactively 'org-tree-to-indirect-buffer)))))
14324 (defvar org-last-heading-marker (make-marker)
14325 "Marker pointing to the headline that last changed its TODO state
14326 by a remote command from the agenda.")
14328 (defun org-agenda-todo (&optional arg)
14329 "Cycle TODO state of line at point, also in Org-mode file.
14330 This changes the line at point, all other lines in the agenda referring to
14331 the same tree node, and the headline of the tree node in the Org-mode file."
14332 (interactive "P")
14333 (org-agenda-check-no-diary)
14334 (let* ((col (current-column))
14335 (marker (or (get-text-property (point) 'org-marker)
14336 (org-agenda-error)))
14337 (buffer (marker-buffer marker))
14338 (pos (marker-position marker))
14339 (hdmarker (get-text-property (point) 'org-hd-marker))
14340 (buffer-read-only nil)
14341 newhead)
14342 (org-with-remote-undo buffer
14343 (with-current-buffer buffer
14344 (widen)
14345 (goto-char pos)
14346 (org-show-context 'agenda)
14347 (save-excursion
14348 (and (outline-next-heading)
14349 (org-flag-heading nil))) ; show the next heading
14350 (org-todo arg)
14351 (and (bolp) (forward-char 1))
14352 (setq newhead (org-get-heading))
14353 (save-excursion
14354 (org-back-to-heading)
14355 (move-marker org-last-heading-marker (point))))
14356 (beginning-of-line 1)
14357 (save-excursion
14358 (org-agenda-change-all-lines newhead hdmarker 'fixface))
14359 (move-to-column col))))
14361 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
14362 "Change all lines in the agenda buffer which match HDMARKER.
14363 The new content of the line will be NEWHEAD (as modified by
14364 `org-format-agenda-item'). HDMARKER is checked with
14365 `equal' against all `org-hd-marker' text properties in the file.
14366 If FIXFACE is non-nil, the face of each item is modified acording to
14367 the new TODO state."
14368 (let* ((buffer-read-only nil)
14369 props m pl undone-face done-face finish new dotime cat tags)
14370 (save-excursion
14371 (goto-char (point-max))
14372 (beginning-of-line 1)
14373 (while (not finish)
14374 (setq finish (bobp))
14375 (when (and (setq m (get-text-property (point) 'org-hd-marker))
14376 (equal m hdmarker))
14377 (setq props (text-properties-at (point))
14378 dotime (get-text-property (point) 'dotime)
14379 cat (get-text-property (point) 'category)
14380 tags (get-text-property (point) 'tags)
14381 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
14382 pl (get-text-property (point) 'prefix-length)
14383 undone-face (get-text-property (point) 'undone-face)
14384 done-face (get-text-property (point) 'done-face))
14385 (move-to-column pl)
14386 (cond
14387 ((equal new "")
14388 (beginning-of-line 1)
14389 (and (looking-at ".*\n?") (replace-match "")))
14390 ((looking-at ".*")
14391 (replace-match new t t)
14392 (beginning-of-line 1)
14393 (add-text-properties (point-at-bol) (point-at-eol) props)
14394 (when fixface
14395 (add-text-properties
14396 (point-at-bol) (point-at-eol)
14397 (list 'face
14398 (if org-last-todo-state-is-todo
14399 undone-face done-face))))
14400 (org-agenda-highlight-todo 'line)
14401 (beginning-of-line 1))
14402 (t (error "Line update did not work"))))
14403 (beginning-of-line 0)))
14404 (org-finalize-agenda)))
14406 (defun org-agenda-align-tags (&optional line)
14407 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
14408 (let ((buffer-read-only))
14409 (save-excursion
14410 (goto-char (if line (point-at-bol) (point-min)))
14411 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
14412 (if line (point-at-eol) nil) t)
14413 (delete-region (match-beginning 1) (match-end 1))
14414 (goto-char (match-beginning 1))
14415 (insert (org-add-props
14416 (make-string (max 1 (- org-agenda-align-tags-to-column
14417 (current-column))) ?\ )
14418 (text-properties-at (point))))))))
14420 (defun org-agenda-priority-up ()
14421 "Increase the priority of line at point, also in Org-mode file."
14422 (interactive)
14423 (org-agenda-priority 'up))
14425 (defun org-agenda-priority-down ()
14426 "Decrease the priority of line at point, also in Org-mode file."
14427 (interactive)
14428 (org-agenda-priority 'down))
14430 (defun org-agenda-priority (&optional force-direction)
14431 "Set the priority of line at point, also in Org-mode file.
14432 This changes the line at point, all other lines in the agenda referring to
14433 the same tree node, and the headline of the tree node in the Org-mode file."
14434 (interactive)
14435 (org-agenda-check-no-diary)
14436 (let* ((marker (or (get-text-property (point) 'org-marker)
14437 (org-agenda-error)))
14438 (buffer (marker-buffer marker))
14439 (pos (marker-position marker))
14440 (hdmarker (get-text-property (point) 'org-hd-marker))
14441 (buffer-read-only nil)
14442 newhead)
14443 (org-with-remote-undo buffer
14444 (with-current-buffer buffer
14445 (widen)
14446 (goto-char pos)
14447 (org-show-context 'agenda)
14448 (save-excursion
14449 (and (outline-next-heading)
14450 (org-flag-heading nil))) ; show the next heading
14451 (funcall 'org-priority force-direction)
14452 (end-of-line 1)
14453 (setq newhead (org-get-heading)))
14454 (org-agenda-change-all-lines newhead hdmarker)
14455 (beginning-of-line 1))))
14457 (defun org-get-tags-at (&optional pos)
14458 "Get a list of all headline tags applicable at POS.
14459 POS defaults to point. If tags are inherited, the list contains
14460 the targets in the same sequence as the headlines appear, i.e.
14461 the tags of the current headline come last."
14462 (interactive)
14463 (let (tags)
14464 (save-excursion
14465 (goto-char (or pos (point)))
14466 (save-match-data
14467 (org-back-to-heading t)
14468 (condition-case nil
14469 (while t
14470 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
14471 (setq tags (append (org-split-string
14472 (org-match-string-no-properties 1) ":")
14473 tags)))
14474 (or org-use-tag-inheritance (error ""))
14475 (org-up-heading-all 1))
14476 (error nil))))
14477 tags))
14479 ;; FIXME: should fix the tags property of the agenda line.
14480 (defun org-agenda-set-tags ()
14481 "Set tags for the current headline."
14482 (interactive)
14483 (org-agenda-check-no-diary)
14484 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
14485 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
14486 (org-agenda-error)))
14487 (buffer (marker-buffer hdmarker))
14488 (pos (marker-position hdmarker))
14489 (buffer-read-only nil)
14490 newhead)
14491 (org-with-remote-undo buffer
14492 (with-current-buffer buffer
14493 (widen)
14494 (goto-char pos)
14495 (org-show-context 'agenda)
14496 (save-excursion
14497 (and (outline-next-heading)
14498 (org-flag-heading nil))) ; show the next heading
14499 (call-interactively 'org-set-tags)
14500 (end-of-line 1)
14501 (setq newhead (org-get-heading)))
14502 (org-agenda-change-all-lines newhead hdmarker)
14503 (beginning-of-line 1))))
14505 (defun org-agenda-toggle-archive-tag ()
14506 "Toggle the archive tag for the current entry."
14507 (interactive)
14508 (org-agenda-check-no-diary)
14509 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
14510 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
14511 (org-agenda-error)))
14512 (buffer (marker-buffer hdmarker))
14513 (pos (marker-position hdmarker))
14514 (buffer-read-only nil)
14515 newhead)
14516 (org-with-remote-undo buffer
14517 (with-current-buffer buffer
14518 (widen)
14519 (goto-char pos)
14520 (org-show-context 'agenda)
14521 (save-excursion
14522 (and (outline-next-heading)
14523 (org-flag-heading nil))) ; show the next heading
14524 (call-interactively 'org-toggle-archive-tag)
14525 (end-of-line 1)
14526 (setq newhead (org-get-heading)))
14527 (org-agenda-change-all-lines newhead hdmarker)
14528 (beginning-of-line 1))))
14530 (defun org-agenda-date-later (arg &optional what)
14531 "Change the date of this item to one day later."
14532 (interactive "p")
14533 (org-agenda-check-type t 'agenda 'timeline)
14534 (org-agenda-check-no-diary)
14535 (let* ((marker (or (get-text-property (point) 'org-marker)
14536 (org-agenda-error)))
14537 (buffer (marker-buffer marker))
14538 (pos (marker-position marker)))
14539 (org-with-remote-undo buffer
14540 (with-current-buffer buffer
14541 (widen)
14542 (goto-char pos)
14543 (if (not (org-at-timestamp-p))
14544 (error "Cannot find time stamp"))
14545 (org-timestamp-change arg (or what 'day)))
14546 (org-agenda-show-new-time marker org-last-changed-timestamp))
14547 (message "Time stamp changed to %s" org-last-changed-timestamp)))
14549 (defun org-agenda-date-earlier (arg &optional what)
14550 "Change the date of this item to one day earlier."
14551 (interactive "p")
14552 (org-agenda-date-later (- arg) what))
14554 (defun org-agenda-show-new-time (marker stamp)
14555 "Show new date stamp via text properties."
14556 ;; We use text properties to make this undoable
14557 (let ((buffer-read-only nil)
14558 ovs ov)
14559 (setq stamp (concat " => " stamp))
14560 (save-excursion
14561 (goto-char (point-max))
14562 (while (not (bobp))
14563 (when (equal marker (get-text-property (point) 'org-marker))
14564 (move-to-column (- (window-width) (length stamp)) t)
14565 (if (featurep 'xemacs)
14566 ;; Use `duplicable' property to trigger undo recording
14567 (let ((ex (make-extent nil nil))
14568 (gl (make-glyph stamp)))
14569 (set-glyph-face gl 'secondary-selection)
14570 (set-extent-properties
14571 ex (list 'invisible t 'end-glyph gl 'duplicable t))
14572 (insert-extent ex (1- (point)) (point-at-eol)))
14573 (add-text-properties
14574 (1- (point)) (point-at-eol)
14575 (list 'display (org-add-props stamp nil
14576 'face 'secondary-selection))))
14577 (beginning-of-line 1))
14578 (beginning-of-line 0)))))
14580 (defun org-agenda-date-prompt (arg)
14581 "Change the date of this item. Date is prompted for, with default today.
14582 The prefix ARG is passed to the `org-time-stamp' command and can therefore
14583 be used to request time specification in the time stamp."
14584 (interactive "P")
14585 (org-agenda-check-type t 'agenda 'timeline)
14586 (org-agenda-check-no-diary)
14587 (let* ((marker (or (get-text-property (point) 'org-marker)
14588 (org-agenda-error)))
14589 (buffer (marker-buffer marker))
14590 (pos (marker-position marker)))
14591 (org-with-remote-undo buffer
14592 (with-current-buffer buffer
14593 (widen)
14594 (goto-char pos)
14595 (if (not (org-at-timestamp-p))
14596 (error "Cannot find time stamp"))
14597 (org-time-stamp arg)
14598 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
14600 (defun org-agenda-schedule (arg)
14601 "Schedule the item at point."
14602 (interactive "P")
14603 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
14604 (org-agenda-check-no-diary)
14605 (let* ((marker (or (get-text-property (point) 'org-marker)
14606 (org-agenda-error)))
14607 (buffer (marker-buffer marker))
14608 (pos (marker-position marker))
14609 (org-insert-labeled-timestamps-at-point nil)
14611 (org-with-remote-undo buffer
14612 (with-current-buffer buffer
14613 (widen)
14614 (goto-char pos)
14615 (setq ts (org-schedule))
14616 (message "Item scheduled for %s" ts)))))
14618 (defun org-agenda-deadline (arg)
14619 "Schedule the item at point."
14620 (interactive "P")
14621 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
14622 (org-agenda-check-no-diary)
14623 (let* ((marker (or (get-text-property (point) 'org-marker)
14624 (org-agenda-error)))
14625 (buffer (marker-buffer marker))
14626 (pos (marker-position marker))
14627 (org-insert-labeled-timestamps-at-point nil)
14629 (org-with-remote-undo buffer
14630 (with-current-buffer buffer
14631 (widen)
14632 (goto-char pos)
14633 (setq ts (org-deadline))
14634 (message "Deadline for this item set to %s" ts)))))
14636 (defun org-get-heading ()
14637 "Return the heading of the current entry, without the stars."
14638 (save-excursion
14639 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
14640 (if (and (re-search-backward "[\r\n]\\*" nil t)
14641 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
14642 (match-string 1)
14643 "")))
14645 (defun org-agenda-clock-in (&optional arg)
14646 "Start the clock on the currently selected item."
14647 (interactive "P")
14648 (org-agenda-check-no-diary)
14649 (let* ((marker (or (get-text-property (point) 'org-marker)
14650 (org-agenda-error)))
14651 (pos (marker-position marker)))
14652 (org-with-remote-undo (marker-buffer marker)
14653 (with-current-buffer (marker-buffer marker)
14654 (widen)
14655 (goto-char pos)
14656 (org-clock-in)))))
14658 (defun org-agenda-clock-out (&optional arg)
14659 "Stop the currently running clock."
14660 (interactive "P")
14661 (unless (marker-buffer org-clock-marker)
14662 (error "No running clock"))
14663 (org-with-remote-undo (marker-buffer org-clock-marker)
14664 (org-clock-out)))
14666 (defun org-agenda-clock-cancel (&optional arg)
14667 "Cancel the currently running clock."
14668 (interactive "P")
14669 (unless (marker-buffer org-clock-marker)
14670 (error "No running clock"))
14671 (org-with-remote-undo (marker-buffer org-clock-marker)
14672 (org-clock-cancel)))
14674 (defun org-agenda-diary-entry ()
14675 "Make a diary entry, like the `i' command from the calendar.
14676 All the standard commands work: block, weekly etc."
14677 (interactive)
14678 (org-agenda-check-type t 'agenda 'timeline)
14679 (require 'diary-lib)
14680 (let* ((char (progn
14681 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
14682 (read-char-exclusive)))
14683 (cmd (cdr (assoc char
14684 '((?d . insert-diary-entry)
14685 (?w . insert-weekly-diary-entry)
14686 (?m . insert-monthly-diary-entry)
14687 (?y . insert-yearly-diary-entry)
14688 (?a . insert-anniversary-diary-entry)
14689 (?b . insert-block-diary-entry)
14690 (?c . insert-cyclic-diary-entry)))))
14691 (oldf (symbol-function 'calendar-cursor-to-date))
14692 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
14693 (point (point))
14694 (mark (or (mark t) (point))))
14695 (unless cmd
14696 (error "No command associated with <%c>" char))
14697 (unless (and (get-text-property point 'day)
14698 (or (not (equal ?b char))
14699 (get-text-property mark 'day)))
14700 (error "Don't know which date to use for diary entry"))
14701 ;; We implement this by hacking the `calendar-cursor-to-date' function
14702 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
14703 (let ((calendar-mark-ring
14704 (list (calendar-gregorian-from-absolute
14705 (or (get-text-property mark 'day)
14706 (get-text-property point 'day))))))
14707 (unwind-protect
14708 (progn
14709 (fset 'calendar-cursor-to-date
14710 (lambda (&optional error)
14711 (calendar-gregorian-from-absolute
14712 (get-text-property point 'day))))
14713 (call-interactively cmd))
14714 (fset 'calendar-cursor-to-date oldf)))))
14717 (defun org-agenda-execute-calendar-command (cmd)
14718 "Execute a calendar command from the agenda, with the date associated to
14719 the cursor position."
14720 (org-agenda-check-type t 'agenda 'timeline)
14721 (require 'diary-lib)
14722 (unless (get-text-property (point) 'day)
14723 (error "Don't know which date to use for calendar command"))
14724 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
14725 (point (point))
14726 (date (calendar-gregorian-from-absolute
14727 (get-text-property point 'day)))
14728 (displayed-day (extract-calendar-day date))
14729 (displayed-month (extract-calendar-month date))
14730 (displayed-year (extract-calendar-year date)))
14731 (unwind-protect
14732 (progn
14733 (fset 'calendar-cursor-to-date
14734 (lambda (&optional error)
14735 (calendar-gregorian-from-absolute
14736 (get-text-property point 'day))))
14737 (call-interactively cmd))
14738 (fset 'calendar-cursor-to-date oldf))))
14740 (defun org-agenda-phases-of-moon ()
14741 "Display the phases of the moon for the 3 months around the cursor date."
14742 (interactive)
14743 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
14745 (defun org-agenda-holidays ()
14746 "Display the holidays for the 3 months around the cursor date."
14747 (interactive)
14748 (org-agenda-execute-calendar-command 'list-calendar-holidays))
14750 (defun org-agenda-sunrise-sunset (arg)
14751 "Display sunrise and sunset for the cursor date.
14752 Latitude and longitude can be specified with the variables
14753 `calendar-latitude' and `calendar-longitude'. When called with prefix
14754 argument, latitude and longitude will be prompted for."
14755 (interactive "P")
14756 (let ((calendar-longitude (if arg nil calendar-longitude))
14757 (calendar-latitude (if arg nil calendar-latitude))
14758 (calendar-location-name
14759 (if arg "the given coordinates" calendar-location-name)))
14760 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
14762 (defun org-agenda-goto-calendar ()
14763 "Open the Emacs calendar with the date at the cursor."
14764 (interactive)
14765 (org-agenda-check-type t 'agenda 'timeline)
14766 (let* ((day (or (get-text-property (point) 'day)
14767 (error "Don't know which date to open in calendar")))
14768 (date (calendar-gregorian-from-absolute day))
14769 (calendar-move-hook nil)
14770 (view-calendar-holidays-initially nil)
14771 (view-diary-entries-initially nil))
14772 (calendar)
14773 (calendar-goto-date date)))
14775 (defun org-calendar-goto-agenda ()
14776 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
14777 This is a command that has to be installed in `calendar-mode-map'."
14778 (interactive)
14779 (org-agenda-list nil (calendar-absolute-from-gregorian
14780 (calendar-cursor-to-date))
14781 nil))
14783 (defun org-agenda-convert-date ()
14784 (interactive)
14785 (org-agenda-check-type t 'agenda 'timeline)
14786 (let ((day (get-text-property (point) 'day))
14787 date s)
14788 (unless day
14789 (error "Don't know which date to convert"))
14790 (setq date (calendar-gregorian-from-absolute day))
14791 (setq s (concat
14792 "Gregorian: " (calendar-date-string date) "\n"
14793 "ISO: " (calendar-iso-date-string date) "\n"
14794 "Day of Yr: " (calendar-day-of-year-string date) "\n"
14795 "Julian: " (calendar-julian-date-string date) "\n"
14796 "Astron. JD: " (calendar-astro-date-string date)
14797 " (Julian date number at noon UTC)\n"
14798 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
14799 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
14800 "French: " (calendar-french-date-string date) "\n"
14801 "Mayan: " (calendar-mayan-date-string date) "\n"
14802 "Coptic: " (calendar-coptic-date-string date) "\n"
14803 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
14804 "Persian: " (calendar-persian-date-string date) "\n"
14805 "Chinese: " (calendar-chinese-date-string date) "\n"))
14806 (with-output-to-temp-buffer "*Dates*"
14807 (princ s))
14808 (if (fboundp 'fit-window-to-buffer)
14809 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
14812 ;;;; Embedded LaTeX
14814 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14815 "Keymap for the minor `org-cdlatex-mode'.")
14817 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14818 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14819 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14820 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14821 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14823 (defvar org-cdlatex-texmathp-advice-is-done nil
14824 "Flag remembering if we have applied the advice to texmathp already.")
14826 (define-minor-mode org-cdlatex-mode
14827 "Toggle the minor `org-cdlatex-mode'.
14828 This mode supports entering LaTeX environment and math in LaTeX fragments
14829 in Org-mode.
14830 \\{org-cdlatex-mode-map}"
14831 nil " OCDL" nil
14832 (when org-cdlatex-mode (require 'cdlatex))
14833 (unless org-cdlatex-texmathp-advice-is-done
14834 (setq org-cdlatex-texmathp-advice-is-done t)
14835 (defadvice texmathp (around org-math-always-on activate)
14836 "Always return t in org-mode buffers.
14837 This is because we want to insert math symbols without dollars even outside
14838 the LaTeX math segments. If Orgmode thinks that point is actually inside
14839 en embedded LaTeX fragement, let texmathp do its job.
14840 \\[org-cdlatex-mode-map]"
14841 (interactive)
14842 (let (p)
14843 (cond
14844 ((not (org-mode-p)) ad-do-it)
14845 ((eq this-command 'cdlatex-math-symbol)
14846 (setq ad-return-value t
14847 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14849 (let ((p (org-inside-LaTeX-fragment-p)))
14850 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14851 (setq ad-return-value t
14852 texmathp-why '("Org-mode embedded math" . 0))
14853 (if p ad-do-it)))))))))
14855 (defun turn-on-org-cdlatex ()
14856 "Unconditionally turn on `org-cdlatex-mode'."
14857 (org-cdlatex-mode 1))
14859 (defun org-inside-LaTeX-fragment-p ()
14860 "Test if point is inside a LaTeX fragment.
14861 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14862 sequence appearing also before point.
14863 Even though the matchers for math are configurable, this function assumes
14864 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14865 delimiters are skipped when they have been removed by customization.
14866 The return value is nil, or a cons cell with the delimiter and
14867 and the position of this delimiter.
14869 This function does a reasonably good job, but can locally be fooled by
14870 for example currency specifications. For example it will assume being in
14871 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14872 fragments that are properly closed, but during editing, we have to live
14873 with the uncertainty caused by missing closing delimiters. This function
14874 looks only before point, not after."
14875 (catch 'exit
14876 (let ((pos (point))
14877 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14878 (lim (progn
14879 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14880 (point)))
14881 dd-on str (start 0) m re)
14882 (goto-char pos)
14883 (when dodollar
14884 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14885 re (nth 1 (assoc "$" org-latex-regexps)))
14886 (while (string-match re str start)
14887 (cond
14888 ((= (match-end 0) (length str))
14889 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
14890 ((= (match-end 0) (- (length str) 5))
14891 (throw 'exit nil))
14892 (t (setq start (match-end 0))))))
14893 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14894 (goto-char pos)
14895 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14896 (and (match-beginning 2) (throw 'exit nil))
14897 ;; count $$
14898 (while (re-search-backward "\\$\\$" lim t)
14899 (setq dd-on (not dd-on)))
14900 (goto-char pos)
14901 (if dd-on (cons "$$" m))))))
14904 (defun org-try-cdlatex-tab ()
14905 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14906 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14907 - inside a LaTeX fragment, or
14908 - after the first word in a line, where an abbreviation expansion could
14909 insert a LaTeX environment."
14910 (when org-cdlatex-mode
14911 (cond
14912 ((save-excursion
14913 (skip-chars-backward "a-zA-Z0-9*")
14914 (skip-chars-backward " \t")
14915 (bolp))
14916 (cdlatex-tab) t)
14917 ((org-inside-LaTeX-fragment-p)
14918 (cdlatex-tab) t)
14919 (t nil))))
14921 (defun org-cdlatex-underscore-caret (&optional arg)
14922 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14923 Revert to the normal definition outside of these fragments."
14924 (interactive "P")
14925 (if (org-inside-LaTeX-fragment-p)
14926 (call-interactively 'cdlatex-sub-superscript)
14927 (let (org-cdlatex-mode)
14928 (call-interactively (key-binding (vector last-input-event))))))
14930 (defun org-cdlatex-math-modify (&optional arg)
14931 "Execute `cdlatex-math-modify' in LaTeX fragments.
14932 Revert to the normal definition outside of these fragments."
14933 (interactive "P")
14934 (if (org-inside-LaTeX-fragment-p)
14935 (call-interactively 'cdlatex-math-modify)
14936 (let (org-cdlatex-mode)
14937 (call-interactively (key-binding (vector last-input-event))))))
14939 (defvar org-latex-fragment-image-overlays nil
14940 "List of overlays carrying the images of latex fragments.")
14941 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14943 (defun org-remove-latex-fragment-image-overlays ()
14944 "Remove all overlays with LaTeX fragment images in current buffer."
14945 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14946 (setq org-latex-fragment-image-overlays nil))
14948 (defun org-preview-latex-fragment (&optional subtree)
14949 "Preview the LaTeX fragment at point, or all locally or globally.
14950 If the cursor is in a LaTeX fragment, create the image and overlay
14951 it over the source code. If there is no fragment at point, display
14952 all fragments in the current text, from one headline to the next. With
14953 prefix SUBTREE, display all fragments in the current subtree. With a
14954 double prefix `C-u C-u', or when the cursor is before the first headline,
14955 display all fragments in the buffer.
14956 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14957 (interactive "P")
14958 (org-remove-latex-fragment-image-overlays)
14959 (save-excursion
14960 (save-restriction
14961 (let (beg end at msg)
14962 (cond
14963 ((or (equal subtree '(16))
14964 (not (save-excursion
14965 (re-search-backward (concat "^" outline-regexp) nil t))))
14966 (setq beg (point-min) end (point-max)
14967 msg "Creating images for buffer...%s"))
14968 ((equal subtree '(4))
14969 (org-back-to-heading)
14970 (setq beg (point) end (org-end-of-subtree t)
14971 msg "Creating images for subtree...%s"))
14973 (if (setq at (org-inside-LaTeX-fragment-p))
14974 (goto-char (max (point-min) (- (cdr at) 2)))
14975 (org-back-to-heading))
14976 (setq beg (point) end (progn (outline-next-heading) (point))
14977 msg (if at "Creating image...%s"
14978 "Creating images for entry...%s"))))
14979 (message msg "")
14980 (narrow-to-region beg end)
14981 (org-format-latex
14982 (concat "ltxpng/" (file-name-sans-extension
14983 (file-name-nondirectory
14984 buffer-file-name)))
14985 default-directory 'overlays msg at)
14986 (message msg "done. Use `C-c C-c' to remove images.")))))
14988 (defvar org-latex-regexps
14989 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14990 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14991 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14992 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
14993 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14994 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
14995 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
14996 "Regular expressions for matching embedded LaTeX.")
14998 (defun org-format-latex (prefix &optional dir overlays msg at)
14999 "Replace LaTeX fragments with links to an image, and produce images."
15000 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15001 (let* ((prefixnodir (file-name-nondirectory prefix))
15002 (absprefix (expand-file-name prefix dir))
15003 (todir (file-name-directory absprefix))
15004 (opt org-format-latex-options)
15005 (matchers (plist-get opt :matchers))
15006 (re-list org-latex-regexps)
15007 (cnt 0) txt link beg end re e oldfiles
15008 m n block linkfile movefile ov)
15009 ;; Make sure the directory exists
15010 (or (file-directory-p todir) (make-directory todir))
15011 ;; Check if there are old images files with this prefix, and remove them
15012 (setq oldfiles (directory-files
15013 todir 'full
15014 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15015 (while oldfiles (delete-file (pop oldfiles)))
15016 ;; Check the different regular expressions
15017 (while (setq e (pop re-list))
15018 (setq m (car e) re (nth 1 e) n (nth 2 e)
15019 block (if (nth 3 e) "\n\n" ""))
15020 (when (member m matchers)
15021 (goto-char (point-min))
15022 (while (re-search-forward re nil t)
15023 (when (or (not at) (equal (cdr at) (match-beginning n)))
15024 (setq txt (match-string n)
15025 beg (match-beginning n) end (match-end n)
15026 cnt (1+ cnt)
15027 linkfile (format "%s_%04d.png" prefix cnt)
15028 movefile (format "%s_%04d.png" absprefix cnt)
15029 link (concat block "[[file:" linkfile "]]" block))
15030 (if msg (message msg cnt))
15031 (goto-char beg)
15032 (org-create-formula-image
15033 txt movefile opt)
15034 (if overlays
15035 (progn
15036 (setq ov (org-make-overlay beg end))
15037 (if (featurep 'xemacs)
15038 (progn
15039 (org-overlay-put ov 'invisible t)
15040 (org-overlay-put
15041 ov 'end-glyph
15042 (make-glyph (vector 'png :file movefile))))
15043 (org-overlay-put
15044 ov 'display
15045 (list 'image :type 'png :file movefile :ascent 'center)))
15046 (push ov org-latex-fragment-image-overlays)
15047 (goto-char end))
15048 (delete-region beg end)
15049 (insert link))))))))
15051 ;; This function borrows from Ganesh Swami's latex2png.el
15052 (defun org-create-formula-image (string tofile options)
15053 (let* ((tmpdir (if (featurep 'xemacs)
15054 (temp-directory)
15055 temporary-file-directory))
15056 (texfilebase (make-temp-name
15057 (expand-file-name "orgtex" tmpdir)))
15059 ;(texfilebase (make-temp-file "orgtex"))
15060 ; (dummy (delete-file texfilebase))
15061 (texfile (concat texfilebase ".tex"))
15062 (dvifile (concat texfilebase ".dvi"))
15063 (pngfile (concat texfilebase ".png"))
15064 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15065 (fg (or (plist-get options :foreground) "Black"))
15066 (bg (or (plist-get options :background) "Transparent")))
15067 (with-temp-file texfile
15068 (insert "\\documentclass{article}
15069 \\usepackage{fullpage}
15070 \\usepackage{amssymb}
15071 \\usepackage[usenames]{color}
15072 \\usepackage{amsmath}
15073 \\usepackage{latexsym}
15074 \\usepackage[mathscr]{eucal}
15075 \\pagestyle{empty}
15076 \\begin{document}\n" string "\n\\end{document}\n"))
15077 (let ((dir default-directory))
15078 (condition-case nil
15079 (progn
15080 (cd tmpdir)
15081 (call-process "latex" nil nil nil texfile))
15082 (error nil))
15083 (cd dir))
15084 (if (not (file-exists-p dvifile))
15085 (progn (message "Failed to create dvi file from %s" texfile) nil)
15086 (call-process "dvipng" nil nil nil
15087 "-E" "-fg" fg "-bg" bg
15088 "-x" scale "-y" scale "-T" "tight"
15089 "-o" pngfile
15090 dvifile)
15091 (if (not (file-exists-p pngfile))
15092 (progn (message "Failed to create png file from %s" texfile) nil)
15093 ;; Use the requested file name and clean up
15094 (copy-file pngfile tofile 'replace)
15095 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15096 (delete-file (concat texfilebase e)))
15097 pngfile))))
15099 ;;;; Exporting
15101 ;;; Variables, constants, and parameter plists
15103 (defconst org-level-max 20)
15105 (defvar org-export-html-preamble nil
15106 "Preamble, to be inserted just after <body>. Set by publishing functions.")
15107 (defvar org-export-html-postamble nil
15108 "Preamble, to be inserted just before </body>. Set by publishing functions.")
15109 (defvar org-export-html-auto-preamble t
15110 "Should default preamble be inserted? Set by publishing functions.")
15111 (defvar org-export-html-auto-postamble t
15112 "Should default postamble be inserted? Set by publishing functions.")
15113 (defvar org-current-export-file nil) ; dynamically scoped parameter
15114 (defvar org-current-export-dir nil) ; dynamically scoped parameter
15117 (defconst org-export-plist-vars
15118 '((:language . org-export-default-language)
15119 (:customtime . org-display-custom-times)
15120 (:headline-levels . org-export-headline-levels)
15121 (:section-numbers . org-export-with-section-numbers)
15122 (:table-of-contents . org-export-with-toc)
15123 (:archived-trees . org-export-with-archived-trees)
15124 (:emphasize . org-export-with-emphasize)
15125 (:sub-superscript . org-export-with-sub-superscripts)
15126 (:TeX-macros . org-export-with-TeX-macros)
15127 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
15128 (:fixed-width . org-export-with-fixed-width)
15129 (:timestamps . org-export-with-timestamps)
15130 (:tables . org-export-with-tables)
15131 (:table-auto-headline . org-export-highlight-first-table-line)
15132 (:style . org-export-html-style)
15133 (:convert-org-links . org-export-html-link-org-files-as-html)
15134 (:inline-images . org-export-html-inline-images)
15135 (:expand-quoted-html . org-export-html-expand)
15136 (:timestamp . org-export-html-with-timestamp)
15137 (:publishing-directory . org-export-publishing-directory)
15138 (:preamble . org-export-html-preamble)
15139 (:postamble . org-export-html-postamble)
15140 (:auto-preamble . org-export-html-auto-preamble)
15141 (:auto-postamble . org-export-html-auto-postamble)
15142 (:author . user-full-name)
15143 (:email . user-mail-address)))
15145 (defun org-default-export-plist ()
15146 "Return the property list with default settings for the export variables."
15147 (let ((l org-export-plist-vars) rtn e)
15148 (while (setq e (pop l))
15149 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
15150 rtn))
15152 (defun org-infile-export-plist ()
15153 "Return the property list with file-local settings for export."
15154 (save-excursion
15155 (goto-char 0)
15156 (let ((re (org-make-options-regexp
15157 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
15158 p key val text options)
15159 (while (re-search-forward re nil t)
15160 (setq key (org-match-string-no-properties 1)
15161 val (org-match-string-no-properties 2))
15162 (cond
15163 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
15164 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
15165 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
15166 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
15167 ((string-equal key "TEXT")
15168 (setq text (if text (concat text "\n" val) val)))
15169 ((string-equal key "OPTIONS") (setq options val))))
15170 (setq p (plist-put p :text text))
15171 (when options
15172 (let ((op '(("H" . :headline-levels)
15173 ("num" . :section-numbers)
15174 ("toc" . :table-of-contents)
15175 ("\\n" . :preserve-breaks)
15176 ("@" . :expand-quoted-html)
15177 (":" . :fixed-width)
15178 ("|" . :tables)
15179 ("^" . :sub-superscript)
15180 ("*" . :emphasize)
15181 ("TeX" . :TeX-macros)
15182 ("LaTeX" . :LaTeX-fragments)))
15184 (while (setq o (pop op))
15185 (if (string-match (concat (regexp-quote (car o))
15186 ":\\([^ \t\n\r;,.]*\\)")
15187 options)
15188 (setq p (plist-put p (cdr o)
15189 (car (read-from-string
15190 (match-string 1 options)))))))))
15191 p)))
15193 (defun org-combine-plists (&rest plists)
15194 "Create a single property list from all plists in PLISTS.
15195 The process starts by copying the last list, and then setting properties
15196 from the other lists. Settings in the first list are the most significant
15197 ones and overrule settings in the other lists."
15198 (let ((rtn (copy-sequence (pop plists)))
15199 p v ls)
15200 (while plists
15201 (setq ls (pop plists))
15202 (while ls
15203 (setq p (pop ls) v (pop ls))
15204 (setq rtn (plist-put rtn p v))))
15205 rtn))
15207 (defun org-export-directory (type plist)
15208 (let* ((val (plist-get plist :publishing-directory))
15209 (dir (if (listp val)
15210 (or (cdr (assoc type val)) ".")
15211 val)))
15212 dir))
15214 (defun org-export-find-first-heading-line (list)
15215 "Remove all lines from LIST which are before the first headline."
15216 (let ((orig-list list)
15217 (re (concat "^" outline-regexp)))
15218 (while (and list
15219 (not (string-match re (car list))))
15220 (pop list))
15221 (or list orig-list)))
15223 (defun org-skip-comments (lines)
15224 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
15225 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
15226 (re2 "^\\(\\*+\\)[ \t\n\r]")
15227 rtn line level)
15228 (while (setq line (pop lines))
15229 (cond
15230 ((and (string-match re1 line)
15231 (setq level (- (match-end 1) (match-beginning 1))))
15232 ;; Beginning of a COMMENT subtree. Skip it.
15233 (while (and (setq line (pop lines))
15234 (or (not (string-match re2 line))
15235 (> (- (match-end 1) (match-beginning 1)) level))))
15236 (setq lines (cons line lines)))
15237 ((string-match "^#" line)
15238 ;; an ordinary comment line
15240 ((and org-export-table-remove-special-lines
15241 (string-match "^[ \t]*|" line)
15242 (or (string-match "^[ \t]*| *[!_^] *|" line)
15243 (and (string-match "| *<[0-9]+> *|" line)
15244 (not (string-match "| *[^ <|]" line)))))
15245 ;; a special table line that should be removed
15247 (t (setq rtn (cons line rtn)))))
15248 (nreverse rtn)))
15250 (defun org-export (&optional arg)
15251 (interactive)
15252 (let ((help "[t] insert the export option template
15253 \[v] limit export to visible part of outline tree
15255 \[a] export as ASCII
15256 \[h] export as HTML
15257 \[b] export as HTML and browse immediately
15258 \[x] export as XOXO
15260 \[i] export current file as iCalendar file
15261 \[I] export all agenda files as iCalendar files
15262 \[c] export agenda files into combined iCalendar file
15264 \[F] publish current file
15265 \[P] publish current project
15266 \[X] publish... (project will be prompted for)
15267 \[A] publish all projects")
15268 (cmds
15269 '((?t . org-insert-export-options-template)
15270 (?v . org-export-visible)
15271 (?a . org-export-as-ascii)
15272 (?h . org-export-as-html)
15273 (?b . org-export-as-html-and-open)
15274 (?x . org-export-as-xoxo)
15275 (?i . org-export-icalendar-this-file)
15276 (?I . org-export-icalendar-all-agenda-files)
15277 (?c . org-export-icalendar-combine-agenda-files)
15278 (?F . org-publish-current-file)
15279 (?P . org-publish-current-project)
15280 (?X . org-publish)
15281 (?A . org-publish-all)))
15282 r1 r2 ass)
15283 (save-window-excursion
15284 (delete-other-windows)
15285 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
15286 (princ help))
15287 (message "Select command: ")
15288 (setq r1 (read-char-exclusive)))
15289 (setq r2 (if (< r1 27) (+ r1 96) r1))
15290 (if (setq ass (assq r2 cmds))
15291 (call-interactively (cdr ass))
15292 (error "No command associated with key %c" r1))))
15294 (defconst org-html-entities
15295 '(("nbsp")
15296 ("iexcl")
15297 ("cent")
15298 ("pound")
15299 ("curren")
15300 ("yen")
15301 ("brvbar")
15302 ("sect")
15303 ("uml")
15304 ("copy")
15305 ("ordf")
15306 ("laquo")
15307 ("not")
15308 ("shy")
15309 ("reg")
15310 ("macr")
15311 ("deg")
15312 ("plusmn")
15313 ("sup2")
15314 ("sup3")
15315 ("acute")
15316 ("micro")
15317 ("para")
15318 ("middot")
15319 ("odot"."o")
15320 ("star"."*")
15321 ("cedil")
15322 ("sup1")
15323 ("ordm")
15324 ("raquo")
15325 ("frac14")
15326 ("frac12")
15327 ("frac34")
15328 ("iquest")
15329 ("Agrave")
15330 ("Aacute")
15331 ("Acirc")
15332 ("Atilde")
15333 ("Auml")
15334 ("Aring") ("AA"."&Aring;")
15335 ("AElig")
15336 ("Ccedil")
15337 ("Egrave")
15338 ("Eacute")
15339 ("Ecirc")
15340 ("Euml")
15341 ("Igrave")
15342 ("Iacute")
15343 ("Icirc")
15344 ("Iuml")
15345 ("ETH")
15346 ("Ntilde")
15347 ("Ograve")
15348 ("Oacute")
15349 ("Ocirc")
15350 ("Otilde")
15351 ("Ouml")
15352 ("times")
15353 ("Oslash")
15354 ("Ugrave")
15355 ("Uacute")
15356 ("Ucirc")
15357 ("Uuml")
15358 ("Yacute")
15359 ("THORN")
15360 ("szlig")
15361 ("agrave")
15362 ("aacute")
15363 ("acirc")
15364 ("atilde")
15365 ("auml")
15366 ("aring")
15367 ("aelig")
15368 ("ccedil")
15369 ("egrave")
15370 ("eacute")
15371 ("ecirc")
15372 ("euml")
15373 ("igrave")
15374 ("iacute")
15375 ("icirc")
15376 ("iuml")
15377 ("eth")
15378 ("ntilde")
15379 ("ograve")
15380 ("oacute")
15381 ("ocirc")
15382 ("otilde")
15383 ("ouml")
15384 ("divide")
15385 ("oslash")
15386 ("ugrave")
15387 ("uacute")
15388 ("ucirc")
15389 ("uuml")
15390 ("yacute")
15391 ("thorn")
15392 ("yuml")
15393 ("fnof")
15394 ("Alpha")
15395 ("Beta")
15396 ("Gamma")
15397 ("Delta")
15398 ("Epsilon")
15399 ("Zeta")
15400 ("Eta")
15401 ("Theta")
15402 ("Iota")
15403 ("Kappa")
15404 ("Lambda")
15405 ("Mu")
15406 ("Nu")
15407 ("Xi")
15408 ("Omicron")
15409 ("Pi")
15410 ("Rho")
15411 ("Sigma")
15412 ("Tau")
15413 ("Upsilon")
15414 ("Phi")
15415 ("Chi")
15416 ("Psi")
15417 ("Omega")
15418 ("alpha")
15419 ("beta")
15420 ("gamma")
15421 ("delta")
15422 ("epsilon")
15423 ("varepsilon"."&epsilon;")
15424 ("zeta")
15425 ("eta")
15426 ("theta")
15427 ("iota")
15428 ("kappa")
15429 ("lambda")
15430 ("mu")
15431 ("nu")
15432 ("xi")
15433 ("omicron")
15434 ("pi")
15435 ("rho")
15436 ("sigmaf") ("varsigma"."&sigmaf;")
15437 ("sigma")
15438 ("tau")
15439 ("upsilon")
15440 ("phi")
15441 ("chi")
15442 ("psi")
15443 ("omega")
15444 ("thetasym") ("vartheta"."&thetasym;")
15445 ("upsih")
15446 ("piv")
15447 ("bull") ("bullet"."&bull;")
15448 ("hellip") ("dots"."&hellip;")
15449 ("prime")
15450 ("Prime")
15451 ("oline")
15452 ("frasl")
15453 ("weierp")
15454 ("image")
15455 ("real")
15456 ("trade")
15457 ("alefsym")
15458 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
15459 ("uarr") ("uparrow"."&uarr;")
15460 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
15461 ("darr")("downarrow"."&darr;")
15462 ("harr") ("leftrightarrow"."&harr;")
15463 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
15464 ("lArr") ("Leftarrow"."&lArr;")
15465 ("uArr") ("Uparrow"."&uArr;")
15466 ("rArr") ("Rightarrow"."&rArr;")
15467 ("dArr") ("Downarrow"."&dArr;")
15468 ("hArr") ("Leftrightarrow"."&hArr;")
15469 ("forall")
15470 ("part") ("partial"."&part;")
15471 ("exist") ("exists"."&exist;")
15472 ("empty") ("emptyset"."&empty;")
15473 ("nabla")
15474 ("isin") ("in"."&isin;")
15475 ("notin")
15476 ("ni")
15477 ("prod")
15478 ("sum")
15479 ("minus")
15480 ("lowast") ("ast"."&lowast;")
15481 ("radic")
15482 ("prop") ("proptp"."&prop;")
15483 ("infin") ("infty"."&infin;")
15484 ("ang") ("angle"."&ang;")
15485 ("and") ("vee"."&and;")
15486 ("or") ("wedge"."&or;")
15487 ("cap")
15488 ("cup")
15489 ("int")
15490 ("there4")
15491 ("sim")
15492 ("cong") ("simeq"."&cong;")
15493 ("asymp")("approx"."&asymp;")
15494 ("ne") ("neq"."&ne;")
15495 ("equiv")
15496 ("le")
15497 ("ge")
15498 ("sub") ("subset"."&sub;")
15499 ("sup") ("supset"."&sup;")
15500 ("nsub")
15501 ("sube")
15502 ("supe")
15503 ("oplus")
15504 ("otimes")
15505 ("perp")
15506 ("sdot") ("cdot"."&sdot;")
15507 ("lceil")
15508 ("rceil")
15509 ("lfloor")
15510 ("rfloor")
15511 ("lang")
15512 ("rang")
15513 ("loz") ("Diamond"."&loz;")
15514 ("spades") ("spadesuit"."&spades;")
15515 ("clubs") ("clubsuit"."&clubs;")
15516 ("hearts") ("diamondsuit"."&hearts;")
15517 ("diams") ("diamondsuit"."&diams;")
15518 ("quot")
15519 ("amp")
15520 ("lt")
15521 ("gt")
15522 ("OElig")
15523 ("oelig")
15524 ("Scaron")
15525 ("scaron")
15526 ("Yuml")
15527 ("circ")
15528 ("tilde")
15529 ("ensp")
15530 ("emsp")
15531 ("thinsp")
15532 ("zwnj")
15533 ("zwj")
15534 ("lrm")
15535 ("rlm")
15536 ("ndash")
15537 ("mdash")
15538 ("lsquo")
15539 ("rsquo")
15540 ("sbquo")
15541 ("ldquo")
15542 ("rdquo")
15543 ("bdquo")
15544 ("dagger")
15545 ("Dagger")
15546 ("permil")
15547 ("lsaquo")
15548 ("rsaquo")
15549 ("euro")
15551 ("arccos"."arccos")
15552 ("arcsin"."arcsin")
15553 ("arctan"."arctan")
15554 ("arg"."arg")
15555 ("cos"."cos")
15556 ("cosh"."cosh")
15557 ("cot"."cot")
15558 ("coth"."coth")
15559 ("csc"."csc")
15560 ("deg"."deg")
15561 ("det"."det")
15562 ("dim"."dim")
15563 ("exp"."exp")
15564 ("gcd"."gcd")
15565 ("hom"."hom")
15566 ("inf"."inf")
15567 ("ker"."ker")
15568 ("lg"."lg")
15569 ("lim"."lim")
15570 ("liminf"."liminf")
15571 ("limsup"."limsup")
15572 ("ln"."ln")
15573 ("log"."log")
15574 ("max"."max")
15575 ("min"."min")
15576 ("Pr"."Pr")
15577 ("sec"."sec")
15578 ("sin"."sin")
15579 ("sinh"."sinh")
15580 ("sup"."sup")
15581 ("tan"."tan")
15582 ("tanh"."tanh")
15584 "Entities for TeX->HTML translation.
15585 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
15586 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
15587 In that case, \"\\ent\" will be translated to \"&other;\".
15588 The list contains HTML entities for Latin-1, Greek and other symbols.
15589 It is supplemented by a number of commonly used TeX macros with appropriate
15590 translations. There is currently no way for users to extend this.")
15592 ;;; General functions for all backends
15594 (defun org-cleaned-string-for-export (string &rest parameters)
15595 "Cleanup a buffer substring so that links can be created safely."
15596 (interactive)
15597 (let* ((re-radio (and org-target-link-regexp
15598 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
15599 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
15600 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
15601 (re-archive (concat ":" org-archive-tag ":"))
15602 rtn)
15603 (save-excursion
15604 (set-buffer (get-buffer-create " org-mode-tmp"))
15605 (erase-buffer)
15606 (insert string)
15607 (let ((org-inhibit-startup t)) (org-mode))
15608 (untabify (point-min) (point-max))
15610 ;; Get rid of archived trees
15611 (when (not (eq org-export-with-archived-trees t))
15612 (goto-char (point-min))
15613 (while (re-search-forward re-archive nil t)
15614 (if (not (org-on-heading-p))
15615 (org-end-of-subtree t)
15616 (beginning-of-line 1)
15617 (delete-region
15618 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
15619 (org-end-of-subtree t)))))
15621 ;; Find targets in comments and move them out of comments,
15622 ;; but mark them as targets that should be invisible
15623 (goto-char (point-min))
15624 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
15625 (replace-match "\\1(INVISIBLE)"))
15627 ;; Remove comments
15628 (goto-char (point-min))
15629 (while (re-search-forward "^#.*\n?" nil t)
15630 (replace-match ""))
15632 ;; Find matches for radio targets and turn them into internal links
15633 (goto-char (point-min))
15634 (when re-radio
15635 (while (re-search-forward re-radio nil t)
15636 (replace-match "\\1[[\\2]]")))
15638 ;; Find all links that contain a newline and put them into a single line
15639 (goto-char (point-min))
15640 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
15641 (replace-match "\\1 \\3")
15642 (goto-char (match-beginning 0)))
15644 ;; Convert LaTeX fragments to images
15645 (when (memq :LaTeX-fragments parameters)
15646 (org-format-latex
15647 (concat "ltxpng/" (file-name-sans-extension
15648 (file-name-nondirectory
15649 org-current-export-file)))
15650 org-current-export-dir nil "Creating LaTeX image %s"))
15651 (message "Exporting...")
15653 ;; Normalize links: Convert angle and plain links into bracket links
15654 ;; Expand link abbreviations
15655 (goto-char (point-min))
15656 (while (re-search-forward re-plain-link nil t)
15657 (replace-match
15658 (concat
15659 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
15660 t t))
15661 (goto-char (point-min))
15662 (while (re-search-forward re-angle-link nil t)
15663 (replace-match
15664 (concat
15665 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
15666 t t))
15667 (goto-char (point-min))
15668 (while (re-search-forward org-bracket-link-regexp nil t)
15669 (replace-match
15670 (concat "[[" (save-match-data
15671 (org-link-expand-abbrev (match-string 1)))
15673 (if (match-end 3)
15674 (match-string 2)
15675 (concat "[" (match-string 1) "]"))
15676 "]")
15677 t t))
15679 ;; Find multiline emphasis and put them into single line
15680 (when (memq :emph-multiline parameters)
15681 (goto-char (point-min))
15682 (while (re-search-forward org-emph-re nil t)
15683 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
15684 (goto-char (1- (match-end 0)))))
15686 (setq rtn (buffer-string)))
15687 (kill-buffer " org-mode-tmp")
15688 rtn))
15690 (defun org-solidify-link-text (s &optional alist)
15691 "Take link text and make a safe target out of it."
15692 (save-match-data
15693 (let* ((rtn
15694 (mapconcat
15695 'identity
15696 (org-split-string s "[ \t\r\n]+") "--"))
15697 (a (assoc rtn alist)))
15698 (or (cdr a) rtn))))
15700 ;; Variable holding the vector with section numbers
15701 (defvar org-section-numbers (make-vector org-level-max 0))
15703 (defun org-init-section-numbers ()
15704 "Initialize the vector for the section numbers."
15705 (let* ((level -1)
15706 (numbers (nreverse (org-split-string "" "\\.")))
15707 (depth (1- (length org-section-numbers)))
15708 (i depth) number-string)
15709 (while (>= i 0)
15710 (if (> i level)
15711 (aset org-section-numbers i 0)
15712 (setq number-string (or (car numbers) "0"))
15713 (if (string-match "\\`[A-Z]\\'" number-string)
15714 (aset org-section-numbers i
15715 (- (string-to-char number-string) ?A -1))
15716 (aset org-section-numbers i (string-to-number number-string)))
15717 (pop numbers))
15718 (setq i (1- i)))))
15720 (defun org-section-number (&optional level)
15721 "Return a string with the current section number.
15722 When LEVEL is non-nil, increase section numbers on that level."
15723 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
15724 (when level
15725 (when (> level -1)
15726 (aset org-section-numbers
15727 level (1+ (aref org-section-numbers level))))
15728 (setq idx (1+ level))
15729 (while (<= idx depth)
15730 (if (not (= idx 1))
15731 (aset org-section-numbers idx 0))
15732 (setq idx (1+ idx))))
15733 (setq idx 0)
15734 (while (<= idx depth)
15735 (setq n (aref org-section-numbers idx))
15736 (setq string (concat string (if (not (string= string "")) "." "")
15737 (int-to-string n)))
15738 (setq idx (1+ idx)))
15739 (save-match-data
15740 (if (string-match "\\`\\([@0]\\.\\)+" string)
15741 (setq string (replace-match "" t nil string)))
15742 (if (string-match "\\(\\.0\\)+\\'" string)
15743 (setq string (replace-match "" t nil string))))
15744 string))
15746 ;;; ASCII export
15748 (defvar org-last-level nil) ; dynamically scoped variable
15749 (defvar org-levels-open nil) ; dynamically scoped parameter
15750 (defvar org-ascii-current-indentation nil) ; For communication
15752 (defun org-export-as-ascii (arg)
15753 "Export the outline as a pretty ASCII file.
15754 If there is an active region, export only the region.
15755 The prefix ARG specifies how many levels of the outline should become
15756 underlined headlines. The default is 3."
15757 (interactive "P")
15758 (setq-default org-todo-line-regexp org-todo-line-regexp)
15759 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15760 (org-infile-export-plist)))
15761 (region
15762 (buffer-substring
15763 (if (org-region-active-p) (region-beginning) (point-min))
15764 (if (org-region-active-p) (region-end) (point-max))))
15765 (custom-times org-display-custom-times)
15766 (lines (org-export-find-first-heading-line
15767 (org-skip-comments
15768 (org-split-string
15769 (org-cleaned-string-for-export region)
15770 "[\r\n]"))))
15771 (org-ascii-current-indentation '(0 . 0))
15772 (org-startup-with-deadline-check nil)
15773 (level 0) line txt
15774 (umax nil)
15775 (case-fold-search nil)
15776 (filename (concat (file-name-as-directory
15777 (org-export-directory :ascii opt-plist))
15778 (file-name-sans-extension
15779 (file-name-nondirectory buffer-file-name))
15780 ".txt"))
15781 (buffer (find-file-noselect filename))
15782 (org-levels-open (make-vector org-level-max nil))
15783 (odd org-odd-levels-only)
15784 (date (format-time-string "%Y/%m/%d" (current-time)))
15785 (time (format-time-string "%X" (org-current-time)))
15786 (author (plist-get opt-plist :author))
15787 (title (or (plist-get opt-plist :title)
15788 (file-name-sans-extension
15789 (file-name-nondirectory buffer-file-name))))
15790 (email (plist-get opt-plist :email))
15791 (language (plist-get opt-plist :language))
15792 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
15793 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
15794 (text nil)
15795 (todo nil)
15796 (lang-words nil))
15798 (setq org-last-level 1)
15799 (org-init-section-numbers)
15801 (find-file-noselect filename)
15803 (setq lang-words (or (assoc language org-export-language-setup)
15804 (assoc "en" org-export-language-setup)))
15805 (if org-export-ascii-show-new-buffer
15806 (switch-to-buffer-other-window buffer)
15807 (set-buffer buffer))
15808 (erase-buffer)
15809 (fundamental-mode)
15810 ;; create local variables for all options, to make sure all called
15811 ;; functions get the correct information
15812 (mapcar (lambda (x)
15813 (set (make-local-variable (cdr x))
15814 (plist-get opt-plist (car x))))
15815 org-export-plist-vars)
15816 (org-set-local 'org-odd-levels-only odd)
15817 (setq umax (if arg (prefix-numeric-value arg)
15818 org-export-headline-levels))
15820 ;; File header
15821 (if title (org-insert-centered title ?=))
15822 (insert "\n")
15823 (if (or author email)
15824 (insert (concat (nth 1 lang-words) ": " (or author "")
15825 (if email (concat " <" email ">") "")
15826 "\n")))
15827 (if (and date time)
15828 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
15829 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
15831 (insert "\n\n")
15833 (if org-export-with-toc
15834 (progn
15835 (insert (nth 3 lang-words) "\n"
15836 (make-string (length (nth 3 lang-words)) ?=) "\n")
15837 (mapcar '(lambda (line)
15838 (if (string-match org-todo-line-regexp
15839 line)
15840 ;; This is a headline
15841 (progn
15842 (setq level (- (match-end 1) (match-beginning 1))
15843 level (org-tr-level level)
15844 txt (match-string 3 line)
15845 todo
15846 (or (and org-export-mark-todo-in-toc
15847 (match-beginning 2)
15848 (not (equal (match-string 2 line)
15849 org-done-string)))
15850 ; TODO, not DONE
15851 (and org-export-mark-todo-in-toc
15852 (= level umax)
15853 (org-search-todo-below
15854 line lines level))))
15855 (setq txt (org-html-expand-for-ascii txt))
15857 (if (and (memq org-export-with-tags '(not-in-toc nil))
15858 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
15859 (setq txt (replace-match "" t t txt)))
15860 (if (string-match quote-re0 txt)
15861 (setq txt (replace-match "" t t txt)))
15863 (if org-export-with-section-numbers
15864 (setq txt (concat (org-section-number level)
15865 " " txt)))
15866 (if (<= level umax)
15867 (progn
15868 (insert
15869 (make-string (* (1- level) 4) ?\ )
15870 (format (if todo "%s (*)\n" "%s\n") txt))
15871 (setq org-last-level level))
15872 ))))
15873 lines)))
15875 (org-init-section-numbers)
15876 (while (setq line (pop lines))
15877 ;; Remove the quoted HTML tags.
15878 (setq line (org-html-expand-for-ascii line))
15879 ;; Remove targets
15880 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
15881 (setq line (replace-match "" t t line)))
15882 ;; Replace internal links
15883 (while (string-match org-bracket-link-regexp line)
15884 (setq line (replace-match
15885 (if (match-end 3) "[\\3]" "[\\1]")
15886 t nil line)))
15887 (when custom-times
15888 (setq line (org-translate-time line)))
15889 (cond
15890 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
15891 ;; a Headline
15892 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
15893 txt (match-string 2 line))
15894 (org-ascii-level-start level txt umax lines))
15896 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
15897 (normal-mode)
15898 (save-buffer)
15899 ;; remove display and invisible chars
15900 (let (beg end)
15901 (goto-char (point-min))
15902 (while (setq beg (next-single-property-change (point) 'display))
15903 (setq end (next-single-property-change beg 'display))
15904 (delete-region beg end)
15905 (goto-char beg)
15906 (insert "=>"))
15907 (goto-char (point-min))
15908 (while (setq beg (next-single-property-change (point) 'org-cwidth))
15909 (setq end (next-single-property-change beg 'org-cwidth))
15910 (delete-region beg end)
15911 (goto-char beg)))
15912 (goto-char (point-min))))
15914 (defun org-search-todo-below (line lines level)
15915 "Search the subtree below LINE for any TODO entries."
15916 (let ((rest (cdr (memq line lines)))
15917 (re org-todo-line-regexp)
15918 line lv todo)
15919 (catch 'exit
15920 (while (setq line (pop rest))
15921 (if (string-match re line)
15922 (progn
15923 (setq lv (- (match-end 1) (match-beginning 1))
15924 todo (and (match-beginning 2)
15925 (not (equal (match-string 2 line)
15926 org-done-string))))
15927 ; TODO, not DONE
15928 (if (<= lv level) (throw 'exit nil))
15929 (if todo (throw 'exit t))))))))
15931 (defun org-html-expand-for-ascii (line)
15932 "Handle quoted HTML for ASCII export."
15933 (if org-export-html-expand
15934 (while (string-match "@<[^<>\n]*>" line)
15935 ;; We just remove the tags for now.
15936 (setq line (replace-match "" nil nil line))))
15937 line)
15939 (defun org-insert-centered (s &optional underline)
15940 "Insert the string S centered and underline it with character UNDERLINE."
15941 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
15942 (insert (make-string ind ?\ ) s "\n")
15943 (if underline
15944 (insert (make-string ind ?\ )
15945 (make-string (string-width s) underline)
15946 "\n"))))
15948 (defun org-ascii-level-start (level title umax &optional lines)
15949 "Insert a new level in ASCII export."
15950 (let (char (n (- level umax 1)) (ind 0))
15951 (if (> level umax)
15952 (progn
15953 (insert (make-string (* 2 n) ?\ )
15954 (char-to-string (nth (% n (length org-export-ascii-bullets))
15955 org-export-ascii-bullets))
15956 " " title "\n")
15957 ;; find the indentation of the next non-empty line
15958 (catch 'stop
15959 (while lines
15960 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
15961 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
15962 (throw 'stop (setq ind (org-get-indentation (car lines)))))
15963 (pop lines)))
15964 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
15965 (if (or (not (equal (char-before) ?\n))
15966 (not (equal (char-before (1- (point))) ?\n)))
15967 (insert "\n"))
15968 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
15969 (unless org-export-with-tags
15970 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
15971 (setq title (replace-match "" t t title))))
15972 (if org-export-with-section-numbers
15973 (setq title (concat (org-section-number level) " " title)))
15974 (insert title "\n" (make-string (string-width title) char) "\n")
15975 (setq org-ascii-current-indentation '(0 . 0)))))
15977 (defun org-export-visible (type arg)
15978 "Create a copy of the visible part of the current buffer, and export it.
15979 The copy is created in a temporary buffer and removed after use.
15980 TYPE is the final key (as a string) that also select the export command in
15981 the `C-c C-e' export dispatcher.
15982 As a special case, if the you type SPC at the prompt, the temporary
15983 org-mode file will not be removed but presented to you so that you can
15984 continue to use it. The prefix arg ARG is passed through to the exporting
15985 command."
15986 (interactive
15987 (list (progn
15988 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
15989 (read-char-exclusive))
15990 current-prefix-arg))
15991 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
15992 (error "Invalid export key"))
15993 (let* ((binding (cdr (assoc type
15994 '((?a . org-export-as-ascii)
15995 (?\C-a . org-export-as-ascii)
15996 (?b . org-export-as-html-and-open)
15997 (?\C-b . org-export-as-html-and-open)
15998 (?h . org-export-as-html)
15999 (?x . org-export-as-xoxo)))))
16000 (keepp (equal type ?\ ))
16001 (file buffer-file-name)
16002 (buffer (get-buffer-create "*Org Export Visible*"))
16003 s e)
16004 (with-current-buffer buffer (erase-buffer))
16005 (save-excursion
16006 (setq s (goto-char (point-min)))
16007 (while (not (= (point) (point-max)))
16008 (goto-char (org-find-invisible))
16009 (append-to-buffer buffer s (point))
16010 (setq s (goto-char (org-find-visible))))
16011 (goto-char (point-min))
16012 (unless keepp
16013 ;; Copy all comment lines to the end, to make sure #+ settings are
16014 ;; still available for the second export step. Kind of a hack, but
16015 ;; does do the trick.
16016 (if (looking-at "#[^\r\n]*")
16017 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
16018 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
16019 (append-to-buffer buffer (1+ (match-beginning 0))
16020 (min (point-max) (1+ (match-end 0))))))
16021 (set-buffer buffer)
16022 (let ((buffer-file-name file)
16023 (org-inhibit-startup t))
16024 (org-mode)
16025 (show-all)
16026 (unless keepp (funcall binding arg))))
16027 (if (not keepp)
16028 (kill-buffer buffer)
16029 (switch-to-buffer-other-window buffer)
16030 (goto-char (point-min)))))
16032 (defun org-find-visible ()
16033 (let ((s (point)))
16034 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
16035 (get-char-property s 'invisible)))
16037 (defun org-find-invisible ()
16038 (let ((s (point)))
16039 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
16040 (not (get-char-property s 'invisible))))
16043 ;;; HTML export
16045 (defun org-get-current-options ()
16046 "Return a string with current options as keyword options.
16047 Does include HTML export options as well as TODO and CATEGORY stuff."
16048 (format
16049 "#+TITLE: %s
16050 #+AUTHOR: %s
16051 #+EMAIL: %s
16052 #+LANGUAGE: %s
16053 #+TEXT: Some descriptive text to be emitted. Several lines OK.
16054 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
16055 #+CATEGORY: %s
16056 #+SEQ_TODO: %s
16057 #+TYP_TODO: %s
16058 #+STARTUP: %s %s %s %s %s %s
16059 #+TAGS: %s
16060 #+ARCHIVE: %s
16061 #+LINK: %s
16063 (buffer-name) (user-full-name) user-mail-address org-export-default-language
16064 org-export-headline-levels
16065 org-export-with-section-numbers
16066 org-export-with-toc
16067 org-export-preserve-breaks
16068 org-export-html-expand
16069 org-export-with-fixed-width
16070 org-export-with-tables
16071 org-export-with-sub-superscripts
16072 org-export-with-emphasize
16073 org-export-with-TeX-macros
16074 org-export-with-LaTeX-fragments
16075 (file-name-nondirectory buffer-file-name)
16076 (if (equal org-todo-interpretation 'sequence)
16077 (mapconcat 'identity org-todo-keywords " ")
16078 "TODO FEEDBACK VERIFY DONE")
16079 (if (equal org-todo-interpretation 'type)
16080 (mapconcat 'identity org-todo-keywords " ")
16081 "Me Jason Marie DONE")
16082 (cdr (assoc org-startup-folded
16083 '((nil . "showall") (t . "overview") (content . "content"))))
16084 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
16085 (if org-odd-levels-only "odd" "oddeven")
16086 (if org-hide-leading-stars "hidestars" "showstars")
16087 (if org-startup-align-all-tables "align" "noalign")
16088 (cond ((eq t org-log-done) "logdone")
16089 ((not org-log-done) "nologging")
16090 ((listp org-log-done)
16091 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
16092 org-log-done " ")))
16093 (or (mapconcat (lambda (x)
16094 (cond
16095 ((equal '(:startgroup) x) "{")
16096 ((equal '(:endgroup) x) "}")
16097 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
16098 (t (car x))))
16099 (or org-tag-alist (org-get-buffer-tags)) " ") "")
16100 org-archive-location
16101 "org file:~/org/%s.org"
16104 (defun org-insert-export-options-template ()
16105 "Insert into the buffer a template with information for exporting."
16106 (interactive)
16107 (if (not (bolp)) (newline))
16108 (let ((s (org-get-current-options)))
16109 (and (string-match "#\\+CATEGORY" s)
16110 (setq s (substring s 0 (match-beginning 0))))
16111 (insert s)))
16113 (defun org-toggle-fixed-width-section (arg)
16114 "Toggle the fixed-width export.
16115 If there is no active region, the QUOTE keyword at the current headline is
16116 inserted or removed. When present, it causes the text between this headline
16117 and the next to be exported as fixed-width text, and unmodified.
16118 If there is an active region, this command adds or removes a colon as the
16119 first character of this line. If the first character of a line is a colon,
16120 this line is also exported in fixed-width font."
16121 (interactive "P")
16122 (let* ((cc 0)
16123 (regionp (org-region-active-p))
16124 (beg (if regionp (region-beginning) (point)))
16125 (end (if regionp (region-end)))
16126 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16127 (re "[ \t]*\\(:\\)")
16128 off)
16129 (if regionp
16130 (save-excursion
16131 (goto-char beg)
16132 (setq cc (current-column))
16133 (beginning-of-line 1)
16134 (setq off (looking-at re))
16135 (while (> nlines 0)
16136 (setq nlines (1- nlines))
16137 (beginning-of-line 1)
16138 (cond
16139 (arg
16140 (move-to-column cc t)
16141 (insert ":\n")
16142 (forward-line -1))
16143 ((and off (looking-at re))
16144 (replace-match "" t t nil 1))
16145 ((not off) (move-to-column cc t) (insert ":")))
16146 (forward-line 1)))
16147 (save-excursion
16148 (org-back-to-heading)
16149 (if (looking-at (concat outline-regexp
16150 "\\( +\\<" org-quote-string "\\>\\)"))
16151 (replace-match "" t t nil 1)
16152 (if (looking-at outline-regexp)
16153 (progn
16154 (goto-char (match-end 0))
16155 (insert " " org-quote-string))))))))
16157 (defun org-export-as-html-and-open (arg)
16158 "Export the outline as HTML and immediately open it with a browser.
16159 If there is an active region, export only the region.
16160 The prefix ARG specifies how many levels of the outline should become
16161 headlines. The default is 3. Lower levels will become bulleted lists."
16162 (interactive "P")
16163 (org-export-as-html arg 'hidden)
16164 (org-open-file buffer-file-name))
16166 (defun org-export-as-html-batch ()
16167 "Call `org-export-as-html', may be used in batch processing as
16168 emacs --batch
16169 --load=$HOME/lib/emacs/org.el
16170 --eval \"(setq org-export-headline-levels 2)\"
16171 --visit=MyFile --funcall org-export-as-html-batch"
16172 (org-export-as-html org-export-headline-levels 'hidden))
16174 (defun org-export-as-html (arg &optional hidden ext-plist)
16175 "Export the outline as a pretty HTML file.
16176 If there is an active region, export only the region.
16177 The prefix ARG specifies how many levels of the outline should become
16178 headlines. The default is 3. Lower levels will become bulleted lists.
16179 When HIDDEN is non-nil, don't display the HTML buffer.
16180 EXT-PLIST is a property list with external parameters overriding
16181 org-mode's default settings, but still inferior to file-local settings."
16182 (interactive "P")
16183 (message "Exporting...")
16184 (setq-default org-todo-line-regexp org-todo-line-regexp)
16185 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
16186 (setq-default org-done-string org-done-string)
16187 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
16188 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
16189 ext-plist
16190 (org-infile-export-plist)))
16192 (style (plist-get opt-plist :style))
16193 (link-validate (plist-get opt-plist :link-validation-function))
16194 valid
16195 (odd org-odd-levels-only)
16196 (region-p (org-region-active-p))
16197 (region
16198 (buffer-substring
16199 (if region-p (region-beginning) (point-min))
16200 (if region-p (region-end) (point-max))))
16201 ;; The following two are dynamically scoped into other
16202 ;; routines below.
16203 (org-current-export-dir (org-export-directory :html opt-plist))
16204 (org-current-export-file buffer-file-name)
16205 (all_lines
16206 (org-skip-comments (org-split-string
16207 (org-cleaned-string-for-export
16208 region :emph-multiline
16209 (if (plist-get opt-plist :LaTeX-fragments)
16210 :LaTeX-fragments))
16211 "[\r\n]")))
16212 (lines (org-export-find-first-heading-line all_lines))
16213 (level 0) (line "") (origline "") txt todo
16214 (umax nil)
16215 (filename (concat (file-name-as-directory
16216 (org-export-directory :html opt-plist))
16217 (file-name-sans-extension
16218 (file-name-nondirectory buffer-file-name))
16219 ".html"))
16220 (current-dir (file-name-directory buffer-file-name))
16221 (buffer (find-file-noselect filename))
16222 (org-levels-open (make-vector org-level-max nil))
16223 (date (format-time-string "%Y/%m/%d" (current-time)))
16224 (time (format-time-string "%X" (org-current-time)))
16225 (author (plist-get opt-plist :author))
16226 (title (or (plist-get opt-plist :title)
16227 (file-name-sans-extension
16228 (file-name-nondirectory buffer-file-name))))
16229 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
16230 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
16231 (inquote nil)
16232 (infixed nil)
16233 (in-local-list nil)
16234 (local-list-num nil)
16235 (local-list-indent nil)
16236 (llt org-plain-list-ordered-item-terminator)
16237 (email (plist-get opt-plist :email))
16238 (language (plist-get opt-plist :language))
16239 (text (plist-get opt-plist :text))
16240 (lang-words nil)
16241 (target-alist nil) tg
16242 (head-count 0) cnt
16243 (start 0)
16244 (coding-system (and (boundp 'buffer-file-coding-system)
16245 buffer-file-coding-system))
16246 (coding-system-for-write coding-system)
16247 (save-buffer-coding-system coding-system)
16248 (charset (and coding-system
16249 (fboundp 'coding-system-get)
16250 (coding-system-get coding-system 'mime-charset)))
16251 table-open type
16252 table-buffer table-orig-buffer
16253 ind start-is-num starter
16254 rpl path desc descp desc1 desc2 link
16256 (message "Exporting...")
16258 (setq org-last-level 1)
16259 (org-init-section-numbers)
16261 ;; Get the language-dependent settings
16262 (setq lang-words (or (assoc language org-export-language-setup)
16263 (assoc "en" org-export-language-setup)))
16265 ;; Switch to the output buffer
16266 (if (or hidden (not org-export-html-show-new-buffer))
16267 (set-buffer buffer)
16268 (switch-to-buffer-other-window buffer))
16269 (erase-buffer)
16270 (fundamental-mode)
16271 (let ((case-fold-search nil)
16272 (org-odd-levels-only odd))
16273 ;; create local variables for all options, to make sure all called
16274 ;; functions get the correct information
16275 (mapcar (lambda (x)
16276 (set (make-local-variable (cdr x))
16277 (plist-get opt-plist (car x))))
16278 org-export-plist-vars)
16279 (setq umax (if arg (prefix-numeric-value arg)
16280 org-export-headline-levels))
16282 ;; File header
16283 (insert (format
16284 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
16285 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
16286 <html xmlns=\"http://www.w3.org/1999/xhtml\"
16287 lang=\"%s\" xml:lang=\"%s\">
16288 <head>
16289 <title>%s</title>
16290 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
16291 <meta name=\"generator\" content=\"Org-mode\"/>
16292 <meta name=\"generated\" content=\"%s %s\"/>
16293 <meta name=\"author\" content=\"%s\"/>
16295 </head><body>
16297 language language (org-html-expand title) (or charset "iso-8859-1")
16298 date time author style))
16301 (insert (or (plist-get opt-plist :preamble) ""))
16303 (when (plist-get opt-plist :auto-preamble)
16304 (if title (insert (format org-export-html-title-format
16305 (org-html-expand title))))
16306 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
16308 (if org-export-with-toc
16309 (progn
16310 (insert (format "<h%d>%s</h%d>\n"
16311 org-export-html-toplevel-hlevel
16312 (nth 3 lang-words)
16313 org-export-html-toplevel-hlevel))
16314 (insert "<ul>\n<li>")
16315 (setq lines
16316 (mapcar '(lambda (line)
16317 (if (string-match org-todo-line-regexp line)
16318 ;; This is a headline
16319 (progn
16320 (setq level (- (match-end 1) (match-beginning 1))
16321 level (org-tr-level level)
16322 txt (save-match-data
16323 (org-html-expand
16324 (org-export-cleanup-toc-line
16325 (match-string 3 line))))
16326 todo
16327 (or (and org-export-mark-todo-in-toc
16328 (match-beginning 2)
16329 (not (equal (match-string 2 line)
16330 org-done-string)))
16331 ; TODO, not DONE
16332 (and org-export-mark-todo-in-toc
16333 (= level umax)
16334 (org-search-todo-below
16335 line lines level))))
16336 (if (and (memq org-export-with-tags '(not-in-toc nil))
16337 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
16338 (setq txt (replace-match "" t t txt)))
16339 (if (string-match quote-re0 txt)
16340 (setq txt (replace-match "" t t txt)))
16341 (if org-export-with-section-numbers
16342 (setq txt (concat (org-section-number level)
16343 " " txt)))
16344 (if (<= level umax)
16345 (progn
16346 (setq head-count (+ head-count 1))
16347 (if (> level org-last-level)
16348 (progn
16349 (setq cnt (- level org-last-level))
16350 (while (>= (setq cnt (1- cnt)) 0)
16351 (insert "\n<ul>\n<li>"))
16352 (insert "\n")))
16353 (if (< level org-last-level)
16354 (progn
16355 (setq cnt (- org-last-level level))
16356 (while (>= (setq cnt (1- cnt)) 0)
16357 (insert "</li>\n</ul>"))
16358 (insert "\n")))
16359 ;; Check for targets
16360 (while (string-match org-target-regexp line)
16361 (setq tg (match-string 1 line)
16362 line (replace-match
16363 (concat "@<span class=\"target\">" tg "@</span> ")
16364 t t line))
16365 (push (cons (org-solidify-link-text tg)
16366 (format "sec-%d" head-count))
16367 target-alist))
16368 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
16369 (setq txt (replace-match "" t t txt)))
16370 (insert
16371 (format
16372 (if todo
16373 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
16374 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
16375 head-count txt))
16377 (setq org-last-level level))
16379 line)
16380 lines))
16381 (while (> org-last-level 0)
16382 (setq org-last-level (1- org-last-level))
16383 (insert "</li>\n</ul>\n"))
16385 (setq head-count 0)
16386 (org-init-section-numbers)
16388 (while (setq line (pop lines) origline line)
16389 (catch 'nextline
16391 ;; end of quote section?
16392 (when (and inquote (string-match "^\\*+" line))
16393 (insert "</pre>\n")
16394 (setq inquote nil))
16395 ;; inside a quote section?
16396 (when inquote
16397 (insert (org-html-protect line) "\n")
16398 (throw 'nextline nil))
16400 ;; verbatim lines
16401 (when (and org-export-with-fixed-width
16402 (string-match "^[ \t]*:\\(.*\\)" line))
16403 (when (not infixed)
16404 (setq infixed t)
16405 (insert "<pre>\n"))
16406 (insert (org-html-protect (match-string 1 line)) "\n")
16407 (when (and lines
16408 (not (string-match "^[ \t]*\\(:.*\\)"
16409 (car lines))))
16410 (setq infixed nil)
16411 (insert "</pre>\n"))
16412 (throw 'nextline nil))
16415 ;; make targets to anchors
16416 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
16417 (cond
16418 ((match-end 2)
16419 (setq line (replace-match
16420 (concat "@<a name=\""
16421 (org-solidify-link-text (match-string 1 line))
16422 "\">\\nbsp@</a>")
16423 t t line)))
16424 ((and org-export-with-toc (equal (string-to-char line) ?*))
16425 (setq line (replace-match
16426 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
16427 ; (concat "@<i>" (match-string 1 line) "@</i> ")
16428 t t line)))
16430 (setq line (replace-match
16431 (concat "@<a name=\""
16432 (org-solidify-link-text (match-string 1 line))
16433 "\" class=\"target\">" (match-string 1 line) "@</a> ")
16434 t t line)))))
16436 (setq line (org-html-handle-time-stamps line))
16438 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
16439 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
16440 ;; Also handle sub_superscripts and checkboxes
16441 (setq line (org-html-expand line))
16443 ;; Format the links
16444 (setq start 0)
16445 (while (string-match org-bracket-link-analytic-regexp line start)
16446 (setq start (match-beginning 0))
16447 (setq type (if (match-end 2) (match-string 2 line) "internal"))
16448 (setq path (match-string 3 line))
16449 (setq desc1 (if (match-end 5) (match-string 5 line))
16450 desc2 (if (match-end 2) (concat type ":" path) path)
16451 descp (and desc1 (not (equal desc1 desc2)))
16452 desc (or desc1 desc2))
16453 ;; Make an image out of the description if that is so wanted
16454 (when (and descp (org-file-image-p desc))
16455 (save-match-data
16456 (if (string-match "^file:" desc)
16457 (setq desc (substring desc (match-end 0)))))
16458 (setq desc (concat "<img src=\"" desc "\"/>")))
16459 ;; FIXME: do we need to unescape here somewhere?
16460 (cond
16461 ((equal type "internal")
16462 (setq rpl
16463 (concat
16464 "<a href=\"#"
16465 (org-solidify-link-text path target-alist)
16466 "\">" desc "</a>")))
16467 ((member type '("http" "https")) ; FIXME: need to test this.
16468 ;; standard URL, just check if we need to inline an image
16469 (if (and (or (eq t org-export-html-inline-images)
16470 (and org-export-html-inline-images (not descp)))
16471 (org-file-image-p path))
16472 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
16473 (setq link (concat type ":" path))
16474 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
16475 ((member type '("ftp" "mailto" "news"))
16476 ;; standard URL
16477 (setq link (concat type ":" path))
16478 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
16479 ((string= type "file")
16480 ;; FILE link
16481 (let* ((filename path)
16482 (abs-p (file-name-absolute-p filename))
16483 thefile file-is-image-p search)
16484 (save-match-data
16485 (if (string-match "::\\(.*\\)" filename)
16486 (setq search (match-string 1 filename)
16487 filename (replace-match "" t nil filename)))
16488 (setq valid
16489 (if (functionp link-validate)
16490 (funcall link-validate filename current-dir)
16492 (setq file-is-image-p (org-file-image-p filename))
16493 (setq thefile (if abs-p (expand-file-name filename) filename))
16494 (when (and org-export-html-link-org-files-as-html
16495 (string-match "\\.org$" thefile))
16496 (setq thefile (concat (substring thefile 0
16497 (match-beginning 0))
16498 ".html"))
16499 (if (and search
16500 ;; make sure this is can be used as target search
16501 (not (string-match "^[0-9]*$" search))
16502 (not (string-match "^\\*" search))
16503 (not (string-match "^/.*/$" search)))
16504 (setq thefile (concat thefile "#"
16505 (org-solidify-link-text
16506 (org-link-unescape search)))))
16507 (when (string-match "^file:" desc)
16508 (setq desc (replace-match "" t t desc))
16509 (if (string-match "\\.org$" desc)
16510 (setq desc (replace-match "" t t desc))))))
16511 (setq rpl (if (and file-is-image-p
16512 (or (eq t org-export-html-inline-images)
16513 (and org-export-html-inline-images
16514 (not descp))))
16515 (concat "<img src=\"" thefile "\"/>")
16516 (concat "<a href=\"" thefile "\">" desc "</a>")))
16517 (if (not valid) (setq rpl desc))))
16518 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
16519 (setq rpl (concat "<i>&lt;" type ":"
16520 (save-match-data (org-link-unescape path))
16521 "&gt;</i>"))))
16522 (setq line (replace-match rpl t t line)
16523 start (+ start (length rpl))))
16524 ;; TODO items
16525 (if (and (string-match org-todo-line-regexp line)
16526 (match-beginning 2))
16527 (if (equal (match-string 2 line) org-done-string)
16528 (setq line (replace-match
16529 "<span class=\"done\">\\2</span>"
16530 t nil line 2))
16531 (setq line (replace-match "<span class=\"todo\">\\2</span>"
16532 t nil line 2))))
16534 (cond
16535 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
16536 ;; This is a headline
16537 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
16538 txt (match-string 2 line))
16539 (if (string-match quote-re0 txt)
16540 (setq txt (replace-match "" t t txt)))
16541 (if (<= level umax) (setq head-count (+ head-count 1)))
16542 (when in-local-list
16543 ;; Close any local lists before inserting a new header line
16544 (while local-list-num
16545 (org-close-li)
16546 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
16547 (pop local-list-num))
16548 (setq local-list-indent nil
16549 in-local-list nil))
16550 (org-html-level-start level txt umax
16551 (and org-export-with-toc (<= level umax))
16552 head-count)
16553 ;; QUOTES
16554 (when (string-match quote-re line)
16555 (insert "<pre>")
16556 (setq inquote t)))
16558 ((and org-export-with-tables
16559 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
16560 (if (not table-open)
16561 ;; New table starts
16562 (setq table-open t table-buffer nil table-orig-buffer nil))
16563 ;; Accumulate lines
16564 (setq table-buffer (cons line table-buffer)
16565 table-orig-buffer (cons origline table-orig-buffer))
16566 (when (or (not lines)
16567 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
16568 (car lines))))
16569 (setq table-open nil
16570 table-buffer (nreverse table-buffer)
16571 table-orig-buffer (nreverse table-orig-buffer))
16572 (org-close-par-maybe)
16573 (insert (org-format-table-html table-buffer table-orig-buffer))))
16575 ;; Normal lines
16576 (when (string-match
16577 (cond
16578 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
16579 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
16580 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
16581 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
16582 line)
16583 (setq ind (org-get-string-indentation line)
16584 start-is-num (match-beginning 4)
16585 starter (if (match-beginning 2)
16586 (substring (match-string 2 line) 0 -1))
16587 line (substring line (match-beginning 5)))
16588 (unless (string-match "[^ \t]" line)
16589 ;; empty line. Pretend indentation is large.
16590 (setq ind (1+ (or (car local-list-indent) 1))))
16591 (while (and in-local-list
16592 (or (and (= ind (car local-list-indent))
16593 (not starter))
16594 (< ind (car local-list-indent))))
16595 (org-close-li)
16596 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
16597 (pop local-list-num) (pop local-list-indent)
16598 (setq in-local-list local-list-indent))
16599 (cond
16600 ((and starter
16601 (or (not in-local-list)
16602 (> ind (car local-list-indent))))
16603 ;; Start new (level of ) list
16604 (org-close-par-maybe)
16605 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
16606 (push start-is-num local-list-num)
16607 (push ind local-list-indent)
16608 (setq in-local-list t))
16609 (starter
16610 ;; continue current list
16611 (org-close-li)
16612 (insert "<li>\n")))
16613 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
16614 (setq line
16615 (replace-match
16616 (if (equal (match-string 1 line) "X")
16617 "<b>[X]</b>"
16618 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
16619 t t line))))
16621 ;; Empty lines start a new paragraph. If hand-formatted lists
16622 ;; are not fully interpreted, lines starting with "-", "+", "*"
16623 ;; also start a new paragraph.
16624 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
16626 ;; Check if the line break needs to be conserved
16627 (cond
16628 ((string-match "\\\\\\\\[ \t]*$" line)
16629 (setq line (replace-match "<br/>" t t line)))
16630 (org-export-preserve-breaks
16631 (setq line (concat line "<br/>"))))
16633 (insert line "\n")))))
16635 ;; Properly close all local lists and other lists
16636 (when inquote (insert "</pre>\n"))
16637 (when in-local-list
16638 ;; Close any local lists before inserting a new header line
16639 (while local-list-num
16640 (org-close-li)
16641 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
16642 (pop local-list-num))
16643 (setq local-list-indent nil
16644 in-local-list nil))
16645 (org-html-level-start 1 nil umax
16646 (and org-export-with-toc (<= level umax))
16647 head-count)
16649 (when (plist-get opt-plist :auto-postamble)
16650 (when author
16651 (insert "<p class=\"author\"> "
16652 (nth 1 lang-words) ": " author "\n")
16653 (when email
16654 (insert "<a href=\"mailto:" email "\">&lt;"
16655 email "&gt;</a>\n"))
16656 (insert "</p>\n"))
16657 (when (and date time)
16658 (insert "<p class=\"date\"> "
16659 (nth 2 lang-words) ": "
16660 date " " time "</p>\n")))
16662 (if org-export-html-with-timestamp
16663 (insert org-export-html-html-helper-timestamp))
16664 (insert (or (plist-get opt-plist :postamble) ""))
16665 (insert "</body>\n</html>\n")
16666 (normal-mode)
16667 ;; remove empty paragraphs and lists
16668 (goto-char (point-min))
16669 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
16670 (replace-match ""))
16671 (goto-char (point-min))
16672 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
16673 (replace-match ""))
16674 (save-buffer)
16675 (goto-char (point-min))
16676 (message "Exporting... done"))))
16679 (defun org-format-table-html (lines olines)
16680 "Find out which HTML converter to use and return the HTML code."
16681 (if (string-match "^[ \t]*|" (car lines))
16682 ;; A normal org table
16683 (org-format-org-table-html lines)
16684 ;; Table made by table.el - test for spanning
16685 (let* ((hlines (delq nil (mapcar
16686 (lambda (x)
16687 (if (string-match "^[ \t]*\\+-" x) x
16688 nil))
16689 lines)))
16690 (first (car hlines))
16691 (ll (and (string-match "\\S-+" first)
16692 (match-string 0 first)))
16693 (re (concat "^[ \t]*" (regexp-quote ll)))
16694 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
16695 hlines))))
16696 (if (and (not spanning)
16697 (not org-export-prefer-native-exporter-for-tables))
16698 ;; We can use my own converter with HTML conversions
16699 (org-format-table-table-html lines)
16700 ;; Need to use the code generator in table.el, with the original text.
16701 (org-format-table-table-html-using-table-generate-source olines)))))
16703 (defun org-format-org-table-html (lines)
16704 "Format a table into HTML."
16705 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
16706 (setq lines (nreverse lines))
16707 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
16708 (setq lines (nreverse lines))
16709 (when org-export-table-remove-special-lines
16710 ;; Check if the table has a marking column. If yes remove the
16711 ;; column and the special lines
16712 (let* ((special
16713 (not
16714 (memq nil
16715 (mapcar
16716 (lambda (x)
16717 (or (string-match "^[ \t]*|-" x)
16718 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
16719 lines)))))
16720 (if special
16721 (setq lines
16722 (delq nil
16723 (mapcar
16724 (lambda (x)
16725 (if (string-match "^[ \t]*| *[!_^] *|" x)
16726 nil ; ignore this line
16727 (and (or (string-match "^[ \t]*|-+\\+" x)
16728 (string-match "^[ \t]*|[^|]*|" x))
16729 (replace-match "|" t t x))))
16730 lines))))))
16732 (let ((head (and org-export-highlight-first-table-line
16733 (delq nil (mapcar
16734 (lambda (x) (string-match "^[ \t]*|-" x))
16735 (cdr lines)))))
16736 line fields html)
16737 (setq html (concat org-export-html-table-tag "\n"))
16738 (while (setq line (pop lines))
16739 (catch 'next-line
16740 (if (string-match "^[ \t]*|-" line)
16741 (progn
16742 (setq head nil) ;; head ends here, first time around
16743 ;; ignore this line
16744 (throw 'next-line t)))
16745 ;; Break the line into fields
16746 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
16747 (setq html (concat
16748 html
16749 "<tr>"
16750 (mapconcat (lambda (x)
16751 (if head
16752 (concat "<th>" x "</th>")
16753 (concat "<td>" x "</td>")))
16754 fields "")
16755 "</tr>\n"))))
16756 (setq html (concat html "</table>\n"))
16757 html))
16759 (defun org-fake-empty-table-line (line)
16760 "Replace everything except \"|\" with spaces."
16761 (let ((i (length line))
16762 (newstr (copy-sequence line)))
16763 (while (> i 0)
16764 (setq i (1- i))
16765 (if (not (eq (aref newstr i) ?|))
16766 (aset newstr i ?\ )))
16767 newstr))
16769 (defun org-format-table-table-html (lines)
16770 "Format a table generated by table.el into HTML.
16771 This conversion does *not* use `table-generate-source' from table.el.
16772 This has the advantage that Org-mode's HTML conversions can be used.
16773 But it has the disadvantage, that no cell- or row-spanning is allowed."
16774 (let (line field-buffer
16775 (head org-export-highlight-first-table-line)
16776 fields html empty)
16777 (setq html (concat org-export-html-table-tag "\n"))
16778 (while (setq line (pop lines))
16779 (setq empty "&nbsp;")
16780 (catch 'next-line
16781 (if (string-match "^[ \t]*\\+-" line)
16782 (progn
16783 (if field-buffer
16784 (progn
16785 (setq html (concat
16786 html
16787 "<tr>"
16788 (mapconcat
16789 (lambda (x)
16790 (if (equal x "") (setq x empty))
16791 (if head
16792 (concat "<th>" x "</th>\n")
16793 (concat "<td>" x "</td>\n")))
16794 field-buffer "\n")
16795 "</tr>\n"))
16796 (setq head nil)
16797 (setq field-buffer nil)))
16798 ;; Ignore this line
16799 (throw 'next-line t)))
16800 ;; Break the line into fields and store the fields
16801 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
16802 (if field-buffer
16803 (setq field-buffer (mapcar
16804 (lambda (x)
16805 (concat x "<br/>" (pop fields)))
16806 field-buffer))
16807 (setq field-buffer fields))))
16808 (setq html (concat html "</table>\n"))
16809 html))
16811 (defun org-format-table-table-html-using-table-generate-source (lines)
16812 "Format a table into html, using `table-generate-source' from table.el.
16813 This has the advantage that cell- or row-spanning is allowed.
16814 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
16815 (require 'table)
16816 (with-current-buffer (get-buffer-create " org-tmp1 ")
16817 (erase-buffer)
16818 (insert (mapconcat 'identity lines "\n"))
16819 (goto-char (point-min))
16820 (if (not (re-search-forward "|[^+]" nil t))
16821 (error "Error processing table"))
16822 (table-recognize-table)
16823 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
16824 (table-generate-source 'html " org-tmp2 ")
16825 (set-buffer " org-tmp2 ")
16826 (buffer-substring (point-min) (point-max))))
16828 (defun org-html-handle-time-stamps (s)
16829 "Format time stamps in string S, or remove them."
16830 (catch 'exit
16831 (let (r b)
16832 (while (string-match org-maybe-keyword-time-regexp s)
16833 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
16834 ;; never export CLOCK
16835 (throw 'exit ""))
16836 (or b (setq b (substring s 0 (match-beginning 0))))
16837 (if (not org-export-with-timestamps)
16838 (setq r (concat r (substring s 0 (match-beginning 0)))
16839 s (substring s (match-end 0)))
16840 (setq r (concat
16841 r (substring s 0 (match-beginning 0))
16842 (if (match-end 1)
16843 (format "@<span class=\"timestamp-kwd\">%s @</span>"
16844 (match-string 1 s)))
16845 (format " @<span class=\"timestamp\">%s@</span>"
16846 (substring
16847 (org-translate-time (match-string 3 s)) 1 -1)))
16848 s (substring s (match-end 0)))))
16849 ;; Line break if line started and ended with time stamp stuff
16850 (if (not r)
16852 (setq r (concat r s))
16853 (unless (string-match "\\S-" (concat b s))
16854 (setq r (concat r "@<br/>")))
16855 r))))
16857 (defun org-html-protect (s)
16858 ;; convert & to &amp;, < to &lt; and > to &gt;
16859 (let ((start 0))
16860 (while (string-match "&" s start)
16861 (setq s (replace-match "&amp;" t t s)
16862 start (1+ (match-beginning 0))))
16863 (while (string-match "<" s)
16864 (setq s (replace-match "&lt;" t t s)))
16865 (while (string-match ">" s)
16866 (setq s (replace-match "&gt;" t t s))))
16869 (defun org-export-cleanup-toc-line (s)
16870 "Remove tags and time staps from lines going into the toc."
16871 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
16872 (setq s (replace-match "" t t s)))
16873 (when org-export-remove-timestamps-from-toc
16874 (while (string-match org-maybe-keyword-time-regexp s)
16875 (setq s (replace-match "" t t s))))
16878 (defun org-html-expand (string)
16879 "Prepare STRING for HTML export. Applies all active conversions.
16880 If there are links in the string, don't modify these."
16881 (let* (m s l res)
16882 (while (setq m (string-match org-bracket-link-regexp string))
16883 (setq s (substring string 0 m)
16884 l (match-string 0 string)
16885 string (substring string (match-end 0)))
16886 (push (org-html-do-expand s) res)
16887 (push l res))
16888 (push (org-html-do-expand string) res)
16889 (apply 'concat (nreverse res))))
16891 (defun org-html-do-expand (s)
16892 "Apply all active conversions to translate special ASCII to HTML."
16893 (setq s (org-html-protect s))
16894 (if org-export-html-expand
16895 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
16896 (setq s (replace-match "<\\1>" t nil s))))
16897 (if org-export-with-emphasize
16898 (setq s (org-export-html-convert-emphasize s)))
16899 (if org-export-with-sub-superscripts
16900 (setq s (org-export-html-convert-sub-super s)))
16901 (if org-export-with-TeX-macros
16902 (let ((start 0) wd ass)
16903 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
16904 (setq wd (match-string 1 s))
16905 (if (setq ass (assoc wd org-html-entities))
16906 (setq s (replace-match (or (cdr ass)
16907 (concat "&" (car ass) ";"))
16908 t t s))
16909 (setq start (+ start (length wd)))))))
16912 (defun org-create-multibrace-regexp (left right n)
16913 "Create a regular expression which will match a balanced sexp.
16914 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
16915 as single character strings.
16916 The regexp returned will match the entire expression including the
16917 delimiters. It will also define a single group which contains the
16918 match except for the outermost delimiters. The maximum depth of
16919 stacked delimiters is N. Escaping delimiters is not possible."
16920 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
16921 (or "\\|")
16922 (re nothing)
16923 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
16924 (while (> n 1)
16925 (setq n (1- n)
16926 re (concat re or next)
16927 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
16928 (concat left "\\(" re "\\)" right)))
16930 (defvar org-match-substring-regexp
16931 (concat
16932 "\\([^\\]\\)\\([_^]\\)\\("
16933 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
16934 "\\|"
16935 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
16936 "\\|"
16937 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
16938 "The regular expression matching a sub- or superscript.")
16940 (defun org-export-html-convert-sub-super (string)
16941 "Convert sub- and superscripts in STRING to HTML."
16942 (let (key c)
16943 (while (string-match org-match-substring-regexp string)
16944 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
16945 (setq c (or (match-string 8 string)
16946 (match-string 6 string)
16947 (match-string 5 string)))
16948 (setq string (replace-match
16949 (concat (match-string 1 string)
16950 "<" key ">" c "</" key ">")
16951 t t string)))
16952 (while (string-match "\\\\\\([_^]\\)" string)
16953 (setq string (replace-match (match-string 1 string) t t string))))
16954 string)
16956 (defun org-export-html-convert-emphasize (string)
16957 "Apply emphasis."
16958 (while (string-match org-emph-re string)
16959 (setq string (replace-match (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist)) "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist)) "\\5") t nil string)))
16960 string)
16962 (defvar org-par-open nil)
16963 (defun org-open-par ()
16964 "Insert <p>, but first close previous paragraph if any."
16965 (org-close-par-maybe)
16966 (insert "\n<p>")
16967 (setq org-par-open t))
16968 (defun org-close-par-maybe ()
16969 "Close paragraph if there is one open."
16970 (when org-par-open
16971 (insert "</p>")
16972 (setq org-par-open nil)))
16973 (defun org-close-li ()
16974 "Close <li> if necessary."
16975 (org-close-par-maybe)
16976 (insert "</li>\n"))
16977 ; (when (save-excursion
16978 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
16979 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
16980 ; (insert "</li>"))))
16982 (defun org-html-level-start (level title umax with-toc head-count)
16983 "Insert a new level in HTML export.
16984 When TITLE is nil, just close all open levels."
16985 (org-close-par-maybe)
16986 (let ((l (1+ (max level umax))))
16987 (while (<= l org-level-max)
16988 (if (aref org-levels-open (1- l))
16989 (progn
16990 (org-html-level-close l)
16991 (aset org-levels-open (1- l) nil)))
16992 (setq l (1+ l)))
16993 (when title
16994 ;; If title is nil, this means this function is called to close
16995 ;; all levels, so the rest is done only if title is given
16996 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
16997 (setq title (replace-match
16998 (if org-export-with-tags
16999 (save-match-data
17000 (concat
17001 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
17002 (mapconcat 'identity (org-split-string
17003 (match-string 1 title) ":")
17004 "&nbsp;")
17005 "</span>"))
17007 t t title)))
17008 (if (> level umax)
17009 (progn
17010 (if (aref org-levels-open (1- level))
17011 (progn
17012 (org-close-li)
17013 (insert "<li>" title "<br/>\n"))
17014 (aset org-levels-open (1- level) t)
17015 (org-close-par-maybe)
17016 (insert "<ul>\n<li>" title "<br/>\n")))
17017 (if org-export-with-section-numbers
17018 (setq title (concat (org-section-number level) " " title)))
17019 (setq level (+ level org-export-html-toplevel-hlevel -1))
17020 (if with-toc
17021 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
17022 level head-count title level))
17023 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
17024 (org-open-par)))))
17026 (defun org-html-level-close (&rest args)
17027 "Terminate one level in HTML export."
17028 (org-close-li)
17029 (insert "</ul>"))
17031 ;;; iCalendar export
17033 ;;;###autoload
17034 (defun org-export-icalendar-this-file ()
17035 "Export current file as an iCalendar file.
17036 The iCalendar file will be located in the same directory as the Org-mode
17037 file, but with extension `.ics'."
17038 (interactive)
17039 (org-export-icalendar nil buffer-file-name))
17041 ;;;###autoload
17042 (defun org-export-icalendar-all-agenda-files ()
17043 "Export all files in `org-agenda-files' to iCalendar .ics files.
17044 Each iCalendar file will be located in the same directory as the Org-mode
17045 file, but with extension `.ics'."
17046 (interactive)
17047 (apply 'org-export-icalendar nil (org-agenda-files t)))
17049 ;;;###autoload
17050 (defun org-export-icalendar-combine-agenda-files ()
17051 "Export all files in `org-agenda-files' to a single combined iCalendar file.
17052 The file is stored under the name `org-combined-agenda-icalendar-file'."
17053 (interactive)
17054 (apply 'org-export-icalendar t (org-agenda-files t)))
17056 (defun org-export-icalendar (combine &rest files)
17057 "Create iCalendar files for all elements of FILES.
17058 If COMBINE is non-nil, combine all calendar entries into a single large
17059 file and store it under the name `org-combined-agenda-icalendar-file'."
17060 (save-excursion
17061 (let* ((dir (org-export-directory
17062 :ical (list :publishing-directory
17063 org-export-publishing-directory)))
17064 file ical-file ical-buffer category started org-agenda-new-buffers)
17066 (when combine
17067 (setq ical-file
17068 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
17069 org-combined-agenda-icalendar-file
17070 (expand-file-name org-combined-agenda-icalendar-file dir))
17071 ical-buffer (org-get-agenda-file-buffer ical-file))
17072 (set-buffer ical-buffer) (erase-buffer))
17073 (while (setq file (pop files))
17074 (catch 'nextfile
17075 (org-check-agenda-file file)
17076 (set-buffer (org-get-agenda-file-buffer file))
17077 (unless combine
17078 (setq ical-file (concat (file-name-as-directory dir)
17079 (file-name-sans-extension
17080 (file-name-nondirectory buffer-file-name))
17081 ".ics"))
17082 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
17083 (with-current-buffer ical-buffer (erase-buffer)))
17084 (setq category (or org-category
17085 (file-name-sans-extension
17086 (file-name-nondirectory buffer-file-name))))
17087 (if (symbolp category) (setq category (symbol-name category)))
17088 (let ((standard-output ical-buffer))
17089 (if combine
17090 (and (not started) (setq started t)
17091 (org-start-icalendar-file org-icalendar-combined-name))
17092 (org-start-icalendar-file category))
17093 (org-print-icalendar-entries combine category)
17094 (when (or (and combine (not files)) (not combine))
17095 (org-finish-icalendar-file)
17096 (set-buffer ical-buffer)
17097 (save-buffer)
17098 (run-hooks 'org-after-save-iCalendar-file-hook)))))
17099 (org-release-buffers org-agenda-new-buffers))))
17101 (defvar org-after-save-iCalendar-file-hook nil
17102 "Hook run after an iCalendar file has been saved.
17103 The iCalendar buffer is still current when this hook is run.
17104 A good way to use this is to tell a desktop calenndar application to re-read
17105 the iCalendar file.")
17108 ;; FIXME: Strip down the links
17109 (defun org-print-icalendar-entries (&optional combine category)
17110 "Print iCalendar entries for the current Org-mode file to `standard-output'.
17111 When COMBINE is non nil, add the category to each line."
17112 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
17113 (dts (org-ical-ts-to-string
17114 (format-time-string (cdr org-time-stamp-formats) (current-time))
17115 "DTSTART"))
17116 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
17117 (save-excursion
17118 (goto-char (point-min))
17119 (while (re-search-forward org-ts-regexp nil t)
17120 (setq pos (match-beginning 0)
17121 ts (match-string 0)
17122 inc t
17123 hd (org-get-heading))
17124 (if (looking-at re2)
17125 (progn
17126 (goto-char (match-end 0))
17127 (setq ts2 (match-string 1) inc nil))
17128 (setq ts2 ts
17129 tmp (buffer-substring (max (point-min)
17130 (- pos org-ds-keyword-length))
17131 pos)
17132 deadlinep (string-match org-deadline-regexp tmp)
17133 scheduledp (string-match org-scheduled-regexp tmp)
17134 ;; donep (org-entry-is-done-p)
17136 (if (or (string-match org-tr-regexp hd)
17137 (string-match org-ts-regexp hd))
17138 (setq hd (replace-match "" t t hd)))
17139 (if (string-match org-bracket-link-regexp hd)
17140 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
17141 (match-string 1 hd))
17142 t t hd)))
17143 (if deadlinep (setq hd (concat "DL: " hd)))
17144 (if scheduledp (setq hd (concat "S: " hd)))
17145 (princ (format "BEGIN:VEVENT
17148 SUMMARY:%s
17149 CATEGORIES:%s
17150 END:VEVENT\n"
17151 (org-ical-ts-to-string ts "DTSTART")
17152 (org-ical-ts-to-string ts2 "DTEND" inc)
17153 hd category)))
17154 (when org-icalendar-include-todo
17155 (goto-char (point-min))
17156 (while (re-search-forward org-todo-line-regexp nil t)
17157 (setq state (match-string 1))
17158 (unless (equal state org-done-string)
17159 (setq hd (match-string 3))
17160 (if (string-match org-priority-regexp hd)
17161 (setq pri (string-to-char (match-string 2 hd))
17162 hd (concat (substring hd 0 (match-beginning 1))
17163 (substring hd (- (match-end 1)))))
17164 (setq pri org-default-priority))
17165 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
17166 (- org-lowest-priority ?A))))))
17168 (princ (format "BEGIN:VTODO
17170 SUMMARY:%s
17171 CATEGORIES:%s
17172 SEQUENCE:1
17173 PRIORITY:%d
17174 END:VTODO\n"
17175 dts hd category pri))))))))
17177 (defun org-start-icalendar-file (name)
17178 "Start an iCalendar file by inserting the header."
17179 (let ((user user-full-name)
17180 (name (or name "unknown"))
17181 (timezone (cadr (current-time-zone))))
17182 (princ
17183 (format "BEGIN:VCALENDAR
17184 VERSION:2.0
17185 X-WR-CALNAME:%s
17186 PRODID:-//%s//Emacs with Org-mode//EN
17187 X-WR-TIMEZONE:%s
17188 CALSCALE:GREGORIAN\n" name user timezone))))
17190 (defun org-finish-icalendar-file ()
17191 "Finish an iCalendar file by inserting the END statement."
17192 (princ "END:VCALENDAR\n"))
17194 (defun org-ical-ts-to-string (s keyword &optional inc)
17195 "Take a time string S and convert it to iCalendar format.
17196 KEYWORD is added in front, to make a complete line like DTSTART....
17197 When INC is non-nil, increase the hour by two (if time string contains
17198 a time), or the day by one (if it does not contain a time)."
17199 (let ((t1 (org-parse-time-string s 'nodefault))
17200 t2 fmt have-time time)
17201 (if (and (car t1) (nth 1 t1) (nth 2 t1))
17202 (setq t2 t1 have-time t)
17203 (setq t2 (org-parse-time-string s)))
17204 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
17205 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
17206 (when inc
17207 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
17208 (setq time (encode-time s mi h d m y)))
17209 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
17210 (concat keyword (format-time-string fmt time))))
17212 ;;; XOXO export
17214 (defun org-export-as-xoxo-insert-into (buffer &rest output)
17215 (with-current-buffer buffer
17216 (apply 'insert output)))
17217 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
17219 (defun org-export-as-xoxo (&optional buffer)
17220 "Export the org buffer as XOXO.
17221 The XOXO buffer is named *xoxo-<source buffer name>*"
17222 (interactive (list (current-buffer)))
17223 ;; A quickie abstraction
17225 ;; Output everything as XOXO
17226 (with-current-buffer (get-buffer buffer)
17227 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
17228 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17229 (org-infile-export-plist)))
17230 (filename (concat (file-name-as-directory
17231 (org-export-directory :xoxo opt-plist))
17232 (file-name-sans-extension
17233 (file-name-nondirectory buffer-file-name))
17234 ".html"))
17235 (out (find-file-noselect filename))
17236 (last-level 1)
17237 (hanging-li nil))
17238 ;; Check the output buffer is empty.
17239 (with-current-buffer out (erase-buffer))
17240 ;; Kick off the output
17241 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
17242 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
17243 (let* ((hd (match-string-no-properties 1))
17244 (level (length hd))
17245 (text (concat
17246 (match-string-no-properties 2)
17247 (save-excursion
17248 (goto-char (match-end 0))
17249 (let ((str ""))
17250 (catch 'loop
17251 (while 't
17252 (forward-line)
17253 (if (looking-at "^[ \t]\\(.*\\)")
17254 (setq str (concat str (match-string-no-properties 1)))
17255 (throw 'loop str)))))))))
17257 ;; Handle level rendering
17258 (cond
17259 ((> level last-level)
17260 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
17262 ((< level last-level)
17263 (dotimes (- (- last-level level) 1)
17264 (if hanging-li
17265 (org-export-as-xoxo-insert-into out "</li>\n"))
17266 (org-export-as-xoxo-insert-into out "</ol>\n"))
17267 (when hanging-li
17268 (org-export-as-xoxo-insert-into out "</li>\n")
17269 (setq hanging-li nil)))
17271 ((equal level last-level)
17272 (if hanging-li
17273 (org-export-as-xoxo-insert-into out "</li>\n")))
17276 (setq last-level level)
17278 ;; And output the new li
17279 (setq hanging-li 't)
17280 (if (equal ?+ (elt text 0))
17281 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
17282 (org-export-as-xoxo-insert-into out "<li>" text))))
17284 ;; Finally finish off the ol
17285 (dotimes (- last-level 1)
17286 (if hanging-li
17287 (org-export-as-xoxo-insert-into out "</li>\n"))
17288 (org-export-as-xoxo-insert-into out "</ol>\n"))
17290 ;; Finish the buffer off and clean it up.
17291 (switch-to-buffer-other-window out)
17292 (indent-region (point-min) (point-max) nil)
17293 (save-buffer)
17294 (goto-char (point-min))
17298 ;;;; Key bindings
17300 ;; - Bindings in Org-mode map are currently
17301 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
17302 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
17303 ;; e (?) useful from outline-mode
17304 ;; i k @ expendable from outline-mode
17305 ;; 0123456789 % & ()_{} " ` free
17307 ;; Make `C-c C-x' a prefix key
17308 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
17310 ;; TAB key with modifiers
17311 (define-key org-mode-map "\C-i" 'org-cycle)
17312 (define-key org-mode-map [(tab)] 'org-cycle)
17313 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
17314 (define-key org-mode-map [(meta tab)] 'org-complete)
17315 (define-key org-mode-map "\M-\C-i" 'org-complete)
17316 ;; The following line is necessary under Suse GNU/Linux
17317 (unless (featurep 'xemacs)
17318 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
17319 (define-key org-mode-map [(shift tab)] 'org-shifttab)
17321 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
17322 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17323 (define-key org-mode-map [(meta return)] 'org-meta-return)
17325 ;; Cursor keys with modifiers
17326 (define-key org-mode-map [(meta left)] 'org-metaleft)
17327 (define-key org-mode-map [(meta right)] 'org-metaright)
17328 (define-key org-mode-map [(meta up)] 'org-metaup)
17329 (define-key org-mode-map [(meta down)] 'org-metadown)
17331 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17332 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
17333 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
17334 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
17336 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
17337 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
17338 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
17339 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
17341 ;;; Extra keys for tty access.
17342 ;; We only set them when really needed because otherwise the
17343 ;; menus don't show the simple keys
17345 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17346 (not window-system))
17347 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17348 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17349 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return)
17350 (define-key org-mode-map [?\e (return)] 'org-meta-return)
17351 (define-key org-mode-map [?\e (left)] 'org-metaleft)
17352 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft)
17353 (define-key org-mode-map [?\e (right)] 'org-metaright)
17354 (define-key org-mode-map "\C-c\C-xr" 'org-metaright)
17355 (define-key org-mode-map [?\e (up)] 'org-metaup)
17356 (define-key org-mode-map "\C-c\C-xu" 'org-metaup)
17357 (define-key org-mode-map [?\e (down)] 'org-metadown)
17358 (define-key org-mode-map "\C-c\C-xd" 'org-metadown)
17359 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17360 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17361 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17362 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17363 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
17364 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
17365 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
17366 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
17368 ;; All the other keys
17370 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17371 (define-key org-mode-map "\C-c\C-r" 'org-reveal)
17372 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
17373 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
17374 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
17375 (define-key org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17376 (define-key org-mode-map "\C-c\C-j" 'org-goto)
17377 (define-key org-mode-map "\C-c\C-t" 'org-todo)
17378 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
17379 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
17380 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
17381 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
17382 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
17383 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
17384 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
17385 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
17386 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
17387 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
17388 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
17389 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
17390 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
17391 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
17392 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17393 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17394 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17395 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17396 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
17397 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
17398 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17399 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
17400 (define-key org-mode-map "\C-c]" 'org-remove-file)
17401 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
17402 (define-key org-mode-map "\C-c^" 'org-sort)
17403 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17404 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
17405 (define-key org-mode-map "\C-m" 'org-return)
17406 (define-key org-mode-map "\C-c?" 'org-table-current-column)
17407 (define-key org-mode-map "\C-c " 'org-table-blank-field)
17408 (define-key org-mode-map "\C-c+" 'org-table-sum)
17409 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
17410 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
17411 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
17412 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17413 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
17414 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17415 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
17416 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
17417 (define-key org-mode-map "\C-c\C-e" 'org-export)
17418 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17420 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
17421 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17422 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17423 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17425 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17426 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17427 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17428 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17429 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17430 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17431 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17432 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17433 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17435 (when (featurep 'xemacs)
17436 (define-key org-mode-map 'button3 'popup-mode-menu))
17438 (defsubst org-table-p () (org-at-table-p))
17440 (defun org-self-insert-command (N)
17441 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17442 If the cursor is in a table looking at whitespace, the whitespace is
17443 overwritten, and the table is not marked as requiring realignment."
17444 (interactive "p")
17445 (if (and (org-table-p)
17446 (progn
17447 ;; check if we blank the field, and if that triggers align
17448 (and org-table-auto-blank-field
17449 (member last-command
17450 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
17451 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17452 ;; got extra space, this field does not determine column width
17453 (let (org-table-may-need-update) (org-table-blank-field))
17454 ;; no extra space, this field may determine column width
17455 (org-table-blank-field)))
17457 (eq N 1)
17458 (looking-at "[^|\n]* |"))
17459 (let (org-table-may-need-update)
17460 (goto-char (1- (match-end 0)))
17461 (delete-backward-char 1)
17462 (goto-char (match-beginning 0))
17463 (self-insert-command N))
17464 (setq org-table-may-need-update t)
17465 (self-insert-command N)))
17467 (defun org-delete-backward-char (N)
17468 "Like `delete-backward-char', insert whitespace at field end in tables.
17469 When deleting backwards, in tables this function will insert whitespace in
17470 front of the next \"|\" separator, to keep the table aligned. The table will
17471 still be marked for re-alignment if the field did fill the entire column,
17472 because, in this case the deletion might narrow the column."
17473 (interactive "p")
17474 (if (and (org-table-p)
17475 (eq N 1)
17476 (string-match "|" (buffer-substring (point-at-bol) (point)))
17477 (looking-at ".*?|"))
17478 (let ((pos (point))
17479 (noalign (looking-at "[^|\n\r]* |"))
17480 (c org-table-may-need-update))
17481 (backward-delete-char N)
17482 (skip-chars-forward "^|")
17483 (insert " ")
17484 (goto-char (1- pos))
17485 ;; noalign: if there were two spaces at the end, this field
17486 ;; does not determine the width of the column.
17487 (if noalign (setq org-table-may-need-update c)))
17488 (backward-delete-char N)))
17490 (defun org-delete-char (N)
17491 "Like `delete-char', but insert whitespace at field end in tables.
17492 When deleting characters, in tables this function will insert whitespace in
17493 front of the next \"|\" separator, to keep the table aligned. The table will
17494 still be marked for re-alignment if the field did fill the entire column,
17495 because, in this case the deletion might narrow the column."
17496 (interactive "p")
17497 (if (and (org-table-p)
17498 (not (bolp))
17499 (not (= (char-after) ?|))
17500 (eq N 1))
17501 (if (looking-at ".*?|")
17502 (let ((pos (point))
17503 (noalign (looking-at "[^|\n\r]* |"))
17504 (c org-table-may-need-update))
17505 (replace-match (concat
17506 (substring (match-string 0) 1 -1)
17507 " |"))
17508 (goto-char pos)
17509 ;; noalign: if there were two spaces at the end, this field
17510 ;; does not determine the width of the column.
17511 (if noalign (setq org-table-may-need-update c)))
17512 (delete-char N))
17513 (delete-char N)))
17515 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17516 (put 'org-self-insert-command 'delete-selection t)
17517 (put 'orgtbl-self-insert-command 'delete-selection t)
17518 (put 'org-delete-char 'delete-selection 'supersede)
17519 (put 'org-delete-backward-char 'delete-selection 'supersede)
17521 ;; How to do this: Measure non-white length of current string
17522 ;; If equal to column width, we should realign.
17524 (defun org-remap (map &rest commands)
17525 "In MAP, remap the functions given in COMMANDS.
17526 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17527 (let (new old)
17528 (while commands
17529 (setq old (pop commands) new (pop commands))
17530 (if (fboundp 'command-remapping)
17531 (define-key map (vector 'remap old) new)
17532 (substitute-key-definition old new map global-map)))))
17534 (when (eq org-enable-table-editor 'optimized)
17535 ;; If the user wants maximum table support, we need to hijack
17536 ;; some standard editing functions
17537 (org-remap org-mode-map
17538 'self-insert-command 'org-self-insert-command
17539 'delete-char 'org-delete-char
17540 'delete-backward-char 'org-delete-backward-char)
17541 (define-key org-mode-map "|" 'org-force-self-insert))
17543 (defun org-shiftcursor-error ()
17544 "Throw an error because Shift-Cursor command was applied in wrong context."
17545 (error "This command is active in special context like tables, headlines or timestamps"))
17547 (defun org-shifttab (&optional arg)
17548 "Global visibility cycling or move to previous table field.
17549 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17550 on context.
17551 See the individual commands for more information."
17552 (interactive "P")
17553 (cond
17554 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17555 (t (call-interactively 'org-global-cycle))))
17557 (defun org-shiftmetaleft ()
17558 "Promote subtree or delete table column.
17559 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
17560 See the individual commands for more information."
17561 (interactive)
17562 (cond
17563 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17564 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17565 ((org-at-item-p) (call-interactively 'org-outdent-item))
17566 (t (org-shiftcursor-error))))
17568 (defun org-shiftmetaright ()
17569 "Demote subtree or insert table column.
17570 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
17571 See the individual commands for more information."
17572 (interactive)
17573 (cond
17574 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17575 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17576 ((org-at-item-p) (call-interactively 'org-indent-item))
17577 (t (org-shiftcursor-error))))
17579 (defun org-shiftmetaup (&optional arg)
17580 "Move subtree up or kill table row.
17581 Calls `org-move-subtree-up' or `org-table-kill-row' or
17582 `org-move-item-up' depending on context. See the individual commands
17583 for more information."
17584 (interactive "P")
17585 (cond
17586 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17587 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17588 ((org-at-item-p) (call-interactively 'org-move-item-up))
17589 (t (org-shiftcursor-error))))
17590 (defun org-shiftmetadown (&optional arg)
17591 "Move subtree down or insert table row.
17592 Calls `org-move-subtree-down' or `org-table-insert-row' or
17593 `org-move-item-down', depending on context. See the individual
17594 commands for more information."
17595 (interactive "P")
17596 (cond
17597 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17598 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17599 ((org-at-item-p) (call-interactively 'org-move-item-down))
17600 (t (org-shiftcursor-error))))
17602 (defun org-metaleft (&optional arg)
17603 "Promote heading or move table column to left.
17604 Calls `org-do-promote' or `org-table-move-column', depending on context.
17605 With no specific context, calls the Emacs default `backward-word'.
17606 See the individual commands for more information."
17607 (interactive "P")
17608 (cond
17609 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17610 ((or (org-on-heading-p) (org-region-active-p))
17611 (call-interactively 'org-do-promote))
17612 ((org-at-item-p) (call-interactively 'org-outdent-item))
17613 (t (call-interactively 'backward-word))))
17615 (defun org-metaright (&optional arg)
17616 "Demote subtree or move table column to right.
17617 Calls `org-do-demote' or `org-table-move-column', depending on context.
17618 With no specific context, calls the Emacs default `forward-word'.
17619 See the individual commands for more information."
17620 (interactive "P")
17621 (cond
17622 ((org-at-table-p) (call-interactively 'org-table-move-column))
17623 ((or (org-on-heading-p) (org-region-active-p))
17624 (call-interactively 'org-do-demote))
17625 ((org-at-item-p) (call-interactively 'org-indent-item))
17626 (t (call-interactively 'forward-word))))
17628 (defun org-metaup (&optional arg)
17629 "Move subtree up or move table row up.
17630 Calls `org-move-subtree-up' or `org-table-move-row' or
17631 `org-move-item-up', depending on context. See the individual commands
17632 for more information."
17633 (interactive "P")
17634 (cond
17635 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17636 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17637 ((org-at-item-p) (call-interactively 'org-move-item-up))
17638 (t (org-shiftcursor-error))))
17640 (defun org-metadown (&optional arg)
17641 "Move subtree down or move table row down.
17642 Calls `org-move-subtree-down' or `org-table-move-row' or
17643 `org-move-item-down', depending on context. See the individual
17644 commands for more information."
17645 (interactive "P")
17646 (cond
17647 ((org-at-table-p) (call-interactively 'org-table-move-row))
17648 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17649 ((org-at-item-p) (call-interactively 'org-move-item-down))
17650 (t (org-shiftcursor-error))))
17652 (defun org-shiftup (&optional arg)
17653 "Increase item in timestamp or increase priority of current headline.
17654 Calls `org-timestamp-up' or `org-priority-up', depending on context.
17655 See the individual commands for more information."
17656 (interactive "P")
17657 (cond
17658 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
17659 ((org-on-heading-p) (call-interactively 'org-priority-up))
17660 ((org-at-item-p) (call-interactively 'org-previous-item))
17661 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
17663 (defun org-shiftdown (&optional arg)
17664 "Decrease item in timestamp or decrease priority of current headline.
17665 Calls `org-timestamp-down' or `org-priority-down', depending on context.
17666 See the individual commands for more information."
17667 (interactive "P")
17668 (cond
17669 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
17670 ((org-on-heading-p) (call-interactively 'org-priority-down))
17671 (t (call-interactively 'org-next-item))))
17673 (defun org-shiftright ()
17674 "Next TODO keyword or timestamp one day later, depending on context."
17675 (interactive)
17676 (cond
17677 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17678 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
17679 (t (org-shiftcursor-error))))
17681 (defun org-shiftleft ()
17682 "Previous TODO keyword or timestamp one day earlier, depending on context."
17683 (interactive)
17684 (cond
17685 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17686 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
17687 (t (org-shiftcursor-error))))
17689 (defun org-copy-special ()
17690 "Copy region in table or copy current subtree.
17691 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17692 See the individual commands for more information."
17693 (interactive)
17694 (call-interactively
17695 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17697 (defun org-cut-special ()
17698 "Cut region in table or cut current subtree.
17699 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17700 See the individual commands for more information."
17701 (interactive)
17702 (call-interactively
17703 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17705 (defun org-paste-special (arg)
17706 "Paste rectangular region into table, or past subtree relative to level.
17707 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17708 See the individual commands for more information."
17709 (interactive "P")
17710 (if (org-at-table-p)
17711 (org-table-paste-rectangle)
17712 (org-paste-subtree arg)))
17714 (defun org-ctrl-c-ctrl-c (&optional arg)
17715 "Set tags in headline, or update according to changed information at point.
17717 This command does many different things, depending on context:
17719 - If the cursor is in a headline, prompt for tags and insert them
17720 into the current line, aligned to `org-tags-column'. When called
17721 with prefix arg, realign all tags in the current buffer.
17723 - If the cursor is in one of the special #+KEYWORD lines, this
17724 triggers scanning the buffer for these lines and updating the
17725 information.
17727 - If the cursor is inside a table, realign the table. This command
17728 works even if the automatic table editor has been turned off.
17730 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17731 the entire table.
17733 - If the cursor is inside a table created by the table.el package,
17734 activate that table.
17736 - If the current buffer is a remember buffer, close note and file it.
17737 with a prefix argument, file it without further interaction to the default
17738 location.
17740 - If the cursor is on a <<<target>>>, update radio targets and corresponding
17741 links in this buffer.
17743 - If the cursor is on a numbered item in a plain list, renumber the
17744 ordered list."
17745 (interactive "P")
17746 (let ((org-enable-table-editor t))
17747 (cond
17748 ((or org-clock-overlays
17749 org-occur-highlights
17750 org-latex-fragment-image-overlays)
17751 (org-remove-clock-overlays)
17752 (org-remove-occur-highlights)
17753 (org-remove-latex-fragment-image-overlays)
17754 (message "Temporary highlights/overlays removed from current buffer"))
17755 ((and (local-variable-p 'org-finish-function (current-buffer))
17756 (fboundp org-finish-function))
17757 (funcall org-finish-function))
17758 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17759 ((org-on-heading-p) (call-interactively 'org-set-tags))
17760 ((org-at-table.el-p)
17761 (require 'table)
17762 (beginning-of-line 1)
17763 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
17764 (call-interactively 'table-recognize-table))
17765 ((org-at-table-p)
17766 (org-table-maybe-eval-formula)
17767 (if arg
17768 (call-interactively 'org-table-recalculate)
17769 (org-table-maybe-recalculate-line))
17770 (call-interactively 'org-table-align))
17771 ((org-at-item-checkbox-p)
17772 (call-interactively 'org-toggle-checkbox))
17773 ((org-at-item-p)
17774 (call-interactively 'org-renumber-ordered-list))
17775 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
17776 (cond
17777 ((equal (match-string 1) "TBLFM")
17778 ;; Recalculate the table before this line
17779 (save-excursion
17780 (beginning-of-line 1)
17781 (skip-chars-backward " \r\n\t")
17782 (if (org-at-table-p)
17783 (org-call-with-arg 'org-table-recalculate t))))
17785 (call-interactively 'org-mode-restart))))
17786 (t (error "C-c C-c can do nothing useful at this location.")))))
17788 (defun org-mode-restart ()
17789 "Restart Org-mode, to scan again for special lines.
17790 Also updates the keyword regular expressions."
17791 (interactive)
17792 (let ((org-inhibit-startup t)) (org-mode))
17793 (message "Org-mode restarted to refresh keyword and special line setup"))
17795 (defun org-return ()
17796 "Goto next table row or insert a newline.
17797 Calls `org-table-next-row' or `newline', depending on context.
17798 See the individual commands for more information."
17799 (interactive)
17800 (cond
17801 ((org-at-table-p)
17802 (org-table-justify-field-maybe)
17803 (call-interactively 'org-table-next-row))
17804 (t (newline))))
17806 (defun org-meta-return (&optional arg)
17807 "Insert a new heading or wrap a region in a table.
17808 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17809 See the individual commands for more information."
17810 (interactive "P")
17811 (cond
17812 ((org-at-table-p)
17813 (call-interactively 'org-table-wrap-region))
17814 (t (call-interactively 'org-insert-heading))))
17816 ;;; Menu entries
17818 ;; Define the Org-mode menus
17819 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17820 '("Tbl"
17821 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
17822 ["Next Field" org-cycle (org-at-table-p)]
17823 ["Previous Field" org-shifttab (org-at-table-p)]
17824 ["Next Row" org-return (org-at-table-p)]
17825 "--"
17826 ["Blank Field" org-table-blank-field (org-at-table-p)]
17827 ["Edit Field" org-table-edit-field (org-at-table-p)]
17828 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17829 "--"
17830 ("Column"
17831 ["Move Column Left" org-metaleft (org-at-table-p)]
17832 ["Move Column Right" org-metaright (org-at-table-p)]
17833 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17834 ["Insert Column" org-shiftmetaright (org-at-table-p)]
17835 "--"
17836 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :active (org-at-table-p) :selected org-table-limit-column-width :style toggle])
17837 ("Row"
17838 ["Move Row Up" org-metaup (org-at-table-p)]
17839 ["Move Row Down" org-metadown (org-at-table-p)]
17840 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17841 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17842 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17843 "--"
17844 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
17845 ("Rectangle"
17846 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17847 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17848 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17849 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17850 "--"
17851 ("Calculate"
17852 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17853 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17854 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
17855 "--"
17856 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17857 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17858 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17859 "--"
17860 ["Sum Column/Rectangle" org-table-sum
17861 (or (org-at-table-p) (org-region-active-p))]
17862 ["Which Column?" org-table-current-column (org-at-table-p)])
17863 ["Debug Formulas"
17864 (setq org-table-formula-debug (not org-table-formula-debug))
17865 :style toggle :selected org-table-formula-debug]
17866 "--"
17867 ["Create" org-table-create (and (not (org-at-table-p))
17868 org-enable-table-editor)]
17869 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17870 ["Import from File" org-table-import (not (org-at-table-p))]
17871 ["Export to File" org-table-export (org-at-table-p)]
17872 "--"
17873 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17875 (easy-menu-define org-org-menu org-mode-map "Org menu"
17876 '("Org"
17877 ("Show/Hide"
17878 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
17879 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
17880 ["Sparse Tree" org-occur t]
17881 ["Reveal Context" org-reveal t]
17882 ["Show All" show-all t]
17883 "--"
17884 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17885 "--"
17886 ["New Heading" org-insert-heading t]
17887 ("Navigate Headings"
17888 ["Up" outline-up-heading t]
17889 ["Next" outline-next-visible-heading t]
17890 ["Previous" outline-previous-visible-heading t]
17891 ["Next Same Level" outline-forward-same-level t]
17892 ["Previous Same Level" outline-backward-same-level t]
17893 "--"
17894 ["Jump" org-goto t])
17895 ("Edit Structure"
17896 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17897 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
17898 "--"
17899 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
17900 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
17901 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
17902 "--"
17903 ["Promote Heading" org-metaleft (not (org-at-table-p))]
17904 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
17905 ["Demote Heading" org-metaright (not (org-at-table-p))]
17906 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
17907 "--"
17908 ["Sort Region/Children" org-sort (not (org-at-table-p))]
17909 "--"
17910 ["Convert to odd levels" org-convert-to-odd-levels t]
17911 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
17912 ("Archive"
17913 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
17914 ["Check and Tag Children" (org-toggle-archive-tag (4))
17915 :active t :keys "C-u C-c C-x C-a"]
17916 ["Sparse trees open ARCHIVE trees"
17917 (setq org-sparse-tree-open-archived-trees
17918 (not org-sparse-tree-open-archived-trees))
17919 :style toggle :selected org-sparse-tree-open-archived-trees]
17920 ["Cycling opens ARCHIVE trees"
17921 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
17922 :style toggle :selected org-cycle-open-archived-trees]
17923 ["Agenda includes ARCHIVE trees"
17924 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
17925 :style toggle :selected (not org-agenda-skip-archived-trees)]
17926 "--"
17927 ["Move Subtree to Archive" org-archive-subtree t]
17928 ["Check and Move Children" (org-archive-subtree '(4))
17929 :active t :keys "C-u C-c $"])
17930 "--"
17931 ("TODO Lists"
17932 ["TODO/DONE/-" org-todo t]
17933 ("Select keyword"
17934 ["Next keyword" org-shiftright (org-on-heading-p)]
17935 ["Previous keyword" org-shiftleft (org-on-heading-p)]
17936 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
17937 ["Show TODO Tree" org-show-todo-tree t]
17938 ["Global TODO list" org-todo-list t]
17939 "--"
17940 ["Set Priority" org-priority t]
17941 ["Priority Up" org-shiftup t]
17942 ["Priority Down" org-shiftdown t]
17943 "--"
17944 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
17945 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
17946 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
17947 ; (or (org-on-heading-p) (org-at-item-p))]
17948 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
17949 ; (or (org-on-heading-p) (org-at-item-p))]
17950 ; ["Update Statistics" org-update-checkbox-count t]
17952 ("Dates and Scheduling"
17953 ["Timestamp" org-time-stamp t]
17954 ["Timestamp (inactive)" org-time-stamp-inactive t]
17955 ("Change Date"
17956 ["1 Day Later" org-shiftright t]
17957 ["1 Day Earlier" org-shiftleft t]
17958 ["1 ... Later" org-shiftup t]
17959 ["1 ... Earlier" org-shiftdown t])
17960 ["Compute Time Range" org-evaluate-time-range t]
17961 ["Schedule Item" org-schedule t]
17962 ["Deadline" org-deadline t]
17963 "--"
17964 ["Custom time format" org-toggle-time-stamp-overlays
17965 :style radio :selected org-display-custom-times]
17966 "--"
17967 ["Goto Calendar" org-goto-calendar t]
17968 ["Date from Calendar" org-date-from-calendar t])
17969 ("Logging work"
17970 ["Clock in" org-clock-in t]
17971 ["Clock out" org-clock-out t]
17972 ["Clock cancel" org-clock-cancel t]
17973 ["Display times" org-clock-display t]
17974 ["Create clock table" org-clock-report t]
17975 "--"
17976 ["Record DONE time"
17977 (progn (setq org-log-done (not org-log-done))
17978 (message "Switching to %s will %s record a timestamp"
17979 org-done-string
17980 (if org-log-done "automatically" "not")))
17981 :style toggle :selected org-log-done])
17982 "--"
17983 ["Agenda Command..." org-agenda t]
17984 ("File List for Agenda")
17985 ("Special views current file"
17986 ["TODO Tree" org-show-todo-tree t]
17987 ["Check Deadlines" org-check-deadlines t]
17988 ["Timeline" org-timeline t]
17989 ["Tags Tree" org-tags-sparse-tree t])
17990 "--"
17991 ("Hyperlinks"
17992 ["Store Link (Global)" org-store-link t]
17993 ["Insert Link" org-insert-link t]
17994 ["Follow Link" org-open-at-point t]
17995 "--"
17996 ["Descriptive Links"
17997 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
17998 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
17999 ["Literal Links"
18000 (progn
18001 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18002 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
18003 "--"
18004 ["Export/Publish..." org-export t]
18005 ("LaTeX"
18006 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18007 :selected org-cdlatex-mode]
18008 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18009 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18010 ["Modify math symbol" org-cdlatex-math-modify
18011 (org-inside-LaTeX-fragment-p)]
18012 ["Export LaTeX fragments as images"
18013 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
18014 :style toggle :selected org-export-with-LaTeX-fragments])
18015 "--"
18016 ("Documentation"
18017 ["Show Version" org-version t]
18018 ["Info Documentation" org-info t])
18019 ("Customize"
18020 ["Browse Org Group" org-customize t]
18021 "--"
18022 ["Expand This Menu" org-create-customize-menu
18023 (fboundp 'customize-menu-create)])
18024 "--"
18025 ["Refresh setup" org-mode-restart t]
18028 (defun org-toggle-log-option (type)
18029 (if (not (listp org-log-done)) (setq org-log-done nil))
18030 (if (memq type org-log-done)
18031 (setq org-log-done (delq type org-log-done))
18032 (add-to-list 'org-log-done type)))
18034 (defun org-check-log-option (type)
18035 (and (listp org-log-done) (memq type org-log-done)))
18037 (defun org-info (&optional node)
18038 "Read documentation for Org-mode in the info system.
18039 With optional NODE, go directly to that node."
18040 (interactive)
18041 (require 'info)
18042 (Info-goto-node (format "(org)%s" (or node ""))))
18044 (defun org-install-agenda-files-menu ()
18045 (let ((bl (buffer-list)))
18046 (save-excursion
18047 (while bl
18048 (set-buffer (pop bl))
18049 (if (org-mode-p) (setq bl nil)))
18050 (when (org-mode-p)
18051 (easy-menu-change
18052 '("Org") "File List for Agenda"
18053 (append
18054 (list
18055 ["Edit File List" (org-edit-agenda-file-list) t]
18056 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18057 ["Remove Current File from List" org-remove-file t]
18058 ["Cycle through agenda files" org-cycle-agenda-files t]
18059 "--")
18060 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18062 ;;;; Documentation
18064 (defun org-customize ()
18065 "Call the customize function with org as argument."
18066 (interactive)
18067 (customize-browse 'org))
18069 (defun org-create-customize-menu ()
18070 "Create a full customization menu for Org-mode, insert it into the menu."
18071 (interactive)
18072 (if (fboundp 'customize-menu-create)
18073 (progn
18074 (easy-menu-change
18075 '("Org") "Customize"
18076 `(["Browse Org group" org-customize t]
18077 "--"
18078 ,(customize-menu-create 'org)
18079 ["Set" Custom-set t]
18080 ["Save" Custom-save t]
18081 ["Reset to Current" Custom-reset-current t]
18082 ["Reset to Saved" Custom-reset-saved t]
18083 ["Reset to Standard Settings" Custom-reset-standard t]))
18084 (message "\"Org\"-menu now contains full customization menu"))
18085 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18087 ;;;; Miscellaneous stuff
18090 ;;; Generally useful functions
18092 (defun org-context ()
18093 "Return a list of contexts of the current cursor position.
18094 If several contexts apply, all are returned.
18095 Each context entry is a list with a symbol naming the context, and
18096 two positions indicating start and end of the context. Possible
18097 contexts are:
18099 :headline anywhere in a headline
18100 :headline-stars on the leading stars in a headline
18101 :todo-keyword on a TODO keyword (including DONE) in a headline
18102 :tags on the TAGS in a headline
18103 :priority on the priority cookie in a headline
18104 :item on the first line of a plain list item
18105 :item-bullet on the bullet/number of a plain list item
18106 :checkbox on the checkbox in a plain list item
18107 :table in an org-mode table
18108 :table-special on a special filed in a table
18109 :table-table in a table.el table
18110 :link on a hyperline
18111 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18112 :target on a <<target>>
18113 :radio-target on a <<<radio-target>>>
18114 :latex-fragment on a LaTeX fragment
18115 :latex-preview on a LaTeX fragment with overlayed preview image
18117 This function expects the position to be visible because it uses font-lock
18118 faces as a help to recognize the following contexts: :table-special, :link,
18119 and :keyword."
18120 (let* ((f (get-text-property (point) 'face))
18121 (faces (if (listp f) f (list f)))
18122 (p (point)) clist o)
18123 ;; First the large context
18124 (cond
18125 ((org-on-heading-p)
18126 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18127 (when (progn
18128 (beginning-of-line 1)
18129 (looking-at org-todo-line-tags-regexp))
18130 (push (org-point-in-group p 1 :headline-stars) clist)
18131 (push (org-point-in-group p 2 :todo-keyword) clist)
18132 (push (org-point-in-group p 4 :tags) clist))
18133 (goto-char p)
18134 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
18135 (if (looking-at "\\[#[A-Z]\\]")
18136 (push (org-point-in-group p 0 :priority) clist)))
18138 ((org-at-item-p)
18139 (push (org-point-in-group p 2 :item-bullet) clist)
18140 (push (list :item (point-at-bol)
18141 (save-excursion (org-end-of-item) (point)))
18142 clist)
18143 (and (org-at-item-checkbox-p)
18144 (push (org-point-in-group p 0 :checkbox) clist)))
18146 ((org-at-table-p)
18147 (push (list :table (org-table-begin) (org-table-end)) clist)
18148 (if (memq 'org-formula faces)
18149 (push (list :table-special
18150 (previous-single-property-change p 'face)
18151 (next-single-property-change p 'face)) clist)))
18152 ((org-at-table-p 'any)
18153 (push (list :table-table) clist)))
18154 (goto-char p)
18156 ;; Now the small context
18157 (cond
18158 ((org-at-timestamp-p)
18159 (push (org-point-in-group p 0 :timestamp) clist))
18160 ((memq 'org-link faces)
18161 (push (list :link
18162 (previous-single-property-change p 'face)
18163 (next-single-property-change p 'face)) clist))
18164 ((memq 'org-special-keyword faces)
18165 (push (list :keyword
18166 (previous-single-property-change p 'face)
18167 (next-single-property-change p 'face)) clist))
18168 ((org-on-target-p)
18169 (push (org-point-in-group p 0 :target) clist)
18170 (goto-char (1- (match-beginning 0)))
18171 (if (looking-at org-radio-target-regexp)
18172 (push (org-point-in-group p 0 :radio-target) clist))
18173 (goto-char p))
18174 ((setq o (car (delq nil
18175 (mapcar
18176 (lambda (x)
18177 (if (memq x org-latex-fragment-image-overlays) x))
18178 (org-overlays-at (point))))))
18179 (push (list :latex-fragment
18180 (org-overlay-start o) (org-overlay-end o)) clist)
18181 (push (list :latex-preview
18182 (org-overlay-start o) (org-overlay-end o)) clist))
18183 ((org-inside-LaTeX-fragment-p)
18184 ;; FIXME: positions wrong.
18185 (push (list :latex-fragment (point) (point)) clist)))
18187 (setq clist (nreverse (delq nil clist)))
18188 clist))
18190 (defun org-point-in-group (point group &optional context)
18191 "Check if POINT is in match-group GROUP.
18192 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18193 match. If the match group does ot exist or point is not inside it,
18194 return nil."
18195 (and (match-beginning group)
18196 (>= point (match-beginning group))
18197 (<= point (match-end group))
18198 (if context
18199 (list context (match-beginning group) (match-end group))
18200 t)))
18202 (defun org-move-line-down (arg)
18203 "Move the current line down. With prefix argument, move it past ARG lines."
18204 (interactive "p")
18205 (let ((col (current-column))
18206 beg end pos)
18207 (beginning-of-line 1) (setq beg (point))
18208 (beginning-of-line 2) (setq end (point))
18209 (beginning-of-line (+ 1 arg))
18210 (setq pos (move-marker (make-marker) (point)))
18211 (insert (delete-and-extract-region beg end))
18212 (goto-char pos)
18213 (move-to-column col)))
18215 (defun org-move-line-up (arg)
18216 "Move the current line up. With prefix argument, move it past ARG lines."
18217 (interactive "p")
18218 (let ((col (current-column))
18219 beg end pos)
18220 (beginning-of-line 1) (setq beg (point))
18221 (beginning-of-line 2) (setq end (point))
18222 (beginning-of-line (- arg))
18223 (setq pos (move-marker (make-marker) (point)))
18224 (insert (delete-and-extract-region beg end))
18225 (goto-char pos)
18226 (move-to-column col)))
18228 (defun org-replace-escapes (string table)
18229 ;; FIXME: document and make safer
18230 (let (e re rpl)
18231 (while (setq e (pop table))
18232 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18233 (while (string-match re string)
18234 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18235 (cdr e)))
18236 (setq string (replace-match rpl t t string))))
18237 string))
18239 ;;; Paragraph filling stuff.
18240 ;; We want this to be just right, so use the full arsenal.
18241 ;; FIXME: configure filladapt for XEmacs
18243 (defun org-set-autofill-regexps ()
18244 (interactive)
18245 ;; In the paragraph separator we include headlines, because filling
18246 ;; text in a line directly attached to a headline would otherwise
18247 ;; fill the headline as well.
18248 (org-set-local 'comment-start-skip "^#+[ \t]*")
18249 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
18250 ;; The paragraph starter includes hand-formatted lists.
18251 (org-set-local 'paragraph-start
18252 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
18253 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18254 ;; But only if the user has not turned off tables or fixed-width regions
18255 (org-set-local
18256 'auto-fill-inhibit-regexp
18257 (concat "\\*\\|#\\+"
18258 "\\|[ \t]*" org-keyword-time-regexp
18259 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18260 (concat
18261 "\\|[ \t]*["
18262 (if org-enable-table-editor "|" "")
18263 (if org-enable-fixed-width-editor ":" "")
18264 "]"))))
18265 ;; We use our own fill-paragraph function, to make sure that tables
18266 ;; and fixed-width regions are not wrapped. That function will pass
18267 ;; through to `fill-paragraph' when appropriate.
18268 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18269 ; Adaptive filling: To get full control, first make sure that
18270 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18271 (org-set-local 'adaptive-fill-regexp "\000")
18272 (org-set-local 'adaptive-fill-function
18273 'org-adaptive-fill-function))
18275 (defun org-fill-paragraph (&optional justify)
18276 "Re-align a table, pass through to fill-paragraph if no table."
18277 (let ((table-p (org-at-table-p))
18278 (table.el-p (org-at-table.el-p)))
18279 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
18280 (table.el-p t) ; skip table.el tables
18281 (table-p (org-table-align) t) ; align org-mode tables
18282 (t nil)))) ; call paragraph-fill
18284 ;; For reference, this is the default value of adaptive-fill-regexp
18285 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18287 (defun org-adaptive-fill-function ()
18288 "Return a fill prefix for org-mode files.
18289 In particular, this makes sure hanging paragraphs for hand-formatted lists
18290 work correctly."
18291 (cond ((looking-at "#[ \t]+")
18292 (match-string 0))
18293 ((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
18294 (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
18295 (t nil)))
18298 (defun org-image-file-name-regexp ()
18299 "Return regexp matching the file names of images."
18300 (if (fboundp 'image-file-name-regexp)
18301 (image-file-name-regexp)
18302 (let ((image-file-name-extensions
18303 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18304 "xbm" "xpm" "pbm" "pgm" "ppm")))
18305 (concat "\\."
18306 (regexp-opt (nconc (mapcar 'upcase
18307 image-file-name-extensions)
18308 image-file-name-extensions)
18310 "\\'"))))
18312 (defun org-file-image-p (file)
18313 "Return non-nil if FILE is an image."
18314 (save-match-data
18315 (string-match (org-image-file-name-regexp) file)))
18317 ;;;; Functions extending outline functionality
18319 ;; C-a should go to the beginning of a *visible* line, also in the
18320 ;; new outline.el. I guess this should be patched into Emacs?
18321 (defun org-beginning-of-line ()
18322 "Go to the beginning of the current line. If that is invisible, continue
18323 to a visible line beginning. This makes the function of C-a more intuitive."
18324 (interactive)
18325 (beginning-of-line 1)
18326 (if (bobp)
18328 (backward-char 1)
18329 (if (org-invisible-p)
18330 (while (and (not (bobp)) (org-invisible-p))
18331 (backward-char 1)
18332 (beginning-of-line 1))
18333 (forward-char 1))))
18335 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18337 (defun org-invisible-p ()
18338 "Check if point is at a character currently not visible."
18339 ;; Early versions of noutline don't have `outline-invisible-p'.
18340 (if (fboundp 'outline-invisible-p)
18341 (outline-invisible-p)
18342 (get-char-property (point) 'invisible)))
18344 (defun org-invisible-p2 ()
18345 "Check if point is at a character currently not visible."
18346 (save-excursion
18347 (if (and (eolp) (not (bobp))) (backward-char 1))
18348 ;; Early versions of noutline don't have `outline-invisible-p'.
18349 (if (fboundp 'outline-invisible-p)
18350 (outline-invisible-p)
18351 (get-char-property (point) 'invisible))))
18353 (defalias 'org-back-to-heading 'outline-back-to-heading)
18354 (defalias 'org-on-heading-p 'outline-on-heading-p)
18356 (defun org-on-target-p ()
18357 (let ((pos (point)))
18358 (save-excursion
18359 (skip-chars-forward "<")
18360 (and (re-search-backward "<<" nil t)
18361 (or (looking-at org-radio-target-regexp)
18362 (looking-at org-target-regexp))
18363 (<= (match-beginning 0) pos)
18364 (>= (1+ (match-end 0)) pos)))))
18366 (defun org-up-heading-all (arg)
18367 "Move to the heading line of which the present line is a subheading.
18368 This function considers both visible and invisible heading lines.
18369 With argument, move up ARG levels."
18370 (if (fboundp 'outline-up-heading-all)
18371 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18372 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18374 (defun org-goto-sibling (&optional previous)
18375 "Goto the next sibling, even if it is invisible.
18376 When PREVIOUS is set, go to the previous sibling instead. Returns t
18377 when a sibling was found. When none is found, return nil and don't
18378 move point."
18379 (let ((fun (if previous 're-search-backward 're-search-forward))
18380 (pos (point))
18381 (re (concat "^" outline-regexp))
18382 level l)
18383 (org-back-to-heading t)
18384 (setq level (funcall outline-level))
18385 (catch 'exit
18386 (or previous (forward-char 1))
18387 (while (funcall fun re nil t)
18388 (setq l (funcall outline-level))
18389 (when (< l level) (goto-char pos) (throw 'exit nil))
18390 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18391 (goto-char pos)
18392 nil)))
18394 (defun org-show-siblings ()
18395 "Show all siblings of the current headline."
18396 (save-excursion
18397 (while (org-goto-sibling) (org-flag-heading nil)))
18398 (save-excursion
18399 (while (org-goto-sibling 'previous)
18400 (org-flag-heading nil))))
18402 (defun org-show-hidden-entry ()
18403 "Show an entry where even the heading is hidden."
18404 (save-excursion
18405 (org-show-entry)))
18407 (defun org-flag-heading (flag &optional entry)
18408 "Flag the current heading. FLAG non-nil means make invisible.
18409 When ENTRY is non-nil, show the entire entry."
18410 (save-excursion
18411 (org-back-to-heading t)
18412 ;; Check if we should show the entire entry
18413 (if entry
18414 (progn
18415 (org-show-entry)
18416 (save-excursion
18417 (and (outline-next-heading)
18418 (org-flag-heading nil))))
18419 (outline-flag-region (max 1 (1- (point)))
18420 (save-excursion (outline-end-of-heading) (point))
18421 flag))))
18423 (defun org-end-of-subtree (&optional invisible-OK)
18424 ;; This is an exact copy of the original function, but it uses
18425 ;; `org-back-to-heading', to make it work also in invisible
18426 ;; trees. And is uses an invisible-OK argument.
18427 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18428 (org-back-to-heading invisible-OK)
18429 (let ((first t)
18430 (level (funcall outline-level)))
18431 (while (and (not (eobp))
18432 (or first (> (funcall outline-level) level)))
18433 (setq first nil)
18434 (outline-next-heading))
18435 (if (memq (preceding-char) '(?\n ?\^M))
18436 (progn
18437 ;; Go to end of line before heading
18438 (forward-char -1)
18439 (if (memq (preceding-char) '(?\n ?\^M))
18440 ;; leave blank line before heading
18441 (forward-char -1)))))
18442 (point))
18444 (defun org-show-subtree ()
18445 "Show everything after this heading at deeper levels."
18446 (outline-flag-region
18447 (point)
18448 (save-excursion
18449 (outline-end-of-subtree) (outline-next-heading) (point))
18450 nil))
18452 (defun org-show-entry ()
18453 "Show the body directly following this heading.
18454 Show the heading too, if it is currently invisible."
18455 (interactive)
18456 (save-excursion
18457 (org-back-to-heading t)
18458 (outline-flag-region
18459 (max 1 (1- (point)))
18460 (save-excursion
18461 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
18462 (or (match-beginning 1) (point-max)))
18463 nil)))
18465 (defun org-make-options-regexp (kwds)
18466 "Make a regular expression for keyword lines."
18467 (concat
18469 "#?[ \t]*\\+\\("
18470 (mapconcat 'regexp-quote kwds "\\|")
18471 "\\):[ \t]*"
18472 "\\(.+\\)"))
18474 ;; Make isearch reveal the necessary context
18475 (defun org-isearch-end ()
18476 "Reveal context after isearch exits."
18477 (when isearch-success ; only if search was successful
18478 (if (featurep 'xemacs)
18479 ;; Under XEmacs, the hook is run in the correct place,
18480 ;; we directly show the context.
18481 (org-show-context 'isearch)
18482 ;; In Emacs the hook runs *before* restoring the overlays.
18483 ;; So we have to use a one-time post-command-hook to do this.
18484 ;; (Emacs 22 has a special variable, see function `org-mode')
18485 (unless (and (boundp 'isearch-mode-end-hook-quit)
18486 isearch-mode-end-hook-quit)
18487 ;; Only when the isearch was not quitted.
18488 (org-add-hook 'post-command-hook 'org-isearch-post-command
18489 'append 'local)))))
18491 (defun org-isearch-post-command ()
18492 "Remove self from hook, and show context."
18493 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18494 (org-show-context 'isearch))
18496 ;;;; Repair problems with some other packages
18498 ;; Make `bookmark-jump' show the jump location if it was hidden.
18499 (eval-after-load "bookmark"
18500 '(if (boundp 'bookmark-after-jump-hook)
18501 ;; We can use the hook
18502 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18503 ;; Hook not available, use advice
18504 (defadvice bookmark-jump (after org-make-visible activate)
18505 "Make the position visible."
18506 (org-bookmark-jump-unhide))))
18508 (defun org-bookmark-jump-unhide ()
18509 "Unhide the current position, to show the bookmark location."
18510 (and (org-mode-p)
18511 (or (org-invisible-p)
18512 (save-excursion (goto-char (max (point-min) (1- (point))))
18513 (org-invisible-p)))
18514 (org-show-context 'bookmark-jump)))
18516 ;; Make session.el ignore our circular variable
18517 (eval-after-load "session"
18518 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18520 ;;;; Experimental code
18522 (defun org-auto-repeat-maybe ()
18523 "Check if the current headline contains a REPEAT key.
18524 If yes, set TODO state back to what it was and change any SCHEDULED
18525 or DEADLINE times the new date.
18526 This function should be run in the `org-after-todo-state-change-hook'."
18527 ;; last-state is dynamically scoped into this function
18528 (let ((repeat (org-get-repeat))
18529 (whata '(("d" . day) ("m" . month) ("y" . year)))
18530 (msg "Entry repeats: ")
18531 (org-log-done)
18532 re type n what start)
18533 (when repeat
18534 (org-todo (if (eq 'org-todo-interpretation 'type)
18535 last-state
18536 (car org-todo-keywords)))
18537 (org-back-to-heading t)
18538 (org-add-planning-info nil nil 'closed)
18539 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
18540 org-deadline-time-regexp "\\)"))
18541 (while (re-search-forward
18542 re (save-excursion (outline-next-heading) (point)) t)
18543 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
18544 start 0)
18545 (while (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" repeat start)
18546 (setq start (match-end 0)
18547 n (string-to-number (match-string 1 repeat))
18548 what (match-string 2 repeat))
18549 (if (equal what "w") (setq n (* n 7) what "d"))
18550 (org-timestamp-change n (cdr (assoc what whata))))
18551 (setq msg (concat msg type org-last-changed-timestamp " ")))
18552 (message msg) (sit-for 1))))
18554 ;;;; Finish up
18556 (provide 'org)
18558 (run-hooks 'org-load-hook)
18560 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18561 ;;; org.el ends here