Release 4.68
[org-mode.git] / org.el
blobee73a2646551a9c673c363a1554216568a17dda3
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.68
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 (defconst org-version "4.68"
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-use-standard-references t
787 "Should org-mode work with table refrences like B3 instead of @3$2?
788 Possible values are:
789 nil never use them
790 from accept as input, do not present for editing
791 t: accept as input and present for editing"
792 :group 'org-table-calculation
793 :type '(choice
794 (const :tag "Never, don't even check unser input for them" nil)
795 (const :tag "Always, both as user input, and when editing" t)
796 (const :tag "Conver user input, don't offerr during editing" 'from)))
798 (defcustom org-table-copy-increment t
799 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
800 :group 'org-table-calculation
801 :type 'boolean)
803 (defcustom org-calc-default-modes
804 '(calc-internal-prec 12
805 calc-float-format (float 5)
806 calc-angle-mode deg
807 calc-prefer-frac nil
808 calc-symbolic-mode nil
809 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
810 calc-display-working-message t
812 "List with Calc mode settings for use in calc-eval for table formulas.
813 The list must contain alternating symbols (Calc modes variables and values).
814 Don't remove any of the default settings, just change the values. Org-mode
815 relies on the variables to be present in the list."
816 :group 'org-table-calculation
817 :type 'plist)
819 (defcustom org-table-formula-evaluate-inline t
820 "Non-nil means, TAB and RET evaluate a formula in current table field.
821 If the current field starts with an equal sign, it is assumed to be a formula
822 which should be evaluated as described in the manual and in the documentation
823 string of the command `org-table-eval-formula'. This feature requires the
824 Emacs calc package.
825 When this variable is nil, formula calculation is only available through
826 the command \\[org-table-eval-formula]."
827 :group 'org-table-calculation
828 :type 'boolean)
830 (defcustom org-table-formula-use-constants t
831 "Non-nil means, interpret constants in formulas in tables.
832 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
833 by the value given in `org-table-formula-constants', or by a value obtained
834 from the `constants.el' package."
835 :group 'org-table-calculation
836 :type 'boolean)
838 ;; FIXME this is also a variable that makes Org-mode files non-portable
839 ;; Maybe I should have a #+ options for constants?
840 (defcustom org-table-formula-constants nil
841 "Alist with constant names and values, for use in table formulas.
842 The car of each element is a name of a constant, without the `$' before it.
843 The cdr is the value as a string. For example, if you'd like to use the
844 speed of light in a formula, you would configure
846 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
848 and then use it in an equation like `$1*$c'."
849 :group 'org-table-calculation
850 :type '(repeat
851 (cons (string :tag "name")
852 (string :tag "value"))))
854 (defcustom org-table-allow-automatic-line-recalculation t
855 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
856 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
857 :group 'org-table-calculation
858 :type 'boolean)
860 (defgroup org-link nil
861 "Options concerning links in Org-mode."
862 :tag "Org Link"
863 :group 'org)
865 (defvar org-link-abbrev-alist-local nil
866 "buffer-local version of `org-link-abbrev-alist', which see.
867 The value of this is taken from the #+LINK lines.")
868 (make-variable-buffer-local 'org-link-abbrev-alist-local)
870 (defcustom org-link-abbrev-alist nil
871 "Alist of link abbreviations.
872 The car of each element is a string, to be replaced at the start of a link.
873 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
874 links in Org-mode buffers can have an optional tag after a double colon, e.g.
876 [[linkkey:tag][description]]
878 If REPLACE is a string, the tag will simply be appended to create the link.
879 If the string contains \"%s\", the tag will be inserted there. REPLACE may
880 also be a function that will be called with the tag as the only argument to
881 create the link. See the manual for examples."
882 :group 'org-link
883 :type 'alist)
885 (defcustom org-descriptive-links t
886 "Non-nil means, hide link part and only show description of bracket links.
887 Bracket links are like [[link][descritpion]]. This variable sets the initial
888 state in new org-mode buffers. The setting can then be toggled on a
889 per-buffer basis from the Org->Hyperlinks menu."
890 :group 'org-link
891 :type 'boolean)
893 (defcustom org-link-file-path-type 'adaptive
894 "How the path name in file links should be stored.
895 Valid values are:
897 relative relative to the current directory, i.e. the directory of the file
898 into which the link is being inserted.
899 absolute absolute path, if possible with ~ for home directory.
900 noabbrev absolute path, no abbreviation of home directory.
901 adaptive Use relative path for files in the current directory and sub-
902 directories of it. For other files, use an absolute path."
903 :group 'org-link
904 :type '(choice
905 (const relative)
906 (const absolute)
907 (const noabbrev)
908 (const adaptive)))
910 (defcustom org-activate-links '(bracket angle plain radio tag date)
911 "Types of links that should be activated in Org-mode files.
912 This is a list of symbols, each leading to the activation of a certain link
913 type. In principle, it does not hurt to turn on most link types - there may
914 be a small gain when turning off unused link types. The types are:
916 bracket The recommended [[link][description]] or [[link]] links with hiding.
917 angular Links in angular brackes that may contain whitespace like
918 <bbdb:Carsten Dominik>.
919 plain Plain links in normal text, no whitespace, like http://google.com.
920 radio Text that is matched by a radio target, see manual for details.
921 tag Tag settings in a headline (link to tag search).
922 date Time stamps (link to calendar).
924 Changing this variable requires a restart of Emacs to become effective."
925 :group 'org-link
926 :type '(set (const :tag "Double bracket links (new style)" bracket)
927 (const :tag "Angular bracket links (old style)" angular)
928 (const :tag "plain text links" plain)
929 (const :tag "Radio target matches" radio)
930 (const :tag "Tags" tag)
931 (const :tag "Timestamps" date)))
933 (defgroup org-link-store nil
934 "Options concerning storing links in Org-mode"
935 :tag "Org Store Link"
936 :group 'org-link)
938 (defcustom org-email-link-description-format "Email %c: %.30s"
939 "Format of the description part of a link to an email or usenet message.
940 The following %-excapes will be replaced by corresponding information:
942 %F full \"From\" field
943 %f name, taken from \"From\" field, address if no name
944 %T full \"To\" field
945 %t first name in \"To\" field, address if no name
946 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
947 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
948 %s subject
949 %m message-id.
951 You may use normal field width specification between the % and the letter.
952 This is for example useful to limit the length of the subject.
954 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
955 :group 'org-link-store
956 :type 'string)
958 (defcustom org-from-is-user-regexp
959 (let (r1 r2)
960 (when (and user-mail-address (not (string= user-mail-address "")))
961 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
962 (when (and user-full-name (not (string= user-full-name "")))
963 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
964 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
965 "Regexp mached against the \"From:\" header of an email or usenet message.
966 It should match if the message is from the user him/herself."
967 :group 'org-link-store
968 :type 'regexp)
970 (defcustom org-context-in-file-links t
971 "Non-nil means, file links from `org-store-link' contain context.
972 A search string will be added to the file name with :: as separator and
973 used to find the context when the link is activated by the command
974 `org-open-at-point'.
975 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
976 negates this setting for the duration of the command."
977 :group 'org-link-store
978 :type 'boolean)
980 (defcustom org-keep-stored-link-after-insertion nil
981 "Non-nil means, keep link in list for entire session.
983 The command `org-store-link' adds a link pointing to the current
984 location to an internal list. These links accumulate during a session.
985 The command `org-insert-link' can be used to insert links into any
986 Org-mode file (offering completion for all stored links). When this
987 option is nil, every link which has been inserted once using \\[org-insert-link]
988 will be removed from the list, to make completing the unused links
989 more efficient."
990 :group 'org-link-store
991 :type 'boolean)
993 (defcustom org-usenet-links-prefer-google nil
994 "Non-nil means, `org-store-link' will create web links to Google groups.
995 When nil, Gnus will be used for such links.
996 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
997 negates this setting for the duration of the command."
998 :group 'org-link-store
999 :type 'boolean)
1001 (defgroup org-link-follow nil
1002 "Options concerning following links in Org-mode"
1003 :tag "Org Follow Link"
1004 :group 'org-link)
1006 (defcustom org-tab-follows-link nil
1007 "Non-nil means, on links TAB will follow the link.
1008 Needs to be set before org.el is loaded."
1009 :group 'org-link-follow
1010 :type 'boolean)
1012 (defcustom org-return-follows-link nil
1013 "Non-nil means, on links RET will follow the link.
1014 Needs to be set before org.el is loaded."
1015 :group 'org-link-follow
1016 :type 'boolean)
1018 (defcustom org-mouse-1-follows-link t
1019 "Non-nil means, mouse-1 on a link will follow the link.
1020 A longer mouse click will still set point. Does not wortk on XEmacs.
1021 Needs to be set before org.el is loaded."
1022 :group 'org-link-follow
1023 :type 'boolean)
1025 (defcustom org-mark-ring-length 4
1026 "Number of different positions to be recorded in the ring
1027 Changing this requires a restart of Emacs to work correctly."
1028 :group 'org-link-follow
1029 :type 'interger)
1031 (defcustom org-link-frame-setup
1032 '((vm . vm-visit-folder-other-frame)
1033 (gnus . gnus-other-frame)
1034 (file . find-file-other-window))
1035 "Setup the frame configuration for following links.
1036 When following a link with Emacs, it may often be useful to display
1037 this link in another window or frame. This variable can be used to
1038 set this up for the different types of links.
1039 For VM, use any of
1040 `vm-visit-folder'
1041 `vm-visit-folder-other-frame'
1042 For Gnus, use any of
1043 `gnus'
1044 `gnus-other-frame'
1045 For FILE, use any of
1046 `find-file'
1047 `find-file-other-window'
1048 `find-file-other-frame'
1049 For the calendar, use the variable `calendar-setup'.
1050 For BBDB, it is currently only possible to display the matches in
1051 another window."
1052 :group 'org-link-follow
1053 :type '(list
1054 (cons (const vm)
1055 (choice
1056 (const vm-visit-folder)
1057 (const vm-visit-folder-other-window)
1058 (const vm-visit-folder-other-frame)))
1059 (cons (const gnus)
1060 (choice
1061 (const gnus)
1062 (const gnus-other-frame)))
1063 (cons (const file)
1064 (choice
1065 (const find-file)
1066 (const find-file-other-window)
1067 (const find-file-other-frame)))))
1069 (defcustom org-display-internal-link-with-indirect-buffer nil
1070 "Non-nil means, use indirect buffer to display infile links.
1071 Activating internal links (from one location in a file to another location
1072 in the same file) normally just jumps to the location. When the link is
1073 activated with a C-u prefix (or with mouse-3), the link is displayed in
1074 another window. When this option is set, the other window actually displays
1075 an indirect buffer clone of the current buffer, to avoid any visibility
1076 changes to the current buffer."
1077 :group 'org-link-follow
1078 :type 'boolean)
1080 (defcustom org-open-non-existing-files nil
1081 "Non-nil means, `org-open-file' will open non-existing files.
1082 When nil, an error will be generated."
1083 :group 'org-link-follow
1084 :type 'boolean)
1086 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1087 "Function and arguments to call for following mailto links.
1088 This is a list with the first element being a lisp function, and the
1089 remaining elements being arguments to the function. In string arguments,
1090 %a will be replaced by the address, and %s will be replaced by the subject
1091 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1092 :group 'org-link-follow
1093 :type '(choice
1094 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1095 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1096 (const :tag "message-mail" (message-mail "%a" "%s"))
1097 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1099 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1100 "Non-nil means, ask for confirmation before executing shell links.
1101 Shell links can be dangerous, just thing about a link
1103 [[shell:rm -rf ~/*][Google Search]]
1105 This link would show up in your Org-mode document as \"Google Search\"
1106 but really it would remove your entire home directory.
1107 Therefore I *definitely* advise against setting this variable to nil.
1108 Just change it to `y-or-n-p' of you want to confirm with a single key press
1109 rather than having to type \"yes\"."
1110 :group 'org-link-follow
1111 :type '(choice
1112 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1113 (const :tag "with y-or-n (faster)" y-or-n-p)
1114 (const :tag "no confirmation (dangerous)" nil)))
1116 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1117 "Non-nil means, ask for confirmation before executing elisp links.
1118 Elisp links can be dangerous, just think about a link
1120 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1122 This link would show up in your Org-mode document as \"Google Search\"
1123 but really it would remove your entire home directory.
1124 Therefore I *definitely* advise against setting this variable to nil.
1125 Just change it to `y-or-n-p' of you want to confirm with a single key press
1126 rather than having to type \"yes\"."
1127 :group 'org-link-follow
1128 :type '(choice
1129 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1130 (const :tag "with y-or-n (faster)" y-or-n-p)
1131 (const :tag "no confirmation (dangerous)" nil)))
1133 (defconst org-file-apps-defaults-gnu
1134 '((remote . emacs)
1135 (t . mailcap))
1136 "Default file applications on a UNIX or GNU/Linux system.
1137 See `org-file-apps'.")
1139 (defconst org-file-apps-defaults-macosx
1140 '((remote . emacs)
1141 (t . "open %s")
1142 ("ps" . "gv %s")
1143 ("ps.gz" . "gv %s")
1144 ("eps" . "gv %s")
1145 ("eps.gz" . "gv %s")
1146 ("dvi" . "xdvi %s")
1147 ("fig" . "xfig %s"))
1148 "Default file applications on a MacOS X system.
1149 The system \"open\" is known as a default, but we use X11 applications
1150 for some files for which the OS does not have a good default.
1151 See `org-file-apps'.")
1153 (defconst org-file-apps-defaults-windowsnt
1154 (list
1155 '(remote . emacs)
1156 (cons t
1157 (list (if (featurep 'xemacs)
1158 'mswindows-shell-execute
1159 'w32-shell-execute)
1160 "open" 'file)))
1161 "Default file applications on a Windows NT system.
1162 The system \"open\" is used for most files.
1163 See `org-file-apps'.")
1165 (defcustom org-file-apps
1167 ("txt" . emacs)
1168 ("tex" . emacs)
1169 ("ltx" . emacs)
1170 ("org" . emacs)
1171 ("el" . emacs)
1172 ("bib" . emacs)
1174 "External applications for opening `file:path' items in a document.
1175 Org-mode uses system defaults for different file types, but
1176 you can use this variable to set the application for a given file
1177 extension. The entries in this list are cons cells where the car identifies
1178 files and the cdr the corresponding command. Possible values for the
1179 file identifier are
1180 \"ext\" A string identifying an extension
1181 `directory' Matches a directory
1182 `remote' Matches a remote file, accessible through tramp or efs.
1183 Remote files most likely should be visited through Emacs
1184 because external applications cannot handle such paths.
1185 t Default for all remaining files
1187 Possible values for the command are:
1188 `emacs' The file will be visited by the current Emacs process.
1189 `default' Use the default application for this file type.
1190 string A command to be executed by a shell; %s will be replaced
1191 by the path to the file.
1192 sexp A Lisp form which will be evaluated. The file path will
1193 be available in the Lisp variable `file'.
1194 For more examples, see the system specific constants
1195 `org-file-apps-defaults-macosx'
1196 `org-file-apps-defaults-windowsnt'
1197 `org-file-apps-defaults-gnu'."
1198 :group 'org-link-follow
1199 :type '(repeat
1200 (cons (choice :value ""
1201 (string :tag "Extension")
1202 (const :tag "Default for unrecognized files" t)
1203 (const :tag "Remote file" remote)
1204 (const :tag "Links to a directory" directory))
1205 (choice :value ""
1206 (const :tag "Visit with Emacs" emacs)
1207 (const :tag "Use system default" default)
1208 (string :tag "Command")
1209 (sexp :tag "Lisp form")))))
1211 (defcustom org-mhe-search-all-folders nil
1212 "Non-nil means, that the search for the mh-message will be extended to
1213 all folders if the message cannot be found in the folder given in the link.
1214 Searching all folders is very efficient with one of the search engines
1215 supported by MH-E, but will be slow with pick."
1216 :group 'org-link-follow
1217 :type 'boolean)
1219 (defgroup org-remember nil
1220 "Options concerning interaction with remember.el."
1221 :tag "Org Remember"
1222 :group 'org)
1224 (defcustom org-directory "~/org"
1225 "Directory with org files.
1226 This directory will be used as default to prompt for org files.
1227 Used by the hooks for remember.el."
1228 :group 'org-remember
1229 :type 'directory)
1231 (defcustom org-default-notes-file "~/.notes"
1232 "Default target for storing notes.
1233 Used by the hooks for remember.el. This can be a string, or nil to mean
1234 the value of `remember-data-file'.
1235 You can set this on a per-template basis with the variable
1236 `org-remember-templates'."
1237 :group 'org-remember
1238 :type '(choice
1239 (const :tag "Default from remember-data-file" nil)
1240 file))
1242 (defcustom org-remember-default-headline ""
1243 "The headline that should be the default location in the notes file.
1244 When filing remember notes, the cursor will start at that position.
1245 You can set this on a per-template basis with the variable
1246 `org-remember-templates'."
1247 :group 'org-remember
1248 :type 'string)
1250 (defcustom org-remember-templates nil
1251 "Templates for the creation of remember buffers.
1252 When nil, just let remember make the buffer.
1253 When not nil, this is a list of 4-element lists. In each entry, the first
1254 element is a character, a unique key to select this template.
1255 The second element is the template. The third element is optional and can
1256 specify a destination file for remember items created with this template.
1257 The default file is given by `org-default-notes-file'. An optional third
1258 element can specify the headline in that file that should be offered
1259 first when the user is asked to file the entry. The default headline is
1260 given in the variable `org-remember-default-headline'.
1262 The template specifies the structure of the remember buffer. It should have
1263 a first line starting with a star, to act as the org-mode headline.
1264 Furthermore, the following %-escapes will be replaced with content:
1266 %^{prompt} prompt the user for a string and replace this sequence with it.
1267 %t time stamp, date only
1268 %T time stamp with date and time
1269 %u, %U like the above, but inactive time stamps
1270 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1271 You may define a prompt like %^{Please specify birthday}t
1272 %n user name (taken from `user-full-name')
1273 %a annotation, normally the link created with org-store-link
1274 %i initial content, the region when remember is called with C-u.
1275 If %i is indented, the entire inserted text will be indented
1276 as well.
1278 %? After completing the template, position cursor here.
1280 Apart from these general escapes, you can access information specific to the
1281 link type that is created. For example, calling `remember' in emails or gnus
1282 will record the author and the subject of the message, which you can access
1283 with %:author and %:subject, respectively. Here is a complete list of what
1284 is recorded for each link type.
1286 Link type | Available information
1287 -------------------+------------------------------------------------------
1288 bbdb | %:type %:name %:company
1289 vm, wl, mh, rmail | %:type %:subject %:message-id
1290 | %:from %:fromname %:fromaddress
1291 | %:to %:toname %:toaddress
1292 | %:fromto (either \"to NAME\" or \"from NAME\")
1293 gnus | %:group, for messages also all email fields
1294 w3, w3m | %:type %:url
1295 info | %:type %:file %:node
1296 calendar | %:type %:date"
1297 :group 'org-remember
1298 :get (lambda (var) ; Make sure all entries have 4 elements
1299 (mapcar (lambda (x)
1300 (cond ((= (length x) 3) (append x '("")))
1301 ((= (length x) 2) (append x '("" "")))
1302 (t x)))
1303 (default-value var)))
1304 :type '(repeat
1305 :tag "enabled"
1306 (list :value (?a "\n" nil nil)
1307 (character :tag "Selection Key")
1308 (string :tag "Template")
1309 (file :tag "Destination file (optional)")
1310 (string :tag "Destination headline (optional)"))))
1312 (defcustom org-reverse-note-order nil
1313 "Non-nil means, store new notes at the beginning of a file or entry.
1314 When nil, new notes will be filed to the end of a file or entry."
1315 :group 'org-remember
1316 :type '(choice
1317 (const :tag "Reverse always" t)
1318 (const :tag "Reverse never" nil)
1319 (repeat :tag "By file name regexp"
1320 (cons regexp boolean))))
1322 (defgroup org-todo nil
1323 "Options concerning TODO items in Org-mode."
1324 :tag "Org TODO"
1325 :group 'org)
1327 (defgroup org-progress nil
1328 "Options concerning Progress logging in Org-mode."
1329 :tag "Org Progress"
1330 :group 'org-time)
1332 (defcustom org-todo-keywords '("TODO" "DONE")
1333 "List of TODO entry keywords.
1334 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1335 considered to mean that the entry is \"done\". All the other mean that
1336 action is required, and will make the entry show up in todo lists, diaries
1337 etc.
1338 The command \\[org-todo] cycles an entry through these states, and an
1339 additional state where no keyword is present. For details about this
1340 cycling, see also the variable `org-todo-interpretation'
1341 Changes become only effective after restarting Emacs."
1342 :group 'org-todo
1343 :group 'org-keywords
1344 :type '(repeat (string :tag "Keyword")))
1346 ;; FIXME: remove priority as a possible value, this seems to be obsolete.
1347 (defcustom org-todo-interpretation 'sequence
1348 "Controls how TODO keywords are interpreted.
1349 This variable is only relevant if `org-todo-keywords' contains more than two
1350 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1352 When `sequence', \\[org-todo] will always switch to the next state in the
1353 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1354 to state when executed several times in direct succession. Otherwise, it
1355 switches directly to DONE from any state.
1356 See the manual for more information."
1357 :group 'org-todo
1358 :group 'org-keywords
1359 :type '(choice (const sequence)
1360 (const type)))
1362 (defcustom org-after-todo-state-change-hook nil
1363 "Hook which is run after the state of a TODO item was changed.
1364 The new state (a string with a TODO keyword, or nil) is available in the
1365 Lisp variable `state'."
1366 :group 'org-todo
1367 :type 'hook)
1369 (defcustom org-log-done nil
1370 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1371 When the state of an entry is changed from nothing to TODO, remove a previous
1372 closing date.
1374 This can also be a list of symbols indicating under which conditions
1375 the time stamp recording the action should be annotated with a short note.
1376 Valid members of this list are
1378 done Offer to record a note when marking entries done
1379 state Offer to record a note whenever changing the TODO state
1380 of an item. This is only relevant if TODO keywords are
1381 interpreted as sequence, see variable `org-todo-interpretation'.
1382 When `state' is set, this includes tracking `done'.
1383 clock-out Offer to record a note when clocking out of an item.
1385 A separate window will then pop up and allow you to type a note.
1386 After finishing with C-c C-c, the note will be added directly after the
1387 timestamp, as a plain list item. See also the variable
1388 `org-log-note-headings'.
1390 Logging can also be configured on a per-file basis by adding one of
1391 the following lines anywhere in the buffer:
1393 #+STARTUP: logdone
1394 #+STARTUP: nologging
1395 #+STARTUP: lognotedone
1396 #+STARTUP: lognotestate
1397 #+STARTUP: lognoteclock-out"
1398 :group 'org-todo
1399 :group 'org-progress
1400 :type '(choice
1401 (const :tag "off" nil)
1402 (const :tag "on" t)
1403 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1404 (const :tag "when item is marked DONE" done)
1405 (const :tag "when TODO state changes" state)
1406 (const :tag "when clocking out" clock-out))))
1408 (defcustom org-log-note-headings
1409 '((done . "CLOSING NOTE %t")
1410 (state . "State %-12s %t")
1411 (clock-out . ""))
1412 "Headings for notes added when clocking out or closing TODO items.
1413 The value is an alist, with the car being a sympol indicating the note
1414 context, and the cdr is the heading to be used. The heading may also be the
1415 empty string.
1416 %t in the heading will be replaced by a time stamp.
1417 %s will be replaced by the new TODO state, in double quotes.
1418 %u will be replaced by the user name.
1419 %U will be replaced by the full user name."
1420 :group 'org-todo
1421 :group 'org-progress
1422 :type '(list :greedy t
1423 (cons (const :tag "Heading when closing an item" done) string)
1424 (cons (const :tag
1425 "Heading when changing todo state (todo sequence only)"
1426 state) string)
1427 (cons (const :tag "Heading when clocking out" clock-out) string)))
1429 (defcustom org-allow-auto-repeat t
1430 "Non-nil means, find REPEAT cookies in entries and apply them.
1431 A repeat cookie looks like REPEAT(+1m) and causes deadlines and schedules
1432 to repeat themselves shifted by a certain amount of time, each time an
1433 entry is marked DONE."
1434 :group 'org-todo
1435 :group 'org-progress
1436 :type 'boolean)
1438 (defgroup org-priorities nil
1439 "Priorities in Org-mode."
1440 :tag "Org Priorities"
1441 :group 'org-todo)
1443 (defcustom org-default-priority ?B
1444 "The default priority of TODO items.
1445 This is the priority an item get if no explicit priority is given."
1446 :group 'org-priorities
1447 :type 'character)
1449 (defcustom org-lowest-priority ?C
1450 "The lowest priority of TODO items. A character like ?A, ?B etc."
1451 :group 'org-priorities
1452 :type 'character)
1454 (defgroup org-time nil
1455 "Options concerning time stamps and deadlines in Org-mode."
1456 :tag "Org Time"
1457 :group 'org)
1459 (defcustom org-insert-labeled-timestamps-at-point nil
1460 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1461 When nil, these labeled time stamps are forces into the second line of an
1462 entry, just after the headline. When scheduling from the global TODO list,
1463 the time stamp will always be forced into the second line."
1464 :group 'org-time
1465 :type 'boolean)
1467 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1468 "Formats for `format-time-string' which are used for time stamps.
1469 It is not recommended to change this constant.")
1471 (defcustom org-time-stamp-rounding-minutes 0
1472 "Number of minutes to round time stamps to upon insertion.
1473 When zero, insert the time unmodified. Useful rounding numbers
1474 should be factors of 60, so for example 5, 10, 15.
1475 When this is not zero, you can still force an exact time-stamp by using
1476 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1477 :group 'org-time
1478 :type 'integer)
1480 (defcustom org-display-custom-times nil
1481 "Non-nil means, overlay custom formats over all time stamps.
1482 The formats are defined through the variable `org-time-stamp-custom-formats'.
1483 To turn this on on a per-file basis, insert anywhere in the file:
1484 #+STARTUP: customtime"
1485 :group 'org-time
1486 :set 'set-default
1487 :type 'sexp)
1488 (make-variable-buffer-local 'org-display-custom-times)
1490 (defcustom org-time-stamp-custom-formats
1491 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1492 "Custom formats for time stamps. See `format-time-string' for the syntax.
1493 These are overlayed over the default ISO format if the variable
1494 `org-display-custom-times' is set."
1495 :group 'org-time
1496 :type 'sexp)
1498 (defun org-time-stamp-format (&optional long inactive)
1499 "Get the right format for a time string."
1500 (let ((f (if long (cdr org-time-stamp-formats)
1501 (car org-time-stamp-formats))))
1502 (if inactive
1503 (concat "[" (substring f 1 -1) "]")
1504 f)))
1506 (defcustom org-deadline-warning-days 30
1507 "No. of days before expiration during which a deadline becomes active.
1508 This variable governs the display in sparse trees and in the agenda."
1509 :group 'org-time
1510 :type 'number)
1512 (defcustom org-popup-calendar-for-date-prompt t
1513 "Non-nil means, pop up a calendar when prompting for a date.
1514 In the calendar, the date can be selected with mouse-1. However, the
1515 minibuffer will also be active, and you can simply enter the date as well.
1516 When nil, only the minibuffer will be available."
1517 :group 'org-time
1518 :type 'boolean)
1520 (defcustom org-calendar-follow-timestamp-change t
1521 "Non-nil means, make the calendar window follow timestamp changes.
1522 When a timestamp is modified and the calendar window is visible, it will be
1523 moved to the new date."
1524 :group 'org-time
1525 :type 'boolean)
1527 (defgroup org-tags nil
1528 "Options concerning tags in Org-mode."
1529 :tag "Org Tags"
1530 :group 'org)
1532 (defcustom org-tag-alist nil
1533 "List of tags allowed in Org-mode files.
1534 When this list is nil, Org-mode will base TAG input on what is already in the
1535 buffer.
1536 The value of this variable is an alist, the car may be (and should) be a
1537 character that is used to select that tag through the fast-tag-selection
1538 interface. See the manual for details."
1539 :group 'org-tags
1540 :type '(repeat
1541 (choice
1542 (cons (string :tag "Tag name")
1543 (character :tag "Access char"))
1544 (const :tag "Start radio group" (:startgroup))
1545 (const :tag "End radio group" (:endgroup)))))
1547 (defcustom org-use-fast-tag-selection 'auto
1548 "Non-nil means, use fast tag selection scheme.
1549 This is a special interface to select and deselect tags with single keys.
1550 When nil, fast selection is never used.
1551 When the symbol `auto', fast selection is used if and only if selection
1552 characters for tags have been configured, either through the variable
1553 `org-tag-alist' or through a #+TAGS line in the buffer.
1554 When t, fast selection is always used and selection keys are assigned
1555 automatically if necessary."
1556 :group 'org-tags
1557 :type '(choice
1558 (const :tag "Always" t)
1559 (const :tag "Never" nil)
1560 (const :tag "When selection characters are configured" 'auto)))
1562 (defcustom org-fast-tag-selection-single-key nil
1563 "Non-nil means, fast tag selection exits after first change.
1564 When nil, you have to press RET to exit it.
1565 During fast tag selection, you can toggle this flag with `C-c'.
1566 This variable can also have the value `expert'. In this case, the window
1567 displaying the tags menu is not even shown, until you press C-c again."
1568 :group 'org-tags
1569 :type '(choice
1570 (const :tag "No" nil)
1571 (const :tag "Yes" t)
1572 (const :tag "Expert" expert)))
1574 (defcustom org-tags-column 48
1575 "The column to which tags should be indented in a headline.
1576 If this number is positive, it specifies the column. If it is negative,
1577 it means that the tags should be flushright to that column. For example,
1578 -79 works well for a normal 80 character screen."
1579 :group 'org-tags
1580 :type 'integer)
1582 (defcustom org-auto-align-tags t
1583 "Non-nil means, realign tags after pro/demotion of TODO state change.
1584 These operations change the length of a headline and therefore shift
1585 the tags around. With this options turned on, after each such operation
1586 the tags are again aligned to `org-tags-column'."
1587 :group 'org-tags
1588 :type 'boolean)
1590 (defcustom org-use-tag-inheritance t
1591 "Non-nil means, tags in levels apply also for sublevels.
1592 When nil, only the tags directly given in a specific line apply there.
1593 If you turn off this option, you very likely want to turn on the
1594 companion option `org-tags-match-list-sublevels'."
1595 :group 'org-tags
1596 :type 'boolean)
1598 (defcustom org-tags-match-list-sublevels nil
1599 "Non-nil means list also sublevels of headlines matching tag search.
1600 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1601 the sublevels of a headline matching a tag search often also match
1602 the same search. Listing all of them can create very long lists.
1603 Setting this variable to nil causes subtrees of a match to be skipped.
1604 This option is off by default, because inheritance in on. If you turn
1605 inheritance off, you very likely want to turn this option on.
1607 As a special case, if the tag search is restricted to TODO items, the
1608 value of this variable is ignored and sublevels are always checked, to
1609 make sure all corresponding TODO items find their way into the list."
1610 :group 'org-tags
1611 :type 'boolean)
1613 (defvar org-tags-history nil
1614 "History of minibuffer reads for tags.")
1615 (defvar org-last-tags-completion-table nil
1616 "The last used completion table for tags.")
1618 (defgroup org-agenda nil
1619 "Options concerning agenda views in Org-mode."
1620 :tag "Org Agenda"
1621 :group 'org)
1623 (defvar org-category nil
1624 "Variable used by org files to set a category for agenda display.
1625 Such files should use a file variable to set it, for example
1627 -*- mode: org; org-category: \"ELisp\"
1629 or contain a special line
1631 #+CATEGORY: ELisp
1633 If the file does not specify a category, then file's base name
1634 is used instead.")
1635 (make-variable-buffer-local 'org-category)
1637 (defcustom org-agenda-files nil
1638 "The files to be used for agenda display.
1639 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1640 \\[org-remove-file]. You can also use customize to edit the list.
1642 If the value of the variable is not a list but a single file name, then
1643 the list of agenda files is actually stored and maintained in that file, one
1644 agenda file per line."
1645 :group 'org-agenda
1646 :type '(choice
1647 (repeat :tag "List of files" file)
1648 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1651 (defcustom org-agenda-confirm-kill 1
1652 "When set, remote killing from the agenda buffer needs confirmation.
1653 When t, a confirmation is always needed. When a number N, confirmation is
1654 only needed when the text to be killed contains more than N non-white lines."
1655 :group 'org-agenda
1656 :type '(choice
1657 (const :tag "Never" nil)
1658 (const :tag "Always" t)
1659 (number :tag "When more than N lines")))
1661 (defcustom org-calendar-to-agenda-key [?c]
1662 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1663 The command `org-calendar-goto-agenda' will be bound to this key. The
1664 default is the character `c' because then `c' can be used to switch back and
1665 forth between agenda and calendar."
1666 :group 'org-agenda
1667 :type 'sexp)
1669 (defgroup org-agenda-custom-commands nil
1670 "Options concerning agenda views in Org-mode."
1671 :tag "Org Agenda Custom Commands"
1672 :group 'org-agenda)
1674 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1675 "Custom commands for the agenda.
1676 These commands will be offered on the splash screen displayed by the
1677 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1679 (key type match options)
1681 key The key (a single char as a string) to be associated with the command.
1682 type The command type, any of the following symbols:
1683 todo Entries with a specific TODO keyword, in all agenda files.
1684 tags Tags match in all agenda files.
1685 tags-todo Tags match in all agenda files, TODO entries only.
1686 todo-tree Sparse tree of specific TODO keyword in *current* file.
1687 tags-tree Sparse tree with all tags matches in *current* file.
1688 occur-tree Occur sparse tree for *current* file.
1689 match What to search for:
1690 - a single keyword for TODO keyword searches
1691 - a tags match expression for tags searches
1692 - a regular expression for occur searches
1693 options A list of option setttings, similar to that in a let form, so like
1694 this: ((opt1 val1) (opt2 val2) ...)
1696 You can also define a set of commands, to create a composite agenda buffer.
1697 In this case, an entry looks like this:
1699 (key desc (cmd1 cmd2 ...) general-options)
1701 where
1703 desc A description string to be displayed in the dispatcher menu.
1704 cmd An agenda command, similar to the above. However, tree commands
1705 are no allowed, but instead you can get agenda and global todo list.
1706 So valid commands for a set are:
1707 (agenda)
1708 (alltodo)
1709 (stuck)
1710 (todo \"match\" options)
1711 (tags \"match\" options )
1712 (tags-todo \"match\" options)
1714 Each command can carry a list of options, and another set of options can be
1715 given for the whole set of commands. Individual command options take
1716 precedence over the general options."
1717 :group 'org-agenda-custom-commands
1718 :type '(repeat
1719 (choice
1720 (list :tag "Single command"
1721 (string :tag "Key")
1722 (choice
1723 (const :tag "Tags search (all agenda files)" tags)
1724 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1725 (const :tag "TODO keyword search (all agenda files)" todo)
1726 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1727 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1728 (const :tag "Occur tree (current buffer)" occur-tree)
1729 (symbol :tag "Other, user-defined function"))
1730 (string :tag "Match")
1731 (repeat :tag "Local options"
1732 (list (variable :tag "Option") (sexp :tag "Value"))))
1733 (list :tag "Command series, all agenda files"
1734 (string :tag "Key")
1735 (string :tag "Description")
1736 (repeat
1737 (choice
1738 (const :tag "Agenda" (agenda))
1739 (const :tag "TODO list" (alltodo))
1740 (const :tag "Stuck projects" (stuck))
1741 (list :tag "Tags search"
1742 (const :format "" tags)
1743 (string :tag "Match")
1744 (repeat :tag "Local options"
1745 (list (variable :tag "Option")
1746 (sexp :tag "Value"))))
1748 (list :tag "Tags search, TODO entries only"
1749 (const :format "" tags-todo)
1750 (string :tag "Match")
1751 (repeat :tag "Local options"
1752 (list (variable :tag "Option")
1753 (sexp :tag "Value"))))
1755 (list :tag "TODO keyword search"
1756 (const :format "" todo)
1757 (string :tag "Match")
1758 (repeat :tag "Local options"
1759 (list (variable :tag "Option")
1760 (sexp :tag "Value"))))
1762 (list :tag "Other, user-defined function"
1763 (symbol :tag "function")
1764 (string :tag "Match")
1765 (repeat :tag "Local options"
1766 (list (variable :tag "Option")
1767 (sexp :tag "Value"))))))
1769 (repeat :tag "General options"
1770 (list (variable :tag "Option")
1771 (sexp :tag "Value")))))))
1773 (defcustom org-stuck-projects
1774 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil)
1775 "How to identify stuck projects.
1776 This is a list of three items:
1777 1. A tags/todo matcher string that is used to identify a project.
1778 The entire tree below a headline matched by this is considered a project.
1779 2. A list of TODO keywords itentifying non-stuck projects.
1780 If the project subtree contains any headline with one of these todo
1781 keywords, the project is consitered to be not stuck.
1782 3. A list of tags identifying non-stuck projects.
1783 If the project subtree contains any headline with one of these tags,
1784 the project is consitered to be not stuck.
1786 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1787 or `C-c a #' to produce the list."
1788 :group 'org-agenda-custom-commands
1789 :type '(list
1790 (string :tag "Tags/TODO match to identify a project")
1791 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1792 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))))
1795 (defgroup org-agenda-skip nil
1796 "Options concerning skipping parts of agenda files."
1797 :tag "Org Agenda Skip"
1798 :group 'org-agenda)
1800 (defcustom org-agenda-todo-list-sublevels t
1801 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1802 When nil, the sublevels of a TODO entry are not checked, resulting in
1803 potentially much shorter TODO lists."
1804 :group 'org-agenda-skip
1805 :group 'org-todo
1806 :type 'boolean)
1808 (defcustom org-agenda-todo-ignore-scheduled nil
1809 "Non-nil means, don't show scheduled entries in the global todo list.
1810 The idea behind this is that by scheduling it, you have already taken care
1811 of this item."
1812 :group 'org-agenda-skip
1813 :group 'org-todo
1814 :type 'boolean)
1816 (defcustom org-agenda-todo-ignore-deadlines nil
1817 "Non-nil means, don't show near deadline entries in the global todo list.
1818 Near means closer than `org-deadline-warning-days' days.
1819 The idea behind this is that such items will appear in the agenda anyway."
1820 :group 'org-agenda-skip
1821 :group 'org-todo
1822 :type 'boolean)
1824 (defcustom org-agenda-skip-scheduled-if-done nil
1825 "Non-nil means don't show scheduled items in agenda when they are done.
1826 This is relevant for the daily/weekly agenda, not for the TODO list."
1827 :group 'org-agenda-skip
1828 :type 'boolean)
1830 (defcustom org-timeline-show-empty-dates 3
1831 "Non-nil means, `org-timeline' also shows dates without an entry.
1832 When nil, only the days which actually have entries are shown.
1833 When t, all days between the first and the last date are shown.
1834 When an integer, show also empty dates, but if there is a gap of more than
1835 N days, just insert a special line indicating the size of the gap."
1836 :group 'org-agenda-skip
1837 :type '(choice
1838 (const :tag "None" nil)
1839 (const :tag "All" t)
1840 (number :tag "at most")))
1843 (defgroup org-agenda-startup nil
1844 "Options concerning initial settings in the Agenda in Org Mode."
1845 :tag "Org Agenda Startup"
1846 :group 'org-agenda)
1848 (defcustom org-finalize-agenda-hook nil
1849 "Hook run just before displaying an agenda buffer."
1850 :group 'org-agenda-startup
1851 :type 'hook)
1853 (defcustom org-agenda-mouse-1-follows-link nil
1854 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1855 A longer mouse click will still set point. Does not wortk on XEmacs.
1856 Needs to be set before org.el is loaded."
1857 :group 'org-agenda-startup
1858 :type 'boolean)
1860 (defcustom org-agenda-start-with-follow-mode nil
1861 "The initial value of follwo-mode in a newly created agenda window."
1862 :group 'org-agenda-startup
1863 :type 'boolean)
1865 (defgroup org-agenda-windows nil
1866 "Options concerning the windows used by the Agenda in Org Mode."
1867 :tag "Org Agenda Windows"
1868 :group 'org-agenda)
1870 (defcustom org-agenda-window-setup 'reorganize-frame
1871 "How the agenda buffer should be displayed.
1872 Possible values for this option are:
1874 current-window Show agenda in the current window, keeping all other windows.
1875 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1876 other-window Use `switch-to-buffer-other-window' to display agenda.
1877 reorganize-frame Show only two windows on the current frame, the current
1878 window and the agenda.
1879 See also the variable `org-agenda-restore-windows-after-quit'."
1880 :group 'org-agenda-windows
1881 :type '(choice
1882 (const current-window)
1883 (const other-frame)
1884 (const other-window)
1885 (const reorganize-frame)))
1887 (defcustom org-agenda-restore-windows-after-quit nil
1888 "Non-nil means, restore window configuration open exiting agenda.
1889 Before the window configuration is changed for displaying the agenda,
1890 the current status is recorded. When the agenda is exited with
1891 `q' or `x' and this option is set, the old state is restored. If
1892 `org-agenda-window-setup' is `other-frame', the value of this
1893 option will be ignored.."
1894 :group 'org-agenda-windows
1895 :type 'boolean)
1897 (defcustom org-indirect-buffer-display 'other-window
1898 "How should indirect tree buffers be displayed?
1899 This applies to indirect buffers created with the commands
1900 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1901 Valid values are:
1902 current-window Display in the current window
1903 other-window Just display in another window.
1904 dedicated-frame Create one new frame, and re-use it each time.
1905 new-frame Make a new frame each time."
1906 :group 'org-structure
1907 :group 'org-agenda-windows
1908 :type '(choice
1909 (const :tag "In current window" current-window)
1910 (const :tag "In current frame, other window" other-window)
1911 (const :tag "Each time a new frame" new-frame)
1912 (const :tag "One dedicated frame" dedicated-frame)))
1914 (defgroup org-agenda-daily/weekly nil
1915 "Options concerning the daily/weekly agenda."
1916 :tag "Org Agenda Daily/Weekly"
1917 :group 'org-agenda)
1919 (defcustom org-agenda-ndays 7
1920 "Number of days to include in overview display.
1921 Should be 1 or 7."
1922 :group 'org-agenda-daily/weekly
1923 :type 'number)
1925 (defcustom org-agenda-start-on-weekday 1
1926 "Non-nil means, start the overview always on the specified weekday.
1927 0 denotes Sunday, 1 denotes Monday etc.
1928 When nil, always start on the current day."
1929 :group 'org-agenda-daily/weekly
1930 :type '(choice (const :tag "Today" nil)
1931 (number :tag "Weekday No.")))
1933 (defcustom org-agenda-show-all-dates t
1934 "Non-nil means, `org-agenda' shows every day in the selected range.
1935 When nil, only the days which actually have entries are shown."
1936 :group 'org-agenda-daily/weekly
1937 :type 'boolean)
1939 (defcustom org-agenda-date-format "%A %d %B %Y"
1940 "Format string for displaying dates in the agenda.
1941 Used by the daily/weekly agenda and by the timeline. This should be
1942 a format string understood by `format-time-string'.
1943 FIXME: Not used currently, because of timezone problem."
1944 :group 'org-agenda-daily/weekly
1945 :type 'string)
1947 (defcustom org-agenda-include-diary nil
1948 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1949 :group 'org-agenda-daily/weekly
1950 :type 'boolean)
1952 (defcustom org-agenda-include-all-todo nil
1953 "Set means weekly/daily agenda will always contain all TODO entries.
1954 The TODO entries will be listed at the top of the agenda, before
1955 the entries for specific days."
1956 :group 'org-agenda-daily/weekly
1957 :type 'boolean)
1959 (defgroup org-agenda-time-grid nil
1960 "Options concerning the time grid in the Org-mode Agenda."
1961 :tag "Org Agenda Time Grid"
1962 :group 'org-agenda)
1964 (defcustom org-agenda-use-time-grid t
1965 "Non-nil means, show a time grid in the agenda schedule.
1966 A time grid is a set of lines for specific times (like every two hours between
1967 8:00 and 20:00). The items scheduled for a day at specific times are
1968 sorted in between these lines.
1969 For details about when the grid will be shown, and what it will look like, see
1970 the variable `org-agenda-time-grid'."
1971 :group 'org-agenda-time-grid
1972 :type 'boolean)
1974 (defcustom org-agenda-time-grid
1975 '((daily today require-timed)
1976 "----------------"
1977 (800 1000 1200 1400 1600 1800 2000))
1979 "The settings for time grid for agenda display.
1980 This is a list of three items. The first item is again a list. It contains
1981 symbols specifying conditions when the grid should be displayed:
1983 daily if the agenda shows a single day
1984 weekly if the agenda shows an entire week
1985 today show grid on current date, independent of daily/weekly display
1986 require-timed show grid only if at least one item has a time specification
1988 The second item is a string which will be places behing the grid time.
1990 The third item is a list of integers, indicating the times that should have
1991 a grid line."
1992 :group 'org-agenda-time-grid
1993 :type
1994 '(list
1995 (set :greedy t :tag "Grid Display Options"
1996 (const :tag "Show grid in single day agenda display" daily)
1997 (const :tag "Show grid in weekly agenda display" weekly)
1998 (const :tag "Always show grid for today" today)
1999 (const :tag "Show grid only if any timed entries are present"
2000 require-timed)
2001 (const :tag "Skip grid times already present in an entry"
2002 remove-match))
2003 (string :tag "Grid String")
2004 (repeat :tag "Grid Times" (integer :tag "Time"))))
2006 (defgroup org-agenda-sorting nil
2007 "Options concerning sorting in the Org-mode Agenda."
2008 :tag "Org Agenda Sorting"
2009 :group 'org-agenda)
2011 (let ((sorting-choice
2012 '(choice
2013 (const time-up) (const time-down)
2014 (const category-keep) (const category-up) (const category-down)
2015 (const tag-down) (const tag-up)
2016 (const priority-up) (const priority-down))))
2018 (defcustom org-agenda-sorting-strategy
2019 '((agenda time-up category-keep priority-down)
2020 (todo category-keep priority-down)
2021 (tags category-keep priority-down))
2022 "Sorting structure for the agenda items of a single day.
2023 This is a list of symbols which will be used in sequence to determine
2024 if an entry should be listed before another entry. The following
2025 symbols are recognized:
2027 time-up Put entries with time-of-day indications first, early first
2028 time-down Put entries with time-of-day indications first, late first
2029 category-keep Keep the default order of categories, corresponding to the
2030 sequence in `org-agenda-files'.
2031 category-up Sort alphabetically by category, A-Z.
2032 category-down Sort alphabetically by category, Z-A.
2033 tag-up Sort alphabetically by last tag, A-Z.
2034 tag-down Sort alphabetically by last tag, Z-A.
2035 priority-up Sort numerically by priority, high priority last.
2036 priority-down Sort numerically by priority, high priority first.
2038 The different possibilities will be tried in sequence, and testing stops
2039 if one comparison returns a \"not-equal\". For example, the default
2040 '(time-up category-keep priority-down)
2041 means: Pull out all entries having a specified time of day and sort them,
2042 in order to make a time schedule for the current day the first thing in the
2043 agenda listing for the day. Of the entries without a time indication, keep
2044 the grouped in categories, don't sort the categories, but keep them in
2045 the sequence given in `org-agenda-files'. Within each category sort by
2046 priority.
2048 Leaving out `category-keep' would mean that items will be sorted across
2049 categories by priority."
2050 :group 'org-agenda-sorting
2051 :type `(choice
2052 (repeat :tag "General" ,sorting-choice)
2053 (list :tag "Individually"
2054 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2055 (repeat ,sorting-choice))
2056 (cons (const :tag "Strategy for TODO lists" todo)
2057 (repeat ,sorting-choice))
2058 (cons (const :tag "Strategy for Tags matches" tags)
2059 (repeat ,sorting-choice))))))
2061 (defcustom org-sort-agenda-notime-is-late t
2062 "Non-nil means, items without time are considered late.
2063 This is only relevant for sorting. When t, items which have no explicit
2064 time like 15:30 will be considered as 99:01, i.e. later than any items which
2065 do have a time. When nil, the default time is before 0:00. You can use this
2066 option to decide if the schedule for today should come before or after timeless
2067 agenda entries."
2068 :group 'org-agenda-sorting
2069 :type 'boolean)
2071 (defgroup org-agenda-prefix nil
2072 "Options concerning the entry prefix in the Org-mode agenda display."
2073 :tag "Org Agenda Prefix"
2074 :group 'org-agenda)
2076 (defcustom org-agenda-prefix-format
2077 '((agenda . " %-12:c%?-12t% s")
2078 (timeline . " % s")
2079 (todo . " %-12:c")
2080 (tags . " %-12:c"))
2081 "Format specifications for the prefix of items in the agenda views.
2082 An alist with four entries, for the different agenda types. The keys to the
2083 sublists are `agenda', `timeline', `todo', and `tags'. The values
2084 are format strings.
2085 This format works similar to a printf format, with the following meaning:
2087 %c the category of the item, \"Diary\" for entries from the diary, or
2088 as given by the CATEGORY keyword or derived from the file name.
2089 %T the *last* tag of the item. Last because inherited tags come
2090 first in the list.
2091 %t the time-of-day specification if one applies to the entry, in the
2092 format HH:MM
2093 %s Scheduling/Deadline information, a short string
2095 All specifiers work basically like the standard `%s' of printf, but may
2096 contain two additional characters: A question mark just after the `%' and
2097 a whitespace/punctuation character just before the final letter.
2099 If the first character after `%' is a question mark, the entire field
2100 will only be included if the corresponding value applies to the
2101 current entry. This is useful for fields which should have fixed
2102 width when present, but zero width when absent. For example,
2103 \"%?-12t\" will result in a 12 character time field if a time of the
2104 day is specified, but will completely disappear in entries which do
2105 not contain a time.
2107 If there is punctuation or whitespace character just before the final
2108 format letter, this character will be appended to the field value if
2109 the value is not empty. For example, the format \"%-12:c\" leads to
2110 \"Diary: \" if the category is \"Diary\". If the category were be
2111 empty, no additional colon would be interted.
2113 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2114 - Indent the line with two space characters
2115 - Give the category in a 12 chars wide field, padded with whitespace on
2116 the right (because of `-'). Append a colon if there is a category
2117 (because of `:').
2118 - If there is a time-of-day, put it into a 12 chars wide field. If no
2119 time, don't put in an empty field, just skip it (because of '?').
2120 - Finally, put the scheduling information and append a whitespace.
2122 As another example, if you don't want the time-of-day of entries in
2123 the prefix, you could use:
2125 (setq org-agenda-prefix-format \" %-11:c% s\")
2127 See also the variables `org-agenda-remove-times-when-in-prefix' and
2128 `org-agenda-remove-tags-when-in-prefix'."
2129 :type '(choice
2130 (string :tag "General format")
2131 (list :greedy t :tag "View dependent"
2132 (cons (const agenda) (string :tag "Format"))
2133 (cons (const timeline) (string :tag "Format"))
2134 (cons (const todo) (string :tag "Format"))
2135 (cons (const tags) (string :tag "Format"))))
2136 :group 'org-agenda-prefix)
2138 (defvar org-prefix-format-compiled nil
2139 "The compiled version of the most recently used prefix format.
2140 See the variable `org-agenda-prefix-format'.")
2142 (defcustom org-agenda-remove-times-when-in-prefix t
2143 "Non-nil means, remove duplicate time specifications in agenda items.
2144 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2145 time-of-day specification in a headline or diary entry is extracted and
2146 placed into the prefix. If this option is non-nil, the original specification
2147 \(a timestamp or -range, or just a plain time(range) specification like
2148 11:30-4pm) will be removed for agenda display. This makes the agenda less
2149 cluttered.
2150 The option can be t or nil. It may also be the symbol `beg', indicating
2151 that the time should only be removed what it is located at the beginning of
2152 the headline/diary entry."
2153 :group 'org-agenda-prefix
2154 :type '(choice
2155 (const :tag "Always" t)
2156 (const :tag "Never" nil)
2157 (const :tag "When at beginning of entry" beg)))
2159 (defcustom org-agenda-remove-tags-when-in-prefix nil
2160 "Non-nil means, remove the tags from the headline copy in the agenda.
2161 When this is the symbol `prefix', only remove tags when
2162 `org-agenda-prefix-format' contains a `%T' specifier."
2163 :group 'org-agenda-prefix
2164 :type '(choice
2165 (const :tag "Always" t)
2166 (const :tag "Never" nil)
2167 (const :tag "When prefix format contains %T" prefix)))
2169 (defcustom org-agenda-align-tags-to-column 65
2170 "Shift tags in agenda items to this column."
2171 :group 'org-agenda-prefix
2172 :type 'integer)
2174 (defgroup org-latex nil
2175 "Options for embedding LaTeX code into Org-mode"
2176 :tag "Org LaTeX"
2177 :group 'org)
2179 (defcustom org-format-latex-options
2180 '(:foreground "Black" :background "Transparent" :scale 1.0
2181 :matchers ("begin" "$" "$$" "\\(" "\\["))
2182 "Options for creating images from LaTeX fragments.
2183 This is a property list with the following properties:
2184 :foreground the foreground color, for example \"Black\".
2185 :background the background color, or \"Transparent\".
2186 :scale a scaling factor for the size of the images
2187 :matchers a list indicating which matchers should be used to
2188 find LaTeX fragments. Valid members of this list are:
2189 \"begin\" find environments
2190 \"$\" find math expressions surrounded by $...$
2191 \"$$\" find math expressions surrounded by $$....$$
2192 \"\\(\" find math expressions surrounded by \\(...\\)
2193 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2194 :group 'org-latex
2195 :type 'plist)
2197 (defgroup org-export nil
2198 "Options for exporting org-listings."
2199 :tag "Org Export"
2200 :group 'org)
2202 (defgroup org-export-general nil
2203 "General options for exporting Org-mode files."
2204 :tag "Org Export General"
2205 :group 'org-export)
2207 (defcustom org-export-publishing-directory "."
2208 "Path to the location where exported files should be located.
2209 This path may be relative to the directory where the Org-mode file lives.
2210 The default is to put them into the same directory as the Org-mode file.
2211 The variable may also be an alist with export types `:html', `:ascii',
2212 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2213 is relative, it is interpreted relative to the directory where the exported
2214 Org-mode files lives."
2215 :group 'org-export-general
2216 :type '(choice
2217 (directory)
2218 (repeat
2219 (cons
2220 (choice :tag "Type"
2221 (const :html) (const :ascii) (const :ical) (const :xoxo))
2222 (directory)))))
2224 (defcustom org-export-language-setup
2225 '(("en" "Author" "Date" "Table of Contents")
2226 ("cs" "Autor" "Datum" "Obsah")
2227 ("da" "Ophavsmand" "Dato" "Indhold")
2228 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2229 ("es" "Autor" "Fecha" "\xccndice")
2230 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2231 ("it" "Autore" "Data" "Indice")
2232 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2233 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2234 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2235 "Terms used in export text, translated to different languages.
2236 Use the variable `org-export-default-language' to set the language,
2237 or use the +OPTION lines for a per-file setting."
2238 :group 'org-export-general
2239 :type '(repeat
2240 (list
2241 (string :tag "HTML language tag")
2242 (string :tag "Author")
2243 (string :tag "Date")
2244 (string :tag "Table of Contents"))))
2246 (defcustom org-export-default-language "en"
2247 "The default language of HTML export, as a string.
2248 This should have an association in `org-export-language-setup'."
2249 :group 'org-export-general
2250 :type 'string)
2252 (defcustom org-export-headline-levels 3
2253 "The last level which is still exported as a headline.
2254 Inferior levels will produce itemize lists when exported.
2255 Note that a numeric prefix argument to an exporter function overrides
2256 this setting.
2258 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2259 :group 'org-export-general
2260 :type 'number)
2262 (defcustom org-export-with-section-numbers t
2263 "Non-nil means, add section numbers to headlines when exporting.
2265 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2266 :group 'org-export-general
2267 :type 'boolean)
2269 (defcustom org-export-with-toc t
2270 "Non-nil means, create a table of contents in exported files.
2271 The TOC contains headlines with levels up to`org-export-headline-levels'.
2272 When an integer, include levels up to N in the toc, this may then be
2273 different from `org-export-headline-levels', but it will not be allowed
2274 to be larger than the number of headline levels.
2275 When nil, no table of contents is made.
2277 Headlines which contain any TODO items will be marked with \"(*)\" in
2278 ASCII export, and with red color in HTML output, if the option
2279 `org-export-mark-todo-in-toc' is set.
2281 In HTML output, the TOC will be clickable.
2283 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2284 or \"toc:3\"."
2285 :group 'org-export-general
2286 :type '(choice
2287 (const :tag "No Table of Contents" nil)
2288 (const :tag "Full Table of Contents" t)
2289 (integer :tag "TOC to level")))
2291 (defcustom org-export-mark-todo-in-toc nil
2292 "Non-nil means, mark TOC lines that contain any open TODO items."
2293 :group 'org-export-general
2294 :type 'boolean)
2296 (defcustom org-export-preserve-breaks nil
2297 "Non-nil means, preserve all line breaks when exporting.
2298 Normally, in HTML output paragraphs will be reformatted. In ASCII
2299 export, line breaks will always be preserved, regardless of this variable.
2301 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2302 :group 'org-export-general
2303 :type 'boolean)
2305 (defcustom org-export-with-archived-trees 'headline
2306 "Whether subtrees with the ARCHIVE tag should be exported.
2307 This can have three different values
2308 nil Do not export, pretend this tree is not present
2309 t Do export the entire tree
2310 headline Only export the headline, but skip the tree below it."
2311 :group 'org-export-general
2312 :group 'org-archive
2313 :type '(choice
2314 (const :tag "not at all" nil)
2315 (const :tag "headline only" 'headline)
2316 (const :tag "entirely" t)))
2318 (defcustom org-export-with-timestamps t
2319 "If nil, do not export time stamps and associated keywords."
2320 :group 'org-export-general
2321 :type 'boolean)
2323 (defcustom org-export-remove-timestamps-from-toc t
2324 "If nil, remove timestamps from the table of contents entries."
2325 :group 'org-export-general
2326 :type 'boolean)
2328 (defcustom org-export-with-tags 'not-in-toc
2329 "If nil, do not export tags, just remove them from headlines.
2330 If this is the symbol `not-in-toc', tags will be removed from table of
2331 contents entries, but still be shown in the headlines of the document."
2332 :group 'org-export-general
2333 :type '(choice
2334 (const :tag "Off" nil)
2335 (const :tag "Not in TOC" not-in-toc)
2336 (const :tag "On" t)))
2338 (defgroup org-export-translation nil
2339 "Options for translating special ascii sequences for the export backends."
2340 :tag "Org Export Translation"
2341 :group 'org-export)
2343 (defcustom org-export-with-emphasize t
2344 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2345 If the export target supports emphasizing text, the word will be
2346 typeset in bold, italic, or underlined, respectively. Works only for
2347 single words, but you can say: I *really* *mean* *this*.
2348 Not all export backends support this.
2350 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2351 :group 'org-export-translation
2352 :type 'boolean)
2354 (defcustom org-export-with-sub-superscripts t
2355 "Non-nil means, interpret \"_\" and \"^\" for export.
2356 When this option is turned on, you can use TeX-like syntax for sub- and
2357 superscripts. Several characters after \"_\" or \"^\" will be
2358 considered as a single item - so grouping with {} is normally not
2359 needed. For example, the following things will be parsed as single
2360 sub- or superscripts.
2362 10^24 or 10^tau several digits will be considered 1 item.
2363 10^-12 or 10^-tau a leading sign with digits or a word
2364 x^2-y^3 will be read as x^2 - y^3, because items are
2365 terminated by almost any nonword/nondigit char.
2366 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2368 Still, ambiguity is possible - so when in doubt use {} to enclose the
2369 sub/superscript.
2370 Not all export backends support this, but HTML does.
2372 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2373 :group 'org-export-translation
2374 :type 'boolean)
2376 (defcustom org-export-with-TeX-macros t
2377 "Non-nil means, interpret simple TeX-like macros when exporting.
2378 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2379 No only real TeX macros will work here, but the standard HTML entities
2380 for math can be used as macro names as well. For a list of supported
2381 names in HTML export, see the constant `org-html-entities'.
2382 Not all export backends support this.
2384 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2385 :group 'org-export-translation
2386 :group 'org-latex
2387 :type 'boolean)
2389 (defcustom org-export-with-LaTeX-fragments nil
2390 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2391 When set, the exporter will find LaTeX environments if the \\begin line is
2392 the first non-white thing on a line. It will also find the math delimiters
2393 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2394 display math.
2396 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2397 :group 'org-export-translation
2398 :group 'org-latex
2399 :type 'boolean)
2401 (defcustom org-export-with-fixed-width t
2402 "Non-nil means, lines starting with \":\" will be in fixed width font.
2403 This can be used to have pre-formatted text, fragments of code etc. For
2404 example:
2405 : ;; Some Lisp examples
2406 : (while (defc cnt)
2407 : (ding))
2408 will be looking just like this in also HTML. See also the QUOTE keyword.
2409 Not all export backends support this.
2411 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2412 :group 'org-export-translation
2413 :type 'boolean)
2415 (defcustom org-match-sexp-depth 3
2416 "Number of stacked braces for sub/superscript matching.
2417 This has to be set before loading org.el to be effective."
2418 :group 'org-export-translation
2419 :type 'integer)
2421 (defgroup org-export-tables nil
2422 "Options for exporting tables in Org-mode."
2423 :tag "Org Export Tables"
2424 :group 'org-export)
2426 (defcustom org-export-with-tables t
2427 "If non-nil, lines starting with \"|\" define a table.
2428 For example:
2430 | Name | Address | Birthday |
2431 |-------------+----------+-----------|
2432 | Arthur Dent | England | 29.2.2100 |
2434 Not all export backends support this.
2436 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2437 :group 'org-export-tables
2438 :type 'boolean)
2440 (defcustom org-export-highlight-first-table-line t
2441 "Non-nil means, highlight the first table line.
2442 In HTML export, this means use <th> instead of <td>.
2443 In tables created with table.el, this applies to the first table line.
2444 In Org-mode tables, all lines before the first horizontal separator
2445 line will be formatted with <th> tags."
2446 :group 'org-export-tables
2447 :type 'boolean)
2449 (defcustom org-export-table-remove-special-lines t
2450 "Remove special lines and marking characters in calculating tables.
2451 This removes the special marking character column from tables that are set
2452 up for spreadsheet calculations. It also removes the entire lines
2453 marked with `!', `_', or `^'. The lines with `$' are kept, because
2454 the values of constants may be useful to have."
2455 :group 'org-export-tables
2456 :type 'boolean)
2458 (defcustom org-export-prefer-native-exporter-for-tables nil
2459 "Non-nil means, always export tables created with table.el natively.
2460 Natively means, use the HTML code generator in table.el.
2461 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2462 the table does not use row- or column-spanning). This has the
2463 advantage, that the automatic HTML conversions for math symbols and
2464 sub/superscripts can be applied. Org-mode's HTML generator is also
2465 much faster."
2466 :group 'org-export-tables
2467 :type 'boolean)
2469 (defgroup org-export-ascii nil
2470 "Options specific for ASCII export of Org-mode files."
2471 :tag "Org Export ASCII"
2472 :group 'org-export)
2474 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2475 "Characters for underlining headings in ASCII export.
2476 In the given sequence, these characters will be used for level 1, 2, ..."
2477 :group 'org-export-ascii
2478 :type '(repeat character))
2480 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2481 "Bullet characters for headlines converted to lists in ASCII export.
2482 The first character is is used for the first lest level generated in this
2483 way, and so on. If there are more levels than characters given here,
2484 the list will be repeated.
2485 Note that plain lists will keep the same bullets as the have in the
2486 Org-mode file."
2487 :group 'org-export-ascii
2488 :type '(repeat character))
2490 (defgroup org-export-xml nil
2491 "Options specific for XML export of Org-mode files."
2492 :tag "Org Export XML"
2493 :group 'org-export)
2495 (defgroup org-export-html nil
2496 "Options specific for HTML export of Org-mode files."
2497 :tag "Org Export HTML"
2498 :group 'org-export)
2500 (defcustom org-export-html-style
2501 "<style type=\"text/css\">
2502 html {
2503 font-family: Times, serif;
2504 font-size: 12pt;
2506 .title { text-align: center; }
2507 .todo { color: red; }
2508 .done { color: green; }
2509 .timestamp { color: grey }
2510 .timestamp-kwd { color: CadetBlue }
2511 .tag { background-color:lightblue; font-weight:normal }
2512 .target { background-color: lavender; }
2513 pre {
2514 border: 1pt solid #AEBDCC;
2515 background-color: #F3F5F7;
2516 padding: 5pt;
2517 font-family: courier, monospace;
2519 table { border-collapse: collapse; }
2520 td, th {
2521 vertical-align: top;
2522 <!--border: 1pt solid #ADB9CC;-->
2524 </style>"
2525 "The default style specification for exported HTML files.
2526 Since there are different ways of setting style information, this variable
2527 needs to contain the full HTML structure to provide a style, including the
2528 surrounding HTML tags. The style specifications should include definitions
2529 for new classes todo, done, title, and deadline. For example, legal values
2530 would be:
2532 <style type=\"text/css\">
2533 p { font-weight: normal; color: gray; }
2534 h1 { color: black; }
2535 .title { text-align: center; }
2536 .todo, .deadline { color: red; }
2537 .done { color: green; }
2538 </style>
2540 or, if you want to keep the style in a file,
2542 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2544 As the value of this option simply gets inserted into the HTML <head> header,
2545 you can \"misuse\" it to add arbitrary text to the header."
2546 :group 'org-export-html
2547 :type 'string)
2549 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2550 "Format for typesetting the document title in HTML export."
2551 :group 'org-export-html
2552 :type 'string)
2554 (defcustom org-export-html-toplevel-hlevel 2
2555 "The <H> level for level 1 headings in HTML export."
2556 :group 'org-export-html
2557 :type 'string)
2559 (defcustom org-export-html-link-org-files-as-html t
2560 "Non-nil means, make file links to `file.org' point to `file.html'.
2561 When org-mode is exporting an org-mode file to HTML, links to
2562 non-html files are directly put into a href tag in HTML.
2563 However, links to other Org-mode files (recognized by the
2564 extension `.org.) should become links to the corresponding html
2565 file, assuming that the linked org-mode file will also be
2566 converted to HTML.
2567 When nil, the links still point to the plain `.org' file."
2568 :group 'org-export-html
2569 :type 'boolean)
2571 (defcustom org-export-html-inline-images 'maybe
2572 "Non-nil means, inline images into exported HTML pages.
2573 This is done using an <img> tag. When nil, an anchor with href is used to
2574 link to the image. If this option is `maybe', then images in links with
2575 an empty description will be inlined, while images with a description will
2576 be linked only."
2577 :group 'org-export-html
2578 :type '(choice (const :tag "Never" nil)
2579 (const :tag "Always" t)
2580 (const :tag "When there is no description" maybe)))
2582 ;; FIXME: rename
2583 (defcustom org-export-html-expand t
2584 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2585 When nil, these tags will be exported as plain text and therefore
2586 not be interpreted by a browser.
2588 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2589 :group 'org-export-html
2590 :type 'boolean)
2592 (defcustom org-export-html-table-tag
2593 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
2594 "The HTML tag used to start a table.
2595 This must be a <table> tag, but you may change the options like
2596 borders and spacing."
2597 :group 'org-export-html
2598 :type 'string)
2600 (defcustom org-export-html-with-timestamp nil
2601 "If non-nil, write `org-export-html-html-helper-timestamp'
2602 into the exported HTML text. Otherwise, the buffer will just be saved
2603 to a file."
2604 :group 'org-export-html
2605 :type 'boolean)
2607 (defcustom org-export-html-html-helper-timestamp
2608 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2609 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2610 :group 'org-export-html
2611 :type 'string)
2613 (defgroup org-export-icalendar nil
2614 "Options specific for iCalendar export of Org-mode files."
2615 :tag "Org Export iCalendar"
2616 :group 'org-export)
2618 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2619 "The file name for the iCalendar file covering all agenda files.
2620 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2621 The file name should be absolute."
2622 :group 'org-export-icalendar
2623 :type 'file)
2625 (defcustom org-icalendar-include-todo nil
2626 "Non-nil means, export to iCalendar files should also cover TODO items."
2627 :group 'org-export-icalendar
2628 :type '(choice
2629 (const :tag "None" nil)
2630 (const :tag "Unfinished" t)
2631 (const :tag "All" all)))
2633 (defcustom org-icalendar-combined-name "OrgMode"
2634 "Calendar name for the combined iCalendar representing all agenda files."
2635 :group 'org-export-icalendar
2636 :type 'string)
2638 (defgroup org-font-lock nil
2639 "Font-lock settings for highlighting in Org-mode."
2640 :tag "Org Font Lock"
2641 :group 'org)
2643 (defcustom org-level-color-stars-only nil
2644 "Non-nil means fontify only the stars in each headline.
2645 When nil, the entire headline is fontified.
2646 Changing it requires restart of `font-lock-mode' to become effective
2647 also in regions already fontified."
2648 :group 'org-font-lock
2649 :type 'boolean)
2651 (defcustom org-hide-leading-stars nil
2652 "Non-nil means, hide the first N-1 stars in a headline.
2653 This works by using the face `org-hide' for these stars. This
2654 face is white for a light background, and black for a dark
2655 background. You may have to customize the face `org-hide' to
2656 make this work.
2657 Changing it requires restart of `font-lock-mode' to become effective
2658 also in regions already fontified.
2659 You may also set this on a per-file basis by adding one of the following
2660 lines to the buffer:
2662 #+STARTUP: hidestars
2663 #+STARTUP: showstars"
2664 :group 'org-font-lock
2665 :type 'boolean)
2667 (defcustom org-fontify-done-headline nil
2668 "Non-nil means, change the face of a headline if it is marked DONE.
2669 Normally, only the TODO/DONE keyword indicates the state of a headline.
2670 When this is non-nil, the headline after the keyword is set to the
2671 `org-headline-done' as an additional indication."
2672 :group 'org-font-lock
2673 :type 'boolean)
2675 (defcustom org-fontify-emphasized-text t
2676 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2677 Changing this variable requires a restart of Emacs to take effect."
2678 :group 'org-font-lock
2679 :type 'boolean)
2681 (defvar org-emph-re nil
2682 "Regular expression for matching emphasis.")
2683 (defvar org-emphasis-regexp-components) ; defined just below
2684 (defvar org-emphasis-alist) ; defined just below
2685 (defun org-set-emph-re (var val)
2686 "Set variable and compute the emphasis regular expression."
2687 (set var val)
2688 (when (and (boundp 'org-emphasis-alist)
2689 (boundp 'org-emphasis-regexp-components)
2690 org-emphasis-alist org-emphasis-regexp-components)
2691 (let* ((e org-emphasis-regexp-components)
2692 (pre (car e))
2693 (post (nth 1 e))
2694 (border (nth 2 e))
2695 (body (nth 3 e))
2696 (nl (nth 4 e))
2697 (stacked (nth 5 e))
2698 (body1 (concat body "*?"))
2699 (markers (mapconcat 'car org-emphasis-alist "")))
2700 ;; make sure special characters appear at the right position in the class
2701 (if (string-match "\\^" markers)
2702 (setq markers (concat (replace-match "" t t markers) "^")))
2703 (if (string-match "-" markers)
2704 (setq markers (concat (replace-match "" t t markers) "-")))
2705 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2706 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2707 (if (> nl 0)
2708 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2709 (int-to-string nl) "\\}")))
2710 ;; Make the regexp
2711 (setq org-emph-re
2712 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2713 "\\("
2714 "\\([" markers "]\\)"
2715 "\\("
2716 "[^" border markers "]"
2717 body1
2718 "[^" border markers "]"
2719 "\\)"
2720 "\\3\\)"
2721 "\\([" post (if stacked markers) "]\\|$\\)")))))
2723 (defcustom org-emphasis-regexp-components
2724 '(" \t('\"" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2725 "Components used to build the reqular expression for emphasis.
2726 This is a list with 6 entries. Terminology: In an emphasis string
2727 like \" *strong word* \", we call the initial space PREMATCH, the final
2728 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2729 and \"trong wor\" is the body. The different components in this variable
2730 specify what is allowed/forbidden in each part:
2732 pre Chars allowed as prematch. Beginning of line will be allowed too.
2733 post Chars allowed as postmatch. End of line will be allowed too.
2734 border The chars *forbidden* as border characters. In addition to the
2735 characters given here, all marker characters are forbidden too.
2736 body-regexp A regexp like \".\" to match a body character. Don't use
2737 non-shy groups here, and don't allow newline here.
2738 newline The maximum number of newlines allowed in an emphasis exp.
2739 stacked Non-nil means, allow stacked styles. This works only in HTML
2740 export. When this is set, all marker characters (as given in
2741 `org-emphasis-alist') will be allowed as pre/post, aiding
2742 inside-out matching.
2743 Use customize to modify this, or restart Emacs after changing it."
2744 :group 'org-font-lock
2745 :set 'org-set-emph-re
2746 :type '(list
2747 (sexp :tag "Allowed chars in pre ")
2748 (sexp :tag "Allowed chars in post ")
2749 (sexp :tag "Forbidden chars in border ")
2750 (sexp :tag "Regexp for body ")
2751 (integer :tag "number of newlines allowed")
2752 (boolean :tag "Stacking allowed ")))
2754 (defcustom org-emphasis-alist
2755 '(("*" bold "<b>" "</b>")
2756 ("/" italic "<i>" "</i>")
2757 ("_" underline "<u>" "</u>")
2758 ("=" shadow "<code>" "</code>")
2759 ("+" (:strike-through t) "<del>" "</del>")
2761 "Special syntax for emphasized text.
2762 Text starting and ending with a special character will be emphasized, for
2763 example *bold*, _underlined_ and /italic/. This variable sets the marker
2764 characters, the face to bbe used by font-lock for highlighting in Org-mode
2765 Emacs buffers, and the HTML tags to be used for this.
2766 Use customize to modify this, or restart Emacs after changing it."
2767 :group 'org-font-lock
2768 :set 'org-set-emph-re
2769 :type '(repeat
2770 (list
2771 (string :tag "Marker character")
2772 (choice
2773 (face :tag "Font-lock-face")
2774 (plist :tag "Face property list"))
2775 (string :tag "HTML start tag")
2776 (string :tag "HTML end tag"))))
2778 ;;; The faces
2780 (defgroup org-faces nil
2781 "Faces in Org-mode."
2782 :tag "Org Faces"
2783 :group 'org-font-lock)
2785 (defun org-compatible-face (specs)
2786 "Make a compatible face specification.
2787 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2788 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2789 to the top of the list. The `min-colors' attribute will be removed from
2790 any other entries, and any resulting duplicates will be removed entirely."
2791 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2792 (let (r e a)
2793 (while (setq e (pop specs))
2794 (cond
2795 ((memq (car e) '(t default)) (push e r))
2796 ((setq a (member '(min-colors 8) (car e)))
2797 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2798 (cdr e)))))
2799 ((setq a (assq 'min-colors (car e)))
2800 (setq e (cons (delq a (car e)) (cdr e)))
2801 (or (assoc (car e) r) (push e r)))
2802 (t (or (assoc (car e) r) (push e r)))))
2803 (nreverse r))
2804 specs))
2806 (defface org-hide
2807 '((((background light)) (:foreground "white"))
2808 (((background dark)) (:foreground "black")))
2809 "Face used to hide leading stars in headlines.
2810 The forground color of this face should be equal to the background
2811 color of the frame."
2812 :group 'org-faces)
2814 (defface org-level-1 ;; font-lock-function-name-face
2815 (org-compatible-face
2816 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2817 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2818 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2819 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2820 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2821 (t (:bold t))))
2822 "Face used for level 1 headlines."
2823 :group 'org-faces)
2825 (defface org-level-2 ;; font-lock-variable-name-face
2826 (org-compatible-face
2827 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2828 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2829 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2830 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2831 (t (:bold t))))
2832 "Face used for level 2 headlines."
2833 :group 'org-faces)
2835 (defface org-level-3 ;; font-lock-keyword-face
2836 (org-compatible-face
2837 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2838 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2839 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2840 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2841 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2842 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2843 (t (:bold t))))
2844 "Face used for level 3 headlines."
2845 :group 'org-faces)
2847 (defface org-level-4 ;; font-lock-comment-face
2848 (org-compatible-face
2849 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2850 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2851 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2852 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2853 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2854 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2855 (t (:bold t))))
2856 "Face used for level 4 headlines."
2857 :group 'org-faces)
2859 (defface org-level-5 ;; font-lock-type-face
2860 (org-compatible-face
2861 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2862 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2863 (((class color) (min-colors 8)) (:foreground "green"))))
2864 "Face used for level 5 headlines."
2865 :group 'org-faces)
2867 (defface org-level-6 ;; font-lock-constant-face
2868 (org-compatible-face
2869 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2870 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2871 (((class color) (min-colors 8)) (:foreground "magenta"))))
2872 "Face used for level 6 headlines."
2873 :group 'org-faces)
2875 (defface org-level-7 ;; font-lock-builtin-face
2876 (org-compatible-face
2877 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2878 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2879 (((class color) (min-colors 8)) (:foreground "blue"))))
2880 "Face used for level 7 headlines."
2881 :group 'org-faces)
2883 (defface org-level-8 ;; font-lock-string-face
2884 (org-compatible-face
2885 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2886 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2887 (((class color) (min-colors 8)) (:foreground "green"))))
2888 "Face used for level 8 headlines."
2889 :group 'org-faces)
2891 (defface org-special-keyword ;; font-lock-string-face
2892 (org-compatible-face
2893 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2894 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2895 (t (:italic t))))
2896 "Face used for special keywords."
2897 :group 'org-faces)
2899 (defface org-warning ;; font-lock-warning-face
2900 (org-compatible-face
2901 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2902 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2903 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2904 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2905 (t (:bold t))))
2906 "Face for deadlines and TODO keywords."
2907 :group 'org-faces)
2909 (defface org-headline-done ;; font-lock-string-face
2910 (org-compatible-face
2911 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2912 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2913 (((class color) (min-colors 8) (background light)) (:bold nil))))
2914 "Face used to indicate that a headline is DONE.
2915 This face is only used if `org-fontify-done-headline' is set."
2916 :group 'org-faces)
2918 (defface org-archived ; similar to shadow
2919 (org-compatible-face
2920 '((((class color grayscale) (min-colors 88) (background light))
2921 (:foreground "grey50"))
2922 (((class color grayscale) (min-colors 88) (background dark))
2923 (:foreground "grey70"))
2924 (((class color) (min-colors 8) (background light))
2925 (:foreground "green"))
2926 (((class color) (min-colors 8) (background dark))
2927 (:foreground "yellow"))))
2928 "Face for headline with the ARCHIVE tag."
2929 :group 'org-faces)
2931 (defface org-link
2932 '((((class color) (background light)) (:foreground "Purple" :underline t))
2933 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2934 (t (:underline t)))
2935 "Face for links."
2936 :group 'org-faces)
2938 (defface org-date
2939 '((((class color) (background light)) (:foreground "Purple" :underline t))
2940 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2941 (t (:underline t)))
2942 "Face for links."
2943 :group 'org-faces)
2945 (defface org-tag
2946 '((t (:bold t)))
2947 "Face for tags."
2948 :group 'org-faces)
2950 (defface org-todo ;; font-lock-warning-face
2951 (org-compatible-face
2952 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2953 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2954 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2955 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2956 (t (:inverse-video t :bold t))))
2957 "Face for TODO keywords."
2958 :group 'org-faces)
2960 (defface org-done ;; font-lock-type-face
2961 (org-compatible-face
2962 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2963 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2964 (((class color) (min-colors 8)) (:foreground "green"))
2965 (t (:bold t))))
2966 "Face used for DONE."
2967 :group 'org-faces)
2969 (defface org-table ;; font-lock-function-name-face
2970 (org-compatible-face
2971 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2972 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2973 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2974 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2975 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2976 (((class color) (min-colors 8) (background dark)))))
2977 "Face used for tables."
2978 :group 'org-faces)
2980 (defface org-formula
2981 (org-compatible-face
2982 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2983 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2984 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2985 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2986 (t (:bold t :italic t))))
2987 "Face for formulas."
2988 :group 'org-faces)
2990 (defface org-scheduled-today
2991 (org-compatible-face
2992 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2993 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2994 (((class color) (min-colors 8)) (:foreground "green"))
2995 (t (:bold t :italic t))))
2996 "Face for items scheduled for a certain day."
2997 :group 'org-faces)
2999 (defface org-scheduled-previously
3000 (org-compatible-face
3001 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3002 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3003 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3004 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3005 (t (:bold t))))
3006 "Face for items scheduled previously, and not yet done."
3007 :group 'org-faces)
3009 (defface org-upcoming-deadline
3010 (org-compatible-face
3011 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3012 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3013 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3014 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3015 (t (:bold t))))
3016 "Face for items scheduled previously, and not yet done."
3017 :group 'org-faces)
3019 (defface org-time-grid ;; font-lock-variable-name-face
3020 (org-compatible-face
3021 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3022 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3023 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3024 "Face used for time grids."
3025 :group 'org-faces)
3027 (defconst org-level-faces
3028 '(org-level-1 org-level-2 org-level-3 org-level-4
3029 org-level-5 org-level-6 org-level-7 org-level-8
3031 (defconst org-n-levels (length org-level-faces))
3034 ;;; Variables for pre-computed regular expressions, all buffer local
3036 (defvar org-done-string nil
3037 "The last string in `org-todo-keywords', indicating an item is DONE.")
3038 (make-variable-buffer-local 'org-done-string)
3039 (defvar org-todo-regexp nil
3040 "Matches any of the TODO state keywords.")
3041 (make-variable-buffer-local 'org-todo-regexp)
3042 (defvar org-not-done-regexp nil
3043 "Matches any of the TODO state keywords except the last one.")
3044 (make-variable-buffer-local 'org-not-done-regexp)
3045 (defvar org-todo-line-regexp nil
3046 "Matches a headline and puts TODO state into group 2 if present.")
3047 (make-variable-buffer-local 'org-todo-line-regexp)
3048 (defvar org-todo-line-tags-regexp nil
3049 "Matches a headline and puts TODO state into group 2 if present.
3050 Also put tags into group 4 if tags are present.")
3051 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3052 (defvar org-nl-done-regexp nil
3053 "Matches newline followed by a headline with the DONE keyword.")
3054 (make-variable-buffer-local 'org-nl-done-regexp)
3055 (defvar org-looking-at-done-regexp nil
3056 "Matches the DONE keyword a point.")
3057 (make-variable-buffer-local 'org-looking-at-done-regexp)
3058 (defvar org-todo-kwd-priority-p nil
3059 "Do TODO items have priorities?")
3060 (make-variable-buffer-local 'org-todo-kwd-priority-p)
3061 (defvar org-todo-kwd-max-priority nil
3062 "Maximum priority of TODO items.")
3063 (make-variable-buffer-local 'org-todo-kwd-max-priority)
3064 (defvar org-ds-keyword-length 12
3065 "Maximum length of the Deadline and SCHEDULED keywords.")
3066 (make-variable-buffer-local 'org-ds-keyword-length)
3067 (defvar org-deadline-regexp nil
3068 "Matches the DEADLINE keyword.")
3069 (make-variable-buffer-local 'org-deadline-regexp)
3070 (defvar org-deadline-time-regexp nil
3071 "Matches the DEADLINE keyword together with a time stamp.")
3072 (make-variable-buffer-local 'org-deadline-time-regexp)
3073 (defvar org-deadline-line-regexp nil
3074 "Matches the DEADLINE keyword and the rest of the line.")
3075 (make-variable-buffer-local 'org-deadline-line-regexp)
3076 (defvar org-scheduled-regexp nil
3077 "Matches the SCHEDULED keyword.")
3078 (make-variable-buffer-local 'org-scheduled-regexp)
3079 (defvar org-scheduled-time-regexp nil
3080 "Matches the SCHEDULED keyword together with a time stamp.")
3081 (make-variable-buffer-local 'org-scheduled-time-regexp)
3082 (defvar org-closed-time-regexp nil
3083 "Matches the CLOSED keyword together with a time stamp.")
3084 (make-variable-buffer-local 'org-closed-time-regexp)
3086 (defvar org-keyword-time-regexp nil
3087 "Matches any of the 4 keywords, together with the time stamp.")
3088 (make-variable-buffer-local 'org-keyword-time-regexp)
3089 (defvar org-keyword-time-not-clock-regexp nil
3090 "Matches any of the 3 keywords, together with the time stamp.")
3091 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3092 (defvar org-maybe-keyword-time-regexp nil
3093 "Matches a timestamp, possibly preceeded by a keyword.")
3094 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3096 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3097 rear-nonsticky t mouse-map t fontified t)
3098 "Properties to remove when a string without properties is wanted.")
3100 (defsubst org-match-string-no-properties (num &optional string)
3101 (if (featurep 'xemacs)
3102 (let ((s (match-string num string)))
3103 (remove-text-properties 0 (length s) org-rm-props s)
3105 (match-string-no-properties num string)))
3107 (defsubst org-no-properties (s)
3108 (remove-text-properties 0 (length s) org-rm-props s)
3111 (defsubst org-get-alist-option (option key)
3112 (cond ((eq key t) t)
3113 ((eq option t) t)
3114 ((assoc key option) (cdr (assoc key option)))
3115 (t (cdr (assq 'default option)))))
3117 (defsubst org-inhibit-invisibility ()
3118 "Modified `buffer-invisibility-spec' for Emacs 21.
3119 Some ops with invisible text do not work correctly on Emacs 21. For these
3120 we turn off invisibility temporarily. Use this in a `let' form."
3121 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3123 (defsubst org-set-local (var value)
3124 "Make VAR local in current buffer and set it to VALUE."
3125 (set (make-variable-buffer-local var) value))
3127 (defsubst org-mode-p ()
3128 "Check if the current buffer is in Org-mode."
3129 (eq major-mode 'org-mode))
3131 (defsubst org-last (list)
3132 "Return the last element of LIST."
3133 (car (last list)))
3135 (defun org-let (list &rest body)
3136 (eval (cons 'let (cons list body))))
3137 (put 'org-let 'lisp-indent-function 1)
3139 (defun org-let2 (list1 list2 &rest body)
3140 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3141 (put 'org-let2 'lisp-indent-function 2)
3142 (defconst org-startup-options
3143 '(("fold" org-startup-folded t)
3144 ("overview" org-startup-folded t)
3145 ("nofold" org-startup-folded nil)
3146 ("showall" org-startup-folded nil)
3147 ("content" org-startup-folded content)
3148 ("hidestars" org-hide-leading-stars t)
3149 ("showstars" org-hide-leading-stars nil)
3150 ("odd" org-odd-levels-only t)
3151 ("oddeven" org-odd-levels-only nil)
3152 ("align" org-startup-align-all-tables t)
3153 ("noalign" org-startup-align-all-tables nil)
3154 ("customtime" org-display-custom-times t)
3155 ("logging" org-log-done t)
3156 ("logdone" org-log-done t)
3157 ("nologging" org-log-done nil)
3158 ("lognotedone" org-log-done done push)
3159 ("lognotestate" org-log-done state push)
3160 ("lognoteclock-out" org-log-done clock-out push)
3161 ("constcgs" constants-unit-system cgs)
3162 ("constSI" constants-unit-system SI))
3163 "Variable associated with STARTUP options for org-mode.
3164 Each element is a list of three items: The startup options as written
3165 in the #+STARTUP line, the corresponding variable, and the value to
3166 set this variable to if the option is found. An optional forth element PUSH
3167 means to push this value onto the list in the variable.")
3169 (defun org-set-regexps-and-options ()
3170 "Precompute regular expressions for current buffer."
3171 (when (org-mode-p)
3172 (let ((re (org-make-options-regexp
3173 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3174 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
3175 (splitre "[ \t]+")
3176 kwds int key value cat arch tags links)
3177 (save-excursion
3178 (save-restriction
3179 (widen)
3180 (goto-char (point-min))
3181 (while (re-search-forward re nil t)
3182 (setq key (match-string 1) value (org-match-string-no-properties 2))
3183 (cond
3184 ((equal key "CATEGORY")
3185 (if (string-match "[ \t]+$" value)
3186 (setq value (replace-match "" t t value)))
3187 (setq cat (intern value)))
3188 ((equal key "SEQ_TODO")
3189 (setq int 'sequence
3190 kwds (append kwds (org-split-string value splitre))))
3191 ((equal key "PRI_TODO")
3192 (setq int 'priority
3193 kwds (append kwds (org-split-string value splitre))))
3194 ((equal key "TYP_TODO")
3195 (setq int 'type
3196 kwds (append kwds (org-split-string value splitre))))
3197 ((equal key "TAGS")
3198 (setq tags (append tags (org-split-string value splitre))))
3199 ((equal key "LINK")
3200 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3201 (push (cons (match-string 1 value)
3202 (org-trim (match-string 2 value)))
3203 links)))
3204 ((equal key "STARTUP")
3205 (let ((opts (org-split-string value splitre))
3206 l var val)
3207 (while (setq l (pop opts))
3208 (when (setq l (assoc l org-startup-options))
3209 (setq var (nth 1 l) val (nth 2 l))
3210 (if (not (nth 3 l))
3211 (set (make-local-variable var) val)
3212 (if (not (listp (symbol-value var)))
3213 (set (make-local-variable var) nil))
3214 (set (make-local-variable var) (symbol-value var))
3215 (add-to-list var val))))))
3216 ((equal key "ARCHIVE")
3217 (string-match " *$" value)
3218 (setq arch (replace-match "" t t value))
3219 (remove-text-properties 0 (length arch)
3220 '(face t fontified t) arch)))
3222 (and cat (org-set-local 'org-category cat))
3223 (and kwds (org-set-local 'org-todo-keywords kwds))
3224 (and arch (org-set-local 'org-archive-location arch))
3225 (and int (org-set-local 'org-todo-interpretation int))
3226 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3227 (when tags
3228 (let (e tgs)
3229 (while (setq e (pop tags))
3230 (cond
3231 ((equal e "{") (push '(:startgroup) tgs))
3232 ((equal e "}") (push '(:endgroup) tgs))
3233 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3234 (push (cons (match-string 1 e)
3235 (string-to-char (match-string 2 e)))
3236 tgs))
3237 (t (push (list e) tgs))))
3238 (org-set-local 'org-tag-alist nil)
3239 (while (setq e (pop tgs))
3240 (or (and (stringp (car e))
3241 (assoc (car e) org-tag-alist))
3242 (push e org-tag-alist))))))
3244 ;; Compute the regular expressions and other local variables
3245 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3246 org-todo-kwd-max-priority (1- (length org-todo-keywords))
3247 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3248 (length org-scheduled-string)))
3249 org-done-string
3250 (nth (1- (length org-todo-keywords)) org-todo-keywords)
3251 org-todo-regexp
3252 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3253 "\\|") "\\)\\>")
3254 org-not-done-regexp
3255 (concat "\\<\\("
3256 (mapconcat 'regexp-quote
3257 (nreverse (cdr (reverse org-todo-keywords)))
3258 "\\|")
3259 "\\)\\>")
3260 org-todo-line-regexp
3261 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3262 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3263 "\\)\\>\\)? *\\(.*\\)")
3264 org-nl-done-regexp
3265 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3266 org-todo-line-tags-regexp
3267 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3268 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3269 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3270 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3271 org-deadline-regexp (concat "\\<" org-deadline-string)
3272 org-deadline-time-regexp
3273 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3274 org-deadline-line-regexp
3275 (concat "\\<\\(" org-deadline-string "\\).*")
3276 org-scheduled-regexp
3277 (concat "\\<" org-scheduled-string)
3278 org-scheduled-time-regexp
3279 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3280 org-closed-time-regexp
3281 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3282 org-keyword-time-regexp
3283 (concat "\\<\\(" org-scheduled-string
3284 "\\|" org-deadline-string
3285 "\\|" org-closed-string
3286 "\\|" org-clock-string "\\)"
3287 " *[[<]\\([^]>]+\\)[]>]")
3288 org-keyword-time-not-clock-regexp
3289 (concat "\\<\\(" org-scheduled-string
3290 "\\|" org-deadline-string
3291 "\\|" org-closed-string "\\)"
3292 " *[[<]\\([^]>]+\\)[]>]")
3293 org-maybe-keyword-time-regexp
3294 (concat "\\(\\<\\(" org-scheduled-string
3295 "\\|" org-deadline-string
3296 "\\|" org-closed-string
3297 "\\|" org-clock-string "\\)\\)?"
3298 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3300 (org-set-font-lock-defaults)))
3303 ;;; Some variables ujsed in various places
3305 (defvar org-window-configuration nil
3306 "Used in various places to store a window configuration.")
3307 (defvar org-finish-function nil
3308 "Function to be called when `C-c C-c' is used.
3309 This is for getting out of special buffers like remember.")
3311 ;;; Foreign variables, to inform the compiler
3313 ;; XEmacs only
3314 (defvar outline-mode-menu-heading)
3315 (defvar outline-mode-menu-show)
3316 (defvar outline-mode-menu-hide)
3317 (defvar zmacs-regions) ; XEmacs regions
3318 ;; Emacs only
3319 (defvar mark-active)
3321 ;; Packages that org-mode interacts with
3322 (defvar calc-embedded-close-formula)
3323 (defvar calc-embedded-open-formula)
3324 (defvar font-lock-unfontify-region-function)
3325 (defvar org-goto-start-pos)
3326 (defvar vm-message-pointer)
3327 (defvar vm-folder-directory)
3328 (defvar wl-summary-buffer-elmo-folder)
3329 (defvar wl-summary-buffer-folder-name)
3330 (defvar gnus-other-frame-object)
3331 (defvar gnus-group-name)
3332 (defvar gnus-article-current)
3333 (defvar w3m-current-url)
3334 (defvar w3m-current-title)
3335 (defvar mh-progs)
3336 (defvar mh-current-folder)
3337 (defvar mh-show-folder-buffer)
3338 (defvar mh-index-folder)
3339 (defvar mh-searcher)
3340 (defvar calendar-mode-map)
3341 (defvar Info-current-file)
3342 (defvar Info-current-node)
3343 (defvar texmathp-why)
3344 (defvar remember-save-after-remembering)
3345 (defvar remember-data-file)
3346 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3347 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3348 (defvar org-latex-regexps)
3349 (defvar constants-unit-system)
3351 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3353 ;; FIXME: Occasionally check by commenting these, to make sure
3354 ;; no other functions uses these, forgetting to let-bind them.
3355 (defvar entry)
3356 (defvar state)
3357 (defvar last-state)
3358 (defvar date)
3359 (defvar description)
3362 ;; Defined somewhere in this file, but used before definition.
3363 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3364 (defvar org-agenda-undo-list)
3365 (defvar org-agenda-pending-undo-list)
3366 (defvar org-agenda-overriding-header)
3367 (defvar orgtbl-mode)
3368 (defvar org-html-entities)
3369 (defvar org-struct-menu)
3370 (defvar org-org-menu)
3371 (defvar org-tbl-menu)
3372 (defvar org-agenda-keymap)
3373 (defvar org-category-table)
3375 ;;;; Emacs/XEmacs compatibility
3377 ;; Overlay compatibility functions
3378 (defun org-make-overlay (beg end &optional buffer)
3379 (if (featurep 'xemacs)
3380 (make-extent beg end buffer)
3381 (make-overlay beg end buffer)))
3382 (defun org-delete-overlay (ovl)
3383 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3384 (defun org-detach-overlay (ovl)
3385 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3386 (defun org-move-overlay (ovl beg end &optional buffer)
3387 (if (featurep 'xemacs)
3388 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3389 (move-overlay ovl beg end buffer)))
3390 (defun org-overlay-put (ovl prop value)
3391 (if (featurep 'xemacs)
3392 (set-extent-property ovl prop value)
3393 (overlay-put ovl prop value)))
3394 (defun org-overlay-display (ovl text &optional face evap)
3395 "Make overlay OVL display TEXT with face FACE."
3396 (if (featurep 'xemacs)
3397 (let ((gl (make-glyph text)))
3398 (and face (set-glyph-face gl face))
3399 (set-extent-property ovl 'invisible t)
3400 (set-extent-property ovl 'end-glyph gl))
3401 (overlay-put ovl 'display text)
3402 (if face (overlay-put ovl 'face face))
3403 (if evap (overlay-put ovl 'evaporate t))))
3404 (defun org-overlay-before-string (ovl text &optional face evap)
3405 "Make overlay OVL display TEXT with face FACE."
3406 (if (featurep 'xemacs)
3407 (let ((gl (make-glyph text)))
3408 (and face (set-glyph-face gl face))
3409 (set-extent-property ovl 'begin-glyph gl))
3410 (if face (org-add-props text nil 'face face))
3411 (overlay-put ovl 'before-string text)
3412 (if evap (overlay-put ovl 'evaporate t))))
3413 (defun org-overlay-get (ovl prop)
3414 (if (featurep 'xemacs)
3415 (extent-property ovl prop)
3416 (overlay-get ovl prop)))
3417 (defun org-overlays-at (pos)
3418 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3419 (defun org-overlays-in (&optional start end)
3420 (if (featurep 'xemacs)
3421 (extent-list nil start end)
3422 (overlays-in start end)))
3423 (defun org-overlay-start (o)
3424 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3425 (defun org-overlay-end (o)
3426 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3427 (defun org-find-overlays (prop &optional pos delete)
3428 "Find all overlays specifying PROP at POS or point.
3429 If DELETE is non-nil, delete all those overlays."
3430 (let ((overlays (org-overlays-at (or pos (point))))
3431 ov found)
3432 (while (setq ov (pop overlays))
3433 (if (org-overlay-get ov prop)
3434 (if delete (org-delete-overlay ov) (push ov found))))
3435 found))
3437 ;; Region compatibility
3439 (defun org-add-hook (hook function &optional append local)
3440 "Add-hook, compatible with both Emacsen."
3441 (if (and local (featurep 'xemacs))
3442 (add-local-hook hook function append)
3443 (add-hook hook function append local)))
3445 (defvar org-ignore-region nil
3446 "To temporarily disable the active region.")
3448 (defun org-region-active-p ()
3449 "Is `transient-mark-mode' on and the region active?
3450 Works on both Emacs and XEmacs."
3451 (if org-ignore-region
3453 (if (featurep 'xemacs)
3454 (and zmacs-regions (region-active-p))
3455 (and transient-mark-mode mark-active))))
3457 ;; Invisibility compatibility
3459 (defun org-add-to-invisibility-spec (arg)
3460 "Add elements to `buffer-invisibility-spec'.
3461 See documentation for `buffer-invisibility-spec' for the kind of elements
3462 that can be added."
3463 (cond
3464 ((fboundp 'add-to-invisibility-spec)
3465 (add-to-invisibility-spec arg))
3466 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3467 (setq buffer-invisibility-spec (list arg)))
3469 (setq buffer-invisibility-spec
3470 (cons arg buffer-invisibility-spec)))))
3472 (defun org-remove-from-invisibility-spec (arg)
3473 "Remove elements from `buffer-invisibility-spec'."
3474 (if (fboundp 'remove-from-invisibility-spec)
3475 (remove-from-invisibility-spec arg)
3476 (if (consp buffer-invisibility-spec)
3477 (setq buffer-invisibility-spec
3478 (delete arg buffer-invisibility-spec)))))
3480 (defun org-in-invisibility-spec-p (arg)
3481 "Is ARG a member of `buffer-invisibility-spec'?"
3482 (if (consp buffer-invisibility-spec)
3483 (member arg buffer-invisibility-spec)
3484 nil))
3486 ;;;; Define the Org-mode
3488 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3489 (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."))
3492 ;; We use a before-change function to check if a table might need
3493 ;; an update.
3494 (defvar org-table-may-need-update t
3495 "Indicates that a table might need an update.
3496 This variable is set by `org-before-change-function'.
3497 `org-table-align' sets it back to nil.")
3498 (defvar org-mode-map)
3499 (defvar org-mode-hook nil)
3500 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3501 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3504 ;;;###autoload
3505 (define-derived-mode org-mode outline-mode "Org"
3506 "Outline-based notes management and organizer, alias
3507 \"Carsten's outline-mode for keeping track of everything.\"
3509 Org-mode develops organizational tasks around a NOTES file which
3510 contains information about projects as plain text. Org-mode is
3511 implemented on top of outline-mode, which is ideal to keep the content
3512 of large files well structured. It supports ToDo items, deadlines and
3513 time stamps, which magically appear in the diary listing of the Emacs
3514 calendar. Tables are easily created with a built-in table editor.
3515 Plain text URL-like links connect to websites, emails (VM), Usenet
3516 messages (Gnus), BBDB entries, and any files related to the project.
3517 For printing and sharing of notes, an Org-mode file (or a part of it)
3518 can be exported as a structured ASCII or HTML file.
3520 The following commands are available:
3522 \\{org-mode-map}"
3524 ;; Get rid of Outline menus, they are not needed
3525 ;; Need to do this here because define-derived-mode sets up
3526 ;; the keymap so late. Still, it is a waste to call this each time
3527 ;; we switch another buffer into org-mode.
3528 (if (featurep 'xemacs)
3529 (when (boundp 'outline-mode-menu-heading)
3530 ;; Assume this is Greg's port, it used easymenu
3531 (easy-menu-remove outline-mode-menu-heading)
3532 (easy-menu-remove outline-mode-menu-show)
3533 (easy-menu-remove outline-mode-menu-hide))
3534 (define-key org-mode-map [menu-bar headings] 'undefined)
3535 (define-key org-mode-map [menu-bar hide] 'undefined)
3536 (define-key org-mode-map [menu-bar show] 'undefined))
3538 (easy-menu-add org-org-menu)
3539 (easy-menu-add org-tbl-menu)
3540 (org-install-agenda-files-menu)
3541 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3542 (org-add-to-invisibility-spec '(org-cwidth))
3543 (when (featurep 'xemacs)
3544 (org-set-local 'line-move-ignore-invisible t))
3545 (setq outline-regexp "\\*+")
3546 (setq outline-level 'org-outline-level)
3547 (when (and org-ellipsis (stringp org-ellipsis)
3548 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
3549 (unless org-display-table
3550 (setq org-display-table (make-display-table)))
3551 (set-display-table-slot org-display-table
3552 4 (string-to-vector org-ellipsis))
3553 (setq buffer-display-table org-display-table))
3554 (org-set-regexps-and-options)
3555 ;; Calc embedded
3556 (org-set-local 'calc-embedded-open-mode "# ")
3557 (modify-syntax-entry ?# "<")
3558 (modify-syntax-entry ?@ "w")
3559 (if org-startup-truncated (setq truncate-lines t))
3560 (org-set-local 'font-lock-unfontify-region-function
3561 'org-unfontify-region)
3562 ;; Activate before-change-function
3563 (org-set-local 'org-table-may-need-update t)
3564 (org-add-hook 'before-change-functions 'org-before-change-function nil
3565 'local)
3566 ;; Check for running clock before killing a buffer
3567 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3568 ;; Paragraphs and auto-filling
3569 (org-set-autofill-regexps)
3570 (setq indent-line-function 'org-indent-line-function)
3571 (org-update-radio-target-regexp)
3573 ;; Comment characters
3574 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3575 (org-set-local 'comment-padding " ")
3577 ;; Make isearch reveal context
3578 (if (or (featurep 'xemacs)
3579 (not (boundp 'outline-isearch-open-invisible-function)))
3580 ;; Emacs 21 and XEmacs make use of the hook
3581 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3582 ;; Emacs 22 deals with this through a special variable
3583 (org-set-local 'outline-isearch-open-invisible-function
3584 (lambda (&rest ignore) (org-show-context 'isearch))))
3586 ;; If empty file that did not turn on org-mode automatically, make it to.
3587 (if (and org-insert-mode-line-in-empty-file
3588 (interactive-p)
3589 (= (point-min) (point-max)))
3590 (insert " -*- mode: org -*-\n\n"))
3592 (unless org-inhibit-startup
3593 (when org-startup-align-all-tables
3594 (let ((bmp (buffer-modified-p)))
3595 (org-table-map-tables 'org-table-align)
3596 (set-buffer-modified-p bmp)))
3597 (cond
3598 ((eq org-startup-folded t)
3599 (org-cycle '(4)))
3600 ((eq org-startup-folded 'content)
3601 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3602 (org-cycle '(4)) (org-cycle '(4)))))))
3604 (defsubst org-call-with-arg (command arg)
3605 "Call COMMAND interactively, but pretend prefix are was ARG."
3606 (let ((current-prefix-arg arg)) (call-interactively command)))
3608 (defsubst org-current-line (&optional pos)
3609 (save-excursion
3610 (and pos (goto-char pos))
3611 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
3613 (defun org-current-time ()
3614 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3615 (if (> org-time-stamp-rounding-minutes 0)
3616 (let ((r org-time-stamp-rounding-minutes)
3617 (time (decode-time)))
3618 (apply 'encode-time
3619 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3620 (nthcdr 2 time))))
3621 (current-time)))
3623 (defun org-add-props (string plist &rest props)
3624 "Add text properties to entire string, from beginning to end.
3625 PLIST may be a list of properties, PROPS are individual properties and values
3626 that will be added to PLIST. Returns the string that was modified."
3627 (add-text-properties
3628 0 (length string) (if props (append plist props) plist) string)
3629 string)
3630 (put 'org-add-props 'lisp-indent-function 2)
3633 ;;;; Font-Lock stuff, including the activators
3635 (defvar org-mouse-map (make-sparse-keymap))
3636 (define-key org-mouse-map
3637 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3638 (define-key org-mouse-map
3639 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3640 (when org-mouse-1-follows-link
3641 (define-key org-mouse-map [follow-link] 'mouse-face))
3642 (when org-tab-follows-link
3643 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3644 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3645 (when org-return-follows-link
3646 (define-key org-mouse-map [(return)] 'org-open-at-point)
3647 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3649 (require 'font-lock)
3651 (defconst org-non-link-chars "]\t\n\r<>")
3652 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3653 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3654 (defconst org-link-re-with-space
3655 (concat
3656 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3657 "\\([^" org-non-link-chars " ]"
3658 "[^" org-non-link-chars "]*"
3659 "[^" org-non-link-chars " ]\\)>?")
3660 "Matches a link with spaces, optional angular brackets around it.")
3662 (defconst org-link-re-with-space2
3663 (concat
3664 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3665 "\\([^" org-non-link-chars " ]"
3666 "[^]\t\n\r]*"
3667 "[^" org-non-link-chars " ]\\)>?")
3668 "Matches a link with spaces, optional angular brackets around it.")
3670 (defconst org-angle-link-re
3671 (concat
3672 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3673 "\\([^" org-non-link-chars " ]"
3674 "[^" org-non-link-chars "]*"
3675 "\\)>")
3676 "Matches link with angular brackets, spaces are allowed.")
3677 (defconst org-plain-link-re
3678 (concat
3679 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3680 "\\([^]\t\n\r<>,;() ]+\\)")
3681 "Matches plain link, without spaces.")
3683 (defconst org-bracket-link-regexp
3684 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3685 "Matches a link in double brackets.")
3687 (defconst org-bracket-link-analytic-regexp
3688 (concat
3689 "\\[\\["
3690 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3691 "\\([^]]+\\)"
3692 "\\]"
3693 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3694 "\\]"))
3695 ; 1: http:
3696 ; 2: http
3697 ; 3: path
3698 ; 4: [desc]
3699 ; 5: desc
3701 (defconst org-any-link-re
3702 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3703 org-angle-link-re "\\)\\|\\("
3704 org-plain-link-re "\\)")
3705 "Regular expression matching any link.")
3707 (defconst org-ts-lengths
3708 (cons (length (format-time-string (car org-time-stamp-formats)))
3709 (length (format-time-string (cdr org-time-stamp-formats))))
3710 "This holds the lengths of the two different time formats.")
3711 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3712 "Regular expression for fast time stamp matching.")
3713 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3714 "Regular expression for fast time stamp matching.")
3715 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3716 "Regular expression matching time strings for analysis.")
3717 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3718 "Regular expression matching time stamps, with groups.")
3719 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3720 "Regular expression matching time stamps (also [..]), with groups.")
3721 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3722 "Regular expression matching a time stamp range.")
3723 (defconst org-tr-regexp-both
3724 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3725 "Regular expression matching a time stamp range.")
3726 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3727 org-ts-regexp "\\)?")
3728 "Regular expression matching a time stamp or time stamp range.")
3729 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3730 org-ts-regexp-both "\\)?")
3731 "Regular expression matching a time stamp or time stamp range.
3732 The time stamps may be either active or inactive.")
3734 (defvar org-emph-face nil)
3736 (defun org-do-emphasis-faces (limit)
3737 "Run through the buffer and add overlays to links."
3738 (if (re-search-forward org-emph-re limit t)
3739 (progn
3740 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3741 'face
3742 (nth 1 (assoc (match-string 3)
3743 org-emphasis-alist)))
3744 (add-text-properties (match-beginning 2) (match-end 2)
3745 '(font-lock-multiline t))
3746 (backward-char 1)
3747 t)))
3749 (defun org-activate-plain-links (limit)
3750 "Run through the buffer and add overlays to links."
3751 (if (re-search-forward org-plain-link-re limit t)
3752 (progn
3753 (add-text-properties (match-beginning 0) (match-end 0)
3754 (list 'mouse-face 'highlight
3755 'rear-nonsticky t
3756 'keymap org-mouse-map
3758 t)))
3760 (defun org-activate-angle-links (limit)
3761 "Run through the buffer and add overlays to links."
3762 (if (re-search-forward org-angle-link-re limit t)
3763 (progn
3764 (add-text-properties (match-beginning 0) (match-end 0)
3765 (list 'mouse-face 'highlight
3766 'rear-nonsticky t
3767 'keymap org-mouse-map
3769 t)))
3771 (defmacro org-maybe-intangible (props)
3772 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3773 In emacs 21, invisible text is not avoided by the command loop, so the
3774 intangible property is needed to make sure point skips this text.
3775 In Emacs 22, this is not necessary. The intangible text property has
3776 led to problems with flyspell. These problems are fixed in flyspell.el,
3777 but we still avoid setting the property in Emacs 22 and later.
3778 We use a macro so that the test can happen at compilation time."
3779 (if (< emacs-major-version 22)
3780 `(append '(intangible t) ,props)
3781 props))
3783 (defun org-activate-bracket-links (limit)
3784 "Run through the buffer and add overlays to bracketed links."
3785 (if (re-search-forward org-bracket-link-regexp limit t)
3786 (let* ((help (concat "LINK: "
3787 (org-match-string-no-properties 1)))
3788 ;; FIXME: above we should remove the escapes.
3789 ;; but that requires another match, protecting match data,
3790 ;; a lot of overhead for font-lock.
3791 (ip (org-maybe-intangible
3792 (list 'invisible 'org-link 'rear-nonsticky t
3793 'keymap org-mouse-map 'mouse-face 'highlight
3794 'help-echo help)))
3795 (vp (list 'rear-nonsticky t
3796 'keymap org-mouse-map 'mouse-face 'highlight
3797 'help-echo help)))
3798 ;; We need to remove the invisible property here. Table narrowing
3799 ;; may have made some of this invisible.
3800 (remove-text-properties (match-beginning 0) (match-end 0)
3801 '(invisible nil))
3802 (if (match-end 3)
3803 (progn
3804 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3805 (add-text-properties (match-beginning 3) (match-end 3) vp)
3806 (add-text-properties (match-end 3) (match-end 0) ip))
3807 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3808 (add-text-properties (match-beginning 1) (match-end 1) vp)
3809 (add-text-properties (match-end 1) (match-end 0) ip))
3810 t)))
3812 (defun org-activate-dates (limit)
3813 "Run through the buffer and add overlays to dates."
3814 (if (re-search-forward org-tsr-regexp-both 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 (when org-display-custom-times
3821 (if (match-end 3)
3822 (org-display-custom-time (match-beginning 3) (match-end 3)))
3823 (org-display-custom-time (match-beginning 1) (match-end 1)))
3824 t)))
3826 (defvar org-target-link-regexp nil
3827 "Regular expression matching radio targets in plain text.")
3828 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3829 "Regular expression matching a link target.")
3830 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3831 "Regular expression matching a link target.")
3833 (defun org-activate-target-links (limit)
3834 "Run through the buffer and add overlays to target matches."
3835 (when org-target-link-regexp
3836 (let ((case-fold-search t))
3837 (if (re-search-forward org-target-link-regexp limit t)
3838 (progn
3839 (add-text-properties (match-beginning 0) (match-end 0)
3840 (list 'mouse-face 'highlight
3841 'rear-nonsticky t
3842 'keymap org-mouse-map
3843 'help-echo "Radio target link"
3844 'org-linked-text t))
3845 t)))))
3847 (defun org-update-radio-target-regexp ()
3848 "Find all radio targets in this file and update the regular expression."
3849 (interactive)
3850 (when (memq 'radio org-activate-links)
3851 (setq org-target-link-regexp
3852 (org-make-target-link-regexp (org-all-targets 'radio)))
3853 (org-restart-font-lock)))
3855 (defun org-hide-wide-columns (limit)
3856 (let (s e)
3857 (setq s (text-property-any (point) (or limit (point-max))
3858 'org-cwidth t))
3859 (when s
3860 (setq e (next-single-property-change s 'org-cwidth))
3861 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3862 (goto-char e)
3863 t)))
3865 (defun org-restart-font-lock ()
3866 "Restart font-lock-mode, to force refontification."
3867 (when (and (boundp 'font-lock-mode) font-lock-mode)
3868 (font-lock-mode -1)
3869 (font-lock-mode 1)))
3871 (defun org-all-targets (&optional radio)
3872 "Return a list of all targets in this file.
3873 With optional argument RADIO, only find radio targets."
3874 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3875 rtn)
3876 (save-excursion
3877 (goto-char (point-min))
3878 (while (re-search-forward re nil t)
3879 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3880 rtn)))
3882 (defun org-make-target-link-regexp (targets)
3883 "Make regular expression matching all strings in TARGETS.
3884 The regular expression finds the targets also if there is a line break
3885 between words."
3886 (and targets
3887 (concat
3888 "\\<\\("
3889 (mapconcat
3890 (lambda (x)
3891 (while (string-match " +" x)
3892 (setq x (replace-match "\\s-+" t t x)))
3894 targets
3895 "\\|")
3896 "\\)\\>")))
3898 (defun org-activate-tags (limit)
3899 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3900 (progn
3901 (add-text-properties (match-beginning 1) (match-end 1)
3902 (list 'mouse-face 'highlight
3903 'rear-nonsticky t
3904 'keymap org-mouse-map))
3905 t)))
3907 (defun org-font-lock-level ()
3908 (save-excursion
3909 (org-back-to-heading t)
3910 (- (match-end 0) (match-beginning 0))))
3912 (defun org-outline-level ()
3913 (save-excursion
3914 (looking-at outline-regexp)
3915 (if (match-beginning 1)
3916 (+ (org-get-string-indentation (match-string 1)) 1000)
3917 (- (match-end 0) (match-beginning 0)))))
3919 (defvar org-font-lock-keywords nil)
3921 (defun org-set-font-lock-defaults ()
3922 (let* ((em org-fontify-emphasized-text)
3923 (lk org-activate-links)
3924 (org-font-lock-extra-keywords
3925 ;; Headlines
3926 (list
3927 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3928 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3929 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3930 (1 'org-table))
3931 ;; Links
3932 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3933 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3934 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3935 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3936 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3937 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3938 '(org-hide-wide-columns (0 nil append))
3939 ;; TODO lines
3940 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3941 '(1 'org-todo t))
3942 ;; Priorities
3943 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3944 ;; Special keywords
3945 (list org-repeat-re '(0 'org-special-keyword t))
3946 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3947 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3948 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3949 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3950 ;; Emphasis
3951 (if em
3952 (if (featurep 'xemacs)
3953 '(org-do-emphasis-faces (0 nil append))
3954 '(org-do-emphasis-faces)))
3955 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3956 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3957 2 'bold prepend)
3958 (if org-provide-checkbox-statistics
3959 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3960 (0 (org-get-checkbox-statistics-face) t)))
3961 ;; COMMENT
3962 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3963 "\\|" org-quote-string "\\)\\>")
3964 '(1 'org-special-keyword t))
3965 '("^#.*" (0 'font-lock-comment-face t))
3966 ;; DONE
3967 (if org-fontify-done-headline
3968 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3969 '(1 'org-done t) '(2 'org-headline-done t))
3970 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3971 '(1 'org-done t)))
3972 ;; Table stuff
3973 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3974 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3975 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3976 (if org-format-transports-properties-p
3977 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3978 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3980 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3981 ;; Now set the full font-lock-keywords
3982 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3983 (org-set-local 'font-lock-defaults
3984 '(org-font-lock-keywords t nil nil backward-paragraph))
3985 (kill-local-variable 'font-lock-keywords) nil))
3987 (defvar org-m nil)
3988 (defvar org-l nil)
3989 (defvar org-f nil)
3990 (defun org-get-level-face (n)
3991 "Get the right face for match N in font-lock matching of healdines."
3992 (setq org-l (- (match-end 2) (match-beginning 1)))
3993 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3994 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3995 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3996 (cond
3997 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3998 ((eq n 2) org-f)
3999 (t (if org-level-color-stars-only nil org-f))))
4001 (defun org-unfontify-region (beg end &optional maybe_loudly)
4002 "Remove fontification and activation overlays from links."
4003 (font-lock-default-unfontify-region beg end)
4004 (let* ((buffer-undo-list t)
4005 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4006 (inhibit-modification-hooks t)
4007 deactivate-mark buffer-file-name buffer-file-truename)
4008 (remove-text-properties beg end
4009 '(mouse-face t keymap t org-linked-text t
4010 rear-nonsticky t
4011 invisible t intangible t))))
4013 ;;;; Visibility cycling, including org-goto and indirect buffer
4015 ;;; Cycling
4017 (defvar org-cycle-global-status nil)
4018 (make-variable-buffer-local 'org-cycle-global-status)
4019 (defvar org-cycle-subtree-status nil)
4020 (make-variable-buffer-local 'org-cycle-subtree-status)
4022 ;;;###autoload
4023 (defun org-cycle (&optional arg)
4024 "Visibility cycling for Org-mode.
4026 - When this function is called with a prefix argument, rotate the entire
4027 buffer through 3 states (global cycling)
4028 1. OVERVIEW: Show only top-level headlines.
4029 2. CONTENTS: Show all headlines of all levels, but no body text.
4030 3. SHOW ALL: Show everything.
4032 - When point is at the beginning of a headline, rotate the subtree started
4033 by this line through 3 different states (local cycling)
4034 1. FOLDED: Only the main headline is shown.
4035 2. CHILDREN: The main headline and the direct children are shown.
4036 From this state, you can move to one of the children
4037 and zoom in further.
4038 3. SUBTREE: Show the entire subtree, including body text.
4040 - When there is a numeric prefix, go up to a heading with level ARG, do
4041 a `show-subtree' and return to the previous cursor position. If ARG
4042 is negative, go up that many levels.
4044 - When point is not at the beginning of a headline, execute
4045 `indent-relative', like TAB normally does. See the option
4046 `org-cycle-emulate-tab' for details.
4048 - Special case: if point is the the beginning of the buffer and there is
4049 no headline in line 1, this function will act as if called with prefix arg."
4050 (interactive "P")
4051 (let* ((outline-regexp
4052 (if (and (org-mode-p) org-cycle-include-plain-lists)
4053 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4054 outline-regexp))
4055 (bob-special (and org-cycle-global-at-bob (bobp)
4056 (not (looking-at outline-regexp))))
4057 (org-cycle-hook
4058 (if bob-special
4059 (delq 'org-optimize-window-after-visibility-change
4060 (copy-sequence org-cycle-hook))
4061 org-cycle-hook))
4062 (pos (point)))
4064 (if (or bob-special (equal arg '(4)))
4065 ;; special case: use global cycling
4066 (setq arg t))
4068 (cond
4070 ((org-at-table-p 'any)
4071 ;; Enter the table or move to the next field in the table
4072 (or (org-table-recognize-table.el)
4073 (progn
4074 (if arg (org-table-edit-field t)
4075 (org-table-justify-field-maybe)
4076 (call-interactively 'org-table-next-field)))))
4078 ((eq arg t) ;; Global cycling
4080 (cond
4081 ((and (eq last-command this-command)
4082 (eq org-cycle-global-status 'overview))
4083 ;; We just created the overview - now do table of contents
4084 ;; This can be slow in very large buffers, so indicate action
4085 (message "CONTENTS...")
4086 (org-content)
4087 (message "CONTENTS...done")
4088 (setq org-cycle-global-status 'contents)
4089 (run-hook-with-args 'org-cycle-hook 'contents))
4091 ((and (eq last-command this-command)
4092 (eq org-cycle-global-status 'contents))
4093 ;; We just showed the table of contents - now show everything
4094 (show-all)
4095 (message "SHOW ALL")
4096 (setq org-cycle-global-status 'all)
4097 (run-hook-with-args 'org-cycle-hook 'all))
4100 ;; Default action: go to overview
4101 (org-overview)
4102 (message "OVERVIEW")
4103 (setq org-cycle-global-status 'overview)
4104 (run-hook-with-args 'org-cycle-hook 'overview))))
4106 ((integerp arg)
4107 ;; Show-subtree, ARG levels up from here.
4108 (save-excursion
4109 (org-back-to-heading)
4110 (outline-up-heading (if (< arg 0) (- arg)
4111 (- (funcall outline-level) arg)))
4112 (org-show-subtree)))
4114 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4115 ;; At a heading: rotate between three different views
4116 (org-back-to-heading)
4117 (let ((goal-column 0) eoh eol eos)
4118 ;; First, some boundaries
4119 (save-excursion
4120 (org-back-to-heading)
4121 (save-excursion
4122 (beginning-of-line 2)
4123 (while (and (not (eobp)) ;; this is like `next-line'
4124 (get-char-property (1- (point)) 'invisible))
4125 (beginning-of-line 2)) (setq eol (point)))
4126 (outline-end-of-heading) (setq eoh (point))
4127 (org-end-of-subtree t)
4128 (skip-chars-forward " \t\n")
4129 (beginning-of-line 1) ; in case this is an item
4130 (setq eos (1- (point))))
4131 ;; Find out what to do next and set `this-command'
4132 (cond
4133 ((= eos eoh)
4134 ;; Nothing is hidden behind this heading
4135 (message "EMPTY ENTRY")
4136 (setq org-cycle-subtree-status nil))
4137 ((>= eol eos)
4138 ;; Entire subtree is hidden in one line: open it
4139 (org-show-entry)
4140 (show-children)
4141 (message "CHILDREN")
4142 (setq org-cycle-subtree-status 'children)
4143 (run-hook-with-args 'org-cycle-hook 'children))
4144 ((and (eq last-command this-command)
4145 (eq org-cycle-subtree-status 'children))
4146 ;; We just showed the children, now show everything.
4147 (org-show-subtree)
4148 (message "SUBTREE")
4149 (setq org-cycle-subtree-status 'subtree)
4150 (run-hook-with-args 'org-cycle-hook 'subtree))
4152 ;; Default action: hide the subtree.
4153 (hide-subtree)
4154 (message "FOLDED")
4155 (setq org-cycle-subtree-status 'folded)
4156 (run-hook-with-args 'org-cycle-hook 'folded)))))
4158 ;; TAB emulation
4159 (buffer-read-only (org-back-to-heading))
4161 ((org-try-cdlatex-tab))
4163 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4164 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4165 (or (and (eq org-cycle-emulate-tab 'white)
4166 (= (match-end 0) (point-at-eol)))
4167 (and (eq org-cycle-emulate-tab 'whitestart)
4168 (>= (match-end 0) pos))))
4170 (eq org-cycle-emulate-tab t))
4171 (if (and (looking-at "[ \n\r\t]")
4172 (string-match "^[ \t]*$" (buffer-substring
4173 (point-at-bol) (point))))
4174 (progn
4175 (beginning-of-line 1)
4176 (and (looking-at "[ \t]+") (replace-match ""))))
4177 (indent-relative))
4179 (t (save-excursion
4180 (org-back-to-heading)
4181 (org-cycle))))))
4183 ;;;###autoload
4184 (defun org-global-cycle (&optional arg)
4185 "Cycle the global visibility. For details see `org-cycle'."
4186 (interactive "P")
4187 (let ((org-cycle-include-plain-lists
4188 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4189 (if (integerp arg)
4190 (progn
4191 (show-all)
4192 (hide-sublevels arg)
4193 (setq org-cycle-global-status 'contents))
4194 (org-cycle '(4)))))
4196 (defun org-overview ()
4197 "Switch to overview mode, shoing only top-level headlines.
4198 Really, this shows all headlines with level equal or greater than the level
4199 of the first headline in the buffer. This is important, because if the
4200 first headline is not level one, then (hide-sublevels 1) gives confusing
4201 results."
4202 (interactive)
4203 (hide-sublevels (save-excursion
4204 (goto-char (point-min))
4205 (if (re-search-forward (concat "^" outline-regexp) nil t)
4206 (progn
4207 (goto-char (match-beginning 0))
4208 (funcall outline-level))
4209 1))))
4211 (defun org-content (&optional arg)
4212 "Show all headlines in the buffer, like a table of contents.
4213 With numerical argument N, show content up to level N."
4214 (interactive "P")
4215 (save-excursion
4216 ;; Visit all headings and show their offspring
4217 (and (integerp arg) (org-overview))
4218 (goto-char (point-max))
4219 (catch 'exit
4220 (while (and (progn (condition-case nil
4221 (outline-previous-visible-heading 1)
4222 (error (goto-char (point-min))))
4224 (looking-at outline-regexp))
4225 (if (integerp arg)
4226 (show-children (1- arg))
4227 (show-branches))
4228 (if (bobp) (throw 'exit nil))))))
4231 (defun org-optimize-window-after-visibility-change (state)
4232 "Adjust the window after a change in outline visibility.
4233 This function is the default value of the hook `org-cycle-hook'."
4234 (when (get-buffer-window (current-buffer))
4235 (cond
4236 ((eq state 'overview) (org-first-headline-recenter 1))
4237 ((eq state 'content) nil)
4238 ((eq state 'all) nil)
4239 ((eq state 'folded) nil)
4240 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4241 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4243 (defun org-subtree-end-visible-p ()
4244 "Is the end of the current subtree visible?"
4245 (pos-visible-in-window-p
4246 (save-excursion (org-end-of-subtree t) (point))))
4248 (defun org-first-headline-recenter (&optional N)
4249 "Move cursor to the first headline and recenter the headline.
4250 Optional argument N means, put the headline into the Nth line of the window."
4251 (goto-char (point-min))
4252 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4253 (beginning-of-line)
4254 (recenter (prefix-numeric-value N))))
4256 ;;; Org-goto
4258 (defvar org-goto-window-configuration nil)
4259 (defvar org-goto-marker nil)
4260 (defvar org-goto-map (make-sparse-keymap))
4261 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4262 (while (setq cmd (pop cmds))
4263 (substitute-key-definition cmd cmd org-goto-map global-map)))
4264 (define-key org-goto-map "\C-m" 'org-goto-ret)
4265 (define-key org-goto-map [(left)] 'org-goto-left)
4266 (define-key org-goto-map [(right)] 'org-goto-right)
4267 (define-key org-goto-map [(?q)] 'org-goto-quit)
4268 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
4269 (define-key org-goto-map "\C-i" 'org-cycle)
4270 (define-key org-goto-map [(tab)] 'org-cycle)
4271 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
4272 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
4273 (define-key org-goto-map "n" 'outline-next-visible-heading)
4274 (define-key org-goto-map "p" 'outline-previous-visible-heading)
4275 (define-key org-goto-map "f" 'outline-forward-same-level)
4276 (define-key org-goto-map "b" 'outline-backward-same-level)
4277 (define-key org-goto-map "u" 'outline-up-heading)
4278 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4279 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4280 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4281 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4282 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
4283 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4284 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
4286 (defconst org-goto-help
4287 "Select a location to jump to, press RET
4288 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4290 (defun org-goto ()
4291 "Go to a different location of the document, keeping current visibility.
4293 When you want to go to a different location in a document, the fastest way
4294 is often to fold the entire buffer and then dive into the tree. This
4295 method has the disadvantage, that the previous location will be folded,
4296 which may not be what you want.
4298 This command works around this by showing a copy of the current buffer in
4299 overview mode. You can dive into the tree in that copy, to find the
4300 location you want to reach. When pressing RET, the command returns to the
4301 original buffer in which the visibility is still unchanged. It then jumps
4302 to the new location, making it and the headline hierarchy above it visible."
4303 (interactive)
4304 (let* ((org-goto-start-pos (point))
4305 (selected-point
4306 (org-get-location (current-buffer) org-goto-help)))
4307 (if selected-point
4308 (progn
4309 (org-mark-ring-push org-goto-start-pos)
4310 (goto-char selected-point)
4311 (if (or (org-invisible-p) (org-invisible-p2))
4312 (org-show-context 'org-goto)))
4313 (error "Quit"))))
4315 (defvar org-selected-point nil) ; dynamically scoped parameter
4317 (defun org-get-location (buf help)
4318 "Let the user select a location in the Org-mode buffer BUF.
4319 This function uses a recursive edit. It returns the selected position
4320 or nil."
4321 (let (org-selected-point)
4322 (save-excursion
4323 (save-window-excursion
4324 (delete-other-windows)
4325 (switch-to-buffer (get-buffer-create "*org-goto*"))
4326 (with-output-to-temp-buffer "*Help*"
4327 (princ help))
4328 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4329 (setq buffer-read-only nil)
4330 (erase-buffer)
4331 (insert-buffer-substring buf)
4332 (let ((org-startup-truncated t)
4333 (org-startup-folded t)
4334 (org-startup-align-all-tables nil))
4335 (org-mode))
4336 (setq buffer-read-only t)
4337 (if (and (boundp 'org-goto-start-pos)
4338 (integer-or-marker-p org-goto-start-pos))
4339 (let ((org-show-hierarchy-above t)
4340 (org-show-siblings t)
4341 (org-show-following-heading t))
4342 (goto-char org-goto-start-pos)
4343 (and (org-invisible-p) (org-show-context)))
4344 (goto-char (point-min)))
4345 (org-beginning-of-line)
4346 (message "Select location and press RET")
4347 ;; now we make sure that during selection, ony very few keys work
4348 ;; and that it is impossible to switch to another window.
4349 (let ((gm (current-global-map))
4350 (overriding-local-map org-goto-map))
4351 (unwind-protect
4352 (progn
4353 (use-global-map org-goto-map)
4354 (recursive-edit))
4355 (use-global-map gm)))))
4356 (kill-buffer "*org-goto*")
4357 org-selected-point))
4359 (defun org-goto-ret (&optional arg)
4360 "Finish `org-goto' by going to the new location."
4361 (interactive "P")
4362 (setq org-selected-point (point)
4363 current-prefix-arg arg)
4364 (throw 'exit nil))
4366 (defun org-goto-left ()
4367 "Finish `org-goto' by going to the new location."
4368 (interactive)
4369 (if (org-on-heading-p)
4370 (progn
4371 (beginning-of-line 1)
4372 (setq org-selected-point (point)
4373 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4374 (throw 'exit nil))
4375 (error "Not on a heading")))
4377 (defun org-goto-right ()
4378 "Finish `org-goto' by going to the new location."
4379 (interactive)
4380 (if (org-on-heading-p)
4381 (progn
4382 (outline-end-of-subtree)
4383 (or (eobp) (forward-char 1))
4384 (setq org-selected-point (point)
4385 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4386 (throw 'exit nil))
4387 (error "Not on a heading")))
4389 (defun org-goto-quit ()
4390 "Finish `org-goto' without cursor motion."
4391 (interactive)
4392 (setq org-selected-point nil)
4393 (throw 'exit nil))
4395 ;;; Indirect buffer display of subtrees
4397 (defvar org-indirect-dedicated-frame nil
4398 "This is the frame being used for indirect tree display.")
4399 (defvar org-last-indirect-buffer nil)
4401 (defun org-tree-to-indirect-buffer (&optional arg)
4402 "Create indirect buffer and narrow it to current subtree.
4403 With numerical prefix ARG, go up to this level and then take that tree.
4404 If ARG is negative, go up that many levels.
4405 Normally this command removes the indirect buffer previously made
4406 with this command. However, when called with a C-u prefix, the last buffer
4407 is kept so that you can work with several indirect buffers at the same time.
4408 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4409 requests that a new frame be made for the new buffer, so that the dedicated
4410 frame is not changed."
4411 (interactive "P")
4412 (let ((cbuf (current-buffer))
4413 (cwin (selected-window))
4414 (pos (point))
4415 beg end level heading ibuf)
4416 (save-excursion
4417 (org-back-to-heading t)
4418 (when (numberp arg)
4419 (setq level (org-outline-level))
4420 (if (< arg 0) (setq arg (+ level arg)))
4421 (while (> (setq level (org-outline-level)) arg)
4422 (outline-up-heading 1 t)))
4423 (setq beg (point)
4424 heading (org-get-heading))
4425 (org-end-of-subtree t) (setq end (point)))
4426 (if (and (not arg)
4427 (buffer-live-p org-last-indirect-buffer))
4428 (kill-buffer org-last-indirect-buffer))
4429 (setq ibuf (org-get-indirect-buffer cbuf)
4430 org-last-indirect-buffer ibuf)
4431 (cond
4432 ((or (eq org-indirect-buffer-display 'new-frame)
4433 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4434 (select-frame (make-frame))
4435 (delete-other-windows)
4436 (switch-to-buffer ibuf)
4437 (org-set-frame-title heading))
4438 ((eq org-indirect-buffer-display 'dedicated-frame)
4439 (raise-frame
4440 (select-frame (or (and org-indirect-dedicated-frame
4441 (frame-live-p org-indirect-dedicated-frame)
4442 org-indirect-dedicated-frame)
4443 (setq org-indirect-dedicated-frame (make-frame)))))
4444 (delete-other-windows)
4445 (switch-to-buffer ibuf)
4446 (org-set-frame-title (concat "Indirect: " heading)))
4447 ((eq org-indirect-buffer-display 'current-window)
4448 (switch-to-buffer ibuf))
4449 ((eq org-indirect-buffer-display 'other-window)
4450 (pop-to-buffer ibuf))
4451 (t (error "Invalid value.")))
4452 (if (featurep 'xemacs)
4453 (save-excursion (org-mode) (turn-on-font-lock)))
4454 (narrow-to-region beg end)
4455 (show-all)
4456 (goto-char pos)
4457 (and (window-live-p cwin) (select-window cwin))))
4459 (defun org-get-indirect-buffer (&optional buffer)
4460 (setq buffer (or buffer (current-buffer)))
4461 (let ((n 1) (base (buffer-name buffer)) bname)
4462 (while (buffer-live-p
4463 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4464 (setq n (1+ n)))
4465 (condition-case nil
4466 (make-indirect-buffer buffer bname 'clone)
4467 (error (make-indirect-buffer buffer bname)))))
4469 (defun org-set-frame-title (title)
4470 "Set the title of the current frame to the string TITLE."
4471 ;; FIXME: how to name a single frame in XEmacs???
4472 (unless (featurep 'xemacs)
4473 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4475 ;;;; Structure editing
4477 ;;; Inserting headlines
4479 (defun org-insert-heading (&optional force-heading)
4480 "Insert a new heading or item with same depth at point.
4481 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4482 If point is at the beginning of a headline, insert a sibling before the
4483 current headline. If point is in the middle of a headline, split the headline
4484 at that position and make the rest of the headline part of the sibling below
4485 the current headline."
4486 (interactive "P")
4487 (if (= (buffer-size) 0)
4488 (insert "\n* ")
4489 (when (or force-heading (not (org-insert-item)))
4490 (let* ((head (save-excursion
4491 (condition-case nil
4492 (progn
4493 (org-back-to-heading)
4494 (match-string 0))
4495 (error "*"))))
4496 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4497 pos)
4498 (cond
4499 ((and (org-on-heading-p) (bolp)
4500 (or (bobp)
4501 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4502 (open-line (if blank 2 1)))
4503 ((and (bolp)
4504 (or (bobp)
4505 (save-excursion
4506 (backward-char 1) (not (org-invisible-p)))))
4507 nil)
4508 (t (newline (if blank 2 1))))
4509 (insert head) (just-one-space)
4510 (setq pos (point))
4511 (end-of-line 1)
4512 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4513 (run-hooks 'org-insert-heading-hook)))))
4516 (defun org-insert-todo-heading (arg)
4517 "Insert a new heading with the same level and TODO state as current heading.
4518 If the heading has no TODO state, or if the state is DONE, use the first
4519 state (TODO by default). Also with prefix arg, force first state."
4520 (interactive "P")
4521 (when (not (org-insert-item 'checkbox))
4522 (org-insert-heading)
4523 (save-excursion
4524 (org-back-to-heading)
4525 (outline-previous-heading)
4526 (looking-at org-todo-line-regexp))
4527 (if (or arg
4528 (not (match-beginning 2))
4529 (equal (match-string 2) org-done-string))
4530 (insert (car org-todo-keywords) " ")
4531 (insert (match-string 2) " "))))
4533 ;;; Promotion and Demotion
4535 (defun org-promote-subtree ()
4536 "Promote the entire subtree.
4537 See also `org-promote'."
4538 (interactive)
4539 (save-excursion
4540 (org-map-tree 'org-promote))
4541 (org-fix-position-after-promote))
4543 (defun org-demote-subtree ()
4544 "Demote the entire subtree. See `org-demote'.
4545 See also `org-promote'."
4546 (interactive)
4547 (save-excursion
4548 (org-map-tree 'org-demote))
4549 (org-fix-position-after-promote))
4552 (defun org-do-promote ()
4553 "Promote the current heading higher up the tree.
4554 If the region is active in `transient-mark-mode', promote all headings
4555 in the region."
4556 (interactive)
4557 (save-excursion
4558 (if (org-region-active-p)
4559 (org-map-region 'org-promote (region-beginning) (region-end))
4560 (org-promote)))
4561 (org-fix-position-after-promote))
4563 (defun org-do-demote ()
4564 "Demote the current heading lower down the tree.
4565 If the region is active in `transient-mark-mode', demote all headings
4566 in the region."
4567 (interactive)
4568 (save-excursion
4569 (if (org-region-active-p)
4570 (org-map-region 'org-demote (region-beginning) (region-end))
4571 (org-demote)))
4572 (org-fix-position-after-promote))
4574 (defun org-fix-position-after-promote ()
4575 "Make sure that after pro/demotion cursor position is right."
4576 (let ((pos (point)))
4577 (when (save-excursion
4578 (beginning-of-line 1)
4579 (looking-at org-todo-line-regexp)
4580 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4581 (cond ((eobp) (insert " "))
4582 ((eolp) (insert " "))
4583 ((equal (char-after) ?\ ) (forward-char 1))))))
4585 (defun org-get-legal-level (level &optional change)
4586 "Rectify a level change under the influence of `org-odd-levels-only'
4587 LEVEL is a current level, CHANGE is by how much the level should be
4588 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4589 even level numbers will become the next higher odd number."
4590 (if org-odd-levels-only
4591 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4592 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4593 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4594 (max 1 (+ level change))))
4596 (defun org-promote ()
4597 "Promote the current heading higher up the tree.
4598 If the region is active in `transient-mark-mode', promote all headings
4599 in the region."
4600 (org-back-to-heading t)
4601 (let* ((level (save-match-data (funcall outline-level)))
4602 (up-head (make-string (org-get-legal-level level -1) ?*))
4603 (diff (abs (- level (length up-head)))))
4604 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4605 (replace-match up-head nil t)
4606 ;; Fixup tag positioning
4607 (and org-auto-align-tags (org-set-tags nil t))
4608 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4610 (defun org-demote ()
4611 "Demote the current heading lower down the tree.
4612 If the region is active in `transient-mark-mode', demote all headings
4613 in the region."
4614 (org-back-to-heading t)
4615 (let* ((level (save-match-data (funcall outline-level)))
4616 (down-head (make-string (org-get-legal-level level 1) ?*))
4617 (diff (abs (- level (length down-head)))))
4618 (replace-match down-head nil t)
4619 ;; Fixup tag positioning
4620 (and org-auto-align-tags (org-set-tags nil t))
4621 (if org-adapt-indentation (org-fixup-indentation diff))))
4623 (defun org-map-tree (fun)
4624 "Call FUN for every heading underneath the current one."
4625 (org-back-to-heading)
4626 (let ((level (funcall outline-level)))
4627 (save-excursion
4628 (funcall fun)
4629 (while (and (progn
4630 (outline-next-heading)
4631 (> (funcall outline-level) level))
4632 (not (eobp)))
4633 (funcall fun)))))
4635 (defun org-map-region (fun beg end)
4636 "Call FUN for every heading between BEG and END."
4637 (let ((org-ignore-region t))
4638 (save-excursion
4639 (setq end (copy-marker end))
4640 (goto-char beg)
4641 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4642 (< (point) end))
4643 (funcall fun))
4644 (while (and (progn
4645 (outline-next-heading)
4646 (< (point) end))
4647 (not (eobp)))
4648 (funcall fun)))))
4650 (defun org-fixup-indentation (diff)
4651 "Change the indentation in the current entry by DIFF
4652 However, if any line in the current entry has no indentation, or if it
4653 would end up with no indentation after the change, nothing at all is done."
4654 (save-excursion
4655 (let ((end (save-excursion (outline-next-heading)
4656 (point-marker)))
4657 (prohibit (if (> diff 0)
4658 "^\\S-"
4659 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4660 col)
4661 (unless (save-excursion (re-search-forward prohibit end t))
4662 (while (re-search-forward "^[ \t]+" end t)
4663 (goto-char (match-end 0))
4664 (setq col (current-column))
4665 (if (< diff 0) (replace-match ""))
4666 (indent-to (+ diff col))))
4667 (move-marker end nil))))
4669 (defun org-convert-to-odd-levels ()
4670 "Convert an org-mode file with all levels allowed to one with odd levels.
4671 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4672 level 5 etc."
4673 (interactive)
4674 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4675 (let ((org-odd-levels-only nil) n)
4676 (save-excursion
4677 (goto-char (point-min))
4678 (while (re-search-forward "^\\*\\*+" nil t)
4679 (setq n (1- (length (match-string 0))))
4680 (while (>= (setq n (1- n)) 0)
4681 (org-demote))
4682 (end-of-line 1))))))
4685 (defun org-convert-to-oddeven-levels ()
4686 "Convert an org-mode file with only odd levels to one with odd and even levels.
4687 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4688 section with an even level, conversion would destroy the structure of the file. An error
4689 is signaled in this case."
4690 (interactive)
4691 (goto-char (point-min))
4692 ;; First check if there are no even levels
4693 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
4694 (org-show-context t)
4695 (error "Not all levels are odd in this file. Conversion not possible."))
4696 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4697 (let ((org-odd-levels-only nil) n)
4698 (save-excursion
4699 (goto-char (point-min))
4700 (while (re-search-forward "^\\*\\*+" nil t)
4701 (setq n (/ (length (match-string 0)) 2))
4702 (while (>= (setq n (1- n)) 0)
4703 (org-promote))
4704 (end-of-line 1))))))
4706 (defun org-tr-level (n)
4707 "Make N odd if required."
4708 (if org-odd-levels-only (1+ (/ n 2)) n))
4710 ;;; Vertical tree motion, cutting and pasting of subtrees
4712 (defun org-move-subtree-up (&optional arg)
4713 "Move the current subtree up past ARG headlines of the same level."
4714 (interactive "p")
4715 (org-move-subtree-down (- (prefix-numeric-value arg))))
4717 (defun org-move-subtree-down (&optional arg)
4718 "Move the current subtree down past ARG headlines of the same level."
4719 (interactive "p")
4720 (setq arg (prefix-numeric-value arg))
4721 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4722 'outline-get-last-sibling))
4723 (ins-point (make-marker))
4724 (cnt (abs arg))
4725 beg end txt folded)
4726 ;; Select the tree
4727 (org-back-to-heading)
4728 (setq beg (point))
4729 (save-match-data
4730 (save-excursion (outline-end-of-heading)
4731 (setq folded (org-invisible-p)))
4732 (outline-end-of-subtree))
4733 (outline-next-heading)
4734 (setq end (point))
4735 ;; Find insertion point, with error handling
4736 (goto-char beg)
4737 (while (> cnt 0)
4738 (or (and (funcall movfunc) (looking-at outline-regexp))
4739 (progn (goto-char beg)
4740 (error "Cannot move past superior level or buffer limit")))
4741 (setq cnt (1- cnt)))
4742 (if (> arg 0)
4743 ;; Moving forward - still need to move over subtree
4744 (progn (outline-end-of-subtree)
4745 (outline-next-heading)
4746 (if (not (or (looking-at (concat "^" outline-regexp))
4747 (bolp)))
4748 (newline))))
4749 (move-marker ins-point (point))
4750 (setq txt (buffer-substring beg end))
4751 (delete-region beg end)
4752 (insert txt)
4753 (goto-char ins-point)
4754 (if folded (hide-subtree))
4755 (move-marker ins-point nil)))
4757 (defvar org-subtree-clip ""
4758 "Clipboard for cut and paste of subtrees.
4759 This is actually only a copy of the kill, because we use the normal kill
4760 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4762 (defvar org-subtree-clip-folded nil
4763 "Was the last copied subtree folded?
4764 This is used to fold the tree back after pasting.")
4766 (defun org-cut-subtree ()
4767 "Cut the current subtree into the clipboard.
4768 This is a short-hand for marking the subtree and then cutting it."
4769 (interactive)
4770 (org-copy-subtree 'cut))
4772 (defun org-copy-subtree (&optional cut)
4773 "Cut the current subtree into the clipboard.
4774 This is a short-hand for marking the subtree and then copying it.
4775 If CUT is non-nil, actually cut the subtree."
4776 (interactive)
4777 (let (beg end folded)
4778 (org-back-to-heading)
4779 (setq beg (point))
4780 (save-match-data
4781 (save-excursion (outline-end-of-heading)
4782 (setq folded (org-invisible-p)))
4783 (outline-end-of-subtree))
4784 (if (equal (char-after) ?\n) (forward-char 1))
4785 (setq end (point))
4786 (goto-char beg)
4787 (when (> end beg)
4788 (setq org-subtree-clip-folded folded)
4789 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4790 (setq org-subtree-clip (current-kill 0))
4791 (message "%s: Subtree with %d characters"
4792 (if cut "Cut" "Copied")
4793 (length org-subtree-clip)))))
4795 (defun org-paste-subtree (&optional level tree)
4796 "Paste the clipboard as a subtree, with modification of headline level.
4797 The entire subtree is promoted or demoted in order to match a new headline
4798 level. By default, the new level is derived from the visible headings
4799 before and after the insertion point, and taken to be the inferior headline
4800 level of the two. So if the previous visible heading is level 3 and the
4801 next is level 4 (or vice versa), level 4 will be used for insertion.
4802 This makes sure that the subtree remains an independent subtree and does
4803 not swallow low level entries.
4805 You can also force a different level, either by using a numeric prefix
4806 argument, or by inserting the heading marker by hand. For example, if the
4807 cursor is after \"*****\", then the tree will be shifted to level 5.
4809 If you want to insert the tree as is, just use \\[yank].
4811 If optional TREE is given, use this text instead of the kill ring."
4812 (interactive "P")
4813 (unless (org-kill-is-subtree-p tree)
4814 (error
4815 (substitute-command-keys
4816 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4817 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4818 (^re (concat "^\\(" outline-regexp "\\)"))
4819 (re (concat "\\(" outline-regexp "\\)"))
4820 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4822 (old-level (if (string-match ^re txt)
4823 (- (match-end 0) (match-beginning 0))
4824 -1))
4825 (force-level (cond (level (prefix-numeric-value level))
4826 ((string-match
4827 ^re_ (buffer-substring (point-at-bol) (point)))
4828 (- (match-end 0) (match-beginning 0)))
4829 (t nil)))
4830 (previous-level (save-excursion
4831 (condition-case nil
4832 (progn
4833 (outline-previous-visible-heading 1)
4834 (if (looking-at re)
4835 (- (match-end 0) (match-beginning 0))
4837 (error 1))))
4838 (next-level (save-excursion
4839 (condition-case nil
4840 (progn
4841 (outline-next-visible-heading 1)
4842 (if (looking-at re)
4843 (- (match-end 0) (match-beginning 0))
4845 (error 1))))
4846 (new-level (or force-level (max previous-level next-level)))
4847 (shift (if (or (= old-level -1)
4848 (= new-level -1)
4849 (= old-level new-level))
4851 (- new-level old-level)))
4852 (shift1 shift)
4853 (delta (if (> shift 0) -1 1))
4854 (func (if (> shift 0) 'org-demote 'org-promote))
4855 (org-odd-levels-only nil)
4856 beg end)
4857 ;; Remove the forces level indicator
4858 (if force-level
4859 (delete-region (point-at-bol) (point)))
4860 ;; Make sure we start at the beginning of an empty line
4861 (if (not (bolp)) (insert "\n"))
4862 (if (not (looking-at "[ \t]*$"))
4863 (progn (insert "\n") (backward-char 1)))
4864 ;; Paste
4865 (setq beg (point))
4866 (if (string-match "[ \t\r\n]+\\'" txt)
4867 (setq txt (replace-match "\n" t t txt)))
4868 (insert txt)
4869 (setq end (point))
4870 (if (looking-at "[ \t\r\n]+")
4871 (replace-match "\n"))
4872 (goto-char beg)
4873 ;; Shift if necessary
4874 (if (= shift 0)
4875 (message "Pasted at level %d, without shift" new-level)
4876 (save-restriction
4877 (narrow-to-region beg end)
4878 (while (not (= shift 0))
4879 (org-map-region func (point-min) (point-max))
4880 (setq shift (+ delta shift)))
4881 (goto-char (point-min))
4882 (message "Pasted at level %d, with shift by %d levels"
4883 new-level shift1)))
4884 (if (and kill-ring
4885 (eq org-subtree-clip (current-kill 0))
4886 org-subtree-clip-folded)
4887 ;; The tree was folded before it was killed/copied
4888 (hide-subtree))))
4890 (defun org-kill-is-subtree-p (&optional txt)
4891 "Check if the current kill is an outline subtree, or a set of trees.
4892 Returns nil if kill does not start with a headline, or if the first
4893 headline level is not the largest headline level in the tree.
4894 So this will actually accept several entries of equal levels as well,
4895 which is OK for `org-paste-subtree'.
4896 If optional TXT is given, check this string instead of the current kill."
4897 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4898 (start-level (and kill
4899 (string-match (concat "\\`" outline-regexp) kill)
4900 (- (match-end 0) (match-beginning 0))))
4901 (re (concat "^" outline-regexp))
4902 (start 1))
4903 (if (not start-level)
4904 nil ;; does not even start with a heading
4905 (catch 'exit
4906 (while (setq start (string-match re kill (1+ start)))
4907 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4908 (throw 'exit nil)))
4909 t))))
4911 (defun org-narrow-to-subtree ()
4912 "Narrow buffer to the current subtree."
4913 (interactive)
4914 (save-excursion
4915 (narrow-to-region
4916 (progn (org-back-to-heading) (point))
4917 (progn (org-end-of-subtree t) (point)))))
4920 ;;; Outline Sorting
4922 (defun org-sort (with-case)
4923 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
4924 (interactive "P")
4925 (if (org-at-table-p)
4926 (org-call-with-arg 'org-table-sort-lines with-case)
4927 (org-call-with-arg 'org-sort-entries with-case)))
4929 (defun org-sort-entries (&optional with-case sorting-type)
4930 "Sort entries on a certain level of an outline tree.
4931 If there is an active region, the entries in the region are sorted.
4932 Else, if the cursor is before the first entry, sort the top-level items.
4933 Else, the children of the entry at point are sorted.
4935 Sorting can be alphabetically, numerically, and by date/time as given by
4936 the first time stamp in the entry. The command prompts for the sorting
4937 type unless it has been given to the function through the SORTING-TYPE
4938 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
4940 Comparing entries ignores case by default. However, with an optional argument
4941 WITH-CASE, the sorting considers case as well. With two prefix arguments
4942 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
4943 (interactive "P")
4944 (let ((unique (equal with-case '(16)))
4945 start beg end entries stars re re2 p nentries (nremoved 0)
4946 last txt what)
4947 ;; Find beginning and end of region to sort
4948 (cond
4949 ((org-region-active-p)
4950 ;; we will sort the region
4951 (setq end (region-end)
4952 what "region")
4953 (goto-char (region-beginning))
4954 (if (not (org-on-heading-p)) (outline-next-heading))
4955 (setq start (point)))
4956 ((or (org-on-heading-p)
4957 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4958 ;; we will sort the children of the current headline
4959 (org-back-to-heading)
4960 (setq start (point) end (org-end-of-subtree) what "children")
4961 (goto-char start)
4962 (show-subtree)
4963 (outline-next-heading))
4965 ;; we will sort the top-level entries in this file
4966 (goto-char (point-min))
4967 (or (org-on-heading-p) (outline-next-heading))
4968 (setq start (point) end (point-max) what "top-level")
4969 (goto-char start)
4970 (show-all)))
4971 (setq beg (point))
4972 (if (>= (point) end) (error "Nothing to sort"))
4973 (looking-at "\\(\\*+\\)")
4974 (setq stars (match-string 1)
4975 re (concat "^" (regexp-quote stars) " +")
4976 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4977 txt (buffer-substring beg end))
4978 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4979 (if (and (not (equal stars "*")) (string-match re2 txt))
4980 (error "Region to sort contains a level above the first entry"))
4981 ;; Make a list that can be sorted.
4982 ;; The car is the string for comparison, the cdr is the subtree
4983 (message "Sorting entries...")
4984 (setq entries
4985 (mapcar
4986 (lambda (x)
4987 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
4988 (cons (match-string 0 x) x))
4989 (org-split-string txt re)))
4991 ;; Sort the list
4992 (save-excursion
4993 (goto-char start)
4994 (setq entries (org-do-sort entries what with-case sorting-type)))
4996 ;; Delete the old stuff
4997 (goto-char beg)
4998 (kill-region beg end)
4999 (setq nentries (length entries))
5000 ;; Insert the sorted entries, and remove duplicates if this is required
5001 (while (setq p (pop entries))
5002 (if (and unique (equal last (setq last (org-trim (cdr p)))))
5003 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
5004 (insert stars " " (cdr p))))
5005 (goto-char start)
5006 (message "Sorting entries...done (%d entries%s)"
5007 nentries
5008 (if unique (format ", %d duplicates removed" nremoved) ""))))
5010 (defun org-do-sort (table what &optional with-case sorting-type)
5011 "Sort TABLE of WHAT according to SORTING-TYPE.
5012 The user will be prompted for the SORTING-TYPE if the call to this
5013 function does not specify it. WHAT is only for the prompt, to indicate
5014 what is being sorted. The sorting key will be extracted from
5015 the car of the elements of the table.
5016 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5017 (unless sorting-type
5018 (message
5019 "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
5020 what)
5021 (setq sorting-type (read-char-exclusive)))
5022 (let ((dcst (downcase sorting-type))
5023 extractfun comparefun)
5024 ;; Define the appropriate functions
5025 (cond
5026 ((= dcst ?n)
5027 (setq extractfun 'string-to-number
5028 comparefun (if (= dcst sorting-type) '< '>)))
5029 ((= dcst ?a)
5030 (setq extractfun (if with-case 'identity 'downcase)
5031 comparefun (if (= dcst sorting-type)
5032 'string<
5033 (lambda (a b) (and (not (string< a b))
5034 (not (string= a b)))))))
5035 ((= dcst ?t)
5036 (setq extractfun
5037 (lambda (x)
5038 (if (string-match org-ts-regexp x)
5039 (time-to-seconds
5040 (org-time-string-to-time (match-string 0 x)))
5042 comparefun (if (= dcst sorting-type) '< '>)))
5043 (t (error "Invalid sorting type `%c'" sorting-type)))
5045 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5046 table)
5047 (lambda (a b) (funcall comparefun (car a) (car b))))))
5049 ;;;; Plain list items, including checkboxes
5051 ;;; Plain list items
5053 (defun org-at-item-p ()
5054 "Is point in a line starting a hand-formatted item?"
5055 (let ((llt org-plain-list-ordered-item-terminator))
5056 (save-excursion
5057 (goto-char (point-at-bol))
5058 (looking-at
5059 (cond
5060 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5061 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5062 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5063 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5066 (defun org-in-item-p ()
5067 "It the cursor inside a plain list item.
5068 Does not have to be the first line."
5069 (save-excursion
5070 (condition-case nil
5071 (progn
5072 (org-beginning-of-item)
5073 (org-at-item-p)
5075 (error nil))))
5077 (defun org-insert-item (&optional checkbox)
5078 "Insert a new item at the current level.
5079 Return t when things worked, nil when we are not in an item."
5080 (when (save-excursion
5081 (condition-case nil
5082 (progn
5083 (org-beginning-of-item)
5084 (org-at-item-p)
5085 (if (org-invisible-p) (error "Invisible item"))
5087 (error nil)))
5088 (let* ((bul (match-string 0))
5089 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5090 (match-end 0)))
5091 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5092 pos)
5093 (cond
5094 ((and (org-at-item-p) (<= (point) eow))
5095 ;; before the bullet
5096 (beginning-of-line 1)
5097 (open-line (if blank 2 1)))
5098 ((<= (point) eow)
5099 (beginning-of-line 1))
5100 (t (newline (if blank 2 1))))
5101 (insert bul (if checkbox "[ ]" ""))
5102 (just-one-space)
5103 (setq pos (point))
5104 (end-of-line 1)
5105 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5106 (org-maybe-renumber-ordered-list)
5107 (and checkbox (org-update-checkbox-count-maybe))
5110 ;;; Checkboxes
5112 (defun org-at-item-checkbox-p ()
5113 "Is point at a line starting a plain-list item with a checklet?"
5114 (and (org-at-item-p)
5115 (save-excursion
5116 (goto-char (match-end 0))
5117 (skip-chars-forward " \t")
5118 (looking-at "\\[[ X]\\]"))))
5120 (defun org-toggle-checkbox (&optional arg)
5121 "Toggle the checkbox in the current line."
5122 (interactive "P")
5123 (catch 'exit
5124 (let (beg end status (firstnew 'unknown))
5125 (cond
5126 ((org-region-active-p)
5127 (setq beg (region-beginning) end (region-end)))
5128 ((org-on-heading-p)
5129 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5130 ((org-at-item-checkbox-p)
5131 (save-excursion
5132 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
5133 (throw 'exit t))
5134 (t (error "Not at a checkbox or heading, and no active region")))
5135 (save-excursion
5136 (goto-char beg)
5137 (while (< (point) end)
5138 (when (org-at-item-checkbox-p)
5139 (setq status (equal (match-string 0) "[X]"))
5140 (when (eq firstnew 'unknown)
5141 (setq firstnew (not status)))
5142 (replace-match
5143 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5144 (beginning-of-line 2)))))
5145 (org-update-checkbox-count-maybe))
5147 (defun org-update-checkbox-count-maybe ()
5148 "Update checkbox statistics unless turned off by user."
5149 (when org-provide-checkbox-statistics
5150 (org-update-checkbox-count)))
5152 (defun org-update-checkbox-count (&optional all)
5153 "Update the checkbox statistics in the current section.
5154 This will find all statistic cookies like [57%] and [6/12] and update them
5155 with the current numbers. With optional prefix argument ALL, do this for
5156 the whole buffer."
5157 (interactive "P")
5158 (save-excursion
5159 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5160 (beg (progn (outline-back-to-heading) (point)))
5161 (end (move-marker (make-marker)
5162 (progn (outline-next-heading) (point))))
5163 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5164 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
5165 b1 e1 f1 c-on c-off lim (cstat 0))
5166 (when all
5167 (goto-char (point-min))
5168 (outline-next-heading)
5169 (setq beg (point) end (point-max)))
5170 (goto-char beg)
5171 (while (re-search-forward re end t)
5172 (setq cstat (1+ cstat)
5173 b1 (match-beginning 0)
5174 e1 (match-end 0)
5175 f1 (match-beginning 1)
5176 lim (cond
5177 ((org-on-heading-p) (outline-next-heading) (point))
5178 ((org-at-item-p) (org-end-of-item) (point))
5179 (t nil))
5180 c-on 0 c-off 0)
5181 (goto-char e1)
5182 (when lim
5183 (while (re-search-forward re-box lim t)
5184 (if (equal (match-string 2) "[ ]")
5185 (setq c-off (1+ c-off))
5186 (setq c-on (1+ c-on))))
5187 (delete-region b1 e1)
5188 (goto-char b1)
5189 (insert (if f1
5190 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5191 (format "[%d/%d]" c-on (+ c-on c-off))))))
5192 (when (interactive-p)
5193 (message "Checkbox satistics updated %s (%d places)"
5194 (if all "in entire file" "in current outline entry") cstat)))))
5196 (defun org-get-checkbox-statistics-face ()
5197 "Select the face for checkbox statistics.
5198 The face will be `org-done' when all relevant boxes are checked. Otherwise
5199 it will be `org-todo'."
5200 (if (match-end 1)
5201 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5202 (if (and (> (match-end 2) (match-beginning 2))
5203 (equal (match-string 2) (match-string 3)))
5204 'org-done
5205 'org-todo)))
5207 (defun org-get-indentation (&optional line)
5208 "Get the indentation of the current line, interpreting tabs.
5209 When LINE is given, assume it represents a line and compute its indentation."
5210 (if line
5211 (if (string-match "^ *" (org-remove-tabs line))
5212 (match-end 0))
5213 (save-excursion
5214 (beginning-of-line 1)
5215 (skip-chars-forward " \t")
5216 (current-column))))
5218 (defun org-remove-tabs (s &optional width)
5219 "Replace tabulators in S with spaces.
5220 Assumes that s is a single line, starting in column 0."
5221 (setq width (or width tab-width))
5222 (while (string-match "\t" s)
5223 (setq s (replace-match
5224 (make-string
5225 (- (* width (/ (+ (match-beginning 0) width) width))
5226 (match-beginning 0)) ?\ )
5227 t t s)))
5230 (defun org-fix-indentation (line ind)
5231 "Fix indentation in LINE.
5232 IND is a cons cell with target and minimum indentation.
5233 If the current indenation in LINE is smaller than the minimum,
5234 leave it alone. If it is larger than ind, set it to the target."
5235 (let* ((l (org-remove-tabs line))
5236 (i (org-get-indentation l))
5237 (i1 (car ind)) (i2 (cdr ind)))
5238 (if (>= i i2) (setq l (substring line i2)))
5239 (if (> i1 0)
5240 (concat (make-string i1 ?\ ) l)
5241 l)))
5243 (defun org-beginning-of-item ()
5244 "Go to the beginning of the current hand-formatted item.
5245 If the cursor is not in an item, throw an error."
5246 (interactive)
5247 (let ((pos (point))
5248 (limit (save-excursion (org-back-to-heading)
5249 (beginning-of-line 2) (point)))
5250 ind ind1)
5251 (if (org-at-item-p)
5252 (beginning-of-line 1)
5253 (beginning-of-line 1)
5254 (skip-chars-forward " \t")
5255 (setq ind (current-column))
5256 (if (catch 'exit
5257 (while t
5258 (beginning-of-line 0)
5259 (if (< (point) limit) (throw 'exit nil))
5260 (unless (looking-at "[ \t]*$")
5261 (skip-chars-forward " \t")
5262 (setq ind1 (current-column))
5263 (if (< ind1 ind)
5264 (throw 'exit (org-at-item-p))))))
5266 (goto-char pos)
5267 (error "Not in an item")))))
5269 (defun org-end-of-item ()
5270 "Go to the end of the current hand-formatted item.
5271 If the cursor is not in an item, throw an error."
5272 (interactive)
5273 (let ((pos (point))
5274 (limit (save-excursion (outline-next-heading) (point)))
5275 (ind (save-excursion
5276 (org-beginning-of-item)
5277 (skip-chars-forward " \t")
5278 (current-column)))
5279 ind1)
5280 (if (catch 'exit
5281 (while t
5282 (beginning-of-line 2)
5283 (if (>= (point) limit) (throw 'exit t))
5284 (unless (looking-at "[ \t]*$")
5285 (skip-chars-forward " \t")
5286 (setq ind1 (current-column))
5287 (if (<= ind1 ind) (throw 'exit t)))))
5288 (beginning-of-line 1)
5289 (goto-char pos)
5290 (error "Not in an item"))))
5292 (defun org-next-item ()
5293 "Move to the beginning of the next item in the current plain list.
5294 Error if not at a plain list, or if this is the last item in the list."
5295 (interactive)
5296 (let (ind ind1 (pos (point)))
5297 (org-beginning-of-item)
5298 (setq ind (org-get-indentation))
5299 (org-end-of-item)
5300 (setq ind1 (org-get-indentation))
5301 (unless (and (org-at-item-p) (= ind ind1))
5302 (goto-char pos)
5303 (error "On last item"))))
5305 (defun org-previous-item ()
5306 "Move to the beginning of the previous item in the current plain list.
5307 Error if not at a plain list, or if this is the last item in the list."
5308 (interactive)
5309 (let (beg ind (pos (point)))
5310 (org-beginning-of-item)
5311 (setq beg (point))
5312 (setq ind (org-get-indentation))
5313 (goto-char beg)
5314 (catch 'exit
5315 (while t
5316 (beginning-of-line 0)
5317 (if (looking-at "[ \t]*$")
5319 (if (<= (org-get-indentation) ind)
5320 (throw 'exit t)))))
5321 (condition-case nil
5322 (org-beginning-of-item)
5323 (error (goto-char pos)
5324 (error "On first item")))))
5326 (defun org-move-item-down ()
5327 "Move the plain list item at point down, i.e. swap with following item.
5328 Subitems (items with larger indentation) are considered part of the item,
5329 so this really moves item trees."
5330 (interactive)
5331 (let (beg end ind ind1 (pos (point)) txt)
5332 (org-beginning-of-item)
5333 (setq beg (point))
5334 (setq ind (org-get-indentation))
5335 (org-end-of-item)
5336 (setq end (point))
5337 (setq ind1 (org-get-indentation))
5338 (if (and (org-at-item-p) (= ind ind1))
5339 (progn
5340 (org-end-of-item)
5341 (setq txt (buffer-substring beg end))
5342 (save-excursion
5343 (delete-region beg end))
5344 (setq pos (point))
5345 (insert txt)
5346 (goto-char pos)
5347 (org-maybe-renumber-ordered-list))
5348 (goto-char pos)
5349 (error "Cannot move this item further down"))))
5351 (defun org-move-item-up (arg)
5352 "Move the plain list item at point up, i.e. swap with previous item.
5353 Subitems (items with larger indentation) are considered part of the item,
5354 so this really moves item trees."
5355 (interactive "p")
5356 (let (beg end ind ind1 (pos (point)) txt)
5357 (org-beginning-of-item)
5358 (setq beg (point))
5359 (setq ind (org-get-indentation))
5360 (org-end-of-item)
5361 (setq end (point))
5362 (goto-char beg)
5363 (catch 'exit
5364 (while t
5365 (beginning-of-line 0)
5366 (if (looking-at "[ \t]*$")
5368 (if (<= (setq ind1 (org-get-indentation)) ind)
5369 (throw 'exit t)))))
5370 (condition-case nil
5371 (org-beginning-of-item)
5372 (error (goto-char beg)
5373 (error "Cannot move this item further up")))
5374 (setq ind1 (org-get-indentation))
5375 (if (and (org-at-item-p) (= ind ind1))
5376 (progn
5377 (setq txt (buffer-substring beg end))
5378 (save-excursion
5379 (delete-region beg end))
5380 (setq pos (point))
5381 (insert txt)
5382 (goto-char pos)
5383 (org-maybe-renumber-ordered-list))
5384 (goto-char pos)
5385 (error "Cannot move this item further up"))))
5387 (defun org-maybe-renumber-ordered-list ()
5388 "Renumber the ordered list at point if setup allows it.
5389 This tests the user option `org-auto-renumber-ordered-lists' before
5390 doing the renumbering."
5391 (and org-auto-renumber-ordered-lists
5392 (org-at-item-p)
5393 (match-beginning 3)
5394 (org-renumber-ordered-list 1)))
5396 (defun org-get-string-indentation (s)
5397 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5398 (let ((n -1) (i 0) (w tab-width) c)
5399 (catch 'exit
5400 (while (< (setq n (1+ n)) (length s))
5401 (setq c (aref s n))
5402 (cond ((= c ?\ ) (setq i (1+ i)))
5403 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5404 (t (throw 'exit t)))))
5407 (defun org-renumber-ordered-list (arg)
5408 "Renumber an ordered plain list.
5409 Cursor needs to be in the first line of an item, the line that starts
5410 with something like \"1.\" or \"2)\"."
5411 (interactive "p")
5412 (unless (and (org-at-item-p)
5413 (match-beginning 3))
5414 (error "This is not an ordered list"))
5415 (let ((line (org-current-line))
5416 (col (current-column))
5417 (ind (org-get-string-indentation
5418 (buffer-substring (point-at-bol) (match-beginning 3))))
5419 ;; (term (substring (match-string 3) -1))
5420 ind1 (n (1- arg)))
5421 ;; find where this list begins
5422 (catch 'exit
5423 (while t
5424 (catch 'next
5425 (beginning-of-line 0)
5426 (if (looking-at "[ \t]*$") (throw 'next t))
5427 (skip-chars-forward " \t") (setq ind1 (current-column))
5428 (if (or (< ind1 ind)
5429 (and (= ind1 ind)
5430 (not (org-at-item-p))))
5431 (throw 'exit t)))))
5432 ;; Walk forward and replace these numbers
5433 (catch 'exit
5434 (while t
5435 (catch 'next
5436 (beginning-of-line 2)
5437 (if (eobp) (throw 'exit nil))
5438 (if (looking-at "[ \t]*$") (throw 'next nil))
5439 (skip-chars-forward " \t") (setq ind1 (current-column))
5440 (if (> ind1 ind) (throw 'next t))
5441 (if (< ind1 ind) (throw 'exit t))
5442 (if (not (org-at-item-p)) (throw 'exit nil))
5443 (if (not (match-beginning 3))
5444 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
5445 (delete-region (match-beginning 3) (1- (match-end 3)))
5446 (goto-char (match-beginning 3))
5447 (insert (format "%d" (setq n (1+ n)))))))
5448 (goto-line line)
5449 (move-to-column col)))
5451 (defvar org-last-indent-begin-marker (make-marker))
5452 (defvar org-last-indent-end-marker (make-marker))
5454 (defun org-outdent-item (arg)
5455 "Outdent a local list item."
5456 (interactive "p")
5457 (org-indent-item (- arg)))
5459 (defun org-indent-item (arg)
5460 "Indent a local list item."
5461 (interactive "p")
5462 (unless (org-at-item-p)
5463 (error "Not on an item"))
5464 (save-excursion
5465 (let (beg end ind ind1)
5466 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5467 (setq beg org-last-indent-begin-marker
5468 end org-last-indent-end-marker)
5469 (org-beginning-of-item)
5470 (setq beg (move-marker org-last-indent-begin-marker (point)))
5471 (org-end-of-item)
5472 (setq end (move-marker org-last-indent-end-marker (point))))
5473 (goto-char beg)
5474 (skip-chars-forward " \t") (setq ind (current-column))
5475 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
5476 (while (< (point) end)
5477 (beginning-of-line 1)
5478 (skip-chars-forward " \t") (setq ind1 (current-column))
5479 (delete-region (point-at-bol) (point))
5480 (indent-to-column (+ ind1 arg))
5481 (beginning-of-line 2)))))
5483 ;;;; Archiving
5485 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
5487 (defun org-archive-subtree (&optional find-done)
5488 "Move the current subtree to the archive.
5489 The archive can be a certain top-level heading in the current file, or in
5490 a different file. The tree will be moved to that location, the subtree
5491 heading be marked DONE, and the current time will be added.
5493 When called with prefix argument FIND-DONE, find whole trees without any
5494 open TODO items and archive them (after getting confirmation from the user).
5495 If the cursor is not at a headline when this comand is called, try all level
5496 1 trees. If the cursor is on a headline, only try the direct children of
5497 this heading. "
5498 (interactive "P")
5499 (if find-done
5500 (org-archive-all-done)
5501 ;; Save all relevant TODO keyword-relatex variables
5503 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5504 (tr-org-todo-keywords org-todo-keywords)
5505 (tr-org-todo-interpretation org-todo-interpretation)
5506 (tr-org-done-string org-done-string)
5507 (tr-org-todo-regexp org-todo-regexp)
5508 (tr-org-todo-line-regexp org-todo-line-regexp)
5509 (tr-org-odd-levels-only org-odd-levels-only)
5510 (this-buffer (current-buffer))
5511 (org-archive-location org-archive-location)
5512 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
5513 file heading buffer level newfile-p)
5515 ;; Try to find a local archive location
5516 (save-excursion
5517 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
5518 (setq org-archive-location (match-string 1))))
5520 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5521 (progn
5522 (setq file (format (match-string 1 org-archive-location)
5523 (file-name-nondirectory buffer-file-name))
5524 heading (match-string 2 org-archive-location)))
5525 (error "Invalid `org-archive-location'"))
5526 (if (> (length file) 0)
5527 (setq newfile-p (not (file-exists-p file))
5528 buffer (find-file-noselect file))
5529 (setq buffer (current-buffer)))
5530 (unless buffer
5531 (error "Cannot access file \"%s\"" file))
5532 (if (and (> (length heading) 0)
5533 (string-match "^\\*+" heading))
5534 (setq level (match-end 0))
5535 (setq heading nil level 0))
5536 (save-excursion
5537 ;; We first only copy, in case something goes wrong
5538 ;; we need to protect this-command, to avoid kill-region sets it,
5539 ;; which would lead to duplication of subtrees
5540 (let (this-command) (org-copy-subtree))
5541 (set-buffer buffer)
5542 ;; Enforce org-mode for the archive buffer
5543 (if (not (org-mode-p))
5544 ;; Force the mode for future visits.
5545 (let ((org-insert-mode-line-in-empty-file t))
5546 (call-interactively 'org-mode)))
5547 (when newfile-p
5548 (goto-char (point-max))
5549 (insert (format "\nArchived entries from file %s\n\n"
5550 (buffer-file-name this-buffer))))
5551 ;; Force the TODO keywords of the original buffer
5552 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
5553 (org-todo-keywords tr-org-todo-keywords)
5554 (org-todo-interpretation tr-org-todo-interpretation)
5555 (org-done-string tr-org-done-string)
5556 (org-todo-regexp tr-org-todo-regexp)
5557 (org-todo-line-regexp tr-org-todo-line-regexp)
5558 (org-odd-levels-only
5559 (if (local-variable-p 'org-odd-levels-only (current-buffer))
5560 org-odd-levels-only
5561 tr-org-odd-levels-only)))
5562 (goto-char (point-min))
5563 (if heading
5564 (progn
5565 (if (re-search-forward
5566 (concat "\\(^\\|\r\\)"
5567 (regexp-quote heading) "[ \t]*\\(:[a-zA-Z0-9_@:]+:\\)?[ \t]*\\($\\|\r\\)")
5568 nil t)
5569 (goto-char (match-end 0))
5570 ;; Heading not found, just insert it at the end
5571 (goto-char (point-max))
5572 (or (bolp) (insert "\n"))
5573 (insert "\n" heading "\n")
5574 (end-of-line 0))
5575 ;; Make the subtree visible
5576 (show-subtree)
5577 (org-end-of-subtree t)
5578 (skip-chars-backward " \t\r\n")
5579 (and (looking-at "[ \t\r\n]*")
5580 (replace-match "\n\n")))
5581 ;; No specific heading, just go to end of file.
5582 (goto-char (point-max)) (insert "\n"))
5583 ;; Paste
5584 (org-paste-subtree (org-get-legal-level level 1))
5585 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
5586 (if org-archive-mark-done
5587 (let (org-log-done)
5588 (org-todo (length org-todo-keywords))))
5589 ;; Move cursor to right after the TODO keyword
5590 (when org-archive-stamp-time
5591 (beginning-of-line 1)
5592 (looking-at org-todo-line-regexp)
5593 (goto-char (or (match-end 2) (match-beginning 3)))
5594 (org-insert-time-stamp (org-current-time) t t "(" ")"))
5595 ;; Save the buffer, if it is not the same buffer.
5596 (if (not (eq this-buffer buffer)) (save-buffer))))
5597 ;; Here we are back in the original buffer. Everything seems to have
5598 ;; worked. So now cut the tree and finish up.
5599 (let (this-command) (org-cut-subtree))
5600 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5601 (message "Subtree archived %s"
5602 (if (eq this-buffer buffer)
5603 (concat "under heading: " heading)
5604 (concat "in file: " (abbreviate-file-name file)))))))
5606 (defun org-archive-all-done (&optional tag)
5607 "Archive sublevels of the current tree without open TODO items.
5608 If the cursor is not on a headline, try all level 1 trees. If
5609 it is on a headline, try all direct children.
5610 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5611 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5612 (rea (concat ".*:" org-archive-tag ":"))
5613 (begm (make-marker))
5614 (endm (make-marker))
5615 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
5616 "Move subtree to archive (no open TODO items)? "))
5617 beg end (cntarch 0))
5618 (if (org-on-heading-p)
5619 (progn
5620 (setq re1 (concat "^" (regexp-quote
5621 (make-string
5622 (1+ (- (match-end 0) (match-beginning 0)))
5623 ?*))
5624 " "))
5625 (move-marker begm (point))
5626 (move-marker endm (org-end-of-subtree t)))
5627 (setq re1 "^* ")
5628 (move-marker begm (point-min))
5629 (move-marker endm (point-max)))
5630 (save-excursion
5631 (goto-char begm)
5632 (while (re-search-forward re1 endm t)
5633 (setq beg (match-beginning 0)
5634 end (save-excursion (org-end-of-subtree t) (point)))
5635 (goto-char beg)
5636 (if (re-search-forward re end t)
5637 (goto-char end)
5638 (goto-char beg)
5639 (if (and (or (not tag) (not (looking-at rea)))
5640 (y-or-n-p question))
5641 (progn
5642 (if tag
5643 (org-toggle-tag org-archive-tag 'on)
5644 (org-archive-subtree))
5645 (setq cntarch (1+ cntarch)))
5646 (goto-char end)))))
5647 (message "%d trees archived" cntarch)))
5649 (defun org-cycle-hide-archived-subtrees (state)
5650 "Re-hide all archived subtrees after a visibility state change."
5651 (when (and (not org-cycle-open-archived-trees)
5652 (not (memq state '(overview folded))))
5653 (save-excursion
5654 (let* ((globalp (memq state '(contents all)))
5655 (beg (if globalp (point-min) (point)))
5656 (end (if globalp (point-max) (org-end-of-subtree t))))
5657 (org-hide-archived-subtrees beg end)
5658 (goto-char beg)
5659 (if (looking-at (concat ".*:" org-archive-tag ":"))
5660 (message (substitute-command-keys
5661 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5663 (defun org-force-cycle-archived ()
5664 "Cycle subtree even if it is archived."
5665 (interactive)
5666 (setq this-command 'org-cycle)
5667 (let ((org-cycle-open-archived-trees t))
5668 (call-interactively 'org-cycle)))
5670 (defun org-hide-archived-subtrees (beg end)
5671 "Re-hide all archived subtrees after a visibility state change."
5672 (save-excursion
5673 (let* ((re (concat ":" org-archive-tag ":")))
5674 (goto-char beg)
5675 (while (re-search-forward re end t)
5676 (and (org-on-heading-p) (hide-subtree))
5677 (org-end-of-subtree t)))))
5679 (defun org-toggle-tag (tag &optional onoff)
5680 "Toggle the tag TAG for the current line.
5681 If ONOFF is `on' or `off', don't toggle but set to this state."
5682 (unless (org-on-heading-p t) (error "Not on headling"))
5683 (let (res current)
5684 (save-excursion
5685 (beginning-of-line)
5686 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5687 (point-at-eol) t)
5688 (progn
5689 (setq current (match-string 1))
5690 (replace-match ""))
5691 (setq current ""))
5692 (setq current (nreverse (org-split-string current ":")))
5693 (cond
5694 ((eq onoff 'on)
5695 (setq res t)
5696 (or (member tag current) (push tag current)))
5697 ((eq onoff 'off)
5698 (or (not (member tag current)) (setq current (delete tag current))))
5699 (t (if (member tag current)
5700 (setq current (delete tag current))
5701 (setq res t)
5702 (push tag current))))
5703 (end-of-line 1)
5704 (when current
5705 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5706 (org-set-tags nil t))
5707 res))
5709 (defun org-toggle-archive-tag (&optional arg)
5710 "Toggle the archive tag for the current headline.
5711 With prefix ARG, check all children of current headline and offer tagging
5712 the children that do not contain any open TODO items."
5713 (interactive "P")
5714 (if arg
5715 (org-archive-all-done 'tag)
5716 (let (set)
5717 (save-excursion
5718 (org-back-to-heading t)
5719 (setq set (org-toggle-tag org-archive-tag))
5720 (when set (hide-subtree)))
5721 (and set (beginning-of-line 1))
5722 (message "Subtree %s" (if set "archived" "unarchived")))))
5725 ;;;; Tables
5727 ;;; The table editor
5729 ;; Watch out: Here we are talking about two different kind of tables.
5730 ;; Most of the code is for the tables created with the Org-mode table editor.
5731 ;; Sometimes, we talk about tables created and edited with the table.el
5732 ;; Emacs package. We call the former org-type tables, and the latter
5733 ;; table.el-type tables.
5735 (defun org-before-change-function (beg end)
5736 "Every change indicates that a table might need an update."
5737 (setq org-table-may-need-update t))
5739 (defconst org-table-line-regexp "^[ \t]*|"
5740 "Detects an org-type table line.")
5741 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5742 "Detects an org-type table line.")
5743 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5744 "Detects a table line marked for automatic recalculation.")
5745 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5746 "Detects a table line marked for automatic recalculation.")
5747 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5748 "Detects a table line marked for automatic recalculation.")
5749 (defconst org-table-hline-regexp "^[ \t]*|-"
5750 "Detects an org-type table hline.")
5751 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5752 "Detects a table-type table hline.")
5753 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5754 "Detects an org-type or table-type table.")
5755 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5756 "Searching from within a table (any type) this finds the first line
5757 outside the table.")
5758 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5759 "Searching from within a table (any type) this finds the first line
5760 outside the table.")
5762 (defvar org-table-last-highlighted-reference nil)
5763 (defvar org-table-formula-history nil)
5765 (defvar org-table-column-names nil
5766 "Alist with column names, derived from the `!' line.")
5767 (defvar org-table-column-name-regexp nil
5768 "Regular expression matching the current column names.")
5769 (defvar org-table-local-parameters nil
5770 "Alist with parameter names, derived from the `$' line.")
5771 (defvar org-table-named-field-locations nil
5772 "Alist with locations of named fields.")
5774 (defvar org-table-current-line-types nil
5775 "Table row types, non-nil only for the duration of a comand.")
5776 (defvar org-table-current-begin-line nil
5777 "Table begin line, non-nil only for the duration of a comand.")
5778 (defvar org-table-current-begin-pos nil
5779 "Table begin position, non-nil only for the duration of a comand.")
5780 (defvar org-table-dlines nil
5781 "Vector of data line line numbers in the current table.")
5782 (defvar org-table-hlines nil
5783 "Vector of hline line numbers in the current table.")
5785 (defconst org-table-range-regexp
5786 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
5787 ;; 1 2 3 4 5
5788 "Regular expression for matching ranges in formulas.")
5790 (defconst org-table-range-regexp2
5791 (concat
5792 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
5793 "\\.\\."
5794 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
5795 "Match a range for reference display.")
5797 (defconst org-table-translate-regexp
5798 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
5799 "Match a reference that needs translation, for reference display.")
5801 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
5803 (defun org-table-create-with-table.el ()
5804 "Use the table.el package to insert a new table.
5805 If there is already a table at point, convert between Org-mode tables
5806 and table.el tables."
5807 (interactive)
5808 (require 'table)
5809 (cond
5810 ((org-at-table.el-p)
5811 (if (y-or-n-p "Convert table to Org-mode table? ")
5812 (org-table-convert)))
5813 ((org-at-table-p)
5814 (if (y-or-n-p "Convert table to table.el table? ")
5815 (org-table-convert)))
5816 (t (call-interactively 'table-insert))))
5818 (defun org-table-create-or-convert-from-region (arg)
5819 "Convert region to table, or create an empty table.
5820 If there is an active region, convert it to a table. If there is no such
5821 region, create an empty table."
5822 (interactive "P")
5823 (if (org-region-active-p)
5824 (org-table-convert-region (region-beginning) (region-end) arg)
5825 (org-table-create arg)))
5827 (defun org-table-create (&optional size)
5828 "Query for a size and insert a table skeleton.
5829 SIZE is a string Columns x Rows like for example \"3x2\"."
5830 (interactive "P")
5831 (unless size
5832 (setq size (read-string
5833 (concat "Table size Columns x Rows [e.g. "
5834 org-table-default-size "]: ")
5835 "" nil org-table-default-size)))
5837 (let* ((pos (point))
5838 (indent (make-string (current-column) ?\ ))
5839 (split (org-split-string size " *x *"))
5840 (rows (string-to-number (nth 1 split)))
5841 (columns (string-to-number (car split)))
5842 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5843 "\n")))
5844 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5845 (point-at-bol) (point)))
5846 (beginning-of-line 1)
5847 (newline))
5848 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5849 (dotimes (i rows) (insert line))
5850 (goto-char pos)
5851 (if (> rows 1)
5852 ;; Insert a hline after the first row.
5853 (progn
5854 (end-of-line 1)
5855 (insert "\n|-")
5856 (goto-char pos)))
5857 (org-table-align)))
5859 (defun org-table-convert-region (beg0 end0 &optional nspace)
5860 "Convert region to a table.
5861 The region goes from BEG0 to END0, but these borders will be moved
5862 slightly, to make sure a beginning of line in the first line is included.
5863 When NSPACE is non-nil, it indicates the minimum number of spaces that
5864 separate columns (default: just one space)."
5865 (interactive "rP")
5866 (let* ((beg (min beg0 end0))
5867 (end (max beg0 end0))
5868 (tabsep t)
5870 (goto-char beg)
5871 (beginning-of-line 1)
5872 (setq beg (move-marker (make-marker) (point)))
5873 (goto-char end)
5874 (if (bolp) (backward-char 1) (end-of-line 1))
5875 (setq end (move-marker (make-marker) (point)))
5876 ;; Lets see if this is tab-separated material. If every nonempty line
5877 ;; contains a tab, we will assume that it is tab-separated material
5878 (if nspace
5879 (setq tabsep nil)
5880 (goto-char beg)
5881 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5882 (if nspace (setq tabsep nil))
5883 (if tabsep
5884 (setq re "^\\|\t")
5885 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5886 (max 1 (prefix-numeric-value nspace)))))
5887 (goto-char beg)
5888 (while (re-search-forward re end t)
5889 (replace-match "| " t t))
5890 (goto-char beg)
5891 (insert " ")
5892 (org-table-align)))
5894 (defun org-table-import (file arg)
5895 "Import FILE as a table.
5896 The file is assumed to be tab-separated. Such files can be produced by most
5897 spreadsheet and database applications. If no tabs (at least one per line)
5898 are found, lines will be split on whitespace into fields."
5899 (interactive "f\nP")
5900 (or (bolp) (newline))
5901 (let ((beg (point))
5902 (pm (point-max)))
5903 (insert-file-contents file)
5904 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5906 (defun org-table-export ()
5907 "Export table as a tab-separated file.
5908 Such a file can be imported into a spreadsheet program like Excel."
5909 (interactive)
5910 (let* ((beg (org-table-begin))
5911 (end (org-table-end))
5912 (table (buffer-substring beg end))
5913 (file (read-file-name "Export table to: "))
5914 buf)
5915 (unless (or (not (file-exists-p file))
5916 (y-or-n-p (format "Overwrite file %s? " file)))
5917 (error "Abort"))
5918 (with-current-buffer (find-file-noselect file)
5919 (setq buf (current-buffer))
5920 (erase-buffer)
5921 (fundamental-mode)
5922 (insert table)
5923 (goto-char (point-min))
5924 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5925 (replace-match "" t t)
5926 (end-of-line 1))
5927 (goto-char (point-min))
5928 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5929 (replace-match "" t t)
5930 (goto-char (min (1+ (point)) (point-max))))
5931 (goto-char (point-min))
5932 (while (re-search-forward "^-[-+]*$" nil t)
5933 (replace-match "")
5934 (if (looking-at "\n")
5935 (delete-char 1)))
5936 (goto-char (point-min))
5937 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5938 (replace-match "\t" t t))
5939 (save-buffer))
5940 (kill-buffer buf)))
5942 (defvar org-table-aligned-begin-marker (make-marker)
5943 "Marker at the beginning of the table last aligned.
5944 Used to check if cursor still is in that table, to minimize realignment.")
5945 (defvar org-table-aligned-end-marker (make-marker)
5946 "Marker at the end of the table last aligned.
5947 Used to check if cursor still is in that table, to minimize realignment.")
5948 (defvar org-table-last-alignment nil
5949 "List of flags for flushright alignment, from the last re-alignment.
5950 This is being used to correctly align a single field after TAB or RET.")
5951 (defvar org-table-last-column-widths nil
5952 "List of max width of fields in each column.
5953 This is being used to correctly align a single field after TAB or RET.")
5954 (defvar org-table-overlay-coordinates nil
5955 "Overlay coordinates after each align of a table.")
5956 (make-variable-buffer-local 'org-table-overlay-coordinates)
5958 (defvar org-last-recalc-line nil)
5959 (defconst org-narrow-column-arrow "=>"
5960 "Used as display property in narrowed table columns.")
5962 (defun org-table-align ()
5963 "Align the table at point by aligning all vertical bars."
5964 (interactive)
5965 (let* (
5966 ;; Limits of table
5967 (beg (org-table-begin))
5968 (end (org-table-end))
5969 ;; Current cursor position
5970 (linepos (org-current-line))
5971 (colpos (org-table-current-column))
5972 (winstart (window-start))
5973 (winstartline (org-current-line (min winstart (1- (point-max)))))
5974 lines (new "") lengths l typenums ty fields maxfields i
5975 column
5976 (indent "") cnt frac
5977 rfmt hfmt
5978 (spaces '(1 . 1))
5979 (sp1 (car spaces))
5980 (sp2 (cdr spaces))
5981 (rfmt1 (concat
5982 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5983 (hfmt1 (concat
5984 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5985 emptystrings links dates narrow fmax f1 len c e)
5986 (untabify beg end)
5987 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
5988 ;; Check if we have links or dates
5989 (goto-char beg)
5990 (setq links (re-search-forward org-bracket-link-regexp end t))
5991 (goto-char beg)
5992 (setq dates (and org-display-custom-times
5993 (re-search-forward org-ts-regexp-both end t)))
5994 ;; Make sure the link properties are right
5995 (when links (goto-char beg) (while (org-activate-bracket-links end)))
5996 ;; Make sure the date properties are right
5997 (when dates (goto-char beg) (while (org-activate-dates end)))
5999 ;; Check if we are narrowing any columns
6000 (goto-char beg)
6001 (setq narrow (and org-format-transports-properties-p
6002 (re-search-forward "<[0-9]+>" end t)))
6003 ;; Get the rows
6004 (setq lines (org-split-string
6005 (buffer-substring beg end) "\n"))
6006 ;; Store the indentation of the first line
6007 (if (string-match "^ *" (car lines))
6008 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6009 ;; Mark the hlines by setting the corresponding element to nil
6010 ;; At the same time, we remove trailing space.
6011 (setq lines (mapcar (lambda (l)
6012 (if (string-match "^ *|-" l)
6014 (if (string-match "[ \t]+$" l)
6015 (substring l 0 (match-beginning 0))
6016 l)))
6017 lines))
6018 ;; Get the data fields by splitting the lines.
6019 (setq fields (mapcar
6020 (lambda (l)
6021 (org-split-string l " *| *"))
6022 (delq nil (copy-sequence lines))))
6023 ;; How many fields in the longest line?
6024 (condition-case nil
6025 (setq maxfields (apply 'max (mapcar 'length fields)))
6026 (error
6027 (kill-region beg end)
6028 (org-table-create org-table-default-size)
6029 (error "Empty table - created default table")))
6030 ;; A list of empty strings to fill any short rows on output
6031 (setq emptystrings (make-list maxfields ""))
6032 ;; Check for special formatting.
6033 (setq i -1)
6034 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6035 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6036 ;; Check if there is an explicit width specified
6037 (when narrow
6038 (setq c column fmax nil)
6039 (while c
6040 (setq e (pop c))
6041 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
6042 (setq fmax (string-to-number (match-string 1 e)) c nil)))
6043 ;; Find fields that are wider than fmax, and shorten them
6044 (when fmax
6045 (loop for xx in column do
6046 (when (and (stringp xx)
6047 (> (org-string-width xx) fmax))
6048 (org-add-props xx nil
6049 'help-echo
6050 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
6051 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
6052 (unless (> f1 1)
6053 (error "Cannot narrow field starting with wide link \"%s\""
6054 (match-string 0 xx)))
6055 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
6056 (add-text-properties (- f1 2) f1
6057 (list 'display org-narrow-column-arrow)
6058 xx)))))
6059 ;; Get the maximum width for each column
6060 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
6061 ;; Get the fraction of numbers, to decide about alignment of the column
6062 (setq cnt 0 frac 0.0)
6063 (loop for x in column do
6064 (if (equal x "")
6066 (setq frac ( / (+ (* frac cnt)
6067 (if (string-match org-table-number-regexp x) 1 0))
6068 (setq cnt (1+ cnt))))))
6069 (push (>= frac org-table-number-fraction) typenums))
6070 (setq lengths (nreverse lengths) typenums (nreverse typenums))
6072 ;; Store the alignment of this table, for later editing of single fields
6073 (setq org-table-last-alignment typenums
6074 org-table-last-column-widths lengths)
6076 ;; With invisible characters, `format' does not get the field width right
6077 ;; So we need to make these fields wide by hand.
6078 (when links
6079 (loop for i from 0 upto (1- maxfields) do
6080 (setq len (nth i lengths))
6081 (loop for j from 0 upto (1- (length fields)) do
6082 (setq c (nthcdr i (car (nthcdr j fields))))
6083 (if (and (stringp (car c))
6084 (string-match org-bracket-link-regexp (car c))
6085 (< (org-string-width (car c)) len))
6086 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
6088 ;; Compute the formats needed for output of the table
6089 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6090 (while (setq l (pop lengths))
6091 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6092 (setq rfmt (concat rfmt (format rfmt1 ty l))
6093 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6094 (setq rfmt (concat rfmt "\n")
6095 hfmt (concat (substring hfmt 0 -1) "|\n"))
6097 (setq new (mapconcat
6098 (lambda (l)
6099 (if l (apply 'format rfmt
6100 (append (pop fields) emptystrings))
6101 hfmt))
6102 lines ""))
6103 ;; Replace the old one
6104 (delete-region beg end)
6105 (move-marker end nil)
6106 (move-marker org-table-aligned-begin-marker (point))
6107 (insert new)
6108 (move-marker org-table-aligned-end-marker (point))
6109 (when (and orgtbl-mode (not (org-mode-p)))
6110 (goto-char org-table-aligned-begin-marker)
6111 (while (org-hide-wide-columns org-table-aligned-end-marker)))
6112 ;; Try to move to the old location
6113 (goto-line winstartline)
6114 (setq winstart (point-at-bol))
6115 (goto-line linepos)
6116 (set-window-start (selected-window) winstart 'noforce)
6117 (org-table-goto-column colpos)
6118 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
6119 (setq org-table-may-need-update nil)
6122 (defun org-string-width (s)
6123 "Compute width of string, ignoring invisible characters.
6124 This ignores character with invisibility property `org-link', and also
6125 characters with property `org-cwidth', because these will become invisible
6126 upon the next fontification round."
6127 (let (b l)
6128 (when (or (eq t buffer-invisibility-spec)
6129 (assq 'org-link buffer-invisibility-spec))
6130 (while (setq b (text-property-any 0 (length s)
6131 'invisible 'org-link s))
6132 (setq s (concat (substring s 0 b)
6133 (substring s (or (next-single-property-change
6134 b 'invisible s) (length s)))))))
6135 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
6136 (setq s (concat (substring s 0 b)
6137 (substring s (or (next-single-property-change
6138 b 'org-cwidth s) (length s))))))
6139 (setq l (string-width s) b -1)
6140 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
6141 (setq l (- l (get-text-property b 'org-dwidth-n s))))
6144 (defun org-table-begin (&optional table-type)
6145 "Find the beginning of the table and return its position.
6146 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6147 (save-excursion
6148 (if (not (re-search-backward
6149 (if table-type org-table-any-border-regexp
6150 org-table-border-regexp)
6151 nil t))
6152 (progn (goto-char (point-min)) (point))
6153 (goto-char (match-beginning 0))
6154 (beginning-of-line 2)
6155 (point))))
6157 (defun org-table-end (&optional table-type)
6158 "Find the end of the table and return its position.
6159 With argument TABLE-TYPE, go to the end of a table.el-type table."
6160 (save-excursion
6161 (if (not (re-search-forward
6162 (if table-type org-table-any-border-regexp
6163 org-table-border-regexp)
6164 nil t))
6165 (goto-char (point-max))
6166 (goto-char (match-beginning 0)))
6167 (point-marker)))
6169 (defun org-table-justify-field-maybe (&optional new)
6170 "Justify the current field, text to left, number to right.
6171 Optional argument NEW may specify text to replace the current field content."
6172 (cond
6173 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6174 ((org-at-table-hline-p))
6175 ((and (not new)
6176 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6177 (current-buffer)))
6178 (< (point) org-table-aligned-begin-marker)
6179 (>= (point) org-table-aligned-end-marker)))
6180 ;; This is not the same table, force a full re-align
6181 (setq org-table-may-need-update t))
6182 (t ;; realign the current field, based on previous full realign
6183 (let* ((pos (point)) s
6184 (col (org-table-current-column))
6185 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
6186 l f n o e)
6187 (when (> col 0)
6188 (skip-chars-backward "^|\n")
6189 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6190 (progn
6191 (setq s (match-string 1)
6192 o (match-string 0)
6193 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6194 e (not (= (match-beginning 2) (match-end 2))))
6195 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6196 l (if e "|" (setq org-table-may-need-update t) ""))
6197 n (format f s))
6198 (if new
6199 (if (<= (length new) l) ;; FIXME: length -> str-width?
6200 (setq n (format f new))
6201 (setq n (concat new "|") org-table-may-need-update t)))
6202 (or (equal n o)
6203 (let (org-table-may-need-update)
6204 (replace-match n))))
6205 (setq org-table-may-need-update t))
6206 (goto-char pos))))))
6208 (defun org-table-next-field ()
6209 "Go to the next field in the current table, creating new lines as needed.
6210 Before doing so, re-align the table if necessary."
6211 (interactive)
6212 (org-table-maybe-eval-formula)
6213 (org-table-maybe-recalculate-line)
6214 (if (and org-table-automatic-realign
6215 org-table-may-need-update)
6216 (org-table-align))
6217 (let ((end (org-table-end)))
6218 (if (org-at-table-hline-p)
6219 (end-of-line 1))
6220 (condition-case nil
6221 (progn
6222 (re-search-forward "|" end)
6223 (if (looking-at "[ \t]*$")
6224 (re-search-forward "|" end))
6225 (if (and (looking-at "-")
6226 org-table-tab-jumps-over-hlines
6227 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
6228 (goto-char (match-beginning 1)))
6229 (if (looking-at "-")
6230 (progn
6231 (beginning-of-line 0)
6232 (org-table-insert-row 'below))
6233 (if (looking-at " ") (forward-char 1))))
6234 (error
6235 (org-table-insert-row 'below)))))
6237 (defun org-table-previous-field ()
6238 "Go to the previous field in the table.
6239 Before doing so, re-align the table if necessary."
6240 (interactive)
6241 (org-table-justify-field-maybe)
6242 (org-table-maybe-recalculate-line)
6243 (if (and org-table-automatic-realign
6244 org-table-may-need-update)
6245 (org-table-align))
6246 (if (org-at-table-hline-p)
6247 (end-of-line 1))
6248 (re-search-backward "|" (org-table-begin))
6249 (re-search-backward "|" (org-table-begin))
6250 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6251 (re-search-backward "|" (org-table-begin)))
6252 (if (looking-at "| ?")
6253 (goto-char (match-end 0))))
6255 (defun org-table-next-row ()
6256 "Go to the next row (same column) in the current table.
6257 Before doing so, re-align the table if necessary."
6258 (interactive)
6259 (org-table-maybe-eval-formula)
6260 (org-table-maybe-recalculate-line)
6261 (if (or (looking-at "[ \t]*$")
6262 (save-excursion (skip-chars-backward " \t") (bolp)))
6263 (newline)
6264 (if (and org-table-automatic-realign
6265 org-table-may-need-update)
6266 (org-table-align))
6267 (let ((col (org-table-current-column)))
6268 (beginning-of-line 2)
6269 (if (or (not (org-at-table-p))
6270 (org-at-table-hline-p))
6271 (progn
6272 (beginning-of-line 0)
6273 (org-table-insert-row 'below)))
6274 (org-table-goto-column col)
6275 (skip-chars-backward "^|\n\r")
6276 (if (looking-at " ") (forward-char 1)))))
6278 (defun org-table-copy-down (n)
6279 "Copy a field down in the current column.
6280 If the field at the cursor is empty, copy into it the content of the nearest
6281 non-empty field above. With argument N, use the Nth non-empty field.
6282 If the current field is not empty, it is copied down to the next row, and
6283 the cursor is moved with it. Therefore, repeating this command causes the
6284 column to be filled row-by-row.
6285 If the variable `org-table-copy-increment' is non-nil and the field is an
6286 integer, it will be incremented while copying."
6287 (interactive "p")
6288 (let* ((colpos (org-table-current-column))
6289 (field (org-table-get-field))
6290 (non-empty (string-match "[^ \t]" field))
6291 (beg (org-table-begin))
6292 txt)
6293 (org-table-check-inside-data-field)
6294 (if non-empty
6295 (progn
6296 (setq txt (org-trim field))
6297 (org-table-next-row)
6298 (org-table-blank-field))
6299 (save-excursion
6300 (setq txt
6301 (catch 'exit
6302 (while (progn (beginning-of-line 1)
6303 (re-search-backward org-table-dataline-regexp
6304 beg t))
6305 (org-table-goto-column colpos t)
6306 (if (and (looking-at
6307 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6308 (= (setq n (1- n)) 0))
6309 (throw 'exit (match-string 1))))))))
6310 (if txt
6311 (progn
6312 (if (and org-table-copy-increment
6313 (string-match "^[0-9]+$" txt))
6314 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6315 (insert txt)
6316 (org-table-maybe-recalculate-line)
6317 (org-table-align))
6318 (error "No non-empty field found"))))
6320 (defun org-table-check-inside-data-field ()
6321 "Is point inside a table data field?
6322 I.e. not on a hline or before the first or after the last column?
6323 This actually throws an error, so it aborts the current command."
6324 (if (or (not (org-at-table-p))
6325 (= (org-table-current-column) 0)
6326 (org-at-table-hline-p)
6327 (looking-at "[ \t]*$"))
6328 (error "Not in table data field")))
6330 (defvar org-table-clip nil
6331 "Clipboard for table regions.")
6333 (defun org-table-blank-field ()
6334 "Blank the current table field or active region."
6335 (interactive)
6336 (org-table-check-inside-data-field)
6337 (if (and (interactive-p) (org-region-active-p))
6338 (let (org-table-clip)
6339 (org-table-cut-region (region-beginning) (region-end)))
6340 (skip-chars-backward "^|")
6341 (backward-char 1)
6342 (if (looking-at "|[^|\n]+")
6343 (let* ((pos (match-beginning 0))
6344 (match (match-string 0))
6345 (len (org-string-width match)))
6346 (replace-match (concat "|" (make-string (1- len) ?\ )))
6347 (goto-char (+ 2 pos))
6348 (substring match 1)))))
6350 (defun org-table-get-field (&optional n replace)
6351 "Return the value of the field in column N of current row.
6352 N defaults to current field.
6353 If REPLACE is a string, replace field with this value. The return value
6354 is always the old value."
6355 (and n (org-table-goto-column n))
6356 (skip-chars-backward "^|\n")
6357 (backward-char 1)
6358 (if (looking-at "|[^|\r\n]*")
6359 (let* ((pos (match-beginning 0))
6360 (val (buffer-substring (1+ pos) (match-end 0))))
6361 (if replace
6362 (replace-match (concat "|" replace) t t))
6363 (goto-char (min (point-at-eol) (+ 2 pos)))
6364 val)
6365 (forward-char 1) ""))
6368 (defun org-table-field-info (arg)
6369 "Show info about the current field, and highlight any reference at point."
6370 (interactive "P")
6371 (org-table-get-specials)
6372 (save-excursion
6373 (let* ((pos (point))
6374 (col (org-table-current-column))
6375 (cname (car (rassoc (int-to-string col) org-table-column-names)))
6376 (name (car (rassoc (list (org-current-line) col)
6377 org-table-named-field-locations)))
6378 (eql (org-table-get-stored-formulas))
6379 (dline (org-table-current-dline))
6380 (ref (format "@%d$%d" dline col))
6381 (ref1 (org-table-convert-refs-to-an ref))
6382 (fequation (or (assoc name eql) (assoc ref eql)))
6383 (cequation (assoc (int-to-string col) eql))
6384 (eqn (or fequation cequation)))
6385 (goto-char pos)
6386 (condition-case nil
6387 (org-table-show-reference 'local)
6388 (error nil))
6389 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
6390 dline col
6391 (if cname (concat " or $" cname) "")
6392 dline col ref1
6393 (if name (concat " or $" name) "")
6394 ;; FIXME: formula info not correct if special table line
6395 (if eqn
6396 (concat ", formula: "
6397 (org-table-formula-to-user
6398 (concat
6399 (if (string-match "^[$@]"(car eqn)) "" "$")
6400 (car eqn) "=" (cdr eqn))))
6401 "")))))
6403 (defun org-table-current-column ()
6404 "Find out which column we are in.
6405 When called interactively, column is also displayed in echo area."
6406 (interactive)
6407 (if (interactive-p) (org-table-check-inside-data-field))
6408 (save-excursion
6409 (let ((cnt 0) (pos (point)))
6410 (beginning-of-line 1)
6411 (while (search-forward "|" pos t)
6412 (setq cnt (1+ cnt)))
6413 (if (interactive-p) (message "This is table column %d" cnt))
6414 cnt)))
6416 (defun org-table-current-dline ()
6417 "Find out what table data line we are in.
6418 Only datalins count for this."
6419 (interactive)
6420 (if (interactive-p) (org-table-check-inside-data-field))
6421 (save-excursion
6422 (let ((cnt 0) (pos (point)))
6423 (goto-char (org-table-begin))
6424 (while (<= (point) pos)
6425 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
6426 (beginning-of-line 2))
6427 (if (interactive-p) (message "This is table line %d" cnt))
6428 cnt)))
6430 (defun org-table-goto-column (n &optional on-delim force)
6431 "Move the cursor to the Nth column in the current table line.
6432 With optional argument ON-DELIM, stop with point before the left delimiter
6433 of the field.
6434 If there are less than N fields, just go to after the last delimiter.
6435 However, when FORCE is non-nil, create new columns if necessary."
6436 (interactive "p")
6437 (let ((pos (point-at-eol)))
6438 (beginning-of-line 1)
6439 (when (> n 0)
6440 (while (and (> (setq n (1- n)) -1)
6441 (or (search-forward "|" pos t)
6442 (and force
6443 (progn (end-of-line 1)
6444 (skip-chars-backward "^|")
6445 (insert " | "))))))
6446 ; (backward-char 2) t)))))
6447 (when (and force (not (looking-at ".*|")))
6448 (save-excursion (end-of-line 1) (insert " | ")))
6449 (if on-delim
6450 (backward-char 1)
6451 (if (looking-at " ") (forward-char 1))))))
6453 (defun org-at-table-p (&optional table-type)
6454 "Return t if the cursor is inside an org-type table.
6455 If TABLE-TYPE is non-nil, also check for table.el-type tables."
6456 (if org-enable-table-editor
6457 (save-excursion
6458 (beginning-of-line 1)
6459 (looking-at (if table-type org-table-any-line-regexp
6460 org-table-line-regexp)))
6461 nil))
6463 (defun org-at-table.el-p ()
6464 "Return t if and only if we are at a table.el table."
6465 (and (org-at-table-p 'any)
6466 (save-excursion
6467 (goto-char (org-table-begin 'any))
6468 (looking-at org-table1-hline-regexp))))
6470 (defun org-table-recognize-table.el ()
6471 "If there is a table.el table nearby, recognize it and move into it."
6472 (if org-table-tab-recognizes-table.el
6473 (if (org-at-table.el-p)
6474 (progn
6475 (beginning-of-line 1)
6476 (if (looking-at org-table-dataline-regexp)
6478 (if (looking-at org-table1-hline-regexp)
6479 (progn
6480 (beginning-of-line 2)
6481 (if (looking-at org-table-any-border-regexp)
6482 (beginning-of-line -1)))))
6483 (if (re-search-forward "|" (org-table-end t) t)
6484 (progn
6485 (require 'table)
6486 (if (table--at-cell-p (point))
6488 (message "recognizing table.el table...")
6489 (table-recognize-table)
6490 (message "recognizing table.el table...done")))
6491 (error "This should not happen..."))
6493 nil)
6494 nil))
6496 (defun org-at-table-hline-p ()
6497 "Return t if the cursor is inside a hline in a table."
6498 (if org-enable-table-editor
6499 (save-excursion
6500 (beginning-of-line 1)
6501 (looking-at org-table-hline-regexp))
6502 nil))
6504 (defun org-table-insert-column ()
6505 "Insert a new column into the table."
6506 (interactive)
6507 (if (not (org-at-table-p))
6508 (error "Not at a table"))
6509 (org-table-find-dataline)
6510 (let* ((col (max 1 (org-table-current-column)))
6511 (beg (org-table-begin))
6512 (end (org-table-end))
6513 ;; Current cursor position
6514 (linepos (org-current-line))
6515 (colpos col))
6516 (goto-char beg)
6517 (while (< (point) end)
6518 (if (org-at-table-hline-p)
6520 (org-table-goto-column col t)
6521 (insert "| "))
6522 (beginning-of-line 2))
6523 (move-marker end nil)
6524 (goto-line linepos)
6525 (org-table-goto-column colpos)
6526 (org-table-align)
6527 (org-table-fix-formulas "$" nil (1- col) 1)))
6529 (defun org-table-find-dataline ()
6530 "Find a dataline in the current table, which is needed for column commands."
6531 (if (and (org-at-table-p)
6532 (not (org-at-table-hline-p)))
6534 (let ((col (current-column))
6535 (end (org-table-end)))
6536 (move-to-column col)
6537 (while (and (< (point) end)
6538 (or (not (= (current-column) col))
6539 (org-at-table-hline-p)))
6540 (beginning-of-line 2)
6541 (move-to-column col))
6542 (if (and (org-at-table-p)
6543 (not (org-at-table-hline-p)))
6545 (error
6546 "Please position cursor in a data line for column operations")))))
6548 (defun org-table-delete-column ()
6549 "Delete a column from the table."
6550 (interactive)
6551 (if (not (org-at-table-p))
6552 (error "Not at a table"))
6553 (org-table-find-dataline)
6554 (org-table-check-inside-data-field)
6555 (let* ((col (org-table-current-column))
6556 (beg (org-table-begin))
6557 (end (org-table-end))
6558 ;; Current cursor position
6559 (linepos (org-current-line))
6560 (colpos col))
6561 (goto-char beg)
6562 (while (< (point) end)
6563 (if (org-at-table-hline-p)
6565 (org-table-goto-column col t)
6566 (and (looking-at "|[^|\n]+|")
6567 (replace-match "|")))
6568 (beginning-of-line 2))
6569 (move-marker end nil)
6570 (goto-line linepos)
6571 (org-table-goto-column colpos)
6572 (org-table-align)
6573 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
6574 col -1 col)))
6576 (defun org-table-move-column-right ()
6577 "Move column to the right."
6578 (interactive)
6579 (org-table-move-column nil))
6580 (defun org-table-move-column-left ()
6581 "Move column to the left."
6582 (interactive)
6583 (org-table-move-column 'left))
6585 (defun org-table-move-column (&optional left)
6586 "Move the current column to the right. With arg LEFT, move to the left."
6587 (interactive "P")
6588 (if (not (org-at-table-p))
6589 (error "Not at a table"))
6590 (org-table-find-dataline)
6591 (org-table-check-inside-data-field)
6592 (let* ((col (org-table-current-column))
6593 (col1 (if left (1- col) col))
6594 (beg (org-table-begin))
6595 (end (org-table-end))
6596 ;; Current cursor position
6597 (linepos (org-current-line))
6598 (colpos (if left (1- col) (1+ col))))
6599 (if (and left (= col 1))
6600 (error "Cannot move column further left"))
6601 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6602 (error "Cannot move column further right"))
6603 (goto-char beg)
6604 (while (< (point) end)
6605 (if (org-at-table-hline-p)
6607 (org-table-goto-column col1 t)
6608 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6609 (replace-match "|\\2|\\1|")))
6610 (beginning-of-line 2))
6611 (move-marker end nil)
6612 (goto-line linepos)
6613 (org-table-goto-column colpos)
6614 (org-table-align)
6615 (org-table-fix-formulas
6616 "$" (list (cons (number-to-string col) (number-to-string colpos))
6617 (cons (number-to-string colpos) (number-to-string col))))))
6619 (defun org-table-move-row-down ()
6620 "Move table row down."
6621 (interactive)
6622 (org-table-move-row nil))
6623 (defun org-table-move-row-up ()
6624 "Move table row up."
6625 (interactive)
6626 (org-table-move-row 'up))
6628 (defun org-table-move-row (&optional up)
6629 "Move the current table line down. With arg UP, move it up."
6630 (interactive "P")
6631 (let* ((col (current-column))
6632 (pos (point))
6633 (hline1p (save-excursion (beginning-of-line 1)
6634 (looking-at org-table-hline-regexp)))
6635 (dline1 (org-table-current-dline))
6636 (dline2 (+ dline1 (if up -1 1)))
6637 (tonew (if up 0 2))
6638 txt hline2p)
6639 (beginning-of-line tonew)
6640 (unless (org-at-table-p)
6641 (goto-char pos)
6642 (error "Cannot move row further"))
6643 (setq hline2p (looking-at org-table-hline-regexp))
6644 (goto-char pos)
6645 (beginning-of-line 1)
6646 (setq pos (point))
6647 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6648 (delete-region (point) (1+ (point-at-eol)))
6649 (beginning-of-line tonew)
6650 (insert txt)
6651 (beginning-of-line 0)
6652 (move-to-column col)
6653 (unless (or hline1p hline2p)
6654 (org-table-fix-formulas
6655 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
6656 (cons (number-to-string dline2) (number-to-string dline1)))))))
6658 (defun org-table-insert-row (&optional arg)
6659 "Insert a new row above the current line into the table.
6660 With prefix ARG, insert below the current line."
6661 (interactive "P")
6662 (if (not (org-at-table-p))
6663 (error "Not at a table"))
6664 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
6665 (new (org-table-clean-line line)))
6666 ;; Fix the first field if necessary
6667 (if (string-match "^[ \t]*| *[#$] *|" line)
6668 (setq new (replace-match (match-string 0 line) t t new)))
6669 (beginning-of-line (if arg 2 1))
6670 (let (org-table-may-need-update) (insert-before-markers new "\n"))
6671 (beginning-of-line 0)
6672 (re-search-forward "| ?" (point-at-eol) t)
6673 (and (or org-table-may-need-update org-table-overlay-coordinates)
6674 (org-table-align))
6675 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
6677 (defun org-table-insert-hline (&optional arg)
6678 "Insert a horizontal-line below the current line into the table.
6679 With prefix ARG, insert above the current line."
6680 (interactive "P")
6681 (if (not (org-at-table-p))
6682 (error "Not at a table"))
6683 (let ((line (org-table-clean-line
6684 (buffer-substring (point-at-bol) (point-at-eol))))
6685 (col (current-column)))
6686 (while (string-match "|\\( +\\)|" line)
6687 (setq line (replace-match
6688 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
6689 ?-) "|") t t line)))
6690 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
6691 (beginning-of-line (if arg 1 2))
6692 (insert line "\n")
6693 (beginning-of-line (if arg 1 -1))
6694 (move-to-column col)
6695 (and org-table-overlay-coordinates (org-table-align))))
6697 (defun org-table-clean-line (s)
6698 "Convert a table line S into a string with only \"|\" and space.
6699 In particular, this does handle wide and invisible characters."
6700 (if (string-match "^[ \t]*|-" s)
6701 ;; It's a hline, just map the characters
6702 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
6703 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
6704 (setq s (replace-match
6705 (concat "|" (make-string (org-string-width (match-string 1 s))
6706 ?\ ) "|")
6707 t t s)))
6710 (defun org-table-kill-row ()
6711 "Delete the current row or horizontal line from the table."
6712 (interactive)
6713 (if (not (org-at-table-p))
6714 (error "Not at a table"))
6715 (let ((col (current-column))
6716 (dline (org-table-current-dline)))
6717 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6718 (if (not (org-at-table-p)) (beginning-of-line 0))
6719 (move-to-column col)
6720 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
6721 dline -1 dline)))
6724 (defun org-table-sort-lines (with-case &optional sorting-type)
6725 "Sort table lines according to the column at point.
6727 The position of point indicates the column to be used for
6728 sorting, and the range of lines is the range between the nearest
6729 horizontal separator lines, or the entire table of no such lines
6730 exist. If point is before the first column, you will be prompted
6731 for the sorting column. If there is an active region, the mark
6732 specifies the first line and the sorting column, while point
6733 should be in the last line to be included into the sorting.
6735 The command then prompts for the sorting type which can be
6736 alphabetically, numerically, or by time (as given in a time stamp
6737 in the field). Sorting in reverse order is also possible.
6739 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
6741 If SORTING-TYPE is specified when this function is called from a Lisp
6742 program, no prompting will take place. SORTING-TYPE must be a character,
6743 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
6744 should be done in reverse order."
6745 (interactive "P")
6746 (let* ((thisline (org-current-line))
6747 (thiscol (org-table-current-column))
6748 beg end bcol ecol tend tbeg column lns pos)
6749 (when (equal thiscol 0)
6750 (if (interactive-p)
6751 (setq thiscol
6752 (string-to-number
6753 (read-string "Use column N for sorting: ")))
6754 (setq thiscol 1))
6755 (org-table-goto-column thiscol))
6756 (org-table-check-inside-data-field)
6757 (if (org-region-active-p)
6758 (progn
6759 (setq beg (region-beginning) end (region-end))
6760 (goto-char beg)
6761 (setq column (org-table-current-column)
6762 beg (point-at-bol))
6763 (goto-char end)
6764 (setq end (point-at-bol 2)))
6765 (setq column (org-table-current-column)
6766 pos (point)
6767 tbeg (org-table-begin)
6768 tend (org-table-end))
6769 (if (re-search-backward org-table-hline-regexp tbeg t)
6770 (setq beg (point-at-bol 2))
6771 (goto-char tbeg)
6772 (setq beg (point-at-bol 1)))
6773 (goto-char pos)
6774 (if (re-search-forward org-table-hline-regexp tend t)
6775 (setq beg (point-at-bol 0))
6776 (goto-char tend)
6777 (setq end (point-at-bol))))
6778 (setq beg (move-marker (make-marker) beg)
6779 end (move-marker (make-marker) end))
6780 (untabify beg end)
6781 (goto-char beg)
6782 (org-table-goto-column column)
6783 (skip-chars-backward "^|")
6784 (setq bcol (current-column))
6785 (org-table-goto-column (1+ column))
6786 (skip-chars-backward "^|")
6787 (setq ecol (1- (current-column)))
6788 (org-table-goto-column column)
6789 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
6790 (org-split-string (buffer-substring beg end) "\n")))
6791 (setq lns (org-do-sort lns "Table" with-case sorting-type))
6792 (delete-region beg end)
6793 (move-marker beg nil)
6794 (move-marker end nil)
6795 (insert (mapconcat 'cdr lns "\n") "\n")
6796 (goto-line thisline)
6797 (org-table-goto-column thiscol)
6798 (message "%d lines sorted, based on column %d" (length lns) column)))
6800 (defun org-table-cut-region (beg end)
6801 "Copy region in table to the clipboard and blank all relevant fields."
6802 (interactive "r")
6803 (org-table-copy-region beg end 'cut))
6805 (defun org-table-copy-region (beg end &optional cut)
6806 "Copy rectangular region in table to clipboard.
6807 A special clipboard is used which can only be accessed
6808 with `org-table-paste-rectangle'."
6809 (interactive "rP")
6810 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6811 region cols
6812 (rpl (if cut " " nil)))
6813 (goto-char beg)
6814 (org-table-check-inside-data-field)
6815 (setq l01 (org-current-line)
6816 c01 (org-table-current-column))
6817 (goto-char end)
6818 (org-table-check-inside-data-field)
6819 (setq l02 (org-current-line)
6820 c02 (org-table-current-column))
6821 (setq l1 (min l01 l02) l2 (max l01 l02)
6822 c1 (min c01 c02) c2 (max c01 c02))
6823 (catch 'exit
6824 (while t
6825 (catch 'nextline
6826 (if (> l1 l2) (throw 'exit t))
6827 (goto-line l1)
6828 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6829 (setq cols nil ic1 c1 ic2 c2)
6830 (while (< ic1 (1+ ic2))
6831 (push (org-table-get-field ic1 rpl) cols)
6832 (setq ic1 (1+ ic1)))
6833 (push (nreverse cols) region)
6834 (setq l1 (1+ l1)))))
6835 (setq org-table-clip (nreverse region))
6836 (if cut (org-table-align))
6837 org-table-clip))
6839 (defun org-table-paste-rectangle ()
6840 "Paste a rectangular region into a table.
6841 The upper right corner ends up in the current field. All involved fields
6842 will be overwritten. If the rectangle does not fit into the present table,
6843 the table is enlarged as needed. The process ignores horizontal separator
6844 lines."
6845 (interactive)
6846 (unless (and org-table-clip (listp org-table-clip))
6847 (error "First cut/copy a region to paste!"))
6848 (org-table-check-inside-data-field)
6849 (let* ((clip org-table-clip)
6850 (line (org-current-line))
6851 (col (org-table-current-column))
6852 (org-enable-table-editor t)
6853 (org-table-automatic-realign nil)
6854 c cols field)
6855 (while (setq cols (pop clip))
6856 (while (org-at-table-hline-p) (beginning-of-line 2))
6857 (if (not (org-at-table-p))
6858 (progn (end-of-line 0) (org-table-next-field)))
6859 (setq c col)
6860 (while (setq field (pop cols))
6861 (org-table-goto-column c nil 'force)
6862 (org-table-get-field nil field)
6863 (setq c (1+ c)))
6864 (beginning-of-line 2))
6865 (goto-line line)
6866 (org-table-goto-column col)
6867 (org-table-align)))
6869 (defun org-table-convert ()
6870 "Convert from `org-mode' table to table.el and back.
6871 Obviously, this only works within limits. When an Org-mode table is
6872 converted to table.el, all horizontal separator lines get lost, because
6873 table.el uses these as cell boundaries and has no notion of horizontal lines.
6874 A table.el table can be converted to an Org-mode table only if it does not
6875 do row or column spanning. Multiline cells will become multiple cells.
6876 Beware, Org-mode does not test if the table can be successfully converted - it
6877 blindly applies a recipe that works for simple tables."
6878 (interactive)
6879 (require 'table)
6880 (if (org-at-table.el-p)
6881 ;; convert to Org-mode table
6882 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6883 (end (move-marker (make-marker) (org-table-end t))))
6884 (table-unrecognize-region beg end)
6885 (goto-char beg)
6886 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6887 (replace-match ""))
6888 (goto-char beg))
6889 (if (org-at-table-p)
6890 ;; convert to table.el table
6891 (let ((beg (move-marker (make-marker) (org-table-begin)))
6892 (end (move-marker (make-marker) (org-table-end))))
6893 ;; first, get rid of all horizontal lines
6894 (goto-char beg)
6895 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6896 (replace-match ""))
6897 ;; insert a hline before first
6898 (goto-char beg)
6899 (org-table-insert-hline 'above)
6900 (beginning-of-line -1)
6901 ;; insert a hline after each line
6902 (while (progn (beginning-of-line 3) (< (point) end))
6903 (org-table-insert-hline))
6904 (goto-char beg)
6905 (setq end (move-marker end (org-table-end)))
6906 ;; replace "+" at beginning and ending of hlines
6907 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6908 (replace-match "\\1+-"))
6909 (goto-char beg)
6910 (while (re-search-forward "-|[ \t]*$" end t)
6911 (replace-match "-+"))
6912 (goto-char beg)))))
6914 (defun org-table-wrap-region (arg)
6915 "Wrap several fields in a column like a paragraph.
6916 This is useful if you'd like to spread the contents of a field over several
6917 lines, in order to keep the table compact.
6919 If there is an active region, and both point and mark are in the same column,
6920 the text in the column is wrapped to minimum width for the given number of
6921 lines. Generally, this makes the table more compact. A prefix ARG may be
6922 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6923 formats the selected text to two lines. If the region was longer than two
6924 lines, the remaining lines remain empty. A negative prefix argument reduces
6925 the current number of lines by that amount. The wrapped text is pasted back
6926 into the table. If you formatted it to more lines than it was before, fields
6927 further down in the table get overwritten - so you might need to make space in
6928 the table first.
6930 If there is no region, the current field is split at the cursor position and
6931 the text fragment to the right of the cursor is prepended to the field one
6932 line down.
6934 If there is no region, but you specify a prefix ARG, the current field gets
6935 blank, and the content is appended to the field above."
6936 (interactive "P")
6937 (org-table-check-inside-data-field)
6938 (if (org-region-active-p)
6939 ;; There is a region: fill as a paragraph
6940 (let* ((beg (region-beginning))
6941 (cline (save-excursion (goto-char beg) (org-current-line)))
6942 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
6943 nlines)
6944 (org-table-cut-region (region-beginning) (region-end))
6945 (if (> (length (car org-table-clip)) 1)
6946 (error "Region must be limited to single column"))
6947 (setq nlines (if arg
6948 (if (< arg 1)
6949 (+ (length org-table-clip) arg)
6950 arg)
6951 (length org-table-clip)))
6952 (setq org-table-clip
6953 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6954 nil nlines)))
6955 (goto-line cline)
6956 (org-table-goto-column ccol)
6957 (org-table-paste-rectangle))
6958 ;; No region, split the current field at point
6959 (if arg
6960 ;; combine with field above
6961 (let ((s (org-table-blank-field))
6962 (col (org-table-current-column)))
6963 (beginning-of-line 0)
6964 (while (org-at-table-hline-p) (beginning-of-line 0))
6965 (org-table-goto-column col)
6966 (skip-chars-forward "^|")
6967 (skip-chars-backward " ")
6968 (insert " " (org-trim s))
6969 (org-table-align))
6970 ;; split field
6971 (when (looking-at "\\([^|]+\\)+|")
6972 (let ((s (match-string 1)))
6973 (replace-match " |")
6974 (goto-char (match-beginning 0))
6975 (org-table-next-row)
6976 (insert (org-trim s) " ")
6977 (org-table-align))))))
6979 (defvar org-field-marker nil)
6981 (defun org-table-edit-field (arg)
6982 "Edit table field in a different window.
6983 This is mainly useful for fields that contain hidden parts.
6984 When called with a \\[universal-argument] prefix, just make the full field visible so that
6985 it can be edited in place."
6986 (interactive "P")
6987 (if arg
6988 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
6989 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
6990 (remove-text-properties b e '(org-cwidth t invisible t
6991 display t intangible t))
6992 (if (and (boundp 'font-lock-mode) font-lock-mode)
6993 (font-lock-fontify-block)))
6994 (let ((pos (move-marker (make-marker) (point)))
6995 (field (org-table-get-field))
6996 (cw (current-window-configuration))
6998 (switch-to-buffer-other-window "*Org tmp*")
6999 (erase-buffer)
7000 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
7001 (org-mode)
7002 (goto-char (setq p (point-max)))
7003 (insert (org-trim field))
7004 (remove-text-properties p (point-max)
7005 '(invisible t org-cwidth t display t
7006 intangible t))
7007 (goto-char p)
7008 (org-set-local 'org-finish-function
7009 'org-table-finish-edit-field)
7010 (org-set-local 'org-window-configuration cw)
7011 (org-set-local 'org-field-marker pos)
7012 (message "Edit and finish with C-c C-c"))))
7014 (defun org-table-finish-edit-field ()
7015 "Finish editing a table data field.
7016 Remove all newline characters, insert the result into the table, realign
7017 the table and kill the editing buffer."
7018 (let ((pos org-field-marker)
7019 (cw org-window-configuration)
7020 (cb (current-buffer))
7021 text)
7022 (goto-char (point-min))
7023 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
7024 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
7025 (replace-match " "))
7026 (setq text (org-trim (buffer-string)))
7027 (set-window-configuration cw)
7028 (kill-buffer cb)
7029 (select-window (get-buffer-window (marker-buffer pos)))
7030 (goto-char pos)
7031 (move-marker pos nil)
7032 (org-table-check-inside-data-field)
7033 (org-table-get-field nil text)
7034 (org-table-align)
7035 (message "New field value inserted")))
7037 (defun org-trim (s)
7038 "Remove whitespace at beginning and end of string."
7039 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
7040 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
7043 (defun org-wrap (string &optional width lines)
7044 "Wrap string to either a number of lines, or a width in characters.
7045 If WIDTH is non-nil, the string is wrapped to that width, however many lines
7046 that costs. If there is a word longer than WIDTH, the text is actually
7047 wrapped to the length of that word.
7048 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
7049 many lines, whatever width that takes.
7050 The return value is a list of lines, without newlines at the end."
7051 (let* ((words (org-split-string string "[ \t\n]+"))
7052 (maxword (apply 'max (mapcar 'org-string-width words)))
7053 w ll)
7054 (cond (width
7055 (org-do-wrap words (max maxword width)))
7056 (lines
7057 (setq w maxword)
7058 (setq ll (org-do-wrap words maxword))
7059 (if (<= (length ll) lines)
7061 (setq ll words)
7062 (while (> (length ll) lines)
7063 (setq w (1+ w))
7064 (setq ll (org-do-wrap words w)))
7065 ll))
7066 (t (error "Cannot wrap this")))))
7069 (defun org-do-wrap (words width)
7070 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
7071 (let (lines line)
7072 (while words
7073 (setq line (pop words))
7074 (while (and words (< (+ (length line) (length (car words))) width))
7075 (setq line (concat line " " (pop words))))
7076 (setq lines (push line lines)))
7077 (nreverse lines)))
7079 (defun org-split-string (string &optional separators)
7080 "Splits STRING into substrings at SEPARATORS.
7081 No empty strings are returned if there are matches at the beginning
7082 and end of string."
7083 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
7084 (start 0)
7085 notfirst
7086 (list nil))
7087 (while (and (string-match rexp string
7088 (if (and notfirst
7089 (= start (match-beginning 0))
7090 (< start (length string)))
7091 (1+ start) start))
7092 (< (match-beginning 0) (length string)))
7093 (setq notfirst t)
7094 (or (eq (match-beginning 0) 0)
7095 (and (eq (match-beginning 0) (match-end 0))
7096 (eq (match-beginning 0) start))
7097 (setq list
7098 (cons (substring string start (match-beginning 0))
7099 list)))
7100 (setq start (match-end 0)))
7101 (or (eq start (length string))
7102 (setq list
7103 (cons (substring string start)
7104 list)))
7105 (nreverse list)))
7107 (defun org-table-map-tables (function)
7108 "Apply FUNCTION to the start of all tables in the buffer."
7109 (save-excursion
7110 (save-restriction
7111 (widen)
7112 (goto-char (point-min))
7113 (while (re-search-forward org-table-any-line-regexp nil t)
7114 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7115 (beginning-of-line 1)
7116 (if (looking-at org-table-line-regexp)
7117 (save-excursion (funcall function)))
7118 (re-search-forward org-table-any-border-regexp nil 1))))
7119 (message "Mapping tables: done"))
7121 (defvar org-timecnt) ; dynamically scoped parameter
7123 (defun org-table-sum (&optional beg end nlast)
7124 "Sum numbers in region of current table column.
7125 The result will be displayed in the echo area, and will be available
7126 as kill to be inserted with \\[yank].
7128 If there is an active region, it is interpreted as a rectangle and all
7129 numbers in that rectangle will be summed. If there is no active
7130 region and point is located in a table column, sum all numbers in that
7131 column.
7133 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7134 numbers are assumed to be times as well (in decimal hours) and the
7135 numbers are added as such.
7137 If NLAST is a number, only the NLAST fields will actually be summed."
7138 (interactive)
7139 (save-excursion
7140 (let (col (org-timecnt 0) diff h m s org-table-clip)
7141 (cond
7142 ((and beg end)) ; beg and end given explicitly
7143 ((org-region-active-p)
7144 (setq beg (region-beginning) end (region-end)))
7146 (setq col (org-table-current-column))
7147 (goto-char (org-table-begin))
7148 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7149 (error "No table data"))
7150 (org-table-goto-column col)
7151 (setq beg (point))
7152 (goto-char (org-table-end))
7153 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7154 (error "No table data"))
7155 (org-table-goto-column col)
7156 (setq end (point))))
7157 (let* ((items (apply 'append (org-table-copy-region beg end)))
7158 (items1 (cond ((not nlast) items)
7159 ((>= nlast (length items)) items)
7160 (t (setq items (reverse items))
7161 (setcdr (nthcdr (1- nlast) items) nil)
7162 (nreverse items))))
7163 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7164 items1)))
7165 (res (apply '+ numbers))
7166 (sres (if (= org-timecnt 0)
7167 (format "%g" res)
7168 (setq diff (* 3600 res)
7169 h (floor (/ diff 3600)) diff (mod diff 3600)
7170 m (floor (/ diff 60)) diff (mod diff 60)
7171 s diff)
7172 (format "%d:%02d:%02d" h m s))))
7173 (kill-new sres)
7174 (if (interactive-p)
7175 (message "%s"
7176 (substitute-command-keys
7177 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7178 (length numbers) sres))))
7179 sres))))
7181 (defun org-table-get-number-for-summing (s)
7182 (let (n)
7183 (if (string-match "^ *|? *" s)
7184 (setq s (replace-match "" nil nil s)))
7185 (if (string-match " *|? *$" s)
7186 (setq s (replace-match "" nil nil s)))
7187 (setq n (string-to-number s))
7188 (cond
7189 ((and (string-match "0" s)
7190 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7191 ((string-match "\\`[ \t]+\\'" s) nil)
7192 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7193 (let ((h (string-to-number (or (match-string 1 s) "0")))
7194 (m (string-to-number (or (match-string 2 s) "0")))
7195 (s (string-to-number (or (match-string 4 s) "0"))))
7196 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
7197 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7198 ((equal n 0) nil)
7199 (t n))))
7201 (defun org-table-current-field-formula (&optional key noerror)
7202 "Return the formula active for the current field.
7203 Assumes that specials are in place.
7204 If KEY is given, return the key to this formula.
7205 Otherwise return the formula preceeded with \"=\" or \":=\"."
7206 (let* ((name (car (rassoc (list (org-current-line)
7207 (org-table-current-column))
7208 org-table-named-field-locations)))
7209 (col (org-table-current-column))
7210 (scol (int-to-string col))
7211 (ref (format "@%d$%d" (org-table-current-dline) col))
7212 (stored-list (org-table-get-stored-formulas noerror))
7213 (ass (or (assoc name stored-list)
7214 (assoc ref stored-list)
7215 (assoc scol stored-list))))
7216 (if key
7217 (car ass)
7218 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
7219 (cdr ass))))))
7221 (defun org-table-get-formula (&optional equation named)
7222 "Read a formula from the minibuffer, offer stored formula as default.
7223 When NAMED is non-nil, look for a named equation."
7224 (let* ((stored-list (org-table-get-stored-formulas))
7225 (name (car (rassoc (list (org-current-line)
7226 (org-table-current-column))
7227 org-table-named-field-locations)))
7228 (ref (format "@%d$%d" (org-table-current-dline)
7229 (org-table-current-column)))
7230 (refass (assoc ref stored-list))
7231 (scol (if named
7232 (if name name ref)
7233 (int-to-string (org-table-current-column))))
7234 (dummy (and (or name refass) (not named)
7235 (not (y-or-n-p "Replace field formula with column formula? " ))
7236 (error "Abort")))
7237 (name (or name ref))
7238 (org-table-may-need-update nil)
7239 (stored (cdr (assoc scol stored-list)))
7240 (eq (cond
7241 ((and stored equation (string-match "^ *=? *$" equation))
7242 stored)
7243 ((stringp equation)
7244 equation)
7245 (t (org-table-formula-from-user
7246 (read-string
7247 (org-table-formula-to-user
7248 (format "%s formula %s%s="
7249 (if named "Field" "Column")
7250 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
7251 scol))
7252 (if stored (org-table-formula-to-user stored) "")
7253 'org-table-formula-history
7254 )))))
7255 mustsave)
7256 (when (not (string-match "\\S-" eq))
7257 ;; remove formula
7258 (setq stored-list (delq (assoc scol stored-list) stored-list))
7259 (org-table-store-formulas stored-list)
7260 (error "Formula removed"))
7261 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7262 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7263 (if (and name (not named))
7264 ;; We set the column equation, delete the named one.
7265 (setq stored-list (delq (assoc name stored-list) stored-list)
7266 mustsave t))
7267 (if stored
7268 (setcdr (assoc scol stored-list) eq)
7269 (setq stored-list (cons (cons scol eq) stored-list)))
7270 (if (or mustsave (not (equal stored eq)))
7271 (org-table-store-formulas stored-list))
7272 eq))
7274 (defun org-table-store-formulas (alist)
7275 "Store the list of formulas below the current table."
7276 (setq alist (sort alist 'org-table-formula-less-p))
7277 (save-excursion
7278 (goto-char (org-table-end))
7279 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
7280 (progn
7281 ;; don't overwrite TBLFM, we might use text properties to store stuff
7282 (goto-char (match-beginning 2))
7283 (delete-region (match-beginning 2) (match-end 0)))
7284 (insert "#+TBLFM:"))
7285 (insert " "
7286 (mapconcat (lambda (x)
7287 (concat
7288 (if (equal (string-to-char (car x)) ?@) "" "$")
7289 (car x) "=" (cdr x)))
7290 alist "::")
7291 "\n")))
7293 (defsubst org-table-formula-make-cmp-string (a)
7294 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
7295 (concat
7296 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
7297 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
7298 (if (match-end 5) (concat "@@" (match-string 5 a))))))
7300 (defun org-table-formula-less-p (a b)
7301 "Compare two formulas for sorting."
7302 (let ((as (org-table-formula-make-cmp-string (car a)))
7303 (bs (org-table-formula-make-cmp-string (car b))))
7304 (and as bs (string< as bs))))
7306 (defun org-table-get-stored-formulas (&optional noerror)
7307 "Return an alist with the stored formulas directly after current table."
7308 (interactive)
7309 (let (scol eq eq-alist strings string seen)
7310 (save-excursion
7311 (goto-char (org-table-end))
7312 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7313 (setq strings (org-split-string (match-string 2) " *:: *"))
7314 (while (setq string (pop strings))
7315 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
7316 (setq scol (if (match-end 2)
7317 (match-string 2 string)
7318 (match-string 1 string))
7319 eq (match-string 3 string)
7320 eq-alist (cons (cons scol eq) eq-alist))
7321 (if (member scol seen)
7322 (if noerror
7323 (progn
7324 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7325 (ding)
7326 (sit-for 2))
7327 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
7328 (push scol seen))))))
7329 (nreverse eq-alist)))
7331 (defun org-table-fix-formulas (key replace &optional limit delta remove)
7332 "Modify the equations after the table structure has been edited.
7333 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
7334 For all numbers larger than LIMIT, shift them by DELTA."
7335 (save-excursion
7336 (goto-char (org-table-end))
7337 (when (looking-at "#\\+TBLFM:")
7338 (let ((re (concat key "\\([0-9]+\\)"))
7339 (re2
7340 (when remove
7341 (if (equal key "$")
7342 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
7343 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
7344 s n a)
7345 (when remove
7346 (while (re-search-forward re2 (point-at-eol) t)
7347 (replace-match "")))
7348 (while (re-search-forward re (point-at-eol) t)
7349 (setq s (match-string 1) n (string-to-number s))
7350 (cond
7351 ((setq a (assoc s replace))
7352 (replace-match (concat key (cdr a)) t t))
7353 ((and limit (> n limit))
7354 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
7356 (defun org-table-get-specials ()
7357 "Get the column names and local parameters for this table."
7358 (save-excursion
7359 (let ((beg (org-table-begin)) (end (org-table-end))
7360 names name fields fields1 field cnt
7361 c v l line col types dlines hlines)
7362 (setq org-table-column-names nil
7363 org-table-local-parameters nil
7364 org-table-named-field-locations nil
7365 org-table-current-begin-line nil
7366 org-table-current-begin-pos nil
7367 org-table-current-line-types nil)
7368 (goto-char beg)
7369 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7370 (setq names (org-split-string (match-string 1) " *| *")
7371 cnt 1)
7372 (while (setq name (pop names))
7373 (setq cnt (1+ cnt))
7374 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7375 (push (cons name (int-to-string cnt)) org-table-column-names))))
7376 (setq org-table-column-names (nreverse org-table-column-names))
7377 (setq org-table-column-name-regexp
7378 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7379 (goto-char beg)
7380 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7381 (setq fields (org-split-string (match-string 1) " *| *"))
7382 (while (setq field (pop fields))
7383 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7384 (push (cons (match-string 1 field) (match-string 2 field))
7385 org-table-local-parameters))))
7386 (goto-char beg)
7387 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7388 (setq c (match-string 1)
7389 fields (org-split-string (match-string 2) " *| *"))
7390 (save-excursion
7391 (beginning-of-line (if (equal c "_") 2 0))
7392 (setq line (org-current-line) col 1)
7393 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7394 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7395 (while (and fields1 (setq field (pop fields)))
7396 (setq v (pop fields1) col (1+ col))
7397 (when (and (stringp field) (stringp v)
7398 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7399 (push (cons field v) org-table-local-parameters)
7400 (push (list field line col) org-table-named-field-locations))))
7401 ;; Analyse the line types
7402 (goto-char beg)
7403 (setq org-table-current-begin-line (org-current-line)
7404 org-table-current-begin-pos (point)
7405 l org-table-current-begin-line)
7406 (while (looking-at "[ \t]*|\\(-\\)?")
7407 (push (if (match-end 1) 'hline 'dline) types)
7408 (if (match-end 1) (push l hlines) (push l dlines))
7409 (beginning-of-line 2)
7410 (setq l (1+ l)))
7411 (setq org-table-current-line-types (apply 'vector (nreverse types))
7412 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
7413 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
7415 (defun org-this-word ()
7416 ;; Get the current word
7417 (save-excursion
7418 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7419 (end (progn (skip-chars-forward "^ \t\n") (point))))
7420 (buffer-substring-no-properties beg end))))
7422 (defun org-table-maybe-eval-formula ()
7423 "Check if the current field starts with \"=\" or \":=\".
7424 If yes, store the formula and apply it."
7425 ;; We already know we are in a table. Get field will only return a formula
7426 ;; when appropriate. It might return a separator line, but no problem.
7427 (when org-table-formula-evaluate-inline
7428 (let* ((field (org-trim (or (org-table-get-field) "")))
7429 named eq)
7430 (when (string-match "^:?=\\(.*\\)" field)
7431 (setq named (equal (string-to-char field) ?:)
7432 eq (match-string 1 field))
7433 (if (or (fboundp 'calc-eval)
7434 (equal (substring eq 0 (min 2 (length eq))) "'("))
7435 (org-table-eval-formula (if named '(4) nil)
7436 (org-table-formula-from-user eq))
7437 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
7439 (defvar org-recalc-commands nil
7440 "List of commands triggering the recalculation of a line.
7441 Will be filled automatically during use.")
7443 (defvar org-recalc-marks
7444 '((" " . "Unmarked: no special line, no automatic recalculation")
7445 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7446 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7447 ("!" . "Column name definition line. Reference in formula as $name.")
7448 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7449 ("_" . "Names for values in row below this one.")
7450 ("^" . "Names for values in row above this one.")))
7452 (defun org-table-rotate-recalc-marks (&optional newchar)
7453 "Rotate the recalculation mark in the first column.
7454 If in any row, the first field is not consistent with a mark,
7455 insert a new column for the markers.
7456 When there is an active region, change all the lines in the region,
7457 after prompting for the marking character.
7458 After each change, a message will be displayed indicating the meaning
7459 of the new mark."
7460 (interactive)
7461 (unless (org-at-table-p) (error "Not at a table"))
7462 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7463 (beg (org-table-begin))
7464 (end (org-table-end))
7465 (l (org-current-line))
7466 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7467 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7468 (have-col
7469 (save-excursion
7470 (goto-char beg)
7471 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7472 (col (org-table-current-column))
7473 (forcenew (car (assoc newchar org-recalc-marks)))
7474 epos new)
7475 (when l1
7476 (message "Change region to what mark? Type # * ! $ or SPC: ")
7477 (setq newchar (char-to-string (read-char-exclusive))
7478 forcenew (car (assoc newchar org-recalc-marks))))
7479 (if (and newchar (not forcenew))
7480 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7481 newchar))
7482 (if l1 (goto-line l1))
7483 (save-excursion
7484 (beginning-of-line 1)
7485 (unless (looking-at org-table-dataline-regexp)
7486 (error "Not at a table data line")))
7487 (unless have-col
7488 (org-table-goto-column 1)
7489 (org-table-insert-column)
7490 (org-table-goto-column (1+ col)))
7491 (setq epos (point-at-eol))
7492 (save-excursion
7493 (beginning-of-line 1)
7494 (org-table-get-field
7495 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7496 (concat " "
7497 (setq new (or forcenew
7498 (cadr (member (match-string 1) marks))))
7499 " ")
7500 " # ")))
7501 (if (and l1 l2)
7502 (progn
7503 (goto-line l1)
7504 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7505 (and (looking-at org-table-dataline-regexp)
7506 (org-table-get-field 1 (concat " " new " "))))
7507 (goto-line l1)))
7508 (if (not (= epos (point-at-eol))) (org-table-align))
7509 (goto-line l)
7510 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7512 (defun org-table-maybe-recalculate-line ()
7513 "Recompute the current line if marked for it, and if we haven't just done it."
7514 (interactive)
7515 (and org-table-allow-automatic-line-recalculation
7516 (not (and (memq last-command org-recalc-commands)
7517 (equal org-last-recalc-line (org-current-line))))
7518 (save-excursion (beginning-of-line 1)
7519 (looking-at org-table-auto-recalculate-regexp))
7520 (org-table-recalculate) t))
7522 (defvar org-table-formula-debug nil
7523 "Non-nil means, debug table formulas.
7524 When nil, simply write \"#ERROR\" in corrupted fields.")
7525 (make-variable-buffer-local 'org-table-formula-debug)
7527 (defvar modes)
7528 (defsubst org-set-calc-mode (var &optional value)
7529 (if (stringp var)
7530 (setq var (assoc var '(("D" calc-angle-mode deg)
7531 ("R" calc-angle-mode rad)
7532 ("F" calc-prefer-frac t)
7533 ("S" calc-symbolic-mode t)))
7534 value (nth 2 var) var (nth 1 var)))
7535 (if (memq var modes)
7536 (setcar (cdr (memq var modes)) value)
7537 (cons var (cons value modes)))
7538 modes)
7540 (defun org-table-eval-formula (&optional arg equation
7541 suppress-align suppress-const
7542 suppress-store suppress-analysis)
7543 "Replace the table field value at the cursor by the result of a calculation.
7545 This function makes use of Dave Gillespie's Calc package, in my view the
7546 most exciting program ever written for GNU Emacs. So you need to have Calc
7547 installed in order to use this function.
7549 In a table, this command replaces the value in the current field with the
7550 result of a formula. It also installs the formula as the \"current\" column
7551 formula, by storing it in a special line below the table. When called
7552 with a `C-u' prefix, the current field must ba a named field, and the
7553 formula is installed as valid in only this specific field.
7555 When called with two `C-u' prefixes, insert the active equation
7556 for the field back into the current field, so that it can be
7557 edited there. This is useful in order to use \\[org-table-show-reference]
7558 to check the referenced fields.
7560 When called, the command first prompts for a formula, which is read in
7561 the minibuffer. Previously entered formulas are available through the
7562 history list, and the last used formula is offered as a default.
7563 These stored formulas are adapted correctly when moving, inserting, or
7564 deleting columns with the corresponding commands.
7566 The formula can be any algebraic expression understood by the Calc package.
7567 For details, see the Org-mode manual.
7569 This function can also be called from Lisp programs and offers
7570 additional arguments: EQUATION can be the formula to apply. If this
7571 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7572 used to speed-up recursive calls by by-passing unnecessary aligns.
7573 SUPPRESS-CONST suppresses the interpretation of constants in the
7574 formula, assuming that this has been done already outside the function.
7575 SUPPRESS-STORE means the formula should not be stored, either because
7576 it is already stored, or because it is a modified equation that should
7577 not overwrite the stored one."
7578 (interactive "P")
7579 (org-table-check-inside-data-field)
7580 (or suppress-analysis (org-table-get-specials))
7581 (if (equal arg '(16))
7582 (let ((eq (org-table-current-field-formula)))
7583 (or eq (error "No equation active for current field"))
7584 (org-table-get-field nil eq)
7585 (org-table-align)
7586 (setq org-table-may-need-update t))
7587 (let* (fields
7588 (ndown (if (integerp arg) arg 1))
7589 (org-table-automatic-realign nil)
7590 (case-fold-search nil)
7591 (down (> ndown 1))
7592 (formula (if (and equation suppress-store)
7593 equation
7594 (org-table-get-formula equation (equal arg '(4)))))
7595 (n0 (org-table-current-column))
7596 (modes (copy-sequence org-calc-default-modes))
7597 (numbers nil) ; was a variable, now fixed default
7598 (keep-empty nil)
7599 n form form0 bw fmt x ev orig c lispp)
7600 ;; Parse the format string. Since we have a lot of modes, this is
7601 ;; a lot of work. However, I think calc still uses most of the time.
7602 (if (string-match ";" formula)
7603 (let ((tmp (org-split-string formula ";")))
7604 (setq formula (car tmp)
7605 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7606 (nth 1 tmp)))
7607 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
7608 (setq c (string-to-char (match-string 1 fmt))
7609 n (string-to-number (match-string 2 fmt)))
7610 (if (= c ?p)
7611 (setq modes (org-set-calc-mode 'calc-internal-prec n))
7612 (setq modes (org-set-calc-mode
7613 'calc-float-format
7614 (list (cdr (assoc c '((?n . float) (?f . fix)
7615 (?s . sci) (?e . eng))))
7616 n))))
7617 (setq fmt (replace-match "" t t fmt)))
7618 (if (string-match "[NT]" fmt)
7619 (setq numbers (equal (match-string 0 fmt) "N")
7620 fmt (replace-match "" t t fmt)))
7621 (if (string-match "E" fmt)
7622 (setq keep-empty t
7623 fmt (replace-match "" t t fmt)))
7624 (while (string-match "[DRFS]" fmt)
7625 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7626 (setq fmt (replace-match "" t t fmt)))
7627 (unless (string-match "\\S-" fmt)
7628 (setq fmt nil))))
7629 (if (and (not suppress-const) org-table-formula-use-constants)
7630 (setq formula (org-table-formula-substitute-names formula)))
7631 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7632 (while (> ndown 0)
7633 (setq fields (org-split-string
7634 (org-no-properties
7635 (buffer-substring (point-at-bol) (point-at-eol)))
7636 " *| *"))
7637 (if numbers
7638 (setq fields (mapcar
7639 (lambda (x) (number-to-string (string-to-number x)))
7640 fields)))
7641 (setq ndown (1- ndown))
7642 (setq form (copy-sequence formula)
7643 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
7644 ;; Check for old vertical references
7645 (setq form (org-rewrite-old-row-references form))
7646 ;; Insert complex ranges
7647 (while (string-match org-table-range-regexp form)
7648 (setq form
7649 (replace-match
7650 (save-match-data
7651 (org-table-make-reference
7652 (org-table-get-range (match-string 0 form) nil n0)
7653 keep-empty numbers lispp))
7654 t t form)))
7655 ;; Insert simple ranges
7656 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
7657 (setq form
7658 (replace-match
7659 (save-match-data
7660 (org-table-make-reference
7661 (org-sublist
7662 fields (string-to-number (match-string 1 form))
7663 (string-to-number (match-string 2 form)))
7664 keep-empty numbers lispp))
7665 t t form)))
7666 (setq form0 form)
7667 ;; Insert the references to fields in same row
7668 (while (string-match "\\$\\([0-9]+\\)" form)
7669 (setq n (string-to-number (match-string 1 form))
7670 x (nth (1- (if (= n 0) n0 n)) fields))
7671 (unless x (error "Invalid field specifier \"%s\""
7672 (match-string 0 form)))
7673 (setq form (replace-match
7674 (save-match-data
7675 (org-table-make-reference x nil numbers lispp))
7676 t t form)))
7678 (if lispp
7679 (setq ev (condition-case nil
7680 (eval (eval (read form)))
7681 (error "#ERROR"))
7682 ev (if (numberp ev) (number-to-string ev) ev))
7683 (or (fboundp 'calc-eval)
7684 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
7685 (setq ev (calc-eval (cons form modes)
7686 (if numbers 'num))))
7688 (when org-table-formula-debug
7689 (with-output-to-temp-buffer "*Substitution History*"
7690 (princ (format "Substitution history of formula
7691 Orig: %s
7692 $xyz-> %s
7693 @r$c-> %s
7694 $1-> %s\n" orig formula form0 form))
7695 (if (listp ev)
7696 (princ (format " %s^\nError: %s"
7697 (make-string (car ev) ?\-) (nth 1 ev)))
7698 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7699 ev (or fmt "NONE")
7700 (if fmt (format fmt (string-to-number ev)) ev)))))
7701 (setq bw (get-buffer-window "*Substitution History*"))
7702 (shrink-window-if-larger-than-buffer bw)
7703 (unless (and (interactive-p) (not ndown))
7704 (unless (let (inhibit-redisplay)
7705 (y-or-n-p "Debugging Formula. Continue to next? "))
7706 (org-table-align)
7707 (error "Abort"))
7708 (delete-window bw)
7709 (message "")))
7710 (if (listp ev) (setq fmt nil ev "#ERROR"))
7711 (org-table-justify-field-maybe
7712 (if fmt (format fmt (string-to-number ev)) ev))
7713 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7714 (call-interactively 'org-return)
7715 (setq ndown 0)))
7716 (and down (org-table-maybe-recalculate-line))
7717 (or suppress-align (and org-table-may-need-update
7718 (org-table-align))))))
7720 (defun org-table-get-range (desc &optional tbeg col highlight)
7721 "Get a calc vector from a column, accorting to descriptor DESC.
7722 Optional arguments TBEG and COL can give the beginning of the table and
7723 the current column, to avoid unnecessary parsing.
7724 HIGHLIGHT means, just highlight the range."
7725 (if (not (equal (string-to-char desc) ?@))
7726 (setq desc (concat "@" desc)))
7727 (save-excursion
7728 (or tbeg (setq tbeg (org-table-begin)))
7729 (or col (setq col (org-table-current-column)))
7730 (let ((thisline (org-current-line))
7731 beg end c1 c2 r1 r2 rangep tmp)
7732 (unless (string-match org-table-range-regexp desc)
7733 (error "Invalid table range specifier `%s'" desc))
7734 (setq rangep (match-end 3)
7735 r1 (and (match-end 1) (match-string 1 desc))
7736 r2 (and (match-end 4) (match-string 4 desc))
7737 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
7738 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
7740 (and c1 (setq c1 (+ (string-to-number c1)
7741 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
7742 (and c2 (setq c2 (+ (string-to-number c2)
7743 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
7744 (if (equal r1 "") (setq r1 nil))
7745 (if (equal r2 "") (setq r2 nil))
7746 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
7747 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
7748 ; (setq r2 (or r2 r1) c2 (or c2 c1))
7749 (if (not r1) (setq r1 thisline))
7750 (if (not r2) (setq r2 thisline))
7751 (if (not c1) (setq c1 col))
7752 (if (not c2) (setq c2 col))
7753 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
7754 ;; just one field
7755 (progn
7756 (goto-line r1)
7757 (while (not (looking-at org-table-dataline-regexp))
7758 (beginning-of-line 2))
7759 (prog1 (org-table-get-field c1)
7760 (if highlight (org-table-highlight-rectangle (point) (point)))))
7761 ;; A range, return a vector
7762 ;; First sort the numbers to get a regular ractangle
7763 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
7764 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
7765 (goto-line r1)
7766 (while (not (looking-at org-table-dataline-regexp))
7767 (beginning-of-line 2))
7768 (org-table-goto-column c1)
7769 (setq beg (point))
7770 (goto-line r2)
7771 (while (not (looking-at org-table-dataline-regexp))
7772 (beginning-of-line 0))
7773 (org-table-goto-column c2)
7774 (setq end (point))
7775 (if highlight
7776 (org-table-highlight-rectangle
7777 beg (progn (skip-chars-forward "^|\n") (point))))
7778 ;; return string representation of calc vector
7779 (apply 'append (org-table-copy-region beg end))))))
7781 (defun org-table-get-descriptor-line (desc &optional cline bline table)
7782 "Analyze descriptor DESC and retrieve the corresponding line number.
7783 The cursor is currently in line CLINE, the table begins in line BLINE,
7784 and TABLE is a vector with line types."
7785 (if (string-match "^[0-9]+$" desc)
7786 (aref org-table-dlines (string-to-number desc))
7787 (setq cline (or cline (org-current-line))
7788 bline (or bline org-table-current-begin-line)
7789 table (or table org-table-current-line-types))
7790 (if (or
7791 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
7792 ;; 1 2 3 4 5 6
7793 (and (not (match-end 3)) (not (match-end 6)))
7794 (and (match-end 3) (match-end 6) (not (match-end 5))))
7795 (error "invalid row descriptor `%s'" desc))
7796 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
7797 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
7798 (odir (and (match-end 5) (match-string 5 desc)))
7799 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
7800 (i (- cline bline))
7801 (rel (and (match-end 6)
7802 (or (and (match-end 1) (not (match-end 3)))
7803 (match-end 5)))))
7804 (if (and hn (not hdir))
7805 (progn
7806 (setq i 0 hdir "+")
7807 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
7808 (if (and (not hn) on (not odir))
7809 (error "should never happen");;(aref org-table-dlines on) FIXME
7810 (if (and hn (> hn 0))
7811 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
7812 (if on
7813 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
7814 (+ bline i)))))
7816 (defun org-find-row-type (table i type backwards relative n)
7817 (let ((l (length table)))
7818 (while (> n 0)
7819 (while (and (setq i (+ i (if backwards -1 1)))
7820 (>= i 0) (< i l)
7821 (not (eq (aref table i) type))
7822 (if (and relative (eq (aref table i) 'hline))
7823 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
7824 t)))
7825 (setq n (1- n)))
7826 (if (or (< i 0) (>= i l))
7827 (error "Row descriptior leads outside table")
7828 i)))
7830 (defun org-rewrite-old-row-references (s)
7831 (if (string-match "&[-+0-9I]" s)
7832 (error "Formula contains old &row reference, please rewrite using @-syntax")
7835 (defun org-table-make-reference (elements keep-empty numbers lispp)
7836 "Convert list ELEMENTS to something appropriate to insert into formula.
7837 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
7838 NUMBERS indicates that everything should be converted to numbers.
7839 LISPP means to return something appropriate for a Lisp list."
7840 (if (stringp elements) ; just a single val
7841 (if lispp
7842 (prin1-to-string (if numbers (string-to-number elements) elements))
7843 (if (equal elements "") (setq elements "0"))
7844 (if numbers (number-to-string (string-to-number elements)) elements))
7845 (unless keep-empty
7846 (setq elements
7847 (delq nil
7848 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
7849 elements))))
7850 (setq elements (or elements '("0")))
7851 (if lispp
7852 (mapconcat 'prin1-to-string
7853 (if numbers (mapcar 'string-to-number elements) elements)
7854 " ")
7855 (concat "[" (mapconcat
7856 (lambda (x)
7857 (if numbers (number-to-string (string-to-number x)) x))
7858 elements
7859 ",") "]"))))
7861 (defun org-table-recalculate (&optional all noalign)
7862 "Recalculate the current table line by applying all stored formulas.
7863 With prefix arg ALL, do this for all lines in the table."
7864 (interactive "P")
7865 (or (memq this-command org-recalc-commands)
7866 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7867 (unless (org-at-table-p) (error "Not at a table"))
7868 (if (equal all '(16))
7869 (org-table-iterate)
7870 (org-table-get-specials)
7871 (let* ((eqlist (sort (org-table-get-stored-formulas)
7872 (lambda (a b) (string< (car a) (car b)))))
7873 (inhibit-redisplay (not debug-on-error))
7874 (line-re org-table-dataline-regexp)
7875 (thisline (org-current-line))
7876 (thiscol (org-table-current-column))
7877 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7878 ;; Insert constants in all formulas
7879 (setq eqlist
7880 (mapcar (lambda (x)
7881 (setcdr x (org-table-formula-substitute-names (cdr x)))
7883 eqlist))
7884 ;; Split the equation list
7885 (while (setq eq (pop eqlist))
7886 (if (<= (string-to-char (car eq)) ?9)
7887 (push eq eqlnum)
7888 (push eq eqlname)))
7889 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7890 (if all
7891 (progn
7892 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7893 (goto-char (setq beg (org-table-begin)))
7894 (if (re-search-forward org-table-calculate-mark-regexp end t)
7895 ;; This is a table with marked lines, compute selected lines
7896 (setq line-re org-table-recalculate-regexp)
7897 ;; Move forward to the first non-header line
7898 (if (and (re-search-forward org-table-dataline-regexp end t)
7899 (re-search-forward org-table-hline-regexp end t)
7900 (re-search-forward org-table-dataline-regexp end t))
7901 (setq beg (match-beginning 0))
7902 nil))) ;; just leave beg where it is
7903 (setq beg (point-at-bol)
7904 end (move-marker (make-marker) (1+ (point-at-eol)))))
7905 (goto-char beg)
7906 (and all (message "Re-applying formulas to full table..."))
7907 (while (re-search-forward line-re end t)
7908 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7909 ;; Unprotected line, recalculate
7910 (and all (message "Re-applying formulas to full table...(line %d)"
7911 (setq cnt (1+ cnt))))
7912 (setq org-last-recalc-line (org-current-line))
7913 (setq eql eqlnum)
7914 (while (setq entry (pop eql))
7915 (goto-line org-last-recalc-line)
7916 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7917 (org-table-eval-formula nil (cdr entry)
7918 'noalign 'nocst 'nostore 'noanalysis))))
7919 (goto-line thisline)
7920 (org-table-goto-column thiscol)
7921 (or noalign (and org-table-may-need-update (org-table-align))
7922 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7923 ;; Now do the named fields
7924 (while (setq eq (pop eqlname))
7925 (setq name (car eq)
7926 a (assoc name org-table-named-field-locations))
7927 (and (not a)
7928 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
7929 (setq a
7930 (list
7931 name
7932 (aref org-table-dlines
7933 (string-to-number (match-string 1 name)))
7934 (string-to-number (match-string 2 name)))))
7935 (when (and a (or all (equal (nth 1 a) thisline)))
7936 (message "Re-applying formula to field: %s" name)
7937 (goto-line (nth 1 a))
7938 (org-table-goto-column (nth 2 a))
7939 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
7940 'nostore 'noanalysis)))
7941 ;; back to initial position
7942 (message "Re-applying formulas...done")
7943 (goto-line thisline)
7944 (org-table-goto-column thiscol)
7945 (or noalign (and org-table-may-need-update (org-table-align))
7946 (and all (message "Re-applying formulas...done"))))))
7948 (defun org-table-iterate (&optional arg)
7949 "Recalculate the table until it does not change anymore."
7950 (interactive "P")
7951 (let ((imax (if arg (prefix-numeric-value arg) 10))
7952 (i 0)
7953 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
7954 thistbl)
7955 (catch 'exit
7956 (while (< i imax)
7957 (setq i (1+ i))
7958 (org-table-recalculate 'all)
7959 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
7960 (if (not (string= lasttbl thistbl))
7961 (setq lasttbl thistbl)
7962 (if (> i 1)
7963 (message "Convergence after %d iterations" i)
7964 (message "Table was already stable"))
7965 (throw 'exit t)))
7966 (error "No convergence after %d iterations" i))))
7968 (defun org-table-formula-substitute-names (f)
7969 "Replace $const with values in string F."
7970 (let ((start 0) a (f1 f))
7971 ;; First, check for column names
7972 (while (setq start (string-match org-table-column-name-regexp f start))
7973 (setq start (1+ start))
7974 (setq a (assoc (match-string 1 f) org-table-column-names))
7975 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7976 ;; Parameters and constants
7977 (setq start 0)
7978 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7979 (setq start (1+ start))
7980 (if (setq a (save-match-data
7981 (org-table-get-constant (match-string 1 f))))
7982 (setq f (replace-match (concat "(" a ")") t t f))))
7983 (if org-table-formula-debug
7984 (put-text-property 0 (length f) :orig-formula f1 f))
7987 (defun org-table-get-constant (const)
7988 "Find the value for a parameter or constant in a formula.
7989 Parameters get priority."
7990 (or (cdr (assoc const org-table-local-parameters))
7991 (cdr (assoc const org-table-formula-constants))
7992 (and (fboundp 'constants-get) (constants-get const))
7993 "#UNDEFINED_NAME"))
7995 (defvar org-table-fedit-map (make-sparse-keymap))
7996 (define-key org-table-fedit-map "\C-x\C-s" 'org-table-fedit-finish)
7997 (define-key org-table-fedit-map "\C-c\C-s" 'org-table-fedit-finish)
7998 (define-key org-table-fedit-map "\C-c\C-c" 'org-table-fedit-finish)
7999 (define-key org-table-fedit-map "\C-c\C-q" 'org-table-fedit-abort)
8000 (define-key org-table-fedit-map "\C-c?" 'org-table-show-reference)
8001 (define-key org-table-fedit-map [(meta shift up)] 'org-table-fedit-line-up)
8002 (define-key org-table-fedit-map [(meta shift down)] 'org-table-fedit-line-down)
8003 (define-key org-table-fedit-map [(shift up)] 'org-table-fedit-ref-up)
8004 (define-key org-table-fedit-map [(shift down)] 'org-table-fedit-ref-down)
8005 (define-key org-table-fedit-map [(shift left)] 'org-table-fedit-ref-left)
8006 (define-key org-table-fedit-map [(shift right)] 'org-table-fedit-ref-right)
8007 (define-key org-table-fedit-map [(meta up)] 'org-table-fedit-scroll-down)
8008 (define-key org-table-fedit-map [(meta down)] 'org-table-fedit-scroll)
8009 (define-key org-table-fedit-map [(meta tab)] 'lisp-complete-symbol)
8010 (define-key org-table-fedit-map "\M-\C-i" 'lisp-complete-symbol)
8011 (define-key org-table-fedit-map [(tab)] 'org-table-fedit-lisp-indent)
8012 (define-key org-table-fedit-map "\C-i" 'org-table-fedit-lisp-indent)
8013 (define-key org-table-fedit-map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
8014 (define-key org-table-fedit-map "\C-c}" 'org-table-fedit-toggle-coordinates)
8016 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
8017 '("Edit-Formulas"
8018 ["Finish and Install" org-table-fedit-finish t]
8019 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
8020 ["Abort" org-table-fedit-abort t]
8021 "--"
8022 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
8023 ["Complete Lisp Symbol" lisp-complete-symbol t]
8024 "--"
8025 "Shift Reference at Point"
8026 ["Up" org-table-fedit-ref-up t]
8027 ["Down" org-table-fedit-ref-down t]
8028 ["Left" org-table-fedit-ref-left t]
8029 ["Right" org-table-fedit-ref-right t]
8031 "Change Test Row for Column Formulas"
8032 ["Up" org-table-fedit-line-up t]
8033 ["Down" org-table-fedit-line-down t]
8034 "--"
8035 ["Scroll Table Window" org-table-fedit-scroll t]
8036 ["Scroll Table Window down" org-table-fedit-scroll-down t]
8037 ["Show Table Grid" org-table-fedit-toggle-coordinates
8038 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
8039 org-table-overlay-coordinates)]
8040 "--"
8041 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
8042 :style toggle :selected org-table-buffer-is-an]))
8044 (defvar org-pos)
8046 (defun org-table-edit-formulas ()
8047 "Edit the formulas of the current table in a separate buffer."
8048 (interactive)
8049 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
8050 (beginning-of-line 0))
8051 (unless (org-at-table-p) (error "Not at a table"))
8052 (org-table-get-specials)
8053 (let ((key (org-table-current-field-formula 'key 'noerror))
8054 (eql (sort (org-table-get-stored-formulas 'noerror)
8055 'org-table-formula-less-p))
8056 (pos (move-marker (make-marker) (point)))
8057 (startline 1)
8058 (wc (current-window-configuration))
8059 (titles '((column . "# Column Formulas\n")
8060 (field . "# Field Formulas\n")
8061 (named . "# Named Field Formulas\n")))
8062 entry s type title)
8063 (switch-to-buffer-other-window "*Edit Formulas*")
8064 (erase-buffer)
8065 (fundamental-mode)
8066 (org-set-local 'org-pos pos)
8067 (org-set-local 'org-window-configuration wc)
8068 (use-local-map org-table-fedit-map)
8069 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
8070 (easy-menu-add org-table-fedit-menu)
8071 (setq startline (org-current-line))
8072 (while (setq entry (pop eql))
8073 (setq type (cond
8074 ((equal (string-to-char (car entry)) ?@) 'field)
8075 ((string-match "^[0-9]" (car entry)) 'column)
8076 (t 'named)))
8077 (when (setq title (assq type titles))
8078 (or (bobp) (insert "\n"))
8079 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
8080 (setq titles (delq title titles)))
8081 (if (equal key (car entry)) (setq startline (org-current-line)))
8082 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
8083 (car entry) " = " (cdr entry) "\n"))
8084 (remove-text-properties 0 (length s) '(face nil) s)
8085 (insert s))
8086 (if (eq org-table-use-standard-references t)
8087 (org-table-fedit-toggle-ref-type))
8088 (goto-line startline)
8089 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
8091 (defun org-table-fedit-post-command ()
8092 (when (not (memq this-command '(lisp-complete-symbol)))
8093 (let ((win (selected-window)))
8094 (save-excursion
8095 (condition-case nil
8096 (org-table-show-reference)
8097 (error nil))
8098 (select-window win)))))
8100 (defun org-table-fedit-finish (&optional arg)
8101 "Parse the buffer for formula definitions and install them.
8102 With prefix ARG, apply the new formulas to the table."
8103 (interactive "P")
8104 (org-table-remove-rectangle-highlight)
8105 (if org-table-use-standard-references
8106 (progn
8107 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
8108 (setq org-table-buffer-is-an nil)))
8109 (let ((pos org-pos) eql var form)
8110 (goto-char (point-min))
8111 (while (re-search-forward
8112 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
8113 nil t)
8114 (setq var (if (match-end 2) (match-string 2) (match-string 1))
8115 form (match-string 3))
8116 (setq form (org-trim form))
8117 (when (not (equal form ""))
8118 (while (string-match "[ \t]*\n[ \t]*" form)
8119 (setq form (replace-match " " t t form)))
8120 (when (assoc var eql)
8121 (error "Double formulas for %s" var))
8122 (push (cons var form) eql)))
8123 (setq org-pos nil)
8124 (set-window-configuration org-window-configuration)
8125 (select-window (get-buffer-window (marker-buffer pos)))
8126 (goto-char pos)
8127 (unless (org-at-table-p)
8128 (error "Lost table position - cannot install formulae"))
8129 (org-table-store-formulas eql)
8130 (move-marker pos nil)
8131 (kill-buffer "*Edit Formulas*")
8132 (if arg
8133 (org-table-recalculate 'all)
8134 (message "New formulas installed - press C-u C-c C-c to apply."))))
8136 (defun org-table-fedit-abort ()
8137 "Abort editing formulas, without installing the changes."
8138 (interactive)
8139 (org-table-remove-rectangle-highlight)
8140 (let ((pos org-pos))
8141 (set-window-configuration org-window-configuration)
8142 (select-window (get-buffer-window (marker-buffer pos)))
8143 (goto-char pos)
8144 (move-marker pos nil)
8145 (message "Formula editing aborted without installing changes")))
8147 (defun org-table-fedit-lisp-indent ()
8148 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
8149 (interactive)
8150 (let ((pos (point)) beg end ind)
8151 (beginning-of-line 1)
8152 (cond
8153 ((looking-at "[ \t]")
8154 (goto-char pos)
8155 (call-interactively 'lisp-indent-line))
8156 ((looking-at "[$@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
8157 ((not (fboundp 'pp-buffer))
8158 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
8159 ((looking-at "[$@0-9a-zA-Z]+ *= *'(")
8160 (goto-char (- (match-end 0) 2))
8161 (setq beg (point))
8162 (setq ind (make-string (current-column) ?\ ))
8163 (condition-case nil (forward-sexp 1)
8164 (error
8165 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
8166 (setq end (point))
8167 (save-restriction
8168 (narrow-to-region beg end)
8169 (if (eq last-command this-command)
8170 (progn
8171 (goto-char (point-min))
8172 (setq this-command nil)
8173 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
8174 (replace-match " ")))
8175 (pp-buffer)
8176 (untabify (point-min) (point-max))
8177 (goto-char (1+ (point-min)))
8178 (while (re-search-forward "^." nil t)
8179 (beginning-of-line 1)
8180 (insert ind))
8181 (goto-char (point-max))
8182 (backward-delete-char 1)))
8183 (goto-char beg))
8184 (t nil))))
8186 (defvar org-show-positions nil)
8188 (defun org-table-show-reference (&optional local)
8189 "Show the location/value of the $ expression at point."
8190 (interactive)
8191 (org-table-remove-rectangle-highlight)
8192 (catch 'exit
8193 (let ((pos (if local (point) org-pos))
8194 (face2 'highlight)
8195 (org-inhibit-highlight-removal t)
8196 (win (selected-window))
8197 (org-show-positions nil)
8198 var name e what match dest)
8199 (if local (org-table-get-specials))
8200 (setq what (cond
8201 ((or (org-at-regexp-p org-table-range-regexp2)
8202 (org-at-regexp-p org-table-translate-regexp)
8203 (org-at-regexp-p org-table-range-regexp))
8204 (setq match
8205 (save-match-data
8206 (org-table-convert-refs-to-rc (match-string 0))))
8207 'range)
8208 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
8209 ((org-at-regexp-p "\\$[0-9]+") 'column)
8210 ((not local) nil)
8211 (t (error "No reference at point")))
8212 match (and what (or match (match-string 0))))
8213 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
8214 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
8215 'secondary-selection))
8216 (org-add-hook 'before-change-functions
8217 'org-table-remove-rectangle-highlight)
8218 (if (eq what 'name) (setq var (substring match 1)))
8219 (when (eq what 'range)
8220 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
8221 (setq match (org-table-formula-substitute-names match)))
8222 (unless local
8223 (save-excursion
8224 (end-of-line 1)
8225 (re-search-backward "^\\S-" nil t)
8226 (beginning-of-line 1)
8227 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
8228 (setq dest
8229 (save-match-data
8230 (org-table-convert-refs-to-rc (match-string 1))))
8231 (org-table-add-rectangle-overlay
8232 (match-beginning 1) (match-end 1) face2))))
8233 (if (and (markerp pos) (marker-buffer pos))
8234 (if (get-buffer-window (marker-buffer pos))
8235 (select-window (get-buffer-window (marker-buffer pos)))
8236 (switch-to-buffer-other-window (get-buffer-window
8237 (marker-buffer pos)))))
8238 (goto-char pos)
8239 (org-table-force-dataline)
8240 (when dest
8241 (setq name (substring dest 1))
8242 (cond
8243 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
8244 (setq e (assoc name org-table-named-field-locations))
8245 (goto-line (nth 1 e))
8246 (org-table-goto-column (nth 2 e)))
8247 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
8248 (let ((l (string-to-number (match-string 1 dest)))
8249 (c (string-to-number (match-string 2 dest))))
8250 (goto-line (aref org-table-dlines l))
8251 (org-table-goto-column c)))
8252 (t (org-table-goto-column (string-to-number name))))
8253 (move-marker pos (point))
8254 (org-table-highlight-rectangle nil nil face2))
8255 (cond
8256 ((equal dest match))
8257 ((not match))
8258 ((eq what 'range)
8259 (condition-case nil
8260 (save-excursion
8261 (org-table-get-range match nil nil 'highlight))
8262 (error nil)))
8263 ((setq e (assoc var org-table-named-field-locations))
8264 (goto-line (nth 1 e))
8265 (org-table-goto-column (nth 2 e))
8266 (org-table-highlight-rectangle (point) (point))
8267 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
8268 ((setq e (assoc var org-table-column-names))
8269 (org-table-goto-column (string-to-number (cdr e)))
8270 (org-table-highlight-rectangle (point) (point))
8271 (goto-char (org-table-begin))
8272 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
8273 (org-table-end) t)
8274 (progn
8275 (goto-char (match-beginning 1))
8276 (org-table-highlight-rectangle)
8277 (message "Named column (column %s)" (cdr e)))
8278 (error "Column name not found")))
8279 ((eq what 'column)
8280 ;; column number
8281 (org-table-goto-column (string-to-number (substring match 1)))
8282 (org-table-highlight-rectangle (point) (point))
8283 (message "Column %s" (substring match 1)))
8284 ((setq e (assoc var org-table-local-parameters))
8285 (goto-char (org-table-begin))
8286 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
8287 (progn
8288 (goto-char (match-beginning 1))
8289 (org-table-highlight-rectangle)
8290 (message "Local parameter."))
8291 (error "Parameter not found")))
8293 (cond
8294 ((not var) (error "No reference at point"))
8295 ((setq e (assoc var org-table-formula-constants))
8296 (message "Constant: $%s=%s in `org-table-formula-constants'."
8297 var (cdr e)))
8298 ((setq e (and (fboundp 'constants-get) (constants-get var)))
8299 (message "Constant: $%s=%s, from `constants.el'%s."
8300 var e (format " (%s units)" constants-unit-system)))
8301 (t (error "Undefined name $%s" var)))))
8302 (goto-char pos)
8303 (when (and org-show-positions
8304 (not (memq this-command '(org-table-fedit-scroll
8305 org-table-fedit-scroll-down))))
8306 (push pos org-show-positions)
8307 (push org-table-current-begin-pos org-show-positions)
8308 (let ((min (apply 'min org-show-positions))
8309 (max (apply 'max org-show-positions)))
8310 (goto-char min) (recenter 0)
8311 (goto-char max)
8312 (or (pos-visible-in-window-p max) (recenter -1))))
8313 (select-window win))))
8315 (defun org-table-force-dataline ()
8316 "Make sure the cursor is in a dataline in a table."
8317 (unless (save-excursion
8318 (beginning-of-line 1)
8319 (looking-at org-table-dataline-regexp))
8320 (let* ((re org-table-dataline-regexp)
8321 (p1 (save-excursion (re-search-forward re nil 'move)))
8322 (p2 (save-excursion (re-search-backward re nil 'move))))
8323 (cond ((and p1 p2)
8324 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
8325 p1 p2)))
8326 ((or p1 p2) (goto-char (or p1 p2)))
8327 (t (error "No table dataline around here"))))))
8329 (defun org-table-fedit-line-up ()
8330 "Move cursor one line up in the window showing the table."
8331 (interactive)
8332 (org-table-fedit-move 'previous-line))
8334 (defun org-table-fedit-line-down ()
8335 "Move cursor one line down in the window showing the table."
8336 (interactive)
8337 (org-table-fedit-move 'next-line))
8339 (defun org-table-fedit-move (command)
8340 "Move the cursor in the window shoinw the table.
8341 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
8342 (let ((org-table-allow-automatic-line-recalculation nil)
8343 (pos org-pos) (win (selected-window)) p)
8344 (select-window (get-buffer-window (marker-buffer org-pos)))
8345 (setq p (point))
8346 (call-interactively command)
8347 (while (and (org-at-table-p)
8348 (org-at-table-hline-p))
8349 (call-interactively command))
8350 (or (org-at-table-p) (goto-char p))
8351 (move-marker pos (point))
8352 (select-window win)))
8354 (defun org-table-fedit-scroll (N)
8355 (interactive "p")
8356 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
8357 (scroll-other-window N)))
8359 (defun org-table-fedit-scroll-down (N)
8360 (interactive "p")
8361 (org-table-fedit-scroll (- N)))
8363 (defvar org-table-rectangle-overlays nil)
8365 (defun org-table-add-rectangle-overlay (beg end &optional face)
8366 "Add a new overlay."
8367 (let ((ov (org-make-overlay beg end)))
8368 (org-overlay-put ov 'face (or face 'secondary-selection))
8369 (push ov org-table-rectangle-overlays)))
8371 (defun org-table-highlight-rectangle (&optional beg end face)
8372 "Highlight rectangular region in a table."
8373 (setq beg (or beg (point)) end (or end (point)))
8374 (let ((b (min beg end))
8375 (e (max beg end))
8376 l1 c1 l2 c2 tmp)
8377 (and (boundp 'org-show-positions)
8378 (setq org-show-positions (cons b (cons e org-show-positions))))
8379 (goto-char (min beg end))
8380 (setq l1 (org-current-line)
8381 c1 (org-table-current-column))
8382 (goto-char (max beg end))
8383 (setq l2 (org-current-line)
8384 c2 (org-table-current-column))
8385 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
8386 (goto-line l1)
8387 (beginning-of-line 1)
8388 (loop for line from l1 to l2 do
8389 (when (looking-at org-table-dataline-regexp)
8390 (org-table-goto-column c1)
8391 (skip-chars-backward "^|\n") (setq beg (point))
8392 (org-table-goto-column c2)
8393 (skip-chars-forward "^|\n") (setq end (point))
8394 (org-table-add-rectangle-overlay beg end face))
8395 (beginning-of-line 2))
8396 (goto-char b))
8397 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
8399 (defun org-table-remove-rectangle-highlight (&rest ignore)
8400 "Remove the rectangle overlays."
8401 (unless org-inhibit-highlight-removal
8402 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
8403 (mapc 'org-delete-overlay org-table-rectangle-overlays)
8404 (setq org-table-rectangle-overlays nil)))
8406 (defvar org-table-coordinate-overlays nil
8407 "Collects the cooordinate grid overlays, so that they can be removed.")
8408 (make-variable-buffer-local 'org-table-coordinate-overlays)
8410 (defun org-table-overlay-coordinates ()
8411 "Add overlays to the table at point, to show row/column coordinates."
8412 (interactive)
8413 (mapc 'org-delete-overlay org-table-coordinate-overlays)
8414 (setq org-table-coordinate-overlays nil)
8415 (save-excursion
8416 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
8417 (goto-char (org-table-begin))
8418 (while (org-at-table-p)
8419 (setq eol (point-at-eol))
8420 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
8421 (push ov org-table-coordinate-overlays)
8422 (setq hline (looking-at org-table-hline-regexp))
8423 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
8424 (format "%4d" (setq id (1+ id)))))
8425 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
8426 (when hline
8427 (setq ic 0)
8428 (while (re-search-forward "[+|]\\(-+\\)" eol t)
8429 (setq beg (1+ (match-beginning 0))
8430 ic (1+ ic)
8431 s1 (concat "$" (int-to-string ic))
8432 s2 (org-number-to-letters ic)
8433 str (if org-table-use-standard-references s2 s1))
8434 (setq ov (org-make-overlay beg (+ beg (length str))))
8435 (push ov org-table-coordinate-overlays)
8436 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
8437 (beginning-of-line 2)))))
8439 (defun org-table-toggle-coordinate-overlays ()
8440 "Toggle the display of Row/Column numbers in tables."
8441 (interactive)
8442 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
8443 (message "Row/Column number display turned %s"
8444 (if org-table-overlay-coordinates "on" "off"))
8445 (if (and (org-at-table-p) org-table-overlay-coordinates)
8446 (org-table-align))
8447 (unless org-table-overlay-coordinates
8448 (mapc 'org-delete-overlay org-table-coordinate-overlays)
8449 (setq org-table-coordinate-overlays nil)))
8451 (defun org-table-toggle-formula-debugger ()
8452 "Toggle the formula debugger in tables."
8453 (interactive)
8454 (setq org-table-formula-debug (not org-table-formula-debug))
8455 (message "Formula debugging has been turned %s"
8456 (if org-table-formula-debug "on" "off")))
8458 ;;; The orgtbl minor mode
8460 ;; Define a minor mode which can be used in other modes in order to
8461 ;; integrate the org-mode table editor.
8463 ;; This is really a hack, because the org-mode table editor uses several
8464 ;; keys which normally belong to the major mode, for example the TAB and
8465 ;; RET keys. Here is how it works: The minor mode defines all the keys
8466 ;; necessary to operate the table editor, but wraps the commands into a
8467 ;; function which tests if the cursor is currently inside a table. If that
8468 ;; is the case, the table editor command is executed. However, when any of
8469 ;; those keys is used outside a table, the function uses `key-binding' to
8470 ;; look up if the key has an associated command in another currently active
8471 ;; keymap (minor modes, major mode, global), and executes that command.
8472 ;; There might be problems if any of the keys used by the table editor is
8473 ;; otherwise used as a prefix key.
8475 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8476 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8477 ;; addresses this by checking explicitly for both bindings.
8479 ;; The optimized version (see variable `orgtbl-optimized') takes over
8480 ;; all keys which are bound to `self-insert-command' in the *global map*.
8481 ;; Some modes bind other commands to simple characters, for example
8482 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
8483 ;; active, this binding is ignored inside tables and replaced with a
8484 ;; modified self-insert.
8486 (defvar orgtbl-mode nil
8487 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
8488 table editor in arbitrary modes.")
8489 (make-variable-buffer-local 'orgtbl-mode)
8491 (defvar orgtbl-mode-map (make-keymap)
8492 "Keymap for `orgtbl-mode'.")
8494 ;;;###autoload
8495 (defun turn-on-orgtbl ()
8496 "Unconditionally turn on `orgtbl-mode'."
8497 (orgtbl-mode 1))
8499 (defvar org-old-auto-fill-inhibit-regexp nil
8500 "Local variable used by `orgtbl-mode'")
8502 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
8503 "Matches a line belonging to an orgtbl.")
8505 (defconst orgtbl-extra-font-lock-keywords
8506 (list (list (concat "^" orgtbl-line-start-regexp ".*")
8507 0 (quote 'org-table) 'prepend))
8508 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
8510 ;;;###autoload
8511 (defun orgtbl-mode (&optional arg)
8512 "The `org-mode' table editor as a minor mode for use in other modes."
8513 (interactive)
8514 (if (org-mode-p)
8515 ;; Exit without error, in case some hook functions calls this
8516 ;; by accident in org-mode.
8517 (message "Orgtbl-mode is not useful in org-mode, command ignored")
8518 (setq orgtbl-mode
8519 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
8520 (if orgtbl-mode
8521 (progn
8522 (and (orgtbl-setup) (defun orgtbl-setup () nil))
8523 ;; Make sure we are first in minor-mode-map-alist
8524 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
8525 (and c (setq minor-mode-map-alist
8526 (cons c (delq c minor-mode-map-alist)))))
8527 (org-set-local (quote org-table-may-need-update) t)
8528 (org-add-hook 'before-change-functions 'org-before-change-function
8529 nil 'local)
8530 (org-set-local 'org-old-auto-fill-inhibit-regexp
8531 auto-fill-inhibit-regexp)
8532 (org-set-local 'auto-fill-inhibit-regexp
8533 (if auto-fill-inhibit-regexp
8534 (concat orgtbl-line-start-regexp "\\|"
8535 auto-fill-inhibit-regexp)
8536 orgtbl-line-start-regexp))
8537 (org-add-to-invisibility-spec '(org-cwidth))
8538 (when (fboundp 'font-lock-add-keywords)
8539 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
8540 (org-restart-font-lock))
8541 (easy-menu-add orgtbl-mode-menu)
8542 (run-hooks 'orgtbl-mode-hook))
8543 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
8544 (org-cleanup-narrow-column-properties)
8545 (org-remove-from-invisibility-spec '(org-cwidth))
8546 (remove-hook 'before-change-functions 'org-before-change-function t)
8547 (when (fboundp 'font-lock-remove-keywords)
8548 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
8549 (org-restart-font-lock))
8550 (easy-menu-remove orgtbl-mode-menu)
8551 (force-mode-line-update 'all))))
8553 (defun org-cleanup-narrow-column-properties ()
8554 "Remove all properties related to narrow-column invisibility."
8555 (let ((s 1))
8556 (while (setq s (text-property-any s (point-max)
8557 'display org-narrow-column-arrow))
8558 (remove-text-properties s (1+ s) '(display t)))
8559 (setq s 1)
8560 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
8561 (remove-text-properties s (1+ s) '(org-cwidth t)))
8562 (setq s 1)
8563 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
8564 (remove-text-properties s (1+ s) '(invisible t)))))
8566 ;; Install it as a minor mode.
8567 (put 'orgtbl-mode :included t)
8568 (put 'orgtbl-mode :menu-tag "Org Table Mode")
8569 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
8571 (defun orgtbl-make-binding (fun n &rest keys)
8572 "Create a function for binding in the table minor mode.
8573 FUN is the command to call inside a table. N is used to create a unique
8574 command name. KEYS are keys that should be checked in for a command
8575 to execute outside of tables."
8576 (eval
8577 (list 'defun
8578 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
8579 '(arg)
8580 (concat "In tables, run `" (symbol-name fun) "'.\n"
8581 "Outside of tables, run the binding of `"
8582 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8583 "'.")
8584 '(interactive "p")
8585 (list 'if
8586 '(org-at-table-p)
8587 (list 'call-interactively (list 'quote fun))
8588 (list 'let '(orgtbl-mode)
8589 (list 'call-interactively
8590 (append '(or)
8591 (mapcar (lambda (k)
8592 (list 'key-binding k))
8593 keys)
8594 '('orgtbl-error))))))))
8596 (defun orgtbl-error ()
8597 "Error when there is no default binding for a table key."
8598 (interactive)
8599 (error "This key is has no function outside tables"))
8601 (defun orgtbl-setup ()
8602 "Setup orgtbl keymaps."
8603 (let ((nfunc 0)
8604 (bindings
8605 (list
8606 '([(meta shift left)] org-table-delete-column)
8607 '([(meta left)] org-table-move-column-left)
8608 '([(meta right)] org-table-move-column-right)
8609 '([(meta shift right)] org-table-insert-column)
8610 '([(meta shift up)] org-table-kill-row)
8611 '([(meta shift down)] org-table-insert-row)
8612 '([(meta up)] org-table-move-row-up)
8613 '([(meta down)] org-table-move-row-down)
8614 '("\C-c\C-w" org-table-cut-region)
8615 '("\C-c\M-w" org-table-copy-region)
8616 '("\C-c\C-y" org-table-paste-rectangle)
8617 '("\C-c-" org-table-insert-hline)
8618 '("\C-c}" org-table-toggle-coordinate-overlays)
8619 '("\C-c{" org-table-toggle-formula-debugger)
8620 '("\C-m" org-table-next-row)
8621 (list (org-key 'S-return) 'org-table-copy-down)
8622 '("\C-c\C-q" org-table-wrap-region)
8623 '("\C-c?" org-table-field-info)
8624 '("\C-c " org-table-blank-field)
8625 '("\C-c+" org-table-sum)
8626 '("\C-c=" org-table-eval-formula)
8627 '("\C-c'" org-table-edit-formulas)
8628 '("\C-c`" org-table-edit-field)
8629 '("\C-c*" org-table-recalculate)
8630 '("\C-c|" org-table-create-or-convert-from-region)
8631 '("\C-c^" org-table-sort-lines)
8632 '([(control ?#)] org-table-rotate-recalc-marks)))
8633 elt key fun cmd)
8634 (while (setq elt (pop bindings))
8635 (setq nfunc (1+ nfunc))
8636 (setq key (car elt)
8637 fun (nth 1 elt)
8638 cmd (orgtbl-make-binding fun nfunc key))
8639 (define-key orgtbl-mode-map key cmd))
8641 ;; Special treatment needed for TAB and RET
8642 (define-key orgtbl-mode-map [(return)]
8643 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
8644 (define-key orgtbl-mode-map "\C-m"
8645 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
8647 (define-key orgtbl-mode-map [(tab)]
8648 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
8649 (define-key orgtbl-mode-map "\C-i"
8650 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
8652 (define-key orgtbl-mode-map [(shift tab)]
8653 (orgtbl-make-binding 'org-table-previous-field 104
8654 [(shift tab)] [(tab)] "\C-i"))
8656 (define-key orgtbl-mode-map "\M-\C-m"
8657 (orgtbl-make-binding 'org-table-wrap-region 105
8658 "\M-\C-m" [(meta return)]))
8659 (define-key orgtbl-mode-map [(meta return)]
8660 (orgtbl-make-binding 'org-table-wrap-region 106
8661 [(meta return)] "\M-\C-m"))
8663 (define-key orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
8664 (when orgtbl-optimized
8665 ;; If the user wants maximum table support, we need to hijack
8666 ;; some standard editing functions
8667 (org-remap orgtbl-mode-map
8668 'self-insert-command 'orgtbl-self-insert-command
8669 'delete-char 'org-delete-char
8670 'delete-backward-char 'org-delete-backward-char)
8671 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8672 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8673 '("OrgTbl"
8674 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8675 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8676 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8677 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8678 "--"
8679 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8680 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
8681 ["Copy Field from Above"
8682 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8683 "--"
8684 ("Column"
8685 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8686 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8687 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8688 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8689 ("Row"
8690 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8691 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8692 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8693 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8694 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
8695 "--"
8696 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8697 ("Rectangle"
8698 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
8699 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
8700 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
8701 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
8702 "--"
8703 ("Radio tables"
8704 ["Insert table template" orgtbl-insert-radio-table
8705 (assq major-mode orgtbl-radio-table-templates)]
8706 ["Comment/uncomment table" orgtbl-toggle-comment t])
8707 "--"
8708 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8709 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8710 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8711 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8712 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8713 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
8714 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8715 ["Sum Column/Rectangle" org-table-sum
8716 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8717 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8718 ["Debug Formulas"
8719 org-table-toggle-formula-debugger :active (org-at-table-p)
8720 :keys "C-c {"
8721 :style toggle :selected org-table-formula-debug]
8722 ["Show Col/Row Numbers"
8723 org-table-toggle-coordinate-overlays :active (org-at-table-p)
8724 :keys "C-c }"
8725 :style toggle :selected org-table-overlay-coordinates]
8729 (defun orgtbl-ctrl-c-ctrl-c (arg)
8730 "If the cursor is inside a table, realign the table.
8731 It it is a table to be sent away to a receiver, do it.
8732 With prefix arg, also recompute table."
8733 (interactive "P")
8734 (let ((pos (point)) action)
8735 (save-excursion
8736 (beginning-of-line 1)
8737 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
8738 ((looking-at "[ \t]*|") pos)
8739 ((looking-at "#\\+TBLFM:") 'recalc))))
8740 (cond
8741 ((integerp action)
8742 (goto-char action)
8743 (org-table-maybe-eval-formula)
8744 (if arg
8745 (call-interactively 'org-table-recalculate)
8746 (org-table-maybe-recalculate-line))
8747 (call-interactively 'org-table-align)
8748 (orgtbl-send-table 'maybe))
8749 ((eq action 'recalc)
8750 (save-excursion
8751 (beginning-of-line 1)
8752 (skip-chars-backward " \r\n\t")
8753 (if (org-at-table-p)
8754 (org-call-with-arg 'org-table-recalculate t))))
8755 (t (let (orgtbl-mode)
8756 (call-interactively (key-binding "\C-c\C-c")))))))
8758 (defun orgtbl-tab (arg)
8759 "Justification and field motion for `orgtbl-mode'."
8760 (interactive "P")
8761 (if arg (org-table-edit-field t)
8762 (org-table-justify-field-maybe)
8763 (org-table-next-field)))
8765 (defun orgtbl-ret ()
8766 "Justification and field motion for `orgtbl-mode'."
8767 (interactive)
8768 (org-table-justify-field-maybe)
8769 (org-table-next-row))
8771 (defun orgtbl-self-insert-command (N)
8772 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8773 If the cursor is in a table looking at whitespace, the whitespace is
8774 overwritten, and the table is not marked as requiring realignment."
8775 (interactive "p")
8776 (if (and (org-at-table-p)
8778 (and org-table-auto-blank-field
8779 (member last-command
8780 '(orgtbl-hijacker-command-100
8781 orgtbl-hijacker-command-101
8782 orgtbl-hijacker-command-102
8783 orgtbl-hijacker-command-103
8784 orgtbl-hijacker-command-104
8785 orgtbl-hijacker-command-105))
8786 (org-table-blank-field))
8788 (eq N 1)
8789 (looking-at "[^|\n]* +|"))
8790 (let (org-table-may-need-update)
8791 (goto-char (1- (match-end 0)))
8792 (delete-backward-char 1)
8793 (goto-char (match-beginning 0))
8794 (self-insert-command N))
8795 (setq org-table-may-need-update t)
8796 (let (orgtbl-mode)
8797 (call-interactively (key-binding (vector last-input-event))))))
8799 (defun org-force-self-insert (N)
8800 "Needed to enforce self-insert under remapping."
8801 (interactive "p")
8802 (self-insert-command N))
8804 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
8805 "Regula expression matching exponentials as produced by calc.")
8807 (defvar org-table-clean-did-remove-column-1 nil)
8809 (defun orgtbl-send-table (&optional maybe)
8810 "Send a tranformed version of this table to the receiver position.
8811 With argument MAYBE, fail quietly if no transformation is defined for
8812 this table."
8813 (interactive)
8814 (catch 'exit
8815 (unless (org-at-table-p) (error "Not at a table"))
8816 ;; when non-interactive, we assume align has just happened.
8817 (when (interactive-p) (org-table-align))
8818 (save-excursion
8819 (goto-char (org-table-begin))
8820 (beginning-of-line 0)
8821 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
8822 (if maybe
8823 (throw 'exit nil)
8824 (error "Don't know how to transform this table."))))
8825 (let* ((name (match-string 1))
8827 (transform (intern (match-string 2)))
8828 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
8829 (skip (plist-get params :skip))
8830 (skipcols (plist-get params :skipcols))
8831 (txt (buffer-substring-no-properties
8832 (org-table-begin) (org-table-end)))
8833 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
8834 (lines (org-table-clean-before-export lines))
8835 (i0 (if org-table-clean-did-remove-column-1 2 1))
8836 (table (mapcar
8837 (lambda (x)
8838 (if (string-match org-table-hline-regexp x)
8839 'hline
8840 (org-remove-by-index
8841 (org-split-string (org-trim x) "\\s-*|\\s-*")
8842 skipcols i0)))
8843 lines))
8844 (fun (if (= i0 2) 'cdr 'identity))
8845 (org-table-last-alignment
8846 (org-remove-by-index (funcall fun org-table-last-alignment)
8847 skipcols i0))
8848 (org-table-last-column-widths
8849 (org-remove-by-index (funcall fun org-table-last-column-widths)
8850 skipcols i0)))
8852 (unless (fboundp transform)
8853 (error "No such transformation function %s" transform))
8854 (setq txt (funcall transform table params))
8855 ;; Find the insertion place
8856 (save-excursion
8857 (goto-char (point-min))
8858 (unless (re-search-forward
8859 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
8860 (error "Don't know where to insert translated table"))
8861 (goto-char (match-beginning 0))
8862 (beginning-of-line 2)
8863 (setq beg (point))
8864 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
8865 (error "Cannot find end of insertion region"))
8866 (beginning-of-line 1)
8867 (delete-region beg (point))
8868 (goto-char beg)
8869 (insert txt "\n"))
8870 (message "Table converted and installed at receiver location"))))
8872 (defun org-remove-by-index (list indices &optional i0)
8873 "Remove the elements in LIST with indices in INDICES.
8874 First element has index 0, or I0 if given."
8875 (if (not indices)
8876 list
8877 (if (integerp indices) (setq indices (list indices)))
8878 (setq i0 (1- (or i0 0)))
8879 (delq :rm (mapcar (lambda (x)
8880 (setq i0 (1+ i0))
8881 (if (memq i0 indices) :rm x))
8882 list))))
8884 (defun orgtbl-toggle-comment ()
8885 "Comment or uncomment the orgtbl at point."
8886 (interactive)
8887 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
8888 (re2 (concat "^" orgtbl-line-start-regexp))
8889 (commented (save-excursion (beginning-of-line 1)
8890 (cond ((looking-at re1) t)
8891 ((looking-at re2) nil)
8892 (t (error "Not at an org table")))))
8893 (re (if commented re1 re2))
8894 beg end)
8895 (save-excursion
8896 (beginning-of-line 1)
8897 (while (looking-at re) (beginning-of-line 0))
8898 (beginning-of-line 2)
8899 (setq beg (point))
8900 (while (looking-at re) (beginning-of-line 2))
8901 (setq end (point)))
8902 (comment-region beg end (if commented '(4) nil))))
8904 (defun orgtbl-insert-radio-table ()
8905 "Insert a radio table template appropriate for this major mode."
8906 (interactive)
8907 (let* ((e (assq major-mode orgtbl-radio-table-templates))
8908 (txt (nth 1 e))
8909 name pos)
8910 (unless e (error "No radio table setup defined for %s" major-mode))
8911 (setq name (read-string "Table name: "))
8912 (while (string-match "%n" txt)
8913 (setq txt (replace-match name t t txt)))
8914 (or (bolp) (insert "\n"))
8915 (setq pos (point))
8916 (insert txt)
8917 (goto-char pos)))
8919 (defun org-get-param (params header i sym &optional hsym)
8920 "Get parameter value for symbol SYM.
8921 If this is a header line, actually get the value for the symbol with an
8922 additional \"h\" inserted after the colon.
8923 If the value is a protperty list, get the element for the current column.
8924 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
8925 (let ((val (plist-get params sym)))
8926 (and hsym header (setq val (or (plist-get params hsym) val)))
8927 (if (consp val) (plist-get val i) val)))
8929 (defun orgtbl-to-generic (table params)
8930 "Convert the orgtbl-mode TABLE to some other format.
8931 This generic routine can be used for many standard cases.
8932 TABLE is a list, each entry either the symbol `hline' for a horizontal
8933 separator line, or a list of fields for that line.
8934 PARAMS is a property list of parameters that can influence the conversion.
8935 For the generic converter, some parameters are obligatory: You need to
8936 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
8937 :splice, you must have :tstart and :tend.
8939 Valid parameters are
8941 :tstart String to start the table. Ignored when :splice is t.
8942 :tend String to end the table. Ignored when :splice is t.
8944 :splice When set to t, return only table body lines, don't wrap
8945 them into :tstart and :tend. Default is nil.
8947 :hline String to be inserted on horizontal separation lines.
8948 May be nil to ignore hlines.
8950 :lstart String to start a new table line.
8951 :lend String to end a table line
8952 :sep Separator between two fields
8953 :lfmt Format for entire line, with enough %s to capture all fields.
8954 If this is present, :lstart, :lend, and :sep are ignored.
8955 :fmt A format to be used to wrap the field, should contain
8956 %s for the original field value. For example, to wrap
8957 everything in dollars, you could use :fmt \"$%s$\".
8958 This may also be a property list with column numbers and
8959 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
8961 :hlstart :hlend :hlsep :hlfmt :hfmt
8962 Same as above, specific for the header lines in the table.
8963 All lines before the first hline are treated as header.
8964 If any of these is not present, the data line value is used.
8966 :efmt Use this format to print numbers with exponentials.
8967 The format should have %s twice for inserting mantissa
8968 and exponent, for example \"%s\\\\times10^{%s}\". This
8969 may also be a property list with column numbers and
8970 formats. :fmt will still be applied after :efmt.
8972 In addition to this, the parameters :skip and :skipcols are always handled
8973 directly by `orgtbl-send-table'. See manual."
8974 (interactive)
8975 (let* ((p params)
8976 (splicep (plist-get p :splice))
8977 (hline (plist-get p :hline))
8978 rtn line i fm efm lfmt h)
8980 ;; Do we have a header?
8981 (if (and (not splicep) (listp (car table)) (memq 'hline table))
8982 (setq h t))
8984 ;; Put header
8985 (unless splicep
8986 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
8988 ;; Now loop over all lines
8989 (while (setq line (pop table))
8990 (if (eq line 'hline)
8991 ;; A horizontal separator line
8992 (progn (if hline (push hline rtn))
8993 (setq h nil)) ; no longer in header
8994 ;; A normal line. Convert the fields, push line onto the result list
8995 (setq i 0)
8996 (setq line
8997 (mapcar
8998 (lambda (f)
8999 (setq i (1+ i)
9000 fm (org-get-param p h i :fmt :hfmt)
9001 efm (org-get-param p h i :efmt))
9002 (if (and efm (string-match orgtbl-exp-regexp f))
9003 (setq f (format
9004 efm (match-string 1 f) (match-string 2 f))))
9005 (if fm (setq f (format fm f)))
9007 line))
9008 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
9009 (push (apply 'format lfmt line) rtn)
9010 (push (concat
9011 (org-get-param p h i :lstart :hlstart)
9012 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
9013 (org-get-param p h i :lend :hlend))
9014 rtn))))
9016 (unless splicep
9017 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
9019 (mapconcat 'identity (nreverse rtn) "\n")))
9021 (defun orgtbl-to-latex (table params)
9022 "Convert the orgtbl-mode TABLE to LaTeX.
9023 TABLE is a list, each entry either the symbol `hline' for a horizontal
9024 separator line, or a list of fields for that line.
9025 PARAMS is a property list of parameters that can influence the conversion.
9026 Supports all parameters from `orgtbl-to-generic'. Most important for
9027 LaTeX are:
9029 :splice When set to t, return only table body lines, don't wrap
9030 them into a tabular environment. Default is nil.
9032 :fmt A format to be used to wrap the field, should contain %s for the
9033 original field value. For example, to wrap everything in dollars,
9034 use :fmt \"$%s$\". This may also be a property list with column
9035 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
9037 :efmt Format for transforming numbers with exponentials. The format
9038 should have %s twice for inserting mantissa and exponent, for
9039 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
9040 This may also be a property list with column numbers and formats.
9042 The general parameters :skip and :skipcols have already been applied when
9043 this function is called."
9044 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
9045 org-table-last-alignment ""))
9046 (params2
9047 (list
9048 :tstart (concat "\\begin{tabular}{" alignment "}")
9049 :tend "\\end{tabular}"
9050 :lstart "" :lend " \\\\" :sep " & "
9051 :efmt "%s\\,(%s)" :hline "\\hline")))
9052 (orgtbl-to-generic table (org-combine-plists params2 params))))
9054 (defun orgtbl-to-html (table params)
9055 "Convert the orgtbl-mode TABLE to LaTeX.
9056 TABLE is a list, each entry either the symbol `hline' for a horizontal
9057 separator line, or a list of fields for that line.
9058 PARAMS is a property list of parameters that can influence the conversion.
9059 Currently this function recognizes the following parameters:
9061 :splice When set to t, return only table body lines, don't wrap
9062 them into a <table> environment. Default is nil.
9064 The general parameters :skip and :skipcols have already been applied when
9065 this function is called. The function does *not* use `orgtbl-to-generic',
9066 so you cannot specify parameters for it."
9067 (let* ((splicep (plist-get params :splice))
9068 html)
9069 ;; Just call the formatter we already have
9070 ;; We need to make text lines for it, so put the fields back together.
9071 (setq html (org-format-org-table-html
9072 (mapcar
9073 (lambda (x)
9074 (if (eq x 'hline)
9075 "|----+----|"
9076 (concat "| " (mapconcat 'identity x " | ") " |")))
9077 table)
9078 splicep))
9079 (if (string-match "\n+\\'" html)
9080 (setq html (replace-match "" t t html)))
9081 html))
9083 (defun orgtbl-to-texinfo (table params)
9084 "Convert the orgtbl-mode TABLE to TeXInfo.
9085 TABLE is a list, each entry either the symbol `hline' for a horizontal
9086 separator line, or a list of fields for that line.
9087 PARAMS is a property list of parameters that can influence the conversion.
9088 Supports all parameters from `orgtbl-to-generic'. Most important for
9089 TeXInfo are:
9091 :splice nil/t When set to t, return only table body lines, don't wrap
9092 them into a multitable environment. Default is nil.
9094 :fmt fmt A format to be used to wrap the field, should contain
9095 %s for the original field value. For example, to wrap
9096 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
9097 This may also be a property list with column numbers and
9098 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
9100 :cf \"f1 f2..\" The column fractions for the table. Bye default these
9101 are computed automatically from the width of the columns
9102 under org-mode.
9104 The general parameters :skip and :skipcols have already been applied when
9105 this function is called."
9106 (let* ((total (float (apply '+ org-table-last-column-widths)))
9107 (colfrac (or (plist-get params :cf)
9108 (mapconcat
9109 (lambda (x) (format "%.3f" (/ (float x) total)))
9110 org-table-last-column-widths " ")))
9111 (params2
9112 (list
9113 :tstart (concat "@multitable @columnfractions " colfrac)
9114 :tend "@end multitable"
9115 :lstart "@item " :lend "" :sep " @tab "
9116 :hlstart "@headitem ")))
9117 (orgtbl-to-generic table (org-combine-plists params2 params))))
9119 ;;;; Link Stuff
9121 ;;; Link abbreviations
9123 (defun org-link-expand-abbrev (link)
9124 "Apply replacements as defined in `org-link-abbrev-alist."
9125 (if (string-match "^\\([a-zA-Z]+\\)\\(::?\\(.*\\)\\)?$" link)
9126 (let* ((key (match-string 1 link))
9127 (as (or (assoc key org-link-abbrev-alist-local)
9128 (assoc key org-link-abbrev-alist)))
9129 (tag (and (match-end 2) (match-string 3 link)))
9130 rpl)
9131 (if (not as)
9132 link
9133 (setq rpl (cdr as))
9134 (cond
9135 ((symbolp rpl) (funcall rpl tag))
9136 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9137 (t (concat rpl tag)))))
9138 link))
9140 ;;; Storing and inserting links
9142 (defvar org-insert-link-history nil
9143 "Minibuffer history for links inserted with `org-insert-link'.")
9145 (defvar org-stored-links nil
9146 "Contains the links stored with `org-store-link'.")
9148 (defvar org-store-link-plist nil
9149 "Plist with info about the most recently link created with `org-store-link'.")
9151 ;;;###autoload
9152 (defun org-store-link (arg)
9153 "\\<org-mode-map>Store an org-link to the current location.
9154 This link can later be inserted into an org-buffer with
9155 \\[org-insert-link].
9156 For some link types, a prefix arg is interpreted:
9157 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9158 For file links, arg negates `org-context-in-file-links'."
9159 (interactive "P")
9160 (setq org-store-link-plist nil) ; reset
9161 (let (link cpltxt desc description search txt)
9162 (cond
9164 ((eq major-mode 'bbdb-mode)
9165 (let ((name (bbdb-record-name (bbdb-current-record)))
9166 (company (bbdb-record-company (bbdb-current-record))))
9167 (setq cpltxt (concat "bbdb:" (or name company))
9168 link (org-make-link cpltxt))
9169 (org-store-link-props :type "bbdb" :name name :company company)))
9171 ((eq major-mode 'Info-mode)
9172 (setq link (org-make-link "info:"
9173 (file-name-nondirectory Info-current-file)
9174 ":" Info-current-node))
9175 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9176 ":" Info-current-node))
9177 (org-store-link-props :type "info" :file Info-current-file
9178 :node Info-current-node))
9180 ((eq major-mode 'calendar-mode)
9181 (let ((cd (calendar-cursor-to-date)))
9182 (setq link
9183 (format-time-string
9184 (car org-time-stamp-formats)
9185 (apply 'encode-time
9186 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9187 nil nil nil))))
9188 (org-store-link-props :type "calendar" :date cd)))
9190 ((or (eq major-mode 'vm-summary-mode)
9191 (eq major-mode 'vm-presentation-mode))
9192 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9193 (vm-follow-summary-cursor)
9194 (save-excursion
9195 (vm-select-folder-buffer)
9196 (let* ((message (car vm-message-pointer))
9197 (folder buffer-file-name)
9198 (subject (vm-su-subject message))
9199 (to (vm-get-header-contents message "To"))
9200 (from (vm-get-header-contents message "From"))
9201 (message-id (vm-su-message-id message)))
9202 (org-store-link-props :type "vm" :from from :to to :subject subject
9203 :message-id message-id)
9204 (setq message-id (org-remove-angle-brackets message-id))
9205 (setq folder (abbreviate-file-name folder))
9206 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9207 folder)
9208 (setq folder (replace-match "" t t folder)))
9209 (setq cpltxt (org-email-link-description))
9210 (setq link (org-make-link "vm:" folder "#" message-id)))))
9212 ((eq major-mode 'wl-summary-mode)
9213 (let* ((msgnum (wl-summary-message-number))
9214 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9215 msgnum 'message-id))
9216 (wl-message-entity
9217 (if (fboundp 'elmo-message-entity)
9218 (elmo-message-entity
9219 wl-summary-buffer-elmo-folder msgnum)
9220 (elmo-msgdb-overview-get-entity
9221 msgnum (wl-summary-buffer-msgdb))))
9222 (from (wl-summary-line-from))
9223 (to (car (elmo-message-entity-field wl-message-entity 'to)))
9224 (subject (let (wl-thr-indent-string wl-parent-message-entity)
9225 (wl-summary-line-subject))))
9226 (org-store-link-props :type "wl" :from from :to to
9227 :subject subject :message-id message-id)
9228 (setq message-id (org-remove-angle-brackets message-id))
9229 (setq cpltxt (org-email-link-description))
9230 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9231 "#" message-id))))
9233 ((or (equal major-mode 'mh-folder-mode)
9234 (equal major-mode 'mh-show-mode))
9235 (let ((from (org-mhe-get-header "From:"))
9236 (to (org-mhe-get-header "To:"))
9237 (message-id (org-mhe-get-header "Message-Id:"))
9238 (subject (org-mhe-get-header "Subject:")))
9239 (org-store-link-props :type "mh" :from from :to to
9240 :subject subject :message-id message-id)
9241 (setq cpltxt (org-email-link-description))
9242 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9243 (org-remove-angle-brackets message-id)))))
9245 ((eq major-mode 'rmail-mode)
9246 (save-excursion
9247 (save-restriction
9248 (rmail-narrow-to-non-pruned-header)
9249 (let ((folder buffer-file-name)
9250 (message-id (mail-fetch-field "message-id"))
9251 (from (mail-fetch-field "from"))
9252 (to (mail-fetch-field "to"))
9253 (subject (mail-fetch-field "subject")))
9254 (org-store-link-props
9255 :type "rmail" :from from :to to
9256 :subject subject :message-id message-id)
9257 (setq message-id (org-remove-angle-brackets message-id))
9258 (setq cpltxt (org-email-link-description))
9259 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9261 ((eq major-mode 'gnus-group-mode)
9262 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9263 (gnus-group-group-name)) ; version
9264 ((fboundp 'gnus-group-name)
9265 (gnus-group-name))
9266 (t "???"))))
9267 (unless group (error "Not on a group"))
9268 (org-store-link-props :type "gnus" :group group)
9269 (setq cpltxt (concat
9270 (if (org-xor arg org-usenet-links-prefer-google)
9271 "http://groups.google.com/groups?group="
9272 "gnus:")
9273 group)
9274 link (org-make-link cpltxt))))
9276 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9277 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9278 (let* ((group gnus-newsgroup-name)
9279 (article (gnus-summary-article-number))
9280 (header (gnus-summary-article-header article))
9281 (from (mail-header-from header))
9282 (message-id (mail-header-id header))
9283 (date (mail-header-date header))
9284 (subject (gnus-summary-subject-string)))
9285 (org-store-link-props :type "gnus" :from from :subject subject
9286 :message-id message-id :group group)
9287 (setq cpltxt (org-email-link-description))
9288 (if (org-xor arg org-usenet-links-prefer-google)
9289 (setq link
9290 (concat
9291 cpltxt "\n "
9292 (format "http://groups.google.com/groups?as_umsgid=%s"
9293 (org-fixup-message-id-for-http message-id))))
9294 (setq link (org-make-link "gnus:" group
9295 "#" (number-to-string article))))))
9297 ((eq major-mode 'w3-mode)
9298 (setq cpltxt (url-view-url t)
9299 link (org-make-link cpltxt))
9300 (org-store-link-props :type "w3" :url (url-view-url t)))
9302 ((eq major-mode 'w3m-mode)
9303 (setq cpltxt (or w3m-current-title w3m-current-url)
9304 link (org-make-link w3m-current-url))
9305 (org-store-link-props :type "w3m" :url (url-view-url t)))
9307 ((setq search (run-hook-with-args-until-success
9308 'org-create-file-search-functions))
9309 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9310 "::" search))
9311 (setq cpltxt (or description link)))
9313 ((eq major-mode 'image-mode)
9314 (setq cpltxt (concat "file:"
9315 (abbreviate-file-name buffer-file-name))
9316 link (org-make-link cpltxt))
9317 (org-store-link-props :type "image" :file buffer-file-name))
9319 ((eq major-mode 'dired-mode)
9320 ;; link to the file in the current line
9321 (setq cpltxt (concat "file:"
9322 (abbreviate-file-name
9323 (expand-file-name
9324 (dired-get-filename nil t))))
9325 link (org-make-link cpltxt)))
9327 ((and buffer-file-name (org-mode-p))
9328 ;; Just link to current headline
9329 (setq cpltxt (concat "file:"
9330 (abbreviate-file-name buffer-file-name)))
9331 ;; Add a context search string
9332 (when (org-xor org-context-in-file-links arg)
9333 ;; Check if we are on a target
9334 (if (org-in-regexp "<<\\(.*?\\)>>")
9335 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9336 (setq txt (cond
9337 ((org-on-heading-p) nil)
9338 ((org-region-active-p)
9339 (buffer-substring (region-beginning) (region-end)))
9340 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9341 (when (or (null txt) (string-match "\\S-" txt))
9342 (setq cpltxt
9343 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9344 desc "NONE"))))
9345 (if (string-match "::\\'" cpltxt)
9346 (setq cpltxt (substring cpltxt 0 -2)))
9347 (setq link (org-make-link cpltxt)))
9349 (buffer-file-name
9350 ;; Just link to this file here.
9351 (setq cpltxt (concat "file:"
9352 (abbreviate-file-name buffer-file-name)))
9353 ;; Add a context string
9354 (when (org-xor org-context-in-file-links arg)
9355 (setq txt (if (org-region-active-p)
9356 (buffer-substring (region-beginning) (region-end))
9357 (buffer-substring (point-at-bol) (point-at-eol))))
9358 ;; Only use search option if there is some text.
9359 (when (string-match "\\S-" txt)
9360 (setq cpltxt
9361 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9362 desc "NONE")))
9363 (setq link (org-make-link cpltxt)))
9365 ((interactive-p)
9366 (error "Cannot link to a buffer which is not visiting a file"))
9368 (t (setq link nil)))
9370 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9371 (setq link (or link cpltxt)
9372 desc (or desc cpltxt))
9373 (if (equal desc "NONE") (setq desc nil))
9375 (if (and (interactive-p) link)
9376 (progn
9377 (setq org-stored-links
9378 (cons (list cpltxt link desc) org-stored-links))
9379 (message "Stored: %s" (or cpltxt link)))
9380 (org-make-link-string link desc))))
9382 (defun org-store-link-props (&rest plist)
9383 "Store link properties, extract names and addresses."
9384 (let (x adr)
9385 (when (setq x (plist-get plist :from))
9386 (setq adr (mail-extract-address-components x))
9387 (plist-put plist :fromname (car adr))
9388 (plist-put plist :fromaddress (nth 1 adr)))
9389 (when (setq x (plist-get plist :to))
9390 (setq adr (mail-extract-address-components x))
9391 (plist-put plist :toname (car adr))
9392 (plist-put plist :toaddress (nth 1 adr))))
9393 (let ((from (plist-get plist :from))
9394 (to (plist-get plist :to)))
9395 (when (and from to org-from-is-user-regexp)
9396 (plist-put plist :fromto
9397 (if (string-match org-from-is-user-regexp from)
9398 (concat "to %t")
9399 (concat "from %f")))))
9400 (setq org-store-link-plist plist))
9402 (defun org-email-link-description (&optional fmt)
9403 "Return the description part of an email link.
9404 This takes information from `org-store-link-plist' and formats it
9405 according to FMT (default from `org-email-link-description-format')."
9406 (setq fmt (or fmt org-email-link-description-format))
9407 (let* ((p org-store-link-plist)
9408 (to (plist-get p :toaddress))
9409 (from (plist-get p :fromaddress))
9410 (table
9411 (list
9412 (cons "%c" (plist-get p :fromto))
9413 (cons "%F" (plist-get p :from))
9414 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9415 (cons "%T" (plist-get p :to))
9416 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9417 (cons "%s" (plist-get p :subject))
9418 (cons "%m" (plist-get p :message-id)))))
9419 (when (string-match "%c" fmt)
9420 ;; Check if the user wrote this message
9421 (if (and org-from-is-user-regexp from to
9422 (save-match-data (string-match org-from-is-user-regexp from)))
9423 (setq fmt (replace-match "to %t" t t fmt))
9424 (setq fmt (replace-match "from %f" t t fmt))))
9425 (org-replace-escapes fmt table)))
9427 (defun org-make-org-heading-search-string (&optional string heading)
9428 "Make search string for STRING or current headline."
9429 (interactive)
9430 (let ((s (or string (org-get-heading))))
9431 (unless (and string (not heading))
9432 ;; We are using a headline, clean up garbage in there.
9433 (if (string-match org-todo-regexp s)
9434 (setq s (replace-match "" t t s)))
9435 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9436 (setq s (replace-match "" t t s)))
9437 (setq s (org-trim s))
9438 (if (string-match (concat "^\\(" org-quote-string "\\|"
9439 org-comment-string "\\)") s)
9440 (setq s (replace-match "" t t s)))
9441 (while (string-match org-ts-regexp s)
9442 (setq s (replace-match "" t t s))))
9443 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9444 (setq s (replace-match " " t t s)))
9445 (or string (setq s (concat "*" s))) ; Add * for headlines
9446 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9448 (defun org-make-link (&rest strings)
9449 "Concatenate STRINGS, format resulting string with `org-link-format'."
9450 (apply 'concat strings))
9452 (defun org-make-link-string (link &optional description)
9453 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9454 (when (stringp description)
9455 ;; Remove brackets from the description, they are fatal.
9456 (while (string-match "\\[\\|\\]" description)
9457 (setq description (replace-match "" t t description))))
9458 (when (equal (org-link-escape link) description)
9459 ;; No description needed, it is identical
9460 (setq description nil))
9461 (when (and (not description)
9462 (not (equal link (org-link-escape link))))
9463 (setq description link))
9464 (concat "[[" (org-link-escape link) "]"
9465 (if description (concat "[" description "]") "")
9466 "]"))
9468 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9469 "Association list of escapes for some characters problematic in links.")
9471 (defun org-link-escape (text)
9472 "Escape charaters in TEXT that are problematic for links."
9473 (when text
9474 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9475 org-link-escape-chars "\\|")))
9476 (while (string-match re text)
9477 (setq text
9478 (replace-match
9479 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9480 t t text)))
9481 text)))
9483 (defun org-link-unescape (text)
9484 "Reverse the action of `org-link-escape'."
9485 (when text
9486 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9487 org-link-escape-chars "\\|")))
9488 (while (string-match re text)
9489 (setq text
9490 (replace-match
9491 (car (rassoc (match-string 0 text) org-link-escape-chars))
9492 t t text)))
9493 text)))
9495 (defun org-xor (a b)
9496 "Exclusive or."
9497 (if a (not b) b))
9499 (defun org-get-header (header)
9500 "Find a header field in the current buffer."
9501 (save-excursion
9502 (goto-char (point-min))
9503 (let ((case-fold-search t) s)
9504 (cond
9505 ((eq header 'from)
9506 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
9507 (setq s (match-string 1)))
9508 (while (string-match "\"" s)
9509 (setq s (replace-match "" t t s)))
9510 (if (string-match "[<(].*" s)
9511 (setq s (replace-match "" t t s))))
9512 ((eq header 'message-id)
9513 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
9514 (setq s (match-string 1))))
9515 ((eq header 'subject)
9516 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
9517 (setq s (match-string 1)))))
9518 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
9519 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
9520 s)))
9523 (defun org-fixup-message-id-for-http (s)
9524 "Replace special characters in a message id, so it can be used in an http query."
9525 (while (string-match "<" s)
9526 (setq s (replace-match "%3C" t t s)))
9527 (while (string-match ">" s)
9528 (setq s (replace-match "%3E" t t s)))
9529 (while (string-match "@" s)
9530 (setq s (replace-match "%40" t t s)))
9533 (defun org-insert-link (&optional complete-file)
9534 "Insert a link. At the prompt, enter the link.
9536 Completion can be used to select a link previously stored with
9537 `org-store-link'. When the empty string is entered (i.e. if you just
9538 press RET at the prompt), the link defaults to the most recently
9539 stored link. As SPC triggers completion in the minibuffer, you need to
9540 use M-SPC or C-q SPC to force the insertion of a space character.
9542 You will also be prompted for a description, and if one is given, it will
9543 be displayed in the buffer instead of the link.
9545 If there is already a link at point, this command will allow you to edit link
9546 and description parts.
9548 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
9549 selected using completion. The path to the file will be relative to
9550 the current directory if the file is in the current directory or a
9551 subdirectory. Otherwise, the link will be the absolute path as
9552 completed in the minibuffer (i.e. normally ~/path/to/file).
9554 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
9555 is in the current directory or below.
9556 With three \\[universal-argument] prefixes, negate the meaning of
9557 `org-keep-stored-link-after-insertion'."
9558 (interactive "P")
9559 (let ((region (if (org-region-active-p)
9560 (prog1 (buffer-substring (region-beginning) (region-end))
9561 (delete-region (region-beginning) (region-end)))))
9562 tmphist ; byte-compile incorrectly complains about this
9563 link desc entry remove file)
9564 (cond
9565 ((org-in-regexp org-bracket-link-regexp 1)
9566 ;; We do have a link at point, and we are going to edit it.
9567 (setq remove (list (match-beginning 0) (match-end 0)))
9568 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9569 (setq link (read-string "Link: "
9570 (org-link-unescape
9571 (org-match-string-no-properties 1)))))
9572 ((or (org-in-regexp org-angle-link-re)
9573 (org-in-regexp org-plain-link-re))
9574 ;; Convert to bracket link
9575 (setq remove (list (match-beginning 0) (match-end 0))
9576 link (read-string "Link: "
9577 (org-remove-angle-brackets (match-string 0)))))
9578 ((equal complete-file '(4))
9579 ;; Completing read for file names.
9580 (setq file (read-file-name "File: "))
9581 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9582 (pwd1 (file-name-as-directory (abbreviate-file-name
9583 (expand-file-name ".")))))
9584 (cond
9585 ((equal complete-file '(16))
9586 (setq link (org-make-link
9587 "file:"
9588 (abbreviate-file-name (expand-file-name file)))))
9589 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9590 (setq link (org-make-link "file:" (match-string 1 file))))
9591 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9592 (expand-file-name file))
9593 (setq link (org-make-link
9594 "file:" (match-string 1 (expand-file-name file)))))
9595 (t (setq link (org-make-link "file:" file))))))
9597 ;; Read link, with completion for stored links.
9598 ;; Fake a link history
9599 (setq tmphist (append (mapcar 'car org-stored-links)
9600 org-insert-link-history))
9601 (setq link (org-completing-read
9602 "Link: " org-stored-links nil nil nil
9603 'tmphist
9604 (or (car (car org-stored-links)))))
9605 (setq entry (assoc link org-stored-links))
9606 (or entry (push link org-insert-link-history))
9607 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9608 (not org-keep-stored-link-after-insertion))
9609 (setq org-stored-links (delq (assoc link org-stored-links)
9610 org-stored-links)))
9611 (setq link (if entry (nth 1 entry) link)
9612 desc (or region desc (nth 2 entry)))))
9614 (if (string-match org-plain-link-re link)
9615 ;; URL-like link, normalize the use of angular brackets.
9616 (setq link (org-make-link (org-remove-angle-brackets link))))
9618 ;; Check if we are linking to the current file with a search option
9619 ;; If yes, simplify the link by using only the search option.
9620 (when (and buffer-file-name
9621 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
9622 (let* ((path (match-string 1 link))
9623 (case-fold-search nil)
9624 (search (match-string 2 link)))
9625 (save-match-data
9626 (if (equal (file-truename buffer-file-name) (file-truename path))
9627 ;; We are linking to this same file, with a search option
9628 (setq link search)))))
9630 ;; Check if we can/should use a relative path. If yes, simplify the link
9631 (when (string-match "\\<file:\\(.*\\)" link)
9632 (let* ((path (match-string 1 link))
9633 (case-fold-search nil))
9634 (cond
9635 ((eq org-link-file-path-type 'absolute)
9636 (setq path (abbreviate-file-name (expand-file-name path))))
9637 ((eq org-link-file-path-type 'noabbrev)
9638 (setq path (expand-file-name path)))
9639 ((eq org-link-file-path-type 'relative)
9640 (setq path (file-relative-name path)))
9642 (save-match-data
9643 (if (string-match (concat "^" (regexp-quote
9644 (file-name-as-directory
9645 (expand-file-name "."))))
9646 (expand-file-name path))
9647 ;; We are linking a file with relative path name.
9648 (setq path (substring (expand-file-name path)
9649 (match-end 0)))))))
9650 (setq link (concat "file:" path))))
9652 (setq desc (read-string "Description: " desc))
9653 (unless (string-match "\\S-" desc) (setq desc nil))
9654 (if remove (apply 'delete-region remove))
9655 (insert (org-make-link-string link desc))))
9657 (defun org-completing-read (&rest args)
9658 (let ((minibuffer-local-completion-map
9659 (copy-keymap minibuffer-local-completion-map)))
9660 (define-key minibuffer-local-completion-map " " 'self-insert-command)
9661 (apply 'completing-read args)))
9663 ;;; Opening/following a link
9664 (defvar org-link-search-failed nil)
9666 (defun org-next-link ()
9667 "Move forward to the next link.
9668 If the link is in hidden text, expose it."
9669 (interactive)
9670 (when (and org-link-search-failed (eq this-command last-command))
9671 (goto-char (point-min))
9672 (message "Link search wrapped back to beginning of buffer"))
9673 (setq org-link-search-failed nil)
9674 (let* ((pos (point))
9675 (ct (org-context))
9676 (a (assoc :link ct)))
9677 (if a (goto-char (nth 2 a)))
9678 (if (re-search-forward org-any-link-re nil t)
9679 (progn
9680 (goto-char (match-beginning 0))
9681 (if (org-invisible-p) (org-show-context)))
9682 (goto-char pos)
9683 (setq org-link-search-failed t)
9684 (error "No further link found"))))
9686 (defun org-previous-link ()
9687 "Move backward to the previous link.
9688 If the link is in hidden text, expose it."
9689 (interactive)
9690 (when (and org-link-search-failed (eq this-command last-command))
9691 (goto-char (point-max))
9692 (message "Link search wrapped back to end of buffer"))
9693 (setq org-link-search-failed nil)
9694 (let* ((pos (point))
9695 (ct (org-context))
9696 (a (assoc :link ct)))
9697 (if a (goto-char (nth 1 a)))
9698 (if (re-search-backward org-any-link-re nil t)
9699 (progn
9700 (goto-char (match-beginning 0))
9701 (if (org-invisible-p) (org-show-context)))
9702 (goto-char pos)
9703 (setq org-link-search-failed t)
9704 (error "No further link found"))))
9706 (defun org-find-file-at-mouse (ev)
9707 "Open file link or URL at mouse."
9708 (interactive "e")
9709 (mouse-set-point ev)
9710 (org-open-at-point 'in-emacs))
9712 (defun org-open-at-mouse (ev)
9713 "Open file link or URL at mouse."
9714 (interactive "e")
9715 (mouse-set-point ev)
9716 (org-open-at-point))
9718 (defvar org-window-config-before-follow-link nil
9719 "The window configuration before following a link.
9720 This is saved in case the need arises to restore it.")
9722 (defvar org-open-link-marker (make-marker)
9723 "Marker pointing to the location where `org-open-at-point; was called.")
9725 (defun org-open-at-point (&optional in-emacs)
9726 "Open link at or after point.
9727 If there is no link at point, this function will search forward up to
9728 the end of the current subtree.
9729 Normally, files will be opened by an appropriate application. If the
9730 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9731 (interactive "P")
9732 (move-marker org-open-link-marker (point))
9733 (setq org-window-config-before-follow-link (current-window-configuration))
9734 (org-remove-occur-highlights nil nil t)
9735 (if (org-at-timestamp-p t)
9736 (org-follow-timestamp-link)
9737 (let (type path link line search (pos (point)))
9738 (catch 'match
9739 (save-excursion
9740 (skip-chars-forward "^]\n\r")
9741 (when (org-in-regexp org-bracket-link-regexp)
9742 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9743 (while (string-match " *\n *" link)
9744 (setq link (replace-match " " t t link)))
9745 (setq link (org-link-expand-abbrev link))
9746 (if (string-match org-link-re-with-space2 link)
9747 (setq type (match-string 1 link) path (match-string 2 link))
9748 (setq type "thisfile" path link))
9749 (throw 'match t)))
9751 (when (get-text-property (point) 'org-linked-text)
9752 (setq type "thisfile"
9753 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9754 (1+ (point)) (point))
9755 path (buffer-substring
9756 (previous-single-property-change pos 'org-linked-text)
9757 (next-single-property-change pos 'org-linked-text)))
9758 (throw 'match t))
9760 (save-excursion
9761 (when (or (org-in-regexp org-angle-link-re)
9762 (org-in-regexp org-plain-link-re))
9763 (setq type (match-string 1) path (match-string 2))
9764 (throw 'match t)))
9765 (save-excursion
9766 (when (org-in-regexp "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9767 (setq type "tags"
9768 path (match-string 1))
9769 (while (string-match ":" path)
9770 (setq path (replace-match "+" t t path)))
9771 (throw 'match t))))
9772 (unless path
9773 (error "No link found"))
9774 ;; Remove any trailing spaces in path
9775 (if (string-match " +\\'" path)
9776 (setq path (replace-match "" t t path)))
9778 (cond
9780 ((equal type "mailto")
9781 (let ((cmd (car org-link-mailto-program))
9782 (args (cdr org-link-mailto-program)) args1
9783 (address path) (subject "") a)
9784 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9785 (setq address (match-string 1 path)
9786 subject (org-link-escape (match-string 2 path))))
9787 (while args
9788 (cond
9789 ((not (stringp (car args))) (push (pop args) args1))
9790 (t (setq a (pop args))
9791 (if (string-match "%a" a)
9792 (setq a (replace-match address t t a)))
9793 (if (string-match "%s" a)
9794 (setq a (replace-match subject t t a)))
9795 (push a args1))))
9796 (apply cmd (nreverse args1))))
9798 ((member type '("http" "https" "ftp" "news"))
9799 (browse-url (concat type ":" path)))
9801 ((string= type "tags")
9802 (org-tags-view in-emacs path))
9803 ((string= type "thisfile")
9804 (if in-emacs
9805 (switch-to-buffer-other-window
9806 (org-get-buffer-for-internal-link (current-buffer)))
9807 (org-mark-ring-push))
9808 (org-link-search
9809 path
9810 (cond ((equal in-emacs '(4)) 'occur)
9811 ((equal in-emacs '(16)) 'org-occur)
9812 (t nil))
9813 pos))
9815 ((string= type "file")
9816 (if (string-match "::\\([0-9]+\\)\\'" path)
9817 (setq line (string-to-number (match-string 1 path))
9818 path (substring path 0 (match-beginning 0)))
9819 (if (string-match "::\\(.+\\)\\'" path)
9820 (setq search (match-string 1 path)
9821 path (substring path 0 (match-beginning 0)))))
9822 (org-open-file path in-emacs line search))
9824 ((string= type "news")
9825 (org-follow-gnus-link path))
9827 ((string= type "bbdb")
9828 (org-follow-bbdb-link path))
9830 ((string= type "info")
9831 (org-follow-info-link path))
9833 ((string= type "gnus")
9834 (let (group article)
9835 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9836 (error "Error in Gnus link"))
9837 (setq group (match-string 1 path)
9838 article (match-string 3 path))
9839 (org-follow-gnus-link group article)))
9841 ((string= type "vm")
9842 (let (folder article)
9843 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9844 (error "Error in VM link"))
9845 (setq folder (match-string 1 path)
9846 article (match-string 3 path))
9847 ;; in-emacs is the prefix arg, will be interpreted as read-only
9848 (org-follow-vm-link folder article in-emacs)))
9850 ((string= type "wl")
9851 (let (folder article)
9852 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9853 (error "Error in Wanderlust link"))
9854 (setq folder (match-string 1 path)
9855 article (match-string 3 path))
9856 (org-follow-wl-link folder article)))
9858 ((string= type "mhe")
9859 (let (folder article)
9860 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9861 (error "Error in MHE link"))
9862 (setq folder (match-string 1 path)
9863 article (match-string 3 path))
9864 (org-follow-mhe-link folder article)))
9866 ((string= type "rmail")
9867 (let (folder article)
9868 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9869 (error "Error in RMAIL link"))
9870 (setq folder (match-string 1 path)
9871 article (match-string 3 path))
9872 (org-follow-rmail-link folder article)))
9874 ((string= type "shell")
9875 (let ((cmd path))
9876 ;; FIXME: the following is only for backward compatibility
9877 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
9878 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
9879 (if (or (not org-confirm-shell-link-function)
9880 (funcall org-confirm-shell-link-function
9881 (format "Execute \"%s\" in shell? "
9882 (org-add-props cmd nil
9883 'face 'org-warning))))
9884 (progn
9885 (message "Executing %s" cmd)
9886 (shell-command cmd))
9887 (error "Abort"))))
9889 ((string= type "elisp")
9890 (let ((cmd path))
9891 (if (or (not org-confirm-elisp-link-function)
9892 (funcall org-confirm-elisp-link-function
9893 (format "Execute \"%s\" as elisp? "
9894 (org-add-props cmd nil
9895 'face 'org-warning))))
9896 (message "%s => %s" cmd (eval (read cmd)))
9897 (error "Abort"))))
9900 (browse-url-at-point)))))
9901 (move-marker org-open-link-marker nil))
9904 ;;; File search
9906 (defvar org-create-file-search-functions nil
9907 "List of functions to construct the right search string for a file link.
9908 These functions are called in turn with point at the location to
9909 which the link should point.
9911 A function in the hook should first test if it would like to
9912 handle this file type, for example by checking the major-mode or
9913 the file extension. If it decides not to handle this file, it
9914 should just return nil to give other functions a chance. If it
9915 does handle the file, it must return the search string to be used
9916 when following the link. The search string will be part of the
9917 file link, given after a double colon, and `org-open-at-point'
9918 will automatically search for it. If special measures must be
9919 taken to make the search successful, another function should be
9920 added to the companion hook `org-execute-file-search-functions',
9921 which see.
9923 A function in this hook may also use `setq' to set the variable
9924 `description' to provide a suggestion for the descriptive text to
9925 be used for this link when it gets inserted into an Org-mode
9926 buffer with \\[org-insert-link].")
9928 (defvar org-execute-file-search-functions nil
9929 "List of functions to execute a file search triggered by a link.
9931 Functions added to this hook must accept a single argument, the
9932 search string that was part of the file link, the part after the
9933 double colon. The function must first check if it would like to
9934 handle this search, for example by checking the major-mode or the
9935 file extension. If it decides not to handle this search, it
9936 should just return nil to give other functions a chance. If it
9937 does handle the search, it must return a non-nil value to keep
9938 other functions from trying.
9940 Each function can access the current prefix argument through the
9941 variable `current-prefix-argument'. Note that a single prefix is
9942 used to force opening a link in Emacs, so it may be good to only
9943 use a numeric or double prefix to guide the search function.
9945 In case this is needed, a function in this hook can also restore
9946 the window configuration before `org-open-at-point' was called using:
9948 (set-window-configuration org-window-config-before-follow-link)")
9950 (defun org-link-search (s &optional type avoid-pos)
9951 "Search for a link search option.
9952 If S is surrounded by forward slashes, it is interpreted as a
9953 regular expression. In org-mode files, this will create an `org-occur'
9954 sparse tree. In ordinary files, `occur' will be used to list matches.
9955 If the current buffer is in `dired-mode', grep will be used to search
9956 in all files. If AVOID-POS is given, ignore matches near that position."
9957 (let ((case-fold-search t)
9958 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9959 (pos (point))
9960 (pre "") (post "")
9961 words re0 re1 re2 re3 re4 re5 re2a reall)
9962 (cond
9963 ;; First check if there are any special
9964 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9965 ;; Now try the builtin stuff
9966 ((save-excursion
9967 (goto-char (point-min))
9968 (and
9969 (re-search-forward
9970 (concat "<<" (regexp-quote s0) ">>") nil t)
9971 (setq pos (match-beginning 0))))
9972 ;; There is an exact target for this
9973 (goto-char pos))
9974 ((string-match "^/\\(.*\\)/$" s)
9975 ;; A regular expression
9976 (cond
9977 ((org-mode-p)
9978 (org-occur (match-string 1 s)))
9979 ;;((eq major-mode 'dired-mode)
9980 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9981 (t (org-do-occur (match-string 1 s)))))
9983 ;; A normal search string
9984 (when (equal (string-to-char s) ?*)
9985 ;; Anchor on headlines, post may include tags.
9986 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9987 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9988 s (substring s 1)))
9989 (remove-text-properties
9990 0 (length s)
9991 '(face nil mouse-face nil keymap nil fontified nil) s)
9992 ;; Make a series of regular expressions to find a match
9993 (setq words (org-split-string s "[ \n\r\t]+")
9994 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9995 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9996 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9997 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9998 re1 (concat pre re2 post)
9999 re3 (concat pre re4 post)
10000 re5 (concat pre ".*" re4)
10001 re2 (concat pre re2)
10002 re2a (concat pre re2a)
10003 re4 (concat pre re4)
10004 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10005 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10006 re5 "\\)"
10008 (cond
10009 ((eq type 'org-occur) (org-occur reall))
10010 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10011 (t (goto-char (point-min))
10012 (if (or (org-search-not-self 1 re0 nil t)
10013 (org-search-not-self 1 re1 nil t)
10014 (org-search-not-self 1 re2 nil t)
10015 (org-search-not-self 1 re2a nil t)
10016 (org-search-not-self 1 re3 nil t)
10017 (org-search-not-self 1 re4 nil t)
10018 (org-search-not-self 1 re5 nil t)
10020 (goto-char (match-beginning 1))
10021 (goto-char pos)
10022 (error "No match")))))
10024 ;; Normal string-search
10025 (goto-char (point-min))
10026 (if (search-forward s nil t)
10027 (goto-char (match-beginning 0))
10028 (error "No match"))))
10029 (and (org-mode-p) (org-show-context 'link-search))))
10031 (defun org-search-not-self (group &rest args)
10032 "Execute `re-search-forward', but only accept matches that do not
10033 enclose the position of `org-open-link-marker'."
10034 (let ((m org-open-link-marker))
10035 (catch 'exit
10036 (while (apply 're-search-forward args)
10037 (goto-char (match-end group))
10038 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10039 (> (match-beginning 0) (marker-position m))
10040 (< (match-end 0) (marker-position m)))
10041 (save-match-data
10042 (or (not (org-in-regexp org-bracket-link-analytic-regexp 1))
10043 (not (match-end 4)) ; no description
10044 (and (<= (match-beginning 4) (point))
10045 (>= (match-end 4) (point))))))
10046 (throw 'exit (point)))))))
10048 (defun org-get-buffer-for-internal-link (buffer)
10049 "Return a buffer to be used for displaying the link target of internal links."
10050 (cond
10051 ((not org-display-internal-link-with-indirect-buffer)
10052 buffer)
10053 ((string-match "(Clone)$" (buffer-name buffer))
10054 (message "Buffer is already a clone, not making another one")
10055 ;; we also do not modify visibility in this case
10056 buffer)
10057 (t ; make a new indirect buffer for displaying the link
10058 (let* ((bn (buffer-name buffer))
10059 (ibn (concat bn "(Clone)"))
10060 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10061 (with-current-buffer ib (org-overview))
10062 ib))))
10064 (defun org-do-occur (regexp &optional cleanup)
10065 "Call the Emacs command `occur'.
10066 If CLEANUP is non-nil, remove the printout of the regular expression
10067 in the *Occur* buffer. This is useful if the regex is long and not useful
10068 to read."
10069 (occur regexp)
10070 (when cleanup
10071 (let ((cwin (selected-window)) win beg end)
10072 (when (setq win (get-buffer-window "*Occur*"))
10073 (select-window win))
10074 (goto-char (point-min))
10075 (when (re-search-forward "match[a-z]+" nil t)
10076 (setq beg (match-end 0))
10077 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10078 (setq end (1- (match-beginning 0)))))
10079 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
10080 (goto-char (point-min))
10081 (select-window cwin))))
10083 ;;; The mark ring for links jumps
10085 (defvar org-mark-ring nil
10086 "Mark ring for positions before jumps in Org-mode.")
10087 (defvar org-mark-ring-last-goto nil
10088 "Last position in the mark ring used to go back.")
10089 ;; Fill and close the ring
10090 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10091 (loop for i from 1 to org-mark-ring-length do
10092 (push (make-marker) org-mark-ring))
10093 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10094 org-mark-ring)
10096 (defun org-mark-ring-push (&optional pos buffer)
10097 "Put the current position or POS into the mark ring and rotate it."
10098 (interactive)
10099 (setq pos (or pos (point)))
10100 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10101 (move-marker (car org-mark-ring)
10102 (or pos (point))
10103 (or buffer (current-buffer)))
10104 (message
10105 (substitute-command-keys
10106 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10108 (defun org-mark-ring-goto (&optional n)
10109 "Jump to the previous position in the mark ring.
10110 With prefix arg N, jump back that many stored positions. When
10111 called several times in succession, walk through the entire ring.
10112 Org-mode commands jumping to a different position in the current file,
10113 or to another Org-mode file, automatically push the old position
10114 onto the ring."
10115 (interactive "p")
10116 (let (p m)
10117 (if (eq last-command this-command)
10118 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10119 (setq p org-mark-ring))
10120 (setq org-mark-ring-last-goto p)
10121 (setq m (car p))
10122 (switch-to-buffer (marker-buffer m))
10123 (goto-char m)
10124 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10126 (defun org-remove-angle-brackets (s)
10127 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10128 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10130 (defun org-add-angle-brackets (s)
10131 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10132 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10135 ;;; Following specific links
10137 (defun org-follow-timestamp-link ()
10138 (cond
10139 ((org-at-date-range-p t)
10140 (let ((org-agenda-start-on-weekday)
10141 (t1 (match-string 1))
10142 (t2 (match-string 2)))
10143 (setq t1 (time-to-days (org-time-string-to-time t1))
10144 t2 (time-to-days (org-time-string-to-time t2)))
10145 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10146 ((org-at-timestamp-p t)
10147 (org-agenda-list nil (time-to-days (org-time-string-to-time
10148 (substring (match-string 1) 0 10)))
10150 (t (error "This should not happen"))))
10153 (defun org-follow-bbdb-link (name)
10154 "Follow a BBDB link to NAME."
10155 (require 'bbdb)
10156 (let ((inhibit-redisplay (not debug-on-error))
10157 (bbdb-electric-p nil))
10158 (catch 'exit
10159 ;; Exact match on name
10160 (bbdb-name (concat "\\`" name "\\'") nil)
10161 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10162 ;; Exact match on name
10163 (bbdb-company (concat "\\`" name "\\'") nil)
10164 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10165 ;; Partial match on name
10166 (bbdb-name name nil)
10167 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10168 ;; Partial match on company
10169 (bbdb-company name nil)
10170 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10171 ;; General match including network address and notes
10172 (bbdb name nil)
10173 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10174 (delete-window (get-buffer-window "*BBDB*"))
10175 (error "No matching BBDB record")))))
10177 (defun org-follow-info-link (name)
10178 "Follow an info file & node link to NAME."
10179 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10180 (string-match "\\(.*\\)" name))
10181 (progn
10182 (require 'info)
10183 (if (match-string 2 name) ; If there isn't a node, choose "Top"
10184 (Info-find-node (match-string 1 name) (match-string 2 name))
10185 (Info-find-node (match-string 1 name) "Top")))
10186 (message (concat "Could not open: " name))))
10188 (defun org-follow-gnus-link (&optional group article)
10189 "Follow a Gnus link to GROUP and ARTICLE."
10190 (require 'gnus)
10191 (funcall (cdr (assq 'gnus org-link-frame-setup)))
10192 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10193 (cond ((and group article)
10194 (gnus-group-read-group 0 nil group)
10195 (gnus-summary-goto-article (string-to-number article) nil t))
10196 (group (gnus-group-jump-to-group group))))
10198 (defun org-follow-vm-link (&optional folder article readonly)
10199 "Follow a VM link to FOLDER and ARTICLE."
10200 (require 'vm)
10201 (setq article (org-add-angle-brackets article))
10202 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
10203 ;; ange-ftp or efs or tramp access
10204 (let ((user (or (match-string 1 folder) (user-login-name)))
10205 (host (match-string 2 folder))
10206 (file (match-string 3 folder)))
10207 (cond
10208 ((featurep 'tramp)
10209 ;; use tramp to access the file
10210 (if (featurep 'xemacs)
10211 (setq folder (format "[%s@%s]%s" user host file))
10212 (setq folder (format "/%s@%s:%s" user host file))))
10214 ;; use ange-ftp or efs
10215 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
10216 (setq folder (format "/%s@%s:%s" user host file))))))
10217 (when folder
10218 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
10219 (sit-for 0.1)
10220 (when article
10221 (vm-select-folder-buffer)
10222 (widen)
10223 (let ((case-fold-search t))
10224 (goto-char (point-min))
10225 (if (not (re-search-forward
10226 (concat "^" "message-id: *" (regexp-quote article))))
10227 (error "Could not find the specified message in this folder"))
10228 (vm-isearch-update)
10229 (vm-isearch-narrow)
10230 (vm-beginning-of-message)
10231 (vm-summarize)))))
10233 (defun org-follow-wl-link (folder article)
10234 "Follow a Wanderlust link to FOLDER and ARTICLE."
10235 (if (and (string= folder "%")
10236 article
10237 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
10238 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
10239 ;; Thus, we recompose folder and article ids.
10240 (setq folder (format "%s#%s" folder (match-string 1 article))
10241 article (match-string 3 article)))
10242 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
10243 (error "No such folder: %s" folder))
10244 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
10245 (and article
10246 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
10247 (wl-summary-redisplay)))
10249 (defun org-follow-rmail-link (folder article)
10250 "Follow an RMAIL link to FOLDER and ARTICLE."
10251 (setq article (org-add-angle-brackets article))
10252 (let (message-number)
10253 (save-excursion
10254 (save-window-excursion
10255 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10256 (setq message-number
10257 (save-restriction
10258 (widen)
10259 (goto-char (point-max))
10260 (if (re-search-backward
10261 (concat "^Message-ID:\\s-+" (regexp-quote
10262 (or article "")))
10263 nil t)
10264 (rmail-what-message))))))
10265 (if message-number
10266 (progn
10267 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10268 (rmail-show-message message-number)
10269 message-number)
10270 (error "Message not found"))))
10272 ;;; mh-e integration based on planner-mode
10273 (defun org-mhe-get-message-real-folder ()
10274 "Return the name of the current message real folder, so if you use
10275 sequences, it will now work."
10276 (save-excursion
10277 (let* ((folder
10278 (if (equal major-mode 'mh-folder-mode)
10279 mh-current-folder
10280 ;; Refer to the show buffer
10281 mh-show-folder-buffer))
10282 (end-index
10283 (if (boundp 'mh-index-folder)
10284 (min (length mh-index-folder) (length folder))))
10286 ;; a simple test on mh-index-data does not work, because
10287 ;; mh-index-data is always nil in a show buffer.
10288 (if (and (boundp 'mh-index-folder)
10289 (string= mh-index-folder (substring folder 0 end-index)))
10290 (if (equal major-mode 'mh-show-mode)
10291 (save-window-excursion
10292 (when (buffer-live-p (get-buffer folder))
10293 (progn
10294 (pop-to-buffer folder)
10295 (org-mhe-get-message-folder-from-index)
10298 (org-mhe-get-message-folder-from-index)
10300 folder
10304 (defun org-mhe-get-message-folder-from-index ()
10305 "Returns the name of the message folder in a index folder buffer."
10306 (save-excursion
10307 (mh-index-previous-folder)
10308 (re-search-forward "^\\(+.*\\)$" nil t)
10309 (message (match-string 1))))
10311 (defun org-mhe-get-message-folder ()
10312 "Return the name of the current message folder. Be careful if you
10313 use sequences."
10314 (save-excursion
10315 (if (equal major-mode 'mh-folder-mode)
10316 mh-current-folder
10317 ;; Refer to the show buffer
10318 mh-show-folder-buffer)))
10320 (defun org-mhe-get-message-num ()
10321 "Return the number of the current message. Be careful if you
10322 use sequences."
10323 (save-excursion
10324 (if (equal major-mode 'mh-folder-mode)
10325 (mh-get-msg-num nil)
10326 ;; Refer to the show buffer
10327 (mh-show-buffer-message-number))))
10329 (defun org-mhe-get-header (header)
10330 "Return a header of the message in folder mode. This will create a
10331 show buffer for the corresponding message. If you have a more clever
10332 idea..."
10333 (let* ((folder (org-mhe-get-message-folder))
10334 (num (org-mhe-get-message-num))
10335 (buffer (get-buffer-create (concat "show-" folder)))
10336 (header-field))
10337 (with-current-buffer buffer
10338 (mh-display-msg num folder)
10339 (if (equal major-mode 'mh-folder-mode)
10340 (mh-header-display)
10341 (mh-show-header-display))
10342 (set-buffer buffer)
10343 (setq header-field (mh-get-header-field header))
10344 (if (equal major-mode 'mh-folder-mode)
10345 (mh-show)
10346 (mh-show-show))
10347 header-field)))
10349 (defun org-follow-mhe-link (folder article)
10350 "Follow an MHE link to FOLDER and ARTICLE.
10351 If ARTICLE is nil FOLDER is shown. If the configuration variable
10352 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
10353 ARTICLE is searched in all folders. Indexed searches (swish++,
10354 namazu, and others supported by MH-E) will always search in all
10355 folders."
10356 (require 'mh-e)
10357 (require 'mh-search)
10358 (require 'mh-utils)
10359 (mh-find-path)
10360 (if (not article)
10361 (mh-visit-folder (mh-normalize-folder-name folder))
10362 (setq article (org-add-angle-brackets article))
10363 (mh-search-choose)
10364 (if (equal mh-searcher 'pick)
10365 (progn
10366 (mh-search folder (list "--message-id" article))
10367 (when (and org-mhe-search-all-folders
10368 (not (org-mhe-get-message-real-folder)))
10369 (kill-this-buffer)
10370 (mh-search "+" (list "--message-id" article))))
10371 (mh-search "+" article))
10372 (if (org-mhe-get-message-real-folder)
10373 (mh-show-msg 1)
10374 (kill-this-buffer)
10375 (error "Message not found"))))
10377 ;;; BibTeX links
10379 ;; Use the custom search meachnism to construct and use search strings for
10380 ;; file links to BibTeX database entries.
10382 (defun org-create-file-search-in-bibtex ()
10383 "Create the search string and description for a BibTeX database entry."
10384 (when (eq major-mode 'bibtex-mode)
10385 ;; yes, we want to construct this search string.
10386 ;; Make a good description for this entry, using names, year and the title
10387 ;; Put it into the `description' variable which is dynamically scoped.
10388 (let ((bibtex-autokey-names 1)
10389 (bibtex-autokey-names-stretch 1)
10390 (bibtex-autokey-name-case-convert-function 'identity)
10391 (bibtex-autokey-name-separator " & ")
10392 (bibtex-autokey-additional-names " et al.")
10393 (bibtex-autokey-year-length 4)
10394 (bibtex-autokey-name-year-separator " ")
10395 (bibtex-autokey-titlewords 3)
10396 (bibtex-autokey-titleword-separator " ")
10397 (bibtex-autokey-titleword-case-convert-function 'identity)
10398 (bibtex-autokey-titleword-length 'infty)
10399 (bibtex-autokey-year-title-separator ": "))
10400 (setq description (bibtex-generate-autokey)))
10401 ;; Now parse the entry, get the key and return it.
10402 (save-excursion
10403 (bibtex-beginning-of-entry)
10404 (cdr (assoc "=key=" (bibtex-parse-entry))))))
10406 (defun org-execute-file-search-in-bibtex (s)
10407 "Find the link search string S as a key for a database entry."
10408 (when (eq major-mode 'bibtex-mode)
10409 ;; Yes, we want to do the search in this file.
10410 ;; We construct a regexp that searches for "@entrytype{" followed by the key
10411 (goto-char (point-min))
10412 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
10413 (regexp-quote s) "[ \t\n]*,") nil t)
10414 (goto-char (match-beginning 0)))
10415 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
10416 ;; Use double prefix to indicate that any web link should be browsed
10417 (let ((b (current-buffer)) (p (point)))
10418 ;; Restore the window configuration because we just use the web link
10419 (set-window-configuration org-window-config-before-follow-link)
10420 (save-excursion (set-buffer b) (goto-char p)
10421 (bibtex-url)))
10422 (recenter 0)) ; Move entry start to beginning of window
10423 ;; return t to indicate that the search is done.
10426 ;; Finally add the functions to the right hooks.
10427 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10428 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10430 ;; end of Bibtex link setup
10432 ;;; Following file links
10434 (defun org-open-file (path &optional in-emacs line search)
10435 "Open the file at PATH.
10436 First, this expands any special file name abbreviations. Then the
10437 configuration variable `org-file-apps' is checked if it contains an
10438 entry for this file type, and if yes, the corresponding command is launched.
10439 If no application is found, Emacs simply visits the file.
10440 With optional argument IN-EMACS, Emacs will visit the file.
10441 Optional LINE specifies a line to go to, optional SEARCH a string to
10442 search for. If LINE or SEARCH is given, the file will always be
10443 opened in Emacs.
10444 If the file does not exist, an error is thrown."
10445 (setq in-emacs (or in-emacs line search))
10446 (let* ((file (if (equal path "")
10447 buffer-file-name
10448 (substitute-in-file-name (expand-file-name path))))
10449 (apps (append org-file-apps (org-default-apps)))
10450 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10451 (dirp (if remp nil (file-directory-p file)))
10452 (dfile (downcase file))
10453 (old-buffer (current-buffer))
10454 (old-pos (point))
10455 (old-mode major-mode)
10456 ext cmd)
10457 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10458 (setq ext (match-string 1 dfile))
10459 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10460 (setq ext (match-string 1 dfile))))
10461 (if in-emacs
10462 (setq cmd 'emacs)
10463 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10464 (and dirp (cdr (assoc 'directory apps)))
10465 (cdr (assoc ext apps))
10466 (cdr (assoc t apps)))))
10467 (when (eq cmd 'mailcap)
10468 (require 'mailcap)
10469 (mailcap-parse-mailcaps)
10470 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10471 (command (mailcap-mime-info mime-type)))
10472 (if (stringp command)
10473 (setq cmd command)
10474 (setq cmd 'emacs))))
10475 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
10476 (not (file-exists-p file))
10477 (not org-open-non-existing-files))
10478 (error "No such file: %s" file))
10479 (cond
10480 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10481 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10482 (if (string-match "['\"]%s['\"]" cmd)
10483 (setq cmd (replace-match "%s" t t cmd)))
10484 (setq cmd (format cmd (shell-quote-argument file)))
10485 (save-window-excursion
10486 (shell-command (concat cmd " &"))))
10487 ((or (stringp cmd)
10488 (eq cmd 'emacs))
10489 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10490 (if line (goto-line line)
10491 (if search (org-link-search search))))
10492 ((consp cmd)
10493 (eval cmd))
10494 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10495 (and (org-mode-p) (eq old-mode 'org-mode)
10496 (or (not (equal old-buffer (current-buffer)))
10497 (not (equal old-pos (point))))
10498 (org-mark-ring-push old-pos old-buffer))))
10500 (defun org-default-apps ()
10501 "Return the default applications for this operating system."
10502 (cond
10503 ((eq system-type 'darwin)
10504 org-file-apps-defaults-macosx)
10505 ((eq system-type 'windows-nt)
10506 org-file-apps-defaults-windowsnt)
10507 (t org-file-apps-defaults-gnu)))
10509 (defun org-expand-file-name (path)
10510 "Replace special path abbreviations and expand the file name."
10511 (expand-file-name path))
10513 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10514 (defun org-file-remote-p (file)
10515 "Test whether FILE specifies a location on a remote system.
10516 Return non-nil if the location is indeed remote.
10518 For example, the filename \"/user@host:/foo\" specifies a location
10519 on the system \"/user@host:\"."
10520 (cond ((fboundp 'file-remote-p)
10521 (file-remote-p file))
10522 ((fboundp 'tramp-handle-file-remote-p)
10523 (tramp-handle-file-remote-p file))
10524 ((and (boundp 'ange-ftp-name-format)
10525 (string-match (car ange-ftp-name-format) file))
10527 (t nil)))
10530 ;;;; Hooks for remember.el
10532 ;;;###autoload
10533 (defun org-remember-annotation ()
10534 "Return a link to the current location as an annotation for remember.el.
10535 If you are using Org-mode files as target for data storage with
10536 remember.el, then the annotations should include a link compatible with the
10537 conventions in Org-mode. This function returns such a link."
10538 (org-store-link nil))
10540 (defconst org-remember-help
10541 "Select a destination location for the note.
10542 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10543 RET at beg-of-buf -> Append to file as level 2 headline
10544 RET on headline -> Store as sublevel entry to current headline
10545 <left>/<right> -> before/after current headline, same headings level")
10547 ;;;###autoload
10548 (defun org-remember-apply-template (&optional use-char skip-interactive)
10549 "Initialize *remember* buffer with template, invoke `org-mode'.
10550 This function should be placed into `remember-mode-hook' and in fact requires
10551 to be run from that hook to fucntion properly."
10552 (if org-remember-templates
10554 (let* ((char (or use-char
10555 (if (= (length org-remember-templates) 1)
10556 (caar org-remember-templates)
10557 (message "Select template: %s"
10558 (mapconcat
10559 (lambda (x) (char-to-string (car x)))
10560 org-remember-templates " "))
10561 (read-char-exclusive))))
10562 (entry (cdr (assoc char org-remember-templates)))
10563 (tpl (car entry))
10564 (plist-p (if org-store-link-plist t nil))
10565 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
10566 (string-match "\\S-" (nth 1 entry)))
10567 (nth 1 entry)
10568 org-default-notes-file))
10569 (headline (nth 2 entry))
10570 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10571 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10572 (v-u (concat "[" (substring v-t 1 -1) "]"))
10573 (v-U (concat "[" (substring v-T 1 -1) "]"))
10574 (v-i initial) ; defined in `remember-mode'
10575 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
10576 (v-n user-full-name)
10577 (org-startup-folded nil)
10578 org-time-was-given x prompt char time)
10579 (setq org-store-link-plist
10580 (append (list :annotation v-a :initial v-i)))
10581 (unless tpl (setq tpl "") (message "No template") (ding))
10582 (erase-buffer)
10583 (insert (substitute-command-keys
10584 (format
10585 "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
10586 ## Target file \"%s\", headline \"%s\"
10587 ## To switch templates, use `\\[org-remember]'.\n\n"
10588 (abbreviate-file-name (or file org-default-notes-file))
10589 (or headline ""))))
10590 (insert tpl) (goto-char (point-min))
10591 ;; Simple %-escapes
10592 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
10593 (when (and initial (equal (match-string 0) "%i"))
10594 (save-match-data
10595 (let* ((lead (buffer-substring
10596 (point-at-bol) (match-beginning 0))))
10597 (setq v-i (mapconcat 'identity
10598 (org-split-string initial "\n")
10599 (concat "\n" lead))))))
10600 (replace-match
10601 (or (eval (intern (concat "v-" (match-string 1)))) "")
10602 t t))
10603 ;; From the property list
10604 (when plist-p
10605 (goto-char (point-min))
10606 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
10607 (and (setq x (plist-get org-store-link-plist
10608 (intern (match-string 1))))
10609 (replace-match x t t))))
10610 ;; Turn on org-mode in the remember buffer, set local variables
10611 (org-mode)
10612 (org-set-local 'org-finish-function 'remember-buffer)
10613 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10614 (org-set-local 'org-default-notes-file file))
10615 (if (and headline (stringp headline) (string-match "\\S-" headline))
10616 (org-set-local 'org-remember-default-headline headline))
10617 ;; Interactive template entries
10618 (goto-char (point-min))
10619 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([uUtT]\\)?" nil t)
10620 (setq char (if (match-end 3) (match-string 3))
10621 prompt (if (match-end 2) (match-string 2)))
10622 (goto-char (match-beginning 0))
10623 (replace-match "")
10624 (if char
10625 (progn
10626 (setq org-time-was-given (equal (upcase char) char))
10627 (setq time (org-read-date (equal (upcase char) "U") t nil
10628 prompt))
10629 (org-insert-time-stamp time org-time-was-given
10630 (member char '("u" "U"))))
10631 (insert (read-string
10632 (if prompt (concat prompt ": ") "Enter string")))))
10633 (goto-char (point-min))
10634 (if (re-search-forward "%\\?" nil t)
10635 (replace-match "")
10636 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
10637 (org-mode)
10638 (org-set-local 'org-finish-function 'remember-buffer)))
10640 ;;;###autoload
10641 (defun org-remember ()
10642 "Call `remember'. If this is already a remember buffer, re-apply template.
10643 If there is an active region, make sure remember uses it as initial content
10644 of the remember buffer."
10645 (interactive)
10646 (if (eq org-finish-function 'remember-buffer)
10647 (progn
10648 (when (< (length org-remember-templates) 2)
10649 (error "No other template available"))
10650 (erase-buffer)
10651 (let ((annotation (plist-get org-store-link-plist :annotation))
10652 (initial (plist-get org-store-link-plist :initial)))
10653 (org-remember-apply-template))
10654 (message "Press C-c C-c to remember data"))
10655 (if (org-region-active-p)
10656 (remember (buffer-substring (point) (mark)))
10657 (call-interactively 'remember))))
10659 ;;;###autoload
10660 (defun org-remember-handler ()
10661 "Store stuff from remember.el into an org file.
10662 First prompts for an org file. If the user just presses return, the value
10663 of `org-default-notes-file' is used.
10664 Then the command offers the headings tree of the selected file in order to
10665 file the text at a specific location.
10666 You can either immediately press RET to get the note appended to the
10667 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10668 find a better place. Then press RET or <left> or <right> in insert the note.
10670 Key Cursor position Note gets inserted
10671 -----------------------------------------------------------------------------
10672 RET buffer-start as level 2 heading at end of file
10673 RET on headline as sublevel of the heading at cursor
10674 RET no heading at cursor position, level taken from context.
10675 Or use prefix arg to specify level manually.
10676 <left> on headline as same level, before current heading
10677 <right> on headline as same level, after current heading
10679 So the fastest way to store the note is to press RET RET to append it to
10680 the default file. This way your current train of thought is not
10681 interrupted, in accordance with the principles of remember.el. But with
10682 little extra effort, you can push it directly to the correct location.
10684 Before being stored away, the function ensures that the text has a
10685 headline, i.e. a first line that starts with a \"*\". If not, a headline
10686 is constructed from the current date and some additional data.
10688 If the variable `org-adapt-indentation' is non-nil, the entire text is
10689 also indented so that it starts in the same column as the headline
10690 \(i.e. after the stars).
10692 See also the variable `org-reverse-note-order'."
10693 (goto-char (point-min))
10694 (while (looking-at "^[ \t]*\n\\|^##.*\n")
10695 (replace-match ""))
10696 (catch 'quit
10697 (let* ((txt (buffer-substring (point-min) (point-max)))
10698 (fastp current-prefix-arg)
10699 (file (if fastp org-default-notes-file (org-get-org-file)))
10700 (heading org-remember-default-headline)
10701 (visiting (org-find-base-buffer-visiting file))
10702 (org-startup-folded nil)
10703 (org-startup-align-all-tables nil)
10704 (org-goto-start-pos 1)
10705 spos level indent reversed)
10706 ;; Modify text so that it becomes a nice subtree which can be inserted
10707 ;; into an org tree.
10708 (let* ((lines (split-string txt "\n"))
10709 first)
10710 (setq first (car lines) lines (cdr lines))
10711 (if (string-match "^\\*+" first)
10712 ;; Is already a headline
10713 (setq indent nil)
10714 ;; We need to add a headline: Use time and first buffer line
10715 (setq lines (cons first lines)
10716 first (concat "* " (current-time-string)
10717 " (" (remember-buffer-desc) ")")
10718 indent " "))
10719 (if (and org-adapt-indentation indent)
10720 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10721 (setq txt (concat first "\n"
10722 (mapconcat 'identity lines "\n"))))
10723 ;; Find the file
10724 (if (not visiting) (find-file-noselect file))
10725 (with-current-buffer (or visiting (get-file-buffer file))
10726 (save-excursion (and (goto-char (point-min))
10727 (not (re-search-forward "^\\* " nil t))
10728 (insert "\n* Notes\n")))
10729 (setq reversed (org-notes-order-reversed-p))
10730 (save-excursion
10731 (save-restriction
10732 (widen)
10734 ;; Find the default location
10735 (when (and heading (stringp heading) (string-match "\\S-" heading))
10736 (goto-char (point-min))
10737 (if (re-search-forward
10738 (concat "^\\*+[ \t]+" (regexp-quote heading)
10739 "\\([ \t]+:[@a-zA-Z0-9_:]*\\)?[ \t]*$")
10740 nil t)
10741 (setq org-goto-start-pos (match-beginning 0))))
10743 ;; Ask the User for a location
10744 (setq spos (if fastp
10745 org-goto-start-pos
10746 (org-get-location (current-buffer) org-remember-help)))
10747 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10748 ; not handle this note
10749 (goto-char spos)
10750 (cond ((and (bobp) (not reversed))
10751 ;; Put it at the end, one level below level 1
10752 (save-restriction
10753 (widen)
10754 (goto-char (point-max))
10755 (if (not (bolp)) (newline))
10756 (org-paste-subtree (org-get-legal-level 1 1) txt)))
10757 ((and (bobp) reversed)
10758 ;; Put it at the start, as level 1
10759 (save-restriction
10760 (widen)
10761 (goto-char (point-min))
10762 (re-search-forward "^\\*" nil t)
10763 (beginning-of-line 1)
10764 (org-paste-subtree 1 txt)))
10765 ((and (org-on-heading-p nil) (not current-prefix-arg))
10766 ;; Put it below this entry, at the beg/end of the subtree
10767 (org-back-to-heading t)
10768 (setq level (funcall outline-level))
10769 (if reversed
10770 (outline-end-of-heading)
10771 (org-end-of-subtree t))
10772 (if (not (bolp)) (newline))
10773 (beginning-of-line 1)
10774 (org-paste-subtree (org-get-legal-level level 1) txt))
10776 ;; Put it right there, with automatic level determined by
10777 ;; org-paste-subtree or from prefix arg
10778 (org-paste-subtree current-prefix-arg txt)))
10779 (when remember-save-after-remembering
10780 (save-buffer)
10781 (if (not visiting) (kill-buffer (current-buffer)))))))))
10782 t) ;; return t to indicate that we took care of this note.
10784 (defun org-get-org-file ()
10785 "Read a filename, with default directory `org-directory'."
10786 (let ((default (or org-default-notes-file remember-data-file)))
10787 (read-file-name (format "File name [%s]: " default)
10788 (file-name-as-directory org-directory)
10789 default)))
10791 (defun org-notes-order-reversed-p ()
10792 "Check if the current file should receive notes in reversed order."
10793 (cond
10794 ((not org-reverse-note-order) nil)
10795 ((eq t org-reverse-note-order) t)
10796 ((not (listp org-reverse-note-order)) nil)
10797 (t (catch 'exit
10798 (let ((all org-reverse-note-order)
10799 entry)
10800 (while (setq entry (pop all))
10801 (if (string-match (car entry) buffer-file-name)
10802 (throw 'exit (cdr entry))))
10803 nil)))))
10805 ;;;; Dynamic blocks
10807 (defun org-find-dblock (name)
10808 "Find the first dynamic block with name NAME in the buffer.
10809 If not found, stay at current position and return nil."
10810 (let (pos)
10811 (save-excursion
10812 (goto-char (point-min))
10813 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
10814 nil t)
10815 (match-beginning 0))))
10816 (if pos (goto-char pos))
10817 pos))
10819 (defconst org-dblock-start-re
10820 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
10821 "Matches the startline of a dynamic block, with parameters.")
10823 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
10824 "Matches the end of a dyhamic block.")
10826 (defun org-create-dblock (plist)
10827 "Create a dynamic block section, with parameters taken from PLIST.
10828 PLIST must containe a :name entry which is used as name of the block."
10829 (unless (bolp) (newline))
10830 (let ((name (plist-get plist :name)))
10831 (insert "#+BEGIN: " name)
10832 (while plist
10833 (if (eq (car plist) :name)
10834 (setq plist (cddr plist))
10835 (insert " " (prin1-to-string (pop plist)))))
10836 (insert "\n\n#+END:\n")
10837 (beginning-of-line -2)))
10839 (defun org-prepare-dblock ()
10840 "Prepare dynamic block for refresh.
10841 This empties the block, puts the cursor at the insert position and returns
10842 the property list including an extra property :name with the block name."
10843 (unless (looking-at org-dblock-start-re)
10844 (error "Not at a dynamic block"))
10845 (let* ((begdel (1+ (match-end 0)))
10846 (name (match-string 1))
10847 (params (append (list :name name)
10848 (read (concat "(" (match-string 3) ")")))))
10849 (unless (re-search-forward org-dblock-end-re nil t)
10850 (error "Dynamic block not terminated"))
10851 (delete-region begdel (match-beginning 0))
10852 (goto-char begdel)
10853 (open-line 1)
10854 params))
10856 (defun org-map-dblocks (&optional command)
10857 "Apply COMMAND to all dynamic blocks in the current buffer.
10858 If COMMAND is not given, use `org-update-dblock'."
10859 (let ((cmd (or command 'org-update-dblock))
10860 pos)
10861 (save-excursion
10862 (goto-char (point-min))
10863 (while (re-search-forward org-dblock-start-re nil t)
10864 (goto-char (setq pos (match-beginning 0)))
10865 (condition-case nil
10866 (funcall cmd)
10867 (error (message "Error during update of dynamic block")))
10868 (goto-char pos)
10869 (unless (re-search-forward org-dblock-end-re nil t)
10870 (error "Dynamic block not terminated"))))))
10872 (defun org-dblock-update (&optional arg)
10873 "User command for updating dynamic blocks.
10874 Update the dynamic block at point. With prefix ARG, update all dynamic
10875 blocks in the buffer."
10876 (interactive "P")
10877 (if arg
10878 (org-update-all-dblocks)
10879 (or (looking-at org-dblock-start-re)
10880 (org-beginning-of-dblock))
10881 (org-update-dblock)))
10883 (defun org-update-dblock ()
10884 "Update the dynamic block at point
10885 This means to empty the block, parse for parameters and then call
10886 the correct writing function."
10887 (let* ((pos (point))
10888 (params (org-prepare-dblock))
10889 (name (plist-get params :name))
10890 (cmd (intern (concat "org-dblock-write:" name))))
10891 (funcall cmd params)
10892 (goto-char pos)))
10894 (defun org-beginning-of-dblock ()
10895 "Find the beginning of the dynamic block at point.
10896 Error if there is no scuh block at point."
10897 (let ((pos (point))
10898 beg)
10899 (end-of-line 1)
10900 (if (and (re-search-backward org-dblock-start-re nil t)
10901 (setq beg (match-beginning 0))
10902 (re-search-forward org-dblock-end-re nil t)
10903 (> (match-end 0) pos))
10904 (goto-char beg)
10905 (goto-char pos)
10906 (error "Not in a dynamic block"))))
10908 (defun org-update-all-dblocks ()
10909 "Update all dynamic blocks in the buffer.
10910 This function can be used in a hook."
10911 (when (org-mode-p)
10912 (org-map-dblocks 'org-update-dblock)))
10915 ;;;; Completion
10917 (defun org-complete (&optional arg)
10918 "Perform completion on word at point.
10919 At the beginning of a headline, this completes TODO keywords as given in
10920 `org-todo-keywords'.
10921 If the current word is preceded by a backslash, completes the TeX symbols
10922 that are supported for HTML support.
10923 If the current word is preceded by \"#+\", completes special words for
10924 setting file options.
10925 In the line after \"#+STARTUP:, complete valid keywords.\"
10926 At all other locations, this simply calls `ispell-complete-word'."
10927 (interactive "P")
10928 (catch 'exit
10929 (let* ((end (point))
10930 (beg1 (save-excursion
10931 (skip-chars-backward "a-zA-Z_@0-9")
10932 (point)))
10933 (beg (save-excursion
10934 (skip-chars-backward "a-zA-Z0-9_:$")
10935 (point)))
10936 (confirm (lambda (x) (stringp (car x))))
10937 (searchhead (equal (char-before beg) ?*))
10938 (tag (equal (char-before beg1) ?:))
10939 (texp (equal (char-before beg) ?\\))
10940 (link (equal (char-before beg) ?\[))
10941 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10942 beg)
10943 "#+"))
10944 (startup (string-match "^#\\+STARTUP:.*"
10945 (buffer-substring (point-at-bol) (point))))
10946 (completion-ignore-case opt)
10947 (type nil)
10948 (tbl nil)
10949 (table (cond
10950 (opt
10951 (setq type :opt)
10952 (mapcar (lambda (x)
10953 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10954 (cons (match-string 2 x) (match-string 1 x)))
10955 (org-split-string (org-get-current-options) "\n")))
10956 (startup
10957 (setq type :startup)
10958 org-startup-options)
10959 (link (append org-link-abbrev-alist-local
10960 org-link-abbrev-alist))
10961 (texp
10962 (setq type :tex)
10963 org-html-entities)
10964 ((string-match "\\`\\*+[ \t]*\\'"
10965 (buffer-substring (point-at-bol) beg))
10966 (setq type :todo)
10967 (mapcar 'list org-todo-keywords))
10968 (searchhead
10969 (setq type :searchhead)
10970 (save-excursion
10971 (goto-char (point-min))
10972 (while (re-search-forward org-todo-line-regexp nil t)
10973 (push (list
10974 (org-make-org-heading-search-string
10975 (match-string 3) t))
10976 tbl)))
10977 tbl)
10978 (tag (setq type :tag beg beg1)
10979 (or org-tag-alist (org-get-buffer-tags)))
10980 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
10981 (pattern (buffer-substring-no-properties beg end))
10982 (completion (try-completion pattern table confirm)))
10983 (cond ((eq completion t)
10984 (if (equal type :opt)
10985 (insert (substring (cdr (assoc (upcase pattern) table))
10986 (length pattern)))
10987 (if (equal type :tag) (insert ":"))))
10988 ((null completion)
10989 (message "Can't find completion for \"%s\"" pattern)
10990 (ding))
10991 ((not (string= pattern completion))
10992 (delete-region beg end)
10993 (if (string-match " +$" completion)
10994 (setq completion (replace-match "" t t completion)))
10995 (insert completion)
10996 (if (get-buffer-window "*Completions*")
10997 (delete-window (get-buffer-window "*Completions*")))
10998 (if (assoc completion table)
10999 (if (eq type :todo) (insert " ")
11000 (if (eq type :tag) (insert ":"))))
11001 (if (and (equal type :opt) (assoc completion table))
11002 (message "%s" (substitute-command-keys
11003 "Press \\[org-complete] again to insert example settings"))))
11005 (message "Making completion list...")
11006 (let ((list (sort (all-completions pattern table confirm)
11007 'string<)))
11008 (with-output-to-temp-buffer "*Completions*"
11009 (condition-case nil
11010 ;; Protection needed for XEmacs and emacs 21
11011 (display-completion-list list pattern)
11012 (error (display-completion-list list)))))
11013 (message "Making completion list...%s" "done"))))))
11015 ;;;; TODO, DEADLINE, Comments
11017 (defun org-toggle-comment ()
11018 "Change the COMMENT state of an entry."
11019 (interactive)
11020 (save-excursion
11021 (org-back-to-heading)
11022 (if (looking-at (concat outline-regexp
11023 "\\( +\\<" org-comment-string "\\>\\)"))
11024 (replace-match "" t t nil 1)
11025 (if (looking-at outline-regexp)
11026 (progn
11027 (goto-char (match-end 0))
11028 (insert " " org-comment-string))))))
11030 (defvar org-last-todo-state-is-todo nil
11031 "This is non-nil when the last TODO state change led to a TODO state.
11032 If the last change removed the TODO tag or switched to DONE, then
11033 this is nil.")
11035 (defun org-todo (&optional arg)
11036 "Change the TODO state of an item.
11037 The state of an item is given by a keyword at the start of the heading,
11038 like
11039 *** TODO Write paper
11040 *** DONE Call mom
11042 The different keywords are specified in the variable `org-todo-keywords'.
11043 By default the available states are \"TODO\" and \"DONE\".
11044 So for this example: when the item starts with TODO, it is changed to DONE.
11045 When it starts with DONE, the DONE is removed. And when neither TODO nor
11046 DONE are present, add TODO at the beginning of the heading.
11048 With C-u prefix arg, use completion to determine the new state.
11049 With numeric prefix arg, switch to that state.
11051 For calling through lisp, arg is also interpreted in the following way:
11052 'none -> empty state
11053 \"\"(empty string) -> switch to empty state
11054 'done -> switch to DONE
11055 \"WAITING\" -> switch to the specified keyword, but only if it
11056 really is a member of `org-todo-keywords'."
11057 (interactive "P")
11058 (save-excursion
11059 (org-back-to-heading)
11060 (if (looking-at outline-regexp) (goto-char (match-end 0)))
11061 (or (looking-at (concat " +" org-todo-regexp " *"))
11062 (looking-at " *"))
11063 (let* ((this (match-string 1))
11064 (last-state (or this ""))
11065 (completion-ignore-case t)
11066 (member (member this org-todo-keywords))
11067 (tail (cdr member))
11068 (state (cond
11069 ((equal arg '(4))
11070 ;; Read a state with completion
11071 (completing-read "State: " (mapcar (lambda(x) (list x))
11072 org-todo-keywords)
11073 nil t))
11074 ((eq arg 'right)
11075 (if this
11076 (if tail (car tail) nil)
11077 (car org-todo-keywords)))
11078 ((eq arg 'left)
11079 (if (equal member org-todo-keywords)
11081 (if this
11082 (nth (- (length org-todo-keywords) (length tail) 2)
11083 org-todo-keywords)
11084 org-done-string)))
11085 (arg
11086 ;; user requests a specific state
11087 (cond
11088 ((equal arg "") nil)
11089 ((eq arg 'none) nil)
11090 ((eq arg 'done) (org-last org-todo-keywords))
11091 ((car (member arg org-todo-keywords)))
11092 ((nth (1- (prefix-numeric-value arg))
11093 org-todo-keywords))))
11094 ((null member) (car org-todo-keywords))
11095 ((null tail) nil) ;; -> first entry
11096 ((eq org-todo-interpretation 'sequence)
11097 (car tail))
11098 ((memq org-todo-interpretation '(type priority))
11099 (if (eq this-command last-command)
11100 (car tail)
11101 (if (> (length tail) 0) org-done-string nil)))
11102 (t nil)))
11103 (next (if state (concat " " state " ") " "))
11104 dostates)
11105 (replace-match next t t)
11106 (setq org-last-todo-state-is-todo
11107 (not (equal state org-done-string)))
11108 (when org-log-done
11109 (setq dostates (and (eq org-todo-interpretation 'sequence)
11110 (listp org-log-done) (memq 'state org-log-done)))
11111 (cond
11112 ((and state (not this))
11113 (org-add-planning-info nil nil 'closed)
11114 (and dostates (org-add-log-maybe 'state state 'findpos)))
11115 ((and state dostates)
11116 (org-add-log-maybe 'state state 'findpos))
11117 ((equal state org-done-string)
11118 ;; Planning info calls the note-setting command.
11119 (org-add-planning-info 'closed (org-current-time)
11120 (if (org-get-repeat) nil 'scheduled))
11121 (org-add-log-maybe 'done state 'findpos))))
11122 ;; Fixup tag positioning
11123 (and org-auto-align-tags (org-set-tags nil t))
11124 (run-hooks 'org-after-todo-state-change-hook)
11125 (and (equal state org-done-string) (org-auto-repeat-maybe))
11127 ;; Fixup cursor location if close to the keyword
11128 (if (and (outline-on-heading-p)
11129 (not (bolp))
11130 (save-excursion (beginning-of-line 1)
11131 (looking-at org-todo-line-regexp))
11132 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11133 (progn
11134 (goto-char (or (match-end 2) (match-end 1)))
11135 (just-one-space))))
11137 (defun org-get-repeat ()
11138 "Return the REPEAT statement of this entry."
11139 (save-match-data
11140 (save-excursion
11141 (org-back-to-heading t)
11142 (if (re-search-forward
11143 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
11144 (match-string 1)))))
11146 (defvar org-last-changed-timestamp)
11147 (defvar org-log-post-message)
11148 (defun org-auto-repeat-maybe ()
11149 "Check if the current headline contains a REPEAT key.
11150 If yes, set TODO state back to what it was and change any SCHEDULED
11151 or DEADLINE times the new date.
11152 This function should be run in the `org-after-todo-state-change-hook'."
11153 ;; last-state is dynamically scoped into this function
11154 (let ((repeat (org-get-repeat))
11155 (whata '(("d" . day) ("m" . month) ("y" . year)))
11156 (msg "Entry repeats: ")
11157 (org-log-done)
11158 re type n what start)
11159 (when repeat
11160 (org-todo (if (eq 'org-todo-interpretation 'type)
11161 last-state
11162 (car org-todo-keywords)))
11163 (unless (memq 'org-add-log-note (default-value 'post-command-hook))
11164 ;; Make sure a note is taken
11165 (let ((org-log-done '(done)))
11166 (org-add-log-maybe 'done org-done-string 'findpos)))
11167 (org-back-to-heading t)
11168 (org-add-planning-info nil nil 'closed)
11169 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11170 org-deadline-time-regexp "\\)"))
11171 (while (re-search-forward
11172 re (save-excursion (outline-next-heading) (point)) t)
11173 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
11174 start 0)
11175 (while (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" repeat start)
11176 (setq start (match-end 0)
11177 n (string-to-number (match-string 1 repeat))
11178 what (match-string 2 repeat))
11179 (if (equal what "w") (setq n (* n 7) what "d"))
11180 (org-timestamp-change n (cdr (assoc what whata))))
11181 (setq msg (concat msg type org-last-changed-timestamp " ")))
11182 (setq org-log-post-message msg)
11183 (message msg))))
11185 (defun org-show-todo-tree (arg)
11186 "Make a compact tree which shows all headlines marked with TODO.
11187 The tree will show the lines where the regexp matches, and all higher
11188 headlines above the match.
11189 With \\[universal-argument] prefix, also show the DONE entries.
11190 With a numeric prefix N, construct a sparse tree for the Nth element
11191 of `org-todo-keywords'."
11192 (interactive "P")
11193 (let ((case-fold-search nil)
11194 (kwd-re
11195 (cond ((null arg) org-not-done-regexp)
11196 ((equal arg '(4)) org-todo-regexp)
11197 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
11198 (regexp-quote (nth (1- (prefix-numeric-value arg))
11199 org-todo-keywords)))
11200 (t (error "Invalid prefix argument: %s" arg)))))
11201 (message "%d TODO entries found"
11202 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
11204 (defun org-deadline ()
11205 "Insert the DEADLINE: string to make a deadline.
11206 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11207 to modify it to the correct date."
11208 (interactive)
11209 (org-add-planning-info 'deadline nil 'closed))
11211 (defun org-schedule ()
11212 "Insert the SCHEDULED: string to schedule a TODO item.
11213 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11214 to modify it to the correct date."
11215 (interactive)
11216 (org-add-planning-info 'scheduled nil 'closed))
11218 (defun org-add-planning-info (what &optional time &rest remove)
11219 "Insert new timestamp with keyword in the line directly after the headline.
11220 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11221 If non is given, the user is prompted for a date.
11222 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11223 be removed."
11224 (interactive)
11225 (let (org-time-was-given)
11226 (when what (setq time (or time (org-read-date nil 'to-time))))
11227 (when (and org-insert-labeled-timestamps-at-point
11228 (member what '(scheduled deadline)))
11229 (insert
11230 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11231 (org-insert-time-stamp time org-time-was-given)
11232 (setq what nil))
11233 (save-excursion
11234 (save-restriction
11235 (let (col list elt ts buffer-invisibility-spec)
11236 (org-back-to-heading t)
11237 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11238 (goto-char (match-end 1))
11239 (setq col (current-column))
11240 (goto-char (1+ (match-end 0)))
11241 (if (and (not (looking-at outline-regexp))
11242 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11243 "[^\r\n]*"))
11244 (not (equal (match-string 1) org-clock-string)))
11245 (narrow-to-region (match-beginning 0) (match-end 0))
11246 (insert "\n")
11247 (backward-char 1)
11248 (narrow-to-region (point) (point))
11249 (indent-to-column col))
11250 ;; Check if we have to remove something.
11251 (setq list (cons what remove))
11252 (while list
11253 (setq elt (pop list))
11254 (goto-char (point-min))
11255 (when (or (and (eq elt 'scheduled)
11256 (re-search-forward org-scheduled-time-regexp nil t))
11257 (and (eq elt 'deadline)
11258 (re-search-forward org-deadline-time-regexp nil t))
11259 (and (eq elt 'closed)
11260 (re-search-forward org-closed-time-regexp nil t)))
11261 (replace-match "")
11262 (if (looking-at "--+<[^>]+>") (replace-match ""))
11263 (if (looking-at " +") (replace-match ""))))
11264 (goto-char (point-max))
11265 (when what
11266 (insert
11267 (if (not (equal (char-before) ?\ )) " " "")
11268 (cond ((eq what 'scheduled) org-scheduled-string)
11269 ((eq what 'deadline) org-deadline-string)
11270 ((eq what 'closed) org-closed-string))
11271 " ")
11272 (org-insert-time-stamp time
11273 (or org-time-was-given (eq what 'closed))
11274 (eq what 'closed))
11275 (end-of-line 1))
11276 (goto-char (point-min))
11277 (widen)
11278 (if (looking-at "[ \t]+\r?\n")
11279 (replace-match ""))
11280 ts)))))
11282 (defvar org-log-note-marker (make-marker))
11283 (defvar org-log-note-purpose nil)
11284 (defvar org-log-note-state nil)
11285 (defvar org-log-note-window-configuration nil)
11286 (defvar org-log-note-return-to (make-marker))
11287 (defvar org-log-post-message nil
11288 "Message to be displayed after a log note has been stored.
11289 The auto-repeater uses this.")
11291 (defun org-add-log-maybe (&optional purpose state findpos)
11292 (save-excursion
11293 (when (and (listp org-log-done)
11294 (memq purpose org-log-done))
11295 (when findpos
11296 (org-back-to-heading t)
11297 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11298 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11299 "[^\r\n]*\\)?"))
11300 (goto-char (match-end 0)))
11301 (move-marker org-log-note-marker (point))
11302 (setq org-log-note-purpose purpose)
11303 (setq org-log-note-state state)
11304 (add-hook 'post-command-hook 'org-add-log-note 'append))))
11306 (defun org-add-log-note (&optional purpose)
11307 "Pop up a window for taking a note, and add this note later at point."
11308 (remove-hook 'post-command-hook 'org-add-log-note)
11309 (setq org-log-note-window-configuration (current-window-configuration))
11310 (delete-other-windows)
11311 (move-marker org-log-note-return-to (point))
11312 (switch-to-buffer (marker-buffer org-log-note-marker))
11313 (goto-char org-log-note-marker)
11314 (switch-to-buffer-other-window "*Org Note*")
11315 (erase-buffer)
11316 (let ((org-inhibit-startup t)) (org-mode))
11317 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
11318 (cond
11319 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11320 ((eq org-log-note-purpose 'done) "closed todo item")
11321 ((eq org-log-note-purpose 'state) "state change")
11322 (t (error "This should not happen")))))
11323 (org-set-local 'org-finish-function 'org-store-log-note))
11325 (defun org-store-log-note ()
11326 "Finish taking a log note, and insert it to where it belongs."
11327 (let ((txt (buffer-string))
11328 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11329 lines ind)
11330 (kill-buffer (current-buffer))
11331 (if (string-match "^#.*\n[ \t\n]*" txt)
11332 (setq txt (replace-match "" t t txt)))
11333 (if (string-match "\\s-+\\'" txt)
11334 (setq txt (replace-match "" t t txt)))
11335 (setq lines (org-split-string txt "\n"))
11336 (when (and note (string-match "\\S-" note))
11337 (setq note
11338 (org-replace-escapes
11339 note
11340 (list (cons "%u" (user-login-name))
11341 (cons "%U" user-full-name)
11342 (cons "%t" (format-time-string
11343 (org-time-stamp-format 'long 'inactive)
11344 (current-time)))
11345 (cons "%s" (if org-log-note-state
11346 (concat "\"" org-log-note-state "\"")
11347 "")))))
11348 (if lines (setq note (concat note " \\\\")))
11349 (push note lines))
11350 (save-excursion
11351 (set-buffer (marker-buffer org-log-note-marker))
11352 (save-excursion
11353 (goto-char org-log-note-marker)
11354 (move-marker org-log-note-marker nil)
11355 (end-of-line 1)
11356 (if (not (bolp)) (insert "\n")) (indent-relative nil)
11357 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
11358 (insert " - " (pop lines))
11359 (while lines
11360 (insert "\n" ind (pop lines))))))
11361 (set-window-configuration org-log-note-window-configuration)
11362 (with-current-buffer (marker-buffer org-log-note-return-to)
11363 (goto-char org-log-note-return-to))
11364 (move-marker org-log-note-return-to nil)
11365 (and org-log-post-message (message org-log-post-message)))
11367 (defvar org-occur-highlights nil)
11368 (make-variable-buffer-local 'org-occur-highlights)
11370 (defun org-occur (regexp &optional keep-previous callback)
11371 "Make a compact tree which shows all matches of REGEXP.
11372 The tree will show the lines where the regexp matches, and all higher
11373 headlines above the match. It will also show the heading after the match,
11374 to make sure editing the matching entry is easy.
11375 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11376 call to `org-occur' will be kept, to allow stacking of calls to this
11377 command.
11378 If CALLBACK is non-nil, it is a function which is called to confirm
11379 that the match should indeed be shown."
11380 (interactive "sRegexp: \nP")
11381 (or keep-previous (org-remove-occur-highlights nil nil t))
11382 (let ((cnt 0))
11383 (save-excursion
11384 (goto-char (point-min))
11385 (if (or (not keep-previous) ; do not want to keep
11386 (not org-occur-highlights)) ; no previous matches
11387 ;; hide everything
11388 (org-overview))
11389 (while (re-search-forward regexp nil t)
11390 (when (or (not callback)
11391 (save-match-data (funcall callback)))
11392 (setq cnt (1+ cnt))
11393 (org-highlight-new-match (match-beginning 0) (match-end 0))
11394 (org-show-context 'occur-tree))))
11395 (when org-remove-highlights-with-change
11396 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11397 nil 'local))
11398 (unless org-sparse-tree-open-archived-trees
11399 (org-hide-archived-subtrees (point-min) (point-max)))
11400 (run-hooks 'org-occur-hook)
11401 (if (interactive-p)
11402 (message "%d match(es) for regexp %s" cnt regexp))
11403 cnt))
11405 (defun org-show-context (&optional key)
11406 "Make sure point and context and visible.
11407 How much context is shown depends upon the variables
11408 `org-show-hierarchy-above', `org-show-following-heading'. and
11409 `org-show-siblings'."
11410 (let ((heading-p (org-on-heading-p t))
11411 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11412 (following-p (org-get-alist-option org-show-following-heading key))
11413 (siblings-p (org-get-alist-option org-show-siblings key)))
11414 (catch 'exit
11415 ;; Show heading or entry text
11416 (if heading-p
11417 (org-flag-heading nil) ; only show the heading
11418 (and (or (org-invisible-p) (org-invisible-p2))
11419 (org-show-hidden-entry))) ; show entire entry
11420 (when following-p
11421 ;; Show next sibling, or heading below text
11422 (save-excursion
11423 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11424 (org-flag-heading nil))))
11425 (when siblings-p (org-show-siblings))
11426 (when hierarchy-p
11427 ;; show all higher headings, possibly with siblings
11428 (save-excursion
11429 (while (and (condition-case nil
11430 (progn (org-up-heading-all 1) t)
11431 (error nil))
11432 (not (bobp)))
11433 (org-flag-heading nil)
11434 (when siblings-p (org-show-siblings))))))))
11436 (defun org-reveal (&optional siblings)
11437 "Show current entry, hierarchy above it, and the following headline.
11438 This can be used to show a consistent set of context around locations
11439 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11440 not t for the search context.
11442 With optional argument SIBLINGS, on each level of the hierarchy all
11443 siblings are shown. This repairs the tree structure to what it would
11444 look like when opened with hierarchical calls to `org-cycle'."
11445 (interactive "P")
11446 (let ((org-show-hierarchy-above t)
11447 (org-show-following-heading t)
11448 (org-show-siblings (if siblings t org-show-siblings)))
11449 (org-show-context nil)))
11451 (defun org-highlight-new-match (beg end)
11452 "Highlight from BEG to END and mark the highlight is an occur headline."
11453 (let ((ov (org-make-overlay beg end)))
11454 (org-overlay-put ov 'face 'secondary-selection)
11455 (push ov org-occur-highlights)))
11457 (defun org-remove-occur-highlights (&optional beg end noremove)
11458 "Remove the occur highlights from the buffer.
11459 BEG and END are ignored. If NOREMOVE is nil, remove this function
11460 from the `before-change-functions' in the current buffer."
11461 (interactive)
11462 (unless org-inhibit-highlight-removal
11463 (mapc 'org-delete-overlay org-occur-highlights)
11464 (setq org-occur-highlights nil)
11465 (unless noremove
11466 (remove-hook 'before-change-functions
11467 'org-remove-occur-highlights 'local))))
11469 ;;;; Priorities
11471 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
11472 "Regular expression matching the priority indicator.")
11474 (defvar org-remove-priority-next-time nil)
11476 (defun org-priority-up ()
11477 "Increase the priority of the current item."
11478 (interactive)
11479 (org-priority 'up))
11481 (defun org-priority-down ()
11482 "Decrease the priority of the current item."
11483 (interactive)
11484 (org-priority 'down))
11486 (defun org-priority (&optional action)
11487 "Change the priority of an item by ARG.
11488 ACTION can be set, up, or down."
11489 (interactive)
11490 (setq action (or action 'set))
11491 (let (current new news have remove)
11492 (save-excursion
11493 (org-back-to-heading)
11494 (if (looking-at org-priority-regexp)
11495 (setq current (string-to-char (match-string 2))
11496 have t)
11497 (setq current org-default-priority))
11498 (cond
11499 ((eq action 'set)
11500 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
11501 (setq new (read-char-exclusive))
11502 (cond ((equal new ?\ ) (setq remove t))
11503 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
11504 (error "Priority must be between `%c' and `%c'"
11505 ?A org-lowest-priority))))
11506 ((eq action 'up)
11507 (setq new (1- current)))
11508 ((eq action 'down)
11509 (setq new (1+ current)))
11510 (t (error "Invalid action")))
11511 (setq new (min (max ?A (upcase new)) org-lowest-priority))
11512 (setq news (format "%c" new))
11513 (if have
11514 (if remove
11515 (replace-match "" t t nil 1)
11516 (replace-match news t t nil 2))
11517 (if remove
11518 (error "No priority cookie found in line")
11519 (looking-at org-todo-line-regexp)
11520 (if (match-end 2)
11521 (progn
11522 (goto-char (match-end 2))
11523 (insert " [#" news "]"))
11524 (goto-char (match-beginning 3))
11525 (insert "[#" news "] ")))))
11526 (if remove
11527 (message "Priority removed")
11528 (message "Priority of current item set to %s" news))))
11531 (defun org-get-priority (s)
11532 "Find priority cookie and return priority."
11533 (save-match-data
11534 (if (not (string-match org-priority-regexp s))
11535 (* 1000 (- org-lowest-priority org-default-priority))
11536 (* 1000 (- org-lowest-priority
11537 (string-to-char (match-string 2 s)))))))
11539 ;;;; Tags
11541 (defun org-scan-tags (action matcher &optional todo-only)
11542 "Scan headline tags with inheritance and produce output ACTION.
11543 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
11544 evaluated, testing if a given set of tags qualifies a headline for
11545 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
11546 are included in the output."
11547 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
11548 (mapconcat 'regexp-quote
11549 (nreverse (cdr (reverse org-todo-keywords)))
11550 "\\|")
11551 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
11552 (props (list 'face nil
11553 'done-face 'org-done
11554 'undone-face nil
11555 'mouse-face 'highlight
11556 'org-not-done-regexp org-not-done-regexp
11557 'keymap org-agenda-keymap
11558 'help-echo
11559 (format "mouse-2 or RET jump to org file %s"
11560 (abbreviate-file-name buffer-file-name))))
11561 (case-fold-search nil)
11562 lspos
11563 tags tags-list tags-alist (llast 0) rtn level category i txt
11564 todo marker entry priority)
11565 (save-excursion
11566 (goto-char (point-min))
11567 (when (eq action 'sparse-tree) (org-overview))
11568 (while (re-search-forward re nil t)
11569 (catch :skip
11570 (setq todo (if (match-end 1) (match-string 2))
11571 tags (if (match-end 4) (match-string 4)))
11572 (goto-char (setq lspos (1+ (match-beginning 0))))
11573 (setq level (funcall outline-level)
11574 category (org-get-category))
11575 (setq i llast llast level)
11576 ;; remove tag lists from same and sublevels
11577 (while (>= i level)
11578 (when (setq entry (assoc i tags-alist))
11579 (setq tags-alist (delete entry tags-alist)))
11580 (setq i (1- i)))
11581 ;; add the nex tags
11582 (when tags
11583 (setq tags (mapcar 'downcase (org-split-string tags ":"))
11584 tags-alist
11585 (cons (cons level tags) tags-alist)))
11586 ;; compile tags for current headline
11587 (setq tags-list
11588 (if org-use-tag-inheritance
11589 (apply 'append (mapcar 'cdr tags-alist))
11590 tags))
11591 (when (and (or (not todo-only) todo)
11592 (eval matcher)
11593 (or (not org-agenda-skip-archived-trees)
11594 (not (member org-archive-tag tags-list))))
11595 (and (eq action 'agenda) (org-agenda-skip))
11596 ;; list this headline
11597 (if (eq action 'sparse-tree)
11598 (progn
11599 (org-show-context 'tags-tree))
11600 (setq txt (org-format-agenda-item
11602 (concat
11603 (if org-tags-match-list-sublevels
11604 (make-string (1- level) ?.) "")
11605 (org-get-heading))
11606 category tags-list)
11607 priority (org-get-priority txt))
11608 (goto-char lspos)
11609 (setq marker (org-agenda-new-marker))
11610 (org-add-props txt props
11611 'org-marker marker 'org-hd-marker marker 'org-category category
11612 'priority priority)
11613 (push txt rtn))
11614 ;; if we are to skip sublevels, jump to end of subtree
11615 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
11616 (when (and (eq action 'sparse-tree)
11617 (not org-sparse-tree-open-archived-trees))
11618 (org-hide-archived-subtrees (point-min) (point-max)))
11619 (nreverse rtn)))
11621 (defvar todo-only) ;; dynamically scoped
11623 (defun org-tags-sparse-tree (&optional todo-only match)
11624 "Create a sparse tree according to tags string MATCH.
11625 MATCH can contain positive and negative selection of tags, like
11626 \"+WORK+URGENT-WITHBOSS\".
11627 If optional argument TODO_ONLY is non-nil, only select lines that are
11628 also TODO lines."
11629 (interactive "P")
11630 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11632 (defun org-make-tags-matcher (match)
11633 "Create the TAGS//TODO matcher form for the selection string MATCH."
11634 ;; todo-only is scoped dynamically into this function, and the function
11635 ;; may change it it the matcher asksk for it.
11636 (unless match
11637 ;; Get a new match request, with completion
11638 (setq org-last-tags-completion-table
11639 (or org-tag-alist
11640 org-last-tags-completion-table))
11641 (setq match (completing-read
11642 "Match: " 'org-tags-completion-function nil nil nil
11643 'org-tags-history)))
11645 ;; Parse the string and create a lisp form
11646 (let ((match0 match)
11647 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[A-Za-z_@0-9]+\\)")
11648 minus tag mm
11649 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11650 orterms term orlist re-p level-p)
11651 (if (string-match "/+" match)
11652 ;; match contains also a todo-matching request
11653 (progn
11654 (setq tagsmatch (substring match 0 (match-beginning 0))
11655 todomatch (substring match (match-end 0)))
11656 (if (string-match "^!" todomatch)
11657 (setq todo-only t todomatch (substring todomatch 1)))
11658 (if (string-match "^\\s-*$" todomatch)
11659 (setq todomatch nil)))
11660 ;; only matching tags
11661 (setq tagsmatch match todomatch nil))
11663 ;; Make the tags matcher
11664 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11665 (setq tagsmatcher t)
11666 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11667 (while (setq term (pop orterms))
11668 (while (and (equal (substring term -1) "\\") orterms)
11669 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11670 (while (string-match re term)
11671 (setq minus (and (match-end 1)
11672 (equal (match-string 1 term) "-"))
11673 tag (match-string 2 term)
11674 re-p (equal (string-to-char tag) ?{)
11675 level-p (match-end 3)
11676 mm (cond
11677 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11678 (level-p `(= level ,(string-to-number
11679 (match-string 3 term))))
11680 (t `(member ,(downcase tag) tags-list)))
11681 mm (if minus (list 'not mm) mm)
11682 term (substring term (match-end 0)))
11683 (push mm tagsmatcher))
11684 (push (if (> (length tagsmatcher) 1)
11685 (cons 'and tagsmatcher)
11686 (car tagsmatcher))
11687 orlist)
11688 (setq tagsmatcher nil))
11689 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
11691 ;; Make the todo matcher
11692 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11693 (setq todomatcher t)
11694 (setq orterms (org-split-string todomatch "|") orlist nil)
11695 (while (setq term (pop orterms))
11696 (while (string-match re term)
11697 (setq minus (and (match-end 1)
11698 (equal (match-string 1 term) "-"))
11699 kwd (match-string 2 term)
11700 re-p (equal (string-to-char kwd) ?{)
11701 term (substring term (match-end 0))
11702 mm (if re-p
11703 `(string-match ,(substring kwd 1 -1) todo)
11704 (list 'equal 'todo kwd))
11705 mm (if minus (list 'not mm) mm))
11706 (push mm todomatcher))
11707 (push (if (> (length todomatcher) 1)
11708 (cons 'and todomatcher)
11709 (car todomatcher))
11710 orlist)
11711 (setq todomatcher nil))
11712 (setq todomatcher (if (> (length orlist) 1)
11713 (cons 'or orlist) (car orlist))))
11715 ;; Return the string and lisp forms of the matcher
11716 (setq matcher (if todomatcher
11717 (list 'and tagsmatcher todomatcher)
11718 tagsmatcher))
11719 (cons match0 matcher)))
11721 (defun org-match-any-p (re list)
11722 "Does re match any element of list?"
11723 (setq list (mapcar (lambda (x) (string-match re x)) list))
11724 (delq nil list))
11726 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
11727 (defvar org-tags-overlay (org-make-overlay 1 1))
11728 (org-detach-overlay org-tags-overlay)
11730 (defun org-set-tags (&optional arg just-align)
11731 "Set the tags for the current headline.
11732 With prefix ARG, realign all tags in headings in the current buffer."
11733 (interactive "P")
11734 (let* ((re (concat "^" outline-regexp))
11735 (current (org-get-tags))
11736 table current-tags inherited-tags ; computed below when needed
11737 tags p0 c0 c1 rpl)
11738 (if arg
11739 (save-excursion
11740 (goto-char (point-min))
11741 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11742 (while (re-search-forward re nil t)
11743 (org-set-tags nil t)
11744 (end-of-line 1)))
11745 (message "All tags realigned to column %d" org-tags-column))
11746 (if just-align
11747 (setq tags current)
11748 ;; Get a new set of tags from the user
11749 (save-excursion
11750 (setq table (or org-tag-alist (org-get-buffer-tags))
11751 org-last-tags-completion-table table
11752 current-tags (org-split-string current ":")
11753 inherited-tags (nreverse
11754 (nthcdr (length current-tags)
11755 (nreverse (org-get-tags-at))))
11756 tags
11757 (if (or (eq t org-use-fast-tag-selection)
11758 (and org-use-fast-tag-selection
11759 (delq nil (mapcar 'cdr table))))
11760 (org-fast-tag-selection current-tags inherited-tags table)
11761 (let ((org-add-colon-after-tag-completion t))
11762 (org-trim
11763 (completing-read "Tags: " 'org-tags-completion-function
11764 nil nil current 'org-tags-history))))))
11765 (while (string-match "[-+&]+" tags)
11766 ;; No boolean logic, just a list
11767 (setq tags (replace-match ":" t t tags))))
11769 (if (string-match "\\`[\t ]*\\'" tags)
11770 (setq tags "")
11771 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11772 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11774 ;; Insert new tags at the correct column
11775 (beginning-of-line 1)
11776 (if (re-search-forward
11777 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11778 (point-at-eol) t)
11779 (progn
11780 (if (equal tags "")
11781 (setq rpl "")
11782 (goto-char (match-beginning 0))
11783 (setq c0 (current-column) p0 (point)
11784 c1 (max (1+ c0) (if (> org-tags-column 0)
11785 org-tags-column
11786 (- (- org-tags-column) (length tags))))
11787 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11788 (replace-match rpl t t)
11789 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
11790 tags)
11791 (error "Tags alignment failed")))))
11793 (defun org-tags-completion-function (string predicate &optional flag)
11794 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11795 (confirm (lambda (x) (stringp (car x)))))
11796 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11797 (setq s1 (match-string 1 string)
11798 s2 (match-string 2 string))
11799 (setq s1 "" s2 string))
11800 (cond
11801 ((eq flag nil)
11802 ;; try completion
11803 (setq rtn (try-completion s2 ctable confirm))
11804 (if (stringp rtn)
11805 (concat s1 s2 (substring rtn (length s2))
11806 (if (and org-add-colon-after-tag-completion
11807 (assoc rtn ctable))
11808 ":" "")))
11810 ((eq flag t)
11811 ;; all-completions
11812 (all-completions s2 ctable confirm)
11814 ((eq flag 'lambda)
11815 ;; exact match?
11816 (assoc s2 ctable)))
11819 (defun org-fast-tag-insert (kwd tags face &optional end)
11820 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
11821 (insert (format "%-12s" (concat kwd ":"))
11822 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11823 (or end "")))
11825 (defun org-fast-tag-show-exit (flag)
11826 (save-excursion
11827 (goto-line 3)
11828 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11829 (replace-match ""))
11830 (when flag
11831 (end-of-line 1)
11832 (move-to-column (- (window-width) 19) t)
11833 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11835 (defun org-set-current-tags-overlay (current prefix)
11836 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11837 (if (featurep 'xemacs)
11838 (org-overlay-display org-tags-overlay (concat prefix s)
11839 'secondary-selection)
11840 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11841 (org-overlay-display org-tags-overlay (concat prefix s)))))
11843 (defun org-fast-tag-selection (current inherited table)
11844 "Fast tag selection with single keys.
11845 CURRENT is the current list of tags in the headline, INHERITED is the
11846 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11847 possibly with grouping information.
11848 If the keys are nil, a-z are automatically assigned.
11849 Returns the new tags string, or nil to not change the current settings."
11850 (let* ((maxlen (apply 'max (mapcar
11851 (lambda (x)
11852 (if (stringp (car x)) (string-width (car x)) 0))
11853 table)))
11854 (buf (current-buffer))
11855 (expert (eq org-fast-tag-selection-single-key 'expert))
11856 (buffer-tags nil)
11857 (fwidth (+ maxlen 3 1 3))
11858 (ncol (/ (- (window-width) 4) fwidth))
11859 (i-face 'org-done)
11860 (c-face 'org-tag)
11861 tg cnt e c char c1 c2 ntable tbl rtn
11862 ov-start ov-end ov-prefix
11863 (exit-after-next org-fast-tag-selection-single-key)
11864 groups ingroup)
11865 (save-excursion
11866 (beginning-of-line 1)
11867 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
11868 (setq ov-start (match-beginning 1)
11869 ov-end (match-end 1)
11870 ov-prefix "")
11871 (setq ov-start (1- (point-at-eol))
11872 ov-end (1+ ov-start))
11873 (skip-chars-forward "^\n\r")
11874 (setq ov-prefix
11875 (concat
11876 (buffer-substring (1- (point)) (point))
11877 (if (> (current-column) org-tags-column)
11879 (make-string (- org-tags-column (current-column)) ?\ ))))))
11880 (org-move-overlay org-tags-overlay ov-start ov-end)
11881 (save-window-excursion
11882 (if expert
11883 (set-buffer (get-buffer-create " *Org tags*"))
11884 (delete-other-windows)
11885 (split-window-vertically)
11886 (switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11887 (erase-buffer)
11888 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11889 (org-fast-tag-insert "Current" current c-face "\n\n")
11890 (org-fast-tag-show-exit exit-after-next)
11891 (org-set-current-tags-overlay current ov-prefix)
11892 (setq tbl table char ?a cnt 0)
11893 (while (setq e (pop tbl))
11894 (cond
11895 ((equal e '(:startgroup))
11896 (push '() groups) (setq ingroup t)
11897 (when (not (= cnt 0))
11898 (setq cnt 0)
11899 (insert "\n"))
11900 (insert "{ "))
11901 ((equal e '(:endgroup))
11902 (setq ingroup nil cnt 0)
11903 (insert "}\n"))
11905 (setq tg (car e) c2 nil)
11906 (if (cdr e)
11907 (setq c (cdr e))
11908 ;; automatically assign a character.
11909 (setq c1 (string-to-char
11910 (downcase (substring
11911 tg (if (= (string-to-char tg) ?@) 1 0)))))
11912 (if (or (rassoc c1 ntable) (rassoc c1 table))
11913 (while (or (rassoc char ntable) (rassoc char table))
11914 (setq char (1+ char)))
11915 (setq c2 c1))
11916 (setq c (or c2 char)))
11917 (if ingroup (push tg (car groups)))
11918 (setq tg (org-add-props tg nil 'face
11919 (cond
11920 ((member tg current) c-face)
11921 ((member tg inherited) i-face)
11922 (t nil))))
11923 (if (and (= cnt 0) (not ingroup)) (insert " "))
11924 (insert "[" c "] " tg (make-string
11925 (- fwidth 4 (length tg)) ?\ ))
11926 (push (cons tg c) ntable)
11927 (when (= (setq cnt (1+ cnt)) ncol)
11928 (insert "\n")
11929 (if ingroup (insert " "))
11930 (setq cnt 0)))))
11931 (setq ntable (nreverse ntable))
11932 (insert "\n")
11933 (goto-char (point-min))
11934 (if (and (not expert) (fboundp 'fit-window-to-buffer))
11935 (fit-window-to-buffer))
11936 (setq rtn
11937 (catch 'exit
11938 (while t
11939 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11940 (if groups " [!] no groups" " [!]groups")
11941 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11942 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11943 (cond
11944 ((= c ?\r) (throw 'exit t))
11945 ((= c ?!)
11946 (setq groups (not groups))
11947 (goto-char (point-min))
11948 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11949 ((= c ?\C-c)
11950 (if (not expert)
11951 (org-fast-tag-show-exit
11952 (setq exit-after-next (not exit-after-next)))
11953 (setq expert nil)
11954 (delete-other-windows)
11955 (split-window-vertically)
11956 (switch-to-buffer-other-window " *Org tags*")
11957 (and (fboundp 'fit-window-to-buffer)
11958 (fit-window-to-buffer))))
11959 ((or (= c ?\C-g)
11960 (and (= c ?q) (not (rassoc c ntable))))
11961 (org-detach-overlay org-tags-overlay)
11962 (setq quit-flag t))
11963 ((= c ?\ )
11964 (setq current nil)
11965 (if exit-after-next (setq exit-after-next 'now)))
11966 ((= c ?\t)
11967 (condition-case nil
11968 (setq tg (completing-read
11969 "Tag: "
11970 (or buffer-tags
11971 (with-current-buffer buf
11972 (org-get-buffer-tags)))))
11973 (quit (setq tg "")))
11974 (when (string-match "\\S-" tg)
11975 (add-to-list 'buffer-tags (list tg))
11976 (if (member tg current)
11977 (setq current (delete tg current))
11978 (push tg current)))
11979 (if exit-after-next (setq exit-after-next 'now)))
11980 ((setq e (rassoc c ntable) tg (car e))
11981 (if (member tg current)
11982 (setq current (delete tg current))
11983 (loop for g in groups do
11984 (if (member tg g)
11985 (mapcar (lambda (x)
11986 (setq current (delete x current)))
11987 g)))
11988 (push tg current))
11989 (if exit-after-next (setq exit-after-next 'now))))
11991 ;; Create a sorted list
11992 (setq current
11993 (sort current
11994 (lambda (a b)
11995 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11996 (if (eq exit-after-next 'now) (throw 'exit t))
11997 (goto-char (point-min))
11998 (beginning-of-line 2)
11999 (delete-region (point) (point-at-eol))
12000 (org-fast-tag-insert "Current" current c-face)
12001 (org-set-current-tags-overlay current ov-prefix)
12002 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
12003 (setq tg (match-string 1))
12004 (add-text-properties (match-beginning 1) (match-end 1)
12005 (list 'face
12006 (cond
12007 ((member tg current) c-face)
12008 ((member tg inherited) i-face)
12009 (t nil)))))
12010 (goto-char (point-min)))))
12011 (org-detach-overlay org-tags-overlay)
12012 (if rtn
12013 (mapconcat 'identity current ":")
12014 nil))))
12016 (defun org-get-tags ()
12017 "Get the TAGS string in the current headline."
12018 (unless (org-on-heading-p t)
12019 (error "Not on a heading"))
12020 (save-excursion
12021 (beginning-of-line 1)
12022 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
12023 (org-match-string-no-properties 1)
12024 "")))
12026 (defun org-get-buffer-tags ()
12027 "Get a table of all tags used in the buffer, for completion."
12028 (let (tags)
12029 (save-excursion
12030 (goto-char (point-min))
12031 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
12032 (mapc (lambda (x) (add-to-list 'tags x))
12033 (org-split-string (org-match-string-no-properties 1) ":"))))
12034 (mapcar 'list tags)))
12036 ;;;; Timestamps
12038 (defvar org-last-changed-timestamp nil)
12039 (defvar org-time-was-given) ; dynamically scoped parameter
12040 (defvar org-ts-what) ; dynamically scoped parameter
12042 (defun org-time-stamp (arg)
12043 "Prompt for a date/time and insert a time stamp.
12044 If the user specifies a time like HH:MM, or if this command is called
12045 with a prefix argument, the time stamp will contain date and time.
12046 Otherwise, only the date will be included. All parts of a date not
12047 specified by the user will be filled in from the current date/time.
12048 So if you press just return without typing anything, the time stamp
12049 will represent the current date/time. If there is already a timestamp
12050 at the cursor, it will be modified."
12051 (interactive "P")
12052 (let (org-time-was-given time)
12053 (cond
12054 ((and (org-at-timestamp-p)
12055 (eq last-command 'org-time-stamp)
12056 (eq this-command 'org-time-stamp))
12057 (insert "--")
12058 (setq time (let ((this-command this-command))
12059 (org-read-date arg 'totime)))
12060 (org-insert-time-stamp time (or org-time-was-given arg)))
12061 ((org-at-timestamp-p)
12062 (setq time (let ((this-command this-command))
12063 (org-read-date arg 'totime)))
12064 (when (org-at-timestamp-p) ; just to get the match data
12065 (replace-match "")
12066 (setq org-last-changed-timestamp
12067 (org-insert-time-stamp time (or org-time-was-given arg))))
12068 (message "Timestamp updated"))
12070 (setq time (let ((this-command this-command))
12071 (org-read-date arg 'totime)))
12072 (org-insert-time-stamp time (or org-time-was-given arg))))))
12074 (defun org-time-stamp-inactive (&optional arg)
12075 "Insert an inactive time stamp.
12076 An inactive time stamp is enclosed in square brackets instead of angle
12077 brackets. It is inactive in the sense that it does not trigger agenda entries,
12078 does not link to the calendar and cannot be changed with the S-cursor keys.
12079 So these are more for recording a certain time/date."
12080 (interactive "P")
12081 (let (org-time-was-given time)
12082 (setq time (org-read-date arg 'totime))
12083 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
12085 (defvar org-date-ovl (org-make-overlay 1 1))
12086 (org-overlay-put org-date-ovl 'face 'org-warning)
12087 (org-detach-overlay org-date-ovl)
12089 (defvar org-ans1) ; dynamically scoped parameter
12090 (defvar org-ans2) ; dynamically scoped parameter
12092 (defun org-read-date (&optional with-time to-time from-string prompt)
12093 "Read a date and make things smooth for the user.
12094 The prompt will suggest to enter an ISO date, but you can also enter anything
12095 which will at least partially be understood by `parse-time-string'.
12096 Unrecognized parts of the date will default to the current day, month, year,
12097 hour and minute. For example,
12098 3-2-5 --> 2003-02-05
12099 feb 15 --> currentyear-02-15
12100 sep 12 9 --> 2009-09-12
12101 12:45 --> today 12:45
12102 22 sept 0:34 --> currentyear-09-22 0:34
12103 12 --> currentyear-currentmonth-12
12104 Fri --> nearest Friday (today or later)
12105 +4 --> four days from today (only if +N is the only thing given)
12106 etc.
12107 The function understands only English month and weekday abbreviations,
12108 but this can be configured with the variables `parse-time-months' and
12109 `parse-time-weekdays'.
12111 While prompting, a calendar is popped up - you can also select the
12112 date with the mouse (button 1). The calendar shows a period of three
12113 months. To scroll it to other months, use the keys `>' and `<'.
12114 If you don't like the calendar, turn it off with
12115 \(setq org-popup-calendar-for-date-prompt nil)
12117 With optional argument TO-TIME, the date will immediately be converted
12118 to an internal time.
12119 With an optional argument WITH-TIME, the prompt will suggest to also
12120 insert a time. Note that when WITH-TIME is not set, you can still
12121 enter a time, and this function will inform the calling routine about
12122 this change. The calling routine may then choose to change the format
12123 used to insert the time stamp into the buffer to include the time."
12124 (require 'parse-time)
12125 (let* ((org-time-stamp-rounding-minutes
12126 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
12127 (ct (org-current-time))
12128 (default-time
12129 ;; Default time is either today, or, when entering a range,
12130 ;; the range start.
12131 (if (save-excursion
12132 (re-search-backward
12133 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12134 (- (point) 20) t))
12135 (apply
12136 'encode-time
12137 (mapcar (lambda(x) (or x 0))
12138 (parse-time-string (match-string 1))))
12139 ct))
12140 (calendar-move-hook nil)
12141 (view-diary-entries-initially nil)
12142 (view-calendar-holidays-initially nil)
12143 (timestr (format-time-string
12144 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
12145 (prompt (concat (if prompt (concat prompt " ") "")
12146 (format "Date and/or time (default [%s]): " timestr)))
12147 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
12148 second minute hour day month year tl wday wday1 pm)
12150 (cond
12151 (from-string (setq ans from-string))
12152 (org-popup-calendar-for-date-prompt
12153 (save-excursion
12154 (save-window-excursion
12155 (calendar)
12156 (calendar-forward-day (- (time-to-days default-time)
12157 (calendar-absolute-from-gregorian
12158 (calendar-current-date))))
12159 (org-eval-in-calendar nil)
12160 (let* ((old-map (current-local-map))
12161 (map (copy-keymap calendar-mode-map))
12162 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12163 (define-key map (kbd "RET") 'org-calendar-select)
12164 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
12165 'org-calendar-select-mouse)
12166 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
12167 'org-calendar-select-mouse)
12168 (define-key minibuffer-local-map [(meta shift left)]
12169 (lambda () (interactive)
12170 (org-eval-in-calendar '(calendar-backward-month 1))))
12171 (define-key minibuffer-local-map [(meta shift right)]
12172 (lambda () (interactive)
12173 (org-eval-in-calendar '(calendar-forward-month 1))))
12174 (define-key minibuffer-local-map [(shift up)]
12175 (lambda () (interactive)
12176 (org-eval-in-calendar '(calendar-backward-week 1))))
12177 (define-key minibuffer-local-map [(shift down)]
12178 (lambda () (interactive)
12179 (org-eval-in-calendar '(calendar-forward-week 1))))
12180 (define-key minibuffer-local-map [(shift left)]
12181 (lambda () (interactive)
12182 (org-eval-in-calendar '(calendar-backward-day 1))))
12183 (define-key minibuffer-local-map [(shift right)]
12184 (lambda () (interactive)
12185 (org-eval-in-calendar '(calendar-forward-day 1))))
12186 (define-key minibuffer-local-map ">"
12187 (lambda () (interactive)
12188 (org-eval-in-calendar '(scroll-calendar-left 1))))
12189 (define-key minibuffer-local-map "<"
12190 (lambda () (interactive)
12191 (org-eval-in-calendar '(scroll-calendar-right 1))))
12192 (unwind-protect
12193 (progn
12194 (use-local-map map)
12195 (setq org-ans0 (read-string prompt "" nil nil))
12196 ;; org-ans0: from prompt
12197 ;; org-ans1: from mouse click
12198 ;; org-ans2: from calendar motion
12199 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12200 (use-local-map old-map))))))
12201 (t ; Naked prompt only
12202 (setq ans (read-string prompt "" nil timestr))))
12203 (org-detach-overlay org-date-ovl)
12205 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
12206 (setq deltadays (string-to-number ans) ans ""))
12208 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12209 (when (string-match
12210 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12211 (setq year (if (match-end 2)
12212 (string-to-number (match-string 2 ans))
12213 (string-to-number (format-time-string "%Y")))
12214 month (string-to-number (match-string 3 ans))
12215 day (string-to-number (match-string 4 ans)))
12216 (if (< year 100) (setq year (+ 2000 year)))
12217 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12218 t nil ans)))
12219 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12220 ;; If there is a time with am/pm, and *no* time without it, we convert
12221 ;; convert so that matching will be successful.
12222 (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12223 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12224 (setq hour (string-to-number (match-string 1 ans))
12225 minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
12226 pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
12227 (if (and (= hour 12) (not pm))
12228 (setq hour 0)
12229 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12230 (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
12232 (setq tl (parse-time-string ans)
12233 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
12234 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
12235 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
12236 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
12237 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
12238 second (or (nth 0 tl) 0)
12239 wday (nth 6 tl))
12240 (setq day (+ day deltadays))
12241 (when (and wday (not (nth 3 tl)))
12242 ;; Weekday was given, but no day, so pick that day in the week
12243 ;; on or after the derived date.
12244 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12245 (unless (equal wday wday1)
12246 (setq day (+ day (% (- wday wday1 -7) 7)))))
12247 (if (and (boundp 'org-time-was-given)
12248 (nth 2 tl))
12249 (setq org-time-was-given t))
12250 (if (< year 100) (setq year (+ 2000 year)))
12251 (if to-time
12252 (encode-time second minute hour day month year)
12253 (if (or (nth 1 tl) (nth 2 tl))
12254 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
12255 (format "%04d-%02d-%02d" year month day)))))
12257 (defun org-eval-in-calendar (form)
12258 "Eval FORM in the calendar window and return to current window.
12259 Also, store the cursor date in variable org-ans2."
12260 (let ((sw (selected-window)))
12261 (select-window (get-buffer-window "*Calendar*"))
12262 (eval form)
12263 (when (calendar-cursor-to-date)
12264 (let* ((date (calendar-cursor-to-date))
12265 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12266 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12267 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12268 (select-window sw)
12269 ;; Update the prompt to show new default date
12270 (save-excursion
12271 (goto-char (point-min))
12272 (when (and (re-search-forward "\\[[-0-9]+\\]" nil t)
12273 (get-text-property (match-end 0) 'field))
12274 (let ((inhibit-read-only t))
12275 (replace-match (concat "[" org-ans2 "]") t t)
12276 (add-text-properties (point-min) (1+ (match-end 0))
12277 (text-properties-at (1+ (point-min)))))))))
12279 (defun org-calendar-select ()
12280 "Return to `org-read-date' with the date currently selected.
12281 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12282 (interactive)
12283 (when (calendar-cursor-to-date)
12284 (let* ((date (calendar-cursor-to-date))
12285 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12286 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12287 (if (active-minibuffer-window) (exit-minibuffer))))
12289 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
12290 "Insert a date stamp for the date given by the internal TIME.
12291 WITH-HM means, use the stamp format that includes the time of the day.
12292 INACTIVE means use square brackets instead of angular ones, so that the
12293 stamp will not contribute to the agenda.
12294 PRE and POST are optional strings to be inserted before and after the
12295 stamp.
12296 The command returns the inserted time stamp."
12297 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12298 stamp)
12299 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12300 (insert (or pre ""))
12301 (insert (setq stamp (format-time-string fmt time)))
12302 (insert (or post ""))
12303 stamp))
12305 (defun org-toggle-time-stamp-overlays ()
12306 "Toggle the use of custom time stamp formats."
12307 (interactive)
12308 (setq org-display-custom-times (not org-display-custom-times))
12309 (unless org-display-custom-times
12310 (let ((p (point-min)) (bmp (buffer-modified-p)))
12311 (while (setq p (next-single-property-change p 'display))
12312 (if (and (get-text-property p 'display)
12313 (eq (get-text-property p 'face) 'org-date))
12314 (remove-text-properties
12315 p (setq p (next-single-property-change p 'display))
12316 '(display t))))
12317 (set-buffer-modified-p bmp)))
12318 (if (featurep 'xemacs)
12319 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12320 (org-restart-font-lock)
12321 (setq org-table-may-need-update t)
12322 (if org-display-custom-times
12323 (message "Time stamps are overlayed with custom format")
12324 (message "Time stamp overlays removed")))
12326 (defun org-display-custom-time (beg end)
12327 "Overlay modified time stamp format over timestamp between BED and END."
12328 (let* ((t1 (save-match-data
12329 (org-parse-time-string (buffer-substring beg end) t)))
12330 (w1 (- end beg))
12331 (with-hm (and (nth 1 t1) (nth 2 t1)))
12332 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
12333 (time (org-fix-decoded-time t1))
12334 (str (org-add-props
12335 (format-time-string
12336 (substring tf 1 -1) (apply 'encode-time time))
12337 nil 'mouse-face 'highlight))
12338 (w2 (length str)))
12339 (if (not (= w2 w1))
12340 (add-text-properties (1+ beg) (+ 2 beg)
12341 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12342 (if (featurep 'xemacs)
12343 (progn
12344 (put-text-property beg end 'invisible t)
12345 (put-text-property beg end 'end-glyph (make-glyph str)))
12346 (put-text-property beg end 'display str))))
12348 (defun org-translate-time (string)
12349 "Translate all timestamps in STRING to custom format.
12350 But do this only if the variable `org-display-custom-times' is set."
12351 (when org-display-custom-times
12352 (save-match-data
12353 (let* ((start 0)
12354 (re org-ts-regexp-both)
12355 t1 with-hm inactive tf time str beg end)
12356 (while (setq start (string-match re string start))
12357 (setq beg (match-beginning 0)
12358 end (match-end 0)
12359 t1 (save-match-data
12360 (org-parse-time-string (substring string beg end) t))
12361 with-hm (and (nth 1 t1) (nth 2 t1))
12362 inactive (equal (substring string beg (1+ beg)) "[")
12363 tf (funcall (if with-hm 'cdr 'car)
12364 org-time-stamp-custom-formats)
12365 time (org-fix-decoded-time t1)
12366 str (format-time-string
12367 (concat
12368 (if inactive "[" "<") (substring tf 1 -1)
12369 (if inactive "]" ">"))
12370 (apply 'encode-time time))
12371 string (replace-match str t t string)
12372 start (+ start (length str)))))))
12373 string)
12375 (defun org-fix-decoded-time (time)
12376 "Set 0 instead of nil for the first 6 elements of time.
12377 Don't touch the rest."
12378 (let ((n 0))
12379 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12381 (defun org-days-to-time (timestamp-string)
12382 "Difference between TIMESTAMP-STRING and now in days."
12383 (- (time-to-days (org-time-string-to-time timestamp-string))
12384 (time-to-days (current-time))))
12386 (defun org-deadline-close (timestamp-string &optional ndays)
12387 "Is the time in TIMESTAMP-STRING close to the current date?"
12388 (and (< (org-days-to-time timestamp-string)
12389 (or ndays org-deadline-warning-days))
12390 (not (org-entry-is-done-p))))
12392 (defun org-calendar-select-mouse (ev)
12393 "Return to `org-read-date' with the date currently selected.
12394 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12395 (interactive "e")
12396 (mouse-set-point ev)
12397 (when (calendar-cursor-to-date)
12398 (let* ((date (calendar-cursor-to-date))
12399 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12400 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12401 (if (active-minibuffer-window) (exit-minibuffer))))
12403 (defun org-check-deadlines (ndays)
12404 "Check if there are any deadlines due or past due.
12405 A deadline is considered due if it happens within `org-deadline-warning-days'
12406 days from today's date. If the deadline appears in an entry marked DONE,
12407 it is not shown. The prefix arg NDAYS can be used to test that many
12408 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12409 (interactive "P")
12410 (let* ((org-warn-days
12411 (cond
12412 ((equal ndays '(4)) 100000)
12413 (ndays (prefix-numeric-value ndays))
12414 (t org-deadline-warning-days)))
12415 (case-fold-search nil)
12416 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12417 (callback
12418 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12420 (message "%d deadlines past-due or due within %d days"
12421 (org-occur regexp nil callback)
12422 org-warn-days)))
12424 (defun org-evaluate-time-range (&optional to-buffer)
12425 "Evaluate a time range by computing the difference between start and end.
12426 Normally the result is just printed in the echo area, but with prefix arg
12427 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12428 If the time range is actually in a table, the result is inserted into the
12429 next column.
12430 For time difference computation, a year is assumed to be exactly 365
12431 days in order to avoid rounding problems."
12432 (interactive "P")
12434 (org-clock-update-time-maybe)
12435 (save-excursion
12436 (unless (org-at-date-range-p)
12437 (goto-char (point-at-bol))
12438 (re-search-forward org-tr-regexp (point-at-eol) t))
12439 (if (not (org-at-date-range-p))
12440 (error "Not at a time-stamp range, and none found in current line")))
12441 (let* ((ts1 (match-string 1))
12442 (ts2 (match-string 2))
12443 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12444 (match-end (match-end 0))
12445 (time1 (org-time-string-to-time ts1))
12446 (time2 (org-time-string-to-time ts2))
12447 (t1 (time-to-seconds time1))
12448 (t2 (time-to-seconds time2))
12449 (diff (abs (- t2 t1)))
12450 (negative (< (- t2 t1) 0))
12451 ;; (ys (floor (* 365 24 60 60)))
12452 (ds (* 24 60 60))
12453 (hs (* 60 60))
12454 (fy "%dy %dd %02d:%02d")
12455 (fy1 "%dy %dd")
12456 (fd "%dd %02d:%02d")
12457 (fd1 "%dd")
12458 (fh "%02d:%02d")
12459 y d h m align)
12460 (if havetime
12461 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12463 d (floor (/ diff ds)) diff (mod diff ds)
12464 h (floor (/ diff hs)) diff (mod diff hs)
12465 m (floor (/ diff 60)))
12466 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12468 d (floor (+ (/ diff ds) 0.5))
12469 h 0 m 0))
12470 (if (not to-buffer)
12471 (message (org-make-tdiff-string y d h m))
12472 (when (org-at-table-p)
12473 (goto-char match-end)
12474 (setq align t)
12475 (and (looking-at " *|") (goto-char (match-end 0))))
12476 (if (looking-at
12477 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12478 (replace-match ""))
12479 (if negative (insert " -"))
12480 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12481 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12482 (insert " " (format fh h m))))
12483 (if align (org-table-align))
12484 (message "Time difference inserted")))))
12486 (defun org-make-tdiff-string (y d h m)
12487 (let ((fmt "")
12488 (l nil))
12489 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12490 l (push y l)))
12491 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12492 l (push d l)))
12493 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12494 l (push h l)))
12495 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12496 l (push m l)))
12497 (apply 'format fmt (nreverse l))))
12499 (defun org-time-string-to-time (s)
12500 (apply 'encode-time (org-parse-time-string s)))
12502 (defun org-parse-time-string (s &optional nodefault)
12503 "Parse the standard Org-mode time string.
12504 This should be a lot faster than the normal `parse-time-string'.
12505 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12506 hour and minute fields will be nil if not given."
12507 (if (string-match org-ts-regexp1 s)
12508 (list 0
12509 (if (or (match-beginning 8) (not nodefault))
12510 (string-to-number (or (match-string 8 s) "0")))
12511 (if (or (match-beginning 7) (not nodefault))
12512 (string-to-number (or (match-string 7 s) "0")))
12513 (string-to-number (match-string 4 s))
12514 (string-to-number (match-string 3 s))
12515 (string-to-number (match-string 2 s))
12516 nil nil nil)
12517 (make-list 9 0)))
12519 (defun org-timestamp-up (&optional arg)
12520 "Increase the date item at the cursor by one.
12521 If the cursor is on the year, change the year. If it is on the month or
12522 the day, change that.
12523 With prefix ARG, change by that many units."
12524 (interactive "p")
12525 (org-timestamp-change (prefix-numeric-value arg)))
12527 (defun org-timestamp-down (&optional arg)
12528 "Decrease the date item at the cursor by one.
12529 If the cursor is on the year, change the year. If it is on the month or
12530 the day, change that.
12531 With prefix ARG, change by that many units."
12532 (interactive "p")
12533 (org-timestamp-change (- (prefix-numeric-value arg))))
12535 (defun org-timestamp-up-day (&optional arg)
12536 "Increase the date in the time stamp by one day.
12537 With prefix ARG, change that many days."
12538 (interactive "p")
12539 (if (and (not (org-at-timestamp-p t))
12540 (org-on-heading-p))
12541 (org-todo 'up)
12542 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12544 (defun org-timestamp-down-day (&optional arg)
12545 "Decrease the date in the time stamp by one day.
12546 With prefix ARG, change that many days."
12547 (interactive "p")
12548 (if (and (not (org-at-timestamp-p t))
12549 (org-on-heading-p))
12550 (org-todo 'down)
12551 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12553 (defsubst org-pos-in-match-range (pos n)
12554 (and (match-beginning n)
12555 (<= (match-beginning n) pos)
12556 (>= (match-end n) pos)))
12558 (defun org-at-timestamp-p (&optional inactive-ok)
12559 "Determine if the cursor is in or at a timestamp."
12560 (interactive)
12561 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12562 (pos (point))
12563 (ans (or (looking-at tsr)
12564 (save-excursion
12565 (skip-chars-backward "^[<\n\r\t")
12566 (if (> (point) 1) (backward-char 1))
12567 (and (looking-at tsr)
12568 (> (- (match-end 0) pos) -1))))))
12569 (and (boundp 'org-ts-what)
12570 (setq org-ts-what
12571 (cond
12572 ((org-pos-in-match-range pos 2) 'year)
12573 ((org-pos-in-match-range pos 3) 'month)
12574 ((org-pos-in-match-range pos 7) 'hour)
12575 ((org-pos-in-match-range pos 8) 'minute)
12576 ((or (org-pos-in-match-range pos 4)
12577 (org-pos-in-match-range pos 5)) 'day)
12578 (t 'day))))
12579 ans))
12581 (defun org-timestamp-change (n &optional what)
12582 "Change the date in the time stamp at point.
12583 The date will be changed by N times WHAT. WHAT can be `day', `month',
12584 `year', `minute', `second'. If WHAT is not given, the cursor position
12585 in the timestamp determines what will be changed."
12586 (let ((pos (point))
12587 with-hm inactive
12588 org-ts-what
12589 ts time time0)
12590 (if (not (org-at-timestamp-p t))
12591 (error "Not at a timestamp"))
12592 (if (and (not what) (not (eq org-ts-what 'day))
12593 org-display-custom-times
12594 (get-text-property (point) 'display)
12595 (not (get-text-property (1- (point)) 'display)))
12596 (setq org-ts-what 'day))
12597 (setq org-ts-what (or what org-ts-what)
12598 with-hm (<= (abs (- (cdr org-ts-lengths)
12599 (- (match-end 0) (match-beginning 0))))
12601 inactive (= (char-after (match-beginning 0)) ?\[)
12602 ts (match-string 0))
12603 (replace-match "")
12604 (setq time0 (org-parse-time-string ts))
12605 (setq time
12606 (apply 'encode-time
12607 (append
12608 (list (or (car time0) 0))
12609 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
12610 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
12611 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
12612 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
12613 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
12614 (nthcdr 6 time0))))
12615 (if (eq what 'calendar)
12616 (let ((cal-date
12617 (save-excursion
12618 (save-match-data
12619 (set-buffer "*Calendar*")
12620 (calendar-cursor-to-date)))))
12621 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12622 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12623 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12624 (setcar time0 (or (car time0) 0))
12625 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12626 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
12627 (setq time (apply 'encode-time time0))))
12628 (setq org-last-changed-timestamp
12629 (org-insert-time-stamp time with-hm inactive))
12630 (org-clock-update-time-maybe)
12631 (goto-char pos)
12632 ;; Try to recenter the calendar window, if any
12633 (if (and org-calendar-follow-timestamp-change
12634 (get-buffer-window "*Calendar*" t)
12635 (memq org-ts-what '(day month year)))
12636 (org-recenter-calendar (time-to-days time)))))
12638 (defun org-recenter-calendar (date)
12639 "If the calendar is visible, recenter it to DATE."
12640 (let* ((win (selected-window))
12641 (cwin (get-buffer-window "*Calendar*" t))
12642 (calendar-move-hook nil))
12643 (when cwin
12644 (select-window cwin)
12645 (calendar-goto-date (if (listp date) date
12646 (calendar-gregorian-from-absolute date)))
12647 (select-window win))))
12649 (defun org-goto-calendar (&optional arg)
12650 "Go to the Emacs calendar at the current date.
12651 If there is a time stamp in the current line, go to that date.
12652 A prefix ARG can be used to force the current date."
12653 (interactive "P")
12654 (let ((tsr org-ts-regexp) diff
12655 (calendar-move-hook nil)
12656 (view-calendar-holidays-initially nil)
12657 (view-diary-entries-initially nil))
12658 (if (or (org-at-timestamp-p)
12659 (save-excursion
12660 (beginning-of-line 1)
12661 (looking-at (concat ".*" tsr))))
12662 (let ((d1 (time-to-days (current-time)))
12663 (d2 (time-to-days
12664 (org-time-string-to-time (match-string 1)))))
12665 (setq diff (- d2 d1))))
12666 (calendar)
12667 (calendar-goto-today)
12668 (if (and diff (not arg)) (calendar-forward-day diff))))
12670 (defun org-date-from-calendar ()
12671 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12672 If there is already a time stamp at the cursor position, update it."
12673 (interactive)
12674 (org-timestamp-change 0 'calendar))
12676 ;;; The clock for measuring work time.
12678 (defvar org-clock-marker (make-marker)
12679 "Marker recording the last clock-in.")
12681 (defun org-clock-in ()
12682 "Start the clock on the current item.
12683 If necessary, clock-out of the currently active clock."
12684 (interactive)
12685 (org-clock-out t)
12686 (let (ts)
12687 (save-excursion
12688 (org-back-to-heading t)
12689 (beginning-of-line 2)
12690 (when (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12691 (not (equal (match-string 1) org-clock-string)))
12692 ;; First line hast scheduling info, move one further
12693 (beginning-of-line 2)
12694 (or (bolp) (newline)))
12695 (insert "\n") (backward-char 1)
12696 (indent-relative)
12697 (insert org-clock-string " ")
12698 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12699 (move-marker org-clock-marker (point) (buffer-base-buffer))
12700 (message "Clock started at %s" ts))))
12702 (defun org-clock-out (&optional fail-quietly)
12703 "Stop the currently running clock.
12704 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
12705 (interactive)
12706 (catch 'exit
12707 (if (not (marker-buffer org-clock-marker))
12708 (if fail-quietly (throw 'exit t) (error "No active clock")))
12709 (let (ts te s h m)
12710 (save-excursion
12711 (set-buffer (marker-buffer org-clock-marker))
12712 (goto-char org-clock-marker)
12713 (beginning-of-line 1)
12714 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12715 (equal (match-string 1) org-clock-string))
12716 (setq ts (match-string 2))
12717 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
12718 (goto-char org-clock-marker)
12719 (insert "--")
12720 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12721 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
12722 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
12723 h (floor (/ s 3600))
12724 s (- s (* 3600 h))
12725 m (floor (/ s 60))
12726 s (- s (* 60 s)))
12727 (insert " => " (format "%2d:%02d" h m))
12728 (move-marker org-clock-marker nil)
12729 (org-add-log-maybe 'clock-out)
12730 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
12732 (defun org-clock-cancel ()
12733 "Cancel the running clock be removing the start timestamp."
12734 (interactive)
12735 (if (not (marker-buffer org-clock-marker))
12736 (error "No active clock"))
12737 (save-excursion
12738 (set-buffer (marker-buffer org-clock-marker))
12739 (goto-char org-clock-marker)
12740 (delete-region (1- (point-at-bol)) (point-at-eol)))
12741 (message "Clock canceled"))
12743 (defvar org-clock-file-total-minutes nil
12744 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
12745 (make-variable-buffer-local 'org-clock-file-total-minutes)
12747 (defun org-clock-sum (&optional tstart tend)
12748 "Sum the times for each subtree.
12749 Puts the resulting times in minutes as a text property on each headline."
12750 (interactive)
12751 (let* ((bmp (buffer-modified-p))
12752 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
12753 org-clock-string
12754 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
12755 (lmax 30)
12756 (ltimes (make-vector lmax 0))
12757 (t1 0)
12758 (level 0)
12759 ts te dt
12760 time)
12761 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
12762 (save-excursion
12763 (goto-char (point-max))
12764 (while (re-search-backward re nil t)
12765 (if (match-end 2)
12766 ;; A time
12767 (setq ts (match-string 2)
12768 te (match-string 3)
12769 ts (time-to-seconds
12770 (apply 'encode-time (org-parse-time-string ts)))
12771 te (time-to-seconds
12772 (apply 'encode-time (org-parse-time-string te)))
12773 ts (if tstart (max ts tstart) ts)
12774 te (if tend (min te tend) te)
12775 dt (- te ts)
12776 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
12777 ;; A headline
12778 (setq level (- (match-end 1) (match-beginning 1)))
12779 (when (or (> t1 0) (> (aref ltimes level) 0))
12780 (loop for l from 0 to level do
12781 (aset ltimes l (+ (aref ltimes l) t1)))
12782 (setq t1 0 time (aref ltimes level))
12783 (loop for l from level to (1- lmax) do
12784 (aset ltimes l 0))
12785 (goto-char (match-beginning 0))
12786 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
12787 (setq org-clock-file-total-minutes (aref ltimes 0)))
12788 (set-buffer-modified-p bmp)))
12790 (defun org-clock-display (&optional total-only)
12791 "Show subtree times in the entire buffer.
12792 If TOTAL-ONLY is non-nil, only show the total time for the entire file
12793 in the echo area."
12794 (interactive)
12795 (org-remove-clock-overlays)
12796 (let (time h m p)
12797 (org-clock-sum)
12798 (unless total-only
12799 (save-excursion
12800 (goto-char (point-min))
12801 (while (setq p (next-single-property-change (point) :org-clock-minutes))
12802 (goto-char p)
12803 (when (setq time (get-text-property p :org-clock-minutes))
12804 (org-put-clock-overlay time (funcall outline-level))))
12805 (setq h (/ org-clock-file-total-minutes 60)
12806 m (- org-clock-file-total-minutes (* 60 h)))
12807 ;; Arrange to remove the overlays upon next change.
12808 (when org-remove-highlights-with-change
12809 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
12810 nil 'local))))
12811 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
12813 (defvar org-clock-overlays nil)
12814 (make-variable-buffer-local 'org-clock-overlays)
12816 (defun org-put-clock-overlay (time &optional level)
12817 "Put an overlays on the current line, displaying TIME.
12818 If LEVEL is given, prefix time with a corresponding number of stars.
12819 This creates a new overlay and stores it in `org-clock-overlays', so that it
12820 will be easy to remove."
12821 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
12822 (l (if level (org-get-legal-level level 0) 0))
12823 (off 0)
12824 ov tx)
12825 (move-to-column c)
12826 (unless (eolp) (skip-chars-backward "^ \t"))
12827 (skip-chars-backward " \t")
12828 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
12829 tx (concat (buffer-substring (1- (point)) (point))
12830 (make-string (+ off (max 0 (- c (current-column)))) ?.)
12831 (org-add-props (format "%s %2d:%02d%s"
12832 (make-string l ?*) h m
12833 (make-string (- 10 l) ?\ ))
12834 '(face secondary-selection))
12835 ""))
12836 (if (not (featurep 'xemacs))
12837 (org-overlay-put ov 'display tx)
12838 (org-overlay-put ov 'invisible t)
12839 (org-overlay-put ov 'end-glyph (make-glyph tx)))
12840 (push ov org-clock-overlays)))
12842 (defun org-remove-clock-overlays (&optional beg end noremove)
12843 "Remove the occur highlights from the buffer.
12844 BEG and END are ignored. If NOREMOVE is nil, remove this function
12845 from the `before-change-functions' in the current buffer."
12846 (interactive)
12847 (unless org-inhibit-highlight-removal
12848 (mapc 'org-delete-overlay org-clock-overlays)
12849 (setq org-clock-overlays nil)
12850 (unless noremove
12851 (remove-hook 'before-change-functions
12852 'org-remove-clock-overlays 'local))))
12854 (defun org-clock-out-if-current ()
12855 "Clock out if the current entry contains the running clock.
12856 This is used to stop the clock after a TODO entry is marked DONE."
12857 (when (and (equal state org-done-string)
12858 (equal (marker-buffer org-clock-marker) (current-buffer))
12859 (< (point) org-clock-marker)
12860 (> (save-excursion (outline-next-heading) (point))
12861 org-clock-marker))
12862 ;; Clock out, but don't accept a logging message for this.
12863 (let ((org-log-done (if (and (listp org-log-done)
12864 (member 'clock-out org-log-done))
12865 '(done)
12866 org-log-done)))
12867 (org-clock-out))))
12869 (add-hook 'org-after-todo-state-change-hook
12870 'org-clock-out-if-current)
12872 (defun org-check-running-clock ()
12873 "Check if the current buffer contains the running clock.
12874 If yes, offer to stop it and to save the buffer with the changes."
12875 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
12876 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
12877 (buffer-name))))
12878 (org-clock-out)
12879 (when (y-or-n-p "Save changed buffer?")
12880 (save-buffer))))
12882 (defun org-clock-report ()
12883 "Create a table containing a report about clocked time.
12884 If the buffer contains lines
12885 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
12887 #+END: clocktable
12888 then the table will be inserted between these lines, replacing whatever
12889 is was there before. If these lines are not in the buffer, the table
12890 is inserted at point, surrounded by the special lines.
12891 The BEGIN line can contain parameters. Allowed are:
12892 :maxlevel The maximum level to be included in the table. Default is 3.
12893 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
12894 (interactive)
12895 (org-remove-clock-overlays)
12896 (unless (org-find-dblock "clocktable")
12897 (org-create-dblock (list :name "clocktable"
12898 :maxlevel 2 :emphasize nil)))
12899 (org-update-dblock))
12901 (defun org-clock-update-time-maybe ()
12902 "If this is a CLOCK line, update it and return t.
12903 Otherwise, return nil."
12904 (interactive)
12905 (save-excursion
12906 (beginning-of-line 1)
12907 (skip-chars-forward " \t")
12908 (when (looking-at org-clock-string)
12909 (let ((re (concat "[ \t]*" org-clock-string
12910 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
12911 "\\([ \t]*=>.*\\)?"))
12912 ts te h m s)
12913 (if (not (looking-at re))
12915 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
12916 (end-of-line 1)
12917 (setq ts (match-string 1)
12918 te (match-string 2))
12919 (setq s (- (time-to-seconds
12920 (apply 'encode-time (org-parse-time-string te)))
12921 (time-to-seconds
12922 (apply 'encode-time (org-parse-time-string ts))))
12923 h (floor (/ s 3600))
12924 s (- s (* 3600 h))
12925 m (floor (/ s 60))
12926 s (- s (* 60 s)))
12927 (insert " => " (format "%2d:%02d" h m))
12928 t)))))
12930 (defun org-clock-special-range (key &optional time as-strings)
12931 "Return two times bordering a special time range.
12932 Key is a symbol specifying the range and can be one of `today', `yesterday',
12933 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
12934 A week starts Monday 0:00 and ends Sunday 24:00.
12935 The range is determined relative to TIME. TIME defaults to the current time.
12936 The return value is a cons cell with two internal times like the ones
12937 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
12938 the returned times will be formatted strings."
12939 (let* ((tm (decode-time (or time (current-time))))
12940 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
12941 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
12942 (dow (nth 6 tm))
12943 s1 m1 h1 d1 month1 y1 diff ts te fm)
12944 (cond
12945 ((eq key 'today)
12946 (setq h 0 m 0 h1 24 m1 0))
12947 ((eq key 'yesterday)
12948 (setq d (1- d) h 0 m 0 h1 24 m1 0))
12949 ((eq key 'thisweek)
12950 (setq diff (if (= dow 0) 6 (1- dow))
12951 m 0 h 0 d (- d diff) d1 (+ 7 d)))
12952 ((eq key 'lastweek)
12953 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
12954 m 0 h 0 d (- d diff) d1 (+ 7 d)))
12955 ((eq key 'thismonth)
12956 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
12957 ((eq key 'lastmonth)
12958 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
12959 ((eq key 'thisyear)
12960 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
12961 ((eq key 'lastyear)
12962 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
12963 (t (error "No such time block %s" key)))
12964 (setq ts (encode-time s m h d month y)
12965 te (encode-time (or s1 s) (or m1 m) (or h1 h)
12966 (or d1 d) (or month1 month) (or y1 y)))
12967 (setq fm (cdr org-time-stamp-formats))
12968 (if as-strings
12969 (cons (format-time-string fm ts) (format-time-string fm te))
12970 (cons ts te))))
12972 (defun org-dblock-write:clocktable (params)
12973 "Write the standard clocktable."
12974 (let ((hlchars '((1 . "*") (2 . ?/)))
12975 (emph nil)
12976 (ins (make-marker))
12977 ipos time h m p level hlc hdl maxlevel
12978 ts te cc block)
12979 (setq maxlevel (or (plist-get params :maxlevel) 3)
12980 emph (plist-get params :emphasize)
12981 ts (plist-get params :tstart)
12982 te (plist-get params :tend)
12983 block (plist-get params :block))
12984 (when block
12985 (setq cc (org-clock-special-range block nil t)
12986 ts (car cc) te (cdr cc)))
12987 (if ts (setq ts (time-to-seconds
12988 (apply 'encode-time (org-parse-time-string ts)))))
12989 (if te (setq te (time-to-seconds
12990 (apply 'encode-time (org-parse-time-string te)))))
12991 (move-marker ins (point))
12992 (setq ipos (point))
12993 (insert-before-markers "Clock summary at ["
12994 (substring
12995 (format-time-string (cdr org-time-stamp-formats))
12996 1 -1)
12997 "]."
12998 (if block
12999 (format " Considered range is /%s/." block)
13001 "\n\n|L|Headline|Time|\n")
13002 (org-clock-sum ts te)
13003 (setq h (/ org-clock-file-total-minutes 60)
13004 m (- org-clock-file-total-minutes (* 60 h)))
13005 (insert-before-markers "|-\n|0|" "*Total file time*| "
13006 (format "*%d:%02d*" h m)
13007 "|\n")
13008 (goto-char (point-min))
13009 (while (setq p (next-single-property-change (point) :org-clock-minutes))
13010 (goto-char p)
13011 (when (setq time (get-text-property p :org-clock-minutes))
13012 (save-excursion
13013 (beginning-of-line 1)
13014 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
13015 (setq level (- (match-end 1) (match-beginning 1)))
13016 (<= level maxlevel))
13017 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
13018 hdl (match-string 2)
13019 h (/ time 60)
13020 m (- time (* 60 h)))
13021 (goto-char ins)
13022 (if (= level 1) (insert-before-markers "|-\n"))
13023 (insert-before-markers
13024 "| " (int-to-string level) "|" hlc hdl hlc " |"
13025 (make-string (1- level) ?|)
13027 (format "%d:%02d" h m)
13029 " |\n")))))
13030 (goto-char ins)
13031 (backward-delete-char 1)
13032 (goto-char ipos)
13033 (skip-chars-forward "^|")
13034 (org-table-align)))
13036 ;; FIXME: I don't think anybody uses this, ask David
13037 (defun org-collect-clock-time-entries ()
13038 "Return an internal list with clocking information.
13039 This list has one entry for each CLOCK interval.
13040 FIXME: describe the elements."
13041 (interactive)
13042 (let ((re (concat "^[ \t]*" org-clock-string
13043 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
13044 rtn beg end next cont level title total closedp leafp
13045 clockpos titlepos h m donep)
13046 (save-excursion
13047 (org-clock-sum)
13048 (goto-char (point-min))
13049 (while (re-search-forward re nil t)
13050 (setq clockpos (match-beginning 0)
13051 beg (match-string 1) end (match-string 2)
13052 cont (match-end 0))
13053 (setq beg (apply 'encode-time (org-parse-time-string beg))
13054 end (apply 'encode-time (org-parse-time-string end)))
13055 (org-back-to-heading t)
13056 (setq donep (org-entry-is-done-p))
13057 (setq titlepos (point)
13058 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
13059 h (/ total 60) m (- total (* 60 h))
13060 total (cons h m))
13061 (looking-at "\\(\\*+\\) +\\(.*\\)")
13062 (setq level (- (match-end 1) (match-beginning 1))
13063 title (org-match-string-no-properties 2))
13064 (save-excursion (outline-next-heading) (setq next (point)))
13065 (setq closedp (re-search-forward org-closed-time-regexp next t))
13066 (goto-char next)
13067 (setq leafp (and (looking-at "^\\*+ ")
13068 (<= (- (match-end 0) (point)) level)))
13069 (push (list beg end clockpos closedp donep
13070 total title titlepos level leafp)
13071 rtn)
13072 (goto-char cont)))
13073 (nreverse rtn)))
13075 ;;;; Agenda, and Diary Integration
13077 ;;; Define the Org-agenda-mode
13079 (defvar org-agenda-mode-map (make-sparse-keymap)
13080 "Keymap for `org-agenda-mode'.")
13082 (defvar org-agenda-menu) ; defined later in this file.
13083 (defvar org-agenda-follow-mode nil)
13084 (defvar org-agenda-show-log nil)
13085 (defvar org-agenda-redo-command nil)
13086 (defvar org-agenda-mode-hook nil)
13087 (defvar org-agenda-type nil)
13088 (defvar org-agenda-force-single-file nil)
13090 (defun org-agenda-mode ()
13091 "Mode for time-sorted view on action items in Org-mode files.
13093 The following commands are available:
13095 \\{org-agenda-mode-map}"
13096 (interactive)
13097 (kill-all-local-variables)
13098 (setq org-agenda-undo-list nil
13099 org-agenda-pending-undo-list nil)
13100 (setq major-mode 'org-agenda-mode)
13101 (setq mode-name "Org-Agenda")
13102 (use-local-map org-agenda-mode-map)
13103 (easy-menu-add org-agenda-menu)
13104 (if org-startup-truncated (setq truncate-lines t))
13105 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
13106 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
13107 ;; Make sure properties are removed when copying text
13108 (when (boundp 'buffer-substring-filters)
13109 (org-set-local 'buffer-substring-filters
13110 (cons (lambda (x)
13111 (set-text-properties 0 (length x) nil x) x)
13112 buffer-substring-filters)))
13113 (unless org-agenda-keep-modes
13114 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
13115 org-agenda-show-log nil))
13116 (easy-menu-change
13117 '("Agenda") "Agenda Files"
13118 (append
13119 (list
13120 (vector
13121 (if (get 'org-agenda-files 'org-restrict)
13122 "Restricted to single file"
13123 "Edit File List")
13124 '(org-edit-agenda-file-list)
13125 (not (get 'org-agenda-files 'org-restrict)))
13126 "--")
13127 (mapcar 'org-file-menu-entry (org-agenda-files))))
13128 (org-agenda-set-mode-name)
13129 (apply
13130 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
13131 (list 'org-agenda-mode-hook)))
13133 (substitute-key-definition 'undo 'org-agenda-undo
13134 org-agenda-mode-map global-map)
13135 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
13136 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
13137 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
13138 (define-key org-agenda-mode-map "\C-k" 'org-agenda-kill)
13139 (define-key org-agenda-mode-map "\C-c$" 'org-agenda-archive)
13140 (define-key org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
13141 (define-key org-agenda-mode-map "$" 'org-agenda-archive)
13142 (define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
13143 (define-key org-agenda-mode-map " " 'org-agenda-show)
13144 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
13145 (define-key org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
13146 (define-key org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
13147 (define-key org-agenda-mode-map "o" 'delete-other-windows)
13148 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
13149 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
13150 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
13151 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
13152 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
13153 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
13154 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
13155 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
13156 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
13157 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
13158 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
13160 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
13161 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
13162 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
13163 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
13164 (while l (define-key org-agenda-mode-map
13165 (int-to-string (pop l)) 'digit-argument)))
13167 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
13168 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
13169 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
13170 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
13171 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
13172 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
13173 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
13174 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
13175 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
13176 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
13177 (define-key org-agenda-mode-map "n" 'next-line)
13178 (define-key org-agenda-mode-map "p" 'previous-line)
13179 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
13180 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
13181 (define-key org-agenda-mode-map "," 'org-agenda-priority)
13182 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
13183 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
13184 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
13185 (eval-after-load "calendar"
13186 '(define-key calendar-mode-map org-calendar-to-agenda-key
13187 'org-calendar-goto-agenda))
13188 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
13189 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
13190 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
13191 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
13192 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
13193 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
13194 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
13195 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
13196 (define-key org-agenda-mode-map "O" 'org-agenda-clock-out)
13197 (define-key org-agenda-mode-map "X" 'org-agenda-clock-cancel)
13198 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
13199 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
13200 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
13201 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
13202 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
13203 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
13204 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
13205 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
13206 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
13207 "Local keymap for agenda entries from Org-mode.")
13209 (define-key org-agenda-keymap
13210 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
13211 (define-key org-agenda-keymap
13212 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
13213 (when org-agenda-mouse-1-follows-link
13214 (define-key org-agenda-keymap [follow-link] 'mouse-face))
13215 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
13216 '("Agenda"
13217 ("Agenda Files")
13218 "--"
13219 ["Show" org-agenda-show t]
13220 ["Go To (other window)" org-agenda-goto t]
13221 ["Go To (this window)" org-agenda-switch-to t]
13222 ["Follow Mode" org-agenda-follow-mode
13223 :style toggle :selected org-agenda-follow-mode :active t]
13224 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
13225 "--"
13226 ["Cycle TODO" org-agenda-todo t]
13227 ["Archive subtree" org-agenda-archive t]
13228 ["Delete subtree" org-agenda-kill t]
13229 "--"
13230 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
13231 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
13232 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
13233 "--"
13234 ("Tags"
13235 ["Show all Tags" org-agenda-show-tags t]
13236 ["Set Tags" org-agenda-set-tags t])
13237 ("Date/Schedule"
13238 ["Schedule" org-agenda-schedule t]
13239 ["Set Deadline" org-agenda-deadline t]
13240 "--"
13241 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
13242 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
13243 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
13244 ("Priority"
13245 ["Set Priority" org-agenda-priority t]
13246 ["Increase Priority" org-agenda-priority-up t]
13247 ["Decrease Priority" org-agenda-priority-down t]
13248 ["Show Priority" org-agenda-show-priority t])
13249 ("Calendar/Diary"
13250 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
13251 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
13252 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
13253 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
13254 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
13255 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
13256 "--"
13257 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
13258 "--"
13259 ("View"
13260 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
13261 :style radio :selected (equal org-agenda-ndays 1)]
13262 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
13263 :style radio :selected (equal org-agenda-ndays 7)]
13264 "--"
13265 ["Show Logbook entries" org-agenda-log-mode
13266 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
13267 ["Include Diary" org-agenda-toggle-diary
13268 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
13269 ["Use Time Grid" org-agenda-toggle-time-grid
13270 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
13271 ["Rebuild buffer" org-agenda-redo t]
13272 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
13273 "--"
13274 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
13275 "--"
13276 ["Quit" org-agenda-quit t]
13277 ["Exit and Release Buffers" org-agenda-exit t]
13280 ;;; Agenda undo
13282 (defvar org-agenda-allow-remote-undo t
13283 "Non-nil means, allow remote undo from the agenda buffer.")
13284 (defvar org-agenda-undo-list nil
13285 "List of undoable operations in the agenda since last refresh.")
13286 (defvar org-agenda-undo-has-started-in nil
13287 "Buffers that have already seen `undo-start' in the current undo sequence.")
13288 (defvar org-agenda-pending-undo-list nil
13289 "In a series of undo commands, this is the list of remaning undo items.")
13291 (defmacro org-if-unprotected (&rest body)
13292 "Execute BODY if ther is no `org-protected' text property at point."
13293 (declare (debug t))
13294 `(unless (get-text-property (point) 'org-protected)
13295 ,@body))
13297 (defmacro org-with-remote-undo (_buffer &rest _body)
13298 "Execute BODY while recording undo information in two buffers."
13299 (declare (indent 1) (debug t))
13300 `(let ((_cline (org-current-line))
13301 (_cmd this-command)
13302 (_buf1 (current-buffer))
13303 (_buf2 ,_buffer)
13304 (_undo1 buffer-undo-list)
13305 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
13306 _c1 _c2)
13307 ,@_body
13308 (when org-agenda-allow-remote-undo
13309 (setq _c1 (org-verify-change-for-undo
13310 _undo1 (with-current-buffer _buf1 buffer-undo-list))
13311 _c2 (org-verify-change-for-undo
13312 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
13313 (when (or _c1 _c2)
13314 ;; make sure there are undo boundaries
13315 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
13316 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
13317 ;; remember which buffer to undo
13318 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
13319 org-agenda-undo-list)))))
13321 (defun org-agenda-undo ()
13322 "Undo a remote editing step in the agenda.
13323 This undoes changes both in the agenda buffer and in the remote buffer
13324 that have been changed along."
13325 (interactive)
13326 (or org-agenda-allow-remote-undo
13327 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
13328 (if (not (eq this-command last-command))
13329 (setq org-agenda-undo-has-started-in nil
13330 org-agenda-pending-undo-list org-agenda-undo-list))
13331 (if (not org-agenda-pending-undo-list)
13332 (error "No further undo information"))
13333 (let* ((entry (pop org-agenda-pending-undo-list))
13334 buf line cmd rembuf)
13335 (setq cmd (pop entry) line (pop entry))
13336 (setq rembuf (nth 2 entry))
13337 (org-with-remote-undo rembuf
13338 (while (bufferp (setq buf (pop entry)))
13339 (if (pop entry)
13340 (with-current-buffer buf
13341 (let ((last-undo-buffer buf)
13342 buffer-read-only)
13343 (unless (memq buf org-agenda-undo-has-started-in)
13344 (push buf org-agenda-undo-has-started-in)
13345 (make-local-variable 'pending-undo-list)
13346 (undo-start))
13347 (while (and pending-undo-list
13348 (listp pending-undo-list)
13349 (not (car pending-undo-list)))
13350 (pop pending-undo-list))
13351 (undo-more 1))))))
13352 (goto-line line)
13353 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
13355 (defun org-verify-change-for-undo (l1 l2)
13356 "Verify that a real change occurred between the undo lists L1 and L2."
13357 (while (and l1 (listp l1) (null (car l1))) (pop l1))
13358 (while (and l2 (listp l2) (null (car l2))) (pop l2))
13359 (not (eq l1 l2)))
13361 ;;; Agenda dispatch
13363 (defvar org-agenda-restrict nil)
13364 (defvar org-agenda-restrict-begin (make-marker))
13365 (defvar org-agenda-restrict-end (make-marker))
13366 (defvar org-agenda-last-dispatch-buffer nil)
13368 ;;;###autoload
13369 (defun org-agenda (arg)
13370 "Dispatch agenda commands to collect entries to the agenda buffer.
13371 Prompts for a character to select a command. Any prefix arg will be passed
13372 on to the selected command. The default selections are:
13374 a Call `org-agenda-list' to display the agenda for current day or week.
13375 t Call `org-todo-list' to display the global todo list.
13376 T Call `org-todo-list' to display the global todo list, select only
13377 entries with a specific TODO keyword (the user gets a prompt).
13378 m Call `org-tags-view' to display headlines with tags matching
13379 a condition (the user is prompted for the condition).
13380 M Like `m', but select only TODO entries, no ordinary headlines.
13381 l Create a timeeline for the current buffer.
13383 More commands can be added by configuring the variable
13384 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
13385 searches can be pre-defined in this way.
13387 If the current buffer is in Org-mode and visiting a file, you can also
13388 first press `1' to indicate that the agenda should be temporarily (until the
13389 next use of \\[org-agenda]) restricted to the current file."
13390 (interactive "P")
13391 (catch 'exit
13392 (let* ((buf (current-buffer))
13393 (bfn (buffer-file-name (buffer-base-buffer)))
13394 (restrict-ok (and bfn (org-mode-p)))
13395 (custom org-agenda-custom-commands)
13396 c entry key type match lprops)
13397 ;; Turn off restriction
13398 (put 'org-agenda-files 'org-restrict nil)
13399 (setq org-agenda-restrict nil)
13400 (move-marker org-agenda-restrict-begin nil)
13401 (move-marker org-agenda-restrict-end nil)
13402 ;; Remember where this call originated
13403 (setq org-agenda-last-dispatch-buffer (current-buffer))
13404 (save-window-excursion
13405 (delete-other-windows)
13406 (switch-to-buffer-other-window " *Agenda Commands*")
13407 (erase-buffer)
13408 (insert (eval-when-compile
13409 (let ((header
13410 "Press key for an agenda command:
13411 -------------------------------- C Configure custom agenda commands
13412 a Agenda for current week or day
13413 t List of all TODO entries T Entries with special TODO kwd
13414 m Match a TAGS query M Like m, but only TODO entries
13415 L Timeline for current buffer # List stuck projects (!=configure)
13417 (start 0))
13418 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
13419 (setq start (match-end 0))
13420 (add-text-properties (match-beginning 2) (match-end 2)
13421 '(face bold) header))
13422 header)))
13423 (while (setq entry (pop custom))
13424 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
13425 (insert (format "\n%-4s%-14s: %s"
13426 (org-add-props (copy-sequence key)
13427 '(face bold))
13428 (cond
13429 ((stringp type) type)
13430 ((eq type 'todo) "TODO keyword")
13431 ((eq type 'tags) "Tags query")
13432 ((eq type 'tags-todo) "Tags (TODO)")
13433 ((eq type 'tags-tree) "Tags tree")
13434 ((eq type 'todo-tree) "TODO kwd tree")
13435 ((eq type 'occur-tree) "Occur tree")
13436 ((functionp type) (symbol-name type))
13437 (t "???"))
13438 (if (stringp match)
13439 (org-add-props match nil 'face 'org-warning)
13440 (format "set of %d commands" (length match))))))
13441 (if restrict-ok
13442 (insert "\n"
13443 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
13444 (goto-char (point-min))
13445 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
13446 (message "Press key for agenda command%s"
13447 (if restrict-ok ", or [1] or [0] to restrict" ""))
13448 (setq c (read-char-exclusive))
13449 (message "")
13450 (when (memq c '(?L ?1 ?0))
13451 (if restrict-ok
13452 (put 'org-agenda-files 'org-restrict (list bfn))
13453 (error "Cannot restrict agenda to current buffer"))
13454 (with-current-buffer " *Agenda Commands*"
13455 (goto-char (point-max))
13456 (delete-region (point-at-bol) (point))
13457 (goto-char (point-min)))
13458 (when (eq c ?0)
13459 (setq org-agenda-restrict t)
13460 (with-current-buffer buf
13461 (if (org-region-active-p)
13462 (progn
13463 (move-marker org-agenda-restrict-begin (region-beginning))
13464 (move-marker org-agenda-restrict-end (region-end)))
13465 (save-excursion
13466 (org-back-to-heading t)
13467 (move-marker org-agenda-restrict-begin (point))
13468 (move-marker org-agenda-restrict-end
13469 (progn (org-end-of-subtree t)))))))
13470 (unless (eq c ?L)
13471 (message "Press key for agenda command%s"
13472 (if restrict-ok " (restricted to current file)" ""))
13473 (setq c (read-char-exclusive)))
13474 (message "")))
13475 (require 'calendar) ; FIXME: can we avoid this for some commands?
13476 ;; For example the todo list should not need it (but does...)
13477 (cond
13478 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
13479 (if (symbolp (nth 1 entry))
13480 (progn
13481 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
13482 lprops (nth 3 entry))
13483 (cond
13484 ((eq type 'tags)
13485 (org-let lprops '(org-tags-view current-prefix-arg match)))
13486 ((eq type 'tags-todo)
13487 (org-let lprops '(org-tags-view '(4) match)))
13488 ((eq type 'todo)
13489 (org-let lprops '(org-todo-list match)))
13490 ((eq type 'tags-tree)
13491 (org-check-for-org-mode)
13492 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
13493 ((eq type 'todo-tree)
13494 (org-check-for-org-mode)
13495 (org-let lprops
13496 '(org-occur (concat "^" outline-regexp "[ \t]*"
13497 (regexp-quote match) "\\>"))))
13498 ((eq type 'occur-tree)
13499 (org-check-for-org-mode)
13500 (org-let lprops '(org-occur match)))
13501 ((fboundp type)
13502 (org-let lprops '(funcall type match)))
13503 (t (error "Invalid custom agenda command type %s" type))))
13504 (org-run-agenda-series (cddr entry))))
13505 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
13506 ((equal c ?a) (call-interactively 'org-agenda-list))
13507 ((equal c ?t) (call-interactively 'org-todo-list))
13508 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
13509 ((equal c ?m) (call-interactively 'org-tags-view))
13510 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
13511 ((equal c ?L)
13512 (unless restrict-ok
13513 (error "This is not an Org-mode file"))
13514 (org-call-with-arg 'org-timeline arg))
13515 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
13516 ((equal c ?!) (customize-variable 'org-stuck-projects))
13517 (t (error "Invalid key"))))))
13519 (defun org-run-agenda-series (series)
13520 (org-prepare-agenda)
13521 (let* ((org-agenda-multi t)
13522 (redo (list 'org-run-agenda-series (list 'quote series)))
13523 (cmds (car series))
13524 (gprops (nth 1 series))
13525 match ;; The byte compiler incorrectly complains about this. Keep it!
13526 cmd type lprops)
13527 (while (setq cmd (pop cmds))
13528 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
13529 (cond
13530 ((eq type 'agenda)
13531 (call-interactively 'org-agenda-list))
13532 ((eq type 'alltodo)
13533 (call-interactively 'org-todo-list))
13534 ((eq type 'stuck)
13535 (call-interactively 'org-agenda-list-stuck-projects))
13536 ((eq type 'tags)
13537 (org-let2 gprops lprops
13538 '(org-tags-view current-prefix-arg match)))
13539 ((eq type 'tags-todo)
13540 (org-let2 gprops lprops
13541 '(org-tags-view '(4) match)))
13542 ((eq type 'todo)
13543 (org-let2 gprops lprops
13544 '(org-todo-list match)))
13545 ((fboundp type)
13546 (org-let2 gprops lprops
13547 '(funcall type match)))
13548 (t (error "Invalid type in command series"))))
13549 (widen)
13550 (setq org-agenda-redo-command redo)
13551 (goto-char (point-min)))
13552 (org-finalize-agenda))
13554 ;;;###autoload
13555 (defmacro org-batch-agenda (cmd-key &rest parameters)
13556 "Run an agenda command in batch mode, send result to STDOUT.
13557 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
13558 Paramters are alternating variable names and values that will be bound
13559 before running the agenda command."
13560 (let (pars)
13561 (while parameters
13562 (push (list (pop parameters) (if parameters (pop parameters))) pars))
13563 (flet ((read-char-exclusive () (string-to-char cmd-key)))
13564 (eval (list 'let (nreverse pars) '(org-agenda nil))))
13565 (set-buffer "*Org Agenda*")
13566 (princ (buffer-string))))
13568 (defmacro org-no-read-only (&rest body)
13569 "Inhibit read-only for BODY."
13570 `(let ((inhibit-read-only t)) ,@body))
13572 (defun org-check-for-org-mode ()
13573 "Make sure current buffer is in org-mode. Error if not."
13574 (or (org-mode-p)
13575 (error "Cannot execute org-mode agenda command on buffer in %s."
13576 major-mode)))
13578 (defun org-fit-agenda-window ()
13579 "Fit the window to the buffer size."
13580 (and (memq org-agenda-window-setup '(reorganize-frame))
13581 (fboundp 'fit-window-to-buffer)
13582 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
13583 (/ (frame-height) 2))))
13585 ;;; Agenda file list
13587 (defun org-agenda-files (&optional unrestricted)
13588 "Get the list of agenda files.
13589 Optional UNRESTRICTED means return the full list even if a restriction
13590 is currently in place."
13591 (cond
13592 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13593 ((stringp org-agenda-files) (org-read-agenda-file-list))
13594 ((listp org-agenda-files) org-agenda-files)
13595 (t (error "Invalid value of `org-agenda-files'"))))
13597 (defun org-edit-agenda-file-list ()
13598 "Edit the list of agenda files.
13599 Depending on setup, this either uses customize to edit the variable
13600 `org-agenda-files', or it visits the file that is holding the list. In the
13601 latter case, the buffer is set up in a way that saving it automatically kills
13602 the buffer and restores the previous window configuration."
13603 (interactive)
13604 (if (stringp org-agenda-files)
13605 (let ((cw (current-window-configuration)))
13606 (find-file org-agenda-files)
13607 (org-set-local 'org-window-configuration cw)
13608 (org-add-hook 'after-save-hook
13609 (lambda ()
13610 (set-window-configuration
13611 (prog1 org-window-configuration
13612 (kill-buffer (current-buffer))))
13613 (org-install-agenda-files-menu)
13614 (message "New agenda file list installed"))
13615 nil 'local)
13616 (message (substitute-command-keys
13617 "Edit list and finish with \\[save-buffer]")))
13618 (customize-variable 'org-agenda-files)))
13620 (defun org-store-new-agenda-file-list (list)
13621 "Set new value for the agenda file list and save it correcly."
13622 (if (stringp org-agenda-files)
13623 (let ((f org-agenda-files) b)
13624 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13625 (with-temp-file f
13626 (insert (mapconcat 'identity list "\n") "\n")))
13627 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13628 (setq org-agenda-files list)
13629 (customize-save-variable 'org-agenda-files org-agenda-files))))
13631 (defun org-read-agenda-file-list ()
13632 "Read the list of agenda files from a file."
13633 (when (stringp org-agenda-files)
13634 (with-temp-buffer
13635 (insert-file-contents org-agenda-files)
13636 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13639 ;;;###autoload
13640 (defun org-cycle-agenda-files ()
13641 "Cycle through the files in `org-agenda-files'.
13642 If the current buffer visits an agenda file, find the next one in the list.
13643 If the current buffer does not, find the first agenda file."
13644 (interactive)
13645 (let* ((fs (org-agenda-files t))
13646 (files (append fs (list (car fs))))
13647 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13648 file)
13649 (unless files (error "No agenda files"))
13650 (catch 'exit
13651 (while (setq file (pop files))
13652 (if (equal (file-truename file) tcf)
13653 (when (car files)
13654 (find-file (car files))
13655 (throw 'exit t))))
13656 (find-file (car fs)))
13657 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13659 (defun org-agenda-file-to-end ()
13660 "Move/add the current file to the end of the agenda file list.
13661 If the file is not present in the list, it is appended to the list. If it is
13662 present, it is moved there."
13663 (interactive)
13664 (org-agenda-file-to-front 'to-end))
13666 (defun org-agenda-file-to-front (&optional to-end)
13667 "Move/add the current file to the top of the agenda file list.
13668 If the file is not present in the list, it is added to the front. If it is
13669 present, it is moved there. With optional argument TO-END, add/move to the
13670 end of the list."
13671 (interactive "P")
13672 (let ((file-alist (mapcar (lambda (x)
13673 (cons (file-truename x) x))
13674 (org-agenda-files t)))
13675 (ctf (file-truename buffer-file-name))
13676 x had)
13677 (setq x (assoc ctf file-alist) had x)
13679 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13680 (if to-end
13681 (setq file-alist (append (delq x file-alist) (list x)))
13682 (setq file-alist (cons x (delq x file-alist))))
13683 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13684 (org-install-agenda-files-menu)
13685 (message "File %s to %s of agenda file list"
13686 (if had "moved" "added") (if to-end "end" "front"))))
13688 (defun org-remove-file (&optional file)
13689 "Remove current file from the list of files in variable `org-agenda-files'.
13690 These are the files which are being checked for agenda entries.
13691 Optional argument FILE means, use this file instead of the current."
13692 (interactive)
13693 (let* ((file (or file buffer-file-name))
13694 (true-file (file-truename file))
13695 (afile (abbreviate-file-name file))
13696 (files (delq nil (mapcar
13697 (lambda (x)
13698 (if (equal true-file
13699 (file-truename x))
13700 nil x))
13701 (org-agenda-files t)))))
13702 (if (not (= (length files) (length (org-agenda-files t))))
13703 (progn
13704 (org-store-new-agenda-file-list files)
13705 (org-install-agenda-files-menu)
13706 (message "Removed file: %s" afile))
13707 (message "File was not in list: %s" afile))))
13709 (defun org-file-menu-entry (file)
13710 (vector file (list 'find-file file) t))
13712 (defun org-check-agenda-file (file)
13713 "Make sure FILE exists. If not, ask user what to do."
13714 (when (not (file-exists-p file))
13715 (message "non-existent file %s. [R]emove from list or [A]bort?"
13716 (abbreviate-file-name file))
13717 (let ((r (downcase (read-char-exclusive))))
13718 (cond
13719 ((equal r ?r)
13720 (org-remove-file file)
13721 (throw 'nextfile t))
13722 (t (error "Abort"))))))
13724 ;;; Agenda prepare and finalize
13726 (defvar org-agenda-multi nil) ; dynammically scoped
13727 (defvar org-agenda-buffer-name "*Org Agenda*")
13728 (defvar org-pre-agenda-window-conf nil)
13729 (defun org-prepare-agenda ()
13730 (if org-agenda-multi
13731 (progn
13732 (setq buffer-read-only nil)
13733 (goto-char (point-max))
13734 (unless (= (point) 1)
13735 (insert "\n" (make-string (window-width) ?=) "\n"))
13736 (narrow-to-region (point) (point-max)))
13737 (org-agenda-maybe-reset-markers 'force)
13738 (org-prepare-agenda-buffers (org-agenda-files))
13739 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
13740 (awin (get-buffer-window abuf)))
13741 (cond
13742 ((equal (current-buffer) abuf) nil)
13743 (awin (select-window awin))
13744 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
13745 ((equal org-agenda-window-setup 'current-window)
13746 (switch-to-buffer abuf))
13747 ((equal org-agenda-window-setup 'other-window)
13748 (switch-to-buffer-other-window abuf))
13749 ((equal org-agenda-window-setup 'other-frame)
13750 (switch-to-buffer-other-frame abuf))
13751 ((equal org-agenda-window-setup 'reorganize-frame)
13752 (delete-other-windows)
13753 (switch-to-buffer-other-window abuf))))
13754 (setq buffer-read-only nil)
13755 (erase-buffer)
13756 (org-agenda-mode))
13757 (setq buffer-read-only nil))
13759 (defun org-finalize-agenda ()
13760 "Finishing touch for the agenda buffer, called just before displaying it."
13761 (unless org-agenda-multi
13762 (org-agenda-align-tags)
13763 (save-excursion
13764 (let ((buffer-read-only))
13765 (goto-char (point-min))
13766 (while (org-activate-bracket-links (point-max))
13767 (add-text-properties (match-beginning 0) (match-end 0)
13768 '(face org-link))))
13769 (run-hooks 'org-finalize-agenda-hook))))
13771 (defun org-prepare-agenda-buffers (files)
13772 "Create buffers for all agenda files, protect archived trees and comments."
13773 (interactive)
13774 (let ((pa '(:org-archived t))
13775 (pc '(:org-comment t))
13776 (pall '(:org-archived t :org-comment t))
13777 (rea (concat ":" org-archive-tag ":"))
13778 bmp file re)
13779 (save-excursion
13780 (save-restriction
13781 (while (setq file (pop files))
13782 (org-check-agenda-file file)
13783 (set-buffer (org-get-agenda-file-buffer file))
13784 (widen)
13785 (setq bmp (buffer-modified-p))
13786 (save-excursion
13787 (remove-text-properties (point-min) (point-max) pall)
13788 (when org-agenda-skip-archived-trees
13789 (goto-char (point-min))
13790 (while (re-search-forward rea nil t)
13791 (if (org-on-heading-p t)
13792 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13793 (goto-char (point-min))
13794 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13795 (while (re-search-forward re nil t)
13796 (add-text-properties
13797 (match-beginning 0) (org-end-of-subtree t) pc)))
13798 (set-buffer-modified-p bmp))))))
13800 (defvar org-agenda-skip-function nil
13801 "Function to be called at each match during agenda construction.
13802 If this function return nil, the current match should not be skipped.
13803 Otherwise, the function must return a position from where the search
13804 should be continued.
13805 Never set this variable using `setq' or so, because then it will apply
13806 to all future agenda commands. Instead, bind it with `let' to scope
13807 it dynamically into the agenda-constructing command.")
13809 (defun org-agenda-skip ()
13810 "Throw to `:skip' in places that should be skipped.
13811 Also moves point to the end of the skipped region, so that search can
13812 continue from there."
13813 (let ((p (point-at-bol)) to)
13814 (and org-agenda-skip-archived-trees
13815 (get-text-property p :org-archived)
13816 (org-end-of-subtree t)
13817 (throw :skip t))
13818 (and (get-text-property p :org-comment)
13819 (org-end-of-subtree t)
13820 (throw :skip t))
13821 (if (equal (char-after p) ?#) (throw :skip t))
13822 (when (and (functionp org-agenda-skip-function)
13823 (setq to (save-excursion
13824 (save-match-data
13825 (funcall org-agenda-skip-function)))))
13826 (goto-char to)
13827 (throw :skip t))))
13829 (defvar org-agenda-markers nil
13830 "List of all currently active markers created by `org-agenda'.")
13831 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
13832 "Creation time of the last agenda marker.")
13834 (defun org-agenda-new-marker (&optional pos)
13835 "Return a new agenda marker.
13836 Org-mode keeps a list of these markers and resets them when they are
13837 no longer in use."
13838 (let ((m (copy-marker (or pos (point)))))
13839 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
13840 (push m org-agenda-markers)
13843 (defun org-agenda-maybe-reset-markers (&optional force)
13844 "Reset markers created by `org-agenda'. But only if they are old enough."
13845 (if (or (and force (not org-agenda-multi))
13846 (> (- (time-to-seconds (current-time))
13847 org-agenda-last-marker-time)
13849 (while org-agenda-markers
13850 (move-marker (pop org-agenda-markers) nil))))
13852 (defvar org-agenda-new-buffers nil
13853 "Buffers created to visit agenda files.")
13855 (defun org-get-agenda-file-buffer (file)
13856 "Get a buffer visiting FILE. If the buffer needs to be created, add
13857 it to the list of buffers which might be released later."
13858 (let ((buf (org-find-base-buffer-visiting file)))
13859 (if buf
13860 buf ; just return it
13861 ;; Make a new buffer and remember it
13862 (setq buf (find-file-noselect file))
13863 (if buf (push buf org-agenda-new-buffers))
13864 buf)))
13866 (defun org-release-buffers (blist)
13867 "Release all buffers in list, asking the user for confirmation when needed.
13868 When a buffer is unmodified, it is just killed. When modified, it is saved
13869 \(if the user agrees) and then killed."
13870 (let (buf file)
13871 (while (setq buf (pop blist))
13872 (setq file (buffer-file-name buf))
13873 (when (and (buffer-modified-p buf)
13874 file
13875 (y-or-n-p (format "Save file %s? " file)))
13876 (with-current-buffer buf (save-buffer)))
13877 (kill-buffer buf))))
13879 (defvar org-category-table nil)
13880 (defun org-get-category-table ()
13881 "Get the table of categories and positions in current buffer."
13882 (let (tbl)
13883 (save-excursion
13884 (goto-char (point-min))
13885 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
13886 (push (cons (point) (org-trim (match-string 2))) tbl)))
13887 tbl))
13889 (defun org-get-category (&optional pos)
13890 "Get the category applying to position POS."
13891 (if (not org-category-table)
13892 (cond
13893 ((null org-category)
13894 (setq org-category
13895 (if buffer-file-name
13896 (file-name-sans-extension
13897 (file-name-nondirectory buffer-file-name))
13898 "???")))
13899 ((symbolp org-category) (symbol-name org-category))
13900 (t org-category))
13901 (let ((tbl org-category-table)
13902 (pos (or pos (point))))
13903 (while (and tbl (> (caar tbl) pos))
13904 (pop tbl))
13905 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
13906 org-category-table))))))
13907 ;;; Agenda timeline
13909 (defun org-timeline (&optional include-all)
13910 "Show a time-sorted view of the entries in the current org file.
13911 Only entries with a time stamp of today or later will be listed. With
13912 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
13913 under the current date.
13914 If the buffer contains an active region, only check the region for
13915 dates."
13916 (interactive "P")
13917 (require 'calendar)
13918 (org-compile-prefix-format 'timeline)
13919 (org-set-sorting-strategy 'timeline)
13920 (let* ((dopast t)
13921 (dotodo include-all)
13922 (doclosed org-agenda-show-log)
13923 (entry buffer-file-name)
13924 (date (calendar-current-date))
13925 (beg (if (org-region-active-p) (region-beginning) (point-min)))
13926 (end (if (org-region-active-p) (region-end) (point-max)))
13927 (day-numbers (org-get-all-dates beg end 'no-ranges
13928 t doclosed ; always include today
13929 org-timeline-show-empty-dates))
13930 (today (time-to-days (current-time)))
13931 (past t)
13932 args
13933 s e rtn d emptyp)
13934 (setq org-agenda-redo-command
13935 (list 'progn
13936 (list 'switch-to-buffer-other-window (current-buffer))
13937 (list 'org-timeline (list 'quote include-all))))
13938 (if (not dopast)
13939 ;; Remove past dates from the list of dates.
13940 (setq day-numbers (delq nil (mapcar (lambda(x)
13941 (if (>= x today) x nil))
13942 day-numbers))))
13943 (org-prepare-agenda)
13944 (if doclosed (push :closed args))
13945 (push :timestamp args)
13946 (if dotodo (push :todo args))
13947 (while (setq d (pop day-numbers))
13948 (if (and (listp d) (eq (car d) :omitted))
13949 (progn
13950 (setq s (point))
13951 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
13952 (put-text-property s (1- (point)) 'face 'org-level-3))
13953 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
13954 (if (and (>= d today)
13955 dopast
13956 past)
13957 (progn
13958 (setq past nil)
13959 (insert (make-string 79 ?-) "\n")))
13960 (setq date (calendar-gregorian-from-absolute d))
13961 (setq s (point))
13962 (setq rtn (and (not emptyp)
13963 (apply 'org-agenda-get-day-entries
13964 entry date args)))
13965 (if (or rtn (equal d today) org-timeline-show-empty-dates)
13966 (progn
13967 (insert (calendar-day-name date) " "
13968 (number-to-string (extract-calendar-day date)) " "
13969 (calendar-month-name (extract-calendar-month date)) " "
13970 (number-to-string (extract-calendar-year date)) "\n")
13971 ; FIXME: this gives a timezone problem
13972 ; (insert (format-time-string org-agenda-date-format
13973 ; (calendar-time-from-absolute d 0))
13974 ; "\n")
13975 (put-text-property s (1- (point)) 'face 'org-level-3)
13976 (put-text-property s (1- (point)) 'org-date-line t)
13977 (if (equal d today)
13978 (put-text-property s (1- (point)) 'org-today t))
13979 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
13980 (put-text-property s (1- (point)) 'day d)))))
13981 (goto-char (point-min))
13982 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
13983 (point-min)))
13984 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
13985 (org-finalize-agenda)
13986 (setq buffer-read-only t)))
13988 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
13989 "Return a list of all relevant day numbers from BEG to END buffer positions.
13990 If NO-RANGES is non-nil, include only the start and end dates of a range,
13991 not every single day in the range. If FORCE-TODAY is non-nil, make
13992 sure that TODAY is included in the list. If INACTIVE is non-nil, also
13993 inactive time stamps (those in square brackets) are included.
13994 When EMPTY is non-nil, also include days without any entries."
13995 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
13996 dates dates1 date day day1 day2 ts1 ts2)
13997 (if force-today
13998 (setq dates (list (time-to-days (current-time)))))
13999 (save-excursion
14000 (goto-char beg)
14001 (while (re-search-forward re end t)
14002 (setq day (time-to-days (org-time-string-to-time
14003 (substring (match-string 1) 0 10))))
14004 (or (memq day dates) (push day dates)))
14005 (unless no-ranges
14006 (goto-char beg)
14007 (while (re-search-forward org-tr-regexp end t)
14008 (setq ts1 (substring (match-string 1) 0 10)
14009 ts2 (substring (match-string 2) 0 10)
14010 day1 (time-to-days (org-time-string-to-time ts1))
14011 day2 (time-to-days (org-time-string-to-time ts2)))
14012 (while (< (setq day1 (1+ day1)) day2)
14013 (or (memq day1 dates) (push day1 dates)))))
14014 (setq dates (sort dates '<))
14015 (when empty
14016 (while (setq day (pop dates))
14017 (setq day2 (car dates))
14018 (push day dates1)
14019 (when (and day2 empty)
14020 (if (or (eq empty t)
14021 (and (numberp empty) (<= (- day2 day) empty)))
14022 (while (< (setq day (1+ day)) day2)
14023 (push (list day) dates1))
14024 (push (cons :omitted (- day2 day)) dates1))))
14025 (setq dates (nreverse dates1)))
14026 dates)))
14028 ;;; Agenda Daily/Weekly
14030 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
14031 (defvar org-agenda-last-arguments nil
14032 "The arguments of the previous call to org-agenda")
14033 (defvar org-starting-day nil) ; local variable in the agenda buffer
14034 (defvar org-include-all-loc nil) ; local variable
14037 ;;;###autoload
14038 (defun org-agenda-list (&optional include-all start-day ndays)
14039 "Produce a weekly view from all files in variable `org-agenda-files'.
14040 The view will be for the current week, but from the overview buffer you
14041 will be able to go to other weeks.
14042 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
14043 also be shown, under the current date.
14044 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
14045 on the days are also shown. See the variable `org-log-done' for how
14046 to turn on logging.
14047 START-DAY defaults to TODAY, or to the most recent match for the weekday
14048 given in `org-agenda-start-on-weekday'.
14049 NDAYS defaults to `org-agenda-ndays'."
14050 (interactive "P")
14051 (if org-agenda-overriding-arguments
14052 (setq include-all (car org-agenda-overriding-arguments)
14053 start-day (nth 1 org-agenda-overriding-arguments)
14054 ndays (nth 2 org-agenda-overriding-arguments)))
14055 (setq org-agenda-last-arguments (list include-all start-day ndays))
14056 (org-compile-prefix-format 'agenda)
14057 (org-set-sorting-strategy 'agenda)
14058 (require 'calendar)
14059 (let* ((org-agenda-start-on-weekday
14060 (if (or (equal ndays 1)
14061 (and (null ndays) (equal 1 org-agenda-ndays)))
14062 nil org-agenda-start-on-weekday))
14063 (thefiles (org-agenda-files))
14064 (files thefiles)
14065 (today (time-to-days (current-time)))
14066 (sd (or start-day today))
14067 (start (if (or (null org-agenda-start-on-weekday)
14068 (< org-agenda-ndays 7))
14070 (let* ((nt (calendar-day-of-week
14071 (calendar-gregorian-from-absolute sd)))
14072 (n1 org-agenda-start-on-weekday)
14073 (d (- nt n1)))
14074 (- sd (+ (if (< d 0) 7 0) d)))))
14075 (day-numbers (list start))
14076 (inhibit-redisplay (not debug-on-error))
14077 s e rtn rtnall file date d start-pos end-pos todayp nd)
14078 (setq org-agenda-redo-command
14079 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
14080 ;; Make the list of days
14081 (setq ndays (or ndays org-agenda-ndays)
14082 nd ndays)
14083 (while (> ndays 1)
14084 (push (1+ (car day-numbers)) day-numbers)
14085 (setq ndays (1- ndays)))
14086 (setq day-numbers (nreverse day-numbers))
14087 (org-prepare-agenda)
14088 (org-set-local 'org-starting-day (car day-numbers))
14089 (org-set-local 'org-include-all-loc include-all)
14090 (when (and (or include-all org-agenda-include-all-todo)
14091 (member today day-numbers))
14092 (setq files thefiles
14093 rtnall nil)
14094 (while (setq file (pop files))
14095 (catch 'nextfile
14096 (org-check-agenda-file file)
14097 (setq date (calendar-gregorian-from-absolute today)
14098 rtn (org-agenda-get-day-entries
14099 file date :todo))
14100 (setq rtnall (append rtnall rtn))))
14101 (when rtnall
14102 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
14103 (add-text-properties (point-min) (1- (point))
14104 (list 'face 'org-level-3))
14105 (insert (org-finalize-agenda-entries rtnall) "\n")))
14106 (setq s (point))
14107 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
14108 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
14109 (while (setq d (pop day-numbers))
14110 (setq date (calendar-gregorian-from-absolute d)
14111 s (point))
14112 (if (or (setq todayp (= d today))
14113 (and (not start-pos) (= d sd)))
14114 (setq start-pos (point))
14115 (if (and start-pos (not end-pos))
14116 (setq end-pos (point))))
14117 (setq files thefiles
14118 rtnall nil)
14119 (while (setq file (pop files))
14120 (catch 'nextfile
14121 (org-check-agenda-file file)
14122 (if org-agenda-show-log
14123 (setq rtn (org-agenda-get-day-entries
14124 file date
14125 :deadline :scheduled :timestamp :closed))
14126 (setq rtn (org-agenda-get-day-entries
14127 file date
14128 :deadline :scheduled :timestamp)))
14129 (setq rtnall (append rtnall rtn))))
14130 (if org-agenda-include-diary
14131 (progn
14132 (require 'diary-lib)
14133 (setq rtn (org-get-entries-from-diary date))
14134 (setq rtnall (append rtnall rtn))))
14135 (if (or rtnall org-agenda-show-all-dates)
14136 (progn
14137 (insert (format "%-9s %2d %s %4d\n"
14138 (calendar-day-name date)
14139 (extract-calendar-day date)
14140 (calendar-month-name (extract-calendar-month date))
14141 (extract-calendar-year date)))
14142 ; FIXME: this gives a timezone problem
14143 ; (insert (format-time-string org-agenda-date-format
14144 ; (calendar-time-from-absolute d 0)) "\n")
14145 (put-text-property s (1- (point)) 'face 'org-level-3)
14146 (put-text-property s (1- (point)) 'org-date-line t)
14147 (if todayp (put-text-property s (1- (point)) 'org-today t))
14148 (if rtnall (insert
14149 (org-finalize-agenda-entries
14150 (org-agenda-add-time-grid-maybe
14151 rtnall nd todayp))
14152 "\n"))
14153 (put-text-property s (1- (point)) 'day d))))
14154 (goto-char (point-min))
14155 (org-fit-agenda-window)
14156 (unless (and (pos-visible-in-window-p (point-min))
14157 (pos-visible-in-window-p (point-max)))
14158 (goto-char (1- (point-max)))
14159 (recenter -1)
14160 (if (not (pos-visible-in-window-p (or start-pos 1)))
14161 (progn
14162 (goto-char (or start-pos 1))
14163 (recenter 1))))
14164 (goto-char (or start-pos 1))
14165 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
14166 (org-finalize-agenda)
14167 (setq buffer-read-only t)
14168 (message "")))
14170 ;;; Agenda TODO list
14172 (defvar org-select-this-todo-keyword nil)
14173 (defvar org-last-arg nil)
14175 ;;;###autoload
14176 (defun org-todo-list (arg)
14177 "Show all TODO entries from all agenda file in a single list.
14178 The prefix arg can be used to select a specific TODO keyword and limit
14179 the list to these. When using \\[universal-argument], you will be prompted
14180 for a keyword. A numeric prefix directly selects the Nth keyword in
14181 `org-todo-keywords'."
14182 (interactive "P")
14183 (require 'calendar)
14184 (org-compile-prefix-format 'todo)
14185 (org-set-sorting-strategy 'todo)
14186 (let* ((today (time-to-days (current-time)))
14187 (date (calendar-gregorian-from-absolute today))
14188 (kwds org-todo-keywords)
14189 (completion-ignore-case t)
14190 (org-select-this-todo-keyword
14191 (if (stringp arg) arg
14192 (and arg (integerp arg) (> arg 0)
14193 (nth (1- arg) org-todo-keywords))))
14194 rtn rtnall files file pos)
14195 (when (equal arg '(4))
14196 (setq org-select-this-todo-keyword
14197 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
14198 nil t)))
14199 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
14200 (org-prepare-agenda)
14201 (org-set-local 'org-last-arg arg)
14202 (org-set-local 'org-todo-keywords kwds)
14203 (setq org-agenda-redo-command
14204 '(org-todo-list (or current-prefix-arg org-last-arg)))
14205 (setq files (org-agenda-files)
14206 rtnall nil)
14207 (while (setq file (pop files))
14208 (catch 'nextfile
14209 (org-check-agenda-file file)
14210 (setq rtn (org-agenda-get-day-entries file date :todo))
14211 (setq rtnall (append rtnall rtn))))
14212 (if org-agenda-overriding-header
14213 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
14214 nil 'face 'org-level-3) "\n")
14215 (insert "Global list of TODO items of type: ")
14216 (add-text-properties (point-min) (1- (point))
14217 (list 'face 'org-level-3))
14218 (setq pos (point))
14219 (insert (or org-select-this-todo-keyword "ALL") "\n")
14220 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14221 (setq pos (point))
14222 (unless org-agenda-multi
14223 (insert
14224 "Available with `N r': (0)ALL "
14225 (let ((n 0))
14226 (mapconcat (lambda (x)
14227 (format "(%d)%s" (setq n (1+ n)) x))
14228 org-todo-keywords " "))
14229 "\n"))
14230 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14231 (when rtnall
14232 (insert (org-finalize-agenda-entries rtnall) "\n"))
14233 (goto-char (point-min))
14234 (org-fit-agenda-window)
14235 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
14236 (org-finalize-agenda)
14237 (setq buffer-read-only t)))
14239 ;;; Agenda tags match
14241 ;;;###autoload
14242 (defun org-tags-view (&optional todo-only match)
14243 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
14244 The prefix arg TODO-ONLY limits the search to TODO entries."
14245 (interactive "P")
14246 (org-compile-prefix-format 'tags)
14247 (org-set-sorting-strategy 'tags)
14248 (let* ((org-tags-match-list-sublevels
14249 (if todo-only t org-tags-match-list-sublevels))
14250 (completion-ignore-case t)
14251 rtn rtnall files file pos matcher
14252 buffer)
14253 (setq matcher (org-make-tags-matcher match)
14254 match (car matcher) matcher (cdr matcher))
14255 (org-prepare-agenda)
14256 (setq org-agenda-redo-command
14257 (list 'org-tags-view (list 'quote todo-only)
14258 (list 'if 'current-prefix-arg nil match)))
14259 (setq files (org-agenda-files)
14260 rtnall nil)
14261 (while (setq file (pop files))
14262 (catch 'nextfile
14263 (org-check-agenda-file file)
14264 (setq buffer (if (file-exists-p file)
14265 (org-get-agenda-file-buffer file)
14266 (error "No such file %s" file)))
14267 (if (not buffer)
14268 ;; If file does not exist, merror message to agenda
14269 (setq rtn (list
14270 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14271 rtnall (append rtnall rtn))
14272 (with-current-buffer buffer
14273 (unless (org-mode-p)
14274 (error "Agenda file %s is not in `org-mode'" file))
14275 (setq org-category-table (org-get-category-table))
14276 (save-excursion
14277 (save-restriction
14278 (if org-agenda-restrict
14279 (narrow-to-region org-agenda-restrict-begin
14280 org-agenda-restrict-end)
14281 (widen))
14282 (setq rtn (org-scan-tags 'agenda matcher todo-only))
14283 (setq rtnall (append rtnall rtn))))))))
14284 (if org-agenda-overriding-header
14285 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
14286 nil 'face 'org-level-3) "\n")
14287 (insert "Headlines with TAGS match: ")
14288 (add-text-properties (point-min) (1- (point))
14289 (list 'face 'org-level-3))
14290 (setq pos (point))
14291 (insert match "\n")
14292 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14293 (setq pos (point))
14294 (unless org-agenda-multi
14295 (insert "Press `C-u r' to search again with new search string\n"))
14296 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14297 (when rtnall
14298 (insert (org-finalize-agenda-entries rtnall) "\n"))
14299 (goto-char (point-min))
14300 (org-fit-agenda-window)
14301 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
14302 (org-finalize-agenda)
14303 (setq buffer-read-only t)))
14305 ;;; Agenda Finding stuck projects
14307 (defvar org-agenda-skip-regexp nil
14308 "Regular expression used in skipping subtrees for the agenda.
14309 This is basically a temporary global variable that can be set and then
14310 used by user-defined selections using `org-agenda-skip-function'.")
14312 (defvar org-agenda-overriding-header nil
14313 "When this is set during todo and tags searches, will replace header.")
14315 (defun org-agenda-skip-subtree-when-regexp-matches ()
14316 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
14317 If yes, it returns the end position of this tree, causing agenda commands
14318 to skip this subtree. This is a function that can be put into
14319 `org-agenda-skip-function' for the duration of a command."
14320 (save-match-data
14321 (let ((end (save-excursion (org-end-of-subtree t)))
14322 skip)
14323 (save-excursion
14324 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
14325 (and skip end))))
14327 (defun org-agenda-list-stuck-projects (&rest ignore)
14328 "Create agenda view for projects that are stuck.
14329 Stuck projects are project that have no next actions. For the definitions
14330 of what a project is and how to check if it stuck, customize the variable
14331 `org-stuck-projects'.
14332 MATCH is being ignored."
14333 (interactive)
14334 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
14335 (org-agenda-overriding-header "List of stuck projects: ")
14336 (matcher (nth 0 org-stuck-projects))
14337 (todo (nth 1 org-stuck-projects))
14338 (tags (nth 2 org-stuck-projects))
14339 (todo-re (concat "^\\*+[ \t]+\\("
14340 (mapconcat 'identity todo "\\|")
14341 "\\)\\>"))
14342 (tags-re (concat "^\\*+.*:\\("
14343 (mapconcat 'identity tags "\\|")
14344 "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
14346 (setq org-agenda-skip-regexp
14347 (cond
14348 ((and todo tags)
14349 (concat todo-re "\\|" tags-re))
14350 (todo todo-re)
14351 (tags tags-re)
14352 (t (error "No information how to identify unstuck projects"))))
14353 (org-tags-view nil matcher)
14354 (with-current-buffer org-agenda-buffer-name
14355 (setq org-agenda-redo-command
14356 '(org-agenda-list-stuck-projects
14357 (or current-prefix-arg org-last-arg))))))
14359 ;;; Diary integration
14361 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
14363 (defun org-get-entries-from-diary (date)
14364 "Get the (Emacs Calendar) diary entries for DATE."
14365 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
14366 (diary-display-hook '(fancy-diary-display))
14367 (list-diary-entries-hook
14368 (cons 'org-diary-default-entry list-diary-entries-hook))
14369 (diary-file-name-prefix-function nil) ; turn this feature off
14370 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
14371 entries
14372 (org-disable-agenda-to-diary t))
14373 (save-excursion
14374 (save-window-excursion
14375 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
14376 (if (not (get-buffer fancy-diary-buffer))
14377 (setq entries nil)
14378 (with-current-buffer fancy-diary-buffer
14379 (setq buffer-read-only nil)
14380 (if (= (point-max) 1)
14381 ;; No entries
14382 (setq entries nil)
14383 ;; Omit the date and other unnecessary stuff
14384 (org-agenda-cleanup-fancy-diary)
14385 ;; Add prefix to each line and extend the text properties
14386 (if (= (point-max) 1)
14387 (setq entries nil)
14388 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
14389 (set-buffer-modified-p nil)
14390 (kill-buffer fancy-diary-buffer)))
14391 (when entries
14392 (setq entries (org-split-string entries "\n"))
14393 (setq entries
14394 (mapcar
14395 (lambda (x)
14396 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
14397 ;; Extend the text properties to the beginning of the line
14398 (org-add-props x (text-properties-at (1- (length x)) x)))
14399 entries)))))
14401 (defun org-agenda-cleanup-fancy-diary ()
14402 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
14403 This gets rid of the date, the underline under the date, and
14404 the dummy entry installed by `org-mode' to ensure non-empty diary for each
14405 date. It also removes lines that contain only whitespace."
14406 (goto-char (point-min))
14407 (if (looking-at ".*?:[ \t]*")
14408 (progn
14409 (replace-match "")
14410 (re-search-forward "\n=+$" nil t)
14411 (replace-match "")
14412 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
14413 (re-search-forward "\n=+$" nil t)
14414 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
14415 (goto-char (point-min))
14416 (while (re-search-forward "^ +\n" nil t)
14417 (replace-match ""))
14418 (goto-char (point-min))
14419 (if (re-search-forward "^Org-mode dummy\n?" nil t)
14420 (replace-match "")))
14422 ;; Make sure entries from the diary have the right text properties.
14423 (eval-after-load "diary-lib"
14424 '(if (boundp 'diary-modify-entry-list-string-function)
14425 ;; We can rely on the hook, nothing to do
14427 ;; Hook not avaiable, must use advice to make this work
14428 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
14429 "Make the position visible."
14430 (if (and org-disable-agenda-to-diary ;; called from org-agenda
14431 (stringp string)
14432 buffer-file-name)
14433 (setq string (org-modify-diary-entry-string string))))))
14435 (defun org-modify-diary-entry-string (string)
14436 "Add text properties to string, allowing org-mode to act on it."
14437 (org-add-props string nil
14438 'mouse-face 'highlight
14439 'keymap org-agenda-keymap
14440 'help-echo (format "mouse-2 or RET jump to diary file %s"
14441 (abbreviate-file-name buffer-file-name))
14442 'org-agenda-diary-link t
14443 'org-marker (org-agenda-new-marker (point-at-bol))))
14445 (defun org-diary-default-entry ()
14446 "Add a dummy entry to the diary.
14447 Needed to avoid empty dates which mess up holiday display."
14448 ;; Catch the error if dealing with the new add-to-diary-alist
14449 (when org-disable-agenda-to-diary
14450 (condition-case nil
14451 (add-to-diary-list original-date "Org-mode dummy" "")
14452 (error
14453 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
14455 ;;;###autoload
14456 (defun org-diary (&rest args)
14457 "Return diary information from org-files.
14458 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
14459 It accesses org files and extracts information from those files to be
14460 listed in the diary. The function accepts arguments specifying what
14461 items should be listed. The following arguments are allowed:
14463 :timestamp List the headlines of items containing a date stamp or
14464 date range matching the selected date. Deadlines will
14465 also be listed, on the expiration day.
14467 :deadline List any deadlines past due, or due within
14468 `org-deadline-warning-days'. The listing occurs only
14469 in the diary for *today*, not at any other date. If
14470 an entry is marked DONE, it is no longer listed.
14472 :scheduled List all items which are scheduled for the given date.
14473 The diary for *today* also contains items which were
14474 scheduled earlier and are not yet marked DONE.
14476 :todo List all TODO items from the org-file. This may be a
14477 long list - so this is not turned on by default.
14478 Like deadlines, these entries only show up in the
14479 diary for *today*, not at any other date.
14481 The call in the diary file should look like this:
14483 &%%(org-diary) ~/path/to/some/orgfile.org
14485 Use a separate line for each org file to check. Or, if you omit the file name,
14486 all files listed in `org-agenda-files' will be checked automatically:
14488 &%%(org-diary)
14490 If you don't give any arguments (as in the example above), the default
14491 arguments (:deadline :scheduled :timestamp) are used. So the example above may
14492 also be written as
14494 &%%(org-diary :deadline :timestamp :scheduled)
14496 The function expects the lisp variables `entry' and `date' to be provided
14497 by the caller, because this is how the calendar works. Don't use this
14498 function from a program - use `org-agenda-get-day-entries' instead."
14499 (org-agenda-maybe-reset-markers)
14500 (org-compile-prefix-format 'agenda)
14501 (org-set-sorting-strategy 'agenda)
14502 (setq args (or args '(:deadline :scheduled :timestamp)))
14503 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
14504 (list entry)
14505 (org-agenda-files t)))
14506 file rtn results)
14507 ;; If this is called during org-agenda, don't return any entries to
14508 ;; the calendar. Org Agenda will list these entries itself.
14509 (if org-disable-agenda-to-diary (setq files nil))
14510 (while (setq file (pop files))
14511 (setq rtn (apply 'org-agenda-get-day-entries file date args))
14512 (setq results (append results rtn)))
14513 (if results
14514 (concat (org-finalize-agenda-entries results) "\n"))))
14516 ;;; Agenda entry finders
14518 (defun org-agenda-get-day-entries (file date &rest args)
14519 "Does the work for `org-diary' and `org-agenda'.
14520 FILE is the path to a file to be checked for entries. DATE is date like
14521 the one returned by `calendar-current-date'. ARGS are symbols indicating
14522 which kind of entries should be extracted. For details about these, see
14523 the documentation of `org-diary'."
14524 (setq args (or args '(:deadline :scheduled :timestamp)))
14525 (let* ((org-startup-folded nil)
14526 (org-startup-align-all-tables nil)
14527 (buffer (if (file-exists-p file)
14528 (org-get-agenda-file-buffer file)
14529 (error "No such file %s" file)))
14530 arg results rtn)
14531 (if (not buffer)
14532 ;; If file does not exist, make sure an error message ends up in diary
14533 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14534 (with-current-buffer buffer
14535 (unless (org-mode-p)
14536 (error "Agenda file %s is not in `org-mode'" file))
14537 (setq org-category-table (org-get-category-table))
14538 (let ((case-fold-search nil))
14539 (save-excursion
14540 (save-restriction
14541 (if org-agenda-restrict
14542 (narrow-to-region org-agenda-restrict-begin
14543 org-agenda-restrict-end)
14544 (widen))
14545 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
14546 (while (setq arg (pop args))
14547 (cond
14548 ((and (eq arg :todo)
14549 (equal date (calendar-current-date)))
14550 (setq rtn (org-agenda-get-todos))
14551 (setq results (append results rtn)))
14552 ((eq arg :timestamp)
14553 (setq rtn (org-agenda-get-blocks))
14554 (setq results (append results rtn))
14555 (setq rtn (org-agenda-get-timestamps))
14556 (setq results (append results rtn)))
14557 ((eq arg :scheduled)
14558 (setq rtn (org-agenda-get-scheduled))
14559 (setq results (append results rtn)))
14560 ((eq arg :closed)
14561 (setq rtn (org-agenda-get-closed))
14562 (setq results (append results rtn)))
14563 ((and (eq arg :deadline)
14564 (equal date (calendar-current-date)))
14565 (setq rtn (org-agenda-get-deadlines))
14566 (setq results (append results rtn))))))))
14567 results))))
14569 (defun org-entry-is-done-p ()
14570 "Is the current entry marked DONE?"
14571 (save-excursion
14572 (and (re-search-backward "[\r\n]\\*" nil t)
14573 (looking-at org-nl-done-regexp))))
14575 (defun org-at-date-range-p (&optional inactive-ok)
14576 "Is the cursor inside a date range?"
14577 (interactive)
14578 (save-excursion
14579 (catch 'exit
14580 (let ((pos (point)))
14581 (skip-chars-backward "^[<\r\n")
14582 (skip-chars-backward "<[")
14583 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
14584 (>= (match-end 0) pos)
14585 (throw 'exit t))
14586 (skip-chars-backward "^<[\r\n")
14587 (skip-chars-backward "<[")
14588 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
14589 (>= (match-end 0) pos)
14590 (throw 'exit t)))
14591 nil)))
14593 (defun org-agenda-get-todos ()
14594 "Return the TODO information for agenda display."
14595 (let* ((props (list 'face nil
14596 'done-face 'org-done
14597 'org-not-done-regexp org-not-done-regexp
14598 'mouse-face 'highlight
14599 'keymap org-agenda-keymap
14600 'help-echo
14601 (format "mouse-2 or RET jump to org file %s"
14602 (abbreviate-file-name buffer-file-name))))
14603 ;; FIXME: get rid of the \n at some point but watch out
14604 (regexp (concat "[\n\r]\\*+ *\\("
14605 (if org-select-this-todo-keyword
14606 (concat "\\<\\(" org-select-this-todo-keyword
14607 "\\)\\>")
14608 org-not-done-regexp)
14609 "[^\n\r]*\\)"))
14610 marker priority category tags
14611 ee txt beg end)
14612 (goto-char (point-min))
14613 (while (re-search-forward regexp nil t)
14614 (catch :skip
14615 (save-match-data
14616 (beginning-of-line)
14617 (setq beg (point) end (progn (outline-next-heading) (point)))
14618 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
14619 (re-search-forward org-scheduled-time-regexp end t))
14620 (and org-agenda-todo-ignore-deadlines (goto-char beg)
14621 (re-search-forward org-deadline-time-regexp end t)
14622 (org-deadline-close (match-string 1))))
14623 (goto-char beg)
14624 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
14625 (throw :skip nil)))
14626 (goto-char beg)
14627 (org-agenda-skip)
14628 (goto-char (match-beginning 1))
14629 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
14630 category (org-get-category)
14631 tags (org-get-tags-at (point))
14632 txt (org-format-agenda-item "" (match-string 1) category tags)
14633 priority
14634 (+ (org-get-priority txt)
14635 (if org-todo-kwd-priority-p
14636 (- org-todo-kwd-max-priority -2
14637 (length
14638 (member (match-string 2) org-todo-keywords)))
14639 1)))
14640 (org-add-props txt props
14641 'org-marker marker 'org-hd-marker marker
14642 'priority priority 'org-category category)
14643 (push txt ee)
14644 (if org-agenda-todo-list-sublevels
14645 (goto-char (match-end 1))
14646 (org-end-of-subtree 'invisible))))
14647 (nreverse ee)))
14649 (defconst org-agenda-no-heading-message
14650 "No heading for this item in buffer or region.")
14652 (defun org-agenda-get-timestamps ()
14653 "Return the date stamp information for agenda display."
14654 (let* ((props (list 'face nil
14655 'org-not-done-regexp org-not-done-regexp
14656 'mouse-face 'highlight
14657 'keymap org-agenda-keymap
14658 'help-echo
14659 (format "mouse-2 or RET jump to org file %s"
14660 (abbreviate-file-name buffer-file-name))))
14661 (regexp (regexp-quote
14662 (substring
14663 (format-time-string
14664 (car org-time-stamp-formats)
14665 (apply 'encode-time ; DATE bound by calendar
14666 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
14667 0 11)))
14668 marker hdmarker deadlinep scheduledp donep tmp priority category
14669 ee txt timestr tags)
14670 (goto-char (point-min))
14671 (while (re-search-forward regexp nil t)
14672 (catch :skip
14673 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
14674 (org-agenda-skip)
14675 (setq marker (org-agenda-new-marker (match-beginning 0))
14676 category (org-get-category (match-beginning 0))
14677 tmp (buffer-substring (max (point-min)
14678 (- (match-beginning 0)
14679 org-ds-keyword-length))
14680 (match-beginning 0))
14681 timestr (buffer-substring (match-beginning 0) (point-at-eol))
14682 deadlinep (string-match org-deadline-regexp tmp)
14683 scheduledp (string-match org-scheduled-regexp tmp)
14684 donep (org-entry-is-done-p))
14685 (and org-agenda-skip-scheduled-if-done
14686 scheduledp donep
14687 (throw :skip t))
14688 (if (string-match ">" timestr)
14689 ;; substring should only run to end of time stamp
14690 (setq timestr (substring timestr 0 (match-end 0))))
14691 (save-excursion
14692 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
14693 (progn
14694 (goto-char (match-end 1))
14695 (setq hdmarker (org-agenda-new-marker)
14696 tags (org-get-tags-at))
14697 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
14698 (setq txt (org-format-agenda-item
14699 (format "%s%s"
14700 (if deadlinep "Deadline: " "")
14701 (if scheduledp "Scheduled: " ""))
14702 (match-string 1) category tags timestr)))
14703 (setq txt org-agenda-no-heading-message))
14704 (setq priority (org-get-priority txt))
14705 (org-add-props txt props
14706 'org-marker marker 'org-hd-marker hdmarker)
14707 (if deadlinep
14708 (org-add-props txt nil
14709 'face (if donep 'org-done 'org-warning)
14710 'undone-face 'org-warning 'done-face 'org-done
14711 'org-category category 'priority (+ 100 priority))
14712 (if scheduledp
14713 (org-add-props txt nil
14714 'face 'org-scheduled-today
14715 'undone-face 'org-scheduled-today 'done-face 'org-done
14716 'org-category category 'priority (+ 99 priority))
14717 (org-add-props txt nil 'priority priority 'org-category category)))
14718 (push txt ee))
14719 (outline-next-heading)))
14720 (nreverse ee)))
14722 (defun org-agenda-get-closed ()
14723 "Return the logged TODO entries for agenda display."
14724 (let* ((props (list 'mouse-face 'highlight
14725 'org-not-done-regexp org-not-done-regexp
14726 'keymap org-agenda-keymap
14727 'help-echo
14728 (format "mouse-2 or RET jump to org file %s"
14729 (abbreviate-file-name buffer-file-name))))
14730 (regexp (concat
14731 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
14732 (regexp-quote
14733 (substring
14734 (format-time-string
14735 (car org-time-stamp-formats)
14736 (apply 'encode-time ; DATE bound by calendar
14737 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
14738 1 11))))
14739 marker hdmarker priority category tags closedp
14740 ee txt timestr)
14741 (goto-char (point-min))
14742 (while (re-search-forward regexp nil t)
14743 (catch :skip
14744 (org-agenda-skip)
14745 (setq marker (org-agenda-new-marker (match-beginning 0))
14746 closedp (equal (match-string 1) org-closed-string)
14747 category (org-get-category (match-beginning 0))
14748 timestr (buffer-substring (match-beginning 0) (point-at-eol))
14749 ;; donep (org-entry-is-done-p)
14751 (if (string-match "\\]" timestr)
14752 ;; substring should only run to end of time stamp
14753 (setq timestr (substring timestr 0 (match-end 0))))
14754 (save-excursion
14755 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
14756 (progn
14757 (goto-char (match-end 1))
14758 (setq hdmarker (org-agenda-new-marker)
14759 tags (org-get-tags-at))
14760 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
14761 (setq txt (org-format-agenda-item
14762 (if closedp "Closed: " "Clocked: ")
14763 (match-string 1) category tags timestr)))
14764 (setq txt org-agenda-no-heading-message))
14765 (setq priority 100000)
14766 (org-add-props txt props
14767 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
14768 'priority priority 'org-category category
14769 'undone-face 'org-warning 'done-face 'org-done)
14770 (push txt ee))
14771 (outline-next-heading)))
14772 (nreverse ee)))
14774 (defun org-agenda-get-deadlines ()
14775 "Return the deadline information for agenda display."
14776 (let* ((wdays org-deadline-warning-days)
14777 (props (list 'mouse-face 'highlight
14778 'org-not-done-regexp org-not-done-regexp
14779 'keymap org-agenda-keymap
14780 'help-echo
14781 (format "mouse-2 or RET jump to org file %s"
14782 (abbreviate-file-name buffer-file-name))))
14783 (regexp org-deadline-time-regexp)
14784 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
14785 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
14786 d2 diff pos pos1 category tags
14787 ee txt head face)
14788 (goto-char (point-min))
14789 (while (re-search-forward regexp nil t)
14790 (catch :skip
14791 (org-agenda-skip)
14792 (setq pos (1- (match-beginning 1))
14793 d2 (time-to-days
14794 (org-time-string-to-time (match-string 1)))
14795 diff (- d2 d1))
14796 ;; When to show a deadline in the calendar:
14797 ;; If the expiration is within wdays warning time.
14798 ;; Past-due deadlines are only shown on the current date
14799 (if (and (< diff wdays) todayp (not (= diff 0)))
14800 (save-excursion
14801 (setq category (org-get-category))
14802 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
14803 (progn
14804 (goto-char (match-end 0))
14805 (setq pos1 (match-end 1))
14806 (setq tags (org-get-tags-at pos1))
14807 (setq head (buffer-substring-no-properties
14808 (point)
14809 (progn (skip-chars-forward "^\r\n")
14810 (point))))
14811 (if (string-match org-looking-at-done-regexp head)
14812 (setq txt nil)
14813 (setq txt (org-format-agenda-item
14814 (format "In %3d d.: " diff) head category tags))))
14815 (setq txt org-agenda-no-heading-message))
14816 (when txt
14817 (setq face (cond ((<= diff 0) 'org-warning)
14818 ((<= diff 5) 'org-upcoming-deadline)
14819 (t nil)))
14820 (org-add-props txt props
14821 'org-marker (org-agenda-new-marker pos)
14822 'org-hd-marker (org-agenda-new-marker pos1)
14823 'priority (+ (- 10 diff) (org-get-priority txt))
14824 'org-category category
14825 'face face 'undone-face face 'done-face 'org-done)
14826 (push txt ee))))))
14827 ee))
14829 (defun org-agenda-get-scheduled ()
14830 "Return the scheduled information for agenda display."
14831 (let* ((props (list 'face 'org-scheduled-previously
14832 'org-not-done-regexp org-not-done-regexp
14833 'undone-face 'org-scheduled-previously
14834 'done-face 'org-done
14835 'mouse-face 'highlight
14836 'keymap org-agenda-keymap
14837 'help-echo
14838 (format "mouse-2 or RET jump to org file %s"
14839 (abbreviate-file-name buffer-file-name))))
14840 (regexp org-scheduled-time-regexp)
14841 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
14842 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
14843 d2 diff pos pos1 category tags
14844 ee txt head)
14845 (goto-char (point-min))
14846 (while (re-search-forward regexp nil t)
14847 (catch :skip
14848 (org-agenda-skip)
14849 (setq pos (1- (match-beginning 1))
14850 d2 (time-to-days
14851 (org-time-string-to-time (match-string 1)))
14852 diff (- d2 d1))
14853 ;; When to show a scheduled item in the calendar:
14854 ;; If it is on or past the date.
14855 (if (and (< diff 0) todayp)
14856 (save-excursion
14857 (setq category (org-get-category))
14858 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
14859 (progn
14860 (goto-char (match-end 0))
14861 (setq pos1 (match-end 1))
14862 (setq tags (org-get-tags-at))
14863 (setq head (buffer-substring-no-properties
14864 (point)
14865 (progn (skip-chars-forward "^\r\n") (point))))
14866 (if (string-match org-looking-at-done-regexp head)
14867 (setq txt nil)
14868 (setq txt (org-format-agenda-item
14869 (format "Sched.%2dx: " (- 1 diff)) head
14870 category tags))))
14871 (setq txt org-agenda-no-heading-message))
14872 (when txt
14873 (org-add-props txt props
14874 'org-marker (org-agenda-new-marker pos)
14875 'org-hd-marker (org-agenda-new-marker pos1)
14876 'priority (+ (- 5 diff) (org-get-priority txt))
14877 'org-category category)
14878 (push txt ee))))))
14879 ee))
14881 (defun org-agenda-get-blocks ()
14882 "Return the date-range information for agenda display."
14883 (let* ((props (list 'face nil
14884 'org-not-done-regexp org-not-done-regexp
14885 'mouse-face 'highlight
14886 'keymap org-agenda-keymap
14887 'help-echo
14888 (format "mouse-2 or RET jump to org file %s"
14889 (abbreviate-file-name buffer-file-name))))
14890 (regexp org-tr-regexp)
14891 (d0 (calendar-absolute-from-gregorian date))
14892 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
14893 (goto-char (point-min))
14894 (while (re-search-forward regexp nil t)
14895 (catch :skip
14896 (org-agenda-skip)
14897 (setq pos (point))
14898 (setq timestr (match-string 0)
14899 s1 (match-string 1)
14900 s2 (match-string 2)
14901 d1 (time-to-days (org-time-string-to-time s1))
14902 d2 (time-to-days (org-time-string-to-time s2)))
14903 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
14904 ;; Only allow days between the limits, because the normal
14905 ;; date stamps will catch the limits.
14906 (save-excursion
14907 (setq marker (org-agenda-new-marker (point)))
14908 (setq category (org-get-category))
14909 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
14910 (progn
14911 (setq hdmarker (org-agenda-new-marker (match-end 1)))
14912 (goto-char (match-end 1))
14913 (setq tags (org-get-tags-at))
14914 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
14915 (setq txt (org-format-agenda-item
14916 (format (if (= d1 d2) "" "(%d/%d): ")
14917 (1+ (- d0 d1)) (1+ (- d2 d1)))
14918 (match-string 1) category tags
14919 (if (= d0 d1) timestr))))
14920 (setq txt org-agenda-no-heading-message))
14921 (org-add-props txt props
14922 'org-marker marker 'org-hd-marker hdmarker
14923 'priority (org-get-priority txt) 'org-category category)
14924 (push txt ee)))
14925 (goto-char pos)))
14926 ;; Sort the entries by expiration date.
14927 (nreverse ee)))
14929 ;;; Agenda presentation and sorting
14931 ;; FIXME: should I allow spaces around the dash?
14932 (defconst org-plain-time-of-day-regexp
14933 (concat
14934 "\\(\\<[012]?[0-9]"
14935 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
14936 "\\(--?"
14937 "\\(\\<[012]?[0-9]"
14938 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
14939 "\\)?")
14940 "Regular expression to match a plain time or time range.
14941 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
14942 groups carry important information:
14943 0 the full match
14944 1 the first time, range or not
14945 8 the second time, if it is a range.")
14947 (defconst org-stamp-time-of-day-regexp
14948 (concat
14949 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
14950 "\\([012][0-9]:[0-5][0-9]\\)>"
14951 "\\(--?"
14952 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
14953 "Regular expression to match a timestamp time or time range.
14954 After a match, the following groups carry important information:
14955 0 the full match
14956 1 date plus weekday, for backreferencing to make sure both times on same day
14957 2 the first time, range or not
14958 4 the second time, if it is a range.")
14960 (defvar org-prefix-has-time nil
14961 "A flag, set by `org-compile-prefix-format'.
14962 The flag is set if the currently compiled format contains a `%t'.")
14963 (defvar org-prefix-has-tag nil
14964 "A flag, set by `org-compile-prefix-format'.
14965 The flag is set if the currently compiled format contains a `%T'.")
14967 (defun org-format-agenda-item (extra txt &optional category tags dotime
14968 noprefix)
14969 "Format TXT to be inserted into the agenda buffer.
14970 In particular, it adds the prefix and corresponding text properties. EXTRA
14971 must be a string and replaces the `%s' specifier in the prefix format.
14972 CATEGORY (string, symbol or nil) may be used to overrule the default
14973 category taken from local variable or file name. It will replace the `%c'
14974 specifier in the format. DOTIME, when non-nil, indicates that a
14975 time-of-day should be extracted from TXT for sorting of this entry, and for
14976 the `%t' specifier in the format. When DOTIME is a string, this string is
14977 searched for a time before TXT is. NOPREFIX is a flag and indicates that
14978 only the correctly processes TXT should be returned - this is used by
14979 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
14980 (save-match-data
14981 ;; Diary entries sometimes have extra whitespace at the beginning
14982 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
14983 (let* ((category (or category
14984 org-category
14985 (if buffer-file-name
14986 (file-name-sans-extension
14987 (file-name-nondirectory buffer-file-name))
14988 "")))
14989 (tag (if tags (nth (1- (length tags)) tags) ""))
14990 time ; time and tag are needed for the eval of the prefix format
14991 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
14992 (time-of-day (and dotime (org-get-time-of-day ts)))
14993 stamp plain s0 s1 s2 rtn)
14994 (when (and dotime time-of-day org-prefix-has-time)
14995 ;; Extract starting and ending time and move them to prefix
14996 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
14997 (setq plain (string-match org-plain-time-of-day-regexp ts)))
14998 (setq s0 (match-string 0 ts)
14999 s1 (match-string (if plain 1 2) ts)
15000 s2 (match-string (if plain 8 4) ts))
15002 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
15003 ;; them, we might want to remove them there to avoid duplication.
15004 ;; The user can turn this off with a variable.
15005 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
15006 (string-match (concat (regexp-quote s0) " *") txt)
15007 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
15008 (= (match-beginning 0) 0)
15010 (setq txt (replace-match "" nil nil txt))))
15011 ;; Normalize the time(s) to 24 hour
15012 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
15013 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
15015 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
15016 ;; Tags are in the string
15017 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
15018 (and org-agenda-remove-tags-when-in-prefix
15019 org-prefix-has-tag))
15020 (setq txt (replace-match "" t t txt))
15021 (setq txt (replace-match
15022 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
15023 (match-string 2 txt))
15024 t t txt))))
15026 ;; Create the final string
15027 (if noprefix
15028 (setq rtn txt)
15029 ;; Prepare the variables needed in the eval of the compiled format
15030 (setq time (cond (s2 (concat s1 "-" s2))
15031 (s1 (concat s1 "......"))
15032 (t ""))
15033 extra (or extra "")
15034 category (if (symbolp category) (symbol-name category) category))
15035 ;; Evaluate the compiled format
15036 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
15038 ;; And finally add the text properties
15039 (org-add-props rtn nil
15040 'org-category (downcase category) 'tags tags
15041 'prefix-length (- (length rtn) (length txt))
15042 'time-of-day time-of-day
15043 'dotime dotime))))
15045 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
15046 (defvar org-agenda-sorting-strategy-selected nil)
15048 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
15049 (catch 'exit
15050 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
15051 ((and todayp (member 'today (car org-agenda-time-grid))))
15052 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
15053 ((member 'weekly (car org-agenda-time-grid)))
15054 (t (throw 'exit list)))
15055 (let* ((have (delq nil (mapcar
15056 (lambda (x) (get-text-property 1 'time-of-day x))
15057 list)))
15058 (string (nth 1 org-agenda-time-grid))
15059 (gridtimes (nth 2 org-agenda-time-grid))
15060 (req (car org-agenda-time-grid))
15061 (remove (member 'remove-match req))
15062 new time)
15063 (if (and (member 'require-timed req) (not have))
15064 ;; don't show empty grid
15065 (throw 'exit list))
15066 (while (setq time (pop gridtimes))
15067 (unless (and remove (member time have))
15068 (setq time (int-to-string time))
15069 (push (org-format-agenda-item
15070 nil string "" nil
15071 (concat (substring time 0 -2) ":" (substring time -2)))
15072 new)
15073 (put-text-property
15074 1 (length (car new)) 'face 'org-time-grid (car new))))
15075 (if (member 'time-up org-agenda-sorting-strategy-selected)
15076 (append new list)
15077 (append list new)))))
15079 (defun org-compile-prefix-format (key)
15080 "Compile the prefix format into a Lisp form that can be evaluated.
15081 The resulting form is returned and stored in the variable
15082 `org-prefix-format-compiled'."
15083 (setq org-prefix-has-time nil org-prefix-has-tag nil)
15084 (let ((s (cond
15085 ((stringp org-agenda-prefix-format)
15086 org-agenda-prefix-format)
15087 ((assq key org-agenda-prefix-format)
15088 (cdr (assq key org-agenda-prefix-format)))
15089 (t " %-12:c%?-12t% s")))
15090 (start 0)
15091 varform vars var e c f opt)
15092 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
15093 s start)
15094 (setq var (cdr (assoc (match-string 4 s)
15095 '(("c" . category) ("t" . time) ("s" . extra)
15096 ("T" . tag))))
15097 c (or (match-string 3 s) "")
15098 opt (match-beginning 1)
15099 start (1+ (match-beginning 0)))
15100 (if (equal var 'time) (setq org-prefix-has-time t))
15101 (if (equal var 'tag) (setq org-prefix-has-tag t))
15102 (setq f (concat "%" (match-string 2 s) "s"))
15103 (if opt
15104 (setq varform
15105 `(if (equal "" ,var)
15107 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
15108 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
15109 (setq s (replace-match "%s" t nil s))
15110 (push varform vars))
15111 (setq vars (nreverse vars))
15112 (setq org-prefix-format-compiled `(format ,s ,@vars))))
15114 (defun org-set-sorting-strategy (key)
15115 (if (symbolp (car org-agenda-sorting-strategy))
15116 ;; the old format
15117 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
15118 (setq org-agenda-sorting-strategy-selected
15119 (or (cdr (assq key org-agenda-sorting-strategy))
15120 (cdr (assq 'agenda org-agenda-sorting-strategy))
15121 '(time-up category-keep priority-down)))))
15123 (defun org-get-time-of-day (s &optional string mod24)
15124 "Check string S for a time of day.
15125 If found, return it as a military time number between 0 and 2400.
15126 If not found, return nil.
15127 The optional STRING argument forces conversion into a 5 character wide string
15128 HH:MM."
15129 (save-match-data
15130 (when
15132 (string-match
15133 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
15134 (string-match
15135 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
15136 (let* ((h (string-to-number (match-string 1 s)))
15137 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
15138 (ampm (if (match-end 4) (downcase (match-string 4 s))))
15139 (am-p (equal ampm "am"))
15140 (h1 (cond ((not ampm) h)
15141 ((= h 12) (if am-p 0 12))
15142 (t (+ h (if am-p 0 12)))))
15143 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
15144 (mod h1 24) h1))
15145 (t0 (+ (* 100 h2) m))
15146 (t1 (concat (if (>= h1 24) "+" " ")
15147 (if (< t0 100) "0" "")
15148 (if (< t0 10) "0" "")
15149 (int-to-string t0))))
15150 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
15152 (defun org-finalize-agenda-entries (list &optional nosort)
15153 "Sort and concatenate the agenda items."
15154 (setq list (mapcar 'org-agenda-highlight-todo list))
15155 (if nosort
15156 list
15157 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
15159 (defun org-agenda-highlight-todo (x)
15160 (let (re pl)
15161 (if (eq x 'line)
15162 (save-excursion
15163 (beginning-of-line 1)
15164 (setq re (get-text-property (point) 'org-not-done-regexp))
15165 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
15166 (and (looking-at (concat "[ \t]*\\.*" re))
15167 (add-text-properties (match-beginning 0) (match-end 0)
15168 '(face org-todo))))
15169 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
15170 pl (get-text-property 0 'prefix-length x))
15171 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
15172 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
15173 '(face org-todo) x))
15174 x)))
15176 (defsubst org-cmp-priority (a b)
15177 "Compare the priorities of string A and B."
15178 (let ((pa (or (get-text-property 1 'priority a) 0))
15179 (pb (or (get-text-property 1 'priority b) 0)))
15180 (cond ((> pa pb) +1)
15181 ((< pa pb) -1)
15182 (t nil))))
15184 (defsubst org-cmp-category (a b)
15185 "Compare the string values of categories of strings A and B."
15186 (let ((ca (or (get-text-property 1 'category a) ""))
15187 (cb (or (get-text-property 1 'category b) "")))
15188 (cond ((string-lessp ca cb) -1)
15189 ((string-lessp cb ca) +1)
15190 (t nil))))
15192 (defsubst org-cmp-tag (a b)
15193 "Compare the string values of categories of strings A and B."
15194 (let ((ta (car (last (get-text-property 1 'tags a))))
15195 (tb (car (last (get-text-property 1 'tags b)))))
15196 (cond ((not ta) +1)
15197 ((not tb) -1)
15198 ((string-lessp ta tb) -1)
15199 ((string-lessp tb ta) +1)
15200 (t nil))))
15202 (defsubst org-cmp-time (a b)
15203 "Compare the time-of-day values of strings A and B."
15204 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
15205 (ta (or (get-text-property 1 'time-of-day a) def))
15206 (tb (or (get-text-property 1 'time-of-day b) def)))
15207 (cond ((< ta tb) -1)
15208 ((< tb ta) +1)
15209 (t nil))))
15211 (defun org-entries-lessp (a b)
15212 "Predicate for sorting agenda entries."
15213 ;; The following variables will be used when the form is evaluated.
15214 ;; So even though the compiler complains, keep them.
15215 (let* ((time-up (org-cmp-time a b))
15216 (time-down (if time-up (- time-up) nil))
15217 (priority-up (org-cmp-priority a b))
15218 (priority-down (if priority-up (- priority-up) nil))
15219 (category-up (org-cmp-category a b))
15220 (category-down (if category-up (- category-up) nil))
15221 (category-keep (if category-up +1 nil))
15222 (tag-up (org-cmp-tag a b))
15223 (tag-down (if tag-up (- tag-up) nil)))
15224 (cdr (assoc
15225 (eval (cons 'or org-agenda-sorting-strategy-selected))
15226 '((-1 . t) (1 . nil) (nil . nil))))))
15228 ;;; Agenda commands
15230 (defun org-agenda-check-type (error &rest types)
15231 "Check if agenda buffer is of allowed type.
15232 If ERROR is non-nil, throw an error, otherwise just return nil."
15233 (if (memq org-agenda-type types)
15235 (if error
15236 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
15237 nil)))
15239 (defun org-agenda-quit ()
15240 "Exit agenda by removing the window or the buffer."
15241 (interactive)
15242 (let ((buf (current-buffer)))
15243 (if (not (one-window-p)) (delete-window))
15244 (kill-buffer buf)
15245 (org-agenda-maybe-reset-markers 'force))
15246 ;; Maybe restore the pre-agenda window configuration.
15247 (and org-agenda-restore-windows-after-quit
15248 (not (eq org-agenda-window-setup 'other-frame))
15249 org-pre-agenda-window-conf
15250 (set-window-configuration org-pre-agenda-window-conf)))
15252 (defun org-agenda-exit ()
15253 "Exit agenda by removing the window or the buffer.
15254 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
15255 Org-mode buffers visited directly by the user will not be touched."
15256 (interactive)
15257 (org-release-buffers org-agenda-new-buffers)
15258 (setq org-agenda-new-buffers nil)
15259 (org-agenda-quit))
15261 (defun org-save-all-org-buffers ()
15262 "Save all Org-mode buffers without user confirmation."
15263 (interactive)
15264 (message "Saving all Org-mode buffers...")
15265 (save-some-buffers t 'org-mode-p)
15266 (message "Saving all Org-mode buffers... done"))
15268 (defun org-agenda-redo ()
15269 "Rebuild Agenda.
15270 When this is the global TODO list, a prefix argument will be interpreted."
15271 (interactive)
15272 (let* ((org-agenda-keep-modes t)
15273 (line (org-current-line))
15274 (window-line (- line (org-current-line (window-start)))))
15275 (message "Rebuilding agenda buffer...")
15276 (eval org-agenda-redo-command)
15277 (setq org-agenda-undo-list nil
15278 org-agenda-pending-undo-list nil)
15279 (message "Rebuilding agenda buffer...done")
15280 (goto-line line)
15281 (recenter window-line)))
15283 (defun org-agenda-goto-today ()
15284 "Go to today."
15285 (interactive)
15286 (org-agenda-check-type t 'timeline 'agenda)
15287 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
15288 (cond
15289 (tdpos (goto-char tdpos))
15290 ((eq org-agenda-type 'agenda)
15291 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
15292 (setf (nth 1 org-agenda-overriding-arguments) nil)
15293 (org-agenda-redo)
15294 (org-agenda-find-today-or-agenda)))
15295 (t (error "Cannot find today")))))
15297 (defun org-agenda-find-today-or-agenda ()
15298 (goto-char
15299 (or (text-property-any (point-min) (point-max) 'org-today t)
15300 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
15301 (point-min))))
15303 (defun org-agenda-later (arg)
15304 "Go forward in time by `org-agenda-ndays' days.
15305 With prefix ARG, go forward that many times `org-agenda-ndays'."
15306 (interactive "p")
15307 (org-agenda-check-type t 'agenda)
15308 (let ((org-agenda-overriding-arguments
15309 (list (car org-agenda-last-arguments)
15310 (+ org-starting-day (* arg org-agenda-ndays))
15311 nil t)))
15312 (org-agenda-redo)
15313 (org-agenda-find-today-or-agenda)))
15315 (defun org-agenda-earlier (arg)
15316 "Go back in time by `org-agenda-ndays' days.
15317 With prefix ARG, go back that many times `org-agenda-ndays'."
15318 (interactive "p")
15319 (org-agenda-check-type t 'agenda)
15320 (let ((org-agenda-overriding-arguments
15321 (list (car org-agenda-last-arguments)
15322 (- org-starting-day (* arg org-agenda-ndays))
15323 nil t)))
15324 (org-agenda-redo)
15325 (org-agenda-find-today-or-agenda)))
15327 (defun org-agenda-week-view ()
15328 "Switch to weekly view for agenda."
15329 (interactive)
15330 (org-agenda-check-type t 'agenda)
15331 (if (= org-agenda-ndays 7)
15332 (error "This is already the week view"))
15333 (setq org-agenda-ndays 7)
15334 (let ((org-agenda-overriding-arguments
15335 (list (car org-agenda-last-arguments)
15336 (or (get-text-property (point) 'day)
15337 org-starting-day)
15338 nil t)))
15339 (org-agenda-redo)
15340 (org-agenda-find-today-or-agenda))
15341 (org-agenda-set-mode-name)
15342 (message "Switched to week view"))
15344 (defun org-agenda-day-view ()
15345 "Switch to daily view for agenda."
15346 (interactive)
15347 (org-agenda-check-type t 'agenda)
15348 (if (= org-agenda-ndays 1)
15349 (error "This is already the day view"))
15350 (setq org-agenda-ndays 1)
15351 (let ((org-agenda-overriding-arguments
15352 (list (car org-agenda-last-arguments)
15353 (or (get-text-property (point) 'day)
15354 org-starting-day)
15355 nil t)))
15356 (org-agenda-redo)
15357 (org-agenda-find-today-or-agenda))
15358 (org-agenda-set-mode-name)
15359 (message "Switched to day view"))
15361 ;; FIXME: this no longer works if user make date format that starts with a blank
15362 (defun org-agenda-next-date-line (&optional arg)
15363 "Jump to the next line indicating a date in agenda buffer."
15364 (interactive "p")
15365 (org-agenda-check-type t 'agenda 'timeline)
15366 (beginning-of-line 1)
15367 (if (looking-at "^\\S-") (forward-char 1))
15368 (if (not (re-search-forward "^\\S-" nil t arg))
15369 (progn
15370 (backward-char 1)
15371 (error "No next date after this line in this buffer")))
15372 (goto-char (match-beginning 0)))
15374 (defun org-agenda-previous-date-line (&optional arg)
15375 "Jump to the previous line indicating a date in agenda buffer."
15376 (interactive "p")
15377 (org-agenda-check-type t 'agenda 'timeline)
15378 (beginning-of-line 1)
15379 (if (not (re-search-backward "^\\S-" nil t arg))
15380 (error "No previous date before this line in this buffer")))
15382 ;; Initialize the highlight
15383 (defvar org-hl (org-make-overlay 1 1))
15384 (org-overlay-put org-hl 'face 'highlight)
15386 (defun org-highlight (begin end &optional buffer)
15387 "Highlight a region with overlay."
15388 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
15389 org-hl begin end (or buffer (current-buffer))))
15391 (defun org-unhighlight ()
15392 "Detach overlay INDEX."
15393 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
15395 (defun org-highlight-until-next-command (beg end &optional buffer)
15396 (org-highlight beg end buffer)
15397 (add-hook 'pre-command-hook 'org-unhighlight-once))
15399 (defun org-unhighlight-once ()
15400 (remove-hook 'pre-command-hook 'org-unhighlight-once)
15401 (org-unhighlight))
15403 (defun org-agenda-follow-mode ()
15404 "Toggle follow mode in an agenda buffer."
15405 (interactive)
15406 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
15407 (org-agenda-set-mode-name)
15408 (message "Follow mode is %s"
15409 (if org-agenda-follow-mode "on" "off")))
15411 (defun org-agenda-log-mode ()
15412 "Toggle log mode in an agenda buffer."
15413 (interactive)
15414 (org-agenda-check-type t 'agenda 'timeline)
15415 (setq org-agenda-show-log (not org-agenda-show-log))
15416 (org-agenda-set-mode-name)
15417 (org-agenda-redo)
15418 (message "Log mode is %s"
15419 (if org-agenda-show-log "on" "off")))
15421 (defun org-agenda-toggle-diary ()
15422 "Toggle diary inclusion in an agenda buffer."
15423 (interactive)
15424 (org-agenda-check-type t 'agenda)
15425 (setq org-agenda-include-diary (not org-agenda-include-diary))
15426 (org-agenda-redo)
15427 (org-agenda-set-mode-name)
15428 (message "Diary inclusion turned %s"
15429 (if org-agenda-include-diary "on" "off")))
15431 (defun org-agenda-toggle-time-grid ()
15432 "Toggle time grid in an agenda buffer."
15433 (interactive)
15434 (org-agenda-check-type t 'agenda)
15435 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
15436 (org-agenda-redo)
15437 (org-agenda-set-mode-name)
15438 (message "Time-grid turned %s"
15439 (if org-agenda-use-time-grid "on" "off")))
15441 (defun org-agenda-set-mode-name ()
15442 "Set the mode name to indicate all the small mode settings."
15443 (setq mode-name
15444 (concat "Org-Agenda"
15445 (if (equal org-agenda-ndays 1) " Day" "")
15446 (if (equal org-agenda-ndays 7) " Week" "")
15447 (if org-agenda-follow-mode " Follow" "")
15448 (if org-agenda-include-diary " Diary" "")
15449 (if org-agenda-use-time-grid " Grid" "")
15450 (if org-agenda-show-log " Log" "")))
15451 (force-mode-line-update))
15453 (defun org-agenda-post-command-hook ()
15454 (and (eolp) (not (bolp)) (backward-char 1))
15455 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
15456 (if (and org-agenda-follow-mode
15457 (get-text-property (point) 'org-marker))
15458 (org-agenda-show)))
15460 (defun org-agenda-show-priority ()
15461 "Show the priority of the current item.
15462 This priority is composed of the main priority given with the [#A] cookies,
15463 and by additional input from the age of a schedules or deadline entry."
15464 (interactive)
15465 (let* ((pri (get-text-property (point-at-bol) 'priority)))
15466 (message "Priority is %d" (if pri pri -1000))))
15468 (defun org-agenda-show-tags ()
15469 "Show the tags applicable to the current item."
15470 (interactive)
15471 (let* ((tags (get-text-property (point-at-bol) 'tags)))
15472 (if tags
15473 (message "Tags are :%s:"
15474 (org-no-properties (mapconcat 'identity tags ":")))
15475 (message "No tags associated with this line"))))
15477 (defun org-agenda-goto (&optional highlight)
15478 "Go to the Org-mode file which contains the item at point."
15479 (interactive)
15480 (let* ((marker (or (get-text-property (point) 'org-marker)
15481 (org-agenda-error)))
15482 (buffer (marker-buffer marker))
15483 (pos (marker-position marker)))
15484 (switch-to-buffer-other-window buffer)
15485 (widen)
15486 (goto-char pos)
15487 (when (org-mode-p)
15488 (org-show-context 'agenda)
15489 (save-excursion
15490 (and (outline-next-heading)
15491 (org-flag-heading nil)))) ; show the next heading
15492 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
15494 (defun org-agenda-kill ()
15495 "Kill the entry or subtree belonging to the current agenda entry."
15496 (interactive)
15497 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15498 (let* ((marker (or (get-text-property (point) 'org-marker)
15499 (org-agenda-error)))
15500 (buffer (marker-buffer marker))
15501 (pos (marker-position marker))
15502 dbeg dend (n 0) conf)
15503 (org-with-remote-undo buffer
15504 (with-current-buffer buffer
15505 (save-excursion
15506 (goto-char pos)
15507 (if (org-mode-p)
15508 (setq dbeg (progn (org-back-to-heading t) (point))
15509 dend (org-end-of-subtree t))
15510 (setq dbeg (point-at-bol)
15511 dend (min (point-max) (1+ (point-at-eol)))))
15512 (goto-char dbeg)
15513 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
15514 (setq conf (or (eq t org-agenda-confirm-kill)
15515 (and (numberp org-agenda-confirm-kill)
15516 (> n org-agenda-confirm-kill))))
15517 (and conf
15518 (not (y-or-n-p
15519 (format "Delete entry with %d lines in buffer \"%s\"? "
15520 n (buffer-name buffer))))
15521 (error "Abort"))
15522 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
15523 (with-current-buffer buffer (delete-region dbeg dend))
15524 (message "Agenda item and source killed"))))
15526 (defun org-agenda-archive ()
15527 "Kill the entry or subtree belonging to the current agenda entry."
15528 (interactive)
15529 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15530 (let* ((marker (or (get-text-property (point) 'org-marker)
15531 (org-agenda-error)))
15532 (buffer (marker-buffer marker))
15533 (pos (marker-position marker)))
15534 (org-with-remote-undo buffer
15535 (with-current-buffer buffer
15536 (if (org-mode-p)
15537 (save-excursion
15538 (goto-char pos)
15539 (org-remove-subtree-entries-from-agenda)
15540 (org-back-to-heading t)
15541 (org-archive-subtree))
15542 (error "Archiving works only in Org-mode files"))))))
15544 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
15545 "Remove all lines in the agenda that correspond to a given subtree.
15546 The subtree is the one in buffer BUF, starting at BEG and ending at END.
15547 If this information is not given, the function uses the tree at point."
15548 (let ((buf (or buf (current-buffer))) m p)
15549 (save-excursion
15550 (unless (and beg end)
15551 (org-back-to-heading t)
15552 (setq beg (point))
15553 (org-end-of-subtree t)
15554 (setq end (point)))
15555 (set-buffer (get-buffer org-agenda-buffer-name))
15556 (save-excursion
15557 (goto-char (point-max))
15558 (beginning-of-line 1)
15559 (while (not (bobp))
15560 (when (and (setq m (get-text-property (point) 'org-marker))
15561 (equal buf (marker-buffer m))
15562 (setq p (marker-position m))
15563 (>= p beg)
15564 (<= p end))
15565 (let (buffer-read-only)
15566 (delete-region (point-at-bol) (1+ (point-at-eol)))))
15567 (beginning-of-line 0))))))
15569 (defun org-agenda-open-link ()
15570 "Follow the link in the current line, if any."
15571 (interactive)
15572 (let ((eol (point-at-eol)))
15573 (save-excursion
15574 (if (or (re-search-forward org-bracket-link-regexp eol t)
15575 (re-search-forward org-angle-link-re eol t)
15576 (re-search-forward org-plain-link-re eol t))
15577 (call-interactively 'org-open-at-point)
15578 (error "No link in current line")))))
15580 (defun org-agenda-switch-to (&optional delete-other-windows)
15581 "Go to the Org-mode file which contains the item at point."
15582 (interactive)
15583 (let* ((marker (or (get-text-property (point) 'org-marker)
15584 (org-agenda-error)))
15585 (buffer (marker-buffer marker))
15586 (pos (marker-position marker)))
15587 (switch-to-buffer buffer)
15588 (and delete-other-windows (delete-other-windows))
15589 (widen)
15590 (goto-char pos)
15591 (when (org-mode-p)
15592 (org-show-context 'agenda)
15593 (save-excursion
15594 (and (outline-next-heading)
15595 (org-flag-heading nil)))))) ; show the next heading
15597 (defun org-agenda-goto-mouse (ev)
15598 "Go to the Org-mode file which contains the item at the mouse click."
15599 (interactive "e")
15600 (mouse-set-point ev)
15601 (org-agenda-goto))
15603 (defun org-agenda-show ()
15604 "Display the Org-mode file which contains the item at point."
15605 (interactive)
15606 (let ((win (selected-window)))
15607 (org-agenda-goto t)
15608 (select-window win)))
15610 (defun org-agenda-recenter (arg)
15611 "Display the Org-mode file which contains the item at point and recenter."
15612 (interactive "P")
15613 (let ((win (selected-window)))
15614 (org-agenda-goto t)
15615 (recenter arg)
15616 (select-window win)))
15618 (defun org-agenda-show-mouse (ev)
15619 "Display the Org-mode file which contains the item at the mouse click."
15620 (interactive "e")
15621 (mouse-set-point ev)
15622 (org-agenda-show))
15624 (defun org-agenda-check-no-diary ()
15625 "Check if the entry is a diary link and abort if yes."
15626 (if (get-text-property (point) 'org-agenda-diary-link)
15627 (org-agenda-error)))
15629 (defun org-agenda-error ()
15630 (error "Command not allowed in this line"))
15632 (defun org-agenda-tree-to-indirect-buffer ()
15633 "Show the subtree corresponding to the current entry in an indirect buffer.
15634 This calls the command `org-tree-to-indirect-buffer' from the original
15635 Org-mode buffer.
15636 With numerical prefix arg ARG, go up to this level and then take that tree.
15637 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
15638 dedicated frame)."
15639 (interactive)
15640 (org-agenda-check-no-diary)
15641 (let* ((marker (or (get-text-property (point) 'org-marker)
15642 (org-agenda-error)))
15643 (buffer (marker-buffer marker))
15644 (pos (marker-position marker)))
15645 (with-current-buffer buffer
15646 (save-excursion
15647 (goto-char pos)
15648 (call-interactively 'org-tree-to-indirect-buffer)))))
15650 (defvar org-last-heading-marker (make-marker)
15651 "Marker pointing to the headline that last changed its TODO state
15652 by a remote command from the agenda.")
15654 (defun org-agenda-todo (&optional arg)
15655 "Cycle TODO state of line at point, also in Org-mode file.
15656 This changes the line at point, all other lines in the agenda referring to
15657 the same tree node, and the headline of the tree node in the Org-mode file."
15658 (interactive "P")
15659 (org-agenda-check-no-diary)
15660 (let* ((col (current-column))
15661 (marker (or (get-text-property (point) 'org-marker)
15662 (org-agenda-error)))
15663 (buffer (marker-buffer marker))
15664 (pos (marker-position marker))
15665 (hdmarker (get-text-property (point) 'org-hd-marker))
15666 (buffer-read-only nil)
15667 newhead)
15668 (org-with-remote-undo buffer
15669 (with-current-buffer buffer
15670 (widen)
15671 (goto-char pos)
15672 (org-show-context 'agenda)
15673 (save-excursion
15674 (and (outline-next-heading)
15675 (org-flag-heading nil))) ; show the next heading
15676 (org-todo arg)
15677 (and (bolp) (forward-char 1))
15678 (setq newhead (org-get-heading))
15679 (save-excursion
15680 (org-back-to-heading)
15681 (move-marker org-last-heading-marker (point))))
15682 (beginning-of-line 1)
15683 (save-excursion
15684 (org-agenda-change-all-lines newhead hdmarker 'fixface))
15685 (move-to-column col))))
15687 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
15688 "Change all lines in the agenda buffer which match HDMARKER.
15689 The new content of the line will be NEWHEAD (as modified by
15690 `org-format-agenda-item'). HDMARKER is checked with
15691 `equal' against all `org-hd-marker' text properties in the file.
15692 If FIXFACE is non-nil, the face of each item is modified acording to
15693 the new TODO state."
15694 (let* ((buffer-read-only nil)
15695 props m pl undone-face done-face finish new dotime cat tags)
15696 (save-excursion
15697 (goto-char (point-max))
15698 (beginning-of-line 1)
15699 (while (not finish)
15700 (setq finish (bobp))
15701 (when (and (setq m (get-text-property (point) 'org-hd-marker))
15702 (equal m hdmarker))
15703 (setq props (text-properties-at (point))
15704 dotime (get-text-property (point) 'dotime)
15705 cat (get-text-property (point) 'org-category)
15706 tags (get-text-property (point) 'tags)
15707 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
15708 pl (get-text-property (point) 'prefix-length)
15709 undone-face (get-text-property (point) 'undone-face)
15710 done-face (get-text-property (point) 'done-face))
15711 (move-to-column pl)
15712 (cond
15713 ((equal new "")
15714 (beginning-of-line 1)
15715 (and (looking-at ".*\n?") (replace-match "")))
15716 ((looking-at ".*")
15717 (replace-match new t t)
15718 (beginning-of-line 1)
15719 (add-text-properties (point-at-bol) (point-at-eol) props)
15720 (when fixface
15721 (add-text-properties
15722 (point-at-bol) (point-at-eol)
15723 (list 'face
15724 (if org-last-todo-state-is-todo
15725 undone-face done-face))))
15726 (org-agenda-highlight-todo 'line)
15727 (beginning-of-line 1))
15728 (t (error "Line update did not work"))))
15729 (beginning-of-line 0)))
15730 (org-finalize-agenda)))
15732 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
15733 ;; See the code in set-tags for the way to do this.
15734 (defun org-agenda-align-tags (&optional line)
15735 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
15736 (let ((buffer-read-only))
15737 (save-excursion
15738 (goto-char (if line (point-at-bol) (point-min)))
15739 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
15740 (if line (point-at-eol) nil) t)
15741 (delete-region (match-beginning 1) (match-end 1))
15742 (goto-char (match-beginning 1))
15743 (insert (org-add-props
15744 (make-string (max 1 (- org-agenda-align-tags-to-column
15745 (current-column))) ?\ )
15746 (text-properties-at (point))))))))
15748 (defun org-agenda-priority-up ()
15749 "Increase the priority of line at point, also in Org-mode file."
15750 (interactive)
15751 (org-agenda-priority 'up))
15753 (defun org-agenda-priority-down ()
15754 "Decrease the priority of line at point, also in Org-mode file."
15755 (interactive)
15756 (org-agenda-priority 'down))
15758 (defun org-agenda-priority (&optional force-direction)
15759 "Set the priority of line at point, also in Org-mode file.
15760 This changes the line at point, all other lines in the agenda referring to
15761 the same tree node, and the headline of the tree node in the Org-mode file."
15762 (interactive)
15763 (org-agenda-check-no-diary)
15764 (let* ((marker (or (get-text-property (point) 'org-marker)
15765 (org-agenda-error)))
15766 (buffer (marker-buffer marker))
15767 (pos (marker-position marker))
15768 (hdmarker (get-text-property (point) 'org-hd-marker))
15769 (buffer-read-only nil)
15770 newhead)
15771 (org-with-remote-undo buffer
15772 (with-current-buffer buffer
15773 (widen)
15774 (goto-char pos)
15775 (org-show-context 'agenda)
15776 (save-excursion
15777 (and (outline-next-heading)
15778 (org-flag-heading nil))) ; show the next heading
15779 (funcall 'org-priority force-direction)
15780 (end-of-line 1)
15781 (setq newhead (org-get-heading)))
15782 (org-agenda-change-all-lines newhead hdmarker)
15783 (beginning-of-line 1))))
15785 (defun org-get-tags-at (&optional pos)
15786 "Get a list of all headline tags applicable at POS.
15787 POS defaults to point. If tags are inherited, the list contains
15788 the targets in the same sequence as the headlines appear, i.e.
15789 the tags of the current headline come last."
15790 (interactive)
15791 (let (tags)
15792 (save-excursion
15793 (save-restriction
15794 (widen)
15795 (goto-char (or pos (point)))
15796 (save-match-data
15797 (org-back-to-heading t)
15798 (condition-case nil
15799 (while t
15800 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
15801 (setq tags (append (org-split-string
15802 (org-match-string-no-properties 1) ":")
15803 tags)))
15804 (or org-use-tag-inheritance (error ""))
15805 (org-up-heading-all 1))
15806 (error nil))))
15807 tags)))
15809 ;; FIXME: should fix the tags property of the agenda line.
15810 (defun org-agenda-set-tags ()
15811 "Set tags for the current headline."
15812 (interactive)
15813 (org-agenda-check-no-diary)
15814 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
15815 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
15816 (org-agenda-error)))
15817 (buffer (marker-buffer hdmarker))
15818 (pos (marker-position hdmarker))
15819 (buffer-read-only nil)
15820 newhead)
15821 (org-with-remote-undo buffer
15822 (with-current-buffer buffer
15823 (widen)
15824 (goto-char pos)
15825 (save-excursion
15826 (org-show-context 'agenda))
15827 (save-excursion
15828 (and (outline-next-heading)
15829 (org-flag-heading nil))) ; show the next heading
15830 (goto-char pos)
15831 (call-interactively 'org-set-tags)
15832 (end-of-line 1)
15833 (setq newhead (org-get-heading)))
15834 (org-agenda-change-all-lines newhead hdmarker)
15835 (beginning-of-line 1))))
15837 (defun org-agenda-toggle-archive-tag ()
15838 "Toggle the archive tag for the current entry."
15839 (interactive)
15840 (org-agenda-check-no-diary)
15841 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
15842 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
15843 (org-agenda-error)))
15844 (buffer (marker-buffer hdmarker))
15845 (pos (marker-position hdmarker))
15846 (buffer-read-only nil)
15847 newhead)
15848 (org-with-remote-undo buffer
15849 (with-current-buffer buffer
15850 (widen)
15851 (goto-char pos)
15852 (org-show-context 'agenda)
15853 (save-excursion
15854 (and (outline-next-heading)
15855 (org-flag-heading nil))) ; show the next heading
15856 (call-interactively 'org-toggle-archive-tag)
15857 (end-of-line 1)
15858 (setq newhead (org-get-heading)))
15859 (org-agenda-change-all-lines newhead hdmarker)
15860 (beginning-of-line 1))))
15862 (defun org-agenda-date-later (arg &optional what)
15863 "Change the date of this item to one day later."
15864 (interactive "p")
15865 (org-agenda-check-type t 'agenda 'timeline)
15866 (org-agenda-check-no-diary)
15867 (let* ((marker (or (get-text-property (point) 'org-marker)
15868 (org-agenda-error)))
15869 (buffer (marker-buffer marker))
15870 (pos (marker-position marker)))
15871 (org-with-remote-undo buffer
15872 (with-current-buffer buffer
15873 (widen)
15874 (goto-char pos)
15875 (if (not (org-at-timestamp-p))
15876 (error "Cannot find time stamp"))
15877 (org-timestamp-change arg (or what 'day)))
15878 (org-agenda-show-new-time marker org-last-changed-timestamp))
15879 (message "Time stamp changed to %s" org-last-changed-timestamp)))
15881 (defun org-agenda-date-earlier (arg &optional what)
15882 "Change the date of this item to one day earlier."
15883 (interactive "p")
15884 (org-agenda-date-later (- arg) what))
15886 (defun org-agenda-show-new-time (marker stamp)
15887 "Show new date stamp via text properties."
15888 ;; We use text properties to make this undoable
15889 (let ((buffer-read-only nil))
15890 (setq stamp (concat " => " stamp))
15891 (save-excursion
15892 (goto-char (point-max))
15893 (while (not (bobp))
15894 (when (equal marker (get-text-property (point) 'org-marker))
15895 (move-to-column (- (window-width) (length stamp)) t)
15896 (if (featurep 'xemacs)
15897 ;; Use `duplicable' property to trigger undo recording
15898 (let ((ex (make-extent nil nil))
15899 (gl (make-glyph stamp)))
15900 (set-glyph-face gl 'secondary-selection)
15901 (set-extent-properties
15902 ex (list 'invisible t 'end-glyph gl 'duplicable t))
15903 (insert-extent ex (1- (point)) (point-at-eol)))
15904 (add-text-properties
15905 (1- (point)) (point-at-eol)
15906 (list 'display (org-add-props stamp nil
15907 'face 'secondary-selection))))
15908 (beginning-of-line 1))
15909 (beginning-of-line 0)))))
15911 (defun org-agenda-date-prompt (arg)
15912 "Change the date of this item. Date is prompted for, with default today.
15913 The prefix ARG is passed to the `org-time-stamp' command and can therefore
15914 be used to request time specification in the time stamp."
15915 (interactive "P")
15916 (org-agenda-check-type t 'agenda 'timeline)
15917 (org-agenda-check-no-diary)
15918 (let* ((marker (or (get-text-property (point) 'org-marker)
15919 (org-agenda-error)))
15920 (buffer (marker-buffer marker))
15921 (pos (marker-position marker)))
15922 (org-with-remote-undo buffer
15923 (with-current-buffer buffer
15924 (widen)
15925 (goto-char pos)
15926 (if (not (org-at-timestamp-p))
15927 (error "Cannot find time stamp"))
15928 (org-time-stamp arg)
15929 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
15931 (defun org-agenda-schedule (arg)
15932 "Schedule the item at point."
15933 (interactive "P")
15934 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
15935 (org-agenda-check-no-diary)
15936 (let* ((marker (or (get-text-property (point) 'org-marker)
15937 (org-agenda-error)))
15938 (buffer (marker-buffer marker))
15939 (pos (marker-position marker))
15940 (org-insert-labeled-timestamps-at-point nil)
15942 (org-with-remote-undo buffer
15943 (with-current-buffer buffer
15944 (widen)
15945 (goto-char pos)
15946 (setq ts (org-schedule))
15947 (message "Item scheduled for %s" ts)))))
15949 (defun org-agenda-deadline (arg)
15950 "Schedule the item at point."
15951 (interactive "P")
15952 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
15953 (org-agenda-check-no-diary)
15954 (let* ((marker (or (get-text-property (point) 'org-marker)
15955 (org-agenda-error)))
15956 (buffer (marker-buffer marker))
15957 (pos (marker-position marker))
15958 (org-insert-labeled-timestamps-at-point nil)
15960 (org-with-remote-undo buffer
15961 (with-current-buffer buffer
15962 (widen)
15963 (goto-char pos)
15964 (setq ts (org-deadline))
15965 (message "Deadline for this item set to %s" ts)))))
15967 (defun org-get-heading ()
15968 "Return the heading of the current entry, without the stars."
15969 (save-excursion
15970 (org-back-to-heading t)
15971 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
15973 (defun org-agenda-clock-in (&optional arg)
15974 "Start the clock on the currently selected item."
15975 (interactive "P")
15976 (org-agenda-check-no-diary)
15977 (let* ((marker (or (get-text-property (point) 'org-marker)
15978 (org-agenda-error)))
15979 (pos (marker-position marker)))
15980 (org-with-remote-undo (marker-buffer marker)
15981 (with-current-buffer (marker-buffer marker)
15982 (widen)
15983 (goto-char pos)
15984 (org-clock-in)))))
15986 (defun org-agenda-clock-out (&optional arg)
15987 "Stop the currently running clock."
15988 (interactive "P")
15989 (unless (marker-buffer org-clock-marker)
15990 (error "No running clock"))
15991 (org-with-remote-undo (marker-buffer org-clock-marker)
15992 (org-clock-out)))
15994 (defun org-agenda-clock-cancel (&optional arg)
15995 "Cancel the currently running clock."
15996 (interactive "P")
15997 (unless (marker-buffer org-clock-marker)
15998 (error "No running clock"))
15999 (org-with-remote-undo (marker-buffer org-clock-marker)
16000 (org-clock-cancel)))
16002 (defun org-agenda-diary-entry ()
16003 "Make a diary entry, like the `i' command from the calendar.
16004 All the standard commands work: block, weekly etc."
16005 (interactive)
16006 (org-agenda-check-type t 'agenda 'timeline)
16007 (require 'diary-lib)
16008 (let* ((char (progn
16009 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
16010 (read-char-exclusive)))
16011 (cmd (cdr (assoc char
16012 '((?d . insert-diary-entry)
16013 (?w . insert-weekly-diary-entry)
16014 (?m . insert-monthly-diary-entry)
16015 (?y . insert-yearly-diary-entry)
16016 (?a . insert-anniversary-diary-entry)
16017 (?b . insert-block-diary-entry)
16018 (?c . insert-cyclic-diary-entry)))))
16019 (oldf (symbol-function 'calendar-cursor-to-date))
16020 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
16021 (point (point))
16022 (mark (or (mark t) (point))))
16023 (unless cmd
16024 (error "No command associated with <%c>" char))
16025 (unless (and (get-text-property point 'day)
16026 (or (not (equal ?b char))
16027 (get-text-property mark 'day)))
16028 (error "Don't know which date to use for diary entry"))
16029 ;; We implement this by hacking the `calendar-cursor-to-date' function
16030 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
16031 (let ((calendar-mark-ring
16032 (list (calendar-gregorian-from-absolute
16033 (or (get-text-property mark 'day)
16034 (get-text-property point 'day))))))
16035 (unwind-protect
16036 (progn
16037 (fset 'calendar-cursor-to-date
16038 (lambda (&optional error)
16039 (calendar-gregorian-from-absolute
16040 (get-text-property point 'day))))
16041 (call-interactively cmd))
16042 (fset 'calendar-cursor-to-date oldf)))))
16045 (defun org-agenda-execute-calendar-command (cmd)
16046 "Execute a calendar command from the agenda, with the date associated to
16047 the cursor position."
16048 (org-agenda-check-type t 'agenda 'timeline)
16049 (require 'diary-lib)
16050 (unless (get-text-property (point) 'day)
16051 (error "Don't know which date to use for calendar command"))
16052 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
16053 (point (point))
16054 (date (calendar-gregorian-from-absolute
16055 (get-text-property point 'day)))
16056 ;; the following 3 vars are needed in the calendar
16057 (displayed-day (extract-calendar-day date))
16058 (displayed-month (extract-calendar-month date))
16059 (displayed-year (extract-calendar-year date)))
16060 (unwind-protect
16061 (progn
16062 (fset 'calendar-cursor-to-date
16063 (lambda (&optional error)
16064 (calendar-gregorian-from-absolute
16065 (get-text-property point 'day))))
16066 (call-interactively cmd))
16067 (fset 'calendar-cursor-to-date oldf))))
16069 (defun org-agenda-phases-of-moon ()
16070 "Display the phases of the moon for the 3 months around the cursor date."
16071 (interactive)
16072 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
16074 (defun org-agenda-holidays ()
16075 "Display the holidays for the 3 months around the cursor date."
16076 (interactive)
16077 (org-agenda-execute-calendar-command 'list-calendar-holidays))
16079 (defun org-agenda-sunrise-sunset (arg)
16080 "Display sunrise and sunset for the cursor date.
16081 Latitude and longitude can be specified with the variables
16082 `calendar-latitude' and `calendar-longitude'. When called with prefix
16083 argument, latitude and longitude will be prompted for."
16084 (interactive "P")
16085 (let ((calendar-longitude (if arg nil calendar-longitude))
16086 (calendar-latitude (if arg nil calendar-latitude))
16087 (calendar-location-name
16088 (if arg "the given coordinates" calendar-location-name)))
16089 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
16091 (defun org-agenda-goto-calendar ()
16092 "Open the Emacs calendar with the date at the cursor."
16093 (interactive)
16094 (org-agenda-check-type t 'agenda 'timeline)
16095 (let* ((day (or (get-text-property (point) 'day)
16096 (error "Don't know which date to open in calendar")))
16097 (date (calendar-gregorian-from-absolute day))
16098 (calendar-move-hook nil)
16099 (view-calendar-holidays-initially nil)
16100 (view-diary-entries-initially nil))
16101 (calendar)
16102 (calendar-goto-date date)))
16104 (defun org-calendar-goto-agenda ()
16105 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
16106 This is a command that has to be installed in `calendar-mode-map'."
16107 (interactive)
16108 (org-agenda-list nil (calendar-absolute-from-gregorian
16109 (calendar-cursor-to-date))
16110 nil))
16112 (defun org-agenda-convert-date ()
16113 (interactive)
16114 (org-agenda-check-type t 'agenda 'timeline)
16115 (let ((day (get-text-property (point) 'day))
16116 date s)
16117 (unless day
16118 (error "Don't know which date to convert"))
16119 (setq date (calendar-gregorian-from-absolute day))
16120 (setq s (concat
16121 "Gregorian: " (calendar-date-string date) "\n"
16122 "ISO: " (calendar-iso-date-string date) "\n"
16123 "Day of Yr: " (calendar-day-of-year-string date) "\n"
16124 "Julian: " (calendar-julian-date-string date) "\n"
16125 "Astron. JD: " (calendar-astro-date-string date)
16126 " (Julian date number at noon UTC)\n"
16127 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
16128 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
16129 "French: " (calendar-french-date-string date) "\n"
16130 "Mayan: " (calendar-mayan-date-string date) "\n"
16131 "Coptic: " (calendar-coptic-date-string date) "\n"
16132 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
16133 "Persian: " (calendar-persian-date-string date) "\n"
16134 "Chinese: " (calendar-chinese-date-string date) "\n"))
16135 (with-output-to-temp-buffer "*Dates*"
16136 (princ s))
16137 (if (fboundp 'fit-window-to-buffer)
16138 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
16141 ;;;; Embedded LaTeX
16143 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16144 "Keymap for the minor `org-cdlatex-mode'.")
16146 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16147 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16148 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16149 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16150 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16152 (defvar org-cdlatex-texmathp-advice-is-done nil
16153 "Flag remembering if we have applied the advice to texmathp already.")
16155 (define-minor-mode org-cdlatex-mode
16156 "Toggle the minor `org-cdlatex-mode'.
16157 This mode supports entering LaTeX environment and math in LaTeX fragments
16158 in Org-mode.
16159 \\{org-cdlatex-mode-map}"
16160 nil " OCDL" nil
16161 (when org-cdlatex-mode (require 'cdlatex))
16162 (unless org-cdlatex-texmathp-advice-is-done
16163 (setq org-cdlatex-texmathp-advice-is-done t)
16164 (defadvice texmathp (around org-math-always-on activate)
16165 "Always return t in org-mode buffers.
16166 This is because we want to insert math symbols without dollars even outside
16167 the LaTeX math segments. If Orgmode thinks that point is actually inside
16168 en embedded LaTeX fragement, let texmathp do its job.
16169 \\[org-cdlatex-mode-map]"
16170 (interactive)
16171 (let (p)
16172 (cond
16173 ((not (org-mode-p)) ad-do-it)
16174 ((eq this-command 'cdlatex-math-symbol)
16175 (setq ad-return-value t
16176 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16178 (let ((p (org-inside-LaTeX-fragment-p)))
16179 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16180 (setq ad-return-value t
16181 texmathp-why '("Org-mode embedded math" . 0))
16182 (if p ad-do-it)))))))))
16184 (defun turn-on-org-cdlatex ()
16185 "Unconditionally turn on `org-cdlatex-mode'."
16186 (org-cdlatex-mode 1))
16188 (defun org-inside-LaTeX-fragment-p ()
16189 "Test if point is inside a LaTeX fragment.
16190 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16191 sequence appearing also before point.
16192 Even though the matchers for math are configurable, this function assumes
16193 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16194 delimiters are skipped when they have been removed by customization.
16195 The return value is nil, or a cons cell with the delimiter and
16196 and the position of this delimiter.
16198 This function does a reasonably good job, but can locally be fooled by
16199 for example currency specifications. For example it will assume being in
16200 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16201 fragments that are properly closed, but during editing, we have to live
16202 with the uncertainty caused by missing closing delimiters. This function
16203 looks only before point, not after."
16204 (catch 'exit
16205 (let ((pos (point))
16206 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16207 (lim (progn
16208 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16209 (point)))
16210 dd-on str (start 0) m re)
16211 (goto-char pos)
16212 (when dodollar
16213 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16214 re (nth 1 (assoc "$" org-latex-regexps)))
16215 (while (string-match re str start)
16216 (cond
16217 ((= (match-end 0) (length str))
16218 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
16219 ((= (match-end 0) (- (length str) 5))
16220 (throw 'exit nil))
16221 (t (setq start (match-end 0))))))
16222 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16223 (goto-char pos)
16224 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16225 (and (match-beginning 2) (throw 'exit nil))
16226 ;; count $$
16227 (while (re-search-backward "\\$\\$" lim t)
16228 (setq dd-on (not dd-on)))
16229 (goto-char pos)
16230 (if dd-on (cons "$$" m))))))
16233 (defun org-try-cdlatex-tab ()
16234 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16235 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16236 - inside a LaTeX fragment, or
16237 - after the first word in a line, where an abbreviation expansion could
16238 insert a LaTeX environment."
16239 (when org-cdlatex-mode
16240 (cond
16241 ((save-excursion
16242 (skip-chars-backward "a-zA-Z0-9*")
16243 (skip-chars-backward " \t")
16244 (bolp))
16245 (cdlatex-tab) t)
16246 ((org-inside-LaTeX-fragment-p)
16247 (cdlatex-tab) t)
16248 (t nil))))
16250 (defun org-cdlatex-underscore-caret (&optional arg)
16251 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16252 Revert to the normal definition outside of these fragments."
16253 (interactive "P")
16254 (if (org-inside-LaTeX-fragment-p)
16255 (call-interactively 'cdlatex-sub-superscript)
16256 (let (org-cdlatex-mode)
16257 (call-interactively (key-binding (vector last-input-event))))))
16259 (defun org-cdlatex-math-modify (&optional arg)
16260 "Execute `cdlatex-math-modify' in LaTeX fragments.
16261 Revert to the normal definition outside of these fragments."
16262 (interactive "P")
16263 (if (org-inside-LaTeX-fragment-p)
16264 (call-interactively 'cdlatex-math-modify)
16265 (let (org-cdlatex-mode)
16266 (call-interactively (key-binding (vector last-input-event))))))
16268 (defvar org-latex-fragment-image-overlays nil
16269 "List of overlays carrying the images of latex fragments.")
16270 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16272 (defun org-remove-latex-fragment-image-overlays ()
16273 "Remove all overlays with LaTeX fragment images in current buffer."
16274 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
16275 (setq org-latex-fragment-image-overlays nil))
16277 (defun org-preview-latex-fragment (&optional subtree)
16278 "Preview the LaTeX fragment at point, or all locally or globally.
16279 If the cursor is in a LaTeX fragment, create the image and overlay
16280 it over the source code. If there is no fragment at point, display
16281 all fragments in the current text, from one headline to the next. With
16282 prefix SUBTREE, display all fragments in the current subtree. With a
16283 double prefix `C-u C-u', or when the cursor is before the first headline,
16284 display all fragments in the buffer.
16285 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16286 (interactive "P")
16287 (org-remove-latex-fragment-image-overlays)
16288 (save-excursion
16289 (save-restriction
16290 (let (beg end at msg)
16291 (cond
16292 ((or (equal subtree '(16))
16293 (not (save-excursion
16294 (re-search-backward (concat "^" outline-regexp) nil t))))
16295 (setq beg (point-min) end (point-max)
16296 msg "Creating images for buffer...%s"))
16297 ((equal subtree '(4))
16298 (org-back-to-heading)
16299 (setq beg (point) end (org-end-of-subtree t)
16300 msg "Creating images for subtree...%s"))
16302 (if (setq at (org-inside-LaTeX-fragment-p))
16303 (goto-char (max (point-min) (- (cdr at) 2)))
16304 (org-back-to-heading))
16305 (setq beg (point) end (progn (outline-next-heading) (point))
16306 msg (if at "Creating image...%s"
16307 "Creating images for entry...%s"))))
16308 (message msg "")
16309 (narrow-to-region beg end)
16310 (org-format-latex
16311 (concat "ltxpng/" (file-name-sans-extension
16312 (file-name-nondirectory
16313 buffer-file-name)))
16314 default-directory 'overlays msg at)
16315 (message msg "done. Use `C-c C-c' to remove images.")))))
16317 (defvar org-latex-regexps
16318 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16319 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16320 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16321 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
16322 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16323 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
16324 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
16325 "Regular expressions for matching embedded LaTeX.")
16327 (defun org-format-latex (prefix &optional dir overlays msg at)
16328 "Replace LaTeX fragments with links to an image, and produce images."
16329 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16330 (let* ((prefixnodir (file-name-nondirectory prefix))
16331 (absprefix (expand-file-name prefix dir))
16332 (todir (file-name-directory absprefix))
16333 (opt org-format-latex-options)
16334 (matchers (plist-get opt :matchers))
16335 (re-list org-latex-regexps)
16336 (cnt 0) txt link beg end re e checkdir
16337 m n block linkfile movefile ov)
16338 ;; Check if there are old images files with this prefix, and remove them
16339 (when (file-directory-p todir)
16340 (mapc 'delete-file
16341 (directory-files
16342 todir 'full
16343 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
16344 ;; Check the different regular expressions
16345 (while (setq e (pop re-list))
16346 (setq m (car e) re (nth 1 e) n (nth 2 e)
16347 block (if (nth 3 e) "\n\n" ""))
16348 (when (member m matchers)
16349 (goto-char (point-min))
16350 (while (re-search-forward re nil t)
16351 (when (or (not at) (equal (cdr at) (match-beginning n)))
16352 (setq txt (match-string n)
16353 beg (match-beginning n) end (match-end n)
16354 cnt (1+ cnt)
16355 linkfile (format "%s_%04d.png" prefix cnt)
16356 movefile (format "%s_%04d.png" absprefix cnt)
16357 link (concat block "[[file:" linkfile "]]" block))
16358 (if msg (message msg cnt))
16359 (goto-char beg)
16360 (unless checkdir ; make sure the directory exists
16361 (setq checkdir t)
16362 (or (file-directory-p todir) (make-directory todir)))
16363 (org-create-formula-image
16364 txt movefile opt)
16365 (if overlays
16366 (progn
16367 (setq ov (org-make-overlay beg end))
16368 (if (featurep 'xemacs)
16369 (progn
16370 (org-overlay-put ov 'invisible t)
16371 (org-overlay-put
16372 ov 'end-glyph
16373 (make-glyph (vector 'png :file movefile))))
16374 (org-overlay-put
16375 ov 'display
16376 (list 'image :type 'png :file movefile :ascent 'center)))
16377 (push ov org-latex-fragment-image-overlays)
16378 (goto-char end))
16379 (delete-region beg end)
16380 (insert link))))))))
16382 ;; This function borrows from Ganesh Swami's latex2png.el
16383 (defun org-create-formula-image (string tofile options)
16384 (let* ((tmpdir (if (featurep 'xemacs)
16385 (temp-directory)
16386 temporary-file-directory))
16387 (texfilebase (make-temp-name
16388 (expand-file-name "orgtex" tmpdir)))
16390 ;(texfilebase (make-temp-file "orgtex"))
16391 ; (dummy (delete-file texfilebase))
16392 (texfile (concat texfilebase ".tex"))
16393 (dvifile (concat texfilebase ".dvi"))
16394 (pngfile (concat texfilebase ".png"))
16395 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
16396 (fg (or (plist-get options :foreground) "Black"))
16397 (bg (or (plist-get options :background) "Transparent")))
16398 (with-temp-file texfile
16399 (insert "\\documentclass{article}
16400 \\usepackage{fullpage}
16401 \\usepackage{amssymb}
16402 \\usepackage[usenames]{color}
16403 \\usepackage{amsmath}
16404 \\usepackage{latexsym}
16405 \\usepackage[mathscr]{eucal}
16406 \\pagestyle{empty}
16407 \\begin{document}\n" string "\n\\end{document}\n"))
16408 (let ((dir default-directory))
16409 (condition-case nil
16410 (progn
16411 (cd tmpdir)
16412 (call-process "latex" nil nil nil texfile))
16413 (error nil))
16414 (cd dir))
16415 (if (not (file-exists-p dvifile))
16416 (progn (message "Failed to create dvi file from %s" texfile) nil)
16417 (call-process "dvipng" nil nil nil
16418 "-E" "-fg" fg "-bg" bg
16419 "-x" scale "-y" scale "-T" "tight"
16420 "-o" pngfile
16421 dvifile)
16422 (if (not (file-exists-p pngfile))
16423 (progn (message "Failed to create png file from %s" texfile) nil)
16424 ;; Use the requested file name and clean up
16425 (copy-file pngfile tofile 'replace)
16426 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16427 (delete-file (concat texfilebase e)))
16428 pngfile))))
16430 ;;;; Exporting
16432 ;;; Variables, constants, and parameter plists
16434 (defconst org-level-max 20)
16436 (defvar org-export-html-preamble nil
16437 "Preamble, to be inserted just after <body>. Set by publishing functions.")
16438 (defvar org-export-html-postamble nil
16439 "Preamble, to be inserted just before </body>. Set by publishing functions.")
16440 (defvar org-export-html-auto-preamble t
16441 "Should default preamble be inserted? Set by publishing functions.")
16442 (defvar org-export-html-auto-postamble t
16443 "Should default postamble be inserted? Set by publishing functions.")
16444 (defvar org-current-export-file nil) ; dynamically scoped parameter
16445 (defvar org-current-export-dir nil) ; dynamically scoped parameter
16448 (defconst org-export-plist-vars
16449 '((:language . org-export-default-language)
16450 (:customtime . org-display-custom-times)
16451 (:headline-levels . org-export-headline-levels)
16452 (:section-numbers . org-export-with-section-numbers)
16453 (:table-of-contents . org-export-with-toc)
16454 (:archived-trees . org-export-with-archived-trees)
16455 (:emphasize . org-export-with-emphasize)
16456 (:sub-superscript . org-export-with-sub-superscripts)
16457 (:TeX-macros . org-export-with-TeX-macros)
16458 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
16459 (:fixed-width . org-export-with-fixed-width)
16460 (:timestamps . org-export-with-timestamps)
16461 (:tables . org-export-with-tables)
16462 (:table-auto-headline . org-export-highlight-first-table-line)
16463 (:style . org-export-html-style)
16464 (:convert-org-links . org-export-html-link-org-files-as-html)
16465 (:inline-images . org-export-html-inline-images)
16466 (:expand-quoted-html . org-export-html-expand)
16467 (:timestamp . org-export-html-with-timestamp)
16468 (:publishing-directory . org-export-publishing-directory)
16469 (:preamble . org-export-html-preamble)
16470 (:postamble . org-export-html-postamble)
16471 (:auto-preamble . org-export-html-auto-preamble)
16472 (:auto-postamble . org-export-html-auto-postamble)
16473 (:author . user-full-name)
16474 (:email . user-mail-address)))
16476 (defun org-default-export-plist ()
16477 "Return the property list with default settings for the export variables."
16478 (let ((l org-export-plist-vars) rtn e)
16479 (while (setq e (pop l))
16480 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
16481 rtn))
16483 (defun org-infile-export-plist ()
16484 "Return the property list with file-local settings for export."
16485 (save-excursion
16486 (goto-char 0)
16487 (let ((re (org-make-options-regexp
16488 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
16489 p key val text options)
16490 (while (re-search-forward re nil t)
16491 (setq key (org-match-string-no-properties 1)
16492 val (org-match-string-no-properties 2))
16493 (cond
16494 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
16495 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
16496 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
16497 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
16498 ((string-equal key "TEXT")
16499 (setq text (if text (concat text "\n" val) val)))
16500 ((string-equal key "OPTIONS") (setq options val))))
16501 (setq p (plist-put p :text text))
16502 (when options
16503 (let ((op '(("H" . :headline-levels)
16504 ("num" . :section-numbers)
16505 ("toc" . :table-of-contents)
16506 ("\\n" . :preserve-breaks)
16507 ("@" . :expand-quoted-html)
16508 (":" . :fixed-width)
16509 ("|" . :tables)
16510 ("^" . :sub-superscript)
16511 ("*" . :emphasize)
16512 ("TeX" . :TeX-macros)
16513 ("LaTeX" . :LaTeX-fragments)))
16515 (while (setq o (pop op))
16516 (if (string-match (concat (regexp-quote (car o))
16517 ":\\([^ \t\n\r;,.]*\\)")
16518 options)
16519 (setq p (plist-put p (cdr o)
16520 (car (read-from-string
16521 (match-string 1 options)))))))))
16522 p)))
16524 (defun org-export-directory (type plist)
16525 (let* ((val (plist-get plist :publishing-directory))
16526 (dir (if (listp val)
16527 (or (cdr (assoc type val)) ".")
16528 val)))
16529 dir))
16531 (defun org-export-find-first-heading-line (list)
16532 "Remove all lines from LIST which are before the first headline."
16533 (let ((orig-list list)
16534 (re (concat "^" outline-regexp)))
16535 (while (and list
16536 (not (string-match re (car list))))
16537 (pop list))
16538 (or list orig-list)))
16540 (defun org-skip-comments (lines)
16541 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
16542 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
16543 (re2 "^\\(\\*+\\)[ \t\n\r]")
16544 rtn line level)
16545 (while (setq line (pop lines))
16546 (cond
16547 ((and (string-match re1 line)
16548 (setq level (- (match-end 1) (match-beginning 1))))
16549 ;; Beginning of a COMMENT subtree. Skip it.
16550 (while (and (setq line (pop lines))
16551 (or (not (string-match re2 line))
16552 (> (- (match-end 1) (match-beginning 1)) level))))
16553 (setq lines (cons line lines)))
16554 ((string-match "^#" line)
16555 ;; an ordinary comment line
16557 ((and org-export-table-remove-special-lines
16558 (string-match "^[ \t]*|" line)
16559 (or (string-match "^[ \t]*| *[!_^] *|" line)
16560 (and (string-match "| *<[0-9]+> *|" line)
16561 (not (string-match "| *[^ <|]" line)))))
16562 ;; a special table line that should be removed
16564 (t (setq rtn (cons line rtn)))))
16565 (nreverse rtn)))
16567 (defun org-export (&optional arg)
16568 (interactive)
16569 (let ((help "[t] insert the export option template
16570 \[v] limit export to visible part of outline tree
16572 \[a] export as ASCII
16573 \[h] export as HTML
16574 \[b] export as HTML and browse immediately
16575 \[x] export as XOXO
16577 \[i] export current file as iCalendar file
16578 \[I] export all agenda files as iCalendar files
16579 \[c] export agenda files into combined iCalendar file
16581 \[F] publish current file
16582 \[P] publish current project
16583 \[X] publish... (project will be prompted for)
16584 \[A] publish all projects")
16585 (cmds
16586 '((?t . org-insert-export-options-template)
16587 (?v . org-export-visible)
16588 (?a . org-export-as-ascii)
16589 (?h . org-export-as-html)
16590 (?b . org-export-as-html-and-open)
16591 (?x . org-export-as-xoxo)
16592 (?i . org-export-icalendar-this-file)
16593 (?I . org-export-icalendar-all-agenda-files)
16594 (?c . org-export-icalendar-combine-agenda-files)
16595 (?F . org-publish-current-file)
16596 (?P . org-publish-current-project)
16597 (?X . org-publish)
16598 (?A . org-publish-all)))
16599 r1 r2 ass)
16600 (save-window-excursion
16601 (delete-other-windows)
16602 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
16603 (princ help))
16604 (message "Select command: ")
16605 (setq r1 (read-char-exclusive)))
16606 (setq r2 (if (< r1 27) (+ r1 96) r1))
16607 (if (setq ass (assq r2 cmds))
16608 (call-interactively (cdr ass))
16609 (error "No command associated with key %c" r1))))
16611 (defconst org-html-entities
16612 '(("nbsp")
16613 ("iexcl")
16614 ("cent")
16615 ("pound")
16616 ("curren")
16617 ("yen")
16618 ("brvbar")
16619 ("sect")
16620 ("uml")
16621 ("copy")
16622 ("ordf")
16623 ("laquo")
16624 ("not")
16625 ("shy")
16626 ("reg")
16627 ("macr")
16628 ("deg")
16629 ("plusmn")
16630 ("sup2")
16631 ("sup3")
16632 ("acute")
16633 ("micro")
16634 ("para")
16635 ("middot")
16636 ("odot"."o")
16637 ("star"."*")
16638 ("cedil")
16639 ("sup1")
16640 ("ordm")
16641 ("raquo")
16642 ("frac14")
16643 ("frac12")
16644 ("frac34")
16645 ("iquest")
16646 ("Agrave")
16647 ("Aacute")
16648 ("Acirc")
16649 ("Atilde")
16650 ("Auml")
16651 ("Aring") ("AA"."&Aring;")
16652 ("AElig")
16653 ("Ccedil")
16654 ("Egrave")
16655 ("Eacute")
16656 ("Ecirc")
16657 ("Euml")
16658 ("Igrave")
16659 ("Iacute")
16660 ("Icirc")
16661 ("Iuml")
16662 ("ETH")
16663 ("Ntilde")
16664 ("Ograve")
16665 ("Oacute")
16666 ("Ocirc")
16667 ("Otilde")
16668 ("Ouml")
16669 ("times")
16670 ("Oslash")
16671 ("Ugrave")
16672 ("Uacute")
16673 ("Ucirc")
16674 ("Uuml")
16675 ("Yacute")
16676 ("THORN")
16677 ("szlig")
16678 ("agrave")
16679 ("aacute")
16680 ("acirc")
16681 ("atilde")
16682 ("auml")
16683 ("aring")
16684 ("aelig")
16685 ("ccedil")
16686 ("egrave")
16687 ("eacute")
16688 ("ecirc")
16689 ("euml")
16690 ("igrave")
16691 ("iacute")
16692 ("icirc")
16693 ("iuml")
16694 ("eth")
16695 ("ntilde")
16696 ("ograve")
16697 ("oacute")
16698 ("ocirc")
16699 ("otilde")
16700 ("ouml")
16701 ("divide")
16702 ("oslash")
16703 ("ugrave")
16704 ("uacute")
16705 ("ucirc")
16706 ("uuml")
16707 ("yacute")
16708 ("thorn")
16709 ("yuml")
16710 ("fnof")
16711 ("Alpha")
16712 ("Beta")
16713 ("Gamma")
16714 ("Delta")
16715 ("Epsilon")
16716 ("Zeta")
16717 ("Eta")
16718 ("Theta")
16719 ("Iota")
16720 ("Kappa")
16721 ("Lambda")
16722 ("Mu")
16723 ("Nu")
16724 ("Xi")
16725 ("Omicron")
16726 ("Pi")
16727 ("Rho")
16728 ("Sigma")
16729 ("Tau")
16730 ("Upsilon")
16731 ("Phi")
16732 ("Chi")
16733 ("Psi")
16734 ("Omega")
16735 ("alpha")
16736 ("beta")
16737 ("gamma")
16738 ("delta")
16739 ("epsilon")
16740 ("varepsilon"."&epsilon;")
16741 ("zeta")
16742 ("eta")
16743 ("theta")
16744 ("iota")
16745 ("kappa")
16746 ("lambda")
16747 ("mu")
16748 ("nu")
16749 ("xi")
16750 ("omicron")
16751 ("pi")
16752 ("rho")
16753 ("sigmaf") ("varsigma"."&sigmaf;")
16754 ("sigma")
16755 ("tau")
16756 ("upsilon")
16757 ("phi")
16758 ("chi")
16759 ("psi")
16760 ("omega")
16761 ("thetasym") ("vartheta"."&thetasym;")
16762 ("upsih")
16763 ("piv")
16764 ("bull") ("bullet"."&bull;")
16765 ("hellip") ("dots"."&hellip;")
16766 ("prime")
16767 ("Prime")
16768 ("oline")
16769 ("frasl")
16770 ("weierp")
16771 ("image")
16772 ("real")
16773 ("trade")
16774 ("alefsym")
16775 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
16776 ("uarr") ("uparrow"."&uarr;")
16777 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
16778 ("darr")("downarrow"."&darr;")
16779 ("harr") ("leftrightarrow"."&harr;")
16780 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
16781 ("lArr") ("Leftarrow"."&lArr;")
16782 ("uArr") ("Uparrow"."&uArr;")
16783 ("rArr") ("Rightarrow"."&rArr;")
16784 ("dArr") ("Downarrow"."&dArr;")
16785 ("hArr") ("Leftrightarrow"."&hArr;")
16786 ("forall")
16787 ("part") ("partial"."&part;")
16788 ("exist") ("exists"."&exist;")
16789 ("empty") ("emptyset"."&empty;")
16790 ("nabla")
16791 ("isin") ("in"."&isin;")
16792 ("notin")
16793 ("ni")
16794 ("prod")
16795 ("sum")
16796 ("minus")
16797 ("lowast") ("ast"."&lowast;")
16798 ("radic")
16799 ("prop") ("proptp"."&prop;")
16800 ("infin") ("infty"."&infin;")
16801 ("ang") ("angle"."&ang;")
16802 ("and") ("vee"."&and;")
16803 ("or") ("wedge"."&or;")
16804 ("cap")
16805 ("cup")
16806 ("int")
16807 ("there4")
16808 ("sim")
16809 ("cong") ("simeq"."&cong;")
16810 ("asymp")("approx"."&asymp;")
16811 ("ne") ("neq"."&ne;")
16812 ("equiv")
16813 ("le")
16814 ("ge")
16815 ("sub") ("subset"."&sub;")
16816 ("sup") ("supset"."&sup;")
16817 ("nsub")
16818 ("sube")
16819 ("supe")
16820 ("oplus")
16821 ("otimes")
16822 ("perp")
16823 ("sdot") ("cdot"."&sdot;")
16824 ("lceil")
16825 ("rceil")
16826 ("lfloor")
16827 ("rfloor")
16828 ("lang")
16829 ("rang")
16830 ("loz") ("Diamond"."&loz;")
16831 ("spades") ("spadesuit"."&spades;")
16832 ("clubs") ("clubsuit"."&clubs;")
16833 ("hearts") ("diamondsuit"."&hearts;")
16834 ("diams") ("diamondsuit"."&diams;")
16835 ("quot")
16836 ("amp")
16837 ("lt")
16838 ("gt")
16839 ("OElig")
16840 ("oelig")
16841 ("Scaron")
16842 ("scaron")
16843 ("Yuml")
16844 ("circ")
16845 ("tilde")
16846 ("ensp")
16847 ("emsp")
16848 ("thinsp")
16849 ("zwnj")
16850 ("zwj")
16851 ("lrm")
16852 ("rlm")
16853 ("ndash")
16854 ("mdash")
16855 ("lsquo")
16856 ("rsquo")
16857 ("sbquo")
16858 ("ldquo")
16859 ("rdquo")
16860 ("bdquo")
16861 ("dagger")
16862 ("Dagger")
16863 ("permil")
16864 ("lsaquo")
16865 ("rsaquo")
16866 ("euro")
16868 ("arccos"."arccos")
16869 ("arcsin"."arcsin")
16870 ("arctan"."arctan")
16871 ("arg"."arg")
16872 ("cos"."cos")
16873 ("cosh"."cosh")
16874 ("cot"."cot")
16875 ("coth"."coth")
16876 ("csc"."csc")
16877 ("deg"."deg")
16878 ("det"."det")
16879 ("dim"."dim")
16880 ("exp"."exp")
16881 ("gcd"."gcd")
16882 ("hom"."hom")
16883 ("inf"."inf")
16884 ("ker"."ker")
16885 ("lg"."lg")
16886 ("lim"."lim")
16887 ("liminf"."liminf")
16888 ("limsup"."limsup")
16889 ("ln"."ln")
16890 ("log"."log")
16891 ("max"."max")
16892 ("min"."min")
16893 ("Pr"."Pr")
16894 ("sec"."sec")
16895 ("sin"."sin")
16896 ("sinh"."sinh")
16897 ("sup"."sup")
16898 ("tan"."tan")
16899 ("tanh"."tanh")
16901 "Entities for TeX->HTML translation.
16902 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
16903 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
16904 In that case, \"\\ent\" will be translated to \"&other;\".
16905 The list contains HTML entities for Latin-1, Greek and other symbols.
16906 It is supplemented by a number of commonly used TeX macros with appropriate
16907 translations. There is currently no way for users to extend this.")
16909 ;;; General functions for all backends
16911 (defun org-cleaned-string-for-export (string &rest parameters)
16912 "Cleanup a buffer substring so that links can be created safely."
16913 (interactive)
16914 (let* ((re-radio (and org-target-link-regexp
16915 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
16916 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
16917 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
16918 (re-archive (concat ":" org-archive-tag ":"))
16919 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
16920 (htmlp (memq :for-html parameters))
16921 (outline-regexp "\\*+")
16922 rtn)
16923 (save-excursion
16924 (set-buffer (get-buffer-create " org-mode-tmp"))
16925 (erase-buffer)
16926 (insert string)
16927 (let ((org-inhibit-startup t)) (org-mode))
16928 (untabify (point-min) (point-max))
16930 ;; Get rid of archived trees
16931 (when (not (eq org-export-with-archived-trees t))
16932 (goto-char (point-min))
16933 (while (re-search-forward re-archive nil t)
16934 (if (not (org-on-heading-p t))
16935 (org-end-of-subtree t)
16936 (beginning-of-line 1)
16937 (delete-region
16938 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
16939 (org-end-of-subtree t)))))
16941 ;; Protect stuff from HTML processing
16942 (goto-char (point-min))
16943 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
16944 (add-text-properties (match-beginning 0) (match-end 0)
16945 '(org-protected t)))
16946 (when htmlp
16947 (goto-char (point-min))
16948 (while (re-search-forward "^#\\+HTML:[ \t]*\\(.*\\)" nil t)
16949 (replace-match "\\1" t)
16950 (add-text-properties
16951 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
16952 '(org-protected t))))
16953 (goto-char (point-min))
16954 (while (re-search-forward
16955 "^#\\+BEGIN_HTML\\>.*\\(\n.*\\)*?\n#\\+END_HTML\\>.*\n?" nil t)
16956 (if htmlp
16957 (add-text-properties (match-beginning 1) (1+ (match-end 1))
16958 '(org-protected t))
16959 (delete-region (match-beginning 0) (match-end 0))))
16960 (goto-char (point-min))
16961 (while (re-search-forward re-quote nil t)
16962 (goto-char (match-beginning 0))
16963 (end-of-line 1)
16964 (add-text-properties (point) (org-end-of-subtree t)
16965 '(org-protected t)))
16967 ;; Find targets in comments and move them out of comments,
16968 ;; but mark them as targets that should be invisible
16969 (goto-char (point-min))
16970 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
16971 (replace-match "\\1(INVISIBLE)"))
16973 ;; Remove comments
16974 (goto-char (point-min))
16975 (while (re-search-forward "^#.*\n?" nil t)
16976 (replace-match ""))
16978 ;; Find matches for radio targets and turn them into internal links
16979 (goto-char (point-min))
16980 (when re-radio
16981 (while (re-search-forward re-radio nil t)
16982 (org-if-unprotected
16983 (replace-match "\\1[[\\2]]"))))
16985 ;; Find all links that contain a newline and put them into a single line
16986 (goto-char (point-min))
16987 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
16988 (org-if-unprotected
16989 (replace-match "\\1 \\3")
16990 (goto-char (match-beginning 0))))
16992 ;; Convert LaTeX fragments to images
16993 (when (memq :LaTeX-fragments parameters)
16994 (org-format-latex
16995 (concat "ltxpng/" (file-name-sans-extension
16996 (file-name-nondirectory
16997 org-current-export-file)))
16998 org-current-export-dir nil "Creating LaTeX image %s"))
16999 (message "Exporting...")
17001 ;; Normalize links: Convert angle and plain links into bracket links
17002 ;; Expand link abbreviations
17003 (goto-char (point-min))
17004 (while (re-search-forward re-plain-link nil t)
17005 (org-if-unprotected
17006 (replace-match
17007 (concat
17008 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
17009 t t)))
17010 (goto-char (point-min))
17011 (while (re-search-forward re-angle-link nil t)
17012 (org-if-unprotected
17013 (replace-match
17014 (concat
17015 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
17016 t t)))
17017 (goto-char (point-min))
17018 (while (re-search-forward org-bracket-link-regexp nil t)
17019 (org-if-unprotected
17020 (replace-match
17021 (concat "[[" (save-match-data
17022 (org-link-expand-abbrev (match-string 1)))
17024 (if (match-end 3)
17025 (match-string 2)
17026 (concat "[" (match-string 1) "]"))
17027 "]")
17028 t t)))
17030 ;; Find multiline emphasis and put them into single line
17031 (when (memq :emph-multiline parameters)
17032 (goto-char (point-min))
17033 (while (re-search-forward org-emph-re nil t)
17034 (org-if-unprotected
17035 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
17036 (goto-char (1- (match-end 0))))))
17038 (setq rtn (buffer-string)))
17039 (kill-buffer " org-mode-tmp")
17040 rtn))
17042 (defun org-solidify-link-text (s &optional alist)
17043 "Take link text and make a safe target out of it."
17044 (save-match-data
17045 (let* ((rtn
17046 (mapconcat
17047 'identity
17048 (org-split-string s "[ \t\r\n]+") "--"))
17049 (a (assoc rtn alist)))
17050 (or (cdr a) rtn))))
17052 ;; Variable holding the vector with section numbers
17053 (defvar org-section-numbers (make-vector org-level-max 0))
17055 (defun org-init-section-numbers ()
17056 "Initialize the vector for the section numbers."
17057 (let* ((level -1)
17058 (numbers (nreverse (org-split-string "" "\\.")))
17059 (depth (1- (length org-section-numbers)))
17060 (i depth) number-string)
17061 (while (>= i 0)
17062 (if (> i level)
17063 (aset org-section-numbers i 0)
17064 (setq number-string (or (car numbers) "0"))
17065 (if (string-match "\\`[A-Z]\\'" number-string)
17066 (aset org-section-numbers i
17067 (- (string-to-char number-string) ?A -1))
17068 (aset org-section-numbers i (string-to-number number-string)))
17069 (pop numbers))
17070 (setq i (1- i)))))
17072 (defun org-section-number (&optional level)
17073 "Return a string with the current section number.
17074 When LEVEL is non-nil, increase section numbers on that level."
17075 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
17076 (when level
17077 (when (> level -1)
17078 (aset org-section-numbers
17079 level (1+ (aref org-section-numbers level))))
17080 (setq idx (1+ level))
17081 (while (<= idx depth)
17082 (if (not (= idx 1))
17083 (aset org-section-numbers idx 0))
17084 (setq idx (1+ idx))))
17085 (setq idx 0)
17086 (while (<= idx depth)
17087 (setq n (aref org-section-numbers idx))
17088 (setq string (concat string (if (not (string= string "")) "." "")
17089 (int-to-string n)))
17090 (setq idx (1+ idx)))
17091 (save-match-data
17092 (if (string-match "\\`\\([@0]\\.\\)+" string)
17093 (setq string (replace-match "" t nil string)))
17094 (if (string-match "\\(\\.0\\)+\\'" string)
17095 (setq string (replace-match "" t nil string))))
17096 string))
17098 ;;; ASCII export
17100 (defvar org-last-level nil) ; dynamically scoped variable
17101 (defvar org-levels-open nil) ; dynamically scoped parameter
17102 (defvar org-ascii-current-indentation nil) ; For communication
17104 (defun org-export-as-ascii (arg)
17105 "Export the outline as a pretty ASCII file.
17106 If there is an active region, export only the region.
17107 The prefix ARG specifies how many levels of the outline should become
17108 underlined headlines. The default is 3."
17109 (interactive "P")
17110 (setq-default org-todo-line-regexp org-todo-line-regexp)
17111 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17112 (org-infile-export-plist)))
17113 (region
17114 (buffer-substring
17115 (if (org-region-active-p) (region-beginning) (point-min))
17116 (if (org-region-active-p) (region-end) (point-max))))
17117 (custom-times org-display-custom-times)
17118 (lines (org-export-find-first-heading-line
17119 (org-skip-comments
17120 (org-split-string
17121 (org-cleaned-string-for-export region)
17122 "[\r\n]"))))
17123 (org-ascii-current-indentation '(0 . 0))
17124 (level 0) line txt
17125 (umax nil)
17126 (umax-toc nil)
17127 (case-fold-search nil)
17128 (filename (concat (file-name-as-directory
17129 (org-export-directory :ascii opt-plist))
17130 (file-name-sans-extension
17131 (file-name-nondirectory buffer-file-name))
17132 ".txt"))
17133 (buffer (find-file-noselect filename))
17134 (org-levels-open (make-vector org-level-max nil))
17135 (odd org-odd-levels-only)
17136 (date (format-time-string "%Y/%m/%d" (current-time)))
17137 (time (format-time-string "%X" (org-current-time)))
17138 (author (plist-get opt-plist :author))
17139 (title (or (plist-get opt-plist :title)
17140 (file-name-sans-extension
17141 (file-name-nondirectory buffer-file-name))))
17142 (email (plist-get opt-plist :email))
17143 (language (plist-get opt-plist :language))
17144 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
17145 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
17146 (text nil)
17147 (todo nil)
17148 (lang-words nil))
17150 (setq org-last-level 1)
17151 (org-init-section-numbers)
17153 (find-file-noselect filename)
17155 (setq lang-words (or (assoc language org-export-language-setup)
17156 (assoc "en" org-export-language-setup)))
17157 (switch-to-buffer-other-window buffer)
17158 (erase-buffer)
17159 (fundamental-mode)
17160 ;; create local variables for all options, to make sure all called
17161 ;; functions get the correct information
17162 (mapcar (lambda (x)
17163 (set (make-local-variable (cdr x))
17164 (plist-get opt-plist (car x))))
17165 org-export-plist-vars)
17166 (org-set-local 'org-odd-levels-only odd)
17167 (setq umax (if arg (prefix-numeric-value arg)
17168 org-export-headline-levels))
17169 (setq umax-toc (if (integerp org-export-with-toc)
17170 (min org-export-with-toc umax)
17171 umax))
17173 ;; File header
17174 (if title (org-insert-centered title ?=))
17175 (insert "\n")
17176 (if (or author email)
17177 (insert (concat (nth 1 lang-words) ": " (or author "")
17178 (if email (concat " <" email ">") "")
17179 "\n")))
17180 (if (and date time)
17181 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
17182 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
17184 (insert "\n\n")
17186 (if org-export-with-toc
17187 (progn
17188 (insert (nth 3 lang-words) "\n"
17189 (make-string (length (nth 3 lang-words)) ?=) "\n")
17190 (mapcar '(lambda (line)
17191 (if (string-match org-todo-line-regexp
17192 line)
17193 ;; This is a headline
17194 (progn
17195 (setq level (- (match-end 1) (match-beginning 1))
17196 level (org-tr-level level)
17197 txt (match-string 3 line)
17198 todo
17199 (or (and org-export-mark-todo-in-toc
17200 (match-beginning 2)
17201 (not (equal (match-string 2 line)
17202 org-done-string)))
17203 ; TODO, not DONE
17204 (and org-export-mark-todo-in-toc
17205 (= level umax-toc)
17206 (org-search-todo-below
17207 line lines level))))
17208 (setq txt (org-html-expand-for-ascii txt))
17210 (if (and (memq org-export-with-tags '(not-in-toc nil))
17211 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
17212 (setq txt (replace-match "" t t txt)))
17213 (if (string-match quote-re0 txt)
17214 (setq txt (replace-match "" t t txt)))
17216 (if org-export-with-section-numbers
17217 (setq txt (concat (org-section-number level)
17218 " " txt)))
17219 (if (<= level umax-toc)
17220 (progn
17221 (insert
17222 (make-string (* (1- level) 4) ?\ )
17223 (format (if todo "%s (*)\n" "%s\n") txt))
17224 (setq org-last-level level))
17225 ))))
17226 lines)))
17228 (org-init-section-numbers)
17229 (while (setq line (pop lines))
17230 ;; Remove the quoted HTML tags.
17231 (setq line (org-html-expand-for-ascii line))
17232 ;; Remove targets
17233 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
17234 (setq line (replace-match "" t t line)))
17235 ;; Replace internal links
17236 (while (string-match org-bracket-link-regexp line)
17237 (setq line (replace-match
17238 (if (match-end 3) "[\\3]" "[\\1]")
17239 t nil line)))
17240 (when custom-times
17241 (setq line (org-translate-time line)))
17242 (cond
17243 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
17244 ;; a Headline
17245 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
17246 txt (match-string 2 line))
17247 (org-ascii-level-start level txt umax lines))
17249 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
17250 (normal-mode)
17251 (save-buffer)
17252 ;; remove display and invisible chars
17253 (let (beg end)
17254 (goto-char (point-min))
17255 (while (setq beg (next-single-property-change (point) 'display))
17256 (setq end (next-single-property-change beg 'display))
17257 (delete-region beg end)
17258 (goto-char beg)
17259 (insert "=>"))
17260 (goto-char (point-min))
17261 (while (setq beg (next-single-property-change (point) 'org-cwidth))
17262 (setq end (next-single-property-change beg 'org-cwidth))
17263 (delete-region beg end)
17264 (goto-char beg)))
17265 (goto-char (point-min))))
17267 (defun org-search-todo-below (line lines level)
17268 "Search the subtree below LINE for any TODO entries."
17269 (let ((rest (cdr (memq line lines)))
17270 (re org-todo-line-regexp)
17271 line lv todo)
17272 (catch 'exit
17273 (while (setq line (pop rest))
17274 (if (string-match re line)
17275 (progn
17276 (setq lv (- (match-end 1) (match-beginning 1))
17277 todo (and (match-beginning 2)
17278 (not (equal (match-string 2 line)
17279 org-done-string))))
17280 ; TODO, not DONE
17281 (if (<= lv level) (throw 'exit nil))
17282 (if todo (throw 'exit t))))))))
17284 (defun org-html-expand-for-ascii (line)
17285 "Handle quoted HTML for ASCII export."
17286 (if org-export-html-expand
17287 (while (string-match "@<[^<>\n]*>" line)
17288 ;; We just remove the tags for now.
17289 (setq line (replace-match "" nil nil line))))
17290 line)
17292 (defun org-insert-centered (s &optional underline)
17293 "Insert the string S centered and underline it with character UNDERLINE."
17294 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
17295 (insert (make-string ind ?\ ) s "\n")
17296 (if underline
17297 (insert (make-string ind ?\ )
17298 (make-string (string-width s) underline)
17299 "\n"))))
17301 (defun org-ascii-level-start (level title umax &optional lines)
17302 "Insert a new level in ASCII export."
17303 (let (char (n (- level umax 1)) (ind 0))
17304 (if (> level umax)
17305 (progn
17306 (insert (make-string (* 2 n) ?\ )
17307 (char-to-string (nth (% n (length org-export-ascii-bullets))
17308 org-export-ascii-bullets))
17309 " " title "\n")
17310 ;; find the indentation of the next non-empty line
17311 (catch 'stop
17312 (while lines
17313 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
17314 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
17315 (throw 'stop (setq ind (org-get-indentation (car lines)))))
17316 (pop lines)))
17317 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
17318 (if (or (not (equal (char-before) ?\n))
17319 (not (equal (char-before (1- (point))) ?\n)))
17320 (insert "\n"))
17321 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
17322 (unless org-export-with-tags
17323 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
17324 (setq title (replace-match "" t t title))))
17325 (if org-export-with-section-numbers
17326 (setq title (concat (org-section-number level) " " title)))
17327 (insert title "\n" (make-string (string-width title) char) "\n")
17328 (setq org-ascii-current-indentation '(0 . 0)))))
17330 (defun org-export-visible (type arg)
17331 "Create a copy of the visible part of the current buffer, and export it.
17332 The copy is created in a temporary buffer and removed after use.
17333 TYPE is the final key (as a string) that also select the export command in
17334 the `C-c C-e' export dispatcher.
17335 As a special case, if the you type SPC at the prompt, the temporary
17336 org-mode file will not be removed but presented to you so that you can
17337 continue to use it. The prefix arg ARG is passed through to the exporting
17338 command."
17339 (interactive
17340 (list (progn
17341 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
17342 (read-char-exclusive))
17343 current-prefix-arg))
17344 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
17345 (error "Invalid export key"))
17346 (let* ((binding (cdr (assoc type
17347 '((?a . org-export-as-ascii)
17348 (?\C-a . org-export-as-ascii)
17349 (?b . org-export-as-html-and-open)
17350 (?\C-b . org-export-as-html-and-open)
17351 (?h . org-export-as-html)
17352 (?x . org-export-as-xoxo)))))
17353 (keepp (equal type ?\ ))
17354 (file buffer-file-name)
17355 (buffer (get-buffer-create "*Org Export Visible*"))
17356 s e)
17357 (with-current-buffer buffer (erase-buffer))
17358 (save-excursion
17359 (setq s (goto-char (point-min)))
17360 (while (not (= (point) (point-max)))
17361 (goto-char (org-find-invisible))
17362 (append-to-buffer buffer s (point))
17363 (setq s (goto-char (org-find-visible))))
17364 (goto-char (point-min))
17365 (unless keepp
17366 ;; Copy all comment lines to the end, to make sure #+ settings are
17367 ;; still available for the second export step. Kind of a hack, but
17368 ;; does do the trick.
17369 (if (looking-at "#[^\r\n]*")
17370 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
17371 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
17372 (append-to-buffer buffer (1+ (match-beginning 0))
17373 (min (point-max) (1+ (match-end 0))))))
17374 (set-buffer buffer)
17375 (let ((buffer-file-name file)
17376 (org-inhibit-startup t))
17377 (org-mode)
17378 (show-all)
17379 (unless keepp (funcall binding arg))))
17380 (if (not keepp)
17381 (kill-buffer buffer)
17382 (switch-to-buffer-other-window buffer)
17383 (goto-char (point-min)))))
17385 (defun org-find-visible ()
17386 (let ((s (point)))
17387 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17388 (get-char-property s 'invisible)))
17390 (defun org-find-invisible ()
17391 (let ((s (point)))
17392 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17393 (not (get-char-property s 'invisible))))
17396 ;;; HTML export
17398 (defun org-get-current-options ()
17399 "Return a string with current options as keyword options.
17400 Does include HTML export options as well as TODO and CATEGORY stuff."
17401 (format
17402 "#+TITLE: %s
17403 #+AUTHOR: %s
17404 #+EMAIL: %s
17405 #+LANGUAGE: %s
17406 #+TEXT: Some descriptive text to be emitted. Several lines OK.
17407 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
17408 #+CATEGORY: %s
17409 #+SEQ_TODO: %s
17410 #+TYP_TODO: %s
17411 #+STARTUP: %s %s %s %s %s
17412 #+TAGS: %s
17413 #+ARCHIVE: %s
17414 #+LINK: %s
17416 (buffer-name) (user-full-name) user-mail-address org-export-default-language
17417 org-export-headline-levels
17418 org-export-with-section-numbers
17419 org-export-with-toc
17420 org-export-preserve-breaks
17421 org-export-html-expand
17422 org-export-with-fixed-width
17423 org-export-with-tables
17424 org-export-with-sub-superscripts
17425 org-export-with-emphasize
17426 org-export-with-TeX-macros
17427 org-export-with-LaTeX-fragments
17428 (file-name-nondirectory buffer-file-name)
17429 (if (equal org-todo-interpretation 'sequence)
17430 (mapconcat 'identity org-todo-keywords " ")
17431 "TODO FEEDBACK VERIFY DONE")
17432 (if (equal org-todo-interpretation 'type)
17433 (mapconcat 'identity org-todo-keywords " ")
17434 "Me Jason Marie DONE")
17435 (cdr (assoc org-startup-folded
17436 '((nil . "showall") (t . "overview") (content . "content"))))
17437 (if org-odd-levels-only "odd" "oddeven")
17438 (if org-hide-leading-stars "hidestars" "showstars")
17439 (if org-startup-align-all-tables "align" "noalign")
17440 (cond ((eq t org-log-done) "logdone")
17441 ((not org-log-done) "nologging")
17442 ((listp org-log-done)
17443 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
17444 org-log-done " ")))
17445 (or (mapconcat (lambda (x)
17446 (cond
17447 ((equal '(:startgroup) x) "{")
17448 ((equal '(:endgroup) x) "}")
17449 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
17450 (t (car x))))
17451 (or org-tag-alist (org-get-buffer-tags)) " ") "")
17452 org-archive-location
17453 "org file:~/org/%s.org"
17456 (defun org-insert-export-options-template ()
17457 "Insert into the buffer a template with information for exporting."
17458 (interactive)
17459 (if (not (bolp)) (newline))
17460 (let ((s (org-get-current-options)))
17461 (and (string-match "#\\+CATEGORY" s)
17462 (setq s (substring s 0 (match-beginning 0))))
17463 (insert s)))
17465 (defun org-toggle-fixed-width-section (arg)
17466 "Toggle the fixed-width export.
17467 If there is no active region, the QUOTE keyword at the current headline is
17468 inserted or removed. When present, it causes the text between this headline
17469 and the next to be exported as fixed-width text, and unmodified.
17470 If there is an active region, this command adds or removes a colon as the
17471 first character of this line. If the first character of a line is a colon,
17472 this line is also exported in fixed-width font."
17473 (interactive "P")
17474 (let* ((cc 0)
17475 (regionp (org-region-active-p))
17476 (beg (if regionp (region-beginning) (point)))
17477 (end (if regionp (region-end)))
17478 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17479 (re "[ \t]*\\(:\\)")
17480 off)
17481 (if regionp
17482 (save-excursion
17483 (goto-char beg)
17484 (setq cc (current-column))
17485 (beginning-of-line 1)
17486 (setq off (looking-at re))
17487 (while (> nlines 0)
17488 (setq nlines (1- nlines))
17489 (beginning-of-line 1)
17490 (cond
17491 (arg
17492 (move-to-column cc t)
17493 (insert ":\n")
17494 (forward-line -1))
17495 ((and off (looking-at re))
17496 (replace-match "" t t nil 1))
17497 ((not off) (move-to-column cc t) (insert ":")))
17498 (forward-line 1)))
17499 (save-excursion
17500 (org-back-to-heading)
17501 (if (looking-at (concat outline-regexp
17502 "\\( +\\<" org-quote-string "\\>\\)"))
17503 (replace-match "" t t nil 1)
17504 (if (looking-at outline-regexp)
17505 (progn
17506 (goto-char (match-end 0))
17507 (insert " " org-quote-string))))))))
17509 (defun org-export-as-html-and-open (arg)
17510 "Export the outline as HTML and immediately open it with a browser.
17511 If there is an active region, export only the region.
17512 The prefix ARG specifies how many levels of the outline should become
17513 headlines. The default is 3. Lower levels will become bulleted lists."
17514 (interactive "P")
17515 (org-export-as-html arg 'hidden)
17516 (org-open-file buffer-file-name))
17518 (defun org-export-as-html-batch ()
17519 "Call `org-export-as-html', may be used in batch processing as
17520 emacs --batch
17521 --load=$HOME/lib/emacs/org.el
17522 --eval \"(setq org-export-headline-levels 2)\"
17523 --visit=MyFile --funcall org-export-as-html-batch"
17524 (org-export-as-html org-export-headline-levels 'hidden))
17526 (defun org-export-as-html (arg &optional hidden ext-plist)
17527 "Export the outline as a pretty HTML file.
17528 If there is an active region, export only the region.
17529 The prefix ARG specifies how many levels of the outline should become
17530 headlines. The default is 3. Lower levels will become bulleted lists.
17531 When HIDDEN is non-nil, don't display the HTML buffer.
17532 EXT-PLIST is a property list with external parameters overriding
17533 org-mode's default settings, but still inferior to file-local settings."
17534 (interactive "P")
17535 (message "Exporting...")
17536 (setq-default org-todo-line-regexp org-todo-line-regexp)
17537 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
17538 (setq-default org-done-string org-done-string)
17539 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
17540 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17541 ext-plist
17542 (org-infile-export-plist)))
17544 (style (plist-get opt-plist :style))
17545 (link-validate (plist-get opt-plist :link-validation-function))
17546 valid
17547 (odd org-odd-levels-only)
17548 (region-p (org-region-active-p))
17549 (region
17550 (buffer-substring
17551 (if region-p (region-beginning) (point-min))
17552 (if region-p (region-end) (point-max))))
17553 ;; The following two are dynamically scoped into other
17554 ;; routines below.
17555 (org-current-export-dir (org-export-directory :html opt-plist))
17556 (org-current-export-file buffer-file-name)
17557 (all_lines
17558 (org-skip-comments (org-split-string
17559 (org-cleaned-string-for-export
17560 region :emph-multiline :for-html
17561 (if (plist-get opt-plist :LaTeX-fragments)
17562 :LaTeX-fragments))
17563 "[\r\n]")))
17564 (lines (org-export-find-first-heading-line all_lines))
17565 (level 0) (line "") (origline "") txt todo
17566 (umax nil)
17567 (umax-toc nil)
17568 (filename (concat (file-name-as-directory
17569 (org-export-directory :html opt-plist))
17570 (file-name-sans-extension
17571 (file-name-nondirectory buffer-file-name))
17572 ".html"))
17573 (current-dir (file-name-directory buffer-file-name))
17574 (buffer (find-file-noselect filename))
17575 (org-levels-open (make-vector org-level-max nil))
17576 (date (format-time-string "%Y/%m/%d" (current-time)))
17577 (time (format-time-string "%X" (org-current-time)))
17578 (author (plist-get opt-plist :author))
17579 (title (or (plist-get opt-plist :title)
17580 (file-name-sans-extension
17581 (file-name-nondirectory buffer-file-name))))
17582 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
17583 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
17584 (inquote nil)
17585 (infixed nil)
17586 (in-local-list nil)
17587 (local-list-num nil)
17588 (local-list-indent nil)
17589 (llt org-plain-list-ordered-item-terminator)
17590 (email (plist-get opt-plist :email))
17591 (language (plist-get opt-plist :language))
17592 (text (plist-get opt-plist :text))
17593 (lang-words nil)
17594 (target-alist nil) tg
17595 (head-count 0) cnt
17596 (start 0)
17597 (coding-system (and (boundp 'buffer-file-coding-system)
17598 buffer-file-coding-system))
17599 (coding-system-for-write coding-system)
17600 (save-buffer-coding-system coding-system)
17601 (charset (and coding-system
17602 (fboundp 'coding-system-get)
17603 (coding-system-get coding-system 'mime-charset)))
17604 table-open type
17605 table-buffer table-orig-buffer
17606 ind start-is-num starter didclose
17607 rpl path desc descp desc1 desc2 link
17609 (message "Exporting...")
17611 (setq org-last-level 1)
17612 (org-init-section-numbers)
17614 ;; Get the language-dependent settings
17615 (setq lang-words (or (assoc language org-export-language-setup)
17616 (assoc "en" org-export-language-setup)))
17618 ;; Switch to the output buffer
17619 (if (or hidden t)
17620 (set-buffer buffer)
17621 (switch-to-buffer-other-window buffer))
17622 (erase-buffer)
17623 (fundamental-mode)
17624 (let ((case-fold-search nil)
17625 (org-odd-levels-only odd))
17626 ;; create local variables for all options, to make sure all called
17627 ;; functions get the correct information
17628 (mapcar (lambda (x)
17629 (set (make-local-variable (cdr x))
17630 (plist-get opt-plist (car x))))
17631 org-export-plist-vars)
17632 (setq umax (if arg (prefix-numeric-value arg)
17633 org-export-headline-levels))
17634 (setq umax-toc (if (integerp org-export-with-toc)
17635 (min org-export-with-toc umax)
17636 umax))
17638 ;; File header
17639 (insert (format
17640 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
17641 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
17642 <html xmlns=\"http://www.w3.org/1999/xhtml\"
17643 lang=\"%s\" xml:lang=\"%s\">
17644 <head>
17645 <title>%s</title>
17646 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
17647 <meta name=\"generator\" content=\"Org-mode\"/>
17648 <meta name=\"generated\" content=\"%s %s\"/>
17649 <meta name=\"author\" content=\"%s\"/>
17651 </head><body>
17653 language language (org-html-expand title) (or charset "iso-8859-1")
17654 date time author style))
17657 (insert (or (plist-get opt-plist :preamble) ""))
17659 (when (plist-get opt-plist :auto-preamble)
17660 (if title (insert (format org-export-html-title-format
17661 (org-html-expand title))))
17662 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
17664 (if org-export-with-toc
17665 (progn
17666 (insert (format "<h%d>%s</h%d>\n"
17667 org-export-html-toplevel-hlevel
17668 (nth 3 lang-words)
17669 org-export-html-toplevel-hlevel))
17670 (insert "<ul>\n<li>")
17671 (setq lines
17672 (mapcar '(lambda (line)
17673 (if (string-match org-todo-line-regexp line)
17674 ;; This is a headline
17675 (progn
17676 (setq level (- (match-end 1) (match-beginning 1))
17677 level (org-tr-level level)
17678 txt (save-match-data
17679 (org-html-expand
17680 (org-export-cleanup-toc-line
17681 (match-string 3 line))))
17682 todo
17683 (or (and org-export-mark-todo-in-toc
17684 (match-beginning 2)
17685 (not (equal (match-string 2 line)
17686 org-done-string)))
17687 ; TODO, not DONE
17688 (and org-export-mark-todo-in-toc
17689 (= level umax-toc)
17690 (org-search-todo-below
17691 line lines level))))
17692 (if (and (memq org-export-with-tags '(not-in-toc nil))
17693 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
17694 (setq txt (replace-match "" t t txt)))
17695 (if (string-match quote-re0 txt)
17696 (setq txt (replace-match "" t t txt)))
17697 (if org-export-with-section-numbers
17698 (setq txt (concat (org-section-number level)
17699 " " txt)))
17700 (if (<= level umax-toc)
17701 (progn
17702 (setq head-count (+ head-count 1))
17703 (if (> level org-last-level)
17704 (progn
17705 (setq cnt (- level org-last-level))
17706 (while (>= (setq cnt (1- cnt)) 0)
17707 (insert "\n<ul>\n<li>"))
17708 (insert "\n")))
17709 (if (< level org-last-level)
17710 (progn
17711 (setq cnt (- org-last-level level))
17712 (while (>= (setq cnt (1- cnt)) 0)
17713 (insert "</li>\n</ul>"))
17714 (insert "\n")))
17715 ;; Check for targets
17716 (while (string-match org-target-regexp line)
17717 (setq tg (match-string 1 line)
17718 line (replace-match
17719 (concat "@<span class=\"target\">" tg "@</span> ")
17720 t t line))
17721 (push (cons (org-solidify-link-text tg)
17722 (format "sec-%d" head-count))
17723 target-alist))
17724 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
17725 (setq txt (replace-match "" t t txt)))
17726 (insert
17727 (format
17728 (if todo
17729 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
17730 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
17731 head-count txt))
17733 (setq org-last-level level))
17735 line)
17736 lines))
17737 (while (> org-last-level 0)
17738 (setq org-last-level (1- org-last-level))
17739 (insert "</li>\n</ul>\n"))
17741 (setq head-count 0)
17742 (org-init-section-numbers)
17744 (while (setq line (pop lines) origline line)
17745 (catch 'nextline
17747 ;; end of quote section?
17748 (when (and inquote (string-match "^\\*+" line))
17749 (insert "</pre>\n")
17750 (setq inquote nil))
17751 ;; inside a quote section?
17752 (when inquote
17753 (insert (org-html-protect line) "\n")
17754 (throw 'nextline nil))
17756 ;; verbatim lines
17757 (when (and org-export-with-fixed-width
17758 (string-match "^[ \t]*:\\(.*\\)" line))
17759 (when (not infixed)
17760 (setq infixed t)
17761 (insert "<pre>\n"))
17762 (insert (org-html-protect (match-string 1 line)) "\n")
17763 (when (and lines
17764 (not (string-match "^[ \t]*\\(:.*\\)"
17765 (car lines))))
17766 (setq infixed nil)
17767 (insert "</pre>\n"))
17768 (throw 'nextline nil))
17770 ;; Protected HTML
17771 (when (get-text-property 0 'org-protected line)
17772 (insert line "\n")
17773 (throw 'nextline nil))
17775 ;; Horizontal line
17776 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
17777 (insert "\n<hr/>\n")
17778 (throw 'nextline nil))
17780 ;; make targets to anchors
17781 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
17782 (cond
17783 ((match-end 2)
17784 (setq line (replace-match
17785 (concat "@<a name=\""
17786 (org-solidify-link-text (match-string 1 line))
17787 "\">\\nbsp@</a>")
17788 t t line)))
17789 ((and org-export-with-toc (equal (string-to-char line) ?*))
17790 (setq line (replace-match
17791 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
17792 ; (concat "@<i>" (match-string 1 line) "@</i> ")
17793 t t line)))
17795 (setq line (replace-match
17796 (concat "@<a name=\""
17797 (org-solidify-link-text (match-string 1 line))
17798 "\" class=\"target\">" (match-string 1 line) "@</a> ")
17799 t t line)))))
17801 (setq line (org-html-handle-time-stamps line))
17803 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
17804 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
17805 ;; Also handle sub_superscripts and checkboxes
17806 (setq line (org-html-expand line))
17808 ;; Format the links
17809 (setq start 0)
17810 (while (string-match org-bracket-link-analytic-regexp line start)
17811 (setq start (match-beginning 0))
17812 (setq type (if (match-end 2) (match-string 2 line) "internal"))
17813 (setq path (match-string 3 line))
17814 (setq desc1 (if (match-end 5) (match-string 5 line))
17815 desc2 (if (match-end 2) (concat type ":" path) path)
17816 descp (and desc1 (not (equal desc1 desc2)))
17817 desc (or desc1 desc2))
17818 ;; Make an image out of the description if that is so wanted
17819 (when (and descp (org-file-image-p desc))
17820 (save-match-data
17821 (if (string-match "^file:" desc)
17822 (setq desc (substring desc (match-end 0)))))
17823 (setq desc (concat "<img src=\"" desc "\"/>")))
17824 ;; FIXME: do we need to unescape here somewhere?
17825 (cond
17826 ((equal type "internal")
17827 (setq rpl
17828 (concat
17829 "<a href=\"#"
17830 (org-solidify-link-text path target-alist)
17831 "\">" desc "</a>")))
17832 ((member type '("http" "https")) ; FIXME: need to test this.
17833 ;; standard URL, just check if we need to inline an image
17834 (if (and (or (eq t org-export-html-inline-images)
17835 (and org-export-html-inline-images (not descp)))
17836 (org-file-image-p path))
17837 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
17838 (setq link (concat type ":" path))
17839 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
17840 ((member type '("ftp" "mailto" "news"))
17841 ;; standard URL
17842 (setq link (concat type ":" path))
17843 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
17844 ((string= type "file")
17845 ;; FILE link
17846 (let* ((filename path)
17847 (abs-p (file-name-absolute-p filename))
17848 thefile file-is-image-p search)
17849 (save-match-data
17850 (if (string-match "::\\(.*\\)" filename)
17851 (setq search (match-string 1 filename)
17852 filename (replace-match "" t nil filename)))
17853 (setq valid
17854 (if (functionp link-validate)
17855 (funcall link-validate filename current-dir)
17857 (setq file-is-image-p (org-file-image-p filename))
17858 (setq thefile (if abs-p (expand-file-name filename) filename))
17859 (when (and org-export-html-link-org-files-as-html
17860 (string-match "\\.org$" thefile))
17861 (setq thefile (concat (substring thefile 0
17862 (match-beginning 0))
17863 ".html"))
17864 (if (and search
17865 ;; make sure this is can be used as target search
17866 (not (string-match "^[0-9]*$" search))
17867 (not (string-match "^\\*" search))
17868 (not (string-match "^/.*/$" search)))
17869 (setq thefile (concat thefile "#"
17870 (org-solidify-link-text
17871 (org-link-unescape search)))))
17872 (when (string-match "^file:" desc)
17873 (setq desc (replace-match "" t t desc))
17874 (if (string-match "\\.org$" desc)
17875 (setq desc (replace-match "" t t desc))))))
17876 (setq rpl (if (and file-is-image-p
17877 (or (eq t org-export-html-inline-images)
17878 (and org-export-html-inline-images
17879 (not descp))))
17880 (concat "<img src=\"" thefile "\"/>")
17881 (concat "<a href=\"" thefile "\">" desc "</a>")))
17882 (if (not valid) (setq rpl desc))))
17883 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
17884 (setq rpl (concat "<i>&lt;" type ":"
17885 (save-match-data (org-link-unescape path))
17886 "&gt;</i>"))))
17887 (setq line (replace-match rpl t t line)
17888 start (+ start (length rpl))))
17889 ;; TODO items
17890 (if (and (string-match org-todo-line-regexp line)
17891 (match-beginning 2))
17892 (if (equal (match-string 2 line) org-done-string)
17893 (setq line (replace-match
17894 "<span class=\"done\">\\2</span>"
17895 t nil line 2))
17896 (setq line (replace-match "<span class=\"todo\">\\2</span>"
17897 t nil line 2))))
17899 (cond
17900 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
17901 ;; This is a headline
17902 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
17903 txt (match-string 2 line))
17904 (if (string-match quote-re0 txt)
17905 (setq txt (replace-match "" t t txt)))
17906 (if (<= level umax) (setq head-count (+ head-count 1)))
17907 (when in-local-list
17908 ;; Close any local lists before inserting a new header line
17909 (while local-list-num
17910 (org-close-li)
17911 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
17912 (pop local-list-num))
17913 (setq local-list-indent nil
17914 in-local-list nil))
17915 (org-html-level-start level txt umax
17916 (and org-export-with-toc (<= level umax))
17917 head-count)
17918 ;; QUOTES
17919 (when (string-match quote-re line)
17920 (insert "<pre>")
17921 (setq inquote t)))
17923 ((and org-export-with-tables
17924 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
17925 (if (not table-open)
17926 ;; New table starts
17927 (setq table-open t table-buffer nil table-orig-buffer nil))
17928 ;; Accumulate lines
17929 (setq table-buffer (cons line table-buffer)
17930 table-orig-buffer (cons origline table-orig-buffer))
17931 (when (or (not lines)
17932 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
17933 (car lines))))
17934 (setq table-open nil
17935 table-buffer (nreverse table-buffer)
17936 table-orig-buffer (nreverse table-orig-buffer))
17937 (org-close-par-maybe)
17938 (insert (org-format-table-html table-buffer table-orig-buffer))))
17940 ;; Normal lines
17941 (when (string-match
17942 (cond
17943 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
17944 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
17945 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
17946 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
17947 line)
17948 (setq ind (org-get-string-indentation line)
17949 start-is-num (match-beginning 4)
17950 starter (if (match-beginning 2)
17951 (substring (match-string 2 line) 0 -1))
17952 line (substring line (match-beginning 5)))
17953 (unless (string-match "[^ \t]" line)
17954 ;; empty line. Pretend indentation is large.
17955 (setq ind (1+ (or (car local-list-indent) 1))))
17956 (setq didclose nil)
17957 (while (and in-local-list
17958 (or (and (= ind (car local-list-indent))
17959 (not starter))
17960 (< ind (car local-list-indent))))
17961 (setq didclose t)
17962 (org-close-li)
17963 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
17964 (pop local-list-num) (pop local-list-indent)
17965 (setq in-local-list local-list-indent))
17966 (cond
17967 ((and starter
17968 (or (not in-local-list)
17969 (> ind (car local-list-indent))))
17970 ;; Start new (level of) list
17971 (org-close-par-maybe)
17972 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
17973 (push start-is-num local-list-num)
17974 (push ind local-list-indent)
17975 (setq in-local-list t))
17976 (starter
17977 ;; continue current list
17978 (org-close-li)
17979 (insert "<li>\n"))
17980 (didclose
17981 ;; we did close a list, normal text follows: need <p>
17982 (org-open-par)))
17983 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
17984 (setq line
17985 (replace-match
17986 (if (equal (match-string 1 line) "X")
17987 "<b>[X]</b>"
17988 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
17989 t t line))))
17991 ;; Empty lines start a new paragraph. If hand-formatted lists
17992 ;; are not fully interpreted, lines starting with "-", "+", "*"
17993 ;; also start a new paragraph.
17994 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
17996 ;; Check if the line break needs to be conserved
17997 (cond
17998 ((string-match "\\\\\\\\[ \t]*$" line)
17999 (setq line (replace-match "<br/>" t t line)))
18000 (org-export-preserve-breaks
18001 (setq line (concat line "<br/>"))))
18003 (insert line "\n")))))
18005 ;; Properly close all local lists and other lists
18006 (when inquote (insert "</pre>\n"))
18007 (when in-local-list
18008 ;; Close any local lists before inserting a new header line
18009 (while local-list-num
18010 (org-close-li)
18011 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
18012 (pop local-list-num))
18013 (setq local-list-indent nil
18014 in-local-list nil))
18015 (org-html-level-start 1 nil umax
18016 (and org-export-with-toc (<= level umax))
18017 head-count)
18019 (when (plist-get opt-plist :auto-postamble)
18020 (when author
18021 (insert "<p class=\"author\"> "
18022 (nth 1 lang-words) ": " author "\n")
18023 (when email
18024 (insert "<a href=\"mailto:" email "\">&lt;"
18025 email "&gt;</a>\n"))
18026 (insert "</p>\n"))
18027 (when (and date time)
18028 (insert "<p class=\"date\"> "
18029 (nth 2 lang-words) ": "
18030 date " " time "</p>\n")))
18032 (if org-export-html-with-timestamp
18033 (insert org-export-html-html-helper-timestamp))
18034 (insert (or (plist-get opt-plist :postamble) ""))
18035 (insert "</body>\n</html>\n")
18036 (normal-mode)
18037 ;; remove empty paragraphs and lists
18038 (goto-char (point-min))
18039 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
18040 (replace-match ""))
18041 (goto-char (point-min))
18042 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
18043 (replace-match ""))
18044 (save-buffer)
18045 (goto-char (point-min))
18046 (message "Exporting... done"))))
18049 (defun org-format-table-html (lines olines)
18050 "Find out which HTML converter to use and return the HTML code."
18051 (if (string-match "^[ \t]*|" (car lines))
18052 ;; A normal org table
18053 (org-format-org-table-html lines)
18054 ;; Table made by table.el - test for spanning
18055 (let* ((hlines (delq nil (mapcar
18056 (lambda (x)
18057 (if (string-match "^[ \t]*\\+-" x) x
18058 nil))
18059 lines)))
18060 (first (car hlines))
18061 (ll (and (string-match "\\S-+" first)
18062 (match-string 0 first)))
18063 (re (concat "^[ \t]*" (regexp-quote ll)))
18064 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
18065 hlines))))
18066 (if (and (not spanning)
18067 (not org-export-prefer-native-exporter-for-tables))
18068 ;; We can use my own converter with HTML conversions
18069 (org-format-table-table-html lines)
18070 ;; Need to use the code generator in table.el, with the original text.
18071 (org-format-table-table-html-using-table-generate-source olines)))))
18073 (defun org-format-org-table-html (lines &optional splice)
18074 "Format a table into HTML."
18075 ;; Get rid of hlines at beginning and end
18076 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
18077 (setq lines (nreverse lines))
18078 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
18079 (setq lines (nreverse lines))
18080 (when org-export-table-remove-special-lines
18081 ;; Check if the table has a marking column. If yes remove the
18082 ;; column and the special lines
18083 (setq lines (org-table-clean-before-export lines)))
18085 (let ((head (and org-export-highlight-first-table-line
18086 (delq nil (mapcar
18087 (lambda (x) (string-match "^[ \t]*|-" x))
18088 (cdr lines)))))
18089 (nlines 0) fnum i
18090 tbopen line fields html)
18091 (if splice (setq head nil))
18092 (unless splice (push (if head "<thead>" "<tbody>") html))
18093 (setq tbopen t)
18094 (while (setq line (pop lines))
18095 (catch 'next-line
18096 (if (string-match "^[ \t]*|-" line)
18097 (progn
18098 (unless splice
18099 (push (if head "</thead>" "</tbody>") html)
18100 (if lines (push "<tbody>" html) (setq tbopen nil)))
18101 (setq head nil) ;; head ends here, first time around
18102 ;; ignore this line
18103 (throw 'next-line t)))
18104 ;; Break the line into fields
18105 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
18106 (unless fnum (setq fnum (make-vector (length fields) 0)))
18107 (setq nlines (1+ nlines) i -1)
18108 (push (concat "<tr>"
18109 (mapconcat
18110 (lambda (x)
18111 (setq i (1+ i))
18112 (if (and (< i nlines)
18113 (string-match org-table-number-regexp x))
18114 (incf (aref fnum i)))
18115 (if head
18116 (concat "<th>" x "</th>")
18117 (concat "<td>" x "</td>")))
18118 fields "")
18119 "</tr>")
18120 html)))
18121 (unless splice (if tbopen (push "</tbody>" html)))
18122 (unless splice (push "</table>\n" html))
18123 (setq html (nreverse html))
18124 (unless splice
18125 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
18126 (push (mapconcat
18127 (lambda (x)
18128 (format "<COL align=\"%s\">"
18129 (if (> (/ (float x) nlines) org-table-number-fraction)
18130 "right" "left")))
18131 fnum "")
18132 html)
18133 (push org-export-html-table-tag html))
18134 (concat (mapconcat 'identity html "\n") "\n")))
18136 (defun org-table-clean-before-export (lines)
18137 "Check if the table has a marking column.
18138 If yes remove the column and the special lines."
18139 (if (memq nil
18140 (mapcar
18141 (lambda (x) (or (string-match "^[ \t]*|-" x)
18142 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
18143 lines))
18144 (progn
18145 (setq org-table-clean-did-remove-column-1 nil)
18146 lines)
18147 (setq org-table-clean-did-remove-column-1 t)
18148 (delq nil
18149 (mapcar
18150 (lambda (x) (if (string-match "^[ \t]*| *[!_^/] *|" x)
18151 nil ; ignore this line
18152 (and (or (string-match "^[ \t]*|-+\\+" x)
18153 (string-match "^[ \t]*|[^|]*|" x))
18154 (replace-match "|" t t x))))
18155 lines))))
18157 (defun org-fake-empty-table-line (line)
18158 "Replace everything except \"|\" with spaces."
18159 (let ((i (length line))
18160 (newstr (copy-sequence line)))
18161 (while (> i 0)
18162 (setq i (1- i))
18163 (if (not (eq (aref newstr i) ?|))
18164 (aset newstr i ?\ )))
18165 newstr))
18167 (defun org-format-table-table-html (lines)
18168 "Format a table generated by table.el into HTML.
18169 This conversion does *not* use `table-generate-source' from table.el.
18170 This has the advantage that Org-mode's HTML conversions can be used.
18171 But it has the disadvantage, that no cell- or row-spanning is allowed."
18172 (let (line field-buffer
18173 (head org-export-highlight-first-table-line)
18174 fields html empty)
18175 (setq html (concat org-export-html-table-tag "\n"))
18176 (while (setq line (pop lines))
18177 (setq empty "&nbsp;")
18178 (catch 'next-line
18179 (if (string-match "^[ \t]*\\+-" line)
18180 (progn
18181 (if field-buffer
18182 (progn
18183 (setq html (concat
18184 html
18185 "<tr>"
18186 (mapconcat
18187 (lambda (x)
18188 (if (equal x "") (setq x empty))
18189 (if head
18190 (concat "<th>" x "</th>\n")
18191 (concat "<td>" x "</td>\n")))
18192 field-buffer "\n")
18193 "</tr>\n"))
18194 (setq head nil)
18195 (setq field-buffer nil)))
18196 ;; Ignore this line
18197 (throw 'next-line t)))
18198 ;; Break the line into fields and store the fields
18199 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
18200 (if field-buffer
18201 (setq field-buffer (mapcar
18202 (lambda (x)
18203 (concat x "<br/>" (pop fields)))
18204 field-buffer))
18205 (setq field-buffer fields))))
18206 (setq html (concat html "</table>\n"))
18207 html))
18209 (defun org-format-table-table-html-using-table-generate-source (lines)
18210 "Format a table into html, using `table-generate-source' from table.el.
18211 This has the advantage that cell- or row-spanning is allowed.
18212 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
18213 (require 'table)
18214 (with-current-buffer (get-buffer-create " org-tmp1 ")
18215 (erase-buffer)
18216 (insert (mapconcat 'identity lines "\n"))
18217 (goto-char (point-min))
18218 (if (not (re-search-forward "|[^+]" nil t))
18219 (error "Error processing table"))
18220 (table-recognize-table)
18221 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
18222 (table-generate-source 'html " org-tmp2 ")
18223 (set-buffer " org-tmp2 ")
18224 (buffer-substring (point-min) (point-max))))
18226 (defun org-html-handle-time-stamps (s)
18227 "Format time stamps in string S, or remove them."
18228 (catch 'exit
18229 (let (r b)
18230 (while (string-match org-maybe-keyword-time-regexp s)
18231 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
18232 ;; never export CLOCK
18233 (throw 'exit ""))
18234 (or b (setq b (substring s 0 (match-beginning 0))))
18235 (if (not org-export-with-timestamps)
18236 (setq r (concat r (substring s 0 (match-beginning 0)))
18237 s (substring s (match-end 0)))
18238 (setq r (concat
18239 r (substring s 0 (match-beginning 0))
18240 (if (match-end 1)
18241 (format "@<span class=\"timestamp-kwd\">%s @</span>"
18242 (match-string 1 s)))
18243 (format " @<span class=\"timestamp\">%s@</span>"
18244 (substring
18245 (org-translate-time (match-string 3 s)) 1 -1)))
18246 s (substring s (match-end 0)))))
18247 ;; Line break if line started and ended with time stamp stuff
18248 (if (not r)
18250 (setq r (concat r s))
18251 (unless (string-match "\\S-" (concat b s))
18252 (setq r (concat r "@<br/>")))
18253 r))))
18255 (defun org-html-protect (s)
18256 ;; convert & to &amp;, < to &lt; and > to &gt;
18257 (let ((start 0))
18258 (while (string-match "&" s start)
18259 (setq s (replace-match "&amp;" t t s)
18260 start (1+ (match-beginning 0))))
18261 (while (string-match "<" s)
18262 (setq s (replace-match "&lt;" t t s)))
18263 (while (string-match ">" s)
18264 (setq s (replace-match "&gt;" t t s))))
18267 (defun org-export-cleanup-toc-line (s)
18268 "Remove tags and time staps from lines going into the toc."
18269 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
18270 (setq s (replace-match "" t t s)))
18271 (when org-export-remove-timestamps-from-toc
18272 (while (string-match org-maybe-keyword-time-regexp s)
18273 (setq s (replace-match "" t t s))))
18276 (defun org-html-expand (string)
18277 "Prepare STRING for HTML export. Applies all active conversions.
18278 If there are links in the string, don't modify these."
18279 (let* (m s l res)
18280 (while (setq m (string-match org-bracket-link-regexp string))
18281 (setq s (substring string 0 m)
18282 l (match-string 0 string)
18283 string (substring string (match-end 0)))
18284 (push (org-html-do-expand s) res)
18285 (push l res))
18286 (push (org-html-do-expand string) res)
18287 (apply 'concat (nreverse res))))
18289 (defun org-html-do-expand (s)
18290 "Apply all active conversions to translate special ASCII to HTML."
18291 (setq s (org-html-protect s))
18292 (if org-export-html-expand
18293 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
18294 (setq s (replace-match "<\\1>" t nil s))))
18295 (if org-export-with-emphasize
18296 (setq s (org-export-html-convert-emphasize s)))
18297 (if org-export-with-sub-superscripts
18298 (setq s (org-export-html-convert-sub-super s)))
18299 (if org-export-with-TeX-macros
18300 (let ((start 0) wd ass)
18301 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
18302 (setq wd (match-string 1 s))
18303 (if (setq ass (assoc wd org-html-entities))
18304 (setq s (replace-match (or (cdr ass)
18305 (concat "&" (car ass) ";"))
18306 t t s))
18307 (setq start (+ start (length wd)))))))
18310 (defun org-create-multibrace-regexp (left right n)
18311 "Create a regular expression which will match a balanced sexp.
18312 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
18313 as single character strings.
18314 The regexp returned will match the entire expression including the
18315 delimiters. It will also define a single group which contains the
18316 match except for the outermost delimiters. The maximum depth of
18317 stacked delimiters is N. Escaping delimiters is not possible."
18318 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
18319 (or "\\|")
18320 (re nothing)
18321 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
18322 (while (> n 1)
18323 (setq n (1- n)
18324 re (concat re or next)
18325 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
18326 (concat left "\\(" re "\\)" right)))
18328 (defvar org-match-substring-regexp
18329 (concat
18330 "\\([^\\]\\)\\([_^]\\)\\("
18331 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
18332 "\\|"
18333 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
18334 "\\|"
18335 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
18336 "The regular expression matching a sub- or superscript.")
18338 (defun org-export-html-convert-sub-super (string)
18339 "Convert sub- and superscripts in STRING to HTML."
18340 (let (key c)
18341 (while (string-match org-match-substring-regexp string)
18342 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
18343 (setq c (or (match-string 8 string)
18344 (match-string 6 string)
18345 (match-string 5 string)))
18346 (setq string (replace-match
18347 (concat (match-string 1 string)
18348 "<" key ">" c "</" key ">")
18349 t t string)))
18350 (while (string-match "\\\\\\([_^]\\)" string)
18351 (setq string (replace-match (match-string 1 string) t t string))))
18352 string)
18354 (defun org-export-html-convert-emphasize (string)
18355 "Apply emphasis."
18356 (while (string-match org-emph-re string)
18357 (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)))
18358 string)
18360 (defvar org-par-open nil)
18361 (defun org-open-par ()
18362 "Insert <p>, but first close previous paragraph if any."
18363 (org-close-par-maybe)
18364 (insert "\n<p>")
18365 (setq org-par-open t))
18366 (defun org-close-par-maybe ()
18367 "Close paragraph if there is one open."
18368 (when org-par-open
18369 (insert "</p>")
18370 (setq org-par-open nil)))
18371 (defun org-close-li ()
18372 "Close <li> if necessary."
18373 (org-close-par-maybe)
18374 (insert "</li>\n"))
18376 (defun org-html-level-start (level title umax with-toc head-count)
18377 "Insert a new level in HTML export.
18378 When TITLE is nil, just close all open levels."
18379 (org-close-par-maybe)
18380 (let ((l (1+ (max level umax))))
18381 (while (<= l org-level-max)
18382 (if (aref org-levels-open (1- l))
18383 (progn
18384 (org-html-level-close l)
18385 (aset org-levels-open (1- l) nil)))
18386 (setq l (1+ l)))
18387 (when title
18388 ;; If title is nil, this means this function is called to close
18389 ;; all levels, so the rest is done only if title is given
18390 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
18391 (setq title (replace-match
18392 (if org-export-with-tags
18393 (save-match-data
18394 (concat
18395 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
18396 (mapconcat 'identity (org-split-string
18397 (match-string 1 title) ":")
18398 "&nbsp;")
18399 "</span>"))
18401 t t title)))
18402 (if (> level umax)
18403 (progn
18404 (if (aref org-levels-open (1- level))
18405 (progn
18406 (org-close-li)
18407 (insert "<li>" title "<br/>\n"))
18408 (aset org-levels-open (1- level) t)
18409 (org-close-par-maybe)
18410 (insert "<ul>\n<li>" title "<br/>\n")))
18411 (if org-export-with-section-numbers
18412 (setq title (concat (org-section-number level) " " title)))
18413 (setq level (+ level org-export-html-toplevel-hlevel -1))
18414 (if with-toc
18415 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
18416 level head-count title level))
18417 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
18418 (org-open-par)))))
18420 (defun org-html-level-close (&rest args)
18421 "Terminate one level in HTML export."
18422 (org-close-li)
18423 (insert "</ul>\n"))
18425 ;;; iCalendar export
18427 ;;;###autoload
18428 (defun org-export-icalendar-this-file ()
18429 "Export current file as an iCalendar file.
18430 The iCalendar file will be located in the same directory as the Org-mode
18431 file, but with extension `.ics'."
18432 (interactive)
18433 (org-export-icalendar nil buffer-file-name))
18435 ;;;###autoload
18436 (defun org-export-icalendar-all-agenda-files ()
18437 "Export all files in `org-agenda-files' to iCalendar .ics files.
18438 Each iCalendar file will be located in the same directory as the Org-mode
18439 file, but with extension `.ics'."
18440 (interactive)
18441 (apply 'org-export-icalendar nil (org-agenda-files t)))
18443 ;;;###autoload
18444 (defun org-export-icalendar-combine-agenda-files ()
18445 "Export all files in `org-agenda-files' to a single combined iCalendar file.
18446 The file is stored under the name `org-combined-agenda-icalendar-file'."
18447 (interactive)
18448 (apply 'org-export-icalendar t (org-agenda-files t)))
18450 (defun org-export-icalendar (combine &rest files)
18451 "Create iCalendar files for all elements of FILES.
18452 If COMBINE is non-nil, combine all calendar entries into a single large
18453 file and store it under the name `org-combined-agenda-icalendar-file'."
18454 (save-excursion
18455 (let* ((dir (org-export-directory
18456 :ical (list :publishing-directory
18457 org-export-publishing-directory)))
18458 file ical-file ical-buffer category started org-agenda-new-buffers)
18460 (when combine
18461 (setq ical-file
18462 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
18463 org-combined-agenda-icalendar-file
18464 (expand-file-name org-combined-agenda-icalendar-file dir))
18465 ical-buffer (org-get-agenda-file-buffer ical-file))
18466 (set-buffer ical-buffer) (erase-buffer))
18467 (while (setq file (pop files))
18468 (catch 'nextfile
18469 (org-check-agenda-file file)
18470 (set-buffer (org-get-agenda-file-buffer file))
18471 (unless combine
18472 (setq ical-file (concat (file-name-as-directory dir)
18473 (file-name-sans-extension
18474 (file-name-nondirectory buffer-file-name))
18475 ".ics"))
18476 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
18477 (with-current-buffer ical-buffer (erase-buffer)))
18478 (setq category (or org-category
18479 (file-name-sans-extension
18480 (file-name-nondirectory buffer-file-name))))
18481 (if (symbolp category) (setq category (symbol-name category)))
18482 (let ((standard-output ical-buffer))
18483 (if combine
18484 (and (not started) (setq started t)
18485 (org-start-icalendar-file org-icalendar-combined-name))
18486 (org-start-icalendar-file category))
18487 (org-print-icalendar-entries combine)
18488 (when (or (and combine (not files)) (not combine))
18489 (org-finish-icalendar-file)
18490 (set-buffer ical-buffer)
18491 (save-buffer)
18492 (run-hooks 'org-after-save-iCalendar-file-hook)))))
18493 (org-release-buffers org-agenda-new-buffers))))
18495 (defvar org-after-save-iCalendar-file-hook nil
18496 "Hook run after an iCalendar file has been saved.
18497 The iCalendar buffer is still current when this hook is run.
18498 A good way to use this is to tell a desktop calenndar application to re-read
18499 the iCalendar file.")
18501 (defun org-print-icalendar-entries (&optional combine)
18502 "Print iCalendar entries for the current Org-mode file to `standard-output'.
18503 When COMBINE is non nil, add the category to each line."
18504 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
18505 (org-category-table (org-get-category-table))
18506 (dts (org-ical-ts-to-string
18507 (format-time-string (cdr org-time-stamp-formats) (current-time))
18508 "DTSTART"))
18509 hd ts ts2 state status (inc t) pos
18510 scheduledp deadlinep tmp pri category)
18511 (save-excursion
18512 (goto-char (point-min))
18513 (while (re-search-forward org-ts-regexp nil t)
18514 (setq pos (match-beginning 0)
18515 ts (match-string 0)
18516 inc t
18517 hd (org-get-heading)
18518 category (org-get-category))
18519 (if (looking-at re2)
18520 (progn
18521 (goto-char (match-end 0))
18522 (setq ts2 (match-string 1) inc nil))
18523 (setq ts2 ts
18524 tmp (buffer-substring (max (point-min)
18525 (- pos org-ds-keyword-length))
18526 pos)
18527 deadlinep (string-match org-deadline-regexp tmp)
18528 scheduledp (string-match org-scheduled-regexp tmp)
18529 ;; donep (org-entry-is-done-p)
18531 (if (or (string-match org-tr-regexp hd)
18532 (string-match org-ts-regexp hd))
18533 (setq hd (replace-match "" t t hd)))
18534 (if (string-match org-bracket-link-regexp hd)
18535 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
18536 (match-string 1 hd))
18537 t t hd)))
18538 (if deadlinep (setq hd (concat "DL: " hd)))
18539 (if scheduledp (setq hd (concat "S: " hd)))
18540 (princ (format "BEGIN:VEVENT
18543 SUMMARY:%s
18544 CATEGORIES:%s
18545 END:VEVENT\n"
18546 (org-ical-ts-to-string ts "DTSTART")
18547 (org-ical-ts-to-string ts2 "DTEND" inc)
18548 hd category)))
18549 (when org-icalendar-include-todo
18550 (goto-char (point-min))
18551 (while (re-search-forward org-todo-line-regexp nil t)
18552 (setq state (match-string 2))
18553 (setq status (if (equal state org-done-string)
18554 "COMPLETED" "NEEDS-ACTION"))
18555 (when (and state
18556 (or (not (equal state org-done-string))
18557 (eq org-icalendar-include-todo 'all)))
18558 (setq hd (match-string 3))
18559 (if (string-match org-priority-regexp hd)
18560 (setq pri (string-to-char (match-string 2 hd))
18561 hd (concat (substring hd 0 (match-beginning 1))
18562 (substring hd (match-end 1))))
18563 (setq pri org-default-priority))
18564 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
18565 (- org-lowest-priority ?A))))))
18567 (princ (format "BEGIN:VTODO
18569 SUMMARY:%s
18570 CATEGORIES:%s
18571 SEQUENCE:1
18572 PRIORITY:%d
18573 STATUS:%s
18574 END:VTODO\n"
18575 dts hd category pri status))))))))
18577 (defun org-start-icalendar-file (name)
18578 "Start an iCalendar file by inserting the header."
18579 (let ((user user-full-name)
18580 (name (or name "unknown"))
18581 (timezone (cadr (current-time-zone))))
18582 (princ
18583 (format "BEGIN:VCALENDAR
18584 VERSION:2.0
18585 X-WR-CALNAME:%s
18586 PRODID:-//%s//Emacs with Org-mode//EN
18587 X-WR-TIMEZONE:%s
18588 CALSCALE:GREGORIAN\n" name user timezone))))
18590 (defun org-finish-icalendar-file ()
18591 "Finish an iCalendar file by inserting the END statement."
18592 (princ "END:VCALENDAR\n"))
18594 (defun org-ical-ts-to-string (s keyword &optional inc)
18595 "Take a time string S and convert it to iCalendar format.
18596 KEYWORD is added in front, to make a complete line like DTSTART....
18597 When INC is non-nil, increase the hour by two (if time string contains
18598 a time), or the day by one (if it does not contain a time)."
18599 (let ((t1 (org-parse-time-string s 'nodefault))
18600 t2 fmt have-time time)
18601 (if (and (car t1) (nth 1 t1) (nth 2 t1))
18602 (setq t2 t1 have-time t)
18603 (setq t2 (org-parse-time-string s)))
18604 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
18605 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
18606 (when inc
18607 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
18608 (setq time (encode-time s mi h d m y)))
18609 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
18610 (concat keyword (format-time-string fmt time))))
18612 ;;; XOXO export
18614 (defun org-export-as-xoxo-insert-into (buffer &rest output)
18615 (with-current-buffer buffer
18616 (apply 'insert output)))
18617 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
18619 (defun org-export-as-xoxo (&optional buffer)
18620 "Export the org buffer as XOXO.
18621 The XOXO buffer is named *xoxo-<source buffer name>*"
18622 (interactive (list (current-buffer)))
18623 ;; A quickie abstraction
18625 ;; Output everything as XOXO
18626 (with-current-buffer (get-buffer buffer)
18627 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
18628 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
18629 (org-infile-export-plist)))
18630 (filename (concat (file-name-as-directory
18631 (org-export-directory :xoxo opt-plist))
18632 (file-name-sans-extension
18633 (file-name-nondirectory buffer-file-name))
18634 ".html"))
18635 (out (find-file-noselect filename))
18636 (last-level 1)
18637 (hanging-li nil))
18638 ;; Check the output buffer is empty.
18639 (with-current-buffer out (erase-buffer))
18640 ;; Kick off the output
18641 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
18642 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
18643 (let* ((hd (match-string-no-properties 1))
18644 (level (length hd))
18645 (text (concat
18646 (match-string-no-properties 2)
18647 (save-excursion
18648 (goto-char (match-end 0))
18649 (let ((str ""))
18650 (catch 'loop
18651 (while 't
18652 (forward-line)
18653 (if (looking-at "^[ \t]\\(.*\\)")
18654 (setq str (concat str (match-string-no-properties 1)))
18655 (throw 'loop str)))))))))
18657 ;; Handle level rendering
18658 (cond
18659 ((> level last-level)
18660 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
18662 ((< level last-level)
18663 (dotimes (- (- last-level level) 1)
18664 (if hanging-li
18665 (org-export-as-xoxo-insert-into out "</li>\n"))
18666 (org-export-as-xoxo-insert-into out "</ol>\n"))
18667 (when hanging-li
18668 (org-export-as-xoxo-insert-into out "</li>\n")
18669 (setq hanging-li nil)))
18671 ((equal level last-level)
18672 (if hanging-li
18673 (org-export-as-xoxo-insert-into out "</li>\n")))
18676 (setq last-level level)
18678 ;; And output the new li
18679 (setq hanging-li 't)
18680 (if (equal ?+ (elt text 0))
18681 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
18682 (org-export-as-xoxo-insert-into out "<li>" text))))
18684 ;; Finally finish off the ol
18685 (dotimes (- last-level 1)
18686 (if hanging-li
18687 (org-export-as-xoxo-insert-into out "</li>\n"))
18688 (org-export-as-xoxo-insert-into out "</ol>\n"))
18690 ;; Finish the buffer off and clean it up.
18691 (switch-to-buffer-other-window out)
18692 (indent-region (point-min) (point-max) nil)
18693 (save-buffer)
18694 (goto-char (point-min))
18698 ;;;; Key bindings
18700 ;; Make `C-c C-x' a prefix key
18701 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
18703 ;; TAB key with modifiers
18704 (define-key org-mode-map "\C-i" 'org-cycle)
18705 (define-key org-mode-map [(tab)] 'org-cycle)
18706 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
18707 (define-key org-mode-map [(meta tab)] 'org-complete)
18708 (define-key org-mode-map "\M-\t" 'org-complete)
18709 (define-key org-mode-map "\M-\C-i" 'org-complete)
18710 ;; The following line is necessary under Suse GNU/Linux
18711 (unless (featurep 'xemacs)
18712 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
18713 (define-key org-mode-map [(shift tab)] 'org-shifttab)
18715 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
18716 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18717 (define-key org-mode-map [(meta return)] 'org-meta-return)
18719 ;; Cursor keys with modifiers
18720 (define-key org-mode-map [(meta left)] 'org-metaleft)
18721 (define-key org-mode-map [(meta right)] 'org-metaright)
18722 (define-key org-mode-map [(meta up)] 'org-metaup)
18723 (define-key org-mode-map [(meta down)] 'org-metadown)
18725 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18726 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
18727 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
18728 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
18730 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
18731 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
18732 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
18733 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
18735 ;;; Extra keys for tty access.
18736 ;; We only set them when really needed because otherwise the
18737 ;; menus don't show the simple keys
18739 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18740 (not window-system))
18741 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18742 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18743 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return)
18744 (define-key org-mode-map [?\e (return)] 'org-meta-return)
18745 (define-key org-mode-map [?\e (left)] 'org-metaleft)
18746 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft)
18747 (define-key org-mode-map [?\e (right)] 'org-metaright)
18748 (define-key org-mode-map "\C-c\C-xr" 'org-metaright)
18749 (define-key org-mode-map [?\e (up)] 'org-metaup)
18750 (define-key org-mode-map "\C-c\C-xu" 'org-metaup)
18751 (define-key org-mode-map [?\e (down)] 'org-metadown)
18752 (define-key org-mode-map "\C-c\C-xd" 'org-metadown)
18753 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18754 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18755 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18756 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18757 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
18758 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
18759 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
18760 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
18762 ;; All the other keys
18764 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18765 (define-key org-mode-map "\C-c\C-r" 'org-reveal)
18766 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
18767 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
18768 (define-key org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18769 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
18770 (define-key org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18771 (define-key org-mode-map "\C-c\C-j" 'org-goto)
18772 (define-key org-mode-map "\C-c\C-t" 'org-todo)
18773 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
18774 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
18775 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
18776 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
18777 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
18778 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
18779 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
18780 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
18781 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
18782 (define-key org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18783 (define-key org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18784 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
18785 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
18786 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
18787 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
18788 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
18789 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18790 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18791 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18792 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18793 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
18794 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
18795 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18796 (define-key org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18797 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
18798 (define-key org-mode-map "\C-c]" 'org-remove-file)
18799 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
18800 (define-key org-mode-map "\C-c^" 'org-sort)
18801 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18802 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
18803 (define-key org-mode-map "\C-m" 'org-return)
18804 (define-key org-mode-map "\C-c?" 'org-table-field-info)
18805 (define-key org-mode-map "\C-c " 'org-table-blank-field)
18806 (define-key org-mode-map "\C-c+" 'org-table-sum)
18807 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
18808 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
18809 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
18810 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18811 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
18812 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18813 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
18814 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
18815 (define-key org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18816 (define-key org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18817 (define-key org-mode-map "\C-c\C-e" 'org-export)
18818 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18820 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
18821 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18822 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18823 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18825 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18826 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18827 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18828 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
18829 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18830 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18831 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18832 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18833 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18835 (when (featurep 'xemacs)
18836 (define-key org-mode-map 'button3 'popup-mode-menu))
18838 (defsubst org-table-p () (org-at-table-p))
18840 (defun org-self-insert-command (N)
18841 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18842 If the cursor is in a table looking at whitespace, the whitespace is
18843 overwritten, and the table is not marked as requiring realignment."
18844 (interactive "p")
18845 (if (and (org-table-p)
18846 (progn
18847 ;; check if we blank the field, and if that triggers align
18848 (and org-table-auto-blank-field
18849 (member last-command
18850 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
18851 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18852 ;; got extra space, this field does not determine column width
18853 (let (org-table-may-need-update) (org-table-blank-field))
18854 ;; no extra space, this field may determine column width
18855 (org-table-blank-field)))
18857 (eq N 1)
18858 (looking-at "[^|\n]* |"))
18859 (let (org-table-may-need-update)
18860 (goto-char (1- (match-end 0)))
18861 (delete-backward-char 1)
18862 (goto-char (match-beginning 0))
18863 (self-insert-command N))
18864 (setq org-table-may-need-update t)
18865 (self-insert-command N)))
18867 (defun org-delete-backward-char (N)
18868 "Like `delete-backward-char', insert whitespace at field end in tables.
18869 When deleting backwards, in tables this function will insert whitespace in
18870 front of the next \"|\" separator, to keep the table aligned. The table will
18871 still be marked for re-alignment if the field did fill the entire column,
18872 because, in this case the deletion might narrow the column."
18873 (interactive "p")
18874 (if (and (org-table-p)
18875 (eq N 1)
18876 (string-match "|" (buffer-substring (point-at-bol) (point)))
18877 (looking-at ".*?|"))
18878 (let ((pos (point))
18879 (noalign (looking-at "[^|\n\r]* |"))
18880 (c org-table-may-need-update))
18881 (backward-delete-char N)
18882 (skip-chars-forward "^|")
18883 (insert " ")
18884 (goto-char (1- pos))
18885 ;; noalign: if there were two spaces at the end, this field
18886 ;; does not determine the width of the column.
18887 (if noalign (setq org-table-may-need-update c)))
18888 (backward-delete-char N)))
18890 (defun org-delete-char (N)
18891 "Like `delete-char', but insert whitespace at field end in tables.
18892 When deleting characters, in tables this function will insert whitespace in
18893 front of the next \"|\" separator, to keep the table aligned. The table will
18894 still be marked for re-alignment if the field did fill the entire column,
18895 because, in this case the deletion might narrow the column."
18896 (interactive "p")
18897 (if (and (org-table-p)
18898 (not (bolp))
18899 (not (= (char-after) ?|))
18900 (eq N 1))
18901 (if (looking-at ".*?|")
18902 (let ((pos (point))
18903 (noalign (looking-at "[^|\n\r]* |"))
18904 (c org-table-may-need-update))
18905 (replace-match (concat
18906 (substring (match-string 0) 1 -1)
18907 " |"))
18908 (goto-char pos)
18909 ;; noalign: if there were two spaces at the end, this field
18910 ;; does not determine the width of the column.
18911 (if noalign (setq org-table-may-need-update c)))
18912 (delete-char N))
18913 (delete-char N)))
18915 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18916 (put 'org-self-insert-command 'delete-selection t)
18917 (put 'orgtbl-self-insert-command 'delete-selection t)
18918 (put 'org-delete-char 'delete-selection 'supersede)
18919 (put 'org-delete-backward-char 'delete-selection 'supersede)
18921 ;; Make `flyspell-mode' delay after some commands
18922 (put 'org-self-insert-command 'flyspell-delayed t)
18923 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18924 (put 'org-delete-char 'flyspell-delayed t)
18925 (put 'org-delete-backward-char 'flyspell-delayed t)
18927 ;; How to do this: Measure non-white length of current string
18928 ;; If equal to column width, we should realign.
18930 (defun org-remap (map &rest commands)
18931 "In MAP, remap the functions given in COMMANDS.
18932 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18933 (let (new old)
18934 (while commands
18935 (setq old (pop commands) new (pop commands))
18936 (if (fboundp 'command-remapping)
18937 (define-key map (vector 'remap old) new)
18938 (substitute-key-definition old new map global-map)))))
18940 (when (eq org-enable-table-editor 'optimized)
18941 ;; If the user wants maximum table support, we need to hijack
18942 ;; some standard editing functions
18943 (org-remap org-mode-map
18944 'self-insert-command 'org-self-insert-command
18945 'delete-char 'org-delete-char
18946 'delete-backward-char 'org-delete-backward-char)
18947 (define-key org-mode-map "|" 'org-force-self-insert))
18949 (defun org-shiftcursor-error ()
18950 "Throw an error because Shift-Cursor command was applied in wrong context."
18951 (error "This command is active in special context like tables, headlines or timestamps"))
18953 (defun org-shifttab (&optional arg)
18954 "Global visibility cycling or move to previous table field.
18955 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18956 on context.
18957 See the individual commands for more information."
18958 (interactive "P")
18959 (cond
18960 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18961 (arg (message "Content view to level: ")
18962 (org-content (prefix-numeric-value arg))
18963 (setq org-cycle-global-status 'overview))
18964 (t (call-interactively 'org-global-cycle))))
18966 (defun org-shiftmetaleft ()
18967 "Promote subtree or delete table column.
18968 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
18969 See the individual commands for more information."
18970 (interactive)
18971 (cond
18972 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18973 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
18974 ((org-at-item-p) (call-interactively 'org-outdent-item))
18975 (t (org-shiftcursor-error))))
18977 (defun org-shiftmetaright ()
18978 "Demote subtree or insert table column.
18979 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
18980 See the individual commands for more information."
18981 (interactive)
18982 (cond
18983 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18984 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
18985 ((org-at-item-p) (call-interactively 'org-indent-item))
18986 (t (org-shiftcursor-error))))
18988 (defun org-shiftmetaup (&optional arg)
18989 "Move subtree up or kill table row.
18990 Calls `org-move-subtree-up' or `org-table-kill-row' or
18991 `org-move-item-up' depending on context. See the individual commands
18992 for more information."
18993 (interactive "P")
18994 (cond
18995 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18996 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
18997 ((org-at-item-p) (call-interactively 'org-move-item-up))
18998 (t (org-shiftcursor-error))))
18999 (defun org-shiftmetadown (&optional arg)
19000 "Move subtree down or insert table row.
19001 Calls `org-move-subtree-down' or `org-table-insert-row' or
19002 `org-move-item-down', depending on context. See the individual
19003 commands for more information."
19004 (interactive "P")
19005 (cond
19006 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19007 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
19008 ((org-at-item-p) (call-interactively 'org-move-item-down))
19009 (t (org-shiftcursor-error))))
19011 (defun org-metaleft (&optional arg)
19012 "Promote heading or move table column to left.
19013 Calls `org-do-promote' or `org-table-move-column', depending on context.
19014 With no specific context, calls the Emacs default `backward-word'.
19015 See the individual commands for more information."
19016 (interactive "P")
19017 (cond
19018 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19019 ((or (org-on-heading-p) (org-region-active-p))
19020 (call-interactively 'org-do-promote))
19021 ((org-at-item-p) (call-interactively 'org-outdent-item))
19022 (t (call-interactively 'backward-word))))
19024 (defun org-metaright (&optional arg)
19025 "Demote subtree or move table column to right.
19026 Calls `org-do-demote' or `org-table-move-column', depending on context.
19027 With no specific context, calls the Emacs default `forward-word'.
19028 See the individual commands for more information."
19029 (interactive "P")
19030 (cond
19031 ((org-at-table-p) (call-interactively 'org-table-move-column))
19032 ((or (org-on-heading-p) (org-region-active-p))
19033 (call-interactively 'org-do-demote))
19034 ((org-at-item-p) (call-interactively 'org-indent-item))
19035 (t (call-interactively 'forward-word))))
19037 (defun org-metaup (&optional arg)
19038 "Move subtree up or move table row up.
19039 Calls `org-move-subtree-up' or `org-table-move-row' or
19040 `org-move-item-up', depending on context. See the individual commands
19041 for more information."
19042 (interactive "P")
19043 (cond
19044 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19045 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
19046 ((org-at-item-p) (call-interactively 'org-move-item-up))
19047 (t (org-shiftcursor-error))))
19049 (defun org-metadown (&optional arg)
19050 "Move subtree down or move table row down.
19051 Calls `org-move-subtree-down' or `org-table-move-row' or
19052 `org-move-item-down', depending on context. See the individual
19053 commands for more information."
19054 (interactive "P")
19055 (cond
19056 ((org-at-table-p) (call-interactively 'org-table-move-row))
19057 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
19058 ((org-at-item-p) (call-interactively 'org-move-item-down))
19059 (t (org-shiftcursor-error))))
19061 (defun org-shiftup (&optional arg)
19062 "Increase item in timestamp or increase priority of current headline.
19063 Calls `org-timestamp-up' or `org-priority-up', depending on context.
19064 See the individual commands for more information."
19065 (interactive "P")
19066 (cond
19067 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
19068 ((org-on-heading-p) (call-interactively 'org-priority-up))
19069 ((org-at-item-p) (call-interactively 'org-previous-item))
19070 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
19072 (defun org-shiftdown (&optional arg)
19073 "Decrease item in timestamp or decrease priority of current headline.
19074 Calls `org-timestamp-down' or `org-priority-down', depending on context.
19075 See the individual commands for more information."
19076 (interactive "P")
19077 (cond
19078 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
19079 ((org-on-heading-p) (call-interactively 'org-priority-down))
19080 (t (call-interactively 'org-next-item))))
19082 (defun org-shiftright ()
19083 "Next TODO keyword or timestamp one day later, depending on context."
19084 (interactive)
19085 (cond
19086 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19087 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
19088 (t (org-shiftcursor-error))))
19090 (defun org-shiftleft ()
19091 "Previous TODO keyword or timestamp one day earlier, depending on context."
19092 (interactive)
19093 (cond
19094 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19095 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
19096 (t (org-shiftcursor-error))))
19098 (defun org-copy-special ()
19099 "Copy region in table or copy current subtree.
19100 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19101 See the individual commands for more information."
19102 (interactive)
19103 (call-interactively
19104 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19106 (defun org-cut-special ()
19107 "Cut region in table or cut current subtree.
19108 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19109 See the individual commands for more information."
19110 (interactive)
19111 (call-interactively
19112 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19114 (defun org-paste-special (arg)
19115 "Paste rectangular region into table, or past subtree relative to level.
19116 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19117 See the individual commands for more information."
19118 (interactive "P")
19119 (if (org-at-table-p)
19120 (org-table-paste-rectangle)
19121 (org-paste-subtree arg)))
19123 (defun org-ctrl-c-ctrl-c (&optional arg)
19124 "Set tags in headline, or update according to changed information at point.
19126 This command does many different things, depending on context:
19128 - If the cursor is in a headline, prompt for tags and insert them
19129 into the current line, aligned to `org-tags-column'. When called
19130 with prefix arg, realign all tags in the current buffer.
19132 - If the cursor is in one of the special #+KEYWORD lines, this
19133 triggers scanning the buffer for these lines and updating the
19134 information.
19136 - If the cursor is inside a table, realign the table. This command
19137 works even if the automatic table editor has been turned off.
19139 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19140 the entire table.
19142 - If the cursor is inside a table created by the table.el package,
19143 activate that table.
19145 - If the current buffer is a remember buffer, close note and file it.
19146 with a prefix argument, file it without further interaction to the default
19147 location.
19149 - If the cursor is on a <<<target>>>, update radio targets and corresponding
19150 links in this buffer.
19152 - If the cursor is on a numbered item in a plain list, renumber the
19153 ordered list."
19154 (interactive "P")
19155 (let ((org-enable-table-editor t))
19156 (cond
19157 ((or org-clock-overlays
19158 org-occur-highlights
19159 org-latex-fragment-image-overlays)
19160 (org-remove-clock-overlays)
19161 (org-remove-occur-highlights)
19162 (org-remove-latex-fragment-image-overlays)
19163 (message "Temporary highlights/overlays removed from current buffer"))
19164 ((and (local-variable-p 'org-finish-function (current-buffer))
19165 (fboundp org-finish-function))
19166 (funcall org-finish-function))
19167 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
19168 ((org-on-heading-p) (call-interactively 'org-set-tags))
19169 ((org-at-table.el-p)
19170 (require 'table)
19171 (beginning-of-line 1)
19172 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
19173 (call-interactively 'table-recognize-table))
19174 ((org-at-table-p)
19175 (org-table-maybe-eval-formula)
19176 (if arg
19177 (call-interactively 'org-table-recalculate)
19178 (org-table-maybe-recalculate-line))
19179 (call-interactively 'org-table-align))
19180 ((org-at-item-checkbox-p)
19181 (call-interactively 'org-toggle-checkbox))
19182 ((org-at-item-p)
19183 (call-interactively 'org-renumber-ordered-list))
19184 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
19185 (cond
19186 ((equal (match-string 1) "TBLFM")
19187 ;; Recalculate the table before this line
19188 (save-excursion
19189 (beginning-of-line 1)
19190 (skip-chars-backward " \r\n\t")
19191 (if (org-at-table-p)
19192 (org-call-with-arg 'org-table-recalculate t))))
19194 (call-interactively 'org-mode-restart))))
19195 (t (error "C-c C-c can do nothing useful at this location.")))))
19197 (defun org-mode-restart ()
19198 "Restart Org-mode, to scan again for special lines.
19199 Also updates the keyword regular expressions."
19200 (interactive)
19201 (let ((org-inhibit-startup t)) (org-mode))
19202 (message "Org-mode restarted to refresh keyword and special line setup"))
19204 (defun org-return ()
19205 "Goto next table row or insert a newline.
19206 Calls `org-table-next-row' or `newline', depending on context.
19207 See the individual commands for more information."
19208 (interactive)
19209 (cond
19210 ((org-at-table-p)
19211 (org-table-justify-field-maybe)
19212 (call-interactively 'org-table-next-row))
19213 (t (newline))))
19215 (defun org-meta-return (&optional arg)
19216 "Insert a new heading or wrap a region in a table.
19217 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19218 See the individual commands for more information."
19219 (interactive "P")
19220 (cond
19221 ((org-at-table-p)
19222 (call-interactively 'org-table-wrap-region))
19223 (t (call-interactively 'org-insert-heading))))
19225 ;;; Menu entries
19227 ;; Define the Org-mode menus
19228 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19229 '("Tbl"
19230 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
19231 ["Next Field" org-cycle (org-at-table-p)]
19232 ["Previous Field" org-shifttab (org-at-table-p)]
19233 ["Next Row" org-return (org-at-table-p)]
19234 "--"
19235 ["Blank Field" org-table-blank-field (org-at-table-p)]
19236 ["Edit Field" org-table-edit-field (org-at-table-p)]
19237 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19238 "--"
19239 ("Column"
19240 ["Move Column Left" org-metaleft (org-at-table-p)]
19241 ["Move Column Right" org-metaright (org-at-table-p)]
19242 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19243 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19244 ("Row"
19245 ["Move Row Up" org-metaup (org-at-table-p)]
19246 ["Move Row Down" org-metadown (org-at-table-p)]
19247 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19248 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19249 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19250 "--"
19251 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
19252 ("Rectangle"
19253 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19254 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19255 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19256 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19257 "--"
19258 ("Calculate"
19259 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19260 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19261 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
19262 "--"
19263 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19264 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19265 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19266 "--"
19267 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19268 "--"
19269 ["Sum Column/Rectangle" org-table-sum
19270 (or (org-at-table-p) (org-region-active-p))]
19271 ["Which Column?" org-table-current-column (org-at-table-p)])
19272 ["Debug Formulas"
19273 org-table-toggle-formula-debugger
19274 :style toggle :selected org-table-formula-debug]
19275 ["Show Col/Row Numbers"
19276 org-table-toggle-coordinate-overlays
19277 :style toggle :selected org-table-overlay-coordinates]
19278 "--"
19279 ["Create" org-table-create (and (not (org-at-table-p))
19280 org-enable-table-editor)]
19281 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19282 ["Import from File" org-table-import (not (org-at-table-p))]
19283 ["Export to File" org-table-export (org-at-table-p)]
19284 "--"
19285 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19287 (easy-menu-define org-org-menu org-mode-map "Org menu"
19288 '("Org"
19289 ("Show/Hide"
19290 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
19291 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
19292 ["Sparse Tree" org-occur t]
19293 ["Reveal Context" org-reveal t]
19294 ["Show All" show-all t]
19295 "--"
19296 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19297 "--"
19298 ["New Heading" org-insert-heading t]
19299 ("Navigate Headings"
19300 ["Up" outline-up-heading t]
19301 ["Next" outline-next-visible-heading t]
19302 ["Previous" outline-previous-visible-heading t]
19303 ["Next Same Level" outline-forward-same-level t]
19304 ["Previous Same Level" outline-backward-same-level t]
19305 "--"
19306 ["Jump" org-goto t])
19307 ("Edit Structure"
19308 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19309 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19310 "--"
19311 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19312 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19313 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19314 "--"
19315 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19316 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19317 ["Demote Heading" org-metaright (not (org-at-table-p))]
19318 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19319 "--"
19320 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19321 "--"
19322 ["Convert to odd levels" org-convert-to-odd-levels t]
19323 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19324 ("Archive"
19325 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19326 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
19327 ; :active t :keys "C-u C-c C-x C-a"]
19328 ["Sparse trees open ARCHIVE trees"
19329 (setq org-sparse-tree-open-archived-trees
19330 (not org-sparse-tree-open-archived-trees))
19331 :style toggle :selected org-sparse-tree-open-archived-trees]
19332 ["Cycling opens ARCHIVE trees"
19333 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
19334 :style toggle :selected org-cycle-open-archived-trees]
19335 ["Agenda includes ARCHIVE trees"
19336 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
19337 :style toggle :selected (not org-agenda-skip-archived-trees)]
19338 "--"
19339 ["Move Subtree to Archive" org-advertized-archive-subtree t]
19340 ; ["Check and Move Children" (org-archive-subtree '(4))
19341 ; :active t :keys "C-u C-c C-x C-s"]
19343 "--"
19344 ("TODO Lists"
19345 ["TODO/DONE/-" org-todo t]
19346 ("Select keyword"
19347 ["Next keyword" org-shiftright (org-on-heading-p)]
19348 ["Previous keyword" org-shiftleft (org-on-heading-p)]
19349 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
19350 ["Show TODO Tree" org-show-todo-tree t]
19351 ["Global TODO list" org-todo-list t]
19352 "--"
19353 ["Set Priority" org-priority t]
19354 ["Priority Up" org-shiftup t]
19355 ["Priority Down" org-shiftdown t]
19356 "--"
19357 ;; FIXME: why is this still here????
19358 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
19359 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
19360 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
19361 ; (or (org-on-heading-p) (org-at-item-p))]
19362 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
19363 ; (or (org-on-heading-p) (org-at-item-p))]
19364 ; ["Update Statistics" org-update-checkbox-count t]
19366 ("Dates and Scheduling"
19367 ["Timestamp" org-time-stamp t]
19368 ["Timestamp (inactive)" org-time-stamp-inactive t]
19369 ("Change Date"
19370 ["1 Day Later" org-shiftright t]
19371 ["1 Day Earlier" org-shiftleft t]
19372 ["1 ... Later" org-shiftup t]
19373 ["1 ... Earlier" org-shiftdown t])
19374 ["Compute Time Range" org-evaluate-time-range t]
19375 ["Schedule Item" org-schedule t]
19376 ["Deadline" org-deadline t]
19377 "--"
19378 ["Custom time format" org-toggle-time-stamp-overlays
19379 :style radio :selected org-display-custom-times]
19380 "--"
19381 ["Goto Calendar" org-goto-calendar t]
19382 ["Date from Calendar" org-date-from-calendar t])
19383 ("Logging work"
19384 ["Clock in" org-clock-in t]
19385 ["Clock out" org-clock-out t]
19386 ["Clock cancel" org-clock-cancel t]
19387 ["Display times" org-clock-display t]
19388 ["Create clock table" org-clock-report t]
19389 "--"
19390 ["Record DONE time"
19391 (progn (setq org-log-done (not org-log-done))
19392 (message "Switching to %s will %s record a timestamp"
19393 org-done-string
19394 (if org-log-done "automatically" "not")))
19395 :style toggle :selected org-log-done])
19396 "--"
19397 ["Agenda Command..." org-agenda t]
19398 ("File List for Agenda")
19399 ("Special views current file"
19400 ["TODO Tree" org-show-todo-tree t]
19401 ["Check Deadlines" org-check-deadlines t]
19402 ["Timeline" org-timeline t]
19403 ["Tags Tree" org-tags-sparse-tree t])
19404 "--"
19405 ("Hyperlinks"
19406 ["Store Link (Global)" org-store-link t]
19407 ["Insert Link" org-insert-link t]
19408 ["Follow Link" org-open-at-point t]
19409 "--"
19410 ["Next link" org-next-link t]
19411 ["Previous link" org-previous-link t]
19412 "--"
19413 ["Descriptive Links"
19414 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
19415 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
19416 ["Literal Links"
19417 (progn
19418 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
19419 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
19420 "--"
19421 ["Export/Publish..." org-export t]
19422 ("LaTeX"
19423 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19424 :selected org-cdlatex-mode]
19425 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19426 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19427 ["Modify math symbol" org-cdlatex-math-modify
19428 (org-inside-LaTeX-fragment-p)]
19429 ["Export LaTeX fragments as images"
19430 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
19431 :style toggle :selected org-export-with-LaTeX-fragments])
19432 "--"
19433 ("Documentation"
19434 ["Show Version" org-version t]
19435 ["Info Documentation" org-info t])
19436 ("Customize"
19437 ["Browse Org Group" org-customize t]
19438 "--"
19439 ["Expand This Menu" org-create-customize-menu
19440 (fboundp 'customize-menu-create)])
19441 "--"
19442 ["Refresh setup" org-mode-restart t]
19445 (defun org-toggle-log-option (type)
19446 (if (not (listp org-log-done)) (setq org-log-done nil))
19447 (if (memq type org-log-done)
19448 (setq org-log-done (delq type org-log-done))
19449 (add-to-list 'org-log-done type)))
19451 (defun org-check-log-option (type)
19452 (and (listp org-log-done) (memq type org-log-done)))
19454 (defun org-info (&optional node)
19455 "Read documentation for Org-mode in the info system.
19456 With optional NODE, go directly to that node."
19457 (interactive)
19458 (require 'info)
19459 (Info-goto-node (format "(org)%s" (or node ""))))
19461 (defun org-install-agenda-files-menu ()
19462 (let ((bl (buffer-list)))
19463 (save-excursion
19464 (while bl
19465 (set-buffer (pop bl))
19466 (if (org-mode-p) (setq bl nil)))
19467 (when (org-mode-p)
19468 (easy-menu-change
19469 '("Org") "File List for Agenda"
19470 (append
19471 (list
19472 ["Edit File List" (org-edit-agenda-file-list) t]
19473 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19474 ["Remove Current File from List" org-remove-file t]
19475 ["Cycle through agenda files" org-cycle-agenda-files t]
19476 "--")
19477 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19479 ;;;; Documentation
19481 (defun org-customize ()
19482 "Call the customize function with org as argument."
19483 (interactive)
19484 (customize-browse 'org))
19486 (defun org-create-customize-menu ()
19487 "Create a full customization menu for Org-mode, insert it into the menu."
19488 (interactive)
19489 (if (fboundp 'customize-menu-create)
19490 (progn
19491 (easy-menu-change
19492 '("Org") "Customize"
19493 `(["Browse Org group" org-customize t]
19494 "--"
19495 ,(customize-menu-create 'org)
19496 ["Set" Custom-set t]
19497 ["Save" Custom-save t]
19498 ["Reset to Current" Custom-reset-current t]
19499 ["Reset to Saved" Custom-reset-saved t]
19500 ["Reset to Standard Settings" Custom-reset-standard t]))
19501 (message "\"Org\"-menu now contains full customization menu"))
19502 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19504 ;;;; Miscellaneous stuff
19507 ;;; Generally useful functions
19509 (defun org-context ()
19510 "Return a list of contexts of the current cursor position.
19511 If several contexts apply, all are returned.
19512 Each context entry is a list with a symbol naming the context, and
19513 two positions indicating start and end of the context. Possible
19514 contexts are:
19516 :headline anywhere in a headline
19517 :headline-stars on the leading stars in a headline
19518 :todo-keyword on a TODO keyword (including DONE) in a headline
19519 :tags on the TAGS in a headline
19520 :priority on the priority cookie in a headline
19521 :item on the first line of a plain list item
19522 :item-bullet on the bullet/number of a plain list item
19523 :checkbox on the checkbox in a plain list item
19524 :table in an org-mode table
19525 :table-special on a special filed in a table
19526 :table-table in a table.el table
19527 :link on a hyperlink
19528 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19529 :target on a <<target>>
19530 :radio-target on a <<<radio-target>>>
19531 :latex-fragment on a LaTeX fragment
19532 :latex-preview on a LaTeX fragment with overlayed preview image
19534 This function expects the position to be visible because it uses font-lock
19535 faces as a help to recognize the following contexts: :table-special, :link,
19536 and :keyword."
19537 (let* ((f (get-text-property (point) 'face))
19538 (faces (if (listp f) f (list f)))
19539 (p (point)) clist o)
19540 ;; First the large context
19541 (cond
19542 ((org-on-heading-p t)
19543 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19544 (when (progn
19545 (beginning-of-line 1)
19546 (looking-at org-todo-line-tags-regexp))
19547 (push (org-point-in-group p 1 :headline-stars) clist)
19548 (push (org-point-in-group p 2 :todo-keyword) clist)
19549 (push (org-point-in-group p 4 :tags) clist))
19550 (goto-char p)
19551 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
19552 (if (looking-at "\\[#[A-Z]\\]")
19553 (push (org-point-in-group p 0 :priority) clist)))
19555 ((org-at-item-p)
19556 (push (org-point-in-group p 2 :item-bullet) clist)
19557 (push (list :item (point-at-bol)
19558 (save-excursion (org-end-of-item) (point)))
19559 clist)
19560 (and (org-at-item-checkbox-p)
19561 (push (org-point-in-group p 0 :checkbox) clist)))
19563 ((org-at-table-p)
19564 (push (list :table (org-table-begin) (org-table-end)) clist)
19565 (if (memq 'org-formula faces)
19566 (push (list :table-special
19567 (previous-single-property-change p 'face)
19568 (next-single-property-change p 'face)) clist)))
19569 ((org-at-table-p 'any)
19570 (push (list :table-table) clist)))
19571 (goto-char p)
19573 ;; Now the small context
19574 (cond
19575 ((org-at-timestamp-p)
19576 (push (org-point-in-group p 0 :timestamp) clist))
19577 ((memq 'org-link faces)
19578 (push (list :link
19579 (previous-single-property-change p 'face)
19580 (next-single-property-change p 'face)) clist))
19581 ((memq 'org-special-keyword faces)
19582 (push (list :keyword
19583 (previous-single-property-change p 'face)
19584 (next-single-property-change p 'face)) clist))
19585 ((org-on-target-p)
19586 (push (org-point-in-group p 0 :target) clist)
19587 (goto-char (1- (match-beginning 0)))
19588 (if (looking-at org-radio-target-regexp)
19589 (push (org-point-in-group p 0 :radio-target) clist))
19590 (goto-char p))
19591 ((setq o (car (delq nil
19592 (mapcar
19593 (lambda (x)
19594 (if (memq x org-latex-fragment-image-overlays) x))
19595 (org-overlays-at (point))))))
19596 (push (list :latex-fragment
19597 (org-overlay-start o) (org-overlay-end o)) clist)
19598 (push (list :latex-preview
19599 (org-overlay-start o) (org-overlay-end o)) clist))
19600 ((org-inside-LaTeX-fragment-p)
19601 ;; FIXME: positions wrong.
19602 (push (list :latex-fragment (point) (point)) clist)))
19604 (setq clist (nreverse (delq nil clist)))
19605 clist))
19607 (defun org-in-regexp (re &optional nlines visually)
19608 "Check if point is inside a match of regexp.
19609 Normally only the current line is checked, but you can include NLINES extra
19610 lines both before and after point into the search.
19611 If VISUALLY is set, require that the cursor is not after the match but
19612 really on, so that the block visually is on the match."
19613 (catch 'exit
19614 (let ((pos (point))
19615 (eol (point-at-eol (+ 1 (or nlines 0))))
19616 (inc (if visually 1 0)))
19617 (save-excursion
19618 (beginning-of-line (- 1 (or nlines 0)))
19619 (while (re-search-forward re eol t)
19620 (if (and (<= (match-beginning 0) pos)
19621 (>= (+ inc (match-end 0)) pos))
19622 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
19624 (defun org-point-in-group (point group &optional context)
19625 "Check if POINT is in match-group GROUP.
19626 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
19627 match. If the match group does ot exist or point is not inside it,
19628 return nil."
19629 (and (match-beginning group)
19630 (>= point (match-beginning group))
19631 (<= point (match-end group))
19632 (if context
19633 (list context (match-beginning group) (match-end group))
19634 t)))
19636 (defun org-combine-plists (&rest plists)
19637 "Create a single property list from all plists in PLISTS.
19638 The process starts by copying the first list, and then setting properties
19639 from the other lists. Settings in the last list are the most significant
19640 ones and overrule settings in the other lists."
19641 (let ((rtn (copy-sequence (pop plists)))
19642 p v ls)
19643 (while plists
19644 (setq ls (pop plists))
19645 (while ls
19646 (setq p (pop ls) v (pop ls))
19647 (setq rtn (plist-put rtn p v))))
19648 rtn))
19650 (defun org-move-line-down (arg)
19651 "Move the current line down. With prefix argument, move it past ARG lines."
19652 (interactive "p")
19653 (let ((col (current-column))
19654 beg end pos)
19655 (beginning-of-line 1) (setq beg (point))
19656 (beginning-of-line 2) (setq end (point))
19657 (beginning-of-line (+ 1 arg))
19658 (setq pos (move-marker (make-marker) (point)))
19659 (insert (delete-and-extract-region beg end))
19660 (goto-char pos)
19661 (move-to-column col)))
19663 (defun org-move-line-up (arg)
19664 "Move the current line up. With prefix argument, move it past ARG lines."
19665 (interactive "p")
19666 (let ((col (current-column))
19667 beg end pos)
19668 (beginning-of-line 1) (setq beg (point))
19669 (beginning-of-line 2) (setq end (point))
19670 (beginning-of-line (- arg))
19671 (setq pos (move-marker (make-marker) (point)))
19672 (insert (delete-and-extract-region beg end))
19673 (goto-char pos)
19674 (move-to-column col)))
19676 (defun org-replace-escapes (string table)
19677 "Replace %-escapes in STRING with values in TABLE.
19678 TABLE is an association list with keys line \"%a\" and string values.
19679 The sequences in STRING may contain normal field width and padding information,
19680 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
19681 so values can contain further %-escapes if they are define later in TABLE."
19682 (let ((case-fold-search nil)
19683 e re rpl)
19684 (while (setq e (pop table))
19685 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
19686 (while (string-match re string)
19687 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
19688 (cdr e)))
19689 (setq string (replace-match rpl t t string))))
19690 string))
19693 (defun org-sublist (list start end)
19694 "Return a section of LIST, from START to END.
19695 Counting starts at 1."
19696 (let (rtn (c start))
19697 (setq list (nthcdr (1- start) list))
19698 (while (and list (<= c end))
19699 (push (pop list) rtn)
19700 (setq c (1+ c)))
19701 (nreverse rtn)))
19703 (defun org-at-regexp-p (regexp)
19704 "Is point inside a match of REGEXP in the current line?"
19705 (catch 'exit
19706 (save-excursion
19707 (let ((pos (point)) (end (point-at-eol)))
19708 (beginning-of-line 1)
19709 (while (re-search-forward regexp end t)
19710 (if (and (<= (match-beginning 0) pos)
19711 (>= (match-end 0) pos))
19712 (throw 'exit t)))
19713 nil))))
19715 (defun org-find-base-buffer-visiting (file)
19716 "Like `find-buffer-visiting' but alway return the base buffer and
19717 not an indirect buffer"
19718 (let ((buf (find-buffer-visiting file)))
19719 (or (buffer-base-buffer buf) buf)))
19721 ;;; Paragraph filling stuff.
19722 ;; We want this to be just right, so use the full arsenal.
19724 (defun org-indent-line-function ()
19725 "Indent line like previous, but further if previous was headline or item."
19726 (interactive)
19727 (let ((column (save-excursion
19728 (beginning-of-line)
19729 (if (looking-at "#") 0
19730 (skip-chars-backward "\n \t")
19731 (beginning-of-line)
19732 (if (or (looking-at "\\*+[ \t]+")
19733 (looking-at "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)"))
19734 (progn (goto-char (match-end 0)) (current-column))
19735 (current-indentation))))))
19736 (if (<= (current-column) (current-indentation))
19737 (indent-line-to column)
19738 (save-excursion (indent-line-to column)))))
19740 (defun org-set-autofill-regexps ()
19741 (interactive)
19742 ;; In the paragraph separator we include headlines, because filling
19743 ;; text in a line directly attached to a headline would otherwise
19744 ;; fill the headline as well.
19745 (org-set-local 'comment-start-skip "^#+[ \t]*")
19746 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
19747 ;; The paragraph starter includes hand-formatted lists.
19748 (org-set-local 'paragraph-start
19749 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
19750 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
19751 ;; But only if the user has not turned off tables or fixed-width regions
19752 (org-set-local
19753 'auto-fill-inhibit-regexp
19754 (concat "\\*\\|#\\+"
19755 "\\|[ \t]*" org-keyword-time-regexp
19756 (if (or org-enable-table-editor org-enable-fixed-width-editor)
19757 (concat
19758 "\\|[ \t]*["
19759 (if org-enable-table-editor "|" "")
19760 (if org-enable-fixed-width-editor ":" "")
19761 "]"))))
19762 ;; We use our own fill-paragraph function, to make sure that tables
19763 ;; and fixed-width regions are not wrapped. That function will pass
19764 ;; through to `fill-paragraph' when appropriate.
19765 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
19766 ; Adaptive filling: To get full control, first make sure that
19767 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
19768 (org-set-local 'adaptive-fill-regexp "\000")
19769 (org-set-local 'adaptive-fill-function
19770 'org-adaptive-fill-function))
19772 (defun org-fill-paragraph (&optional justify)
19773 "Re-align a table, pass through to fill-paragraph if no table."
19774 (let ((table-p (org-at-table-p))
19775 (table.el-p (org-at-table.el-p)))
19776 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
19777 (table.el-p t) ; skip table.el tables
19778 (table-p (org-table-align) t) ; align org-mode tables
19779 (t nil)))) ; call paragraph-fill
19781 ;; For reference, this is the default value of adaptive-fill-regexp
19782 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
19784 (defun org-adaptive-fill-function ()
19785 "Return a fill prefix for org-mode files.
19786 In particular, this makes sure hanging paragraphs for hand-formatted lists
19787 work correctly."
19788 (cond ((looking-at "#[ \t]+")
19789 (match-string 0))
19790 ((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
19791 (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
19792 (t nil)))
19795 ;; FIXME: these 2 functions are not in the right place.
19796 (defun org-image-file-name-regexp ()
19797 "Return regexp matching the file names of images."
19798 (if (fboundp 'image-file-name-regexp)
19799 (image-file-name-regexp)
19800 (let ((image-file-name-extensions
19801 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
19802 "xbm" "xpm" "pbm" "pgm" "ppm")))
19803 (concat "\\."
19804 (regexp-opt (nconc (mapcar 'upcase
19805 image-file-name-extensions)
19806 image-file-name-extensions)
19808 "\\'"))))
19810 (defun org-file-image-p (file)
19811 "Return non-nil if FILE is an image."
19812 (save-match-data
19813 (string-match (org-image-file-name-regexp) file)))
19815 ;;;; Functions extending outline functionality
19817 ;; C-a should go to the beginning of a *visible* line, also in the
19818 ;; new outline.el. I guess this should be patched into Emacs?
19819 (defun org-beginning-of-line ()
19820 "Go to the beginning of the current line. If that is invisible, continue
19821 to a visible line beginning. This makes the function of C-a more intuitive."
19822 (interactive)
19823 (beginning-of-line 1)
19824 (if (bobp)
19826 (backward-char 1)
19827 (if (org-invisible-p)
19828 (while (and (not (bobp)) (org-invisible-p))
19829 (backward-char 1)
19830 (beginning-of-line 1))
19831 (forward-char 1))))
19833 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
19835 (defun org-invisible-p ()
19836 "Check if point is at a character currently not visible."
19837 ;; Early versions of noutline don't have `outline-invisible-p'.
19838 (if (fboundp 'outline-invisible-p)
19839 (outline-invisible-p)
19840 (get-char-property (point) 'invisible)))
19842 (defun org-invisible-p2 ()
19843 "Check if point is at a character currently not visible."
19844 (save-excursion
19845 (if (and (eolp) (not (bobp))) (backward-char 1))
19846 ;; Early versions of noutline don't have `outline-invisible-p'.
19847 (if (fboundp 'outline-invisible-p)
19848 (outline-invisible-p)
19849 (get-char-property (point) 'invisible))))
19851 (defalias 'org-back-to-heading 'outline-back-to-heading)
19852 (defalias 'org-on-heading-p 'outline-on-heading-p)
19854 (defun org-on-target-p ()
19855 (or (org-in-regexp org-radio-target-regexp)
19856 (org-in-regexp org-target-regexp)))
19858 (defun org-up-heading-all (arg)
19859 "Move to the heading line of which the present line is a subheading.
19860 This function considers both visible and invisible heading lines.
19861 With argument, move up ARG levels."
19862 (if (fboundp 'outline-up-heading-all)
19863 (outline-up-heading-all arg) ; emacs 21 version of outline.el
19864 (outline-up-heading arg t))) ; emacs 22 version of outline.el
19866 (defun org-goto-sibling (&optional previous)
19867 "Goto the next sibling, even if it is invisible.
19868 When PREVIOUS is set, go to the previous sibling instead. Returns t
19869 when a sibling was found. When none is found, return nil and don't
19870 move point."
19871 (let ((fun (if previous 're-search-backward 're-search-forward))
19872 (pos (point))
19873 (re (concat "^" outline-regexp))
19874 level l)
19875 (org-back-to-heading t)
19876 (setq level (funcall outline-level))
19877 (catch 'exit
19878 (or previous (forward-char 1))
19879 (while (funcall fun re nil t)
19880 (setq l (funcall outline-level))
19881 (when (< l level) (goto-char pos) (throw 'exit nil))
19882 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
19883 (goto-char pos)
19884 nil)))
19886 (defun org-show-siblings ()
19887 "Show all siblings of the current headline."
19888 (save-excursion
19889 (while (org-goto-sibling) (org-flag-heading nil)))
19890 (save-excursion
19891 (while (org-goto-sibling 'previous)
19892 (org-flag-heading nil))))
19894 (defun org-show-hidden-entry ()
19895 "Show an entry where even the heading is hidden."
19896 (save-excursion
19897 (org-show-entry)))
19899 (defun org-flag-heading (flag &optional entry)
19900 "Flag the current heading. FLAG non-nil means make invisible.
19901 When ENTRY is non-nil, show the entire entry."
19902 (save-excursion
19903 (org-back-to-heading t)
19904 ;; Check if we should show the entire entry
19905 (if entry
19906 (progn
19907 (org-show-entry)
19908 (save-excursion
19909 (and (outline-next-heading)
19910 (org-flag-heading nil))))
19911 (outline-flag-region (max 1 (1- (point)))
19912 (save-excursion (outline-end-of-heading) (point))
19913 flag))))
19915 (defun org-end-of-subtree (&optional invisible-OK)
19916 ;; This is an exact copy of the original function, but it uses
19917 ;; `org-back-to-heading', to make it work also in invisible
19918 ;; trees. And is uses an invisible-OK argument.
19919 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
19920 (org-back-to-heading invisible-OK)
19921 (let ((first t)
19922 (level (funcall outline-level)))
19923 (while (and (not (eobp))
19924 (or first (> (funcall outline-level) level)))
19925 (setq first nil)
19926 (outline-next-heading))
19927 (if (memq (preceding-char) '(?\n ?\^M))
19928 (progn
19929 ;; Go to end of line before heading
19930 (forward-char -1)
19931 (if (memq (preceding-char) '(?\n ?\^M))
19932 ;; leave blank line before heading
19933 (forward-char -1)))))
19934 (point))
19936 (defun org-show-subtree ()
19937 "Show everything after this heading at deeper levels."
19938 (outline-flag-region
19939 (point)
19940 (save-excursion
19941 (outline-end-of-subtree) (outline-next-heading) (point))
19942 nil))
19944 (defun org-show-entry ()
19945 "Show the body directly following this heading.
19946 Show the heading too, if it is currently invisible."
19947 (interactive)
19948 (save-excursion
19949 (org-back-to-heading t)
19950 (outline-flag-region
19951 (max 1 (1- (point)))
19952 (save-excursion
19953 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
19954 (or (match-beginning 1) (point-max)))
19955 nil)))
19957 (defun org-make-options-regexp (kwds)
19958 "Make a regular expression for keyword lines."
19959 (concat
19961 "#?[ \t]*\\+\\("
19962 (mapconcat 'regexp-quote kwds "\\|")
19963 "\\):[ \t]*"
19964 "\\(.+\\)"))
19966 ;; Make isearch reveal the necessary context
19967 (defun org-isearch-end ()
19968 "Reveal context after isearch exits."
19969 (when isearch-success ; only if search was successful
19970 (if (featurep 'xemacs)
19971 ;; Under XEmacs, the hook is run in the correct place,
19972 ;; we directly show the context.
19973 (org-show-context 'isearch)
19974 ;; In Emacs the hook runs *before* restoring the overlays.
19975 ;; So we have to use a one-time post-command-hook to do this.
19976 ;; (Emacs 22 has a special variable, see function `org-mode')
19977 (unless (and (boundp 'isearch-mode-end-hook-quit)
19978 isearch-mode-end-hook-quit)
19979 ;; Only when the isearch was not quitted.
19980 (org-add-hook 'post-command-hook 'org-isearch-post-command
19981 'append 'local)))))
19983 (defun org-isearch-post-command ()
19984 "Remove self from hook, and show context."
19985 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
19986 (org-show-context 'isearch))
19988 ;;;; Repair problems with some other packages
19990 ;; Make `bookmark-jump' show the jump location if it was hidden.
19991 (eval-after-load "bookmark"
19992 '(if (boundp 'bookmark-after-jump-hook)
19993 ;; We can use the hook
19994 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
19995 ;; Hook not available, use advice
19996 (defadvice bookmark-jump (after org-make-visible activate)
19997 "Make the position visible."
19998 (org-bookmark-jump-unhide))))
20000 (defun org-bookmark-jump-unhide ()
20001 "Unhide the current position, to show the bookmark location."
20002 (and (org-mode-p)
20003 (or (org-invisible-p)
20004 (save-excursion (goto-char (max (point-min) (1- (point))))
20005 (org-invisible-p)))
20006 (org-show-context 'bookmark-jump)))
20008 ;; Make session.el ignore our circular variable
20009 (eval-after-load "session"
20010 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20012 ;;;; Experimental code
20014 (defun org-table-formula-to-user (s)
20015 "Convert a formula from internal to user representation."
20016 (if (eq org-table-use-standard-references t)
20017 (org-table-convert-refs-to-an s)
20020 (defun org-table-formula-from-user (s)
20021 "Convert a formula from user to internal representation."
20022 (if org-table-use-standard-references
20023 (org-table-convert-refs-to-rc s)
20026 (defun org-table-convert-refs-to-rc (s)
20027 "Convert spreadsheet references from AB7 to @7$28.
20028 Works for single references, but also for entire formulas and even the
20029 full TBLFM line."
20030 (let ((start 0))
20031 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
20032 (if (match-end 3)
20033 ;; format match, just advance
20034 (setq start (match-end 0))
20035 (setq start (match-beginning 0)
20036 s (replace-match
20037 (if (equal (match-string 2 s) "&")
20038 (format "$%d" (org-letters-to-number (match-string 1 s)))
20039 (format "@%d$%d"
20040 (string-to-number (match-string 2 s))
20041 (org-letters-to-number (match-string 1 s))))
20042 t t s))))
20045 (defun org-table-convert-refs-to-an (s)
20046 "Convert spreadsheet references from to @7$28 to AB7.
20047 Works for single references, but also for entire formulas and even the
20048 full TBLFM line."
20049 (while (string-match "@\\([0-9]+\\)$\\([0-9]+\\)" s)
20050 (setq s (replace-match
20051 (format "%s%d"
20052 (org-number-to-letters
20053 (string-to-number (match-string 2 s)))
20054 (string-to-number (match-string 1 s)))
20055 t t s)))
20056 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
20057 (setq s (replace-match (concat "\\1"
20058 (org-number-to-letters
20059 (string-to-number (match-string 2 s))) "&")
20060 t nil s)))
20063 (defun org-letters-to-number (s)
20064 "Convert a base 26 number represented by letters into an integer.
20065 For example: AB -> 28."
20066 (let ((n 0))
20067 (setq s (upcase s))
20068 (while (> (length s) 0)
20069 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
20070 s (substring s 1)))
20073 (defun org-number-to-letters (n)
20074 "Convert an integer into a base 26 number represented by letters.
20075 For example: 28 -> AB."
20076 (let ((s ""))
20077 (while (> n 0)
20078 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
20079 n (/ (1- n) 26)))
20082 (defun org-table-fedit-convert-buffer (function)
20083 "Convert all references in this buffer, using FUNTION."
20084 (let ((line (org-current-line)))
20085 (goto-char (point-min))
20086 (while (not (eobp))
20087 (insert (funcall function (buffer-substring (point) (point-at-eol))))
20088 (delete-region (point) (point-at-eol))
20089 (or (eobp) (forward-char 1)))
20090 (goto-line line)))
20092 (defvar org-table-buffer-is-an nil)
20094 (defun org-table-fedit-toggle-ref-type ()
20095 "Convert all references in the buffer from B3 to @3$2 and back."
20096 (interactive)
20097 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
20098 (org-table-fedit-convert-buffer
20099 (if org-table-buffer-is-an
20100 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
20101 (message "Reference type switched to %s"
20102 (if org-table-buffer-is-an "A1 etc" "@row$column")))
20104 (defun org-table-fedit-ref-up ()
20105 "Shift the reference at point one row/hline up."
20106 (interactive)
20107 (org-table-fedit-shift-reference 'up))
20108 (defun org-table-fedit-ref-down ()
20109 "Shift the reference at point one row/hline down."
20110 (interactive)
20111 (org-table-fedit-shift-reference 'down))
20112 (defun org-table-fedit-ref-left ()
20113 "Shift the reference at point one field to the left."
20114 (interactive)
20115 (org-table-fedit-shift-reference 'left))
20116 (defun org-table-fedit-ref-right ()
20117 "Shift the reference at point one field to the right."
20118 (interactive)
20119 (org-table-fedit-shift-reference 'right))
20121 (defun org-table-fedit-shift-reference (dir)
20122 (cond
20123 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
20124 (if (memq dir '(left right))
20125 (org-rematch-and-replace 1 (eq dir 'left))
20126 (error "Cannot shift reference in this direction")))
20127 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
20128 ;; A B3-like reference
20129 (if (memq dir '(up down))
20130 (org-rematch-and-replace 2 (eq dir 'up))
20131 (org-rematch-and-replace 1 (eq dir 'left))))
20132 ((org-at-regexp-p
20133 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
20134 ;; An internal reference
20135 (if (memq dir '(up down))
20136 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
20137 (org-rematch-and-replace 5 (eq dir 'left))))))
20139 (defun org-rematch-and-replace (n &optional decr hline)
20140 "Re-match the group N, and replace it with the shifted refrence."
20141 (or (match-end n) (error "Cannot shift reference in this direction"))
20142 (goto-char (match-beginning n))
20143 (and (looking-at (regexp-quote (match-string n)))
20144 (replace-match (org-shift-refpart (match-string 0) decr hline)
20145 t t)))
20147 (defun org-shift-refpart (ref &optional decr hline)
20148 "Shift a refrence part REF.
20149 If DECR is set, decrease the references row/column, else increase.
20150 If HLINE is set, this may be a hline reference, it certainly is not
20151 a translation reference."
20152 (save-match-data
20153 (let* ((sign (string-match "^[-+]" ref)) n)
20155 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
20156 (cond
20157 ((and hline (string-match "^I+" ref))
20158 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
20159 (setq n (+ n (if decr -1 1)))
20160 (if (= n 0) (setq n (+ n (if decr -1 1))))
20161 (if sign
20162 (setq sign (if (< n 0) "-" "+") n (abs n))
20163 (setq n (max 1 n)))
20164 (concat sign (make-string n ?I)))
20166 ((string-match "^[0-9]+" ref)
20167 (setq n (string-to-number (concat sign ref)))
20168 (setq n (+ n (if decr -1 1)))
20169 (if sign
20170 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
20171 (number-to-string (max 1 n))))
20173 ((string-match "^[a-zA-Z]+" ref)
20174 (org-number-to-letters
20175 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
20177 (t (error "Cannot shift reference"))))))
20179 (defun org-table-fedit-toggle-coordinates ()
20180 "Toggle the display of coordinates in the refrenced table."
20181 (interactive)
20182 (let ((pos (marker-position org-pos)))
20183 (with-current-buffer (marker-buffer org-pos)
20184 (save-excursion
20185 (goto-char pos)
20186 (org-table-toggle-coordinate-overlays)))))
20188 ;;;; Finish up
20190 (provide 'org)
20192 (run-hooks 'org-load-hook)
20194 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20195 ;;; org.el ends here