Release 4.67
[org-mode.git] / org.el
blob313748e8e43d60a986140377a07ff2e619fbfb6d
1 ;;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007 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.67
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 ;; A list of recent changes can be found at
63 ;; http://www.astro.uva.nl/~dominik/Tools/org/Changes
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (require 'easymenu)
82 ;;;; Customization variables
84 ;;; Version
86 (defvar org-version "4.67"
87 "The version number of the file org.el.")
88 (defun org-version ()
89 (interactive)
90 (message "Org-mode version %s" org-version))
92 ;;; Compatibility constants
93 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
94 (defconst org-format-transports-properties-p
95 (let ((x "a"))
96 (add-text-properties 0 1 '(test t) x)
97 (get-text-property 0 'test (format "%s" x)))
98 "Does format transport text properties?")
100 ;;; The custom variables
102 (defgroup org nil
103 "Outline-based notes management and organizer."
104 :tag "Org"
105 :group 'outlines
106 :group 'hypermedia
107 :group 'calendar)
109 (defgroup org-startup nil
110 "Options concerning startup of Org-mode."
111 :tag "Org Startup"
112 :group 'org)
114 (defcustom org-startup-folded t
115 "Non-nil means, entering Org-mode will switch to OVERVIEW.
116 This can also be configured on a per-file basis by adding one of
117 the following lines anywhere in the buffer:
119 #+STARTUP: fold
120 #+STARTUP: nofold
121 #+STARTUP: content"
122 :group 'org-startup
123 :type '(choice
124 (const :tag "nofold: show all" nil)
125 (const :tag "fold: overview" t)
126 (const :tag "content: all headlines" content)))
128 (defcustom org-startup-truncated t
129 "Non-nil means, entering Org-mode will set `truncate-lines'.
130 This is useful since some lines containing links can be very long and
131 uninteresting. Also tables look terrible when wrapped."
132 :group 'org-startup
133 :type 'boolean)
135 (defcustom org-startup-align-all-tables nil
136 "Non-nil means, align all tables when visiting a file.
137 This is useful when the column width in tables is forced with <N> cookies
138 in table fields. Such tables will look correct only after the first re-align.
139 This can also be configured on a per-file basis by adding one of
140 the following lines anywhere in the buffer:
141 #+STARTUP: align
142 #+STARTUP: noalign"
143 :group 'org-startup
144 :type 'boolean)
146 (defcustom org-insert-mode-line-in-empty-file nil
147 "Non-nil means insert the first line setting Org-mode in empty files.
148 When the function `org-mode' is called interactively in an empty file, this
149 normally means that the file name does not automatically trigger Org-mode.
150 To ensure that the file will always be in Org-mode in the future, a
151 line enforcing Org-mode will be inserted into the buffer, if this option
152 has been set."
153 :group 'org-startup
154 :type 'boolean)
156 (defcustom org-CUA-compatible nil
157 "Non-nil means use alternative key bindings for S-<cursor movement>.
158 Org-mode used S-<cursor movement> for changing timestamps and priorities.
159 S-<cursor movement> is also used for example by `CUA-mode' to select text.
160 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
161 alternative bindings. Setting this variable to t will replace the following
162 keys both in Org-mode and in the Org-agenda buffer.
164 S-RET -> C-S-RET
165 S-up -> M-p
166 S-down -> M-n
167 S-left -> M--
168 S-right -> M-+
170 If you do not like the alternative keys, take a look at the variable
171 `org-disputed-keys'.
173 This option is only relevant at load-time of Org-mode, and must be set
174 *before* org.el is loaded. Changing it requires a restart of Emacs to
175 become effective."
176 :group 'org-startup
177 :type 'boolean)
179 (defvar org-disputed-keys
180 '((S-up [(shift up)] [(meta ?p)])
181 (S-down [(shift down)] [(meta ?n)])
182 (S-left [(shift left)] [(meta ?-)])
183 (S-right [(shift right)] [(meta ?+)])
184 (S-return [(shift return)] [(control shift return)]))
185 "Keys for which Org-mode and other modes compete.
186 This is an alist, cars are symbols for lookup, 1st element is the default key,
187 second element will be used when `org-CUA-compatible' is t.")
189 (defun org-key (key)
190 "Select a key according to `org-CUA-compatible'."
191 (nth (if org-CUA-compatible 2 1)
192 (or (assq key org-disputed-keys)
193 (error "Invalid Key %s in `org-key'" key))))
195 (defcustom org-ellipsis nil
196 "The ellipsis to use in the Org-mode outline.
197 When nil, just use the standard three dots. When a string, use that instead,
198 and just in Org-mode (which will then use its own display table).
199 Changing this requires executing `M-x org-mode' in a buffer to become
200 effective."
201 :group 'org-startup
202 :type '(choice (const :tag "Default" nil)
203 (string :tag "String" :value "...#")))
205 (defvar org-display-table nil
206 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
208 (defgroup org-keywords nil
209 "Keywords in Org-mode."
210 :tag "Org Keywords"
211 :group 'org)
213 (defcustom org-deadline-string "DEADLINE:"
214 "String to mark deadline entries.
215 A deadline is this string, followed by a time stamp. Should be a word,
216 terminated by a colon. You can insert a schedule keyword and
217 a timestamp with \\[org-deadline].
218 Changes become only effective after restarting Emacs."
219 :group 'org-keywords
220 :type 'string)
222 (defcustom org-scheduled-string "SCHEDULED:"
223 "String to mark scheduled TODO entries.
224 A schedule is this string, followed by a time stamp. Should be a word,
225 terminated by a colon. You can insert a schedule keyword and
226 a timestamp with \\[org-schedule].
227 Changes become only effective after restarting Emacs."
228 :group 'org-keywords
229 :type 'string)
231 (defcustom org-closed-string "CLOSED:"
232 "String used as the prefix for timestamps logging closing a TODO entry."
233 :group 'org-keywords
234 :type 'string)
236 (defcustom org-clock-string "CLOCK:"
237 "String used as prefix for timestamps clocking work hours on an item."
238 :group 'org-keywords
239 :type 'string)
241 (defcustom org-comment-string "COMMENT"
242 "Entries starting with this keyword will never be exported.
243 An entry can be toggled between COMMENT and normal with
244 \\[org-toggle-comment].
245 Changes become only effective after restarting Emacs."
246 :group 'org-keywords
247 :type 'string)
249 (defcustom org-quote-string "QUOTE"
250 "Entries starting with this keyword will be exported in fixed-width font.
251 Quoting applies only to the text in the entry following the headline, and does
252 not extend beyond the next headline, even if that is lower level.
253 An entry can be toggled between QUOTE and normal with
254 \\[org-toggle-fixed-width-section]."
255 :group 'org-keywords
256 :type 'string)
258 (defvar org-repeat-re "\\<REPEAT(\\([-+ 0-9dwmy]+\\))"
259 "Regular expression for specifying repeated events.
260 After a match, group 1 contains the repeat expression.")
262 (defgroup org-structure nil
263 "Options concerning the general structure of Org-mode files."
264 :tag "Org Structure"
265 :group 'org)
267 (defgroup org-reveal-location nil
268 "Options about how to make context of a location visible."
269 :tag "Org Reveal Location"
270 :group 'org-structure)
272 (defcustom org-show-hierarchy-above '((default . t))
273 "Non-nil means, show full hierarchy when revealing a location.
274 Org-mode often shows locations in an org-mode file which might have
275 been invisible before. When this is set, the hierarchy of headings
276 above the exposed location is shown.
277 Turning this off for example for sparse trees makes them very compact.
278 Instead of t, this can also be an alist specifying this option for different
279 contexts. Valid contexts are
280 agenda when exposing an entry from the agenda
281 org-goto when using the command `org-goto' on key C-c C-j
282 occur-tree when using the command `org-occur' on key C-c /
283 tags-tree when constructing a sparse tree based on tags matches
284 link-search when exposing search matches associated with a link
285 mark-goto when exposing the jump goal of a mark
286 bookmark-jump when exposing a bookmark location
287 isearch when exiting from an incremental search
288 default default for all contexts not set explicitly"
289 :group 'org-reveal-location
290 :type '(choice
291 (const :tag "Always" t)
292 (const :tag "Never" nil)
293 (repeat :greedy t :tag "Individual contexts"
294 (cons
295 (choice :tag "Context"
296 (const agenda)
297 (const org-goto)
298 (const occur-tree)
299 (const tags-tree)
300 (const link-search)
301 (const mark-goto)
302 (const bookmark-jump)
303 (const isearch)
304 (const default))
305 (boolean)))))
307 (defcustom org-show-following-heading '((default . t))
308 "Non-nil means, show following heading when revealing a location.
309 Org-mode often shows locations in an org-mode file which might have
310 been invisible before. When this is set, the heading following the
311 match is shown.
312 Turning this off for example for sparse trees makes them very compact,
313 but makes it harder to edit the location of the match. In such a case,
314 use the command \\[org-reveal] to show more context.
315 Instead of t, this can also be an alist specifying this option for different
316 contexts. See `org-show-hierarchy-above' for valid contexts."
317 :group 'org-reveal-location
318 :type '(choice
319 (const :tag "Always" t)
320 (const :tag "Never" nil)
321 (repeat :greedy t :tag "Individual contexts"
322 (cons
323 (choice :tag "Context"
324 (const agenda)
325 (const org-goto)
326 (const occur-tree)
327 (const tags-tree)
328 (const link-search)
329 (const mark-goto)
330 (const bookmark-jump)
331 (const isearch)
332 (const default))
333 (boolean)))))
335 (defcustom org-show-siblings '((default . nil) (isearch t))
336 "Non-nil means, show all sibling heading when revealing a location.
337 Org-mode often shows locations in an org-mode file which might have
338 been invisible before. When this is set, the sibling of the current entry
339 heading are all made visible. If `org-show-hierarchy-above' is t,
340 the same happens on each level of the hierarchy above the current entry.
342 By default this is on for the isearch context, off for all other contexts.
343 Turning this off for example for sparse trees makes them very compact,
344 but makes it harder to edit the location of the match. In such a case,
345 use the command \\[org-reveal] to show more context.
346 Instead of t, this can also be an alist specifying this option for different
347 contexts. See `org-show-hierarchy-above' for valid contexts."
348 :group 'org-reveal-location
349 :type '(choice
350 (const :tag "Always" t)
351 (const :tag "Never" nil)
352 (repeat :greedy t :tag "Individual contexts"
353 (cons
354 (choice :tag "Context"
355 (const agenda)
356 (const org-goto)
357 (const occur-tree)
358 (const tags-tree)
359 (const link-search)
360 (const mark-goto)
361 (const bookmark-jump)
362 (const isearch)
363 (const default))
364 (boolean)))))
366 (defgroup org-cycle nil
367 "Options concerning visibility cycling in Org-mode."
368 :tag "Org Cycle"
369 :group 'org-structure)
371 (defcustom org-cycle-global-at-bob t
372 "Cycle globally if cursor is at beginning of buffer and not at a headline.
373 This makes it possible to do global cycling without having to use S-TAB or
374 C-u TAB. For this special case to work, the first line of the buffer
375 must not be a headline - it may be empty ot some other text. When used in
376 this way, `org-cycle-hook' is disables temporarily, to make sure the
377 cursor stays at the beginning of the buffer.
378 When this option is nil, don't do anything special at the beginning
379 of the buffer."
380 :group 'org-cycle
381 :type 'boolean)
383 (defcustom org-cycle-emulate-tab t
384 "Where should `org-cycle' emulate TAB.
385 nil Never
386 white Only in completely white lines
387 whitestart Only at the beginning of lines, before the first non-white char.
388 t Everywhere except in headlines
389 If TAB is used in a place where it does not emulate TAB, the current subtree
390 visibility is cycled."
391 :group 'org-cycle
392 :type '(choice (const :tag "Never" nil)
393 (const :tag "Only in completely white lines" white)
394 (const :tag "Before first char in a line" whitestart)
395 (const :tag "Everywhere except in headlines" t)
398 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
399 org-optimize-window-after-visibility-change)
400 "Hook that is run after `org-cycle' has changed the buffer visibility.
401 The function(s) in this hook must accept a single argument which indicates
402 the new state that was set by the most recent `org-cycle' command. The
403 argument is a symbol. After a global state change, it can have the values
404 `overview', `content', or `all'. After a local state change, it can have
405 the values `folded', `children', or `subtree'."
406 :group 'org-cycle
407 :type 'hook)
410 (defgroup org-edit-structure nil
411 "Options concerning structure editing in Org-mode."
412 :tag "Org Edit Structure"
413 :group 'org-structure)
415 (defcustom org-odd-levels-only nil
416 "Non-nil means, skip even levels and only use odd levels for the outline.
417 This has the effect that two stars are being added/taken away in
418 promotion/demotion commands. It also influences how levels are
419 handled by the exporters.
420 Changing it requires restart of `font-lock-mode' to become effective
421 for fontification also in regions already fontified.
422 You may also set this on a per-file basis by adding one of the following
423 lines to the buffer:
425 #+STARTUP: odd
426 #+STARTUP: oddeven"
427 :group 'org-edit-structure
428 :group 'org-font-lock
429 :type 'boolean)
431 (defcustom org-adapt-indentation t
432 "Non-nil means, adapt indentation when promoting and demoting.
433 When this is set and the *entire* text in an entry is indented, the
434 indentation is increased by one space in a demotion command, and
435 decreased by one in a promotion command. If any line in the entry
436 body starts at column 0, indentation is not changed at all."
437 :group 'org-edit-structure
438 :type 'boolean)
440 (defcustom org-blank-before-new-entry '((heading . nil)
441 (plain-list-item . nil))
442 "Should `org-insert-heading' leave a blank line before new heading/item?
443 The value is an alist, with `heading' and `plain-list-item' as car,
444 and a boolean flag as cdr."
445 :group 'org-edit-structure
446 :type '(list
447 (cons (const heading) (boolean))
448 (cons (const plain-list-item) (boolean))))
450 (defcustom org-insert-heading-hook nil
451 "Hook being run after inserting a new heading."
452 :group 'org-edit-structure
453 :type 'boolean)
455 (defcustom org-enable-fixed-width-editor t
456 "Non-nil means, lines starting with \":\" are treated as fixed-width.
457 This currently only means, they are never auto-wrapped.
458 When nil, such lines will be treated like ordinary lines.
459 See also the QUOTE keyword."
460 :group 'org-edit-structure
461 :type 'boolean)
463 (defgroup org-sparse-trees nil
464 "Options concerning sparse trees in Org-mode."
465 :tag "Org Sparse Trees"
466 :group 'org-structure)
468 (defcustom org-highlight-sparse-tree-matches t
469 "Non-nil means, highlight all matches that define a sparse tree.
470 The highlights will automatically disappear the next time the buffer is
471 changed by an edit command."
472 :group 'org-sparse-trees
473 :type 'boolean)
475 (defcustom org-remove-highlights-with-change t
476 "Non-nil means, any change to the buffer will remove temporary highlights.
477 Such highlights are created by `org-occur' and `org-clock-display'.
478 When nil, `C-c C-c needs to be used to get rid of the highlights.
479 The highlights created by `org-preview-latex-fragment' always need
480 `C-c C-c' to be removed."
481 :group 'org-sparse-trees
482 :group 'org-time
483 :type 'boolean)
486 (defcustom org-occur-hook '(org-first-headline-recenter)
487 "Hook that is run after `org-occur' has constructed a sparse tree.
488 This can be used to recenter the window to show as much of the structure
489 as possible."
490 :group 'org-sparse-trees
491 :type 'hook)
493 (defgroup org-plain-lists nil
494 "Options concerning plain lists in Org-mode."
495 :tag "Org Plain lists"
496 :group 'org-structure)
498 (defcustom org-cycle-include-plain-lists nil
499 "Non-nil means, include plain lists into visibility cycling.
500 This means that during cycling, plain list items will *temporarily* be
501 interpreted as outline headlines with a level given by 1000+i where i is the
502 indentation of the bullet. In all other operations, plain list items are
503 not seen as headlines. For example, you cannot assign a TODO keyword to
504 such an item."
505 :group 'org-plain-lists
506 :type 'boolean)
508 (defcustom org-plain-list-ordered-item-terminator t
509 "The character that makes a line with leading number an ordered list item.
510 Valid values are ?. and ?\). To get both terminators, use t. While
511 ?. may look nicer, it creates the danger that a line with leading
512 number may be incorrectly interpreted as an item. ?\) therefore is
513 the safe choice."
514 :group 'org-plain-lists
515 :type '(choice (const :tag "dot like in \"2.\"" ?.)
516 (const :tag "paren like in \"2)\"" ?\))
517 (const :tab "both" t)))
519 (defcustom org-auto-renumber-ordered-lists t
520 "Non-nil means, automatically renumber ordered plain lists.
521 Renumbering happens when the sequence have been changed with
522 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
523 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
524 :group 'org-plain-lists
525 :type 'boolean)
527 (defcustom org-provide-checkbox-statistics t
528 "Non-nil means, update checkbox statistics after insert and toggle.
529 When this is set, checkbox statistics is updated each time you either insert
530 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
531 with \\[org-ctrl-c-ctrl-c\\]."
532 :group 'org-plain-lists
533 :type 'boolean)
535 (defgroup org-archive nil
536 "Options concerning archiving in Org-mode."
537 :tag "Org Archive"
538 :group 'org-structure)
540 (defcustom org-archive-tag "ARCHIVE"
541 "The tag that marks a subtree as archived.
542 An archived subtree does not open during visibility cycling, and does
543 not contribute to the agenda listings."
544 :group 'org-archive
545 :group 'org-keywords
546 :type 'string)
548 (defcustom org-agenda-skip-archived-trees t
549 "Non-nil means, the agenda will skip any items located in archived trees.
550 An archived tree is a tree marked with the tag ARCHIVE."
551 :group 'org-archive
552 :group 'org-agenda-skip
553 :type 'boolean)
555 (defcustom org-cycle-open-archived-trees nil
556 "Non-nil means, `org-cycle' will open archived trees.
557 An archived tree is a tree marked with the tag ARCHIVE.
558 When nil, archived trees will stay folded. You can still open them with
559 normal outline commands like `show-all', but not with the cycling commands."
560 :group 'org-archive
561 :group 'org-cycle
562 :type 'boolean)
564 (defcustom org-sparse-tree-open-archived-trees nil
565 "Non-nil means sparse tree construction shows matches in archived trees.
566 When nil, matches in these trees are highlighted, but the trees are kept in
567 collapsed state."
568 :group 'org-archive
569 :group 'org-sparse-trees
570 :type 'boolean)
572 (defcustom org-archive-location "%s_archive::"
573 "The location where subtrees should be archived.
574 This string consists of two parts, separated by a double-colon.
576 The first part is a file name - when omitted, archiving happens in the same
577 file. %s will be replaced by the current file name (without directory part).
578 Archiving to a different file is useful to keep archived entries from
579 contributing to the Org-mode Agenda.
581 The part after the double colon is a headline. The archived entries will be
582 filed under that headline. When omitted, the subtrees are simply filed away
583 at the end of the file, as top-level entries.
585 Here are a few examples:
586 \"%s_archive::\"
587 If the current file is Projects.org, archive in file
588 Projects.org_archive, as top-level trees. This is the default.
590 \"::* Archived Tasks\"
591 Archive in the current file, under the top-level headline
592 \"* Archived Tasks\".
594 \"~/org/archive.org::\"
595 Archive in file ~/org/archive.org (absolute path), as top-level trees.
597 \"basement::** Finished Tasks\"
598 Archive in file ./basement (relative path), as level 3 trees
599 below the level 2 heading \"** Finished Tasks\".
601 You may set this option on a per-file basis by adding to the buffer a
602 line like
604 #+ARCHIVE: basement::** Finished Tasks"
605 :group 'org-archive
606 :type 'string)
608 (defcustom org-archive-mark-done t
609 "Non-nil means, mark entries as DONE when they are moved to the archive file."
610 :group 'org-archive
611 :type 'boolean)
613 (defcustom org-archive-stamp-time t
614 "Non-nil means, add a time stamp to entries moved to an archive file.
615 The time stamp will be added directly after the TODO state keyword in the
616 first line, so it is probably best to use this in combinations with
617 `org-archive-mark-done'."
618 :group 'org-archive
619 :type 'boolean)
621 (defgroup org-table nil
622 "Options concerning tables in Org-mode."
623 :tag "Org Table"
624 :group 'org)
626 (defcustom org-enable-table-editor 'optimized
627 "Non-nil means, lines starting with \"|\" are handled by the table editor.
628 When nil, such lines will be treated like ordinary lines.
630 When equal to the symbol `optimized', the table editor will be optimized to
631 do the following:
632 - Automatic overwrite mode in front of whitespace in table fields.
633 This makes the structure of the table stay in tact as long as the edited
634 field does not exceed the column width.
635 - Minimize the number of realigns. Normally, the table is aligned each time
636 TAB or RET are pressed to move to another field. With optimization this
637 happens only if changes to a field might have changed the column width.
638 Optimization requires replacing the functions `self-insert-command',
639 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
640 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
641 very good at guessing when a re-align will be necessary, but you can always
642 force one with \\[org-ctrl-c-ctrl-c].
644 If you would like to use the optimized version in Org-mode, but the
645 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
647 This variable can be used to turn on and off the table editor during a session,
648 but in order to toggle optimization, a restart is required.
650 See also the variable `org-table-auto-blank-field'."
651 :group 'org-table
652 :type '(choice
653 (const :tag "off" nil)
654 (const :tag "on" t)
655 (const :tag "on, optimized" optimized)))
657 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
658 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
659 In the optimized version, the table editor takes over all simple keys that
660 normally just insert a character. In tables, the characters are inserted
661 in a way to minimize disturbing the table structure (i.e. in overwrite mode
662 for empty fields). Outside tables, the correct binding of the keys is
663 restored.
665 The default for this option is t if the optimized version is also used in
666 Org-mode. See the variable `org-enable-table-editor' for details. Changing
667 this variable requires a restart of Emacs to become effective."
668 :group 'org-table
669 :type 'boolean)
671 (defcustom orgtbl-radio-table-templates
672 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
673 % END RECEIVE ORGTBL %n
674 \\begin{comment}
675 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
676 | | |
677 \\end{comment}\n")
678 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
679 @c END RECEIVE ORGTBL %n
680 @ignore
681 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
682 | | |
683 @end ignore\n")
684 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
685 <!-- END RECEIVE ORGTBL %n -->
686 <!--
687 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
688 | | |
689 -->\n"))
690 "Templates for radio tables in different major modes.
691 All occurrences of %n in a template will be replaced with the name of the
692 table, obtained by prompting the user."
693 :group 'org-table
694 :type '(repeat
695 (list (symbol :tag "Major mode")
696 (string :tag "Format"))))
698 (defgroup org-table-settings nil
699 "Settings for tables in Org-mode."
700 :tag "Org Table Settings"
701 :group 'org-table)
703 (defcustom org-table-default-size "5x2"
704 "The default size for newly created tables, Columns x Rows."
705 :group 'org-table-settings
706 :type 'string)
708 (defcustom org-table-number-regexp
709 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$"
710 "Regular expression for recognizing numbers in table columns.
711 If a table column contains mostly numbers, it will be aligned to the
712 right. If not, it will be aligned to the left.
714 The default value of this option is a regular expression which allows
715 anything which looks remotely like a number as used in scientific
716 context. For example, all of the following will be considered a
717 number:
718 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
720 Other options offered by the customize interface are more restrictive."
721 :group 'org-table-settings
722 :type '(choice
723 (const :tag "Positive Integers"
724 "^[0-9]+$")
725 (const :tag "Integers"
726 "^[-+]?[0-9]+$")
727 (const :tag "Floating Point Numbers"
728 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
729 (const :tag "Floating Point Number or Integer"
730 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
731 (const :tag "Exponential, Floating point, Integer"
732 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
733 (const :tag "Very General Number-Like, including hex"
734 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$")
735 (string :tag "Regexp:")))
737 (defcustom org-table-number-fraction 0.5
738 "Fraction of numbers in a column required to make the column align right.
739 In a column all non-white fields are considered. If at least this
740 fraction of fields is matched by `org-table-number-fraction',
741 alignment to the right border applies."
742 :group 'org-table-settings
743 :type 'number)
745 (defgroup org-table-editing nil
746 "Bahavior of tables during editing in Org-mode."
747 :tag "Org Table Editing"
748 :group 'org-table)
750 (defcustom org-table-automatic-realign t
751 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
752 When nil, aligning is only done with \\[org-table-align], or after column
753 removal/insertion."
754 :group 'org-table-editing
755 :type 'boolean)
757 (defcustom org-table-auto-blank-field t
758 "Non-nil means, automatically blank table field when starting to type into it.
759 This only happens when typing immediately after a field motion
760 command (TAB, S-TAB or RET).
761 Only relevant when `org-enable-table-editor' is equal to `optimized'."
762 :group 'org-table-editing
763 :type 'boolean)
765 (defcustom org-table-tab-jumps-over-hlines t
766 "Non-nil means, tab in the last column of a table with jump over a hline.
767 If a horizontal separator line is following the current line,
768 `org-table-next-field' can either create a new row before that line, or jump
769 over the line. When this option is nil, a new line will be created before
770 this line."
771 :group 'org-table-editing
772 :type 'boolean)
774 (defcustom org-table-tab-recognizes-table.el t
775 "Non-nil means, TAB will automatically notice a table.el table.
776 When it sees such a table, it moves point into it and - if necessary -
777 calls `table-recognize-table'."
778 :group 'org-table-editing
779 :type 'boolean)
781 (defgroup org-table-calculation nil
782 "Options concerning tables in Org-mode."
783 :tag "Org Table Calculation"
784 :group 'org-table)
786 (defcustom org-table-copy-increment t
787 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
788 :group 'org-table-calculation
789 :type 'boolean)
791 (defcustom org-calc-default-modes
792 '(calc-internal-prec 12
793 calc-float-format (float 5)
794 calc-angle-mode deg
795 calc-prefer-frac nil
796 calc-symbolic-mode nil
797 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
798 calc-display-working-message t
800 "List with Calc mode settings for use in calc-eval for table formulas.
801 The list must contain alternating symbols (Calc modes variables and values).
802 Don't remove any of the default settings, just change the values. Org-mode
803 relies on the variables to be present in the list."
804 :group 'org-table-calculation
805 :type 'plist)
807 (defcustom org-table-formula-evaluate-inline t
808 "Non-nil means, TAB and RET evaluate a formula in current table field.
809 If the current field starts with an equal sign, it is assumed to be a formula
810 which should be evaluated as described in the manual and in the documentation
811 string of the command `org-table-eval-formula'. This feature requires the
812 Emacs calc package.
813 When this variable is nil, formula calculation is only available through
814 the command \\[org-table-eval-formula]."
815 :group 'org-table-calculation
816 :type 'boolean)
818 ;; FIXME this is also a variable that makes Org-mode files non-portable
819 ;; Maybe I should have a #+ options for constants?
820 ;; How about the SI/cgs issue?
821 (defcustom org-table-formula-use-constants t
822 "Non-nil means, interpret constants in formulas in tables.
823 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
824 by the value given in `org-table-formula-constants', or by a value obtained
825 from the `constants.el' package."
826 :group 'org-table-calculation
827 :type 'boolean)
829 (defcustom org-table-formula-constants nil
830 "Alist with constant names and values, for use in table formulas.
831 The car of each element is a name of a constant, without the `$' before it.
832 The cdr is the value as a string. For example, if you'd like to use the
833 speed of light in a formula, you would configure
835 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
837 and then use it in an equation like `$1*$c'."
838 :group 'org-table-calculation
839 :type '(repeat
840 (cons (string :tag "name")
841 (string :tag "value"))))
843 (defcustom org-table-allow-automatic-line-recalculation t
844 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
845 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
846 :group 'org-table-calculation
847 :type 'boolean)
849 (defgroup org-link nil
850 "Options concerning links in Org-mode."
851 :tag "Org Link"
852 :group 'org)
854 (defvar org-link-abbrev-alist-local nil
855 "buffer-local version of `org-link-abbrev-alist', which see.
856 The value of this is taken from the #+LINK lines.")
857 (make-variable-buffer-local 'org-link-abbrev-alist-local)
859 (defcustom org-link-abbrev-alist nil
860 "Alist of link abbreviations.
861 The car of each element is a string, to be replaced at the start of a link.
862 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
863 links in Org-mode buffers can have an optional tag after a double colon, e.g.
865 [[linkkey:tag][description]]
867 If REPLACE is a string, the tag will simply be appended to create the link.
868 If the string contains \"%s\", the tag will be inserted there. REPLACE may
869 also be a function that will be called with the tag as the only argument to
870 create the link. See the manual for examples."
871 :group 'org-link
872 :type 'alist)
874 (defcustom org-descriptive-links t
875 "Non-nil means, hide link part and only show description of bracket links.
876 Bracket links are like [[link][descritpion]]. This variable sets the initial
877 state in new org-mode buffers. The setting can then be toggled on a
878 per-buffer basis from the Org->Hyperlinks menu."
879 :group 'org-link
880 :type 'boolean)
882 (defcustom org-link-file-path-type 'adaptive
883 "How the path name in file links should be stored.
884 Valid values are:
886 relative relative to the current directory, i.e. the directory of the file
887 into which the link is being inserted.
888 absolute absolute path, if possible with ~ for home directory.
889 noabbrev absolute path, no abbreviation of home directory.
890 adaptive Use relative path for files in the current directory and sub-
891 directories of it. For other files, use an absolute path."
892 :group 'org-link
893 :type '(choice
894 (const relative)
895 (const absolute)
896 (const noabbrev)
897 (const adaptive)))
899 (defcustom org-activate-links '(bracket angle plain radio tag date)
900 "Types of links that should be activated in Org-mode files.
901 This is a list of symbols, each leading to the activation of a certain link
902 type. In principle, it does not hurt to turn on most link types - there may
903 be a small gain when turning off unused link types. The types are:
905 bracket The recommended [[link][description]] or [[link]] links with hiding.
906 angular Links in angular brackes that may contain whitespace like
907 <bbdb:Carsten Dominik>.
908 plain Plain links in normal text, no whitespace, like http://google.com.
909 radio Text that is matched by a radio target, see manual for details.
910 tag Tag settings in a headline (link to tag search).
911 date Time stamps (link to calendar).
913 Changing this variable requires a restart of Emacs to become effective."
914 :group 'org-link
915 :type '(set (const :tag "Double bracket links (new style)" bracket)
916 (const :tag "Angular bracket links (old style)" angular)
917 (const :tag "plain text links" plain)
918 (const :tag "Radio target matches" radio)
919 (const :tag "Tags" tag)
920 (const :tag "Timestamps" date)))
922 (defgroup org-link-store nil
923 "Options concerning storing links in Org-mode"
924 :tag "Org Store Link"
925 :group 'org-link)
927 (defcustom org-email-link-description-format "Email %c: %.30s"
928 "Format of the description part of a link to an email or usenet message.
929 The following %-excapes will be replaced by corresponding information:
931 %F full \"From\" field
932 %f name, taken from \"From\" field, address if no name
933 %T full \"To\" field
934 %t first name in \"To\" field, address if no name
935 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
936 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
937 %s subject
938 %m message-id.
940 You may use normal field width specification between the % and the letter.
941 This is for example useful to limit the length of the subject.
943 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
944 :group 'org-link-store
945 :type 'string)
947 (defcustom org-from-is-user-regexp
948 (let (r1 r2)
949 (when (and user-mail-address (not (string= user-mail-address "")))
950 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
951 (when (and user-full-name (not (string= user-full-name "")))
952 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
953 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
954 "Regexp mached against the \"From:\" header of an email or usenet message.
955 It should match if the message is from the user him/herself."
956 :group 'org-link-store
957 :type 'regexp)
959 (defcustom org-context-in-file-links t
960 "Non-nil means, file links from `org-store-link' contain context.
961 A search string will be added to the file name with :: as separator and
962 used to find the context when the link is activated by the command
963 `org-open-at-point'.
964 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
965 negates this setting for the duration of the command."
966 :group 'org-link-store
967 :type 'boolean)
969 (defcustom org-keep-stored-link-after-insertion nil
970 "Non-nil means, keep link in list for entire session.
972 The command `org-store-link' adds a link pointing to the current
973 location to an internal list. These links accumulate during a session.
974 The command `org-insert-link' can be used to insert links into any
975 Org-mode file (offering completion for all stored links). When this
976 option is nil, every link which has been inserted once using \\[org-insert-link]
977 will be removed from the list, to make completing the unused links
978 more efficient."
979 :group 'org-link-store
980 :type 'boolean)
982 (defcustom org-usenet-links-prefer-google nil
983 "Non-nil means, `org-store-link' will create web links to Google groups.
984 When nil, Gnus will be used for such links.
985 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
986 negates this setting for the duration of the command."
987 :group 'org-link-store
988 :type 'boolean)
990 (defgroup org-link-follow nil
991 "Options concerning following links in Org-mode"
992 :tag "Org Follow Link"
993 :group 'org-link)
995 (defcustom org-tab-follows-link nil
996 "Non-nil means, on links TAB will follow the link.
997 Needs to be set before org.el is loaded."
998 :group 'org-link-follow
999 :type 'boolean)
1001 (defcustom org-return-follows-link nil
1002 "Non-nil means, on links RET will follow the link.
1003 Needs to be set before org.el is loaded."
1004 :group 'org-link-follow
1005 :type 'boolean)
1007 (defcustom org-mouse-1-follows-link t
1008 "Non-nil means, mouse-1 on a link will follow the link.
1009 A longer mouse click will still set point. Does not wortk on XEmacs.
1010 Needs to be set before org.el is loaded."
1011 :group 'org-link-follow
1012 :type 'boolean)
1014 (defcustom org-mark-ring-length 4
1015 "Number of different positions to be recorded in the ring
1016 Changing this requires a restart of Emacs to work correctly."
1017 :group 'org-link-follow
1018 :type 'interger)
1020 (defcustom org-link-frame-setup
1021 '((vm . vm-visit-folder-other-frame)
1022 (gnus . gnus-other-frame)
1023 (file . find-file-other-window))
1024 "Setup the frame configuration for following links.
1025 When following a link with Emacs, it may often be useful to display
1026 this link in another window or frame. This variable can be used to
1027 set this up for the different types of links.
1028 For VM, use any of
1029 `vm-visit-folder'
1030 `vm-visit-folder-other-frame'
1031 For Gnus, use any of
1032 `gnus'
1033 `gnus-other-frame'
1034 For FILE, use any of
1035 `find-file'
1036 `find-file-other-window'
1037 `find-file-other-frame'
1038 For the calendar, use the variable `calendar-setup'.
1039 For BBDB, it is currently only possible to display the matches in
1040 another window."
1041 :group 'org-link-follow
1042 :type '(list
1043 (cons (const vm)
1044 (choice
1045 (const vm-visit-folder)
1046 (const vm-visit-folder-other-window)
1047 (const vm-visit-folder-other-frame)))
1048 (cons (const gnus)
1049 (choice
1050 (const gnus)
1051 (const gnus-other-frame)))
1052 (cons (const file)
1053 (choice
1054 (const find-file)
1055 (const find-file-other-window)
1056 (const find-file-other-frame)))))
1058 (defcustom org-display-internal-link-with-indirect-buffer nil
1059 "Non-nil means, use indirect buffer to display infile links.
1060 Activating internal links (from one location in a file to another location
1061 in the same file) normally just jumps to the location. When the link is
1062 activated with a C-u prefix (or with mouse-3), the link is displayed in
1063 another window. When this option is set, the other window actually displays
1064 an indirect buffer clone of the current buffer, to avoid any visibility
1065 changes to the current buffer."
1066 :group 'org-link-follow
1067 :type 'boolean)
1069 (defcustom org-open-non-existing-files nil
1070 "Non-nil means, `org-open-file' will open non-existing files.
1071 When nil, an error will be generated."
1072 :group 'org-link-follow
1073 :type 'boolean)
1075 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1076 "Function and arguments to call for following mailto links.
1077 This is a list with the first element being a lisp function, and the
1078 remaining elements being arguments to the function. In string arguments,
1079 %a will be replaced by the address, and %s will be replaced by the subject
1080 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1081 :group 'org-link-follow
1082 :type '(choice
1083 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1084 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1085 (const :tag "message-mail" (message-mail "%a" "%s"))
1086 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1088 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1089 "Non-nil means, ask for confirmation before executing shell links.
1090 Shell links can be dangerous, just thing about a link
1092 [[shell:rm -rf ~/*][Google Search]]
1094 This link would show up in your Org-mode document as \"Google Search\"
1095 but really it would remove your entire home directory.
1096 Therefore I *definitely* advise against setting this variable to nil.
1097 Just change it to `y-or-n-p' of you want to confirm with a single key press
1098 rather than having to type \"yes\"."
1099 :group 'org-link-follow
1100 :type '(choice
1101 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1102 (const :tag "with y-or-n (faster)" y-or-n-p)
1103 (const :tag "no confirmation (dangerous)" nil)))
1105 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1106 "Non-nil means, ask for confirmation before executing elisp links.
1107 Elisp links can be dangerous, just think about a link
1109 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1111 This link would show up in your Org-mode document as \"Google Search\"
1112 but really it would remove your entire home directory.
1113 Therefore I *definitely* advise against setting this variable to nil.
1114 Just change it to `y-or-n-p' of you want to confirm with a single key press
1115 rather than having to type \"yes\"."
1116 :group 'org-link-follow
1117 :type '(choice
1118 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1119 (const :tag "with y-or-n (faster)" y-or-n-p)
1120 (const :tag "no confirmation (dangerous)" nil)))
1122 (defconst org-file-apps-defaults-gnu
1123 '((remote . emacs)
1124 (t . mailcap))
1125 "Default file applications on a UNIX or GNU/Linux system.
1126 See `org-file-apps'.")
1128 (defconst org-file-apps-defaults-macosx
1129 '((remote . emacs)
1130 (t . "open %s")
1131 ("ps" . "gv %s")
1132 ("ps.gz" . "gv %s")
1133 ("eps" . "gv %s")
1134 ("eps.gz" . "gv %s")
1135 ("dvi" . "xdvi %s")
1136 ("fig" . "xfig %s"))
1137 "Default file applications on a MacOS X system.
1138 The system \"open\" is known as a default, but we use X11 applications
1139 for some files for which the OS does not have a good default.
1140 See `org-file-apps'.")
1142 (defconst org-file-apps-defaults-windowsnt
1143 (list
1144 '(remote . emacs)
1145 (cons t
1146 (list (if (featurep 'xemacs)
1147 'mswindows-shell-execute
1148 'w32-shell-execute)
1149 "open" 'file)))
1150 "Default file applications on a Windows NT system.
1151 The system \"open\" is used for most files.
1152 See `org-file-apps'.")
1154 (defcustom org-file-apps
1156 ("txt" . emacs)
1157 ("tex" . emacs)
1158 ("ltx" . emacs)
1159 ("org" . emacs)
1160 ("el" . emacs)
1161 ("bib" . emacs)
1163 "External applications for opening `file:path' items in a document.
1164 Org-mode uses system defaults for different file types, but
1165 you can use this variable to set the application for a given file
1166 extension. The entries in this list are cons cells where the car identifies
1167 files and the cdr the corresponding command. Possible values for the
1168 file identifier are
1169 \"ext\" A string identifying an extension
1170 `directory' Matches a directory
1171 `remote' Matches a remote file, accessible through tramp or efs.
1172 Remote files most likely should be visited through Emacs
1173 because external applications cannot handle such paths.
1174 t Default for all remaining files
1176 Possible values for the command are:
1177 `emacs' The file will be visited by the current Emacs process.
1178 `default' Use the default application for this file type.
1179 string A command to be executed by a shell; %s will be replaced
1180 by the path to the file.
1181 sexp A Lisp form which will be evaluated. The file path will
1182 be available in the Lisp variable `file'.
1183 For more examples, see the system specific constants
1184 `org-file-apps-defaults-macosx'
1185 `org-file-apps-defaults-windowsnt'
1186 `org-file-apps-defaults-gnu'."
1187 :group 'org-link-follow
1188 :type '(repeat
1189 (cons (choice :value ""
1190 (string :tag "Extension")
1191 (const :tag "Default for unrecognized files" t)
1192 (const :tag "Remote file" remote)
1193 (const :tag "Links to a directory" directory))
1194 (choice :value ""
1195 (const :tag "Visit with Emacs" emacs)
1196 (const :tag "Use system default" default)
1197 (string :tag "Command")
1198 (sexp :tag "Lisp form")))))
1200 (defcustom org-mhe-search-all-folders nil
1201 "Non-nil means, that the search for the mh-message will be extended to
1202 all folders if the message cannot be found in the folder given in the link.
1203 Searching all folders is very efficient with one of the search engines
1204 supported by MH-E, but will be slow with pick."
1205 :group 'org-link-follow
1206 :type 'boolean)
1208 (defgroup org-remember nil
1209 "Options concerning interaction with remember.el."
1210 :tag "Org Remember"
1211 :group 'org)
1213 (defcustom org-directory "~/org"
1214 "Directory with org files.
1215 This directory will be used as default to prompt for org files.
1216 Used by the hooks for remember.el."
1217 :group 'org-remember
1218 :type 'directory)
1220 (defcustom org-default-notes-file "~/.notes"
1221 "Default target for storing notes.
1222 Used by the hooks for remember.el. This can be a string, or nil to mean
1223 the value of `remember-data-file'.
1224 You can set this on a per-template basis with the variable
1225 `org-remember-templates'."
1226 :group 'org-remember
1227 :type '(choice
1228 (const :tag "Default from remember-data-file" nil)
1229 file))
1231 (defcustom org-remember-default-headline ""
1232 "The headline that should be the default location in the notes file.
1233 When filing remember notes, the cursor will start at that position.
1234 You can set this on a per-template basis with the variable
1235 `org-remember-templates'."
1236 :group 'org-remember
1237 :type 'string)
1239 (defcustom org-remember-templates nil
1240 "Templates for the creation of remember buffers.
1241 When nil, just let remember make the buffer.
1242 When not nil, this is a list of 4-element lists. In each entry, the first
1243 element is a character, a unique key to select this template.
1244 The second element is the template. The third element is optional and can
1245 specify a destination file for remember items created with this template.
1246 The default file is given by `org-default-notes-file'. An optional third
1247 element can specify the headline in that file that should be offered
1248 first when the user is asked to file the entry. The default headline is
1249 given in the variable `org-remember-default-headline'.
1251 The template specifies the structure of the remember buffer. It should have
1252 a first line starting with a star, to act as the org-mode headline.
1253 Furthermore, the following %-escapes will be replaced with content:
1255 %^{prompt} prompt the user for a string and replace this sequence with it.
1256 %t time stamp, date only
1257 %T time stamp with date and time
1258 %u, %U like the above, but inactive time stamps
1259 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1260 You may define a prompt like %^{Please specify birthday}t
1261 %n user name (taken from `user-full-name')
1262 %a annotation, normally the link created with org-store-link
1263 %i initial content, the region when remember is called with C-u.
1264 If %i is indented, the entire inserted text will be indented
1265 as well.
1267 %? After completing the template, position cursor here.
1269 Apart from these general escapes, you can access information specific to the
1270 link type that is created. For example, calling `remember' in emails or gnus
1271 will record the author and the subject of the message, which you can access
1272 with %:author and %:subject, respectively. Here is a complete list of what
1273 is recorded for each link type.
1275 Link type | Available information
1276 -------------------+------------------------------------------------------
1277 bbdb | %:type %:name %:company
1278 vm, wl, mh, rmail | %:type %:subject %:message-id
1279 | %:from %:fromname %:fromaddress
1280 | %:to %:toname %:toaddress
1281 | %:fromto (either \"to NAME\" or \"from NAME\")
1282 gnus | %:group, for messages also all email fields
1283 w3, w3m | %:type %:url
1284 info | %:type %:file %:node
1285 calendar | %:type %:date"
1286 :group 'org-remember
1287 :get (lambda (var) ; Make sure all entries have 4 elements
1288 (mapcar (lambda (x)
1289 (cond ((= (length x) 3) (append x '("")))
1290 ((= (length x) 2) (append x '("" "")))
1291 (t x)))
1292 (default-value var)))
1293 :type '(repeat
1294 :tag "enabled"
1295 (list :value (?a "\n" nil nil)
1296 (character :tag "Selection Key")
1297 (string :tag "Template")
1298 (file :tag "Destination file (optional)")
1299 (string :tag "Destination headline (optional)"))))
1301 (defcustom org-reverse-note-order nil
1302 "Non-nil means, store new notes at the beginning of a file or entry.
1303 When nil, new notes will be filed to the end of a file or entry."
1304 :group 'org-remember
1305 :type '(choice
1306 (const :tag "Reverse always" t)
1307 (const :tag "Reverse never" nil)
1308 (repeat :tag "By file name regexp"
1309 (cons regexp boolean))))
1311 (defgroup org-todo nil
1312 "Options concerning TODO items in Org-mode."
1313 :tag "Org TODO"
1314 :group 'org)
1316 (defgroup org-progress nil
1317 "Options concerning Progress logging in Org-mode."
1318 :tag "Org Progress"
1319 :group 'org-time)
1321 (defcustom org-todo-keywords '("TODO" "DONE")
1322 "List of TODO entry keywords.
1323 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1324 considered to mean that the entry is \"done\". All the other mean that
1325 action is required, and will make the entry show up in todo lists, diaries
1326 etc.
1327 The command \\[org-todo] cycles an entry through these states, and an
1328 additional state where no keyword is present. For details about this
1329 cycling, see also the variable `org-todo-interpretation'
1330 Changes become only effective after restarting Emacs."
1331 :group 'org-todo
1332 :group 'org-keywords
1333 :type '(repeat (string :tag "Keyword")))
1335 (defcustom org-todo-interpretation 'sequence
1336 "Controls how TODO keywords are interpreted.
1337 This variable is only relevant if `org-todo-keywords' contains more than two
1338 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1340 When `sequence', \\[org-todo] will always switch to the next state in the
1341 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1342 to state when executed several times in direct succession. Otherwise, it
1343 switches directly to DONE from any state.
1344 See the manual for more information."
1345 :group 'org-todo
1346 :group 'org-keywords
1347 :type '(choice (const sequence)
1348 (const type)))
1350 (defcustom org-after-todo-state-change-hook nil
1351 "Hook which is run after the state of a TODO item was changed.
1352 The new state (a string with a TODO keyword, or nil) is available in the
1353 Lisp variable `state'."
1354 :group 'org-todo
1355 :type 'hook)
1357 (defcustom org-log-done nil
1358 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1359 When the state of an entry is changed from nothing to TODO, remove a previous
1360 closing date.
1362 This can also be a list of symbols indicating under which conditions
1363 the time stamp recording the action should be annotated with a short note.
1364 Valid members of this list are
1366 done Offer to record a note when marking entries done
1367 state Offer to record a note whenever changing the TODO state
1368 of an item. This is only relevant if TODO keywords are
1369 interpreted as sequence, see variable `org-todo-interpretation'.
1370 When `state' is set, this includes tracking `done'.
1371 clock-out Offer to record a note when clocking out of an item.
1373 A separate window will then pop up and allow you to type a note.
1374 After finishing with C-c C-c, the note will be added directly after the
1375 timestamp, as a plain list item. See also the variable
1376 `org-log-note-headings'.
1378 Logging can also be configured on a per-file basis by adding one of
1379 the following lines anywhere in the buffer:
1381 #+STARTUP: logdone
1382 #+STARTUP: nologging
1383 #+STARTUP: lognotedone
1384 #+STARTUP: lognotestate
1385 #+STARTUP: lognoteclock-out"
1386 :group 'org-todo
1387 :group 'org-progress
1388 :type '(choice
1389 (const :tag "off" nil)
1390 (const :tag "on" t)
1391 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1392 (const :tag "when item is marked DONE" done)
1393 (const :tag "when TODO state changes" state)
1394 (const :tag "when clocking out" clock-out))))
1396 (defcustom org-log-note-headings
1397 '((done . "CLOSING NOTE %t")
1398 (state . "State %-12s %t")
1399 (clock-out . ""))
1400 "Headings for notes added when clocking out or closing TODO items.
1401 The value is an alist, with the car being a sympol indicating the note
1402 context, and the cdr is the heading to be used. The heading may also be the
1403 empty string.
1404 %t in the heading will be replaced by a time stamp.
1405 %s will be replaced by the new TODO state, in double quotes.
1406 %u will be replaced by the user name.
1407 %U will be replaced by the full user name."
1408 :group 'org-todo
1409 :group 'org-progress
1410 :type '(list :greedy t
1411 (cons (const :tag "Heading when closing an item" done) string)
1412 (cons (const :tag
1413 "Heading when changing todo state (todo sequence only)"
1414 state) string)
1415 (cons (const :tag "Heading when clocking out" clock-out) string)))
1417 (defcustom org-allow-auto-repeat t
1418 "Non-nil means, find REPEAT cookies in entries and apply them.
1419 A repeat cookie looks like REPEAT(+1m) and causes deadlines and schedules
1420 to repeat themselves shifted by a certain amount of time, each time an
1421 entry is marked DONE."
1422 :group 'org-todo
1423 :group 'org-progress
1424 :type 'boolean)
1426 (defgroup org-priorities nil
1427 "Priorities in Org-mode."
1428 :tag "Org Priorities"
1429 :group 'org-todo)
1431 (defcustom org-default-priority ?B
1432 "The default priority of TODO items.
1433 This is the priority an item get if no explicit priority is given."
1434 :group 'org-priorities
1435 :type 'character)
1437 (defcustom org-lowest-priority ?C
1438 "The lowest priority of TODO items. A character like ?A, ?B etc."
1439 :group 'org-priorities
1440 :type 'character)
1442 (defgroup org-time nil
1443 "Options concerning time stamps and deadlines in Org-mode."
1444 :tag "Org Time"
1445 :group 'org)
1447 (defcustom org-insert-labeled-timestamps-at-point nil
1448 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1449 When nil, these labeled time stamps are forces into the second line of an
1450 entry, just after the headline. When scheduling from the global TODO list,
1451 the time stamp will always be forced into the second line."
1452 :group 'org-time
1453 :type 'boolean)
1455 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1456 "Formats for `format-time-string' which are used for time stamps.
1457 It is not recommended to change this constant.")
1459 (defcustom org-time-stamp-rounding-minutes 0
1460 "Number of minutes to round time stamps to upon insertion.
1461 When zero, insert the time unmodified. Useful rounding numbers
1462 should be factors of 60, so for example 5, 10, 15.
1463 When this is not zero, you can still force an exact time-stamp by using
1464 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1465 :group 'org-time
1466 :type 'integer)
1468 (defcustom org-display-custom-times nil
1469 "Non-nil means, overlay custom formats over all time stamps.
1470 The formats are defined through the variable `org-time-stamp-custom-formats'.
1471 To turn this on on a per-file basis, insert anywhere in the file:
1472 #+STARTUP: customtime"
1473 :group 'org-time
1474 :set 'set-default
1475 :type 'sexp)
1476 (make-variable-buffer-local 'org-display-custom-times)
1478 (defcustom org-time-stamp-custom-formats
1479 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1480 "Custom formats for time stamps. See `format-time-string' for the syntax.
1481 These are overlayed over the default ISO format if the variable
1482 `org-display-custom-times' is set."
1483 :group 'org-time
1484 :type 'sexp)
1486 (defun org-time-stamp-format (&optional long inactive)
1487 "Get the right format for a time string."
1488 (let ((f (if long (cdr org-time-stamp-formats)
1489 (car org-time-stamp-formats))))
1490 (if inactive
1491 (concat "[" (substring f 1 -1) "]")
1492 f)))
1494 (defcustom org-deadline-warning-days 30
1495 "No. of days before expiration during which a deadline becomes active.
1496 This variable governs the display in sparse trees and in the agenda."
1497 :group 'org-time
1498 :type 'number)
1500 (defcustom org-popup-calendar-for-date-prompt t
1501 "Non-nil means, pop up a calendar when prompting for a date.
1502 In the calendar, the date can be selected with mouse-1. However, the
1503 minibuffer will also be active, and you can simply enter the date as well.
1504 When nil, only the minibuffer will be available."
1505 :group 'org-time
1506 :type 'boolean)
1508 (defcustom org-calendar-follow-timestamp-change t
1509 "Non-nil means, make the calendar window follow timestamp changes.
1510 When a timestamp is modified and the calendar window is visible, it will be
1511 moved to the new date."
1512 :group 'org-time
1513 :type 'boolean)
1515 (defgroup org-tags nil
1516 "Options concerning tags in Org-mode."
1517 :tag "Org Tags"
1518 :group 'org)
1520 (defcustom org-tag-alist nil
1521 "List of tags allowed in Org-mode files.
1522 When this list is nil, Org-mode will base TAG input on what is already in the
1523 buffer.
1524 The value of this variable is an alist, the car may be (and should) be a
1525 character that is used to select that tag through the fast-tag-selection
1526 interface. See the manual for details."
1527 :group 'org-tags
1528 :type '(repeat
1529 (choice
1530 (cons (string :tag "Tag name")
1531 (character :tag "Access char"))
1532 (const :tag "Start radio group" (:startgroup))
1533 (const :tag "End radio group" (:endgroup)))))
1535 (defcustom org-use-fast-tag-selection 'auto
1536 "Non-nil means, use fast tag selection scheme.
1537 This is a special interface to select and deselect tags with single keys.
1538 When nil, fast selection is never used.
1539 When the symbol `auto', fast selection is used if and only if selection
1540 characters for tags have been configured, either through the variable
1541 `org-tag-alist' or through a #+TAGS line in the buffer.
1542 When t, fast selection is always used and selection keys are assigned
1543 automatically if necessary."
1544 :group 'org-tags
1545 :type '(choice
1546 (const :tag "Always" t)
1547 (const :tag "Never" nil)
1548 (const :tag "When selection characters are configured" 'auto)))
1550 (defcustom org-fast-tag-selection-single-key nil
1551 "Non-nil means, fast tag selection exits after first change.
1552 When nil, you have to press RET to exit it.
1553 During fast tag selection, you can toggle this flag with `C-c'.
1554 This variable can also have the value `expert'. In this case, the window
1555 displaying the tags menu is not even shown, until you press C-c again."
1556 :group 'org-tags
1557 :type '(choice
1558 (const :tag "No" nil)
1559 (const :tag "Yes" t)
1560 (const :tag "Expert" expert)))
1562 (defcustom org-tags-column 48
1563 "The column to which tags should be indented in a headline.
1564 If this number is positive, it specifies the column. If it is negative,
1565 it means that the tags should be flushright to that column. For example,
1566 -79 works well for a normal 80 character screen."
1567 :group 'org-tags
1568 :type 'integer)
1570 (defcustom org-auto-align-tags t
1571 "Non-nil means, realign tags after pro/demotion of TODO state change.
1572 These operations change the length of a headline and therefore shift
1573 the tags around. With this options turned on, after each such operation
1574 the tags are again aligned to `org-tags-column'."
1575 :group 'org-tags
1576 :type 'boolean)
1578 (defcustom org-use-tag-inheritance t
1579 "Non-nil means, tags in levels apply also for sublevels.
1580 When nil, only the tags directly given in a specific line apply there.
1581 If you turn off this option, you very likely want to turn on the
1582 companion option `org-tags-match-list-sublevels'."
1583 :group 'org-tags
1584 :type 'boolean)
1586 (defcustom org-tags-match-list-sublevels nil
1587 "Non-nil means list also sublevels of headlines matching tag search.
1588 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1589 the sublevels of a headline matching a tag search often also match
1590 the same search. Listing all of them can create very long lists.
1591 Setting this variable to nil causes subtrees of a match to be skipped.
1592 This option is off by default, because inheritance in on. If you turn
1593 inheritance off, you very likely want to turn this option on.
1595 As a special case, if the tag search is restricted to TODO items, the
1596 value of this variable is ignored and sublevels are always checked, to
1597 make sure all corresponding TODO items find their way into the list."
1598 :group 'org-tags
1599 :type 'boolean)
1601 (defvar org-tags-history nil
1602 "History of minibuffer reads for tags.")
1603 (defvar org-last-tags-completion-table nil
1604 "The last used completion table for tags.")
1606 (defgroup org-agenda nil
1607 "Options concerning agenda views in Org-mode."
1608 :tag "Org Agenda"
1609 :group 'org)
1611 (defvar org-category nil
1612 "Variable used by org files to set a category for agenda display.
1613 Such files should use a file variable to set it, for example
1615 -*- mode: org; org-category: \"ELisp\"
1617 or contain a special line
1619 #+CATEGORY: ELisp
1621 If the file does not specify a category, then file's base name
1622 is used instead.")
1623 (make-variable-buffer-local 'org-category)
1625 (defcustom org-agenda-files nil
1626 "The files to be used for agenda display.
1627 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1628 \\[org-remove-file]. You can also use customize to edit the list.
1630 If the value of the variable is not a list but a single file name, then
1631 the list of agenda files is actually stored and maintained in that file, one
1632 agenda file per line."
1633 :group 'org-agenda
1634 :type '(choice
1635 (repeat :tag "List of files" file)
1636 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1639 (defcustom org-agenda-confirm-kill 1
1640 "When set, remote killing from the agenda buffer needs confirmation.
1641 When t, a confirmation is always needed. When a number N, confirmation is
1642 only needed when the text to be killed contains more than N non-white lines."
1643 :group 'org-agenda
1644 :type '(choice
1645 (const :tag "Never" nil)
1646 (const :tag "Always" t)
1647 (number :tag "When more than N lines")))
1649 (defcustom org-calendar-to-agenda-key [?c]
1650 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1651 The command `org-calendar-goto-agenda' will be bound to this key. The
1652 default is the character `c' because then `c' can be used to switch back and
1653 forth between agenda and calendar."
1654 :group 'org-agenda
1655 :type 'sexp)
1657 (defgroup org-agenda-custom-commands nil
1658 "Options concerning agenda views in Org-mode."
1659 :tag "Org Agenda Custom Commands"
1660 :group 'org-agenda)
1662 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1663 "Custom commands for the agenda.
1664 These commands will be offered on the splash screen displayed by the
1665 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1667 (key type match options)
1669 key The key (a single char as a string) to be associated with the command.
1670 type The command type, any of the following symbols:
1671 todo Entries with a specific TODO keyword, in all agenda files.
1672 tags Tags match in all agenda files.
1673 tags-todo Tags match in all agenda files, TODO entries only.
1674 todo-tree Sparse tree of specific TODO keyword in *current* file.
1675 tags-tree Sparse tree with all tags matches in *current* file.
1676 occur-tree Occur sparse tree for *current* file.
1677 match What to search for:
1678 - a single keyword for TODO keyword searches
1679 - a tags match expression for tags searches
1680 - a regular expression for occur searches
1681 options A list of option setttings, similar to that in a let form, so like
1682 this: ((opt1 val1) (opt2 val2) ...)
1684 You can also define a set of commands, to create a composite agenda buffer.
1685 In this case, an entry looks like this:
1687 (key desc (cmd1 cmd2 ...) general-options)
1689 where
1691 desc A description string to be displayed in the dispatcher menu.
1692 cmd An agenda command, similar to the above. However, tree commands
1693 are no allowed, but instead you can get agenda and global todo list.
1694 So valid commands for a set are:
1695 (agenda)
1696 (alltodo)
1697 (stuck)
1698 (todo \"match\" options)
1699 (tags \"match\" options )
1700 (tags-todo \"match\" options)
1702 Each command can carry a list of options, and another set of options can be
1703 given for the whole set of commands. Individual command options take
1704 precedence over the general options."
1705 :group 'org-agenda-custom-commands
1706 :type '(repeat
1707 (choice
1708 (list :tag "Single command"
1709 (string :tag "Key")
1710 (choice
1711 (const :tag "Tags search (all agenda files)" tags)
1712 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1713 (const :tag "TODO keyword search (all agenda files)" todo)
1714 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1715 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1716 (const :tag "Occur tree (current buffer)" occur-tree)
1717 (symbol :tag "Other, user-defined function"))
1718 (string :tag "Match")
1719 (repeat :tag "Local options"
1720 (list (variable :tag "Option") (sexp :tag "Value"))))
1721 (list :tag "Command series, all agenda files"
1722 (string :tag "Key")
1723 (string :tag "Description")
1724 (repeat
1725 (choice
1726 (const :tag "Agenda" (agenda))
1727 (const :tag "TODO list" (alltodo))
1728 (const :tag "Stuck projects" (stuck))
1729 (list :tag "Tags search"
1730 (const :format "" tags)
1731 (string :tag "Match")
1732 (repeat :tag "Local options"
1733 (list (variable :tag "Option")
1734 (sexp :tag "Value"))))
1736 (list :tag "Tags search, TODO entries only"
1737 (const :format "" tags-todo)
1738 (string :tag "Match")
1739 (repeat :tag "Local options"
1740 (list (variable :tag "Option")
1741 (sexp :tag "Value"))))
1743 (list :tag "TODO keyword search"
1744 (const :format "" todo)
1745 (string :tag "Match")
1746 (repeat :tag "Local options"
1747 (list (variable :tag "Option")
1748 (sexp :tag "Value"))))
1750 (list :tag "Other, user-defined function"
1751 (symbol :tag "function")
1752 (string :tag "Match")
1753 (repeat :tag "Local options"
1754 (list (variable :tag "Option")
1755 (sexp :tag "Value"))))))
1757 (repeat :tag "General options"
1758 (list (variable :tag "Option")
1759 (sexp :tag "Value")))))))
1761 (defcustom org-stuck-projects
1762 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil)
1763 "How to identify stuck projects.
1764 This is a list of three items:
1765 1. A tags/todo matcher string that is used to identify a project.
1766 The entire tree below a headline matched by this is considered a project.
1767 2. A list of TODO keywords itentifying non-stuck projects.
1768 If the project subtree contains any headline with one of these todo
1769 keywords, the project is consitered to be not stuck.
1770 3. A list of tags identifying non-stuck projects.
1771 If the project subtree contains any headline with one of these tags,
1772 the project is consitered to be not stuck.
1774 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1775 or `C-c a #' to produce the list."
1776 :group 'org-agenda-custom-commands
1777 :type '(list
1778 (string :tag "Tags/TODO match to identify a project")
1779 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1780 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))))
1783 (defgroup org-agenda-skip nil
1784 "Options concerning skipping parts of agenda files."
1785 :tag "Org Agenda Skip"
1786 :group 'org-agenda)
1788 (defcustom org-agenda-todo-list-sublevels t
1789 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1790 When nil, the sublevels of a TODO entry are not checked, resulting in
1791 potentially much shorter TODO lists."
1792 :group 'org-agenda-skip
1793 :group 'org-todo
1794 :type 'boolean)
1796 (defcustom org-agenda-todo-ignore-scheduled nil
1797 "Non-nil means, don't show scheduled entries in the global todo list.
1798 The idea behind this is that by scheduling it, you have already taken care
1799 of this item."
1800 :group 'org-agenda-skip
1801 :group 'org-todo
1802 :type 'boolean)
1804 (defcustom org-agenda-todo-ignore-deadlines nil
1805 "Non-nil means, don't show near deadline entries in the global todo list.
1806 Near means closer than `org-deadline-warning-days' days.
1807 The idea behind this is that such items will appear in the agenda anyway."
1808 :group 'org-agenda-skip
1809 :group 'org-todo
1810 :type 'boolean)
1812 (defcustom org-agenda-skip-scheduled-if-done nil
1813 "Non-nil means don't show scheduled items in agenda when they are done.
1814 This is relevant for the daily/weekly agenda, not for the TODO list."
1815 :group 'org-agenda-skip
1816 :type 'boolean)
1818 (defcustom org-timeline-show-empty-dates 3
1819 "Non-nil means, `org-timeline' also shows dates without an entry.
1820 When nil, only the days which actually have entries are shown.
1821 When t, all days between the first and the last date are shown.
1822 When an integer, show also empty dates, but if there is a gap of more than
1823 N days, just insert a special line indicating the size of the gap."
1824 :group 'org-agenda-skip
1825 :type '(choice
1826 (const :tag "None" nil)
1827 (const :tag "All" t)
1828 (number :tag "at most")))
1831 (defgroup org-agenda-startup nil
1832 "Options concerning initial settings in the Agenda in Org Mode."
1833 :tag "Org Agenda Startup"
1834 :group 'org-agenda)
1836 (defcustom org-finalize-agenda-hook nil
1837 "Hook run just before displaying an agenda buffer."
1838 :group 'org-agenda-startup
1839 :type 'hook)
1841 (defcustom org-agenda-mouse-1-follows-link nil
1842 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1843 A longer mouse click will still set point. Does not wortk on XEmacs.
1844 Needs to be set before org.el is loaded."
1845 :group 'org-agenda-startup
1846 :type 'boolean)
1848 (defcustom org-agenda-start-with-follow-mode nil
1849 "The initial value of follwo-mode in a newly created agenda window."
1850 :group 'org-agenda-startup
1851 :type 'boolean)
1853 (defgroup org-agenda-windows nil
1854 "Options concerning the windows used by the Agenda in Org Mode."
1855 :tag "Org Agenda Windows"
1856 :group 'org-agenda)
1858 (defcustom org-agenda-window-setup 'reorganize-frame
1859 "How the agenda buffer should be displayed.
1860 Possible values for this option are:
1862 current-window Show agenda in the current window, keeping all other windows.
1863 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1864 other-window Use `switch-to-buffer-other-window' to display agenda.
1865 reorganize-frame Show only two windows on the current frame, the current
1866 window and the agenda.
1867 See also the variable `org-agenda-restore-windows-after-quit'."
1868 :group 'org-agenda-windows
1869 :type '(choice
1870 (const current-window)
1871 (const other-frame)
1872 (const other-window)
1873 (const reorganize-frame)))
1875 (defcustom org-agenda-restore-windows-after-quit nil
1876 "Non-nil means, restore window configuration open exiting agenda.
1877 Before the window configuration is changed for displaying the agenda,
1878 the current status is recorded. When the agenda is exited with
1879 `q' or `x' and this option is set, the old state is restored. If
1880 `org-agenda-window-setup' is `other-frame', the value of this
1881 option will be ignored.."
1882 :group 'org-agenda-windows
1883 :type 'boolean)
1885 (defcustom org-indirect-buffer-display 'other-window
1886 "How should indirect tree buffers be displayed?
1887 This applies to indirect buffers created with the commands
1888 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1889 Valid values are:
1890 current-window Display in the current window
1891 other-window Just display in another window.
1892 dedicated-frame Create one new frame, and re-use it each time.
1893 new-frame Make a new frame each time."
1894 :group 'org-structure
1895 :group 'org-agenda-windows
1896 :type '(choice
1897 (const :tag "In current window" current-window)
1898 (const :tag "In current frame, other window" other-window)
1899 (const :tag "Each time a new frame" new-frame)
1900 (const :tag "One dedicated frame" dedicated-frame)))
1902 (defgroup org-agenda-daily/weekly nil
1903 "Options concerning the daily/weekly agenda."
1904 :tag "Org Agenda Daily/Weekly"
1905 :group 'org-agenda)
1907 (defcustom org-agenda-ndays 7
1908 "Number of days to include in overview display.
1909 Should be 1 or 7."
1910 :group 'org-agenda-daily/weekly
1911 :type 'number)
1913 (defcustom org-agenda-start-on-weekday 1
1914 "Non-nil means, start the overview always on the specified weekday.
1915 0 denotes Sunday, 1 denotes Monday etc.
1916 When nil, always start on the current day."
1917 :group 'org-agenda-daily/weekly
1918 :type '(choice (const :tag "Today" nil)
1919 (number :tag "Weekday No.")))
1921 (defcustom org-agenda-show-all-dates t
1922 "Non-nil means, `org-agenda' shows every day in the selected range.
1923 When nil, only the days which actually have entries are shown."
1924 :group 'org-agenda-daily/weekly
1925 :type 'boolean)
1927 (defcustom org-agenda-date-format "%A %d %B %Y"
1928 "Format string for displaying dates in the agenda.
1929 Used by the daily/weekly agenda and by the timeline. This should be
1930 a format string understood by `format-time-string'.
1931 FIXME: Not used currently, because of timezone problem."
1932 :group 'org-agenda-daily/weekly
1933 :type 'string)
1935 (defcustom org-agenda-include-diary nil
1936 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1937 :group 'org-agenda-daily/weekly
1938 :type 'boolean)
1940 (defcustom org-agenda-include-all-todo nil
1941 "Set means weekly/daily agenda will always contain all TODO entries.
1942 The TODO entries will be listed at the top of the agenda, before
1943 the entries for specific days."
1944 :group 'org-agenda-daily/weekly
1945 :type 'boolean)
1947 (defgroup org-agenda-time-grid nil
1948 "Options concerning the time grid in the Org-mode Agenda."
1949 :tag "Org Agenda Time Grid"
1950 :group 'org-agenda)
1952 (defcustom org-agenda-use-time-grid t
1953 "Non-nil means, show a time grid in the agenda schedule.
1954 A time grid is a set of lines for specific times (like every two hours between
1955 8:00 and 20:00). The items scheduled for a day at specific times are
1956 sorted in between these lines.
1957 For details about when the grid will be shown, and what it will look like, see
1958 the variable `org-agenda-time-grid'."
1959 :group 'org-agenda-time-grid
1960 :type 'boolean)
1962 (defcustom org-agenda-time-grid
1963 '((daily today require-timed)
1964 "----------------"
1965 (800 1000 1200 1400 1600 1800 2000))
1967 "The settings for time grid for agenda display.
1968 This is a list of three items. The first item is again a list. It contains
1969 symbols specifying conditions when the grid should be displayed:
1971 daily if the agenda shows a single day
1972 weekly if the agenda shows an entire week
1973 today show grid on current date, independent of daily/weekly display
1974 require-timed show grid only if at least one item has a time specification
1976 The second item is a string which will be places behing the grid time.
1978 The third item is a list of integers, indicating the times that should have
1979 a grid line."
1980 :group 'org-agenda-time-grid
1981 :type
1982 '(list
1983 (set :greedy t :tag "Grid Display Options"
1984 (const :tag "Show grid in single day agenda display" daily)
1985 (const :tag "Show grid in weekly agenda display" weekly)
1986 (const :tag "Always show grid for today" today)
1987 (const :tag "Show grid only if any timed entries are present"
1988 require-timed)
1989 (const :tag "Skip grid times already present in an entry"
1990 remove-match))
1991 (string :tag "Grid String")
1992 (repeat :tag "Grid Times" (integer :tag "Time"))))
1994 (defgroup org-agenda-sorting nil
1995 "Options concerning sorting in the Org-mode Agenda."
1996 :tag "Org Agenda Sorting"
1997 :group 'org-agenda)
1999 (let ((sorting-choice
2000 '(choice
2001 (const time-up) (const time-down)
2002 (const category-keep) (const category-up) (const category-down)
2003 (const tag-down) (const tag-up)
2004 (const priority-up) (const priority-down))))
2006 (defcustom org-agenda-sorting-strategy
2007 '((agenda time-up category-keep priority-down)
2008 (todo category-keep priority-down)
2009 (tags category-keep))
2010 "Sorting structure for the agenda items of a single day.
2011 This is a list of symbols which will be used in sequence to determine
2012 if an entry should be listed before another entry. The following
2013 symbols are recognized:
2015 time-up Put entries with time-of-day indications first, early first
2016 time-down Put entries with time-of-day indications first, late first
2017 category-keep Keep the default order of categories, corresponding to the
2018 sequence in `org-agenda-files'.
2019 category-up Sort alphabetically by category, A-Z.
2020 category-down Sort alphabetically by category, Z-A.
2021 tag-up Sort alphabetically by last tag, A-Z.
2022 tag-down Sort alphabetically by last tag, Z-A.
2023 priority-up Sort numerically by priority, high priority last.
2024 priority-down Sort numerically by priority, high priority first.
2026 The different possibilities will be tried in sequence, and testing stops
2027 if one comparison returns a \"not-equal\". For example, the default
2028 '(time-up category-keep priority-down)
2029 means: Pull out all entries having a specified time of day and sort them,
2030 in order to make a time schedule for the current day the first thing in the
2031 agenda listing for the day. Of the entries without a time indication, keep
2032 the grouped in categories, don't sort the categories, but keep them in
2033 the sequence given in `org-agenda-files'. Within each category sort by
2034 priority.
2036 Leaving out `category-keep' would mean that items will be sorted across
2037 categories by priority."
2038 :group 'org-agenda-sorting
2039 :type `(choice
2040 (repeat :tag "General" ,sorting-choice)
2041 (list :tag "Individually"
2042 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2043 (repeat ,sorting-choice))
2044 (cons (const :tag "Strategy for TODO lists" todo)
2045 (repeat ,sorting-choice))
2046 (cons (const :tag "Strategy for Tags matches" tags)
2047 (repeat ,sorting-choice))))))
2049 (defcustom org-sort-agenda-notime-is-late t
2050 "Non-nil means, items without time are considered late.
2051 This is only relevant for sorting. When t, items which have no explicit
2052 time like 15:30 will be considered as 99:01, i.e. later than any items which
2053 do have a time. When nil, the default time is before 0:00. You can use this
2054 option to decide if the schedule for today should come before or after timeless
2055 agenda entries."
2056 :group 'org-agenda-sorting
2057 :type 'boolean)
2059 (defgroup org-agenda-prefix nil
2060 "Options concerning the entry prefix in the Org-mode agenda display."
2061 :tag "Org Agenda Prefix"
2062 :group 'org-agenda)
2064 (defcustom org-agenda-prefix-format
2065 '((agenda . " %-12:c%?-12t% s")
2066 (timeline . " % s")
2067 (todo . " %-12:c")
2068 (tags . " %-12:c"))
2069 "Format specifications for the prefix of items in the agenda views.
2070 An alist with four entries, for the different agenda types. The keys to the
2071 sublists are `agenda', `timeline', `todo', and `tags'. The values
2072 are format strings.
2073 This format works similar to a printf format, with the following meaning:
2075 %c the category of the item, \"Diary\" for entries from the diary, or
2076 as given by the CATEGORY keyword or derived from the file name.
2077 %T the *last* tag of the item. Last because inherited tags come
2078 first in the list.
2079 %t the time-of-day specification if one applies to the entry, in the
2080 format HH:MM
2081 %s Scheduling/Deadline information, a short string
2083 All specifiers work basically like the standard `%s' of printf, but may
2084 contain two additional characters: A question mark just after the `%' and
2085 a whitespace/punctuation character just before the final letter.
2087 If the first character after `%' is a question mark, the entire field
2088 will only be included if the corresponding value applies to the
2089 current entry. This is useful for fields which should have fixed
2090 width when present, but zero width when absent. For example,
2091 \"%?-12t\" will result in a 12 character time field if a time of the
2092 day is specified, but will completely disappear in entries which do
2093 not contain a time.
2095 If there is punctuation or whitespace character just before the final
2096 format letter, this character will be appended to the field value if
2097 the value is not empty. For example, the format \"%-12:c\" leads to
2098 \"Diary: \" if the category is \"Diary\". If the category were be
2099 empty, no additional colon would be interted.
2101 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2102 - Indent the line with two space characters
2103 - Give the category in a 12 chars wide field, padded with whitespace on
2104 the right (because of `-'). Append a colon if there is a category
2105 (because of `:').
2106 - If there is a time-of-day, put it into a 12 chars wide field. If no
2107 time, don't put in an empty field, just skip it (because of '?').
2108 - Finally, put the scheduling information and append a whitespace.
2110 As another example, if you don't want the time-of-day of entries in
2111 the prefix, you could use:
2113 (setq org-agenda-prefix-format \" %-11:c% s\")
2115 See also the variables `org-agenda-remove-times-when-in-prefix' and
2116 `org-agenda-remove-tags-when-in-prefix'."
2117 :type '(choice
2118 (string :tag "General format")
2119 (list :greedy t :tag "View dependent"
2120 (cons (const agenda) (string :tag "Format"))
2121 (cons (const timeline) (string :tag "Format"))
2122 (cons (const todo) (string :tag "Format"))
2123 (cons (const tags) (string :tag "Format"))))
2124 :group 'org-agenda-prefix)
2126 (defvar org-prefix-format-compiled nil
2127 "The compiled version of the most recently used prefix format.
2128 See the variable `org-agenda-prefix-format'.")
2130 (defcustom org-agenda-remove-times-when-in-prefix t
2131 "Non-nil means, remove duplicate time specifications in agenda items.
2132 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2133 time-of-day specification in a headline or diary entry is extracted and
2134 placed into the prefix. If this option is non-nil, the original specification
2135 \(a timestamp or -range, or just a plain time(range) specification like
2136 11:30-4pm) will be removed for agenda display. This makes the agenda less
2137 cluttered.
2138 The option can be t or nil. It may also be the symbol `beg', indicating
2139 that the time should only be removed what it is located at the beginning of
2140 the headline/diary entry."
2141 :group 'org-agenda-prefix
2142 :type '(choice
2143 (const :tag "Always" t)
2144 (const :tag "Never" nil)
2145 (const :tag "When at beginning of entry" beg)))
2147 (defcustom org-agenda-remove-tags-when-in-prefix nil
2148 "Non-nil means, remove the tags from the headline copy in the agenda.
2149 When this is the symbol `prefix', only remove tags when
2150 `org-agenda-prefix-format' contains a `%T' specifier."
2151 :group 'org-agenda-prefix
2152 :type '(choice
2153 (const :tag "Always" t)
2154 (const :tag "Never" nil)
2155 (const :tag "When prefix format contains %T" prefix)))
2157 (defcustom org-agenda-align-tags-to-column 65
2158 "Shift tags in agenda items to this column."
2159 :group 'org-agenda-prefix
2160 :type 'integer)
2162 (defgroup org-latex nil
2163 "Options for embedding LaTeX code into Org-mode"
2164 :tag "Org LaTeX"
2165 :group 'org)
2167 (defcustom org-format-latex-options
2168 '(:foreground "Black" :background "Transparent" :scale 1.0
2169 :matchers ("begin" "$" "$$" "\\(" "\\["))
2170 "Options for creating images from LaTeX fragments.
2171 This is a property list with the following properties:
2172 :foreground the foreground color, for example \"Black\".
2173 :background the background color, or \"Transparent\".
2174 :scale a scaling factor for the size of the images
2175 :matchers a list indicating which matchers should be used to
2176 find LaTeX fragments. Valid members of this list are:
2177 \"begin\" find environments
2178 \"$\" find math expressions surrounded by $...$
2179 \"$$\" find math expressions surrounded by $$....$$
2180 \"\\(\" find math expressions surrounded by \\(...\\)
2181 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2182 :group 'org-latex
2183 :type 'plist)
2185 (defgroup org-export nil
2186 "Options for exporting org-listings."
2187 :tag "Org Export"
2188 :group 'org)
2190 (defgroup org-export-general nil
2191 "General options for exporting Org-mode files."
2192 :tag "Org Export General"
2193 :group 'org-export)
2195 (defcustom org-export-publishing-directory "."
2196 "Path to the location where exported files should be located.
2197 This path may be relative to the directory where the Org-mode file lives.
2198 The default is to put them into the same directory as the Org-mode file.
2199 The variable may also be an alist with export types `:html', `:ascii',
2200 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2201 is relative, it is interpreted relative to the directory where the exported
2202 Org-mode files lives."
2203 :group 'org-export-general
2204 :type '(choice
2205 (directory)
2206 (repeat
2207 (cons
2208 (choice :tag "Type"
2209 (const :html) (const :ascii) (const :ical) (const :xoxo))
2210 (directory)))))
2212 (defcustom org-export-language-setup
2213 '(("en" "Author" "Date" "Table of Contents")
2214 ("cs" "Autor" "Datum" "Obsah")
2215 ("da" "Ophavsmand" "Dato" "Indhold")
2216 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2217 ("es" "Autor" "Fecha" "\xccndice")
2218 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2219 ("it" "Autore" "Data" "Indice")
2220 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2221 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2222 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2223 "Terms used in export text, translated to different languages.
2224 Use the variable `org-export-default-language' to set the language,
2225 or use the +OPTION lines for a per-file setting."
2226 :group 'org-export-general
2227 :type '(repeat
2228 (list
2229 (string :tag "HTML language tag")
2230 (string :tag "Author")
2231 (string :tag "Date")
2232 (string :tag "Table of Contents"))))
2234 (defcustom org-export-default-language "en"
2235 "The default language of HTML export, as a string.
2236 This should have an association in `org-export-language-setup'."
2237 :group 'org-export-general
2238 :type 'string)
2240 (defcustom org-export-headline-levels 3
2241 "The last level which is still exported as a headline.
2242 Inferior levels will produce itemize lists when exported.
2243 Note that a numeric prefix argument to an exporter function overrides
2244 this setting.
2246 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2247 :group 'org-export-general
2248 :type 'number)
2250 (defcustom org-export-with-section-numbers t
2251 "Non-nil means, add section numbers to headlines when exporting.
2253 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2254 :group 'org-export-general
2255 :type 'boolean)
2257 (defcustom org-export-with-toc t
2258 "Non-nil means, create a table of contents in exported files.
2259 The TOC contains headlines with levels up to`org-export-headline-levels'.
2260 When an integer, include levels up to N in the toc, this may then be
2261 different from `org-export-headline-levels', but it will not be allowed
2262 to be larger than the number of headline levels.
2263 When nil, no table of contents is made.
2265 Headlines which contain any TODO items will be marked with \"(*)\" in
2266 ASCII export, and with red color in HTML output, if the option
2267 `org-export-mark-todo-in-toc' is set.
2269 In HTML output, the TOC will be clickable.
2271 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2272 or \"toc:3\"."
2273 :group 'org-export-general
2274 :type '(choice
2275 (const :tag "No Table of Contents" nil)
2276 (const :tag "Full Table of Contents" t)
2277 (integer :tag "TOC to level")))
2279 (defcustom org-export-mark-todo-in-toc nil
2280 "Non-nil means, mark TOC lines that contain any open TODO items."
2281 :group 'org-export-general
2282 :type 'boolean)
2284 (defcustom org-export-preserve-breaks nil
2285 "Non-nil means, preserve all line breaks when exporting.
2286 Normally, in HTML output paragraphs will be reformatted. In ASCII
2287 export, line breaks will always be preserved, regardless of this variable.
2289 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2290 :group 'org-export-general
2291 :type 'boolean)
2293 (defcustom org-export-with-archived-trees 'headline
2294 "Whether subtrees with the ARCHIVE tag should be exported.
2295 This can have three different values
2296 nil Do not export, pretend this tree is not present
2297 t Do export the entire tree
2298 headline Only export the headline, but skip the tree below it."
2299 :group 'org-export-general
2300 :group 'org-archive
2301 :type '(choice
2302 (const :tag "not at all" nil)
2303 (const :tag "headline only" 'headline)
2304 (const :tag "entirely" t)))
2306 (defcustom org-export-with-timestamps t
2307 "If nil, do not export time stamps and associated keywords."
2308 :group 'org-export-general
2309 :type 'boolean)
2311 (defcustom org-export-remove-timestamps-from-toc t
2312 "If nil, remove timestamps from the table of contents entries."
2313 :group 'org-export-general
2314 :type 'boolean)
2316 (defcustom org-export-with-tags 'not-in-toc
2317 "If nil, do not export tags, just remove them from headlines.
2318 If this is the symbol `not-in-toc', tags will be removed from table of
2319 contents entries, but still be shown in the headlines of the document."
2320 :group 'org-export-general
2321 :type '(choice
2322 (const :tag "Off" nil)
2323 (const :tag "Not in TOC" not-in-toc)
2324 (const :tag "On" t)))
2326 (defgroup org-export-translation nil
2327 "Options for translating special ascii sequences for the export backends."
2328 :tag "Org Export Translation"
2329 :group 'org-export)
2331 (defcustom org-export-with-emphasize t
2332 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2333 If the export target supports emphasizing text, the word will be
2334 typeset in bold, italic, or underlined, respectively. Works only for
2335 single words, but you can say: I *really* *mean* *this*.
2336 Not all export backends support this.
2338 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2339 :group 'org-export-translation
2340 :type 'boolean)
2342 (defcustom org-export-with-sub-superscripts t
2343 "Non-nil means, interpret \"_\" and \"^\" for export.
2344 When this option is turned on, you can use TeX-like syntax for sub- and
2345 superscripts. Several characters after \"_\" or \"^\" will be
2346 considered as a single item - so grouping with {} is normally not
2347 needed. For example, the following things will be parsed as single
2348 sub- or superscripts.
2350 10^24 or 10^tau several digits will be considered 1 item.
2351 10^-12 or 10^-tau a leading sign with digits or a word
2352 x^2-y^3 will be read as x^2 - y^3, because items are
2353 terminated by almost any nonword/nondigit char.
2354 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2356 Still, ambiguity is possible - so when in doubt use {} to enclose the
2357 sub/superscript.
2358 Not all export backends support this, but HTML does.
2360 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2361 :group 'org-export-translation
2362 :type 'boolean)
2364 (defcustom org-export-with-TeX-macros t
2365 "Non-nil means, interpret simple TeX-like macros when exporting.
2366 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2367 No only real TeX macros will work here, but the standard HTML entities
2368 for math can be used as macro names as well. For a list of supported
2369 names in HTML export, see the constant `org-html-entities'.
2370 Not all export backends support this.
2372 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2373 :group 'org-export-translation
2374 :group 'org-latex
2375 :type 'boolean)
2377 (defcustom org-export-with-LaTeX-fragments nil
2378 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2379 When set, the exporter will find LaTeX environments if the \\begin line is
2380 the first non-white thing on a line. It will also find the math delimiters
2381 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2382 display math.
2384 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2385 :group 'org-export-translation
2386 :group 'org-latex
2387 :type 'boolean)
2389 (defcustom org-export-with-fixed-width t
2390 "Non-nil means, lines starting with \":\" will be in fixed width font.
2391 This can be used to have pre-formatted text, fragments of code etc. For
2392 example:
2393 : ;; Some Lisp examples
2394 : (while (defc cnt)
2395 : (ding))
2396 will be looking just like this in also HTML. See also the QUOTE keyword.
2397 Not all export backends support this.
2399 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2400 :group 'org-export-translation
2401 :type 'boolean)
2403 (defcustom org-match-sexp-depth 3
2404 "Number of stacked braces for sub/superscript matching.
2405 This has to be set before loading org.el to be effective."
2406 :group 'org-export-translation
2407 :type 'integer)
2409 (defgroup org-export-tables nil
2410 "Options for exporting tables in Org-mode."
2411 :tag "Org Export Tables"
2412 :group 'org-export)
2414 (defcustom org-export-with-tables t
2415 "If non-nil, lines starting with \"|\" define a table.
2416 For example:
2418 | Name | Address | Birthday |
2419 |-------------+----------+-----------|
2420 | Arthur Dent | England | 29.2.2100 |
2422 Not all export backends support this.
2424 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2425 :group 'org-export-tables
2426 :type 'boolean)
2428 (defcustom org-export-highlight-first-table-line t
2429 "Non-nil means, highlight the first table line.
2430 In HTML export, this means use <th> instead of <td>.
2431 In tables created with table.el, this applies to the first table line.
2432 In Org-mode tables, all lines before the first horizontal separator
2433 line will be formatted with <th> tags."
2434 :group 'org-export-tables
2435 :type 'boolean)
2437 (defcustom org-export-table-remove-special-lines t
2438 "Remove special lines and marking characters in calculating tables.
2439 This removes the special marking character column from tables that are set
2440 up for spreadsheet calculations. It also removes the entire lines
2441 marked with `!', `_', or `^'. The lines with `$' are kept, because
2442 the values of constants may be useful to have."
2443 :group 'org-export-tables
2444 :type 'boolean)
2446 (defcustom org-export-prefer-native-exporter-for-tables nil
2447 "Non-nil means, always export tables created with table.el natively.
2448 Natively means, use the HTML code generator in table.el.
2449 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2450 the table does not use row- or column-spanning). This has the
2451 advantage, that the automatic HTML conversions for math symbols and
2452 sub/superscripts can be applied. Org-mode's HTML generator is also
2453 much faster."
2454 :group 'org-export-tables
2455 :type 'boolean)
2457 (defgroup org-export-ascii nil
2458 "Options specific for ASCII export of Org-mode files."
2459 :tag "Org Export ASCII"
2460 :group 'org-export)
2462 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2463 "Characters for underlining headings in ASCII export.
2464 In the given sequence, these characters will be used for level 1, 2, ..."
2465 :group 'org-export-ascii
2466 :type '(repeat character))
2468 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2469 "Bullet characters for headlines converted to lists in ASCII export.
2470 The first character is is used for the first lest level generated in this
2471 way, and so on. If there are more levels than characters given here,
2472 the list will be repeated.
2473 Note that plain lists will keep the same bullets as the have in the
2474 Org-mode file."
2475 :group 'org-export-ascii
2476 :type '(repeat character))
2478 (defgroup org-export-xml nil
2479 "Options specific for XML export of Org-mode files."
2480 :tag "Org Export XML"
2481 :group 'org-export)
2483 (defgroup org-export-html nil
2484 "Options specific for HTML export of Org-mode files."
2485 :tag "Org Export HTML"
2486 :group 'org-export)
2488 (defcustom org-export-html-style
2489 "<style type=\"text/css\">
2490 html {
2491 font-family: Times, serif;
2492 font-size: 12pt;
2494 .title { text-align: center; }
2495 .todo { color: red; }
2496 .done { color: green; }
2497 .timestamp { color: grey }
2498 .timestamp-kwd { color: CadetBlue }
2499 .tag { background-color:lightblue; font-weight:normal }
2500 .target { background-color: lavender; }
2501 pre {
2502 border: 1pt solid #AEBDCC;
2503 background-color: #F3F5F7;
2504 padding: 5pt;
2505 font-family: courier, monospace;
2507 table { border-collapse: collapse; }
2508 td, th {
2509 vertical-align: top;
2510 <!--border: 1pt solid #ADB9CC;-->
2512 </style>"
2513 "The default style specification for exported HTML files.
2514 Since there are different ways of setting style information, this variable
2515 needs to contain the full HTML structure to provide a style, including the
2516 surrounding HTML tags. The style specifications should include definitions
2517 for new classes todo, done, title, and deadline. For example, legal values
2518 would be:
2520 <style type=\"text/css\">
2521 p { font-weight: normal; color: gray; }
2522 h1 { color: black; }
2523 .title { text-align: center; }
2524 .todo, .deadline { color: red; }
2525 .done { color: green; }
2526 </style>
2528 or, if you want to keep the style in a file,
2530 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2532 As the value of this option simply gets inserted into the HTML <head> header,
2533 you can \"misuse\" it to add arbitrary text to the header."
2534 :group 'org-export-html
2535 :type 'string)
2537 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2538 "Format for typesetting the document title in HTML export."
2539 :group 'org-export-html
2540 :type 'string)
2542 (defcustom org-export-html-toplevel-hlevel 2
2543 "The <H> level for level 1 headings in HTML export."
2544 :group 'org-export-html
2545 :type 'string)
2547 (defcustom org-export-html-link-org-files-as-html t
2548 "Non-nil means, make file links to `file.org' point to `file.html'.
2549 When org-mode is exporting an org-mode file to HTML, links to
2550 non-html files are directly put into a href tag in HTML.
2551 However, links to other Org-mode files (recognized by the
2552 extension `.org.) should become links to the corresponding html
2553 file, assuming that the linked org-mode file will also be
2554 converted to HTML.
2555 When nil, the links still point to the plain `.org' file."
2556 :group 'org-export-html
2557 :type 'boolean)
2559 (defcustom org-export-html-inline-images 'maybe
2560 "Non-nil means, inline images into exported HTML pages.
2561 This is done using an <img> tag. When nil, an anchor with href is used to
2562 link to the image. If this option is `maybe', then images in links with
2563 an empty description will be inlined, while images with a description will
2564 be linked only."
2565 :group 'org-export-html
2566 :type '(choice (const :tag "Never" nil)
2567 (const :tag "Always" t)
2568 (const :tag "When there is no description" maybe)))
2570 ;; FIXME: rename
2571 (defcustom org-export-html-expand t
2572 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2573 When nil, these tags will be exported as plain text and therefore
2574 not be interpreted by a browser.
2576 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2577 :group 'org-export-html
2578 :type 'boolean)
2580 (defcustom org-export-html-table-tag
2581 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
2582 "The HTML tag used to start a table.
2583 This must be a <table> tag, but you may change the options like
2584 borders and spacing."
2585 :group 'org-export-html
2586 :type 'string)
2588 (defcustom org-export-html-with-timestamp nil
2589 "If non-nil, write `org-export-html-html-helper-timestamp'
2590 into the exported HTML text. Otherwise, the buffer will just be saved
2591 to a file."
2592 :group 'org-export-html
2593 :type 'boolean)
2595 (defcustom org-export-html-html-helper-timestamp
2596 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2597 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2598 :group 'org-export-html
2599 :type 'string)
2601 (defgroup org-export-icalendar nil
2602 "Options specific for iCalendar export of Org-mode files."
2603 :tag "Org Export iCalendar"
2604 :group 'org-export)
2606 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2607 "The file name for the iCalendar file covering all agenda files.
2608 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2609 The file name should be absolute."
2610 :group 'org-export-icalendar
2611 :type 'file)
2613 (defcustom org-icalendar-include-todo nil
2614 "Non-nil means, export to iCalendar files should also cover TODO items."
2615 :group 'org-export-icalendar
2616 :type '(choice
2617 (const :tag "None" nil)
2618 (const :tag "Unfinished" t)
2619 (const :tag "All" all)))
2621 (defcustom org-icalendar-combined-name "OrgMode"
2622 "Calendar name for the combined iCalendar representing all agenda files."
2623 :group 'org-export-icalendar
2624 :type 'string)
2626 (defgroup org-font-lock nil
2627 "Font-lock settings for highlighting in Org-mode."
2628 :tag "Org Font Lock"
2629 :group 'org)
2631 (defcustom org-level-color-stars-only nil
2632 "Non-nil means fontify only the stars in each headline.
2633 When nil, the entire headline is fontified.
2634 Changing it requires restart of `font-lock-mode' to become effective
2635 also in regions already fontified."
2636 :group 'org-font-lock
2637 :type 'boolean)
2639 (defcustom org-hide-leading-stars nil
2640 "Non-nil means, hide the first N-1 stars in a headline.
2641 This works by using the face `org-hide' for these stars. This
2642 face is white for a light background, and black for a dark
2643 background. You may have to customize the face `org-hide' to
2644 make this work.
2645 Changing it requires restart of `font-lock-mode' to become effective
2646 also in regions already fontified.
2647 You may also set this on a per-file basis by adding one of the following
2648 lines to the buffer:
2650 #+STARTUP: hidestars
2651 #+STARTUP: showstars"
2652 :group 'org-font-lock
2653 :type 'boolean)
2655 (defcustom org-fontify-done-headline nil
2656 "Non-nil means, change the face of a headline if it is marked DONE.
2657 Normally, only the TODO/DONE keyword indicates the state of a headline.
2658 When this is non-nil, the headline after the keyword is set to the
2659 `org-headline-done' as an additional indication."
2660 :group 'org-font-lock
2661 :type 'boolean)
2663 (defcustom org-fontify-emphasized-text t
2664 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2665 Changing this variable requires a restart of Emacs to take effect."
2666 :group 'org-font-lock
2667 :type 'boolean)
2669 (defvar org-emph-re nil
2670 "Regular expression for matching emphasis.")
2671 (defvar org-emphasis-regexp-components) ; defined just below
2672 (defvar org-emphasis-alist) ; defined just below
2673 (defun org-set-emph-re (var val)
2674 "Set variable and compute the emphasis regular expression."
2675 (set var val)
2676 (when (and (boundp 'org-emphasis-alist)
2677 (boundp 'org-emphasis-regexp-components)
2678 org-emphasis-alist org-emphasis-regexp-components)
2679 (let* ((e org-emphasis-regexp-components)
2680 (pre (car e))
2681 (post (nth 1 e))
2682 (border (nth 2 e))
2683 (body (nth 3 e))
2684 (nl (nth 4 e))
2685 (stacked (nth 5 e))
2686 (body1 (concat body "*?"))
2687 (markers (mapconcat 'car org-emphasis-alist "")))
2688 ;; make sure special characters appear at the right position in the class
2689 (if (string-match "\\^" markers)
2690 (setq markers (concat (replace-match "" t t markers) "^")))
2691 (if (string-match "-" markers)
2692 (setq markers (concat (replace-match "" t t markers) "-")))
2693 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2694 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2695 (if (> nl 0)
2696 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2697 (int-to-string nl) "\\}")))
2698 ;; Make the regexp
2699 (setq org-emph-re
2700 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2701 "\\("
2702 "\\([" markers "]\\)"
2703 "\\("
2704 "[^" border markers "]"
2705 body1
2706 "[^" border markers "]"
2707 "\\)"
2708 "\\3\\)"
2709 "\\([" post (if stacked markers) "]\\|$\\)")))))
2711 (defcustom org-emphasis-regexp-components
2712 '(" \t('\"" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2713 "Components used to build the reqular expression for emphasis.
2714 This is a list with 6 entries. Terminology: In an emphasis string
2715 like \" *strong word* \", we call the initial space PREMATCH, the final
2716 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2717 and \"trong wor\" is the body. The different components in this variable
2718 specify what is allowed/forbidden in each part:
2720 pre Chars allowed as prematch. Beginning of line will be allowed too.
2721 post Chars allowed as postmatch. End of line will be allowed too.
2722 border The chars *forbidden* as border characters. In addition to the
2723 characters given here, all marker characters are forbidden too.
2724 body-regexp A regexp like \".\" to match a body character. Don't use
2725 non-shy groups here, and don't allow newline here.
2726 newline The maximum number of newlines allowed in an emphasis exp.
2727 stacked Non-nil means, allow stacked styles. This works only in HTML
2728 export. When this is set, all marker characters (as given in
2729 `org-emphasis-alist') will be allowed as pre/post, aiding
2730 inside-out matching.
2731 Use customize to modify this, or restart Emacs after changing it."
2732 :group 'org-font-lock
2733 :set 'org-set-emph-re
2734 :type '(list
2735 (sexp :tag "Allowed chars in pre ")
2736 (sexp :tag "Allowed chars in post ")
2737 (sexp :tag "Forbidden chars in border ")
2738 (sexp :tag "Regexp for body ")
2739 (integer :tag "number of newlines allowed")
2740 (boolean :tag "Stacking allowed ")))
2742 (defcustom org-emphasis-alist
2743 '(("*" bold "<b>" "</b>")
2744 ("/" italic "<i>" "</i>")
2745 ("_" underline "<u>" "</u>")
2746 ("=" shadow "<code>" "</code>")
2747 ("+" (:strike-through t) "<del>" "</del>")
2749 "Special syntax for emphasized text.
2750 Text starting and ending with a special character will be emphasized, for
2751 example *bold*, _underlined_ and /italic/. This variable sets the marker
2752 characters, the face to bbe used by font-lock for highlighting in Org-mode
2753 Emacs buffers, and the HTML tags to be used for this.
2754 Use customize to modify this, or restart Emacs after changing it."
2755 :group 'org-font-lock
2756 :set 'org-set-emph-re
2757 :type '(repeat
2758 (list
2759 (string :tag "Marker character")
2760 (choice
2761 (face :tag "Font-lock-face")
2762 (plist :tag "Face property list"))
2763 (string :tag "HTML start tag")
2764 (string :tag "HTML end tag"))))
2766 ;;; The faces
2768 (defgroup org-faces nil
2769 "Faces in Org-mode."
2770 :tag "Org Faces"
2771 :group 'org-font-lock)
2773 (defun org-compatible-face (specs)
2774 "Make a compatible face specification.
2775 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2776 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2777 to the top of the list. The `min-colors' attribute will be removed from
2778 any other entries, and any resulting duplicates will be removed entirely."
2779 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2780 (let (r e a)
2781 (while (setq e (pop specs))
2782 (cond
2783 ((memq (car e) '(t default)) (push e r))
2784 ((setq a (member '(min-colors 8) (car e)))
2785 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2786 (cdr e)))))
2787 ((setq a (assq 'min-colors (car e)))
2788 (setq e (cons (delq a (car e)) (cdr e)))
2789 (or (assoc (car e) r) (push e r)))
2790 (t (or (assoc (car e) r) (push e r)))))
2791 (nreverse r))
2792 specs))
2794 (defface org-hide
2795 '((((background light)) (:foreground "white"))
2796 (((background dark)) (:foreground "black")))
2797 "Face used to hide leading stars in headlines.
2798 The forground color of this face should be equal to the background
2799 color of the frame."
2800 :group 'org-faces)
2802 (defface org-level-1 ;; font-lock-function-name-face
2803 (org-compatible-face
2804 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2805 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2806 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2807 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2808 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2809 (t (:bold t))))
2810 "Face used for level 1 headlines."
2811 :group 'org-faces)
2813 (defface org-level-2 ;; font-lock-variable-name-face
2814 (org-compatible-face
2815 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2816 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2817 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2818 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2819 (t (:bold t))))
2820 "Face used for level 2 headlines."
2821 :group 'org-faces)
2823 (defface org-level-3 ;; font-lock-keyword-face
2824 (org-compatible-face
2825 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2826 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2827 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2828 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2829 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2830 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2831 (t (:bold t))))
2832 "Face used for level 3 headlines."
2833 :group 'org-faces)
2835 (defface org-level-4 ;; font-lock-comment-face
2836 (org-compatible-face
2837 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2838 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2839 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2840 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2841 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2842 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2843 (t (:bold t))))
2844 "Face used for level 4 headlines."
2845 :group 'org-faces)
2847 (defface org-level-5 ;; font-lock-type-face
2848 (org-compatible-face
2849 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2850 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2851 (((class color) (min-colors 8)) (:foreground "green"))))
2852 "Face used for level 5 headlines."
2853 :group 'org-faces)
2855 (defface org-level-6 ;; font-lock-constant-face
2856 (org-compatible-face
2857 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2858 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2859 (((class color) (min-colors 8)) (:foreground "magenta"))))
2860 "Face used for level 6 headlines."
2861 :group 'org-faces)
2863 (defface org-level-7 ;; font-lock-builtin-face
2864 (org-compatible-face
2865 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2866 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2867 (((class color) (min-colors 8)) (:foreground "blue"))))
2868 "Face used for level 7 headlines."
2869 :group 'org-faces)
2871 (defface org-level-8 ;; font-lock-string-face
2872 (org-compatible-face
2873 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2874 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2875 (((class color) (min-colors 8)) (:foreground "green"))))
2876 "Face used for level 8 headlines."
2877 :group 'org-faces)
2879 (defface org-special-keyword ;; font-lock-string-face
2880 (org-compatible-face
2881 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2882 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2883 (t (:italic t))))
2884 "Face used for special keywords."
2885 :group 'org-faces)
2887 (defface org-warning ;; font-lock-warning-face
2888 (org-compatible-face
2889 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2890 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2891 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2892 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2893 (t (:bold t))))
2894 "Face for deadlines and TODO keywords."
2895 :group 'org-faces)
2897 (defface org-headline-done ;; font-lock-string-face
2898 (org-compatible-face
2899 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2900 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2901 (((class color) (min-colors 8) (background light)) (:bold nil))))
2902 "Face used to indicate that a headline is DONE.
2903 This face is only used if `org-fontify-done-headline' is set."
2904 :group 'org-faces)
2906 (defface org-archived ; similar to shadow
2907 (org-compatible-face
2908 '((((class color grayscale) (min-colors 88) (background light))
2909 (:foreground "grey50"))
2910 (((class color grayscale) (min-colors 88) (background dark))
2911 (:foreground "grey70"))
2912 (((class color) (min-colors 8) (background light))
2913 (:foreground "green"))
2914 (((class color) (min-colors 8) (background dark))
2915 (:foreground "yellow"))))
2916 "Face for headline with the ARCHIVE tag."
2917 :group 'org-faces)
2919 (defface org-link
2920 '((((class color) (background light)) (:foreground "Purple" :underline t))
2921 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2922 (t (:underline t)))
2923 "Face for links."
2924 :group 'org-faces)
2926 (defface org-date
2927 '((((class color) (background light)) (:foreground "Purple" :underline t))
2928 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2929 (t (:underline t)))
2930 "Face for links."
2931 :group 'org-faces)
2933 (defface org-tag
2934 '((t (:bold t)))
2935 "Face for tags."
2936 :group 'org-faces)
2938 (defface org-todo ;; font-lock-warning-face
2939 (org-compatible-face
2940 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2941 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2942 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2943 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2944 (t (:inverse-video t :bold t))))
2945 "Face for TODO keywords."
2946 :group 'org-faces)
2948 (defface org-done ;; font-lock-type-face
2949 (org-compatible-face
2950 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2951 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2952 (((class color) (min-colors 8)) (:foreground "green"))
2953 (t (:bold t))))
2954 "Face used for DONE."
2955 :group 'org-faces)
2957 (defface org-table ;; font-lock-function-name-face
2958 (org-compatible-face
2959 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2960 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2961 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2962 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2963 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2964 (((class color) (min-colors 8) (background dark)))))
2965 "Face used for tables."
2966 :group 'org-faces)
2968 (defface org-formula
2969 (org-compatible-face
2970 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2971 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2972 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2973 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2974 (t (:bold t :italic t))))
2975 "Face for formulas."
2976 :group 'org-faces)
2978 (defface org-scheduled-today
2979 (org-compatible-face
2980 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2981 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2982 (((class color) (min-colors 8)) (:foreground "green"))
2983 (t (:bold t :italic t))))
2984 "Face for items scheduled for a certain day."
2985 :group 'org-faces)
2987 (defface org-scheduled-previously
2988 (org-compatible-face
2989 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2990 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2991 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2992 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2993 (t (:bold t))))
2994 "Face for items scheduled previously, and not yet done."
2995 :group 'org-faces)
2997 (defface org-upcoming-deadline
2998 (org-compatible-face
2999 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3000 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3001 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3002 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3003 (t (:bold t))))
3004 "Face for items scheduled previously, and not yet done."
3005 :group 'org-faces)
3007 (defface org-time-grid ;; font-lock-variable-name-face
3008 (org-compatible-face
3009 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3010 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3011 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3012 "Face used for time grids."
3013 :group 'org-faces)
3015 (defconst org-level-faces
3016 '(org-level-1 org-level-2 org-level-3 org-level-4
3017 org-level-5 org-level-6 org-level-7 org-level-8
3019 (defconst org-n-levels (length org-level-faces))
3022 ;;; Variables for pre-computed regular expressions, all buffer local
3024 (defvar org-done-string nil
3025 "The last string in `org-todo-keywords', indicating an item is DONE.")
3026 (make-variable-buffer-local 'org-done-string)
3027 (defvar org-todo-regexp nil
3028 "Matches any of the TODO state keywords.")
3029 (make-variable-buffer-local 'org-todo-regexp)
3030 (defvar org-not-done-regexp nil
3031 "Matches any of the TODO state keywords except the last one.")
3032 (make-variable-buffer-local 'org-not-done-regexp)
3033 (defvar org-todo-line-regexp nil
3034 "Matches a headline and puts TODO state into group 2 if present.")
3035 (make-variable-buffer-local 'org-todo-line-regexp)
3036 (defvar org-todo-line-tags-regexp nil
3037 "Matches a headline and puts TODO state into group 2 if present.
3038 Also put tags into group 4 if tags are present.")
3039 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3040 (defvar org-nl-done-regexp nil
3041 "Matches newline followed by a headline with the DONE keyword.")
3042 (make-variable-buffer-local 'org-nl-done-regexp)
3043 (defvar org-looking-at-done-regexp nil
3044 "Matches the DONE keyword a point.")
3045 (make-variable-buffer-local 'org-looking-at-done-regexp)
3046 (defvar org-todo-kwd-priority-p nil
3047 "Do TODO items have priorities?")
3048 (make-variable-buffer-local 'org-todo-kwd-priority-p)
3049 (defvar org-todo-kwd-max-priority nil
3050 "Maximum priority of TODO items.")
3051 (make-variable-buffer-local 'org-todo-kwd-max-priority)
3052 (defvar org-ds-keyword-length 12
3053 "Maximum length of the Deadline and SCHEDULED keywords.")
3054 (make-variable-buffer-local 'org-ds-keyword-length)
3055 (defvar org-deadline-regexp nil
3056 "Matches the DEADLINE keyword.")
3057 (make-variable-buffer-local 'org-deadline-regexp)
3058 (defvar org-deadline-time-regexp nil
3059 "Matches the DEADLINE keyword together with a time stamp.")
3060 (make-variable-buffer-local 'org-deadline-time-regexp)
3061 (defvar org-deadline-line-regexp nil
3062 "Matches the DEADLINE keyword and the rest of the line.")
3063 (make-variable-buffer-local 'org-deadline-line-regexp)
3064 (defvar org-scheduled-regexp nil
3065 "Matches the SCHEDULED keyword.")
3066 (make-variable-buffer-local 'org-scheduled-regexp)
3067 (defvar org-scheduled-time-regexp nil
3068 "Matches the SCHEDULED keyword together with a time stamp.")
3069 (make-variable-buffer-local 'org-scheduled-time-regexp)
3070 (defvar org-closed-time-regexp nil
3071 "Matches the CLOSED keyword together with a time stamp.")
3072 (make-variable-buffer-local 'org-closed-time-regexp)
3074 (defvar org-keyword-time-regexp nil
3075 "Matches any of the 4 keywords, together with the time stamp.")
3076 (make-variable-buffer-local 'org-keyword-time-regexp)
3077 (defvar org-keyword-time-not-clock-regexp nil
3078 "Matches any of the 3 keywords, together with the time stamp.")
3079 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3080 (defvar org-maybe-keyword-time-regexp nil
3081 "Matches a timestamp, possibly preceeded by a keyword.")
3082 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3084 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3085 rear-nonsticky t mouse-map t fontified t)
3086 "Properties to remove when a string without properties is wanted.")
3088 (defsubst org-match-string-no-properties (num &optional string)
3089 (if (featurep 'xemacs)
3090 (let ((s (match-string num string)))
3091 (remove-text-properties 0 (length s) org-rm-props s)
3093 (match-string-no-properties num string)))
3095 (defsubst org-no-properties (s)
3096 (remove-text-properties 0 (length s) org-rm-props s)
3099 (defsubst org-get-alist-option (option key)
3100 (cond ((eq key t) t)
3101 ((eq option t) t)
3102 ((assoc key option) (cdr (assoc key option)))
3103 (t (cdr (assq 'default option)))))
3105 (defsubst org-set-local (var value)
3106 "Make VAR local in current buffer and set it to VALUE."
3107 (set (make-variable-buffer-local var) value))
3109 (defsubst org-mode-p ()
3110 "Check if the current buffer is in Org-mode."
3111 (eq major-mode 'org-mode))
3113 (defsubst org-last (list)
3114 "Return the last element of LIST."
3115 (car (last list)))
3117 (defun org-let (list &rest body)
3118 (eval (cons 'let (cons list body))))
3119 (put 'org-let 'lisp-indent-function 1)
3121 (defun org-let2 (list1 list2 &rest body)
3122 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3123 (put 'org-let2 'lisp-indent-function 2)
3124 (defconst org-startup-options
3125 '(("fold" org-startup-folded t)
3126 ("overview" org-startup-folded t)
3127 ("nofold" org-startup-folded nil)
3128 ("showall" org-startup-folded nil)
3129 ("content" org-startup-folded content)
3130 ("hidestars" org-hide-leading-stars t)
3131 ("showstars" org-hide-leading-stars nil)
3132 ("odd" org-odd-levels-only t)
3133 ("oddeven" org-odd-levels-only nil)
3134 ("align" org-startup-align-all-tables t)
3135 ("noalign" org-startup-align-all-tables nil)
3136 ("customtime" org-display-custom-times t)
3137 ("logging" org-log-done t)
3138 ("logdone" org-log-done t)
3139 ("nologging" org-log-done nil)
3140 ("lognotedone" org-log-done done push)
3141 ("lognotestate" org-log-done state push)
3142 ("lognoteclock-out" org-log-done clock-out push))
3143 "Variable associated with STARTUP options for org-mode.
3144 Each element is a list of three items: The startup options as written
3145 in the #+STARTUP line, the corresponding variable, and the value to
3146 set this variable to if the option is found. An optional forth element PUSH
3147 means to push this value onto the list in the variable.")
3149 (defun org-set-regexps-and-options ()
3150 "Precompute regular expressions for current buffer."
3151 (when (org-mode-p)
3152 (let ((re (org-make-options-regexp
3153 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3154 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
3155 (splitre "[ \t]+")
3156 kwds int key value cat arch tags links)
3157 (save-excursion
3158 (save-restriction
3159 (widen)
3160 (goto-char (point-min))
3161 (while (re-search-forward re nil t)
3162 (setq key (match-string 1) value (org-match-string-no-properties 2))
3163 (cond
3164 ((equal key "CATEGORY")
3165 (if (string-match "[ \t]+$" value)
3166 (setq value (replace-match "" t t value)))
3167 (setq cat (intern value)))
3168 ((equal key "SEQ_TODO")
3169 (setq int 'sequence
3170 kwds (append kwds (org-split-string value splitre))))
3171 ((equal key "PRI_TODO")
3172 (setq int 'priority
3173 kwds (append kwds (org-split-string value splitre))))
3174 ((equal key "TYP_TODO")
3175 (setq int 'type
3176 kwds (append kwds (org-split-string value splitre))))
3177 ((equal key "TAGS")
3178 (setq tags (append tags (org-split-string value splitre))))
3179 ((equal key "LINK")
3180 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3181 (push (cons (match-string 1 value)
3182 (org-trim (match-string 2 value)))
3183 links)))
3184 ((equal key "STARTUP")
3185 (let ((opts (org-split-string value splitre))
3186 l var val)
3187 (while (setq l (assoc (pop opts) org-startup-options))
3188 (setq var (nth 1 l) val (nth 2 l))
3189 (if (not (nth 3 l))
3190 (set (make-local-variable var) val)
3191 (if (not (listp (symbol-value var)))
3192 (set (make-local-variable var) nil))
3193 (set (make-local-variable var) (symbol-value var))
3194 (add-to-list var val)))))
3195 ((equal key "ARCHIVE")
3196 (string-match " *$" value)
3197 (setq arch (replace-match "" t t value))
3198 (remove-text-properties 0 (length arch)
3199 '(face t fontified t) arch)))
3201 (and cat (org-set-local 'org-category cat))
3202 (and kwds (org-set-local 'org-todo-keywords kwds))
3203 (and arch (org-set-local 'org-archive-location arch))
3204 (and int (org-set-local 'org-todo-interpretation int))
3205 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3206 (when tags
3207 (let (e tgs)
3208 (while (setq e (pop tags))
3209 (cond
3210 ((equal e "{") (push '(:startgroup) tgs))
3211 ((equal e "}") (push '(:endgroup) tgs))
3212 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3213 (push (cons (match-string 1 e)
3214 (string-to-char (match-string 2 e)))
3215 tgs))
3216 (t (push (list e) tgs))))
3217 (org-set-local 'org-tag-alist nil)
3218 (while (setq e (pop tgs))
3219 (or (and (stringp (car e))
3220 (assoc (car e) org-tag-alist))
3221 (push e org-tag-alist))))))
3223 ;; Compute the regular expressions and other local variables
3224 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3225 org-todo-kwd-max-priority (1- (length org-todo-keywords))
3226 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3227 (length org-scheduled-string)))
3228 org-done-string
3229 (nth (1- (length org-todo-keywords)) org-todo-keywords)
3230 org-todo-regexp
3231 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3232 "\\|") "\\)\\>")
3233 org-not-done-regexp
3234 (concat "\\<\\("
3235 (mapconcat 'regexp-quote
3236 (nreverse (cdr (reverse org-todo-keywords)))
3237 "\\|")
3238 "\\)\\>")
3239 org-todo-line-regexp
3240 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3241 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3242 "\\)\\>\\)? *\\(.*\\)")
3243 org-nl-done-regexp
3244 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3245 org-todo-line-tags-regexp
3246 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3247 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3248 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3249 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3250 org-deadline-regexp (concat "\\<" org-deadline-string)
3251 org-deadline-time-regexp
3252 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3253 org-deadline-line-regexp
3254 (concat "\\<\\(" org-deadline-string "\\).*")
3255 org-scheduled-regexp
3256 (concat "\\<" org-scheduled-string)
3257 org-scheduled-time-regexp
3258 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3259 org-closed-time-regexp
3260 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3261 org-keyword-time-regexp
3262 (concat "\\<\\(" org-scheduled-string
3263 "\\|" org-deadline-string
3264 "\\|" org-closed-string
3265 "\\|" org-clock-string "\\)"
3266 " *[[<]\\([^]>]+\\)[]>]")
3267 org-keyword-time-not-clock-regexp
3268 (concat "\\<\\(" org-scheduled-string
3269 "\\|" org-deadline-string
3270 "\\|" org-closed-string "\\)"
3271 " *[[<]\\([^]>]+\\)[]>]")
3272 org-maybe-keyword-time-regexp
3273 (concat "\\(\\<\\(" org-scheduled-string
3274 "\\|" org-deadline-string
3275 "\\|" org-closed-string
3276 "\\|" org-clock-string "\\)\\)?"
3277 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3279 (org-set-font-lock-defaults)))
3282 ;;; Some variables ujsed in various places
3284 (defvar org-window-configuration nil
3285 "Used in various places to store a window configuration.")
3286 (defvar org-finish-function nil
3287 "Function to be called when `C-c C-c' is used.
3288 This is for getting out of special buffers like remember.")
3290 ;;; Foreign variables, to inform the compiler
3292 ;; XEmacs only
3293 (defvar outline-mode-menu-heading)
3294 (defvar outline-mode-menu-show)
3295 (defvar outline-mode-menu-hide)
3296 (defvar zmacs-regions) ; XEmacs regions
3297 ;; Emacs only
3298 (defvar mark-active)
3300 ;; Packages that org-mode interacts with
3301 (defvar calc-embedded-close-formula)
3302 (defvar calc-embedded-open-formula)
3303 (defvar font-lock-unfontify-region-function)
3304 (defvar org-goto-start-pos)
3305 (defvar vm-message-pointer)
3306 (defvar vm-folder-directory)
3307 (defvar wl-summary-buffer-elmo-folder)
3308 (defvar wl-summary-buffer-folder-name)
3309 (defvar gnus-other-frame-object)
3310 (defvar gnus-group-name)
3311 (defvar gnus-article-current)
3312 (defvar w3m-current-url)
3313 (defvar w3m-current-title)
3314 (defvar mh-progs)
3315 (defvar mh-current-folder)
3316 (defvar mh-show-folder-buffer)
3317 (defvar mh-index-folder)
3318 (defvar mh-searcher)
3319 (defvar calendar-mode-map)
3320 (defvar Info-current-file)
3321 (defvar Info-current-node)
3322 (defvar texmathp-why)
3323 (defvar remember-save-after-remembering)
3324 (defvar remember-data-file)
3325 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3326 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3327 (defvar org-latex-regexps)
3329 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3331 ;; FIXME: Occasionally check by commenting these, to make sure
3332 ;; no other functions uses these, forgetting to let-bind them.
3333 (defvar entry)
3334 (defvar state)
3335 (defvar last-state)
3336 (defvar date)
3337 (defvar description)
3340 ;; Defined somewhere in this file, but used before definition.
3341 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3342 (defvar org-agenda-undo-list)
3343 (defvar org-agenda-pending-undo-list)
3344 (defvar org-agenda-overriding-header)
3345 (defvar orgtbl-mode)
3346 (defvar org-html-entities)
3347 (defvar org-struct-menu)
3348 (defvar org-org-menu)
3349 (defvar org-tbl-menu)
3350 (defvar org-agenda-keymap)
3351 (defvar org-category-table)
3353 ;;;; Emacs/XEmacs compatibility
3355 ;; Overlay compatibility functions
3356 (defun org-make-overlay (beg end &optional buffer)
3357 (if (featurep 'xemacs)
3358 (make-extent beg end buffer)
3359 (make-overlay beg end buffer)))
3360 (defun org-delete-overlay (ovl)
3361 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3362 (defun org-detach-overlay (ovl)
3363 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3364 (defun org-move-overlay (ovl beg end &optional buffer)
3365 (if (featurep 'xemacs)
3366 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3367 (move-overlay ovl beg end buffer)))
3368 (defun org-overlay-put (ovl prop value)
3369 (if (featurep 'xemacs)
3370 (set-extent-property ovl prop value)
3371 (overlay-put ovl prop value)))
3372 (defun org-overlay-display (ovl text &optional face evap)
3373 "Make overlay OVL display TEXT with face FACE."
3374 (if (featurep 'xemacs)
3375 (let ((gl (make-glyph text)))
3376 (and face (set-glyph-face gl face))
3377 (set-extent-property ovl 'invisible t)
3378 (set-extent-property ovl 'end-glyph gl))
3379 (overlay-put ovl 'display text)
3380 (if face (overlay-put ovl 'face face))
3381 (if evap (overlay-put ovl 'evaporate t))))
3382 (defun org-overlay-before-string (ovl text &optional face evap)
3383 "Make overlay OVL display TEXT with face FACE."
3384 (if (featurep 'xemacs)
3385 (let ((gl (make-glyph text)))
3386 (and face (set-glyph-face gl face))
3387 (set-extent-property ovl 'begin-glyph gl))
3388 (if face (org-add-props text nil 'face face))
3389 (overlay-put ovl 'before-string text)
3390 (if evap (overlay-put ovl 'evaporate t))))
3391 (defun org-overlay-get (ovl prop)
3392 (if (featurep 'xemacs)
3393 (extent-property ovl prop)
3394 (overlay-get ovl prop)))
3395 (defun org-overlays-at (pos)
3396 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3397 (defun org-overlays-in (&optional start end)
3398 (if (featurep 'xemacs)
3399 (extent-list nil start end)
3400 (overlays-in start end)))
3401 (defun org-overlay-start (o)
3402 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3403 (defun org-overlay-end (o)
3404 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3405 (defun org-find-overlays (prop &optional pos delete)
3406 "Find all overlays specifying PROP at POS or point.
3407 If DELETE is non-nil, delete all those overlays."
3408 (let ((overlays (org-overlays-at (or pos (point))))
3409 ov found)
3410 (while (setq ov (pop overlays))
3411 (if (org-overlay-get ov prop)
3412 (if delete (org-delete-overlay ov) (push ov found))))
3413 found))
3415 ;; Region compatibility
3417 (defun org-add-hook (hook function &optional append local)
3418 "Add-hook, compatible with both Emacsen."
3419 (if (and local (featurep 'xemacs))
3420 (add-local-hook hook function append)
3421 (add-hook hook function append local)))
3423 (defvar org-ignore-region nil
3424 "To temporarily disable the active region.")
3426 (defun org-region-active-p ()
3427 "Is `transient-mark-mode' on and the region active?
3428 Works on both Emacs and XEmacs."
3429 (if org-ignore-region
3431 (if (featurep 'xemacs)
3432 (and zmacs-regions (region-active-p))
3433 (and transient-mark-mode mark-active))))
3435 ;; Invisibility compatibility
3437 (defun org-add-to-invisibility-spec (arg)
3438 "Add elements to `buffer-invisibility-spec'.
3439 See documentation for `buffer-invisibility-spec' for the kind of elements
3440 that can be added."
3441 (cond
3442 ((fboundp 'add-to-invisibility-spec)
3443 (add-to-invisibility-spec arg))
3444 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3445 (setq buffer-invisibility-spec (list arg)))
3447 (setq buffer-invisibility-spec
3448 (cons arg buffer-invisibility-spec)))))
3450 (defun org-remove-from-invisibility-spec (arg)
3451 "Remove elements from `buffer-invisibility-spec'."
3452 (if (fboundp 'remove-from-invisibility-spec)
3453 (remove-from-invisibility-spec arg)
3454 (if (consp buffer-invisibility-spec)
3455 (setq buffer-invisibility-spec
3456 (delete arg buffer-invisibility-spec)))))
3458 (defun org-in-invisibility-spec-p (arg)
3459 "Is ARG a member of `buffer-invisibility-spec'?"
3460 (if (consp buffer-invisibility-spec)
3461 (member arg buffer-invisibility-spec)
3462 nil))
3464 ;;;; Define the Org-mode
3466 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3467 (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."))
3470 ;; We use a before-change function to check if a table might need
3471 ;; an update.
3472 (defvar org-table-may-need-update t
3473 "Indicates that a table might need an update.
3474 This variable is set by `org-before-change-function'.
3475 `org-table-align' sets it back to nil.")
3476 (defvar org-mode-map)
3477 (defvar org-mode-hook nil)
3478 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3479 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3482 ;;;###autoload
3483 (define-derived-mode org-mode outline-mode "Org"
3484 "Outline-based notes management and organizer, alias
3485 \"Carsten's outline-mode for keeping track of everything.\"
3487 Org-mode develops organizational tasks around a NOTES file which
3488 contains information about projects as plain text. Org-mode is
3489 implemented on top of outline-mode, which is ideal to keep the content
3490 of large files well structured. It supports ToDo items, deadlines and
3491 time stamps, which magically appear in the diary listing of the Emacs
3492 calendar. Tables are easily created with a built-in table editor.
3493 Plain text URL-like links connect to websites, emails (VM), Usenet
3494 messages (Gnus), BBDB entries, and any files related to the project.
3495 For printing and sharing of notes, an Org-mode file (or a part of it)
3496 can be exported as a structured ASCII or HTML file.
3498 The following commands are available:
3500 \\{org-mode-map}"
3502 ;; Get rid of Outline menus, they are not needed
3503 ;; Need to do this here because define-derived-mode sets up
3504 ;; the keymap so late. Still, it is a waste to call this each time
3505 ;; we switch another buffer into org-mode.
3506 (if (featurep 'xemacs)
3507 (when (boundp 'outline-mode-menu-heading)
3508 ;; Assume this is Greg's port, it used easymenu
3509 (easy-menu-remove outline-mode-menu-heading)
3510 (easy-menu-remove outline-mode-menu-show)
3511 (easy-menu-remove outline-mode-menu-hide))
3512 (define-key org-mode-map [menu-bar headings] 'undefined)
3513 (define-key org-mode-map [menu-bar hide] 'undefined)
3514 (define-key org-mode-map [menu-bar show] 'undefined))
3516 (easy-menu-add org-org-menu)
3517 (easy-menu-add org-tbl-menu)
3518 (org-install-agenda-files-menu)
3519 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3520 (org-add-to-invisibility-spec '(org-cwidth))
3521 (when (featurep 'xemacs)
3522 (org-set-local 'line-move-ignore-invisible t))
3523 (setq outline-regexp "\\*+")
3524 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
3525 (setq outline-level 'org-outline-level)
3526 (when (and org-ellipsis (stringp org-ellipsis)
3527 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
3528 (unless org-display-table
3529 (setq org-display-table (make-display-table)))
3530 (set-display-table-slot org-display-table
3531 4 (string-to-vector org-ellipsis))
3532 (setq buffer-display-table org-display-table))
3533 (org-set-regexps-and-options)
3534 ;; Calc embedded
3535 (org-set-local 'calc-embedded-open-mode "# ")
3536 (modify-syntax-entry ?# "<")
3537 (if org-startup-truncated (setq truncate-lines t))
3538 (org-set-local 'font-lock-unfontify-region-function
3539 'org-unfontify-region)
3540 ;; Activate before-change-function
3541 (org-set-local 'org-table-may-need-update t)
3542 (org-add-hook 'before-change-functions 'org-before-change-function nil
3543 'local)
3544 ;; Check for running clock before killing a buffer
3545 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3546 ;; Paragraphs and auto-filling
3547 (org-set-autofill-regexps)
3548 (org-update-radio-target-regexp)
3550 ;; Comment characters
3551 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3552 (org-set-local 'comment-padding " ")
3554 ;; Make isearch reveal context
3555 (if (or (featurep 'xemacs)
3556 (not (boundp 'outline-isearch-open-invisible-function)))
3557 ;; Emacs 21 and XEmacs make use of the hook
3558 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3559 ;; Emacs 22 deals with this through a special variable
3560 (org-set-local 'outline-isearch-open-invisible-function
3561 (lambda (&rest ignore) (org-show-context 'isearch))))
3563 ;; If empty file that did not turn on org-mode automatically, make it to.
3564 (if (and org-insert-mode-line-in-empty-file
3565 (interactive-p)
3566 (= (point-min) (point-max)))
3567 (insert " -*- mode: org -*-\n\n"))
3569 (unless org-inhibit-startup
3570 (when org-startup-align-all-tables
3571 (let ((bmp (buffer-modified-p)))
3572 (org-table-map-tables 'org-table-align)
3573 (set-buffer-modified-p bmp)))
3574 (cond
3575 ((eq org-startup-folded t)
3576 (org-cycle '(4)))
3577 ((eq org-startup-folded 'content)
3578 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3579 (org-cycle '(4)) (org-cycle '(4)))))))
3581 (defsubst org-call-with-arg (command arg)
3582 "Call COMMAND interactively, but pretend prefix are was ARG."
3583 (let ((current-prefix-arg arg)) (call-interactively command)))
3585 (defsubst org-current-line (&optional pos)
3586 (save-excursion
3587 (and pos (goto-char pos))
3588 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
3590 (defun org-current-time ()
3591 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3592 (if (> org-time-stamp-rounding-minutes 0)
3593 (let ((r org-time-stamp-rounding-minutes)
3594 (time (decode-time)))
3595 (apply 'encode-time
3596 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3597 (nthcdr 2 time))))
3598 (current-time)))
3600 (defun org-add-props (string plist &rest props)
3601 "Add text properties to entire string, from beginning to end.
3602 PLIST may be a list of properties, PROPS are individual properties and values
3603 that will be added to PLIST. Returns the string that was modified."
3604 (add-text-properties
3605 0 (length string) (if props (append plist props) plist) string)
3606 string)
3607 (put 'org-add-props 'lisp-indent-function 2)
3610 ;;;; Font-Lock stuff, including the activators
3612 (defvar org-mouse-map (make-sparse-keymap))
3613 (define-key org-mouse-map
3614 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3615 (define-key org-mouse-map
3616 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3617 (when org-mouse-1-follows-link
3618 (define-key org-mouse-map [follow-link] 'mouse-face))
3619 (when org-tab-follows-link
3620 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3621 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3622 (when org-return-follows-link
3623 (define-key org-mouse-map [(return)] 'org-open-at-point)
3624 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3626 (require 'font-lock)
3628 (defconst org-non-link-chars "]\t\n\r<>")
3629 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3630 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3631 (defconst org-link-re-with-space
3632 (concat
3633 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3634 "\\([^" org-non-link-chars " ]"
3635 "[^" org-non-link-chars "]*"
3636 "[^" org-non-link-chars " ]\\)>?")
3637 "Matches a link with spaces, optional angular brackets around it.")
3639 (defconst org-link-re-with-space2
3640 (concat
3641 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3642 "\\([^" org-non-link-chars " ]"
3643 "[^]\t\n\r]*"
3644 "[^" org-non-link-chars " ]\\)>?")
3645 "Matches a link with spaces, optional angular brackets around it.")
3647 (defconst org-angle-link-re
3648 (concat
3649 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3650 "\\([^" org-non-link-chars " ]"
3651 "[^" org-non-link-chars "]*"
3652 "\\)>")
3653 "Matches link with angular brackets, spaces are allowed.")
3654 (defconst org-plain-link-re
3655 (concat
3656 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3657 "\\([^]\t\n\r<>,;() ]+\\)")
3658 "Matches plain link, without spaces.")
3660 (defconst org-bracket-link-regexp
3661 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3662 "Matches a link in double brackets.")
3664 (defconst org-bracket-link-analytic-regexp
3665 (concat
3666 "\\[\\["
3667 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3668 "\\([^]]+\\)"
3669 "\\]"
3670 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3671 "\\]"))
3672 ; 1: http:
3673 ; 2: http
3674 ; 3: path
3675 ; 4: [desc]
3676 ; 5: desc
3678 (defconst org-any-link-re
3679 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3680 org-angle-link-re "\\)\\|\\("
3681 org-plain-link-re "\\)")
3682 "Regular expression matching any link.")
3684 (defconst org-ts-lengths
3685 (cons (length (format-time-string (car org-time-stamp-formats)))
3686 (length (format-time-string (cdr org-time-stamp-formats))))
3687 "This holds the lengths of the two different time formats.")
3688 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3689 "Regular expression for fast time stamp matching.")
3690 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3691 "Regular expression for fast time stamp matching.")
3692 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3693 "Regular expression matching time strings for analysis.")
3694 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3695 "Regular expression matching time stamps, with groups.")
3696 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3697 "Regular expression matching time stamps (also [..]), with groups.")
3698 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3699 "Regular expression matching a time stamp range.")
3700 (defconst org-tr-regexp-both
3701 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3702 "Regular expression matching a time stamp range.")
3703 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3704 org-ts-regexp "\\)?")
3705 "Regular expression matching a time stamp or time stamp range.")
3706 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3707 org-ts-regexp-both "\\)?")
3708 "Regular expression matching a time stamp or time stamp range.
3709 The time stamps may be either active or inactive.")
3711 (defvar org-emph-face nil)
3713 (defun org-do-emphasis-faces (limit)
3714 "Run through the buffer and add overlays to links."
3715 (if (re-search-forward org-emph-re limit t)
3716 (progn
3717 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3718 'face
3719 (nth 1 (assoc (match-string 3)
3720 org-emphasis-alist)))
3721 (add-text-properties (match-beginning 2) (match-end 2)
3722 '(font-lock-multiline t))
3723 (backward-char 1)
3724 t)))
3726 (defun org-activate-plain-links (limit)
3727 "Run through the buffer and add overlays to links."
3728 (if (re-search-forward org-plain-link-re limit t)
3729 (progn
3730 (add-text-properties (match-beginning 0) (match-end 0)
3731 (list 'mouse-face 'highlight
3732 'rear-nonsticky t
3733 'keymap org-mouse-map
3735 t)))
3737 (defun org-activate-angle-links (limit)
3738 "Run through the buffer and add overlays to links."
3739 (if (re-search-forward org-angle-link-re limit t)
3740 (progn
3741 (add-text-properties (match-beginning 0) (match-end 0)
3742 (list 'mouse-face 'highlight
3743 'rear-nonsticky t
3744 'keymap org-mouse-map
3746 t)))
3748 (defmacro org-maybe-intangible (props)
3749 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3750 In emacs 21, invisible text is not avoided by the command loop, so the
3751 intangible property is needed to make sure point skips this text.
3752 In Emacs 22, this is not necessary. The intangible text property has
3753 led to problems with flyspell. These problems are fixed in flyspell.el,
3754 but we still avoid setting the property in Emacs 22 and later.
3755 We use a macro so that the test can happen at compilation time."
3756 (if (< emacs-major-version 22)
3757 `(append '(intangible t) ,props)
3758 props))
3760 (defun org-activate-bracket-links (limit)
3761 "Run through the buffer and add overlays to bracketed links."
3762 (if (re-search-forward org-bracket-link-regexp limit t)
3763 (let* ((help (concat "LINK: "
3764 (org-match-string-no-properties 1)))
3765 ;; FIXME: above we should remove the escapes.
3766 ;; but that requires another match, protecting match data,
3767 ;; a lot of overhead for font-lock.
3768 (ip (org-maybe-intangible
3769 (list 'invisible 'org-link 'rear-nonsticky t
3770 'keymap org-mouse-map 'mouse-face 'highlight
3771 'help-echo help)))
3772 (vp (list 'rear-nonsticky t
3773 'keymap org-mouse-map 'mouse-face 'highlight
3774 'help-echo help)))
3775 ;; We need to remove the invisible property here. Table narrowing
3776 ;; may have made some of this invisible.
3777 (remove-text-properties (match-beginning 0) (match-end 0)
3778 '(invisible nil))
3779 (if (match-end 3)
3780 (progn
3781 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3782 (add-text-properties (match-beginning 3) (match-end 3) vp)
3783 (add-text-properties (match-end 3) (match-end 0) ip))
3784 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3785 (add-text-properties (match-beginning 1) (match-end 1) vp)
3786 (add-text-properties (match-end 1) (match-end 0) ip))
3787 t)))
3789 (defun org-activate-dates (limit)
3790 "Run through the buffer and add overlays to dates."
3791 (if (re-search-forward org-tsr-regexp-both limit t)
3792 (progn
3793 (add-text-properties (match-beginning 0) (match-end 0)
3794 (list 'mouse-face 'highlight
3795 'rear-nonsticky t
3796 'keymap org-mouse-map))
3797 (when org-display-custom-times
3798 (if (match-end 3)
3799 (org-display-custom-time (match-beginning 3) (match-end 3)))
3800 (org-display-custom-time (match-beginning 1) (match-end 1)))
3801 t)))
3803 (defvar org-target-link-regexp nil
3804 "Regular expression matching radio targets in plain text.")
3805 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3806 "Regular expression matching a link target.")
3807 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3808 "Regular expression matching a link target.")
3810 (defun org-activate-target-links (limit)
3811 "Run through the buffer and add overlays to target matches."
3812 (when org-target-link-regexp
3813 (let ((case-fold-search t))
3814 (if (re-search-forward org-target-link-regexp limit t)
3815 (progn
3816 (add-text-properties (match-beginning 0) (match-end 0)
3817 (list 'mouse-face 'highlight
3818 'rear-nonsticky t
3819 'keymap org-mouse-map
3820 'help-echo "Radio target link"
3821 'org-linked-text t))
3822 t)))))
3824 (defun org-update-radio-target-regexp ()
3825 "Find all radio targets in this file and update the regular expression."
3826 (interactive)
3827 (when (memq 'radio org-activate-links)
3828 (setq org-target-link-regexp
3829 (org-make-target-link-regexp (org-all-targets 'radio)))
3830 (org-restart-font-lock)))
3832 (defun org-hide-wide-columns (limit)
3833 (let (s e)
3834 (setq s (text-property-any (point) (or limit (point-max))
3835 'org-cwidth t))
3836 (when s
3837 (setq e (next-single-property-change s 'org-cwidth))
3838 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3839 (goto-char e)
3840 t)))
3842 (defun org-restart-font-lock ()
3843 "Restart font-lock-mode, to force refontification."
3844 (when (and (boundp 'font-lock-mode) font-lock-mode)
3845 (font-lock-mode -1)
3846 (font-lock-mode 1)))
3848 (defun org-all-targets (&optional radio)
3849 "Return a list of all targets in this file.
3850 With optional argument RADIO, only find radio targets."
3851 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3852 rtn)
3853 (save-excursion
3854 (goto-char (point-min))
3855 (while (re-search-forward re nil t)
3856 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3857 rtn)))
3859 (defun org-make-target-link-regexp (targets)
3860 "Make regular expression matching all strings in TARGETS.
3861 The regular expression finds the targets also if there is a line break
3862 between words."
3863 (and targets
3864 (concat
3865 "\\<\\("
3866 (mapconcat
3867 (lambda (x)
3868 (while (string-match " +" x)
3869 (setq x (replace-match "\\s-+" t t x)))
3871 targets
3872 "\\|")
3873 "\\)\\>")))
3875 (defun org-activate-tags (limit)
3876 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3877 (progn
3878 (add-text-properties (match-beginning 1) (match-end 1)
3879 (list 'mouse-face 'highlight
3880 'rear-nonsticky t
3881 'keymap org-mouse-map))
3882 t)))
3884 (defun org-font-lock-level ()
3885 (save-excursion
3886 (org-back-to-heading t)
3887 (- (match-end 0) (match-beginning 0))))
3889 (defun org-outline-level ()
3890 (save-excursion
3891 (looking-at outline-regexp)
3892 (if (match-beginning 1)
3893 (+ (org-get-string-indentation (match-string 1)) 1000)
3894 (- (match-end 0) (match-beginning 0)))))
3896 (defvar org-font-lock-keywords nil)
3898 (defun org-set-font-lock-defaults ()
3899 (let* ((em org-fontify-emphasized-text)
3900 (lk org-activate-links)
3901 (org-font-lock-extra-keywords
3902 ;; Headlines
3903 (list
3904 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3905 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3906 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3907 (1 'org-table))
3908 ;; Links
3909 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3910 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3911 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3912 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3913 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3914 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3915 ;; TODO lines
3916 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3917 '(1 'org-todo t))
3918 ;; Priorities
3919 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3920 ;; Special keywords
3921 (list org-repeat-re '(0 'org-special-keyword t))
3922 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3923 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3924 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3925 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3926 ;; Emphasis
3927 (if em
3928 (if (featurep 'xemacs)
3929 '(org-do-emphasis-faces (0 nil append))
3930 '(org-do-emphasis-faces)))
3931 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3932 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3933 2 'bold prepend)
3934 (if org-provide-checkbox-statistics
3935 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3936 (0 (org-get-checkbox-statistics-face) t)))
3937 ;; COMMENT
3938 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3939 "\\|" org-quote-string "\\)\\>")
3940 '(1 'org-special-keyword t))
3941 '("^#.*" (0 'font-lock-comment-face t))
3942 ;; DONE
3943 (if org-fontify-done-headline
3944 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3945 '(1 'org-done t) '(2 'org-headline-done t))
3946 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3947 '(1 'org-done t)))
3948 ;; Table stuff
3949 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3950 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3951 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3952 (if org-format-transports-properties-p
3953 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3954 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3956 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3957 ;; Now set the full font-lock-keywords
3958 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3959 (org-set-local 'font-lock-defaults
3960 '(org-font-lock-keywords t nil nil backward-paragraph))
3961 (kill-local-variable 'font-lock-keywords) nil))
3963 (defvar org-m nil)
3964 (defvar org-l nil)
3965 (defvar org-f nil)
3966 (defun org-get-level-face (n)
3967 "Get the right face for match N in font-lock matching of healdines."
3968 (setq org-l (- (match-end 2) (match-beginning 1)))
3969 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3970 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3971 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3972 (cond
3973 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3974 ((eq n 2) org-f)
3975 (t (if org-level-color-stars-only nil org-f))))
3977 (defun org-unfontify-region (beg end &optional maybe_loudly)
3978 "Remove fontification and activation overlays from links."
3979 (font-lock-default-unfontify-region beg end)
3980 (let* ((buffer-undo-list t)
3981 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3982 (inhibit-modification-hooks t)
3983 deactivate-mark buffer-file-name buffer-file-truename)
3984 (remove-text-properties beg end
3985 '(mouse-face t keymap t org-linked-text t
3986 rear-nonsticky t
3987 invisible t intangible t))))
3989 ;;;; Visibility cycling, including org-goto and indirect buffer
3991 ;;; Cycling
3993 (defvar org-cycle-global-status nil)
3994 (make-variable-buffer-local 'org-cycle-global-status)
3995 (defvar org-cycle-subtree-status nil)
3996 (make-variable-buffer-local 'org-cycle-subtree-status)
3998 ;;;###autoload
3999 (defun org-cycle (&optional arg)
4000 "Visibility cycling for Org-mode.
4002 - When this function is called with a prefix argument, rotate the entire
4003 buffer through 3 states (global cycling)
4004 1. OVERVIEW: Show only top-level headlines.
4005 2. CONTENTS: Show all headlines of all levels, but no body text.
4006 3. SHOW ALL: Show everything.
4008 - When point is at the beginning of a headline, rotate the subtree started
4009 by this line through 3 different states (local cycling)
4010 1. FOLDED: Only the main headline is shown.
4011 2. CHILDREN: The main headline and the direct children are shown.
4012 From this state, you can move to one of the children
4013 and zoom in further.
4014 3. SUBTREE: Show the entire subtree, including body text.
4016 - When there is a numeric prefix, go up to a heading with level ARG, do
4017 a `show-subtree' and return to the previous cursor position. If ARG
4018 is negative, go up that many levels.
4020 - When point is not at the beginning of a headline, execute
4021 `indent-relative', like TAB normally does. See the option
4022 `org-cycle-emulate-tab' for details.
4024 - Special case: if point is the the beginning of the buffer and there is
4025 no headline in line 1, this function will act as if called with prefix arg."
4026 (interactive "P")
4027 (let* ((outline-regexp
4028 (if (and (org-mode-p) org-cycle-include-plain-lists)
4029 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4030 outline-regexp))
4031 (bob-special (and org-cycle-global-at-bob (bobp)
4032 (not (looking-at outline-regexp))))
4033 (org-cycle-hook
4034 (if bob-special
4035 (delq 'org-optimize-window-after-visibility-change
4036 (copy-sequence org-cycle-hook))
4037 org-cycle-hook))
4038 (pos (point)))
4040 (if (or bob-special (equal arg '(4)))
4041 ;; special case: use global cycling
4042 (setq arg t))
4044 (cond
4046 ((org-at-table-p 'any)
4047 ;; Enter the table or move to the next field in the table
4048 (or (org-table-recognize-table.el)
4049 (progn
4050 (if arg (org-table-edit-field t)
4051 (org-table-justify-field-maybe)
4052 (call-interactively 'org-table-next-field)))))
4054 ((eq arg t) ;; Global cycling
4056 (cond
4057 ((and (eq last-command this-command)
4058 (eq org-cycle-global-status 'overview))
4059 ;; We just created the overview - now do table of contents
4060 ;; This can be slow in very large buffers, so indicate action
4061 (message "CONTENTS...")
4062 (org-content)
4063 (message "CONTENTS...done")
4064 (setq org-cycle-global-status 'contents)
4065 (run-hook-with-args 'org-cycle-hook 'contents))
4067 ((and (eq last-command this-command)
4068 (eq org-cycle-global-status 'contents))
4069 ;; We just showed the table of contents - now show everything
4070 (show-all)
4071 (message "SHOW ALL")
4072 (setq org-cycle-global-status 'all)
4073 (run-hook-with-args 'org-cycle-hook 'all))
4076 ;; Default action: go to overview
4077 (org-overview)
4078 (message "OVERVIEW")
4079 (setq org-cycle-global-status 'overview)
4080 (run-hook-with-args 'org-cycle-hook 'overview))))
4082 ((integerp arg)
4083 ;; Show-subtree, ARG levels up from here.
4084 (save-excursion
4085 (org-back-to-heading)
4086 (outline-up-heading (if (< arg 0) (- arg)
4087 (- (funcall outline-level) arg)))
4088 (org-show-subtree)))
4090 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4091 ;; At a heading: rotate between three different views
4092 (org-back-to-heading)
4093 (let ((goal-column 0) eoh eol eos)
4094 ;; First, some boundaries
4095 (save-excursion
4096 (org-back-to-heading)
4097 (save-excursion
4098 (beginning-of-line 2)
4099 (while (and (not (eobp)) ;; this is like `next-line'
4100 (get-char-property (1- (point)) 'invisible))
4101 (beginning-of-line 2)) (setq eol (point)))
4102 (outline-end-of-heading) (setq eoh (point))
4103 (org-end-of-subtree t)
4104 (skip-chars-forward " \t\n")
4105 (beginning-of-line 1) ; in case this is an item
4106 (setq eos (1- (point))))
4107 ;; Find out what to do next and set `this-command'
4108 (cond
4109 ((= eos eoh)
4110 ;; Nothing is hidden behind this heading
4111 (message "EMPTY ENTRY")
4112 (setq org-cycle-subtree-status nil))
4113 ((>= eol eos)
4114 ;; Entire subtree is hidden in one line: open it
4115 (org-show-entry)
4116 (show-children)
4117 (message "CHILDREN")
4118 (setq org-cycle-subtree-status 'children)
4119 (run-hook-with-args 'org-cycle-hook 'children))
4120 ((and (eq last-command this-command)
4121 (eq org-cycle-subtree-status 'children))
4122 ;; We just showed the children, now show everything.
4123 (org-show-subtree)
4124 (message "SUBTREE")
4125 (setq org-cycle-subtree-status 'subtree)
4126 (run-hook-with-args 'org-cycle-hook 'subtree))
4128 ;; Default action: hide the subtree.
4129 (hide-subtree)
4130 (message "FOLDED")
4131 (setq org-cycle-subtree-status 'folded)
4132 (run-hook-with-args 'org-cycle-hook 'folded)))))
4134 ;; TAB emulation
4135 (buffer-read-only (org-back-to-heading))
4137 ((org-try-cdlatex-tab))
4139 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4140 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4141 (or (and (eq org-cycle-emulate-tab 'white)
4142 (= (match-end 0) (point-at-eol)))
4143 (and (eq org-cycle-emulate-tab 'whitestart)
4144 (>= (match-end 0) pos))))
4146 (eq org-cycle-emulate-tab t))
4147 (if (and (looking-at "[ \n\r\t]")
4148 (string-match "^[ \t]*$" (buffer-substring
4149 (point-at-bol) (point))))
4150 (progn
4151 (beginning-of-line 1)
4152 (and (looking-at "[ \t]+") (replace-match ""))))
4153 (indent-relative))
4155 (t (save-excursion
4156 (org-back-to-heading)
4157 (org-cycle))))))
4159 ;;;###autoload
4160 (defun org-global-cycle (&optional arg)
4161 "Cycle the global visibility. For details see `org-cycle'."
4162 (interactive "P")
4163 (let ((org-cycle-include-plain-lists
4164 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4165 (if (integerp arg)
4166 (progn
4167 (show-all)
4168 (hide-sublevels arg)
4169 (setq org-cycle-global-status 'contents))
4170 (org-cycle '(4)))))
4172 (defun org-overview ()
4173 "Switch to overview mode, shoing only top-level headlines.
4174 Really, this shows all headlines with level equal or greater than the level
4175 of the first headline in the buffer. This is important, because if the
4176 first headline is not level one, then (hide-sublevels 1) gives confusing
4177 results."
4178 (interactive)
4179 (hide-sublevels (save-excursion
4180 (goto-char (point-min))
4181 (if (re-search-forward (concat "^" outline-regexp) nil t)
4182 (progn
4183 (goto-char (match-beginning 0))
4184 (funcall outline-level))
4185 1))))
4187 (defun org-content (&optional arg)
4188 "Show all headlines in the buffer, like a table of contents.
4189 With numerical argument N, show content up to level N."
4190 (interactive "P")
4191 (save-excursion
4192 ;; Visit all headings and show their offspring
4193 (and (integerp arg) (org-overview))
4194 (goto-char (point-max))
4195 (catch 'exit
4196 (while (and (progn (condition-case nil
4197 (outline-previous-visible-heading 1)
4198 (error (goto-char (point-min))))
4200 (looking-at outline-regexp))
4201 (if (integerp arg)
4202 (show-children (1- arg))
4203 (show-branches))
4204 (if (bobp) (throw 'exit nil))))))
4207 (defun org-optimize-window-after-visibility-change (state)
4208 "Adjust the window after a change in outline visibility.
4209 This function is the default value of the hook `org-cycle-hook'."
4210 (when (get-buffer-window (current-buffer))
4211 (cond
4212 ((eq state 'overview) (org-first-headline-recenter 1))
4213 ((eq state 'content) nil)
4214 ((eq state 'all) nil)
4215 ((eq state 'folded) nil)
4216 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4217 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4219 (defun org-subtree-end-visible-p ()
4220 "Is the end of the current subtree visible?"
4221 (pos-visible-in-window-p
4222 (save-excursion (org-end-of-subtree t) (point))))
4224 (defun org-first-headline-recenter (&optional N)
4225 "Move cursor to the first headline and recenter the headline.
4226 Optional argument N means, put the headline into the Nth line of the window."
4227 (goto-char (point-min))
4228 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4229 (beginning-of-line)
4230 (recenter (prefix-numeric-value N))))
4232 ;;; Org-goto
4234 (defvar org-goto-window-configuration nil)
4235 (defvar org-goto-marker nil)
4236 (defvar org-goto-map (make-sparse-keymap))
4237 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4238 (while (setq cmd (pop cmds))
4239 (substitute-key-definition cmd cmd org-goto-map global-map)))
4240 (define-key org-goto-map "\C-m" 'org-goto-ret)
4241 (define-key org-goto-map [(left)] 'org-goto-left)
4242 (define-key org-goto-map [(right)] 'org-goto-right)
4243 (define-key org-goto-map [(?q)] 'org-goto-quit)
4244 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
4245 (define-key org-goto-map "\C-i" 'org-cycle)
4246 (define-key org-goto-map [(tab)] 'org-cycle)
4247 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
4248 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
4249 (define-key org-goto-map "n" 'outline-next-visible-heading)
4250 (define-key org-goto-map "p" 'outline-previous-visible-heading)
4251 (define-key org-goto-map "f" 'outline-forward-same-level)
4252 (define-key org-goto-map "b" 'outline-backward-same-level)
4253 (define-key org-goto-map "u" 'outline-up-heading)
4254 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4255 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4256 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4257 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4258 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
4259 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4260 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
4262 (defconst org-goto-help
4263 "Select a location to jump to, press RET
4264 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4266 (defun org-goto ()
4267 "Go to a different location of the document, keeping current visibility.
4269 When you want to go to a different location in a document, the fastest way
4270 is often to fold the entire buffer and then dive into the tree. This
4271 method has the disadvantage, that the previous location will be folded,
4272 which may not be what you want.
4274 This command works around this by showing a copy of the current buffer in
4275 overview mode. You can dive into the tree in that copy, to find the
4276 location you want to reach. When pressing RET, the command returns to the
4277 original buffer in which the visibility is still unchanged. It then jumps
4278 to the new location, making it and the headline hierarchy above it visible."
4279 (interactive)
4280 (let* ((org-goto-start-pos (point))
4281 (selected-point
4282 (org-get-location (current-buffer) org-goto-help)))
4283 (if selected-point
4284 (progn
4285 (org-mark-ring-push org-goto-start-pos)
4286 (goto-char selected-point)
4287 (if (or (org-invisible-p) (org-invisible-p2))
4288 (org-show-context 'org-goto)))
4289 (error "Quit"))))
4291 (defvar org-selected-point nil) ; dynamically scoped parameter
4293 (defun org-get-location (buf help)
4294 "Let the user select a location in the Org-mode buffer BUF.
4295 This function uses a recursive edit. It returns the selected position
4296 or nil."
4297 (let (org-selected-point)
4298 (save-excursion
4299 (save-window-excursion
4300 (delete-other-windows)
4301 (switch-to-buffer (get-buffer-create "*org-goto*"))
4302 (with-output-to-temp-buffer "*Help*"
4303 (princ help))
4304 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4305 (setq buffer-read-only nil)
4306 (erase-buffer)
4307 (insert-buffer-substring buf)
4308 (let ((org-startup-truncated t)
4309 (org-startup-folded t)
4310 (org-startup-align-all-tables nil))
4311 (org-mode))
4312 (setq buffer-read-only t)
4313 (if (and (boundp 'org-goto-start-pos)
4314 (integer-or-marker-p org-goto-start-pos))
4315 (let ((org-show-hierarchy-above t)
4316 (org-show-siblings t)
4317 (org-show-following-heading t))
4318 (goto-char org-goto-start-pos)
4319 (and (org-invisible-p) (org-show-context)))
4320 (goto-char (point-min)))
4321 (org-beginning-of-line)
4322 (message "Select location and press RET")
4323 ;; now we make sure that during selection, ony very few keys work
4324 ;; and that it is impossible to switch to another window.
4325 (let ((gm (current-global-map))
4326 (overriding-local-map org-goto-map))
4327 (unwind-protect
4328 (progn
4329 (use-global-map org-goto-map)
4330 (recursive-edit))
4331 (use-global-map gm)))))
4332 (kill-buffer "*org-goto*")
4333 org-selected-point))
4335 (defun org-goto-ret (&optional arg)
4336 "Finish `org-goto' by going to the new location."
4337 (interactive "P")
4338 (setq org-selected-point (point)
4339 current-prefix-arg arg)
4340 (throw 'exit nil))
4342 (defun org-goto-left ()
4343 "Finish `org-goto' by going to the new location."
4344 (interactive)
4345 (if (org-on-heading-p)
4346 (progn
4347 (beginning-of-line 1)
4348 (setq org-selected-point (point)
4349 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4350 (throw 'exit nil))
4351 (error "Not on a heading")))
4353 (defun org-goto-right ()
4354 "Finish `org-goto' by going to the new location."
4355 (interactive)
4356 (if (org-on-heading-p)
4357 (progn
4358 (outline-end-of-subtree)
4359 (or (eobp) (forward-char 1))
4360 (setq org-selected-point (point)
4361 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4362 (throw 'exit nil))
4363 (error "Not on a heading")))
4365 (defun org-goto-quit ()
4366 "Finish `org-goto' without cursor motion."
4367 (interactive)
4368 (setq org-selected-point nil)
4369 (throw 'exit nil))
4371 ;;; Indirect buffer display of subtrees
4373 (defvar org-indirect-dedicated-frame nil
4374 "This is the frame being used for indirect tree display.")
4375 (defvar org-last-indirect-buffer nil)
4377 (defun org-tree-to-indirect-buffer (&optional arg)
4378 "Create indirect buffer and narrow it to current subtree.
4379 With numerical prefix ARG, go up to this level and then take that tree.
4380 If ARG is negative, go up that many levels.
4381 Normally this command removes the indirect buffer previously made
4382 with this command. However, when called with a C-u prefix, the last buffer
4383 is kept so that you can work with several indirect buffers at the same time.
4384 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4385 requests that a new frame be made for the new buffer, so that the dedicated
4386 frame is not changed."
4387 (interactive "P")
4388 (let ((cbuf (current-buffer))
4389 (cwin (selected-window))
4390 (pos (point))
4391 beg end level heading ibuf)
4392 (save-excursion
4393 (org-back-to-heading t)
4394 (when (numberp arg)
4395 (setq level (org-outline-level))
4396 (if (< arg 0) (setq arg (+ level arg)))
4397 (while (> (setq level (org-outline-level)) arg)
4398 (outline-up-heading 1 t)))
4399 (setq beg (point)
4400 heading (org-get-heading))
4401 (org-end-of-subtree t) (setq end (point)))
4402 (if (and (not arg)
4403 (buffer-live-p org-last-indirect-buffer))
4404 (kill-buffer org-last-indirect-buffer))
4405 (setq ibuf (org-get-indirect-buffer cbuf)
4406 org-last-indirect-buffer ibuf)
4407 (cond
4408 ((or (eq org-indirect-buffer-display 'new-frame)
4409 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4410 (select-frame (make-frame))
4411 (delete-other-windows)
4412 (switch-to-buffer ibuf)
4413 (org-set-frame-title heading))
4414 ((eq org-indirect-buffer-display 'dedicated-frame)
4415 (raise-frame
4416 (select-frame (or (and org-indirect-dedicated-frame
4417 (frame-live-p org-indirect-dedicated-frame)
4418 org-indirect-dedicated-frame)
4419 (setq org-indirect-dedicated-frame (make-frame)))))
4420 (delete-other-windows)
4421 (switch-to-buffer ibuf)
4422 (org-set-frame-title (concat "Indirect: " heading)))
4423 ((eq org-indirect-buffer-display 'current-window)
4424 (switch-to-buffer ibuf))
4425 ((eq org-indirect-buffer-display 'other-window)
4426 (pop-to-buffer ibuf))
4427 (t (error "Invalid value.")))
4428 (if (featurep 'xemacs)
4429 (save-excursion (org-mode) (turn-on-font-lock)))
4430 (narrow-to-region beg end)
4431 (show-all)
4432 (goto-char pos)
4433 (and (window-live-p cwin) (select-window cwin))))
4435 (defun org-get-indirect-buffer (&optional buffer)
4436 (setq buffer (or buffer (current-buffer)))
4437 (let ((n 1) (base (buffer-name buffer)) bname)
4438 (while (buffer-live-p
4439 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4440 (setq n (1+ n)))
4441 (condition-case nil
4442 (make-indirect-buffer buffer bname 'clone)
4443 (error (make-indirect-buffer buffer bname)))))
4445 (defun org-set-frame-title (title)
4446 "Set the title of the current frame to the string TITLE."
4447 ;; FIXME: how to name a single frame in XEmacs???
4448 (unless (featurep 'xemacs)
4449 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4451 ;;;; Structure editing
4453 ;;; Inserting headlines
4455 (defun org-insert-heading (&optional force-heading)
4456 "Insert a new heading or item with same depth at point.
4457 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4458 If point is at the beginning of a headline, insert a sibling before the
4459 current headline. If point is in the middle of a headline, split the headline
4460 at that position and make the rest of the headline part of the sibling below
4461 the current headline."
4462 (interactive "P")
4463 (if (= (buffer-size) 0)
4464 (insert "\n* ")
4465 (when (or force-heading (not (org-insert-item)))
4466 (let* ((head (save-excursion
4467 (condition-case nil
4468 (progn
4469 (org-back-to-heading)
4470 (match-string 0))
4471 (error "*"))))
4472 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4473 pos)
4474 (cond
4475 ((and (org-on-heading-p) (bolp)
4476 (save-excursion (backward-char 1) (not (org-invisible-p))))
4477 (open-line (if blank 2 1)))
4478 ((and (bolp) (save-excursion
4479 (backward-char 1) (not (org-invisible-p))))
4480 nil)
4481 (t (newline (if blank 2 1))))
4482 (insert head) (just-one-space)
4483 (setq pos (point))
4484 (end-of-line 1)
4485 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4486 (run-hooks 'org-insert-heading-hook)))))
4489 (defun org-insert-todo-heading (arg)
4490 "Insert a new heading with the same level and TODO state as current heading.
4491 If the heading has no TODO state, or if the state is DONE, use the first
4492 state (TODO by default). Also with prefix arg, force first state."
4493 (interactive "P")
4494 (when (not (org-insert-item 'checkbox))
4495 (org-insert-heading)
4496 (save-excursion
4497 (org-back-to-heading)
4498 (outline-previous-heading)
4499 (looking-at org-todo-line-regexp))
4500 (if (or arg
4501 (not (match-beginning 2))
4502 (equal (match-string 2) org-done-string))
4503 (insert (car org-todo-keywords) " ")
4504 (insert (match-string 2) " "))))
4506 ;;; Promotion and Demotion
4508 (defun org-promote-subtree ()
4509 "Promote the entire subtree.
4510 See also `org-promote'."
4511 (interactive)
4512 (save-excursion
4513 (org-map-tree 'org-promote))
4514 (org-fix-position-after-promote))
4516 (defun org-demote-subtree ()
4517 "Demote the entire subtree. See `org-demote'.
4518 See also `org-promote'."
4519 (interactive)
4520 (save-excursion
4521 (org-map-tree 'org-demote))
4522 (org-fix-position-after-promote))
4525 (defun org-do-promote ()
4526 "Promote the current heading higher up the tree.
4527 If the region is active in `transient-mark-mode', promote all headings
4528 in the region."
4529 (interactive)
4530 (save-excursion
4531 (if (org-region-active-p)
4532 (org-map-region 'org-promote (region-beginning) (region-end))
4533 (org-promote)))
4534 (org-fix-position-after-promote))
4536 (defun org-do-demote ()
4537 "Demote the current heading lower down the tree.
4538 If the region is active in `transient-mark-mode', demote all headings
4539 in the region."
4540 (interactive)
4541 (save-excursion
4542 (if (org-region-active-p)
4543 (org-map-region 'org-demote (region-beginning) (region-end))
4544 (org-demote)))
4545 (org-fix-position-after-promote))
4547 (defun org-fix-position-after-promote ()
4548 "Make sure that after pro/demotion cursor position is right."
4549 (let ((pos (point)))
4550 (when (save-excursion
4551 (beginning-of-line 1)
4552 (looking-at org-todo-line-regexp)
4553 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4554 (cond ((eobp) (insert " "))
4555 ((eolp) (insert " "))
4556 ((equal (char-after) ?\ ) (forward-char 1))))))
4558 (defun org-get-legal-level (level &optional change)
4559 "Rectify a level change under the influence of `org-odd-levels-only'
4560 LEVEL is a current level, CHANGE is by how much the level should be
4561 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4562 even level numbers will become the next higher odd number."
4563 (if org-odd-levels-only
4564 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4565 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4566 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4567 (max 1 (+ level change))))
4569 (defun org-promote ()
4570 "Promote the current heading higher up the tree.
4571 If the region is active in `transient-mark-mode', promote all headings
4572 in the region."
4573 (org-back-to-heading t)
4574 (let* ((level (save-match-data (funcall outline-level)))
4575 (up-head (make-string (org-get-legal-level level -1) ?*))
4576 (diff (abs (- level (length up-head)))))
4577 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4578 (replace-match up-head nil t)
4579 ;; Fixup tag positioning
4580 (and org-auto-align-tags (org-set-tags nil t))
4581 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4583 (defun org-demote ()
4584 "Demote the current heading lower down the tree.
4585 If the region is active in `transient-mark-mode', demote all headings
4586 in the region."
4587 (org-back-to-heading t)
4588 (let* ((level (save-match-data (funcall outline-level)))
4589 (down-head (make-string (org-get-legal-level level 1) ?*))
4590 (diff (abs (- level (length down-head)))))
4591 (replace-match down-head nil t)
4592 ;; Fixup tag positioning
4593 (and org-auto-align-tags (org-set-tags nil t))
4594 (if org-adapt-indentation (org-fixup-indentation diff))))
4596 (defun org-map-tree (fun)
4597 "Call FUN for every heading underneath the current one."
4598 (org-back-to-heading)
4599 (let ((level (funcall outline-level)))
4600 (save-excursion
4601 (funcall fun)
4602 (while (and (progn
4603 (outline-next-heading)
4604 (> (funcall outline-level) level))
4605 (not (eobp)))
4606 (funcall fun)))))
4608 (defun org-map-region (fun beg end)
4609 "Call FUN for every heading between BEG and END."
4610 (let ((org-ignore-region t))
4611 (save-excursion
4612 (setq end (copy-marker end))
4613 (goto-char beg)
4614 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4615 (< (point) end))
4616 (funcall fun))
4617 (while (and (progn
4618 (outline-next-heading)
4619 (< (point) end))
4620 (not (eobp)))
4621 (funcall fun)))))
4623 (defun org-fixup-indentation (diff)
4624 "Change the indentation in the current entry by DIFF
4625 However, if any line in the current entry has no indentation, or if it
4626 would end up with no indentation after the change, nothing at all is done."
4627 (save-excursion
4628 (let ((end (save-excursion (outline-next-heading)
4629 (point-marker)))
4630 (prohibit (if (> diff 0)
4631 "^\\S-"
4632 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4633 col)
4634 (unless (save-excursion (re-search-forward prohibit end t))
4635 (while (re-search-forward "^[ \t]+" end t)
4636 (goto-char (match-end 0))
4637 (setq col (current-column))
4638 (if (< diff 0) (replace-match ""))
4639 (indent-to (+ diff col))))
4640 (move-marker end nil))))
4642 (defun org-convert-to-odd-levels ()
4643 "Convert an org-mode file with all levels allowed to one with odd levels.
4644 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4645 level 5 etc."
4646 (interactive)
4647 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4648 (let ((org-odd-levels-only nil) n)
4649 (save-excursion
4650 (goto-char (point-min))
4651 (while (re-search-forward "^\\*\\*+" nil t)
4652 (setq n (1- (length (match-string 0))))
4653 (while (>= (setq n (1- n)) 0)
4654 (org-demote))
4655 (end-of-line 1))))))
4658 (defun org-convert-to-oddeven-levels ()
4659 "Convert an org-mode file with only odd levels to one with odd and even levels.
4660 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4661 section with an even level, conversion would destroy the structure of the file. An error
4662 is signaled in this case."
4663 (interactive)
4664 (goto-char (point-min))
4665 ;; First check if there are no even levels
4666 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
4667 (org-show-context t)
4668 (error "Not all levels are odd in this file. Conversion not possible."))
4669 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4670 (let ((org-odd-levels-only nil) n)
4671 (save-excursion
4672 (goto-char (point-min))
4673 (while (re-search-forward "^\\*\\*+" nil t)
4674 (setq n (/ (length (match-string 0)) 2))
4675 (while (>= (setq n (1- n)) 0)
4676 (org-promote))
4677 (end-of-line 1))))))
4679 (defun org-tr-level (n)
4680 "Make N odd if required."
4681 (if org-odd-levels-only (1+ (/ n 2)) n))
4683 ;;; Vertical tree motion, cutting and pasting of subtrees
4685 (defun org-move-subtree-up (&optional arg)
4686 "Move the current subtree up past ARG headlines of the same level."
4687 (interactive "p")
4688 (org-move-subtree-down (- (prefix-numeric-value arg))))
4690 (defun org-move-subtree-down (&optional arg)
4691 "Move the current subtree down past ARG headlines of the same level."
4692 (interactive "p")
4693 (setq arg (prefix-numeric-value arg))
4694 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4695 'outline-get-last-sibling))
4696 (ins-point (make-marker))
4697 (cnt (abs arg))
4698 beg end txt folded)
4699 ;; Select the tree
4700 (org-back-to-heading)
4701 (setq beg (point))
4702 (save-match-data
4703 (save-excursion (outline-end-of-heading)
4704 (setq folded (org-invisible-p)))
4705 (outline-end-of-subtree))
4706 (outline-next-heading)
4707 (setq end (point))
4708 ;; Find insertion point, with error handling
4709 (goto-char beg)
4710 (while (> cnt 0)
4711 (or (and (funcall movfunc) (looking-at outline-regexp))
4712 (progn (goto-char beg)
4713 (error "Cannot move past superior level or buffer limit")))
4714 (setq cnt (1- cnt)))
4715 (if (> arg 0)
4716 ;; Moving forward - still need to move over subtree
4717 (progn (outline-end-of-subtree)
4718 (outline-next-heading)
4719 (if (not (or (looking-at (concat "^" outline-regexp))
4720 (bolp)))
4721 (newline))))
4722 (move-marker ins-point (point))
4723 (setq txt (buffer-substring beg end))
4724 (delete-region beg end)
4725 (insert txt)
4726 (goto-char ins-point)
4727 (if folded (hide-subtree))
4728 (move-marker ins-point nil)))
4730 (defvar org-subtree-clip ""
4731 "Clipboard for cut and paste of subtrees.
4732 This is actually only a copy of the kill, because we use the normal kill
4733 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4735 (defvar org-subtree-clip-folded nil
4736 "Was the last copied subtree folded?
4737 This is used to fold the tree back after pasting.")
4739 (defun org-cut-subtree ()
4740 "Cut the current subtree into the clipboard.
4741 This is a short-hand for marking the subtree and then cutting it."
4742 (interactive)
4743 (org-copy-subtree 'cut))
4745 (defun org-copy-subtree (&optional cut)
4746 "Cut the current subtree into the clipboard.
4747 This is a short-hand for marking the subtree and then copying it.
4748 If CUT is non-nil, actually cut the subtree."
4749 (interactive)
4750 (let (beg end folded)
4751 (org-back-to-heading)
4752 (setq beg (point))
4753 (save-match-data
4754 (save-excursion (outline-end-of-heading)
4755 (setq folded (org-invisible-p)))
4756 (outline-end-of-subtree))
4757 (if (equal (char-after) ?\n) (forward-char 1))
4758 (setq end (point))
4759 (goto-char beg)
4760 (when (> end beg)
4761 (setq org-subtree-clip-folded folded)
4762 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4763 (setq org-subtree-clip (current-kill 0))
4764 (message "%s: Subtree with %d characters"
4765 (if cut "Cut" "Copied")
4766 (length org-subtree-clip)))))
4768 (defun org-paste-subtree (&optional level tree)
4769 "Paste the clipboard as a subtree, with modification of headline level.
4770 The entire subtree is promoted or demoted in order to match a new headline
4771 level. By default, the new level is derived from the visible headings
4772 before and after the insertion point, and taken to be the inferior headline
4773 level of the two. So if the previous visible heading is level 3 and the
4774 next is level 4 (or vice versa), level 4 will be used for insertion.
4775 This makes sure that the subtree remains an independent subtree and does
4776 not swallow low level entries.
4778 You can also force a different level, either by using a numeric prefix
4779 argument, or by inserting the heading marker by hand. For example, if the
4780 cursor is after \"*****\", then the tree will be shifted to level 5.
4782 If you want to insert the tree as is, just use \\[yank].
4784 If optional TREE is given, use this text instead of the kill ring."
4785 (interactive "P")
4786 (unless (org-kill-is-subtree-p tree)
4787 (error
4788 (substitute-command-keys
4789 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4790 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4791 (^re (concat "^\\(" outline-regexp "\\)"))
4792 (re (concat "\\(" outline-regexp "\\)"))
4793 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4795 (old-level (if (string-match ^re txt)
4796 (- (match-end 0) (match-beginning 0))
4797 -1))
4798 (force-level (cond (level (prefix-numeric-value level))
4799 ((string-match
4800 ^re_ (buffer-substring (point-at-bol) (point)))
4801 (- (match-end 0) (match-beginning 0)))
4802 (t nil)))
4803 (previous-level (save-excursion
4804 (condition-case nil
4805 (progn
4806 (outline-previous-visible-heading 1)
4807 (if (looking-at re)
4808 (- (match-end 0) (match-beginning 0))
4810 (error 1))))
4811 (next-level (save-excursion
4812 (condition-case nil
4813 (progn
4814 (outline-next-visible-heading 1)
4815 (if (looking-at re)
4816 (- (match-end 0) (match-beginning 0))
4818 (error 1))))
4819 (new-level (or force-level (max previous-level next-level)))
4820 (shift (if (or (= old-level -1)
4821 (= new-level -1)
4822 (= old-level new-level))
4824 (- new-level old-level)))
4825 (shift1 shift)
4826 (delta (if (> shift 0) -1 1))
4827 (func (if (> shift 0) 'org-demote 'org-promote))
4828 (org-odd-levels-only nil)
4829 beg end)
4830 ;; Remove the forces level indicator
4831 (if force-level
4832 (delete-region (point-at-bol) (point)))
4833 ;; Make sure we start at the beginning of an empty line
4834 (if (not (bolp)) (insert "\n"))
4835 (if (not (looking-at "[ \t]*$"))
4836 (progn (insert "\n") (backward-char 1)))
4837 ;; Paste
4838 (setq beg (point))
4839 (if (string-match "[ \t\r\n]+\\'" txt)
4840 (setq txt (replace-match "\n" t t txt)))
4841 (insert txt)
4842 (setq end (point))
4843 (if (looking-at "[ \t\r\n]+")
4844 (replace-match "\n"))
4845 (goto-char beg)
4846 ;; Shift if necessary
4847 (if (= shift 0)
4848 (message "Pasted at level %d, without shift" new-level)
4849 (save-restriction
4850 (narrow-to-region beg end)
4851 (while (not (= shift 0))
4852 (org-map-region func (point-min) (point-max))
4853 (setq shift (+ delta shift)))
4854 (goto-char (point-min))
4855 (message "Pasted at level %d, with shift by %d levels"
4856 new-level shift1)))
4857 (if (and kill-ring
4858 (eq org-subtree-clip (current-kill 0))
4859 org-subtree-clip-folded)
4860 ;; The tree was folded before it was killed/copied
4861 (hide-subtree))))
4863 (defun org-kill-is-subtree-p (&optional txt)
4864 "Check if the current kill is an outline subtree, or a set of trees.
4865 Returns nil if kill does not start with a headline, or if the first
4866 headline level is not the largest headline level in the tree.
4867 So this will actually accept several entries of equal levels as well,
4868 which is OK for `org-paste-subtree'.
4869 If optional TXT is given, check this string instead of the current kill."
4870 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4871 (start-level (and kill
4872 (string-match (concat "\\`" outline-regexp) kill)
4873 (- (match-end 0) (match-beginning 0))))
4874 (re (concat "^" outline-regexp))
4875 (start 1))
4876 (if (not start-level)
4877 nil ;; does not even start with a heading
4878 (catch 'exit
4879 (while (setq start (string-match re kill (1+ start)))
4880 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4881 (throw 'exit nil)))
4882 t))))
4884 (defun org-narrow-to-subtree ()
4885 "Narrow buffer to the current subtree."
4886 (interactive)
4887 (save-excursion
4888 (narrow-to-region
4889 (progn (org-back-to-heading) (point))
4890 (progn (org-end-of-subtree t) (point)))))
4893 ;;; Outline Sorting
4895 (defun org-sort (with-case)
4896 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
4897 (interactive "P")
4898 (if (org-at-table-p)
4899 (org-call-with-arg 'org-table-sort-lines with-case)
4900 (org-call-with-arg 'org-sort-entries with-case)))
4902 (defun org-sort-entries (&optional with-case sorting-type)
4903 "Sort entries on a certain level of an outline tree.
4904 If there is an active region, the entries in the region are sorted.
4905 Else, if the cursor is before the first entry, sort the top-level items.
4906 Else, the children of the entry at point are sorted.
4908 Sorting can be alphabetically, numerically, and by date/time as given by
4909 the first time stamp in the entry. The command prompts for the sorting
4910 type unless it has been given to the function through the SORTING-TYPE
4911 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
4913 Comparing entries ignores case by default. However, with an optional argument
4914 WITH-CASE, the sorting considers case as well. With two prefix arguments
4915 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
4916 (interactive "P")
4917 (let ((unique (equal with-case '(16)))
4918 start beg end entries stars re re2 p nentries (nremoved 0)
4919 last txt what)
4920 ;; Find beginning and end of region to sort
4921 (cond
4922 ((org-region-active-p)
4923 ;; we will sort the region
4924 (setq end (region-end)
4925 what "region")
4926 (goto-char (region-beginning))
4927 (if (not (org-on-heading-p)) (outline-next-heading))
4928 (setq start (point)))
4929 ((or (org-on-heading-p)
4930 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4931 ;; we will sort the children of the current headline
4932 (org-back-to-heading)
4933 (setq start (point) end (org-end-of-subtree) what "children")
4934 (goto-char start)
4935 (show-subtree)
4936 (outline-next-heading))
4938 ;; we will sort the top-level entries in this file
4939 (goto-char (point-min))
4940 (or (org-on-heading-p) (outline-next-heading))
4941 (setq start (point) end (point-max) what "top-level")
4942 (goto-char start)
4943 (show-all)))
4944 (setq beg (point))
4945 (if (>= (point) end) (error "Nothing to sort"))
4946 (looking-at "\\(\\*+\\)")
4947 (setq stars (match-string 1)
4948 re (concat "^" (regexp-quote stars) " +")
4949 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4950 txt (buffer-substring beg end))
4951 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4952 (if (and (not (equal stars "*")) (string-match re2 txt))
4953 (error "Region to sort contains a level above the first entry"))
4954 ;; Make a list that can be sorted.
4955 ;; The car is the string for comparison, the cdr is the subtree
4956 (message "Sorting entries...")
4957 (setq entries
4958 (mapcar
4959 (lambda (x)
4960 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
4961 (cons (match-string 0 x) x))
4962 (org-split-string txt re)))
4964 ;; Sort the list
4965 (save-excursion
4966 (goto-char start)
4967 (setq entries (org-do-sort entries what with-case sorting-type)))
4969 ;; Delete the old stuff
4970 (goto-char beg)
4971 (kill-region beg end)
4972 (setq nentries (length entries))
4973 ;; Insert the sorted entries, and remove duplicates if this is required
4974 (while (setq p (pop entries))
4975 (if (and unique (equal last (setq last (org-trim (cdr p)))))
4976 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
4977 (insert stars " " (cdr p))))
4978 (goto-char start)
4979 (message "Sorting entries...done (%d entries%s)"
4980 nentries
4981 (if unique (format ", %d duplicates removed" nremoved) ""))))
4983 (defun org-do-sort (table what &optional with-case sorting-type)
4984 "Sort TABLE of WHAT according to SORTING-TYPE.
4985 The user will be prompted for the SORTING-TYPE if the call to this
4986 function does not specify it. WHAT is only for the prompt, to indicate
4987 what is being sorted. The sorting key will be extracted from
4988 the car of the elements of the table.
4989 If WITH-CASE is non-nil, the sorting will be case-sensitive."
4990 (unless sorting-type
4991 (message
4992 "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
4993 what)
4994 (setq sorting-type (read-char-exclusive)))
4995 (let ((dcst (downcase sorting-type))
4996 extractfun comparefun)
4997 ;; Define the appropriate functions
4998 (cond
4999 ((= dcst ?n)
5000 (setq extractfun 'string-to-number
5001 comparefun (if (= dcst sorting-type) '< '>)))
5002 ((= dcst ?a)
5003 (setq extractfun (if with-case 'identity 'downcase)
5004 comparefun (if (= dcst sorting-type)
5005 'string<
5006 (lambda (a b) (and (not (string< a b))
5007 (not (string= a b)))))))
5008 ((= dcst ?t)
5009 (setq extractfun
5010 (lambda (x)
5011 (if (string-match org-ts-regexp x)
5012 (time-to-seconds
5013 (org-time-string-to-time (match-string 0 x)))
5015 comparefun (if (= dcst sorting-type) '< '>)))
5016 (t (error "Invalid sorting type `%c'" sorting-type)))
5018 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5019 table)
5020 (lambda (a b) (funcall comparefun (car a) (car b))))))
5022 ;;;; Plain list items, including checkboxes
5024 ;;; Plain list items
5026 (defun org-at-item-p ()
5027 "Is point in a line starting a hand-formatted item?"
5028 (let ((llt org-plain-list-ordered-item-terminator))
5029 (save-excursion
5030 (goto-char (point-at-bol))
5031 (looking-at
5032 (cond
5033 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5034 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5035 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5036 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5039 (defun org-in-item-p ()
5040 "It the cursor inside a plain list item.
5041 Does not have to be the first line."
5042 (save-excursion
5043 (condition-case nil
5044 (progn
5045 (org-beginning-of-item)
5046 (org-at-item-p)
5048 (error nil))))
5050 (defun org-insert-item (&optional checkbox)
5051 "Insert a new item at the current level.
5052 Return t when things worked, nil when we are not in an item."
5053 (when (save-excursion
5054 (condition-case nil
5055 (progn
5056 (org-beginning-of-item)
5057 (org-at-item-p)
5058 (if (org-invisible-p) (error "Invisible item"))
5060 (error nil)))
5061 (let* ((bul (match-string 0))
5062 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5063 (match-end 0)))
5064 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5065 pos)
5066 (cond
5067 ((and (org-at-item-p) (<= (point) eow))
5068 ;; before the bullet
5069 (beginning-of-line 1)
5070 (open-line (if blank 2 1)))
5071 ((<= (point) eow)
5072 (beginning-of-line 1))
5073 (t (newline (if blank 2 1))))
5074 (insert bul (if checkbox "[ ]" ""))
5075 (just-one-space)
5076 (setq pos (point))
5077 (end-of-line 1)
5078 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5079 (org-maybe-renumber-ordered-list)
5080 (and checkbox (org-update-checkbox-count-maybe))
5083 ;;; Checkboxes
5085 (defun org-at-item-checkbox-p ()
5086 "Is point at a line starting a plain-list item with a checklet?"
5087 (and (org-at-item-p)
5088 (save-excursion
5089 (goto-char (match-end 0))
5090 (skip-chars-forward " \t")
5091 (looking-at "\\[[ X]\\]"))))
5093 (defun org-toggle-checkbox (&optional arg)
5094 "Toggle the checkbox in the current line."
5095 (interactive "P")
5096 (catch 'exit
5097 (let (beg end status (firstnew 'unknown))
5098 (cond
5099 ((org-region-active-p)
5100 (setq beg (region-beginning) end (region-end)))
5101 ((org-on-heading-p)
5102 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5103 ((org-at-item-checkbox-p)
5104 (save-excursion
5105 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
5106 (throw 'exit t))
5107 (t (error "Not at a checkbox or heading, and no active region")))
5108 (save-excursion
5109 (goto-char beg)
5110 (while (< (point) end)
5111 (when (org-at-item-checkbox-p)
5112 (setq status (equal (match-string 0) "[X]"))
5113 (when (eq firstnew 'unknown)
5114 (setq firstnew (not status)))
5115 (replace-match
5116 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5117 (beginning-of-line 2)))))
5118 (org-update-checkbox-count-maybe))
5120 (defun org-update-checkbox-count-maybe ()
5121 "Update checkbox statistics unless turned off by user."
5122 (when org-provide-checkbox-statistics
5123 (org-update-checkbox-count)))
5125 (defun org-update-checkbox-count (&optional all)
5126 "Update the checkbox statistics in the current section.
5127 This will find all statistic cookies like [57%] and [6/12] and update them
5128 with the current numbers. With optional prefix argument ALL, do this for
5129 the whole buffer."
5130 (interactive "P")
5131 (save-excursion
5132 (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
5133 (beg (progn (outline-back-to-heading) (point)))
5134 (end (move-marker (make-marker)
5135 (progn (outline-next-heading) (point))))
5136 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5137 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
5138 b1 e1 f1 c-on c-off lim (cstat 0))
5139 (when all
5140 (goto-char (point-min))
5141 (outline-next-heading)
5142 (setq beg (point) end (point-max)))
5143 (goto-char beg)
5144 (while (re-search-forward re end t)
5145 (setq cstat (1+ cstat)
5146 b1 (match-beginning 0)
5147 e1 (match-end 0)
5148 f1 (match-beginning 1)
5149 lim (cond
5150 ((org-on-heading-p) (outline-next-heading) (point))
5151 ((org-at-item-p) (org-end-of-item) (point))
5152 (t nil))
5153 c-on 0 c-off 0)
5154 (goto-char e1)
5155 (when lim
5156 (while (re-search-forward re-box lim t)
5157 (if (equal (match-string 2) "[ ]")
5158 (setq c-off (1+ c-off))
5159 (setq c-on (1+ c-on))))
5160 (delete-region b1 e1)
5161 (goto-char b1)
5162 (insert (if f1
5163 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5164 (format "[%d/%d]" c-on (+ c-on c-off))))))
5165 (when (interactive-p)
5166 (message "Checkbox satistics updated %s (%d places)"
5167 (if all "in entire file" "in current outline entry") cstat)))))
5169 (defun org-get-checkbox-statistics-face ()
5170 "Select the face for checkbox statistics.
5171 The face will be `org-done' when all relevant boxes are checked. Otherwise
5172 it will be `org-todo'."
5173 (if (match-end 1)
5174 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5175 (if (and (> (match-end 2) (match-beginning 2))
5176 (equal (match-string 2) (match-string 3)))
5177 'org-done
5178 'org-todo)))
5180 (defun org-get-indentation (&optional line)
5181 "Get the indentation of the current line, interpreting tabs.
5182 When LINE is given, assume it represents a line and compute its indentation."
5183 (if line
5184 (if (string-match "^ *" (org-remove-tabs line))
5185 (match-end 0))
5186 (save-excursion
5187 (beginning-of-line 1)
5188 (skip-chars-forward " \t")
5189 (current-column))))
5191 (defun org-remove-tabs (s &optional width)
5192 "Replace tabulators in S with spaces.
5193 Assumes that s is a single line, starting in column 0."
5194 (setq width (or width tab-width))
5195 (while (string-match "\t" s)
5196 (setq s (replace-match
5197 (make-string
5198 (- (* width (/ (+ (match-beginning 0) width) width))
5199 (match-beginning 0)) ?\ )
5200 t t s)))
5203 (defun org-fix-indentation (line ind)
5204 "Fix indentation in LINE.
5205 IND is a cons cell with target and minimum indentation.
5206 If the current indenation in LINE is smaller than the minimum,
5207 leave it alone. If it is larger than ind, set it to the target."
5208 (let* ((l (org-remove-tabs line))
5209 (i (org-get-indentation l))
5210 (i1 (car ind)) (i2 (cdr ind)))
5211 (if (>= i i2) (setq l (substring line i2)))
5212 (if (> i1 0)
5213 (concat (make-string i1 ?\ ) l)
5214 l)))
5216 (defun org-beginning-of-item ()
5217 "Go to the beginning of the current hand-formatted item.
5218 If the cursor is not in an item, throw an error."
5219 (interactive)
5220 (let ((pos (point))
5221 (limit (save-excursion (org-back-to-heading)
5222 (beginning-of-line 2) (point)))
5223 ind ind1)
5224 (if (org-at-item-p)
5225 (beginning-of-line 1)
5226 (beginning-of-line 1)
5227 (skip-chars-forward " \t")
5228 (setq ind (current-column))
5229 (if (catch 'exit
5230 (while t
5231 (beginning-of-line 0)
5232 (if (< (point) limit) (throw 'exit nil))
5233 (unless (looking-at "[ \t]*$")
5234 (skip-chars-forward " \t")
5235 (setq ind1 (current-column))
5236 (if (< ind1 ind)
5237 (throw 'exit (org-at-item-p))))))
5239 (goto-char pos)
5240 (error "Not in an item")))))
5242 (defun org-end-of-item ()
5243 "Go to the end of the current hand-formatted item.
5244 If the cursor is not in an item, throw an error."
5245 (interactive)
5246 (let ((pos (point))
5247 (limit (save-excursion (outline-next-heading) (point)))
5248 (ind (save-excursion
5249 (org-beginning-of-item)
5250 (skip-chars-forward " \t")
5251 (current-column)))
5252 ind1)
5253 (if (catch 'exit
5254 (while t
5255 (beginning-of-line 2)
5256 (if (>= (point) limit) (throw 'exit t))
5257 (unless (looking-at "[ \t]*$")
5258 (skip-chars-forward " \t")
5259 (setq ind1 (current-column))
5260 (if (<= ind1 ind) (throw 'exit t)))))
5261 (beginning-of-line 1)
5262 (goto-char pos)
5263 (error "Not in an item"))))
5265 (defun org-next-item ()
5266 "Move to the beginning of the next item in the current plain list.
5267 Error if not at a plain list, or if this is the last item in the list."
5268 (interactive)
5269 (let (ind ind1 (pos (point)))
5270 (org-beginning-of-item)
5271 (setq ind (org-get-indentation))
5272 (org-end-of-item)
5273 (setq ind1 (org-get-indentation))
5274 (unless (and (org-at-item-p) (= ind ind1))
5275 (goto-char pos)
5276 (error "On last item"))))
5278 (defun org-previous-item ()
5279 "Move to the beginning of the previous item in the current plain list.
5280 Error if not at a plain list, or if this is the last item in the list."
5281 (interactive)
5282 (let (beg ind (pos (point)))
5283 (org-beginning-of-item)
5284 (setq beg (point))
5285 (setq ind (org-get-indentation))
5286 (goto-char beg)
5287 (catch 'exit
5288 (while t
5289 (beginning-of-line 0)
5290 (if (looking-at "[ \t]*$")
5292 (if (<= (org-get-indentation) ind)
5293 (throw 'exit t)))))
5294 (condition-case nil
5295 (org-beginning-of-item)
5296 (error (goto-char pos)
5297 (error "On first item")))))
5299 (defun org-move-item-down ()
5300 "Move the plain list item at point down, i.e. swap with following item.
5301 Subitems (items with larger indentation) are considered part of the item,
5302 so this really moves item trees."
5303 (interactive)
5304 (let (beg end ind ind1 (pos (point)) txt)
5305 (org-beginning-of-item)
5306 (setq beg (point))
5307 (setq ind (org-get-indentation))
5308 (org-end-of-item)
5309 (setq end (point))
5310 (setq ind1 (org-get-indentation))
5311 (if (and (org-at-item-p) (= ind ind1))
5312 (progn
5313 (org-end-of-item)
5314 (setq txt (buffer-substring beg end))
5315 (save-excursion
5316 (delete-region beg end))
5317 (setq pos (point))
5318 (insert txt)
5319 (goto-char pos)
5320 (org-maybe-renumber-ordered-list))
5321 (goto-char pos)
5322 (error "Cannot move this item further down"))))
5324 (defun org-move-item-up (arg)
5325 "Move the plain list item at point up, i.e. swap with previous item.
5326 Subitems (items with larger indentation) are considered part of the item,
5327 so this really moves item trees."
5328 (interactive "p")
5329 (let (beg end ind ind1 (pos (point)) txt)
5330 (org-beginning-of-item)
5331 (setq beg (point))
5332 (setq ind (org-get-indentation))
5333 (org-end-of-item)
5334 (setq end (point))
5335 (goto-char beg)
5336 (catch 'exit
5337 (while t
5338 (beginning-of-line 0)
5339 (if (looking-at "[ \t]*$")
5341 (if (<= (setq ind1 (org-get-indentation)) ind)
5342 (throw 'exit t)))))
5343 (condition-case nil
5344 (org-beginning-of-item)
5345 (error (goto-char beg)
5346 (error "Cannot move this item further up")))
5347 (setq ind1 (org-get-indentation))
5348 (if (and (org-at-item-p) (= ind ind1))
5349 (progn
5350 (setq txt (buffer-substring beg end))
5351 (save-excursion
5352 (delete-region beg end))
5353 (setq pos (point))
5354 (insert txt)
5355 (goto-char pos)
5356 (org-maybe-renumber-ordered-list))
5357 (goto-char pos)
5358 (error "Cannot move this item further up"))))
5360 (defun org-maybe-renumber-ordered-list ()
5361 "Renumber the ordered list at point if setup allows it.
5362 This tests the user option `org-auto-renumber-ordered-lists' before
5363 doing the renumbering."
5364 (and org-auto-renumber-ordered-lists
5365 (org-at-item-p)
5366 (match-beginning 3)
5367 (org-renumber-ordered-list 1)))
5369 (defun org-get-string-indentation (s)
5370 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5371 (let ((n -1) (i 0) (w tab-width) c)
5372 (catch 'exit
5373 (while (< (setq n (1+ n)) (length s))
5374 (setq c (aref s n))
5375 (cond ((= c ?\ ) (setq i (1+ i)))
5376 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5377 (t (throw 'exit t)))))
5380 (defun org-renumber-ordered-list (arg)
5381 "Renumber an ordered plain list.
5382 Cursor needs to be in the first line of an item, the line that starts
5383 with something like \"1.\" or \"2)\"."
5384 (interactive "p")
5385 (unless (and (org-at-item-p)
5386 (match-beginning 3))
5387 (error "This is not an ordered list"))
5388 (let ((line (org-current-line))
5389 (col (current-column))
5390 (ind (org-get-string-indentation
5391 (buffer-substring (point-at-bol) (match-beginning 3))))
5392 ;; (term (substring (match-string 3) -1))
5393 ind1 (n (1- arg)))
5394 ;; find where this list begins
5395 (catch 'exit
5396 (while t
5397 (catch 'next
5398 (beginning-of-line 0)
5399 (if (looking-at "[ \t]*$") (throw 'next t))
5400 (skip-chars-forward " \t") (setq ind1 (current-column))
5401 (if (or (< ind1 ind)
5402 (and (= ind1 ind)
5403 (not (org-at-item-p))))
5404 (throw 'exit t)))))
5405 ;; Walk forward and replace these numbers
5406 (catch 'exit
5407 (while t
5408 (catch 'next
5409 (beginning-of-line 2)
5410 (if (eobp) (throw 'exit nil))
5411 (if (looking-at "[ \t]*$") (throw 'next nil))
5412 (skip-chars-forward " \t") (setq ind1 (current-column))
5413 (if (> ind1 ind) (throw 'next t))
5414 (if (< ind1 ind) (throw 'exit t))
5415 (if (not (org-at-item-p)) (throw 'exit nil))
5416 (if (not (match-beginning 3))
5417 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
5418 (delete-region (match-beginning 3) (1- (match-end 3)))
5419 (goto-char (match-beginning 3))
5420 (insert (format "%d" (setq n (1+ n)))))))
5421 (goto-line line)
5422 (move-to-column col)))
5424 (defvar org-last-indent-begin-marker (make-marker))
5425 (defvar org-last-indent-end-marker (make-marker))
5427 (defun org-outdent-item (arg)
5428 "Outdent a local list item."
5429 (interactive "p")
5430 (org-indent-item (- arg)))
5432 (defun org-indent-item (arg)
5433 "Indent a local list item."
5434 (interactive "p")
5435 (unless (org-at-item-p)
5436 (error "Not on an item"))
5437 (save-excursion
5438 (let (beg end ind ind1)
5439 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5440 (setq beg org-last-indent-begin-marker
5441 end org-last-indent-end-marker)
5442 (org-beginning-of-item)
5443 (setq beg (move-marker org-last-indent-begin-marker (point)))
5444 (org-end-of-item)
5445 (setq end (move-marker org-last-indent-end-marker (point))))
5446 (goto-char beg)
5447 (skip-chars-forward " \t") (setq ind (current-column))
5448 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
5449 (while (< (point) end)
5450 (beginning-of-line 1)
5451 (skip-chars-forward " \t") (setq ind1 (current-column))
5452 (delete-region (point-at-bol) (point))
5453 (indent-to-column (+ ind1 arg))
5454 (beginning-of-line 2)))))
5456 ;;;; Archiving
5458 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
5460 (defun org-archive-subtree (&optional find-done)
5461 "Move the current subtree to the archive.
5462 The archive can be a certain top-level heading in the current file, or in
5463 a different file. The tree will be moved to that location, the subtree
5464 heading be marked DONE, and the current time will be added.
5466 When called with prefix argument FIND-DONE, find whole trees without any
5467 open TODO items and archive them (after getting confirmation from the user).
5468 If the cursor is not at a headline when this comand is called, try all level
5469 1 trees. If the cursor is on a headline, only try the direct children of
5470 this heading. "
5471 (interactive "P")
5472 (if find-done
5473 (org-archive-all-done)
5474 ;; Save all relevant TODO keyword-relatex variables
5476 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5477 (tr-org-todo-keywords org-todo-keywords)
5478 (tr-org-todo-interpretation org-todo-interpretation)
5479 (tr-org-done-string org-done-string)
5480 (tr-org-todo-regexp org-todo-regexp)
5481 (tr-org-todo-line-regexp org-todo-line-regexp)
5482 (tr-org-odd-levels-only org-odd-levels-only)
5483 (this-buffer (current-buffer))
5484 (org-archive-location org-archive-location)
5485 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
5486 file heading buffer level newfile-p)
5488 ;; Try to find a local archive location
5489 (save-excursion
5490 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
5491 (setq org-archive-location (match-string 1))))
5493 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5494 (progn
5495 (setq file (format (match-string 1 org-archive-location)
5496 (file-name-nondirectory buffer-file-name))
5497 heading (match-string 2 org-archive-location)))
5498 (error "Invalid `org-archive-location'"))
5499 (if (> (length file) 0)
5500 (setq newfile-p (not (file-exists-p file))
5501 buffer (find-file-noselect file))
5502 (setq buffer (current-buffer)))
5503 (unless buffer
5504 (error "Cannot access file \"%s\"" file))
5505 (if (and (> (length heading) 0)
5506 (string-match "^\\*+" heading))
5507 (setq level (match-end 0))
5508 (setq heading nil level 0))
5509 (save-excursion
5510 ;; We first only copy, in case something goes wrong
5511 ;; we need to protect this-command, to avoid kill-region sets it,
5512 ;; which would lead to duplication of subtrees
5513 (let (this-command) (org-copy-subtree))
5514 (set-buffer buffer)
5515 ;; Enforce org-mode for the archive buffer
5516 (if (not (org-mode-p))
5517 ;; Force the mode for future visits.
5518 (let ((org-insert-mode-line-in-empty-file t))
5519 (call-interactively 'org-mode)))
5520 (when newfile-p
5521 (goto-char (point-max))
5522 (insert (format "\nArchived entries from file %s\n\n"
5523 (buffer-file-name this-buffer))))
5524 ;; Force the TODO keywords of the original buffer
5525 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
5526 (org-todo-keywords tr-org-todo-keywords)
5527 (org-todo-interpretation tr-org-todo-interpretation)
5528 (org-done-string tr-org-done-string)
5529 (org-todo-regexp tr-org-todo-regexp)
5530 (org-todo-line-regexp tr-org-todo-line-regexp)
5531 (org-odd-levels-only (if (local-variable-p org-odd-levels-only)
5532 org-odd-levels-only
5533 tr-org-odd-levels-only)))
5534 (goto-char (point-min))
5535 (if heading
5536 (progn
5537 (if (re-search-forward
5538 (concat "\\(^\\|\r\\)"
5539 (regexp-quote heading) "[ \t]*\\(:[a-zA-Z0-9_@:]+:\\)?[ \t]*\\($\\|\r\\)")
5540 nil t)
5541 (goto-char (match-end 0))
5542 ;; Heading not found, just insert it at the end
5543 (goto-char (point-max))
5544 (or (bolp) (insert "\n"))
5545 (insert "\n" heading "\n")
5546 (end-of-line 0))
5547 ;; Make the subtree visible
5548 (show-subtree)
5549 (org-end-of-subtree t)
5550 (skip-chars-backward " \t\r\n")
5551 (and (looking-at "[ \t\r\n]*")
5552 (replace-match "\n\n")))
5553 ;; No specific heading, just go to end of file.
5554 (goto-char (point-max)) (insert "\n"))
5555 ;; Paste
5556 (org-paste-subtree (org-get-legal-level level 1))
5557 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
5558 (if org-archive-mark-done
5559 (let (org-log-done)
5560 (org-todo (length org-todo-keywords))))
5561 ;; Move cursor to right after the TODO keyword
5562 (when org-archive-stamp-time
5563 (beginning-of-line 1)
5564 (looking-at org-todo-line-regexp)
5565 (goto-char (or (match-end 2) (match-beginning 3)))
5566 (org-insert-time-stamp (org-current-time) t t "(" ")"))
5567 ;; Save the buffer, if it is not the same buffer.
5568 (if (not (eq this-buffer buffer)) (save-buffer))))
5569 ;; Here we are back in the original buffer. Everything seems to have
5570 ;; worked. So now cut the tree and finish up.
5571 (let (this-command) (org-cut-subtree))
5572 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5573 (message "Subtree archived %s"
5574 (if (eq this-buffer buffer)
5575 (concat "under heading: " heading)
5576 (concat "in file: " (abbreviate-file-name file)))))))
5578 (defun org-archive-all-done (&optional tag)
5579 "Archive sublevels of the current tree without open TODO items.
5580 If the cursor is not on a headline, try all level 1 trees. If
5581 it is on a headline, try all direct children.
5582 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5583 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5584 (rea (concat ".*:" org-archive-tag ":"))
5585 (begm (make-marker))
5586 (endm (make-marker))
5587 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
5588 "Move subtree to archive (no open TODO items)? "))
5589 beg end (cntarch 0))
5590 (if (org-on-heading-p)
5591 (progn
5592 (setq re1 (concat "^" (regexp-quote
5593 (make-string
5594 (1+ (- (match-end 0) (match-beginning 0)))
5595 ?*))
5596 " "))
5597 (move-marker begm (point))
5598 (move-marker endm (org-end-of-subtree t)))
5599 (setq re1 "^* ")
5600 (move-marker begm (point-min))
5601 (move-marker endm (point-max)))
5602 (save-excursion
5603 (goto-char begm)
5604 (while (re-search-forward re1 endm t)
5605 (setq beg (match-beginning 0)
5606 end (save-excursion (org-end-of-subtree t) (point)))
5607 (goto-char beg)
5608 (if (re-search-forward re end t)
5609 (goto-char end)
5610 (goto-char beg)
5611 (if (and (or (not tag) (not (looking-at rea)))
5612 (y-or-n-p question))
5613 (progn
5614 (if tag
5615 (org-toggle-tag org-archive-tag 'on)
5616 (org-archive-subtree))
5617 (setq cntarch (1+ cntarch)))
5618 (goto-char end)))))
5619 (message "%d trees archived" cntarch)))
5621 (defun org-cycle-hide-archived-subtrees (state)
5622 "Re-hide all archived subtrees after a visibility state change."
5623 (when (and (not org-cycle-open-archived-trees)
5624 (not (memq state '(overview folded))))
5625 (save-excursion
5626 (let* ((globalp (memq state '(contents all)))
5627 (beg (if globalp (point-min) (point)))
5628 (end (if globalp (point-max) (org-end-of-subtree t))))
5629 (org-hide-archived-subtrees beg end)
5630 (goto-char beg)
5631 (if (looking-at (concat ".*:" org-archive-tag ":"))
5632 (message (substitute-command-keys
5633 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5635 (defun org-force-cycle-archived ()
5636 "Cycle subtree even if it is archived."
5637 (interactive)
5638 (setq this-command 'org-cycle)
5639 (let ((org-cycle-open-archived-trees t))
5640 (call-interactively 'org-cycle)))
5642 (defun org-hide-archived-subtrees (beg end)
5643 "Re-hide all archived subtrees after a visibility state change."
5644 (save-excursion
5645 (let* ((re (concat ":" org-archive-tag ":")))
5646 (goto-char beg)
5647 (while (re-search-forward re end t)
5648 (and (org-on-heading-p) (hide-subtree))
5649 (org-end-of-subtree t)))))
5651 (defun org-toggle-tag (tag &optional onoff)
5652 "Toggle the tag TAG for the current line.
5653 If ONOFF is `on' or `off', don't toggle but set to this state."
5654 (unless (org-on-heading-p) (error "Not on headling"))
5655 (let (res current)
5656 (save-excursion
5657 (beginning-of-line)
5658 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5659 (point-at-eol) t)
5660 (progn
5661 (setq current (match-string 1))
5662 (replace-match ""))
5663 (setq current ""))
5664 (setq current (nreverse (org-split-string current ":")))
5665 (cond
5666 ((eq onoff 'on)
5667 (setq res t)
5668 (or (member tag current) (push tag current)))
5669 ((eq onoff 'off)
5670 (or (not (member tag current)) (setq current (delete tag current))))
5671 (t (if (member tag current)
5672 (setq current (delete tag current))
5673 (setq res t)
5674 (push tag current))))
5675 (end-of-line 1)
5676 (when current
5677 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5678 (org-set-tags nil t))
5679 res))
5681 (defun org-toggle-archive-tag (&optional arg)
5682 "Toggle the archive tag for the current headline.
5683 With prefix ARG, check all children of current headline and offer tagging
5684 the children that do not contain any open TODO items."
5685 (interactive "P")
5686 (if arg
5687 (org-archive-all-done 'tag)
5688 (let (set)
5689 (save-excursion
5690 (org-back-to-heading t)
5691 (setq set (org-toggle-tag org-archive-tag))
5692 (when set (hide-subtree)))
5693 (and set (beginning-of-line 1))
5694 (message "Subtree %s" (if set "archived" "unarchived")))))
5697 ;;;; Tables
5699 ;;; The table editor
5701 ;; Watch out: Here we are talking about two different kind of tables.
5702 ;; Most of the code is for the tables created with the Org-mode table editor.
5703 ;; Sometimes, we talk about tables created and edited with the table.el
5704 ;; Emacs package. We call the former org-type tables, and the latter
5705 ;; table.el-type tables.
5707 (defun org-before-change-function (beg end)
5708 "Every change indicates that a table might need an update."
5709 (setq org-table-may-need-update t))
5711 (defconst org-table-line-regexp "^[ \t]*|"
5712 "Detects an org-type table line.")
5713 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5714 "Detects an org-type table line.")
5715 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5716 "Detects a table line marked for automatic recalculation.")
5717 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5718 "Detects a table line marked for automatic recalculation.")
5719 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5720 "Detects a table line marked for automatic recalculation.")
5721 (defconst org-table-hline-regexp "^[ \t]*|-"
5722 "Detects an org-type table hline.")
5723 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5724 "Detects a table-type table hline.")
5725 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5726 "Detects an org-type or table-type table.")
5727 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5728 "Searching from within a table (any type) this finds the first line
5729 outside the table.")
5730 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5731 "Searching from within a table (any type) this finds the first line
5732 outside the table.")
5734 (defvar org-table-last-highlighted-reference nil)
5735 (defvar org-table-formula-history nil)
5737 (defvar org-table-column-names nil
5738 "Alist with column names, derived from the `!' line.")
5739 (defvar org-table-column-name-regexp nil
5740 "Regular expression matching the current column names.")
5741 (defvar org-table-local-parameters nil
5742 "Alist with parameter names, derived from the `$' line.")
5743 (defvar org-table-named-field-locations nil
5744 "Alist with locations of named fields.")
5746 (defvar org-table-current-line-types nil
5747 "Table row types, non-nil only for the duration of a comand.")
5748 (defvar org-table-current-begin-line nil
5749 "Table begin line, non-nil only for the duration of a comand.")
5750 (defvar org-table-dlines nil
5751 "Vector of data line line numbers in the current table.")
5752 (defvar org-table-hlines nil
5753 "Vector of hline line numbers in the current table.")
5755 (defconst org-table-range-regexp
5756 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
5757 ;; 1 2 3 4 5
5758 "Regular expression for matching ranges in formulas.")
5760 (defconst org-table-range-regexp2
5761 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[a-zA-Z0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[a-zA-Z0-9]+\\)?\\)?\\|\\$[a-zA-Z0-9]+\\.\\.\\$[a-zA-Z0-9]+"
5762 "Regular expression to recognize ranges in formulas for highlighting.")
5764 (defvar org-inhibit-highlight-removal nil)
5767 (defun org-table-create-with-table.el ()
5768 "Use the table.el package to insert a new table.
5769 If there is already a table at point, convert between Org-mode tables
5770 and table.el tables."
5771 (interactive)
5772 (require 'table)
5773 (cond
5774 ((org-at-table.el-p)
5775 (if (y-or-n-p "Convert table to Org-mode table? ")
5776 (org-table-convert)))
5777 ((org-at-table-p)
5778 (if (y-or-n-p "Convert table to table.el table? ")
5779 (org-table-convert)))
5780 (t (call-interactively 'table-insert))))
5782 (defun org-table-create-or-convert-from-region (arg)
5783 "Convert region to table, or create an empty table.
5784 If there is an active region, convert it to a table. If there is no such
5785 region, create an empty table."
5786 (interactive "P")
5787 (if (org-region-active-p)
5788 (org-table-convert-region (region-beginning) (region-end) arg)
5789 (org-table-create arg)))
5791 (defun org-table-create (&optional size)
5792 "Query for a size and insert a table skeleton.
5793 SIZE is a string Columns x Rows like for example \"3x2\"."
5794 (interactive "P")
5795 (unless size
5796 (setq size (read-string
5797 (concat "Table size Columns x Rows [e.g. "
5798 org-table-default-size "]: ")
5799 "" nil org-table-default-size)))
5801 (let* ((pos (point))
5802 (indent (make-string (current-column) ?\ ))
5803 (split (org-split-string size " *x *"))
5804 (rows (string-to-number (nth 1 split)))
5805 (columns (string-to-number (car split)))
5806 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5807 "\n")))
5808 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5809 (point-at-bol) (point)))
5810 (beginning-of-line 1)
5811 (newline))
5812 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5813 (dotimes (i rows) (insert line))
5814 (goto-char pos)
5815 (if (> rows 1)
5816 ;; Insert a hline after the first row.
5817 (progn
5818 (end-of-line 1)
5819 (insert "\n|-")
5820 (goto-char pos)))
5821 (org-table-align)))
5823 (defun org-table-convert-region (beg0 end0 &optional nspace)
5824 "Convert region to a table.
5825 The region goes from BEG0 to END0, but these borders will be moved
5826 slightly, to make sure a beginning of line in the first line is included.
5827 When NSPACE is non-nil, it indicates the minimum number of spaces that
5828 separate columns (default: just one space)."
5829 (interactive "rP")
5830 (let* ((beg (min beg0 end0))
5831 (end (max beg0 end0))
5832 (tabsep t)
5834 (goto-char beg)
5835 (beginning-of-line 1)
5836 (setq beg (move-marker (make-marker) (point)))
5837 (goto-char end)
5838 (if (bolp) (backward-char 1) (end-of-line 1))
5839 (setq end (move-marker (make-marker) (point)))
5840 ;; Lets see if this is tab-separated material. If every nonempty line
5841 ;; contains a tab, we will assume that it is tab-separated material
5842 (if nspace
5843 (setq tabsep nil)
5844 (goto-char beg)
5845 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5846 (if nspace (setq tabsep nil))
5847 (if tabsep
5848 (setq re "^\\|\t")
5849 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5850 (max 1 (prefix-numeric-value nspace)))))
5851 (goto-char beg)
5852 (while (re-search-forward re end t)
5853 (replace-match "| " t t))
5854 (goto-char beg)
5855 (insert " ")
5856 (org-table-align)))
5858 (defun org-table-import (file arg)
5859 "Import FILE as a table.
5860 The file is assumed to be tab-separated. Such files can be produced by most
5861 spreadsheet and database applications. If no tabs (at least one per line)
5862 are found, lines will be split on whitespace into fields."
5863 (interactive "f\nP")
5864 (or (bolp) (newline))
5865 (let ((beg (point))
5866 (pm (point-max)))
5867 (insert-file-contents file)
5868 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5870 (defun org-table-export ()
5871 "Export table as a tab-separated file.
5872 Such a file can be imported into a spreadsheet program like Excel."
5873 (interactive)
5874 (let* ((beg (org-table-begin))
5875 (end (org-table-end))
5876 (table (buffer-substring beg end))
5877 (file (read-file-name "Export table to: "))
5878 buf)
5879 (unless (or (not (file-exists-p file))
5880 (y-or-n-p (format "Overwrite file %s? " file)))
5881 (error "Abort"))
5882 (with-current-buffer (find-file-noselect file)
5883 (setq buf (current-buffer))
5884 (erase-buffer)
5885 (fundamental-mode)
5886 (insert table)
5887 (goto-char (point-min))
5888 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5889 (replace-match "" t t)
5890 (end-of-line 1))
5891 (goto-char (point-min))
5892 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5893 (replace-match "" t t)
5894 (goto-char (min (1+ (point)) (point-max))))
5895 (goto-char (point-min))
5896 (while (re-search-forward "^-[-+]*$" nil t)
5897 (replace-match "")
5898 (if (looking-at "\n")
5899 (delete-char 1)))
5900 (goto-char (point-min))
5901 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5902 (replace-match "\t" t t))
5903 (save-buffer))
5904 (kill-buffer buf)))
5906 (defvar org-table-aligned-begin-marker (make-marker)
5907 "Marker at the beginning of the table last aligned.
5908 Used to check if cursor still is in that table, to minimize realignment.")
5909 (defvar org-table-aligned-end-marker (make-marker)
5910 "Marker at the end of the table last aligned.
5911 Used to check if cursor still is in that table, to minimize realignment.")
5912 (defvar org-table-last-alignment nil
5913 "List of flags for flushright alignment, from the last re-alignment.
5914 This is being used to correctly align a single field after TAB or RET.")
5915 (defvar org-table-last-column-widths nil
5916 "List of max width of fields in each column.
5917 This is being used to correctly align a single field after TAB or RET.")
5918 (defvar org-table-overlay-coordinates nil
5919 "Overlay coordinates after each align of a table.")
5920 (make-variable-buffer-local 'org-table-overlay-coordinates)
5922 (defvar org-last-recalc-line nil)
5923 (defconst org-narrow-column-arrow "=>"
5924 "Used as display property in narrowed table columns.")
5926 (defun org-table-align ()
5927 "Align the table at point by aligning all vertical bars."
5928 (interactive)
5929 (let* (
5930 ;; Limits of table
5931 (beg (org-table-begin))
5932 (end (org-table-end))
5933 ;; Current cursor position
5934 (linepos (org-current-line))
5935 (colpos (org-table-current-column))
5936 (winstart (window-start))
5937 (winstartline (org-current-line (min winstart (1- (point-max)))))
5938 lines (new "") lengths l typenums ty fields maxfields i
5939 column
5940 (indent "") cnt frac
5941 rfmt hfmt
5942 (spaces '(1 . 1))
5943 (sp1 (car spaces))
5944 (sp2 (cdr spaces))
5945 (rfmt1 (concat
5946 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5947 (hfmt1 (concat
5948 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5949 emptystrings links dates narrow fmax f1 len c e)
5950 (untabify beg end)
5951 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
5952 ;; Check if we have links or dates
5953 (goto-char beg)
5954 (setq links (re-search-forward org-bracket-link-regexp end t))
5955 (goto-char beg)
5956 (setq dates (and org-display-custom-times
5957 (re-search-forward org-ts-regexp-both end t)))
5958 ;; Make sure the link properties are right
5959 (when links (goto-char beg) (while (org-activate-bracket-links end)))
5960 ;; Make sure the date properties are right
5961 (when dates (goto-char beg) (while (org-activate-dates end)))
5963 ;; Check if we are narrowing any columns
5964 (goto-char beg)
5965 (setq narrow (and org-format-transports-properties-p
5966 (re-search-forward "<[0-9]+>" end t)))
5967 ;; Get the rows
5968 (setq lines (org-split-string
5969 (buffer-substring beg end) "\n"))
5970 ;; Store the indentation of the first line
5971 (if (string-match "^ *" (car lines))
5972 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
5973 ;; Mark the hlines by setting the corresponding element to nil
5974 ;; At the same time, we remove trailing space.
5975 (setq lines (mapcar (lambda (l)
5976 (if (string-match "^ *|-" l)
5978 (if (string-match "[ \t]+$" l)
5979 (substring l 0 (match-beginning 0))
5980 l)))
5981 lines))
5982 ;; Get the data fields by splitting the lines.
5983 (setq fields (mapcar
5984 (lambda (l)
5985 (org-split-string l " *| *"))
5986 (delq nil (copy-sequence lines))))
5987 ;; How many fields in the longest line?
5988 (condition-case nil
5989 (setq maxfields (apply 'max (mapcar 'length fields)))
5990 (error
5991 (kill-region beg end)
5992 (org-table-create org-table-default-size)
5993 (error "Empty table - created default table")))
5994 ;; A list of empty strings to fill any short rows on output
5995 (setq emptystrings (make-list maxfields ""))
5996 ;; Check for special formatting.
5997 (setq i -1)
5998 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
5999 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6000 ;; Check if there is an explicit width specified
6001 (when narrow
6002 (setq c column fmax nil)
6003 (while c
6004 (setq e (pop c))
6005 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
6006 (setq fmax (string-to-number (match-string 1 e)) c nil)))
6007 ;; Find fields that are wider than fmax, and shorten them
6008 (when fmax
6009 (loop for xx in column do
6010 (when (and (stringp xx)
6011 (> (org-string-width xx) fmax))
6012 (org-add-props xx nil
6013 'help-echo
6014 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
6015 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
6016 (unless (> f1 1)
6017 (error "Cannot narrow field starting with wide link \"%s\""
6018 (match-string 0 xx)))
6019 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
6020 (add-text-properties (- f1 2) f1
6021 (list 'display org-narrow-column-arrow)
6022 xx)))))
6023 ;; Get the maximum width for each column
6024 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
6025 ;; Get the fraction of numbers, to decide about alignment of the column
6026 (setq cnt 0 frac 0.0)
6027 (loop for x in column do
6028 (if (equal x "")
6030 (setq frac ( / (+ (* frac cnt)
6031 (if (string-match org-table-number-regexp x) 1 0))
6032 (setq cnt (1+ cnt))))))
6033 (push (>= frac org-table-number-fraction) typenums))
6034 (setq lengths (nreverse lengths) typenums (nreverse typenums))
6036 ;; Store the alignment of this table, for later editing of single fields
6037 (setq org-table-last-alignment typenums
6038 org-table-last-column-widths lengths)
6040 ;; With invisible characters, `format' does not get the field width right
6041 ;; So we need to make these fields wide by hand.
6042 (when links
6043 (loop for i from 0 upto (1- maxfields) do
6044 (setq len (nth i lengths))
6045 (loop for j from 0 upto (1- (length fields)) do
6046 (setq c (nthcdr i (car (nthcdr j fields))))
6047 (if (and (stringp (car c))
6048 (string-match org-bracket-link-regexp (car c))
6049 (< (org-string-width (car c)) len))
6050 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
6052 ;; Compute the formats needed for output of the table
6053 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6054 (while (setq l (pop lengths))
6055 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6056 (setq rfmt (concat rfmt (format rfmt1 ty l))
6057 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6058 (setq rfmt (concat rfmt "\n")
6059 hfmt (concat (substring hfmt 0 -1) "|\n"))
6061 (setq new (mapconcat
6062 (lambda (l)
6063 (if l (apply 'format rfmt
6064 (append (pop fields) emptystrings))
6065 hfmt))
6066 lines ""))
6067 ;; Replace the old one
6068 (delete-region beg end)
6069 (move-marker end nil)
6070 (move-marker org-table-aligned-begin-marker (point))
6071 (insert new)
6072 (move-marker org-table-aligned-end-marker (point))
6073 (when (and orgtbl-mode (not (org-mode-p)))
6074 (goto-char org-table-aligned-begin-marker)
6075 (while (org-hide-wide-columns org-table-aligned-end-marker)))
6076 ;; Try to move to the old location
6077 (goto-line winstartline)
6078 (setq winstart (point-at-bol))
6079 (goto-line linepos)
6080 (set-window-start (selected-window) winstart 'noforce)
6081 (org-table-goto-column colpos)
6082 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
6083 (setq org-table-may-need-update nil)
6086 (defun org-string-width (s)
6087 "Compute width of string, ignoring invisible characters.
6088 This ignores character with invisibility property `org-link', and also
6089 characters with property `org-cwidth', because these will become invisible
6090 upon the next fontification round."
6091 (let (b l)
6092 (when (or (eq t buffer-invisibility-spec)
6093 (assq 'org-link buffer-invisibility-spec))
6094 (while (setq b (text-property-any 0 (length s)
6095 'invisible 'org-link s))
6096 (setq s (concat (substring s 0 b)
6097 (substring s (or (next-single-property-change
6098 b 'invisible s) (length s)))))))
6099 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
6100 (setq s (concat (substring s 0 b)
6101 (substring s (or (next-single-property-change
6102 b 'org-cwidth s) (length s))))))
6103 (setq l (string-width s) b -1)
6104 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
6105 (setq l (- l (get-text-property b 'org-dwidth-n s))))
6108 (defun org-table-begin (&optional table-type)
6109 "Find the beginning of the table and return its position.
6110 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6111 (save-excursion
6112 (if (not (re-search-backward
6113 (if table-type org-table-any-border-regexp
6114 org-table-border-regexp)
6115 nil t))
6116 (progn (goto-char (point-min)) (point))
6117 (goto-char (match-beginning 0))
6118 (beginning-of-line 2)
6119 (point))))
6121 (defun org-table-end (&optional table-type)
6122 "Find the end of the table and return its position.
6123 With argument TABLE-TYPE, go to the end of a table.el-type table."
6124 (save-excursion
6125 (if (not (re-search-forward
6126 (if table-type org-table-any-border-regexp
6127 org-table-border-regexp)
6128 nil t))
6129 (goto-char (point-max))
6130 (goto-char (match-beginning 0)))
6131 (point-marker)))
6133 (defun org-table-justify-field-maybe (&optional new)
6134 "Justify the current field, text to left, number to right.
6135 Optional argument NEW may specify text to replace the current field content."
6136 (cond
6137 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6138 ((org-at-table-hline-p))
6139 ((and (not new)
6140 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6141 (current-buffer)))
6142 (< (point) org-table-aligned-begin-marker)
6143 (>= (point) org-table-aligned-end-marker)))
6144 ;; This is not the same table, force a full re-align
6145 (setq org-table-may-need-update t))
6146 (t ;; realign the current field, based on previous full realign
6147 (let* ((pos (point)) s
6148 (col (org-table-current-column))
6149 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
6150 l f n o e)
6151 (when (> col 0)
6152 (skip-chars-backward "^|\n")
6153 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6154 (progn
6155 (setq s (match-string 1)
6156 o (match-string 0)
6157 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6158 e (not (= (match-beginning 2) (match-end 2))))
6159 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6160 l (if e "|" (setq org-table-may-need-update t) ""))
6161 n (format f s))
6162 (if new
6163 (if (<= (length new) l) ;; FIXME: length -> str-width?
6164 (setq n (format f new))
6165 (setq n (concat new "|") org-table-may-need-update t)))
6166 (or (equal n o)
6167 (let (org-table-may-need-update)
6168 (replace-match n))))
6169 (setq org-table-may-need-update t))
6170 (goto-char pos))))))
6172 (defun org-table-next-field ()
6173 "Go to the next field in the current table, creating new lines as needed.
6174 Before doing so, re-align the table if necessary."
6175 (interactive)
6176 (org-table-maybe-eval-formula)
6177 (org-table-maybe-recalculate-line)
6178 (if (and org-table-automatic-realign
6179 org-table-may-need-update)
6180 (org-table-align))
6181 (let ((end (org-table-end)))
6182 (if (org-at-table-hline-p)
6183 (end-of-line 1))
6184 (condition-case nil
6185 (progn
6186 (re-search-forward "|" end)
6187 (if (looking-at "[ \t]*$")
6188 (re-search-forward "|" end))
6189 (if (and (looking-at "-")
6190 org-table-tab-jumps-over-hlines
6191 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
6192 (goto-char (match-beginning 1)))
6193 (if (looking-at "-")
6194 (progn
6195 (beginning-of-line 0)
6196 (org-table-insert-row 'below))
6197 (if (looking-at " ") (forward-char 1))))
6198 (error
6199 (org-table-insert-row 'below)))))
6201 (defun org-table-previous-field ()
6202 "Go to the previous field in the table.
6203 Before doing so, re-align the table if necessary."
6204 (interactive)
6205 (org-table-justify-field-maybe)
6206 (org-table-maybe-recalculate-line)
6207 (if (and org-table-automatic-realign
6208 org-table-may-need-update)
6209 (org-table-align))
6210 (if (org-at-table-hline-p)
6211 (end-of-line 1))
6212 (re-search-backward "|" (org-table-begin))
6213 (re-search-backward "|" (org-table-begin))
6214 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6215 (re-search-backward "|" (org-table-begin)))
6216 (if (looking-at "| ?")
6217 (goto-char (match-end 0))))
6219 (defun org-table-next-row ()
6220 "Go to the next row (same column) in the current table.
6221 Before doing so, re-align the table if necessary."
6222 (interactive)
6223 (org-table-maybe-eval-formula)
6224 (org-table-maybe-recalculate-line)
6225 (if (or (looking-at "[ \t]*$")
6226 (save-excursion (skip-chars-backward " \t") (bolp)))
6227 (newline)
6228 (if (and org-table-automatic-realign
6229 org-table-may-need-update)
6230 (org-table-align))
6231 (let ((col (org-table-current-column)))
6232 (beginning-of-line 2)
6233 (if (or (not (org-at-table-p))
6234 (org-at-table-hline-p))
6235 (progn
6236 (beginning-of-line 0)
6237 (org-table-insert-row 'below)))
6238 (org-table-goto-column col)
6239 (skip-chars-backward "^|\n\r")
6240 (if (looking-at " ") (forward-char 1)))))
6242 (defun org-table-copy-down (n)
6243 "Copy a field down in the current column.
6244 If the field at the cursor is empty, copy into it the content of the nearest
6245 non-empty field above. With argument N, use the Nth non-empty field.
6246 If the current field is not empty, it is copied down to the next row, and
6247 the cursor is moved with it. Therefore, repeating this command causes the
6248 column to be filled row-by-row.
6249 If the variable `org-table-copy-increment' is non-nil and the field is an
6250 integer, it will be incremented while copying."
6251 (interactive "p")
6252 (let* ((colpos (org-table-current-column))
6253 (field (org-table-get-field))
6254 (non-empty (string-match "[^ \t]" field))
6255 (beg (org-table-begin))
6256 txt)
6257 (org-table-check-inside-data-field)
6258 (if non-empty
6259 (progn
6260 (setq txt (org-trim field))
6261 (org-table-next-row)
6262 (org-table-blank-field))
6263 (save-excursion
6264 (setq txt
6265 (catch 'exit
6266 (while (progn (beginning-of-line 1)
6267 (re-search-backward org-table-dataline-regexp
6268 beg t))
6269 (org-table-goto-column colpos t)
6270 (if (and (looking-at
6271 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6272 (= (setq n (1- n)) 0))
6273 (throw 'exit (match-string 1))))))))
6274 (if txt
6275 (progn
6276 (if (and org-table-copy-increment
6277 (string-match "^[0-9]+$" txt))
6278 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6279 (insert txt)
6280 (org-table-maybe-recalculate-line)
6281 (org-table-align))
6282 (error "No non-empty field found"))))
6284 (defun org-table-check-inside-data-field ()
6285 "Is point inside a table data field?
6286 I.e. not on a hline or before the first or after the last column?
6287 This actually throws an error, so it aborts the current command."
6288 (if (or (not (org-at-table-p))
6289 (= (org-table-current-column) 0)
6290 (org-at-table-hline-p)
6291 (looking-at "[ \t]*$"))
6292 (error "Not in table data field")))
6294 (defvar org-table-clip nil
6295 "Clipboard for table regions.")
6297 (defun org-table-blank-field ()
6298 "Blank the current table field or active region."
6299 (interactive)
6300 (org-table-check-inside-data-field)
6301 (if (and (interactive-p) (org-region-active-p))
6302 (let (org-table-clip)
6303 (org-table-cut-region (region-beginning) (region-end)))
6304 (skip-chars-backward "^|")
6305 (backward-char 1)
6306 (if (looking-at "|[^|\n]+")
6307 (let* ((pos (match-beginning 0))
6308 (match (match-string 0))
6309 (len (org-string-width match)))
6310 (replace-match (concat "|" (make-string (1- len) ?\ )))
6311 (goto-char (+ 2 pos))
6312 (substring match 1)))))
6314 (defun org-table-get-field (&optional n replace)
6315 "Return the value of the field in column N of current row.
6316 N defaults to current field.
6317 If REPLACE is a string, replace field with this value. The return value
6318 is always the old value."
6319 (and n (org-table-goto-column n))
6320 (skip-chars-backward "^|\n")
6321 (backward-char 1)
6322 (if (looking-at "|[^|\r\n]*")
6323 (let* ((pos (match-beginning 0))
6324 (val (buffer-substring (1+ pos) (match-end 0))))
6325 (if replace
6326 (replace-match (concat "|" replace)))
6327 (goto-char (min (point-at-eol) (+ 2 pos)))
6328 val)
6329 (forward-char 1) ""))
6332 (defun org-table-field-info (arg)
6333 "Show info about the current field, and highlight any reference at point."
6334 (interactive "P")
6335 (org-table-get-specials)
6336 (save-excursion
6337 (let* ((pos (point))
6338 (col (org-table-current-column))
6339 (cname (car (rassoc (int-to-string col) org-table-column-names)))
6340 (name (car (rassoc (list (org-current-line) col)
6341 org-table-named-field-locations)))
6342 (eql (org-table-get-stored-formulas))
6343 (dline (org-table-current-dline))
6344 (ref (format "@%d$%d" dline col))
6345 (fequation (or (assoc name eql) (assoc ref eql)))
6346 (cequation (assoc (int-to-string col) eql)))
6347 (goto-char pos)
6348 (condition-case nil
6349 (org-show-reference 'local)
6350 (error nil))
6351 (message "line @%d, col $%s%s, ref @%d$%d%s%s"
6352 dline col
6353 (if cname (concat " or $" cname) "")
6354 dline col
6355 (if name (concat " or $" name) "")
6356 ;; FIXME: formula info not correct if special table line
6357 (if (or fequation cequation)
6358 (concat ", " (if fequation "field" "column")
6359 " formula applies" "")
6360 "")))))
6362 (defun org-table-current-column ()
6363 "Find out which column we are in.
6364 When called interactively, column is also displayed in echo area."
6365 (interactive)
6366 (if (interactive-p) (org-table-check-inside-data-field))
6367 (save-excursion
6368 (let ((cnt 0) (pos (point)))
6369 (beginning-of-line 1)
6370 (while (search-forward "|" pos t)
6371 (setq cnt (1+ cnt)))
6372 (if (interactive-p) (message "This is table column %d" cnt))
6373 cnt)))
6375 (defun org-table-current-dline ()
6376 "Find out what table data line we are in.
6377 Only datalins count for this."
6378 (interactive)
6379 (if (interactive-p) (org-table-check-inside-data-field))
6380 (save-excursion
6381 (let ((cnt 0) (pos (point)))
6382 (goto-char (org-table-begin))
6383 (while (<= (point) pos)
6384 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
6385 (beginning-of-line 2))
6386 (if (interactive-p) (message "This is table line %d" cnt))
6387 cnt)))
6389 (defun org-table-goto-column (n &optional on-delim force)
6390 "Move the cursor to the Nth column in the current table line.
6391 With optional argument ON-DELIM, stop with point before the left delimiter
6392 of the field.
6393 If there are less than N fields, just go to after the last delimiter.
6394 However, when FORCE is non-nil, create new columns if necessary."
6395 (interactive "p")
6396 (let ((pos (point-at-eol)))
6397 (beginning-of-line 1)
6398 (when (> n 0)
6399 (while (and (> (setq n (1- n)) -1)
6400 (or (search-forward "|" pos t)
6401 (and force
6402 (progn (end-of-line 1)
6403 (skip-chars-backward "^|")
6404 (insert " | "))))))
6405 ; (backward-char 2) t)))))
6406 (when (and force (not (looking-at ".*|")))
6407 (save-excursion (end-of-line 1) (insert " | ")))
6408 (if on-delim
6409 (backward-char 1)
6410 (if (looking-at " ") (forward-char 1))))))
6412 (defun org-at-table-p (&optional table-type)
6413 "Return t if the cursor is inside an org-type table.
6414 If TABLE-TYPE is non-nil, also check for table.el-type tables."
6415 (if org-enable-table-editor
6416 (save-excursion
6417 (beginning-of-line 1)
6418 (looking-at (if table-type org-table-any-line-regexp
6419 org-table-line-regexp)))
6420 nil))
6422 (defun org-at-table.el-p ()
6423 "Return t if and only if we are at a table.el table."
6424 (and (org-at-table-p 'any)
6425 (save-excursion
6426 (goto-char (org-table-begin 'any))
6427 (looking-at org-table1-hline-regexp))))
6429 (defun org-table-recognize-table.el ()
6430 "If there is a table.el table nearby, recognize it and move into it."
6431 (if org-table-tab-recognizes-table.el
6432 (if (org-at-table.el-p)
6433 (progn
6434 (beginning-of-line 1)
6435 (if (looking-at org-table-dataline-regexp)
6437 (if (looking-at org-table1-hline-regexp)
6438 (progn
6439 (beginning-of-line 2)
6440 (if (looking-at org-table-any-border-regexp)
6441 (beginning-of-line -1)))))
6442 (if (re-search-forward "|" (org-table-end t) t)
6443 (progn
6444 (require 'table)
6445 (if (table--at-cell-p (point))
6447 (message "recognizing table.el table...")
6448 (table-recognize-table)
6449 (message "recognizing table.el table...done")))
6450 (error "This should not happen..."))
6452 nil)
6453 nil))
6455 (defun org-at-table-hline-p ()
6456 "Return t if the cursor is inside a hline in a table."
6457 (if org-enable-table-editor
6458 (save-excursion
6459 (beginning-of-line 1)
6460 (looking-at org-table-hline-regexp))
6461 nil))
6463 (defun org-table-insert-column ()
6464 "Insert a new column into the table."
6465 (interactive)
6466 (if (not (org-at-table-p))
6467 (error "Not at a table"))
6468 (org-table-find-dataline)
6469 (let* ((col (max 1 (org-table-current-column)))
6470 (beg (org-table-begin))
6471 (end (org-table-end))
6472 ;; Current cursor position
6473 (linepos (org-current-line))
6474 (colpos col))
6475 (goto-char beg)
6476 (while (< (point) end)
6477 (if (org-at-table-hline-p)
6479 (org-table-goto-column col t)
6480 (insert "| "))
6481 (beginning-of-line 2))
6482 (move-marker end nil)
6483 (goto-line linepos)
6484 (org-table-goto-column colpos)
6485 (org-table-align)
6486 (org-table-fix-formulas "$" nil (1- col) 1)))
6488 (defun org-table-find-dataline ()
6489 "Find a dataline in the current table, which is needed for column commands."
6490 (if (and (org-at-table-p)
6491 (not (org-at-table-hline-p)))
6493 (let ((col (current-column))
6494 (end (org-table-end)))
6495 (move-to-column col)
6496 (while (and (< (point) end)
6497 (or (not (= (current-column) col))
6498 (org-at-table-hline-p)))
6499 (beginning-of-line 2)
6500 (move-to-column col))
6501 (if (and (org-at-table-p)
6502 (not (org-at-table-hline-p)))
6504 (error
6505 "Please position cursor in a data line for column operations")))))
6507 (defun org-table-delete-column ()
6508 "Delete a column from the table."
6509 (interactive)
6510 (if (not (org-at-table-p))
6511 (error "Not at a table"))
6512 (org-table-find-dataline)
6513 (org-table-check-inside-data-field)
6514 (let* ((col (org-table-current-column))
6515 (beg (org-table-begin))
6516 (end (org-table-end))
6517 ;; Current cursor position
6518 (linepos (org-current-line))
6519 (colpos col))
6520 (goto-char beg)
6521 (while (< (point) end)
6522 (if (org-at-table-hline-p)
6524 (org-table-goto-column col t)
6525 (and (looking-at "|[^|\n]+|")
6526 (replace-match "|")))
6527 (beginning-of-line 2))
6528 (move-marker end nil)
6529 (goto-line linepos)
6530 (org-table-goto-column colpos)
6531 (org-table-align)
6532 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
6533 col -1 col)))
6535 (defun org-table-move-column-right ()
6536 "Move column to the right."
6537 (interactive)
6538 (org-table-move-column nil))
6539 (defun org-table-move-column-left ()
6540 "Move column to the left."
6541 (interactive)
6542 (org-table-move-column 'left))
6544 (defun org-table-move-column (&optional left)
6545 "Move the current column to the right. With arg LEFT, move to the left."
6546 (interactive "P")
6547 (if (not (org-at-table-p))
6548 (error "Not at a table"))
6549 (org-table-find-dataline)
6550 (org-table-check-inside-data-field)
6551 (let* ((col (org-table-current-column))
6552 (col1 (if left (1- col) col))
6553 (beg (org-table-begin))
6554 (end (org-table-end))
6555 ;; Current cursor position
6556 (linepos (org-current-line))
6557 (colpos (if left (1- col) (1+ col))))
6558 (if (and left (= col 1))
6559 (error "Cannot move column further left"))
6560 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6561 (error "Cannot move column further right"))
6562 (goto-char beg)
6563 (while (< (point) end)
6564 (if (org-at-table-hline-p)
6566 (org-table-goto-column col1 t)
6567 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6568 (replace-match "|\\2|\\1|")))
6569 (beginning-of-line 2))
6570 (move-marker end nil)
6571 (goto-line linepos)
6572 (org-table-goto-column colpos)
6573 (org-table-align)
6574 (org-table-fix-formulas
6575 "$" (list (cons (number-to-string col) (number-to-string colpos))
6576 (cons (number-to-string colpos) (number-to-string col))))))
6578 (defun org-table-move-row-down ()
6579 "Move table row down."
6580 (interactive)
6581 (org-table-move-row nil))
6582 (defun org-table-move-row-up ()
6583 "Move table row up."
6584 (interactive)
6585 (org-table-move-row 'up))
6587 (defun org-table-move-row (&optional up)
6588 "Move the current table line down. With arg UP, move it up."
6589 (interactive "P")
6590 (let* ((col (current-column))
6591 (pos (point))
6592 (hline1p (save-excursion (beginning-of-line 1)
6593 (looking-at org-table-hline-regexp)))
6594 (dline1 (org-table-current-dline))
6595 (dline2 (+ dline1 (if up -1 1)))
6596 (tonew (if up 0 2))
6597 txt hline2p)
6598 (beginning-of-line tonew)
6599 (unless (org-at-table-p)
6600 (goto-char pos)
6601 (error "Cannot move row further"))
6602 (setq hline2p (looking-at org-table-hline-regexp))
6603 (goto-char pos)
6604 (beginning-of-line 1)
6605 (setq pos (point))
6606 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6607 (delete-region (point) (1+ (point-at-eol)))
6608 (beginning-of-line tonew)
6609 (insert txt)
6610 (beginning-of-line 0)
6611 (move-to-column col)
6612 (unless (or hline1p hline2p)
6613 (org-table-fix-formulas
6614 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
6615 (cons (number-to-string dline2) (number-to-string dline1)))))))
6617 (defun org-table-insert-row (&optional arg)
6618 "Insert a new row above the current line into the table.
6619 With prefix ARG, insert below the current line."
6620 (interactive "P")
6621 (if (not (org-at-table-p))
6622 (error "Not at a table"))
6623 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
6624 (new (org-table-clean-line line)))
6625 ;; Fix the first field if necessary
6626 (if (string-match "^[ \t]*| *[#$] *|" line)
6627 (setq new (replace-match (match-string 0 line) t t new)))
6628 (beginning-of-line (if arg 2 1))
6629 (let (org-table-may-need-update) (insert-before-markers new "\n"))
6630 (beginning-of-line 0)
6631 (re-search-forward "| ?" (point-at-eol) t)
6632 (and (or org-table-may-need-update org-table-overlay-coordinates)
6633 (org-table-align))
6634 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
6636 (defun org-table-insert-hline (&optional arg)
6637 "Insert a horizontal-line below the current line into the table.
6638 With prefix ARG, insert above the current line."
6639 (interactive "P")
6640 (if (not (org-at-table-p))
6641 (error "Not at a table"))
6642 (let ((line (org-table-clean-line
6643 (buffer-substring (point-at-bol) (point-at-eol))))
6644 (col (current-column)))
6645 (while (string-match "|\\( +\\)|" line)
6646 (setq line (replace-match
6647 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
6648 ?-) "|") t t line)))
6649 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
6650 (beginning-of-line (if arg 1 2))
6651 (insert line "\n")
6652 (beginning-of-line (if arg 1 -1))
6653 (move-to-column col)
6654 (and org-table-overlay-coordinates (org-table-align))))
6656 (defun org-table-clean-line (s)
6657 "Convert a table line S into a string with only \"|\" and space.
6658 In particular, this does handle wide and invisible characters."
6659 (if (string-match "^[ \t]*|-" s)
6660 ;; It's a hline, just map the characters
6661 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
6662 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
6663 (setq s (replace-match
6664 (concat "|" (make-string (org-string-width (match-string 1 s))
6665 ?\ ) "|")
6666 t t s)))
6669 (defun org-table-kill-row ()
6670 "Delete the current row or horizontal line from the table."
6671 (interactive)
6672 (if (not (org-at-table-p))
6673 (error "Not at a table"))
6674 (let ((col (current-column))
6675 (dline (org-table-current-dline)))
6676 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6677 (if (not (org-at-table-p)) (beginning-of-line 0))
6678 (move-to-column col)
6679 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
6680 dline -1 dline)))
6683 (defun org-table-sort-lines (with-case &optional sorting-type)
6684 "Sort table lines according to the column at point.
6686 The position of point indicates the column to be used for
6687 sorting, and the range of lines is the range between the nearest
6688 horizontal separator lines, or the entire table of no such lines
6689 exist. If point is before the first column, you will be prompted
6690 for the sorting column. If there is an active region, the mark
6691 specifies the first line and the sorting column, while point
6692 should be in the last line to be included into the sorting.
6694 The command then prompts for the sorting type which can be
6695 alphabetically, numerically, or by time (as given in a time stamp
6696 in the field). Sorting in reverse order is also possible.
6698 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
6700 If SORTING-TYPE is specified when this function is called from a Lisp
6701 program, no prompting will take place. SORTING-TYPE must be a character,
6702 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
6703 should be done in reverse order."
6704 (interactive "P")
6705 (let* ((thisline (org-current-line))
6706 (thiscol (org-table-current-column))
6707 beg end bcol ecol tend tbeg column lns pos)
6708 (when (equal thiscol 0)
6709 (if (interactive-p)
6710 (setq thiscol
6711 (string-to-number
6712 (read-string "Use column N for sorting: ")))
6713 (setq thiscol 1))
6714 (org-table-goto-column thiscol))
6715 (org-table-check-inside-data-field)
6716 (if (org-region-active-p)
6717 (progn
6718 (setq beg (region-beginning) end (region-end))
6719 (goto-char beg)
6720 (setq column (org-table-current-column)
6721 beg (point-at-bol))
6722 (goto-char end)
6723 (setq end (point-at-bol 2)))
6724 (setq column (org-table-current-column)
6725 pos (point)
6726 tbeg (org-table-begin)
6727 tend (org-table-end))
6728 (if (re-search-backward org-table-hline-regexp tbeg t)
6729 (setq beg (point-at-bol 2))
6730 (goto-char tbeg)
6731 (setq beg (point-at-bol 1)))
6732 (goto-char pos)
6733 (if (re-search-forward org-table-hline-regexp tend t)
6734 (setq beg (point-at-bol 0))
6735 (goto-char tend)
6736 (setq end (point-at-bol))))
6737 (setq beg (move-marker (make-marker) beg)
6738 end (move-marker (make-marker) end))
6739 (untabify beg end)
6740 (goto-char beg)
6741 (org-table-goto-column column)
6742 (skip-chars-backward "^|")
6743 (setq bcol (current-column))
6744 (org-table-goto-column (1+ column))
6745 (skip-chars-backward "^|")
6746 (setq ecol (1- (current-column)))
6747 (org-table-goto-column column)
6748 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
6749 (org-split-string (buffer-substring beg end) "\n")))
6750 (setq lns (org-do-sort lns "Table" with-case sorting-type))
6751 (delete-region beg end)
6752 (move-marker beg nil)
6753 (move-marker end nil)
6754 (insert (mapconcat 'cdr lns "\n") "\n")
6755 (goto-line thisline)
6756 (org-table-goto-column thiscol)
6757 (message "%d lines sorted, based on column %d" (length lns) column)))
6759 (defun org-table-cut-region (beg end)
6760 "Copy region in table to the clipboard and blank all relevant fields."
6761 (interactive "r")
6762 (org-table-copy-region beg end 'cut))
6764 (defun org-table-copy-region (beg end &optional cut)
6765 "Copy rectangular region in table to clipboard.
6766 A special clipboard is used which can only be accessed
6767 with `org-table-paste-rectangle'."
6768 (interactive "rP")
6769 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6770 region cols
6771 (rpl (if cut " " nil)))
6772 (goto-char beg)
6773 (org-table-check-inside-data-field)
6774 (setq l01 (org-current-line)
6775 c01 (org-table-current-column))
6776 (goto-char end)
6777 (org-table-check-inside-data-field)
6778 (setq l02 (org-current-line)
6779 c02 (org-table-current-column))
6780 (setq l1 (min l01 l02) l2 (max l01 l02)
6781 c1 (min c01 c02) c2 (max c01 c02))
6782 (catch 'exit
6783 (while t
6784 (catch 'nextline
6785 (if (> l1 l2) (throw 'exit t))
6786 (goto-line l1)
6787 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6788 (setq cols nil ic1 c1 ic2 c2)
6789 (while (< ic1 (1+ ic2))
6790 (push (org-table-get-field ic1 rpl) cols)
6791 (setq ic1 (1+ ic1)))
6792 (push (nreverse cols) region)
6793 (setq l1 (1+ l1)))))
6794 (setq org-table-clip (nreverse region))
6795 (if cut (org-table-align))
6796 org-table-clip))
6798 (defun org-table-paste-rectangle ()
6799 "Paste a rectangular region into a table.
6800 The upper right corner ends up in the current field. All involved fields
6801 will be overwritten. If the rectangle does not fit into the present table,
6802 the table is enlarged as needed. The process ignores horizontal separator
6803 lines."
6804 (interactive)
6805 (unless (and org-table-clip (listp org-table-clip))
6806 (error "First cut/copy a region to paste!"))
6807 (org-table-check-inside-data-field)
6808 (let* ((clip org-table-clip)
6809 (line (org-current-line))
6810 (col (org-table-current-column))
6811 (org-enable-table-editor t)
6812 (org-table-automatic-realign nil)
6813 c cols field)
6814 (while (setq cols (pop clip))
6815 (while (org-at-table-hline-p) (beginning-of-line 2))
6816 (if (not (org-at-table-p))
6817 (progn (end-of-line 0) (org-table-next-field)))
6818 (setq c col)
6819 (while (setq field (pop cols))
6820 (org-table-goto-column c nil 'force)
6821 (org-table-get-field nil field)
6822 (setq c (1+ c)))
6823 (beginning-of-line 2))
6824 (goto-line line)
6825 (org-table-goto-column col)
6826 (org-table-align)))
6828 (defun org-table-convert ()
6829 "Convert from `org-mode' table to table.el and back.
6830 Obviously, this only works within limits. When an Org-mode table is
6831 converted to table.el, all horizontal separator lines get lost, because
6832 table.el uses these as cell boundaries and has no notion of horizontal lines.
6833 A table.el table can be converted to an Org-mode table only if it does not
6834 do row or column spanning. Multiline cells will become multiple cells.
6835 Beware, Org-mode does not test if the table can be successfully converted - it
6836 blindly applies a recipe that works for simple tables."
6837 (interactive)
6838 (require 'table)
6839 (if (org-at-table.el-p)
6840 ;; convert to Org-mode table
6841 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6842 (end (move-marker (make-marker) (org-table-end t))))
6843 (table-unrecognize-region beg end)
6844 (goto-char beg)
6845 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6846 (replace-match ""))
6847 (goto-char beg))
6848 (if (org-at-table-p)
6849 ;; convert to table.el table
6850 (let ((beg (move-marker (make-marker) (org-table-begin)))
6851 (end (move-marker (make-marker) (org-table-end))))
6852 ;; first, get rid of all horizontal lines
6853 (goto-char beg)
6854 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6855 (replace-match ""))
6856 ;; insert a hline before first
6857 (goto-char beg)
6858 (org-table-insert-hline 'above)
6859 (beginning-of-line -1)
6860 ;; insert a hline after each line
6861 (while (progn (beginning-of-line 3) (< (point) end))
6862 (org-table-insert-hline))
6863 (goto-char beg)
6864 (setq end (move-marker end (org-table-end)))
6865 ;; replace "+" at beginning and ending of hlines
6866 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6867 (replace-match "\\1+-"))
6868 (goto-char beg)
6869 (while (re-search-forward "-|[ \t]*$" end t)
6870 (replace-match "-+"))
6871 (goto-char beg)))))
6873 (defun org-table-wrap-region (arg)
6874 "Wrap several fields in a column like a paragraph.
6875 This is useful if you'd like to spread the contents of a field over several
6876 lines, in order to keep the table compact.
6878 If there is an active region, and both point and mark are in the same column,
6879 the text in the column is wrapped to minimum width for the given number of
6880 lines. Generally, this makes the table more compact. A prefix ARG may be
6881 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6882 formats the selected text to two lines. If the region was longer than two
6883 lines, the remaining lines remain empty. A negative prefix argument reduces
6884 the current number of lines by that amount. The wrapped text is pasted back
6885 into the table. If you formatted it to more lines than it was before, fields
6886 further down in the table get overwritten - so you might need to make space in
6887 the table first.
6889 If there is no region, the current field is split at the cursor position and
6890 the text fragment to the right of the cursor is prepended to the field one
6891 line down.
6893 If there is no region, but you specify a prefix ARG, the current field gets
6894 blank, and the content is appended to the field above."
6895 (interactive "P")
6896 (org-table-check-inside-data-field)
6897 (if (org-region-active-p)
6898 ;; There is a region: fill as a paragraph
6899 (let* ((beg (region-beginning))
6900 (cline (save-excursion (goto-char beg) (org-current-line)))
6901 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
6902 nlines)
6903 (org-table-cut-region (region-beginning) (region-end))
6904 (if (> (length (car org-table-clip)) 1)
6905 (error "Region must be limited to single column"))
6906 (setq nlines (if arg
6907 (if (< arg 1)
6908 (+ (length org-table-clip) arg)
6909 arg)
6910 (length org-table-clip)))
6911 (setq org-table-clip
6912 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6913 nil nlines)))
6914 (goto-line cline)
6915 (org-table-goto-column ccol)
6916 (org-table-paste-rectangle))
6917 ;; No region, split the current field at point
6918 (if arg
6919 ;; combine with field above
6920 (let ((s (org-table-blank-field))
6921 (col (org-table-current-column)))
6922 (beginning-of-line 0)
6923 (while (org-at-table-hline-p) (beginning-of-line 0))
6924 (org-table-goto-column col)
6925 (skip-chars-forward "^|")
6926 (skip-chars-backward " ")
6927 (insert " " (org-trim s))
6928 (org-table-align))
6929 ;; split field
6930 (when (looking-at "\\([^|]+\\)+|")
6931 (let ((s (match-string 1)))
6932 (replace-match " |")
6933 (goto-char (match-beginning 0))
6934 (org-table-next-row)
6935 (insert (org-trim s) " ")
6936 (org-table-align))))))
6938 (defvar org-field-marker nil)
6940 (defun org-table-edit-field (arg)
6941 "Edit table field in a different window.
6942 This is mainly useful for fields that contain hidden parts.
6943 When called with a \\[universal-argument] prefix, just make the full field visible so that
6944 it can be edited in place."
6945 (interactive "P")
6946 (if arg
6947 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
6948 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
6949 (remove-text-properties b e '(org-cwidth t invisible t
6950 display t intangible t))
6951 (if (and (boundp 'font-lock-mode) font-lock-mode)
6952 (font-lock-fontify-block)))
6953 (let ((pos (move-marker (make-marker) (point)))
6954 (field (org-table-get-field))
6955 (cw (current-window-configuration))
6957 (switch-to-buffer-other-window "*Org tmp*")
6958 (erase-buffer)
6959 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
6960 (org-mode)
6961 (goto-char (setq p (point-max)))
6962 (insert (org-trim field))
6963 (remove-text-properties p (point-max)
6964 '(invisible t org-cwidth t display t
6965 intangible t))
6966 (goto-char p)
6967 (org-set-local 'org-finish-function
6968 'org-table-finish-edit-field)
6969 (org-set-local 'org-window-configuration cw)
6970 (org-set-local 'org-field-marker pos)
6971 (message "Edit and finish with C-c C-c"))))
6973 (defun org-table-finish-edit-field ()
6974 "Finish editing a table data field.
6975 Remove all newline characters, insert the result into the table, realign
6976 the table and kill the editing buffer."
6977 (let ((pos org-field-marker)
6978 (cw org-window-configuration)
6979 (cb (current-buffer))
6980 text)
6981 (goto-char (point-min))
6982 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
6983 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
6984 (replace-match " "))
6985 (setq text (org-trim (buffer-string)))
6986 (set-window-configuration cw)
6987 (kill-buffer cb)
6988 (select-window (get-buffer-window (marker-buffer pos)))
6989 (goto-char pos)
6990 (move-marker pos nil)
6991 (org-table-check-inside-data-field)
6992 (org-table-get-field nil text)
6993 (org-table-align)
6994 (message "New field value inserted")))
6996 (defun org-trim (s)
6997 "Remove whitespace at beginning and end of string."
6998 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6999 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
7002 (defun org-wrap (string &optional width lines)
7003 "Wrap string to either a number of lines, or a width in characters.
7004 If WIDTH is non-nil, the string is wrapped to that width, however many lines
7005 that costs. If there is a word longer than WIDTH, the text is actually
7006 wrapped to the length of that word.
7007 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
7008 many lines, whatever width that takes.
7009 The return value is a list of lines, without newlines at the end."
7010 (let* ((words (org-split-string string "[ \t\n]+"))
7011 (maxword (apply 'max (mapcar 'org-string-width words)))
7012 w ll)
7013 (cond (width
7014 (org-do-wrap words (max maxword width)))
7015 (lines
7016 (setq w maxword)
7017 (setq ll (org-do-wrap words maxword))
7018 (if (<= (length ll) lines)
7020 (setq ll words)
7021 (while (> (length ll) lines)
7022 (setq w (1+ w))
7023 (setq ll (org-do-wrap words w)))
7024 ll))
7025 (t (error "Cannot wrap this")))))
7028 (defun org-do-wrap (words width)
7029 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
7030 (let (lines line)
7031 (while words
7032 (setq line (pop words))
7033 (while (and words (< (+ (length line) (length (car words))) width))
7034 (setq line (concat line " " (pop words))))
7035 (setq lines (push line lines)))
7036 (nreverse lines)))
7038 (defun org-split-string (string &optional separators)
7039 "Splits STRING into substrings at SEPARATORS.
7040 No empty strings are returned if there are matches at the beginning
7041 and end of string."
7042 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
7043 (start 0)
7044 notfirst
7045 (list nil))
7046 (while (and (string-match rexp string
7047 (if (and notfirst
7048 (= start (match-beginning 0))
7049 (< start (length string)))
7050 (1+ start) start))
7051 (< (match-beginning 0) (length string)))
7052 (setq notfirst t)
7053 (or (eq (match-beginning 0) 0)
7054 (and (eq (match-beginning 0) (match-end 0))
7055 (eq (match-beginning 0) start))
7056 (setq list
7057 (cons (substring string start (match-beginning 0))
7058 list)))
7059 (setq start (match-end 0)))
7060 (or (eq start (length string))
7061 (setq list
7062 (cons (substring string start)
7063 list)))
7064 (nreverse list)))
7066 (defun org-table-map-tables (function)
7067 "Apply FUNCTION to the start of all tables in the buffer."
7068 (save-excursion
7069 (save-restriction
7070 (widen)
7071 (goto-char (point-min))
7072 (while (re-search-forward org-table-any-line-regexp nil t)
7073 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7074 (beginning-of-line 1)
7075 (if (looking-at org-table-line-regexp)
7076 (save-excursion (funcall function)))
7077 (re-search-forward org-table-any-border-regexp nil 1))))
7078 (message "Mapping tables: done"))
7080 (defvar org-timecnt) ; dynamically scoped parameter
7082 (defun org-table-sum (&optional beg end nlast)
7083 "Sum numbers in region of current table column.
7084 The result will be displayed in the echo area, and will be available
7085 as kill to be inserted with \\[yank].
7087 If there is an active region, it is interpreted as a rectangle and all
7088 numbers in that rectangle will be summed. If there is no active
7089 region and point is located in a table column, sum all numbers in that
7090 column.
7092 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7093 numbers are assumed to be times as well (in decimal hours) and the
7094 numbers are added as such.
7096 If NLAST is a number, only the NLAST fields will actually be summed."
7097 (interactive)
7098 (save-excursion
7099 (let (col (org-timecnt 0) diff h m s org-table-clip)
7100 (cond
7101 ((and beg end)) ; beg and end given explicitly
7102 ((org-region-active-p)
7103 (setq beg (region-beginning) end (region-end)))
7105 (setq col (org-table-current-column))
7106 (goto-char (org-table-begin))
7107 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7108 (error "No table data"))
7109 (org-table-goto-column col)
7110 (setq beg (point))
7111 (goto-char (org-table-end))
7112 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7113 (error "No table data"))
7114 (org-table-goto-column col)
7115 (setq end (point))))
7116 (let* ((items (apply 'append (org-table-copy-region beg end)))
7117 (items1 (cond ((not nlast) items)
7118 ((>= nlast (length items)) items)
7119 (t (setq items (reverse items))
7120 (setcdr (nthcdr (1- nlast) items) nil)
7121 (nreverse items))))
7122 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7123 items1)))
7124 (res (apply '+ numbers))
7125 (sres (if (= org-timecnt 0)
7126 (format "%g" res)
7127 (setq diff (* 3600 res)
7128 h (floor (/ diff 3600)) diff (mod diff 3600)
7129 m (floor (/ diff 60)) diff (mod diff 60)
7130 s diff)
7131 (format "%d:%02d:%02d" h m s))))
7132 (kill-new sres)
7133 (if (interactive-p)
7134 (message "%s"
7135 (substitute-command-keys
7136 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7137 (length numbers) sres))))
7138 sres))))
7140 (defun org-table-get-number-for-summing (s)
7141 (let (n)
7142 (if (string-match "^ *|? *" s)
7143 (setq s (replace-match "" nil nil s)))
7144 (if (string-match " *|? *$" s)
7145 (setq s (replace-match "" nil nil s)))
7146 (setq n (string-to-number s))
7147 (cond
7148 ((and (string-match "0" s)
7149 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7150 ((string-match "\\`[ \t]+\\'" s) nil)
7151 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7152 (let ((h (string-to-number (or (match-string 1 s) "0")))
7153 (m (string-to-number (or (match-string 2 s) "0")))
7154 (s (string-to-number (or (match-string 4 s) "0"))))
7155 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
7156 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7157 ((equal n 0) nil)
7158 (t n))))
7160 (defun org-table-current-field-formula ()
7161 "Return the formula active for the current field.
7162 Assumes that specials are in place."
7163 (let* ((name (car (rassoc (list (org-current-line)
7164 (org-table-current-column))
7165 org-table-named-field-locations)))
7166 (col (org-table-current-column))
7167 (scol (int-to-string col))
7168 (ref (format "@%d$%d" (org-table-current-dline) col))
7169 (stored-list (org-table-get-stored-formulas))
7170 (ass (or (assoc name stored-list)
7171 (assoc ref stored-list)
7172 (assoc scol stored-list))))
7173 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
7174 (cdr ass)))))
7176 (defun org-table-get-formula (&optional equation named)
7177 "Read a formula from the minibuffer, offer stored formula as default.
7178 When NAMED is non-nil, look for a named equation."
7179 (let* ((stored-list (org-table-get-stored-formulas))
7180 (name (car (rassoc (list (org-current-line)
7181 (org-table-current-column))
7182 org-table-named-field-locations)))
7183 (ref (format "@%d$%d" (org-table-current-dline)
7184 (org-table-current-column)))
7185 (refass (assoc ref stored-list))
7186 (scol (if named
7187 (if name name ref)
7188 (int-to-string (org-table-current-column))))
7189 (dummy (and (or name refass) (not named)
7190 (not (y-or-n-p "Replace field formula with column formula? " ))
7191 (error "Abort")))
7192 (name (or name ref))
7193 (org-table-may-need-update nil)
7194 (stored (cdr (assoc scol stored-list)))
7195 (eq (cond
7196 ((and stored equation (string-match "^ *=? *$" equation))
7197 stored)
7198 ((stringp equation)
7199 equation)
7200 (t (read-string
7201 (format "%s formula $%s=" (if named "Field" "Column") scol)
7202 (or stored "") 'org-table-formula-history
7203 ;stored
7204 ))))
7205 mustsave)
7206 (when (not (string-match "\\S-" eq))
7207 ;; remove formula
7208 (setq stored-list (delq (assoc scol stored-list) stored-list))
7209 (org-table-store-formulas stored-list)
7210 (error "Formula removed"))
7211 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7212 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7213 (if (and name (not named))
7214 ;; We set the column equation, delete the named one.
7215 (setq stored-list (delq (assoc name stored-list) stored-list)
7216 mustsave t))
7217 (if stored
7218 (setcdr (assoc scol stored-list) eq)
7219 (setq stored-list (cons (cons scol eq) stored-list)))
7220 (if (or mustsave (not (equal stored eq)))
7221 (org-table-store-formulas stored-list))
7222 eq))
7224 (defun org-table-store-formulas (alist)
7225 "Store the list of formulas below the current table."
7226 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7227 (save-excursion
7228 (goto-char (org-table-end))
7229 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
7230 (progn
7231 ;; don't overwrite TBLFM, we might use text properties to store stuff
7232 (goto-char (match-beginning 2))
7233 (delete-region (match-beginning 2) (match-end 0)))
7234 (insert "#+TBLFM:"))
7235 (insert " "
7236 (mapconcat (lambda (x)
7237 (concat
7238 (if (equal (string-to-char (car x)) ?@) "" "$")
7239 (car x) "=" (cdr x)))
7240 alist "::")
7241 "\n")))
7243 (defun org-table-get-stored-formulas ()
7244 "Return an alist with the stored formulas directly after current table."
7245 (interactive)
7246 (let (scol eq eq-alist strings string seen)
7247 (save-excursion
7248 (goto-char (org-table-end))
7249 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7250 (setq strings (org-split-string (match-string 2) " *:: *"))
7251 (while (setq string (pop strings))
7252 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
7253 (setq scol (if (match-end 2)
7254 (match-string 2 string)
7255 (match-string 1 string))
7256 eq (match-string 3 string)
7257 eq-alist (cons (cons scol eq) eq-alist))
7258 (if (member scol seen)
7259 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7260 (push scol seen))))))
7261 (nreverse eq-alist)))
7263 (defun org-table-fix-formulas (key replace &optional limit delta remove)
7264 "Modify the equations after the table structure has been edited.
7265 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
7266 For all numbers larger than LIMIT, shift them by DELTA."
7267 (save-excursion
7268 (goto-char (org-table-end))
7269 (when (looking-at "#\\+TBLFM:")
7270 (let ((re (concat key "\\([0-9]+\\)"))
7271 (re2
7272 (when remove
7273 (if (equal key "$")
7274 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
7275 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
7276 s n a)
7277 (when remove
7278 (while (re-search-forward re2 (point-at-eol) t)
7279 (replace-match "")))
7280 (while (re-search-forward re (point-at-eol) t)
7281 (setq s (match-string 1) n (string-to-number s))
7282 (cond
7283 ((setq a (assoc s replace))
7284 (replace-match (concat key (cdr a)) t t))
7285 ((and limit (> n limit))
7286 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
7288 (defun org-table-get-specials ()
7289 "Get the column names and local parameters for this table."
7290 (save-excursion
7291 (let ((beg (org-table-begin)) (end (org-table-end))
7292 names name fields fields1 field cnt
7293 c v l line col types dlines hlines)
7294 (setq org-table-column-names nil
7295 org-table-local-parameters nil
7296 org-table-named-field-locations nil
7297 org-table-current-begin-line nil
7298 org-table-current-line-types nil)
7299 (goto-char beg)
7300 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7301 (setq names (org-split-string (match-string 1) " *| *")
7302 cnt 1)
7303 (while (setq name (pop names))
7304 (setq cnt (1+ cnt))
7305 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7306 (push (cons name (int-to-string cnt)) org-table-column-names))))
7307 (setq org-table-column-names (nreverse org-table-column-names))
7308 (setq org-table-column-name-regexp
7309 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7310 (goto-char beg)
7311 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7312 (setq fields (org-split-string (match-string 1) " *| *"))
7313 (while (setq field (pop fields))
7314 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7315 (push (cons (match-string 1 field) (match-string 2 field))
7316 org-table-local-parameters))))
7317 (goto-char beg)
7318 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7319 (setq c (match-string 1)
7320 fields (org-split-string (match-string 2) " *| *"))
7321 (save-excursion
7322 (beginning-of-line (if (equal c "_") 2 0))
7323 (setq line (org-current-line) col 1)
7324 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7325 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7326 (while (and fields1 (setq field (pop fields)))
7327 (setq v (pop fields1) col (1+ col))
7328 (when (and (stringp field) (stringp v)
7329 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7330 (push (cons field v) org-table-local-parameters)
7331 (push (list field line col) org-table-named-field-locations))))
7332 ;; Analyse the line types
7333 (goto-char beg)
7334 (setq org-table-current-begin-line (org-current-line)
7335 l org-table-current-begin-line)
7336 (while (looking-at "[ \t]*|\\(-\\)?")
7337 (push (if (match-end 1) 'hline 'dline) types)
7338 (if (match-end 1) (push l hlines) (push l dlines))
7339 (beginning-of-line 2)
7340 (setq l (1+ l)))
7341 (setq org-table-current-line-types (apply 'vector (nreverse types))
7342 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
7343 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
7345 (defun org-this-word ()
7346 ;; Get the current word
7347 (save-excursion
7348 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7349 (end (progn (skip-chars-forward "^ \t\n") (point))))
7350 (buffer-substring-no-properties beg end))))
7352 (defun org-table-maybe-eval-formula ()
7353 "Check if the current field starts with \"=\" or \":=\".
7354 If yes, store the formula and apply it."
7355 ;; We already know we are in a table. Get field will only return a formula
7356 ;; when appropriate. It might return a separator line, but no problem.
7357 (when org-table-formula-evaluate-inline
7358 (let* ((field (org-trim (or (org-table-get-field) "")))
7359 named eq)
7360 (when (string-match "^:?=\\(.*\\)" field)
7361 (setq named (equal (string-to-char field) ?:)
7362 eq (match-string 1 field))
7363 (if (or (fboundp 'calc-eval)
7364 (equal (substring eq 0 (min 2 (length eq))) "'("))
7365 (org-table-eval-formula (if named '(4) nil) eq)
7366 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
7368 (defvar org-recalc-commands nil
7369 "List of commands triggering the recalculation of a line.
7370 Will be filled automatically during use.")
7372 (defvar org-recalc-marks
7373 '((" " . "Unmarked: no special line, no automatic recalculation")
7374 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7375 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7376 ("!" . "Column name definition line. Reference in formula as $name.")
7377 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7378 ("_" . "Names for values in row below this one.")
7379 ("^" . "Names for values in row above this one.")))
7381 (defun org-table-rotate-recalc-marks (&optional newchar)
7382 "Rotate the recalculation mark in the first column.
7383 If in any row, the first field is not consistent with a mark,
7384 insert a new column for the markers.
7385 When there is an active region, change all the lines in the region,
7386 after prompting for the marking character.
7387 After each change, a message will be displayed indicating the meaning
7388 of the new mark."
7389 (interactive)
7390 (unless (org-at-table-p) (error "Not at a table"))
7391 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7392 (beg (org-table-begin))
7393 (end (org-table-end))
7394 (l (org-current-line))
7395 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7396 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7397 (have-col
7398 (save-excursion
7399 (goto-char beg)
7400 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7401 (col (org-table-current-column))
7402 (forcenew (car (assoc newchar org-recalc-marks)))
7403 epos new)
7404 (when l1
7405 (message "Change region to what mark? Type # * ! $ or SPC: ")
7406 (setq newchar (char-to-string (read-char-exclusive))
7407 forcenew (car (assoc newchar org-recalc-marks))))
7408 (if (and newchar (not forcenew))
7409 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7410 newchar))
7411 (if l1 (goto-line l1))
7412 (save-excursion
7413 (beginning-of-line 1)
7414 (unless (looking-at org-table-dataline-regexp)
7415 (error "Not at a table data line")))
7416 (unless have-col
7417 (org-table-goto-column 1)
7418 (org-table-insert-column)
7419 (org-table-goto-column (1+ col)))
7420 (setq epos (point-at-eol))
7421 (save-excursion
7422 (beginning-of-line 1)
7423 (org-table-get-field
7424 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7425 (concat " "
7426 (setq new (or forcenew
7427 (cadr (member (match-string 1) marks))))
7428 " ")
7429 " # ")))
7430 (if (and l1 l2)
7431 (progn
7432 (goto-line l1)
7433 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7434 (and (looking-at org-table-dataline-regexp)
7435 (org-table-get-field 1 (concat " " new " "))))
7436 (goto-line l1)))
7437 (if (not (= epos (point-at-eol))) (org-table-align))
7438 (goto-line l)
7439 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7441 (defun org-table-maybe-recalculate-line ()
7442 "Recompute the current line if marked for it, and if we haven't just done it."
7443 (interactive)
7444 (and org-table-allow-automatic-line-recalculation
7445 (not (and (memq last-command org-recalc-commands)
7446 (equal org-last-recalc-line (org-current-line))))
7447 (save-excursion (beginning-of-line 1)
7448 (looking-at org-table-auto-recalculate-regexp))
7449 (org-table-recalculate) t))
7451 (defvar org-table-formula-debug nil
7452 "Non-nil means, debug table formulas.
7453 When nil, simply write \"#ERROR\" in corrupted fields.")
7454 (make-variable-buffer-local 'org-table-formula-debug)
7456 (defvar modes)
7457 (defsubst org-set-calc-mode (var &optional value)
7458 (if (stringp var)
7459 (setq var (assoc var '(("D" calc-angle-mode deg)
7460 ("R" calc-angle-mode rad)
7461 ("F" calc-prefer-frac t)
7462 ("S" calc-symbolic-mode t)))
7463 value (nth 2 var) var (nth 1 var)))
7464 (if (memq var modes)
7465 (setcar (cdr (memq var modes)) value)
7466 (cons var (cons value modes)))
7467 modes)
7469 (defun org-table-eval-formula (&optional arg equation
7470 suppress-align suppress-const
7471 suppress-store suppress-analysis)
7472 "Replace the table field value at the cursor by the result of a calculation.
7474 This function makes use of Dave Gillespie's Calc package, in my view the
7475 most exciting program ever written for GNU Emacs. So you need to have Calc
7476 installed in order to use this function.
7478 In a table, this command replaces the value in the current field with the
7479 result of a formula. It also installs the formula as the \"current\" column
7480 formula, by storing it in a special line below the table. When called
7481 with a `C-u' prefix, the current field must ba a named field, and the
7482 formula is installed as valid in only this specific field.
7484 When called with two `C-u' prefixes, insert the active equation
7485 for the field back into the current field, so that it can be
7486 edited there. This is useful in order to use \\[org-show-reference]
7487 to check the referenced fields.
7489 When called, the command first prompts for a formula, which is read in
7490 the minibuffer. Previously entered formulas are available through the
7491 history list, and the last used formula is offered as a default.
7492 These stored formulas are adapted correctly when moving, inserting, or
7493 deleting columns with the corresponding commands.
7495 The formula can be any algebraic expression understood by the Calc package.
7496 For details, see the Org-mode manual.
7498 This function can also be called from Lisp programs and offers
7499 additional arguments: EQUATION can be the formula to apply. If this
7500 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7501 used to speed-up recursive calls by by-passing unnecessary aligns.
7502 SUPPRESS-CONST suppresses the interpretation of constants in the
7503 formula, assuming that this has been done already outside the function.
7504 SUPPRESS-STORE means the formula should not be stored, either because
7505 it is already stored, or because it is a modified equation that should
7506 not overwrite the stored one."
7507 (interactive "P")
7508 (org-table-check-inside-data-field)
7509 (or suppress-analysis (org-table-get-specials))
7510 (if (equal arg '(16))
7511 (let ((eq (org-table-current-field-formula)))
7512 (or eq (error "No equation active for current field"))
7513 (org-table-get-field nil eq)
7514 (org-table-align)
7515 (setq org-table-may-need-update t))
7516 (let* (fields
7517 (ndown (if (integerp arg) arg 1))
7518 (org-table-automatic-realign nil)
7519 (case-fold-search nil)
7520 (down (> ndown 1))
7521 (formula (if (and equation suppress-store)
7522 equation
7523 (org-table-get-formula equation (equal arg '(4)))))
7524 (n0 (org-table-current-column))
7525 (modes (copy-sequence org-calc-default-modes))
7526 (numbers nil) ; was a variable, now fixed default
7527 (keep-empty nil)
7528 n form form0 bw fmt x ev orig c lispp)
7529 ;; Parse the format string. Since we have a lot of modes, this is
7530 ;; a lot of work. However, I think calc still uses most of the time.
7531 (if (string-match ";" formula)
7532 (let ((tmp (org-split-string formula ";")))
7533 (setq formula (car tmp)
7534 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7535 (nth 1 tmp)))
7536 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
7537 (setq c (string-to-char (match-string 1 fmt))
7538 n (string-to-number (match-string 2 fmt)))
7539 (if (= c ?p)
7540 (setq modes (org-set-calc-mode 'calc-internal-prec n))
7541 (setq modes (org-set-calc-mode
7542 'calc-float-format
7543 (list (cdr (assoc c '((?n . float) (?f . fix)
7544 (?s . sci) (?e . eng))))
7545 n))))
7546 (setq fmt (replace-match "" t t fmt)))
7547 (if (string-match "[NT]" fmt)
7548 (setq numbers (equal (match-string 0 fmt) "N")
7549 fmt (replace-match "" t t fmt)))
7550 (if (string-match "E" fmt)
7551 (setq keep-empty t
7552 fmt (replace-match "" t t fmt)))
7553 (while (string-match "[DRFS]" fmt)
7554 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7555 (setq fmt (replace-match "" t t fmt)))
7556 (unless (string-match "\\S-" fmt)
7557 (setq fmt nil))))
7558 (if (and (not suppress-const) org-table-formula-use-constants)
7559 (setq formula (org-table-formula-substitute-names formula)))
7560 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7561 (while (> ndown 0)
7562 (setq fields (org-split-string
7563 (org-no-properties
7564 (buffer-substring (point-at-bol) (point-at-eol)))
7565 " *| *"))
7566 (if numbers
7567 (setq fields (mapcar
7568 (lambda (x) (number-to-string (string-to-number x)))
7569 fields)))
7570 (setq ndown (1- ndown))
7571 (setq form (copy-sequence formula)
7572 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
7573 ;; Check for old vertical references
7574 (setq form (org-rewrite-old-row-references form))
7575 ;; Insert complex ranges
7576 (while (string-match org-table-range-regexp form)
7577 (setq form
7578 (replace-match
7579 (save-match-data
7580 (org-table-make-reference
7581 (org-table-get-range (match-string 0 form) nil n0)
7582 keep-empty numbers lispp))
7583 t t form)))
7584 ;; Insert simple ranges
7585 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
7586 (setq form
7587 (replace-match
7588 (save-match-data
7589 (org-table-make-reference
7590 (org-sublist
7591 fields (string-to-number (match-string 1 form))
7592 (string-to-number (match-string 2 form)))
7593 keep-empty numbers lispp))
7594 t t form)))
7595 (setq form0 form)
7596 ;; Insert the references to fields in same row
7597 (while (string-match "\\$\\([0-9]+\\)?" form)
7598 (setq n (if (match-beginning 1)
7599 (string-to-number (match-string 1 form))
7601 x (nth (1- n) fields))
7602 (unless x (error "Invalid field specifier \"%s\""
7603 (match-string 0 form)))
7604 (setq form (replace-match
7605 (save-match-data
7606 (org-table-make-reference x nil numbers lispp))
7607 t t form)))
7608 (if lispp
7609 (setq ev (condition-case nil
7610 (eval (eval (read form)))
7611 (error "#ERROR"))
7612 ev (if (numberp ev) (number-to-string ev) ev))
7613 (or (fboundp 'calc-eval)
7614 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
7615 (setq ev (calc-eval (cons form modes)
7616 (if numbers 'num))))
7618 (when org-table-formula-debug
7619 (with-output-to-temp-buffer "*Substitution History*"
7620 (princ (format "Substitution history of formula
7621 Orig: %s
7622 $xyz-> %s
7623 @r$c-> %s
7624 $1-> %s\n" orig formula form0 form))
7625 (if (listp ev)
7626 (princ (format " %s^\nError: %s"
7627 (make-string (car ev) ?\-) (nth 1 ev)))
7628 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7629 ev (or fmt "NONE")
7630 (if fmt (format fmt (string-to-number ev)) ev)))))
7631 (setq bw (get-buffer-window "*Substitution History*"))
7632 (shrink-window-if-larger-than-buffer bw)
7633 (unless (and (interactive-p) (not ndown))
7634 (unless (let (inhibit-redisplay)
7635 (y-or-n-p "Debugging Formula. Continue to next? "))
7636 (org-table-align)
7637 (error "Abort"))
7638 (delete-window bw)
7639 (message "")))
7640 (if (listp ev) (setq fmt nil ev "#ERROR"))
7641 (org-table-justify-field-maybe
7642 (if fmt (format fmt (string-to-number ev)) ev))
7643 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7644 (call-interactively 'org-return)
7645 (setq ndown 0)))
7646 (and down (org-table-maybe-recalculate-line))
7647 (or suppress-align (and org-table-may-need-update
7648 (org-table-align))))))
7650 (defun org-table-get-range (desc &optional tbeg col highlight)
7651 "Get a calc vector from a column, accorting to descriptor DESC.
7652 Optional arguments TBEG and COL can give the beginning of the table and
7653 the current column, to avoid unnecessary parsing.
7654 HIGHLIGHT means, just highlight the range."
7655 (if (not (equal (string-to-char desc) ?@))
7656 (setq desc (concat "@" desc)))
7657 (save-excursion
7658 (or tbeg (setq tbeg (org-table-begin)))
7659 (or col (setq col (org-table-current-column)))
7660 (let ((thisline (org-current-line))
7661 beg end c1 c2 r1 r2 rangep tmp)
7662 (unless (string-match org-table-range-regexp desc)
7663 (error "Invalid table range specifier `%s'" desc))
7664 (setq rangep (match-end 3)
7665 r1 (and (match-end 1) (match-string 1 desc))
7666 r2 (and (match-end 4) (match-string 4 desc))
7667 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
7668 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
7670 (and c1 (setq c1 (+ (string-to-number c1)
7671 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
7672 (and c2 (setq c2 (+ (string-to-number c2)
7673 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
7674 (if (equal r1 "") (setq r1 nil))
7675 (if (equal r2 "") (setq r2 nil))
7676 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
7677 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
7678 ; (setq r2 (or r2 r1) c2 (or c2 c1))
7679 (if (not r1) (setq r1 thisline))
7680 (if (not r2) (setq r2 thisline))
7681 (if (not c1) (setq c1 col))
7682 (if (not c2) (setq c2 col))
7683 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
7684 ;; just one field
7685 (progn
7686 (goto-line r1)
7687 (while (not (looking-at org-table-dataline-regexp))
7688 (beginning-of-line 2))
7689 (prog1 (org-table-get-field c1)
7690 (if highlight (org-table-highlight-rectangle (point) (point)))))
7691 ;; A range, return a vector
7692 ;; First sort the numbers to get a regular ractangle
7693 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
7694 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
7695 (goto-line r1)
7696 (while (not (looking-at org-table-dataline-regexp))
7697 (beginning-of-line 2))
7698 (org-table-goto-column c1)
7699 (setq beg (point))
7700 (goto-line r2)
7701 (while (not (looking-at org-table-dataline-regexp))
7702 (beginning-of-line 0))
7703 (org-table-goto-column c2)
7704 (setq end (point))
7705 (if highlight
7706 (org-table-highlight-rectangle
7707 beg (progn (skip-chars-forward "^|\n") (point))))
7708 ;; return string representation of calc vector
7709 (apply 'append (org-table-copy-region beg end))))))
7711 (defun org-table-get-descriptor-line (desc &optional cline bline table)
7712 "Analyze descriptor DESC and retrieve the corresponding line number.
7713 The cursor is currently in line CLINE, the table begins in line BLINE,
7714 and TABLE is a vector with line types."
7715 (if (string-match "^[0-9]+$" desc)
7716 (aref org-table-dlines (string-to-number desc))
7717 (setq cline (or cline (org-current-line))
7718 bline (or bline org-table-current-begin-line)
7719 table (or table org-table-current-line-types))
7720 (if (or
7721 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
7722 ;; 1 2 3 4 5 6
7723 (and (not (match-end 3)) (not (match-end 6)))
7724 (and (match-end 3) (match-end 6) (not (match-end 5))))
7725 (error "invalid row descriptor `%s'" desc))
7726 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
7727 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
7728 (odir (and (match-end 5) (match-string 5 desc)))
7729 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
7730 (i (- cline bline))
7731 (rel (and (match-end 6)
7732 (or (and (match-end 1) (not (match-end 3)))
7733 (match-end 5)))))
7734 (if (and hn (not hdir))
7735 (progn
7736 (setq i 0 hdir "+")
7737 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
7738 (if (and (not hn) on (not odir))
7739 (error "should never happen");;(aref org-table-dlines on) FIXME
7740 (if (and hn (> hn 0))
7741 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
7742 (if on
7743 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
7744 (+ bline i)))))
7746 (defun org-find-row-type (table i type backwards relative n)
7747 (let ((l (length table)))
7748 (while (> n 0)
7749 (while (and (setq i (+ i (if backwards -1 1)))
7750 (>= i 0) (< i l)
7751 (not (eq (aref table i) type))
7752 (if (and relative (eq (aref table i) 'hline))
7753 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
7754 t)))
7755 (setq n (1- n)))
7756 (if (or (< i 0) (>= i l))
7757 (error "Row descriptior leads outside table")
7758 i)))
7760 (defun org-rewrite-old-row-references (s)
7761 (if (string-match "&[-+0-9I]" s)
7762 (error "Formula contains old &row reference, please rewrite using @-syntax")
7765 (defun org-table-make-reference (elements keep-empty numbers lispp)
7766 "Convert list ELEMENTS to something appropriate to insert into formula.
7767 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
7768 NUMBERS indicates that everything should be converted to numbers.
7769 LISPP means to return something appropriate for a Lisp list."
7770 (if (stringp elements) ; just a single val
7771 (if lispp
7772 (prin1-to-string (if numbers (string-to-number elements) elements))
7773 (if (equal elements "") (setq elements "0"))
7774 (if numbers (number-to-string (string-to-number elements)) elements))
7775 (unless keep-empty
7776 (setq elements
7777 (delq nil
7778 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
7779 elements))))
7780 (setq elements (or elements '("0")))
7781 (if lispp
7782 (mapconcat 'prin1-to-string
7783 (if numbers (mapcar 'string-to-number elements) elements)
7784 " ")
7785 (concat "[" (mapconcat
7786 (lambda (x)
7787 (if numbers (number-to-string (string-to-number x)) x))
7788 elements
7789 ",") "]"))))
7791 (defun org-table-recalculate (&optional all noalign)
7792 "Recalculate the current table line by applying all stored formulas.
7793 With prefix arg ALL, do this for all lines in the table."
7794 (interactive "P")
7795 (or (memq this-command org-recalc-commands)
7796 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7797 (unless (org-at-table-p) (error "Not at a table"))
7798 (if (equal all '(16))
7799 (org-table-iterate)
7800 (org-table-get-specials)
7801 (let* ((eqlist (sort (org-table-get-stored-formulas)
7802 (lambda (a b) (string< (car a) (car b)))))
7803 (inhibit-redisplay (not debug-on-error))
7804 (line-re org-table-dataline-regexp)
7805 (thisline (org-current-line))
7806 (thiscol (org-table-current-column))
7807 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7808 ;; Insert constants in all formulas
7809 (setq eqlist
7810 (mapcar (lambda (x)
7811 (setcdr x (org-table-formula-substitute-names (cdr x)))
7813 eqlist))
7814 ;; Split the equation list
7815 (while (setq eq (pop eqlist))
7816 (if (<= (string-to-char (car eq)) ?9)
7817 (push eq eqlnum)
7818 (push eq eqlname)))
7819 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7820 (if all
7821 (progn
7822 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7823 (goto-char (setq beg (org-table-begin)))
7824 (if (re-search-forward org-table-calculate-mark-regexp end t)
7825 ;; This is a table with marked lines, compute selected lines
7826 (setq line-re org-table-recalculate-regexp)
7827 ;; Move forward to the first non-header line
7828 (if (and (re-search-forward org-table-dataline-regexp end t)
7829 (re-search-forward org-table-hline-regexp end t)
7830 (re-search-forward org-table-dataline-regexp end t))
7831 (setq beg (match-beginning 0))
7832 nil))) ;; just leave beg where it is
7833 (setq beg (point-at-bol)
7834 end (move-marker (make-marker) (1+ (point-at-eol)))))
7835 (goto-char beg)
7836 (and all (message "Re-applying formulas to full table..."))
7837 (while (re-search-forward line-re end t)
7838 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7839 ;; Unprotected line, recalculate
7840 (and all (message "Re-applying formulas to full table...(line %d)"
7841 (setq cnt (1+ cnt))))
7842 (setq org-last-recalc-line (org-current-line))
7843 (setq eql eqlnum)
7844 (while (setq entry (pop eql))
7845 (goto-line org-last-recalc-line)
7846 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7847 (org-table-eval-formula nil (cdr entry)
7848 'noalign 'nocst 'nostore 'noanalysis))))
7849 (goto-line thisline)
7850 (org-table-goto-column thiscol)
7851 (or noalign (and org-table-may-need-update (org-table-align))
7852 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7853 ;; Now do the named fields
7854 (while (setq eq (pop eqlname))
7855 (setq name (car eq)
7856 a (assoc name org-table-named-field-locations))
7857 (and (not a)
7858 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
7859 (setq a
7860 (list
7861 name
7862 (aref org-table-dlines
7863 (string-to-number (match-string 1 name)))
7864 (string-to-number (match-string 2 name)))))
7865 (when (and a (or all (equal (nth 1 a) thisline)))
7866 (message "Re-applying formula to field: %s" name)
7867 (goto-line (nth 1 a))
7868 (org-table-goto-column (nth 2 a))
7869 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
7870 'nostore 'noanalysis)))
7871 ;; back to initial position
7872 (message "Re-applying formulas...done")
7873 (goto-line thisline)
7874 (org-table-goto-column thiscol)
7875 (or noalign (and org-table-may-need-update (org-table-align))
7876 (and all (message "Re-applying formulas...done"))))))
7878 (defun org-table-iterate (&optional arg)
7879 "Recalculate the table until it does not change anymore."
7880 (interactive "P")
7881 (let ((imax (if arg (prefix-numeric-value arg) 10))
7882 (i 0)
7883 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
7884 thistbl)
7885 (catch 'exit
7886 (while (< i imax)
7887 (setq i (1+ i))
7888 (org-table-recalculate 'all)
7889 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
7890 (if (not (string= lasttbl thistbl))
7891 (setq lasttbl thistbl)
7892 (if (> i 1)
7893 (message "Convergence after %d iterations" i)
7894 (message "Table was already stable"))
7895 (throw 'exit t)))
7896 (error "No convergence after %d iterations" i))))
7898 (defun org-table-formula-substitute-names (f)
7899 "Replace $const with values in string F."
7900 (let ((start 0) a (f1 f))
7901 ;; First, check for column names
7902 (while (setq start (string-match org-table-column-name-regexp f start))
7903 (setq start (1+ start))
7904 (setq a (assoc (match-string 1 f) org-table-column-names))
7905 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7906 ;; Parameters and constants
7907 (setq start 0)
7908 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7909 (setq start (1+ start))
7910 (if (setq a (save-match-data
7911 (org-table-get-constant (match-string 1 f))))
7912 (setq f (replace-match (concat "(" a ")") t t f))))
7913 (if org-table-formula-debug
7914 (put-text-property 0 (length f) :orig-formula f1 f))
7917 (defun org-table-get-constant (const)
7918 "Find the value for a parameter or constant in a formula.
7919 Parameters get priority."
7920 (or (cdr (assoc const org-table-local-parameters))
7921 (cdr (assoc const org-table-formula-constants))
7922 (and (fboundp 'constants-get) (constants-get const))
7923 "#UNDEFINED_NAME"))
7925 (defvar org-edit-formulas-map (make-sparse-keymap))
7926 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7927 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7928 (define-key org-edit-formulas-map "\C-c?" 'org-show-reference)
7929 (define-key org-edit-formulas-map [(shift up)] 'org-table-edit-line-up)
7930 (define-key org-edit-formulas-map [(shift down)] 'org-table-edit-line-down)
7931 (define-key org-edit-formulas-map [(shift left)] 'org-table-edit-backward-field)
7932 (define-key org-edit-formulas-map [(shift right)] 'org-table-edit-next-field)
7933 (define-key org-edit-formulas-map [(meta up)] 'org-table-edit-scroll-down)
7934 (define-key org-edit-formulas-map [(meta down)] 'org-table-edit-scroll)
7935 (define-key org-edit-formulas-map [(meta tab)] 'lisp-complete-symbol)
7936 (define-key org-edit-formulas-map "\M-\C-i" 'lisp-complete-symbol)
7937 (define-key org-edit-formulas-map [(tab)] 'org-edit-formula-lisp-indent)
7938 (define-key org-edit-formulas-map "\C-i" 'org-edit-formula-lisp-indent)
7940 (defvar org-pos)
7942 (defun org-table-edit-formulas ()
7943 "Edit the formulas of the current table in a separate buffer."
7944 (interactive)
7945 (unless (org-at-table-p) (error "Not at a table"))
7946 (org-table-get-specials)
7947 (let ((eql (org-table-get-stored-formulas))
7948 (pos (move-marker (make-marker) (point)))
7949 (wc (current-window-configuration))
7950 entry s)
7951 (switch-to-buffer-other-window "*Edit Formulas*")
7952 (erase-buffer)
7953 (fundamental-mode)
7954 (org-set-local 'org-pos pos)
7955 (org-set-local 'org-window-configuration wc)
7956 (use-local-map org-edit-formulas-map)
7957 (org-add-hook 'post-command-hook 'org-table-edit-formulas-post-command t t)
7958 (setq s "# `C-c C-c' to finish, `C-u C-c C-c' to also apply, `C-c C-q' to abort.
7959 # `TAB' to pretty-print Lisp expressions, `M-TAB' to complete List symbols
7960 # `M-up/down' to scroll table, `S-up/down' to change line for column formulas\n\n")
7962 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7963 (insert s)
7964 (while (setq entry (pop eql))
7965 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
7966 (car entry) " = " (cdr entry) "\n"))
7967 (remove-text-properties 0 (length s) '(face nil) s)
7968 (insert s))
7969 (goto-char (point-min))
7970 (message "Edit formulas and finish with `C-c C-c'.")))
7972 (defun org-table-edit-formulas-post-command ()
7973 (when (not (memq this-command '(lisp-complete-symbol)))
7974 (let ((win (selected-window)))
7975 (save-excursion
7976 (condition-case nil
7977 (org-show-reference)
7978 (error nil))
7979 (select-window win)))))
7981 (defun org-finish-edit-formulas (&optional arg)
7982 "Parse the buffer for formula definitions and install them.
7983 With prefix ARG, apply the new formulas to the table."
7984 (interactive "P")
7985 (org-table-remove-rectangle-highlight)
7986 (let ((pos org-pos) eql var form)
7987 (setq org-pos nil)
7988 (goto-char (point-min))
7989 (while (re-search-forward
7990 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
7991 nil t)
7992 (setq var (if (match-end 2) (match-string 2) (match-string 1))
7993 form (match-string 3))
7994 (setq form (org-trim form))
7995 (while (string-match "[ \t]*\n[ \t]*" form)
7996 (setq form (replace-match " " t t form)))
7997 (push (cons var form) eql))
7998 (set-window-configuration org-window-configuration)
7999 (select-window (get-buffer-window (marker-buffer pos)))
8000 (goto-char pos)
8001 (unless (org-at-table-p)
8002 (error "Lost table position - cannot install formulae"))
8003 (org-table-store-formulas eql)
8004 (move-marker pos nil)
8005 (kill-buffer "*Edit Formulas*")
8006 (if arg
8007 (org-table-recalculate 'all)
8008 (message "New formulas installed - press C-u C-c C-c to apply."))))
8010 (defun org-abort-edit-formulas ()
8011 "Abort editing formulas, without installing the changes."
8012 (interactive)
8013 (org-table-remove-rectangle-highlight)
8014 (let ((pos org-pos))
8015 (set-window-configuration org-window-configuration)
8016 (select-window (get-buffer-window (marker-buffer pos)))
8017 (goto-char pos)
8018 (move-marker pos nil)
8019 (message "Formula editing aborted without installing changes")))
8021 (defun org-edit-formula-lisp-indent ()
8022 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
8023 (interactive)
8024 (let ((pos (point)) beg end ind)
8025 (beginning-of-line 1)
8026 (cond
8027 ((looking-at "[ \t]")
8028 (goto-char pos)
8029 (call-interactively 'lisp-indent-line))
8030 ((looking-at "[$@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
8031 ((not (fboundp 'pp-buffer))
8032 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
8033 ((looking-at "[$@0-9a-zA-Z]+ *= *'(")
8034 (goto-char (- (match-end 0) 2))
8035 (setq beg (point))
8036 (setq ind (make-string (current-column) ?\ ))
8037 (condition-case nil (forward-sexp 1)
8038 (error
8039 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
8040 (setq end (point))
8041 (save-restriction
8042 (narrow-to-region beg end)
8043 (if (eq last-command this-command)
8044 (progn
8045 (goto-char (point-min))
8046 (setq this-command nil)
8047 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
8048 (replace-match " ")))
8049 (pp-buffer)
8050 (untabify (point-min) (point-max))
8051 (goto-char (1+ (point-min)))
8052 (while (re-search-forward "^." nil t)
8053 (beginning-of-line 1)
8054 (insert ind))
8055 (goto-char (point-max))
8056 (backward-delete-char 1)))
8057 (goto-char beg))
8058 (t nil))))
8060 (defvar org-show-positions nil)
8062 (defun org-show-reference (&optional local)
8063 "Show the location/value of the $ expression at point."
8064 (interactive)
8065 (org-table-remove-rectangle-highlight)
8066 (catch 'exit
8067 (let ((pos (if local (point) org-pos))
8068 (face2 'highlight)
8069 (org-inhibit-highlight-removal t)
8070 (win (selected-window))
8071 (org-show-positions nil)
8072 var name e what match dest)
8073 (if local (org-table-get-specials))
8074 (setq what (cond
8075 ((org-at-regexp-p org-table-range-regexp2) 'range)
8076 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
8077 ((org-at-regexp-p "\\$[0-9]+") 'column)
8078 ((not local) nil)
8079 (t (error "No reference at point")))
8080 match (and what (match-string 0)))
8081 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
8082 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
8083 'secondary-selection))
8084 (org-add-hook 'before-change-functions
8085 'org-table-remove-rectangle-highlight)
8086 (if (eq what 'name) (setq var (substring match 1)))
8087 (when (eq what 'range)
8088 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
8089 (setq match (org-table-formula-substitute-names match)))
8090 (unless local
8091 (save-excursion
8092 (beginning-of-line 1)
8093 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\)=")
8094 (setq dest (match-string 1))
8095 (org-table-add-rectangle-overlay
8096 (match-beginning 1) (match-end 1) face2))))
8097 (if (and (markerp pos) (marker-buffer pos))
8098 (if (get-buffer-window (marker-buffer pos))
8099 (select-window (get-buffer-window (marker-buffer pos)))
8100 (switch-to-buffer-other-window (get-buffer-window
8101 (marker-buffer pos)))))
8102 (goto-char pos)
8103 (org-table-force-dataline)
8104 (when dest
8105 (setq name (substring dest 1))
8106 (cond
8107 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
8108 (setq e (assoc name org-table-named-field-locations))
8109 (goto-line (nth 1 e))
8110 (org-table-goto-column (nth 2 e)))
8111 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
8112 (let ((l (string-to-number (match-string 1 dest)))
8113 (c (string-to-number (match-string 2 dest))))
8114 (goto-line (aref org-table-dlines l))
8115 (org-table-goto-column c)))
8116 (t (org-table-goto-column (string-to-number name))))
8117 (move-marker pos (point))
8118 (org-table-highlight-rectangle nil nil face2))
8119 (cond
8120 ((equal dest match))
8121 ((not match))
8122 ((eq what 'range)
8123 (condition-case nil
8124 (save-excursion
8125 (org-table-get-range match nil nil 'highlight))
8126 (error nil)))
8127 ((setq e (assoc var org-table-named-field-locations))
8128 (goto-line (nth 1 e))
8129 (org-table-goto-column (nth 2 e))
8130 (org-table-highlight-rectangle (point) (point))
8131 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
8132 ((setq e (assoc var org-table-column-names))
8133 (org-table-goto-column (string-to-number (cdr e)))
8134 (org-table-highlight-rectangle (point) (point))
8135 (goto-char (org-table-begin))
8136 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
8137 (org-table-end) t)
8138 (progn
8139 (goto-char (match-beginning 1))
8140 (org-table-highlight-rectangle)
8141 (message "Named column (column %s)" (cdr e)))
8142 (error "Column name not found")))
8143 ((eq what 'column)
8144 ;; column number
8145 (org-table-goto-column (string-to-number (substring match 1)))
8146 (org-table-highlight-rectangle (point) (point))
8147 (message "Column %s" (substring match 1)))
8148 ((setq e (assoc var org-table-local-parameters))
8149 (goto-char (org-table-begin))
8150 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
8151 (progn
8152 (goto-char (match-beginning 1))
8153 (org-table-highlight-rectangle)
8154 (message "Local parameter."))
8155 (error "Parameter not found")))
8157 (cond
8158 ((not var) (error "No reference at point"))
8159 ((setq e (assoc var org-table-formula-constants))
8160 (message "Constant: $%s=%s in `org-table-formula-constants'."
8161 var (cdr e)))
8162 ((setq e (and (fboundp 'constants-get) (constants-get var)))
8163 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
8164 (t (error "Undefined name $%s" var)))))
8165 (goto-char pos)
8166 (when org-show-positions
8167 (push pos org-show-positions)
8168 (let ((min (apply 'min org-show-positions))
8169 (max (apply 'max org-show-positions)))
8170 (when (or (not (pos-visible-in-window-p min))
8171 (not (pos-visible-in-window-p max)))
8172 (goto-char min)
8173 (set-window-start (selected-window) (point-at-bol))
8174 (goto-char pos))))
8175 (select-window win))))
8177 (defun org-table-force-dataline ()
8178 "Make sure the cursor is in a dataline in a table."
8179 (unless (save-excursion
8180 (beginning-of-line 1)
8181 (looking-at org-table-dataline-regexp))
8182 (let* ((re org-table-dataline-regexp)
8183 (p1 (save-excursion (re-search-forward re nil 'move)))
8184 (p2 (save-excursion (re-search-backward re nil 'move))))
8185 (cond ((and p1 p2)
8186 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
8187 p1 p2)))
8188 ((or p1 p2) (goto-char (or p1 p2)))
8189 (t (error "No table dataline around here"))))))
8191 (defun org-table-edit-line-up ()
8192 "Move cursor one line up in the window showing the table."
8193 (interactive)
8194 (org-table-edit-move 'previous-line))
8196 (defun org-table-edit-line-down ()
8197 "Move cursor one line down in the window showing the table."
8198 (interactive)
8199 (org-table-edit-move 'next-line))
8201 (defun org-table-edit-backward-field ()
8202 "Move cursor one field backward in the window showing the table."
8203 (interactive)
8204 (org-table-edit-move 'org-table-previous-field))
8206 (defun org-table-edit-next-field ()
8207 "Move cursor one field forward in the window showing the table."
8208 (interactive)
8209 (org-table-edit-move 'org-table-next-field))
8211 (defun org-table-edit-move (command)
8212 "Move the cursor in the window shoinw the table.
8213 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
8214 (let ((org-table-allow-automatic-line-recalculation nil)
8215 (pos org-pos) (win (selected-window)) p)
8216 (select-window (get-buffer-window (marker-buffer org-pos)))
8217 (setq p (point))
8218 (call-interactively command)
8219 (while (and (org-at-table-p)
8220 (org-at-table-hline-p))
8221 (call-interactively command))
8222 (or (org-at-table-p) (goto-char p))
8223 (move-marker pos (point))
8224 (select-window win)))
8226 (defun org-table-edit-scroll (N)
8227 (interactive "p")
8228 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
8229 (scroll-other-window N)))
8231 (defun org-table-edit-scroll-down (N)
8232 (interactive "p")
8233 (org-table-edit-scroll (- N)))
8235 (defvar org-table-rectangle-overlays nil)
8237 (defun org-table-add-rectangle-overlay (beg end &optional face)
8238 "Add a new overlay."
8239 (let ((ov (org-make-overlay beg end)))
8240 (org-overlay-put ov 'face (or face 'secondary-selection))
8241 (push ov org-table-rectangle-overlays)))
8243 (defun org-table-highlight-rectangle (&optional beg end face)
8244 "Highlight rectangular region in a table."
8245 (setq beg (or beg (point)) end (or end (point)))
8246 (let ((b (min beg end))
8247 (e (max beg end))
8248 l1 c1 l2 c2 tmp)
8249 (and (boundp 'org-show-positions)
8250 (setq org-show-positions (cons b (cons e org-show-positions))))
8251 (goto-char (min beg end))
8252 (setq l1 (org-current-line)
8253 c1 (org-table-current-column))
8254 (goto-char (max beg end))
8255 (setq l2 (org-current-line)
8256 c2 (org-table-current-column))
8257 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
8258 (goto-line l1)
8259 (beginning-of-line 1)
8260 (loop for line from l1 to l2 do
8261 (when (looking-at org-table-dataline-regexp)
8262 (org-table-goto-column c1)
8263 (skip-chars-backward "^|\n") (setq beg (point))
8264 (org-table-goto-column c2)
8265 (skip-chars-forward "^|\n") (setq end (point))
8266 (org-table-add-rectangle-overlay beg end face))
8267 (beginning-of-line 2))
8268 (goto-char b))
8269 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
8271 (defun org-table-remove-rectangle-highlight (&rest ignore)
8272 "Remove the rectangle overlays."
8273 (unless org-inhibit-highlight-removal
8274 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
8275 (mapc 'org-delete-overlay org-table-rectangle-overlays)
8276 (setq org-table-rectangle-overlays nil)))
8278 (defvar org-table-coordinate-overlays nil
8279 "Collects the cooordinate grid overlays, so that they can be removed.")
8280 (make-variable-buffer-local 'org-table-coordinate-overlays)
8282 (defun org-table-overlay-coordinates ()
8283 "Add overlays to the table at point, to show row/column coordinates."
8284 (interactive)
8285 (mapc 'org-delete-overlay org-table-coordinate-overlays)
8286 (setq org-table-coordinate-overlays nil)
8287 (save-excursion
8288 (let ((id 0) (ih 0) hline eol str ic ov beg)
8289 (goto-char (org-table-begin))
8290 (while (org-at-table-p)
8291 (setq eol (point-at-eol))
8292 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
8293 (push ov org-table-coordinate-overlays)
8294 (setq hline (looking-at org-table-hline-regexp))
8295 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
8296 (format "%4d" (setq id (1+ id)))))
8297 (org-overlay-before-string ov str 'org-formula 'evaporate)
8298 (when hline
8299 (setq ic 0)
8300 (while (re-search-forward "[+|]-+" eol t)
8301 (setq beg (1+ (match-beginning 0))
8302 str (concat "$" (int-to-string (setq ic (1+ ic)))))
8303 (setq ov (org-make-overlay beg (+ beg (length str))))
8304 (push ov org-table-coordinate-overlays)
8305 (org-overlay-display ov str 'org-formula 'evaporate)))
8306 (beginning-of-line 2)))))
8308 (defun org-table-toggle-coordinate-overlays ()
8309 "Toggle the display of Row/Column numbers in tables."
8310 (interactive)
8311 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
8312 (message "Row/Column number display turned %s"
8313 (if org-table-overlay-coordinates "on" "off"))
8314 (if (and (org-at-table-p) org-table-overlay-coordinates)
8315 (org-table-align))
8316 (unless org-table-overlay-coordinates
8317 (mapc 'org-delete-overlay org-table-coordinate-overlays)
8318 (setq org-table-coordinate-overlays nil)))
8320 (defun org-table-toggle-formula-debugger ()
8321 "Toggle the formula debugger in tables."
8322 (interactive)
8323 (setq org-table-formula-debug (not org-table-formula-debug))
8324 (message "Formula debugging has been turned %s"
8325 (if org-table-formula-debug "on" "off")))
8327 ;;; The orgtbl minor mode
8329 ;; Define a minor mode which can be used in other modes in order to
8330 ;; integrate the org-mode table editor.
8332 ;; This is really a hack, because the org-mode table editor uses several
8333 ;; keys which normally belong to the major mode, for example the TAB and
8334 ;; RET keys. Here is how it works: The minor mode defines all the keys
8335 ;; necessary to operate the table editor, but wraps the commands into a
8336 ;; function which tests if the cursor is currently inside a table. If that
8337 ;; is the case, the table editor command is executed. However, when any of
8338 ;; those keys is used outside a table, the function uses `key-binding' to
8339 ;; look up if the key has an associated command in another currently active
8340 ;; keymap (minor modes, major mode, global), and executes that command.
8341 ;; There might be problems if any of the keys used by the table editor is
8342 ;; otherwise used as a prefix key.
8344 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8345 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8346 ;; addresses this by checking explicitly for both bindings.
8348 ;; The optimized version (see variable `orgtbl-optimized') takes over
8349 ;; all keys which are bound to `self-insert-command' in the *global map*.
8350 ;; Some modes bind other commands to simple characters, for example
8351 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
8352 ;; active, this binding is ignored inside tables and replaced with a
8353 ;; modified self-insert.
8355 (defvar orgtbl-mode nil
8356 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
8357 table editor in arbitrary modes.")
8358 (make-variable-buffer-local 'orgtbl-mode)
8360 (defvar orgtbl-mode-map (make-keymap)
8361 "Keymap for `orgtbl-mode'.")
8363 ;;;###autoload
8364 (defun turn-on-orgtbl ()
8365 "Unconditionally turn on `orgtbl-mode'."
8366 (orgtbl-mode 1))
8368 (defvar org-old-auto-fill-inhibit-regexp nil
8369 "Local variable used by `orgtbl-mode'")
8371 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
8372 "Matches a line belonging to an orgtbl.")
8374 (defconst orgtbl-extra-font-lock-keywords
8375 (list (list (concat "^" orgtbl-line-start-regexp ".*")
8376 0 (quote 'org-table) 'prepend))
8377 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
8379 ;;;###autoload
8380 (defun orgtbl-mode (&optional arg)
8381 "The `org-mode' table editor as a minor mode for use in other modes."
8382 (interactive)
8383 (if (org-mode-p)
8384 ;; Exit without error, in case some hook functions calls this
8385 ;; by accident in org-mode.
8386 (message "Orgtbl-mode is not useful in org-mode, command ignored")
8387 (setq orgtbl-mode
8388 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
8389 (if orgtbl-mode
8390 (progn
8391 (and (orgtbl-setup) (defun orgtbl-setup () nil))
8392 ;; Make sure we are first in minor-mode-map-alist
8393 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
8394 (and c (setq minor-mode-map-alist
8395 (cons c (delq c minor-mode-map-alist)))))
8396 (org-set-local (quote org-table-may-need-update) t)
8397 (org-add-hook 'before-change-functions 'org-before-change-function
8398 nil 'local)
8399 (org-set-local 'org-old-auto-fill-inhibit-regexp
8400 auto-fill-inhibit-regexp)
8401 (org-set-local 'auto-fill-inhibit-regexp
8402 (if auto-fill-inhibit-regexp
8403 (concat orgtbl-line-start-regexp "\\|"
8404 auto-fill-inhibit-regexp)
8405 orgtbl-line-start-regexp))
8406 (org-add-to-invisibility-spec '(org-cwidth))
8407 (when (fboundp 'font-lock-add-keywords)
8408 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
8409 (org-restart-font-lock))
8410 (easy-menu-add orgtbl-mode-menu)
8411 (run-hooks 'orgtbl-mode-hook))
8412 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
8413 (org-cleanup-narrow-column-properties)
8414 (org-remove-from-invisibility-spec '(org-cwidth))
8415 (remove-hook 'before-change-functions 'org-before-change-function t)
8416 (when (fboundp 'font-lock-remove-keywords)
8417 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
8418 (org-restart-font-lock))
8419 (easy-menu-remove orgtbl-mode-menu)
8420 (force-mode-line-update 'all))))
8422 (defun org-cleanup-narrow-column-properties ()
8423 "Remove all properties related to narrow-column invisibility."
8424 (let ((s 1))
8425 (while (setq s (text-property-any s (point-max)
8426 'display org-narrow-column-arrow))
8427 (remove-text-properties s (1+ s) '(display t)))
8428 (setq s 1)
8429 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
8430 (remove-text-properties s (1+ s) '(org-cwidth t)))
8431 (setq s 1)
8432 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
8433 (remove-text-properties s (1+ s) '(invisible t)))))
8435 ;; Install it as a minor mode.
8436 (put 'orgtbl-mode :included t)
8437 (put 'orgtbl-mode :menu-tag "Org Table Mode")
8438 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
8440 (defun orgtbl-make-binding (fun n &rest keys)
8441 "Create a function for binding in the table minor mode.
8442 FUN is the command to call inside a table. N is used to create a unique
8443 command name. KEYS are keys that should be checked in for a command
8444 to execute outside of tables."
8445 (eval
8446 (list 'defun
8447 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
8448 '(arg)
8449 (concat "In tables, run `" (symbol-name fun) "'.\n"
8450 "Outside of tables, run the binding of `"
8451 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8452 "'.")
8453 '(interactive "p")
8454 (list 'if
8455 '(org-at-table-p)
8456 (list 'call-interactively (list 'quote fun))
8457 (list 'let '(orgtbl-mode)
8458 (list 'call-interactively
8459 (append '(or)
8460 (mapcar (lambda (k)
8461 (list 'key-binding k))
8462 keys)
8463 '('orgtbl-error))))))))
8465 (defun orgtbl-error ()
8466 "Error when there is no default binding for a table key."
8467 (interactive)
8468 (error "This key is has no function outside tables"))
8470 (defun orgtbl-setup ()
8471 "Setup orgtbl keymaps."
8472 (let ((nfunc 0)
8473 (bindings
8474 (list
8475 '([(meta shift left)] org-table-delete-column)
8476 '([(meta left)] org-table-move-column-left)
8477 '([(meta right)] org-table-move-column-right)
8478 '([(meta shift right)] org-table-insert-column)
8479 '([(meta shift up)] org-table-kill-row)
8480 '([(meta shift down)] org-table-insert-row)
8481 '([(meta up)] org-table-move-row-up)
8482 '([(meta down)] org-table-move-row-down)
8483 '("\C-c\C-w" org-table-cut-region)
8484 '("\C-c\M-w" org-table-copy-region)
8485 '("\C-c\C-y" org-table-paste-rectangle)
8486 '("\C-c-" org-table-insert-hline)
8487 '("\C-c}" org-table-toggle-coordinate-overlays)
8488 '("\C-c{" org-table-toggle-formula-debugger)
8489 '("\C-m" org-table-next-row)
8490 (list (org-key 'S-return) 'org-table-copy-down)
8491 '("\C-c\C-q" org-table-wrap-region)
8492 '("\C-c?" org-table-field-info)
8493 '("\C-c " org-table-blank-field)
8494 '("\C-c+" org-table-sum)
8495 '("\C-c=" org-table-eval-formula)
8496 '("\C-c'" org-table-edit-formulas)
8497 '("\C-c`" org-table-edit-field)
8498 '("\C-c*" org-table-recalculate)
8499 '("\C-c|" org-table-create-or-convert-from-region)
8500 '("\C-c^" org-table-sort-lines)
8501 '([(control ?#)] org-table-rotate-recalc-marks)))
8502 elt key fun cmd)
8503 (while (setq elt (pop bindings))
8504 (setq nfunc (1+ nfunc))
8505 (setq key (car elt)
8506 fun (nth 1 elt)
8507 cmd (orgtbl-make-binding fun nfunc key))
8508 (define-key orgtbl-mode-map key cmd))
8510 ;; Special treatment needed for TAB and RET
8511 (define-key orgtbl-mode-map [(return)]
8512 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
8513 (define-key orgtbl-mode-map "\C-m"
8514 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
8516 (define-key orgtbl-mode-map [(tab)]
8517 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
8518 (define-key orgtbl-mode-map "\C-i"
8519 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
8521 (define-key orgtbl-mode-map [(shift tab)]
8522 (orgtbl-make-binding 'org-table-previous-field 104
8523 [(shift tab)] [(tab)] "\C-i"))
8525 (define-key orgtbl-mode-map "\M-\C-m"
8526 (orgtbl-make-binding 'org-table-wrap-region 105
8527 "\M-\C-m" [(meta return)]))
8528 (define-key orgtbl-mode-map [(meta return)]
8529 (orgtbl-make-binding 'org-table-wrap-region 106
8530 [(meta return)] "\M-\C-m"))
8532 (define-key orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
8533 (when orgtbl-optimized
8534 ;; If the user wants maximum table support, we need to hijack
8535 ;; some standard editing functions
8536 (org-remap orgtbl-mode-map
8537 'self-insert-command 'orgtbl-self-insert-command
8538 'delete-char 'org-delete-char
8539 'delete-backward-char 'org-delete-backward-char)
8540 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8541 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8542 '("OrgTbl"
8543 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8544 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8545 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8546 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8547 "--"
8548 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8549 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
8550 ["Copy Field from Above"
8551 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8552 "--"
8553 ("Column"
8554 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8555 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8556 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8557 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8558 ("Row"
8559 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8560 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8561 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8562 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8563 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
8564 "--"
8565 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8566 ("Rectangle"
8567 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
8568 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
8569 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
8570 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
8571 "--"
8572 ("Radio tables"
8573 ["Insert table template" orgtbl-insert-radio-table
8574 (assq major-mode orgtbl-radio-table-templates)]
8575 ["Comment/uncomment table" orgtbl-toggle-comment t])
8576 "--"
8577 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8578 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8579 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8580 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8581 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8582 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
8583 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8584 ["Sum Column/Rectangle" org-table-sum
8585 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8586 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8587 ["Debug Formulas"
8588 org-table-toggle-formula-debugger :active (org-at-table-p)
8589 :keys "C-c {"
8590 :style toggle :selected org-table-formula-debug]
8591 ["Show Col/Row Numbers"
8592 org-table-toggle-coordinate-overlays :active (org-at-table-p)
8593 :keys "C-c }"
8594 :style toggle :selected org-table-overlay-coordinates]
8598 (defun orgtbl-ctrl-c-ctrl-c (arg)
8599 "If the cursor is inside a table, realign the table.
8600 It it is a table to be sent away to a receiver, do it.
8601 With prefix arg, also recompute table."
8602 (interactive "P")
8603 (let ((pos (point)) action)
8604 (save-excursion
8605 (beginning-of-line 1)
8606 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
8607 ((looking-at "[ \t]*|") pos)
8608 ((looking-at "#\\+TBLFM:") 'recalc))))
8609 (cond
8610 ((integerp action)
8611 (goto-char action)
8612 (org-table-maybe-eval-formula)
8613 (if arg
8614 (call-interactively 'org-table-recalculate)
8615 (org-table-maybe-recalculate-line))
8616 (call-interactively 'org-table-align)
8617 (orgtbl-send-table 'maybe))
8618 ((eq action 'recalc)
8619 (save-excursion
8620 (beginning-of-line 1)
8621 (skip-chars-backward " \r\n\t")
8622 (if (org-at-table-p)
8623 (org-call-with-arg 'org-table-recalculate t))))
8624 (t (let (orgtbl-mode)
8625 (call-interactively (key-binding "\C-c\C-c")))))))
8627 (defun orgtbl-tab (arg)
8628 "Justification and field motion for `orgtbl-mode'."
8629 (interactive "P")
8630 (if arg (org-table-edit-field t)
8631 (org-table-justify-field-maybe)
8632 (org-table-next-field)))
8634 (defun orgtbl-ret ()
8635 "Justification and field motion for `orgtbl-mode'."
8636 (interactive)
8637 (org-table-justify-field-maybe)
8638 (org-table-next-row))
8640 (defun orgtbl-self-insert-command (N)
8641 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8642 If the cursor is in a table looking at whitespace, the whitespace is
8643 overwritten, and the table is not marked as requiring realignment."
8644 (interactive "p")
8645 (if (and (org-at-table-p)
8647 (and org-table-auto-blank-field
8648 (member last-command
8649 '(orgtbl-hijacker-command-100
8650 orgtbl-hijacker-command-101
8651 orgtbl-hijacker-command-102
8652 orgtbl-hijacker-command-103
8653 orgtbl-hijacker-command-104
8654 orgtbl-hijacker-command-105))
8655 (org-table-blank-field))
8657 (eq N 1)
8658 (looking-at "[^|\n]* +|"))
8659 (let (org-table-may-need-update)
8660 (goto-char (1- (match-end 0)))
8661 (delete-backward-char 1)
8662 (goto-char (match-beginning 0))
8663 (self-insert-command N))
8664 (setq org-table-may-need-update t)
8665 (let (orgtbl-mode)
8666 (call-interactively (key-binding (vector last-input-event))))))
8668 (defun org-force-self-insert (N)
8669 "Needed to enforce self-insert under remapping."
8670 (interactive "p")
8671 (self-insert-command N))
8673 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
8674 "Regula expression matching exponentials as produced by calc.")
8676 (defvar org-table-clean-did-remove-column-1 nil)
8678 (defun orgtbl-send-table (&optional maybe)
8679 "Send a tranformed version of this table to the receiver position.
8680 With argument MAYBE, fail quietly if no transformation is defined for
8681 this table."
8682 (interactive)
8683 (catch 'exit
8684 (unless (org-at-table-p) (error "Not at a table"))
8685 ;; when non-interactive, we assume align has just happened.
8686 (when (interactive-p) (org-table-align))
8687 (save-excursion
8688 (goto-char (org-table-begin))
8689 (beginning-of-line 0)
8690 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
8691 (if maybe
8692 (throw 'exit nil)
8693 (error "Don't know how to transform this table."))))
8694 (let* ((name (match-string 1))
8696 (transform (intern (match-string 2)))
8697 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
8698 (skip (plist-get params :skip))
8699 (skipcols (plist-get params :skipcols))
8700 (txt (buffer-substring-no-properties
8701 (org-table-begin) (org-table-end)))
8702 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
8703 (lines (org-table-clean-before-export lines))
8704 (i0 (if org-table-clean-did-remove-column-1 2 1))
8705 (table (mapcar
8706 (lambda (x)
8707 (if (string-match org-table-hline-regexp x)
8708 'hline
8709 (org-remove-by-index
8710 (org-split-string (org-trim x) "\\s-*|\\s-*")
8711 skipcols i0)))
8712 lines))
8713 (fun (if (= i0 2) 'cdr 'identity))
8714 (org-table-last-alignment
8715 (org-remove-by-index (funcall fun org-table-last-alignment)
8716 skipcols i0))
8717 (org-table-last-column-widths
8718 (org-remove-by-index (funcall fun org-table-last-column-widths)
8719 skipcols i0)))
8721 (unless (fboundp transform)
8722 (error "No such transformation function %s" transform))
8723 (setq txt (funcall transform table params))
8724 ;; Find the insertion place
8725 (save-excursion
8726 (goto-char (point-min))
8727 (unless (re-search-forward
8728 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
8729 (error "Don't know where to insert translated table"))
8730 (goto-char (match-beginning 0))
8731 (beginning-of-line 2)
8732 (setq beg (point))
8733 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
8734 (error "Cannot find end of insertion region"))
8735 (beginning-of-line 1)
8736 (delete-region beg (point))
8737 (goto-char beg)
8738 (insert txt "\n"))
8739 (message "Table converted and installed at receiver location"))))
8741 (defun org-remove-by-index (list indices &optional i0)
8742 "Remove the elements in LIST with indices in INDICES.
8743 First element has index 0, or I0 if given."
8744 (if (not indices)
8745 list
8746 (if (integerp indices) (setq indices (list indices)))
8747 (setq i0 (1- (or i0 0)))
8748 (delq :rm (mapcar (lambda (x)
8749 (setq i0 (1+ i0))
8750 (if (memq i0 indices) :rm x))
8751 list))))
8753 (defun orgtbl-toggle-comment ()
8754 "Comment or uncomment the orgtbl at point."
8755 (interactive)
8756 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
8757 (re2 (concat "^" orgtbl-line-start-regexp))
8758 (commented (save-excursion (beginning-of-line 1)
8759 (cond ((looking-at re1) t)
8760 ((looking-at re2) nil)
8761 (t (error "Not at an org table")))))
8762 (re (if commented re1 re2))
8763 beg end)
8764 (save-excursion
8765 (beginning-of-line 1)
8766 (while (looking-at re) (beginning-of-line 0))
8767 (beginning-of-line 2)
8768 (setq beg (point))
8769 (while (looking-at re) (beginning-of-line 2))
8770 (setq end (point)))
8771 (comment-region beg end (if commented '(4) nil))))
8773 (defun orgtbl-insert-radio-table ()
8774 "Insert a radio table template appropriate for this major mode."
8775 (interactive)
8776 (let* ((e (assq major-mode orgtbl-radio-table-templates))
8777 (txt (nth 1 e))
8778 name pos)
8779 (unless e (error "No radio table setup defined for %s" major-mode))
8780 (setq name (read-string "Table name: "))
8781 (while (string-match "%n" txt)
8782 (setq txt (replace-match name t t txt)))
8783 (or (bolp) (insert "\n"))
8784 (setq pos (point))
8785 (insert txt)
8786 (goto-char pos)))
8788 (defun org-get-param (params header i sym &optional hsym)
8789 "Get parameter value for symbol SYM.
8790 If this is a header line, actually get the value for the symbol with an
8791 additional \"h\" inserted after the colon.
8792 If the value is a protperty list, get the element for the current column.
8793 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
8794 (let ((val (plist-get params sym)))
8795 (and hsym header (setq val (or (plist-get params hsym) val)))
8796 (if (consp val) (plist-get val i) val)))
8798 (defun orgtbl-to-generic (table params)
8799 "Convert the orgtbl-mode TABLE to some other format.
8800 This generic routine can be used for many standard cases.
8801 TABLE is a list, each entry either the symbol `hline' for a horizontal
8802 separator line, or a list of fields for that line.
8803 PARAMS is a property list of parameters that can influence the conversion.
8804 For the generic converter, some parameters are obligatory: You need to
8805 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
8806 :splice, you must have :tstart and :tend.
8808 Valid parameters are
8810 :tstart String to start the table. Ignored when :splice is t.
8811 :tend String to end the table. Ignored when :splice is t.
8813 :splice When set to t, return only table body lines, don't wrap
8814 them into :tstart and :tend. Default is nil.
8816 :hline String to be inserted on horizontal separation lines.
8817 May be nil to ignore hlines.
8819 :lstart String to start a new table line.
8820 :lend String to end a table line
8821 :sep Separator between two fields
8822 :lfmt Format for entire line, with enough %s to capture all fields.
8823 If this is present, :lstart, :lend, and :sep are ignored.
8824 :fmt A format to be used to wrap the field, should contain
8825 %s for the original field value. For example, to wrap
8826 everything in dollars, you could use :fmt \"$%s$\".
8827 This may also be a property list with column numbers and
8828 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
8830 :hlstart :hlend :hlsep :hlfmt :hfmt
8831 Same as above, specific for the header lines in the table.
8832 All lines before the first hline are treated as header.
8833 If any of these is not present, the data line value is used.
8835 :efmt Use this format to print numbers with exponentials.
8836 The format should have %s twice for inserting mantissa
8837 and exponent, for example \"%s\\\\times10^{%s}\". This
8838 may also be a property list with column numbers and
8839 formats. :fmt will still be applied after :efmt.
8841 In addition to this, the parameters :skip and :skipcols are always handled
8842 directly by `orgtbl-send-table'. See manual."
8843 (interactive)
8844 (let* ((p params)
8845 (splicep (plist-get p :splice))
8846 (hline (plist-get p :hline))
8847 rtn line i fm efm lfmt h)
8849 ;; Do we have a header?
8850 (if (and (not splicep) (listp (car table)) (memq 'hline table))
8851 (setq h t))
8853 ;; Put header
8854 (unless splicep
8855 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
8857 ;; Now loop over all lines
8858 (while (setq line (pop table))
8859 (if (eq line 'hline)
8860 ;; A horizontal separator line
8861 (progn (if hline (push hline rtn))
8862 (setq h nil)) ; no longer in header
8863 ;; A normal line. Convert the fields, push line onto the result list
8864 (setq i 0)
8865 (setq line
8866 (mapcar
8867 (lambda (f)
8868 (setq i (1+ i)
8869 fm (org-get-param p h i :fmt :hfmt)
8870 efm (org-get-param p h i :efmt))
8871 (if (and efm (string-match orgtbl-exp-regexp f))
8872 (setq f (format
8873 efm (match-string 1 f) (match-string 2 f))))
8874 (if fm (setq f (format fm f)))
8876 line))
8877 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
8878 (push (apply 'format lfmt line) rtn)
8879 (push (concat
8880 (org-get-param p h i :lstart :hlstart)
8881 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
8882 (org-get-param p h i :lend :hlend))
8883 rtn))))
8885 (unless splicep
8886 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
8888 (mapconcat 'identity (nreverse rtn) "\n")))
8890 (defun orgtbl-to-latex (table params)
8891 "Convert the orgtbl-mode TABLE to LaTeX.
8892 TABLE is a list, each entry either the symbol `hline' for a horizontal
8893 separator line, or a list of fields for that line.
8894 PARAMS is a property list of parameters that can influence the conversion.
8895 Supports all parameters from `orgtbl-to-generic'. Most important for
8896 LaTeX are:
8898 :splice When set to t, return only table body lines, don't wrap
8899 them into a tabular environment. Default is nil.
8901 :fmt A format to be used to wrap the field, should contain %s for the
8902 original field value. For example, to wrap everything in dollars,
8903 use :fmt \"$%s$\". This may also be a property list with column
8904 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
8906 :efmt Format for transforming numbers with exponentials. The format
8907 should have %s twice for inserting mantissa and exponent, for
8908 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
8909 This may also be a property list with column numbers and formats.
8911 The general parameters :skip and :skipcols have already been applied when
8912 this function is called."
8913 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
8914 org-table-last-alignment ""))
8915 (params2
8916 (list
8917 :tstart (concat "\\begin{tabular}{" alignment "}")
8918 :tend "\\end{tabular}"
8919 :lstart "" :lend " \\\\" :sep " & "
8920 :efmt "%s\\,(%s)" :hline "\\hline")))
8921 (orgtbl-to-generic table (org-combine-plists params2 params))))
8923 (defun orgtbl-to-html (table params)
8924 "Convert the orgtbl-mode TABLE to LaTeX.
8925 TABLE is a list, each entry either the symbol `hline' for a horizontal
8926 separator line, or a list of fields for that line.
8927 PARAMS is a property list of parameters that can influence the conversion.
8928 Currently this function recognizes the following parameters:
8930 :splice When set to t, return only table body lines, don't wrap
8931 them into a <table> environment. Default is nil.
8933 The general parameters :skip and :skipcols have already been applied when
8934 this function is called. The function does *not* use `orgtbl-to-generic',
8935 so you cannot specify parameters for it."
8936 (let* ((splicep (plist-get params :splice))
8937 html)
8938 ;; Just call the formatter we already have
8939 ;; We need to make text lines for it, so put the fields back together.
8940 (setq html (org-format-org-table-html
8941 (mapcar
8942 (lambda (x)
8943 (if (eq x 'hline)
8944 "|----+----|"
8945 (concat "| " (mapconcat 'identity x " | ") " |")))
8946 table)
8947 splicep))
8948 (if (string-match "\n+\\'" html)
8949 (setq html (replace-match "" t t html)))
8950 html))
8952 (defun orgtbl-to-texinfo (table params)
8953 "Convert the orgtbl-mode TABLE to TeXInfo.
8954 TABLE is a list, each entry either the symbol `hline' for a horizontal
8955 separator line, or a list of fields for that line.
8956 PARAMS is a property list of parameters that can influence the conversion.
8957 Supports all parameters from `orgtbl-to-generic'. Most important for
8958 TeXInfo are:
8960 :splice nil/t When set to t, return only table body lines, don't wrap
8961 them into a multitable environment. Default is nil.
8963 :fmt fmt A format to be used to wrap the field, should contain
8964 %s for the original field value. For example, to wrap
8965 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
8966 This may also be a property list with column numbers and
8967 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
8969 :cf \"f1 f2..\" The column fractions for the table. Bye default these
8970 are computed automatically from the width of the columns
8971 under org-mode.
8973 The general parameters :skip and :skipcols have already been applied when
8974 this function is called."
8975 (let* ((total (float (apply '+ org-table-last-column-widths)))
8976 (colfrac (or (plist-get params :cf)
8977 (mapconcat
8978 (lambda (x) (format "%.3f" (/ (float x) total)))
8979 org-table-last-column-widths " ")))
8980 (params2
8981 (list
8982 :tstart (concat "@multitable @columnfractions " colfrac)
8983 :tend "@end multitable"
8984 :lstart "@item " :lend "" :sep " @tab "
8985 :hlstart "@headitem ")))
8986 (orgtbl-to-generic table (org-combine-plists params2 params))))
8988 ;;;; Link Stuff
8990 ;;; Link abbreviations
8992 (defun org-link-expand-abbrev (link)
8993 "Apply replacements as defined in `org-link-abbrev-alist."
8994 (if (string-match "^\\([a-zA-Z]+\\)\\(::?\\(.*\\)\\)?$" link)
8995 (let* ((key (match-string 1 link))
8996 (as (or (assoc key org-link-abbrev-alist-local)
8997 (assoc key org-link-abbrev-alist)))
8998 (tag (and (match-end 2) (match-string 3 link)))
8999 rpl)
9000 (if (not as)
9001 link
9002 (setq rpl (cdr as))
9003 (cond
9004 ((symbolp rpl) (funcall rpl tag))
9005 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9006 (t (concat rpl tag)))))
9007 link))
9009 ;;; Storing and inserting links
9011 (defvar org-insert-link-history nil
9012 "Minibuffer history for links inserted with `org-insert-link'.")
9014 (defvar org-stored-links nil
9015 "Contains the links stored with `org-store-link'.")
9017 (defvar org-store-link-plist nil
9018 "Plist with info about the most recently link created with `org-store-link'.")
9020 ;;;###autoload
9021 (defun org-store-link (arg)
9022 "\\<org-mode-map>Store an org-link to the current location.
9023 This link can later be inserted into an org-buffer with
9024 \\[org-insert-link].
9025 For some link types, a prefix arg is interpreted:
9026 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9027 For file links, arg negates `org-context-in-file-links'."
9028 (interactive "P")
9029 (setq org-store-link-plist nil) ; reset
9030 (let (link cpltxt desc description search txt)
9031 (cond
9033 ((eq major-mode 'bbdb-mode)
9034 (let ((name (bbdb-record-name (bbdb-current-record)))
9035 (company (bbdb-record-company (bbdb-current-record))))
9036 (setq cpltxt (concat "bbdb:" (or name company))
9037 link (org-make-link cpltxt))
9038 (org-store-link-props :type "bbdb" :name name :company company)))
9040 ((eq major-mode 'Info-mode)
9041 (setq link (org-make-link "info:"
9042 (file-name-nondirectory Info-current-file)
9043 ":" Info-current-node))
9044 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9045 ":" Info-current-node))
9046 (org-store-link-props :type "info" :file Info-current-file
9047 :node Info-current-node))
9049 ((eq major-mode 'calendar-mode)
9050 (let ((cd (calendar-cursor-to-date)))
9051 (setq link
9052 (format-time-string
9053 (car org-time-stamp-formats)
9054 (apply 'encode-time
9055 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9056 nil nil nil))))
9057 (org-store-link-props :type "calendar" :date cd)))
9059 ((or (eq major-mode 'vm-summary-mode)
9060 (eq major-mode 'vm-presentation-mode))
9061 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9062 (vm-follow-summary-cursor)
9063 (save-excursion
9064 (vm-select-folder-buffer)
9065 (let* ((message (car vm-message-pointer))
9066 (folder buffer-file-name)
9067 (subject (vm-su-subject message))
9068 (to (vm-get-header-contents message "To"))
9069 (from (vm-get-header-contents message "From"))
9070 (message-id (vm-su-message-id message)))
9071 (org-store-link-props :type "vm" :from from :to to :subject subject
9072 :message-id message-id)
9073 (setq message-id (org-remove-angle-brackets message-id))
9074 (setq folder (abbreviate-file-name folder))
9075 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9076 folder)
9077 (setq folder (replace-match "" t t folder)))
9078 (setq cpltxt (org-email-link-description))
9079 (setq link (org-make-link "vm:" folder "#" message-id)))))
9081 ((eq major-mode 'wl-summary-mode)
9082 (let* ((msgnum (wl-summary-message-number))
9083 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9084 msgnum 'message-id))
9085 (wl-message-entity
9086 (if (fboundp 'elmo-message-entity)
9087 (elmo-message-entity
9088 wl-summary-buffer-elmo-folder msgnum)
9089 (elmo-msgdb-overview-get-entity
9090 msgnum (wl-summary-buffer-msgdb))))
9091 (from (wl-summary-line-from))
9092 (to (car (elmo-message-entity-field wl-message-entity 'to)))
9093 (subject (let (wl-thr-indent-string wl-parent-message-entity)
9094 (wl-summary-line-subject))))
9095 (org-store-link-props :type "wl" :from from :to to
9096 :subject subject :message-id message-id)
9097 (setq message-id (org-remove-angle-brackets message-id))
9098 (setq cpltxt (org-email-link-description))
9099 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9100 "#" message-id))))
9102 ((or (equal major-mode 'mh-folder-mode)
9103 (equal major-mode 'mh-show-mode))
9104 (let ((from (org-mhe-get-header "From:"))
9105 (to (org-mhe-get-header "To:"))
9106 (message-id (org-mhe-get-header "Message-Id:"))
9107 (subject (org-mhe-get-header "Subject:")))
9108 (org-store-link-props :type "mh" :from from :to to
9109 :subject subject :message-id message-id)
9110 (setq cpltxt (org-email-link-description))
9111 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9112 (org-remove-angle-brackets message-id)))))
9114 ((eq major-mode 'rmail-mode)
9115 (save-excursion
9116 (save-restriction
9117 (rmail-narrow-to-non-pruned-header)
9118 (let ((folder buffer-file-name)
9119 (message-id (mail-fetch-field "message-id"))
9120 (from (mail-fetch-field "from"))
9121 (to (mail-fetch-field "to"))
9122 (subject (mail-fetch-field "subject")))
9123 (org-store-link-props
9124 :type "rmail" :from from :to to
9125 :subject subject :message-id message-id)
9126 (setq message-id (org-remove-angle-brackets message-id))
9127 (setq cpltxt (org-email-link-description))
9128 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9130 ((eq major-mode 'gnus-group-mode)
9131 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9132 (gnus-group-group-name)) ; version
9133 ((fboundp 'gnus-group-name)
9134 (gnus-group-name))
9135 (t "???"))))
9136 (unless group (error "Not on a group"))
9137 (org-store-link-props :type "gnus" :group group)
9138 (setq cpltxt (concat
9139 (if (org-xor arg org-usenet-links-prefer-google)
9140 "http://groups.google.com/groups?group="
9141 "gnus:")
9142 group)
9143 link (org-make-link cpltxt))))
9145 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9146 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9147 (let* ((group gnus-newsgroup-name)
9148 (article (gnus-summary-article-number))
9149 (header (gnus-summary-article-header article))
9150 (from (mail-header-from header))
9151 (message-id (mail-header-id header))
9152 (date (mail-header-date header))
9153 (subject (gnus-summary-subject-string)))
9154 (org-store-link-props :type "gnus" :from from :subject subject
9155 :message-id message-id :group group)
9156 (setq cpltxt (org-email-link-description))
9157 (if (org-xor arg org-usenet-links-prefer-google)
9158 (setq link
9159 (concat
9160 cpltxt "\n "
9161 (format "http://groups.google.com/groups?as_umsgid=%s"
9162 (org-fixup-message-id-for-http message-id))))
9163 (setq link (org-make-link "gnus:" group
9164 "#" (number-to-string article))))))
9166 ((eq major-mode 'w3-mode)
9167 (setq cpltxt (url-view-url t)
9168 link (org-make-link cpltxt))
9169 (org-store-link-props :type "w3" :url (url-view-url t)))
9171 ((eq major-mode 'w3m-mode)
9172 (setq cpltxt (or w3m-current-title w3m-current-url)
9173 link (org-make-link w3m-current-url))
9174 (org-store-link-props :type "w3m" :url (url-view-url t)))
9176 ((setq search (run-hook-with-args-until-success
9177 'org-create-file-search-functions))
9178 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9179 "::" search))
9180 (setq cpltxt (or description link)))
9182 ((eq major-mode 'image-mode)
9183 (setq cpltxt (concat "file:"
9184 (abbreviate-file-name buffer-file-name))
9185 link (org-make-link cpltxt))
9186 (org-store-link-props :type "image" :file buffer-file-name))
9188 ((eq major-mode 'dired-mode)
9189 ;; link to the file in the current line
9190 (setq cpltxt (concat "file:"
9191 (abbreviate-file-name
9192 (expand-file-name
9193 (dired-get-filename nil t))))
9194 link (org-make-link cpltxt)))
9196 ((and buffer-file-name (org-mode-p))
9197 ;; Just link to current headline
9198 (setq cpltxt (concat "file:"
9199 (abbreviate-file-name buffer-file-name)))
9200 ;; Add a context search string
9201 (when (org-xor org-context-in-file-links arg)
9202 ;; Check if we are on a target
9203 (if (org-in-regexp "<<\\(.*?\\)>>")
9204 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9205 (setq txt (cond
9206 ((org-on-heading-p) nil)
9207 ((org-region-active-p)
9208 (buffer-substring (region-beginning) (region-end)))
9209 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9210 (when (or (null txt) (string-match "\\S-" txt))
9211 (setq cpltxt
9212 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9213 desc "NONE"))))
9214 (if (string-match "::\\'" cpltxt)
9215 (setq cpltxt (substring cpltxt 0 -2)))
9216 (setq link (org-make-link cpltxt)))
9218 (buffer-file-name
9219 ;; Just link to this file here.
9220 (setq cpltxt (concat "file:"
9221 (abbreviate-file-name buffer-file-name)))
9222 ;; Add a context string
9223 (when (org-xor org-context-in-file-links arg)
9224 (setq txt (if (org-region-active-p)
9225 (buffer-substring (region-beginning) (region-end))
9226 (buffer-substring (point-at-bol) (point-at-eol))))
9227 ;; Only use search option if there is some text.
9228 (when (string-match "\\S-" txt)
9229 (setq cpltxt
9230 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9231 desc "NONE")))
9232 (setq link (org-make-link cpltxt)))
9234 ((interactive-p)
9235 (error "Cannot link to a buffer which is not visiting a file"))
9237 (t (setq link nil)))
9239 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9240 (setq link (or link cpltxt)
9241 desc (or desc cpltxt))
9242 (if (equal desc "NONE") (setq desc nil))
9244 (if (and (interactive-p) link)
9245 (progn
9246 (setq org-stored-links
9247 (cons (list cpltxt link desc) org-stored-links))
9248 (message "Stored: %s" (or cpltxt link)))
9249 (org-make-link-string link desc))))
9251 (defun org-store-link-props (&rest plist)
9252 "Store link properties, extract names and addresses."
9253 (let (x adr)
9254 (when (setq x (plist-get plist :from))
9255 (setq adr (mail-extract-address-components x))
9256 (plist-put plist :fromname (car adr))
9257 (plist-put plist :fromaddress (nth 1 adr)))
9258 (when (setq x (plist-get plist :to))
9259 (setq adr (mail-extract-address-components x))
9260 (plist-put plist :toname (car adr))
9261 (plist-put plist :toaddress (nth 1 adr))))
9262 (let ((from (plist-get plist :from))
9263 (to (plist-get plist :to)))
9264 (when (and from to org-from-is-user-regexp)
9265 (plist-put plist :fromto
9266 (if (string-match org-from-is-user-regexp from)
9267 (concat "to %t")
9268 (concat "from %f")))))
9269 (setq org-store-link-plist plist))
9271 (defun org-email-link-description (&optional fmt)
9272 "Return the description part of an email link.
9273 This takes information from `org-store-link-plist' and formats it
9274 according to FMT (default from `org-email-link-description-format')."
9275 (setq fmt (or fmt org-email-link-description-format))
9276 (let* ((p org-store-link-plist)
9277 (to (plist-get p :toaddress))
9278 (from (plist-get p :fromaddress))
9279 (table
9280 (list
9281 (cons "%c" (plist-get p :fromto))
9282 (cons "%F" (plist-get p :from))
9283 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9284 (cons "%T" (plist-get p :to))
9285 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9286 (cons "%s" (plist-get p :subject))
9287 (cons "%m" (plist-get p :message-id)))))
9288 (when (string-match "%c" fmt)
9289 ;; Check if the user wrote this message
9290 (if (and org-from-is-user-regexp from to
9291 (save-match-data (string-match org-from-is-user-regexp from)))
9292 (setq fmt (replace-match "to %t" t t fmt))
9293 (setq fmt (replace-match "from %f" t t fmt))))
9294 (org-replace-escapes fmt table)))
9296 (defun org-make-org-heading-search-string (&optional string heading)
9297 "Make search string for STRING or current headline."
9298 (interactive)
9299 (let ((s (or string (org-get-heading))))
9300 (unless (and string (not heading))
9301 ;; We are using a headline, clean up garbage in there.
9302 (if (string-match org-todo-regexp s)
9303 (setq s (replace-match "" t t s)))
9304 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9305 (setq s (replace-match "" t t s)))
9306 (setq s (org-trim s))
9307 (if (string-match (concat "^\\(" org-quote-string "\\|"
9308 org-comment-string "\\)") s)
9309 (setq s (replace-match "" t t s)))
9310 (while (string-match org-ts-regexp s)
9311 (setq s (replace-match "" t t s))))
9312 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9313 (setq s (replace-match " " t t s)))
9314 (or string (setq s (concat "*" s))) ; Add * for headlines
9315 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9317 (defun org-make-link (&rest strings)
9318 "Concatenate STRINGS, format resulting string with `org-link-format'."
9319 (apply 'concat strings))
9321 (defun org-make-link-string (link &optional description)
9322 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9323 (when (stringp description)
9324 ;; Remove brackets from the description, they are fatal.
9325 (while (string-match "\\[\\|\\]" description)
9326 (setq description (replace-match "" t t description))))
9327 (when (equal (org-link-escape link) description)
9328 ;; No description needed, it is identical
9329 (setq description nil))
9330 (when (and (not description)
9331 (not (equal link (org-link-escape link))))
9332 (setq description link))
9333 (concat "[[" (org-link-escape link) "]"
9334 (if description (concat "[" description "]") "")
9335 "]"))
9337 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9338 "Association list of escapes for some characters problematic in links.")
9340 (defun org-link-escape (text)
9341 "Escape charaters in TEXT that are problematic for links."
9342 (when text
9343 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9344 org-link-escape-chars "\\|")))
9345 (while (string-match re text)
9346 (setq text
9347 (replace-match
9348 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9349 t t text)))
9350 text)))
9352 (defun org-link-unescape (text)
9353 "Reverse the action of `org-link-escape'."
9354 (when text
9355 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9356 org-link-escape-chars "\\|")))
9357 (while (string-match re text)
9358 (setq text
9359 (replace-match
9360 (car (rassoc (match-string 0 text) org-link-escape-chars))
9361 t t text)))
9362 text)))
9364 (defun org-xor (a b)
9365 "Exclusive or."
9366 (if a (not b) b))
9368 (defun org-get-header (header)
9369 "Find a header field in the current buffer."
9370 (save-excursion
9371 (goto-char (point-min))
9372 (let ((case-fold-search t) s)
9373 (cond
9374 ((eq header 'from)
9375 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
9376 (setq s (match-string 1)))
9377 (while (string-match "\"" s)
9378 (setq s (replace-match "" t t s)))
9379 (if (string-match "[<(].*" s)
9380 (setq s (replace-match "" t t s))))
9381 ((eq header 'message-id)
9382 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
9383 (setq s (match-string 1))))
9384 ((eq header 'subject)
9385 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
9386 (setq s (match-string 1)))))
9387 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
9388 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
9389 s)))
9392 (defun org-fixup-message-id-for-http (s)
9393 "Replace special characters in a message id, so it can be used in an http query."
9394 (while (string-match "<" s)
9395 (setq s (replace-match "%3C" t t s)))
9396 (while (string-match ">" s)
9397 (setq s (replace-match "%3E" t t s)))
9398 (while (string-match "@" s)
9399 (setq s (replace-match "%40" t t s)))
9402 (defun org-insert-link (&optional complete-file)
9403 "Insert a link. At the prompt, enter the link.
9405 Completion can be used to select a link previously stored with
9406 `org-store-link'. When the empty string is entered (i.e. if you just
9407 press RET at the prompt), the link defaults to the most recently
9408 stored link. As SPC triggers completion in the minibuffer, you need to
9409 use M-SPC or C-q SPC to force the insertion of a space character.
9411 You will also be prompted for a description, and if one is given, it will
9412 be displayed in the buffer instead of the link.
9414 If there is already a link at point, this command will allow you to edit link
9415 and description parts.
9417 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
9418 selected using completion. The path to the file will be relative to
9419 the current directory if the file is in the current directory or a
9420 subdirectory. Otherwise, the link will be the absolute path as
9421 completed in the minibuffer (i.e. normally ~/path/to/file).
9423 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
9424 is in the current directory or below.
9425 With three \\[universal-argument] prefixes, negate the meaning of
9426 `org-keep-stored-link-after-insertion'."
9427 (interactive "P")
9428 (let ((region (if (org-region-active-p)
9429 (prog1 (buffer-substring (region-beginning) (region-end))
9430 (delete-region (region-beginning) (region-end)))))
9431 tmphist ; byte-compile incorrectly complains about this
9432 link desc entry remove file)
9433 (cond
9434 ((org-in-regexp org-bracket-link-regexp 1)
9435 ;; We do have a link at point, and we are going to edit it.
9436 (setq remove (list (match-beginning 0) (match-end 0)))
9437 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9438 (setq link (read-string "Link: "
9439 (org-link-unescape
9440 (org-match-string-no-properties 1)))))
9441 ((or (org-in-regexp org-angle-link-re)
9442 (org-in-regexp org-plain-link-re))
9443 ;; Convert to bracket link
9444 (setq remove (list (match-beginning 0) (match-end 0))
9445 link (read-string "Link: "
9446 (org-remove-angle-brackets (match-string 0)))))
9447 ((equal complete-file '(4))
9448 ;; Completing read for file names.
9449 (setq file (read-file-name "File: "))
9450 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9451 (pwd1 (file-name-as-directory (abbreviate-file-name
9452 (expand-file-name ".")))))
9453 (cond
9454 ((equal complete-file '(16))
9455 (setq link (org-make-link
9456 "file:"
9457 (abbreviate-file-name (expand-file-name file)))))
9458 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9459 (setq link (org-make-link "file:" (match-string 1 file))))
9460 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9461 (expand-file-name file))
9462 (setq link (org-make-link
9463 "file:" (match-string 1 (expand-file-name file)))))
9464 (t (setq link (org-make-link "file:" file))))))
9466 ;; Read link, with completion for stored links.
9467 ;; Fake a link history
9468 (setq tmphist (append (mapcar 'car org-stored-links)
9469 org-insert-link-history))
9470 (setq link (org-completing-read
9471 "Link: " org-stored-links nil nil nil
9472 'tmphist
9473 (or (car (car org-stored-links)))))
9474 (setq entry (assoc link org-stored-links))
9475 (or entry (push link org-insert-link-history))
9476 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9477 (not org-keep-stored-link-after-insertion))
9478 (setq org-stored-links (delq (assoc link org-stored-links)
9479 org-stored-links)))
9480 (setq link (if entry (nth 1 entry) link)
9481 desc (or region desc (nth 2 entry)))))
9483 (if (string-match org-plain-link-re link)
9484 ;; URL-like link, normalize the use of angular brackets.
9485 (setq link (org-make-link (org-remove-angle-brackets link))))
9487 ;; Check if we are linking to the current file with a search option
9488 ;; If yes, simplify the link by using only the search option.
9489 (when (and buffer-file-name
9490 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
9491 (let* ((path (match-string 1 link))
9492 (case-fold-search nil)
9493 (search (match-string 2 link)))
9494 (save-match-data
9495 (if (equal (file-truename buffer-file-name) (file-truename path))
9496 ;; We are linking to this same file, with a search option
9497 (setq link search)))))
9499 ;; Check if we can/should use a relative path. If yes, simplify the link
9500 (when (string-match "\\<file:\\(.*\\)" link)
9501 (let* ((path (match-string 1 link))
9502 (case-fold-search nil))
9503 (cond
9504 ((eq org-link-file-path-type 'absolute)
9505 (setq path (abbreviate-file-name (expand-file-name path))))
9506 ((eq org-link-file-path-type 'noabbrev)
9507 (setq path (expand-file-name path)))
9508 ((eq org-link-file-path-type 'relative)
9509 (setq path (file-relative-name path)))
9511 (save-match-data
9512 (if (string-match (concat "^" (regexp-quote
9513 (file-name-as-directory
9514 (expand-file-name "."))))
9515 (expand-file-name path))
9516 ;; We are linking a file with relative path name.
9517 (setq path (substring (expand-file-name path)
9518 (match-end 0)))))))
9519 (setq link (concat "file:" path))))
9521 (setq desc (read-string "Description: " desc))
9522 (unless (string-match "\\S-" desc) (setq desc nil))
9523 (if remove (apply 'delete-region remove))
9524 (insert (org-make-link-string link desc))))
9526 (defun org-completing-read (&rest args)
9527 (let ((minibuffer-local-completion-map
9528 (copy-keymap minibuffer-local-completion-map)))
9529 (define-key minibuffer-local-completion-map " " 'self-insert-command)
9530 (apply 'completing-read args)))
9532 ;;; Opening/following a link
9533 (defvar org-link-search-failed nil)
9535 (defun org-next-link ()
9536 "Move forward to the next link.
9537 If the link is in hidden text, expose it."
9538 (interactive)
9539 (when (and org-link-search-failed (eq this-command last-command))
9540 (goto-char (point-min))
9541 (message "Link search wrapped back to beginning of buffer"))
9542 (setq org-link-search-failed nil)
9543 (let* ((pos (point))
9544 (ct (org-context))
9545 (a (assoc :link ct)))
9546 (if a (goto-char (nth 2 a)))
9547 (if (re-search-forward org-any-link-re nil t)
9548 (progn
9549 (goto-char (match-beginning 0))
9550 (if (org-invisible-p) (org-show-context)))
9551 (goto-char pos)
9552 (setq org-link-search-failed t)
9553 (error "No further link found"))))
9555 (defun org-previous-link ()
9556 "Move backward to the previous link.
9557 If the link is in hidden text, expose it."
9558 (interactive)
9559 (when (and org-link-search-failed (eq this-command last-command))
9560 (goto-char (point-max))
9561 (message "Link search wrapped back to end of buffer"))
9562 (setq org-link-search-failed nil)
9563 (let* ((pos (point))
9564 (ct (org-context))
9565 (a (assoc :link ct)))
9566 (if a (goto-char (nth 1 a)))
9567 (if (re-search-backward org-any-link-re nil t)
9568 (progn
9569 (goto-char (match-beginning 0))
9570 (if (org-invisible-p) (org-show-context)))
9571 (goto-char pos)
9572 (setq org-link-search-failed t)
9573 (error "No further link found"))))
9575 (defun org-find-file-at-mouse (ev)
9576 "Open file link or URL at mouse."
9577 (interactive "e")
9578 (mouse-set-point ev)
9579 (org-open-at-point 'in-emacs))
9581 (defun org-open-at-mouse (ev)
9582 "Open file link or URL at mouse."
9583 (interactive "e")
9584 (mouse-set-point ev)
9585 (org-open-at-point))
9587 (defvar org-window-config-before-follow-link nil
9588 "The window configuration before following a link.
9589 This is saved in case the need arises to restore it.")
9591 (defvar org-open-link-marker (make-marker)
9592 "Marker pointing to the location where `org-open-at-point; was called.")
9594 (defun org-open-at-point (&optional in-emacs)
9595 "Open link at or after point.
9596 If there is no link at point, this function will search forward up to
9597 the end of the current subtree.
9598 Normally, files will be opened by an appropriate application. If the
9599 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9600 (interactive "P")
9601 (move-marker org-open-link-marker (point))
9602 (setq org-window-config-before-follow-link (current-window-configuration))
9603 (org-remove-occur-highlights nil nil t)
9604 (if (org-at-timestamp-p t)
9605 (org-follow-timestamp-link)
9606 (let (type path link line search (pos (point)))
9607 (catch 'match
9608 (save-excursion
9609 (skip-chars-forward "^]\n\r")
9610 (when (org-in-regexp org-bracket-link-regexp)
9611 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9612 (while (string-match " *\n *" link)
9613 (setq link (replace-match " " t t link)))
9614 (setq link (org-link-expand-abbrev link))
9615 (if (string-match org-link-re-with-space2 link)
9616 (setq type (match-string 1 link) path (match-string 2 link))
9617 (setq type "thisfile" path link))
9618 (throw 'match t)))
9620 (when (get-text-property (point) 'org-linked-text)
9621 (setq type "thisfile"
9622 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9623 (1+ (point)) (point))
9624 path (buffer-substring
9625 (previous-single-property-change pos 'org-linked-text)
9626 (next-single-property-change pos 'org-linked-text)))
9627 (throw 'match t))
9629 (save-excursion
9630 (when (or (org-in-regexp org-angle-link-re)
9631 (org-in-regexp org-plain-link-re))
9632 (setq type (match-string 1) path (match-string 2))
9633 (throw 'match t)))
9634 (save-excursion
9635 (when (org-in-regexp "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9636 (setq type "tags"
9637 path (match-string 1))
9638 (while (string-match ":" path)
9639 (setq path (replace-match "+" t t path)))
9640 (throw 'match t))))
9641 (unless path
9642 (error "No link found"))
9643 ;; Remove any trailing spaces in path
9644 (if (string-match " +\\'" path)
9645 (setq path (replace-match "" t t path)))
9647 (cond
9649 ((equal type "mailto")
9650 (let ((cmd (car org-link-mailto-program))
9651 (args (cdr org-link-mailto-program)) args1
9652 (address path) (subject "") a)
9653 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9654 (setq address (match-string 1 path)
9655 subject (org-link-escape (match-string 2 path))))
9656 (while args
9657 (cond
9658 ((not (stringp (car args))) (push (pop args) args1))
9659 (t (setq a (pop args))
9660 (if (string-match "%a" a)
9661 (setq a (replace-match address t t a)))
9662 (if (string-match "%s" a)
9663 (setq a (replace-match subject t t a)))
9664 (push a args1))))
9665 (apply cmd (nreverse args1))))
9667 ((member type '("http" "https" "ftp" "news"))
9668 (browse-url (concat type ":" path)))
9670 ((string= type "tags")
9671 (org-tags-view in-emacs path))
9672 ((string= type "thisfile")
9673 (if in-emacs
9674 (switch-to-buffer-other-window
9675 (org-get-buffer-for-internal-link (current-buffer)))
9676 (org-mark-ring-push))
9677 (org-link-search
9678 path
9679 (cond ((equal in-emacs '(4)) 'occur)
9680 ((equal in-emacs '(16)) 'org-occur)
9681 (t nil))
9682 pos))
9684 ((string= type "file")
9685 (if (string-match "::\\([0-9]+\\)\\'" path)
9686 (setq line (string-to-number (match-string 1 path))
9687 path (substring path 0 (match-beginning 0)))
9688 (if (string-match "::\\(.+\\)\\'" path)
9689 (setq search (match-string 1 path)
9690 path (substring path 0 (match-beginning 0)))))
9691 (org-open-file path in-emacs line search))
9693 ((string= type "news")
9694 (org-follow-gnus-link path))
9696 ((string= type "bbdb")
9697 (org-follow-bbdb-link path))
9699 ((string= type "info")
9700 (org-follow-info-link path))
9702 ((string= type "gnus")
9703 (let (group article)
9704 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9705 (error "Error in Gnus link"))
9706 (setq group (match-string 1 path)
9707 article (match-string 3 path))
9708 (org-follow-gnus-link group article)))
9710 ((string= type "vm")
9711 (let (folder article)
9712 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9713 (error "Error in VM link"))
9714 (setq folder (match-string 1 path)
9715 article (match-string 3 path))
9716 ;; in-emacs is the prefix arg, will be interpreted as read-only
9717 (org-follow-vm-link folder article in-emacs)))
9719 ((string= type "wl")
9720 (let (folder article)
9721 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9722 (error "Error in Wanderlust link"))
9723 (setq folder (match-string 1 path)
9724 article (match-string 3 path))
9725 (org-follow-wl-link folder article)))
9727 ((string= type "mhe")
9728 (let (folder article)
9729 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9730 (error "Error in MHE link"))
9731 (setq folder (match-string 1 path)
9732 article (match-string 3 path))
9733 (org-follow-mhe-link folder article)))
9735 ((string= type "rmail")
9736 (let (folder article)
9737 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9738 (error "Error in RMAIL link"))
9739 (setq folder (match-string 1 path)
9740 article (match-string 3 path))
9741 (org-follow-rmail-link folder article)))
9743 ((string= type "shell")
9744 (let ((cmd path))
9745 ;; FIXME: the following is only for backward compatibility
9746 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
9747 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
9748 (if (or (not org-confirm-shell-link-function)
9749 (funcall org-confirm-shell-link-function
9750 (format "Execute \"%s\" in shell? "
9751 (org-add-props cmd nil
9752 'face 'org-warning))))
9753 (progn
9754 (message "Executing %s" cmd)
9755 (shell-command cmd))
9756 (error "Abort"))))
9758 ((string= type "elisp")
9759 (let ((cmd path))
9760 (if (or (not org-confirm-elisp-link-function)
9761 (funcall org-confirm-elisp-link-function
9762 (format "Execute \"%s\" as elisp? "
9763 (org-add-props cmd nil
9764 'face 'org-warning))))
9765 (message "%s => %s" cmd (eval (read cmd)))
9766 (error "Abort"))))
9769 (browse-url-at-point)))))
9770 (move-marker org-open-link-marker nil))
9773 ;;; File search
9775 (defvar org-create-file-search-functions nil
9776 "List of functions to construct the right search string for a file link.
9777 These functions are called in turn with point at the location to
9778 which the link should point.
9780 A function in the hook should first test if it would like to
9781 handle this file type, for example by checking the major-mode or
9782 the file extension. If it decides not to handle this file, it
9783 should just return nil to give other functions a chance. If it
9784 does handle the file, it must return the search string to be used
9785 when following the link. The search string will be part of the
9786 file link, given after a double colon, and `org-open-at-point'
9787 will automatically search for it. If special measures must be
9788 taken to make the search successful, another function should be
9789 added to the companion hook `org-execute-file-search-functions',
9790 which see.
9792 A function in this hook may also use `setq' to set the variable
9793 `description' to provide a suggestion for the descriptive text to
9794 be used for this link when it gets inserted into an Org-mode
9795 buffer with \\[org-insert-link].")
9797 (defvar org-execute-file-search-functions nil
9798 "List of functions to execute a file search triggered by a link.
9800 Functions added to this hook must accept a single argument, the
9801 search string that was part of the file link, the part after the
9802 double colon. The function must first check if it would like to
9803 handle this search, for example by checking the major-mode or the
9804 file extension. If it decides not to handle this search, it
9805 should just return nil to give other functions a chance. If it
9806 does handle the search, it must return a non-nil value to keep
9807 other functions from trying.
9809 Each function can access the current prefix argument through the
9810 variable `current-prefix-argument'. Note that a single prefix is
9811 used to force opening a link in Emacs, so it may be good to only
9812 use a numeric or double prefix to guide the search function.
9814 In case this is needed, a function in this hook can also restore
9815 the window configuration before `org-open-at-point' was called using:
9817 (set-window-configuration org-window-config-before-follow-link)")
9819 (defun org-link-search (s &optional type avoid-pos)
9820 "Search for a link search option.
9821 If S is surrounded by forward slashes, it is interpreted as a
9822 regular expression. In org-mode files, this will create an `org-occur'
9823 sparse tree. In ordinary files, `occur' will be used to list matches.
9824 If the current buffer is in `dired-mode', grep will be used to search
9825 in all files. If AVOID-POS is given, ignore matches near that position."
9826 (let ((case-fold-search t)
9827 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9828 (pos (point))
9829 (pre "") (post "")
9830 words re0 re1 re2 re3 re4 re5 re2a reall)
9831 (cond
9832 ;; First check if there are any special
9833 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9834 ;; Now try the builtin stuff
9835 ((save-excursion
9836 (goto-char (point-min))
9837 (and
9838 (re-search-forward
9839 (concat "<<" (regexp-quote s0) ">>") nil t)
9840 (setq pos (match-beginning 0))))
9841 ;; There is an exact target for this
9842 (goto-char pos))
9843 ((string-match "^/\\(.*\\)/$" s)
9844 ;; A regular expression
9845 (cond
9846 ((org-mode-p)
9847 (org-occur (match-string 1 s)))
9848 ;;((eq major-mode 'dired-mode)
9849 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9850 (t (org-do-occur (match-string 1 s)))))
9852 ;; A normal search string
9853 (when (equal (string-to-char s) ?*)
9854 ;; Anchor on headlines, post may include tags.
9855 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9856 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9857 s (substring s 1)))
9858 (remove-text-properties
9859 0 (length s)
9860 '(face nil mouse-face nil keymap nil fontified nil) s)
9861 ;; Make a series of regular expressions to find a match
9862 (setq words (org-split-string s "[ \n\r\t]+")
9863 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9864 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9865 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9866 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9867 re1 (concat pre re2 post)
9868 re3 (concat pre re4 post)
9869 re5 (concat pre ".*" re4)
9870 re2 (concat pre re2)
9871 re2a (concat pre re2a)
9872 re4 (concat pre re4)
9873 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9874 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9875 re5 "\\)"
9877 (cond
9878 ((eq type 'org-occur) (org-occur reall))
9879 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9880 (t (goto-char (point-min))
9881 (if (or (org-search-not-self 1 re0 nil t)
9882 (org-search-not-self 1 re1 nil t)
9883 (org-search-not-self 1 re2 nil t)
9884 (org-search-not-self 1 re2a nil t)
9885 (org-search-not-self 1 re3 nil t)
9886 (org-search-not-self 1 re4 nil t)
9887 (org-search-not-self 1 re5 nil t)
9889 (goto-char (match-beginning 1))
9890 (goto-char pos)
9891 (error "No match")))))
9893 ;; Normal string-search
9894 (goto-char (point-min))
9895 (if (search-forward s nil t)
9896 (goto-char (match-beginning 0))
9897 (error "No match"))))
9898 (and (org-mode-p) (org-show-context 'link-search))))
9900 (defun org-search-not-self (group &rest args)
9901 "Execute `re-search-forward', but only accept matches that do not
9902 enclose the position of `org-open-link-marker'."
9903 (let ((m org-open-link-marker))
9904 (catch 'exit
9905 (while (apply 're-search-forward args)
9906 (goto-char (match-end group))
9907 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
9908 (> (match-beginning 0) (marker-position m))
9909 (< (match-end 0) (marker-position m)))
9910 (save-match-data
9911 (or (not (org-in-regexp org-bracket-link-analytic-regexp 1))
9912 (not (match-end 4)) ; no description
9913 (and (<= (match-beginning 4) (point))
9914 (>= (match-end 4) (point))))))
9915 (throw 'exit (point)))))))
9917 (defun org-get-buffer-for-internal-link (buffer)
9918 "Return a buffer to be used for displaying the link target of internal links."
9919 (cond
9920 ((not org-display-internal-link-with-indirect-buffer)
9921 buffer)
9922 ((string-match "(Clone)$" (buffer-name buffer))
9923 (message "Buffer is already a clone, not making another one")
9924 ;; we also do not modify visibility in this case
9925 buffer)
9926 (t ; make a new indirect buffer for displaying the link
9927 (let* ((bn (buffer-name buffer))
9928 (ibn (concat bn "(Clone)"))
9929 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9930 (with-current-buffer ib (org-overview))
9931 ib))))
9933 (defun org-do-occur (regexp &optional cleanup)
9934 "Call the Emacs command `occur'.
9935 If CLEANUP is non-nil, remove the printout of the regular expression
9936 in the *Occur* buffer. This is useful if the regex is long and not useful
9937 to read."
9938 (occur regexp)
9939 (when cleanup
9940 (let ((cwin (selected-window)) win beg end)
9941 (when (setq win (get-buffer-window "*Occur*"))
9942 (select-window win))
9943 (goto-char (point-min))
9944 (when (re-search-forward "match[a-z]+" nil t)
9945 (setq beg (match-end 0))
9946 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9947 (setq end (1- (match-beginning 0)))))
9948 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9949 (goto-char (point-min))
9950 (select-window cwin))))
9952 ;;; The mark ring for links jumps
9954 (defvar org-mark-ring nil
9955 "Mark ring for positions before jumps in Org-mode.")
9956 (defvar org-mark-ring-last-goto nil
9957 "Last position in the mark ring used to go back.")
9958 ;; Fill and close the ring
9959 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9960 (loop for i from 1 to org-mark-ring-length do
9961 (push (make-marker) org-mark-ring))
9962 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9963 org-mark-ring)
9965 (defun org-mark-ring-push (&optional pos buffer)
9966 "Put the current position or POS into the mark ring and rotate it."
9967 (interactive)
9968 (setq pos (or pos (point)))
9969 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9970 (move-marker (car org-mark-ring)
9971 (or pos (point))
9972 (or buffer (current-buffer)))
9973 (message
9974 (substitute-command-keys
9975 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9977 (defun org-mark-ring-goto (&optional n)
9978 "Jump to the previous position in the mark ring.
9979 With prefix arg N, jump back that many stored positions. When
9980 called several times in succession, walk through the entire ring.
9981 Org-mode commands jumping to a different position in the current file,
9982 or to another Org-mode file, automatically push the old position
9983 onto the ring."
9984 (interactive "p")
9985 (let (p m)
9986 (if (eq last-command this-command)
9987 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9988 (setq p org-mark-ring))
9989 (setq org-mark-ring-last-goto p)
9990 (setq m (car p))
9991 (switch-to-buffer (marker-buffer m))
9992 (goto-char m)
9993 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9995 (defun org-remove-angle-brackets (s)
9996 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9997 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9999 (defun org-add-angle-brackets (s)
10000 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10001 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10004 ;;; Following specific links
10006 (defun org-follow-timestamp-link ()
10007 (cond
10008 ((org-at-date-range-p t)
10009 (let ((org-agenda-start-on-weekday)
10010 (t1 (match-string 1))
10011 (t2 (match-string 2)))
10012 (setq t1 (time-to-days (org-time-string-to-time t1))
10013 t2 (time-to-days (org-time-string-to-time t2)))
10014 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10015 ((org-at-timestamp-p t)
10016 (org-agenda-list nil (time-to-days (org-time-string-to-time
10017 (substring (match-string 1) 0 10)))
10019 (t (error "This should not happen"))))
10022 (defun org-follow-bbdb-link (name)
10023 "Follow a BBDB link to NAME."
10024 (require 'bbdb)
10025 (let ((inhibit-redisplay (not debug-on-error))
10026 (bbdb-electric-p nil))
10027 (catch 'exit
10028 ;; Exact match on name
10029 (bbdb-name (concat "\\`" name "\\'") nil)
10030 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10031 ;; Exact match on name
10032 (bbdb-company (concat "\\`" name "\\'") nil)
10033 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10034 ;; Partial match on name
10035 (bbdb-name name nil)
10036 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10037 ;; Partial match on company
10038 (bbdb-company name nil)
10039 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10040 ;; General match including network address and notes
10041 (bbdb name nil)
10042 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10043 (delete-window (get-buffer-window "*BBDB*"))
10044 (error "No matching BBDB record")))))
10046 (defun org-follow-info-link (name)
10047 "Follow an info file & node link to NAME."
10048 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10049 (string-match "\\(.*\\)" name))
10050 (progn
10051 (require 'info)
10052 (if (match-string 2 name) ; If there isn't a node, choose "Top"
10053 (Info-find-node (match-string 1 name) (match-string 2 name))
10054 (Info-find-node (match-string 1 name) "Top")))
10055 (message (concat "Could not open: " name))))
10057 (defun org-follow-gnus-link (&optional group article)
10058 "Follow a Gnus link to GROUP and ARTICLE."
10059 (require 'gnus)
10060 (funcall (cdr (assq 'gnus org-link-frame-setup)))
10061 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10062 (cond ((and group article)
10063 (gnus-group-read-group 0 nil group)
10064 (gnus-summary-goto-article (string-to-number article) nil t))
10065 (group (gnus-group-jump-to-group group))))
10067 (defun org-follow-vm-link (&optional folder article readonly)
10068 "Follow a VM link to FOLDER and ARTICLE."
10069 (require 'vm)
10070 (setq article (org-add-angle-brackets article))
10071 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
10072 ;; ange-ftp or efs or tramp access
10073 (let ((user (or (match-string 1 folder) (user-login-name)))
10074 (host (match-string 2 folder))
10075 (file (match-string 3 folder)))
10076 (cond
10077 ((featurep 'tramp)
10078 ;; use tramp to access the file
10079 (if (featurep 'xemacs)
10080 (setq folder (format "[%s@%s]%s" user host file))
10081 (setq folder (format "/%s@%s:%s" user host file))))
10083 ;; use ange-ftp or efs
10084 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
10085 (setq folder (format "/%s@%s:%s" user host file))))))
10086 (when folder
10087 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
10088 (sit-for 0.1)
10089 (when article
10090 (vm-select-folder-buffer)
10091 (widen)
10092 (let ((case-fold-search t))
10093 (goto-char (point-min))
10094 (if (not (re-search-forward
10095 (concat "^" "message-id: *" (regexp-quote article))))
10096 (error "Could not find the specified message in this folder"))
10097 (vm-isearch-update)
10098 (vm-isearch-narrow)
10099 (vm-beginning-of-message)
10100 (vm-summarize)))))
10102 (defun org-follow-wl-link (folder article)
10103 "Follow a Wanderlust link to FOLDER and ARTICLE."
10104 (if (and (string= folder "%")
10105 article
10106 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
10107 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
10108 ;; Thus, we recompose folder and article ids.
10109 (setq folder (format "%s#%s" folder (match-string 1 article))
10110 article (match-string 3 article)))
10111 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
10112 (error "No such folder: %s" folder))
10113 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
10114 (and article
10115 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
10116 (wl-summary-redisplay)))
10118 (defun org-follow-rmail-link (folder article)
10119 "Follow an RMAIL link to FOLDER and ARTICLE."
10120 (setq article (org-add-angle-brackets article))
10121 (let (message-number)
10122 (save-excursion
10123 (save-window-excursion
10124 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10125 (setq message-number
10126 (save-restriction
10127 (widen)
10128 (goto-char (point-max))
10129 (if (re-search-backward
10130 (concat "^Message-ID:\\s-+" (regexp-quote
10131 (or article "")))
10132 nil t)
10133 (rmail-what-message))))))
10134 (if message-number
10135 (progn
10136 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10137 (rmail-show-message message-number)
10138 message-number)
10139 (error "Message not found"))))
10141 ;;; mh-e integration based on planner-mode
10142 (defun org-mhe-get-message-real-folder ()
10143 "Return the name of the current message real folder, so if you use
10144 sequences, it will now work."
10145 (save-excursion
10146 (let* ((folder
10147 (if (equal major-mode 'mh-folder-mode)
10148 mh-current-folder
10149 ;; Refer to the show buffer
10150 mh-show-folder-buffer))
10151 (end-index
10152 (if (boundp 'mh-index-folder)
10153 (min (length mh-index-folder) (length folder))))
10155 ;; a simple test on mh-index-data does not work, because
10156 ;; mh-index-data is always nil in a show buffer.
10157 (if (and (boundp 'mh-index-folder)
10158 (string= mh-index-folder (substring folder 0 end-index)))
10159 (if (equal major-mode 'mh-show-mode)
10160 (save-window-excursion
10161 (when (buffer-live-p (get-buffer folder))
10162 (progn
10163 (pop-to-buffer folder)
10164 (org-mhe-get-message-folder-from-index)
10167 (org-mhe-get-message-folder-from-index)
10169 folder
10173 (defun org-mhe-get-message-folder-from-index ()
10174 "Returns the name of the message folder in a index folder buffer."
10175 (save-excursion
10176 (mh-index-previous-folder)
10177 (re-search-forward "^\\(+.*\\)$" nil t)
10178 (message (match-string 1))))
10180 (defun org-mhe-get-message-folder ()
10181 "Return the name of the current message folder. Be careful if you
10182 use sequences."
10183 (save-excursion
10184 (if (equal major-mode 'mh-folder-mode)
10185 mh-current-folder
10186 ;; Refer to the show buffer
10187 mh-show-folder-buffer)))
10189 (defun org-mhe-get-message-num ()
10190 "Return the number of the current message. Be careful if you
10191 use sequences."
10192 (save-excursion
10193 (if (equal major-mode 'mh-folder-mode)
10194 (mh-get-msg-num nil)
10195 ;; Refer to the show buffer
10196 (mh-show-buffer-message-number))))
10198 (defun org-mhe-get-header (header)
10199 "Return a header of the message in folder mode. This will create a
10200 show buffer for the corresponding message. If you have a more clever
10201 idea..."
10202 (let* ((folder (org-mhe-get-message-folder))
10203 (num (org-mhe-get-message-num))
10204 (buffer (get-buffer-create (concat "show-" folder)))
10205 (header-field))
10206 (with-current-buffer buffer
10207 (mh-display-msg num folder)
10208 (if (equal major-mode 'mh-folder-mode)
10209 (mh-header-display)
10210 (mh-show-header-display))
10211 (set-buffer buffer)
10212 (setq header-field (mh-get-header-field header))
10213 (if (equal major-mode 'mh-folder-mode)
10214 (mh-show)
10215 (mh-show-show))
10216 header-field)))
10218 (defun org-follow-mhe-link (folder article)
10219 "Follow an MHE link to FOLDER and ARTICLE.
10220 If ARTICLE is nil FOLDER is shown. If the configuration variable
10221 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
10222 ARTICLE is searched in all folders. Indexed searches (swish++,
10223 namazu, and others supported by MH-E) will always search in all
10224 folders."
10225 (require 'mh-e)
10226 (require 'mh-search)
10227 (require 'mh-utils)
10228 (mh-find-path)
10229 (if (not article)
10230 (mh-visit-folder (mh-normalize-folder-name folder))
10231 (setq article (org-add-angle-brackets article))
10232 (mh-search-choose)
10233 (if (equal mh-searcher 'pick)
10234 (progn
10235 (mh-search folder (list "--message-id" article))
10236 (when (and org-mhe-search-all-folders
10237 (not (org-mhe-get-message-real-folder)))
10238 (kill-this-buffer)
10239 (mh-search "+" (list "--message-id" article))))
10240 (mh-search "+" article))
10241 (if (org-mhe-get-message-real-folder)
10242 (mh-show-msg 1)
10243 (kill-this-buffer)
10244 (error "Message not found"))))
10246 ;;; BibTeX links
10248 ;; Use the custom search meachnism to construct and use search strings for
10249 ;; file links to BibTeX database entries.
10251 (defun org-create-file-search-in-bibtex ()
10252 "Create the search string and description for a BibTeX database entry."
10253 (when (eq major-mode 'bibtex-mode)
10254 ;; yes, we want to construct this search string.
10255 ;; Make a good description for this entry, using names, year and the title
10256 ;; Put it into the `description' variable which is dynamically scoped.
10257 (let ((bibtex-autokey-names 1)
10258 (bibtex-autokey-names-stretch 1)
10259 (bibtex-autokey-name-case-convert-function 'identity)
10260 (bibtex-autokey-name-separator " & ")
10261 (bibtex-autokey-additional-names " et al.")
10262 (bibtex-autokey-year-length 4)
10263 (bibtex-autokey-name-year-separator " ")
10264 (bibtex-autokey-titlewords 3)
10265 (bibtex-autokey-titleword-separator " ")
10266 (bibtex-autokey-titleword-case-convert-function 'identity)
10267 (bibtex-autokey-titleword-length 'infty)
10268 (bibtex-autokey-year-title-separator ": "))
10269 (setq description (bibtex-generate-autokey)))
10270 ;; Now parse the entry, get the key and return it.
10271 (save-excursion
10272 (bibtex-beginning-of-entry)
10273 (cdr (assoc "=key=" (bibtex-parse-entry))))))
10275 (defun org-execute-file-search-in-bibtex (s)
10276 "Find the link search string S as a key for a database entry."
10277 (when (eq major-mode 'bibtex-mode)
10278 ;; Yes, we want to do the search in this file.
10279 ;; We construct a regexp that searches for "@entrytype{" followed by the key
10280 (goto-char (point-min))
10281 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
10282 (regexp-quote s) "[ \t\n]*,") nil t)
10283 (goto-char (match-beginning 0)))
10284 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
10285 ;; Use double prefix to indicate that any web link should be browsed
10286 (let ((b (current-buffer)) (p (point)))
10287 ;; Restore the window configuration because we just use the web link
10288 (set-window-configuration org-window-config-before-follow-link)
10289 (save-excursion (set-buffer b) (goto-char p)
10290 (bibtex-url)))
10291 (recenter 0)) ; Move entry start to beginning of window
10292 ;; return t to indicate that the search is done.
10295 ;; Finally add the functions to the right hooks.
10296 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10297 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10299 ;; end of Bibtex link setup
10301 ;;; Following file links
10303 (defun org-open-file (path &optional in-emacs line search)
10304 "Open the file at PATH.
10305 First, this expands any special file name abbreviations. Then the
10306 configuration variable `org-file-apps' is checked if it contains an
10307 entry for this file type, and if yes, the corresponding command is launched.
10308 If no application is found, Emacs simply visits the file.
10309 With optional argument IN-EMACS, Emacs will visit the file.
10310 Optional LINE specifies a line to go to, optional SEARCH a string to
10311 search for. If LINE or SEARCH is given, the file will always be
10312 opened in Emacs.
10313 If the file does not exist, an error is thrown."
10314 (setq in-emacs (or in-emacs line search))
10315 (let* ((file (if (equal path "")
10316 buffer-file-name
10317 (substitute-in-file-name (expand-file-name path))))
10318 (apps (append org-file-apps (org-default-apps)))
10319 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10320 (dirp (if remp nil (file-directory-p file)))
10321 (dfile (downcase file))
10322 (old-buffer (current-buffer))
10323 (old-pos (point))
10324 (old-mode major-mode)
10325 ext cmd)
10326 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10327 (setq ext (match-string 1 dfile))
10328 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10329 (setq ext (match-string 1 dfile))))
10330 (if in-emacs
10331 (setq cmd 'emacs)
10332 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10333 (and dirp (cdr (assoc 'directory apps)))
10334 (cdr (assoc ext apps))
10335 (cdr (assoc t apps)))))
10336 (when (eq cmd 'mailcap)
10337 (require 'mailcap)
10338 (mailcap-parse-mailcaps)
10339 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10340 (command (mailcap-mime-info mime-type)))
10341 (if (stringp command)
10342 (setq cmd command)
10343 (setq cmd 'emacs))))
10344 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
10345 (not (file-exists-p file))
10346 (not org-open-non-existing-files))
10347 (error "No such file: %s" file))
10348 (cond
10349 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10350 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10351 (if (string-match "['\"]%s['\"]" cmd)
10352 (setq cmd (replace-match "%s" t t cmd)))
10353 (setq cmd (format cmd (shell-quote-argument file)))
10354 (save-window-excursion
10355 (shell-command (concat cmd " &"))))
10356 ((or (stringp cmd)
10357 (eq cmd 'emacs))
10358 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10359 (if line (goto-line line)
10360 (if search (org-link-search search))))
10361 ((consp cmd)
10362 (eval cmd))
10363 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10364 (and (org-mode-p) (eq old-mode 'org-mode)
10365 (or (not (equal old-buffer (current-buffer)))
10366 (not (equal old-pos (point))))
10367 (org-mark-ring-push old-pos old-buffer))))
10369 (defun org-default-apps ()
10370 "Return the default applications for this operating system."
10371 (cond
10372 ((eq system-type 'darwin)
10373 org-file-apps-defaults-macosx)
10374 ((eq system-type 'windows-nt)
10375 org-file-apps-defaults-windowsnt)
10376 (t org-file-apps-defaults-gnu)))
10378 (defun org-expand-file-name (path)
10379 "Replace special path abbreviations and expand the file name."
10380 (expand-file-name path))
10382 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10383 (defun org-file-remote-p (file)
10384 "Test whether FILE specifies a location on a remote system.
10385 Return non-nil if the location is indeed remote.
10387 For example, the filename \"/user@host:/foo\" specifies a location
10388 on the system \"/user@host:\"."
10389 (cond ((fboundp 'file-remote-p)
10390 (file-remote-p file))
10391 ((fboundp 'tramp-handle-file-remote-p)
10392 (tramp-handle-file-remote-p file))
10393 ((and (boundp 'ange-ftp-name-format)
10394 (string-match (car ange-ftp-name-format) file))
10396 (t nil)))
10399 ;;;; Hooks for remember.el
10401 ;;;###autoload
10402 (defun org-remember-annotation ()
10403 "Return a link to the current location as an annotation for remember.el.
10404 If you are using Org-mode files as target for data storage with
10405 remember.el, then the annotations should include a link compatible with the
10406 conventions in Org-mode. This function returns such a link."
10407 (org-store-link nil))
10409 (defconst org-remember-help
10410 "Select a destination location for the note.
10411 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10412 RET at beg-of-buf -> Append to file as level 2 headline
10413 RET on headline -> Store as sublevel entry to current headline
10414 <left>/<right> -> before/after current headline, same headings level")
10416 ;;;###autoload
10417 (defun org-remember-apply-template (&optional use-char skip-interactive)
10418 "Initialize *remember* buffer with template, invoke `org-mode'.
10419 This function should be placed into `remember-mode-hook' and in fact requires
10420 to be run from that hook to fucntion properly."
10421 (if org-remember-templates
10423 (let* ((char (or use-char
10424 (if (= (length org-remember-templates) 1)
10425 (caar org-remember-templates)
10426 (message "Select template: %s"
10427 (mapconcat
10428 (lambda (x) (char-to-string (car x)))
10429 org-remember-templates " "))
10430 (read-char-exclusive))))
10431 (entry (cdr (assoc char org-remember-templates)))
10432 (tpl (car entry))
10433 (plist-p (if org-store-link-plist t nil))
10434 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
10435 (string-match "\\S-" (nth 1 entry)))
10436 (nth 1 entry)
10437 org-default-notes-file))
10438 (headline (nth 2 entry))
10439 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10440 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10441 (v-u (concat "[" (substring v-t 1 -1) "]"))
10442 (v-U (concat "[" (substring v-T 1 -1) "]"))
10443 (v-i initial) ; defined in `remember-mode'
10444 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
10445 (v-n user-full-name)
10446 (org-startup-folded nil)
10447 org-time-was-given x prompt char time)
10448 (setq org-store-link-plist
10449 (append (list :annotation v-a :initial v-i)))
10450 (unless tpl (setq tpl "") (message "No template") (ding))
10451 (erase-buffer)
10452 (insert (substitute-command-keys
10453 (format
10454 "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
10455 ## Target file \"%s\", headline \"%s\"
10456 ## To switch templates, use `\\[org-remember]'.\n\n"
10457 (abbreviate-file-name (or file org-default-notes-file))
10458 (or headline ""))))
10459 (insert tpl) (goto-char (point-min))
10460 ;; Simple %-escapes
10461 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
10462 (when (and initial (equal (match-string 0) "%i"))
10463 (save-match-data
10464 (let* ((lead (buffer-substring
10465 (point-at-bol) (match-beginning 0))))
10466 (setq v-i (mapconcat 'identity
10467 (org-split-string initial "\n")
10468 (concat "\n" lead))))))
10469 (replace-match
10470 (or (eval (intern (concat "v-" (match-string 1)))) "")
10471 t t))
10472 ;; From the property list
10473 (when plist-p
10474 (goto-char (point-min))
10475 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
10476 (and (setq x (plist-get org-store-link-plist
10477 (intern (match-string 1))))
10478 (replace-match x t t))))
10479 ;; Turn on org-mode in the remember buffer, set local variables
10480 (org-mode)
10481 (org-set-local 'org-finish-function 'remember-buffer)
10482 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10483 (org-set-local 'org-default-notes-file file))
10484 (if (and headline (stringp headline) (string-match "\\S-" headline))
10485 (org-set-local 'org-remember-default-headline headline))
10486 ;; Interactive template entries
10487 (goto-char (point-min))
10488 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([uUtT]\\)?" nil t)
10489 (setq char (if (match-end 3) (match-string 3))
10490 prompt (if (match-end 2) (match-string 2)))
10491 (goto-char (match-beginning 0))
10492 (replace-match "")
10493 (if char
10494 (progn
10495 (setq org-time-was-given (equal (upcase char) char))
10496 (setq time (org-read-date (equal (upcase char) "U") t nil
10497 prompt))
10498 (org-insert-time-stamp time org-time-was-given
10499 (member char '("u" "U"))))
10500 (insert (read-string
10501 (if prompt (concat prompt ": ") "Enter string")))))
10502 (goto-char (point-min))
10503 (if (re-search-forward "%\\?" nil t)
10504 (replace-match "")
10505 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
10506 (org-mode)
10507 (org-set-local 'org-finish-function 'remember-buffer)))
10509 ;;;###autoload
10510 (defun org-remember ()
10511 "Call `remember'. If this is already a remember buffer, re-apply template.
10512 If there is an active region, make sure remember uses it as initial content
10513 of the remember buffer."
10514 (interactive)
10515 (if (eq org-finish-function 'remember-buffer)
10516 (progn
10517 (when (< (length org-remember-templates) 2)
10518 (error "No other template available"))
10519 (erase-buffer)
10520 (let ((annotation (plist-get org-store-link-plist :annotation))
10521 (initial (plist-get org-store-link-plist :initial)))
10522 (org-remember-apply-template))
10523 (message "Press C-c C-c to remember data"))
10524 (if (org-region-active-p)
10525 (remember (buffer-substring (point) (mark)))
10526 (call-interactively 'remember))))
10528 ;;;###autoload
10529 (defun org-remember-handler ()
10530 "Store stuff from remember.el into an org file.
10531 First prompts for an org file. If the user just presses return, the value
10532 of `org-default-notes-file' is used.
10533 Then the command offers the headings tree of the selected file in order to
10534 file the text at a specific location.
10535 You can either immediately press RET to get the note appended to the
10536 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10537 find a better place. Then press RET or <left> or <right> in insert the note.
10539 Key Cursor position Note gets inserted
10540 -----------------------------------------------------------------------------
10541 RET buffer-start as level 2 heading at end of file
10542 RET on headline as sublevel of the heading at cursor
10543 RET no heading at cursor position, level taken from context.
10544 Or use prefix arg to specify level manually.
10545 <left> on headline as same level, before current heading
10546 <right> on headline as same level, after current heading
10548 So the fastest way to store the note is to press RET RET to append it to
10549 the default file. This way your current train of thought is not
10550 interrupted, in accordance with the principles of remember.el. But with
10551 little extra effort, you can push it directly to the correct location.
10553 Before being stored away, the function ensures that the text has a
10554 headline, i.e. a first line that starts with a \"*\". If not, a headline
10555 is constructed from the current date and some additional data.
10557 If the variable `org-adapt-indentation' is non-nil, the entire text is
10558 also indented so that it starts in the same column as the headline
10559 \(i.e. after the stars).
10561 See also the variable `org-reverse-note-order'."
10562 (goto-char (point-min))
10563 (while (looking-at "^[ \t]*\n\\|^##.*\n")
10564 (replace-match ""))
10565 (catch 'quit
10566 (let* ((txt (buffer-substring (point-min) (point-max)))
10567 (fastp current-prefix-arg)
10568 (file (if fastp org-default-notes-file (org-get-org-file)))
10569 (heading org-remember-default-headline)
10570 (visiting (org-find-base-buffer-visiting file))
10571 (org-startup-folded nil)
10572 (org-startup-align-all-tables nil)
10573 (org-goto-start-pos 1)
10574 spos level indent reversed)
10575 ;; Modify text so that it becomes a nice subtree which can be inserted
10576 ;; into an org tree.
10577 (let* ((lines (split-string txt "\n"))
10578 first)
10579 (setq first (car lines) lines (cdr lines))
10580 (if (string-match "^\\*+" first)
10581 ;; Is already a headline
10582 (setq indent nil)
10583 ;; We need to add a headline: Use time and first buffer line
10584 (setq lines (cons first lines)
10585 first (concat "* " (current-time-string)
10586 " (" (remember-buffer-desc) ")")
10587 indent " "))
10588 (if (and org-adapt-indentation indent)
10589 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10590 (setq txt (concat first "\n"
10591 (mapconcat 'identity lines "\n"))))
10592 ;; Find the file
10593 (if (not visiting) (find-file-noselect file))
10594 (with-current-buffer (or visiting (get-file-buffer file))
10595 (save-excursion (and (goto-char (point-min))
10596 (not (re-search-forward "^\\* " nil t))
10597 (insert "\n* Notes\n")))
10598 (setq reversed (org-notes-order-reversed-p))
10599 (save-excursion
10600 (save-restriction
10601 (widen)
10603 ;; Find the default location
10604 (when (and heading (stringp heading) (string-match "\\S-" heading))
10605 (goto-char (point-min))
10606 (if (re-search-forward
10607 (concat "^\\*+[ \t]+" (regexp-quote heading)
10608 "\\([ \t]+:[@a-zA-Z0-9_:]*\\)?[ \t]*$")
10609 nil t)
10610 (setq org-goto-start-pos (match-beginning 0))))
10612 ;; Ask the User for a location
10613 (setq spos (if fastp
10614 org-goto-start-pos
10615 (org-get-location (current-buffer) org-remember-help)))
10616 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10617 ; not handle this note
10618 (goto-char spos)
10619 (cond ((and (bobp) (not reversed))
10620 ;; Put it at the end, one level below level 1
10621 (save-restriction
10622 (widen)
10623 (goto-char (point-max))
10624 (if (not (bolp)) (newline))
10625 (org-paste-subtree (org-get-legal-level 1 1) txt)))
10626 ((and (bobp) reversed)
10627 ;; Put it at the start, as level 1
10628 (save-restriction
10629 (widen)
10630 (goto-char (point-min))
10631 (re-search-forward "^\\*" nil t)
10632 (beginning-of-line 1)
10633 (org-paste-subtree 1 txt)))
10634 ((and (org-on-heading-p nil) (not current-prefix-arg))
10635 ;; Put it below this entry, at the beg/end of the subtree
10636 (org-back-to-heading t)
10637 (setq level (funcall outline-level))
10638 (if reversed
10639 (outline-end-of-heading)
10640 (org-end-of-subtree t))
10641 (if (not (bolp)) (newline))
10642 (beginning-of-line 1)
10643 (org-paste-subtree (org-get-legal-level level 1) txt))
10645 ;; Put it right there, with automatic level determined by
10646 ;; org-paste-subtree or from prefix arg
10647 (org-paste-subtree current-prefix-arg txt)))
10648 (when remember-save-after-remembering
10649 (save-buffer)
10650 (if (not visiting) (kill-buffer (current-buffer)))))))))
10651 t) ;; return t to indicate that we took care of this note.
10653 (defun org-get-org-file ()
10654 "Read a filename, with default directory `org-directory'."
10655 (let ((default (or org-default-notes-file remember-data-file)))
10656 (read-file-name (format "File name [%s]: " default)
10657 (file-name-as-directory org-directory)
10658 default)))
10660 (defun org-notes-order-reversed-p ()
10661 "Check if the current file should receive notes in reversed order."
10662 (cond
10663 ((not org-reverse-note-order) nil)
10664 ((eq t org-reverse-note-order) t)
10665 ((not (listp org-reverse-note-order)) nil)
10666 (t (catch 'exit
10667 (let ((all org-reverse-note-order)
10668 entry)
10669 (while (setq entry (pop all))
10670 (if (string-match (car entry) buffer-file-name)
10671 (throw 'exit (cdr entry))))
10672 nil)))))
10674 ;;;; Dynamic blocks
10676 (defun org-find-dblock (name)
10677 "Find the first dynamic block with name NAME in the buffer.
10678 If not found, stay at current position and return nil."
10679 (let (pos)
10680 (save-excursion
10681 (goto-char (point-min))
10682 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10683 nil t)
10684 (match-beginning 0))))
10685 (if pos (goto-char pos))
10686 pos))
10688 (defconst org-dblock-start-re
10689 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10690 "Matches the startline of a dynamic block, with parameters.")
10692 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
10693 "Matches the end of a dyhamic block.")
10695 (defun org-create-dblock (plist)
10696 "Create a dynamic block section, with parameters taken from PLIST.
10697 PLIST must containe a :name entry which is used as name of the block."
10698 (unless (bolp) (newline))
10699 (let ((name (plist-get plist :name)))
10700 (insert "#+BEGIN: " name)
10701 (while plist
10702 (if (eq (car plist) :name)
10703 (setq plist (cddr plist))
10704 (insert " " (prin1-to-string (pop plist)))))
10705 (insert "\n\n#+END:\n")
10706 (beginning-of-line -2)))
10708 (defun org-prepare-dblock ()
10709 "Prepare dynamic block for refresh.
10710 This empties the block, puts the cursor at the insert position and returns
10711 the property list including an extra property :name with the block name."
10712 (unless (looking-at org-dblock-start-re)
10713 (error "Not at a dynamic block"))
10714 (let* ((begdel (1+ (match-end 0)))
10715 (name (match-string 1))
10716 (params (append (list :name name)
10717 (read (concat "(" (match-string 3) ")")))))
10718 (unless (re-search-forward org-dblock-end-re nil t)
10719 (error "Dynamic block not terminated"))
10720 (delete-region begdel (match-beginning 0))
10721 (goto-char begdel)
10722 (open-line 1)
10723 params))
10725 (defun org-map-dblocks (&optional command)
10726 "Apply COMMAND to all dynamic blocks in the current buffer.
10727 If COMMAND is not given, use `org-update-dblock'."
10728 (let ((cmd (or command 'org-update-dblock))
10729 pos)
10730 (save-excursion
10731 (goto-char (point-min))
10732 (while (re-search-forward org-dblock-start-re nil t)
10733 (goto-char (setq pos (match-beginning 0)))
10734 (condition-case nil
10735 (funcall cmd)
10736 (error (message "Error during update of dynamic block")))
10737 (goto-char pos)
10738 (unless (re-search-forward org-dblock-end-re nil t)
10739 (error "Dynamic block not terminated"))))))
10741 (defun org-dblock-update (&optional arg)
10742 "User command for updating dynamic blocks.
10743 Update the dynamic block at point. With prefix ARG, update all dynamic
10744 blocks in the buffer."
10745 (interactive "P")
10746 (if arg
10747 (org-update-all-dblocks)
10748 (or (looking-at org-dblock-start-re)
10749 (org-beginning-of-dblock))
10750 (org-update-dblock)))
10752 (defun org-update-dblock ()
10753 "Update the dynamic block at point
10754 This means to empty the block, parse for parameters and then call
10755 the correct writing function."
10756 (let* ((pos (point))
10757 (params (org-prepare-dblock))
10758 (name (plist-get params :name))
10759 (cmd (intern (concat "org-dblock-write:" name))))
10760 (funcall cmd params)
10761 (goto-char pos)))
10763 (defun org-beginning-of-dblock ()
10764 "Find the beginning of the dynamic block at point.
10765 Error if there is no scuh block at point."
10766 (let ((pos (point))
10767 beg)
10768 (end-of-line 1)
10769 (if (and (re-search-backward org-dblock-start-re nil t)
10770 (setq beg (match-beginning 0))
10771 (re-search-forward org-dblock-end-re nil t)
10772 (> (match-end 0) pos))
10773 (goto-char beg)
10774 (goto-char pos)
10775 (error "Not in a dynamic block"))))
10777 (defun org-update-all-dblocks ()
10778 "Update all dynamic blocks in the buffer.
10779 This function can be used in a hook."
10780 (when (org-mode-p)
10781 (org-map-dblocks 'org-update-dblock)))
10784 ;;;; Completion
10786 (defun org-complete (&optional arg)
10787 "Perform completion on word at point.
10788 At the beginning of a headline, this completes TODO keywords as given in
10789 `org-todo-keywords'.
10790 If the current word is preceded by a backslash, completes the TeX symbols
10791 that are supported for HTML support.
10792 If the current word is preceded by \"#+\", completes special words for
10793 setting file options.
10794 In the line after \"#+STARTUP:, complete valid keywords.\"
10795 At all other locations, this simply calls `ispell-complete-word'."
10796 (interactive "P")
10797 (catch 'exit
10798 (let* ((end (point))
10799 (beg1 (save-excursion
10800 (skip-chars-backward "a-zA-Z_@0-9")
10801 (point)))
10802 (beg (save-excursion
10803 (skip-chars-backward "a-zA-Z0-9_:$")
10804 (point)))
10805 (confirm (lambda (x) (stringp (car x))))
10806 (searchhead (equal (char-before beg) ?*))
10807 (tag (equal (char-before beg1) ?:))
10808 (texp (equal (char-before beg) ?\\))
10809 (link (equal (char-before beg) ?\[))
10810 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10811 beg)
10812 "#+"))
10813 (startup (string-match "^#\\+STARTUP:.*"
10814 (buffer-substring (point-at-bol) (point))))
10815 (completion-ignore-case opt)
10816 (type nil)
10817 (tbl nil)
10818 (table (cond
10819 (opt
10820 (setq type :opt)
10821 (mapcar (lambda (x)
10822 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10823 (cons (match-string 2 x) (match-string 1 x)))
10824 (org-split-string (org-get-current-options) "\n")))
10825 (startup
10826 (setq type :startup)
10827 org-startup-options)
10828 (link (append org-link-abbrev-alist-local
10829 org-link-abbrev-alist))
10830 (texp
10831 (setq type :tex)
10832 org-html-entities)
10833 ((string-match "\\`\\*+[ \t]*\\'"
10834 (buffer-substring (point-at-bol) beg))
10835 (setq type :todo)
10836 (mapcar 'list org-todo-keywords))
10837 (searchhead
10838 (setq type :searchhead)
10839 (save-excursion
10840 (goto-char (point-min))
10841 (while (re-search-forward org-todo-line-regexp nil t)
10842 (push (list
10843 (org-make-org-heading-search-string
10844 (match-string 3) t))
10845 tbl)))
10846 tbl)
10847 (tag (setq type :tag beg beg1)
10848 (or org-tag-alist (org-get-buffer-tags)))
10849 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
10850 (pattern (buffer-substring-no-properties beg end))
10851 (completion (try-completion pattern table confirm)))
10852 (cond ((eq completion t)
10853 (if (equal type :opt)
10854 (insert (substring (cdr (assoc (upcase pattern) table))
10855 (length pattern)))
10856 (if (equal type :tag) (insert ":"))))
10857 ((null completion)
10858 (message "Can't find completion for \"%s\"" pattern)
10859 (ding))
10860 ((not (string= pattern completion))
10861 (delete-region beg end)
10862 (if (string-match " +$" completion)
10863 (setq completion (replace-match "" t t completion)))
10864 (insert completion)
10865 (if (get-buffer-window "*Completions*")
10866 (delete-window (get-buffer-window "*Completions*")))
10867 (if (assoc completion table)
10868 (if (eq type :todo) (insert " ")
10869 (if (eq type :tag) (insert ":"))))
10870 (if (and (equal type :opt) (assoc completion table))
10871 (message "%s" (substitute-command-keys
10872 "Press \\[org-complete] again to insert example settings"))))
10874 (message "Making completion list...")
10875 (let ((list (sort (all-completions pattern table confirm)
10876 'string<)))
10877 (with-output-to-temp-buffer "*Completions*"
10878 (condition-case nil
10879 ;; Protection needed for XEmacs and emacs 21
10880 (display-completion-list list pattern)
10881 (error (display-completion-list list)))))
10882 (message "Making completion list...%s" "done"))))))
10884 ;;;; TODO, DEADLINE, Comments
10886 (defun org-toggle-comment ()
10887 "Change the COMMENT state of an entry."
10888 (interactive)
10889 (save-excursion
10890 (org-back-to-heading)
10891 (if (looking-at (concat outline-regexp
10892 "\\( +\\<" org-comment-string "\\>\\)"))
10893 (replace-match "" t t nil 1)
10894 (if (looking-at outline-regexp)
10895 (progn
10896 (goto-char (match-end 0))
10897 (insert " " org-comment-string))))))
10899 (defvar org-last-todo-state-is-todo nil
10900 "This is non-nil when the last TODO state change led to a TODO state.
10901 If the last change removed the TODO tag or switched to DONE, then
10902 this is nil.")
10904 (defun org-todo (&optional arg)
10905 "Change the TODO state of an item.
10906 The state of an item is given by a keyword at the start of the heading,
10907 like
10908 *** TODO Write paper
10909 *** DONE Call mom
10911 The different keywords are specified in the variable `org-todo-keywords'.
10912 By default the available states are \"TODO\" and \"DONE\".
10913 So for this example: when the item starts with TODO, it is changed to DONE.
10914 When it starts with DONE, the DONE is removed. And when neither TODO nor
10915 DONE are present, add TODO at the beginning of the heading.
10917 With C-u prefix arg, use completion to determine the new state.
10918 With numeric prefix arg, switch to that state.
10920 For calling through lisp, arg is also interpreted in the following way:
10921 'none -> empty state
10922 \"\"(empty string) -> switch to empty state
10923 'done -> switch to DONE
10924 \"WAITING\" -> switch to the specified keyword, but only if it
10925 really is a member of `org-todo-keywords'."
10926 (interactive "P")
10927 (save-excursion
10928 (org-back-to-heading)
10929 (if (looking-at outline-regexp) (goto-char (match-end 0)))
10930 (or (looking-at (concat " +" org-todo-regexp " *"))
10931 (looking-at " *"))
10932 (let* ((this (match-string 1))
10933 (last-state (or this ""))
10934 (completion-ignore-case t)
10935 (member (member this org-todo-keywords))
10936 (tail (cdr member))
10937 (state (cond
10938 ((equal arg '(4))
10939 ;; Read a state with completion
10940 (completing-read "State: " (mapcar (lambda(x) (list x))
10941 org-todo-keywords)
10942 nil t))
10943 ((eq arg 'right)
10944 (if this
10945 (if tail (car tail) nil)
10946 (car org-todo-keywords)))
10947 ((eq arg 'left)
10948 (if (equal member org-todo-keywords)
10950 (if this
10951 (nth (- (length org-todo-keywords) (length tail) 2)
10952 org-todo-keywords)
10953 org-done-string)))
10954 (arg
10955 ;; user requests a specific state
10956 (cond
10957 ((equal arg "") nil)
10958 ((eq arg 'none) nil)
10959 ((eq arg 'done) (org-last org-todo-keywords))
10960 ((car (member arg org-todo-keywords)))
10961 ((nth (1- (prefix-numeric-value arg))
10962 org-todo-keywords))))
10963 ((null member) (car org-todo-keywords))
10964 ((null tail) nil) ;; -> first entry
10965 ((eq org-todo-interpretation 'sequence)
10966 (car tail))
10967 ((memq org-todo-interpretation '(type priority))
10968 (if (eq this-command last-command)
10969 (car tail)
10970 (if (> (length tail) 0) org-done-string nil)))
10971 (t nil)))
10972 (next (if state (concat " " state " ") " "))
10973 dostates)
10974 (replace-match next t t)
10975 (setq org-last-todo-state-is-todo
10976 (not (equal state org-done-string)))
10977 (when org-log-done
10978 (setq dostates (and (eq org-todo-interpretation 'sequence)
10979 (listp org-log-done) (memq 'state org-log-done)))
10980 (cond
10981 ((and state (not this))
10982 (org-add-planning-info nil nil 'closed)
10983 (and dostates (org-add-log-maybe 'state state 'findpos)))
10984 ((and state dostates)
10985 (org-add-log-maybe 'state state 'findpos))
10986 ((equal state org-done-string)
10987 ;; Planning info calls the note-setting command.
10988 (org-add-planning-info 'closed (org-current-time)
10989 (if (org-get-repeat) nil 'scheduled))
10990 (org-add-log-maybe 'done state 'findpos))))
10991 ;; Fixup tag positioning
10992 (and org-auto-align-tags (org-set-tags nil t))
10993 (run-hooks 'org-after-todo-state-change-hook)
10994 (and (equal state org-done-string) (org-auto-repeat-maybe))
10996 ;; Fixup cursor location if close to the keyword
10997 (if (and (outline-on-heading-p)
10998 (not (bolp))
10999 (save-excursion (beginning-of-line 1)
11000 (looking-at org-todo-line-regexp))
11001 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11002 (progn
11003 (goto-char (or (match-end 2) (match-end 1)))
11004 (just-one-space))))
11006 (defun org-get-repeat ()
11007 "Return the REPEAT statement of this entry."
11008 (save-match-data
11009 (save-excursion
11010 (org-back-to-heading t)
11011 (if (re-search-forward
11012 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
11013 (match-string 1)))))
11015 (defvar org-last-changed-timestamp)
11016 (defvar org-log-post-message)
11017 (defun org-auto-repeat-maybe ()
11018 "Check if the current headline contains a REPEAT key.
11019 If yes, set TODO state back to what it was and change any SCHEDULED
11020 or DEADLINE times the new date.
11021 This function should be run in the `org-after-todo-state-change-hook'."
11022 ;; last-state is dynamically scoped into this function
11023 (let ((repeat (org-get-repeat))
11024 (whata '(("d" . day) ("m" . month) ("y" . year)))
11025 (msg "Entry repeats: ")
11026 (org-log-done)
11027 re type n what start)
11028 (when repeat
11029 (org-todo (if (eq 'org-todo-interpretation 'type)
11030 last-state
11031 (car org-todo-keywords)))
11032 (unless (memq 'org-add-log-note (default-value 'post-command-hook))
11033 ;; Make sure a note is taken
11034 (let ((org-log-done '(done)))
11035 (org-add-log-maybe 'done org-done-string 'findpos)))
11036 (org-back-to-heading t)
11037 (org-add-planning-info nil nil 'closed)
11038 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11039 org-deadline-time-regexp "\\)"))
11040 (while (re-search-forward
11041 re (save-excursion (outline-next-heading) (point)) t)
11042 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
11043 start 0)
11044 (while (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" repeat start)
11045 (setq start (match-end 0)
11046 n (string-to-number (match-string 1 repeat))
11047 what (match-string 2 repeat))
11048 (if (equal what "w") (setq n (* n 7) what "d"))
11049 (org-timestamp-change n (cdr (assoc what whata))))
11050 (setq msg (concat msg type org-last-changed-timestamp " ")))
11051 (setq org-log-post-message msg)
11052 (message msg))))
11054 (defun org-show-todo-tree (arg)
11055 "Make a compact tree which shows all headlines marked with TODO.
11056 The tree will show the lines where the regexp matches, and all higher
11057 headlines above the match.
11058 With \\[universal-argument] prefix, also show the DONE entries.
11059 With a numeric prefix N, construct a sparse tree for the Nth element
11060 of `org-todo-keywords'."
11061 (interactive "P")
11062 (let ((case-fold-search nil)
11063 (kwd-re
11064 (cond ((null arg) org-not-done-regexp)
11065 ((equal arg '(4)) org-todo-regexp)
11066 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
11067 (regexp-quote (nth (1- (prefix-numeric-value arg))
11068 org-todo-keywords)))
11069 (t (error "Invalid prefix argument: %s" arg)))))
11070 (message "%d TODO entries found"
11071 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
11073 (defun org-deadline ()
11074 "Insert the DEADLINE: string to make a deadline.
11075 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11076 to modify it to the correct date."
11077 (interactive)
11078 (org-add-planning-info 'deadline nil 'closed))
11080 (defun org-schedule ()
11081 "Insert the SCHEDULED: string to schedule a TODO item.
11082 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11083 to modify it to the correct date."
11084 (interactive)
11085 (org-add-planning-info 'scheduled nil 'closed))
11087 (defun org-add-planning-info (what &optional time &rest remove)
11088 "Insert new timestamp with keyword in the line directly after the headline.
11089 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11090 If non is given, the user is prompted for a date.
11091 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11092 be removed."
11093 (interactive)
11094 (let (org-time-was-given)
11095 (when what (setq time (or time (org-read-date nil 'to-time))))
11096 (when (and org-insert-labeled-timestamps-at-point
11097 (member what '(scheduled deadline)))
11098 (insert
11099 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11100 (org-insert-time-stamp time org-time-was-given)
11101 (setq what nil))
11102 (save-excursion
11103 (save-restriction
11104 (let (col list elt ts buffer-invisibility-spec)
11105 (org-back-to-heading t)
11106 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11107 (goto-char (match-end 1))
11108 (setq col (current-column))
11109 (goto-char (1+ (match-end 0)))
11110 (if (and (not (looking-at outline-regexp))
11111 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11112 "[^\r\n]*"))
11113 (not (equal (match-string 1) org-clock-string)))
11114 (narrow-to-region (match-beginning 0) (match-end 0))
11115 (insert "\n")
11116 (backward-char 1)
11117 (narrow-to-region (point) (point))
11118 (indent-to-column col))
11119 ;; Check if we have to remove something.
11120 (setq list (cons what remove))
11121 (while list
11122 (setq elt (pop list))
11123 (goto-char (point-min))
11124 (when (or (and (eq elt 'scheduled)
11125 (re-search-forward org-scheduled-time-regexp nil t))
11126 (and (eq elt 'deadline)
11127 (re-search-forward org-deadline-time-regexp nil t))
11128 (and (eq elt 'closed)
11129 (re-search-forward org-closed-time-regexp nil t)))
11130 (replace-match "")
11131 (if (looking-at "--+<[^>]+>") (replace-match ""))
11132 (if (looking-at " +") (replace-match ""))))
11133 (goto-char (point-max))
11134 (when what
11135 (insert
11136 (if (not (equal (char-before) ?\ )) " " "")
11137 (cond ((eq what 'scheduled) org-scheduled-string)
11138 ((eq what 'deadline) org-deadline-string)
11139 ((eq what 'closed) org-closed-string))
11140 " ")
11141 (org-insert-time-stamp time
11142 (or org-time-was-given (eq what 'closed))
11143 (eq what 'closed))
11144 (end-of-line 1))
11145 (goto-char (point-min))
11146 (widen)
11147 (if (looking-at "[ \t]+\r?\n")
11148 (replace-match ""))
11149 ts)))))
11151 (defvar org-log-note-marker (make-marker))
11152 (defvar org-log-note-purpose nil)
11153 (defvar org-log-note-state nil)
11154 (defvar org-log-note-window-configuration nil)
11155 (defvar org-log-note-return-to (make-marker))
11156 (defvar org-log-post-message nil
11157 "Message to be displayed after a log note has been stored.
11158 The auto-repeater uses this.")
11160 (defun org-add-log-maybe (&optional purpose state findpos)
11161 (save-excursion
11162 (when (and (listp org-log-done)
11163 (memq purpose org-log-done))
11164 (when findpos
11165 (org-back-to-heading t)
11166 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11167 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11168 "[^\r\n]*\\)?"))
11169 (goto-char (match-end 0)))
11170 (move-marker org-log-note-marker (point))
11171 (setq org-log-note-purpose purpose)
11172 (setq org-log-note-state state)
11173 (add-hook 'post-command-hook 'org-add-log-note 'append))))
11175 (defun org-add-log-note (&optional purpose)
11176 "Pop up a window for taking a note, and add this note later at point."
11177 (remove-hook 'post-command-hook 'org-add-log-note)
11178 (setq org-log-note-window-configuration (current-window-configuration))
11179 (delete-other-windows)
11180 (move-marker org-log-note-return-to (point))
11181 (switch-to-buffer (marker-buffer org-log-note-marker))
11182 (goto-char org-log-note-marker)
11183 (switch-to-buffer-other-window "*Org Note*")
11184 (erase-buffer)
11185 (let ((org-inhibit-startup t)) (org-mode))
11186 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
11187 (cond
11188 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11189 ((eq org-log-note-purpose 'done) "closed todo item")
11190 ((eq org-log-note-purpose 'state) "state change")
11191 (t (error "This should not happen")))))
11192 (org-set-local 'org-finish-function 'org-store-log-note))
11194 (defun org-store-log-note ()
11195 "Finish taking a log note, and insert it to where it belongs."
11196 (let ((txt (buffer-string))
11197 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11198 lines ind)
11199 (kill-buffer (current-buffer))
11200 (if (string-match "^#.*\n[ \t\n]*" txt)
11201 (setq txt (replace-match "" t t txt)))
11202 (if (string-match "\\s-+\\'" txt)
11203 (setq txt (replace-match "" t t txt)))
11204 (setq lines (org-split-string txt "\n"))
11205 (when (and note (string-match "\\S-" note))
11206 (setq note
11207 (org-replace-escapes
11208 note
11209 (list (cons "%u" (user-login-name))
11210 (cons "%U" user-full-name)
11211 (cons "%t" (format-time-string
11212 (org-time-stamp-format 'long 'inactive)
11213 (current-time)))
11214 (cons "%s" (if org-log-note-state
11215 (concat "\"" org-log-note-state "\"")
11216 "")))))
11217 (if lines (setq note (concat note " \\\\")))
11218 (push note lines))
11219 (save-excursion
11220 (set-buffer (marker-buffer org-log-note-marker))
11221 (save-excursion
11222 (goto-char org-log-note-marker)
11223 (move-marker org-log-note-marker nil)
11224 (end-of-line 1)
11225 (if (not (bolp)) (insert "\n")) (indent-relative nil)
11226 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
11227 (insert " - " (pop lines))
11228 (while lines
11229 (insert "\n" ind (pop lines))))))
11230 (set-window-configuration org-log-note-window-configuration)
11231 (with-current-buffer (marker-buffer org-log-note-return-to)
11232 (goto-char org-log-note-return-to))
11233 (move-marker org-log-note-return-to nil)
11234 (and org-log-post-message (message org-log-post-message)))
11236 (defvar org-occur-highlights nil)
11237 (make-variable-buffer-local 'org-occur-highlights)
11239 (defun org-occur (regexp &optional keep-previous callback)
11240 "Make a compact tree which shows all matches of REGEXP.
11241 The tree will show the lines where the regexp matches, and all higher
11242 headlines above the match. It will also show the heading after the match,
11243 to make sure editing the matching entry is easy.
11244 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11245 call to `org-occur' will be kept, to allow stacking of calls to this
11246 command.
11247 If CALLBACK is non-nil, it is a function which is called to confirm
11248 that the match should indeed be shown."
11249 (interactive "sRegexp: \nP")
11250 (or keep-previous (org-remove-occur-highlights nil nil t))
11251 (let ((cnt 0))
11252 (save-excursion
11253 (goto-char (point-min))
11254 (if (or (not keep-previous) ; do not want to keep
11255 (not org-occur-highlights)) ; no previous matches
11256 ;; hide everything
11257 (org-overview))
11258 (while (re-search-forward regexp nil t)
11259 (when (or (not callback)
11260 (save-match-data (funcall callback)))
11261 (setq cnt (1+ cnt))
11262 (org-highlight-new-match (match-beginning 0) (match-end 0))
11263 (org-show-context 'occur-tree))))
11264 (when org-remove-highlights-with-change
11265 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11266 nil 'local))
11267 (unless org-sparse-tree-open-archived-trees
11268 (org-hide-archived-subtrees (point-min) (point-max)))
11269 (run-hooks 'org-occur-hook)
11270 (if (interactive-p)
11271 (message "%d match(es) for regexp %s" cnt regexp))
11272 cnt))
11274 (defun org-show-context (&optional key)
11275 "Make sure point and context and visible.
11276 How much context is shown depends upon the variables
11277 `org-show-hierarchy-above', `org-show-following-heading'. and
11278 `org-show-siblings'."
11279 (let ((heading-p (org-on-heading-p t))
11280 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11281 (following-p (org-get-alist-option org-show-following-heading key))
11282 (siblings-p (org-get-alist-option org-show-siblings key)))
11283 (catch 'exit
11284 ;; Show heading or entry text
11285 (if heading-p
11286 (org-flag-heading nil) ; only show the heading
11287 (and (or (org-invisible-p) (org-invisible-p2))
11288 (org-show-hidden-entry))) ; show entire entry
11289 (when following-p
11290 ;; Show next sibling, or heading below text
11291 (save-excursion
11292 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11293 (org-flag-heading nil))))
11294 (when siblings-p (org-show-siblings))
11295 (when hierarchy-p
11296 ;; show all higher headings, possibly with siblings
11297 (save-excursion
11298 (while (and (condition-case nil
11299 (progn (org-up-heading-all 1) t)
11300 (error nil))
11301 (not (bobp)))
11302 (org-flag-heading nil)
11303 (when siblings-p (org-show-siblings))))))))
11305 (defun org-reveal (&optional siblings)
11306 "Show current entry, hierarchy above it, and the following headline.
11307 This can be used to show a consistent set of context around locations
11308 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11309 not t for the search context.
11311 With optional argument SIBLINGS, on each level of the hierarchy all
11312 siblings are shown. This repairs the tree structure to what it would
11313 look like when opened with hierarchical calls to `org-cycle'."
11314 (interactive "P")
11315 (let ((org-show-hierarchy-above t)
11316 (org-show-following-heading t)
11317 (org-show-siblings (if siblings t org-show-siblings)))
11318 (org-show-context nil)))
11320 (defun org-highlight-new-match (beg end)
11321 "Highlight from BEG to END and mark the highlight is an occur headline."
11322 (let ((ov (org-make-overlay beg end)))
11323 (org-overlay-put ov 'face 'secondary-selection)
11324 (push ov org-occur-highlights)))
11326 (defun org-remove-occur-highlights (&optional beg end noremove)
11327 "Remove the occur highlights from the buffer.
11328 BEG and END are ignored. If NOREMOVE is nil, remove this function
11329 from the `before-change-functions' in the current buffer."
11330 (interactive)
11331 (unless org-inhibit-highlight-removal
11332 (mapc 'org-delete-overlay org-occur-highlights)
11333 (setq org-occur-highlights nil)
11334 (unless noremove
11335 (remove-hook 'before-change-functions
11336 'org-remove-occur-highlights 'local))))
11338 ;;;; Priorities
11340 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
11341 "Regular expression matching the priority indicator.")
11343 (defvar org-remove-priority-next-time nil)
11345 (defun org-priority-up ()
11346 "Increase the priority of the current item."
11347 (interactive)
11348 (org-priority 'up))
11350 (defun org-priority-down ()
11351 "Decrease the priority of the current item."
11352 (interactive)
11353 (org-priority 'down))
11355 (defun org-priority (&optional action)
11356 "Change the priority of an item by ARG.
11357 ACTION can be set, up, or down."
11358 (interactive)
11359 (setq action (or action 'set))
11360 (let (current new news have remove)
11361 (save-excursion
11362 (org-back-to-heading)
11363 (if (looking-at org-priority-regexp)
11364 (setq current (string-to-char (match-string 2))
11365 have t)
11366 (setq current org-default-priority))
11367 (cond
11368 ((eq action 'set)
11369 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
11370 (setq new (read-char-exclusive))
11371 (cond ((equal new ?\ ) (setq remove t))
11372 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
11373 (error "Priority must be between `%c' and `%c'"
11374 ?A org-lowest-priority))))
11375 ((eq action 'up)
11376 (setq new (1- current)))
11377 ((eq action 'down)
11378 (setq new (1+ current)))
11379 (t (error "Invalid action")))
11380 (setq new (min (max ?A (upcase new)) org-lowest-priority))
11381 (setq news (format "%c" new))
11382 (if have
11383 (if remove
11384 (replace-match "" t t nil 1)
11385 (replace-match news t t nil 2))
11386 (if remove
11387 (error "No priority cookie found in line")
11388 (looking-at org-todo-line-regexp)
11389 (if (match-end 2)
11390 (progn
11391 (goto-char (match-end 2))
11392 (insert " [#" news "]"))
11393 (goto-char (match-beginning 3))
11394 (insert "[#" news "] ")))))
11395 (if remove
11396 (message "Priority removed")
11397 (message "Priority of current item set to %s" news))))
11400 (defun org-get-priority (s)
11401 "Find priority cookie and return priority."
11402 (save-match-data
11403 (if (not (string-match org-priority-regexp s))
11404 (* 1000 (- org-lowest-priority org-default-priority))
11405 (* 1000 (- org-lowest-priority
11406 (string-to-char (match-string 2 s)))))))
11408 ;;;; Tags
11410 (defun org-scan-tags (action matcher &optional todo-only)
11411 "Scan headline tags with inheritance and produce output ACTION.
11412 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
11413 evaluated, testing if a given set of tags qualifies a headline for
11414 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
11415 are included in the output."
11416 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
11417 (mapconcat 'regexp-quote
11418 (nreverse (cdr (reverse org-todo-keywords)))
11419 "\\|")
11420 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
11421 (props (list 'face nil
11422 'done-face 'org-done
11423 'undone-face nil
11424 'mouse-face 'highlight
11425 'org-not-done-regexp org-not-done-regexp
11426 'keymap org-agenda-keymap
11427 'help-echo
11428 (format "mouse-2 or RET jump to org file %s"
11429 (abbreviate-file-name buffer-file-name))))
11430 (case-fold-search nil)
11431 lspos
11432 tags tags-list tags-alist (llast 0) rtn level category i txt
11433 todo marker entry)
11434 (save-excursion
11435 (goto-char (point-min))
11436 (when (eq action 'sparse-tree) (org-overview))
11437 (while (re-search-forward re nil t)
11438 (catch :skip
11439 (setq todo (if (match-end 1) (match-string 2))
11440 tags (if (match-end 4) (match-string 4)))
11441 (goto-char (setq lspos (1+ (match-beginning 0))))
11442 (setq level (funcall outline-level)
11443 category (org-get-category))
11444 (setq i llast llast level)
11445 ;; remove tag lists from same and sublevels
11446 (while (>= i level)
11447 (when (setq entry (assoc i tags-alist))
11448 (setq tags-alist (delete entry tags-alist)))
11449 (setq i (1- i)))
11450 ;; add the nex tags
11451 (when tags
11452 (setq tags (mapcar 'downcase (org-split-string tags ":"))
11453 tags-alist
11454 (cons (cons level tags) tags-alist)))
11455 ;; compile tags for current headline
11456 (setq tags-list
11457 (if org-use-tag-inheritance
11458 (apply 'append (mapcar 'cdr tags-alist))
11459 tags))
11460 (when (and (or (not todo-only) todo)
11461 (eval matcher)
11462 (or (not org-agenda-skip-archived-trees)
11463 (not (member org-archive-tag tags-list))))
11464 (and (eq action 'agenda) (org-agenda-skip))
11465 ;; list this headline
11466 (if (eq action 'sparse-tree)
11467 (progn
11468 (org-show-context 'tags-tree))
11469 (setq txt (org-format-agenda-item
11471 (concat
11472 (if org-tags-match-list-sublevels
11473 (make-string (1- level) ?.) "")
11474 (org-get-heading))
11475 category tags-list))
11476 (goto-char lspos)
11477 (setq marker (org-agenda-new-marker))
11478 (org-add-props txt props
11479 'org-marker marker 'org-hd-marker marker 'org-category category)
11480 (push txt rtn))
11481 ;; if we are to skip sublevels, jump to end of subtree
11482 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
11483 (when (and (eq action 'sparse-tree)
11484 (not org-sparse-tree-open-archived-trees))
11485 (org-hide-archived-subtrees (point-min) (point-max)))
11486 (nreverse rtn)))
11488 (defvar todo-only) ;; dynamically scoped
11490 (defun org-tags-sparse-tree (&optional todo-only match)
11491 "Create a sparse tree according to tags string MATCH.
11492 MATCH can contain positive and negative selection of tags, like
11493 \"+WORK+URGENT-WITHBOSS\".
11494 If optional argument TODO_ONLY is non-nil, only select lines that are
11495 also TODO lines."
11496 (interactive "P")
11497 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11499 (defun org-make-tags-matcher (match)
11500 "Create the TAGS//TODO matcher form for the selection string MATCH."
11501 ;; todo-only is scoped dynamically into this function, and the function
11502 ;; may change it it the matcher asksk for it.
11503 (unless match
11504 ;; Get a new match request, with completion
11505 (setq org-last-tags-completion-table
11506 (or org-tag-alist
11507 org-last-tags-completion-table))
11508 (setq match (completing-read
11509 "Match: " 'org-tags-completion-function nil nil nil
11510 'org-tags-history)))
11512 ;; Parse the string and create a lisp form
11513 (let ((match0 match)
11514 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[A-Za-z_@0-9]+\\)")
11515 minus tag mm
11516 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11517 orterms term orlist re-p level-p)
11518 (if (string-match "/+" match)
11519 ;; match contains also a todo-matching request
11520 (progn
11521 (setq tagsmatch (substring match 0 (match-beginning 0))
11522 todomatch (substring match (match-end 0)))
11523 (if (string-match "^!" todomatch)
11524 (setq todo-only t todomatch (substring todomatch 1)))
11525 (if (string-match "^\\s-*$" todomatch)
11526 (setq todomatch nil)))
11527 ;; only matching tags
11528 (setq tagsmatch match todomatch nil))
11530 ;; Make the tags matcher
11531 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11532 (setq tagsmatcher t)
11533 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11534 (while (setq term (pop orterms))
11535 (while (and (equal (substring term -1) "\\") orterms)
11536 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11537 (while (string-match re term)
11538 (setq minus (and (match-end 1)
11539 (equal (match-string 1 term) "-"))
11540 tag (match-string 2 term)
11541 re-p (equal (string-to-char tag) ?{)
11542 level-p (match-end 3)
11543 mm (cond
11544 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11545 (level-p `(= level ,(string-to-number
11546 (match-string 3 term))))
11547 (t `(member ,(downcase tag) tags-list)))
11548 mm (if minus (list 'not mm) mm)
11549 term (substring term (match-end 0)))
11550 (push mm tagsmatcher))
11551 (push (if (> (length tagsmatcher) 1)
11552 (cons 'and tagsmatcher)
11553 (car tagsmatcher))
11554 orlist)
11555 (setq tagsmatcher nil))
11556 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
11558 ;; Make the todo matcher
11559 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11560 (setq todomatcher t)
11561 (setq orterms (org-split-string todomatch "|") orlist nil)
11562 (while (setq term (pop orterms))
11563 (while (string-match re term)
11564 (setq minus (and (match-end 1)
11565 (equal (match-string 1 term) "-"))
11566 kwd (match-string 2 term)
11567 re-p (equal (string-to-char kwd) ?{)
11568 term (substring term (match-end 0))
11569 mm (if re-p
11570 `(string-match ,(substring kwd 1 -1) todo)
11571 (list 'equal 'todo kwd))
11572 mm (if minus (list 'not mm) mm))
11573 (push mm todomatcher))
11574 (push (if (> (length todomatcher) 1)
11575 (cons 'and todomatcher)
11576 (car todomatcher))
11577 orlist)
11578 (setq todomatcher nil))
11579 (setq todomatcher (if (> (length orlist) 1)
11580 (cons 'or orlist) (car orlist))))
11582 ;; Return the string and lisp forms of the matcher
11583 (setq matcher (if todomatcher
11584 (list 'and tagsmatcher todomatcher)
11585 tagsmatcher))
11586 (cons match0 matcher)))
11588 (defun org-match-any-p (re list)
11589 "Does re match any element of list?"
11590 (setq list (mapcar (lambda (x) (string-match re x)) list))
11591 (delq nil list))
11593 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
11594 (defvar org-tags-overlay (org-make-overlay 1 1))
11595 (org-detach-overlay org-tags-overlay)
11597 (defun org-set-tags (&optional arg just-align)
11598 "Set the tags for the current headline.
11599 With prefix ARG, realign all tags in headings in the current buffer."
11600 (interactive "P")
11601 (let* ((re (concat "^" outline-regexp))
11602 (current (org-get-tags))
11603 table current-tags inherited-tags ; computed below when needed
11604 tags p0 c0 c1 rpl)
11605 (if arg
11606 (save-excursion
11607 (goto-char (point-min))
11608 (let (buffer-invisibility-spec) ; Emacs 21 compatibility
11609 (while (re-search-forward re nil t)
11610 (org-set-tags nil t)
11611 (end-of-line 1)))
11612 (message "All tags realigned to column %d" org-tags-column))
11613 (if just-align
11614 (setq tags current)
11615 ;; Get a new set of tags from the user
11616 (setq table (or org-tag-alist (org-get-buffer-tags))
11617 org-last-tags-completion-table table
11618 current-tags (org-split-string current ":")
11619 inherited-tags (nreverse
11620 (nthcdr (length current-tags)
11621 (nreverse (org-get-tags-at))))
11622 tags
11623 (if (or (eq t org-use-fast-tag-selection)
11624 (and org-use-fast-tag-selection
11625 (delq nil (mapcar 'cdr table))))
11626 (org-fast-tag-selection current-tags inherited-tags table)
11627 (let ((org-add-colon-after-tag-completion t))
11628 (org-trim
11629 (completing-read "Tags: " 'org-tags-completion-function
11630 nil nil current 'org-tags-history)))))
11631 (while (string-match "[-+&]+" tags)
11632 ;; No boolean logic, just a list
11633 (setq tags (replace-match ":" t t tags))))
11634 (if (string-match "\\`[\t ]*\\'" tags)
11635 (setq tags "")
11636 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11637 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11639 ;; Insert new tags at the correct column
11640 (beginning-of-line 1)
11641 (if (re-search-forward
11642 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11643 (point-at-eol) t)
11644 (progn
11645 (if (equal tags "")
11646 (setq rpl "")
11647 (goto-char (match-beginning 0))
11648 (setq c0 (current-column) p0 (point)
11649 c1 (max (1+ c0) (if (> org-tags-column 0)
11650 org-tags-column
11651 (- (- org-tags-column) (length tags))))
11652 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11653 (replace-match rpl)
11654 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
11655 tags)
11656 (error "Tags alignment failed")))))
11658 (defun org-tags-completion-function (string predicate &optional flag)
11659 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11660 (confirm (lambda (x) (stringp (car x)))))
11661 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11662 (setq s1 (match-string 1 string)
11663 s2 (match-string 2 string))
11664 (setq s1 "" s2 string))
11665 (cond
11666 ((eq flag nil)
11667 ;; try completion
11668 (setq rtn (try-completion s2 ctable confirm))
11669 (if (stringp rtn)
11670 (concat s1 s2 (substring rtn (length s2))
11671 (if (and org-add-colon-after-tag-completion
11672 (assoc rtn ctable))
11673 ":" "")))
11675 ((eq flag t)
11676 ;; all-completions
11677 (all-completions s2 ctable confirm)
11679 ((eq flag 'lambda)
11680 ;; exact match?
11681 (assoc s2 ctable)))
11684 (defun org-fast-tag-insert (kwd tags face &optional end)
11685 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
11686 (insert (format "%-12s" (concat kwd ":"))
11687 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11688 (or end "")))
11690 (defun org-fast-tag-show-exit (flag)
11691 (save-excursion
11692 (goto-line 3)
11693 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11694 (replace-match ""))
11695 (when flag
11696 (end-of-line 1)
11697 (move-to-column (- (window-width) 19) t)
11698 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11700 (defun org-set-current-tags-overlay (current prefix)
11701 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11702 (if (featurep 'xemacs)
11703 (org-overlay-display org-tags-overlay (concat prefix s)
11704 'secondary-selection)
11705 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11706 (org-overlay-display org-tags-overlay (concat prefix s)))))
11708 (defun org-fast-tag-selection (current inherited table)
11709 "Fast tag selection with single keys.
11710 CURRENT is the current list of tags in the headline, INHERITED is the
11711 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11712 possibly with grouping information.
11713 If the keys are nil, a-z are automatically assigned.
11714 Returns the new tags string, or nil to not change the current settings."
11715 (let* ((maxlen (apply 'max (mapcar
11716 (lambda (x)
11717 (if (stringp (car x)) (string-width (car x)) 0))
11718 table)))
11719 (buf (current-buffer))
11720 (expert (eq org-fast-tag-selection-single-key 'expert))
11721 (buffer-tags nil)
11722 (fwidth (+ maxlen 3 1 3))
11723 (ncol (/ (- (window-width) 4) fwidth))
11724 (i-face 'org-done)
11725 (c-face 'org-tag)
11726 tg cnt e c char c1 c2 ntable tbl rtn
11727 ov-start ov-end ov-prefix
11728 (exit-after-next org-fast-tag-selection-single-key)
11729 groups ingroup)
11730 (save-excursion
11731 (beginning-of-line 1)
11732 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
11733 (setq ov-start (match-beginning 1)
11734 ov-end (match-end 1)
11735 ov-prefix "")
11736 (setq ov-start (1- (point-at-eol))
11737 ov-end (1+ ov-start))
11738 (skip-chars-forward "^\n\r")
11739 (setq ov-prefix
11740 (concat
11741 (buffer-substring (1- (point)) (point))
11742 (if (> (current-column) org-tags-column)
11744 (make-string (- org-tags-column (current-column)) ?\ ))))))
11745 (org-move-overlay org-tags-overlay ov-start ov-end)
11746 (save-window-excursion
11747 (if expert
11748 (set-buffer (get-buffer-create " *Org tags*"))
11749 (delete-other-windows)
11750 (split-window-vertically)
11751 (switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11752 (erase-buffer)
11753 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11754 (org-fast-tag-insert "Current" current c-face "\n\n")
11755 (org-fast-tag-show-exit exit-after-next)
11756 (org-set-current-tags-overlay current ov-prefix)
11757 (setq tbl table char ?a cnt 0)
11758 (while (setq e (pop tbl))
11759 (cond
11760 ((equal e '(:startgroup))
11761 (push '() groups) (setq ingroup t)
11762 (when (not (= cnt 0))
11763 (setq cnt 0)
11764 (insert "\n"))
11765 (insert "{ "))
11766 ((equal e '(:endgroup))
11767 (setq ingroup nil cnt 0)
11768 (insert "}\n"))
11770 (setq tg (car e) c2 nil)
11771 (if (cdr e)
11772 (setq c (cdr e))
11773 ;; automatically assign a character.
11774 (setq c1 (string-to-char
11775 (downcase (substring
11776 tg (if (= (string-to-char tg) ?@) 1 0)))))
11777 (if (or (rassoc c1 ntable) (rassoc c1 table))
11778 (while (or (rassoc char ntable) (rassoc char table))
11779 (setq char (1+ char)))
11780 (setq c2 c1))
11781 (setq c (or c2 char)))
11782 (if ingroup (push tg (car groups)))
11783 (setq tg (org-add-props tg nil 'face
11784 (cond
11785 ((member tg current) c-face)
11786 ((member tg inherited) i-face)
11787 (t nil))))
11788 (if (and (= cnt 0) (not ingroup)) (insert " "))
11789 (insert "[" c "] " tg (make-string
11790 (- fwidth 4 (length tg)) ?\ ))
11791 (push (cons tg c) ntable)
11792 (when (= (setq cnt (1+ cnt)) ncol)
11793 (insert "\n")
11794 (if ingroup (insert " "))
11795 (setq cnt 0)))))
11796 (setq ntable (nreverse ntable))
11797 (insert "\n")
11798 (goto-char (point-min))
11799 (if (and (not expert) (fboundp 'fit-window-to-buffer))
11800 (fit-window-to-buffer))
11801 (setq rtn
11802 (catch 'exit
11803 (while t
11804 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11805 (if groups " [!] no groups" " [!]groups")
11806 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11807 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11808 (cond
11809 ((= c ?\r) (throw 'exit t))
11810 ((= c ?!)
11811 (setq groups (not groups))
11812 (goto-char (point-min))
11813 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11814 ((= c ?\C-c)
11815 (if (not expert)
11816 (org-fast-tag-show-exit
11817 (setq exit-after-next (not exit-after-next)))
11818 (setq expert nil)
11819 (delete-other-windows)
11820 (split-window-vertically)
11821 (switch-to-buffer-other-window " *Org tags*")
11822 (and (fboundp 'fit-window-to-buffer)
11823 (fit-window-to-buffer))))
11824 ((or (= c ?\C-g)
11825 (and (= c ?q) (not (rassoc c ntable))))
11826 (org-detach-overlay org-tags-overlay)
11827 (setq quit-flag t))
11828 ((= c ?\ )
11829 (setq current nil)
11830 (if exit-after-next (setq exit-after-next 'now)))
11831 ((= c ?\t)
11832 (condition-case nil
11833 (setq tg (completing-read
11834 "Tag: "
11835 (or buffer-tags
11836 (with-current-buffer buf
11837 (org-get-buffer-tags)))))
11838 (quit (setq tg "")))
11839 (when (string-match "\\S-" tg)
11840 (add-to-list 'buffer-tags (list tg))
11841 (if (member tg current)
11842 (setq current (delete tg current))
11843 (push tg current)))
11844 (if exit-after-next (setq exit-after-next 'now)))
11845 ((setq e (rassoc c ntable) tg (car e))
11846 (if (member tg current)
11847 (setq current (delete tg current))
11848 (loop for g in groups do
11849 (if (member tg g)
11850 (mapcar (lambda (x)
11851 (setq current (delete x current)))
11852 g)))
11853 (push tg current))
11854 (if exit-after-next (setq exit-after-next 'now))))
11856 ;; Create a sorted list
11857 (setq current
11858 (sort current
11859 (lambda (a b)
11860 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11861 (if (eq exit-after-next 'now) (throw 'exit t))
11862 (goto-char (point-min))
11863 (beginning-of-line 2)
11864 (delete-region (point) (point-at-eol))
11865 (org-fast-tag-insert "Current" current c-face)
11866 (org-set-current-tags-overlay current ov-prefix)
11867 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
11868 (setq tg (match-string 1))
11869 (add-text-properties (match-beginning 1) (match-end 1)
11870 (list 'face
11871 (cond
11872 ((member tg current) c-face)
11873 ((member tg inherited) i-face)
11874 (t nil)))))
11875 (goto-char (point-min)))))
11876 (org-detach-overlay org-tags-overlay)
11877 (if rtn
11878 (mapconcat 'identity current ":")
11879 nil))))
11881 (defun org-get-tags ()
11882 "Get the TAGS string in the current headline."
11883 (unless (org-on-heading-p t)
11884 (error "Not on a heading"))
11885 (save-excursion
11886 (beginning-of-line 1)
11887 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
11888 (org-match-string-no-properties 1)
11889 "")))
11891 (defun org-get-buffer-tags ()
11892 "Get a table of all tags used in the buffer, for completion."
11893 (let (tags)
11894 (save-excursion
11895 (goto-char (point-min))
11896 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
11897 (mapc (lambda (x) (add-to-list 'tags x))
11898 (org-split-string (org-match-string-no-properties 1) ":"))))
11899 (mapcar 'list tags)))
11901 ;;;; Timestamps
11903 (defvar org-last-changed-timestamp nil)
11904 (defvar org-time-was-given) ; dynamically scoped parameter
11905 (defvar org-ts-what) ; dynamically scoped parameter
11907 (defun org-time-stamp (arg)
11908 "Prompt for a date/time and insert a time stamp.
11909 If the user specifies a time like HH:MM, or if this command is called
11910 with a prefix argument, the time stamp will contain date and time.
11911 Otherwise, only the date will be included. All parts of a date not
11912 specified by the user will be filled in from the current date/time.
11913 So if you press just return without typing anything, the time stamp
11914 will represent the current date/time. If there is already a timestamp
11915 at the cursor, it will be modified."
11916 (interactive "P")
11917 (let (org-time-was-given time)
11918 (cond
11919 ((and (org-at-timestamp-p)
11920 (eq last-command 'org-time-stamp)
11921 (eq this-command 'org-time-stamp))
11922 (insert "--")
11923 (setq time (let ((this-command this-command))
11924 (org-read-date arg 'totime)))
11925 (org-insert-time-stamp time (or org-time-was-given arg)))
11926 ((org-at-timestamp-p)
11927 (setq time (let ((this-command this-command))
11928 (org-read-date arg 'totime)))
11929 (when (org-at-timestamp-p) ; just to get the match data
11930 (replace-match "")
11931 (setq org-last-changed-timestamp
11932 (org-insert-time-stamp time (or org-time-was-given arg))))
11933 (message "Timestamp updated"))
11935 (setq time (let ((this-command this-command))
11936 (org-read-date arg 'totime)))
11937 (org-insert-time-stamp time (or org-time-was-given arg))))))
11939 (defun org-time-stamp-inactive (&optional arg)
11940 "Insert an inactive time stamp.
11941 An inactive time stamp is enclosed in square brackets instead of angle
11942 brackets. It is inactive in the sense that it does not trigger agenda entries,
11943 does not link to the calendar and cannot be changed with the S-cursor keys.
11944 So these are more for recording a certain time/date."
11945 (interactive "P")
11946 (let (org-time-was-given time)
11947 (setq time (org-read-date arg 'totime))
11948 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
11950 (defvar org-date-ovl (org-make-overlay 1 1))
11951 (org-overlay-put org-date-ovl 'face 'org-warning)
11952 (org-detach-overlay org-date-ovl)
11954 (defvar org-ans1) ; dynamically scoped parameter
11955 (defvar org-ans2) ; dynamically scoped parameter
11957 (defun org-read-date (&optional with-time to-time from-string prompt)
11958 "Read a date and make things smooth for the user.
11959 The prompt will suggest to enter an ISO date, but you can also enter anything
11960 which will at least partially be understood by `parse-time-string'.
11961 Unrecognized parts of the date will default to the current day, month, year,
11962 hour and minute. For example,
11963 3-2-5 --> 2003-02-05
11964 feb 15 --> currentyear-02-15
11965 sep 12 9 --> 2009-09-12
11966 12:45 --> today 12:45
11967 22 sept 0:34 --> currentyear-09-22 0:34
11968 12 --> currentyear-currentmonth-12
11969 Fri --> nearest Friday (today or later)
11970 +4 --> four days from today (only if +N is the only thing given)
11971 etc.
11972 The function understands only English month and weekday abbreviations,
11973 but this can be configured with the variables `parse-time-months' and
11974 `parse-time-weekdays'.
11976 While prompting, a calendar is popped up - you can also select the
11977 date with the mouse (button 1). The calendar shows a period of three
11978 months. To scroll it to other months, use the keys `>' and `<'.
11979 If you don't like the calendar, turn it off with
11980 \(setq org-popup-calendar-for-date-prompt nil)
11982 With optional argument TO-TIME, the date will immediately be converted
11983 to an internal time.
11984 With an optional argument WITH-TIME, the prompt will suggest to also
11985 insert a time. Note that when WITH-TIME is not set, you can still
11986 enter a time, and this function will inform the calling routine about
11987 this change. The calling routine may then choose to change the format
11988 used to insert the time stamp into the buffer to include the time."
11989 (require 'parse-time)
11990 (let* ((org-time-stamp-rounding-minutes
11991 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
11992 (ct (org-current-time))
11993 (default-time
11994 ;; Default time is either today, or, when entering a range,
11995 ;; the range start.
11996 (if (save-excursion
11997 (re-search-backward
11998 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11999 (- (point) 20) t))
12000 (apply
12001 'encode-time
12002 (mapcar (lambda(x) (or x 0))
12003 (parse-time-string (match-string 1))))
12004 ct))
12005 (calendar-move-hook nil)
12006 (view-diary-entries-initially nil)
12007 (view-calendar-holidays-initially nil)
12008 (timestr (format-time-string
12009 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
12010 (prompt (concat (if prompt (concat prompt " ") "")
12011 (format "YYYY-MM-DD [%s]: " timestr)))
12012 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
12013 second minute hour day month year tl wday wday1)
12015 (cond
12016 (from-string (setq ans from-string))
12017 (org-popup-calendar-for-date-prompt
12018 (save-excursion
12019 (save-window-excursion
12020 (calendar)
12021 (calendar-forward-day (- (time-to-days default-time)
12022 (calendar-absolute-from-gregorian
12023 (calendar-current-date))))
12024 (org-eval-in-calendar nil)
12025 (let* ((old-map (current-local-map))
12026 (map (copy-keymap calendar-mode-map))
12027 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12028 (define-key map (kbd "RET") 'org-calendar-select)
12029 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
12030 'org-calendar-select-mouse)
12031 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
12032 'org-calendar-select-mouse)
12033 (define-key minibuffer-local-map [(meta shift left)]
12034 (lambda () (interactive)
12035 (org-eval-in-calendar '(calendar-backward-month 1))))
12036 (define-key minibuffer-local-map [(meta shift right)]
12037 (lambda () (interactive)
12038 (org-eval-in-calendar '(calendar-forward-month 1))))
12039 (define-key minibuffer-local-map [(shift up)]
12040 (lambda () (interactive)
12041 (org-eval-in-calendar '(calendar-backward-week 1))))
12042 (define-key minibuffer-local-map [(shift down)]
12043 (lambda () (interactive)
12044 (org-eval-in-calendar '(calendar-forward-week 1))))
12045 (define-key minibuffer-local-map [(shift left)]
12046 (lambda () (interactive)
12047 (org-eval-in-calendar '(calendar-backward-day 1))))
12048 (define-key minibuffer-local-map [(shift right)]
12049 (lambda () (interactive)
12050 (org-eval-in-calendar '(calendar-forward-day 1))))
12051 (define-key minibuffer-local-map ">"
12052 (lambda () (interactive)
12053 (org-eval-in-calendar '(scroll-calendar-left 1))))
12054 (define-key minibuffer-local-map "<"
12055 (lambda () (interactive)
12056 (org-eval-in-calendar '(scroll-calendar-right 1))))
12057 (unwind-protect
12058 (progn
12059 (use-local-map map)
12060 (setq org-ans0 (read-string prompt "" nil nil))
12061 ; (if (not (string-match "\\S-" org-ans0)) (setq org-ans0 nil))
12062 ;; org-ans0: from prompt
12063 ;; org-ans1: from mouse click
12064 ;; org-ans2: from calendar motion
12065 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12066 (use-local-map old-map))))))
12067 (t ; Naked prompt only
12068 (setq ans (read-string prompt "" nil timestr))))
12069 (org-detach-overlay org-date-ovl)
12071 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
12072 (setq deltadays (string-to-number ans) ans ""))
12074 (if (string-match
12075 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12076 (progn
12077 (setq year (if (match-end 2)
12078 (string-to-number (match-string 2 ans))
12079 (string-to-number (format-time-string "%Y")))
12080 month (string-to-number (match-string 3 ans))
12081 day (string-to-number (match-string 4 ans)))
12082 (if (< year 100) (setq year (+ 2000 year)))
12083 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12084 t nil ans))))
12085 (setq tl (parse-time-string ans)
12086 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
12087 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
12088 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
12089 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
12090 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
12091 second (or (nth 0 tl) 0)
12092 wday (nth 6 tl))
12093 (setq day (+ day deltadays))
12094 (when (and wday (not (nth 3 tl)))
12095 ;; Weekday was given, but no day, so pick that day in the week
12096 ;; on or after the derived date.
12097 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12098 (unless (equal wday wday1)
12099 (setq day (+ day (% (- wday wday1 -7) 7)))))
12100 (if (and (boundp 'org-time-was-given)
12101 (nth 2 tl))
12102 (setq org-time-was-given t))
12103 (if (< year 100) (setq year (+ 2000 year)))
12104 (if to-time
12105 (encode-time second minute hour day month year)
12106 (if (or (nth 1 tl) (nth 2 tl))
12107 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
12108 (format "%04d-%02d-%02d" year month day)))))
12110 (defun org-eval-in-calendar (form)
12111 "Eval FORM in the calendar window and return to current window.
12112 Also, store the cursor date in variable org-ans2."
12113 (let ((sw (selected-window)))
12114 (select-window (get-buffer-window "*Calendar*"))
12115 (eval form)
12116 (when (calendar-cursor-to-date)
12117 (let* ((date (calendar-cursor-to-date))
12118 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12119 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12120 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12121 (select-window sw)))
12123 (defun org-calendar-select ()
12124 "Return to `org-read-date' with the date currently selected.
12125 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12126 (interactive)
12127 (when (calendar-cursor-to-date)
12128 (let* ((date (calendar-cursor-to-date))
12129 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12130 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12131 (if (active-minibuffer-window) (exit-minibuffer))))
12133 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
12134 "Insert a date stamp for the date given by the internal TIME.
12135 WITH-HM means, use the stamp format that includes the time of the day.
12136 INACTIVE means use square brackets instead of angular ones, so that the
12137 stamp will not contribute to the agenda.
12138 PRE and POST are optional strings to be inserted before and after the
12139 stamp.
12140 The command returns the inserted time stamp."
12141 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12142 stamp)
12143 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12144 (insert (or pre ""))
12145 (insert (setq stamp (format-time-string fmt time)))
12146 (insert (or post ""))
12147 stamp))
12149 (defun org-toggle-time-stamp-overlays ()
12150 "Toggle the use of custom time stamp formats."
12151 (interactive)
12152 (setq org-display-custom-times (not org-display-custom-times))
12153 (unless org-display-custom-times
12154 (let ((p (point-min)) (bmp (buffer-modified-p)))
12155 (while (setq p (next-single-property-change p 'display))
12156 (if (and (get-text-property p 'display)
12157 (eq (get-text-property p 'face) 'org-date))
12158 (remove-text-properties
12159 p (setq p (next-single-property-change p 'display))
12160 '(display t))))
12161 (set-buffer-modified-p bmp)))
12162 (if (featurep 'xemacs)
12163 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12164 (org-restart-font-lock)
12165 (setq org-table-may-need-update t)
12166 (if org-display-custom-times
12167 (message "Time stamps are overlayed with custom format")
12168 (message "Time stamp overlays removed")))
12170 (defun org-display-custom-time (beg end)
12171 "Overlay modified time stamp format over timestamp between BED and END."
12172 (let* ((t1 (save-match-data
12173 (org-parse-time-string (buffer-substring beg end) t)))
12174 (w1 (- end beg))
12175 (with-hm (and (nth 1 t1) (nth 2 t1)))
12176 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
12177 (time (org-fix-decoded-time t1))
12178 (str (org-add-props
12179 (format-time-string
12180 (substring tf 1 -1) (apply 'encode-time time))
12181 nil 'mouse-face 'highlight))
12182 (w2 (length str)))
12183 (if (not (= w2 w1))
12184 (add-text-properties (1+ beg) (+ 2 beg)
12185 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12186 (if (featurep 'xemacs)
12187 (progn
12188 (put-text-property beg end 'invisible t)
12189 (put-text-property beg end 'end-glyph (make-glyph str)))
12190 (put-text-property beg end 'display str))))
12192 (defun org-translate-time (string)
12193 "Translate all timestamps in STRING to custom format.
12194 But do this only if the variable `org-display-custom-times' is set."
12195 (when org-display-custom-times
12196 (save-match-data
12197 (let* ((start 0)
12198 (re org-ts-regexp-both)
12199 t1 with-hm inactive tf time str beg end)
12200 (while (setq start (string-match re string start))
12201 (setq beg (match-beginning 0)
12202 end (match-end 0)
12203 t1 (save-match-data
12204 (org-parse-time-string (substring string beg end) t))
12205 with-hm (and (nth 1 t1) (nth 2 t1))
12206 inactive (equal (substring string beg (1+ beg)) "[")
12207 tf (funcall (if with-hm 'cdr 'car)
12208 org-time-stamp-custom-formats)
12209 time (org-fix-decoded-time t1)
12210 str (format-time-string
12211 (concat
12212 (if inactive "[" "<") (substring tf 1 -1)
12213 (if inactive "]" ">"))
12214 (apply 'encode-time time))
12215 string (replace-match str t t string)
12216 start (+ start (length str)))))))
12217 string)
12219 (defun org-fix-decoded-time (time)
12220 "Set 0 instead of nil for the first 6 elements of time.
12221 Don't touch the rest."
12222 (let ((n 0))
12223 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12225 (defun org-days-to-time (timestamp-string)
12226 "Difference between TIMESTAMP-STRING and now in days."
12227 (- (time-to-days (org-time-string-to-time timestamp-string))
12228 (time-to-days (current-time))))
12230 (defun org-deadline-close (timestamp-string &optional ndays)
12231 "Is the time in TIMESTAMP-STRING close to the current date?"
12232 (and (< (org-days-to-time timestamp-string)
12233 (or ndays org-deadline-warning-days))
12234 (not (org-entry-is-done-p))))
12236 (defun org-calendar-select-mouse (ev)
12237 "Return to `org-read-date' with the date currently selected.
12238 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12239 (interactive "e")
12240 (mouse-set-point ev)
12241 (when (calendar-cursor-to-date)
12242 (let* ((date (calendar-cursor-to-date))
12243 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12244 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12245 (if (active-minibuffer-window) (exit-minibuffer))))
12247 (defun org-check-deadlines (ndays)
12248 "Check if there are any deadlines due or past due.
12249 A deadline is considered due if it happens within `org-deadline-warning-days'
12250 days from today's date. If the deadline appears in an entry marked DONE,
12251 it is not shown. The prefix arg NDAYS can be used to test that many
12252 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12253 (interactive "P")
12254 (let* ((org-warn-days
12255 (cond
12256 ((equal ndays '(4)) 100000)
12257 (ndays (prefix-numeric-value ndays))
12258 (t org-deadline-warning-days)))
12259 (case-fold-search nil)
12260 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12261 (callback
12262 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12264 (message "%d deadlines past-due or due within %d days"
12265 (org-occur regexp nil callback)
12266 org-warn-days)))
12268 (defun org-evaluate-time-range (&optional to-buffer)
12269 "Evaluate a time range by computing the difference between start and end.
12270 Normally the result is just printed in the echo area, but with prefix arg
12271 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12272 If the time range is actually in a table, the result is inserted into the
12273 next column.
12274 For time difference computation, a year is assumed to be exactly 365
12275 days in order to avoid rounding problems."
12276 (interactive "P")
12278 (org-clock-update-time-maybe)
12279 (save-excursion
12280 (unless (org-at-date-range-p)
12281 (goto-char (point-at-bol))
12282 (re-search-forward org-tr-regexp (point-at-eol) t))
12283 (if (not (org-at-date-range-p))
12284 (error "Not at a time-stamp range, and none found in current line")))
12285 (let* ((ts1 (match-string 1))
12286 (ts2 (match-string 2))
12287 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12288 (match-end (match-end 0))
12289 (time1 (org-time-string-to-time ts1))
12290 (time2 (org-time-string-to-time ts2))
12291 (t1 (time-to-seconds time1))
12292 (t2 (time-to-seconds time2))
12293 (diff (abs (- t2 t1)))
12294 (negative (< (- t2 t1) 0))
12295 ;; (ys (floor (* 365 24 60 60)))
12296 (ds (* 24 60 60))
12297 (hs (* 60 60))
12298 (fy "%dy %dd %02d:%02d")
12299 (fy1 "%dy %dd")
12300 (fd "%dd %02d:%02d")
12301 (fd1 "%dd")
12302 (fh "%02d:%02d")
12303 y d h m align)
12304 (if havetime
12305 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12307 d (floor (/ diff ds)) diff (mod diff ds)
12308 h (floor (/ diff hs)) diff (mod diff hs)
12309 m (floor (/ diff 60)))
12310 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12312 d (floor (+ (/ diff ds) 0.5))
12313 h 0 m 0))
12314 (if (not to-buffer)
12315 (message (org-make-tdiff-string y d h m))
12316 (when (org-at-table-p)
12317 (goto-char match-end)
12318 (setq align t)
12319 (and (looking-at " *|") (goto-char (match-end 0))))
12320 (if (looking-at
12321 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12322 (replace-match ""))
12323 (if negative (insert " -"))
12324 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12325 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12326 (insert " " (format fh h m))))
12327 (if align (org-table-align))
12328 (message "Time difference inserted")))))
12330 (defun org-make-tdiff-string (y d h m)
12331 (let ((fmt "")
12332 (l nil))
12333 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12334 l (push y l)))
12335 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12336 l (push d l)))
12337 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12338 l (push h l)))
12339 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12340 l (push m l)))
12341 (apply 'format fmt (nreverse l))))
12343 (defun org-time-string-to-time (s)
12344 (apply 'encode-time (org-parse-time-string s)))
12346 (defun org-parse-time-string (s &optional nodefault)
12347 "Parse the standard Org-mode time string.
12348 This should be a lot faster than the normal `parse-time-string'.
12349 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12350 hour and minute fields will be nil if not given."
12351 (if (string-match org-ts-regexp1 s)
12352 (list 0
12353 (if (or (match-beginning 8) (not nodefault))
12354 (string-to-number (or (match-string 8 s) "0")))
12355 (if (or (match-beginning 7) (not nodefault))
12356 (string-to-number (or (match-string 7 s) "0")))
12357 (string-to-number (match-string 4 s))
12358 (string-to-number (match-string 3 s))
12359 (string-to-number (match-string 2 s))
12360 nil nil nil)
12361 (make-list 9 0)))
12363 (defun org-timestamp-up (&optional arg)
12364 "Increase the date item at the cursor by one.
12365 If the cursor is on the year, change the year. If it is on the month or
12366 the day, change that.
12367 With prefix ARG, change by that many units."
12368 (interactive "p")
12369 (org-timestamp-change (prefix-numeric-value arg)))
12371 (defun org-timestamp-down (&optional arg)
12372 "Decrease the date item at the cursor by one.
12373 If the cursor is on the year, change the year. If it is on the month or
12374 the day, change that.
12375 With prefix ARG, change by that many units."
12376 (interactive "p")
12377 (org-timestamp-change (- (prefix-numeric-value arg))))
12379 (defun org-timestamp-up-day (&optional arg)
12380 "Increase the date in the time stamp by one day.
12381 With prefix ARG, change that many days."
12382 (interactive "p")
12383 (if (and (not (org-at-timestamp-p t))
12384 (org-on-heading-p))
12385 (org-todo 'up)
12386 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12388 (defun org-timestamp-down-day (&optional arg)
12389 "Decrease the date in the time stamp by one day.
12390 With prefix ARG, change that many days."
12391 (interactive "p")
12392 (if (and (not (org-at-timestamp-p t))
12393 (org-on-heading-p))
12394 (org-todo 'down)
12395 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12397 (defsubst org-pos-in-match-range (pos n)
12398 (and (match-beginning n)
12399 (<= (match-beginning n) pos)
12400 (>= (match-end n) pos)))
12402 (defun org-at-timestamp-p (&optional inactive-ok)
12403 "Determine if the cursor is in or at a timestamp."
12404 (interactive)
12405 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12406 (pos (point))
12407 (ans (or (looking-at tsr)
12408 (save-excursion
12409 (skip-chars-backward "^[<\n\r\t")
12410 (if (> (point) 1) (backward-char 1))
12411 (and (looking-at tsr)
12412 (> (- (match-end 0) pos) -1))))))
12413 (and (boundp 'org-ts-what)
12414 (setq org-ts-what
12415 (cond
12416 ((org-pos-in-match-range pos 2) 'year)
12417 ((org-pos-in-match-range pos 3) 'month)
12418 ((org-pos-in-match-range pos 7) 'hour)
12419 ((org-pos-in-match-range pos 8) 'minute)
12420 ((or (org-pos-in-match-range pos 4)
12421 (org-pos-in-match-range pos 5)) 'day)
12422 (t 'day))))
12423 ans))
12425 (defun org-timestamp-change (n &optional what)
12426 "Change the date in the time stamp at point.
12427 The date will be changed by N times WHAT. WHAT can be `day', `month',
12428 `year', `minute', `second'. If WHAT is not given, the cursor position
12429 in the timestamp determines what will be changed."
12430 (let ((pos (point))
12431 with-hm inactive
12432 org-ts-what
12433 ts time time0)
12434 (if (not (org-at-timestamp-p t))
12435 (error "Not at a timestamp"))
12436 (if (and (not what) (not (eq org-ts-what 'day))
12437 org-display-custom-times
12438 (get-text-property (point) 'display)
12439 (not (get-text-property (1- (point)) 'display)))
12440 (setq org-ts-what 'day))
12441 (setq org-ts-what (or what org-ts-what)
12442 with-hm (<= (abs (- (cdr org-ts-lengths)
12443 (- (match-end 0) (match-beginning 0))))
12445 inactive (= (char-after (match-beginning 0)) ?\[)
12446 ts (match-string 0))
12447 (replace-match "")
12448 (setq time0 (org-parse-time-string ts))
12449 (setq time
12450 (apply 'encode-time
12451 (append
12452 (list (or (car time0) 0))
12453 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
12454 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
12455 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
12456 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
12457 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
12458 (nthcdr 6 time0))))
12459 (if (eq what 'calendar)
12460 (let ((cal-date
12461 (save-excursion
12462 (save-match-data
12463 (set-buffer "*Calendar*")
12464 (calendar-cursor-to-date)))))
12465 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12466 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12467 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12468 (setcar time0 (or (car time0) 0))
12469 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12470 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
12471 (setq time (apply 'encode-time time0))))
12472 (setq org-last-changed-timestamp
12473 (org-insert-time-stamp time with-hm inactive))
12474 (org-clock-update-time-maybe)
12475 (goto-char pos)
12476 ;; Try to recenter the calendar window, if any
12477 (if (and org-calendar-follow-timestamp-change
12478 (get-buffer-window "*Calendar*" t)
12479 (memq org-ts-what '(day month year)))
12480 (org-recenter-calendar (time-to-days time)))))
12482 (defun org-recenter-calendar (date)
12483 "If the calendar is visible, recenter it to DATE."
12484 (let* ((win (selected-window))
12485 (cwin (get-buffer-window "*Calendar*" t))
12486 (calendar-move-hook nil))
12487 (when cwin
12488 (select-window cwin)
12489 (calendar-goto-date (if (listp date) date
12490 (calendar-gregorian-from-absolute date)))
12491 (select-window win))))
12493 (defun org-goto-calendar (&optional arg)
12494 "Go to the Emacs calendar at the current date.
12495 If there is a time stamp in the current line, go to that date.
12496 A prefix ARG can be used to force the current date."
12497 (interactive "P")
12498 (let ((tsr org-ts-regexp) diff
12499 (calendar-move-hook nil)
12500 (view-calendar-holidays-initially nil)
12501 (view-diary-entries-initially nil))
12502 (if (or (org-at-timestamp-p)
12503 (save-excursion
12504 (beginning-of-line 1)
12505 (looking-at (concat ".*" tsr))))
12506 (let ((d1 (time-to-days (current-time)))
12507 (d2 (time-to-days
12508 (org-time-string-to-time (match-string 1)))))
12509 (setq diff (- d2 d1))))
12510 (calendar)
12511 (calendar-goto-today)
12512 (if (and diff (not arg)) (calendar-forward-day diff))))
12514 (defun org-date-from-calendar ()
12515 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12516 If there is already a time stamp at the cursor position, update it."
12517 (interactive)
12518 (org-timestamp-change 0 'calendar))
12520 ;;; The clock for measuring work time.
12522 (defvar org-clock-marker (make-marker)
12523 "Marker recording the last clock-in.")
12525 (defun org-clock-in ()
12526 "Start the clock on the current item.
12527 If necessary, clock-out of the currently active clock."
12528 (interactive)
12529 (org-clock-out t)
12530 (let (ts)
12531 (save-excursion
12532 (org-back-to-heading t)
12533 (beginning-of-line 2)
12534 (when (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12535 (not (equal (match-string 1) org-clock-string)))
12536 ;; First line hast scheduling info, move one further
12537 (beginning-of-line 2)
12538 (or (bolp) (newline)))
12539 (insert "\n") (backward-char 1)
12540 (indent-relative)
12541 (insert org-clock-string " ")
12542 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12543 (move-marker org-clock-marker (point) (buffer-base-buffer))
12544 (message "Clock started at %s" ts))))
12546 (defun org-clock-out (&optional fail-quietly)
12547 "Stop the currently running clock.
12548 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
12549 (interactive)
12550 (catch 'exit
12551 (if (not (marker-buffer org-clock-marker))
12552 (if fail-quietly (throw 'exit t) (error "No active clock")))
12553 (let (ts te s h m)
12554 (save-excursion
12555 (set-buffer (marker-buffer org-clock-marker))
12556 (goto-char org-clock-marker)
12557 (beginning-of-line 1)
12558 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12559 (equal (match-string 1) org-clock-string))
12560 (setq ts (match-string 2))
12561 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
12562 (goto-char org-clock-marker)
12563 (insert "--")
12564 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12565 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
12566 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
12567 h (floor (/ s 3600))
12568 s (- s (* 3600 h))
12569 m (floor (/ s 60))
12570 s (- s (* 60 s)))
12571 (insert " => " (format "%2d:%02d" h m))
12572 (move-marker org-clock-marker nil)
12573 (org-add-log-maybe 'clock-out)
12574 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
12576 (defun org-clock-cancel ()
12577 "Cancel the running clock be removing the start timestamp."
12578 (interactive)
12579 (if (not (marker-buffer org-clock-marker))
12580 (error "No active clock"))
12581 (save-excursion
12582 (set-buffer (marker-buffer org-clock-marker))
12583 (goto-char org-clock-marker)
12584 (delete-region (1- (point-at-bol)) (point-at-eol)))
12585 (message "Clock canceled"))
12587 (defvar org-clock-file-total-minutes nil
12588 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
12589 (make-variable-buffer-local 'org-clock-file-total-minutes)
12591 (defun org-clock-sum (&optional tstart tend)
12592 "Sum the times for each subtree.
12593 Puts the resulting times in minutes as a text property on each headline."
12594 (interactive)
12595 (let* ((bmp (buffer-modified-p))
12596 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
12597 org-clock-string
12598 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
12599 (lmax 30)
12600 (ltimes (make-vector lmax 0))
12601 (t1 0)
12602 (level 0)
12603 ts te dt
12604 time)
12605 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
12606 (save-excursion
12607 (goto-char (point-max))
12608 (while (re-search-backward re nil t)
12609 (if (match-end 2)
12610 ;; A time
12611 (setq ts (match-string 2)
12612 te (match-string 3)
12613 ts (time-to-seconds
12614 (apply 'encode-time (org-parse-time-string ts)))
12615 te (time-to-seconds
12616 (apply 'encode-time (org-parse-time-string te)))
12617 ts (if tstart (max ts tstart) ts)
12618 te (if tend (min te tend) te)
12619 dt (- te ts)
12620 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
12621 ;; A headline
12622 (setq level (- (match-end 1) (match-beginning 1)))
12623 (when (or (> t1 0) (> (aref ltimes level) 0))
12624 (loop for l from 0 to level do
12625 (aset ltimes l (+ (aref ltimes l) t1)))
12626 (setq t1 0 time (aref ltimes level))
12627 (loop for l from level to (1- lmax) do
12628 (aset ltimes l 0))
12629 (goto-char (match-beginning 0))
12630 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
12631 (setq org-clock-file-total-minutes (aref ltimes 0)))
12632 (set-buffer-modified-p bmp)))
12634 (defun org-clock-display (&optional total-only)
12635 "Show subtree times in the entire buffer.
12636 If TOTAL-ONLY is non-nil, only show the total time for the entire file
12637 in the echo area."
12638 (interactive)
12639 (org-remove-clock-overlays)
12640 (let (time h m p)
12641 (org-clock-sum)
12642 (unless total-only
12643 (save-excursion
12644 (goto-char (point-min))
12645 (while (setq p (next-single-property-change (point) :org-clock-minutes))
12646 (goto-char p)
12647 (when (setq time (get-text-property p :org-clock-minutes))
12648 (org-put-clock-overlay time (funcall outline-level))))
12649 (setq h (/ org-clock-file-total-minutes 60)
12650 m (- org-clock-file-total-minutes (* 60 h)))
12651 ;; Arrange to remove the overlays upon next change.
12652 (when org-remove-highlights-with-change
12653 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
12654 nil 'local))))
12655 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
12657 (defvar org-clock-overlays nil)
12658 (make-variable-buffer-local 'org-clock-overlays)
12660 (defun org-put-clock-overlay (time &optional level)
12661 "Put an overlays on the current line, displaying TIME.
12662 If LEVEL is given, prefix time with a corresponding number of stars.
12663 This creates a new overlay and stores it in `org-clock-overlays', so that it
12664 will be easy to remove."
12665 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
12666 (l (if level (org-get-legal-level level 0) 0))
12667 (off 0)
12668 ov tx)
12669 (move-to-column c)
12670 (unless (eolp) (skip-chars-backward "^ \t"))
12671 (skip-chars-backward " \t")
12672 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
12673 tx (concat (buffer-substring (1- (point)) (point))
12674 (make-string (+ off (max 0 (- c (current-column)))) ?.)
12675 (org-add-props (format "%s %2d:%02d%s"
12676 (make-string l ?*) h m
12677 (make-string (- 10 l) ?\ ))
12678 '(face secondary-selection))
12679 ""))
12680 (if (not (featurep 'xemacs))
12681 (org-overlay-put ov 'display tx)
12682 (org-overlay-put ov 'invisible t)
12683 (org-overlay-put ov 'end-glyph (make-glyph tx)))
12684 (push ov org-clock-overlays)))
12686 (defun org-remove-clock-overlays (&optional beg end noremove)
12687 "Remove the occur highlights from the buffer.
12688 BEG and END are ignored. If NOREMOVE is nil, remove this function
12689 from the `before-change-functions' in the current buffer."
12690 (interactive)
12691 (unless org-inhibit-highlight-removal
12692 (mapc 'org-delete-overlay org-clock-overlays)
12693 (setq org-clock-overlays nil)
12694 (unless noremove
12695 (remove-hook 'before-change-functions
12696 'org-remove-clock-overlays 'local))))
12698 (defun org-clock-out-if-current ()
12699 "Clock out if the current entry contains the running clock.
12700 This is used to stop the clock after a TODO entry is marked DONE."
12701 (when (and (equal state org-done-string)
12702 (equal (marker-buffer org-clock-marker) (current-buffer))
12703 (< (point) org-clock-marker)
12704 (> (save-excursion (outline-next-heading) (point))
12705 org-clock-marker))
12706 ;; Clock out, but don't accept a logging message for this.
12707 (let ((org-log-done (if (and (listp org-log-done)
12708 (member 'clock-out org-log-done))
12709 '(done)
12710 org-log-done)))
12711 (org-clock-out))))
12713 (add-hook 'org-after-todo-state-change-hook
12714 'org-clock-out-if-current)
12716 (defun org-check-running-clock ()
12717 "Check if the current buffer contains the running clock.
12718 If yes, offer to stop it and to save the buffer with the changes."
12719 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
12720 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
12721 (buffer-name))))
12722 (org-clock-out)
12723 (when (y-or-n-p "Save changed buffer?")
12724 (save-buffer))))
12726 (defun org-clock-report ()
12727 "Create a table containing a report about clocked time.
12728 If the buffer contains lines
12729 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
12731 #+END: clocktable
12732 then the table will be inserted between these lines, replacing whatever
12733 is was there before. If these lines are not in the buffer, the table
12734 is inserted at point, surrounded by the special lines.
12735 The BEGIN line can contain parameters. Allowed are:
12736 :maxlevel The maximum level to be included in the table. Default is 3.
12737 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
12738 (interactive)
12739 (org-remove-clock-overlays)
12740 (unless (org-find-dblock "clocktable")
12741 (org-create-dblock (list :name "clocktable"
12742 :maxlevel 2 :emphasize nil)))
12743 (org-update-dblock))
12745 (defun org-clock-update-time-maybe ()
12746 "If this is a CLOCK line, update it and return t.
12747 Otherwise, return nil."
12748 (interactive)
12749 (save-excursion
12750 (beginning-of-line 1)
12751 (skip-chars-forward " \t")
12752 (when (looking-at org-clock-string)
12753 (let ((re (concat "[ \t]*" org-clock-string
12754 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
12755 "\\([ \t]*=>.*\\)?"))
12756 ts te h m s)
12757 (if (not (looking-at re))
12759 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
12760 (end-of-line 1)
12761 (setq ts (match-string 1)
12762 te (match-string 2))
12763 (setq s (- (time-to-seconds
12764 (apply 'encode-time (org-parse-time-string te)))
12765 (time-to-seconds
12766 (apply 'encode-time (org-parse-time-string ts))))
12767 h (floor (/ s 3600))
12768 s (- s (* 3600 h))
12769 m (floor (/ s 60))
12770 s (- s (* 60 s)))
12771 (insert " => " (format "%2d:%02d" h m))
12772 t)))))
12774 (defun org-clock-special-range (key &optional time as-strings)
12775 "Return two times bordering a special time range.
12776 Key is a symbol specifying the range and can be one of `today', `yesterday',
12777 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
12778 A week starts Monday 0:00 and ends Sunday 24:00.
12779 The range is determined relative to TIME. TIME defaults to the current time.
12780 The return value is a cons cell with two internal times like the ones
12781 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
12782 the returned times will be formatted strings."
12783 (let* ((tm (decode-time (or time (current-time))))
12784 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
12785 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
12786 (dow (nth 6 tm))
12787 s1 m1 h1 d1 month1 y1 diff ts te fm)
12788 (cond
12789 ((eq key 'today)
12790 (setq h 0 m 0 h1 24 m1 0))
12791 ((eq key 'yesterday)
12792 (setq d (1- d) h 0 m 0 h1 24 m1 0))
12793 ((eq key 'thisweek)
12794 (setq diff (if (= dow 0) 6 (1- dow))
12795 m 0 h 0 d (- d diff) d1 (+ 7 d)))
12796 ((eq key 'lastweek)
12797 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
12798 m 0 h 0 d (- d diff) d1 (+ 7 d)))
12799 ((eq key 'thismonth)
12800 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
12801 ((eq key 'lastmonth)
12802 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
12803 ((eq key 'thisyear)
12804 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
12805 ((eq key 'lastyear)
12806 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
12807 (t (error "No such time block %s" key)))
12808 (setq ts (encode-time s m h d month y)
12809 te (encode-time (or s1 s) (or m1 m) (or h1 h)
12810 (or d1 d) (or month1 month) (or y1 y)))
12811 (setq fm (cdr org-time-stamp-formats))
12812 (if as-strings
12813 (cons (format-time-string fm ts) (format-time-string fm te))
12814 (cons ts te))))
12816 (defun org-dblock-write:clocktable (params)
12817 "Write the standard clocktable."
12818 (let ((hlchars '((1 . "*") (2 . ?/)))
12819 (emph nil)
12820 (ins (make-marker))
12821 ipos time h m p level hlc hdl maxlevel
12822 ts te cc block)
12823 (setq maxlevel (or (plist-get params :maxlevel) 3)
12824 emph (plist-get params :emphasize)
12825 ts (plist-get params :tstart)
12826 te (plist-get params :tend)
12827 block (plist-get params :block))
12828 (when block
12829 (setq cc (org-clock-special-range block nil t)
12830 ts (car cc) te (cdr cc)))
12831 (if ts (setq ts (time-to-seconds
12832 (apply 'encode-time (org-parse-time-string ts)))))
12833 (if te (setq te (time-to-seconds
12834 (apply 'encode-time (org-parse-time-string te)))))
12835 (move-marker ins (point))
12836 (setq ipos (point))
12837 (insert-before-markers "Clock summary at ["
12838 (substring
12839 (format-time-string (cdr org-time-stamp-formats))
12840 1 -1)
12841 "]."
12842 (if block
12843 (format " Considered range is /%s/." block)
12845 "\n\n|L|Headline|Time|\n")
12846 (org-clock-sum ts te)
12847 (setq h (/ org-clock-file-total-minutes 60)
12848 m (- org-clock-file-total-minutes (* 60 h)))
12849 (insert-before-markers "|-\n|0|" "*Total file time*| "
12850 (format "*%d:%02d*" h m)
12851 "|\n")
12852 (goto-char (point-min))
12853 (while (setq p (next-single-property-change (point) :org-clock-minutes))
12854 (goto-char p)
12855 (when (setq time (get-text-property p :org-clock-minutes))
12856 (save-excursion
12857 (beginning-of-line 1)
12858 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
12859 (setq level (- (match-end 1) (match-beginning 1)))
12860 (<= level maxlevel))
12861 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
12862 hdl (match-string 2)
12863 h (/ time 60)
12864 m (- time (* 60 h)))
12865 (goto-char ins)
12866 (if (= level 1) (insert-before-markers "|-\n"))
12867 (insert-before-markers
12868 "| " (int-to-string level) "|" hlc hdl hlc " |"
12869 (make-string (1- level) ?|)
12871 (format "%d:%02d" h m)
12873 " |\n")))))
12874 (goto-char ins)
12875 (backward-delete-char 1)
12876 (goto-char ipos)
12877 (skip-chars-forward "^|")
12878 (org-table-align)))
12880 ;; FIXME: I don't think anybody uses this, ask David
12881 (defun org-collect-clock-time-entries ()
12882 "Return an internal list with clocking information.
12883 This list has one entry for each CLOCK interval.
12884 FIXME: describe the elements."
12885 (interactive)
12886 (let ((re (concat "^[ \t]*" org-clock-string
12887 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
12888 rtn beg end next cont level title total closedp leafp
12889 clockpos titlepos h m donep)
12890 (save-excursion
12891 (org-clock-sum)
12892 (goto-char (point-min))
12893 (while (re-search-forward re nil t)
12894 (setq clockpos (match-beginning 0)
12895 beg (match-string 1) end (match-string 2)
12896 cont (match-end 0))
12897 (setq beg (apply 'encode-time (org-parse-time-string beg))
12898 end (apply 'encode-time (org-parse-time-string end)))
12899 (org-back-to-heading t)
12900 (setq donep (org-entry-is-done-p))
12901 (setq titlepos (point)
12902 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
12903 h (/ total 60) m (- total (* 60 h))
12904 total (cons h m))
12905 (looking-at "\\(\\*+\\) +\\(.*\\)")
12906 (setq level (- (match-end 1) (match-beginning 1))
12907 title (org-match-string-no-properties 2))
12908 (save-excursion (outline-next-heading) (setq next (point)))
12909 (setq closedp (re-search-forward org-closed-time-regexp next t))
12910 (goto-char next)
12911 (setq leafp (and (looking-at "^\\*+ ")
12912 (<= (- (match-end 0) (point)) level)))
12913 (push (list beg end clockpos closedp donep
12914 total title titlepos level leafp)
12915 rtn)
12916 (goto-char cont)))
12917 (nreverse rtn)))
12919 ;;;; Agenda, and Diary Integration
12921 ;;; Define the Org-agenda-mode
12923 (defvar org-agenda-mode-map (make-sparse-keymap)
12924 "Keymap for `org-agenda-mode'.")
12926 (defvar org-agenda-menu) ; defined later in this file.
12927 (defvar org-agenda-follow-mode nil)
12928 (defvar org-agenda-show-log nil)
12929 (defvar org-agenda-redo-command nil)
12930 (defvar org-agenda-mode-hook nil)
12931 (defvar org-agenda-type nil)
12932 (defvar org-agenda-force-single-file nil)
12934 (defun org-agenda-mode ()
12935 "Mode for time-sorted view on action items in Org-mode files.
12937 The following commands are available:
12939 \\{org-agenda-mode-map}"
12940 (interactive)
12941 (kill-all-local-variables)
12942 (setq org-agenda-undo-list nil
12943 org-agenda-pending-undo-list nil)
12944 (setq major-mode 'org-agenda-mode)
12945 (setq mode-name "Org-Agenda")
12946 (use-local-map org-agenda-mode-map)
12947 (easy-menu-add org-agenda-menu)
12948 (if org-startup-truncated (setq truncate-lines t))
12949 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
12950 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
12951 ;; Make sure properties are removed when copying text
12952 (when (boundp 'buffer-substring-filters)
12953 (org-set-local 'buffer-substring-filters
12954 (cons (lambda (x)
12955 (set-text-properties 0 (length x) nil x) x)
12956 buffer-substring-filters)))
12957 (unless org-agenda-keep-modes
12958 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
12959 org-agenda-show-log nil))
12960 (easy-menu-change
12961 '("Agenda") "Agenda Files"
12962 (append
12963 (list
12964 (vector
12965 (if (get 'org-agenda-files 'org-restrict)
12966 "Restricted to single file"
12967 "Edit File List")
12968 '(org-edit-agenda-file-list)
12969 (not (get 'org-agenda-files 'org-restrict)))
12970 "--")
12971 (mapcar 'org-file-menu-entry (org-agenda-files))))
12972 (org-agenda-set-mode-name)
12973 (apply
12974 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
12975 (list 'org-agenda-mode-hook)))
12977 (substitute-key-definition 'undo 'org-agenda-undo
12978 org-agenda-mode-map global-map)
12979 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
12980 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
12981 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
12982 (define-key org-agenda-mode-map "\C-k" 'org-agenda-kill)
12983 (define-key org-agenda-mode-map "\C-c$" 'org-agenda-archive)
12984 (define-key org-agenda-mode-map "$" 'org-agenda-archive)
12985 (define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
12986 (define-key org-agenda-mode-map " " 'org-agenda-show)
12987 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
12988 (define-key org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
12989 (define-key org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
12990 (define-key org-agenda-mode-map "o" 'delete-other-windows)
12991 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
12992 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
12993 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
12994 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
12995 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
12996 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
12997 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
12998 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
12999 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
13000 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
13001 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
13003 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
13004 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
13005 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
13006 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
13007 (while l (define-key org-agenda-mode-map
13008 (int-to-string (pop l)) 'digit-argument)))
13010 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
13011 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
13012 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
13013 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
13014 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
13015 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
13016 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
13017 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
13018 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
13019 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
13020 (define-key org-agenda-mode-map "n" 'next-line)
13021 (define-key org-agenda-mode-map "p" 'previous-line)
13022 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
13023 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
13024 (define-key org-agenda-mode-map "," 'org-agenda-priority)
13025 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
13026 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
13027 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
13028 (eval-after-load "calendar"
13029 '(define-key calendar-mode-map org-calendar-to-agenda-key
13030 'org-calendar-goto-agenda))
13031 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
13032 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
13033 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
13034 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
13035 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
13036 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
13037 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
13038 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
13039 (define-key org-agenda-mode-map "O" 'org-agenda-clock-out)
13040 (define-key org-agenda-mode-map "X" 'org-agenda-clock-cancel)
13041 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
13042 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
13043 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
13044 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
13045 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
13046 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
13047 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
13048 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
13049 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
13050 "Local keymap for agenda entries from Org-mode.")
13052 (define-key org-agenda-keymap
13053 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
13054 (define-key org-agenda-keymap
13055 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
13056 (when org-agenda-mouse-1-follows-link
13057 (define-key org-agenda-keymap [follow-link] 'mouse-face))
13058 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
13059 '("Agenda"
13060 ("Agenda Files")
13061 "--"
13062 ["Show" org-agenda-show t]
13063 ["Go To (other window)" org-agenda-goto t]
13064 ["Go To (this window)" org-agenda-switch-to t]
13065 ["Follow Mode" org-agenda-follow-mode
13066 :style toggle :selected org-agenda-follow-mode :active t]
13067 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
13068 "--"
13069 ["Cycle TODO" org-agenda-todo t]
13070 ["Archive subtree" org-agenda-archive t]
13071 ["Delete subtree" org-agenda-kill t]
13072 "--"
13073 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
13074 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
13075 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
13076 "--"
13077 ("Tags"
13078 ["Show all Tags" org-agenda-show-tags t]
13079 ["Set Tags" org-agenda-set-tags t])
13080 ("Date/Schedule"
13081 ["Schedule" org-agenda-schedule t]
13082 ["Set Deadline" org-agenda-deadline t]
13083 "--"
13084 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
13085 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
13086 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
13087 ("Priority"
13088 ["Set Priority" org-agenda-priority t]
13089 ["Increase Priority" org-agenda-priority-up t]
13090 ["Decrease Priority" org-agenda-priority-down t]
13091 ["Show Priority" org-agenda-show-priority t])
13092 ("Calendar/Diary"
13093 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
13094 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
13095 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
13096 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
13097 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
13098 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
13099 "--"
13100 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
13101 "--"
13102 ("View"
13103 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
13104 :style radio :selected (equal org-agenda-ndays 1)]
13105 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
13106 :style radio :selected (equal org-agenda-ndays 7)]
13107 "--"
13108 ["Show Logbook entries" org-agenda-log-mode
13109 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
13110 ["Include Diary" org-agenda-toggle-diary
13111 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
13112 ["Use Time Grid" org-agenda-toggle-time-grid
13113 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
13114 ["Rebuild buffer" org-agenda-redo t]
13115 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
13116 "--"
13117 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
13118 "--"
13119 ["Quit" org-agenda-quit t]
13120 ["Exit and Release Buffers" org-agenda-exit t]
13123 ;;; Agenda undo
13125 (defvar org-agenda-allow-remote-undo t
13126 "Non-nil means, allow remote undo from the agenda buffer.")
13127 (defvar org-agenda-undo-list nil
13128 "List of undoable operations in the agenda since last refresh.")
13129 (defvar org-agenda-undo-has-started-in nil
13130 "Buffers that have already seen `undo-start' in the current undo sequence.")
13131 (defvar org-agenda-pending-undo-list nil
13132 "In a series of undo commands, this is the list of remaning undo items.")
13134 (defmacro org-if-unprotected (&rest body)
13135 "Execute BODY if ther is no `org-protected' text property at point."
13136 (declare (debug t))
13137 `(unless (get-text-property (point) 'org-protected)
13138 ,@body))
13140 (defmacro org-with-remote-undo (_buffer &rest _body)
13141 "Execute BODY while recording undo information in two buffers."
13142 (declare (indent 1) (debug t))
13143 `(let ((_cline (org-current-line))
13144 (_cmd this-command)
13145 (_buf1 (current-buffer))
13146 (_buf2 ,_buffer)
13147 (_undo1 buffer-undo-list)
13148 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
13149 _c1 _c2)
13150 ,@_body
13151 (when org-agenda-allow-remote-undo
13152 (setq _c1 (org-verify-change-for-undo
13153 _undo1 (with-current-buffer _buf1 buffer-undo-list))
13154 _c2 (org-verify-change-for-undo
13155 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
13156 (when (or _c1 _c2)
13157 ;; make sure there are undo boundaries
13158 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
13159 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
13160 ;; remember which buffer to undo
13161 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
13162 org-agenda-undo-list)))))
13164 (defun org-agenda-undo ()
13165 "Undo a remote editing step in the agenda.
13166 This undoes changes both in the agenda buffer and in the remote buffer
13167 that have been changed along."
13168 (interactive)
13169 (or org-agenda-allow-remote-undo
13170 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
13171 (if (not (eq this-command last-command))
13172 (setq org-agenda-undo-has-started-in nil
13173 org-agenda-pending-undo-list org-agenda-undo-list))
13174 (if (not org-agenda-pending-undo-list)
13175 (error "No further undo information"))
13176 (let* ((entry (pop org-agenda-pending-undo-list))
13177 buf line cmd rembuf)
13178 (setq cmd (pop entry) line (pop entry))
13179 (setq rembuf (nth 2 entry))
13180 (org-with-remote-undo rembuf
13181 (while (bufferp (setq buf (pop entry)))
13182 (if (pop entry)
13183 (with-current-buffer buf
13184 (let ((last-undo-buffer buf)
13185 buffer-read-only)
13186 (unless (memq buf org-agenda-undo-has-started-in)
13187 (push buf org-agenda-undo-has-started-in)
13188 (make-local-variable 'pending-undo-list)
13189 (undo-start))
13190 (while (and pending-undo-list
13191 (listp pending-undo-list)
13192 (not (car pending-undo-list)))
13193 (pop pending-undo-list))
13194 (undo-more 1))))))
13195 (goto-line line)
13196 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
13198 (defun org-verify-change-for-undo (l1 l2)
13199 "Verify that a real change occurred between the undo lists L1 and L2."
13200 (while (and l1 (listp l1) (null (car l1))) (pop l1))
13201 (while (and l2 (listp l2) (null (car l2))) (pop l2))
13202 (not (eq l1 l2)))
13204 ;;; Agenda dispatch
13206 (defvar org-agenda-restrict nil)
13207 (defvar org-agenda-restrict-begin (make-marker))
13208 (defvar org-agenda-restrict-end (make-marker))
13209 (defvar org-agenda-last-dispatch-buffer nil)
13211 ;;;###autoload
13212 (defun org-agenda (arg)
13213 "Dispatch agenda commands to collect entries to the agenda buffer.
13214 Prompts for a character to select a command. Any prefix arg will be passed
13215 on to the selected command. The default selections are:
13217 a Call `org-agenda-list' to display the agenda for current day or week.
13218 t Call `org-todo-list' to display the global todo list.
13219 T Call `org-todo-list' to display the global todo list, select only
13220 entries with a specific TODO keyword (the user gets a prompt).
13221 m Call `org-tags-view' to display headlines with tags matching
13222 a condition (the user is prompted for the condition).
13223 M Like `m', but select only TODO entries, no ordinary headlines.
13224 l Create a timeeline for the current buffer.
13226 More commands can be added by configuring the variable
13227 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
13228 searches can be pre-defined in this way.
13230 If the current buffer is in Org-mode and visiting a file, you can also
13231 first press `1' to indicate that the agenda should be temporarily (until the
13232 next use of \\[org-agenda]) restricted to the current file."
13233 (interactive "P")
13234 (catch 'exit
13235 (let* ((buf (current-buffer))
13236 (bfn (buffer-file-name (buffer-base-buffer)))
13237 (restrict-ok (and bfn (org-mode-p)))
13238 (custom org-agenda-custom-commands)
13239 c entry key type match lprops)
13240 ;; Turn off restriction
13241 (put 'org-agenda-files 'org-restrict nil)
13242 (setq org-agenda-restrict nil)
13243 (move-marker org-agenda-restrict-begin nil)
13244 (move-marker org-agenda-restrict-end nil)
13245 ;; Remember where this call originated
13246 (setq org-agenda-last-dispatch-buffer (current-buffer))
13247 (save-window-excursion
13248 (delete-other-windows)
13249 (switch-to-buffer-other-window " *Agenda Commands*")
13250 (erase-buffer)
13251 (insert (eval-when-compile
13252 (let ((header
13253 "Press key for an agenda command:
13254 -------------------------------- C Configure custom agenda commands
13255 a Agenda for current week or day
13256 t List of all TODO entries T Entries with special TODO kwd
13257 m Match a TAGS query M Like m, but only TODO entries
13258 L Timeline for current buffer # List stuck projects (!=configure)
13260 (start 0))
13261 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
13262 (setq start (match-end 0))
13263 (add-text-properties (match-beginning 2) (match-end 2)
13264 '(face bold) header))
13265 header)))
13266 (while (setq entry (pop custom))
13267 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
13268 (insert (format "\n%-4s%-14s: %s"
13269 (org-add-props (copy-sequence key)
13270 '(face bold))
13271 (cond
13272 ((stringp type) type)
13273 ((eq type 'todo) "TODO keyword")
13274 ((eq type 'tags) "Tags query")
13275 ((eq type 'tags-todo) "Tags (TODO)")
13276 ((eq type 'tags-tree) "Tags tree")
13277 ((eq type 'todo-tree) "TODO kwd tree")
13278 ((eq type 'occur-tree) "Occur tree")
13279 ((functionp type) (symbol-name type))
13280 (t "???"))
13281 (if (stringp match)
13282 (org-add-props match nil 'face 'org-warning)
13283 (format "set of %d commands" (length match))))))
13284 (if restrict-ok
13285 (insert "\n"
13286 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
13287 (goto-char (point-min))
13288 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
13289 (message "Press key for agenda command%s"
13290 (if restrict-ok ", or [1] or [0] to restrict" ""))
13291 (setq c (read-char-exclusive))
13292 (message "")
13293 (when (memq c '(?L ?1 ?0))
13294 (if restrict-ok
13295 (put 'org-agenda-files 'org-restrict (list bfn))
13296 (error "Cannot restrict agenda to current buffer"))
13297 (with-current-buffer " *Agenda Commands*"
13298 (goto-char (point-max))
13299 (delete-region (point-at-bol) (point))
13300 (goto-char (point-min)))
13301 (when (eq c ?0)
13302 (setq org-agenda-restrict t)
13303 (with-current-buffer buf
13304 (if (org-region-active-p)
13305 (progn
13306 (move-marker org-agenda-restrict-begin (region-beginning))
13307 (move-marker org-agenda-restrict-end (region-end)))
13308 (save-excursion
13309 (org-back-to-heading t)
13310 (move-marker org-agenda-restrict-begin (point))
13311 (move-marker org-agenda-restrict-end
13312 (progn (org-end-of-subtree t)))))))
13313 (unless (eq c ?L)
13314 (message "Press key for agenda command%s"
13315 (if restrict-ok " (restricted to current file)" ""))
13316 (setq c (read-char-exclusive)))
13317 (message "")))
13318 (require 'calendar) ; FIXME: can we avoid this for some commands?
13319 ;; For example the todo list should not need it (but does...)
13320 (cond
13321 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
13322 (if (symbolp (nth 1 entry))
13323 (progn
13324 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
13325 lprops (nth 3 entry))
13326 (cond
13327 ((eq type 'tags)
13328 (org-let lprops '(org-tags-view current-prefix-arg match)))
13329 ((eq type 'tags-todo)
13330 (org-let lprops '(org-tags-view '(4) match)))
13331 ((eq type 'todo)
13332 (org-let lprops '(org-todo-list match)))
13333 ((eq type 'tags-tree)
13334 (org-check-for-org-mode)
13335 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
13336 ((eq type 'todo-tree)
13337 (org-check-for-org-mode)
13338 (org-let lprops
13339 '(org-occur (concat "^" outline-regexp "[ \t]*"
13340 (regexp-quote match) "\\>"))))
13341 ((eq type 'occur-tree)
13342 (org-check-for-org-mode)
13343 (org-let lprops '(org-occur match)))
13344 ((fboundp type)
13345 (org-let lprops '(funcall type match)))
13346 (t (error "Invalid custom agenda command type %s" type))))
13347 (org-run-agenda-series (cddr entry))))
13348 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
13349 ((equal c ?a) (call-interactively 'org-agenda-list))
13350 ((equal c ?t) (call-interactively 'org-todo-list))
13351 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
13352 ((equal c ?m) (call-interactively 'org-tags-view))
13353 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
13354 ((equal c ?L)
13355 (unless restrict-ok
13356 (error "This is not an Org-mode file"))
13357 (org-call-with-arg 'org-timeline arg))
13358 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
13359 ((equal c ?!) (customize-variable 'org-stuck-projects))
13360 (t (error "Invalid key"))))))
13362 (defun org-run-agenda-series (series)
13363 (org-prepare-agenda)
13364 (let* ((org-agenda-multi t)
13365 (redo (list 'org-run-agenda-series (list 'quote series)))
13366 (cmds (car series))
13367 (gprops (nth 1 series))
13368 match ;; The byte compiler incorrectly complains about this. Keep it!
13369 cmd type lprops)
13370 (while (setq cmd (pop cmds))
13371 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
13372 (cond
13373 ((eq type 'agenda)
13374 (call-interactively 'org-agenda-list))
13375 ((eq type 'alltodo)
13376 (call-interactively 'org-todo-list))
13377 ((eq type 'stuck)
13378 (call-interactively 'org-agenda-list-stuck-projects))
13379 ((eq type 'tags)
13380 (org-let2 gprops lprops
13381 '(org-tags-view current-prefix-arg match)))
13382 ((eq type 'tags-todo)
13383 (org-let2 gprops lprops
13384 '(org-tags-view '(4) match)))
13385 ((eq type 'todo)
13386 (org-let2 gprops lprops
13387 '(org-todo-list match)))
13388 ((fboundp type)
13389 (org-let2 gprops lprops
13390 '(funcall type match)))
13391 (t (error "Invalid type in command series"))))
13392 (widen)
13393 (setq org-agenda-redo-command redo)
13394 (goto-char (point-min)))
13395 (org-finalize-agenda))
13397 ;;;###autoload
13398 (defmacro org-batch-agenda (cmd-key &rest parameters)
13399 "Run an agenda command in batch mode, send result to STDOUT.
13400 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
13401 Paramters are alternating variable names and values that will be bound
13402 before running the agenda command."
13403 (let (pars)
13404 (while parameters
13405 (push (list (pop parameters) (if parameters (pop parameters))) pars))
13406 (flet ((read-char-exclusive () (string-to-char cmd-key)))
13407 (eval (list 'let (nreverse pars) '(org-agenda nil))))
13408 (set-buffer "*Org Agenda*")
13409 (princ (buffer-string))))
13411 (defmacro org-no-read-only (&rest body)
13412 "Inhibit read-only for BODY."
13413 `(let ((inhibit-read-only t)) ,@body))
13415 (defun org-check-for-org-mode ()
13416 "Make sure current buffer is in org-mode. Error if not."
13417 (or (org-mode-p)
13418 (error "Cannot execute org-mode agenda command on buffer in %s."
13419 major-mode)))
13421 (defun org-fit-agenda-window ()
13422 "Fit the window to the buffer size."
13423 (and (memq org-agenda-window-setup '(reorganize-frame))
13424 (fboundp 'fit-window-to-buffer)
13425 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
13426 (/ (frame-height) 2))))
13428 ;;; Agenda file list
13430 (defun org-agenda-files (&optional unrestricted)
13431 "Get the list of agenda files.
13432 Optional UNRESTRICTED means return the full list even if a restriction
13433 is currently in place."
13434 (cond
13435 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13436 ((stringp org-agenda-files) (org-read-agenda-file-list))
13437 ((listp org-agenda-files) org-agenda-files)
13438 (t (error "Invalid value of `org-agenda-files'"))))
13440 (defun org-edit-agenda-file-list ()
13441 "Edit the list of agenda files.
13442 Depending on setup, this either uses customize to edit the variable
13443 `org-agenda-files', or it visits the file that is holding the list. In the
13444 latter case, the buffer is set up in a way that saving it automatically kills
13445 the buffer and restores the previous window configuration."
13446 (interactive)
13447 (if (stringp org-agenda-files)
13448 (let ((cw (current-window-configuration)))
13449 (find-file org-agenda-files)
13450 (org-set-local 'org-window-configuration cw)
13451 (org-add-hook 'after-save-hook
13452 (lambda ()
13453 (set-window-configuration
13454 (prog1 org-window-configuration
13455 (kill-buffer (current-buffer))))
13456 (org-install-agenda-files-menu)
13457 (message "New agenda file list installed"))
13458 nil 'local)
13459 (message (substitute-command-keys
13460 "Edit list and finish with \\[save-buffer]")))
13461 (customize-variable 'org-agenda-files)))
13463 (defun org-store-new-agenda-file-list (list)
13464 "Set new value for the agenda file list and save it correcly."
13465 (if (stringp org-agenda-files)
13466 (let ((f org-agenda-files) b)
13467 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13468 (with-temp-file f
13469 (insert (mapconcat 'identity list "\n") "\n")))
13470 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13471 (setq org-agenda-files list)
13472 (customize-save-variable 'org-agenda-files org-agenda-files))))
13474 (defun org-read-agenda-file-list ()
13475 "Read the list of agenda files from a file."
13476 (when (stringp org-agenda-files)
13477 (with-temp-buffer
13478 (insert-file-contents org-agenda-files)
13479 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13482 ;;;###autoload
13483 (defun org-cycle-agenda-files ()
13484 "Cycle through the files in `org-agenda-files'.
13485 If the current buffer visits an agenda file, find the next one in the list.
13486 If the current buffer does not, find the first agenda file."
13487 (interactive)
13488 (let* ((fs (org-agenda-files t))
13489 (files (append fs (list (car fs))))
13490 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13491 file)
13492 (unless files (error "No agenda files"))
13493 (catch 'exit
13494 (while (setq file (pop files))
13495 (if (equal (file-truename file) tcf)
13496 (when (car files)
13497 (find-file (car files))
13498 (throw 'exit t))))
13499 (find-file (car fs)))
13500 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13502 (defun org-agenda-file-to-end ()
13503 "Move/add the current file to the end of the agenda file list.
13504 If the file is not present in the list, it is appended to the list. If it is
13505 present, it is moved there."
13506 (interactive)
13507 (org-agenda-file-to-front 'to-end))
13509 (defun org-agenda-file-to-front (&optional to-end)
13510 "Move/add the current file to the top of the agenda file list.
13511 If the file is not present in the list, it is added to the front. If it is
13512 present, it is moved there. With optional argument TO-END, add/move to the
13513 end of the list."
13514 (interactive "P")
13515 (let ((file-alist (mapcar (lambda (x)
13516 (cons (file-truename x) x))
13517 (org-agenda-files t)))
13518 (ctf (file-truename buffer-file-name))
13519 x had)
13520 (setq x (assoc ctf file-alist) had x)
13522 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13523 (if to-end
13524 (setq file-alist (append (delq x file-alist) (list x)))
13525 (setq file-alist (cons x (delq x file-alist))))
13526 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13527 (org-install-agenda-files-menu)
13528 (message "File %s to %s of agenda file list"
13529 (if had "moved" "added") (if to-end "end" "front"))))
13531 (defun org-remove-file (&optional file)
13532 "Remove current file from the list of files in variable `org-agenda-files'.
13533 These are the files which are being checked for agenda entries.
13534 Optional argument FILE means, use this file instead of the current."
13535 (interactive)
13536 (let* ((file (or file buffer-file-name))
13537 (true-file (file-truename file))
13538 (afile (abbreviate-file-name file))
13539 (files (delq nil (mapcar
13540 (lambda (x)
13541 (if (equal true-file
13542 (file-truename x))
13543 nil x))
13544 (org-agenda-files t)))))
13545 (if (not (= (length files) (length (org-agenda-files t))))
13546 (progn
13547 (org-store-new-agenda-file-list files)
13548 (org-install-agenda-files-menu)
13549 (message "Removed file: %s" afile))
13550 (message "File was not in list: %s" afile))))
13552 (defun org-file-menu-entry (file)
13553 (vector file (list 'find-file file) t))
13555 (defun org-check-agenda-file (file)
13556 "Make sure FILE exists. If not, ask user what to do."
13557 (when (not (file-exists-p file))
13558 (message "non-existent file %s. [R]emove from list or [A]bort?"
13559 (abbreviate-file-name file))
13560 (let ((r (downcase (read-char-exclusive))))
13561 (cond
13562 ((equal r ?r)
13563 (org-remove-file file)
13564 (throw 'nextfile t))
13565 (t (error "Abort"))))))
13567 ;;; Agenda prepare and finalize
13569 (defvar org-agenda-multi nil) ; dynammically scoped
13570 (defvar org-agenda-buffer-name "*Org Agenda*")
13571 (defvar org-pre-agenda-window-conf nil)
13572 (defun org-prepare-agenda ()
13573 (if org-agenda-multi
13574 (progn
13575 (setq buffer-read-only nil)
13576 (goto-char (point-max))
13577 (unless (= (point) 1)
13578 (insert "\n" (make-string (window-width) ?=) "\n"))
13579 (narrow-to-region (point) (point-max)))
13580 (org-agenda-maybe-reset-markers 'force)
13581 (org-prepare-agenda-buffers (org-agenda-files))
13582 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
13583 (awin (get-buffer-window abuf)))
13584 (cond
13585 ((equal (current-buffer) abuf) nil)
13586 (awin (select-window awin))
13587 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
13588 ((equal org-agenda-window-setup 'current-window)
13589 (switch-to-buffer abuf))
13590 ((equal org-agenda-window-setup 'other-window)
13591 (switch-to-buffer-other-window abuf))
13592 ((equal org-agenda-window-setup 'other-frame)
13593 (switch-to-buffer-other-frame abuf))
13594 ((equal org-agenda-window-setup 'reorganize-frame)
13595 (delete-other-windows)
13596 (switch-to-buffer-other-window abuf))))
13597 (setq buffer-read-only nil)
13598 (erase-buffer)
13599 (org-agenda-mode))
13600 (setq buffer-read-only nil))
13602 (defun org-finalize-agenda ()
13603 "Finishing touch for the agenda buffer, called just before displaying it."
13604 (unless org-agenda-multi
13605 (org-agenda-align-tags)
13606 (save-excursion
13607 (let ((buffer-read-only))
13608 (goto-char (point-min))
13609 (while (org-activate-bracket-links (point-max))
13610 (add-text-properties (match-beginning 0) (match-end 0)
13611 '(face org-link))))
13612 (run-hooks 'org-finalize-agenda-hook))))
13614 (defun org-prepare-agenda-buffers (files)
13615 "Create buffers for all agenda files, protect archived trees and comments."
13616 (interactive)
13617 (let ((pa '(:org-archived t))
13618 (pc '(:org-comment t))
13619 (pall '(:org-archived t :org-comment t))
13620 (rea (concat ":" org-archive-tag ":"))
13621 bmp file re)
13622 (save-excursion
13623 (save-restriction
13624 (while (setq file (pop files))
13625 (org-check-agenda-file file)
13626 (set-buffer (org-get-agenda-file-buffer file))
13627 (widen)
13628 (setq bmp (buffer-modified-p))
13629 (save-excursion
13630 (remove-text-properties (point-min) (point-max) pall)
13631 (when org-agenda-skip-archived-trees
13632 (goto-char (point-min))
13633 (while (re-search-forward rea nil t)
13634 (if (org-on-heading-p)
13635 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13636 (goto-char (point-min))
13637 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13638 (while (re-search-forward re nil t)
13639 (add-text-properties
13640 (match-beginning 0) (org-end-of-subtree t) pc)))
13641 (set-buffer-modified-p bmp))))))
13643 (defvar org-agenda-skip-function nil
13644 "Function to be called at each match during agenda construction.
13645 If this function return nil, the current match should not be skipped.
13646 Otherwise, the function must return a position from where the search
13647 should be continued.
13648 Never set this variable using `setq' or so, because then it will apply
13649 to all future agenda commands. Instead, bind it with `let' to scope
13650 it dynamically into the agenda-constructing command.")
13652 (defun org-agenda-skip ()
13653 "Throw to `:skip' in places that should be skipped.
13654 Also moves point to the end of the skipped region, so that search can
13655 continue from there."
13656 (let ((p (point-at-bol)) to)
13657 (and org-agenda-skip-archived-trees
13658 (get-text-property p :org-archived)
13659 (org-end-of-subtree t)
13660 (throw :skip t))
13661 (and (get-text-property p :org-comment)
13662 (org-end-of-subtree t)
13663 (throw :skip t))
13664 (if (equal (char-after p) ?#) (throw :skip t))
13665 (when (and (functionp org-agenda-skip-function)
13666 (setq to (save-excursion
13667 (save-match-data
13668 (funcall org-agenda-skip-function)))))
13669 (goto-char to)
13670 (throw :skip t))))
13672 (defvar org-agenda-markers nil
13673 "List of all currently active markers created by `org-agenda'.")
13674 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
13675 "Creation time of the last agenda marker.")
13677 (defun org-agenda-new-marker (&optional pos)
13678 "Return a new agenda marker.
13679 Org-mode keeps a list of these markers and resets them when they are
13680 no longer in use."
13681 (let ((m (copy-marker (or pos (point)))))
13682 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
13683 (push m org-agenda-markers)
13686 (defun org-agenda-maybe-reset-markers (&optional force)
13687 "Reset markers created by `org-agenda'. But only if they are old enough."
13688 (if (or (and force (not org-agenda-multi))
13689 (> (- (time-to-seconds (current-time))
13690 org-agenda-last-marker-time)
13692 (while org-agenda-markers
13693 (move-marker (pop org-agenda-markers) nil))))
13695 (defvar org-agenda-new-buffers nil
13696 "Buffers created to visit agenda files.")
13698 (defun org-get-agenda-file-buffer (file)
13699 "Get a buffer visiting FILE. If the buffer needs to be created, add
13700 it to the list of buffers which might be released later."
13701 (let ((buf (org-find-base-buffer-visiting file)))
13702 (if buf
13703 buf ; just return it
13704 ;; Make a new buffer and remember it
13705 (setq buf (find-file-noselect file))
13706 (if buf (push buf org-agenda-new-buffers))
13707 buf)))
13709 (defun org-release-buffers (blist)
13710 "Release all buffers in list, asking the user for confirmation when needed.
13711 When a buffer is unmodified, it is just killed. When modified, it is saved
13712 \(if the user agrees) and then killed."
13713 (let (buf file)
13714 (while (setq buf (pop blist))
13715 (setq file (buffer-file-name buf))
13716 (when (and (buffer-modified-p buf)
13717 file
13718 (y-or-n-p (format "Save file %s? " file)))
13719 (with-current-buffer buf (save-buffer)))
13720 (kill-buffer buf))))
13722 (defvar org-category-table nil)
13723 (defun org-get-category-table ()
13724 "Get the table of categories and positions in current buffer."
13725 (let (tbl)
13726 (save-excursion
13727 (goto-char (point-min))
13728 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
13729 (push (cons (point) (org-trim (match-string 2))) tbl)))
13730 tbl))
13732 (defun org-get-category (&optional pos)
13733 "Get the category applying to position POS."
13734 (if (not org-category-table)
13735 (cond
13736 ((null org-category)
13737 (setq org-category
13738 (if buffer-file-name
13739 (file-name-sans-extension
13740 (file-name-nondirectory buffer-file-name))
13741 "???")))
13742 ((symbolp org-category) (symbol-name org-category))
13743 (t org-category))
13744 (let ((tbl org-category-table)
13745 (pos (or pos (point))))
13746 (while (and tbl (> (caar tbl) pos))
13747 (pop tbl))
13748 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
13749 org-category-table))))))
13750 ;;; Agenda timeline
13752 (defun org-timeline (&optional include-all)
13753 "Show a time-sorted view of the entries in the current org file.
13754 Only entries with a time stamp of today or later will be listed. With
13755 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
13756 under the current date.
13757 If the buffer contains an active region, only check the region for
13758 dates."
13759 (interactive "P")
13760 (require 'calendar)
13761 (org-compile-prefix-format 'timeline)
13762 (org-set-sorting-strategy 'timeline)
13763 (let* ((dopast t)
13764 (dotodo include-all)
13765 (doclosed org-agenda-show-log)
13766 (entry buffer-file-name)
13767 (date (calendar-current-date))
13768 (beg (if (org-region-active-p) (region-beginning) (point-min)))
13769 (end (if (org-region-active-p) (region-end) (point-max)))
13770 (day-numbers (org-get-all-dates beg end 'no-ranges
13771 t doclosed ; always include today
13772 org-timeline-show-empty-dates))
13773 (today (time-to-days (current-time)))
13774 (past t)
13775 args
13776 s e rtn d emptyp)
13777 (setq org-agenda-redo-command
13778 (list 'progn
13779 (list 'switch-to-buffer-other-window (current-buffer))
13780 (list 'org-timeline (list 'quote include-all))))
13781 (if (not dopast)
13782 ;; Remove past dates from the list of dates.
13783 (setq day-numbers (delq nil (mapcar (lambda(x)
13784 (if (>= x today) x nil))
13785 day-numbers))))
13786 (org-prepare-agenda)
13787 (if doclosed (push :closed args))
13788 (push :timestamp args)
13789 (if dotodo (push :todo args))
13790 (while (setq d (pop day-numbers))
13791 (if (and (listp d) (eq (car d) :omitted))
13792 (progn
13793 (setq s (point))
13794 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
13795 (put-text-property s (1- (point)) 'face 'org-level-3))
13796 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
13797 (if (and (>= d today)
13798 dopast
13799 past)
13800 (progn
13801 (setq past nil)
13802 (insert (make-string 79 ?-) "\n")))
13803 (setq date (calendar-gregorian-from-absolute d))
13804 (setq s (point))
13805 (setq rtn (and (not emptyp)
13806 (apply 'org-agenda-get-day-entries
13807 entry date args)))
13808 (if (or rtn (equal d today) org-timeline-show-empty-dates)
13809 (progn
13810 (insert (calendar-day-name date) " "
13811 (number-to-string (extract-calendar-day date)) " "
13812 (calendar-month-name (extract-calendar-month date)) " "
13813 (number-to-string (extract-calendar-year date)) "\n")
13814 ; FIXME: this gives a timezone problem
13815 ; (insert (format-time-string org-agenda-date-format
13816 ; (calendar-time-from-absolute d 0))
13817 ; "\n")
13818 (put-text-property s (1- (point)) 'face 'org-level-3)
13819 (put-text-property s (1- (point)) 'org-date-line t)
13820 (if (equal d today)
13821 (put-text-property s (1- (point)) 'org-today t))
13822 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
13823 (put-text-property s (1- (point)) 'day d)))))
13824 (goto-char (point-min))
13825 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
13826 (point-min)))
13827 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
13828 (org-finalize-agenda)
13829 (setq buffer-read-only t)))
13831 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
13832 "Return a list of all relevant day numbers from BEG to END buffer positions.
13833 If NO-RANGES is non-nil, include only the start and end dates of a range,
13834 not every single day in the range. If FORCE-TODAY is non-nil, make
13835 sure that TODAY is included in the list. If INACTIVE is non-nil, also
13836 inactive time stamps (those in square brackets) are included.
13837 When EMPTY is non-nil, also include days without any entries."
13838 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
13839 dates dates1 date day day1 day2 ts1 ts2)
13840 (if force-today
13841 (setq dates (list (time-to-days (current-time)))))
13842 (save-excursion
13843 (goto-char beg)
13844 (while (re-search-forward re end t)
13845 (setq day (time-to-days (org-time-string-to-time
13846 (substring (match-string 1) 0 10))))
13847 (or (memq day dates) (push day dates)))
13848 (unless no-ranges
13849 (goto-char beg)
13850 (while (re-search-forward org-tr-regexp end t)
13851 (setq ts1 (substring (match-string 1) 0 10)
13852 ts2 (substring (match-string 2) 0 10)
13853 day1 (time-to-days (org-time-string-to-time ts1))
13854 day2 (time-to-days (org-time-string-to-time ts2)))
13855 (while (< (setq day1 (1+ day1)) day2)
13856 (or (memq day1 dates) (push day1 dates)))))
13857 (setq dates (sort dates '<))
13858 (when empty
13859 (while (setq day (pop dates))
13860 (setq day2 (car dates))
13861 (push day dates1)
13862 (when (and day2 empty)
13863 (if (or (eq empty t)
13864 (and (numberp empty) (<= (- day2 day) empty)))
13865 (while (< (setq day (1+ day)) day2)
13866 (push (list day) dates1))
13867 (push (cons :omitted (- day2 day)) dates1))))
13868 (setq dates (nreverse dates1)))
13869 dates)))
13871 ;;; Agenda Daily/Weekly
13873 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
13874 (defvar org-agenda-last-arguments nil
13875 "The arguments of the previous call to org-agenda")
13876 (defvar org-starting-day nil) ; local variable in the agenda buffer
13877 (defvar org-include-all-loc nil) ; local variable
13880 ;;;###autoload
13881 (defun org-agenda-list (&optional include-all start-day ndays)
13882 "Produce a weekly view from all files in variable `org-agenda-files'.
13883 The view will be for the current week, but from the overview buffer you
13884 will be able to go to other weeks.
13885 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
13886 also be shown, under the current date.
13887 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
13888 on the days are also shown. See the variable `org-log-done' for how
13889 to turn on logging.
13890 START-DAY defaults to TODAY, or to the most recent match for the weekday
13891 given in `org-agenda-start-on-weekday'.
13892 NDAYS defaults to `org-agenda-ndays'."
13893 (interactive "P")
13894 (if org-agenda-overriding-arguments
13895 (setq include-all (car org-agenda-overriding-arguments)
13896 start-day (nth 1 org-agenda-overriding-arguments)
13897 ndays (nth 2 org-agenda-overriding-arguments)))
13898 (setq org-agenda-last-arguments (list include-all start-day ndays))
13899 (org-compile-prefix-format 'agenda)
13900 (org-set-sorting-strategy 'agenda)
13901 (require 'calendar)
13902 (let* ((org-agenda-start-on-weekday
13903 (if (or (equal ndays 1)
13904 (and (null ndays) (equal 1 org-agenda-ndays)))
13905 nil org-agenda-start-on-weekday))
13906 (thefiles (org-agenda-files))
13907 (files thefiles)
13908 (today (time-to-days (current-time)))
13909 (sd (or start-day today))
13910 (start (if (or (null org-agenda-start-on-weekday)
13911 (< org-agenda-ndays 7))
13913 (let* ((nt (calendar-day-of-week
13914 (calendar-gregorian-from-absolute sd)))
13915 (n1 org-agenda-start-on-weekday)
13916 (d (- nt n1)))
13917 (- sd (+ (if (< d 0) 7 0) d)))))
13918 (day-numbers (list start))
13919 (inhibit-redisplay (not debug-on-error))
13920 s e rtn rtnall file date d start-pos end-pos todayp nd)
13921 (setq org-agenda-redo-command
13922 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
13923 ;; Make the list of days
13924 (setq ndays (or ndays org-agenda-ndays)
13925 nd ndays)
13926 (while (> ndays 1)
13927 (push (1+ (car day-numbers)) day-numbers)
13928 (setq ndays (1- ndays)))
13929 (setq day-numbers (nreverse day-numbers))
13930 (org-prepare-agenda)
13931 (org-set-local 'org-starting-day (car day-numbers))
13932 (org-set-local 'org-include-all-loc include-all)
13933 (when (and (or include-all org-agenda-include-all-todo)
13934 (member today day-numbers))
13935 (setq files thefiles
13936 rtnall nil)
13937 (while (setq file (pop files))
13938 (catch 'nextfile
13939 (org-check-agenda-file file)
13940 (setq date (calendar-gregorian-from-absolute today)
13941 rtn (org-agenda-get-day-entries
13942 file date :todo))
13943 (setq rtnall (append rtnall rtn))))
13944 (when rtnall
13945 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
13946 (add-text-properties (point-min) (1- (point))
13947 (list 'face 'org-level-3))
13948 (insert (org-finalize-agenda-entries rtnall) "\n")))
13949 (setq s (point))
13950 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
13951 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
13952 (while (setq d (pop day-numbers))
13953 (setq date (calendar-gregorian-from-absolute d)
13954 s (point))
13955 (if (or (setq todayp (= d today))
13956 (and (not start-pos) (= d sd)))
13957 (setq start-pos (point))
13958 (if (and start-pos (not end-pos))
13959 (setq end-pos (point))))
13960 (setq files thefiles
13961 rtnall nil)
13962 (while (setq file (pop files))
13963 (catch 'nextfile
13964 (org-check-agenda-file file)
13965 (if org-agenda-show-log
13966 (setq rtn (org-agenda-get-day-entries
13967 file date
13968 :deadline :scheduled :timestamp :closed))
13969 (setq rtn (org-agenda-get-day-entries
13970 file date
13971 :deadline :scheduled :timestamp)))
13972 (setq rtnall (append rtnall rtn))))
13973 (if org-agenda-include-diary
13974 (progn
13975 (require 'diary-lib)
13976 (setq rtn (org-get-entries-from-diary date))
13977 (setq rtnall (append rtnall rtn))))
13978 (if (or rtnall org-agenda-show-all-dates)
13979 (progn
13980 (insert (format "%-9s %2d %s %4d\n"
13981 (calendar-day-name date)
13982 (extract-calendar-day date)
13983 (calendar-month-name (extract-calendar-month date))
13984 (extract-calendar-year date)))
13985 ; FIXME: this gives a timezone problem
13986 ; (insert (format-time-string org-agenda-date-format
13987 ; (calendar-time-from-absolute d 0)) "\n")
13988 (put-text-property s (1- (point)) 'face 'org-level-3)
13989 (put-text-property s (1- (point)) 'org-date-line t)
13990 (if todayp (put-text-property s (1- (point)) 'org-today t))
13991 (if rtnall (insert
13992 (org-finalize-agenda-entries
13993 (org-agenda-add-time-grid-maybe
13994 rtnall nd todayp))
13995 "\n"))
13996 (put-text-property s (1- (point)) 'day d))))
13997 (goto-char (point-min))
13998 (org-fit-agenda-window)
13999 (unless (and (pos-visible-in-window-p (point-min))
14000 (pos-visible-in-window-p (point-max)))
14001 (goto-char (1- (point-max)))
14002 (recenter -1)
14003 (if (not (pos-visible-in-window-p (or start-pos 1)))
14004 (progn
14005 (goto-char (or start-pos 1))
14006 (recenter 1))))
14007 (goto-char (or start-pos 1))
14008 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
14009 (org-finalize-agenda)
14010 (setq buffer-read-only t)
14011 (message "")))
14013 ;;; Agenda TODO list
14015 (defvar org-select-this-todo-keyword nil)
14016 (defvar org-last-arg nil)
14018 ;;;###autoload
14019 (defun org-todo-list (arg)
14020 "Show all TODO entries from all agenda file in a single list.
14021 The prefix arg can be used to select a specific TODO keyword and limit
14022 the list to these. When using \\[universal-argument], you will be prompted
14023 for a keyword. A numeric prefix directly selects the Nth keyword in
14024 `org-todo-keywords'."
14025 (interactive "P")
14026 (require 'calendar)
14027 (org-compile-prefix-format 'todo)
14028 (org-set-sorting-strategy 'todo)
14029 (let* ((today (time-to-days (current-time)))
14030 (date (calendar-gregorian-from-absolute today))
14031 (kwds org-todo-keywords)
14032 (completion-ignore-case t)
14033 (org-select-this-todo-keyword
14034 (if (stringp arg) arg
14035 (and arg (integerp arg) (> arg 0)
14036 (nth (1- arg) org-todo-keywords))))
14037 rtn rtnall files file pos)
14038 (when (equal arg '(4))
14039 (setq org-select-this-todo-keyword
14040 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
14041 nil t)))
14042 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
14043 (org-prepare-agenda)
14044 (org-set-local 'org-last-arg arg)
14045 (org-set-local 'org-todo-keywords kwds)
14046 (setq org-agenda-redo-command
14047 '(org-todo-list (or current-prefix-arg org-last-arg)))
14048 (setq files (org-agenda-files)
14049 rtnall nil)
14050 (while (setq file (pop files))
14051 (catch 'nextfile
14052 (org-check-agenda-file file)
14053 (setq rtn (org-agenda-get-day-entries file date :todo))
14054 (setq rtnall (append rtnall rtn))))
14055 (if org-agenda-overriding-header
14056 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
14057 nil 'face 'org-level-3) "\n")
14058 (insert "Global list of TODO items of type: ")
14059 (add-text-properties (point-min) (1- (point))
14060 (list 'face 'org-level-3))
14061 (setq pos (point))
14062 (insert (or org-select-this-todo-keyword "ALL") "\n")
14063 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14064 (setq pos (point))
14065 (unless org-agenda-multi
14066 (insert
14067 "Available with `N r': (0)ALL "
14068 (let ((n 0))
14069 (mapconcat (lambda (x)
14070 (format "(%d)%s" (setq n (1+ n)) x))
14071 org-todo-keywords " "))
14072 "\n"))
14073 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14074 (when rtnall
14075 (insert (org-finalize-agenda-entries rtnall) "\n"))
14076 (goto-char (point-min))
14077 (org-fit-agenda-window)
14078 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
14079 (org-finalize-agenda)
14080 (setq buffer-read-only t)))
14082 ;;; Agenda tags match
14084 ;;;###autoload
14085 (defun org-tags-view (&optional todo-only match)
14086 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
14087 The prefix arg TODO-ONLY limits the search to TODO entries."
14088 (interactive "P")
14089 (org-compile-prefix-format 'tags)
14090 (org-set-sorting-strategy 'tags)
14091 (let* ((org-tags-match-list-sublevels
14092 (if todo-only t org-tags-match-list-sublevels))
14093 (completion-ignore-case t)
14094 rtn rtnall files file pos matcher
14095 buffer)
14096 (setq matcher (org-make-tags-matcher match)
14097 match (car matcher) matcher (cdr matcher))
14098 (org-prepare-agenda)
14099 (setq org-agenda-redo-command
14100 (list 'org-tags-view (list 'quote todo-only)
14101 (list 'if 'current-prefix-arg nil match)))
14102 (setq files (org-agenda-files)
14103 rtnall nil)
14104 (while (setq file (pop files))
14105 (catch 'nextfile
14106 (org-check-agenda-file file)
14107 (setq buffer (if (file-exists-p file)
14108 (org-get-agenda-file-buffer file)
14109 (error "No such file %s" file)))
14110 (if (not buffer)
14111 ;; If file does not exist, merror message to agenda
14112 (setq rtn (list
14113 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14114 rtnall (append rtnall rtn))
14115 (with-current-buffer buffer
14116 (unless (org-mode-p)
14117 (error "Agenda file %s is not in `org-mode'" file))
14118 (setq org-category-table (org-get-category-table))
14119 (save-excursion
14120 (save-restriction
14121 (if org-agenda-restrict
14122 (narrow-to-region org-agenda-restrict-begin
14123 org-agenda-restrict-end)
14124 (widen))
14125 (setq rtn (org-scan-tags 'agenda matcher todo-only))
14126 (setq rtnall (append rtnall rtn))))))))
14127 (if org-agenda-overriding-header
14128 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
14129 nil 'face 'org-level-3) "\n")
14130 (insert "Headlines with TAGS match: ")
14131 (add-text-properties (point-min) (1- (point))
14132 (list 'face 'org-level-3))
14133 (setq pos (point))
14134 (insert match "\n")
14135 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14136 (setq pos (point))
14137 (unless org-agenda-multi
14138 (insert "Press `C-u r' to search again with new search string\n"))
14139 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14140 (when rtnall
14141 (insert (org-finalize-agenda-entries rtnall) "\n"))
14142 (goto-char (point-min))
14143 (org-fit-agenda-window)
14144 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
14145 (org-finalize-agenda)
14146 (setq buffer-read-only t)))
14148 ;;; Agenda Finding stuck projects
14150 (defvar org-agenda-skip-regexp nil
14151 "Regular expression used in skipping subtrees for the agenda.
14152 This is basically a temporary global variable that can be set and then
14153 used by user-defined selections using `org-agenda-skip-function'.")
14155 (defvar org-agenda-overriding-header nil
14156 "When this is set during todo and tags searches, will replace header.")
14158 (defun org-agenda-skip-subtree-when-regexp-matches ()
14159 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
14160 If yes, it returns the end position of this tree, causing agenda commands
14161 to skip this subtree. This is a function that can be put into
14162 `org-agenda-skip-function' for the duration of a command."
14163 (save-match-data
14164 (let ((end (save-excursion (org-end-of-subtree t)))
14165 skip)
14166 (save-excursion
14167 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
14168 (and skip end))))
14170 (defun org-agenda-list-stuck-projects (&rest ignore)
14171 "Create agenda view for projects that are stuck.
14172 Stuck projects are project that have no next actions. For the definitions
14173 of what a project is and how to check if it stuck, customize the variable
14174 `org-stuck-projects'.
14175 MATCH is being ignored."
14176 (interactive)
14177 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
14178 (org-agenda-overriding-header "List of stuck projects: ")
14179 (matcher (nth 0 org-stuck-projects))
14180 (todo (nth 1 org-stuck-projects))
14181 (tags (nth 2 org-stuck-projects))
14182 (todo-re (concat "^\\*+[ \t]+\\("
14183 (mapconcat 'identity todo "\\|")
14184 "\\)\\>"))
14185 (tags-re (concat "^\\*+.*:\\("
14186 (mapconcat 'identity tags "\\|")
14187 "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
14189 (setq org-agenda-skip-regexp
14190 (cond
14191 ((and todo tags)
14192 (concat todo-re "\\|" tags-re))
14193 (todo todo-re)
14194 (tags tags-re)
14195 (t (error "No information how to identify unstuck projects"))))
14196 (org-tags-view nil matcher)
14197 (with-current-buffer org-agenda-buffer-name
14198 (setq org-agenda-redo-command
14199 '(org-agenda-list-stuck-projects
14200 (or current-prefix-arg org-last-arg))))))
14202 ;;; Diary integration
14204 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
14206 (defun org-get-entries-from-diary (date)
14207 "Get the (Emacs Calendar) diary entries for DATE."
14208 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
14209 (diary-display-hook '(fancy-diary-display))
14210 (list-diary-entries-hook
14211 (cons 'org-diary-default-entry list-diary-entries-hook))
14212 (diary-file-name-prefix-function nil) ; turn this feature off
14213 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
14214 entries
14215 (org-disable-agenda-to-diary t))
14216 (save-excursion
14217 (save-window-excursion
14218 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
14219 (if (not (get-buffer fancy-diary-buffer))
14220 (setq entries nil)
14221 (with-current-buffer fancy-diary-buffer
14222 (setq buffer-read-only nil)
14223 (if (= (point-max) 1)
14224 ;; No entries
14225 (setq entries nil)
14226 ;; Omit the date and other unnecessary stuff
14227 (org-agenda-cleanup-fancy-diary)
14228 ;; Add prefix to each line and extend the text properties
14229 (if (= (point-max) 1)
14230 (setq entries nil)
14231 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
14232 (set-buffer-modified-p nil)
14233 (kill-buffer fancy-diary-buffer)))
14234 (when entries
14235 (setq entries (org-split-string entries "\n"))
14236 (setq entries
14237 (mapcar
14238 (lambda (x)
14239 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
14240 ;; Extend the text properties to the beginning of the line
14241 (org-add-props x (text-properties-at (1- (length x)) x)))
14242 entries)))))
14244 (defun org-agenda-cleanup-fancy-diary ()
14245 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
14246 This gets rid of the date, the underline under the date, and
14247 the dummy entry installed by `org-mode' to ensure non-empty diary for each
14248 date. It also removes lines that contain only whitespace."
14249 (goto-char (point-min))
14250 (if (looking-at ".*?:[ \t]*")
14251 (progn
14252 (replace-match "")
14253 (re-search-forward "\n=+$" nil t)
14254 (replace-match "")
14255 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
14256 (re-search-forward "\n=+$" nil t)
14257 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
14258 (goto-char (point-min))
14259 (while (re-search-forward "^ +\n" nil t)
14260 (replace-match ""))
14261 (goto-char (point-min))
14262 (if (re-search-forward "^Org-mode dummy\n?" nil t)
14263 (replace-match "")))
14265 ;; Make sure entries from the diary have the right text properties.
14266 (eval-after-load "diary-lib"
14267 '(if (boundp 'diary-modify-entry-list-string-function)
14268 ;; We can rely on the hook, nothing to do
14270 ;; Hook not avaiable, must use advice to make this work
14271 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
14272 "Make the position visible."
14273 (if (and org-disable-agenda-to-diary ;; called from org-agenda
14274 (stringp string)
14275 buffer-file-name)
14276 (setq string (org-modify-diary-entry-string string))))))
14278 (defun org-modify-diary-entry-string (string)
14279 "Add text properties to string, allowing org-mode to act on it."
14280 (org-add-props string nil
14281 'mouse-face 'highlight
14282 'keymap org-agenda-keymap
14283 'help-echo (format "mouse-2 or RET jump to diary file %s"
14284 (abbreviate-file-name buffer-file-name))
14285 'org-agenda-diary-link t
14286 'org-marker (org-agenda-new-marker (point-at-bol))))
14288 (defun org-diary-default-entry ()
14289 "Add a dummy entry to the diary.
14290 Needed to avoid empty dates which mess up holiday display."
14291 ;; Catch the error if dealing with the new add-to-diary-alist
14292 (when org-disable-agenda-to-diary
14293 (condition-case nil
14294 (add-to-diary-list original-date "Org-mode dummy" "")
14295 (error
14296 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
14298 ;;;###autoload
14299 (defun org-diary (&rest args)
14300 "Return diary information from org-files.
14301 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
14302 It accesses org files and extracts information from those files to be
14303 listed in the diary. The function accepts arguments specifying what
14304 items should be listed. The following arguments are allowed:
14306 :timestamp List the headlines of items containing a date stamp or
14307 date range matching the selected date. Deadlines will
14308 also be listed, on the expiration day.
14310 :deadline List any deadlines past due, or due within
14311 `org-deadline-warning-days'. The listing occurs only
14312 in the diary for *today*, not at any other date. If
14313 an entry is marked DONE, it is no longer listed.
14315 :scheduled List all items which are scheduled for the given date.
14316 The diary for *today* also contains items which were
14317 scheduled earlier and are not yet marked DONE.
14319 :todo List all TODO items from the org-file. This may be a
14320 long list - so this is not turned on by default.
14321 Like deadlines, these entries only show up in the
14322 diary for *today*, not at any other date.
14324 The call in the diary file should look like this:
14326 &%%(org-diary) ~/path/to/some/orgfile.org
14328 Use a separate line for each org file to check. Or, if you omit the file name,
14329 all files listed in `org-agenda-files' will be checked automatically:
14331 &%%(org-diary)
14333 If you don't give any arguments (as in the example above), the default
14334 arguments (:deadline :scheduled :timestamp) are used. So the example above may
14335 also be written as
14337 &%%(org-diary :deadline :timestamp :scheduled)
14339 The function expects the lisp variables `entry' and `date' to be provided
14340 by the caller, because this is how the calendar works. Don't use this
14341 function from a program - use `org-agenda-get-day-entries' instead."
14342 (org-agenda-maybe-reset-markers)
14343 (org-compile-prefix-format 'agenda)
14344 (org-set-sorting-strategy 'agenda)
14345 (setq args (or args '(:deadline :scheduled :timestamp)))
14346 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
14347 (list entry)
14348 (org-agenda-files t)))
14349 file rtn results)
14350 ;; If this is called during org-agenda, don't return any entries to
14351 ;; the calendar. Org Agenda will list these entries itself.
14352 (if org-disable-agenda-to-diary (setq files nil))
14353 (while (setq file (pop files))
14354 (setq rtn (apply 'org-agenda-get-day-entries file date args))
14355 (setq results (append results rtn)))
14356 (if results
14357 (concat (org-finalize-agenda-entries results) "\n"))))
14359 ;;; Agenda entry finders
14361 (defun org-agenda-get-day-entries (file date &rest args)
14362 "Does the work for `org-diary' and `org-agenda'.
14363 FILE is the path to a file to be checked for entries. DATE is date like
14364 the one returned by `calendar-current-date'. ARGS are symbols indicating
14365 which kind of entries should be extracted. For details about these, see
14366 the documentation of `org-diary'."
14367 (setq args (or args '(:deadline :scheduled :timestamp)))
14368 (let* ((org-startup-folded nil)
14369 (org-startup-align-all-tables nil)
14370 (buffer (if (file-exists-p file)
14371 (org-get-agenda-file-buffer file)
14372 (error "No such file %s" file)))
14373 arg results rtn)
14374 (if (not buffer)
14375 ;; If file does not exist, make sure an error message ends up in diary
14376 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14377 (with-current-buffer buffer
14378 (unless (org-mode-p)
14379 (error "Agenda file %s is not in `org-mode'" file))
14380 (setq org-category-table (org-get-category-table))
14381 (let ((case-fold-search nil))
14382 (save-excursion
14383 (save-restriction
14384 (if org-agenda-restrict
14385 (narrow-to-region org-agenda-restrict-begin
14386 org-agenda-restrict-end)
14387 (widen))
14388 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
14389 (while (setq arg (pop args))
14390 (cond
14391 ((and (eq arg :todo)
14392 (equal date (calendar-current-date)))
14393 (setq rtn (org-agenda-get-todos))
14394 (setq results (append results rtn)))
14395 ((eq arg :timestamp)
14396 (setq rtn (org-agenda-get-blocks))
14397 (setq results (append results rtn))
14398 (setq rtn (org-agenda-get-timestamps))
14399 (setq results (append results rtn)))
14400 ((eq arg :scheduled)
14401 (setq rtn (org-agenda-get-scheduled))
14402 (setq results (append results rtn)))
14403 ((eq arg :closed)
14404 (setq rtn (org-agenda-get-closed))
14405 (setq results (append results rtn)))
14406 ((and (eq arg :deadline)
14407 (equal date (calendar-current-date)))
14408 (setq rtn (org-agenda-get-deadlines))
14409 (setq results (append results rtn))))))))
14410 results))))
14412 (defun org-entry-is-done-p ()
14413 "Is the current entry marked DONE?"
14414 (save-excursion
14415 (and (re-search-backward "[\r\n]\\*" nil t)
14416 (looking-at org-nl-done-regexp))))
14418 (defun org-at-date-range-p (&optional inactive-ok)
14419 "Is the cursor inside a date range?"
14420 (interactive)
14421 (save-excursion
14422 (catch 'exit
14423 (let ((pos (point)))
14424 (skip-chars-backward "^[<\r\n")
14425 (skip-chars-backward "<[")
14426 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
14427 (>= (match-end 0) pos)
14428 (throw 'exit t))
14429 (skip-chars-backward "^<[\r\n")
14430 (skip-chars-backward "<[")
14431 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
14432 (>= (match-end 0) pos)
14433 (throw 'exit t)))
14434 nil)))
14436 (defun org-agenda-get-todos ()
14437 "Return the TODO information for agenda display."
14438 (let* ((props (list 'face nil
14439 'done-face 'org-done
14440 'org-not-done-regexp org-not-done-regexp
14441 'mouse-face 'highlight
14442 'keymap org-agenda-keymap
14443 'help-echo
14444 (format "mouse-2 or RET jump to org file %s"
14445 (abbreviate-file-name buffer-file-name))))
14446 (regexp (concat "[\n\r]\\*+ *\\("
14447 (if org-select-this-todo-keyword
14448 (concat "\\<\\(" org-select-this-todo-keyword
14449 "\\)\\>")
14450 org-not-done-regexp)
14451 "[^\n\r]*\\)"))
14452 marker priority category tags
14453 ee txt beg end)
14454 (goto-char (point-min))
14455 (while (re-search-forward regexp nil t)
14456 (catch :skip
14457 (save-match-data
14458 (beginning-of-line)
14459 (setq beg (point) end (progn (outline-next-heading) (point)))
14460 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
14461 (re-search-forward org-scheduled-time-regexp end t))
14462 (and org-agenda-todo-ignore-deadlines (goto-char beg)
14463 (re-search-forward org-deadline-time-regexp end t)
14464 (org-deadline-close (match-string 1))))
14465 (goto-char beg)
14466 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
14467 (throw :skip nil)))
14468 (org-agenda-skip)
14469 (goto-char (match-beginning 1))
14470 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
14471 category (org-get-category)
14472 tags (org-get-tags-at (point))
14473 txt (org-format-agenda-item "" (match-string 1) category tags)
14474 priority
14475 (+ (org-get-priority txt)
14476 (if org-todo-kwd-priority-p
14477 (- org-todo-kwd-max-priority -2
14478 (length
14479 (member (match-string 2) org-todo-keywords)))
14480 1)))
14481 (org-add-props txt props
14482 'org-marker marker 'org-hd-marker marker
14483 'priority priority 'org-category category)
14484 (push txt ee)
14485 (if org-agenda-todo-list-sublevels
14486 (goto-char (match-end 1))
14487 (org-end-of-subtree 'invisible))))
14488 (nreverse ee)))
14490 (defconst org-agenda-no-heading-message
14491 "No heading for this item in buffer or region.")
14493 (defun org-agenda-get-timestamps ()
14494 "Return the date stamp information for agenda display."
14495 (let* ((props (list 'face nil
14496 'org-not-done-regexp org-not-done-regexp
14497 'mouse-face 'highlight
14498 'keymap org-agenda-keymap
14499 'help-echo
14500 (format "mouse-2 or RET jump to org file %s"
14501 (abbreviate-file-name buffer-file-name))))
14502 (regexp (regexp-quote
14503 (substring
14504 (format-time-string
14505 (car org-time-stamp-formats)
14506 (apply 'encode-time ; DATE bound by calendar
14507 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
14508 0 11)))
14509 marker hdmarker deadlinep scheduledp donep tmp priority category
14510 ee txt timestr tags)
14511 (goto-char (point-min))
14512 (while (re-search-forward regexp nil t)
14513 (catch :skip
14514 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
14515 (org-agenda-skip)
14516 (setq marker (org-agenda-new-marker (match-beginning 0))
14517 category (org-get-category (match-beginning 0))
14518 tmp (buffer-substring (max (point-min)
14519 (- (match-beginning 0)
14520 org-ds-keyword-length))
14521 (match-beginning 0))
14522 timestr (buffer-substring (match-beginning 0) (point-at-eol))
14523 deadlinep (string-match org-deadline-regexp tmp)
14524 scheduledp (string-match org-scheduled-regexp tmp)
14525 donep (org-entry-is-done-p))
14526 (and org-agenda-skip-scheduled-if-done
14527 scheduledp donep
14528 (throw :skip t))
14529 (if (string-match ">" timestr)
14530 ;; substring should only run to end of time stamp
14531 (setq timestr (substring timestr 0 (match-end 0))))
14532 (save-excursion
14533 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
14534 (progn
14535 (goto-char (match-end 1))
14536 (setq hdmarker (org-agenda-new-marker)
14537 tags (org-get-tags-at))
14538 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
14539 (setq txt (org-format-agenda-item
14540 (format "%s%s"
14541 (if deadlinep "Deadline: " "")
14542 (if scheduledp "Scheduled: " ""))
14543 (match-string 1) category tags timestr)))
14544 (setq txt org-agenda-no-heading-message))
14545 (setq priority (org-get-priority txt))
14546 (org-add-props txt props
14547 'org-marker marker 'org-hd-marker hdmarker)
14548 (if deadlinep
14549 (org-add-props txt nil
14550 'face (if donep 'org-done 'org-warning)
14551 'undone-face 'org-warning 'done-face 'org-done
14552 'org-category category 'priority (+ 100 priority))
14553 (if scheduledp
14554 (org-add-props txt nil
14555 'face 'org-scheduled-today
14556 'undone-face 'org-scheduled-today 'done-face 'org-done
14557 'org-category category 'priority (+ 99 priority))
14558 (org-add-props txt nil 'priority priority 'org-category category)))
14559 (push txt ee))
14560 (outline-next-heading)))
14561 (nreverse ee)))
14563 (defun org-agenda-get-closed ()
14564 "Return the logged TODO entries for agenda display."
14565 (let* ((props (list 'mouse-face 'highlight
14566 'org-not-done-regexp org-not-done-regexp
14567 'keymap org-agenda-keymap
14568 'help-echo
14569 (format "mouse-2 or RET jump to org file %s"
14570 (abbreviate-file-name buffer-file-name))))
14571 (regexp (concat
14572 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
14573 (regexp-quote
14574 (substring
14575 (format-time-string
14576 (car org-time-stamp-formats)
14577 (apply 'encode-time ; DATE bound by calendar
14578 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
14579 1 11))))
14580 marker hdmarker priority category tags closedp
14581 ee txt timestr)
14582 (goto-char (point-min))
14583 (while (re-search-forward regexp nil t)
14584 (catch :skip
14585 (org-agenda-skip)
14586 (setq marker (org-agenda-new-marker (match-beginning 0))
14587 closedp (equal (match-string 1) org-closed-string)
14588 category (org-get-category (match-beginning 0))
14589 timestr (buffer-substring (match-beginning 0) (point-at-eol))
14590 ;; donep (org-entry-is-done-p)
14592 (if (string-match "\\]" timestr)
14593 ;; substring should only run to end of time stamp
14594 (setq timestr (substring timestr 0 (match-end 0))))
14595 (save-excursion
14596 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
14597 (progn
14598 (goto-char (match-end 1))
14599 (setq hdmarker (org-agenda-new-marker)
14600 tags (org-get-tags-at))
14601 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
14602 (setq txt (org-format-agenda-item
14603 (if closedp "Closed: " "Clocked: ")
14604 (match-string 1) category tags timestr)))
14605 (setq txt org-agenda-no-heading-message))
14606 (setq priority 100000)
14607 (org-add-props txt props
14608 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
14609 'priority priority 'org-category category
14610 'undone-face 'org-warning 'done-face 'org-done)
14611 (push txt ee))
14612 (outline-next-heading)))
14613 (nreverse ee)))
14615 (defun org-agenda-get-deadlines ()
14616 "Return the deadline information for agenda display."
14617 (let* ((wdays org-deadline-warning-days)
14618 (props (list 'mouse-face 'highlight
14619 'org-not-done-regexp org-not-done-regexp
14620 'keymap org-agenda-keymap
14621 'help-echo
14622 (format "mouse-2 or RET jump to org file %s"
14623 (abbreviate-file-name buffer-file-name))))
14624 (regexp org-deadline-time-regexp)
14625 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
14626 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
14627 d2 diff pos pos1 category tags
14628 ee txt head face)
14629 (goto-char (point-min))
14630 (while (re-search-forward regexp nil t)
14631 (catch :skip
14632 (org-agenda-skip)
14633 (setq pos (1- (match-beginning 1))
14634 d2 (time-to-days
14635 (org-time-string-to-time (match-string 1)))
14636 diff (- d2 d1))
14637 ;; When to show a deadline in the calendar:
14638 ;; If the expiration is within wdays warning time.
14639 ;; Past-due deadlines are only shown on the current date
14640 (if (and (< diff wdays) todayp (not (= diff 0)))
14641 (save-excursion
14642 (setq category (org-get-category))
14643 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
14644 (progn
14645 (goto-char (match-end 0))
14646 (setq pos1 (match-end 1))
14647 (setq tags (org-get-tags-at pos1))
14648 (setq head (buffer-substring-no-properties
14649 (point)
14650 (progn (skip-chars-forward "^\r\n")
14651 (point))))
14652 (if (string-match org-looking-at-done-regexp head)
14653 (setq txt nil)
14654 (setq txt (org-format-agenda-item
14655 (format "In %3d d.: " diff) head category tags))))
14656 (setq txt org-agenda-no-heading-message))
14657 (when txt
14658 (setq face (cond ((<= diff 0) 'org-warning)
14659 ((<= diff 5) 'org-upcoming-deadline)
14660 (t nil)))
14661 (org-add-props txt props
14662 'org-marker (org-agenda-new-marker pos)
14663 'org-hd-marker (org-agenda-new-marker pos1)
14664 'priority (+ (- 10 diff) (org-get-priority txt))
14665 'org-category category
14666 'face face 'undone-face face 'done-face 'org-done)
14667 (push txt ee))))))
14668 ee))
14670 (defun org-agenda-get-scheduled ()
14671 "Return the scheduled information for agenda display."
14672 (let* ((props (list 'face 'org-scheduled-previously
14673 'org-not-done-regexp org-not-done-regexp
14674 'undone-face 'org-scheduled-previously
14675 'done-face 'org-done
14676 'mouse-face 'highlight
14677 'keymap org-agenda-keymap
14678 'help-echo
14679 (format "mouse-2 or RET jump to org file %s"
14680 (abbreviate-file-name buffer-file-name))))
14681 (regexp org-scheduled-time-regexp)
14682 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
14683 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
14684 d2 diff pos pos1 category tags
14685 ee txt head)
14686 (goto-char (point-min))
14687 (while (re-search-forward regexp nil t)
14688 (catch :skip
14689 (org-agenda-skip)
14690 (setq pos (1- (match-beginning 1))
14691 d2 (time-to-days
14692 (org-time-string-to-time (match-string 1)))
14693 diff (- d2 d1))
14694 ;; When to show a scheduled item in the calendar:
14695 ;; If it is on or past the date.
14696 (if (and (< diff 0) todayp)
14697 (save-excursion
14698 (setq category (org-get-category))
14699 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
14700 (progn
14701 (goto-char (match-end 0))
14702 (setq pos1 (match-end 1))
14703 (setq tags (org-get-tags-at))
14704 (setq head (buffer-substring-no-properties
14705 (point)
14706 (progn (skip-chars-forward "^\r\n") (point))))
14707 (if (string-match org-looking-at-done-regexp head)
14708 (setq txt nil)
14709 (setq txt (org-format-agenda-item
14710 (format "Sched.%2dx: " (- 1 diff)) head
14711 category tags))))
14712 (setq txt org-agenda-no-heading-message))
14713 (when txt
14714 (org-add-props txt props
14715 'org-marker (org-agenda-new-marker pos)
14716 'org-hd-marker (org-agenda-new-marker pos1)
14717 'priority (+ (- 5 diff) (org-get-priority txt))
14718 'org-category category)
14719 (push txt ee))))))
14720 ee))
14722 (defun org-agenda-get-blocks ()
14723 "Return the date-range information for agenda display."
14724 (let* ((props (list 'face nil
14725 'org-not-done-regexp org-not-done-regexp
14726 'mouse-face 'highlight
14727 'keymap org-agenda-keymap
14728 'help-echo
14729 (format "mouse-2 or RET jump to org file %s"
14730 (abbreviate-file-name buffer-file-name))))
14731 (regexp org-tr-regexp)
14732 (d0 (calendar-absolute-from-gregorian date))
14733 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
14734 (goto-char (point-min))
14735 (while (re-search-forward regexp nil t)
14736 (catch :skip
14737 (org-agenda-skip)
14738 (setq pos (point))
14739 (setq timestr (match-string 0)
14740 s1 (match-string 1)
14741 s2 (match-string 2)
14742 d1 (time-to-days (org-time-string-to-time s1))
14743 d2 (time-to-days (org-time-string-to-time s2)))
14744 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
14745 ;; Only allow days between the limits, because the normal
14746 ;; date stamps will catch the limits.
14747 (save-excursion
14748 (setq marker (org-agenda-new-marker (point)))
14749 (setq category (org-get-category))
14750 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
14751 (progn
14752 (setq hdmarker (org-agenda-new-marker (match-end 1)))
14753 (goto-char (match-end 1))
14754 (setq tags (org-get-tags-at))
14755 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
14756 (setq txt (org-format-agenda-item
14757 (format (if (= d1 d2) "" "(%d/%d): ")
14758 (1+ (- d0 d1)) (1+ (- d2 d1)))
14759 (match-string 1) category tags
14760 (if (= d0 d1) timestr))))
14761 (setq txt org-agenda-no-heading-message))
14762 (org-add-props txt props
14763 'org-marker marker 'org-hd-marker hdmarker
14764 'priority (org-get-priority txt) 'org-category category)
14765 (push txt ee)))
14766 (goto-char pos)))
14767 ;; Sort the entries by expiration date.
14768 (nreverse ee)))
14770 ;;; Agenda presentation and sorting
14772 ;; FIXME: should I allow spaces around the dash?
14773 (defconst org-plain-time-of-day-regexp
14774 (concat
14775 "\\(\\<[012]?[0-9]"
14776 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
14777 "\\(--?"
14778 "\\(\\<[012]?[0-9]"
14779 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
14780 "\\)?")
14781 "Regular expression to match a plain time or time range.
14782 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
14783 groups carry important information:
14784 0 the full match
14785 1 the first time, range or not
14786 8 the second time, if it is a range.")
14788 (defconst org-stamp-time-of-day-regexp
14789 (concat
14790 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
14791 "\\([012][0-9]:[0-5][0-9]\\)>"
14792 "\\(--?"
14793 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
14794 "Regular expression to match a timestamp time or time range.
14795 After a match, the following groups carry important information:
14796 0 the full match
14797 1 date plus weekday, for backreferencing to make sure both times on same day
14798 2 the first time, range or not
14799 4 the second time, if it is a range.")
14801 (defvar org-prefix-has-time nil
14802 "A flag, set by `org-compile-prefix-format'.
14803 The flag is set if the currently compiled format contains a `%t'.")
14804 (defvar org-prefix-has-tag nil
14805 "A flag, set by `org-compile-prefix-format'.
14806 The flag is set if the currently compiled format contains a `%T'.")
14808 (defun org-format-agenda-item (extra txt &optional category tags dotime
14809 noprefix)
14810 "Format TXT to be inserted into the agenda buffer.
14811 In particular, it adds the prefix and corresponding text properties. EXTRA
14812 must be a string and replaces the `%s' specifier in the prefix format.
14813 CATEGORY (string, symbol or nil) may be used to overrule the default
14814 category taken from local variable or file name. It will replace the `%c'
14815 specifier in the format. DOTIME, when non-nil, indicates that a
14816 time-of-day should be extracted from TXT for sorting of this entry, and for
14817 the `%t' specifier in the format. When DOTIME is a string, this string is
14818 searched for a time before TXT is. NOPREFIX is a flag and indicates that
14819 only the correctly processes TXT should be returned - this is used by
14820 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
14821 (save-match-data
14822 ;; Diary entries sometimes have extra whitespace at the beginning
14823 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
14824 (let* ((category (or category
14825 org-category
14826 (if buffer-file-name
14827 (file-name-sans-extension
14828 (file-name-nondirectory buffer-file-name))
14829 "")))
14830 (tag (if tags (nth (1- (length tags)) tags) ""))
14831 time ; time and tag are needed for the eval of the prefix format
14832 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
14833 (time-of-day (and dotime (org-get-time-of-day ts)))
14834 stamp plain s0 s1 s2 rtn)
14835 (when (and dotime time-of-day org-prefix-has-time)
14836 ;; Extract starting and ending time and move them to prefix
14837 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
14838 (setq plain (string-match org-plain-time-of-day-regexp ts)))
14839 (setq s0 (match-string 0 ts)
14840 s1 (match-string (if plain 1 2) ts)
14841 s2 (match-string (if plain 8 4) ts))
14843 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
14844 ;; them, we might want to remove them there to avoid duplication.
14845 ;; The user can turn this off with a variable.
14846 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
14847 (string-match (concat (regexp-quote s0) " *") txt)
14848 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
14849 (= (match-beginning 0) 0)
14851 (setq txt (replace-match "" nil nil txt))))
14852 ;; Normalize the time(s) to 24 hour
14853 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
14854 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
14856 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
14857 ;; Tags are in the string
14858 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
14859 (and org-agenda-remove-tags-when-in-prefix
14860 org-prefix-has-tag))
14861 (setq txt (replace-match "" t t txt))
14862 (setq txt (replace-match
14863 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
14864 (match-string 2 txt))
14865 t t txt))))
14867 ;; Create the final string
14868 (if noprefix
14869 (setq rtn txt)
14870 ;; Prepare the variables needed in the eval of the compiled format
14871 (setq time (cond (s2 (concat s1 "-" s2))
14872 (s1 (concat s1 "......"))
14873 (t ""))
14874 extra (or extra "")
14875 category (if (symbolp category) (symbol-name category) category))
14876 ;; Evaluate the compiled format
14877 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
14879 ;; And finally add the text properties
14880 (org-add-props rtn nil
14881 'org-category (downcase category) 'tags tags
14882 'prefix-length (- (length rtn) (length txt))
14883 'time-of-day time-of-day
14884 'dotime dotime))))
14886 (defvar org-agenda-sorting-strategy)
14887 (defvar org-agenda-sorting-strategy-selected nil)
14889 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
14890 (catch 'exit
14891 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
14892 ((and todayp (member 'today (car org-agenda-time-grid))))
14893 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
14894 ((member 'weekly (car org-agenda-time-grid)))
14895 (t (throw 'exit list)))
14896 (let* ((have (delq nil (mapcar
14897 (lambda (x) (get-text-property 1 'time-of-day x))
14898 list)))
14899 (string (nth 1 org-agenda-time-grid))
14900 (gridtimes (nth 2 org-agenda-time-grid))
14901 (req (car org-agenda-time-grid))
14902 (remove (member 'remove-match req))
14903 new time)
14904 (if (and (member 'require-timed req) (not have))
14905 ;; don't show empty grid
14906 (throw 'exit list))
14907 (while (setq time (pop gridtimes))
14908 (unless (and remove (member time have))
14909 (setq time (int-to-string time))
14910 (push (org-format-agenda-item
14911 nil string "" nil
14912 (concat (substring time 0 -2) ":" (substring time -2)))
14913 new)
14914 (put-text-property
14915 1 (length (car new)) 'face 'org-time-grid (car new))))
14916 (if (member 'time-up org-agenda-sorting-strategy-selected)
14917 (append new list)
14918 (append list new)))))
14920 (defun org-compile-prefix-format (key)
14921 "Compile the prefix format into a Lisp form that can be evaluated.
14922 The resulting form is returned and stored in the variable
14923 `org-prefix-format-compiled'."
14924 (setq org-prefix-has-time nil org-prefix-has-tag nil)
14925 (let ((s (cond
14926 ((stringp org-agenda-prefix-format)
14927 org-agenda-prefix-format)
14928 ((assq key org-agenda-prefix-format)
14929 (cdr (assq key org-agenda-prefix-format)))
14930 (t " %-12:c%?-12t% s")))
14931 (start 0)
14932 varform vars var e c f opt)
14933 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
14934 s start)
14935 (setq var (cdr (assoc (match-string 4 s)
14936 '(("c" . category) ("t" . time) ("s" . extra)
14937 ("T" . tag))))
14938 c (or (match-string 3 s) "")
14939 opt (match-beginning 1)
14940 start (1+ (match-beginning 0)))
14941 (if (equal var 'time) (setq org-prefix-has-time t))
14942 (if (equal var 'tag) (setq org-prefix-has-tag t))
14943 (setq f (concat "%" (match-string 2 s) "s"))
14944 (if opt
14945 (setq varform
14946 `(if (equal "" ,var)
14948 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
14949 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
14950 (setq s (replace-match "%s" t nil s))
14951 (push varform vars))
14952 (setq vars (nreverse vars))
14953 (setq org-prefix-format-compiled `(format ,s ,@vars))))
14955 (defun org-set-sorting-strategy (key)
14956 (if (symbolp (car org-agenda-sorting-strategy))
14957 ;; the old format
14958 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
14959 (setq org-agenda-sorting-strategy-selected
14960 (or (cdr (assq key org-agenda-sorting-strategy))
14961 (cdr (assq 'agenda org-agenda-sorting-strategy))
14962 '(time-up category-keep priority-down)))))
14964 (defun org-get-time-of-day (s &optional string mod24)
14965 "Check string S for a time of day.
14966 If found, return it as a military time number between 0 and 2400.
14967 If not found, return nil.
14968 The optional STRING argument forces conversion into a 5 character wide string
14969 HH:MM."
14970 (save-match-data
14971 (when
14973 (string-match
14974 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
14975 (string-match
14976 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
14977 (let* ((h (string-to-number (match-string 1 s)))
14978 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
14979 (ampm (if (match-end 4) (downcase (match-string 4 s))))
14980 (am-p (equal ampm "am"))
14981 (h1 (cond ((not ampm) h)
14982 ((= h 12) (if am-p 0 12))
14983 (t (+ h (if am-p 0 12)))))
14984 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
14985 (mod h1 24) h1))
14986 (t0 (+ (* 100 h2) m))
14987 (t1 (concat (if (>= h1 24) "+" " ")
14988 (if (< t0 100) "0" "")
14989 (if (< t0 10) "0" "")
14990 (int-to-string t0))))
14991 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
14993 (defun org-finalize-agenda-entries (list &optional nosort)
14994 "Sort and concatenate the agenda items."
14995 (setq list (mapcar 'org-agenda-highlight-todo list))
14996 (if nosort
14997 list
14998 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
15000 (defun org-agenda-highlight-todo (x)
15001 (let (re pl)
15002 (if (eq x 'line)
15003 (save-excursion
15004 (beginning-of-line 1)
15005 (setq re (get-text-property (point) 'org-not-done-regexp))
15006 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
15007 (and (looking-at (concat "[ \t]*\\.*" re))
15008 (add-text-properties (match-beginning 0) (match-end 0)
15009 '(face org-todo))))
15010 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
15011 pl (get-text-property 0 'prefix-length x))
15012 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
15013 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
15014 '(face org-todo) x))
15015 x)))
15017 (defsubst org-cmp-priority (a b)
15018 "Compare the priorities of string A and B."
15019 (let ((pa (or (get-text-property 1 'priority a) 0))
15020 (pb (or (get-text-property 1 'priority b) 0)))
15021 (cond ((> pa pb) +1)
15022 ((< pa pb) -1)
15023 (t nil))))
15025 (defsubst org-cmp-category (a b)
15026 "Compare the string values of categories of strings A and B."
15027 (let ((ca (or (get-text-property 1 'category a) ""))
15028 (cb (or (get-text-property 1 'category b) "")))
15029 (cond ((string-lessp ca cb) -1)
15030 ((string-lessp cb ca) +1)
15031 (t nil))))
15033 (defsubst org-cmp-tag (a b)
15034 "Compare the string values of categories of strings A and B."
15035 (let ((ta (car (last (get-text-property 1 'tags a))))
15036 (tb (car (last (get-text-property 1 'tags b)))))
15037 (cond ((not ta) +1)
15038 ((not tb) -1)
15039 ((string-lessp ta tb) -1)
15040 ((string-lessp tb ta) +1)
15041 (t nil))))
15043 (defsubst org-cmp-time (a b)
15044 "Compare the time-of-day values of strings A and B."
15045 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
15046 (ta (or (get-text-property 1 'time-of-day a) def))
15047 (tb (or (get-text-property 1 'time-of-day b) def)))
15048 (cond ((< ta tb) -1)
15049 ((< tb ta) +1)
15050 (t nil))))
15052 (defun org-entries-lessp (a b)
15053 "Predicate for sorting agenda entries."
15054 ;; The following variables will be used when the form is evaluated.
15055 ;; So even though the compiler complains, keep them.
15056 (let* ((time-up (org-cmp-time a b))
15057 (time-down (if time-up (- time-up) nil))
15058 (priority-up (org-cmp-priority a b))
15059 (priority-down (if priority-up (- priority-up) nil))
15060 (category-up (org-cmp-category a b))
15061 (category-down (if category-up (- category-up) nil))
15062 (category-keep (if category-up +1 nil))
15063 (tag-up (org-cmp-tag a b))
15064 (tag-down (if tag-up (- tag-up) nil)))
15065 (cdr (assoc
15066 (eval (cons 'or org-agenda-sorting-strategy-selected))
15067 '((-1 . t) (1 . nil) (nil . nil))))))
15069 ;;; Agenda commands
15071 (defun org-agenda-check-type (error &rest types)
15072 "Check if agenda buffer is of allowed type.
15073 If ERROR is non-nil, throw an error, otherwise just return nil."
15074 (if (memq org-agenda-type types)
15076 (if error
15077 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
15078 nil)))
15080 (defun org-agenda-quit ()
15081 "Exit agenda by removing the window or the buffer."
15082 (interactive)
15083 (let ((buf (current-buffer)))
15084 (if (not (one-window-p)) (delete-window))
15085 (kill-buffer buf)
15086 (org-agenda-maybe-reset-markers 'force))
15087 ;; Maybe restore the pre-agenda window configuration.
15088 (and org-agenda-restore-windows-after-quit
15089 (not (eq org-agenda-window-setup 'other-frame))
15090 org-pre-agenda-window-conf
15091 (set-window-configuration org-pre-agenda-window-conf)))
15093 (defun org-agenda-exit ()
15094 "Exit agenda by removing the window or the buffer.
15095 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
15096 Org-mode buffers visited directly by the user will not be touched."
15097 (interactive)
15098 (org-release-buffers org-agenda-new-buffers)
15099 (setq org-agenda-new-buffers nil)
15100 (org-agenda-quit))
15102 (defun org-save-all-org-buffers ()
15103 "Save all Org-mode buffers without user confirmation."
15104 (interactive)
15105 (message "Saving all Org-mode buffers...")
15106 (save-some-buffers t 'org-mode-p)
15107 (message "Saving all Org-mode buffers... done"))
15109 (defun org-agenda-redo ()
15110 "Rebuild Agenda.
15111 When this is the global TODO list, a prefix argument will be interpreted."
15112 (interactive)
15113 (let* ((org-agenda-keep-modes t)
15114 (line (org-current-line))
15115 (window-line (- line (org-current-line (window-start)))))
15116 (message "Rebuilding agenda buffer...")
15117 (eval org-agenda-redo-command)
15118 (setq org-agenda-undo-list nil
15119 org-agenda-pending-undo-list nil)
15120 (message "Rebuilding agenda buffer...done")
15121 (goto-line line)
15122 (recenter window-line)))
15124 (defun org-agenda-goto-today ()
15125 "Go to today."
15126 (interactive)
15127 (org-agenda-check-type t 'timeline 'agenda)
15128 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
15129 (cond
15130 (tdpos (goto-char tdpos))
15131 ((eq org-agenda-type 'agenda)
15132 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
15133 (setf (nth 1 org-agenda-overriding-arguments) nil)
15134 (org-agenda-redo)
15135 (org-agenda-find-today-or-agenda)))
15136 (t (error "Cannot find today")))))
15138 (defun org-agenda-find-today-or-agenda ()
15139 (goto-char
15140 (or (text-property-any (point-min) (point-max) 'org-today t)
15141 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
15142 (point-min))))
15144 (defun org-agenda-later (arg)
15145 "Go forward in time by `org-agenda-ndays' days.
15146 With prefix ARG, go forward that many times `org-agenda-ndays'."
15147 (interactive "p")
15148 (org-agenda-check-type t 'agenda)
15149 (let ((org-agenda-overriding-arguments
15150 (list (car org-agenda-last-arguments)
15151 (+ org-starting-day (* arg org-agenda-ndays))
15152 nil t)))
15153 (org-agenda-redo)
15154 (org-agenda-find-today-or-agenda)))
15156 (defun org-agenda-earlier (arg)
15157 "Go back in time by `org-agenda-ndays' days.
15158 With prefix ARG, go back that many times `org-agenda-ndays'."
15159 (interactive "p")
15160 (org-agenda-check-type t 'agenda)
15161 (let ((org-agenda-overriding-arguments
15162 (list (car org-agenda-last-arguments)
15163 (- org-starting-day (* arg org-agenda-ndays))
15164 nil t)))
15165 (org-agenda-redo)
15166 (org-agenda-find-today-or-agenda)))
15168 (defun org-agenda-week-view ()
15169 "Switch to weekly view for agenda."
15170 (interactive)
15171 (org-agenda-check-type t 'agenda)
15172 (if (= org-agenda-ndays 7)
15173 (error "This is already the week view"))
15174 (setq org-agenda-ndays 7)
15175 (let ((org-agenda-overriding-arguments
15176 (list (car org-agenda-last-arguments)
15177 (or (get-text-property (point) 'day)
15178 org-starting-day)
15179 nil t)))
15180 (org-agenda-redo)
15181 (org-agenda-find-today-or-agenda))
15182 (org-agenda-set-mode-name)
15183 (message "Switched to week view"))
15185 (defun org-agenda-day-view ()
15186 "Switch to daily view for agenda."
15187 (interactive)
15188 (org-agenda-check-type t 'agenda)
15189 (if (= org-agenda-ndays 1)
15190 (error "This is already the day view"))
15191 (setq org-agenda-ndays 1)
15192 (let ((org-agenda-overriding-arguments
15193 (list (car org-agenda-last-arguments)
15194 (or (get-text-property (point) 'day)
15195 org-starting-day)
15196 nil t)))
15197 (org-agenda-redo)
15198 (org-agenda-find-today-or-agenda))
15199 (org-agenda-set-mode-name)
15200 (message "Switched to day view"))
15202 ;; FIXME: this no longer works if user make date format that starts with a blank
15203 (defun org-agenda-next-date-line (&optional arg)
15204 "Jump to the next line indicating a date in agenda buffer."
15205 (interactive "p")
15206 (org-agenda-check-type t 'agenda 'timeline)
15207 (beginning-of-line 1)
15208 (if (looking-at "^\\S-") (forward-char 1))
15209 (if (not (re-search-forward "^\\S-" nil t arg))
15210 (progn
15211 (backward-char 1)
15212 (error "No next date after this line in this buffer")))
15213 (goto-char (match-beginning 0)))
15215 (defun org-agenda-previous-date-line (&optional arg)
15216 "Jump to the previous line indicating a date in agenda buffer."
15217 (interactive "p")
15218 (org-agenda-check-type t 'agenda 'timeline)
15219 (beginning-of-line 1)
15220 (if (not (re-search-backward "^\\S-" nil t arg))
15221 (error "No previous date before this line in this buffer")))
15223 ;; Initialize the highlight
15224 (defvar org-hl (org-make-overlay 1 1))
15225 (org-overlay-put org-hl 'face 'highlight)
15227 (defun org-highlight (begin end &optional buffer)
15228 "Highlight a region with overlay."
15229 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
15230 org-hl begin end (or buffer (current-buffer))))
15232 (defun org-unhighlight ()
15233 "Detach overlay INDEX."
15234 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
15236 (defun org-highlight-until-next-command (beg end &optional buffer)
15237 (org-highlight beg end buffer)
15238 (add-hook 'pre-command-hook 'org-unhighlight-once))
15240 (defun org-unhighlight-once ()
15241 (remove-hook 'pre-command-hook 'org-unhighlight-once)
15242 (org-unhighlight))
15244 (defun org-agenda-follow-mode ()
15245 "Toggle follow mode in an agenda buffer."
15246 (interactive)
15247 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
15248 (org-agenda-set-mode-name)
15249 (message "Follow mode is %s"
15250 (if org-agenda-follow-mode "on" "off")))
15252 (defun org-agenda-log-mode ()
15253 "Toggle log mode in an agenda buffer."
15254 (interactive)
15255 (org-agenda-check-type t 'agenda 'timeline)
15256 (setq org-agenda-show-log (not org-agenda-show-log))
15257 (org-agenda-set-mode-name)
15258 (org-agenda-redo)
15259 (message "Log mode is %s"
15260 (if org-agenda-show-log "on" "off")))
15262 (defun org-agenda-toggle-diary ()
15263 "Toggle diary inclusion in an agenda buffer."
15264 (interactive)
15265 (org-agenda-check-type t 'agenda)
15266 (setq org-agenda-include-diary (not org-agenda-include-diary))
15267 (org-agenda-redo)
15268 (org-agenda-set-mode-name)
15269 (message "Diary inclusion turned %s"
15270 (if org-agenda-include-diary "on" "off")))
15272 (defun org-agenda-toggle-time-grid ()
15273 "Toggle time grid in an agenda buffer."
15274 (interactive)
15275 (org-agenda-check-type t 'agenda)
15276 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
15277 (org-agenda-redo)
15278 (org-agenda-set-mode-name)
15279 (message "Time-grid turned %s"
15280 (if org-agenda-use-time-grid "on" "off")))
15282 (defun org-agenda-set-mode-name ()
15283 "Set the mode name to indicate all the small mode settings."
15284 (setq mode-name
15285 (concat "Org-Agenda"
15286 (if (equal org-agenda-ndays 1) " Day" "")
15287 (if (equal org-agenda-ndays 7) " Week" "")
15288 (if org-agenda-follow-mode " Follow" "")
15289 (if org-agenda-include-diary " Diary" "")
15290 (if org-agenda-use-time-grid " Grid" "")
15291 (if org-agenda-show-log " Log" "")))
15292 (force-mode-line-update))
15294 (defun org-agenda-post-command-hook ()
15295 (and (eolp) (not (bolp)) (backward-char 1))
15296 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
15297 (if (and org-agenda-follow-mode
15298 (get-text-property (point) 'org-marker))
15299 (org-agenda-show)))
15301 (defun org-agenda-show-priority ()
15302 "Show the priority of the current item.
15303 This priority is composed of the main priority given with the [#A] cookies,
15304 and by additional input from the age of a schedules or deadline entry."
15305 (interactive)
15306 (let* ((pri (get-text-property (point-at-bol) 'priority)))
15307 (message "Priority is %d" (if pri pri -1000))))
15309 (defun org-agenda-show-tags ()
15310 "Show the tags applicable to the current item."
15311 (interactive)
15312 (let* ((tags (get-text-property (point-at-bol) 'tags)))
15313 (if tags
15314 (message "Tags are :%s:"
15315 (org-no-properties (mapconcat 'identity tags ":")))
15316 (message "No tags associated with this line"))))
15318 (defun org-agenda-goto (&optional highlight)
15319 "Go to the Org-mode file which contains the item at point."
15320 (interactive)
15321 (let* ((marker (or (get-text-property (point) 'org-marker)
15322 (org-agenda-error)))
15323 (buffer (marker-buffer marker))
15324 (pos (marker-position marker)))
15325 (switch-to-buffer-other-window buffer)
15326 (widen)
15327 (goto-char pos)
15328 (when (org-mode-p)
15329 (org-show-context 'agenda)
15330 (save-excursion
15331 (and (outline-next-heading)
15332 (org-flag-heading nil)))) ; show the next heading
15333 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
15335 (defun org-agenda-kill ()
15336 "Kill the entry or subtree belonging to the current agenda entry."
15337 (interactive)
15338 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15339 (let* ((marker (or (get-text-property (point) 'org-marker)
15340 (org-agenda-error)))
15341 (buffer (marker-buffer marker))
15342 (pos (marker-position marker))
15343 dbeg dend (n 0) conf)
15344 (org-with-remote-undo buffer
15345 (with-current-buffer buffer
15346 (save-excursion
15347 (goto-char pos)
15348 (if (org-mode-p)
15349 (setq dbeg (progn (org-back-to-heading t) (point))
15350 dend (org-end-of-subtree t))
15351 (setq dbeg (point-at-bol)
15352 dend (min (point-max) (1+ (point-at-eol)))))
15353 (goto-char dbeg)
15354 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
15355 (setq conf (or (eq t org-agenda-confirm-kill)
15356 (and (numberp org-agenda-confirm-kill)
15357 (> n org-agenda-confirm-kill))))
15358 (and conf
15359 (not (y-or-n-p
15360 (format "Delete entry with %d lines in buffer \"%s\"? "
15361 n (buffer-name buffer))))
15362 (error "Abort"))
15363 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
15364 (with-current-buffer buffer (delete-region dbeg dend))
15365 (message "Agenda item and source killed"))))
15367 (defun org-agenda-archive ()
15368 "Kill the entry or subtree belonging to the current agenda entry."
15369 (interactive)
15370 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15371 (let* ((marker (or (get-text-property (point) 'org-marker)
15372 (org-agenda-error)))
15373 (buffer (marker-buffer marker))
15374 (pos (marker-position marker)))
15375 (org-with-remote-undo buffer
15376 (with-current-buffer buffer
15377 (if (org-mode-p)
15378 (save-excursion
15379 (goto-char pos)
15380 (org-remove-subtree-entries-from-agenda)
15381 (org-back-to-heading t)
15382 (org-archive-subtree))
15383 (error "Archiving works only in Org-mode files"))))))
15385 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
15386 "Remove all lines in the agenda that correspond to a given subtree.
15387 The subtree is the one in buffer BUF, starting at BEG and ending at END.
15388 If this information is not given, the function uses the tree at point."
15389 (let ((buf (or buf (current-buffer))) m p)
15390 (save-excursion
15391 (unless (and beg end)
15392 (org-back-to-heading t)
15393 (setq beg (point))
15394 (org-end-of-subtree t)
15395 (setq end (point)))
15396 (set-buffer (get-buffer org-agenda-buffer-name))
15397 (save-excursion
15398 (goto-char (point-max))
15399 (beginning-of-line 1)
15400 (while (not (bobp))
15401 (when (and (setq m (get-text-property (point) 'org-marker))
15402 (equal buf (marker-buffer m))
15403 (setq p (marker-position m))
15404 (>= p beg)
15405 (<= p end))
15406 (let (buffer-read-only)
15407 (delete-region (point-at-bol) (1+ (point-at-eol)))))
15408 (beginning-of-line 0))))))
15410 (defun org-agenda-open-link ()
15411 "Follow the link in the current line, if any."
15412 (interactive)
15413 (let ((eol (point-at-eol)))
15414 (save-excursion
15415 (if (or (re-search-forward org-bracket-link-regexp eol t)
15416 (re-search-forward org-angle-link-re eol t)
15417 (re-search-forward org-plain-link-re eol t))
15418 (call-interactively 'org-open-at-point)
15419 (error "No link in current line")))))
15421 (defun org-agenda-switch-to (&optional delete-other-windows)
15422 "Go to the Org-mode file which contains the item at point."
15423 (interactive)
15424 (let* ((marker (or (get-text-property (point) 'org-marker)
15425 (org-agenda-error)))
15426 (buffer (marker-buffer marker))
15427 (pos (marker-position marker)))
15428 (switch-to-buffer buffer)
15429 (and delete-other-windows (delete-other-windows))
15430 (widen)
15431 (goto-char pos)
15432 (when (org-mode-p)
15433 (org-show-context 'agenda)
15434 (save-excursion
15435 (and (outline-next-heading)
15436 (org-flag-heading nil)))))) ; show the next heading
15438 (defun org-agenda-goto-mouse (ev)
15439 "Go to the Org-mode file which contains the item at the mouse click."
15440 (interactive "e")
15441 (mouse-set-point ev)
15442 (org-agenda-goto))
15444 (defun org-agenda-show ()
15445 "Display the Org-mode file which contains the item at point."
15446 (interactive)
15447 (let ((win (selected-window)))
15448 (org-agenda-goto t)
15449 (select-window win)))
15451 (defun org-agenda-recenter (arg)
15452 "Display the Org-mode file which contains the item at point and recenter."
15453 (interactive "P")
15454 (let ((win (selected-window)))
15455 (org-agenda-goto t)
15456 (recenter arg)
15457 (select-window win)))
15459 (defun org-agenda-show-mouse (ev)
15460 "Display the Org-mode file which contains the item at the mouse click."
15461 (interactive "e")
15462 (mouse-set-point ev)
15463 (org-agenda-show))
15465 (defun org-agenda-check-no-diary ()
15466 "Check if the entry is a diary link and abort if yes."
15467 (if (get-text-property (point) 'org-agenda-diary-link)
15468 (org-agenda-error)))
15470 (defun org-agenda-error ()
15471 (error "Command not allowed in this line"))
15473 (defun org-agenda-tree-to-indirect-buffer ()
15474 "Show the subtree corresponding to the current entry in an indirect buffer.
15475 This calls the command `org-tree-to-indirect-buffer' from the original
15476 Org-mode buffer.
15477 With numerical prefix arg ARG, go up to this level and then take that tree.
15478 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
15479 dedicated frame)."
15480 (interactive)
15481 (org-agenda-check-no-diary)
15482 (let* ((marker (or (get-text-property (point) 'org-marker)
15483 (org-agenda-error)))
15484 (buffer (marker-buffer marker))
15485 (pos (marker-position marker)))
15486 (with-current-buffer buffer
15487 (save-excursion
15488 (goto-char pos)
15489 (call-interactively 'org-tree-to-indirect-buffer)))))
15491 (defvar org-last-heading-marker (make-marker)
15492 "Marker pointing to the headline that last changed its TODO state
15493 by a remote command from the agenda.")
15495 (defun org-agenda-todo (&optional arg)
15496 "Cycle TODO state of line at point, also in Org-mode file.
15497 This changes the line at point, all other lines in the agenda referring to
15498 the same tree node, and the headline of the tree node in the Org-mode file."
15499 (interactive "P")
15500 (org-agenda-check-no-diary)
15501 (let* ((col (current-column))
15502 (marker (or (get-text-property (point) 'org-marker)
15503 (org-agenda-error)))
15504 (buffer (marker-buffer marker))
15505 (pos (marker-position marker))
15506 (hdmarker (get-text-property (point) 'org-hd-marker))
15507 (buffer-read-only nil)
15508 newhead)
15509 (org-with-remote-undo buffer
15510 (with-current-buffer buffer
15511 (widen)
15512 (goto-char pos)
15513 (org-show-context 'agenda)
15514 (save-excursion
15515 (and (outline-next-heading)
15516 (org-flag-heading nil))) ; show the next heading
15517 (org-todo arg)
15518 (and (bolp) (forward-char 1))
15519 (setq newhead (org-get-heading))
15520 (save-excursion
15521 (org-back-to-heading)
15522 (move-marker org-last-heading-marker (point))))
15523 (beginning-of-line 1)
15524 (save-excursion
15525 (org-agenda-change-all-lines newhead hdmarker 'fixface))
15526 (move-to-column col))))
15528 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
15529 "Change all lines in the agenda buffer which match HDMARKER.
15530 The new content of the line will be NEWHEAD (as modified by
15531 `org-format-agenda-item'). HDMARKER is checked with
15532 `equal' against all `org-hd-marker' text properties in the file.
15533 If FIXFACE is non-nil, the face of each item is modified acording to
15534 the new TODO state."
15535 (let* ((buffer-read-only nil)
15536 props m pl undone-face done-face finish new dotime cat tags)
15537 (save-excursion
15538 (goto-char (point-max))
15539 (beginning-of-line 1)
15540 (while (not finish)
15541 (setq finish (bobp))
15542 (when (and (setq m (get-text-property (point) 'org-hd-marker))
15543 (equal m hdmarker))
15544 (setq props (text-properties-at (point))
15545 dotime (get-text-property (point) 'dotime)
15546 cat (get-text-property (point) 'org-category)
15547 tags (get-text-property (point) 'tags)
15548 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
15549 pl (get-text-property (point) 'prefix-length)
15550 undone-face (get-text-property (point) 'undone-face)
15551 done-face (get-text-property (point) 'done-face))
15552 (move-to-column pl)
15553 (cond
15554 ((equal new "")
15555 (beginning-of-line 1)
15556 (and (looking-at ".*\n?") (replace-match "")))
15557 ((looking-at ".*")
15558 (replace-match new t t)
15559 (beginning-of-line 1)
15560 (add-text-properties (point-at-bol) (point-at-eol) props)
15561 (when fixface
15562 (add-text-properties
15563 (point-at-bol) (point-at-eol)
15564 (list 'face
15565 (if org-last-todo-state-is-todo
15566 undone-face done-face))))
15567 (org-agenda-highlight-todo 'line)
15568 (beginning-of-line 1))
15569 (t (error "Line update did not work"))))
15570 (beginning-of-line 0)))
15571 (org-finalize-agenda)))
15573 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
15574 ;; See the code in set-tags for the way to do this.
15575 (defun org-agenda-align-tags (&optional line)
15576 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
15577 (let ((buffer-read-only))
15578 (save-excursion
15579 (goto-char (if line (point-at-bol) (point-min)))
15580 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
15581 (if line (point-at-eol) nil) t)
15582 (delete-region (match-beginning 1) (match-end 1))
15583 (goto-char (match-beginning 1))
15584 (insert (org-add-props
15585 (make-string (max 1 (- org-agenda-align-tags-to-column
15586 (current-column))) ?\ )
15587 (text-properties-at (point))))))))
15589 (defun org-agenda-priority-up ()
15590 "Increase the priority of line at point, also in Org-mode file."
15591 (interactive)
15592 (org-agenda-priority 'up))
15594 (defun org-agenda-priority-down ()
15595 "Decrease the priority of line at point, also in Org-mode file."
15596 (interactive)
15597 (org-agenda-priority 'down))
15599 (defun org-agenda-priority (&optional force-direction)
15600 "Set the priority of line at point, also in Org-mode file.
15601 This changes the line at point, all other lines in the agenda referring to
15602 the same tree node, and the headline of the tree node in the Org-mode file."
15603 (interactive)
15604 (org-agenda-check-no-diary)
15605 (let* ((marker (or (get-text-property (point) 'org-marker)
15606 (org-agenda-error)))
15607 (buffer (marker-buffer marker))
15608 (pos (marker-position marker))
15609 (hdmarker (get-text-property (point) 'org-hd-marker))
15610 (buffer-read-only nil)
15611 newhead)
15612 (org-with-remote-undo buffer
15613 (with-current-buffer buffer
15614 (widen)
15615 (goto-char pos)
15616 (org-show-context 'agenda)
15617 (save-excursion
15618 (and (outline-next-heading)
15619 (org-flag-heading nil))) ; show the next heading
15620 (funcall 'org-priority force-direction)
15621 (end-of-line 1)
15622 (setq newhead (org-get-heading)))
15623 (org-agenda-change-all-lines newhead hdmarker)
15624 (beginning-of-line 1))))
15626 (defun org-get-tags-at (&optional pos)
15627 "Get a list of all headline tags applicable at POS.
15628 POS defaults to point. If tags are inherited, the list contains
15629 the targets in the same sequence as the headlines appear, i.e.
15630 the tags of the current headline come last."
15631 (interactive)
15632 (let (tags)
15633 (save-excursion
15634 (save-restriction
15635 (widen)
15636 (goto-char (or pos (point)))
15637 (save-match-data
15638 (org-back-to-heading t)
15639 (condition-case nil
15640 (while t
15641 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
15642 (setq tags (append (org-split-string
15643 (org-match-string-no-properties 1) ":")
15644 tags)))
15645 (or org-use-tag-inheritance (error ""))
15646 (org-up-heading-all 1))
15647 (error nil))))
15648 tags)))
15650 ;; FIXME: should fix the tags property of the agenda line.
15651 (defun org-agenda-set-tags ()
15652 "Set tags for the current headline."
15653 (interactive)
15654 (org-agenda-check-no-diary)
15655 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
15656 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
15657 (org-agenda-error)))
15658 (buffer (marker-buffer hdmarker))
15659 (pos (marker-position hdmarker))
15660 (buffer-read-only nil)
15661 newhead)
15662 (org-with-remote-undo buffer
15663 (with-current-buffer buffer
15664 (widen)
15665 (goto-char pos)
15666 (org-show-context 'agenda)
15667 (save-excursion
15668 (and (outline-next-heading)
15669 (org-flag-heading nil))) ; show the next heading
15670 (call-interactively 'org-set-tags)
15671 (end-of-line 1)
15672 (setq newhead (org-get-heading)))
15673 (org-agenda-change-all-lines newhead hdmarker)
15674 (beginning-of-line 1))))
15676 (defun org-agenda-toggle-archive-tag ()
15677 "Toggle the archive tag for the current entry."
15678 (interactive)
15679 (org-agenda-check-no-diary)
15680 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
15681 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
15682 (org-agenda-error)))
15683 (buffer (marker-buffer hdmarker))
15684 (pos (marker-position hdmarker))
15685 (buffer-read-only nil)
15686 newhead)
15687 (org-with-remote-undo buffer
15688 (with-current-buffer buffer
15689 (widen)
15690 (goto-char pos)
15691 (org-show-context 'agenda)
15692 (save-excursion
15693 (and (outline-next-heading)
15694 (org-flag-heading nil))) ; show the next heading
15695 (call-interactively 'org-toggle-archive-tag)
15696 (end-of-line 1)
15697 (setq newhead (org-get-heading)))
15698 (org-agenda-change-all-lines newhead hdmarker)
15699 (beginning-of-line 1))))
15701 (defun org-agenda-date-later (arg &optional what)
15702 "Change the date of this item to one day later."
15703 (interactive "p")
15704 (org-agenda-check-type t 'agenda 'timeline)
15705 (org-agenda-check-no-diary)
15706 (let* ((marker (or (get-text-property (point) 'org-marker)
15707 (org-agenda-error)))
15708 (buffer (marker-buffer marker))
15709 (pos (marker-position marker)))
15710 (org-with-remote-undo buffer
15711 (with-current-buffer buffer
15712 (widen)
15713 (goto-char pos)
15714 (if (not (org-at-timestamp-p))
15715 (error "Cannot find time stamp"))
15716 (org-timestamp-change arg (or what 'day)))
15717 (org-agenda-show-new-time marker org-last-changed-timestamp))
15718 (message "Time stamp changed to %s" org-last-changed-timestamp)))
15720 (defun org-agenda-date-earlier (arg &optional what)
15721 "Change the date of this item to one day earlier."
15722 (interactive "p")
15723 (org-agenda-date-later (- arg) what))
15725 (defun org-agenda-show-new-time (marker stamp)
15726 "Show new date stamp via text properties."
15727 ;; We use text properties to make this undoable
15728 (let ((buffer-read-only nil))
15729 (setq stamp (concat " => " stamp))
15730 (save-excursion
15731 (goto-char (point-max))
15732 (while (not (bobp))
15733 (when (equal marker (get-text-property (point) 'org-marker))
15734 (move-to-column (- (window-width) (length stamp)) t)
15735 (if (featurep 'xemacs)
15736 ;; Use `duplicable' property to trigger undo recording
15737 (let ((ex (make-extent nil nil))
15738 (gl (make-glyph stamp)))
15739 (set-glyph-face gl 'secondary-selection)
15740 (set-extent-properties
15741 ex (list 'invisible t 'end-glyph gl 'duplicable t))
15742 (insert-extent ex (1- (point)) (point-at-eol)))
15743 (add-text-properties
15744 (1- (point)) (point-at-eol)
15745 (list 'display (org-add-props stamp nil
15746 'face 'secondary-selection))))
15747 (beginning-of-line 1))
15748 (beginning-of-line 0)))))
15750 (defun org-agenda-date-prompt (arg)
15751 "Change the date of this item. Date is prompted for, with default today.
15752 The prefix ARG is passed to the `org-time-stamp' command and can therefore
15753 be used to request time specification in the time stamp."
15754 (interactive "P")
15755 (org-agenda-check-type t 'agenda 'timeline)
15756 (org-agenda-check-no-diary)
15757 (let* ((marker (or (get-text-property (point) 'org-marker)
15758 (org-agenda-error)))
15759 (buffer (marker-buffer marker))
15760 (pos (marker-position marker)))
15761 (org-with-remote-undo buffer
15762 (with-current-buffer buffer
15763 (widen)
15764 (goto-char pos)
15765 (if (not (org-at-timestamp-p))
15766 (error "Cannot find time stamp"))
15767 (org-time-stamp arg)
15768 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
15770 (defun org-agenda-schedule (arg)
15771 "Schedule the item at point."
15772 (interactive "P")
15773 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
15774 (org-agenda-check-no-diary)
15775 (let* ((marker (or (get-text-property (point) 'org-marker)
15776 (org-agenda-error)))
15777 (buffer (marker-buffer marker))
15778 (pos (marker-position marker))
15779 (org-insert-labeled-timestamps-at-point nil)
15781 (org-with-remote-undo buffer
15782 (with-current-buffer buffer
15783 (widen)
15784 (goto-char pos)
15785 (setq ts (org-schedule))
15786 (message "Item scheduled for %s" ts)))))
15788 (defun org-agenda-deadline (arg)
15789 "Schedule the item at point."
15790 (interactive "P")
15791 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
15792 (org-agenda-check-no-diary)
15793 (let* ((marker (or (get-text-property (point) 'org-marker)
15794 (org-agenda-error)))
15795 (buffer (marker-buffer marker))
15796 (pos (marker-position marker))
15797 (org-insert-labeled-timestamps-at-point nil)
15799 (org-with-remote-undo buffer
15800 (with-current-buffer buffer
15801 (widen)
15802 (goto-char pos)
15803 (setq ts (org-deadline))
15804 (message "Deadline for this item set to %s" ts)))))
15806 (defun org-get-heading ()
15807 "Return the heading of the current entry, without the stars."
15808 (save-excursion
15809 (org-back-to-heading t)
15810 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
15812 (defun org-agenda-clock-in (&optional arg)
15813 "Start the clock on the currently selected item."
15814 (interactive "P")
15815 (org-agenda-check-no-diary)
15816 (let* ((marker (or (get-text-property (point) 'org-marker)
15817 (org-agenda-error)))
15818 (pos (marker-position marker)))
15819 (org-with-remote-undo (marker-buffer marker)
15820 (with-current-buffer (marker-buffer marker)
15821 (widen)
15822 (goto-char pos)
15823 (org-clock-in)))))
15825 (defun org-agenda-clock-out (&optional arg)
15826 "Stop the currently running clock."
15827 (interactive "P")
15828 (unless (marker-buffer org-clock-marker)
15829 (error "No running clock"))
15830 (org-with-remote-undo (marker-buffer org-clock-marker)
15831 (org-clock-out)))
15833 (defun org-agenda-clock-cancel (&optional arg)
15834 "Cancel the currently running clock."
15835 (interactive "P")
15836 (unless (marker-buffer org-clock-marker)
15837 (error "No running clock"))
15838 (org-with-remote-undo (marker-buffer org-clock-marker)
15839 (org-clock-cancel)))
15841 (defun org-agenda-diary-entry ()
15842 "Make a diary entry, like the `i' command from the calendar.
15843 All the standard commands work: block, weekly etc."
15844 (interactive)
15845 (org-agenda-check-type t 'agenda 'timeline)
15846 (require 'diary-lib)
15847 (let* ((char (progn
15848 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
15849 (read-char-exclusive)))
15850 (cmd (cdr (assoc char
15851 '((?d . insert-diary-entry)
15852 (?w . insert-weekly-diary-entry)
15853 (?m . insert-monthly-diary-entry)
15854 (?y . insert-yearly-diary-entry)
15855 (?a . insert-anniversary-diary-entry)
15856 (?b . insert-block-diary-entry)
15857 (?c . insert-cyclic-diary-entry)))))
15858 (oldf (symbol-function 'calendar-cursor-to-date))
15859 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
15860 (point (point))
15861 (mark (or (mark t) (point))))
15862 (unless cmd
15863 (error "No command associated with <%c>" char))
15864 (unless (and (get-text-property point 'day)
15865 (or (not (equal ?b char))
15866 (get-text-property mark 'day)))
15867 (error "Don't know which date to use for diary entry"))
15868 ;; We implement this by hacking the `calendar-cursor-to-date' function
15869 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
15870 (let ((calendar-mark-ring
15871 (list (calendar-gregorian-from-absolute
15872 (or (get-text-property mark 'day)
15873 (get-text-property point 'day))))))
15874 (unwind-protect
15875 (progn
15876 (fset 'calendar-cursor-to-date
15877 (lambda (&optional error)
15878 (calendar-gregorian-from-absolute
15879 (get-text-property point 'day))))
15880 (call-interactively cmd))
15881 (fset 'calendar-cursor-to-date oldf)))))
15884 (defun org-agenda-execute-calendar-command (cmd)
15885 "Execute a calendar command from the agenda, with the date associated to
15886 the cursor position."
15887 (org-agenda-check-type t 'agenda 'timeline)
15888 (require 'diary-lib)
15889 (unless (get-text-property (point) 'day)
15890 (error "Don't know which date to use for calendar command"))
15891 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
15892 (point (point))
15893 (date (calendar-gregorian-from-absolute
15894 (get-text-property point 'day)))
15895 ;; the following 3 vars are needed in the calendar
15896 (displayed-day (extract-calendar-day date))
15897 (displayed-month (extract-calendar-month date))
15898 (displayed-year (extract-calendar-year date)))
15899 (unwind-protect
15900 (progn
15901 (fset 'calendar-cursor-to-date
15902 (lambda (&optional error)
15903 (calendar-gregorian-from-absolute
15904 (get-text-property point 'day))))
15905 (call-interactively cmd))
15906 (fset 'calendar-cursor-to-date oldf))))
15908 (defun org-agenda-phases-of-moon ()
15909 "Display the phases of the moon for the 3 months around the cursor date."
15910 (interactive)
15911 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
15913 (defun org-agenda-holidays ()
15914 "Display the holidays for the 3 months around the cursor date."
15915 (interactive)
15916 (org-agenda-execute-calendar-command 'list-calendar-holidays))
15918 (defun org-agenda-sunrise-sunset (arg)
15919 "Display sunrise and sunset for the cursor date.
15920 Latitude and longitude can be specified with the variables
15921 `calendar-latitude' and `calendar-longitude'. When called with prefix
15922 argument, latitude and longitude will be prompted for."
15923 (interactive "P")
15924 (let ((calendar-longitude (if arg nil calendar-longitude))
15925 (calendar-latitude (if arg nil calendar-latitude))
15926 (calendar-location-name
15927 (if arg "the given coordinates" calendar-location-name)))
15928 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
15930 (defun org-agenda-goto-calendar ()
15931 "Open the Emacs calendar with the date at the cursor."
15932 (interactive)
15933 (org-agenda-check-type t 'agenda 'timeline)
15934 (let* ((day (or (get-text-property (point) 'day)
15935 (error "Don't know which date to open in calendar")))
15936 (date (calendar-gregorian-from-absolute day))
15937 (calendar-move-hook nil)
15938 (view-calendar-holidays-initially nil)
15939 (view-diary-entries-initially nil))
15940 (calendar)
15941 (calendar-goto-date date)))
15943 (defun org-calendar-goto-agenda ()
15944 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
15945 This is a command that has to be installed in `calendar-mode-map'."
15946 (interactive)
15947 (org-agenda-list nil (calendar-absolute-from-gregorian
15948 (calendar-cursor-to-date))
15949 nil))
15951 (defun org-agenda-convert-date ()
15952 (interactive)
15953 (org-agenda-check-type t 'agenda 'timeline)
15954 (let ((day (get-text-property (point) 'day))
15955 date s)
15956 (unless day
15957 (error "Don't know which date to convert"))
15958 (setq date (calendar-gregorian-from-absolute day))
15959 (setq s (concat
15960 "Gregorian: " (calendar-date-string date) "\n"
15961 "ISO: " (calendar-iso-date-string date) "\n"
15962 "Day of Yr: " (calendar-day-of-year-string date) "\n"
15963 "Julian: " (calendar-julian-date-string date) "\n"
15964 "Astron. JD: " (calendar-astro-date-string date)
15965 " (Julian date number at noon UTC)\n"
15966 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
15967 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
15968 "French: " (calendar-french-date-string date) "\n"
15969 "Mayan: " (calendar-mayan-date-string date) "\n"
15970 "Coptic: " (calendar-coptic-date-string date) "\n"
15971 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
15972 "Persian: " (calendar-persian-date-string date) "\n"
15973 "Chinese: " (calendar-chinese-date-string date) "\n"))
15974 (with-output-to-temp-buffer "*Dates*"
15975 (princ s))
15976 (if (fboundp 'fit-window-to-buffer)
15977 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
15980 ;;;; Embedded LaTeX
15982 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15983 "Keymap for the minor `org-cdlatex-mode'.")
15985 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15986 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15987 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15988 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15989 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15991 (defvar org-cdlatex-texmathp-advice-is-done nil
15992 "Flag remembering if we have applied the advice to texmathp already.")
15994 (define-minor-mode org-cdlatex-mode
15995 "Toggle the minor `org-cdlatex-mode'.
15996 This mode supports entering LaTeX environment and math in LaTeX fragments
15997 in Org-mode.
15998 \\{org-cdlatex-mode-map}"
15999 nil " OCDL" nil
16000 (when org-cdlatex-mode (require 'cdlatex))
16001 (unless org-cdlatex-texmathp-advice-is-done
16002 (setq org-cdlatex-texmathp-advice-is-done t)
16003 (defadvice texmathp (around org-math-always-on activate)
16004 "Always return t in org-mode buffers.
16005 This is because we want to insert math symbols without dollars even outside
16006 the LaTeX math segments. If Orgmode thinks that point is actually inside
16007 en embedded LaTeX fragement, let texmathp do its job.
16008 \\[org-cdlatex-mode-map]"
16009 (interactive)
16010 (let (p)
16011 (cond
16012 ((not (org-mode-p)) ad-do-it)
16013 ((eq this-command 'cdlatex-math-symbol)
16014 (setq ad-return-value t
16015 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16017 (let ((p (org-inside-LaTeX-fragment-p)))
16018 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16019 (setq ad-return-value t
16020 texmathp-why '("Org-mode embedded math" . 0))
16021 (if p ad-do-it)))))))))
16023 (defun turn-on-org-cdlatex ()
16024 "Unconditionally turn on `org-cdlatex-mode'."
16025 (org-cdlatex-mode 1))
16027 (defun org-inside-LaTeX-fragment-p ()
16028 "Test if point is inside a LaTeX fragment.
16029 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16030 sequence appearing also before point.
16031 Even though the matchers for math are configurable, this function assumes
16032 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16033 delimiters are skipped when they have been removed by customization.
16034 The return value is nil, or a cons cell with the delimiter and
16035 and the position of this delimiter.
16037 This function does a reasonably good job, but can locally be fooled by
16038 for example currency specifications. For example it will assume being in
16039 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16040 fragments that are properly closed, but during editing, we have to live
16041 with the uncertainty caused by missing closing delimiters. This function
16042 looks only before point, not after."
16043 (catch 'exit
16044 (let ((pos (point))
16045 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16046 (lim (progn
16047 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16048 (point)))
16049 dd-on str (start 0) m re)
16050 (goto-char pos)
16051 (when dodollar
16052 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16053 re (nth 1 (assoc "$" org-latex-regexps)))
16054 (while (string-match re str start)
16055 (cond
16056 ((= (match-end 0) (length str))
16057 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
16058 ((= (match-end 0) (- (length str) 5))
16059 (throw 'exit nil))
16060 (t (setq start (match-end 0))))))
16061 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16062 (goto-char pos)
16063 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16064 (and (match-beginning 2) (throw 'exit nil))
16065 ;; count $$
16066 (while (re-search-backward "\\$\\$" lim t)
16067 (setq dd-on (not dd-on)))
16068 (goto-char pos)
16069 (if dd-on (cons "$$" m))))))
16072 (defun org-try-cdlatex-tab ()
16073 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16074 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16075 - inside a LaTeX fragment, or
16076 - after the first word in a line, where an abbreviation expansion could
16077 insert a LaTeX environment."
16078 (when org-cdlatex-mode
16079 (cond
16080 ((save-excursion
16081 (skip-chars-backward "a-zA-Z0-9*")
16082 (skip-chars-backward " \t")
16083 (bolp))
16084 (cdlatex-tab) t)
16085 ((org-inside-LaTeX-fragment-p)
16086 (cdlatex-tab) t)
16087 (t nil))))
16089 (defun org-cdlatex-underscore-caret (&optional arg)
16090 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16091 Revert to the normal definition outside of these fragments."
16092 (interactive "P")
16093 (if (org-inside-LaTeX-fragment-p)
16094 (call-interactively 'cdlatex-sub-superscript)
16095 (let (org-cdlatex-mode)
16096 (call-interactively (key-binding (vector last-input-event))))))
16098 (defun org-cdlatex-math-modify (&optional arg)
16099 "Execute `cdlatex-math-modify' in LaTeX fragments.
16100 Revert to the normal definition outside of these fragments."
16101 (interactive "P")
16102 (if (org-inside-LaTeX-fragment-p)
16103 (call-interactively 'cdlatex-math-modify)
16104 (let (org-cdlatex-mode)
16105 (call-interactively (key-binding (vector last-input-event))))))
16107 (defvar org-latex-fragment-image-overlays nil
16108 "List of overlays carrying the images of latex fragments.")
16109 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16111 (defun org-remove-latex-fragment-image-overlays ()
16112 "Remove all overlays with LaTeX fragment images in current buffer."
16113 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
16114 (setq org-latex-fragment-image-overlays nil))
16116 (defun org-preview-latex-fragment (&optional subtree)
16117 "Preview the LaTeX fragment at point, or all locally or globally.
16118 If the cursor is in a LaTeX fragment, create the image and overlay
16119 it over the source code. If there is no fragment at point, display
16120 all fragments in the current text, from one headline to the next. With
16121 prefix SUBTREE, display all fragments in the current subtree. With a
16122 double prefix `C-u C-u', or when the cursor is before the first headline,
16123 display all fragments in the buffer.
16124 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16125 (interactive "P")
16126 (org-remove-latex-fragment-image-overlays)
16127 (save-excursion
16128 (save-restriction
16129 (let (beg end at msg)
16130 (cond
16131 ((or (equal subtree '(16))
16132 (not (save-excursion
16133 (re-search-backward (concat "^" outline-regexp) nil t))))
16134 (setq beg (point-min) end (point-max)
16135 msg "Creating images for buffer...%s"))
16136 ((equal subtree '(4))
16137 (org-back-to-heading)
16138 (setq beg (point) end (org-end-of-subtree t)
16139 msg "Creating images for subtree...%s"))
16141 (if (setq at (org-inside-LaTeX-fragment-p))
16142 (goto-char (max (point-min) (- (cdr at) 2)))
16143 (org-back-to-heading))
16144 (setq beg (point) end (progn (outline-next-heading) (point))
16145 msg (if at "Creating image...%s"
16146 "Creating images for entry...%s"))))
16147 (message msg "")
16148 (narrow-to-region beg end)
16149 (org-format-latex
16150 (concat "ltxpng/" (file-name-sans-extension
16151 (file-name-nondirectory
16152 buffer-file-name)))
16153 default-directory 'overlays msg at)
16154 (message msg "done. Use `C-c C-c' to remove images.")))))
16156 (defvar org-latex-regexps
16157 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16158 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16159 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16160 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
16161 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16162 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
16163 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
16164 "Regular expressions for matching embedded LaTeX.")
16166 (defun org-format-latex (prefix &optional dir overlays msg at)
16167 "Replace LaTeX fragments with links to an image, and produce images."
16168 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16169 (let* ((prefixnodir (file-name-nondirectory prefix))
16170 (absprefix (expand-file-name prefix dir))
16171 (todir (file-name-directory absprefix))
16172 (opt org-format-latex-options)
16173 (matchers (plist-get opt :matchers))
16174 (re-list org-latex-regexps)
16175 (cnt 0) txt link beg end re e checkdir
16176 m n block linkfile movefile ov)
16177 ;; Check if there are old images files with this prefix, and remove them
16178 (when (file-directory-p todir)
16179 (mapc 'delete-file
16180 (directory-files
16181 todir 'full
16182 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
16183 ;; Check the different regular expressions
16184 (while (setq e (pop re-list))
16185 (setq m (car e) re (nth 1 e) n (nth 2 e)
16186 block (if (nth 3 e) "\n\n" ""))
16187 (when (member m matchers)
16188 (goto-char (point-min))
16189 (while (re-search-forward re nil t)
16190 (when (or (not at) (equal (cdr at) (match-beginning n)))
16191 (setq txt (match-string n)
16192 beg (match-beginning n) end (match-end n)
16193 cnt (1+ cnt)
16194 linkfile (format "%s_%04d.png" prefix cnt)
16195 movefile (format "%s_%04d.png" absprefix cnt)
16196 link (concat block "[[file:" linkfile "]]" block))
16197 (if msg (message msg cnt))
16198 (goto-char beg)
16199 (unless checkdir ; make sure the directory exists
16200 (setq checkdir t)
16201 (or (file-directory-p todir) (make-directory todir)))
16202 (org-create-formula-image
16203 txt movefile opt)
16204 (if overlays
16205 (progn
16206 (setq ov (org-make-overlay beg end))
16207 (if (featurep 'xemacs)
16208 (progn
16209 (org-overlay-put ov 'invisible t)
16210 (org-overlay-put
16211 ov 'end-glyph
16212 (make-glyph (vector 'png :file movefile))))
16213 (org-overlay-put
16214 ov 'display
16215 (list 'image :type 'png :file movefile :ascent 'center)))
16216 (push ov org-latex-fragment-image-overlays)
16217 (goto-char end))
16218 (delete-region beg end)
16219 (insert link))))))))
16221 ;; This function borrows from Ganesh Swami's latex2png.el
16222 (defun org-create-formula-image (string tofile options)
16223 (let* ((tmpdir (if (featurep 'xemacs)
16224 (temp-directory)
16225 temporary-file-directory))
16226 (texfilebase (make-temp-name
16227 (expand-file-name "orgtex" tmpdir)))
16229 ;(texfilebase (make-temp-file "orgtex"))
16230 ; (dummy (delete-file texfilebase))
16231 (texfile (concat texfilebase ".tex"))
16232 (dvifile (concat texfilebase ".dvi"))
16233 (pngfile (concat texfilebase ".png"))
16234 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
16235 (fg (or (plist-get options :foreground) "Black"))
16236 (bg (or (plist-get options :background) "Transparent")))
16237 (with-temp-file texfile
16238 (insert "\\documentclass{article}
16239 \\usepackage{fullpage}
16240 \\usepackage{amssymb}
16241 \\usepackage[usenames]{color}
16242 \\usepackage{amsmath}
16243 \\usepackage{latexsym}
16244 \\usepackage[mathscr]{eucal}
16245 \\pagestyle{empty}
16246 \\begin{document}\n" string "\n\\end{document}\n"))
16247 (let ((dir default-directory))
16248 (condition-case nil
16249 (progn
16250 (cd tmpdir)
16251 (call-process "latex" nil nil nil texfile))
16252 (error nil))
16253 (cd dir))
16254 (if (not (file-exists-p dvifile))
16255 (progn (message "Failed to create dvi file from %s" texfile) nil)
16256 (call-process "dvipng" nil nil nil
16257 "-E" "-fg" fg "-bg" bg
16258 "-x" scale "-y" scale "-T" "tight"
16259 "-o" pngfile
16260 dvifile)
16261 (if (not (file-exists-p pngfile))
16262 (progn (message "Failed to create png file from %s" texfile) nil)
16263 ;; Use the requested file name and clean up
16264 (copy-file pngfile tofile 'replace)
16265 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16266 (delete-file (concat texfilebase e)))
16267 pngfile))))
16269 ;;;; Exporting
16271 ;;; Variables, constants, and parameter plists
16273 (defconst org-level-max 20)
16275 (defvar org-export-html-preamble nil
16276 "Preamble, to be inserted just after <body>. Set by publishing functions.")
16277 (defvar org-export-html-postamble nil
16278 "Preamble, to be inserted just before </body>. Set by publishing functions.")
16279 (defvar org-export-html-auto-preamble t
16280 "Should default preamble be inserted? Set by publishing functions.")
16281 (defvar org-export-html-auto-postamble t
16282 "Should default postamble be inserted? Set by publishing functions.")
16283 (defvar org-current-export-file nil) ; dynamically scoped parameter
16284 (defvar org-current-export-dir nil) ; dynamically scoped parameter
16287 (defconst org-export-plist-vars
16288 '((:language . org-export-default-language)
16289 (:customtime . org-display-custom-times)
16290 (:headline-levels . org-export-headline-levels)
16291 (:section-numbers . org-export-with-section-numbers)
16292 (:table-of-contents . org-export-with-toc)
16293 (:archived-trees . org-export-with-archived-trees)
16294 (:emphasize . org-export-with-emphasize)
16295 (:sub-superscript . org-export-with-sub-superscripts)
16296 (:TeX-macros . org-export-with-TeX-macros)
16297 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
16298 (:fixed-width . org-export-with-fixed-width)
16299 (:timestamps . org-export-with-timestamps)
16300 (:tables . org-export-with-tables)
16301 (:table-auto-headline . org-export-highlight-first-table-line)
16302 (:style . org-export-html-style)
16303 (:convert-org-links . org-export-html-link-org-files-as-html)
16304 (:inline-images . org-export-html-inline-images)
16305 (:expand-quoted-html . org-export-html-expand)
16306 (:timestamp . org-export-html-with-timestamp)
16307 (:publishing-directory . org-export-publishing-directory)
16308 (:preamble . org-export-html-preamble)
16309 (:postamble . org-export-html-postamble)
16310 (:auto-preamble . org-export-html-auto-preamble)
16311 (:auto-postamble . org-export-html-auto-postamble)
16312 (:author . user-full-name)
16313 (:email . user-mail-address)))
16315 (defun org-default-export-plist ()
16316 "Return the property list with default settings for the export variables."
16317 (let ((l org-export-plist-vars) rtn e)
16318 (while (setq e (pop l))
16319 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
16320 rtn))
16322 (defun org-infile-export-plist ()
16323 "Return the property list with file-local settings for export."
16324 (save-excursion
16325 (goto-char 0)
16326 (let ((re (org-make-options-regexp
16327 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
16328 p key val text options)
16329 (while (re-search-forward re nil t)
16330 (setq key (org-match-string-no-properties 1)
16331 val (org-match-string-no-properties 2))
16332 (cond
16333 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
16334 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
16335 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
16336 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
16337 ((string-equal key "TEXT")
16338 (setq text (if text (concat text "\n" val) val)))
16339 ((string-equal key "OPTIONS") (setq options val))))
16340 (setq p (plist-put p :text text))
16341 (when options
16342 (let ((op '(("H" . :headline-levels)
16343 ("num" . :section-numbers)
16344 ("toc" . :table-of-contents)
16345 ("\\n" . :preserve-breaks)
16346 ("@" . :expand-quoted-html)
16347 (":" . :fixed-width)
16348 ("|" . :tables)
16349 ("^" . :sub-superscript)
16350 ("*" . :emphasize)
16351 ("TeX" . :TeX-macros)
16352 ("LaTeX" . :LaTeX-fragments)))
16354 (while (setq o (pop op))
16355 (if (string-match (concat (regexp-quote (car o))
16356 ":\\([^ \t\n\r;,.]*\\)")
16357 options)
16358 (setq p (plist-put p (cdr o)
16359 (car (read-from-string
16360 (match-string 1 options)))))))))
16361 p)))
16363 (defun org-export-directory (type plist)
16364 (let* ((val (plist-get plist :publishing-directory))
16365 (dir (if (listp val)
16366 (or (cdr (assoc type val)) ".")
16367 val)))
16368 dir))
16370 (defun org-export-find-first-heading-line (list)
16371 "Remove all lines from LIST which are before the first headline."
16372 (let ((orig-list list)
16373 (re (concat "^" outline-regexp)))
16374 (while (and list
16375 (not (string-match re (car list))))
16376 (pop list))
16377 (or list orig-list)))
16379 (defun org-skip-comments (lines)
16380 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
16381 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
16382 (re2 "^\\(\\*+\\)[ \t\n\r]")
16383 rtn line level)
16384 (while (setq line (pop lines))
16385 (cond
16386 ((and (string-match re1 line)
16387 (setq level (- (match-end 1) (match-beginning 1))))
16388 ;; Beginning of a COMMENT subtree. Skip it.
16389 (while (and (setq line (pop lines))
16390 (or (not (string-match re2 line))
16391 (> (- (match-end 1) (match-beginning 1)) level))))
16392 (setq lines (cons line lines)))
16393 ((string-match "^#" line)
16394 ;; an ordinary comment line
16396 ((and org-export-table-remove-special-lines
16397 (string-match "^[ \t]*|" line)
16398 (or (string-match "^[ \t]*| *[!_^] *|" line)
16399 (and (string-match "| *<[0-9]+> *|" line)
16400 (not (string-match "| *[^ <|]" line)))))
16401 ;; a special table line that should be removed
16403 (t (setq rtn (cons line rtn)))))
16404 (nreverse rtn)))
16406 (defun org-export (&optional arg)
16407 (interactive)
16408 (let ((help "[t] insert the export option template
16409 \[v] limit export to visible part of outline tree
16411 \[a] export as ASCII
16412 \[h] export as HTML
16413 \[b] export as HTML and browse immediately
16414 \[x] export as XOXO
16416 \[i] export current file as iCalendar file
16417 \[I] export all agenda files as iCalendar files
16418 \[c] export agenda files into combined iCalendar file
16420 \[F] publish current file
16421 \[P] publish current project
16422 \[X] publish... (project will be prompted for)
16423 \[A] publish all projects")
16424 (cmds
16425 '((?t . org-insert-export-options-template)
16426 (?v . org-export-visible)
16427 (?a . org-export-as-ascii)
16428 (?h . org-export-as-html)
16429 (?b . org-export-as-html-and-open)
16430 (?x . org-export-as-xoxo)
16431 (?i . org-export-icalendar-this-file)
16432 (?I . org-export-icalendar-all-agenda-files)
16433 (?c . org-export-icalendar-combine-agenda-files)
16434 (?F . org-publish-current-file)
16435 (?P . org-publish-current-project)
16436 (?X . org-publish)
16437 (?A . org-publish-all)))
16438 r1 r2 ass)
16439 (save-window-excursion
16440 (delete-other-windows)
16441 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
16442 (princ help))
16443 (message "Select command: ")
16444 (setq r1 (read-char-exclusive)))
16445 (setq r2 (if (< r1 27) (+ r1 96) r1))
16446 (if (setq ass (assq r2 cmds))
16447 (call-interactively (cdr ass))
16448 (error "No command associated with key %c" r1))))
16450 (defconst org-html-entities
16451 '(("nbsp")
16452 ("iexcl")
16453 ("cent")
16454 ("pound")
16455 ("curren")
16456 ("yen")
16457 ("brvbar")
16458 ("sect")
16459 ("uml")
16460 ("copy")
16461 ("ordf")
16462 ("laquo")
16463 ("not")
16464 ("shy")
16465 ("reg")
16466 ("macr")
16467 ("deg")
16468 ("plusmn")
16469 ("sup2")
16470 ("sup3")
16471 ("acute")
16472 ("micro")
16473 ("para")
16474 ("middot")
16475 ("odot"."o")
16476 ("star"."*")
16477 ("cedil")
16478 ("sup1")
16479 ("ordm")
16480 ("raquo")
16481 ("frac14")
16482 ("frac12")
16483 ("frac34")
16484 ("iquest")
16485 ("Agrave")
16486 ("Aacute")
16487 ("Acirc")
16488 ("Atilde")
16489 ("Auml")
16490 ("Aring") ("AA"."&Aring;")
16491 ("AElig")
16492 ("Ccedil")
16493 ("Egrave")
16494 ("Eacute")
16495 ("Ecirc")
16496 ("Euml")
16497 ("Igrave")
16498 ("Iacute")
16499 ("Icirc")
16500 ("Iuml")
16501 ("ETH")
16502 ("Ntilde")
16503 ("Ograve")
16504 ("Oacute")
16505 ("Ocirc")
16506 ("Otilde")
16507 ("Ouml")
16508 ("times")
16509 ("Oslash")
16510 ("Ugrave")
16511 ("Uacute")
16512 ("Ucirc")
16513 ("Uuml")
16514 ("Yacute")
16515 ("THORN")
16516 ("szlig")
16517 ("agrave")
16518 ("aacute")
16519 ("acirc")
16520 ("atilde")
16521 ("auml")
16522 ("aring")
16523 ("aelig")
16524 ("ccedil")
16525 ("egrave")
16526 ("eacute")
16527 ("ecirc")
16528 ("euml")
16529 ("igrave")
16530 ("iacute")
16531 ("icirc")
16532 ("iuml")
16533 ("eth")
16534 ("ntilde")
16535 ("ograve")
16536 ("oacute")
16537 ("ocirc")
16538 ("otilde")
16539 ("ouml")
16540 ("divide")
16541 ("oslash")
16542 ("ugrave")
16543 ("uacute")
16544 ("ucirc")
16545 ("uuml")
16546 ("yacute")
16547 ("thorn")
16548 ("yuml")
16549 ("fnof")
16550 ("Alpha")
16551 ("Beta")
16552 ("Gamma")
16553 ("Delta")
16554 ("Epsilon")
16555 ("Zeta")
16556 ("Eta")
16557 ("Theta")
16558 ("Iota")
16559 ("Kappa")
16560 ("Lambda")
16561 ("Mu")
16562 ("Nu")
16563 ("Xi")
16564 ("Omicron")
16565 ("Pi")
16566 ("Rho")
16567 ("Sigma")
16568 ("Tau")
16569 ("Upsilon")
16570 ("Phi")
16571 ("Chi")
16572 ("Psi")
16573 ("Omega")
16574 ("alpha")
16575 ("beta")
16576 ("gamma")
16577 ("delta")
16578 ("epsilon")
16579 ("varepsilon"."&epsilon;")
16580 ("zeta")
16581 ("eta")
16582 ("theta")
16583 ("iota")
16584 ("kappa")
16585 ("lambda")
16586 ("mu")
16587 ("nu")
16588 ("xi")
16589 ("omicron")
16590 ("pi")
16591 ("rho")
16592 ("sigmaf") ("varsigma"."&sigmaf;")
16593 ("sigma")
16594 ("tau")
16595 ("upsilon")
16596 ("phi")
16597 ("chi")
16598 ("psi")
16599 ("omega")
16600 ("thetasym") ("vartheta"."&thetasym;")
16601 ("upsih")
16602 ("piv")
16603 ("bull") ("bullet"."&bull;")
16604 ("hellip") ("dots"."&hellip;")
16605 ("prime")
16606 ("Prime")
16607 ("oline")
16608 ("frasl")
16609 ("weierp")
16610 ("image")
16611 ("real")
16612 ("trade")
16613 ("alefsym")
16614 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
16615 ("uarr") ("uparrow"."&uarr;")
16616 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
16617 ("darr")("downarrow"."&darr;")
16618 ("harr") ("leftrightarrow"."&harr;")
16619 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
16620 ("lArr") ("Leftarrow"."&lArr;")
16621 ("uArr") ("Uparrow"."&uArr;")
16622 ("rArr") ("Rightarrow"."&rArr;")
16623 ("dArr") ("Downarrow"."&dArr;")
16624 ("hArr") ("Leftrightarrow"."&hArr;")
16625 ("forall")
16626 ("part") ("partial"."&part;")
16627 ("exist") ("exists"."&exist;")
16628 ("empty") ("emptyset"."&empty;")
16629 ("nabla")
16630 ("isin") ("in"."&isin;")
16631 ("notin")
16632 ("ni")
16633 ("prod")
16634 ("sum")
16635 ("minus")
16636 ("lowast") ("ast"."&lowast;")
16637 ("radic")
16638 ("prop") ("proptp"."&prop;")
16639 ("infin") ("infty"."&infin;")
16640 ("ang") ("angle"."&ang;")
16641 ("and") ("vee"."&and;")
16642 ("or") ("wedge"."&or;")
16643 ("cap")
16644 ("cup")
16645 ("int")
16646 ("there4")
16647 ("sim")
16648 ("cong") ("simeq"."&cong;")
16649 ("asymp")("approx"."&asymp;")
16650 ("ne") ("neq"."&ne;")
16651 ("equiv")
16652 ("le")
16653 ("ge")
16654 ("sub") ("subset"."&sub;")
16655 ("sup") ("supset"."&sup;")
16656 ("nsub")
16657 ("sube")
16658 ("supe")
16659 ("oplus")
16660 ("otimes")
16661 ("perp")
16662 ("sdot") ("cdot"."&sdot;")
16663 ("lceil")
16664 ("rceil")
16665 ("lfloor")
16666 ("rfloor")
16667 ("lang")
16668 ("rang")
16669 ("loz") ("Diamond"."&loz;")
16670 ("spades") ("spadesuit"."&spades;")
16671 ("clubs") ("clubsuit"."&clubs;")
16672 ("hearts") ("diamondsuit"."&hearts;")
16673 ("diams") ("diamondsuit"."&diams;")
16674 ("quot")
16675 ("amp")
16676 ("lt")
16677 ("gt")
16678 ("OElig")
16679 ("oelig")
16680 ("Scaron")
16681 ("scaron")
16682 ("Yuml")
16683 ("circ")
16684 ("tilde")
16685 ("ensp")
16686 ("emsp")
16687 ("thinsp")
16688 ("zwnj")
16689 ("zwj")
16690 ("lrm")
16691 ("rlm")
16692 ("ndash")
16693 ("mdash")
16694 ("lsquo")
16695 ("rsquo")
16696 ("sbquo")
16697 ("ldquo")
16698 ("rdquo")
16699 ("bdquo")
16700 ("dagger")
16701 ("Dagger")
16702 ("permil")
16703 ("lsaquo")
16704 ("rsaquo")
16705 ("euro")
16707 ("arccos"."arccos")
16708 ("arcsin"."arcsin")
16709 ("arctan"."arctan")
16710 ("arg"."arg")
16711 ("cos"."cos")
16712 ("cosh"."cosh")
16713 ("cot"."cot")
16714 ("coth"."coth")
16715 ("csc"."csc")
16716 ("deg"."deg")
16717 ("det"."det")
16718 ("dim"."dim")
16719 ("exp"."exp")
16720 ("gcd"."gcd")
16721 ("hom"."hom")
16722 ("inf"."inf")
16723 ("ker"."ker")
16724 ("lg"."lg")
16725 ("lim"."lim")
16726 ("liminf"."liminf")
16727 ("limsup"."limsup")
16728 ("ln"."ln")
16729 ("log"."log")
16730 ("max"."max")
16731 ("min"."min")
16732 ("Pr"."Pr")
16733 ("sec"."sec")
16734 ("sin"."sin")
16735 ("sinh"."sinh")
16736 ("sup"."sup")
16737 ("tan"."tan")
16738 ("tanh"."tanh")
16740 "Entities for TeX->HTML translation.
16741 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
16742 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
16743 In that case, \"\\ent\" will be translated to \"&other;\".
16744 The list contains HTML entities for Latin-1, Greek and other symbols.
16745 It is supplemented by a number of commonly used TeX macros with appropriate
16746 translations. There is currently no way for users to extend this.")
16748 ;;; General functions for all backends
16750 (defun org-cleaned-string-for-export (string &rest parameters)
16751 "Cleanup a buffer substring so that links can be created safely."
16752 (interactive)
16753 (let* ((re-radio (and org-target-link-regexp
16754 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
16755 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
16756 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
16757 (re-archive (concat ":" org-archive-tag ":"))
16758 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
16759 (htmlp (memq :for-html parameters))
16760 (outline-regexp "\\*+")
16761 rtn)
16762 (save-excursion
16763 (set-buffer (get-buffer-create " org-mode-tmp"))
16764 (erase-buffer)
16765 (insert string)
16766 (let ((org-inhibit-startup t)) (org-mode))
16767 (untabify (point-min) (point-max))
16769 ;; Get rid of archived trees
16770 (when (not (eq org-export-with-archived-trees t))
16771 (goto-char (point-min))
16772 (while (re-search-forward re-archive nil t)
16773 (if (not (org-on-heading-p))
16774 (org-end-of-subtree t)
16775 (beginning-of-line 1)
16776 (delete-region
16777 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
16778 (org-end-of-subtree t)))))
16780 ;; Protect stuff from HTML processing
16781 (goto-char (point-min))
16782 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
16783 (add-text-properties (match-beginning 0) (match-end 0)
16784 '(org-protected t)))
16785 (when htmlp
16786 (goto-char (point-min))
16787 (while (re-search-forward "^#\\+HTML:[ \t]*\\(.*\\)" nil t)
16788 (replace-match "\\1" t)
16789 (add-text-properties
16790 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
16791 '(org-protected t))))
16792 (goto-char (point-min))
16793 (while (re-search-forward
16794 "^#\\+BEGIN_HTML\\>.*\\(\n.*\\)*?\n#\\+END_HTML\\>.*\n?" nil t)
16795 (if htmlp
16796 (add-text-properties (match-beginning 1) (1+ (match-end 1))
16797 '(org-protected t))
16798 (delete-region (match-beginning 0) (match-end 0))))
16799 (goto-char (point-min))
16800 (while (re-search-forward re-quote nil t)
16801 (goto-char (match-beginning 0))
16802 (end-of-line 1)
16803 (add-text-properties (point) (org-end-of-subtree t)
16804 '(org-protected t)))
16806 ;; Find targets in comments and move them out of comments,
16807 ;; but mark them as targets that should be invisible
16808 (goto-char (point-min))
16809 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
16810 (replace-match "\\1(INVISIBLE)"))
16812 ;; Remove comments
16813 (goto-char (point-min))
16814 (while (re-search-forward "^#.*\n?" nil t)
16815 (replace-match ""))
16817 ;; Find matches for radio targets and turn them into internal links
16818 (goto-char (point-min))
16819 (when re-radio
16820 (while (re-search-forward re-radio nil t)
16821 (org-if-unprotected
16822 (replace-match "\\1[[\\2]]"))))
16824 ;; Find all links that contain a newline and put them into a single line
16825 (goto-char (point-min))
16826 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
16827 (org-if-unprotected
16828 (replace-match "\\1 \\3")
16829 (goto-char (match-beginning 0))))
16831 ;; Convert LaTeX fragments to images
16832 (when (memq :LaTeX-fragments parameters)
16833 (org-format-latex
16834 (concat "ltxpng/" (file-name-sans-extension
16835 (file-name-nondirectory
16836 org-current-export-file)))
16837 org-current-export-dir nil "Creating LaTeX image %s"))
16838 (message "Exporting...")
16840 ;; Normalize links: Convert angle and plain links into bracket links
16841 ;; Expand link abbreviations
16842 (goto-char (point-min))
16843 (while (re-search-forward re-plain-link nil t)
16844 (org-if-unprotected
16845 (replace-match
16846 (concat
16847 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
16848 t t)))
16849 (goto-char (point-min))
16850 (while (re-search-forward re-angle-link nil t)
16851 (org-if-unprotected
16852 (replace-match
16853 (concat
16854 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
16855 t t)))
16856 (goto-char (point-min))
16857 (while (re-search-forward org-bracket-link-regexp nil t)
16858 (org-if-unprotected
16859 (replace-match
16860 (concat "[[" (save-match-data
16861 (org-link-expand-abbrev (match-string 1)))
16863 (if (match-end 3)
16864 (match-string 2)
16865 (concat "[" (match-string 1) "]"))
16866 "]")
16867 t t)))
16869 ;; Find multiline emphasis and put them into single line
16870 (when (memq :emph-multiline parameters)
16871 (goto-char (point-min))
16872 (while (re-search-forward org-emph-re nil t)
16873 (org-if-unprotected
16874 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
16875 (goto-char (1- (match-end 0))))))
16877 (setq rtn (buffer-string)))
16878 (kill-buffer " org-mode-tmp")
16879 rtn))
16881 (defun org-solidify-link-text (s &optional alist)
16882 "Take link text and make a safe target out of it."
16883 (save-match-data
16884 (let* ((rtn
16885 (mapconcat
16886 'identity
16887 (org-split-string s "[ \t\r\n]+") "--"))
16888 (a (assoc rtn alist)))
16889 (or (cdr a) rtn))))
16891 ;; Variable holding the vector with section numbers
16892 (defvar org-section-numbers (make-vector org-level-max 0))
16894 (defun org-init-section-numbers ()
16895 "Initialize the vector for the section numbers."
16896 (let* ((level -1)
16897 (numbers (nreverse (org-split-string "" "\\.")))
16898 (depth (1- (length org-section-numbers)))
16899 (i depth) number-string)
16900 (while (>= i 0)
16901 (if (> i level)
16902 (aset org-section-numbers i 0)
16903 (setq number-string (or (car numbers) "0"))
16904 (if (string-match "\\`[A-Z]\\'" number-string)
16905 (aset org-section-numbers i
16906 (- (string-to-char number-string) ?A -1))
16907 (aset org-section-numbers i (string-to-number number-string)))
16908 (pop numbers))
16909 (setq i (1- i)))))
16911 (defun org-section-number (&optional level)
16912 "Return a string with the current section number.
16913 When LEVEL is non-nil, increase section numbers on that level."
16914 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
16915 (when level
16916 (when (> level -1)
16917 (aset org-section-numbers
16918 level (1+ (aref org-section-numbers level))))
16919 (setq idx (1+ level))
16920 (while (<= idx depth)
16921 (if (not (= idx 1))
16922 (aset org-section-numbers idx 0))
16923 (setq idx (1+ idx))))
16924 (setq idx 0)
16925 (while (<= idx depth)
16926 (setq n (aref org-section-numbers idx))
16927 (setq string (concat string (if (not (string= string "")) "." "")
16928 (int-to-string n)))
16929 (setq idx (1+ idx)))
16930 (save-match-data
16931 (if (string-match "\\`\\([@0]\\.\\)+" string)
16932 (setq string (replace-match "" t nil string)))
16933 (if (string-match "\\(\\.0\\)+\\'" string)
16934 (setq string (replace-match "" t nil string))))
16935 string))
16937 ;;; ASCII export
16939 (defvar org-last-level nil) ; dynamically scoped variable
16940 (defvar org-levels-open nil) ; dynamically scoped parameter
16941 (defvar org-ascii-current-indentation nil) ; For communication
16943 (defun org-export-as-ascii (arg)
16944 "Export the outline as a pretty ASCII file.
16945 If there is an active region, export only the region.
16946 The prefix ARG specifies how many levels of the outline should become
16947 underlined headlines. The default is 3."
16948 (interactive "P")
16949 (setq-default org-todo-line-regexp org-todo-line-regexp)
16950 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
16951 (org-infile-export-plist)))
16952 (region
16953 (buffer-substring
16954 (if (org-region-active-p) (region-beginning) (point-min))
16955 (if (org-region-active-p) (region-end) (point-max))))
16956 (custom-times org-display-custom-times)
16957 (lines (org-export-find-first-heading-line
16958 (org-skip-comments
16959 (org-split-string
16960 (org-cleaned-string-for-export region)
16961 "[\r\n]"))))
16962 (org-ascii-current-indentation '(0 . 0))
16963 (level 0) line txt
16964 (umax nil)
16965 (umax-toc nil)
16966 (case-fold-search nil)
16967 (filename (concat (file-name-as-directory
16968 (org-export-directory :ascii opt-plist))
16969 (file-name-sans-extension
16970 (file-name-nondirectory buffer-file-name))
16971 ".txt"))
16972 (buffer (find-file-noselect filename))
16973 (org-levels-open (make-vector org-level-max nil))
16974 (odd org-odd-levels-only)
16975 (date (format-time-string "%Y/%m/%d" (current-time)))
16976 (time (format-time-string "%X" (org-current-time)))
16977 (author (plist-get opt-plist :author))
16978 (title (or (plist-get opt-plist :title)
16979 (file-name-sans-extension
16980 (file-name-nondirectory buffer-file-name))))
16981 (email (plist-get opt-plist :email))
16982 (language (plist-get opt-plist :language))
16983 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
16984 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
16985 (text nil)
16986 (todo nil)
16987 (lang-words nil))
16989 (setq org-last-level 1)
16990 (org-init-section-numbers)
16992 (find-file-noselect filename)
16994 (setq lang-words (or (assoc language org-export-language-setup)
16995 (assoc "en" org-export-language-setup)))
16996 (switch-to-buffer-other-window buffer)
16997 (erase-buffer)
16998 (fundamental-mode)
16999 ;; create local variables for all options, to make sure all called
17000 ;; functions get the correct information
17001 (mapcar (lambda (x)
17002 (set (make-local-variable (cdr x))
17003 (plist-get opt-plist (car x))))
17004 org-export-plist-vars)
17005 (org-set-local 'org-odd-levels-only odd)
17006 (setq umax (if arg (prefix-numeric-value arg)
17007 org-export-headline-levels))
17008 (setq umax-toc (if (integerp org-export-with-toc)
17009 (min org-export-with-toc umax)
17010 umax))
17012 ;; File header
17013 (if title (org-insert-centered title ?=))
17014 (insert "\n")
17015 (if (or author email)
17016 (insert (concat (nth 1 lang-words) ": " (or author "")
17017 (if email (concat " <" email ">") "")
17018 "\n")))
17019 (if (and date time)
17020 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
17021 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
17023 (insert "\n\n")
17025 (if org-export-with-toc
17026 (progn
17027 (insert (nth 3 lang-words) "\n"
17028 (make-string (length (nth 3 lang-words)) ?=) "\n")
17029 (mapcar '(lambda (line)
17030 (if (string-match org-todo-line-regexp
17031 line)
17032 ;; This is a headline
17033 (progn
17034 (setq level (- (match-end 1) (match-beginning 1))
17035 level (org-tr-level level)
17036 txt (match-string 3 line)
17037 todo
17038 (or (and org-export-mark-todo-in-toc
17039 (match-beginning 2)
17040 (not (equal (match-string 2 line)
17041 org-done-string)))
17042 ; TODO, not DONE
17043 (and org-export-mark-todo-in-toc
17044 (= level umax-toc)
17045 (org-search-todo-below
17046 line lines level))))
17047 (setq txt (org-html-expand-for-ascii txt))
17049 (if (and (memq org-export-with-tags '(not-in-toc nil))
17050 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
17051 (setq txt (replace-match "" t t txt)))
17052 (if (string-match quote-re0 txt)
17053 (setq txt (replace-match "" t t txt)))
17055 (if org-export-with-section-numbers
17056 (setq txt (concat (org-section-number level)
17057 " " txt)))
17058 (if (<= level umax-toc)
17059 (progn
17060 (insert
17061 (make-string (* (1- level) 4) ?\ )
17062 (format (if todo "%s (*)\n" "%s\n") txt))
17063 (setq org-last-level level))
17064 ))))
17065 lines)))
17067 (org-init-section-numbers)
17068 (while (setq line (pop lines))
17069 ;; Remove the quoted HTML tags.
17070 (setq line (org-html-expand-for-ascii line))
17071 ;; Remove targets
17072 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
17073 (setq line (replace-match "" t t line)))
17074 ;; Replace internal links
17075 (while (string-match org-bracket-link-regexp line)
17076 (setq line (replace-match
17077 (if (match-end 3) "[\\3]" "[\\1]")
17078 t nil line)))
17079 (when custom-times
17080 (setq line (org-translate-time line)))
17081 (cond
17082 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
17083 ;; a Headline
17084 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
17085 txt (match-string 2 line))
17086 (org-ascii-level-start level txt umax lines))
17088 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
17089 (normal-mode)
17090 (save-buffer)
17091 ;; remove display and invisible chars
17092 (let (beg end)
17093 (goto-char (point-min))
17094 (while (setq beg (next-single-property-change (point) 'display))
17095 (setq end (next-single-property-change beg 'display))
17096 (delete-region beg end)
17097 (goto-char beg)
17098 (insert "=>"))
17099 (goto-char (point-min))
17100 (while (setq beg (next-single-property-change (point) 'org-cwidth))
17101 (setq end (next-single-property-change beg 'org-cwidth))
17102 (delete-region beg end)
17103 (goto-char beg)))
17104 (goto-char (point-min))))
17106 (defun org-search-todo-below (line lines level)
17107 "Search the subtree below LINE for any TODO entries."
17108 (let ((rest (cdr (memq line lines)))
17109 (re org-todo-line-regexp)
17110 line lv todo)
17111 (catch 'exit
17112 (while (setq line (pop rest))
17113 (if (string-match re line)
17114 (progn
17115 (setq lv (- (match-end 1) (match-beginning 1))
17116 todo (and (match-beginning 2)
17117 (not (equal (match-string 2 line)
17118 org-done-string))))
17119 ; TODO, not DONE
17120 (if (<= lv level) (throw 'exit nil))
17121 (if todo (throw 'exit t))))))))
17123 (defun org-html-expand-for-ascii (line)
17124 "Handle quoted HTML for ASCII export."
17125 (if org-export-html-expand
17126 (while (string-match "@<[^<>\n]*>" line)
17127 ;; We just remove the tags for now.
17128 (setq line (replace-match "" nil nil line))))
17129 line)
17131 (defun org-insert-centered (s &optional underline)
17132 "Insert the string S centered and underline it with character UNDERLINE."
17133 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
17134 (insert (make-string ind ?\ ) s "\n")
17135 (if underline
17136 (insert (make-string ind ?\ )
17137 (make-string (string-width s) underline)
17138 "\n"))))
17140 (defun org-ascii-level-start (level title umax &optional lines)
17141 "Insert a new level in ASCII export."
17142 (let (char (n (- level umax 1)) (ind 0))
17143 (if (> level umax)
17144 (progn
17145 (insert (make-string (* 2 n) ?\ )
17146 (char-to-string (nth (% n (length org-export-ascii-bullets))
17147 org-export-ascii-bullets))
17148 " " title "\n")
17149 ;; find the indentation of the next non-empty line
17150 (catch 'stop
17151 (while lines
17152 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
17153 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
17154 (throw 'stop (setq ind (org-get-indentation (car lines)))))
17155 (pop lines)))
17156 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
17157 (if (or (not (equal (char-before) ?\n))
17158 (not (equal (char-before (1- (point))) ?\n)))
17159 (insert "\n"))
17160 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
17161 (unless org-export-with-tags
17162 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
17163 (setq title (replace-match "" t t title))))
17164 (if org-export-with-section-numbers
17165 (setq title (concat (org-section-number level) " " title)))
17166 (insert title "\n" (make-string (string-width title) char) "\n")
17167 (setq org-ascii-current-indentation '(0 . 0)))))
17169 (defun org-export-visible (type arg)
17170 "Create a copy of the visible part of the current buffer, and export it.
17171 The copy is created in a temporary buffer and removed after use.
17172 TYPE is the final key (as a string) that also select the export command in
17173 the `C-c C-e' export dispatcher.
17174 As a special case, if the you type SPC at the prompt, the temporary
17175 org-mode file will not be removed but presented to you so that you can
17176 continue to use it. The prefix arg ARG is passed through to the exporting
17177 command."
17178 (interactive
17179 (list (progn
17180 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
17181 (read-char-exclusive))
17182 current-prefix-arg))
17183 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
17184 (error "Invalid export key"))
17185 (let* ((binding (cdr (assoc type
17186 '((?a . org-export-as-ascii)
17187 (?\C-a . org-export-as-ascii)
17188 (?b . org-export-as-html-and-open)
17189 (?\C-b . org-export-as-html-and-open)
17190 (?h . org-export-as-html)
17191 (?x . org-export-as-xoxo)))))
17192 (keepp (equal type ?\ ))
17193 (file buffer-file-name)
17194 (buffer (get-buffer-create "*Org Export Visible*"))
17195 s e)
17196 (with-current-buffer buffer (erase-buffer))
17197 (save-excursion
17198 (setq s (goto-char (point-min)))
17199 (while (not (= (point) (point-max)))
17200 (goto-char (org-find-invisible))
17201 (append-to-buffer buffer s (point))
17202 (setq s (goto-char (org-find-visible))))
17203 (goto-char (point-min))
17204 (unless keepp
17205 ;; Copy all comment lines to the end, to make sure #+ settings are
17206 ;; still available for the second export step. Kind of a hack, but
17207 ;; does do the trick.
17208 (if (looking-at "#[^\r\n]*")
17209 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
17210 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
17211 (append-to-buffer buffer (1+ (match-beginning 0))
17212 (min (point-max) (1+ (match-end 0))))))
17213 (set-buffer buffer)
17214 (let ((buffer-file-name file)
17215 (org-inhibit-startup t))
17216 (org-mode)
17217 (show-all)
17218 (unless keepp (funcall binding arg))))
17219 (if (not keepp)
17220 (kill-buffer buffer)
17221 (switch-to-buffer-other-window buffer)
17222 (goto-char (point-min)))))
17224 (defun org-find-visible ()
17225 (let ((s (point)))
17226 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17227 (get-char-property s 'invisible)))
17229 (defun org-find-invisible ()
17230 (let ((s (point)))
17231 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17232 (not (get-char-property s 'invisible))))
17235 ;;; HTML export
17237 (defun org-get-current-options ()
17238 "Return a string with current options as keyword options.
17239 Does include HTML export options as well as TODO and CATEGORY stuff."
17240 (format
17241 "#+TITLE: %s
17242 #+AUTHOR: %s
17243 #+EMAIL: %s
17244 #+LANGUAGE: %s
17245 #+TEXT: Some descriptive text to be emitted. Several lines OK.
17246 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
17247 #+CATEGORY: %s
17248 #+SEQ_TODO: %s
17249 #+TYP_TODO: %s
17250 #+STARTUP: %s %s %s %s %s
17251 #+TAGS: %s
17252 #+ARCHIVE: %s
17253 #+LINK: %s
17255 (buffer-name) (user-full-name) user-mail-address org-export-default-language
17256 org-export-headline-levels
17257 org-export-with-section-numbers
17258 org-export-with-toc
17259 org-export-preserve-breaks
17260 org-export-html-expand
17261 org-export-with-fixed-width
17262 org-export-with-tables
17263 org-export-with-sub-superscripts
17264 org-export-with-emphasize
17265 org-export-with-TeX-macros
17266 org-export-with-LaTeX-fragments
17267 (file-name-nondirectory buffer-file-name)
17268 (if (equal org-todo-interpretation 'sequence)
17269 (mapconcat 'identity org-todo-keywords " ")
17270 "TODO FEEDBACK VERIFY DONE")
17271 (if (equal org-todo-interpretation 'type)
17272 (mapconcat 'identity org-todo-keywords " ")
17273 "Me Jason Marie DONE")
17274 (cdr (assoc org-startup-folded
17275 '((nil . "showall") (t . "overview") (content . "content"))))
17276 (if org-odd-levels-only "odd" "oddeven")
17277 (if org-hide-leading-stars "hidestars" "showstars")
17278 (if org-startup-align-all-tables "align" "noalign")
17279 (cond ((eq t org-log-done) "logdone")
17280 ((not org-log-done) "nologging")
17281 ((listp org-log-done)
17282 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
17283 org-log-done " ")))
17284 (or (mapconcat (lambda (x)
17285 (cond
17286 ((equal '(:startgroup) x) "{")
17287 ((equal '(:endgroup) x) "}")
17288 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
17289 (t (car x))))
17290 (or org-tag-alist (org-get-buffer-tags)) " ") "")
17291 org-archive-location
17292 "org file:~/org/%s.org"
17295 (defun org-insert-export-options-template ()
17296 "Insert into the buffer a template with information for exporting."
17297 (interactive)
17298 (if (not (bolp)) (newline))
17299 (let ((s (org-get-current-options)))
17300 (and (string-match "#\\+CATEGORY" s)
17301 (setq s (substring s 0 (match-beginning 0))))
17302 (insert s)))
17304 (defun org-toggle-fixed-width-section (arg)
17305 "Toggle the fixed-width export.
17306 If there is no active region, the QUOTE keyword at the current headline is
17307 inserted or removed. When present, it causes the text between this headline
17308 and the next to be exported as fixed-width text, and unmodified.
17309 If there is an active region, this command adds or removes a colon as the
17310 first character of this line. If the first character of a line is a colon,
17311 this line is also exported in fixed-width font."
17312 (interactive "P")
17313 (let* ((cc 0)
17314 (regionp (org-region-active-p))
17315 (beg (if regionp (region-beginning) (point)))
17316 (end (if regionp (region-end)))
17317 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17318 (re "[ \t]*\\(:\\)")
17319 off)
17320 (if regionp
17321 (save-excursion
17322 (goto-char beg)
17323 (setq cc (current-column))
17324 (beginning-of-line 1)
17325 (setq off (looking-at re))
17326 (while (> nlines 0)
17327 (setq nlines (1- nlines))
17328 (beginning-of-line 1)
17329 (cond
17330 (arg
17331 (move-to-column cc t)
17332 (insert ":\n")
17333 (forward-line -1))
17334 ((and off (looking-at re))
17335 (replace-match "" t t nil 1))
17336 ((not off) (move-to-column cc t) (insert ":")))
17337 (forward-line 1)))
17338 (save-excursion
17339 (org-back-to-heading)
17340 (if (looking-at (concat outline-regexp
17341 "\\( +\\<" org-quote-string "\\>\\)"))
17342 (replace-match "" t t nil 1)
17343 (if (looking-at outline-regexp)
17344 (progn
17345 (goto-char (match-end 0))
17346 (insert " " org-quote-string))))))))
17348 (defun org-export-as-html-and-open (arg)
17349 "Export the outline as HTML and immediately open it with a browser.
17350 If there is an active region, export only the region.
17351 The prefix ARG specifies how many levels of the outline should become
17352 headlines. The default is 3. Lower levels will become bulleted lists."
17353 (interactive "P")
17354 (org-export-as-html arg 'hidden)
17355 (org-open-file buffer-file-name))
17357 (defun org-export-as-html-batch ()
17358 "Call `org-export-as-html', may be used in batch processing as
17359 emacs --batch
17360 --load=$HOME/lib/emacs/org.el
17361 --eval \"(setq org-export-headline-levels 2)\"
17362 --visit=MyFile --funcall org-export-as-html-batch"
17363 (org-export-as-html org-export-headline-levels 'hidden))
17365 (defun org-export-as-html (arg &optional hidden ext-plist)
17366 "Export the outline as a pretty HTML file.
17367 If there is an active region, export only the region.
17368 The prefix ARG specifies how many levels of the outline should become
17369 headlines. The default is 3. Lower levels will become bulleted lists.
17370 When HIDDEN is non-nil, don't display the HTML buffer.
17371 EXT-PLIST is a property list with external parameters overriding
17372 org-mode's default settings, but still inferior to file-local settings."
17373 (interactive "P")
17374 (message "Exporting...")
17375 (setq-default org-todo-line-regexp org-todo-line-regexp)
17376 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
17377 (setq-default org-done-string org-done-string)
17378 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
17379 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17380 ext-plist
17381 (org-infile-export-plist)))
17383 (style (plist-get opt-plist :style))
17384 (link-validate (plist-get opt-plist :link-validation-function))
17385 valid
17386 (odd org-odd-levels-only)
17387 (region-p (org-region-active-p))
17388 (region
17389 (buffer-substring
17390 (if region-p (region-beginning) (point-min))
17391 (if region-p (region-end) (point-max))))
17392 ;; The following two are dynamically scoped into other
17393 ;; routines below.
17394 (org-current-export-dir (org-export-directory :html opt-plist))
17395 (org-current-export-file buffer-file-name)
17396 (all_lines
17397 (org-skip-comments (org-split-string
17398 (org-cleaned-string-for-export
17399 region :emph-multiline :for-html
17400 (if (plist-get opt-plist :LaTeX-fragments)
17401 :LaTeX-fragments))
17402 "[\r\n]")))
17403 (lines (org-export-find-first-heading-line all_lines))
17404 (level 0) (line "") (origline "") txt todo
17405 (umax nil)
17406 (umax-toc nil)
17407 (filename (concat (file-name-as-directory
17408 (org-export-directory :html opt-plist))
17409 (file-name-sans-extension
17410 (file-name-nondirectory buffer-file-name))
17411 ".html"))
17412 (current-dir (file-name-directory buffer-file-name))
17413 (buffer (find-file-noselect filename))
17414 (org-levels-open (make-vector org-level-max nil))
17415 (date (format-time-string "%Y/%m/%d" (current-time)))
17416 (time (format-time-string "%X" (org-current-time)))
17417 (author (plist-get opt-plist :author))
17418 (title (or (plist-get opt-plist :title)
17419 (file-name-sans-extension
17420 (file-name-nondirectory buffer-file-name))))
17421 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
17422 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
17423 (inquote nil)
17424 (infixed nil)
17425 (in-local-list nil)
17426 (local-list-num nil)
17427 (local-list-indent nil)
17428 (llt org-plain-list-ordered-item-terminator)
17429 (email (plist-get opt-plist :email))
17430 (language (plist-get opt-plist :language))
17431 (text (plist-get opt-plist :text))
17432 (lang-words nil)
17433 (target-alist nil) tg
17434 (head-count 0) cnt
17435 (start 0)
17436 (coding-system (and (boundp 'buffer-file-coding-system)
17437 buffer-file-coding-system))
17438 (coding-system-for-write coding-system)
17439 (save-buffer-coding-system coding-system)
17440 (charset (and coding-system
17441 (fboundp 'coding-system-get)
17442 (coding-system-get coding-system 'mime-charset)))
17443 table-open type
17444 table-buffer table-orig-buffer
17445 ind start-is-num starter
17446 rpl path desc descp desc1 desc2 link
17448 (message "Exporting...")
17450 (setq org-last-level 1)
17451 (org-init-section-numbers)
17453 ;; Get the language-dependent settings
17454 (setq lang-words (or (assoc language org-export-language-setup)
17455 (assoc "en" org-export-language-setup)))
17457 ;; Switch to the output buffer
17458 (if (or hidden t)
17459 (set-buffer buffer)
17460 (switch-to-buffer-other-window buffer))
17461 (erase-buffer)
17462 (fundamental-mode)
17463 (let ((case-fold-search nil)
17464 (org-odd-levels-only odd))
17465 ;; create local variables for all options, to make sure all called
17466 ;; functions get the correct information
17467 (mapcar (lambda (x)
17468 (set (make-local-variable (cdr x))
17469 (plist-get opt-plist (car x))))
17470 org-export-plist-vars)
17471 (setq umax (if arg (prefix-numeric-value arg)
17472 org-export-headline-levels))
17473 (setq umax-toc (if (integerp org-export-with-toc)
17474 (min org-export-with-toc umax)
17475 umax))
17477 ;; File header
17478 (insert (format
17479 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
17480 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
17481 <html xmlns=\"http://www.w3.org/1999/xhtml\"
17482 lang=\"%s\" xml:lang=\"%s\">
17483 <head>
17484 <title>%s</title>
17485 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
17486 <meta name=\"generator\" content=\"Org-mode\"/>
17487 <meta name=\"generated\" content=\"%s %s\"/>
17488 <meta name=\"author\" content=\"%s\"/>
17490 </head><body>
17492 language language (org-html-expand title) (or charset "iso-8859-1")
17493 date time author style))
17496 (insert (or (plist-get opt-plist :preamble) ""))
17498 (when (plist-get opt-plist :auto-preamble)
17499 (if title (insert (format org-export-html-title-format
17500 (org-html-expand title))))
17501 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
17503 (if org-export-with-toc
17504 (progn
17505 (insert (format "<h%d>%s</h%d>\n"
17506 org-export-html-toplevel-hlevel
17507 (nth 3 lang-words)
17508 org-export-html-toplevel-hlevel))
17509 (insert "<ul>\n<li>")
17510 (setq lines
17511 (mapcar '(lambda (line)
17512 (if (string-match org-todo-line-regexp line)
17513 ;; This is a headline
17514 (progn
17515 (setq level (- (match-end 1) (match-beginning 1))
17516 level (org-tr-level level)
17517 txt (save-match-data
17518 (org-html-expand
17519 (org-export-cleanup-toc-line
17520 (match-string 3 line))))
17521 todo
17522 (or (and org-export-mark-todo-in-toc
17523 (match-beginning 2)
17524 (not (equal (match-string 2 line)
17525 org-done-string)))
17526 ; TODO, not DONE
17527 (and org-export-mark-todo-in-toc
17528 (= level umax-toc)
17529 (org-search-todo-below
17530 line lines level))))
17531 (if (and (memq org-export-with-tags '(not-in-toc nil))
17532 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
17533 (setq txt (replace-match "" t t txt)))
17534 (if (string-match quote-re0 txt)
17535 (setq txt (replace-match "" t t txt)))
17536 (if org-export-with-section-numbers
17537 (setq txt (concat (org-section-number level)
17538 " " txt)))
17539 (if (<= level umax-toc)
17540 (progn
17541 (setq head-count (+ head-count 1))
17542 (if (> level org-last-level)
17543 (progn
17544 (setq cnt (- level org-last-level))
17545 (while (>= (setq cnt (1- cnt)) 0)
17546 (insert "\n<ul>\n<li>"))
17547 (insert "\n")))
17548 (if (< level org-last-level)
17549 (progn
17550 (setq cnt (- org-last-level level))
17551 (while (>= (setq cnt (1- cnt)) 0)
17552 (insert "</li>\n</ul>"))
17553 (insert "\n")))
17554 ;; Check for targets
17555 (while (string-match org-target-regexp line)
17556 (setq tg (match-string 1 line)
17557 line (replace-match
17558 (concat "@<span class=\"target\">" tg "@</span> ")
17559 t t line))
17560 (push (cons (org-solidify-link-text tg)
17561 (format "sec-%d" head-count))
17562 target-alist))
17563 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
17564 (setq txt (replace-match "" t t txt)))
17565 (insert
17566 (format
17567 (if todo
17568 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
17569 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
17570 head-count txt))
17572 (setq org-last-level level))
17574 line)
17575 lines))
17576 (while (> org-last-level 0)
17577 (setq org-last-level (1- org-last-level))
17578 (insert "</li>\n</ul>\n"))
17580 (setq head-count 0)
17581 (org-init-section-numbers)
17583 (while (setq line (pop lines) origline line)
17584 (catch 'nextline
17586 ;; end of quote section?
17587 (when (and inquote (string-match "^\\*+" line))
17588 (insert "</pre>\n")
17589 (setq inquote nil))
17590 ;; inside a quote section?
17591 (when inquote
17592 (insert (org-html-protect line) "\n")
17593 (throw 'nextline nil))
17595 ;; verbatim lines
17596 (when (and org-export-with-fixed-width
17597 (string-match "^[ \t]*:\\(.*\\)" line))
17598 (when (not infixed)
17599 (setq infixed t)
17600 (insert "<pre>\n"))
17601 (insert (org-html-protect (match-string 1 line)) "\n")
17602 (when (and lines
17603 (not (string-match "^[ \t]*\\(:.*\\)"
17604 (car lines))))
17605 (setq infixed nil)
17606 (insert "</pre>\n"))
17607 (throw 'nextline nil))
17609 ;; Protected HTML
17610 (when (get-text-property 0 'org-protected line)
17611 (insert line "\n")
17612 (throw 'nextline nil))
17614 ;; Horizontal line
17615 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
17616 (insert "\n<hr/>\n")
17617 (throw 'nextline nil))
17619 ;; make targets to anchors
17620 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
17621 (cond
17622 ((match-end 2)
17623 (setq line (replace-match
17624 (concat "@<a name=\""
17625 (org-solidify-link-text (match-string 1 line))
17626 "\">\\nbsp@</a>")
17627 t t line)))
17628 ((and org-export-with-toc (equal (string-to-char line) ?*))
17629 (setq line (replace-match
17630 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
17631 ; (concat "@<i>" (match-string 1 line) "@</i> ")
17632 t t line)))
17634 (setq line (replace-match
17635 (concat "@<a name=\""
17636 (org-solidify-link-text (match-string 1 line))
17637 "\" class=\"target\">" (match-string 1 line) "@</a> ")
17638 t t line)))))
17640 (setq line (org-html-handle-time-stamps line))
17642 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
17643 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
17644 ;; Also handle sub_superscripts and checkboxes
17645 (setq line (org-html-expand line))
17647 ;; Format the links
17648 (setq start 0)
17649 (while (string-match org-bracket-link-analytic-regexp line start)
17650 (setq start (match-beginning 0))
17651 (setq type (if (match-end 2) (match-string 2 line) "internal"))
17652 (setq path (match-string 3 line))
17653 (setq desc1 (if (match-end 5) (match-string 5 line))
17654 desc2 (if (match-end 2) (concat type ":" path) path)
17655 descp (and desc1 (not (equal desc1 desc2)))
17656 desc (or desc1 desc2))
17657 ;; Make an image out of the description if that is so wanted
17658 (when (and descp (org-file-image-p desc))
17659 (save-match-data
17660 (if (string-match "^file:" desc)
17661 (setq desc (substring desc (match-end 0)))))
17662 (setq desc (concat "<img src=\"" desc "\"/>")))
17663 ;; FIXME: do we need to unescape here somewhere?
17664 (cond
17665 ((equal type "internal")
17666 (setq rpl
17667 (concat
17668 "<a href=\"#"
17669 (org-solidify-link-text path target-alist)
17670 "\">" desc "</a>")))
17671 ((member type '("http" "https")) ; FIXME: need to test this.
17672 ;; standard URL, just check if we need to inline an image
17673 (if (and (or (eq t org-export-html-inline-images)
17674 (and org-export-html-inline-images (not descp)))
17675 (org-file-image-p path))
17676 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
17677 (setq link (concat type ":" path))
17678 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
17679 ((member type '("ftp" "mailto" "news"))
17680 ;; standard URL
17681 (setq link (concat type ":" path))
17682 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
17683 ((string= type "file")
17684 ;; FILE link
17685 (let* ((filename path)
17686 (abs-p (file-name-absolute-p filename))
17687 thefile file-is-image-p search)
17688 (save-match-data
17689 (if (string-match "::\\(.*\\)" filename)
17690 (setq search (match-string 1 filename)
17691 filename (replace-match "" t nil filename)))
17692 (setq valid
17693 (if (functionp link-validate)
17694 (funcall link-validate filename current-dir)
17696 (setq file-is-image-p (org-file-image-p filename))
17697 (setq thefile (if abs-p (expand-file-name filename) filename))
17698 (when (and org-export-html-link-org-files-as-html
17699 (string-match "\\.org$" thefile))
17700 (setq thefile (concat (substring thefile 0
17701 (match-beginning 0))
17702 ".html"))
17703 (if (and search
17704 ;; make sure this is can be used as target search
17705 (not (string-match "^[0-9]*$" search))
17706 (not (string-match "^\\*" search))
17707 (not (string-match "^/.*/$" search)))
17708 (setq thefile (concat thefile "#"
17709 (org-solidify-link-text
17710 (org-link-unescape search)))))
17711 (when (string-match "^file:" desc)
17712 (setq desc (replace-match "" t t desc))
17713 (if (string-match "\\.org$" desc)
17714 (setq desc (replace-match "" t t desc))))))
17715 (setq rpl (if (and file-is-image-p
17716 (or (eq t org-export-html-inline-images)
17717 (and org-export-html-inline-images
17718 (not descp))))
17719 (concat "<img src=\"" thefile "\"/>")
17720 (concat "<a href=\"" thefile "\">" desc "</a>")))
17721 (if (not valid) (setq rpl desc))))
17722 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
17723 (setq rpl (concat "<i>&lt;" type ":"
17724 (save-match-data (org-link-unescape path))
17725 "&gt;</i>"))))
17726 (setq line (replace-match rpl t t line)
17727 start (+ start (length rpl))))
17728 ;; TODO items
17729 (if (and (string-match org-todo-line-regexp line)
17730 (match-beginning 2))
17731 (if (equal (match-string 2 line) org-done-string)
17732 (setq line (replace-match
17733 "<span class=\"done\">\\2</span>"
17734 t nil line 2))
17735 (setq line (replace-match "<span class=\"todo\">\\2</span>"
17736 t nil line 2))))
17738 (cond
17739 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
17740 ;; This is a headline
17741 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
17742 txt (match-string 2 line))
17743 (if (string-match quote-re0 txt)
17744 (setq txt (replace-match "" t t txt)))
17745 (if (<= level umax) (setq head-count (+ head-count 1)))
17746 (when in-local-list
17747 ;; Close any local lists before inserting a new header line
17748 (while local-list-num
17749 (org-close-li)
17750 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
17751 (pop local-list-num))
17752 (setq local-list-indent nil
17753 in-local-list nil))
17754 (org-html-level-start level txt umax
17755 (and org-export-with-toc (<= level umax))
17756 head-count)
17757 ;; QUOTES
17758 (when (string-match quote-re line)
17759 (insert "<pre>")
17760 (setq inquote t)))
17762 ((and org-export-with-tables
17763 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
17764 (if (not table-open)
17765 ;; New table starts
17766 (setq table-open t table-buffer nil table-orig-buffer nil))
17767 ;; Accumulate lines
17768 (setq table-buffer (cons line table-buffer)
17769 table-orig-buffer (cons origline table-orig-buffer))
17770 (when (or (not lines)
17771 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
17772 (car lines))))
17773 (setq table-open nil
17774 table-buffer (nreverse table-buffer)
17775 table-orig-buffer (nreverse table-orig-buffer))
17776 (org-close-par-maybe)
17777 (insert (org-format-table-html table-buffer table-orig-buffer))))
17779 ;; Normal lines
17780 (when (string-match
17781 (cond
17782 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
17783 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
17784 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
17785 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
17786 line)
17787 (setq ind (org-get-string-indentation line)
17788 start-is-num (match-beginning 4)
17789 starter (if (match-beginning 2)
17790 (substring (match-string 2 line) 0 -1))
17791 line (substring line (match-beginning 5)))
17792 (unless (string-match "[^ \t]" line)
17793 ;; empty line. Pretend indentation is large.
17794 (setq ind (1+ (or (car local-list-indent) 1))))
17795 (while (and in-local-list
17796 (or (and (= ind (car local-list-indent))
17797 (not starter))
17798 (< ind (car local-list-indent))))
17799 (org-close-li)
17800 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
17801 (pop local-list-num) (pop local-list-indent)
17802 (setq in-local-list local-list-indent))
17803 (cond
17804 ((and starter
17805 (or (not in-local-list)
17806 (> ind (car local-list-indent))))
17807 ;; Start new (level of ) list
17808 (org-close-par-maybe)
17809 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
17810 (push start-is-num local-list-num)
17811 (push ind local-list-indent)
17812 (setq in-local-list t))
17813 (starter
17814 ;; continue current list
17815 (org-close-li)
17816 (insert "<li>\n")))
17817 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
17818 (setq line
17819 (replace-match
17820 (if (equal (match-string 1 line) "X")
17821 "<b>[X]</b>"
17822 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
17823 t t line))))
17825 ;; Empty lines start a new paragraph. If hand-formatted lists
17826 ;; are not fully interpreted, lines starting with "-", "+", "*"
17827 ;; also start a new paragraph.
17828 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
17830 ;; Check if the line break needs to be conserved
17831 (cond
17832 ((string-match "\\\\\\\\[ \t]*$" line)
17833 (setq line (replace-match "<br/>" t t line)))
17834 (org-export-preserve-breaks
17835 (setq line (concat line "<br/>"))))
17837 (insert line "\n")))))
17839 ;; Properly close all local lists and other lists
17840 (when inquote (insert "</pre>\n"))
17841 (when in-local-list
17842 ;; Close any local lists before inserting a new header line
17843 (while local-list-num
17844 (org-close-li)
17845 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
17846 (pop local-list-num))
17847 (setq local-list-indent nil
17848 in-local-list nil))
17849 (org-html-level-start 1 nil umax
17850 (and org-export-with-toc (<= level umax))
17851 head-count)
17853 (when (plist-get opt-plist :auto-postamble)
17854 (when author
17855 (insert "<p class=\"author\"> "
17856 (nth 1 lang-words) ": " author "\n")
17857 (when email
17858 (insert "<a href=\"mailto:" email "\">&lt;"
17859 email "&gt;</a>\n"))
17860 (insert "</p>\n"))
17861 (when (and date time)
17862 (insert "<p class=\"date\"> "
17863 (nth 2 lang-words) ": "
17864 date " " time "</p>\n")))
17866 (if org-export-html-with-timestamp
17867 (insert org-export-html-html-helper-timestamp))
17868 (insert (or (plist-get opt-plist :postamble) ""))
17869 (insert "</body>\n</html>\n")
17870 (normal-mode)
17871 ;; remove empty paragraphs and lists
17872 (goto-char (point-min))
17873 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
17874 (replace-match ""))
17875 (goto-char (point-min))
17876 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
17877 (replace-match ""))
17878 (save-buffer)
17879 (goto-char (point-min))
17880 (message "Exporting... done"))))
17883 (defun org-format-table-html (lines olines)
17884 "Find out which HTML converter to use and return the HTML code."
17885 (if (string-match "^[ \t]*|" (car lines))
17886 ;; A normal org table
17887 (org-format-org-table-html lines)
17888 ;; Table made by table.el - test for spanning
17889 (let* ((hlines (delq nil (mapcar
17890 (lambda (x)
17891 (if (string-match "^[ \t]*\\+-" x) x
17892 nil))
17893 lines)))
17894 (first (car hlines))
17895 (ll (and (string-match "\\S-+" first)
17896 (match-string 0 first)))
17897 (re (concat "^[ \t]*" (regexp-quote ll)))
17898 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
17899 hlines))))
17900 (if (and (not spanning)
17901 (not org-export-prefer-native-exporter-for-tables))
17902 ;; We can use my own converter with HTML conversions
17903 (org-format-table-table-html lines)
17904 ;; Need to use the code generator in table.el, with the original text.
17905 (org-format-table-table-html-using-table-generate-source olines)))))
17907 (defun org-format-org-table-html (lines &optional splice)
17908 "Format a table into HTML."
17909 ;; Get rid of hlines at beginning and end
17910 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
17911 (setq lines (nreverse lines))
17912 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
17913 (setq lines (nreverse lines))
17914 (when org-export-table-remove-special-lines
17915 ;; Check if the table has a marking column. If yes remove the
17916 ;; column and the special lines
17917 (setq lines (org-table-clean-before-export lines)))
17919 (let ((head (and org-export-highlight-first-table-line
17920 (delq nil (mapcar
17921 (lambda (x) (string-match "^[ \t]*|-" x))
17922 (cdr lines)))))
17923 (nlines 0) fnum i
17924 tbopen line fields html)
17925 (if splice (setq head nil))
17926 (unless splice (push (if head "<thead>" "<tbody>") html))
17927 (setq tbopen t)
17928 (while (setq line (pop lines))
17929 (catch 'next-line
17930 (if (string-match "^[ \t]*|-" line)
17931 (progn
17932 (unless splice
17933 (push (if head "</thead>" "</tbody>") html)
17934 (if lines (push "<tbody>" html) (setq tbopen nil)))
17935 (setq head nil) ;; head ends here, first time around
17936 ;; ignore this line
17937 (throw 'next-line t)))
17938 ;; Break the line into fields
17939 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
17940 (unless fnum (setq fnum (make-vector (length fields) 0)))
17941 (setq nlines (1+ nlines) i -1)
17942 (push (concat "<tr>"
17943 (mapconcat
17944 (lambda (x)
17945 (setq i (1+ i))
17946 (if (and (< i nlines)
17947 (string-match org-table-number-regexp x))
17948 (incf (aref fnum i)))
17949 (if head
17950 (concat "<th>" x "</th>")
17951 (concat "<td>" x "</td>")))
17952 fields "")
17953 "</tr>")
17954 html)))
17955 (unless splice (if tbopen (push "</tbody>" html)))
17956 (unless splice (push "</table>\n" html))
17957 (setq html (nreverse html))
17958 (unless splice
17959 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
17960 (push (mapconcat
17961 (lambda (x)
17962 (format "<COL align=\"%s\">"
17963 (if (> (/ (float x) nlines) org-table-number-fraction)
17964 "right" "left")))
17965 fnum "")
17966 html)
17967 (push org-export-html-table-tag html))
17968 (concat (mapconcat 'identity html "\n") "\n")))
17970 (defun org-table-clean-before-export (lines)
17971 "Check if the table has a marking column.
17972 If yes remove the column and the special lines."
17973 (if (memq nil
17974 (mapcar
17975 (lambda (x) (or (string-match "^[ \t]*|-" x)
17976 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
17977 lines))
17978 (progn
17979 (setq org-table-clean-did-remove-column-1 nil)
17980 lines)
17981 (setq org-table-clean-did-remove-column-1 t)
17982 (delq nil
17983 (mapcar
17984 (lambda (x) (if (string-match "^[ \t]*| *[!_^/] *|" x)
17985 nil ; ignore this line
17986 (and (or (string-match "^[ \t]*|-+\\+" x)
17987 (string-match "^[ \t]*|[^|]*|" x))
17988 (replace-match "|" t t x))))
17989 lines))))
17991 (defun org-fake-empty-table-line (line)
17992 "Replace everything except \"|\" with spaces."
17993 (let ((i (length line))
17994 (newstr (copy-sequence line)))
17995 (while (> i 0)
17996 (setq i (1- i))
17997 (if (not (eq (aref newstr i) ?|))
17998 (aset newstr i ?\ )))
17999 newstr))
18001 (defun org-format-table-table-html (lines)
18002 "Format a table generated by table.el into HTML.
18003 This conversion does *not* use `table-generate-source' from table.el.
18004 This has the advantage that Org-mode's HTML conversions can be used.
18005 But it has the disadvantage, that no cell- or row-spanning is allowed."
18006 (let (line field-buffer
18007 (head org-export-highlight-first-table-line)
18008 fields html empty)
18009 (setq html (concat org-export-html-table-tag "\n"))
18010 (while (setq line (pop lines))
18011 (setq empty "&nbsp;")
18012 (catch 'next-line
18013 (if (string-match "^[ \t]*\\+-" line)
18014 (progn
18015 (if field-buffer
18016 (progn
18017 (setq html (concat
18018 html
18019 "<tr>"
18020 (mapconcat
18021 (lambda (x)
18022 (if (equal x "") (setq x empty))
18023 (if head
18024 (concat "<th>" x "</th>\n")
18025 (concat "<td>" x "</td>\n")))
18026 field-buffer "\n")
18027 "</tr>\n"))
18028 (setq head nil)
18029 (setq field-buffer nil)))
18030 ;; Ignore this line
18031 (throw 'next-line t)))
18032 ;; Break the line into fields and store the fields
18033 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
18034 (if field-buffer
18035 (setq field-buffer (mapcar
18036 (lambda (x)
18037 (concat x "<br/>" (pop fields)))
18038 field-buffer))
18039 (setq field-buffer fields))))
18040 (setq html (concat html "</table>\n"))
18041 html))
18043 (defun org-format-table-table-html-using-table-generate-source (lines)
18044 "Format a table into html, using `table-generate-source' from table.el.
18045 This has the advantage that cell- or row-spanning is allowed.
18046 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
18047 (require 'table)
18048 (with-current-buffer (get-buffer-create " org-tmp1 ")
18049 (erase-buffer)
18050 (insert (mapconcat 'identity lines "\n"))
18051 (goto-char (point-min))
18052 (if (not (re-search-forward "|[^+]" nil t))
18053 (error "Error processing table"))
18054 (table-recognize-table)
18055 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
18056 (table-generate-source 'html " org-tmp2 ")
18057 (set-buffer " org-tmp2 ")
18058 (buffer-substring (point-min) (point-max))))
18060 (defun org-html-handle-time-stamps (s)
18061 "Format time stamps in string S, or remove them."
18062 (catch 'exit
18063 (let (r b)
18064 (while (string-match org-maybe-keyword-time-regexp s)
18065 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
18066 ;; never export CLOCK
18067 (throw 'exit ""))
18068 (or b (setq b (substring s 0 (match-beginning 0))))
18069 (if (not org-export-with-timestamps)
18070 (setq r (concat r (substring s 0 (match-beginning 0)))
18071 s (substring s (match-end 0)))
18072 (setq r (concat
18073 r (substring s 0 (match-beginning 0))
18074 (if (match-end 1)
18075 (format "@<span class=\"timestamp-kwd\">%s @</span>"
18076 (match-string 1 s)))
18077 (format " @<span class=\"timestamp\">%s@</span>"
18078 (substring
18079 (org-translate-time (match-string 3 s)) 1 -1)))
18080 s (substring s (match-end 0)))))
18081 ;; Line break if line started and ended with time stamp stuff
18082 (if (not r)
18084 (setq r (concat r s))
18085 (unless (string-match "\\S-" (concat b s))
18086 (setq r (concat r "@<br/>")))
18087 r))))
18089 (defun org-html-protect (s)
18090 ;; convert & to &amp;, < to &lt; and > to &gt;
18091 (let ((start 0))
18092 (while (string-match "&" s start)
18093 (setq s (replace-match "&amp;" t t s)
18094 start (1+ (match-beginning 0))))
18095 (while (string-match "<" s)
18096 (setq s (replace-match "&lt;" t t s)))
18097 (while (string-match ">" s)
18098 (setq s (replace-match "&gt;" t t s))))
18101 (defun org-export-cleanup-toc-line (s)
18102 "Remove tags and time staps from lines going into the toc."
18103 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
18104 (setq s (replace-match "" t t s)))
18105 (when org-export-remove-timestamps-from-toc
18106 (while (string-match org-maybe-keyword-time-regexp s)
18107 (setq s (replace-match "" t t s))))
18110 (defun org-html-expand (string)
18111 "Prepare STRING for HTML export. Applies all active conversions.
18112 If there are links in the string, don't modify these."
18113 (let* (m s l res)
18114 (while (setq m (string-match org-bracket-link-regexp string))
18115 (setq s (substring string 0 m)
18116 l (match-string 0 string)
18117 string (substring string (match-end 0)))
18118 (push (org-html-do-expand s) res)
18119 (push l res))
18120 (push (org-html-do-expand string) res)
18121 (apply 'concat (nreverse res))))
18123 (defun org-html-do-expand (s)
18124 "Apply all active conversions to translate special ASCII to HTML."
18125 (setq s (org-html-protect s))
18126 (if org-export-html-expand
18127 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
18128 (setq s (replace-match "<\\1>" t nil s))))
18129 (if org-export-with-emphasize
18130 (setq s (org-export-html-convert-emphasize s)))
18131 (if org-export-with-sub-superscripts
18132 (setq s (org-export-html-convert-sub-super s)))
18133 (if org-export-with-TeX-macros
18134 (let ((start 0) wd ass)
18135 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
18136 (setq wd (match-string 1 s))
18137 (if (setq ass (assoc wd org-html-entities))
18138 (setq s (replace-match (or (cdr ass)
18139 (concat "&" (car ass) ";"))
18140 t t s))
18141 (setq start (+ start (length wd)))))))
18144 (defun org-create-multibrace-regexp (left right n)
18145 "Create a regular expression which will match a balanced sexp.
18146 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
18147 as single character strings.
18148 The regexp returned will match the entire expression including the
18149 delimiters. It will also define a single group which contains the
18150 match except for the outermost delimiters. The maximum depth of
18151 stacked delimiters is N. Escaping delimiters is not possible."
18152 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
18153 (or "\\|")
18154 (re nothing)
18155 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
18156 (while (> n 1)
18157 (setq n (1- n)
18158 re (concat re or next)
18159 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
18160 (concat left "\\(" re "\\)" right)))
18162 (defvar org-match-substring-regexp
18163 (concat
18164 "\\([^\\]\\)\\([_^]\\)\\("
18165 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
18166 "\\|"
18167 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
18168 "\\|"
18169 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
18170 "The regular expression matching a sub- or superscript.")
18172 (defun org-export-html-convert-sub-super (string)
18173 "Convert sub- and superscripts in STRING to HTML."
18174 (let (key c)
18175 (while (string-match org-match-substring-regexp string)
18176 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
18177 (setq c (or (match-string 8 string)
18178 (match-string 6 string)
18179 (match-string 5 string)))
18180 (setq string (replace-match
18181 (concat (match-string 1 string)
18182 "<" key ">" c "</" key ">")
18183 t t string)))
18184 (while (string-match "\\\\\\([_^]\\)" string)
18185 (setq string (replace-match (match-string 1 string) t t string))))
18186 string)
18188 (defun org-export-html-convert-emphasize (string)
18189 "Apply emphasis."
18190 (while (string-match org-emph-re string)
18191 (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)))
18192 string)
18194 (defvar org-par-open nil)
18195 (defun org-open-par ()
18196 "Insert <p>, but first close previous paragraph if any."
18197 (org-close-par-maybe)
18198 (insert "\n<p>")
18199 (setq org-par-open t))
18200 (defun org-close-par-maybe ()
18201 "Close paragraph if there is one open."
18202 (when org-par-open
18203 (insert "</p>")
18204 (setq org-par-open nil)))
18205 (defun org-close-li ()
18206 "Close <li> if necessary."
18207 (org-close-par-maybe)
18208 (insert "</li>\n"))
18209 ; (when (save-excursion
18210 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
18211 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
18212 ; (insert "</li>"))))
18214 (defun org-html-level-start (level title umax with-toc head-count)
18215 "Insert a new level in HTML export.
18216 When TITLE is nil, just close all open levels."
18217 (org-close-par-maybe)
18218 (let ((l (1+ (max level umax))))
18219 (while (<= l org-level-max)
18220 (if (aref org-levels-open (1- l))
18221 (progn
18222 (org-html-level-close l)
18223 (aset org-levels-open (1- l) nil)))
18224 (setq l (1+ l)))
18225 (when title
18226 ;; If title is nil, this means this function is called to close
18227 ;; all levels, so the rest is done only if title is given
18228 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
18229 (setq title (replace-match
18230 (if org-export-with-tags
18231 (save-match-data
18232 (concat
18233 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
18234 (mapconcat 'identity (org-split-string
18235 (match-string 1 title) ":")
18236 "&nbsp;")
18237 "</span>"))
18239 t t title)))
18240 (if (> level umax)
18241 (progn
18242 (if (aref org-levels-open (1- level))
18243 (progn
18244 (org-close-li)
18245 (insert "<li>" title "<br/>\n"))
18246 (aset org-levels-open (1- level) t)
18247 (org-close-par-maybe)
18248 (insert "<ul>\n<li>" title "<br/>\n")))
18249 (if org-export-with-section-numbers
18250 (setq title (concat (org-section-number level) " " title)))
18251 (setq level (+ level org-export-html-toplevel-hlevel -1))
18252 (if with-toc
18253 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
18254 level head-count title level))
18255 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
18256 (org-open-par)))))
18258 (defun org-html-level-close (&rest args)
18259 "Terminate one level in HTML export."
18260 (org-close-li)
18261 (insert "</ul>"))
18263 ;;; iCalendar export
18265 ;;;###autoload
18266 (defun org-export-icalendar-this-file ()
18267 "Export current file as an iCalendar file.
18268 The iCalendar file will be located in the same directory as the Org-mode
18269 file, but with extension `.ics'."
18270 (interactive)
18271 (org-export-icalendar nil buffer-file-name))
18273 ;;;###autoload
18274 (defun org-export-icalendar-all-agenda-files ()
18275 "Export all files in `org-agenda-files' to iCalendar .ics files.
18276 Each iCalendar file will be located in the same directory as the Org-mode
18277 file, but with extension `.ics'."
18278 (interactive)
18279 (apply 'org-export-icalendar nil (org-agenda-files t)))
18281 ;;;###autoload
18282 (defun org-export-icalendar-combine-agenda-files ()
18283 "Export all files in `org-agenda-files' to a single combined iCalendar file.
18284 The file is stored under the name `org-combined-agenda-icalendar-file'."
18285 (interactive)
18286 (apply 'org-export-icalendar t (org-agenda-files t)))
18288 (defun org-export-icalendar (combine &rest files)
18289 "Create iCalendar files for all elements of FILES.
18290 If COMBINE is non-nil, combine all calendar entries into a single large
18291 file and store it under the name `org-combined-agenda-icalendar-file'."
18292 (save-excursion
18293 (let* ((dir (org-export-directory
18294 :ical (list :publishing-directory
18295 org-export-publishing-directory)))
18296 file ical-file ical-buffer category started org-agenda-new-buffers)
18298 (when combine
18299 (setq ical-file
18300 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
18301 org-combined-agenda-icalendar-file
18302 (expand-file-name org-combined-agenda-icalendar-file dir))
18303 ical-buffer (org-get-agenda-file-buffer ical-file))
18304 (set-buffer ical-buffer) (erase-buffer))
18305 (while (setq file (pop files))
18306 (catch 'nextfile
18307 (org-check-agenda-file file)
18308 (set-buffer (org-get-agenda-file-buffer file))
18309 (unless combine
18310 (setq ical-file (concat (file-name-as-directory dir)
18311 (file-name-sans-extension
18312 (file-name-nondirectory buffer-file-name))
18313 ".ics"))
18314 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
18315 (with-current-buffer ical-buffer (erase-buffer)))
18316 (setq category (or org-category
18317 (file-name-sans-extension
18318 (file-name-nondirectory buffer-file-name))))
18319 (if (symbolp category) (setq category (symbol-name category)))
18320 (let ((standard-output ical-buffer))
18321 (if combine
18322 (and (not started) (setq started t)
18323 (org-start-icalendar-file org-icalendar-combined-name))
18324 (org-start-icalendar-file category))
18325 (org-print-icalendar-entries combine)
18326 (when (or (and combine (not files)) (not combine))
18327 (org-finish-icalendar-file)
18328 (set-buffer ical-buffer)
18329 (save-buffer)
18330 (run-hooks 'org-after-save-iCalendar-file-hook)))))
18331 (org-release-buffers org-agenda-new-buffers))))
18333 (defvar org-after-save-iCalendar-file-hook nil
18334 "Hook run after an iCalendar file has been saved.
18335 The iCalendar buffer is still current when this hook is run.
18336 A good way to use this is to tell a desktop calenndar application to re-read
18337 the iCalendar file.")
18339 (defun org-print-icalendar-entries (&optional combine)
18340 "Print iCalendar entries for the current Org-mode file to `standard-output'.
18341 When COMBINE is non nil, add the category to each line."
18342 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
18343 (org-category-table (org-get-category-table))
18344 (dts (org-ical-ts-to-string
18345 (format-time-string (cdr org-time-stamp-formats) (current-time))
18346 "DTSTART"))
18347 hd ts ts2 state status (inc t) pos
18348 scheduledp deadlinep tmp pri category)
18349 (save-excursion
18350 (goto-char (point-min))
18351 (while (re-search-forward org-ts-regexp nil t)
18352 (setq pos (match-beginning 0)
18353 ts (match-string 0)
18354 inc t
18355 hd (org-get-heading)
18356 category (org-get-category))
18357 (if (looking-at re2)
18358 (progn
18359 (goto-char (match-end 0))
18360 (setq ts2 (match-string 1) inc nil))
18361 (setq ts2 ts
18362 tmp (buffer-substring (max (point-min)
18363 (- pos org-ds-keyword-length))
18364 pos)
18365 deadlinep (string-match org-deadline-regexp tmp)
18366 scheduledp (string-match org-scheduled-regexp tmp)
18367 ;; donep (org-entry-is-done-p)
18369 (if (or (string-match org-tr-regexp hd)
18370 (string-match org-ts-regexp hd))
18371 (setq hd (replace-match "" t t hd)))
18372 (if (string-match org-bracket-link-regexp hd)
18373 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
18374 (match-string 1 hd))
18375 t t hd)))
18376 (if deadlinep (setq hd (concat "DL: " hd)))
18377 (if scheduledp (setq hd (concat "S: " hd)))
18378 (princ (format "BEGIN:VEVENT
18381 SUMMARY:%s
18382 CATEGORIES:%s
18383 END:VEVENT\n"
18384 (org-ical-ts-to-string ts "DTSTART")
18385 (org-ical-ts-to-string ts2 "DTEND" inc)
18386 hd category)))
18387 (when org-icalendar-include-todo
18388 (goto-char (point-min))
18389 (while (re-search-forward org-todo-line-regexp nil t)
18390 (setq state (match-string 2))
18391 (setq status (if (equal state org-done-string)
18392 "COMPLETED" "NEEDS-ACTION"))
18393 (when (and state
18394 (or (not (equal state org-done-string))
18395 (eq org-icalendar-include-todo 'all)))
18396 (setq hd (match-string 3))
18397 (if (string-match org-priority-regexp hd)
18398 (setq pri (string-to-char (match-string 2 hd))
18399 hd (concat (substring hd 0 (match-beginning 1))
18400 (substring hd (match-end 1))))
18401 (setq pri org-default-priority))
18402 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
18403 (- org-lowest-priority ?A))))))
18405 (princ (format "BEGIN:VTODO
18407 SUMMARY:%s
18408 CATEGORIES:%s
18409 SEQUENCE:1
18410 PRIORITY:%d
18411 STATUS:%s
18412 END:VTODO\n"
18413 dts hd category pri status))))))))
18415 (defun org-start-icalendar-file (name)
18416 "Start an iCalendar file by inserting the header."
18417 (let ((user user-full-name)
18418 (name (or name "unknown"))
18419 (timezone (cadr (current-time-zone))))
18420 (princ
18421 (format "BEGIN:VCALENDAR
18422 VERSION:2.0
18423 X-WR-CALNAME:%s
18424 PRODID:-//%s//Emacs with Org-mode//EN
18425 X-WR-TIMEZONE:%s
18426 CALSCALE:GREGORIAN\n" name user timezone))))
18428 (defun org-finish-icalendar-file ()
18429 "Finish an iCalendar file by inserting the END statement."
18430 (princ "END:VCALENDAR\n"))
18432 (defun org-ical-ts-to-string (s keyword &optional inc)
18433 "Take a time string S and convert it to iCalendar format.
18434 KEYWORD is added in front, to make a complete line like DTSTART....
18435 When INC is non-nil, increase the hour by two (if time string contains
18436 a time), or the day by one (if it does not contain a time)."
18437 (let ((t1 (org-parse-time-string s 'nodefault))
18438 t2 fmt have-time time)
18439 (if (and (car t1) (nth 1 t1) (nth 2 t1))
18440 (setq t2 t1 have-time t)
18441 (setq t2 (org-parse-time-string s)))
18442 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
18443 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
18444 (when inc
18445 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
18446 (setq time (encode-time s mi h d m y)))
18447 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
18448 (concat keyword (format-time-string fmt time))))
18450 ;;; XOXO export
18452 (defun org-export-as-xoxo-insert-into (buffer &rest output)
18453 (with-current-buffer buffer
18454 (apply 'insert output)))
18455 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
18457 (defun org-export-as-xoxo (&optional buffer)
18458 "Export the org buffer as XOXO.
18459 The XOXO buffer is named *xoxo-<source buffer name>*"
18460 (interactive (list (current-buffer)))
18461 ;; A quickie abstraction
18463 ;; Output everything as XOXO
18464 (with-current-buffer (get-buffer buffer)
18465 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
18466 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
18467 (org-infile-export-plist)))
18468 (filename (concat (file-name-as-directory
18469 (org-export-directory :xoxo opt-plist))
18470 (file-name-sans-extension
18471 (file-name-nondirectory buffer-file-name))
18472 ".html"))
18473 (out (find-file-noselect filename))
18474 (last-level 1)
18475 (hanging-li nil))
18476 ;; Check the output buffer is empty.
18477 (with-current-buffer out (erase-buffer))
18478 ;; Kick off the output
18479 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
18480 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
18481 (let* ((hd (match-string-no-properties 1))
18482 (level (length hd))
18483 (text (concat
18484 (match-string-no-properties 2)
18485 (save-excursion
18486 (goto-char (match-end 0))
18487 (let ((str ""))
18488 (catch 'loop
18489 (while 't
18490 (forward-line)
18491 (if (looking-at "^[ \t]\\(.*\\)")
18492 (setq str (concat str (match-string-no-properties 1)))
18493 (throw 'loop str)))))))))
18495 ;; Handle level rendering
18496 (cond
18497 ((> level last-level)
18498 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
18500 ((< level last-level)
18501 (dotimes (- (- last-level level) 1)
18502 (if hanging-li
18503 (org-export-as-xoxo-insert-into out "</li>\n"))
18504 (org-export-as-xoxo-insert-into out "</ol>\n"))
18505 (when hanging-li
18506 (org-export-as-xoxo-insert-into out "</li>\n")
18507 (setq hanging-li nil)))
18509 ((equal level last-level)
18510 (if hanging-li
18511 (org-export-as-xoxo-insert-into out "</li>\n")))
18514 (setq last-level level)
18516 ;; And output the new li
18517 (setq hanging-li 't)
18518 (if (equal ?+ (elt text 0))
18519 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
18520 (org-export-as-xoxo-insert-into out "<li>" text))))
18522 ;; Finally finish off the ol
18523 (dotimes (- last-level 1)
18524 (if hanging-li
18525 (org-export-as-xoxo-insert-into out "</li>\n"))
18526 (org-export-as-xoxo-insert-into out "</ol>\n"))
18528 ;; Finish the buffer off and clean it up.
18529 (switch-to-buffer-other-window out)
18530 (indent-region (point-min) (point-max) nil)
18531 (save-buffer)
18532 (goto-char (point-min))
18536 ;;;; Key bindings
18538 ;; - Bindings in Org-mode map are currently
18539 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
18540 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
18541 ;; e (?) useful from outline-mode
18542 ;; i k @ expendable from outline-mode
18543 ;; 0123456789 % & ()_{} " ` free
18545 ;; Make `C-c C-x' a prefix key
18546 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
18548 ;; TAB key with modifiers
18549 (define-key org-mode-map "\C-i" 'org-cycle)
18550 (define-key org-mode-map [(tab)] 'org-cycle)
18551 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
18552 (define-key org-mode-map [(meta tab)] 'org-complete)
18553 (define-key org-mode-map "\M-\t" 'org-complete)
18554 (define-key org-mode-map "\M-\C-i" 'org-complete)
18555 ;; The following line is necessary under Suse GNU/Linux
18556 (unless (featurep 'xemacs)
18557 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
18558 (define-key org-mode-map [(shift tab)] 'org-shifttab)
18560 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
18561 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18562 (define-key org-mode-map [(meta return)] 'org-meta-return)
18564 ;; Cursor keys with modifiers
18565 (define-key org-mode-map [(meta left)] 'org-metaleft)
18566 (define-key org-mode-map [(meta right)] 'org-metaright)
18567 (define-key org-mode-map [(meta up)] 'org-metaup)
18568 (define-key org-mode-map [(meta down)] 'org-metadown)
18570 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18571 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
18572 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
18573 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
18575 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
18576 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
18577 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
18578 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
18580 ;;; Extra keys for tty access.
18581 ;; We only set them when really needed because otherwise the
18582 ;; menus don't show the simple keys
18584 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18585 (not window-system))
18586 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18587 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18588 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return)
18589 (define-key org-mode-map [?\e (return)] 'org-meta-return)
18590 (define-key org-mode-map [?\e (left)] 'org-metaleft)
18591 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft)
18592 (define-key org-mode-map [?\e (right)] 'org-metaright)
18593 (define-key org-mode-map "\C-c\C-xr" 'org-metaright)
18594 (define-key org-mode-map [?\e (up)] 'org-metaup)
18595 (define-key org-mode-map "\C-c\C-xu" 'org-metaup)
18596 (define-key org-mode-map [?\e (down)] 'org-metadown)
18597 (define-key org-mode-map "\C-c\C-xd" 'org-metadown)
18598 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18599 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18600 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18601 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18602 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
18603 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
18604 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
18605 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
18607 ;; All the other keys
18609 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18610 (define-key org-mode-map "\C-c\C-r" 'org-reveal)
18611 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
18612 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
18613 (define-key org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18614 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
18615 (define-key org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18616 (define-key org-mode-map "\C-c\C-j" 'org-goto)
18617 (define-key org-mode-map "\C-c\C-t" 'org-todo)
18618 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
18619 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
18620 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
18621 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
18622 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
18623 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
18624 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
18625 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
18626 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
18627 (define-key org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18628 (define-key org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18629 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
18630 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
18631 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
18632 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
18633 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
18634 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18635 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18636 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18637 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18638 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
18639 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
18640 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18641 (define-key org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18642 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
18643 (define-key org-mode-map "\C-c]" 'org-remove-file)
18644 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
18645 (define-key org-mode-map "\C-c^" 'org-sort)
18646 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18647 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
18648 (define-key org-mode-map "\C-m" 'org-return)
18649 (define-key org-mode-map "\C-c?" 'org-table-field-info)
18650 (define-key org-mode-map "\C-c " 'org-table-blank-field)
18651 (define-key org-mode-map "\C-c+" 'org-table-sum)
18652 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
18653 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
18654 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
18655 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18656 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
18657 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18658 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
18659 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
18660 (define-key org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18661 (define-key org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18662 (define-key org-mode-map "\C-c\C-e" 'org-export)
18663 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18665 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
18666 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18667 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18668 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18670 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18671 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18672 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18673 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
18674 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18675 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18676 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18677 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18678 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18680 (when (featurep 'xemacs)
18681 (define-key org-mode-map 'button3 'popup-mode-menu))
18683 (defsubst org-table-p () (org-at-table-p))
18685 (defun org-self-insert-command (N)
18686 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18687 If the cursor is in a table looking at whitespace, the whitespace is
18688 overwritten, and the table is not marked as requiring realignment."
18689 (interactive "p")
18690 (if (and (org-table-p)
18691 (progn
18692 ;; check if we blank the field, and if that triggers align
18693 (and org-table-auto-blank-field
18694 (member last-command
18695 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
18696 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18697 ;; got extra space, this field does not determine column width
18698 (let (org-table-may-need-update) (org-table-blank-field))
18699 ;; no extra space, this field may determine column width
18700 (org-table-blank-field)))
18702 (eq N 1)
18703 (looking-at "[^|\n]* |"))
18704 (let (org-table-may-need-update)
18705 (goto-char (1- (match-end 0)))
18706 (delete-backward-char 1)
18707 (goto-char (match-beginning 0))
18708 (self-insert-command N))
18709 (setq org-table-may-need-update t)
18710 (self-insert-command N)))
18712 (defun org-delete-backward-char (N)
18713 "Like `delete-backward-char', insert whitespace at field end in tables.
18714 When deleting backwards, in tables this function will insert whitespace in
18715 front of the next \"|\" separator, to keep the table aligned. The table will
18716 still be marked for re-alignment if the field did fill the entire column,
18717 because, in this case the deletion might narrow the column."
18718 (interactive "p")
18719 (if (and (org-table-p)
18720 (eq N 1)
18721 (string-match "|" (buffer-substring (point-at-bol) (point)))
18722 (looking-at ".*?|"))
18723 (let ((pos (point))
18724 (noalign (looking-at "[^|\n\r]* |"))
18725 (c org-table-may-need-update))
18726 (backward-delete-char N)
18727 (skip-chars-forward "^|")
18728 (insert " ")
18729 (goto-char (1- pos))
18730 ;; noalign: if there were two spaces at the end, this field
18731 ;; does not determine the width of the column.
18732 (if noalign (setq org-table-may-need-update c)))
18733 (backward-delete-char N)))
18735 (defun org-delete-char (N)
18736 "Like `delete-char', but insert whitespace at field end in tables.
18737 When deleting characters, in tables this function will insert whitespace in
18738 front of the next \"|\" separator, to keep the table aligned. The table will
18739 still be marked for re-alignment if the field did fill the entire column,
18740 because, in this case the deletion might narrow the column."
18741 (interactive "p")
18742 (if (and (org-table-p)
18743 (not (bolp))
18744 (not (= (char-after) ?|))
18745 (eq N 1))
18746 (if (looking-at ".*?|")
18747 (let ((pos (point))
18748 (noalign (looking-at "[^|\n\r]* |"))
18749 (c org-table-may-need-update))
18750 (replace-match (concat
18751 (substring (match-string 0) 1 -1)
18752 " |"))
18753 (goto-char pos)
18754 ;; noalign: if there were two spaces at the end, this field
18755 ;; does not determine the width of the column.
18756 (if noalign (setq org-table-may-need-update c)))
18757 (delete-char N))
18758 (delete-char N)))
18760 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18761 (put 'org-self-insert-command 'delete-selection t)
18762 (put 'orgtbl-self-insert-command 'delete-selection t)
18763 (put 'org-delete-char 'delete-selection 'supersede)
18764 (put 'org-delete-backward-char 'delete-selection 'supersede)
18766 ;; How to do this: Measure non-white length of current string
18767 ;; If equal to column width, we should realign.
18769 (defun org-remap (map &rest commands)
18770 "In MAP, remap the functions given in COMMANDS.
18771 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18772 (let (new old)
18773 (while commands
18774 (setq old (pop commands) new (pop commands))
18775 (if (fboundp 'command-remapping)
18776 (define-key map (vector 'remap old) new)
18777 (substitute-key-definition old new map global-map)))))
18779 (when (eq org-enable-table-editor 'optimized)
18780 ;; If the user wants maximum table support, we need to hijack
18781 ;; some standard editing functions
18782 (org-remap org-mode-map
18783 'self-insert-command 'org-self-insert-command
18784 'delete-char 'org-delete-char
18785 'delete-backward-char 'org-delete-backward-char)
18786 (define-key org-mode-map "|" 'org-force-self-insert))
18788 (defun org-shiftcursor-error ()
18789 "Throw an error because Shift-Cursor command was applied in wrong context."
18790 (error "This command is active in special context like tables, headlines or timestamps"))
18792 (defun org-shifttab (&optional arg)
18793 "Global visibility cycling or move to previous table field.
18794 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18795 on context.
18796 See the individual commands for more information."
18797 (interactive "P")
18798 (cond
18799 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18800 (arg (message "Content view to level: ")
18801 (org-content (prefix-numeric-value arg))
18802 (setq org-cycle-global-status 'overview))
18803 (t (call-interactively 'org-global-cycle))))
18805 (defun org-shiftmetaleft ()
18806 "Promote subtree or delete table column.
18807 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
18808 See the individual commands for more information."
18809 (interactive)
18810 (cond
18811 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18812 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
18813 ((org-at-item-p) (call-interactively 'org-outdent-item))
18814 (t (org-shiftcursor-error))))
18816 (defun org-shiftmetaright ()
18817 "Demote subtree or insert table column.
18818 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
18819 See the individual commands for more information."
18820 (interactive)
18821 (cond
18822 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18823 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
18824 ((org-at-item-p) (call-interactively 'org-indent-item))
18825 (t (org-shiftcursor-error))))
18827 (defun org-shiftmetaup (&optional arg)
18828 "Move subtree up or kill table row.
18829 Calls `org-move-subtree-up' or `org-table-kill-row' or
18830 `org-move-item-up' depending on context. See the individual commands
18831 for more information."
18832 (interactive "P")
18833 (cond
18834 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18835 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
18836 ((org-at-item-p) (call-interactively 'org-move-item-up))
18837 (t (org-shiftcursor-error))))
18838 (defun org-shiftmetadown (&optional arg)
18839 "Move subtree down or insert table row.
18840 Calls `org-move-subtree-down' or `org-table-insert-row' or
18841 `org-move-item-down', depending on context. See the individual
18842 commands for more information."
18843 (interactive "P")
18844 (cond
18845 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18846 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
18847 ((org-at-item-p) (call-interactively 'org-move-item-down))
18848 (t (org-shiftcursor-error))))
18850 (defun org-metaleft (&optional arg)
18851 "Promote heading or move table column to left.
18852 Calls `org-do-promote' or `org-table-move-column', depending on context.
18853 With no specific context, calls the Emacs default `backward-word'.
18854 See the individual commands for more information."
18855 (interactive "P")
18856 (cond
18857 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18858 ((or (org-on-heading-p) (org-region-active-p))
18859 (call-interactively 'org-do-promote))
18860 ((org-at-item-p) (call-interactively 'org-outdent-item))
18861 (t (call-interactively 'backward-word))))
18863 (defun org-metaright (&optional arg)
18864 "Demote subtree or move table column to right.
18865 Calls `org-do-demote' or `org-table-move-column', depending on context.
18866 With no specific context, calls the Emacs default `forward-word'.
18867 See the individual commands for more information."
18868 (interactive "P")
18869 (cond
18870 ((org-at-table-p) (call-interactively 'org-table-move-column))
18871 ((or (org-on-heading-p) (org-region-active-p))
18872 (call-interactively 'org-do-demote))
18873 ((org-at-item-p) (call-interactively 'org-indent-item))
18874 (t (call-interactively 'forward-word))))
18876 (defun org-metaup (&optional arg)
18877 "Move subtree up or move table row up.
18878 Calls `org-move-subtree-up' or `org-table-move-row' or
18879 `org-move-item-up', depending on context. See the individual commands
18880 for more information."
18881 (interactive "P")
18882 (cond
18883 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18884 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
18885 ((org-at-item-p) (call-interactively 'org-move-item-up))
18886 (t (org-shiftcursor-error))))
18888 (defun org-metadown (&optional arg)
18889 "Move subtree down or move table row down.
18890 Calls `org-move-subtree-down' or `org-table-move-row' or
18891 `org-move-item-down', depending on context. See the individual
18892 commands for more information."
18893 (interactive "P")
18894 (cond
18895 ((org-at-table-p) (call-interactively 'org-table-move-row))
18896 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
18897 ((org-at-item-p) (call-interactively 'org-move-item-down))
18898 (t (org-shiftcursor-error))))
18900 (defun org-shiftup (&optional arg)
18901 "Increase item in timestamp or increase priority of current headline.
18902 Calls `org-timestamp-up' or `org-priority-up', depending on context.
18903 See the individual commands for more information."
18904 (interactive "P")
18905 (cond
18906 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
18907 ((org-on-heading-p) (call-interactively 'org-priority-up))
18908 ((org-at-item-p) (call-interactively 'org-previous-item))
18909 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
18911 (defun org-shiftdown (&optional arg)
18912 "Decrease item in timestamp or decrease priority of current headline.
18913 Calls `org-timestamp-down' or `org-priority-down', depending on context.
18914 See the individual commands for more information."
18915 (interactive "P")
18916 (cond
18917 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
18918 ((org-on-heading-p) (call-interactively 'org-priority-down))
18919 (t (call-interactively 'org-next-item))))
18921 (defun org-shiftright ()
18922 "Next TODO keyword or timestamp one day later, depending on context."
18923 (interactive)
18924 (cond
18925 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18926 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
18927 (t (org-shiftcursor-error))))
18929 (defun org-shiftleft ()
18930 "Previous TODO keyword or timestamp one day earlier, depending on context."
18931 (interactive)
18932 (cond
18933 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18934 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
18935 (t (org-shiftcursor-error))))
18937 (defun org-copy-special ()
18938 "Copy region in table or copy current subtree.
18939 Calls `org-table-copy' or `org-copy-subtree', depending on context.
18940 See the individual commands for more information."
18941 (interactive)
18942 (call-interactively
18943 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
18945 (defun org-cut-special ()
18946 "Cut region in table or cut current subtree.
18947 Calls `org-table-copy' or `org-cut-subtree', depending on context.
18948 See the individual commands for more information."
18949 (interactive)
18950 (call-interactively
18951 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
18953 (defun org-paste-special (arg)
18954 "Paste rectangular region into table, or past subtree relative to level.
18955 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
18956 See the individual commands for more information."
18957 (interactive "P")
18958 (if (org-at-table-p)
18959 (org-table-paste-rectangle)
18960 (org-paste-subtree arg)))
18962 (defun org-ctrl-c-ctrl-c (&optional arg)
18963 "Set tags in headline, or update according to changed information at point.
18965 This command does many different things, depending on context:
18967 - If the cursor is in a headline, prompt for tags and insert them
18968 into the current line, aligned to `org-tags-column'. When called
18969 with prefix arg, realign all tags in the current buffer.
18971 - If the cursor is in one of the special #+KEYWORD lines, this
18972 triggers scanning the buffer for these lines and updating the
18973 information.
18975 - If the cursor is inside a table, realign the table. This command
18976 works even if the automatic table editor has been turned off.
18978 - If the cursor is on a #+TBLFM line, re-apply the formulas to
18979 the entire table.
18981 - If the cursor is inside a table created by the table.el package,
18982 activate that table.
18984 - If the current buffer is a remember buffer, close note and file it.
18985 with a prefix argument, file it without further interaction to the default
18986 location.
18988 - If the cursor is on a <<<target>>>, update radio targets and corresponding
18989 links in this buffer.
18991 - If the cursor is on a numbered item in a plain list, renumber the
18992 ordered list."
18993 (interactive "P")
18994 (let ((org-enable-table-editor t))
18995 (cond
18996 ((or org-clock-overlays
18997 org-occur-highlights
18998 org-latex-fragment-image-overlays)
18999 (org-remove-clock-overlays)
19000 (org-remove-occur-highlights)
19001 (org-remove-latex-fragment-image-overlays)
19002 (message "Temporary highlights/overlays removed from current buffer"))
19003 ((and (local-variable-p 'org-finish-function (current-buffer))
19004 (fboundp org-finish-function))
19005 (funcall org-finish-function))
19006 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
19007 ((org-on-heading-p) (call-interactively 'org-set-tags))
19008 ((org-at-table.el-p)
19009 (require 'table)
19010 (beginning-of-line 1)
19011 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
19012 (call-interactively 'table-recognize-table))
19013 ((org-at-table-p)
19014 (org-table-maybe-eval-formula)
19015 (if arg
19016 (call-interactively 'org-table-recalculate)
19017 (org-table-maybe-recalculate-line))
19018 (call-interactively 'org-table-align))
19019 ((org-at-item-checkbox-p)
19020 (call-interactively 'org-toggle-checkbox))
19021 ((org-at-item-p)
19022 (call-interactively 'org-renumber-ordered-list))
19023 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
19024 (cond
19025 ((equal (match-string 1) "TBLFM")
19026 ;; Recalculate the table before this line
19027 (save-excursion
19028 (beginning-of-line 1)
19029 (skip-chars-backward " \r\n\t")
19030 (if (org-at-table-p)
19031 (org-call-with-arg 'org-table-recalculate t))))
19033 (call-interactively 'org-mode-restart))))
19034 (t (error "C-c C-c can do nothing useful at this location.")))))
19036 (defun org-mode-restart ()
19037 "Restart Org-mode, to scan again for special lines.
19038 Also updates the keyword regular expressions."
19039 (interactive)
19040 (let ((org-inhibit-startup t)) (org-mode))
19041 (message "Org-mode restarted to refresh keyword and special line setup"))
19043 (defun org-return ()
19044 "Goto next table row or insert a newline.
19045 Calls `org-table-next-row' or `newline', depending on context.
19046 See the individual commands for more information."
19047 (interactive)
19048 (cond
19049 ((org-at-table-p)
19050 (org-table-justify-field-maybe)
19051 (call-interactively 'org-table-next-row))
19052 (t (newline))))
19054 (defun org-meta-return (&optional arg)
19055 "Insert a new heading or wrap a region in a table.
19056 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19057 See the individual commands for more information."
19058 (interactive "P")
19059 (cond
19060 ((org-at-table-p)
19061 (call-interactively 'org-table-wrap-region))
19062 (t (call-interactively 'org-insert-heading))))
19064 ;;; Menu entries
19066 ;; Define the Org-mode menus
19067 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19068 '("Tbl"
19069 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
19070 ["Next Field" org-cycle (org-at-table-p)]
19071 ["Previous Field" org-shifttab (org-at-table-p)]
19072 ["Next Row" org-return (org-at-table-p)]
19073 "--"
19074 ["Blank Field" org-table-blank-field (org-at-table-p)]
19075 ["Edit Field" org-table-edit-field (org-at-table-p)]
19076 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19077 "--"
19078 ("Column"
19079 ["Move Column Left" org-metaleft (org-at-table-p)]
19080 ["Move Column Right" org-metaright (org-at-table-p)]
19081 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19082 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19083 ("Row"
19084 ["Move Row Up" org-metaup (org-at-table-p)]
19085 ["Move Row Down" org-metadown (org-at-table-p)]
19086 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19087 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19088 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19089 "--"
19090 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
19091 ("Rectangle"
19092 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19093 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19094 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19095 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19096 "--"
19097 ("Calculate"
19098 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19099 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19100 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
19101 "--"
19102 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19103 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19104 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19105 "--"
19106 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19107 "--"
19108 ["Sum Column/Rectangle" org-table-sum
19109 (or (org-at-table-p) (org-region-active-p))]
19110 ["Which Column?" org-table-current-column (org-at-table-p)])
19111 ["Debug Formulas"
19112 org-table-toggle-formula-debugger
19113 :style toggle :selected org-table-formula-debug]
19114 ["Show Col/Row Numbers"
19115 org-table-toggle-coordinate-overlays
19116 :style toggle :selected org-table-overlay-coordinates]
19117 "--"
19118 ["Create" org-table-create (and (not (org-at-table-p))
19119 org-enable-table-editor)]
19120 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19121 ["Import from File" org-table-import (not (org-at-table-p))]
19122 ["Export to File" org-table-export (org-at-table-p)]
19123 "--"
19124 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19126 (easy-menu-define org-org-menu org-mode-map "Org menu"
19127 '("Org"
19128 ("Show/Hide"
19129 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
19130 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
19131 ["Sparse Tree" org-occur t]
19132 ["Reveal Context" org-reveal t]
19133 ["Show All" show-all t]
19134 "--"
19135 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19136 "--"
19137 ["New Heading" org-insert-heading t]
19138 ("Navigate Headings"
19139 ["Up" outline-up-heading t]
19140 ["Next" outline-next-visible-heading t]
19141 ["Previous" outline-previous-visible-heading t]
19142 ["Next Same Level" outline-forward-same-level t]
19143 ["Previous Same Level" outline-backward-same-level t]
19144 "--"
19145 ["Jump" org-goto t])
19146 ("Edit Structure"
19147 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19148 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19149 "--"
19150 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19151 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19152 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19153 "--"
19154 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19155 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19156 ["Demote Heading" org-metaright (not (org-at-table-p))]
19157 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19158 "--"
19159 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19160 "--"
19161 ["Convert to odd levels" org-convert-to-odd-levels t]
19162 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19163 ("Archive"
19164 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19165 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
19166 ; :active t :keys "C-u C-c C-x C-a"]
19167 ["Sparse trees open ARCHIVE trees"
19168 (setq org-sparse-tree-open-archived-trees
19169 (not org-sparse-tree-open-archived-trees))
19170 :style toggle :selected org-sparse-tree-open-archived-trees]
19171 ["Cycling opens ARCHIVE trees"
19172 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
19173 :style toggle :selected org-cycle-open-archived-trees]
19174 ["Agenda includes ARCHIVE trees"
19175 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
19176 :style toggle :selected (not org-agenda-skip-archived-trees)]
19177 "--"
19178 ["Move Subtree to Archive" org-advertized-archive-subtree t]
19179 ; ["Check and Move Children" (org-archive-subtree '(4))
19180 ; :active t :keys "C-u C-c C-x C-s"]
19182 "--"
19183 ("TODO Lists"
19184 ["TODO/DONE/-" org-todo t]
19185 ("Select keyword"
19186 ["Next keyword" org-shiftright (org-on-heading-p)]
19187 ["Previous keyword" org-shiftleft (org-on-heading-p)]
19188 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
19189 ["Show TODO Tree" org-show-todo-tree t]
19190 ["Global TODO list" org-todo-list t]
19191 "--"
19192 ["Set Priority" org-priority t]
19193 ["Priority Up" org-shiftup t]
19194 ["Priority Down" org-shiftdown t]
19195 "--"
19196 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
19197 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
19198 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
19199 ; (or (org-on-heading-p) (org-at-item-p))]
19200 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
19201 ; (or (org-on-heading-p) (org-at-item-p))]
19202 ; ["Update Statistics" org-update-checkbox-count t]
19204 ("Dates and Scheduling"
19205 ["Timestamp" org-time-stamp t]
19206 ["Timestamp (inactive)" org-time-stamp-inactive t]
19207 ("Change Date"
19208 ["1 Day Later" org-shiftright t]
19209 ["1 Day Earlier" org-shiftleft t]
19210 ["1 ... Later" org-shiftup t]
19211 ["1 ... Earlier" org-shiftdown t])
19212 ["Compute Time Range" org-evaluate-time-range t]
19213 ["Schedule Item" org-schedule t]
19214 ["Deadline" org-deadline t]
19215 "--"
19216 ["Custom time format" org-toggle-time-stamp-overlays
19217 :style radio :selected org-display-custom-times]
19218 "--"
19219 ["Goto Calendar" org-goto-calendar t]
19220 ["Date from Calendar" org-date-from-calendar t])
19221 ("Logging work"
19222 ["Clock in" org-clock-in t]
19223 ["Clock out" org-clock-out t]
19224 ["Clock cancel" org-clock-cancel t]
19225 ["Display times" org-clock-display t]
19226 ["Create clock table" org-clock-report t]
19227 "--"
19228 ["Record DONE time"
19229 (progn (setq org-log-done (not org-log-done))
19230 (message "Switching to %s will %s record a timestamp"
19231 org-done-string
19232 (if org-log-done "automatically" "not")))
19233 :style toggle :selected org-log-done])
19234 "--"
19235 ["Agenda Command..." org-agenda t]
19236 ("File List for Agenda")
19237 ("Special views current file"
19238 ["TODO Tree" org-show-todo-tree t]
19239 ["Check Deadlines" org-check-deadlines t]
19240 ["Timeline" org-timeline t]
19241 ["Tags Tree" org-tags-sparse-tree t])
19242 "--"
19243 ("Hyperlinks"
19244 ["Store Link (Global)" org-store-link t]
19245 ["Insert Link" org-insert-link t]
19246 ["Follow Link" org-open-at-point t]
19247 "--"
19248 ["Next link" org-next-link t]
19249 ["Previous link" org-previous-link t]
19250 "--"
19251 ["Descriptive Links"
19252 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
19253 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
19254 ["Literal Links"
19255 (progn
19256 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
19257 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
19258 "--"
19259 ["Export/Publish..." org-export t]
19260 ("LaTeX"
19261 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19262 :selected org-cdlatex-mode]
19263 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19264 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19265 ["Modify math symbol" org-cdlatex-math-modify
19266 (org-inside-LaTeX-fragment-p)]
19267 ["Export LaTeX fragments as images"
19268 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
19269 :style toggle :selected org-export-with-LaTeX-fragments])
19270 "--"
19271 ("Documentation"
19272 ["Show Version" org-version t]
19273 ["Info Documentation" org-info t])
19274 ("Customize"
19275 ["Browse Org Group" org-customize t]
19276 "--"
19277 ["Expand This Menu" org-create-customize-menu
19278 (fboundp 'customize-menu-create)])
19279 "--"
19280 ["Refresh setup" org-mode-restart t]
19283 (defun org-toggle-log-option (type)
19284 (if (not (listp org-log-done)) (setq org-log-done nil))
19285 (if (memq type org-log-done)
19286 (setq org-log-done (delq type org-log-done))
19287 (add-to-list 'org-log-done type)))
19289 (defun org-check-log-option (type)
19290 (and (listp org-log-done) (memq type org-log-done)))
19292 (defun org-info (&optional node)
19293 "Read documentation for Org-mode in the info system.
19294 With optional NODE, go directly to that node."
19295 (interactive)
19296 (require 'info)
19297 (Info-goto-node (format "(org)%s" (or node ""))))
19299 (defun org-install-agenda-files-menu ()
19300 (let ((bl (buffer-list)))
19301 (save-excursion
19302 (while bl
19303 (set-buffer (pop bl))
19304 (if (org-mode-p) (setq bl nil)))
19305 (when (org-mode-p)
19306 (easy-menu-change
19307 '("Org") "File List for Agenda"
19308 (append
19309 (list
19310 ["Edit File List" (org-edit-agenda-file-list) t]
19311 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19312 ["Remove Current File from List" org-remove-file t]
19313 ["Cycle through agenda files" org-cycle-agenda-files t]
19314 "--")
19315 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19317 ;;;; Documentation
19319 (defun org-customize ()
19320 "Call the customize function with org as argument."
19321 (interactive)
19322 (customize-browse 'org))
19324 (defun org-create-customize-menu ()
19325 "Create a full customization menu for Org-mode, insert it into the menu."
19326 (interactive)
19327 (if (fboundp 'customize-menu-create)
19328 (progn
19329 (easy-menu-change
19330 '("Org") "Customize"
19331 `(["Browse Org group" org-customize t]
19332 "--"
19333 ,(customize-menu-create 'org)
19334 ["Set" Custom-set t]
19335 ["Save" Custom-save t]
19336 ["Reset to Current" Custom-reset-current t]
19337 ["Reset to Saved" Custom-reset-saved t]
19338 ["Reset to Standard Settings" Custom-reset-standard t]))
19339 (message "\"Org\"-menu now contains full customization menu"))
19340 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19342 ;;;; Miscellaneous stuff
19345 ;;; Generally useful functions
19347 (defun org-context ()
19348 "Return a list of contexts of the current cursor position.
19349 If several contexts apply, all are returned.
19350 Each context entry is a list with a symbol naming the context, and
19351 two positions indicating start and end of the context. Possible
19352 contexts are:
19354 :headline anywhere in a headline
19355 :headline-stars on the leading stars in a headline
19356 :todo-keyword on a TODO keyword (including DONE) in a headline
19357 :tags on the TAGS in a headline
19358 :priority on the priority cookie in a headline
19359 :item on the first line of a plain list item
19360 :item-bullet on the bullet/number of a plain list item
19361 :checkbox on the checkbox in a plain list item
19362 :table in an org-mode table
19363 :table-special on a special filed in a table
19364 :table-table in a table.el table
19365 :link on a hyperlink
19366 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19367 :target on a <<target>>
19368 :radio-target on a <<<radio-target>>>
19369 :latex-fragment on a LaTeX fragment
19370 :latex-preview on a LaTeX fragment with overlayed preview image
19372 This function expects the position to be visible because it uses font-lock
19373 faces as a help to recognize the following contexts: :table-special, :link,
19374 and :keyword."
19375 (let* ((f (get-text-property (point) 'face))
19376 (faces (if (listp f) f (list f)))
19377 (p (point)) clist o)
19378 ;; First the large context
19379 (cond
19380 ((org-on-heading-p)
19381 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19382 (when (progn
19383 (beginning-of-line 1)
19384 (looking-at org-todo-line-tags-regexp))
19385 (push (org-point-in-group p 1 :headline-stars) clist)
19386 (push (org-point-in-group p 2 :todo-keyword) clist)
19387 (push (org-point-in-group p 4 :tags) clist))
19388 (goto-char p)
19389 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
19390 (if (looking-at "\\[#[A-Z]\\]")
19391 (push (org-point-in-group p 0 :priority) clist)))
19393 ((org-at-item-p)
19394 (push (org-point-in-group p 2 :item-bullet) clist)
19395 (push (list :item (point-at-bol)
19396 (save-excursion (org-end-of-item) (point)))
19397 clist)
19398 (and (org-at-item-checkbox-p)
19399 (push (org-point-in-group p 0 :checkbox) clist)))
19401 ((org-at-table-p)
19402 (push (list :table (org-table-begin) (org-table-end)) clist)
19403 (if (memq 'org-formula faces)
19404 (push (list :table-special
19405 (previous-single-property-change p 'face)
19406 (next-single-property-change p 'face)) clist)))
19407 ((org-at-table-p 'any)
19408 (push (list :table-table) clist)))
19409 (goto-char p)
19411 ;; Now the small context
19412 (cond
19413 ((org-at-timestamp-p)
19414 (push (org-point-in-group p 0 :timestamp) clist))
19415 ((memq 'org-link faces)
19416 (push (list :link
19417 (previous-single-property-change p 'face)
19418 (next-single-property-change p 'face)) clist))
19419 ((memq 'org-special-keyword faces)
19420 (push (list :keyword
19421 (previous-single-property-change p 'face)
19422 (next-single-property-change p 'face)) clist))
19423 ((org-on-target-p)
19424 (push (org-point-in-group p 0 :target) clist)
19425 (goto-char (1- (match-beginning 0)))
19426 (if (looking-at org-radio-target-regexp)
19427 (push (org-point-in-group p 0 :radio-target) clist))
19428 (goto-char p))
19429 ((setq o (car (delq nil
19430 (mapcar
19431 (lambda (x)
19432 (if (memq x org-latex-fragment-image-overlays) x))
19433 (org-overlays-at (point))))))
19434 (push (list :latex-fragment
19435 (org-overlay-start o) (org-overlay-end o)) clist)
19436 (push (list :latex-preview
19437 (org-overlay-start o) (org-overlay-end o)) clist))
19438 ((org-inside-LaTeX-fragment-p)
19439 ;; FIXME: positions wrong.
19440 (push (list :latex-fragment (point) (point)) clist)))
19442 (setq clist (nreverse (delq nil clist)))
19443 clist))
19445 (defun org-in-regexp (re &optional nlines visually)
19446 "Check if point is inside a match of regexp.
19447 Normally only the current line is checked, but you can include NLINES extra
19448 lines both before and after point into the search.
19449 If VISUALLY is set, require that the cursor is not after the match but
19450 really on, so that the block visually is on the match."
19451 (catch 'exit
19452 (let ((pos (point))
19453 (eol (point-at-eol (+ 1 (or nlines 0))))
19454 (inc (if visually 1 0)))
19455 (save-excursion
19456 (beginning-of-line (- 1 (or nlines 0)))
19457 (while (re-search-forward re eol t)
19458 (if (and (<= (match-beginning 0) pos)
19459 (>= (+ inc (match-end 0)) pos))
19460 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19462 (defun org-point-in-group (point group &optional context)
19463 "Check if POINT is in match-group GROUP.
19464 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19465 match. If the match group does ot exist or point is not inside it,
19466 return nil."
19467 (and (match-beginning group)
19468 (>= point (match-beginning group))
19469 (<= point (match-end group))
19470 (if context
19471 (list context (match-beginning group) (match-end group))
19472 t)))
19474 (defun org-combine-plists (&rest plists)
19475 "Create a single property list from all plists in PLISTS.
19476 The process starts by copying the first list, and then setting properties
19477 from the other lists. Settings in the last list are the most significant
19478 ones and overrule settings in the other lists."
19479 (let ((rtn (copy-sequence (pop plists)))
19480 p v ls)
19481 (while plists
19482 (setq ls (pop plists))
19483 (while ls
19484 (setq p (pop ls) v (pop ls))
19485 (setq rtn (plist-put rtn p v))))
19486 rtn))
19488 (defun org-move-line-down (arg)
19489 "Move the current line down. With prefix argument, move it past ARG lines."
19490 (interactive "p")
19491 (let ((col (current-column))
19492 beg end pos)
19493 (beginning-of-line 1) (setq beg (point))
19494 (beginning-of-line 2) (setq end (point))
19495 (beginning-of-line (+ 1 arg))
19496 (setq pos (move-marker (make-marker) (point)))
19497 (insert (delete-and-extract-region beg end))
19498 (goto-char pos)
19499 (move-to-column col)))
19501 (defun org-move-line-up (arg)
19502 "Move the current line up. With prefix argument, move it past ARG lines."
19503 (interactive "p")
19504 (let ((col (current-column))
19505 beg end pos)
19506 (beginning-of-line 1) (setq beg (point))
19507 (beginning-of-line 2) (setq end (point))
19508 (beginning-of-line (- arg))
19509 (setq pos (move-marker (make-marker) (point)))
19510 (insert (delete-and-extract-region beg end))
19511 (goto-char pos)
19512 (move-to-column col)))
19514 (defun org-replace-escapes (string table)
19515 "Replace %-escapes in STRING with values in TABLE.
19516 TABLE is an association list with keys line \"%a\" and string values.
19517 The sequences in STRING may contain normal field width and padding information,
19518 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19519 so values can contain further %-escapes if they are define later in TABLE."
19520 (let ((case-fold-search nil)
19521 e re rpl)
19522 (while (setq e (pop table))
19523 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19524 (while (string-match re string)
19525 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19526 (cdr e)))
19527 (setq string (replace-match rpl t t string))))
19528 string))
19531 (defun org-sublist (list start end)
19532 "Return a section of LIST, from START to END.
19533 Counting starts at 1."
19534 (let (rtn (c start))
19535 (setq list (nthcdr (1- start) list))
19536 (while (and list (<= c end))
19537 (push (pop list) rtn)
19538 (setq c (1+ c)))
19539 (nreverse rtn)))
19541 (defun org-at-regexp-p (regexp)
19542 "Is point inside a match of REGEXP in the current line?"
19543 (catch 'exit
19544 (save-excursion
19545 (let ((pos (point)) (end (point-at-eol)))
19546 (beginning-of-line 1)
19547 (while (re-search-forward regexp end t)
19548 (if (and (<= (match-beginning 0) pos)
19549 (>= (match-end 0) pos))
19550 (throw 'exit t)))
19551 nil))))
19553 (defun org-find-base-buffer-visiting (file)
19554 "Like `find-buffer-visiting' but alway return the base buffer and
19555 not an indirect buffer"
19556 (let ((buf (find-buffer-visiting file)))
19557 (or (buffer-base-buffer buf) buf)))
19559 ;;; Paragraph filling stuff.
19560 ;; We want this to be just right, so use the full arsenal.
19561 ;; FIXME: configure filladapt for XEmacs
19563 (defun org-set-autofill-regexps ()
19564 (interactive)
19565 ;; In the paragraph separator we include headlines, because filling
19566 ;; text in a line directly attached to a headline would otherwise
19567 ;; fill the headline as well.
19568 (org-set-local 'comment-start-skip "^#+[ \t]*")
19569 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
19570 ;; The paragraph starter includes hand-formatted lists.
19571 (org-set-local 'paragraph-start
19572 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
19573 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19574 ;; But only if the user has not turned off tables or fixed-width regions
19575 (org-set-local
19576 'auto-fill-inhibit-regexp
19577 (concat "\\*\\|#\\+"
19578 "\\|[ \t]*" org-keyword-time-regexp
19579 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19580 (concat
19581 "\\|[ \t]*["
19582 (if org-enable-table-editor "|" "")
19583 (if org-enable-fixed-width-editor ":" "")
19584 "]"))))
19585 ;; We use our own fill-paragraph function, to make sure that tables
19586 ;; and fixed-width regions are not wrapped. That function will pass
19587 ;; through to `fill-paragraph' when appropriate.
19588 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19589 ; Adaptive filling: To get full control, first make sure that
19590 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19591 (org-set-local 'adaptive-fill-regexp "\000")
19592 (org-set-local 'adaptive-fill-function
19593 'org-adaptive-fill-function))
19595 (defun org-fill-paragraph (&optional justify)
19596 "Re-align a table, pass through to fill-paragraph if no table."
19597 (let ((table-p (org-at-table-p))
19598 (table.el-p (org-at-table.el-p)))
19599 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
19600 (table.el-p t) ; skip table.el tables
19601 (table-p (org-table-align) t) ; align org-mode tables
19602 (t nil)))) ; call paragraph-fill
19604 ;; For reference, this is the default value of adaptive-fill-regexp
19605 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19607 (defun org-adaptive-fill-function ()
19608 "Return a fill prefix for org-mode files.
19609 In particular, this makes sure hanging paragraphs for hand-formatted lists
19610 work correctly."
19611 (cond ((looking-at "#[ \t]+")
19612 (match-string 0))
19613 ((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
19614 (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
19615 (t nil)))
19618 (defun org-image-file-name-regexp ()
19619 "Return regexp matching the file names of images."
19620 (if (fboundp 'image-file-name-regexp)
19621 (image-file-name-regexp)
19622 (let ((image-file-name-extensions
19623 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19624 "xbm" "xpm" "pbm" "pgm" "ppm")))
19625 (concat "\\."
19626 (regexp-opt (nconc (mapcar 'upcase
19627 image-file-name-extensions)
19628 image-file-name-extensions)
19630 "\\'"))))
19632 (defun org-file-image-p (file)
19633 "Return non-nil if FILE is an image."
19634 (save-match-data
19635 (string-match (org-image-file-name-regexp) file)))
19637 ;;;; Functions extending outline functionality
19639 ;; C-a should go to the beginning of a *visible* line, also in the
19640 ;; new outline.el. I guess this should be patched into Emacs?
19641 (defun org-beginning-of-line ()
19642 "Go to the beginning of the current line. If that is invisible, continue
19643 to a visible line beginning. This makes the function of C-a more intuitive."
19644 (interactive)
19645 (beginning-of-line 1)
19646 (if (bobp)
19648 (backward-char 1)
19649 (if (org-invisible-p)
19650 (while (and (not (bobp)) (org-invisible-p))
19651 (backward-char 1)
19652 (beginning-of-line 1))
19653 (forward-char 1))))
19655 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19657 (defun org-invisible-p ()
19658 "Check if point is at a character currently not visible."
19659 ;; Early versions of noutline don't have `outline-invisible-p'.
19660 (if (fboundp 'outline-invisible-p)
19661 (outline-invisible-p)
19662 (get-char-property (point) 'invisible)))
19664 (defun org-invisible-p2 ()
19665 "Check if point is at a character currently not visible."
19666 (save-excursion
19667 (if (and (eolp) (not (bobp))) (backward-char 1))
19668 ;; Early versions of noutline don't have `outline-invisible-p'.
19669 (if (fboundp 'outline-invisible-p)
19670 (outline-invisible-p)
19671 (get-char-property (point) 'invisible))))
19673 (defalias 'org-back-to-heading 'outline-back-to-heading)
19674 (defalias 'org-on-heading-p 'outline-on-heading-p)
19676 (defun org-on-target-p ()
19677 (or (org-in-regexp org-radio-target-regexp)
19678 (org-in-regexp org-target-regexp)))
19680 (defun org-up-heading-all (arg)
19681 "Move to the heading line of which the present line is a subheading.
19682 This function considers both visible and invisible heading lines.
19683 With argument, move up ARG levels."
19684 (if (fboundp 'outline-up-heading-all)
19685 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19686 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19688 (defun org-goto-sibling (&optional previous)
19689 "Goto the next sibling, even if it is invisible.
19690 When PREVIOUS is set, go to the previous sibling instead. Returns t
19691 when a sibling was found. When none is found, return nil and don't
19692 move point."
19693 (let ((fun (if previous 're-search-backward 're-search-forward))
19694 (pos (point))
19695 (re (concat "^" outline-regexp))
19696 level l)
19697 (org-back-to-heading t)
19698 (setq level (funcall outline-level))
19699 (catch 'exit
19700 (or previous (forward-char 1))
19701 (while (funcall fun re nil t)
19702 (setq l (funcall outline-level))
19703 (when (< l level) (goto-char pos) (throw 'exit nil))
19704 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19705 (goto-char pos)
19706 nil)))
19708 (defun org-show-siblings ()
19709 "Show all siblings of the current headline."
19710 (save-excursion
19711 (while (org-goto-sibling) (org-flag-heading nil)))
19712 (save-excursion
19713 (while (org-goto-sibling 'previous)
19714 (org-flag-heading nil))))
19716 (defun org-show-hidden-entry ()
19717 "Show an entry where even the heading is hidden."
19718 (save-excursion
19719 (org-show-entry)))
19721 (defun org-flag-heading (flag &optional entry)
19722 "Flag the current heading. FLAG non-nil means make invisible.
19723 When ENTRY is non-nil, show the entire entry."
19724 (save-excursion
19725 (org-back-to-heading t)
19726 ;; Check if we should show the entire entry
19727 (if entry
19728 (progn
19729 (org-show-entry)
19730 (save-excursion
19731 (and (outline-next-heading)
19732 (org-flag-heading nil))))
19733 (outline-flag-region (max 1 (1- (point)))
19734 (save-excursion (outline-end-of-heading) (point))
19735 flag))))
19737 (defun org-end-of-subtree (&optional invisible-OK)
19738 ;; This is an exact copy of the original function, but it uses
19739 ;; `org-back-to-heading', to make it work also in invisible
19740 ;; trees. And is uses an invisible-OK argument.
19741 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19742 (org-back-to-heading invisible-OK)
19743 (let ((first t)
19744 (level (funcall outline-level)))
19745 (while (and (not (eobp))
19746 (or first (> (funcall outline-level) level)))
19747 (setq first nil)
19748 (outline-next-heading))
19749 (if (memq (preceding-char) '(?\n ?\^M))
19750 (progn
19751 ;; Go to end of line before heading
19752 (forward-char -1)
19753 (if (memq (preceding-char) '(?\n ?\^M))
19754 ;; leave blank line before heading
19755 (forward-char -1)))))
19756 (point))
19758 (defun org-show-subtree ()
19759 "Show everything after this heading at deeper levels."
19760 (outline-flag-region
19761 (point)
19762 (save-excursion
19763 (outline-end-of-subtree) (outline-next-heading) (point))
19764 nil))
19766 (defun org-show-entry ()
19767 "Show the body directly following this heading.
19768 Show the heading too, if it is currently invisible."
19769 (interactive)
19770 (save-excursion
19771 (org-back-to-heading t)
19772 (outline-flag-region
19773 (max 1 (1- (point)))
19774 (save-excursion
19775 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
19776 (or (match-beginning 1) (point-max)))
19777 nil)))
19779 (defun org-make-options-regexp (kwds)
19780 "Make a regular expression for keyword lines."
19781 (concat
19783 "#?[ \t]*\\+\\("
19784 (mapconcat 'regexp-quote kwds "\\|")
19785 "\\):[ \t]*"
19786 "\\(.+\\)"))
19788 ;; Make isearch reveal the necessary context
19789 (defun org-isearch-end ()
19790 "Reveal context after isearch exits."
19791 (when isearch-success ; only if search was successful
19792 (if (featurep 'xemacs)
19793 ;; Under XEmacs, the hook is run in the correct place,
19794 ;; we directly show the context.
19795 (org-show-context 'isearch)
19796 ;; In Emacs the hook runs *before* restoring the overlays.
19797 ;; So we have to use a one-time post-command-hook to do this.
19798 ;; (Emacs 22 has a special variable, see function `org-mode')
19799 (unless (and (boundp 'isearch-mode-end-hook-quit)
19800 isearch-mode-end-hook-quit)
19801 ;; Only when the isearch was not quitted.
19802 (org-add-hook 'post-command-hook 'org-isearch-post-command
19803 'append 'local)))))
19805 (defun org-isearch-post-command ()
19806 "Remove self from hook, and show context."
19807 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19808 (org-show-context 'isearch))
19810 ;;;; Repair problems with some other packages
19812 ;; Make `bookmark-jump' show the jump location if it was hidden.
19813 (eval-after-load "bookmark"
19814 '(if (boundp 'bookmark-after-jump-hook)
19815 ;; We can use the hook
19816 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19817 ;; Hook not available, use advice
19818 (defadvice bookmark-jump (after org-make-visible activate)
19819 "Make the position visible."
19820 (org-bookmark-jump-unhide))))
19822 (defun org-bookmark-jump-unhide ()
19823 "Unhide the current position, to show the bookmark location."
19824 (and (org-mode-p)
19825 (or (org-invisible-p)
19826 (save-excursion (goto-char (max (point-min) (1- (point))))
19827 (org-invisible-p)))
19828 (org-show-context 'bookmark-jump)))
19830 ;; Make session.el ignore our circular variable
19831 (eval-after-load "session"
19832 '(add-to-list 'session-globals-exclude 'org-mark-ring))
19834 ;;;; Experimental code
19837 ;;;; Finish up
19839 (provide 'org)
19841 (run-hooks 'org-load-hook)
19843 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
19844 ;;; org.el ends here