Release 4.70
[org-mode.git] / org.el
blob904c92175358e8a88bb869a7146c37fa57023d67
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.70
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.70"
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 '((sequence "TODO" "DONE"))
1333 "List of TODO entry keyword sequences and their interpretation.
1334 \\<org-mode-map>This is a list of sequences.
1336 Each sequence starts with a symbol, either `sequence' or `type',
1337 indicating if the keywords should be interpreted as a sequence of
1338 action steps, or as different types of TODO items. The first
1339 keywords are states requiring action - these states will select a headline
1340 for inclusion into the global TODO list Org-mode produces. If one of
1341 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1342 signify that no further action is necessary. If \"|\" is not found,
1343 the last keyword is treated as the only DONE state of the sequence.
1345 The command \\[org-todo] cycles an entry through these states, and one
1346 additional state where no keyword is present. For details about this
1347 cycling, see the manual.
1349 TODO keywords and interpretation can also be set on a per-file basis with
1350 the special #+SEQ_TODO and #+TYP_TODO lines.
1352 For backward compatibility, this variable may also be just a list
1353 of keywords - in this case the interptetation (sequence or type) will be
1354 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1355 :group 'org-todo
1356 :group 'org-keywords
1357 :type '(choice
1358 (repeat :tag "Old syntax, just keywords"
1359 (string :tag "Keyword"))
1360 (repeat :tag "New syntax"
1361 (cons
1362 (choice
1363 :tag "Interpretation"
1364 (const :tag "Sequence (cycling hits every state)" sequence)
1365 (const :tag "Type (cycling directly to DONE)" type))
1366 (repeat
1367 (string :tag "Keyword"))))))
1369 (defvar org-todo-keywords-1 nil)
1370 (make-variable-buffer-local 'org-todo-keywords-1)
1371 (defvar org-not-done-keywords nil)
1372 (make-variable-buffer-local 'org-not-done-keywords)
1373 (defvar org-done-keywords nil)
1374 (make-variable-buffer-local 'org-done-keywords)
1375 (defvar org-todo-heads nil)
1376 (make-variable-buffer-local 'org-todo-heads)
1377 (defvar org-todo-sets nil)
1378 (make-variable-buffer-local 'org-todo-sets)
1379 (defvar org-todo-kwd-alist nil)
1380 (make-variable-buffer-local 'org-todo-kwd-alist)
1382 (defcustom org-todo-interpretation 'sequence
1383 "Controls how TODO keywords are interpreted.
1384 This variable is in principle obsolete and is only used for
1385 backward compatibility, if the interpretation of todo keywords is
1386 not given already in `org-todo-keywords'. See that variable for
1387 more information."
1388 :group 'org-todo
1389 :group 'org-keywords
1390 :type '(choice (const sequence)
1391 (const type)))
1393 (defcustom org-after-todo-state-change-hook nil
1394 "Hook which is run after the state of a TODO item was changed.
1395 The new state (a string with a TODO keyword, or nil) is available in the
1396 Lisp variable `state'."
1397 :group 'org-todo
1398 :type 'hook)
1400 (defcustom org-log-done nil
1401 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1402 When the state of an entry is changed from nothing to TODO, remove a previous
1403 closing date.
1405 This can also be a list of symbols indicating under which conditions
1406 the time stamp recording the action should be annotated with a short note.
1407 Valid members of this list are
1409 done Offer to record a note when marking entries done
1410 state Offer to record a note whenever changing the TODO state
1411 of an item. This is only relevant if TODO keywords are
1412 interpreted as sequence, see variable `org-todo-interpretation'.
1413 When `state' is set, this includes tracking `done'.
1414 clock-out Offer to record a note when clocking out of an item.
1416 A separate window will then pop up and allow you to type a note.
1417 After finishing with C-c C-c, the note will be added directly after the
1418 timestamp, as a plain list item. See also the variable
1419 `org-log-note-headings'.
1421 Logging can also be configured on a per-file basis by adding one of
1422 the following lines anywhere in the buffer:
1424 #+STARTUP: logdone
1425 #+STARTUP: nologging
1426 #+STARTUP: lognotedone
1427 #+STARTUP: lognotestate
1428 #+STARTUP: lognoteclock-out"
1429 :group 'org-todo
1430 :group 'org-progress
1431 :type '(choice
1432 (const :tag "off" nil)
1433 (const :tag "on" t)
1434 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1435 (const :tag "when item is marked DONE" done)
1436 (const :tag "when TODO state changes" state)
1437 (const :tag "when clocking out" clock-out))))
1439 (defcustom org-log-note-headings
1440 '((done . "CLOSING NOTE %t")
1441 (state . "State %-12s %t")
1442 (clock-out . ""))
1443 "Headings for notes added when clocking out or closing TODO items.
1444 The value is an alist, with the car being a sympol indicating the note
1445 context, and the cdr is the heading to be used. The heading may also be the
1446 empty string.
1447 %t in the heading will be replaced by a time stamp.
1448 %s will be replaced by the new TODO state, in double quotes.
1449 %u will be replaced by the user name.
1450 %U will be replaced by the full user name."
1451 :group 'org-todo
1452 :group 'org-progress
1453 :type '(list :greedy t
1454 (cons (const :tag "Heading when closing an item" done) string)
1455 (cons (const :tag
1456 "Heading when changing todo state (todo sequence only)"
1457 state) string)
1458 (cons (const :tag "Heading when clocking out" clock-out) string)))
1460 (defcustom org-allow-auto-repeat t
1461 "Non-nil means, find REPEAT cookies in entries and apply them.
1462 A repeat cookie looks like REPEAT(+1m) and causes deadlines and schedules
1463 to repeat themselves shifted by a certain amount of time, each time an
1464 entry is marked DONE."
1465 :group 'org-todo
1466 :group 'org-progress
1467 :type 'boolean)
1469 (defcustom org-log-repeat t
1470 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1471 When nil, no note will be taken."
1472 :group 'org-todo
1473 :group 'org-progress
1474 :type 'boolean)
1476 (defgroup org-priorities nil
1477 "Priorities in Org-mode."
1478 :tag "Org Priorities"
1479 :group 'org-todo)
1481 (defcustom org-default-priority ?B
1482 "The default priority of TODO items.
1483 This is the priority an item get if no explicit priority is given."
1484 :group 'org-priorities
1485 :type 'character)
1487 (defcustom org-lowest-priority ?C
1488 "The lowest priority of TODO items. A character like ?A, ?B etc."
1489 :group 'org-priorities
1490 :type 'character)
1492 (defgroup org-time nil
1493 "Options concerning time stamps and deadlines in Org-mode."
1494 :tag "Org Time"
1495 :group 'org)
1497 (defcustom org-insert-labeled-timestamps-at-point nil
1498 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1499 When nil, these labeled time stamps are forces into the second line of an
1500 entry, just after the headline. When scheduling from the global TODO list,
1501 the time stamp will always be forced into the second line."
1502 :group 'org-time
1503 :type 'boolean)
1505 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1506 "Formats for `format-time-string' which are used for time stamps.
1507 It is not recommended to change this constant.")
1509 (defcustom org-time-stamp-rounding-minutes 0
1510 "Number of minutes to round time stamps to upon insertion.
1511 When zero, insert the time unmodified. Useful rounding numbers
1512 should be factors of 60, so for example 5, 10, 15.
1513 When this is not zero, you can still force an exact time-stamp by using
1514 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1515 :group 'org-time
1516 :type 'integer)
1518 (defcustom org-display-custom-times nil
1519 "Non-nil means, overlay custom formats over all time stamps.
1520 The formats are defined through the variable `org-time-stamp-custom-formats'.
1521 To turn this on on a per-file basis, insert anywhere in the file:
1522 #+STARTUP: customtime"
1523 :group 'org-time
1524 :set 'set-default
1525 :type 'sexp)
1526 (make-variable-buffer-local 'org-display-custom-times)
1528 (defcustom org-time-stamp-custom-formats
1529 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1530 "Custom formats for time stamps. See `format-time-string' for the syntax.
1531 These are overlayed over the default ISO format if the variable
1532 `org-display-custom-times' is set."
1533 :group 'org-time
1534 :type 'sexp)
1536 (defun org-time-stamp-format (&optional long inactive)
1537 "Get the right format for a time string."
1538 (let ((f (if long (cdr org-time-stamp-formats)
1539 (car org-time-stamp-formats))))
1540 (if inactive
1541 (concat "[" (substring f 1 -1) "]")
1542 f)))
1544 (defcustom org-deadline-warning-days 30
1545 "No. of days before expiration during which a deadline becomes active.
1546 This variable governs the display in sparse trees and in the agenda."
1547 :group 'org-time
1548 :type 'number)
1550 (defcustom org-popup-calendar-for-date-prompt t
1551 "Non-nil means, pop up a calendar when prompting for a date.
1552 In the calendar, the date can be selected with mouse-1. However, the
1553 minibuffer will also be active, and you can simply enter the date as well.
1554 When nil, only the minibuffer will be available."
1555 :group 'org-time
1556 :type 'boolean)
1558 (defcustom org-calendar-follow-timestamp-change t
1559 "Non-nil means, make the calendar window follow timestamp changes.
1560 When a timestamp is modified and the calendar window is visible, it will be
1561 moved to the new date."
1562 :group 'org-time
1563 :type 'boolean)
1565 (defgroup org-tags nil
1566 "Options concerning tags in Org-mode."
1567 :tag "Org Tags"
1568 :group 'org)
1570 (defcustom org-tag-alist nil
1571 "List of tags allowed in Org-mode files.
1572 When this list is nil, Org-mode will base TAG input on what is already in the
1573 buffer.
1574 The value of this variable is an alist, the car may be (and should) be a
1575 character that is used to select that tag through the fast-tag-selection
1576 interface. See the manual for details."
1577 :group 'org-tags
1578 :type '(repeat
1579 (choice
1580 (cons (string :tag "Tag name")
1581 (character :tag "Access char"))
1582 (const :tag "Start radio group" (:startgroup))
1583 (const :tag "End radio group" (:endgroup)))))
1585 (defcustom org-use-fast-tag-selection 'auto
1586 "Non-nil means, use fast tag selection scheme.
1587 This is a special interface to select and deselect tags with single keys.
1588 When nil, fast selection is never used.
1589 When the symbol `auto', fast selection is used if and only if selection
1590 characters for tags have been configured, either through the variable
1591 `org-tag-alist' or through a #+TAGS line in the buffer.
1592 When t, fast selection is always used and selection keys are assigned
1593 automatically if necessary."
1594 :group 'org-tags
1595 :type '(choice
1596 (const :tag "Always" t)
1597 (const :tag "Never" nil)
1598 (const :tag "When selection characters are configured" 'auto)))
1600 (defcustom org-fast-tag-selection-single-key nil
1601 "Non-nil means, fast tag selection exits after first change.
1602 When nil, you have to press RET to exit it.
1603 During fast tag selection, you can toggle this flag with `C-c'.
1604 This variable can also have the value `expert'. In this case, the window
1605 displaying the tags menu is not even shown, until you press C-c again."
1606 :group 'org-tags
1607 :type '(choice
1608 (const :tag "No" nil)
1609 (const :tag "Yes" t)
1610 (const :tag "Expert" expert)))
1612 (defcustom org-tags-column 48
1613 "The column to which tags should be indented in a headline.
1614 If this number is positive, it specifies the column. If it is negative,
1615 it means that the tags should be flushright to that column. For example,
1616 -79 works well for a normal 80 character screen."
1617 :group 'org-tags
1618 :type 'integer)
1620 (defcustom org-auto-align-tags t
1621 "Non-nil means, realign tags after pro/demotion of TODO state change.
1622 These operations change the length of a headline and therefore shift
1623 the tags around. With this options turned on, after each such operation
1624 the tags are again aligned to `org-tags-column'."
1625 :group 'org-tags
1626 :type 'boolean)
1628 (defcustom org-use-tag-inheritance t
1629 "Non-nil means, tags in levels apply also for sublevels.
1630 When nil, only the tags directly given in a specific line apply there.
1631 If you turn off this option, you very likely want to turn on the
1632 companion option `org-tags-match-list-sublevels'."
1633 :group 'org-tags
1634 :type 'boolean)
1636 (defcustom org-tags-match-list-sublevels nil
1637 "Non-nil means list also sublevels of headlines matching tag search.
1638 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1639 the sublevels of a headline matching a tag search often also match
1640 the same search. Listing all of them can create very long lists.
1641 Setting this variable to nil causes subtrees of a match to be skipped.
1642 This option is off by default, because inheritance in on. If you turn
1643 inheritance off, you very likely want to turn this option on.
1645 As a special case, if the tag search is restricted to TODO items, the
1646 value of this variable is ignored and sublevels are always checked, to
1647 make sure all corresponding TODO items find their way into the list."
1648 :group 'org-tags
1649 :type 'boolean)
1651 (defvar org-tags-history nil
1652 "History of minibuffer reads for tags.")
1653 (defvar org-last-tags-completion-table nil
1654 "The last used completion table for tags.")
1656 (defgroup org-agenda nil
1657 "Options concerning agenda views in Org-mode."
1658 :tag "Org Agenda"
1659 :group 'org)
1661 (defvar org-category nil
1662 "Variable used by org files to set a category for agenda display.
1663 Such files should use a file variable to set it, for example
1665 # -*- mode: org; org-category: \"ELisp\"
1667 or contain a special line
1669 #+CATEGORY: ELisp
1671 If the file does not specify a category, then file's base name
1672 is used instead.")
1673 (make-variable-buffer-local 'org-category)
1675 (defcustom org-agenda-files nil
1676 "The files to be used for agenda display.
1677 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1678 \\[org-remove-file]. You can also use customize to edit the list.
1680 If the value of the variable is not a list but a single file name, then
1681 the list of agenda files is actually stored and maintained in that file, one
1682 agenda file per line."
1683 :group 'org-agenda
1684 :type '(choice
1685 (repeat :tag "List of files" file)
1686 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1689 (defcustom org-agenda-confirm-kill 1
1690 "When set, remote killing from the agenda buffer needs confirmation.
1691 When t, a confirmation is always needed. When a number N, confirmation is
1692 only needed when the text to be killed contains more than N non-white lines."
1693 :group 'org-agenda
1694 :type '(choice
1695 (const :tag "Never" nil)
1696 (const :tag "Always" t)
1697 (number :tag "When more than N lines")))
1699 (defcustom org-calendar-to-agenda-key [?c]
1700 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1701 The command `org-calendar-goto-agenda' will be bound to this key. The
1702 default is the character `c' because then `c' can be used to switch back and
1703 forth between agenda and calendar."
1704 :group 'org-agenda
1705 :type 'sexp)
1707 (defgroup org-agenda-custom-commands nil
1708 "Options concerning agenda views in Org-mode."
1709 :tag "Org Agenda Custom Commands"
1710 :group 'org-agenda)
1712 (defcustom org-agenda-custom-commands nil
1713 "Custom commands for the agenda.
1714 These commands will be offered on the splash screen displayed by the
1715 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1717 (key type match options)
1719 key The key (a single char as a string) to be associated with the command.
1720 type The command type, any of the following symbols:
1721 todo Entries with a specific TODO keyword, in all agenda files.
1722 tags Tags match in all agenda files.
1723 tags-todo Tags match in all agenda files, TODO entries only.
1724 todo-tree Sparse tree of specific TODO keyword in *current* file.
1725 tags-tree Sparse tree with all tags matches in *current* file.
1726 occur-tree Occur sparse tree for *current* file.
1727 match What to search for:
1728 - a single keyword for TODO keyword searches
1729 - a tags match expression for tags searches
1730 - a regular expression for occur searches
1731 options A list of option setttings, similar to that in a let form, so like
1732 this: ((opt1 val1) (opt2 val2) ...)
1734 You can also define a set of commands, to create a composite agenda buffer.
1735 In this case, an entry looks like this:
1737 (key desc (cmd1 cmd2 ...) general-options)
1739 where
1741 desc A description string to be displayed in the dispatcher menu.
1742 cmd An agenda command, similar to the above. However, tree commands
1743 are no allowed, but instead you can get agenda and global todo list.
1744 So valid commands for a set are:
1745 (agenda)
1746 (alltodo)
1747 (stuck)
1748 (todo \"match\" options)
1749 (tags \"match\" options )
1750 (tags-todo \"match\" options)
1752 Each command can carry a list of options, and another set of options can be
1753 given for the whole set of commands. Individual command options take
1754 precedence over the general options."
1755 :group 'org-agenda-custom-commands
1756 :type '(repeat
1757 (choice
1758 (list :tag "Single command"
1759 (string :tag "Key")
1760 (choice
1761 (const :tag "Tags search (all agenda files)" tags)
1762 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1763 (const :tag "TODO keyword search (all agenda files)" todo)
1764 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1765 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1766 (const :tag "Occur tree (current buffer)" occur-tree)
1767 (symbol :tag "Other, user-defined function"))
1768 (string :tag "Match")
1769 (repeat :tag "Local options"
1770 (list (variable :tag "Option") (sexp :tag "Value"))))
1771 (list :tag "Command series, all agenda files"
1772 (string :tag "Key")
1773 (string :tag "Description")
1774 (repeat
1775 (choice
1776 (const :tag "Agenda" (agenda))
1777 (const :tag "TODO list" (alltodo))
1778 (const :tag "Stuck projects" (stuck))
1779 (list :tag "Tags search"
1780 (const :format "" tags)
1781 (string :tag "Match")
1782 (repeat :tag "Local options"
1783 (list (variable :tag "Option")
1784 (sexp :tag "Value"))))
1786 (list :tag "Tags search, TODO entries only"
1787 (const :format "" tags-todo)
1788 (string :tag "Match")
1789 (repeat :tag "Local options"
1790 (list (variable :tag "Option")
1791 (sexp :tag "Value"))))
1793 (list :tag "TODO keyword search"
1794 (const :format "" todo)
1795 (string :tag "Match")
1796 (repeat :tag "Local options"
1797 (list (variable :tag "Option")
1798 (sexp :tag "Value"))))
1800 (list :tag "Other, user-defined function"
1801 (symbol :tag "function")
1802 (string :tag "Match")
1803 (repeat :tag "Local options"
1804 (list (variable :tag "Option")
1805 (sexp :tag "Value"))))))
1807 (repeat :tag "General options"
1808 (list (variable :tag "Option")
1809 (sexp :tag "Value")))))))
1811 (defcustom org-stuck-projects
1812 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil)
1813 "How to identify stuck projects.
1814 This is a list of three items:
1815 1. A tags/todo matcher string that is used to identify a project.
1816 The entire tree below a headline matched by this is considered a project.
1817 2. A list of TODO keywords itentifying non-stuck projects.
1818 If the project subtree contains any headline with one of these todo
1819 keywords, the project is consitered to be not stuck.
1820 3. A list of tags identifying non-stuck projects.
1821 If the project subtree contains any headline with one of these tags,
1822 the project is consitered to be not stuck.
1824 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1825 or `C-c a #' to produce the list."
1826 :group 'org-agenda-custom-commands
1827 :type '(list
1828 (string :tag "Tags/TODO match to identify a project")
1829 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1830 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))))
1833 (defgroup org-agenda-skip nil
1834 "Options concerning skipping parts of agenda files."
1835 :tag "Org Agenda Skip"
1836 :group 'org-agenda)
1838 (defcustom org-agenda-todo-list-sublevels t
1839 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1840 When nil, the sublevels of a TODO entry are not checked, resulting in
1841 potentially much shorter TODO lists."
1842 :group 'org-agenda-skip
1843 :group 'org-todo
1844 :type 'boolean)
1846 (defcustom org-agenda-todo-ignore-scheduled nil
1847 "Non-nil means, don't show scheduled entries in the global todo list.
1848 The idea behind this is that by scheduling it, you have already taken care
1849 of this item."
1850 :group 'org-agenda-skip
1851 :group 'org-todo
1852 :type 'boolean)
1854 (defcustom org-agenda-todo-ignore-deadlines nil
1855 "Non-nil means, don't show near deadline entries in the global todo list.
1856 Near means closer than `org-deadline-warning-days' days.
1857 The idea behind this is that such items will appear in the agenda anyway."
1858 :group 'org-agenda-skip
1859 :group 'org-todo
1860 :type 'boolean)
1862 (defcustom org-agenda-skip-scheduled-if-done nil
1863 "Non-nil means don't show scheduled items in agenda when they are done.
1864 This is relevant for the daily/weekly agenda, not for the TODO list."
1865 :group 'org-agenda-skip
1866 :type 'boolean)
1868 (defcustom org-timeline-show-empty-dates 3
1869 "Non-nil means, `org-timeline' also shows dates without an entry.
1870 When nil, only the days which actually have entries are shown.
1871 When t, all days between the first and the last date are shown.
1872 When an integer, show also empty dates, but if there is a gap of more than
1873 N days, just insert a special line indicating the size of the gap."
1874 :group 'org-agenda-skip
1875 :type '(choice
1876 (const :tag "None" nil)
1877 (const :tag "All" t)
1878 (number :tag "at most")))
1881 (defgroup org-agenda-startup nil
1882 "Options concerning initial settings in the Agenda in Org Mode."
1883 :tag "Org Agenda Startup"
1884 :group 'org-agenda)
1886 (defcustom org-finalize-agenda-hook nil
1887 "Hook run just before displaying an agenda buffer."
1888 :group 'org-agenda-startup
1889 :type 'hook)
1891 (defcustom org-agenda-mouse-1-follows-link nil
1892 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1893 A longer mouse click will still set point. Does not wortk on XEmacs.
1894 Needs to be set before org.el is loaded."
1895 :group 'org-agenda-startup
1896 :type 'boolean)
1898 (defcustom org-agenda-start-with-follow-mode nil
1899 "The initial value of follwo-mode in a newly created agenda window."
1900 :group 'org-agenda-startup
1901 :type 'boolean)
1903 (defgroup org-agenda-windows nil
1904 "Options concerning the windows used by the Agenda in Org Mode."
1905 :tag "Org Agenda Windows"
1906 :group 'org-agenda)
1908 (defcustom org-agenda-window-setup 'reorganize-frame
1909 "How the agenda buffer should be displayed.
1910 Possible values for this option are:
1912 current-window Show agenda in the current window, keeping all other windows.
1913 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1914 other-window Use `switch-to-buffer-other-window' to display agenda.
1915 reorganize-frame Show only two windows on the current frame, the current
1916 window and the agenda.
1917 See also the variable `org-agenda-restore-windows-after-quit'."
1918 :group 'org-agenda-windows
1919 :type '(choice
1920 (const current-window)
1921 (const other-frame)
1922 (const other-window)
1923 (const reorganize-frame)))
1925 (defcustom org-agenda-restore-windows-after-quit nil
1926 "Non-nil means, restore window configuration open exiting agenda.
1927 Before the window configuration is changed for displaying the agenda,
1928 the current status is recorded. When the agenda is exited with
1929 `q' or `x' and this option is set, the old state is restored. If
1930 `org-agenda-window-setup' is `other-frame', the value of this
1931 option will be ignored.."
1932 :group 'org-agenda-windows
1933 :type 'boolean)
1935 (defcustom org-indirect-buffer-display 'other-window
1936 "How should indirect tree buffers be displayed?
1937 This applies to indirect buffers created with the commands
1938 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1939 Valid values are:
1940 current-window Display in the current window
1941 other-window Just display in another window.
1942 dedicated-frame Create one new frame, and re-use it each time.
1943 new-frame Make a new frame each time."
1944 :group 'org-structure
1945 :group 'org-agenda-windows
1946 :type '(choice
1947 (const :tag "In current window" current-window)
1948 (const :tag "In current frame, other window" other-window)
1949 (const :tag "Each time a new frame" new-frame)
1950 (const :tag "One dedicated frame" dedicated-frame)))
1952 (defgroup org-agenda-daily/weekly nil
1953 "Options concerning the daily/weekly agenda."
1954 :tag "Org Agenda Daily/Weekly"
1955 :group 'org-agenda)
1957 (defcustom org-agenda-ndays 7
1958 "Number of days to include in overview display.
1959 Should be 1 or 7."
1960 :group 'org-agenda-daily/weekly
1961 :type 'number)
1963 (defcustom org-agenda-start-on-weekday 1
1964 "Non-nil means, start the overview always on the specified weekday.
1965 0 denotes Sunday, 1 denotes Monday etc.
1966 When nil, always start on the current day."
1967 :group 'org-agenda-daily/weekly
1968 :type '(choice (const :tag "Today" nil)
1969 (number :tag "Weekday No.")))
1971 (defcustom org-agenda-show-all-dates t
1972 "Non-nil means, `org-agenda' shows every day in the selected range.
1973 When nil, only the days which actually have entries are shown."
1974 :group 'org-agenda-daily/weekly
1975 :type 'boolean)
1977 (defcustom org-agenda-date-format "%A %d %B %Y"
1978 "Format string for displaying dates in the agenda.
1979 Used by the daily/weekly agenda and by the timeline. This should be
1980 a format string understood by `format-time-string'.
1981 FIXME: Not used currently, because of timezone problem."
1982 :group 'org-agenda-daily/weekly
1983 :type 'string)
1985 (defcustom org-agenda-include-diary nil
1986 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1987 :group 'org-agenda-daily/weekly
1988 :type 'boolean)
1990 (defcustom org-agenda-include-all-todo nil
1991 "Set means weekly/daily agenda will always contain all TODO entries.
1992 The TODO entries will be listed at the top of the agenda, before
1993 the entries for specific days."
1994 :group 'org-agenda-daily/weekly
1995 :type 'boolean)
1997 (defgroup org-agenda-time-grid nil
1998 "Options concerning the time grid in the Org-mode Agenda."
1999 :tag "Org Agenda Time Grid"
2000 :group 'org-agenda)
2002 (defcustom org-agenda-use-time-grid t
2003 "Non-nil means, show a time grid in the agenda schedule.
2004 A time grid is a set of lines for specific times (like every two hours between
2005 8:00 and 20:00). The items scheduled for a day at specific times are
2006 sorted in between these lines.
2007 For details about when the grid will be shown, and what it will look like, see
2008 the variable `org-agenda-time-grid'."
2009 :group 'org-agenda-time-grid
2010 :type 'boolean)
2012 (defcustom org-agenda-time-grid
2013 '((daily today require-timed)
2014 "----------------"
2015 (800 1000 1200 1400 1600 1800 2000))
2017 "The settings for time grid for agenda display.
2018 This is a list of three items. The first item is again a list. It contains
2019 symbols specifying conditions when the grid should be displayed:
2021 daily if the agenda shows a single day
2022 weekly if the agenda shows an entire week
2023 today show grid on current date, independent of daily/weekly display
2024 require-timed show grid only if at least one item has a time specification
2026 The second item is a string which will be places behing the grid time.
2028 The third item is a list of integers, indicating the times that should have
2029 a grid line."
2030 :group 'org-agenda-time-grid
2031 :type
2032 '(list
2033 (set :greedy t :tag "Grid Display Options"
2034 (const :tag "Show grid in single day agenda display" daily)
2035 (const :tag "Show grid in weekly agenda display" weekly)
2036 (const :tag "Always show grid for today" today)
2037 (const :tag "Show grid only if any timed entries are present"
2038 require-timed)
2039 (const :tag "Skip grid times already present in an entry"
2040 remove-match))
2041 (string :tag "Grid String")
2042 (repeat :tag "Grid Times" (integer :tag "Time"))))
2044 (defgroup org-agenda-sorting nil
2045 "Options concerning sorting in the Org-mode Agenda."
2046 :tag "Org Agenda Sorting"
2047 :group 'org-agenda)
2049 (let ((sorting-choice
2050 '(choice
2051 (const time-up) (const time-down)
2052 (const category-keep) (const category-up) (const category-down)
2053 (const tag-down) (const tag-up)
2054 (const priority-up) (const priority-down))))
2056 (defcustom org-agenda-sorting-strategy
2057 '((agenda time-up category-keep priority-down)
2058 (todo category-keep priority-down)
2059 (tags category-keep priority-down))
2060 "Sorting structure for the agenda items of a single day.
2061 This is a list of symbols which will be used in sequence to determine
2062 if an entry should be listed before another entry. The following
2063 symbols are recognized:
2065 time-up Put entries with time-of-day indications first, early first
2066 time-down Put entries with time-of-day indications first, late first
2067 category-keep Keep the default order of categories, corresponding to the
2068 sequence in `org-agenda-files'.
2069 category-up Sort alphabetically by category, A-Z.
2070 category-down Sort alphabetically by category, Z-A.
2071 tag-up Sort alphabetically by last tag, A-Z.
2072 tag-down Sort alphabetically by last tag, Z-A.
2073 priority-up Sort numerically by priority, high priority last.
2074 priority-down Sort numerically by priority, high priority first.
2076 The different possibilities will be tried in sequence, and testing stops
2077 if one comparison returns a \"not-equal\". For example, the default
2078 '(time-up category-keep priority-down)
2079 means: Pull out all entries having a specified time of day and sort them,
2080 in order to make a time schedule for the current day the first thing in the
2081 agenda listing for the day. Of the entries without a time indication, keep
2082 the grouped in categories, don't sort the categories, but keep them in
2083 the sequence given in `org-agenda-files'. Within each category sort by
2084 priority.
2086 Leaving out `category-keep' would mean that items will be sorted across
2087 categories by priority."
2088 :group 'org-agenda-sorting
2089 :type `(choice
2090 (repeat :tag "General" ,sorting-choice)
2091 (list :tag "Individually"
2092 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2093 (repeat ,sorting-choice))
2094 (cons (const :tag "Strategy for TODO lists" todo)
2095 (repeat ,sorting-choice))
2096 (cons (const :tag "Strategy for Tags matches" tags)
2097 (repeat ,sorting-choice))))))
2099 (defcustom org-sort-agenda-notime-is-late t
2100 "Non-nil means, items without time are considered late.
2101 This is only relevant for sorting. When t, items which have no explicit
2102 time like 15:30 will be considered as 99:01, i.e. later than any items which
2103 do have a time. When nil, the default time is before 0:00. You can use this
2104 option to decide if the schedule for today should come before or after timeless
2105 agenda entries."
2106 :group 'org-agenda-sorting
2107 :type 'boolean)
2109 (defgroup org-agenda-prefix nil
2110 "Options concerning the entry prefix in the Org-mode agenda display."
2111 :tag "Org Agenda Prefix"
2112 :group 'org-agenda)
2114 (defcustom org-agenda-prefix-format
2115 '((agenda . " %-12:c%?-12t% s")
2116 (timeline . " % s")
2117 (todo . " %-12:c")
2118 (tags . " %-12:c"))
2119 "Format specifications for the prefix of items in the agenda views.
2120 An alist with four entries, for the different agenda types. The keys to the
2121 sublists are `agenda', `timeline', `todo', and `tags'. The values
2122 are format strings.
2123 This format works similar to a printf format, with the following meaning:
2125 %c the category of the item, \"Diary\" for entries from the diary, or
2126 as given by the CATEGORY keyword or derived from the file name.
2127 %T the *last* tag of the item. Last because inherited tags come
2128 first in the list.
2129 %t the time-of-day specification if one applies to the entry, in the
2130 format HH:MM
2131 %s Scheduling/Deadline information, a short string
2133 All specifiers work basically like the standard `%s' of printf, but may
2134 contain two additional characters: A question mark just after the `%' and
2135 a whitespace/punctuation character just before the final letter.
2137 If the first character after `%' is a question mark, the entire field
2138 will only be included if the corresponding value applies to the
2139 current entry. This is useful for fields which should have fixed
2140 width when present, but zero width when absent. For example,
2141 \"%?-12t\" will result in a 12 character time field if a time of the
2142 day is specified, but will completely disappear in entries which do
2143 not contain a time.
2145 If there is punctuation or whitespace character just before the final
2146 format letter, this character will be appended to the field value if
2147 the value is not empty. For example, the format \"%-12:c\" leads to
2148 \"Diary: \" if the category is \"Diary\". If the category were be
2149 empty, no additional colon would be interted.
2151 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2152 - Indent the line with two space characters
2153 - Give the category in a 12 chars wide field, padded with whitespace on
2154 the right (because of `-'). Append a colon if there is a category
2155 (because of `:').
2156 - If there is a time-of-day, put it into a 12 chars wide field. If no
2157 time, don't put in an empty field, just skip it (because of '?').
2158 - Finally, put the scheduling information and append a whitespace.
2160 As another example, if you don't want the time-of-day of entries in
2161 the prefix, you could use:
2163 (setq org-agenda-prefix-format \" %-11:c% s\")
2165 See also the variables `org-agenda-remove-times-when-in-prefix' and
2166 `org-agenda-remove-tags-when-in-prefix'."
2167 :type '(choice
2168 (string :tag "General format")
2169 (list :greedy t :tag "View dependent"
2170 (cons (const agenda) (string :tag "Format"))
2171 (cons (const timeline) (string :tag "Format"))
2172 (cons (const todo) (string :tag "Format"))
2173 (cons (const tags) (string :tag "Format"))))
2174 :group 'org-agenda-prefix)
2176 (defvar org-prefix-format-compiled nil
2177 "The compiled version of the most recently used prefix format.
2178 See the variable `org-agenda-prefix-format'.")
2180 (defcustom org-agenda-remove-times-when-in-prefix t
2181 "Non-nil means, remove duplicate time specifications in agenda items.
2182 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2183 time-of-day specification in a headline or diary entry is extracted and
2184 placed into the prefix. If this option is non-nil, the original specification
2185 \(a timestamp or -range, or just a plain time(range) specification like
2186 11:30-4pm) will be removed for agenda display. This makes the agenda less
2187 cluttered.
2188 The option can be t or nil. It may also be the symbol `beg', indicating
2189 that the time should only be removed what it is located at the beginning of
2190 the headline/diary entry."
2191 :group 'org-agenda-prefix
2192 :type '(choice
2193 (const :tag "Always" t)
2194 (const :tag "Never" nil)
2195 (const :tag "When at beginning of entry" beg)))
2197 (defcustom org-agenda-remove-tags-when-in-prefix nil
2198 "Non-nil means, remove the tags from the headline copy in the agenda.
2199 When this is the symbol `prefix', only remove tags when
2200 `org-agenda-prefix-format' contains a `%T' specifier."
2201 :group 'org-agenda-prefix
2202 :type '(choice
2203 (const :tag "Always" t)
2204 (const :tag "Never" nil)
2205 (const :tag "When prefix format contains %T" prefix)))
2207 (defcustom org-agenda-align-tags-to-column 65
2208 "Shift tags in agenda items to this column."
2209 :group 'org-agenda-prefix
2210 :type 'integer)
2212 (defgroup org-latex nil
2213 "Options for embedding LaTeX code into Org-mode"
2214 :tag "Org LaTeX"
2215 :group 'org)
2217 (defcustom org-format-latex-options
2218 '(:foreground "Black" :background "Transparent" :scale 1.0
2219 :matchers ("begin" "$" "$$" "\\(" "\\["))
2220 "Options for creating images from LaTeX fragments.
2221 This is a property list with the following properties:
2222 :foreground the foreground color, for example \"Black\".
2223 :background the background color, or \"Transparent\".
2224 :scale a scaling factor for the size of the images
2225 :matchers a list indicating which matchers should be used to
2226 find LaTeX fragments. Valid members of this list are:
2227 \"begin\" find environments
2228 \"$\" find math expressions surrounded by $...$
2229 \"$$\" find math expressions surrounded by $$....$$
2230 \"\\(\" find math expressions surrounded by \\(...\\)
2231 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2232 :group 'org-latex
2233 :type 'plist)
2235 (defgroup org-export nil
2236 "Options for exporting org-listings."
2237 :tag "Org Export"
2238 :group 'org)
2240 (defgroup org-export-general nil
2241 "General options for exporting Org-mode files."
2242 :tag "Org Export General"
2243 :group 'org-export)
2245 (defcustom org-export-publishing-directory "."
2246 "Path to the location where exported files should be located.
2247 This path may be relative to the directory where the Org-mode file lives.
2248 The default is to put them into the same directory as the Org-mode file.
2249 The variable may also be an alist with export types `:html', `:ascii',
2250 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2251 is relative, it is interpreted relative to the directory where the exported
2252 Org-mode files lives."
2253 :group 'org-export-general
2254 :type '(choice
2255 (directory)
2256 (repeat
2257 (cons
2258 (choice :tag "Type"
2259 (const :html) (const :ascii) (const :ical) (const :xoxo))
2260 (directory)))))
2262 (defcustom org-export-language-setup
2263 '(("en" "Author" "Date" "Table of Contents")
2264 ("cs" "Autor" "Datum" "Obsah")
2265 ("da" "Ophavsmand" "Dato" "Indhold")
2266 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2267 ("es" "Autor" "Fecha" "\xccndice")
2268 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2269 ("it" "Autore" "Data" "Indice")
2270 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2271 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2272 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2273 "Terms used in export text, translated to different languages.
2274 Use the variable `org-export-default-language' to set the language,
2275 or use the +OPTION lines for a per-file setting."
2276 :group 'org-export-general
2277 :type '(repeat
2278 (list
2279 (string :tag "HTML language tag")
2280 (string :tag "Author")
2281 (string :tag "Date")
2282 (string :tag "Table of Contents"))))
2284 (defcustom org-export-default-language "en"
2285 "The default language of HTML export, as a string.
2286 This should have an association in `org-export-language-setup'."
2287 :group 'org-export-general
2288 :type 'string)
2290 (defcustom org-export-skip-text-before-1st-heading t
2291 "Non-nil means, skip all text before the first headline when exporting.
2292 When nil, that text is exported as well."
2293 :group 'org-export-general
2294 :type 'boolean)
2296 (defcustom org-export-headline-levels 3
2297 "The last level which is still exported as a headline.
2298 Inferior levels will produce itemize lists when exported.
2299 Note that a numeric prefix argument to an exporter function overrides
2300 this setting.
2302 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2303 :group 'org-export-general
2304 :type 'number)
2306 (defcustom org-export-with-section-numbers t
2307 "Non-nil means, add section numbers to headlines when exporting.
2309 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2310 :group 'org-export-general
2311 :type 'boolean)
2313 (defcustom org-export-with-toc t
2314 "Non-nil means, create a table of contents in exported files.
2315 The TOC contains headlines with levels up to`org-export-headline-levels'.
2316 When an integer, include levels up to N in the toc, this may then be
2317 different from `org-export-headline-levels', but it will not be allowed
2318 to be larger than the number of headline levels.
2319 When nil, no table of contents is made.
2321 Headlines which contain any TODO items will be marked with \"(*)\" in
2322 ASCII export, and with red color in HTML output, if the option
2323 `org-export-mark-todo-in-toc' is set.
2325 In HTML output, the TOC will be clickable.
2327 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2328 or \"toc:3\"."
2329 :group 'org-export-general
2330 :type '(choice
2331 (const :tag "No Table of Contents" nil)
2332 (const :tag "Full Table of Contents" t)
2333 (integer :tag "TOC to level")))
2335 (defcustom org-export-mark-todo-in-toc nil
2336 "Non-nil means, mark TOC lines that contain any open TODO items."
2337 :group 'org-export-general
2338 :type 'boolean)
2340 (defcustom org-export-preserve-breaks nil
2341 "Non-nil means, preserve all line breaks when exporting.
2342 Normally, in HTML output paragraphs will be reformatted. In ASCII
2343 export, line breaks will always be preserved, regardless of this variable.
2345 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2346 :group 'org-export-general
2347 :type 'boolean)
2349 (defcustom org-export-with-archived-trees 'headline
2350 "Whether subtrees with the ARCHIVE tag should be exported.
2351 This can have three different values
2352 nil Do not export, pretend this tree is not present
2353 t Do export the entire tree
2354 headline Only export the headline, but skip the tree below it."
2355 :group 'org-export-general
2356 :group 'org-archive
2357 :type '(choice
2358 (const :tag "not at all" nil)
2359 (const :tag "headline only" 'headline)
2360 (const :tag "entirely" t)))
2362 (defcustom org-export-with-timestamps t
2363 "If nil, do not export time stamps and associated keywords."
2364 :group 'org-export-general
2365 :type 'boolean)
2367 (defcustom org-export-remove-timestamps-from-toc t
2368 "If nil, remove timestamps from the table of contents entries."
2369 :group 'org-export-general
2370 :type 'boolean)
2372 (defcustom org-export-with-tags 'not-in-toc
2373 "If nil, do not export tags, just remove them from headlines.
2374 If this is the symbol `not-in-toc', tags will be removed from table of
2375 contents entries, but still be shown in the headlines of the document."
2376 :group 'org-export-general
2377 :type '(choice
2378 (const :tag "Off" nil)
2379 (const :tag "Not in TOC" not-in-toc)
2380 (const :tag "On" t)))
2382 (defgroup org-export-translation nil
2383 "Options for translating special ascii sequences for the export backends."
2384 :tag "Org Export Translation"
2385 :group 'org-export)
2387 (defcustom org-export-with-emphasize t
2388 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2389 If the export target supports emphasizing text, the word will be
2390 typeset in bold, italic, or underlined, respectively. Works only for
2391 single words, but you can say: I *really* *mean* *this*.
2392 Not all export backends support this.
2394 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2395 :group 'org-export-translation
2396 :type 'boolean)
2398 (defcustom org-export-with-sub-superscripts t
2399 "Non-nil means, interpret \"_\" and \"^\" for export.
2400 When this option is turned on, you can use TeX-like syntax for sub- and
2401 superscripts. Several characters after \"_\" or \"^\" will be
2402 considered as a single item - so grouping with {} is normally not
2403 needed. For example, the following things will be parsed as single
2404 sub- or superscripts.
2406 10^24 or 10^tau several digits will be considered 1 item.
2407 10^-12 or 10^-tau a leading sign with digits or a word
2408 x^2-y^3 will be read as x^2 - y^3, because items are
2409 terminated by almost any nonword/nondigit char.
2410 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2412 Still, ambiguity is possible - so when in doubt use {} to enclose the
2413 sub/superscript. If you set this variable to the symbol `{}',
2414 the braces are *required* in order to trigger interpretations as
2415 sub/superscript. This can be helpful in documents that need \"_\"
2416 frequently in plain text.
2418 Not all export backends support this, but HTML does.
2420 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2421 :group 'org-export-translation
2422 :type '(choice
2423 (const :tag "Always interpret" t)
2424 (const :tag "Only with braces" {})
2425 (const :tag "Never interpret" nil)))
2427 (defcustom org-export-with-TeX-macros t
2428 "Non-nil means, interpret simple TeX-like macros when exporting.
2429 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2430 No only real TeX macros will work here, but the standard HTML entities
2431 for math can be used as macro names as well. For a list of supported
2432 names in HTML export, see the constant `org-html-entities'.
2433 Not all export backends support this.
2435 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2436 :group 'org-export-translation
2437 :group 'org-latex
2438 :type 'boolean)
2440 (defcustom org-export-with-LaTeX-fragments nil
2441 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2442 When set, the exporter will find LaTeX environments if the \\begin line is
2443 the first non-white thing on a line. It will also find the math delimiters
2444 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2445 display math.
2447 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2448 :group 'org-export-translation
2449 :group 'org-latex
2450 :type 'boolean)
2452 (defcustom org-export-with-fixed-width t
2453 "Non-nil means, lines starting with \":\" will be in fixed width font.
2454 This can be used to have pre-formatted text, fragments of code etc. For
2455 example:
2456 : ;; Some Lisp examples
2457 : (while (defc cnt)
2458 : (ding))
2459 will be looking just like this in also HTML. See also the QUOTE keyword.
2460 Not all export backends support this.
2462 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2463 :group 'org-export-translation
2464 :type 'boolean)
2466 (defcustom org-match-sexp-depth 3
2467 "Number of stacked braces for sub/superscript matching.
2468 This has to be set before loading org.el to be effective."
2469 :group 'org-export-translation
2470 :type 'integer)
2472 (defgroup org-export-tables nil
2473 "Options for exporting tables in Org-mode."
2474 :tag "Org Export Tables"
2475 :group 'org-export)
2477 (defcustom org-export-with-tables t
2478 "If non-nil, lines starting with \"|\" define a table.
2479 For example:
2481 | Name | Address | Birthday |
2482 |-------------+----------+-----------|
2483 | Arthur Dent | England | 29.2.2100 |
2485 Not all export backends support this.
2487 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2488 :group 'org-export-tables
2489 :type 'boolean)
2491 (defcustom org-export-highlight-first-table-line t
2492 "Non-nil means, highlight the first table line.
2493 In HTML export, this means use <th> instead of <td>.
2494 In tables created with table.el, this applies to the first table line.
2495 In Org-mode tables, all lines before the first horizontal separator
2496 line will be formatted with <th> tags."
2497 :group 'org-export-tables
2498 :type 'boolean)
2500 (defcustom org-export-table-remove-special-lines t
2501 "Remove special lines and marking characters in calculating tables.
2502 This removes the special marking character column from tables that are set
2503 up for spreadsheet calculations. It also removes the entire lines
2504 marked with `!', `_', or `^'. The lines with `$' are kept, because
2505 the values of constants may be useful to have."
2506 :group 'org-export-tables
2507 :type 'boolean)
2509 (defcustom org-export-prefer-native-exporter-for-tables nil
2510 "Non-nil means, always export tables created with table.el natively.
2511 Natively means, use the HTML code generator in table.el.
2512 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2513 the table does not use row- or column-spanning). This has the
2514 advantage, that the automatic HTML conversions for math symbols and
2515 sub/superscripts can be applied. Org-mode's HTML generator is also
2516 much faster."
2517 :group 'org-export-tables
2518 :type 'boolean)
2520 (defgroup org-export-ascii nil
2521 "Options specific for ASCII export of Org-mode files."
2522 :tag "Org Export ASCII"
2523 :group 'org-export)
2525 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2526 "Characters for underlining headings in ASCII export.
2527 In the given sequence, these characters will be used for level 1, 2, ..."
2528 :group 'org-export-ascii
2529 :type '(repeat character))
2531 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2532 "Bullet characters for headlines converted to lists in ASCII export.
2533 The first character is is used for the first lest level generated in this
2534 way, and so on. If there are more levels than characters given here,
2535 the list will be repeated.
2536 Note that plain lists will keep the same bullets as the have in the
2537 Org-mode file."
2538 :group 'org-export-ascii
2539 :type '(repeat character))
2541 (defgroup org-export-xml nil
2542 "Options specific for XML export of Org-mode files."
2543 :tag "Org Export XML"
2544 :group 'org-export)
2546 (defgroup org-export-html nil
2547 "Options specific for HTML export of Org-mode files."
2548 :tag "Org Export HTML"
2549 :group 'org-export)
2551 (defcustom org-export-html-style
2552 "<style type=\"text/css\">
2553 html {
2554 font-family: Times, serif;
2555 font-size: 12pt;
2557 .title { text-align: center; }
2558 .todo { color: red; }
2559 .done { color: green; }
2560 .timestamp { color: grey }
2561 .timestamp-kwd { color: CadetBlue }
2562 .tag { background-color:lightblue; font-weight:normal }
2563 .target { background-color: lavender; }
2564 pre {
2565 border: 1pt solid #AEBDCC;
2566 background-color: #F3F5F7;
2567 padding: 5pt;
2568 font-family: courier, monospace;
2570 table { border-collapse: collapse; }
2571 td, th {
2572 vertical-align: top;
2573 <!--border: 1pt solid #ADB9CC;-->
2575 </style>"
2576 "The default style specification for exported HTML files.
2577 Since there are different ways of setting style information, this variable
2578 needs to contain the full HTML structure to provide a style, including the
2579 surrounding HTML tags. The style specifications should include definitions
2580 for new classes todo, done, title, and deadline. For example, legal values
2581 would be:
2583 <style type=\"text/css\">
2584 p { font-weight: normal; color: gray; }
2585 h1 { color: black; }
2586 .title { text-align: center; }
2587 .todo, .deadline { color: red; }
2588 .done { color: green; }
2589 </style>
2591 or, if you want to keep the style in a file,
2593 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2595 As the value of this option simply gets inserted into the HTML <head> header,
2596 you can \"misuse\" it to add arbitrary text to the header."
2597 :group 'org-export-html
2598 :type 'string)
2600 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2601 "Format for typesetting the document title in HTML export."
2602 :group 'org-export-html
2603 :type 'string)
2605 (defcustom org-export-html-toplevel-hlevel 2
2606 "The <H> level for level 1 headings in HTML export."
2607 :group 'org-export-html
2608 :type 'string)
2610 (defcustom org-export-html-link-org-files-as-html t
2611 "Non-nil means, make file links to `file.org' point to `file.html'.
2612 When org-mode is exporting an org-mode file to HTML, links to
2613 non-html files are directly put into a href tag in HTML.
2614 However, links to other Org-mode files (recognized by the
2615 extension `.org.) should become links to the corresponding html
2616 file, assuming that the linked org-mode file will also be
2617 converted to HTML.
2618 When nil, the links still point to the plain `.org' file."
2619 :group 'org-export-html
2620 :type 'boolean)
2622 (defcustom org-export-html-inline-images 'maybe
2623 "Non-nil means, inline images into exported HTML pages.
2624 This is done using an <img> tag. When nil, an anchor with href is used to
2625 link to the image. If this option is `maybe', then images in links with
2626 an empty description will be inlined, while images with a description will
2627 be linked only."
2628 :group 'org-export-html
2629 :type '(choice (const :tag "Never" nil)
2630 (const :tag "Always" t)
2631 (const :tag "When there is no description" maybe)))
2633 ;; FIXME: rename
2634 (defcustom org-export-html-expand t
2635 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2636 When nil, these tags will be exported as plain text and therefore
2637 not be interpreted by a browser.
2639 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2640 :group 'org-export-html
2641 :type 'boolean)
2643 (defcustom org-export-html-table-tag
2644 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
2645 "The HTML tag used to start a table.
2646 This must be a <table> tag, but you may change the options like
2647 borders and spacing."
2648 :group 'org-export-html
2649 :type 'string)
2651 (defcustom org-export-html-with-timestamp nil
2652 "If non-nil, write `org-export-html-html-helper-timestamp'
2653 into the exported HTML text. Otherwise, the buffer will just be saved
2654 to a file."
2655 :group 'org-export-html
2656 :type 'boolean)
2658 (defcustom org-export-html-html-helper-timestamp
2659 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2660 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2661 :group 'org-export-html
2662 :type 'string)
2664 (defgroup org-export-icalendar nil
2665 "Options specific for iCalendar export of Org-mode files."
2666 :tag "Org Export iCalendar"
2667 :group 'org-export)
2669 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2670 "The file name for the iCalendar file covering all agenda files.
2671 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2672 The file name should be absolute."
2673 :group 'org-export-icalendar
2674 :type 'file)
2676 (defcustom org-icalendar-include-todo nil
2677 "Non-nil means, export to iCalendar files should also cover TODO items."
2678 :group 'org-export-icalendar
2679 :type '(choice
2680 (const :tag "None" nil)
2681 (const :tag "Unfinished" t)
2682 (const :tag "All" all)))
2684 (defcustom org-icalendar-combined-name "OrgMode"
2685 "Calendar name for the combined iCalendar representing all agenda files."
2686 :group 'org-export-icalendar
2687 :type 'string)
2689 (defgroup org-font-lock nil
2690 "Font-lock settings for highlighting in Org-mode."
2691 :tag "Org Font Lock"
2692 :group 'org)
2694 (defcustom org-level-color-stars-only nil
2695 "Non-nil means fontify only the stars in each headline.
2696 When nil, the entire headline is fontified.
2697 Changing it requires restart of `font-lock-mode' to become effective
2698 also in regions already fontified."
2699 :group 'org-font-lock
2700 :type 'boolean)
2702 (defcustom org-hide-leading-stars nil
2703 "Non-nil means, hide the first N-1 stars in a headline.
2704 This works by using the face `org-hide' for these stars. This
2705 face is white for a light background, and black for a dark
2706 background. You may have to customize the face `org-hide' to
2707 make this work.
2708 Changing it requires restart of `font-lock-mode' to become effective
2709 also in regions already fontified.
2710 You may also set this on a per-file basis by adding one of the following
2711 lines to the buffer:
2713 #+STARTUP: hidestars
2714 #+STARTUP: showstars"
2715 :group 'org-font-lock
2716 :type 'boolean)
2718 (defcustom org-fontify-done-headline nil
2719 "Non-nil means, change the face of a headline if it is marked DONE.
2720 Normally, only the TODO/DONE keyword indicates the state of a headline.
2721 When this is non-nil, the headline after the keyword is set to the
2722 `org-headline-done' as an additional indication."
2723 :group 'org-font-lock
2724 :type 'boolean)
2726 (defcustom org-fontify-emphasized-text t
2727 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2728 Changing this variable requires a restart of Emacs to take effect."
2729 :group 'org-font-lock
2730 :type 'boolean)
2732 (defvar org-emph-re nil
2733 "Regular expression for matching emphasis.")
2734 (defvar org-emphasis-regexp-components) ; defined just below
2735 (defvar org-emphasis-alist) ; defined just below
2736 (defun org-set-emph-re (var val)
2737 "Set variable and compute the emphasis regular expression."
2738 (set var val)
2739 (when (and (boundp 'org-emphasis-alist)
2740 (boundp 'org-emphasis-regexp-components)
2741 org-emphasis-alist org-emphasis-regexp-components)
2742 (let* ((e org-emphasis-regexp-components)
2743 (pre (car e))
2744 (post (nth 1 e))
2745 (border (nth 2 e))
2746 (body (nth 3 e))
2747 (nl (nth 4 e))
2748 (stacked (nth 5 e))
2749 (body1 (concat body "*?"))
2750 (markers (mapconcat 'car org-emphasis-alist "")))
2751 ;; make sure special characters appear at the right position in the class
2752 (if (string-match "\\^" markers)
2753 (setq markers (concat (replace-match "" t t markers) "^")))
2754 (if (string-match "-" markers)
2755 (setq markers (concat (replace-match "" t t markers) "-")))
2756 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2757 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2758 (if (> nl 0)
2759 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2760 (int-to-string nl) "\\}")))
2761 ;; Make the regexp
2762 (setq org-emph-re
2763 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2764 "\\("
2765 "\\([" markers "]\\)"
2766 "\\("
2767 "[^" border markers "]"
2768 body1
2769 "[^" border markers "]"
2770 "\\)"
2771 "\\3\\)"
2772 "\\([" post (if stacked markers) "]\\|$\\)")))))
2774 (defcustom org-emphasis-regexp-components
2775 '(" \t('\"" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2776 "Components used to build the reqular expression for emphasis.
2777 This is a list with 6 entries. Terminology: In an emphasis string
2778 like \" *strong word* \", we call the initial space PREMATCH, the final
2779 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2780 and \"trong wor\" is the body. The different components in this variable
2781 specify what is allowed/forbidden in each part:
2783 pre Chars allowed as prematch. Beginning of line will be allowed too.
2784 post Chars allowed as postmatch. End of line will be allowed too.
2785 border The chars *forbidden* as border characters. In addition to the
2786 characters given here, all marker characters are forbidden too.
2787 body-regexp A regexp like \".\" to match a body character. Don't use
2788 non-shy groups here, and don't allow newline here.
2789 newline The maximum number of newlines allowed in an emphasis exp.
2790 stacked Non-nil means, allow stacked styles. This works only in HTML
2791 export. When this is set, all marker characters (as given in
2792 `org-emphasis-alist') will be allowed as pre/post, aiding
2793 inside-out matching.
2794 Use customize to modify this, or restart Emacs after changing it."
2795 :group 'org-font-lock
2796 :set 'org-set-emph-re
2797 :type '(list
2798 (sexp :tag "Allowed chars in pre ")
2799 (sexp :tag "Allowed chars in post ")
2800 (sexp :tag "Forbidden chars in border ")
2801 (sexp :tag "Regexp for body ")
2802 (integer :tag "number of newlines allowed")
2803 (boolean :tag "Stacking allowed ")))
2805 (defcustom org-emphasis-alist
2806 '(("*" bold "<b>" "</b>")
2807 ("/" italic "<i>" "</i>")
2808 ("_" underline "<u>" "</u>")
2809 ("=" shadow "<code>" "</code>")
2810 ("+" (:strike-through t) "<del>" "</del>")
2812 "Special syntax for emphasized text.
2813 Text starting and ending with a special character will be emphasized, for
2814 example *bold*, _underlined_ and /italic/. This variable sets the marker
2815 characters, the face to bbe used by font-lock for highlighting in Org-mode
2816 Emacs buffers, and the HTML tags to be used for this.
2817 Use customize to modify this, or restart Emacs after changing it."
2818 :group 'org-font-lock
2819 :set 'org-set-emph-re
2820 :type '(repeat
2821 (list
2822 (string :tag "Marker character")
2823 (choice
2824 (face :tag "Font-lock-face")
2825 (plist :tag "Face property list"))
2826 (string :tag "HTML start tag")
2827 (string :tag "HTML end tag"))))
2829 ;;; The faces
2831 (defgroup org-faces nil
2832 "Faces in Org-mode."
2833 :tag "Org Faces"
2834 :group 'org-font-lock)
2836 (defun org-compatible-face (specs)
2837 "Make a compatible face specification.
2838 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2839 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2840 to the top of the list. The `min-colors' attribute will be removed from
2841 any other entries, and any resulting duplicates will be removed entirely."
2842 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2843 (let (r e a)
2844 (while (setq e (pop specs))
2845 (cond
2846 ((memq (car e) '(t default)) (push e r))
2847 ((setq a (member '(min-colors 8) (car e)))
2848 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2849 (cdr e)))))
2850 ((setq a (assq 'min-colors (car e)))
2851 (setq e (cons (delq a (car e)) (cdr e)))
2852 (or (assoc (car e) r) (push e r)))
2853 (t (or (assoc (car e) r) (push e r)))))
2854 (nreverse r))
2855 specs))
2857 (defface org-hide
2858 '((((background light)) (:foreground "white"))
2859 (((background dark)) (:foreground "black")))
2860 "Face used to hide leading stars in headlines.
2861 The forground color of this face should be equal to the background
2862 color of the frame."
2863 :group 'org-faces)
2865 (defface org-level-1 ;; font-lock-function-name-face
2866 (org-compatible-face
2867 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2868 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2869 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2870 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2871 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2872 (t (:bold t))))
2873 "Face used for level 1 headlines."
2874 :group 'org-faces)
2876 (defface org-level-2 ;; font-lock-variable-name-face
2877 (org-compatible-face
2878 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2879 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2880 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2881 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2882 (t (:bold t))))
2883 "Face used for level 2 headlines."
2884 :group 'org-faces)
2886 (defface org-level-3 ;; font-lock-keyword-face
2887 (org-compatible-face
2888 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2889 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2890 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2891 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2892 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2893 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2894 (t (:bold t))))
2895 "Face used for level 3 headlines."
2896 :group 'org-faces)
2898 (defface org-level-4 ;; font-lock-comment-face
2899 (org-compatible-face
2900 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2901 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2902 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2903 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2904 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2905 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2906 (t (:bold t))))
2907 "Face used for level 4 headlines."
2908 :group 'org-faces)
2910 (defface org-level-5 ;; font-lock-type-face
2911 (org-compatible-face
2912 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2913 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2914 (((class color) (min-colors 8)) (:foreground "green"))))
2915 "Face used for level 5 headlines."
2916 :group 'org-faces)
2918 (defface org-level-6 ;; font-lock-constant-face
2919 (org-compatible-face
2920 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2921 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2922 (((class color) (min-colors 8)) (:foreground "magenta"))))
2923 "Face used for level 6 headlines."
2924 :group 'org-faces)
2926 (defface org-level-7 ;; font-lock-builtin-face
2927 (org-compatible-face
2928 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2929 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2930 (((class color) (min-colors 8)) (:foreground "blue"))))
2931 "Face used for level 7 headlines."
2932 :group 'org-faces)
2934 (defface org-level-8 ;; font-lock-string-face
2935 (org-compatible-face
2936 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2937 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2938 (((class color) (min-colors 8)) (:foreground "green"))))
2939 "Face used for level 8 headlines."
2940 :group 'org-faces)
2942 (defface org-special-keyword ;; font-lock-string-face
2943 (org-compatible-face
2944 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2945 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2946 (t (:italic t))))
2947 "Face used for special keywords."
2948 :group 'org-faces)
2950 (defface org-warning ;; 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 (:bold t))))
2957 "Face for deadlines and TODO keywords."
2958 :group 'org-faces)
2960 (defface org-archived ; similar to shadow
2961 (org-compatible-face
2962 '((((class color grayscale) (min-colors 88) (background light))
2963 (:foreground "grey50"))
2964 (((class color grayscale) (min-colors 88) (background dark))
2965 (:foreground "grey70"))
2966 (((class color) (min-colors 8) (background light))
2967 (:foreground "green"))
2968 (((class color) (min-colors 8) (background dark))
2969 (:foreground "yellow"))))
2970 "Face for headline with the ARCHIVE tag."
2971 :group 'org-faces)
2973 (defface org-link
2974 '((((class color) (background light)) (:foreground "Purple" :underline t))
2975 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2976 (t (:underline t)))
2977 "Face for links."
2978 :group 'org-faces)
2980 (defface org-date
2981 '((((class color) (background light)) (:foreground "Purple" :underline t))
2982 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2983 (t (:underline t)))
2984 "Face for links."
2985 :group 'org-faces)
2987 (defface org-tag
2988 '((t (:bold t)))
2989 "Face for tags."
2990 :group 'org-faces)
2992 (defface org-todo ;; font-lock-warning-face
2993 (org-compatible-face
2994 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2995 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2996 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2997 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2998 (t (:inverse-video t :bold t))))
2999 "Face for TODO keywords."
3000 :group 'org-faces)
3002 (defface org-done ;; font-lock-type-face
3003 (org-compatible-face
3004 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3005 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3006 (((class color) (min-colors 8)) (:foreground "green"))
3007 (t (:bold t))))
3008 "Face used for todo keywords that indicate DONE items."
3009 :group 'org-faces)
3011 (defface org-headline-done ;; font-lock-string-face
3012 (org-compatible-face
3013 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3014 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3015 (((class color) (min-colors 8) (background light)) (:bold nil))))
3016 "Face used to indicate that a headline is DONE.
3017 This face is only used if `org-fontify-done-headline' is set. If applies
3018 to the part of the headline after the DONE keyword."
3019 :group 'org-faces)
3021 (defface org-table ;; font-lock-function-name-face
3022 (org-compatible-face
3023 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3024 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3025 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3026 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3027 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3028 (((class color) (min-colors 8) (background dark)))))
3029 "Face used for tables."
3030 :group 'org-faces)
3032 (defface org-formula
3033 (org-compatible-face
3034 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3035 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3036 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3037 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3038 (t (:bold t :italic t))))
3039 "Face for formulas."
3040 :group 'org-faces)
3042 (defface org-scheduled-today
3043 (org-compatible-face
3044 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3045 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3046 (((class color) (min-colors 8)) (:foreground "green"))
3047 (t (:bold t :italic t))))
3048 "Face for items scheduled for a certain day."
3049 :group 'org-faces)
3051 (defface org-scheduled-previously
3052 (org-compatible-face
3053 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3054 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3055 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3056 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3057 (t (:bold t))))
3058 "Face for items scheduled previously, and not yet done."
3059 :group 'org-faces)
3061 (defface org-upcoming-deadline
3062 (org-compatible-face
3063 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3064 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3065 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3066 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3067 (t (:bold t))))
3068 "Face for items scheduled previously, and not yet done."
3069 :group 'org-faces)
3071 (defface org-time-grid ;; font-lock-variable-name-face
3072 (org-compatible-face
3073 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3074 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3075 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3076 "Face used for time grids."
3077 :group 'org-faces)
3079 (defconst org-level-faces
3080 '(org-level-1 org-level-2 org-level-3 org-level-4
3081 org-level-5 org-level-6 org-level-7 org-level-8
3083 (defconst org-n-levels (length org-level-faces))
3086 ;;; Variables for pre-computed regular expressions, all buffer local
3088 (defvar org-todo-regexp nil
3089 "Matches any of the TODO state keywords.")
3090 (make-variable-buffer-local 'org-todo-regexp)
3091 (defvar org-not-done-regexp nil
3092 "Matches any of the TODO state keywords except the last one.")
3093 (make-variable-buffer-local 'org-not-done-regexp)
3094 (defvar org-todo-line-regexp nil
3095 "Matches a headline and puts TODO state into group 2 if present.")
3096 (make-variable-buffer-local 'org-todo-line-regexp)
3097 (defvar org-todo-line-tags-regexp nil
3098 "Matches a headline and puts TODO state into group 2 if present.
3099 Also put tags into group 4 if tags are present.")
3100 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3101 (defvar org-nl-done-regexp nil
3102 "Matches newline followed by a headline with the DONE keyword.")
3103 (make-variable-buffer-local 'org-nl-done-regexp)
3104 (defvar org-looking-at-done-regexp nil
3105 "Matches the DONE keyword a point.")
3106 (make-variable-buffer-local 'org-looking-at-done-regexp)
3107 (defvar org-ds-keyword-length 12
3108 "Maximum length of the Deadline and SCHEDULED keywords.")
3109 (make-variable-buffer-local 'org-ds-keyword-length)
3110 (defvar org-deadline-regexp nil
3111 "Matches the DEADLINE keyword.")
3112 (make-variable-buffer-local 'org-deadline-regexp)
3113 (defvar org-deadline-time-regexp nil
3114 "Matches the DEADLINE keyword together with a time stamp.")
3115 (make-variable-buffer-local 'org-deadline-time-regexp)
3116 (defvar org-deadline-line-regexp nil
3117 "Matches the DEADLINE keyword and the rest of the line.")
3118 (make-variable-buffer-local 'org-deadline-line-regexp)
3119 (defvar org-scheduled-regexp nil
3120 "Matches the SCHEDULED keyword.")
3121 (make-variable-buffer-local 'org-scheduled-regexp)
3122 (defvar org-scheduled-time-regexp nil
3123 "Matches the SCHEDULED keyword together with a time stamp.")
3124 (make-variable-buffer-local 'org-scheduled-time-regexp)
3125 (defvar org-closed-time-regexp nil
3126 "Matches the CLOSED keyword together with a time stamp.")
3127 (make-variable-buffer-local 'org-closed-time-regexp)
3129 (defvar org-keyword-time-regexp nil
3130 "Matches any of the 4 keywords, together with the time stamp.")
3131 (make-variable-buffer-local 'org-keyword-time-regexp)
3132 (defvar org-keyword-time-not-clock-regexp nil
3133 "Matches any of the 3 keywords, together with the time stamp.")
3134 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3135 (defvar org-maybe-keyword-time-regexp nil
3136 "Matches a timestamp, possibly preceeded by a keyword.")
3137 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3139 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3140 rear-nonsticky t mouse-map t fontified t)
3141 "Properties to remove when a string without properties is wanted.")
3143 (defsubst org-match-string-no-properties (num &optional string)
3144 (if (featurep 'xemacs)
3145 (let ((s (match-string num string)))
3146 (remove-text-properties 0 (length s) org-rm-props s)
3148 (match-string-no-properties num string)))
3150 (defsubst org-no-properties (s)
3151 (remove-text-properties 0 (length s) org-rm-props s)
3154 (defsubst org-get-alist-option (option key)
3155 (cond ((eq key t) t)
3156 ((eq option t) t)
3157 ((assoc key option) (cdr (assoc key option)))
3158 (t (cdr (assq 'default option)))))
3160 (defsubst org-inhibit-invisibility ()
3161 "Modified `buffer-invisibility-spec' for Emacs 21.
3162 Some ops with invisible text do not work correctly on Emacs 21. For these
3163 we turn off invisibility temporarily. Use this in a `let' form."
3164 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3166 (defsubst org-set-local (var value)
3167 "Make VAR local in current buffer and set it to VALUE."
3168 (set (make-variable-buffer-local var) value))
3170 (defsubst org-mode-p ()
3171 "Check if the current buffer is in Org-mode."
3172 (eq major-mode 'org-mode))
3174 (defsubst org-last (list)
3175 "Return the last element of LIST."
3176 (car (last list)))
3178 (defun org-let (list &rest body)
3179 (eval (cons 'let (cons list body))))
3180 (put 'org-let 'lisp-indent-function 1)
3182 (defun org-let2 (list1 list2 &rest body)
3183 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3184 (put 'org-let2 'lisp-indent-function 2)
3185 (defconst org-startup-options
3186 '(("fold" org-startup-folded t)
3187 ("overview" org-startup-folded t)
3188 ("nofold" org-startup-folded nil)
3189 ("showall" org-startup-folded nil)
3190 ("content" org-startup-folded content)
3191 ("hidestars" org-hide-leading-stars t)
3192 ("showstars" org-hide-leading-stars nil)
3193 ("odd" org-odd-levels-only t)
3194 ("oddeven" org-odd-levels-only nil)
3195 ("align" org-startup-align-all-tables t)
3196 ("noalign" org-startup-align-all-tables nil)
3197 ("customtime" org-display-custom-times t)
3198 ("logging" org-log-done t)
3199 ("logdone" org-log-done t)
3200 ("nologging" org-log-done nil)
3201 ("lognotedone" org-log-done done push)
3202 ("lognotestate" org-log-done state push)
3203 ("lognoteclock-out" org-log-done clock-out push)
3204 ("constcgs" constants-unit-system cgs)
3205 ("constSI" constants-unit-system SI))
3206 "Variable associated with STARTUP options for org-mode.
3207 Each element is a list of three items: The startup options as written
3208 in the #+STARTUP line, the corresponding variable, and the value to
3209 set this variable to if the option is found. An optional forth element PUSH
3210 means to push this value onto the list in the variable.")
3212 (defun org-set-regexps-and-options ()
3213 "Precompute regular expressions for current buffer."
3214 (when (org-mode-p)
3215 (org-set-local 'org-todo-kwd-alist nil)
3216 (org-set-local 'org-todo-keywords-1 nil)
3217 (org-set-local 'org-done-keywords nil)
3218 (org-set-local 'org-todo-heads nil)
3219 (org-set-local 'org-todo-sets nil)
3220 (let ((re (org-make-options-regexp
3221 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3222 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
3223 (splitre "[ \t]+")
3224 kwds key value cat arch tags links hw dws tail sep kws1)
3225 (save-excursion
3226 (save-restriction
3227 (widen)
3228 (goto-char (point-min))
3229 (while (re-search-forward re nil t)
3230 (setq key (match-string 1) value (org-match-string-no-properties 2))
3231 (cond
3232 ((equal key "CATEGORY")
3233 (if (string-match "[ \t]+$" value)
3234 (setq value (replace-match "" t t value)))
3235 (setq cat (intern value)))
3236 ((equal key "SEQ_TODO")
3237 (push (cons 'sequence (org-split-string value splitre)) kwds))
3238 ((equal key "TYP_TODO")
3239 (push (cons 'type (org-split-string value splitre)) kwds))
3240 ((equal key "TAGS")
3241 (setq tags (append tags (org-split-string value splitre))))
3242 ((equal key "LINK")
3243 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3244 (push (cons (match-string 1 value)
3245 (org-trim (match-string 2 value)))
3246 links)))
3247 ((equal key "STARTUP")
3248 (let ((opts (org-split-string value splitre))
3249 l var val)
3250 (while (setq l (pop opts))
3251 (when (setq l (assoc l org-startup-options))
3252 (setq var (nth 1 l) val (nth 2 l))
3253 (if (not (nth 3 l))
3254 (set (make-local-variable var) val)
3255 (if (not (listp (symbol-value var)))
3256 (set (make-local-variable var) nil))
3257 (set (make-local-variable var) (symbol-value var))
3258 (add-to-list var val))))))
3259 ((equal key "ARCHIVE")
3260 (string-match " *$" value)
3261 (setq arch (replace-match "" t t value))
3262 (remove-text-properties 0 (length arch)
3263 '(face t fontified t) arch)))
3265 (and cat (org-set-local 'org-category cat))
3266 (and arch (org-set-local 'org-archive-location arch))
3267 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3268 ;; Process the TODO keywords
3269 (unless kwds
3270 ;; Use the global values as if they had been given locally.
3271 (setq kwds (default-value 'org-todo-keywords))
3272 (if (stringp (car kwds))
3273 (setq kwds (list (cons org-todo-interpretation
3274 (default-value 'org-todo-keywords)))))
3275 (setq kwds (reverse kwds)))
3276 (setq kwds (nreverse kwds))
3277 (let (inter kws)
3278 (while (setq kws (pop kwds))
3279 (setq inter (pop kws) sep (member "|" kws)
3280 kws1 (delete "|" (copy-sequence kws))
3281 hw (car kws1)
3282 dws (if sep (cdr sep) (last kws1))
3283 tail (list inter hw (car dws) (org-last dws)))
3284 (add-to-list 'org-todo-heads hw 'append)
3285 (push kws1 org-todo-sets)
3286 (setq org-done-keywords (append org-done-keywords dws nil))
3287 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3288 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3289 (setq org-todo-sets (nreverse org-todo-sets)
3290 org-todo-kwd-alist (nreverse org-todo-kwd-alist)))
3291 ;; Process the tags.
3292 (when tags
3293 (let (e tgs)
3294 (while (setq e (pop tags))
3295 (cond
3296 ((equal e "{") (push '(:startgroup) tgs))
3297 ((equal e "}") (push '(:endgroup) tgs))
3298 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3299 (push (cons (match-string 1 e)
3300 (string-to-char (match-string 2 e)))
3301 tgs))
3302 (t (push (list e) tgs))))
3303 (org-set-local 'org-tag-alist nil)
3304 (while (setq e (pop tgs))
3305 (or (and (stringp (car e))
3306 (assoc (car e) org-tag-alist))
3307 (push e org-tag-alist))))))
3309 ;; Compute the regular expressions and other local variables
3310 (if (not org-done-keywords)
3311 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3312 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3313 (length org-scheduled-string)))
3314 org-not-done-keywords
3315 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3316 org-todo-regexp
3317 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3318 "\\|") "\\)\\>")
3319 org-not-done-regexp
3320 (concat "\\<\\("
3321 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3322 "\\)\\>")
3323 org-todo-line-regexp
3324 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3325 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3326 "\\)\\>\\)? *\\(.*\\)")
3327 org-nl-done-regexp
3328 (concat "[\r\n]\\*+[ \t]+"
3329 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3330 "\\)" "\\>")
3331 org-todo-line-tags-regexp
3332 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3333 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3334 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3335 org-looking-at-done-regexp
3336 (concat "^" "\\(?:"
3337 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3338 "\\>")
3339 org-deadline-regexp (concat "\\<" org-deadline-string)
3340 org-deadline-time-regexp
3341 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3342 org-deadline-line-regexp
3343 (concat "\\<\\(" org-deadline-string "\\).*")
3344 org-scheduled-regexp
3345 (concat "\\<" org-scheduled-string)
3346 org-scheduled-time-regexp
3347 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3348 org-closed-time-regexp
3349 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3350 org-keyword-time-regexp
3351 (concat "\\<\\(" org-scheduled-string
3352 "\\|" org-deadline-string
3353 "\\|" org-closed-string
3354 "\\|" org-clock-string "\\)"
3355 " *[[<]\\([^]>]+\\)[]>]")
3356 org-keyword-time-not-clock-regexp
3357 (concat "\\<\\(" org-scheduled-string
3358 "\\|" org-deadline-string
3359 "\\|" org-closed-string "\\)"
3360 " *[[<]\\([^]>]+\\)[]>]")
3361 org-maybe-keyword-time-regexp
3362 (concat "\\(\\<\\(" org-scheduled-string
3363 "\\|" org-deadline-string
3364 "\\|" org-closed-string
3365 "\\|" org-clock-string "\\)\\)?"
3366 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3368 (org-set-font-lock-defaults)))
3371 ;;; Some variables ujsed in various places
3373 (defvar org-window-configuration nil
3374 "Used in various places to store a window configuration.")
3375 (defvar org-finish-function nil
3376 "Function to be called when `C-c C-c' is used.
3377 This is for getting out of special buffers like remember.")
3379 ;;; Foreign variables, to inform the compiler
3381 ;; XEmacs only
3382 (defvar outline-mode-menu-heading)
3383 (defvar outline-mode-menu-show)
3384 (defvar outline-mode-menu-hide)
3385 (defvar zmacs-regions) ; XEmacs regions
3386 ;; Emacs only
3387 (defvar mark-active)
3389 ;; Packages that org-mode interacts with
3390 (defvar calc-embedded-close-formula)
3391 (defvar calc-embedded-open-formula)
3392 (defvar font-lock-unfontify-region-function)
3393 (defvar org-goto-start-pos)
3394 (defvar vm-message-pointer)
3395 (defvar vm-folder-directory)
3396 (defvar wl-summary-buffer-elmo-folder)
3397 (defvar wl-summary-buffer-folder-name)
3398 (defvar gnus-other-frame-object)
3399 (defvar gnus-group-name)
3400 (defvar gnus-article-current)
3401 (defvar w3m-current-url)
3402 (defvar w3m-current-title)
3403 (defvar mh-progs)
3404 (defvar mh-current-folder)
3405 (defvar mh-show-folder-buffer)
3406 (defvar mh-index-folder)
3407 (defvar mh-searcher)
3408 (defvar calendar-mode-map)
3409 (defvar Info-current-file)
3410 (defvar Info-current-node)
3411 (defvar texmathp-why)
3412 (defvar remember-save-after-remembering)
3413 (defvar remember-data-file)
3414 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3415 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3416 (defvar org-latex-regexps)
3417 (defvar constants-unit-system)
3419 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3421 ;; FIXME: Occasionally check by commenting these, to make sure
3422 ;; no other functions uses these, forgetting to let-bind them.
3423 (defvar entry)
3424 (defvar state)
3425 (defvar last-state)
3426 (defvar date)
3427 (defvar description)
3430 ;; Defined somewhere in this file, but used before definition.
3431 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3432 (defvar org-agenda-undo-list)
3433 (defvar org-agenda-pending-undo-list)
3434 (defvar org-agenda-overriding-header)
3435 (defvar orgtbl-mode)
3436 (defvar org-html-entities)
3437 (defvar org-struct-menu)
3438 (defvar org-org-menu)
3439 (defvar org-tbl-menu)
3440 (defvar org-agenda-keymap)
3441 (defvar org-category-table)
3443 ;;;; Emacs/XEmacs compatibility
3445 ;; Overlay compatibility functions
3446 (defun org-make-overlay (beg end &optional buffer)
3447 (if (featurep 'xemacs)
3448 (make-extent beg end buffer)
3449 (make-overlay beg end buffer)))
3450 (defun org-delete-overlay (ovl)
3451 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3452 (defun org-detach-overlay (ovl)
3453 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3454 (defun org-move-overlay (ovl beg end &optional buffer)
3455 (if (featurep 'xemacs)
3456 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3457 (move-overlay ovl beg end buffer)))
3458 (defun org-overlay-put (ovl prop value)
3459 (if (featurep 'xemacs)
3460 (set-extent-property ovl prop value)
3461 (overlay-put ovl prop value)))
3462 (defun org-overlay-display (ovl text &optional face evap)
3463 "Make overlay OVL display TEXT with face FACE."
3464 (if (featurep 'xemacs)
3465 (let ((gl (make-glyph text)))
3466 (and face (set-glyph-face gl face))
3467 (set-extent-property ovl 'invisible t)
3468 (set-extent-property ovl 'end-glyph gl))
3469 (overlay-put ovl 'display text)
3470 (if face (overlay-put ovl 'face face))
3471 (if evap (overlay-put ovl 'evaporate t))))
3472 (defun org-overlay-before-string (ovl text &optional face evap)
3473 "Make overlay OVL display TEXT with face FACE."
3474 (if (featurep 'xemacs)
3475 (let ((gl (make-glyph text)))
3476 (and face (set-glyph-face gl face))
3477 (set-extent-property ovl 'begin-glyph gl))
3478 (if face (org-add-props text nil 'face face))
3479 (overlay-put ovl 'before-string text)
3480 (if evap (overlay-put ovl 'evaporate t))))
3481 (defun org-overlay-get (ovl prop)
3482 (if (featurep 'xemacs)
3483 (extent-property ovl prop)
3484 (overlay-get ovl prop)))
3485 (defun org-overlays-at (pos)
3486 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3487 ;; FIXME: this is currently not used
3488 (defun org-overlays-in (&optional start end)
3489 (if (featurep 'xemacs)
3490 (extent-list nil start end)
3491 (overlays-in start end)))
3492 (defun org-overlay-start (o)
3493 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3494 (defun org-overlay-end (o)
3495 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3496 ;; FIXME: this is currently not used
3497 (defun org-find-overlays (prop &optional pos delete)
3498 "Find all overlays specifying PROP at POS or point.
3499 If DELETE is non-nil, delete all those overlays."
3500 (let ((overlays (org-overlays-at (or pos (point))))
3501 ov found)
3502 (while (setq ov (pop overlays))
3503 (if (org-overlay-get ov prop)
3504 (if delete (org-delete-overlay ov) (push ov found))))
3505 found))
3507 ;; Region compatibility
3509 (defun org-add-hook (hook function &optional append local)
3510 "Add-hook, compatible with both Emacsen."
3511 (if (and local (featurep 'xemacs))
3512 (add-local-hook hook function append)
3513 (add-hook hook function append local)))
3515 (defvar org-ignore-region nil
3516 "To temporarily disable the active region.")
3518 (defun org-region-active-p ()
3519 "Is `transient-mark-mode' on and the region active?
3520 Works on both Emacs and XEmacs."
3521 (if org-ignore-region
3523 (if (featurep 'xemacs)
3524 (and zmacs-regions (region-active-p))
3525 (and transient-mark-mode mark-active))))
3527 ;; Invisibility compatibility
3529 (defun org-add-to-invisibility-spec (arg)
3530 "Add elements to `buffer-invisibility-spec'.
3531 See documentation for `buffer-invisibility-spec' for the kind of elements
3532 that can be added."
3533 (cond
3534 ((fboundp 'add-to-invisibility-spec)
3535 (add-to-invisibility-spec arg))
3536 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3537 (setq buffer-invisibility-spec (list arg)))
3539 (setq buffer-invisibility-spec
3540 (cons arg buffer-invisibility-spec)))))
3542 (defun org-remove-from-invisibility-spec (arg)
3543 "Remove elements from `buffer-invisibility-spec'."
3544 (if (fboundp 'remove-from-invisibility-spec)
3545 (remove-from-invisibility-spec arg)
3546 (if (consp buffer-invisibility-spec)
3547 (setq buffer-invisibility-spec
3548 (delete arg buffer-invisibility-spec)))))
3550 ;; FIXME: this is currently not used
3551 (defun org-in-invisibility-spec-p (arg)
3552 "Is ARG a member of `buffer-invisibility-spec'?"
3553 (if (consp buffer-invisibility-spec)
3554 (member arg buffer-invisibility-spec)
3555 nil))
3557 ;;;; Define the Org-mode
3559 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3560 (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."))
3563 ;; We use a before-change function to check if a table might need
3564 ;; an update.
3565 (defvar org-table-may-need-update t
3566 "Indicates that a table might need an update.
3567 This variable is set by `org-before-change-function'.
3568 `org-table-align' sets it back to nil.")
3569 (defvar org-mode-map)
3570 (defvar org-mode-hook nil)
3571 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3572 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3573 (defvar org-table-buffer-is-an nil)
3576 ;;;###autoload
3577 (define-derived-mode org-mode outline-mode "Org"
3578 "Outline-based notes management and organizer, alias
3579 \"Carsten's outline-mode for keeping track of everything.\"
3581 Org-mode develops organizational tasks around a NOTES file which
3582 contains information about projects as plain text. Org-mode is
3583 implemented on top of outline-mode, which is ideal to keep the content
3584 of large files well structured. It supports ToDo items, deadlines and
3585 time stamps, which magically appear in the diary listing of the Emacs
3586 calendar. Tables are easily created with a built-in table editor.
3587 Plain text URL-like links connect to websites, emails (VM), Usenet
3588 messages (Gnus), BBDB entries, and any files related to the project.
3589 For printing and sharing of notes, an Org-mode file (or a part of it)
3590 can be exported as a structured ASCII or HTML file.
3592 The following commands are available:
3594 \\{org-mode-map}"
3596 ;; Get rid of Outline menus, they are not needed
3597 ;; Need to do this here because define-derived-mode sets up
3598 ;; the keymap so late. Still, it is a waste to call this each time
3599 ;; we switch another buffer into org-mode.
3600 (if (featurep 'xemacs)
3601 (when (boundp 'outline-mode-menu-heading)
3602 ;; Assume this is Greg's port, it used easymenu
3603 (easy-menu-remove outline-mode-menu-heading)
3604 (easy-menu-remove outline-mode-menu-show)
3605 (easy-menu-remove outline-mode-menu-hide))
3606 (define-key org-mode-map [menu-bar headings] 'undefined)
3607 (define-key org-mode-map [menu-bar hide] 'undefined)
3608 (define-key org-mode-map [menu-bar show] 'undefined))
3610 (easy-menu-add org-org-menu)
3611 (easy-menu-add org-tbl-menu)
3612 (org-install-agenda-files-menu)
3613 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3614 (org-add-to-invisibility-spec '(org-cwidth))
3615 (when (featurep 'xemacs)
3616 (org-set-local 'line-move-ignore-invisible t))
3617 (setq outline-regexp "\\*+")
3618 (setq outline-level 'org-outline-level)
3619 (when (and org-ellipsis (stringp org-ellipsis)
3620 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
3621 (unless org-display-table
3622 (setq org-display-table (make-display-table)))
3623 (set-display-table-slot org-display-table
3624 4 (string-to-vector org-ellipsis))
3625 (setq buffer-display-table org-display-table))
3626 (org-set-regexps-and-options)
3627 ;; Calc embedded
3628 (org-set-local 'calc-embedded-open-mode "# ")
3629 (modify-syntax-entry ?# "<")
3630 (modify-syntax-entry ?@ "w")
3631 (if org-startup-truncated (setq truncate-lines t))
3632 (org-set-local 'font-lock-unfontify-region-function
3633 'org-unfontify-region)
3634 ;; Activate before-change-function
3635 (org-set-local 'org-table-may-need-update t)
3636 (org-add-hook 'before-change-functions 'org-before-change-function nil
3637 'local)
3638 ;; Check for running clock before killing a buffer
3639 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3640 ;; Paragraphs and auto-filling
3641 (org-set-autofill-regexps)
3642 (setq indent-line-function 'org-indent-line-function)
3643 (org-update-radio-target-regexp)
3645 ;; Comment characters
3646 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3647 (org-set-local 'comment-padding " ")
3649 ;; Make isearch reveal context
3650 (if (or (featurep 'xemacs)
3651 (not (boundp 'outline-isearch-open-invisible-function)))
3652 ;; Emacs 21 and XEmacs make use of the hook
3653 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3654 ;; Emacs 22 deals with this through a special variable
3655 (org-set-local 'outline-isearch-open-invisible-function
3656 (lambda (&rest ignore) (org-show-context 'isearch))))
3658 ;; If empty file that did not turn on org-mode automatically, make it to.
3659 (if (and org-insert-mode-line-in-empty-file
3660 (interactive-p)
3661 (= (point-min) (point-max)))
3662 (insert "# -*- mode: org -*-\n\n"))
3664 (unless org-inhibit-startup
3665 (when org-startup-align-all-tables
3666 (let ((bmp (buffer-modified-p)))
3667 (org-table-map-tables 'org-table-align)
3668 (set-buffer-modified-p bmp)))
3669 (cond
3670 ((eq org-startup-folded t)
3671 (org-cycle '(4)))
3672 ((eq org-startup-folded 'content)
3673 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3674 (org-cycle '(4)) (org-cycle '(4)))))))
3676 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3678 (defsubst org-call-with-arg (command arg)
3679 "Call COMMAND interactively, but pretend prefix are was ARG."
3680 (let ((current-prefix-arg arg)) (call-interactively command)))
3682 (defsubst org-current-line (&optional pos)
3683 (save-excursion
3684 (and pos (goto-char pos))
3685 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
3687 (defun org-current-time ()
3688 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3689 (if (> org-time-stamp-rounding-minutes 0)
3690 (let ((r org-time-stamp-rounding-minutes)
3691 (time (decode-time)))
3692 (apply 'encode-time
3693 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3694 (nthcdr 2 time))))
3695 (current-time)))
3697 (defun org-add-props (string plist &rest props)
3698 "Add text properties to entire string, from beginning to end.
3699 PLIST may be a list of properties, PROPS are individual properties and values
3700 that will be added to PLIST. Returns the string that was modified."
3701 (add-text-properties
3702 0 (length string) (if props (append plist props) plist) string)
3703 string)
3704 (put 'org-add-props 'lisp-indent-function 2)
3707 ;;;; Font-Lock stuff, including the activators
3709 (defvar org-mouse-map (make-sparse-keymap))
3710 (define-key org-mouse-map
3711 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3712 (define-key org-mouse-map
3713 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3714 (when org-mouse-1-follows-link
3715 (define-key org-mouse-map [follow-link] 'mouse-face))
3716 (when org-tab-follows-link
3717 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3718 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3719 (when org-return-follows-link
3720 (define-key org-mouse-map [(return)] 'org-open-at-point)
3721 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3723 (require 'font-lock)
3725 (defconst org-non-link-chars "]\t\n\r<>")
3726 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3727 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3728 (defconst org-link-re-with-space
3729 (concat
3730 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3731 "\\([^" org-non-link-chars " ]"
3732 "[^" org-non-link-chars "]*"
3733 "[^" org-non-link-chars " ]\\)>?")
3734 "Matches a link with spaces, optional angular brackets around it.")
3736 (defconst org-link-re-with-space2
3737 (concat
3738 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3739 "\\([^" org-non-link-chars " ]"
3740 "[^]\t\n\r]*"
3741 "[^" org-non-link-chars " ]\\)>?")
3742 "Matches a link with spaces, optional angular brackets around it.")
3744 (defconst org-angle-link-re
3745 (concat
3746 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3747 "\\([^" org-non-link-chars " ]"
3748 "[^" org-non-link-chars "]*"
3749 "\\)>")
3750 "Matches link with angular brackets, spaces are allowed.")
3751 (defconst org-plain-link-re
3752 (concat
3753 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3754 "\\([^]\t\n\r<>,;() ]+\\)")
3755 "Matches plain link, without spaces.")
3757 (defconst org-bracket-link-regexp
3758 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3759 "Matches a link in double brackets.")
3761 (defconst org-bracket-link-analytic-regexp
3762 (concat
3763 "\\[\\["
3764 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3765 "\\([^]]+\\)"
3766 "\\]"
3767 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3768 "\\]"))
3769 ; 1: http:
3770 ; 2: http
3771 ; 3: path
3772 ; 4: [desc]
3773 ; 5: desc
3775 (defconst org-any-link-re
3776 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3777 org-angle-link-re "\\)\\|\\("
3778 org-plain-link-re "\\)")
3779 "Regular expression matching any link.")
3781 (defconst org-ts-lengths
3782 (cons (length (format-time-string (car org-time-stamp-formats)))
3783 (length (format-time-string (cdr org-time-stamp-formats))))
3784 "This holds the lengths of the two different time formats.")
3785 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3786 "Regular expression for fast time stamp matching.")
3787 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3788 "Regular expression for fast time stamp matching.")
3789 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3790 "Regular expression matching time strings for analysis.")
3791 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3792 "Regular expression matching time stamps, with groups.")
3793 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3794 "Regular expression matching time stamps (also [..]), with groups.")
3795 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3796 "Regular expression matching a time stamp range.")
3797 (defconst org-tr-regexp-both
3798 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3799 "Regular expression matching a time stamp range.")
3800 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3801 org-ts-regexp "\\)?")
3802 "Regular expression matching a time stamp or time stamp range.")
3803 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3804 org-ts-regexp-both "\\)?")
3805 "Regular expression matching a time stamp or time stamp range.
3806 The time stamps may be either active or inactive.")
3808 (defvar org-emph-face nil)
3810 (defun org-do-emphasis-faces (limit)
3811 "Run through the buffer and add overlays to links."
3812 (if (re-search-forward org-emph-re limit t)
3813 (progn
3814 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3815 'face
3816 (nth 1 (assoc (match-string 3)
3817 org-emphasis-alist)))
3818 (add-text-properties (match-beginning 2) (match-end 2)
3819 '(font-lock-multiline t))
3820 (backward-char 1)
3821 t)))
3823 (defun org-activate-plain-links (limit)
3824 "Run through the buffer and add overlays to links."
3825 (if (re-search-forward org-plain-link-re limit t)
3826 (progn
3827 (add-text-properties (match-beginning 0) (match-end 0)
3828 (list 'mouse-face 'highlight
3829 'rear-nonsticky t
3830 'keymap org-mouse-map
3832 t)))
3834 (defun org-activate-angle-links (limit)
3835 "Run through the buffer and add overlays to links."
3836 (if (re-search-forward org-angle-link-re limit t)
3837 (progn
3838 (add-text-properties (match-beginning 0) (match-end 0)
3839 (list 'mouse-face 'highlight
3840 'rear-nonsticky t
3841 'keymap org-mouse-map
3843 t)))
3845 (defmacro org-maybe-intangible (props)
3846 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3847 In emacs 21, invisible text is not avoided by the command loop, so the
3848 intangible property is needed to make sure point skips this text.
3849 In Emacs 22, this is not necessary. The intangible text property has
3850 led to problems with flyspell. These problems are fixed in flyspell.el,
3851 but we still avoid setting the property in Emacs 22 and later.
3852 We use a macro so that the test can happen at compilation time."
3853 (if (< emacs-major-version 22)
3854 `(append '(intangible t) ,props)
3855 props))
3857 (defun org-activate-bracket-links (limit)
3858 "Run through the buffer and add overlays to bracketed links."
3859 (if (re-search-forward org-bracket-link-regexp limit t)
3860 (let* ((help (concat "LINK: "
3861 (org-match-string-no-properties 1)))
3862 ;; FIXME: above we should remove the escapes.
3863 ;; but that requires another match, protecting match data,
3864 ;; a lot of overhead for font-lock.
3865 (ip (org-maybe-intangible
3866 (list 'invisible 'org-link 'rear-nonsticky t
3867 'keymap org-mouse-map 'mouse-face 'highlight
3868 'help-echo help)))
3869 (vp (list 'rear-nonsticky t
3870 'keymap org-mouse-map 'mouse-face 'highlight
3871 'help-echo help)))
3872 ;; We need to remove the invisible property here. Table narrowing
3873 ;; may have made some of this invisible.
3874 (remove-text-properties (match-beginning 0) (match-end 0)
3875 '(invisible nil))
3876 (if (match-end 3)
3877 (progn
3878 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3879 (add-text-properties (match-beginning 3) (match-end 3) vp)
3880 (add-text-properties (match-end 3) (match-end 0) ip))
3881 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3882 (add-text-properties (match-beginning 1) (match-end 1) vp)
3883 (add-text-properties (match-end 1) (match-end 0) ip))
3884 t)))
3886 (defun org-activate-dates (limit)
3887 "Run through the buffer and add overlays to dates."
3888 (if (re-search-forward org-tsr-regexp-both limit t)
3889 (progn
3890 (add-text-properties (match-beginning 0) (match-end 0)
3891 (list 'mouse-face 'highlight
3892 'rear-nonsticky t
3893 'keymap org-mouse-map))
3894 (when org-display-custom-times
3895 (if (match-end 3)
3896 (org-display-custom-time (match-beginning 3) (match-end 3)))
3897 (org-display-custom-time (match-beginning 1) (match-end 1)))
3898 t)))
3900 (defvar org-target-link-regexp nil
3901 "Regular expression matching radio targets in plain text.")
3902 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3903 "Regular expression matching a link target.")
3904 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3905 "Regular expression matching a link target.")
3907 (defun org-activate-target-links (limit)
3908 "Run through the buffer and add overlays to target matches."
3909 (when org-target-link-regexp
3910 (let ((case-fold-search t))
3911 (if (re-search-forward org-target-link-regexp limit t)
3912 (progn
3913 (add-text-properties (match-beginning 0) (match-end 0)
3914 (list 'mouse-face 'highlight
3915 'rear-nonsticky t
3916 'keymap org-mouse-map
3917 'help-echo "Radio target link"
3918 'org-linked-text t))
3919 t)))))
3921 (defun org-update-radio-target-regexp ()
3922 "Find all radio targets in this file and update the regular expression."
3923 (interactive)
3924 (when (memq 'radio org-activate-links)
3925 (setq org-target-link-regexp
3926 (org-make-target-link-regexp (org-all-targets 'radio)))
3927 (org-restart-font-lock)))
3929 (defun org-hide-wide-columns (limit)
3930 (let (s e)
3931 (setq s (text-property-any (point) (or limit (point-max))
3932 'org-cwidth t))
3933 (when s
3934 (setq e (next-single-property-change s 'org-cwidth))
3935 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3936 (goto-char e)
3937 t)))
3939 (defun org-restart-font-lock ()
3940 "Restart font-lock-mode, to force refontification."
3941 (when (and (boundp 'font-lock-mode) font-lock-mode)
3942 (font-lock-mode -1)
3943 (font-lock-mode 1)))
3945 (defun org-all-targets (&optional radio)
3946 "Return a list of all targets in this file.
3947 With optional argument RADIO, only find radio targets."
3948 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3949 rtn)
3950 (save-excursion
3951 (goto-char (point-min))
3952 (while (re-search-forward re nil t)
3953 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3954 rtn)))
3956 (defun org-make-target-link-regexp (targets)
3957 "Make regular expression matching all strings in TARGETS.
3958 The regular expression finds the targets also if there is a line break
3959 between words."
3960 (and targets
3961 (concat
3962 "\\<\\("
3963 (mapconcat
3964 (lambda (x)
3965 (while (string-match " +" x)
3966 (setq x (replace-match "\\s-+" t t x)))
3968 targets
3969 "\\|")
3970 "\\)\\>")))
3972 (defun org-activate-tags (limit)
3973 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3974 (progn
3975 (add-text-properties (match-beginning 1) (match-end 1)
3976 (list 'mouse-face 'highlight
3977 'rear-nonsticky t
3978 'keymap org-mouse-map))
3979 t)))
3981 (defun org-outline-level ()
3982 (save-excursion
3983 (looking-at outline-regexp)
3984 (if (match-beginning 1)
3985 (+ (org-get-string-indentation (match-string 1)) 1000)
3986 (- (match-end 0) (match-beginning 0)))))
3988 (defvar org-font-lock-keywords nil)
3990 (defun org-set-font-lock-defaults ()
3991 (let* ((em org-fontify-emphasized-text)
3992 (lk org-activate-links)
3993 (org-font-lock-extra-keywords
3994 ;; Headlines
3995 (list
3996 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3997 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3998 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3999 (1 'org-table))
4000 ;; Links
4001 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4002 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4003 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4004 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4005 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4006 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4007 '(org-hide-wide-columns (0 nil append))
4008 ;; TODO lines
4009 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
4010 '(1 'org-todo t))
4011 ;; Priorities
4012 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
4013 ;; Special keywords
4014 (list org-repeat-re '(0 'org-special-keyword t))
4015 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4016 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4017 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4018 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4019 ;; Emphasis
4020 (if em
4021 (if (featurep 'xemacs)
4022 '(org-do-emphasis-faces (0 nil append))
4023 '(org-do-emphasis-faces)))
4024 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
4025 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
4026 2 'bold prepend)
4027 (if org-provide-checkbox-statistics
4028 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4029 (0 (org-get-checkbox-statistics-face) t)))
4030 ;; COMMENT
4031 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
4032 "\\|" org-quote-string "\\)\\>")
4033 '(1 'org-special-keyword t))
4034 '("^#.*" (0 'font-lock-comment-face t))
4035 ;; DONE
4036 (if org-fontify-done-headline
4037 (list (concat "^[*]+ +\\<\\("
4038 (mapconcat 'regexp-quote org-done-keywords "\\|")
4039 "\\)\\(.*\\)\\>")
4040 '(1 'org-done t) '(2 'org-headline-done t))
4041 (list (concat "^[*]+ +\\<\\("
4042 (mapconcat 'regexp-quote org-done-keywords "\\|")
4043 "\\)\\>")
4044 '(1 'org-done t)))
4045 ;; Table stuff
4046 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
4047 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4048 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
4049 (if org-format-transports-properties-p
4050 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4051 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4053 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4054 ;; Now set the full font-lock-keywords
4055 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4056 (org-set-local 'font-lock-defaults
4057 '(org-font-lock-keywords t nil nil backward-paragraph))
4058 (kill-local-variable 'font-lock-keywords) nil))
4060 (defvar org-m nil)
4061 (defvar org-l nil)
4062 (defvar org-f nil)
4063 (defun org-get-level-face (n)
4064 "Get the right face for match N in font-lock matching of healdines."
4065 (setq org-l (- (match-end 2) (match-beginning 1)))
4066 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4067 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
4068 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
4069 (cond
4070 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4071 ((eq n 2) org-f)
4072 (t (if org-level-color-stars-only nil org-f))))
4074 (defun org-unfontify-region (beg end &optional maybe_loudly)
4075 "Remove fontification and activation overlays from links."
4076 (font-lock-default-unfontify-region beg end)
4077 (let* ((buffer-undo-list t)
4078 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4079 (inhibit-modification-hooks t)
4080 deactivate-mark buffer-file-name buffer-file-truename)
4081 (remove-text-properties beg end
4082 '(mouse-face t keymap t org-linked-text t
4083 rear-nonsticky t
4084 invisible t intangible t))))
4086 ;;;; Visibility cycling, including org-goto and indirect buffer
4088 ;;; Cycling
4090 (defvar org-cycle-global-status nil)
4091 (make-variable-buffer-local 'org-cycle-global-status)
4092 (defvar org-cycle-subtree-status nil)
4093 (make-variable-buffer-local 'org-cycle-subtree-status)
4095 ;;;###autoload
4096 (defun org-cycle (&optional arg)
4097 "Visibility cycling for Org-mode.
4099 - When this function is called with a prefix argument, rotate the entire
4100 buffer through 3 states (global cycling)
4101 1. OVERVIEW: Show only top-level headlines.
4102 2. CONTENTS: Show all headlines of all levels, but no body text.
4103 3. SHOW ALL: Show everything.
4105 - When point is at the beginning of a headline, rotate the subtree started
4106 by this line through 3 different states (local cycling)
4107 1. FOLDED: Only the main headline is shown.
4108 2. CHILDREN: The main headline and the direct children are shown.
4109 From this state, you can move to one of the children
4110 and zoom in further.
4111 3. SUBTREE: Show the entire subtree, including body text.
4113 - When there is a numeric prefix, go up to a heading with level ARG, do
4114 a `show-subtree' and return to the previous cursor position. If ARG
4115 is negative, go up that many levels.
4117 - When point is not at the beginning of a headline, execute
4118 `indent-relative', like TAB normally does. See the option
4119 `org-cycle-emulate-tab' for details.
4121 - Special case: if point is the the beginning of the buffer and there is
4122 no headline in line 1, this function will act as if called with prefix arg."
4123 (interactive "P")
4124 (let* ((outline-regexp
4125 (if (and (org-mode-p) org-cycle-include-plain-lists)
4126 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4127 outline-regexp))
4128 (bob-special (and org-cycle-global-at-bob (bobp)
4129 (not (looking-at outline-regexp))))
4130 (org-cycle-hook
4131 (if bob-special
4132 (delq 'org-optimize-window-after-visibility-change
4133 (copy-sequence org-cycle-hook))
4134 org-cycle-hook))
4135 (pos (point)))
4137 (if (or bob-special (equal arg '(4)))
4138 ;; special case: use global cycling
4139 (setq arg t))
4141 (cond
4143 ((org-at-table-p 'any)
4144 ;; Enter the table or move to the next field in the table
4145 (or (org-table-recognize-table.el)
4146 (progn
4147 (if arg (org-table-edit-field t)
4148 (org-table-justify-field-maybe)
4149 (call-interactively 'org-table-next-field)))))
4151 ((eq arg t) ;; Global cycling
4153 (cond
4154 ((and (eq last-command this-command)
4155 (eq org-cycle-global-status 'overview))
4156 ;; We just created the overview - now do table of contents
4157 ;; This can be slow in very large buffers, so indicate action
4158 (message "CONTENTS...")
4159 (org-content)
4160 (message "CONTENTS...done")
4161 (setq org-cycle-global-status 'contents)
4162 (run-hook-with-args 'org-cycle-hook 'contents))
4164 ((and (eq last-command this-command)
4165 (eq org-cycle-global-status 'contents))
4166 ;; We just showed the table of contents - now show everything
4167 (show-all)
4168 (message "SHOW ALL")
4169 (setq org-cycle-global-status 'all)
4170 (run-hook-with-args 'org-cycle-hook 'all))
4173 ;; Default action: go to overview
4174 (org-overview)
4175 (message "OVERVIEW")
4176 (setq org-cycle-global-status 'overview)
4177 (run-hook-with-args 'org-cycle-hook 'overview))))
4179 ((integerp arg)
4180 ;; Show-subtree, ARG levels up from here.
4181 (save-excursion
4182 (org-back-to-heading)
4183 (outline-up-heading (if (< arg 0) (- arg)
4184 (- (funcall outline-level) arg)))
4185 (org-show-subtree)))
4187 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4188 ;; At a heading: rotate between three different views
4189 (org-back-to-heading)
4190 (let ((goal-column 0) eoh eol eos)
4191 ;; First, some boundaries
4192 (save-excursion
4193 (org-back-to-heading)
4194 (save-excursion
4195 (beginning-of-line 2)
4196 (while (and (not (eobp)) ;; this is like `next-line'
4197 (get-char-property (1- (point)) 'invisible))
4198 (beginning-of-line 2)) (setq eol (point)))
4199 (outline-end-of-heading) (setq eoh (point))
4200 (org-end-of-subtree t)
4201 (skip-chars-forward " \t\n")
4202 (beginning-of-line 1) ; in case this is an item
4203 (setq eos (1- (point))))
4204 ;; Find out what to do next and set `this-command'
4205 (cond
4206 ((= eos eoh)
4207 ;; Nothing is hidden behind this heading
4208 (message "EMPTY ENTRY")
4209 (setq org-cycle-subtree-status nil))
4210 ((>= eol eos)
4211 ;; Entire subtree is hidden in one line: open it
4212 (org-show-entry)
4213 (show-children)
4214 (message "CHILDREN")
4215 (setq org-cycle-subtree-status 'children)
4216 (run-hook-with-args 'org-cycle-hook 'children))
4217 ((and (eq last-command this-command)
4218 (eq org-cycle-subtree-status 'children))
4219 ;; We just showed the children, now show everything.
4220 (org-show-subtree)
4221 (message "SUBTREE")
4222 (setq org-cycle-subtree-status 'subtree)
4223 (run-hook-with-args 'org-cycle-hook 'subtree))
4225 ;; Default action: hide the subtree.
4226 (hide-subtree)
4227 (message "FOLDED")
4228 (setq org-cycle-subtree-status 'folded)
4229 (run-hook-with-args 'org-cycle-hook 'folded)))))
4231 ;; TAB emulation
4232 (buffer-read-only (org-back-to-heading))
4234 ((org-try-cdlatex-tab))
4236 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4237 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4238 (or (and (eq org-cycle-emulate-tab 'white)
4239 (= (match-end 0) (point-at-eol)))
4240 (and (eq org-cycle-emulate-tab 'whitestart)
4241 (>= (match-end 0) pos))))
4243 (eq org-cycle-emulate-tab t))
4244 (if (and (looking-at "[ \n\r\t]")
4245 (string-match "^[ \t]*$" (buffer-substring
4246 (point-at-bol) (point))))
4247 (progn
4248 (beginning-of-line 1)
4249 (and (looking-at "[ \t]+") (replace-match ""))))
4250 (indent-relative))
4252 (t (save-excursion
4253 (org-back-to-heading)
4254 (org-cycle))))))
4256 ;;;###autoload
4257 (defun org-global-cycle (&optional arg)
4258 "Cycle the global visibility. For details see `org-cycle'."
4259 (interactive "P")
4260 (let ((org-cycle-include-plain-lists
4261 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4262 (if (integerp arg)
4263 (progn
4264 (show-all)
4265 (hide-sublevels arg)
4266 (setq org-cycle-global-status 'contents))
4267 (org-cycle '(4)))))
4269 (defun org-overview ()
4270 "Switch to overview mode, shoing only top-level headlines.
4271 Really, this shows all headlines with level equal or greater than the level
4272 of the first headline in the buffer. This is important, because if the
4273 first headline is not level one, then (hide-sublevels 1) gives confusing
4274 results."
4275 (interactive)
4276 (hide-sublevels (save-excursion
4277 (goto-char (point-min))
4278 (if (re-search-forward (concat "^" outline-regexp) nil t)
4279 (progn
4280 (goto-char (match-beginning 0))
4281 (funcall outline-level))
4282 1))))
4284 (defun org-content (&optional arg)
4285 "Show all headlines in the buffer, like a table of contents.
4286 With numerical argument N, show content up to level N."
4287 (interactive "P")
4288 (save-excursion
4289 ;; Visit all headings and show their offspring
4290 (and (integerp arg) (org-overview))
4291 (goto-char (point-max))
4292 (catch 'exit
4293 (while (and (progn (condition-case nil
4294 (outline-previous-visible-heading 1)
4295 (error (goto-char (point-min))))
4297 (looking-at outline-regexp))
4298 (if (integerp arg)
4299 (show-children (1- arg))
4300 (show-branches))
4301 (if (bobp) (throw 'exit nil))))))
4304 (defun org-optimize-window-after-visibility-change (state)
4305 "Adjust the window after a change in outline visibility.
4306 This function is the default value of the hook `org-cycle-hook'."
4307 (when (get-buffer-window (current-buffer))
4308 (cond
4309 ((eq state 'overview) (org-first-headline-recenter 1))
4310 ((eq state 'content) nil)
4311 ((eq state 'all) nil)
4312 ((eq state 'folded) nil)
4313 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4314 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4316 (defun org-subtree-end-visible-p ()
4317 "Is the end of the current subtree visible?"
4318 (pos-visible-in-window-p
4319 (save-excursion (org-end-of-subtree t) (point))))
4321 (defun org-first-headline-recenter (&optional N)
4322 "Move cursor to the first headline and recenter the headline.
4323 Optional argument N means, put the headline into the Nth line of the window."
4324 (goto-char (point-min))
4325 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4326 (beginning-of-line)
4327 (recenter (prefix-numeric-value N))))
4329 ;;; Org-goto
4331 (defvar org-goto-window-configuration nil)
4332 (defvar org-goto-marker nil)
4333 (defvar org-goto-map (make-sparse-keymap))
4334 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4335 (while (setq cmd (pop cmds))
4336 (substitute-key-definition cmd cmd org-goto-map global-map)))
4337 (define-key org-goto-map "\C-m" 'org-goto-ret)
4338 (define-key org-goto-map [(left)] 'org-goto-left)
4339 (define-key org-goto-map [(right)] 'org-goto-right)
4340 (define-key org-goto-map [(?q)] 'org-goto-quit)
4341 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
4342 (define-key org-goto-map "\C-i" 'org-cycle)
4343 (define-key org-goto-map [(tab)] 'org-cycle)
4344 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
4345 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
4346 (define-key org-goto-map "n" 'outline-next-visible-heading)
4347 (define-key org-goto-map "p" 'outline-previous-visible-heading)
4348 (define-key org-goto-map "f" 'outline-forward-same-level)
4349 (define-key org-goto-map "b" 'outline-backward-same-level)
4350 (define-key org-goto-map "u" 'outline-up-heading)
4351 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4352 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4353 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4354 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4355 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
4356 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4357 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
4359 (defconst org-goto-help
4360 "Select a location to jump to, press RET
4361 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4363 (defun org-goto ()
4364 "Go to a different location of the document, keeping current visibility.
4366 When you want to go to a different location in a document, the fastest way
4367 is often to fold the entire buffer and then dive into the tree. This
4368 method has the disadvantage, that the previous location will be folded,
4369 which may not be what you want.
4371 This command works around this by showing a copy of the current buffer in
4372 overview mode. You can dive into the tree in that copy, to find the
4373 location you want to reach. When pressing RET, the command returns to the
4374 original buffer in which the visibility is still unchanged. It then jumps
4375 to the new location, making it and the headline hierarchy above it visible."
4376 (interactive)
4377 (let* ((org-goto-start-pos (point))
4378 (selected-point
4379 (org-get-location (current-buffer) org-goto-help)))
4380 (if selected-point
4381 (progn
4382 (org-mark-ring-push org-goto-start-pos)
4383 (goto-char selected-point)
4384 (if (or (org-invisible-p) (org-invisible-p2))
4385 (org-show-context 'org-goto)))
4386 (error "Quit"))))
4388 (defvar org-selected-point nil) ; dynamically scoped parameter
4390 (defun org-get-location (buf help)
4391 "Let the user select a location in the Org-mode buffer BUF.
4392 This function uses a recursive edit. It returns the selected position
4393 or nil."
4394 (let (org-selected-point)
4395 (save-excursion
4396 (save-window-excursion
4397 (delete-other-windows)
4398 (switch-to-buffer (get-buffer-create "*org-goto*"))
4399 (with-output-to-temp-buffer "*Help*"
4400 (princ help))
4401 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4402 (setq buffer-read-only nil)
4403 (erase-buffer)
4404 (insert-buffer-substring buf)
4405 (let ((org-startup-truncated t)
4406 (org-startup-folded t)
4407 (org-startup-align-all-tables nil))
4408 (org-mode))
4409 (setq buffer-read-only t)
4410 (if (and (boundp 'org-goto-start-pos)
4411 (integer-or-marker-p org-goto-start-pos))
4412 (let ((org-show-hierarchy-above t)
4413 (org-show-siblings t)
4414 (org-show-following-heading t))
4415 (goto-char org-goto-start-pos)
4416 (and (org-invisible-p) (org-show-context)))
4417 (goto-char (point-min)))
4418 (org-beginning-of-line)
4419 (message "Select location and press RET")
4420 ;; now we make sure that during selection, ony very few keys work
4421 ;; and that it is impossible to switch to another window.
4422 (let ((gm (current-global-map))
4423 (overriding-local-map org-goto-map))
4424 (unwind-protect
4425 (progn
4426 (use-global-map org-goto-map)
4427 (recursive-edit))
4428 (use-global-map gm)))))
4429 (kill-buffer "*org-goto*")
4430 org-selected-point))
4432 (defun org-goto-ret (&optional arg)
4433 "Finish `org-goto' by going to the new location."
4434 (interactive "P")
4435 (setq org-selected-point (point)
4436 current-prefix-arg arg)
4437 (throw 'exit nil))
4439 (defun org-goto-left ()
4440 "Finish `org-goto' by going to the new location."
4441 (interactive)
4442 (if (org-on-heading-p)
4443 (progn
4444 (beginning-of-line 1)
4445 (setq org-selected-point (point)
4446 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4447 (throw 'exit nil))
4448 (error "Not on a heading")))
4450 (defun org-goto-right ()
4451 "Finish `org-goto' by going to the new location."
4452 (interactive)
4453 (if (org-on-heading-p)
4454 (progn
4455 (outline-end-of-subtree)
4456 (or (eobp) (forward-char 1))
4457 (setq org-selected-point (point)
4458 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4459 (throw 'exit nil))
4460 (error "Not on a heading")))
4462 (defun org-goto-quit ()
4463 "Finish `org-goto' without cursor motion."
4464 (interactive)
4465 (setq org-selected-point nil)
4466 (throw 'exit nil))
4468 ;;; Indirect buffer display of subtrees
4470 (defvar org-indirect-dedicated-frame nil
4471 "This is the frame being used for indirect tree display.")
4472 (defvar org-last-indirect-buffer nil)
4474 (defun org-tree-to-indirect-buffer (&optional arg)
4475 "Create indirect buffer and narrow it to current subtree.
4476 With numerical prefix ARG, go up to this level and then take that tree.
4477 If ARG is negative, go up that many levels.
4478 Normally this command removes the indirect buffer previously made
4479 with this command. However, when called with a C-u prefix, the last buffer
4480 is kept so that you can work with several indirect buffers at the same time.
4481 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4482 requests that a new frame be made for the new buffer, so that the dedicated
4483 frame is not changed."
4484 (interactive "P")
4485 (let ((cbuf (current-buffer))
4486 (cwin (selected-window))
4487 (pos (point))
4488 beg end level heading ibuf)
4489 (save-excursion
4490 (org-back-to-heading t)
4491 (when (numberp arg)
4492 (setq level (org-outline-level))
4493 (if (< arg 0) (setq arg (+ level arg)))
4494 (while (> (setq level (org-outline-level)) arg)
4495 (outline-up-heading 1 t)))
4496 (setq beg (point)
4497 heading (org-get-heading))
4498 (org-end-of-subtree t) (setq end (point)))
4499 (if (and (not arg)
4500 (buffer-live-p org-last-indirect-buffer))
4501 (kill-buffer org-last-indirect-buffer))
4502 (setq ibuf (org-get-indirect-buffer cbuf)
4503 org-last-indirect-buffer ibuf)
4504 (cond
4505 ((or (eq org-indirect-buffer-display 'new-frame)
4506 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4507 (select-frame (make-frame))
4508 (delete-other-windows)
4509 (switch-to-buffer ibuf)
4510 (org-set-frame-title heading))
4511 ((eq org-indirect-buffer-display 'dedicated-frame)
4512 (raise-frame
4513 (select-frame (or (and org-indirect-dedicated-frame
4514 (frame-live-p org-indirect-dedicated-frame)
4515 org-indirect-dedicated-frame)
4516 (setq org-indirect-dedicated-frame (make-frame)))))
4517 (delete-other-windows)
4518 (switch-to-buffer ibuf)
4519 (org-set-frame-title (concat "Indirect: " heading)))
4520 ((eq org-indirect-buffer-display 'current-window)
4521 (switch-to-buffer ibuf))
4522 ((eq org-indirect-buffer-display 'other-window)
4523 (pop-to-buffer ibuf))
4524 (t (error "Invalid value.")))
4525 (if (featurep 'xemacs)
4526 (save-excursion (org-mode) (turn-on-font-lock)))
4527 (narrow-to-region beg end)
4528 (show-all)
4529 (goto-char pos)
4530 (and (window-live-p cwin) (select-window cwin))))
4532 (defun org-get-indirect-buffer (&optional buffer)
4533 (setq buffer (or buffer (current-buffer)))
4534 (let ((n 1) (base (buffer-name buffer)) bname)
4535 (while (buffer-live-p
4536 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4537 (setq n (1+ n)))
4538 (condition-case nil
4539 (make-indirect-buffer buffer bname 'clone)
4540 (error (make-indirect-buffer buffer bname)))))
4542 (defun org-set-frame-title (title)
4543 "Set the title of the current frame to the string TITLE."
4544 ;; FIXME: how to name a single frame in XEmacs???
4545 (unless (featurep 'xemacs)
4546 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4548 ;;;; Structure editing
4550 ;;; Inserting headlines
4552 (defun org-insert-heading (&optional force-heading)
4553 "Insert a new heading or item with same depth at point.
4554 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4555 If point is at the beginning of a headline, insert a sibling before the
4556 current headline. If point is in the middle of a headline, split the headline
4557 at that position and make the rest of the headline part of the sibling below
4558 the current headline."
4559 (interactive "P")
4560 (if (= (buffer-size) 0)
4561 (insert "\n* ")
4562 (when (or force-heading (not (org-insert-item)))
4563 (let* ((head (save-excursion
4564 (condition-case nil
4565 (progn
4566 (org-back-to-heading)
4567 (match-string 0))
4568 (error "*"))))
4569 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4570 pos)
4571 (cond
4572 ((and (org-on-heading-p) (bolp)
4573 (or (bobp)
4574 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4575 (open-line (if blank 2 1)))
4576 ((and (bolp)
4577 (or (bobp)
4578 (save-excursion
4579 (backward-char 1) (not (org-invisible-p)))))
4580 nil)
4581 (t (newline (if blank 2 1))))
4582 (insert head) (just-one-space)
4583 (setq pos (point))
4584 (end-of-line 1)
4585 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4586 (run-hooks 'org-insert-heading-hook)))))
4589 (defun org-insert-todo-heading (arg)
4590 "Insert a new heading with the same level and TODO state as current heading.
4591 If the heading has no TODO state, or if the state is DONE, use the first
4592 state (TODO by default). Also with prefix arg, force first state."
4593 (interactive "P")
4594 (when (not (org-insert-item 'checkbox))
4595 (org-insert-heading)
4596 (save-excursion
4597 (org-back-to-heading)
4598 (outline-previous-heading)
4599 (looking-at org-todo-line-regexp))
4600 (if (or arg
4601 (not (match-beginning 2))
4602 (member (match-string 2) org-done-keywords))
4603 (insert (car org-todo-keywords-1) " ")
4604 (insert (match-string 2) " "))))
4606 ;;; Promotion and Demotion
4608 (defun org-promote-subtree ()
4609 "Promote the entire subtree.
4610 See also `org-promote'."
4611 (interactive)
4612 (save-excursion
4613 (org-map-tree 'org-promote))
4614 (org-fix-position-after-promote))
4616 (defun org-demote-subtree ()
4617 "Demote the entire subtree. See `org-demote'.
4618 See also `org-promote'."
4619 (interactive)
4620 (save-excursion
4621 (org-map-tree 'org-demote))
4622 (org-fix-position-after-promote))
4625 (defun org-do-promote ()
4626 "Promote the current heading higher up the tree.
4627 If the region is active in `transient-mark-mode', promote all headings
4628 in the region."
4629 (interactive)
4630 (save-excursion
4631 (if (org-region-active-p)
4632 (org-map-region 'org-promote (region-beginning) (region-end))
4633 (org-promote)))
4634 (org-fix-position-after-promote))
4636 (defun org-do-demote ()
4637 "Demote the current heading lower down the tree.
4638 If the region is active in `transient-mark-mode', demote all headings
4639 in the region."
4640 (interactive)
4641 (save-excursion
4642 (if (org-region-active-p)
4643 (org-map-region 'org-demote (region-beginning) (region-end))
4644 (org-demote)))
4645 (org-fix-position-after-promote))
4647 (defun org-fix-position-after-promote ()
4648 "Make sure that after pro/demotion cursor position is right."
4649 (let ((pos (point)))
4650 (when (save-excursion
4651 (beginning-of-line 1)
4652 (looking-at org-todo-line-regexp)
4653 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4654 (cond ((eobp) (insert " "))
4655 ((eolp) (insert " "))
4656 ((equal (char-after) ?\ ) (forward-char 1))))))
4658 (defun org-get-legal-level (level &optional change)
4659 "Rectify a level change under the influence of `org-odd-levels-only'
4660 LEVEL is a current level, CHANGE is by how much the level should be
4661 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4662 even level numbers will become the next higher odd number."
4663 (if org-odd-levels-only
4664 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4665 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4666 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4667 (max 1 (+ level change))))
4669 (defun org-promote ()
4670 "Promote the current heading higher up the tree.
4671 If the region is active in `transient-mark-mode', promote all headings
4672 in the region."
4673 (org-back-to-heading t)
4674 (let* ((level (save-match-data (funcall outline-level)))
4675 (up-head (make-string (org-get-legal-level level -1) ?*))
4676 (diff (abs (- level (length up-head)))))
4677 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4678 (replace-match up-head nil t)
4679 ;; Fixup tag positioning
4680 (and org-auto-align-tags (org-set-tags nil t))
4681 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4683 (defun org-demote ()
4684 "Demote the current heading lower down the tree.
4685 If the region is active in `transient-mark-mode', demote all headings
4686 in the region."
4687 (org-back-to-heading t)
4688 (let* ((level (save-match-data (funcall outline-level)))
4689 (down-head (make-string (org-get-legal-level level 1) ?*))
4690 (diff (abs (- level (length down-head)))))
4691 (replace-match down-head nil t)
4692 ;; Fixup tag positioning
4693 (and org-auto-align-tags (org-set-tags nil t))
4694 (if org-adapt-indentation (org-fixup-indentation diff))))
4696 (defun org-map-tree (fun)
4697 "Call FUN for every heading underneath the current one."
4698 (org-back-to-heading)
4699 (let ((level (funcall outline-level)))
4700 (save-excursion
4701 (funcall fun)
4702 (while (and (progn
4703 (outline-next-heading)
4704 (> (funcall outline-level) level))
4705 (not (eobp)))
4706 (funcall fun)))))
4708 (defun org-map-region (fun beg end)
4709 "Call FUN for every heading between BEG and END."
4710 (let ((org-ignore-region t))
4711 (save-excursion
4712 (setq end (copy-marker end))
4713 (goto-char beg)
4714 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4715 (< (point) end))
4716 (funcall fun))
4717 (while (and (progn
4718 (outline-next-heading)
4719 (< (point) end))
4720 (not (eobp)))
4721 (funcall fun)))))
4723 (defun org-fixup-indentation (diff)
4724 "Change the indentation in the current entry by DIFF
4725 However, if any line in the current entry has no indentation, or if it
4726 would end up with no indentation after the change, nothing at all is done."
4727 (save-excursion
4728 (let ((end (save-excursion (outline-next-heading)
4729 (point-marker)))
4730 (prohibit (if (> diff 0)
4731 "^\\S-"
4732 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4733 col)
4734 (unless (save-excursion (re-search-forward prohibit end t))
4735 (while (re-search-forward "^[ \t]+" end t)
4736 (goto-char (match-end 0))
4737 (setq col (current-column))
4738 (if (< diff 0) (replace-match ""))
4739 (indent-to (+ diff col))))
4740 (move-marker end nil))))
4742 (defun org-convert-to-odd-levels ()
4743 "Convert an org-mode file with all levels allowed to one with odd levels.
4744 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4745 level 5 etc."
4746 (interactive)
4747 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4748 (let ((org-odd-levels-only nil) n)
4749 (save-excursion
4750 (goto-char (point-min))
4751 (while (re-search-forward "^\\*\\*+" nil t)
4752 (setq n (1- (length (match-string 0))))
4753 (while (>= (setq n (1- n)) 0)
4754 (org-demote))
4755 (end-of-line 1))))))
4758 (defun org-convert-to-oddeven-levels ()
4759 "Convert an org-mode file with only odd levels to one with odd and even levels.
4760 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4761 section with an even level, conversion would destroy the structure of the file. An error
4762 is signaled in this case."
4763 (interactive)
4764 (goto-char (point-min))
4765 ;; First check if there are no even levels
4766 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
4767 (org-show-context t)
4768 (error "Not all levels are odd in this file. Conversion not possible."))
4769 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4770 (let ((org-odd-levels-only nil) n)
4771 (save-excursion
4772 (goto-char (point-min))
4773 (while (re-search-forward "^\\*\\*+" nil t)
4774 (setq n (/ (length (match-string 0)) 2))
4775 (while (>= (setq n (1- n)) 0)
4776 (org-promote))
4777 (end-of-line 1))))))
4779 (defun org-tr-level (n)
4780 "Make N odd if required."
4781 (if org-odd-levels-only (1+ (/ n 2)) n))
4783 ;;; Vertical tree motion, cutting and pasting of subtrees
4785 (defun org-move-subtree-up (&optional arg)
4786 "Move the current subtree up past ARG headlines of the same level."
4787 (interactive "p")
4788 (org-move-subtree-down (- (prefix-numeric-value arg))))
4790 (defun org-move-subtree-down (&optional arg)
4791 "Move the current subtree down past ARG headlines of the same level."
4792 (interactive "p")
4793 (setq arg (prefix-numeric-value arg))
4794 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4795 'outline-get-last-sibling))
4796 (ins-point (make-marker))
4797 (cnt (abs arg))
4798 beg end txt folded)
4799 ;; Select the tree
4800 (org-back-to-heading)
4801 (setq beg (point))
4802 (save-match-data
4803 (save-excursion (outline-end-of-heading)
4804 (setq folded (org-invisible-p)))
4805 (outline-end-of-subtree))
4806 (outline-next-heading)
4807 (setq end (point))
4808 ;; Find insertion point, with error handling
4809 (goto-char beg)
4810 (while (> cnt 0)
4811 (or (and (funcall movfunc) (looking-at outline-regexp))
4812 (progn (goto-char beg)
4813 (error "Cannot move past superior level or buffer limit")))
4814 (setq cnt (1- cnt)))
4815 (if (> arg 0)
4816 ;; Moving forward - still need to move over subtree
4817 (progn (outline-end-of-subtree)
4818 (outline-next-heading)
4819 (if (not (or (looking-at (concat "^" outline-regexp))
4820 (bolp)))
4821 (newline))))
4822 (move-marker ins-point (point))
4823 (setq txt (buffer-substring beg end))
4824 (delete-region beg end)
4825 (insert txt)
4826 (goto-char ins-point)
4827 (if folded (hide-subtree))
4828 (move-marker ins-point nil)))
4830 (defvar org-subtree-clip ""
4831 "Clipboard for cut and paste of subtrees.
4832 This is actually only a copy of the kill, because we use the normal kill
4833 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4835 (defvar org-subtree-clip-folded nil
4836 "Was the last copied subtree folded?
4837 This is used to fold the tree back after pasting.")
4839 (defun org-cut-subtree ()
4840 "Cut the current subtree into the clipboard.
4841 This is a short-hand for marking the subtree and then cutting it."
4842 (interactive)
4843 (org-copy-subtree 'cut))
4845 (defun org-copy-subtree (&optional cut)
4846 "Cut the current subtree into the clipboard.
4847 This is a short-hand for marking the subtree and then copying it.
4848 If CUT is non-nil, actually cut the subtree."
4849 (interactive)
4850 (let (beg end folded)
4851 (org-back-to-heading)
4852 (setq beg (point))
4853 (save-match-data
4854 (save-excursion (outline-end-of-heading)
4855 (setq folded (org-invisible-p)))
4856 (outline-end-of-subtree))
4857 (if (equal (char-after) ?\n) (forward-char 1))
4858 (setq end (point))
4859 (goto-char beg)
4860 (when (> end beg)
4861 (setq org-subtree-clip-folded folded)
4862 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4863 (setq org-subtree-clip (current-kill 0))
4864 (message "%s: Subtree with %d characters"
4865 (if cut "Cut" "Copied")
4866 (length org-subtree-clip)))))
4868 (defun org-paste-subtree (&optional level tree)
4869 "Paste the clipboard as a subtree, with modification of headline level.
4870 The entire subtree is promoted or demoted in order to match a new headline
4871 level. By default, the new level is derived from the visible headings
4872 before and after the insertion point, and taken to be the inferior headline
4873 level of the two. So if the previous visible heading is level 3 and the
4874 next is level 4 (or vice versa), level 4 will be used for insertion.
4875 This makes sure that the subtree remains an independent subtree and does
4876 not swallow low level entries.
4878 You can also force a different level, either by using a numeric prefix
4879 argument, or by inserting the heading marker by hand. For example, if the
4880 cursor is after \"*****\", then the tree will be shifted to level 5.
4882 If you want to insert the tree as is, just use \\[yank].
4884 If optional TREE is given, use this text instead of the kill ring."
4885 (interactive "P")
4886 (unless (org-kill-is-subtree-p tree)
4887 (error
4888 (substitute-command-keys
4889 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4890 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4891 (^re (concat "^\\(" outline-regexp "\\)"))
4892 (re (concat "\\(" outline-regexp "\\)"))
4893 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4895 (old-level (if (string-match ^re txt)
4896 (- (match-end 0) (match-beginning 0))
4897 -1))
4898 (force-level (cond (level (prefix-numeric-value level))
4899 ((string-match
4900 ^re_ (buffer-substring (point-at-bol) (point)))
4901 (- (match-end 0) (match-beginning 0)))
4902 (t nil)))
4903 (previous-level (save-excursion
4904 (condition-case nil
4905 (progn
4906 (outline-previous-visible-heading 1)
4907 (if (looking-at re)
4908 (- (match-end 0) (match-beginning 0))
4910 (error 1))))
4911 (next-level (save-excursion
4912 (condition-case nil
4913 (progn
4914 (outline-next-visible-heading 1)
4915 (if (looking-at re)
4916 (- (match-end 0) (match-beginning 0))
4918 (error 1))))
4919 (new-level (or force-level (max previous-level next-level)))
4920 (shift (if (or (= old-level -1)
4921 (= new-level -1)
4922 (= old-level new-level))
4924 (- new-level old-level)))
4925 (shift1 shift)
4926 (delta (if (> shift 0) -1 1))
4927 (func (if (> shift 0) 'org-demote 'org-promote))
4928 (org-odd-levels-only nil)
4929 beg end)
4930 ;; Remove the forces level indicator
4931 (if force-level
4932 (delete-region (point-at-bol) (point)))
4933 ;; Make sure we start at the beginning of an empty line
4934 (if (not (bolp)) (insert "\n"))
4935 (if (not (looking-at "[ \t]*$"))
4936 (progn (insert "\n") (backward-char 1)))
4937 ;; Paste
4938 (setq beg (point))
4939 (if (string-match "[ \t\r\n]+\\'" txt)
4940 (setq txt (replace-match "\n" t t txt)))
4941 (insert txt)
4942 (setq end (point))
4943 (if (looking-at "[ \t\r\n]+")
4944 (replace-match "\n"))
4945 (goto-char beg)
4946 ;; Shift if necessary
4947 (if (= shift 0)
4948 (message "Pasted at level %d, without shift" new-level)
4949 (save-restriction
4950 (narrow-to-region beg end)
4951 (while (not (= shift 0))
4952 (org-map-region func (point-min) (point-max))
4953 (setq shift (+ delta shift)))
4954 (goto-char (point-min))
4955 (message "Pasted at level %d, with shift by %d levels"
4956 new-level shift1)))
4957 (if (and kill-ring
4958 (eq org-subtree-clip (current-kill 0))
4959 org-subtree-clip-folded)
4960 ;; The tree was folded before it was killed/copied
4961 (hide-subtree))))
4963 (defun org-kill-is-subtree-p (&optional txt)
4964 "Check if the current kill is an outline subtree, or a set of trees.
4965 Returns nil if kill does not start with a headline, or if the first
4966 headline level is not the largest headline level in the tree.
4967 So this will actually accept several entries of equal levels as well,
4968 which is OK for `org-paste-subtree'.
4969 If optional TXT is given, check this string instead of the current kill."
4970 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4971 (start-level (and kill
4972 (string-match (concat "\\`" outline-regexp) kill)
4973 (- (match-end 0) (match-beginning 0))))
4974 (re (concat "^" outline-regexp))
4975 (start 1))
4976 (if (not start-level)
4977 nil ;; does not even start with a heading
4978 (catch 'exit
4979 (while (setq start (string-match re kill (1+ start)))
4980 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4981 (throw 'exit nil)))
4982 t))))
4984 (defun org-narrow-to-subtree ()
4985 "Narrow buffer to the current subtree."
4986 (interactive)
4987 (save-excursion
4988 (narrow-to-region
4989 (progn (org-back-to-heading) (point))
4990 (progn (org-end-of-subtree t) (point)))))
4993 ;;; Outline Sorting
4995 (defun org-sort (with-case)
4996 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
4997 (interactive "P")
4998 (if (org-at-table-p)
4999 (org-call-with-arg 'org-table-sort-lines with-case)
5000 (org-call-with-arg 'org-sort-entries with-case)))
5002 (defun org-sort-entries (&optional with-case sorting-type)
5003 "Sort entries on a certain level of an outline tree.
5004 If there is an active region, the entries in the region are sorted.
5005 Else, if the cursor is before the first entry, sort the top-level items.
5006 Else, the children of the entry at point are sorted.
5008 Sorting can be alphabetically, numerically, and by date/time as given by
5009 the first time stamp in the entry. The command prompts for the sorting
5010 type unless it has been given to the function through the SORTING-TYPE
5011 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
5013 Comparing entries ignores case by default. However, with an optional argument
5014 WITH-CASE, the sorting considers case as well. With two prefix arguments
5015 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
5016 (interactive "P")
5017 (let ((unique (equal with-case '(16)))
5018 start beg end entries stars re re2 p nentries (nremoved 0)
5019 last txt what)
5020 ;; Find beginning and end of region to sort
5021 (cond
5022 ((org-region-active-p)
5023 ;; we will sort the region
5024 (setq end (region-end)
5025 what "region")
5026 (goto-char (region-beginning))
5027 (if (not (org-on-heading-p)) (outline-next-heading))
5028 (setq start (point)))
5029 ((or (org-on-heading-p)
5030 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5031 ;; we will sort the children of the current headline
5032 (org-back-to-heading)
5033 (setq start (point) end (org-end-of-subtree) what "children")
5034 (goto-char start)
5035 (show-subtree)
5036 (outline-next-heading))
5038 ;; we will sort the top-level entries in this file
5039 (goto-char (point-min))
5040 (or (org-on-heading-p) (outline-next-heading))
5041 (setq start (point) end (point-max) what "top-level")
5042 (goto-char start)
5043 (show-all)))
5044 (setq beg (point))
5045 (if (>= (point) end) (error "Nothing to sort"))
5046 (looking-at "\\(\\*+\\)")
5047 (setq stars (match-string 1)
5048 re (concat "^" (regexp-quote stars) " +")
5049 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5050 txt (buffer-substring beg end))
5051 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5052 (if (and (not (equal stars "*")) (string-match re2 txt))
5053 (error "Region to sort contains a level above the first entry"))
5054 ;; Make a list that can be sorted.
5055 ;; The car is the string for comparison, the cdr is the subtree
5056 (message "Sorting entries...")
5057 (setq entries
5058 (mapcar
5059 (lambda (x)
5060 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
5061 (cons (match-string 0 x) x))
5062 (org-split-string txt re)))
5064 ;; Sort the list
5065 (save-excursion
5066 (goto-char start)
5067 (setq entries (org-do-sort entries what with-case sorting-type)))
5069 ;; Delete the old stuff
5070 (goto-char beg)
5071 (kill-region beg end)
5072 (setq nentries (length entries))
5073 ;; Insert the sorted entries, and remove duplicates if this is required
5074 (while (setq p (pop entries))
5075 (if (and unique (equal last (setq last (org-trim (cdr p)))))
5076 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
5077 (insert stars " " (cdr p))))
5078 (goto-char start)
5079 (message "Sorting entries...done (%d entries%s)"
5080 nentries
5081 (if unique (format ", %d duplicates removed" nremoved) ""))))
5083 (defun org-do-sort (table what &optional with-case sorting-type)
5084 "Sort TABLE of WHAT according to SORTING-TYPE.
5085 The user will be prompted for the SORTING-TYPE if the call to this
5086 function does not specify it. WHAT is only for the prompt, to indicate
5087 what is being sorted. The sorting key will be extracted from
5088 the car of the elements of the table.
5089 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5090 (unless sorting-type
5091 (message
5092 "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
5093 what)
5094 (setq sorting-type (read-char-exclusive)))
5095 (let ((dcst (downcase sorting-type))
5096 extractfun comparefun)
5097 ;; Define the appropriate functions
5098 (cond
5099 ((= dcst ?n)
5100 (setq extractfun 'string-to-number
5101 comparefun (if (= dcst sorting-type) '< '>)))
5102 ((= dcst ?a)
5103 (setq extractfun (if with-case 'identity 'downcase)
5104 comparefun (if (= dcst sorting-type)
5105 'string<
5106 (lambda (a b) (and (not (string< a b))
5107 (not (string= a b)))))))
5108 ((= dcst ?t)
5109 (setq extractfun
5110 (lambda (x)
5111 (if (string-match org-ts-regexp x)
5112 (time-to-seconds
5113 (org-time-string-to-time (match-string 0 x)))
5115 comparefun (if (= dcst sorting-type) '< '>)))
5116 (t (error "Invalid sorting type `%c'" sorting-type)))
5118 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5119 table)
5120 (lambda (a b) (funcall comparefun (car a) (car b))))))
5122 ;;;; Plain list items, including checkboxes
5124 ;;; Plain list items
5126 (defun org-at-item-p ()
5127 "Is point in a line starting a hand-formatted item?"
5128 (let ((llt org-plain-list-ordered-item-terminator))
5129 (save-excursion
5130 (goto-char (point-at-bol))
5131 (looking-at
5132 (cond
5133 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5134 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5135 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5136 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5139 (defun org-in-item-p ()
5140 "It the cursor inside a plain list item.
5141 Does not have to be the first line."
5142 (save-excursion
5143 (condition-case nil
5144 (progn
5145 (org-beginning-of-item)
5146 (org-at-item-p)
5148 (error nil))))
5150 (defun org-insert-item (&optional checkbox)
5151 "Insert a new item at the current level.
5152 Return t when things worked, nil when we are not in an item."
5153 (when (save-excursion
5154 (condition-case nil
5155 (progn
5156 (org-beginning-of-item)
5157 (org-at-item-p)
5158 (if (org-invisible-p) (error "Invisible item"))
5160 (error nil)))
5161 (let* ((bul (match-string 0))
5162 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5163 (match-end 0)))
5164 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5165 pos)
5166 (cond
5167 ((and (org-at-item-p) (<= (point) eow))
5168 ;; before the bullet
5169 (beginning-of-line 1)
5170 (open-line (if blank 2 1)))
5171 ((<= (point) eow)
5172 (beginning-of-line 1))
5173 (t (newline (if blank 2 1))))
5174 (insert bul (if checkbox "[ ]" ""))
5175 (just-one-space)
5176 (setq pos (point))
5177 (end-of-line 1)
5178 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5179 (org-maybe-renumber-ordered-list)
5180 (and checkbox (org-update-checkbox-count-maybe))
5183 ;;; Checkboxes
5185 (defun org-at-item-checkbox-p ()
5186 "Is point at a line starting a plain-list item with a checklet?"
5187 (and (org-at-item-p)
5188 (save-excursion
5189 (goto-char (match-end 0))
5190 (skip-chars-forward " \t")
5191 (looking-at "\\[[ X]\\]"))))
5193 (defun org-toggle-checkbox (&optional arg)
5194 "Toggle the checkbox in the current line."
5195 (interactive "P")
5196 (catch 'exit
5197 (let (beg end status (firstnew 'unknown))
5198 (cond
5199 ((org-region-active-p)
5200 (setq beg (region-beginning) end (region-end)))
5201 ((org-on-heading-p)
5202 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5203 ((org-at-item-checkbox-p)
5204 (save-excursion
5205 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
5206 (throw 'exit t))
5207 (t (error "Not at a checkbox or heading, and no active region")))
5208 (save-excursion
5209 (goto-char beg)
5210 (while (< (point) end)
5211 (when (org-at-item-checkbox-p)
5212 (setq status (equal (match-string 0) "[X]"))
5213 (when (eq firstnew 'unknown)
5214 (setq firstnew (not status)))
5215 (replace-match
5216 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5217 (beginning-of-line 2)))))
5218 (org-update-checkbox-count-maybe))
5220 (defun org-update-checkbox-count-maybe ()
5221 "Update checkbox statistics unless turned off by user."
5222 (when org-provide-checkbox-statistics
5223 (org-update-checkbox-count)))
5225 (defun org-update-checkbox-count (&optional all)
5226 "Update the checkbox statistics in the current section.
5227 This will find all statistic cookies like [57%] and [6/12] and update them
5228 with the current numbers. With optional prefix argument ALL, do this for
5229 the whole buffer."
5230 (interactive "P")
5231 (save-excursion
5232 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5233 (beg (progn (outline-back-to-heading) (point)))
5234 (end (move-marker (make-marker)
5235 (progn (outline-next-heading) (point))))
5236 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5237 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
5238 b1 e1 f1 c-on c-off lim (cstat 0))
5239 (when all
5240 (goto-char (point-min))
5241 (outline-next-heading)
5242 (setq beg (point) end (point-max)))
5243 (goto-char beg)
5244 (while (re-search-forward re end t)
5245 (setq cstat (1+ cstat)
5246 b1 (match-beginning 0)
5247 e1 (match-end 0)
5248 f1 (match-beginning 1)
5249 lim (cond
5250 ((org-on-heading-p) (outline-next-heading) (point))
5251 ((org-at-item-p) (org-end-of-item) (point))
5252 (t nil))
5253 c-on 0 c-off 0)
5254 (goto-char e1)
5255 (when lim
5256 (while (re-search-forward re-box lim t)
5257 (if (equal (match-string 2) "[ ]")
5258 (setq c-off (1+ c-off))
5259 (setq c-on (1+ c-on))))
5260 (delete-region b1 e1)
5261 (goto-char b1)
5262 (insert (if f1
5263 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5264 (format "[%d/%d]" c-on (+ c-on c-off))))))
5265 (when (interactive-p)
5266 (message "Checkbox satistics updated %s (%d places)"
5267 (if all "in entire file" "in current outline entry") cstat)))))
5269 (defun org-get-checkbox-statistics-face ()
5270 "Select the face for checkbox statistics.
5271 The face will be `org-done' when all relevant boxes are checked. Otherwise
5272 it will be `org-todo'."
5273 (if (match-end 1)
5274 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5275 (if (and (> (match-end 2) (match-beginning 2))
5276 (equal (match-string 2) (match-string 3)))
5277 'org-done
5278 'org-todo)))
5280 (defun org-get-indentation (&optional line)
5281 "Get the indentation of the current line, interpreting tabs.
5282 When LINE is given, assume it represents a line and compute its indentation."
5283 (if line
5284 (if (string-match "^ *" (org-remove-tabs line))
5285 (match-end 0))
5286 (save-excursion
5287 (beginning-of-line 1)
5288 (skip-chars-forward " \t")
5289 (current-column))))
5291 (defun org-remove-tabs (s &optional width)
5292 "Replace tabulators in S with spaces.
5293 Assumes that s is a single line, starting in column 0."
5294 (setq width (or width tab-width))
5295 (while (string-match "\t" s)
5296 (setq s (replace-match
5297 (make-string
5298 (- (* width (/ (+ (match-beginning 0) width) width))
5299 (match-beginning 0)) ?\ )
5300 t t s)))
5303 (defun org-fix-indentation (line ind)
5304 "Fix indentation in LINE.
5305 IND is a cons cell with target and minimum indentation.
5306 If the current indenation in LINE is smaller than the minimum,
5307 leave it alone. If it is larger than ind, set it to the target."
5308 (let* ((l (org-remove-tabs line))
5309 (i (org-get-indentation l))
5310 (i1 (car ind)) (i2 (cdr ind)))
5311 (if (>= i i2) (setq l (substring line i2)))
5312 (if (> i1 0)
5313 (concat (make-string i1 ?\ ) l)
5314 l)))
5316 (defcustom org-empty-line-terminates-plain-lists nil
5317 "Non-nil means, an empty line ends all plain list levels.
5318 When nil, empty lines are part of the preceeding item."
5319 :group 'org-plain-lists
5320 :type 'boolean)
5322 (defun org-beginning-of-item ()
5323 "Go to the beginning of the current hand-formatted item.
5324 If the cursor is not in an item, throw an error."
5325 (interactive)
5326 (let ((pos (point))
5327 (limit (save-excursion
5328 (condition-case nil
5329 (progn
5330 (org-back-to-heading)
5331 (beginning-of-line 2) (point))
5332 (error (point-min)))))
5333 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5334 ind ind1)
5335 (if (org-at-item-p)
5336 (beginning-of-line 1)
5337 (beginning-of-line 1)
5338 (skip-chars-forward " \t")
5339 (setq ind (current-column))
5340 (if (catch 'exit
5341 (while t
5342 (beginning-of-line 0)
5343 (if (< (point) limit) (throw 'exit nil))
5345 (if (looking-at "[ \t]*$")
5346 (setq ind1 ind-empty)
5347 (skip-chars-forward " \t")
5348 (setq ind1 (current-column)))
5349 (if (< ind1 ind)
5350 (throw 'exit (org-at-item-p)))))
5352 (goto-char pos)
5353 (error "Not in an item")))))
5355 (defun org-end-of-item ()
5356 "Go to the end of the current hand-formatted item.
5357 If the cursor is not in an item, throw an error."
5358 (interactive)
5359 (let* ((pos (point))
5360 ind1
5361 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5362 (limit (save-excursion (outline-next-heading) (point)))
5363 (ind (save-excursion
5364 (org-beginning-of-item)
5365 (skip-chars-forward " \t")
5366 (current-column)))
5367 (end (catch 'exit
5368 (while t
5369 (beginning-of-line 2)
5370 (if (eobp) (throw 'exit (point)))
5371 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5372 (if (looking-at "[ \t]*$")
5373 (setq ind1 ind-empty)
5374 (skip-chars-forward " \t")
5375 (setq ind1 (current-column)))
5376 (if (<= ind1 ind)
5377 (throw 'exit (point-at-bol)))))))
5378 (if end
5379 (goto-char end)
5380 (goto-char pos)
5381 (error "Not in an item"))))
5383 (defun org-next-item ()
5384 "Move to the beginning of the next item in the current plain list.
5385 Error if not at a plain list, or if this is the last item in the list."
5386 (interactive)
5387 (let (ind ind1 (pos (point)))
5388 (org-beginning-of-item)
5389 (setq ind (org-get-indentation))
5390 (org-end-of-item)
5391 (setq ind1 (org-get-indentation))
5392 (unless (and (org-at-item-p) (= ind ind1))
5393 (goto-char pos)
5394 (error "On last item"))))
5396 (defun org-previous-item ()
5397 "Move to the beginning of the previous item in the current plain list.
5398 Error if not at a plain list, or if this is the last item in the list."
5399 (interactive)
5400 (let (beg ind (pos (point)))
5401 (org-beginning-of-item)
5402 (setq beg (point))
5403 (setq ind (org-get-indentation))
5404 (goto-char beg)
5405 (catch 'exit
5406 (while t
5407 (beginning-of-line 0)
5408 (if (looking-at "[ \t]*$")
5410 (if (<= (org-get-indentation) ind)
5411 (throw 'exit t)))))
5412 (condition-case nil
5413 (org-beginning-of-item)
5414 (error (goto-char pos)
5415 (error "On first item")))))
5417 (defun org-move-item-down ()
5418 "Move the plain list item at point down, i.e. swap with following item.
5419 Subitems (items with larger indentation) are considered part of the item,
5420 so this really moves item trees."
5421 (interactive)
5422 (let (beg end ind ind1 (pos (point)) txt)
5423 (org-beginning-of-item)
5424 (setq beg (point))
5425 (setq ind (org-get-indentation))
5426 (org-end-of-item)
5427 (setq end (point))
5428 (setq ind1 (org-get-indentation))
5429 (if (and (org-at-item-p) (= ind ind1))
5430 (progn
5431 (org-end-of-item)
5432 (setq txt (buffer-substring beg end))
5433 (save-excursion
5434 (delete-region beg end))
5435 (setq pos (point))
5436 (insert txt)
5437 (goto-char pos)
5438 (org-maybe-renumber-ordered-list))
5439 (goto-char pos)
5440 (error "Cannot move this item further down"))))
5442 (defun org-move-item-up (arg)
5443 "Move the plain list item at point up, i.e. swap with previous item.
5444 Subitems (items with larger indentation) are considered part of the item,
5445 so this really moves item trees."
5446 (interactive "p")
5447 (let (beg end ind ind1 (pos (point)) txt)
5448 (org-beginning-of-item)
5449 (setq beg (point))
5450 (setq ind (org-get-indentation))
5451 (org-end-of-item)
5452 (setq end (point))
5453 (goto-char beg)
5454 (catch 'exit
5455 (while t
5456 (beginning-of-line 0)
5457 (if (looking-at "[ \t]*$")
5458 (if org-empty-line-terminates-plain-lists
5459 (progn
5460 (goto-char pos)
5461 (error "Cannot move this item further up"))
5462 nil)
5463 (if (<= (setq ind1 (org-get-indentation)) ind)
5464 (throw 'exit t)))))
5465 (condition-case nil
5466 (org-beginning-of-item)
5467 (error (goto-char beg)
5468 (error "Cannot move this item further up")))
5469 (setq ind1 (org-get-indentation))
5470 (if (and (org-at-item-p) (= ind ind1))
5471 (progn
5472 (setq txt (buffer-substring beg end))
5473 (save-excursion
5474 (delete-region beg end))
5475 (setq pos (point))
5476 (insert txt)
5477 (goto-char pos)
5478 (org-maybe-renumber-ordered-list))
5479 (goto-char pos)
5480 (error "Cannot move this item further up"))))
5482 (defun org-maybe-renumber-ordered-list ()
5483 "Renumber the ordered list at point if setup allows it.
5484 This tests the user option `org-auto-renumber-ordered-lists' before
5485 doing the renumbering."
5486 (and org-auto-renumber-ordered-lists
5487 (org-at-item-p)
5488 (match-beginning 3)
5489 (org-renumber-ordered-list 1)))
5491 (defun org-get-string-indentation (s)
5492 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5493 (let ((n -1) (i 0) (w tab-width) c)
5494 (catch 'exit
5495 (while (< (setq n (1+ n)) (length s))
5496 (setq c (aref s n))
5497 (cond ((= c ?\ ) (setq i (1+ i)))
5498 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5499 (t (throw 'exit t)))))
5502 (defun org-renumber-ordered-list (arg)
5503 "Renumber an ordered plain list.
5504 Cursor needs to be in the first line of an item, the line that starts
5505 with something like \"1.\" or \"2)\"."
5506 (interactive "p")
5507 (unless (and (org-at-item-p)
5508 (match-beginning 3))
5509 (error "This is not an ordered list"))
5510 (let ((line (org-current-line))
5511 (col (current-column))
5512 (ind (org-get-string-indentation
5513 (buffer-substring (point-at-bol) (match-beginning 3))))
5514 ;; (term (substring (match-string 3) -1))
5515 ind1 (n (1- arg)))
5516 ;; find where this list begins
5517 (catch 'exit
5518 (while t
5519 (catch 'next
5520 (beginning-of-line 0)
5521 (if (looking-at "[ \t]*$") (throw 'next t))
5522 (skip-chars-forward " \t") (setq ind1 (current-column))
5523 (if (or (< ind1 ind)
5524 (and (= ind1 ind)
5525 (not (org-at-item-p))))
5526 (throw 'exit t)))))
5527 ;; Walk forward and replace these numbers
5528 (catch 'exit
5529 (while t
5530 (catch 'next
5531 (beginning-of-line 2)
5532 (if (eobp) (throw 'exit nil))
5533 (if (looking-at "[ \t]*$") (throw 'next nil))
5534 (skip-chars-forward " \t") (setq ind1 (current-column))
5535 (if (> ind1 ind) (throw 'next t))
5536 (if (< ind1 ind) (throw 'exit t))
5537 (if (not (org-at-item-p)) (throw 'exit nil))
5538 (if (not (match-beginning 3))
5539 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
5540 (delete-region (match-beginning 3) (1- (match-end 3)))
5541 (goto-char (match-beginning 3))
5542 (insert (format "%d" (setq n (1+ n)))))))
5543 (goto-line line)
5544 (move-to-column col)))
5546 (defvar org-last-indent-begin-marker (make-marker))
5547 (defvar org-last-indent-end-marker (make-marker))
5549 (defun org-outdent-item (arg)
5550 "Outdent a local list item."
5551 (interactive "p")
5552 (org-indent-item (- arg)))
5554 (defun org-indent-item (arg)
5555 "Indent a local list item."
5556 (interactive "p")
5557 (unless (org-at-item-p)
5558 (error "Not on an item"))
5559 (save-excursion
5560 (let (beg end ind ind1)
5561 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5562 (setq beg org-last-indent-begin-marker
5563 end org-last-indent-end-marker)
5564 (org-beginning-of-item)
5565 (setq beg (move-marker org-last-indent-begin-marker (point)))
5566 (org-end-of-item)
5567 (setq end (move-marker org-last-indent-end-marker (point))))
5568 (goto-char beg)
5569 (skip-chars-forward " \t") (setq ind (current-column))
5570 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
5571 (while (< (point) end)
5572 (beginning-of-line 1)
5573 (skip-chars-forward " \t") (setq ind1 (current-column))
5574 (delete-region (point-at-bol) (point))
5575 (indent-to-column (+ ind1 arg))
5576 (beginning-of-line 2)))))
5578 ;;;; Archiving
5580 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
5582 (defun org-archive-subtree (&optional find-done)
5583 "Move the current subtree to the archive.
5584 The archive can be a certain top-level heading in the current file, or in
5585 a different file. The tree will be moved to that location, the subtree
5586 heading be marked DONE, and the current time will be added.
5588 When called with prefix argument FIND-DONE, find whole trees without any
5589 open TODO items and archive them (after getting confirmation from the user).
5590 If the cursor is not at a headline when this comand is called, try all level
5591 1 trees. If the cursor is on a headline, only try the direct children of
5592 this heading."
5593 (interactive "P")
5594 (if find-done
5595 (org-archive-all-done)
5596 ;; Save all relevant TODO keyword-relatex variables
5598 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5599 (tr-org-todo-keywords-1 org-todo-keywords-1)
5600 (tr-org-todo-kwd-alist org-todo-kwd-alist)
5601 (tr-org-done-keywords org-done-keywords)
5602 (tr-org-todo-regexp org-todo-regexp)
5603 (tr-org-todo-line-regexp org-todo-line-regexp)
5604 (tr-org-odd-levels-only org-odd-levels-only)
5605 (this-buffer (current-buffer))
5606 (org-archive-location org-archive-location)
5607 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
5608 file heading buffer level newfile-p)
5610 ;; Try to find a local archive location
5611 (save-excursion
5612 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
5613 (setq org-archive-location (match-string 1))))
5615 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5616 (progn
5617 (setq file (format (match-string 1 org-archive-location)
5618 (file-name-nondirectory buffer-file-name))
5619 heading (match-string 2 org-archive-location)))
5620 (error "Invalid `org-archive-location'"))
5621 (if (> (length file) 0)
5622 (setq newfile-p (not (file-exists-p file))
5623 buffer (find-file-noselect file))
5624 (setq buffer (current-buffer)))
5625 (unless buffer
5626 (error "Cannot access file \"%s\"" file))
5627 (if (and (> (length heading) 0)
5628 (string-match "^\\*+" heading))
5629 (setq level (match-end 0))
5630 (setq heading nil level 0))
5631 (save-excursion
5632 ;; We first only copy, in case something goes wrong
5633 ;; we need to protect this-command, to avoid kill-region sets it,
5634 ;; which would lead to duplication of subtrees
5635 (let (this-command) (org-copy-subtree))
5636 (set-buffer buffer)
5637 ;; Enforce org-mode for the archive buffer
5638 (if (not (org-mode-p))
5639 ;; Force the mode for future visits.
5640 (let ((org-insert-mode-line-in-empty-file t)
5641 (org-inhibit-startup t))
5642 (call-interactively 'org-mode)))
5643 (when newfile-p
5644 (goto-char (point-max))
5645 (insert (format "\nArchived entries from file %s\n\n"
5646 (buffer-file-name this-buffer))))
5647 ;; Force the TODO keywords of the original buffer
5648 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
5649 (org-todo-keywords-1 tr-org-todo-keywords-1)
5650 (org-todo-kwd-alist tr-org-todo-kwd-alist)
5651 (org-done-keywords tr-org-done-keywords)
5652 (org-todo-regexp tr-org-todo-regexp)
5653 (org-todo-line-regexp tr-org-todo-line-regexp)
5654 (org-odd-levels-only
5655 (if (local-variable-p 'org-odd-levels-only (current-buffer))
5656 org-odd-levels-only
5657 tr-org-odd-levels-only)))
5658 (goto-char (point-min))
5659 (if heading
5660 (progn
5661 (if (re-search-forward
5662 (concat "\\(^\\|\r\\)"
5663 (regexp-quote heading) "[ \t]*\\(:[a-zA-Z0-9_@:]+:\\)?[ \t]*\\($\\|\r\\)")
5664 nil t)
5665 (goto-char (match-end 0))
5666 ;; Heading not found, just insert it at the end
5667 (goto-char (point-max))
5668 (or (bolp) (insert "\n"))
5669 (insert "\n" heading "\n")
5670 (end-of-line 0))
5671 ;; Make the subtree visible
5672 (show-subtree)
5673 (org-end-of-subtree t)
5674 (skip-chars-backward " \t\r\n")
5675 (and (looking-at "[ \t\r\n]*")
5676 (replace-match "\n\n")))
5677 ;; No specific heading, just go to end of file.
5678 (goto-char (point-max)) (insert "\n"))
5679 ;; Paste
5680 (org-paste-subtree (org-get-legal-level level 1))
5681 ;; Mark the entry as done, i.e. set to last word in org-todo-keywords-1 FIXME: not right anymore!!!!!!!
5682 (if org-archive-mark-done
5683 (let (org-log-done)
5684 (org-todo (length org-todo-keywords-1))))
5685 ;; Move cursor to right after the TODO keyword
5686 (when org-archive-stamp-time
5687 (beginning-of-line 1)
5688 (looking-at org-todo-line-regexp)
5689 (goto-char (or (match-end 2) (match-beginning 3)))
5690 (org-insert-time-stamp (org-current-time) t t "(" ")"))
5691 ;; Save the buffer, if it is not the same buffer.
5692 (if (not (eq this-buffer buffer)) (save-buffer))))
5693 ;; Here we are back in the original buffer. Everything seems to have
5694 ;; worked. So now cut the tree and finish up.
5695 (let (this-command) (org-cut-subtree))
5696 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5697 (message "Subtree archived %s"
5698 (if (eq this-buffer buffer)
5699 (concat "under heading: " heading)
5700 (concat "in file: " (abbreviate-file-name file)))))))
5702 (defun org-archive-all-done (&optional tag)
5703 "Archive sublevels of the current tree without open TODO items.
5704 If the cursor is not on a headline, try all level 1 trees. If
5705 it is on a headline, try all direct children.
5706 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5707 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5708 (rea (concat ".*:" org-archive-tag ":"))
5709 (begm (make-marker))
5710 (endm (make-marker))
5711 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
5712 "Move subtree to archive (no open TODO items)? "))
5713 beg end (cntarch 0))
5714 (if (org-on-heading-p)
5715 (progn
5716 (setq re1 (concat "^" (regexp-quote
5717 (make-string
5718 (1+ (- (match-end 0) (match-beginning 0)))
5719 ?*))
5720 " "))
5721 (move-marker begm (point))
5722 (move-marker endm (org-end-of-subtree t)))
5723 (setq re1 "^* ")
5724 (move-marker begm (point-min))
5725 (move-marker endm (point-max)))
5726 (save-excursion
5727 (goto-char begm)
5728 (while (re-search-forward re1 endm t)
5729 (setq beg (match-beginning 0)
5730 end (save-excursion (org-end-of-subtree t) (point)))
5731 (goto-char beg)
5732 (if (re-search-forward re end t)
5733 (goto-char end)
5734 (goto-char beg)
5735 (if (and (or (not tag) (not (looking-at rea)))
5736 (y-or-n-p question))
5737 (progn
5738 (if tag
5739 (org-toggle-tag org-archive-tag 'on)
5740 (org-archive-subtree))
5741 (setq cntarch (1+ cntarch)))
5742 (goto-char end)))))
5743 (message "%d trees archived" cntarch)))
5745 (defun org-cycle-hide-archived-subtrees (state)
5746 "Re-hide all archived subtrees after a visibility state change."
5747 (when (and (not org-cycle-open-archived-trees)
5748 (not (memq state '(overview folded))))
5749 (save-excursion
5750 (let* ((globalp (memq state '(contents all)))
5751 (beg (if globalp (point-min) (point)))
5752 (end (if globalp (point-max) (org-end-of-subtree t))))
5753 (org-hide-archived-subtrees beg end)
5754 (goto-char beg)
5755 (if (looking-at (concat ".*:" org-archive-tag ":"))
5756 (message (substitute-command-keys
5757 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5759 (defun org-force-cycle-archived ()
5760 "Cycle subtree even if it is archived."
5761 (interactive)
5762 (setq this-command 'org-cycle)
5763 (let ((org-cycle-open-archived-trees t))
5764 (call-interactively 'org-cycle)))
5766 (defun org-hide-archived-subtrees (beg end)
5767 "Re-hide all archived subtrees after a visibility state change."
5768 (save-excursion
5769 (let* ((re (concat ":" org-archive-tag ":")))
5770 (goto-char beg)
5771 (while (re-search-forward re end t)
5772 (and (org-on-heading-p) (hide-subtree))
5773 (org-end-of-subtree t)))))
5775 (defun org-toggle-tag (tag &optional onoff)
5776 "Toggle the tag TAG for the current line.
5777 If ONOFF is `on' or `off', don't toggle but set to this state."
5778 (unless (org-on-heading-p t) (error "Not on headling"))
5779 (let (res current)
5780 (save-excursion
5781 (beginning-of-line)
5782 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5783 (point-at-eol) t)
5784 (progn
5785 (setq current (match-string 1))
5786 (replace-match ""))
5787 (setq current ""))
5788 (setq current (nreverse (org-split-string current ":")))
5789 (cond
5790 ((eq onoff 'on)
5791 (setq res t)
5792 (or (member tag current) (push tag current)))
5793 ((eq onoff 'off)
5794 (or (not (member tag current)) (setq current (delete tag current))))
5795 (t (if (member tag current)
5796 (setq current (delete tag current))
5797 (setq res t)
5798 (push tag current))))
5799 (end-of-line 1)
5800 (when current
5801 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5802 (org-set-tags nil t))
5803 res))
5805 (defun org-toggle-archive-tag (&optional arg)
5806 "Toggle the archive tag for the current headline.
5807 With prefix ARG, check all children of current headline and offer tagging
5808 the children that do not contain any open TODO items."
5809 (interactive "P")
5810 (if arg
5811 (org-archive-all-done 'tag)
5812 (let (set)
5813 (save-excursion
5814 (org-back-to-heading t)
5815 (setq set (org-toggle-tag org-archive-tag))
5816 (when set (hide-subtree)))
5817 (and set (beginning-of-line 1))
5818 (message "Subtree %s" (if set "archived" "unarchived")))))
5821 ;;;; Tables
5823 ;;; The table editor
5825 ;; Watch out: Here we are talking about two different kind of tables.
5826 ;; Most of the code is for the tables created with the Org-mode table editor.
5827 ;; Sometimes, we talk about tables created and edited with the table.el
5828 ;; Emacs package. We call the former org-type tables, and the latter
5829 ;; table.el-type tables.
5831 (defun org-before-change-function (beg end)
5832 "Every change indicates that a table might need an update."
5833 (setq org-table-may-need-update t))
5835 (defconst org-table-line-regexp "^[ \t]*|"
5836 "Detects an org-type table line.")
5837 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5838 "Detects an org-type table line.")
5839 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5840 "Detects a table line marked for automatic recalculation.")
5841 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5842 "Detects a table line marked for automatic recalculation.")
5843 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5844 "Detects a table line marked for automatic recalculation.")
5845 (defconst org-table-hline-regexp "^[ \t]*|-"
5846 "Detects an org-type table hline.")
5847 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5848 "Detects a table-type table hline.")
5849 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5850 "Detects an org-type or table-type table.")
5851 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5852 "Searching from within a table (any type) this finds the first line
5853 outside the table.")
5854 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5855 "Searching from within a table (any type) this finds the first line
5856 outside the table.")
5858 (defvar org-table-last-highlighted-reference nil)
5859 (defvar org-table-formula-history nil)
5861 (defvar org-table-column-names nil
5862 "Alist with column names, derived from the `!' line.")
5863 (defvar org-table-column-name-regexp nil
5864 "Regular expression matching the current column names.")
5865 (defvar org-table-local-parameters nil
5866 "Alist with parameter names, derived from the `$' line.")
5867 (defvar org-table-named-field-locations nil
5868 "Alist with locations of named fields.")
5870 (defvar org-table-current-line-types nil
5871 "Table row types, non-nil only for the duration of a comand.")
5872 (defvar org-table-current-begin-line nil
5873 "Table begin line, non-nil only for the duration of a comand.")
5874 (defvar org-table-current-begin-pos nil
5875 "Table begin position, non-nil only for the duration of a comand.")
5876 (defvar org-table-dlines nil
5877 "Vector of data line line numbers in the current table.")
5878 (defvar org-table-hlines nil
5879 "Vector of hline line numbers in the current table.")
5881 (defconst org-table-range-regexp
5882 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
5883 ;; 1 2 3 4 5
5884 "Regular expression for matching ranges in formulas.")
5886 (defconst org-table-range-regexp2
5887 (concat
5888 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
5889 "\\.\\."
5890 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
5891 "Match a range for reference display.")
5893 (defconst org-table-translate-regexp
5894 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
5895 "Match a reference that needs translation, for reference display.")
5897 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
5899 (defun org-table-create-with-table.el ()
5900 "Use the table.el package to insert a new table.
5901 If there is already a table at point, convert between Org-mode tables
5902 and table.el tables."
5903 (interactive)
5904 (require 'table)
5905 (cond
5906 ((org-at-table.el-p)
5907 (if (y-or-n-p "Convert table to Org-mode table? ")
5908 (org-table-convert)))
5909 ((org-at-table-p)
5910 (if (y-or-n-p "Convert table to table.el table? ")
5911 (org-table-convert)))
5912 (t (call-interactively 'table-insert))))
5914 (defun org-table-create-or-convert-from-region (arg)
5915 "Convert region to table, or create an empty table.
5916 If there is an active region, convert it to a table. If there is no such
5917 region, create an empty table."
5918 (interactive "P")
5919 (if (org-region-active-p)
5920 (org-table-convert-region (region-beginning) (region-end) arg)
5921 (org-table-create arg)))
5923 (defun org-table-create (&optional size)
5924 "Query for a size and insert a table skeleton.
5925 SIZE is a string Columns x Rows like for example \"3x2\"."
5926 (interactive "P")
5927 (unless size
5928 (setq size (read-string
5929 (concat "Table size Columns x Rows [e.g. "
5930 org-table-default-size "]: ")
5931 "" nil org-table-default-size)))
5933 (let* ((pos (point))
5934 (indent (make-string (current-column) ?\ ))
5935 (split (org-split-string size " *x *"))
5936 (rows (string-to-number (nth 1 split)))
5937 (columns (string-to-number (car split)))
5938 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5939 "\n")))
5940 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5941 (point-at-bol) (point)))
5942 (beginning-of-line 1)
5943 (newline))
5944 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5945 (dotimes (i rows) (insert line))
5946 (goto-char pos)
5947 (if (> rows 1)
5948 ;; Insert a hline after the first row.
5949 (progn
5950 (end-of-line 1)
5951 (insert "\n|-")
5952 (goto-char pos)))
5953 (org-table-align)))
5955 (defun org-table-convert-region (beg0 end0 &optional nspace)
5956 "Convert region to a table.
5957 The region goes from BEG0 to END0, but these borders will be moved
5958 slightly, to make sure a beginning of line in the first line is included.
5959 When NSPACE is non-nil, it indicates the minimum number of spaces that
5960 separate columns (default: just one space)."
5961 (interactive "rP")
5962 (let* ((beg (min beg0 end0))
5963 (end (max beg0 end0))
5964 (tabsep t)
5966 (goto-char beg)
5967 (beginning-of-line 1)
5968 (setq beg (move-marker (make-marker) (point)))
5969 (goto-char end)
5970 (if (bolp) (backward-char 1) (end-of-line 1))
5971 (setq end (move-marker (make-marker) (point)))
5972 ;; Lets see if this is tab-separated material. If every nonempty line
5973 ;; contains a tab, we will assume that it is tab-separated material
5974 (if nspace
5975 (setq tabsep nil)
5976 (goto-char beg)
5977 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5978 (if nspace (setq tabsep nil))
5979 (if tabsep
5980 (setq re "^\\|\t")
5981 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5982 (max 1 (prefix-numeric-value nspace)))))
5983 (goto-char beg)
5984 (while (re-search-forward re end t)
5985 (replace-match "| " t t))
5986 (goto-char beg)
5987 (insert " ")
5988 (org-table-align)))
5990 (defun org-table-import (file arg)
5991 "Import FILE as a table.
5992 The file is assumed to be tab-separated. Such files can be produced by most
5993 spreadsheet and database applications. If no tabs (at least one per line)
5994 are found, lines will be split on whitespace into fields."
5995 (interactive "f\nP")
5996 (or (bolp) (newline))
5997 (let ((beg (point))
5998 (pm (point-max)))
5999 (insert-file-contents file)
6000 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
6002 (defun org-table-export ()
6003 "Export table as a tab-separated file.
6004 Such a file can be imported into a spreadsheet program like Excel."
6005 (interactive)
6006 (let* ((beg (org-table-begin))
6007 (end (org-table-end))
6008 (table (buffer-substring beg end))
6009 (file (read-file-name "Export table to: "))
6010 buf)
6011 (unless (or (not (file-exists-p file))
6012 (y-or-n-p (format "Overwrite file %s? " file)))
6013 (error "Abort"))
6014 (with-current-buffer (find-file-noselect file)
6015 (setq buf (current-buffer))
6016 (erase-buffer)
6017 (fundamental-mode)
6018 (insert table)
6019 (goto-char (point-min))
6020 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6021 (replace-match "" t t)
6022 (end-of-line 1))
6023 (goto-char (point-min))
6024 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6025 (replace-match "" t t)
6026 (goto-char (min (1+ (point)) (point-max))))
6027 (goto-char (point-min))
6028 (while (re-search-forward "^-[-+]*$" nil t)
6029 (replace-match "")
6030 (if (looking-at "\n")
6031 (delete-char 1)))
6032 (goto-char (point-min))
6033 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6034 (replace-match "\t" t t))
6035 (save-buffer))
6036 (kill-buffer buf)))
6038 (defvar org-table-aligned-begin-marker (make-marker)
6039 "Marker at the beginning of the table last aligned.
6040 Used to check if cursor still is in that table, to minimize realignment.")
6041 (defvar org-table-aligned-end-marker (make-marker)
6042 "Marker at the end of the table last aligned.
6043 Used to check if cursor still is in that table, to minimize realignment.")
6044 (defvar org-table-last-alignment nil
6045 "List of flags for flushright alignment, from the last re-alignment.
6046 This is being used to correctly align a single field after TAB or RET.")
6047 (defvar org-table-last-column-widths nil
6048 "List of max width of fields in each column.
6049 This is being used to correctly align a single field after TAB or RET.")
6050 (defvar org-table-overlay-coordinates nil
6051 "Overlay coordinates after each align of a table.")
6052 (make-variable-buffer-local 'org-table-overlay-coordinates)
6054 (defvar org-last-recalc-line nil)
6055 (defconst org-narrow-column-arrow "=>"
6056 "Used as display property in narrowed table columns.")
6058 (defun org-table-align ()
6059 "Align the table at point by aligning all vertical bars."
6060 (interactive)
6061 (let* (
6062 ;; Limits of table
6063 (beg (org-table-begin))
6064 (end (org-table-end))
6065 ;; Current cursor position
6066 (linepos (org-current-line))
6067 (colpos (org-table-current-column))
6068 (winstart (window-start))
6069 (winstartline (org-current-line (min winstart (1- (point-max)))))
6070 lines (new "") lengths l typenums ty fields maxfields i
6071 column
6072 (indent "") cnt frac
6073 rfmt hfmt
6074 (spaces '(1 . 1))
6075 (sp1 (car spaces))
6076 (sp2 (cdr spaces))
6077 (rfmt1 (concat
6078 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6079 (hfmt1 (concat
6080 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6081 emptystrings links dates narrow fmax f1 len c e)
6082 (untabify beg end)
6083 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
6084 ;; Check if we have links or dates
6085 (goto-char beg)
6086 (setq links (re-search-forward org-bracket-link-regexp end t))
6087 (goto-char beg)
6088 (setq dates (and org-display-custom-times
6089 (re-search-forward org-ts-regexp-both end t)))
6090 ;; Make sure the link properties are right
6091 (when links (goto-char beg) (while (org-activate-bracket-links end)))
6092 ;; Make sure the date properties are right
6093 (when dates (goto-char beg) (while (org-activate-dates end)))
6095 ;; Check if we are narrowing any columns
6096 (goto-char beg)
6097 (setq narrow (and org-format-transports-properties-p
6098 (re-search-forward "<[0-9]+>" end t)))
6099 ;; Get the rows
6100 (setq lines (org-split-string
6101 (buffer-substring beg end) "\n"))
6102 ;; Store the indentation of the first line
6103 (if (string-match "^ *" (car lines))
6104 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6105 ;; Mark the hlines by setting the corresponding element to nil
6106 ;; At the same time, we remove trailing space.
6107 (setq lines (mapcar (lambda (l)
6108 (if (string-match "^ *|-" l)
6110 (if (string-match "[ \t]+$" l)
6111 (substring l 0 (match-beginning 0))
6112 l)))
6113 lines))
6114 ;; Get the data fields by splitting the lines.
6115 (setq fields (mapcar
6116 (lambda (l)
6117 (org-split-string l " *| *"))
6118 (delq nil (copy-sequence lines))))
6119 ;; How many fields in the longest line?
6120 (condition-case nil
6121 (setq maxfields (apply 'max (mapcar 'length fields)))
6122 (error
6123 (kill-region beg end)
6124 (org-table-create org-table-default-size)
6125 (error "Empty table - created default table")))
6126 ;; A list of empty strings to fill any short rows on output
6127 (setq emptystrings (make-list maxfields ""))
6128 ;; Check for special formatting.
6129 (setq i -1)
6130 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6131 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6132 ;; Check if there is an explicit width specified
6133 (when narrow
6134 (setq c column fmax nil)
6135 (while c
6136 (setq e (pop c))
6137 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
6138 (setq fmax (string-to-number (match-string 1 e)) c nil)))
6139 ;; Find fields that are wider than fmax, and shorten them
6140 (when fmax
6141 (loop for xx in column do
6142 (when (and (stringp xx)
6143 (> (org-string-width xx) fmax))
6144 (org-add-props xx nil
6145 'help-echo
6146 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
6147 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
6148 (unless (> f1 1)
6149 (error "Cannot narrow field starting with wide link \"%s\""
6150 (match-string 0 xx)))
6151 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
6152 (add-text-properties (- f1 2) f1
6153 (list 'display org-narrow-column-arrow)
6154 xx)))))
6155 ;; Get the maximum width for each column
6156 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
6157 ;; Get the fraction of numbers, to decide about alignment of the column
6158 (setq cnt 0 frac 0.0)
6159 (loop for x in column do
6160 (if (equal x "")
6162 (setq frac ( / (+ (* frac cnt)
6163 (if (string-match org-table-number-regexp x) 1 0))
6164 (setq cnt (1+ cnt))))))
6165 (push (>= frac org-table-number-fraction) typenums))
6166 (setq lengths (nreverse lengths) typenums (nreverse typenums))
6168 ;; Store the alignment of this table, for later editing of single fields
6169 (setq org-table-last-alignment typenums
6170 org-table-last-column-widths lengths)
6172 ;; With invisible characters, `format' does not get the field width right
6173 ;; So we need to make these fields wide by hand.
6174 (when links
6175 (loop for i from 0 upto (1- maxfields) do
6176 (setq len (nth i lengths))
6177 (loop for j from 0 upto (1- (length fields)) do
6178 (setq c (nthcdr i (car (nthcdr j fields))))
6179 (if (and (stringp (car c))
6180 (string-match org-bracket-link-regexp (car c))
6181 (< (org-string-width (car c)) len))
6182 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
6184 ;; Compute the formats needed for output of the table
6185 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6186 (while (setq l (pop lengths))
6187 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6188 (setq rfmt (concat rfmt (format rfmt1 ty l))
6189 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6190 (setq rfmt (concat rfmt "\n")
6191 hfmt (concat (substring hfmt 0 -1) "|\n"))
6193 (setq new (mapconcat
6194 (lambda (l)
6195 (if l (apply 'format rfmt
6196 (append (pop fields) emptystrings))
6197 hfmt))
6198 lines ""))
6199 ;; Replace the old one
6200 (delete-region beg end)
6201 (move-marker end nil)
6202 (move-marker org-table-aligned-begin-marker (point))
6203 (insert new)
6204 (move-marker org-table-aligned-end-marker (point))
6205 (when (and orgtbl-mode (not (org-mode-p)))
6206 (goto-char org-table-aligned-begin-marker)
6207 (while (org-hide-wide-columns org-table-aligned-end-marker)))
6208 ;; Try to move to the old location
6209 (goto-line winstartline)
6210 (setq winstart (point-at-bol))
6211 (goto-line linepos)
6212 (set-window-start (selected-window) winstart 'noforce)
6213 (org-table-goto-column colpos)
6214 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
6215 (setq org-table-may-need-update nil)
6218 (defun org-string-width (s)
6219 "Compute width of string, ignoring invisible characters.
6220 This ignores character with invisibility property `org-link', and also
6221 characters with property `org-cwidth', because these will become invisible
6222 upon the next fontification round."
6223 (let (b l)
6224 (when (or (eq t buffer-invisibility-spec)
6225 (assq 'org-link buffer-invisibility-spec))
6226 (while (setq b (text-property-any 0 (length s)
6227 'invisible 'org-link s))
6228 (setq s (concat (substring s 0 b)
6229 (substring s (or (next-single-property-change
6230 b 'invisible s) (length s)))))))
6231 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
6232 (setq s (concat (substring s 0 b)
6233 (substring s (or (next-single-property-change
6234 b 'org-cwidth s) (length s))))))
6235 (setq l (string-width s) b -1)
6236 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
6237 (setq l (- l (get-text-property b 'org-dwidth-n s))))
6240 (defun org-table-begin (&optional table-type)
6241 "Find the beginning of the table and return its position.
6242 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6243 (save-excursion
6244 (if (not (re-search-backward
6245 (if table-type org-table-any-border-regexp
6246 org-table-border-regexp)
6247 nil t))
6248 (progn (goto-char (point-min)) (point))
6249 (goto-char (match-beginning 0))
6250 (beginning-of-line 2)
6251 (point))))
6253 (defun org-table-end (&optional table-type)
6254 "Find the end of the table and return its position.
6255 With argument TABLE-TYPE, go to the end of a table.el-type table."
6256 (save-excursion
6257 (if (not (re-search-forward
6258 (if table-type org-table-any-border-regexp
6259 org-table-border-regexp)
6260 nil t))
6261 (goto-char (point-max))
6262 (goto-char (match-beginning 0)))
6263 (point-marker)))
6265 (defun org-table-justify-field-maybe (&optional new)
6266 "Justify the current field, text to left, number to right.
6267 Optional argument NEW may specify text to replace the current field content."
6268 (cond
6269 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6270 ((org-at-table-hline-p))
6271 ((and (not new)
6272 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6273 (current-buffer)))
6274 (< (point) org-table-aligned-begin-marker)
6275 (>= (point) org-table-aligned-end-marker)))
6276 ;; This is not the same table, force a full re-align
6277 (setq org-table-may-need-update t))
6278 (t ;; realign the current field, based on previous full realign
6279 (let* ((pos (point)) s
6280 (col (org-table-current-column))
6281 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
6282 l f n o e)
6283 (when (> col 0)
6284 (skip-chars-backward "^|\n")
6285 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6286 (progn
6287 (setq s (match-string 1)
6288 o (match-string 0)
6289 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6290 e (not (= (match-beginning 2) (match-end 2))))
6291 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6292 l (if e "|" (setq org-table-may-need-update t) ""))
6293 n (format f s))
6294 (if new
6295 (if (<= (length new) l) ;; FIXME: length -> str-width?
6296 (setq n (format f new))
6297 (setq n (concat new "|") org-table-may-need-update t)))
6298 (or (equal n o)
6299 (let (org-table-may-need-update)
6300 (replace-match n))))
6301 (setq org-table-may-need-update t))
6302 (goto-char pos))))))
6304 (defun org-table-next-field ()
6305 "Go to the next field in the current table, creating new lines as needed.
6306 Before doing so, re-align the table if necessary."
6307 (interactive)
6308 (org-table-maybe-eval-formula)
6309 (org-table-maybe-recalculate-line)
6310 (if (and org-table-automatic-realign
6311 org-table-may-need-update)
6312 (org-table-align))
6313 (let ((end (org-table-end)))
6314 (if (org-at-table-hline-p)
6315 (end-of-line 1))
6316 (condition-case nil
6317 (progn
6318 (re-search-forward "|" end)
6319 (if (looking-at "[ \t]*$")
6320 (re-search-forward "|" end))
6321 (if (and (looking-at "-")
6322 org-table-tab-jumps-over-hlines
6323 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
6324 (goto-char (match-beginning 1)))
6325 (if (looking-at "-")
6326 (progn
6327 (beginning-of-line 0)
6328 (org-table-insert-row 'below))
6329 (if (looking-at " ") (forward-char 1))))
6330 (error
6331 (org-table-insert-row 'below)))))
6333 (defun org-table-previous-field ()
6334 "Go to the previous field in the table.
6335 Before doing so, re-align the table if necessary."
6336 (interactive)
6337 (org-table-justify-field-maybe)
6338 (org-table-maybe-recalculate-line)
6339 (if (and org-table-automatic-realign
6340 org-table-may-need-update)
6341 (org-table-align))
6342 (if (org-at-table-hline-p)
6343 (end-of-line 1))
6344 (re-search-backward "|" (org-table-begin))
6345 (re-search-backward "|" (org-table-begin))
6346 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6347 (re-search-backward "|" (org-table-begin)))
6348 (if (looking-at "| ?")
6349 (goto-char (match-end 0))))
6351 (defun org-table-next-row ()
6352 "Go to the next row (same column) in the current table.
6353 Before doing so, re-align the table if necessary."
6354 (interactive)
6355 (org-table-maybe-eval-formula)
6356 (org-table-maybe-recalculate-line)
6357 (if (or (looking-at "[ \t]*$")
6358 (save-excursion (skip-chars-backward " \t") (bolp)))
6359 (newline)
6360 (if (and org-table-automatic-realign
6361 org-table-may-need-update)
6362 (org-table-align))
6363 (let ((col (org-table-current-column)))
6364 (beginning-of-line 2)
6365 (if (or (not (org-at-table-p))
6366 (org-at-table-hline-p))
6367 (progn
6368 (beginning-of-line 0)
6369 (org-table-insert-row 'below)))
6370 (org-table-goto-column col)
6371 (skip-chars-backward "^|\n\r")
6372 (if (looking-at " ") (forward-char 1)))))
6374 (defun org-table-copy-down (n)
6375 "Copy a field down in the current column.
6376 If the field at the cursor is empty, copy into it the content of the nearest
6377 non-empty field above. With argument N, use the Nth non-empty field.
6378 If the current field is not empty, it is copied down to the next row, and
6379 the cursor is moved with it. Therefore, repeating this command causes the
6380 column to be filled row-by-row.
6381 If the variable `org-table-copy-increment' is non-nil and the field is an
6382 integer, it will be incremented while copying."
6383 (interactive "p")
6384 (let* ((colpos (org-table-current-column))
6385 (field (org-table-get-field))
6386 (non-empty (string-match "[^ \t]" field))
6387 (beg (org-table-begin))
6388 txt)
6389 (org-table-check-inside-data-field)
6390 (if non-empty
6391 (progn
6392 (setq txt (org-trim field))
6393 (org-table-next-row)
6394 (org-table-blank-field))
6395 (save-excursion
6396 (setq txt
6397 (catch 'exit
6398 (while (progn (beginning-of-line 1)
6399 (re-search-backward org-table-dataline-regexp
6400 beg t))
6401 (org-table-goto-column colpos t)
6402 (if (and (looking-at
6403 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6404 (= (setq n (1- n)) 0))
6405 (throw 'exit (match-string 1))))))))
6406 (if txt
6407 (progn
6408 (if (and org-table-copy-increment
6409 (string-match "^[0-9]+$" txt))
6410 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6411 (insert txt)
6412 (org-table-maybe-recalculate-line)
6413 (org-table-align))
6414 (error "No non-empty field found"))))
6416 (defun org-table-check-inside-data-field ()
6417 "Is point inside a table data field?
6418 I.e. not on a hline or before the first or after the last column?
6419 This actually throws an error, so it aborts the current command."
6420 (if (or (not (org-at-table-p))
6421 (= (org-table-current-column) 0)
6422 (org-at-table-hline-p)
6423 (looking-at "[ \t]*$"))
6424 (error "Not in table data field")))
6426 (defvar org-table-clip nil
6427 "Clipboard for table regions.")
6429 (defun org-table-blank-field ()
6430 "Blank the current table field or active region."
6431 (interactive)
6432 (org-table-check-inside-data-field)
6433 (if (and (interactive-p) (org-region-active-p))
6434 (let (org-table-clip)
6435 (org-table-cut-region (region-beginning) (region-end)))
6436 (skip-chars-backward "^|")
6437 (backward-char 1)
6438 (if (looking-at "|[^|\n]+")
6439 (let* ((pos (match-beginning 0))
6440 (match (match-string 0))
6441 (len (org-string-width match)))
6442 (replace-match (concat "|" (make-string (1- len) ?\ )))
6443 (goto-char (+ 2 pos))
6444 (substring match 1)))))
6446 (defun org-table-get-field (&optional n replace)
6447 "Return the value of the field in column N of current row.
6448 N defaults to current field.
6449 If REPLACE is a string, replace field with this value. The return value
6450 is always the old value."
6451 (and n (org-table-goto-column n))
6452 (skip-chars-backward "^|\n")
6453 (backward-char 1)
6454 (if (looking-at "|[^|\r\n]*")
6455 (let* ((pos (match-beginning 0))
6456 (val (buffer-substring (1+ pos) (match-end 0))))
6457 (if replace
6458 (replace-match (concat "|" replace) t t))
6459 (goto-char (min (point-at-eol) (+ 2 pos)))
6460 val)
6461 (forward-char 1) ""))
6464 (defun org-table-field-info (arg)
6465 "Show info about the current field, and highlight any reference at point."
6466 (interactive "P")
6467 (org-table-get-specials)
6468 (save-excursion
6469 (let* ((pos (point))
6470 (col (org-table-current-column))
6471 (cname (car (rassoc (int-to-string col) org-table-column-names)))
6472 (name (car (rassoc (list (org-current-line) col)
6473 org-table-named-field-locations)))
6474 (eql (org-table-get-stored-formulas))
6475 (dline (org-table-current-dline))
6476 (ref (format "@%d$%d" dline col))
6477 (ref1 (org-table-convert-refs-to-an ref))
6478 (fequation (or (assoc name eql) (assoc ref eql)))
6479 (cequation (assoc (int-to-string col) eql))
6480 (eqn (or fequation cequation)))
6481 (goto-char pos)
6482 (condition-case nil
6483 (org-table-show-reference 'local)
6484 (error nil))
6485 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
6486 dline col
6487 (if cname (concat " or $" cname) "")
6488 dline col ref1
6489 (if name (concat " or $" name) "")
6490 ;; FIXME: formula info not correct if special table line
6491 (if eqn
6492 (concat ", formula: "
6493 (org-table-formula-to-user
6494 (concat
6495 (if (string-match "^[$@]"(car eqn)) "" "$")
6496 (car eqn) "=" (cdr eqn))))
6497 "")))))
6499 (defun org-table-current-column ()
6500 "Find out which column we are in.
6501 When called interactively, column is also displayed in echo area."
6502 (interactive)
6503 (if (interactive-p) (org-table-check-inside-data-field))
6504 (save-excursion
6505 (let ((cnt 0) (pos (point)))
6506 (beginning-of-line 1)
6507 (while (search-forward "|" pos t)
6508 (setq cnt (1+ cnt)))
6509 (if (interactive-p) (message "This is table column %d" cnt))
6510 cnt)))
6512 (defun org-table-current-dline ()
6513 "Find out what table data line we are in.
6514 Only datalins count for this."
6515 (interactive)
6516 (if (interactive-p) (org-table-check-inside-data-field))
6517 (save-excursion
6518 (let ((cnt 0) (pos (point)))
6519 (goto-char (org-table-begin))
6520 (while (<= (point) pos)
6521 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
6522 (beginning-of-line 2))
6523 (if (interactive-p) (message "This is table line %d" cnt))
6524 cnt)))
6526 (defun org-table-goto-column (n &optional on-delim force)
6527 "Move the cursor to the Nth column in the current table line.
6528 With optional argument ON-DELIM, stop with point before the left delimiter
6529 of the field.
6530 If there are less than N fields, just go to after the last delimiter.
6531 However, when FORCE is non-nil, create new columns if necessary."
6532 (interactive "p")
6533 (let ((pos (point-at-eol)))
6534 (beginning-of-line 1)
6535 (when (> n 0)
6536 (while (and (> (setq n (1- n)) -1)
6537 (or (search-forward "|" pos t)
6538 (and force
6539 (progn (end-of-line 1)
6540 (skip-chars-backward "^|")
6541 (insert " | "))))))
6542 ; (backward-char 2) t)))))
6543 (when (and force (not (looking-at ".*|")))
6544 (save-excursion (end-of-line 1) (insert " | ")))
6545 (if on-delim
6546 (backward-char 1)
6547 (if (looking-at " ") (forward-char 1))))))
6549 (defun org-at-table-p (&optional table-type)
6550 "Return t if the cursor is inside an org-type table.
6551 If TABLE-TYPE is non-nil, also check for table.el-type tables."
6552 (if org-enable-table-editor
6553 (save-excursion
6554 (beginning-of-line 1)
6555 (looking-at (if table-type org-table-any-line-regexp
6556 org-table-line-regexp)))
6557 nil))
6559 (defun org-at-table.el-p ()
6560 "Return t if and only if we are at a table.el table."
6561 (and (org-at-table-p 'any)
6562 (save-excursion
6563 (goto-char (org-table-begin 'any))
6564 (looking-at org-table1-hline-regexp))))
6566 (defun org-table-recognize-table.el ()
6567 "If there is a table.el table nearby, recognize it and move into it."
6568 (if org-table-tab-recognizes-table.el
6569 (if (org-at-table.el-p)
6570 (progn
6571 (beginning-of-line 1)
6572 (if (looking-at org-table-dataline-regexp)
6574 (if (looking-at org-table1-hline-regexp)
6575 (progn
6576 (beginning-of-line 2)
6577 (if (looking-at org-table-any-border-regexp)
6578 (beginning-of-line -1)))))
6579 (if (re-search-forward "|" (org-table-end t) t)
6580 (progn
6581 (require 'table)
6582 (if (table--at-cell-p (point))
6584 (message "recognizing table.el table...")
6585 (table-recognize-table)
6586 (message "recognizing table.el table...done")))
6587 (error "This should not happen..."))
6589 nil)
6590 nil))
6592 (defun org-at-table-hline-p ()
6593 "Return t if the cursor is inside a hline in a table."
6594 (if org-enable-table-editor
6595 (save-excursion
6596 (beginning-of-line 1)
6597 (looking-at org-table-hline-regexp))
6598 nil))
6600 (defun org-table-insert-column ()
6601 "Insert a new column into the table."
6602 (interactive)
6603 (if (not (org-at-table-p))
6604 (error "Not at a table"))
6605 (org-table-find-dataline)
6606 (let* ((col (max 1 (org-table-current-column)))
6607 (beg (org-table-begin))
6608 (end (org-table-end))
6609 ;; Current cursor position
6610 (linepos (org-current-line))
6611 (colpos col))
6612 (goto-char beg)
6613 (while (< (point) end)
6614 (if (org-at-table-hline-p)
6616 (org-table-goto-column col t)
6617 (insert "| "))
6618 (beginning-of-line 2))
6619 (move-marker end nil)
6620 (goto-line linepos)
6621 (org-table-goto-column colpos)
6622 (org-table-align)
6623 (org-table-fix-formulas "$" nil (1- col) 1)))
6625 (defun org-table-find-dataline ()
6626 "Find a dataline in the current table, which is needed for column commands."
6627 (if (and (org-at-table-p)
6628 (not (org-at-table-hline-p)))
6630 (let ((col (current-column))
6631 (end (org-table-end)))
6632 (move-to-column col)
6633 (while (and (< (point) end)
6634 (or (not (= (current-column) col))
6635 (org-at-table-hline-p)))
6636 (beginning-of-line 2)
6637 (move-to-column col))
6638 (if (and (org-at-table-p)
6639 (not (org-at-table-hline-p)))
6641 (error
6642 "Please position cursor in a data line for column operations")))))
6644 (defun org-table-delete-column ()
6645 "Delete a column from the table."
6646 (interactive)
6647 (if (not (org-at-table-p))
6648 (error "Not at a table"))
6649 (org-table-find-dataline)
6650 (org-table-check-inside-data-field)
6651 (let* ((col (org-table-current-column))
6652 (beg (org-table-begin))
6653 (end (org-table-end))
6654 ;; Current cursor position
6655 (linepos (org-current-line))
6656 (colpos col))
6657 (goto-char beg)
6658 (while (< (point) end)
6659 (if (org-at-table-hline-p)
6661 (org-table-goto-column col t)
6662 (and (looking-at "|[^|\n]+|")
6663 (replace-match "|")))
6664 (beginning-of-line 2))
6665 (move-marker end nil)
6666 (goto-line linepos)
6667 (org-table-goto-column colpos)
6668 (org-table-align)
6669 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
6670 col -1 col)))
6672 (defun org-table-move-column-right ()
6673 "Move column to the right."
6674 (interactive)
6675 (org-table-move-column nil))
6676 (defun org-table-move-column-left ()
6677 "Move column to the left."
6678 (interactive)
6679 (org-table-move-column 'left))
6681 (defun org-table-move-column (&optional left)
6682 "Move the current column to the right. With arg LEFT, move to the left."
6683 (interactive "P")
6684 (if (not (org-at-table-p))
6685 (error "Not at a table"))
6686 (org-table-find-dataline)
6687 (org-table-check-inside-data-field)
6688 (let* ((col (org-table-current-column))
6689 (col1 (if left (1- col) col))
6690 (beg (org-table-begin))
6691 (end (org-table-end))
6692 ;; Current cursor position
6693 (linepos (org-current-line))
6694 (colpos (if left (1- col) (1+ col))))
6695 (if (and left (= col 1))
6696 (error "Cannot move column further left"))
6697 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6698 (error "Cannot move column further right"))
6699 (goto-char beg)
6700 (while (< (point) end)
6701 (if (org-at-table-hline-p)
6703 (org-table-goto-column col1 t)
6704 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6705 (replace-match "|\\2|\\1|")))
6706 (beginning-of-line 2))
6707 (move-marker end nil)
6708 (goto-line linepos)
6709 (org-table-goto-column colpos)
6710 (org-table-align)
6711 (org-table-fix-formulas
6712 "$" (list (cons (number-to-string col) (number-to-string colpos))
6713 (cons (number-to-string colpos) (number-to-string col))))))
6715 (defun org-table-move-row-down ()
6716 "Move table row down."
6717 (interactive)
6718 (org-table-move-row nil))
6719 (defun org-table-move-row-up ()
6720 "Move table row up."
6721 (interactive)
6722 (org-table-move-row 'up))
6724 (defun org-table-move-row (&optional up)
6725 "Move the current table line down. With arg UP, move it up."
6726 (interactive "P")
6727 (let* ((col (current-column))
6728 (pos (point))
6729 (hline1p (save-excursion (beginning-of-line 1)
6730 (looking-at org-table-hline-regexp)))
6731 (dline1 (org-table-current-dline))
6732 (dline2 (+ dline1 (if up -1 1)))
6733 (tonew (if up 0 2))
6734 txt hline2p)
6735 (beginning-of-line tonew)
6736 (unless (org-at-table-p)
6737 (goto-char pos)
6738 (error "Cannot move row further"))
6739 (setq hline2p (looking-at org-table-hline-regexp))
6740 (goto-char pos)
6741 (beginning-of-line 1)
6742 (setq pos (point))
6743 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6744 (delete-region (point) (1+ (point-at-eol)))
6745 (beginning-of-line tonew)
6746 (insert txt)
6747 (beginning-of-line 0)
6748 (move-to-column col)
6749 (unless (or hline1p hline2p)
6750 (org-table-fix-formulas
6751 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
6752 (cons (number-to-string dline2) (number-to-string dline1)))))))
6754 (defun org-table-insert-row (&optional arg)
6755 "Insert a new row above the current line into the table.
6756 With prefix ARG, insert below the current line."
6757 (interactive "P")
6758 (if (not (org-at-table-p))
6759 (error "Not at a table"))
6760 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
6761 (new (org-table-clean-line line)))
6762 ;; Fix the first field if necessary
6763 (if (string-match "^[ \t]*| *[#$] *|" line)
6764 (setq new (replace-match (match-string 0 line) t t new)))
6765 (beginning-of-line (if arg 2 1))
6766 (let (org-table-may-need-update) (insert-before-markers new "\n"))
6767 (beginning-of-line 0)
6768 (re-search-forward "| ?" (point-at-eol) t)
6769 (and (or org-table-may-need-update org-table-overlay-coordinates)
6770 (org-table-align))
6771 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
6773 (defun org-table-insert-hline (&optional above)
6774 "Insert a horizontal-line below the current line into the table.
6775 With prefix ABOVE, insert above the current line."
6776 (interactive "P")
6777 (if (not (org-at-table-p))
6778 (error "Not at a table"))
6779 (let ((line (org-table-clean-line
6780 (buffer-substring (point-at-bol) (point-at-eol))))
6781 (col (current-column)))
6782 (while (string-match "|\\( +\\)|" line)
6783 (setq line (replace-match
6784 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
6785 ?-) "|") t t line)))
6786 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
6787 (beginning-of-line (if above 1 2))
6788 (insert line "\n")
6789 (beginning-of-line (if above 1 -1))
6790 (move-to-column col)
6791 (and org-table-overlay-coordinates (org-table-align))))
6793 (defun org-table-hline-and-move (&optional same-column)
6794 "Insert a hline and move to the row below that line."
6795 (interactive "P")
6796 (let ((col (org-table-current-column)))
6797 (org-table-maybe-eval-formula)
6798 (org-table-maybe-recalculate-line)
6799 (org-table-insert-hline)
6800 (end-of-line 2)
6801 (if (looking-at "\n[ \t]*|-")
6802 (progn (insert "\n|") (org-table-align))
6803 (org-table-next-field))
6804 (if same-column (org-table-goto-column col))))
6806 (defun org-table-clean-line (s)
6807 "Convert a table line S into a string with only \"|\" and space.
6808 In particular, this does handle wide and invisible characters."
6809 (if (string-match "^[ \t]*|-" s)
6810 ;; It's a hline, just map the characters
6811 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
6812 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
6813 (setq s (replace-match
6814 (concat "|" (make-string (org-string-width (match-string 1 s))
6815 ?\ ) "|")
6816 t t s)))
6819 (defun org-table-kill-row ()
6820 "Delete the current row or horizontal line from the table."
6821 (interactive)
6822 (if (not (org-at-table-p))
6823 (error "Not at a table"))
6824 (let ((col (current-column))
6825 (dline (org-table-current-dline)))
6826 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6827 (if (not (org-at-table-p)) (beginning-of-line 0))
6828 (move-to-column col)
6829 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
6830 dline -1 dline)))
6833 (defun org-table-sort-lines (with-case &optional sorting-type)
6834 "Sort table lines according to the column at point.
6836 The position of point indicates the column to be used for
6837 sorting, and the range of lines is the range between the nearest
6838 horizontal separator lines, or the entire table of no such lines
6839 exist. If point is before the first column, you will be prompted
6840 for the sorting column. If there is an active region, the mark
6841 specifies the first line and the sorting column, while point
6842 should be in the last line to be included into the sorting.
6844 The command then prompts for the sorting type which can be
6845 alphabetically, numerically, or by time (as given in a time stamp
6846 in the field). Sorting in reverse order is also possible.
6848 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
6850 If SORTING-TYPE is specified when this function is called from a Lisp
6851 program, no prompting will take place. SORTING-TYPE must be a character,
6852 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
6853 should be done in reverse order."
6854 (interactive "P")
6855 (let* ((thisline (org-current-line))
6856 (thiscol (org-table-current-column))
6857 beg end bcol ecol tend tbeg column lns pos)
6858 (when (equal thiscol 0)
6859 (if (interactive-p)
6860 (setq thiscol
6861 (string-to-number
6862 (read-string "Use column N for sorting: ")))
6863 (setq thiscol 1))
6864 (org-table-goto-column thiscol))
6865 (org-table-check-inside-data-field)
6866 (if (org-region-active-p)
6867 (progn
6868 (setq beg (region-beginning) end (region-end))
6869 (goto-char beg)
6870 (setq column (org-table-current-column)
6871 beg (point-at-bol))
6872 (goto-char end)
6873 (setq end (point-at-bol 2)))
6874 (setq column (org-table-current-column)
6875 pos (point)
6876 tbeg (org-table-begin)
6877 tend (org-table-end))
6878 (if (re-search-backward org-table-hline-regexp tbeg t)
6879 (setq beg (point-at-bol 2))
6880 (goto-char tbeg)
6881 (setq beg (point-at-bol 1)))
6882 (goto-char pos)
6883 (if (re-search-forward org-table-hline-regexp tend t)
6884 (setq beg (point-at-bol 0))
6885 (goto-char tend)
6886 (setq end (point-at-bol))))
6887 (setq beg (move-marker (make-marker) beg)
6888 end (move-marker (make-marker) end))
6889 (untabify beg end)
6890 (goto-char beg)
6891 (org-table-goto-column column)
6892 (skip-chars-backward "^|")
6893 (setq bcol (current-column))
6894 (org-table-goto-column (1+ column))
6895 (skip-chars-backward "^|")
6896 (setq ecol (1- (current-column)))
6897 (org-table-goto-column column)
6898 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
6899 (org-split-string (buffer-substring beg end) "\n")))
6900 (setq lns (org-do-sort lns "Table" with-case sorting-type))
6901 (delete-region beg end)
6902 (move-marker beg nil)
6903 (move-marker end nil)
6904 (insert (mapconcat 'cdr lns "\n") "\n")
6905 (goto-line thisline)
6906 (org-table-goto-column thiscol)
6907 (message "%d lines sorted, based on column %d" (length lns) column)))
6909 (defun org-table-cut-region (beg end)
6910 "Copy region in table to the clipboard and blank all relevant fields."
6911 (interactive "r")
6912 (org-table-copy-region beg end 'cut))
6914 (defun org-table-copy-region (beg end &optional cut)
6915 "Copy rectangular region in table to clipboard.
6916 A special clipboard is used which can only be accessed
6917 with `org-table-paste-rectangle'."
6918 (interactive "rP")
6919 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6920 region cols
6921 (rpl (if cut " " nil)))
6922 (goto-char beg)
6923 (org-table-check-inside-data-field)
6924 (setq l01 (org-current-line)
6925 c01 (org-table-current-column))
6926 (goto-char end)
6927 (org-table-check-inside-data-field)
6928 (setq l02 (org-current-line)
6929 c02 (org-table-current-column))
6930 (setq l1 (min l01 l02) l2 (max l01 l02)
6931 c1 (min c01 c02) c2 (max c01 c02))
6932 (catch 'exit
6933 (while t
6934 (catch 'nextline
6935 (if (> l1 l2) (throw 'exit t))
6936 (goto-line l1)
6937 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6938 (setq cols nil ic1 c1 ic2 c2)
6939 (while (< ic1 (1+ ic2))
6940 (push (org-table-get-field ic1 rpl) cols)
6941 (setq ic1 (1+ ic1)))
6942 (push (nreverse cols) region)
6943 (setq l1 (1+ l1)))))
6944 (setq org-table-clip (nreverse region))
6945 (if cut (org-table-align))
6946 org-table-clip))
6948 (defun org-table-paste-rectangle ()
6949 "Paste a rectangular region into a table.
6950 The upper right corner ends up in the current field. All involved fields
6951 will be overwritten. If the rectangle does not fit into the present table,
6952 the table is enlarged as needed. The process ignores horizontal separator
6953 lines."
6954 (interactive)
6955 (unless (and org-table-clip (listp org-table-clip))
6956 (error "First cut/copy a region to paste!"))
6957 (org-table-check-inside-data-field)
6958 (let* ((clip org-table-clip)
6959 (line (org-current-line))
6960 (col (org-table-current-column))
6961 (org-enable-table-editor t)
6962 (org-table-automatic-realign nil)
6963 c cols field)
6964 (while (setq cols (pop clip))
6965 (while (org-at-table-hline-p) (beginning-of-line 2))
6966 (if (not (org-at-table-p))
6967 (progn (end-of-line 0) (org-table-next-field)))
6968 (setq c col)
6969 (while (setq field (pop cols))
6970 (org-table-goto-column c nil 'force)
6971 (org-table-get-field nil field)
6972 (setq c (1+ c)))
6973 (beginning-of-line 2))
6974 (goto-line line)
6975 (org-table-goto-column col)
6976 (org-table-align)))
6978 (defun org-table-convert ()
6979 "Convert from `org-mode' table to table.el and back.
6980 Obviously, this only works within limits. When an Org-mode table is
6981 converted to table.el, all horizontal separator lines get lost, because
6982 table.el uses these as cell boundaries and has no notion of horizontal lines.
6983 A table.el table can be converted to an Org-mode table only if it does not
6984 do row or column spanning. Multiline cells will become multiple cells.
6985 Beware, Org-mode does not test if the table can be successfully converted - it
6986 blindly applies a recipe that works for simple tables."
6987 (interactive)
6988 (require 'table)
6989 (if (org-at-table.el-p)
6990 ;; convert to Org-mode table
6991 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6992 (end (move-marker (make-marker) (org-table-end t))))
6993 (table-unrecognize-region beg end)
6994 (goto-char beg)
6995 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6996 (replace-match ""))
6997 (goto-char beg))
6998 (if (org-at-table-p)
6999 ;; convert to table.el table
7000 (let ((beg (move-marker (make-marker) (org-table-begin)))
7001 (end (move-marker (make-marker) (org-table-end))))
7002 ;; first, get rid of all horizontal lines
7003 (goto-char beg)
7004 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
7005 (replace-match ""))
7006 ;; insert a hline before first
7007 (goto-char beg)
7008 (org-table-insert-hline 'above)
7009 (beginning-of-line -1)
7010 ;; insert a hline after each line
7011 (while (progn (beginning-of-line 3) (< (point) end))
7012 (org-table-insert-hline))
7013 (goto-char beg)
7014 (setq end (move-marker end (org-table-end)))
7015 ;; replace "+" at beginning and ending of hlines
7016 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
7017 (replace-match "\\1+-"))
7018 (goto-char beg)
7019 (while (re-search-forward "-|[ \t]*$" end t)
7020 (replace-match "-+"))
7021 (goto-char beg)))))
7023 (defun org-table-wrap-region (arg)
7024 "Wrap several fields in a column like a paragraph.
7025 This is useful if you'd like to spread the contents of a field over several
7026 lines, in order to keep the table compact.
7028 If there is an active region, and both point and mark are in the same column,
7029 the text in the column is wrapped to minimum width for the given number of
7030 lines. Generally, this makes the table more compact. A prefix ARG may be
7031 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
7032 formats the selected text to two lines. If the region was longer than two
7033 lines, the remaining lines remain empty. A negative prefix argument reduces
7034 the current number of lines by that amount. The wrapped text is pasted back
7035 into the table. If you formatted it to more lines than it was before, fields
7036 further down in the table get overwritten - so you might need to make space in
7037 the table first.
7039 If there is no region, the current field is split at the cursor position and
7040 the text fragment to the right of the cursor is prepended to the field one
7041 line down.
7043 If there is no region, but you specify a prefix ARG, the current field gets
7044 blank, and the content is appended to the field above."
7045 (interactive "P")
7046 (org-table-check-inside-data-field)
7047 (if (org-region-active-p)
7048 ;; There is a region: fill as a paragraph
7049 (let* ((beg (region-beginning))
7050 (cline (save-excursion (goto-char beg) (org-current-line)))
7051 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
7052 nlines)
7053 (org-table-cut-region (region-beginning) (region-end))
7054 (if (> (length (car org-table-clip)) 1)
7055 (error "Region must be limited to single column"))
7056 (setq nlines (if arg
7057 (if (< arg 1)
7058 (+ (length org-table-clip) arg)
7059 arg)
7060 (length org-table-clip)))
7061 (setq org-table-clip
7062 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
7063 nil nlines)))
7064 (goto-line cline)
7065 (org-table-goto-column ccol)
7066 (org-table-paste-rectangle))
7067 ;; No region, split the current field at point
7068 (if arg
7069 ;; combine with field above
7070 (let ((s (org-table-blank-field))
7071 (col (org-table-current-column)))
7072 (beginning-of-line 0)
7073 (while (org-at-table-hline-p) (beginning-of-line 0))
7074 (org-table-goto-column col)
7075 (skip-chars-forward "^|")
7076 (skip-chars-backward " ")
7077 (insert " " (org-trim s))
7078 (org-table-align))
7079 ;; split field
7080 (when (looking-at "\\([^|]+\\)+|")
7081 (let ((s (match-string 1)))
7082 (replace-match " |")
7083 (goto-char (match-beginning 0))
7084 (org-table-next-row)
7085 (insert (org-trim s) " ")
7086 (org-table-align))))))
7088 (defvar org-field-marker nil)
7090 (defun org-table-edit-field (arg)
7091 "Edit table field in a different window.
7092 This is mainly useful for fields that contain hidden parts.
7093 When called with a \\[universal-argument] prefix, just make the full field visible so that
7094 it can be edited in place."
7095 (interactive "P")
7096 (if arg
7097 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
7098 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
7099 (remove-text-properties b e '(org-cwidth t invisible t
7100 display t intangible t))
7101 (if (and (boundp 'font-lock-mode) font-lock-mode)
7102 (font-lock-fontify-block)))
7103 (let ((pos (move-marker (make-marker) (point)))
7104 (field (org-table-get-field))
7105 (cw (current-window-configuration))
7107 (switch-to-buffer-other-window "*Org tmp*")
7108 (erase-buffer)
7109 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
7110 (org-mode)
7111 (goto-char (setq p (point-max)))
7112 (insert (org-trim field))
7113 (remove-text-properties p (point-max)
7114 '(invisible t org-cwidth t display t
7115 intangible t))
7116 (goto-char p)
7117 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
7118 (org-set-local 'org-window-configuration cw)
7119 (org-set-local 'org-field-marker pos)
7120 (message "Edit and finish with C-c C-c"))))
7122 (defun org-table-finish-edit-field ()
7123 "Finish editing a table data field.
7124 Remove all newline characters, insert the result into the table, realign
7125 the table and kill the editing buffer."
7126 (let ((pos org-field-marker)
7127 (cw org-window-configuration)
7128 (cb (current-buffer))
7129 text)
7130 (goto-char (point-min))
7131 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
7132 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
7133 (replace-match " "))
7134 (setq text (org-trim (buffer-string)))
7135 (set-window-configuration cw)
7136 (kill-buffer cb)
7137 (select-window (get-buffer-window (marker-buffer pos)))
7138 (goto-char pos)
7139 (move-marker pos nil)
7140 (org-table-check-inside-data-field)
7141 (org-table-get-field nil text)
7142 (org-table-align)
7143 (message "New field value inserted")))
7145 (defun org-trim (s)
7146 "Remove whitespace at beginning and end of string."
7147 (if (string-match "^[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
7148 (if (string-match "[ \t\n\r]+$" s) (setq s (replace-match "" t t s)))
7151 (defun org-wrap (string &optional width lines)
7152 "Wrap string to either a number of lines, or a width in characters.
7153 If WIDTH is non-nil, the string is wrapped to that width, however many lines
7154 that costs. If there is a word longer than WIDTH, the text is actually
7155 wrapped to the length of that word.
7156 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
7157 many lines, whatever width that takes.
7158 The return value is a list of lines, without newlines at the end."
7159 (let* ((words (org-split-string string "[ \t\n]+"))
7160 (maxword (apply 'max (mapcar 'org-string-width words)))
7161 w ll)
7162 (cond (width
7163 (org-do-wrap words (max maxword width)))
7164 (lines
7165 (setq w maxword)
7166 (setq ll (org-do-wrap words maxword))
7167 (if (<= (length ll) lines)
7169 (setq ll words)
7170 (while (> (length ll) lines)
7171 (setq w (1+ w))
7172 (setq ll (org-do-wrap words w)))
7173 ll))
7174 (t (error "Cannot wrap this")))))
7177 (defun org-do-wrap (words width)
7178 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
7179 (let (lines line)
7180 (while words
7181 (setq line (pop words))
7182 (while (and words (< (+ (length line) (length (car words))) width))
7183 (setq line (concat line " " (pop words))))
7184 (setq lines (push line lines)))
7185 (nreverse lines)))
7187 (defun org-split-string (string &optional separators)
7188 "Splits STRING into substrings at SEPARATORS.
7189 No empty strings are returned if there are matches at the beginning
7190 and end of string."
7191 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
7192 (start 0)
7193 notfirst
7194 (list nil))
7195 (while (and (string-match rexp string
7196 (if (and notfirst
7197 (= start (match-beginning 0))
7198 (< start (length string)))
7199 (1+ start) start))
7200 (< (match-beginning 0) (length string)))
7201 (setq notfirst t)
7202 (or (eq (match-beginning 0) 0)
7203 (and (eq (match-beginning 0) (match-end 0))
7204 (eq (match-beginning 0) start))
7205 (setq list
7206 (cons (substring string start (match-beginning 0))
7207 list)))
7208 (setq start (match-end 0)))
7209 (or (eq start (length string))
7210 (setq list
7211 (cons (substring string start)
7212 list)))
7213 (nreverse list)))
7215 (defun org-table-map-tables (function)
7216 "Apply FUNCTION to the start of all tables in the buffer."
7217 (save-excursion
7218 (save-restriction
7219 (widen)
7220 (goto-char (point-min))
7221 (while (re-search-forward org-table-any-line-regexp nil t)
7222 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7223 (beginning-of-line 1)
7224 (if (looking-at org-table-line-regexp)
7225 (save-excursion (funcall function)))
7226 (re-search-forward org-table-any-border-regexp nil 1))))
7227 (message "Mapping tables: done"))
7229 (defvar org-timecnt) ; dynamically scoped parameter
7231 (defun org-table-sum (&optional beg end nlast)
7232 "Sum numbers in region of current table column.
7233 The result will be displayed in the echo area, and will be available
7234 as kill to be inserted with \\[yank].
7236 If there is an active region, it is interpreted as a rectangle and all
7237 numbers in that rectangle will be summed. If there is no active
7238 region and point is located in a table column, sum all numbers in that
7239 column.
7241 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7242 numbers are assumed to be times as well (in decimal hours) and the
7243 numbers are added as such.
7245 If NLAST is a number, only the NLAST fields will actually be summed."
7246 (interactive)
7247 (save-excursion
7248 (let (col (org-timecnt 0) diff h m s org-table-clip)
7249 (cond
7250 ((and beg end)) ; beg and end given explicitly
7251 ((org-region-active-p)
7252 (setq beg (region-beginning) end (region-end)))
7254 (setq col (org-table-current-column))
7255 (goto-char (org-table-begin))
7256 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7257 (error "No table data"))
7258 (org-table-goto-column col)
7259 (setq beg (point))
7260 (goto-char (org-table-end))
7261 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7262 (error "No table data"))
7263 (org-table-goto-column col)
7264 (setq end (point))))
7265 (let* ((items (apply 'append (org-table-copy-region beg end)))
7266 (items1 (cond ((not nlast) items)
7267 ((>= nlast (length items)) items)
7268 (t (setq items (reverse items))
7269 (setcdr (nthcdr (1- nlast) items) nil)
7270 (nreverse items))))
7271 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7272 items1)))
7273 (res (apply '+ numbers))
7274 (sres (if (= org-timecnt 0)
7275 (format "%g" res)
7276 (setq diff (* 3600 res)
7277 h (floor (/ diff 3600)) diff (mod diff 3600)
7278 m (floor (/ diff 60)) diff (mod diff 60)
7279 s diff)
7280 (format "%d:%02d:%02d" h m s))))
7281 (kill-new sres)
7282 (if (interactive-p)
7283 (message "%s"
7284 (substitute-command-keys
7285 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7286 (length numbers) sres))))
7287 sres))))
7289 (defun org-table-get-number-for-summing (s)
7290 (let (n)
7291 (if (string-match "^ *|? *" s)
7292 (setq s (replace-match "" nil nil s)))
7293 (if (string-match " *|? *$" s)
7294 (setq s (replace-match "" nil nil s)))
7295 (setq n (string-to-number s))
7296 (cond
7297 ((and (string-match "0" s)
7298 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7299 ((string-match "\\`[ \t]+\\'" s) nil)
7300 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7301 (let ((h (string-to-number (or (match-string 1 s) "0")))
7302 (m (string-to-number (or (match-string 2 s) "0")))
7303 (s (string-to-number (or (match-string 4 s) "0"))))
7304 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
7305 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7306 ((equal n 0) nil)
7307 (t n))))
7309 (defun org-table-current-field-formula (&optional key noerror)
7310 "Return the formula active for the current field.
7311 Assumes that specials are in place.
7312 If KEY is given, return the key to this formula.
7313 Otherwise return the formula preceeded with \"=\" or \":=\"."
7314 (let* ((name (car (rassoc (list (org-current-line)
7315 (org-table-current-column))
7316 org-table-named-field-locations)))
7317 (col (org-table-current-column))
7318 (scol (int-to-string col))
7319 (ref (format "@%d$%d" (org-table-current-dline) col))
7320 (stored-list (org-table-get-stored-formulas noerror))
7321 (ass (or (assoc name stored-list)
7322 (assoc ref stored-list)
7323 (assoc scol stored-list))))
7324 (if key
7325 (car ass)
7326 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
7327 (cdr ass))))))
7329 (defun org-table-get-formula (&optional equation named)
7330 "Read a formula from the minibuffer, offer stored formula as default.
7331 When NAMED is non-nil, look for a named equation."
7332 (let* ((stored-list (org-table-get-stored-formulas))
7333 (name (car (rassoc (list (org-current-line)
7334 (org-table-current-column))
7335 org-table-named-field-locations)))
7336 (ref (format "@%d$%d" (org-table-current-dline)
7337 (org-table-current-column)))
7338 (refass (assoc ref stored-list))
7339 (scol (if named
7340 (if name name ref)
7341 (int-to-string (org-table-current-column))))
7342 (dummy (and (or name refass) (not named)
7343 (not (y-or-n-p "Replace field formula with column formula? " ))
7344 (error "Abort")))
7345 (name (or name ref))
7346 (org-table-may-need-update nil)
7347 (stored (cdr (assoc scol stored-list)))
7348 (eq (cond
7349 ((and stored equation (string-match "^ *=? *$" equation))
7350 stored)
7351 ((stringp equation)
7352 equation)
7353 (t (org-table-formula-from-user
7354 (read-string
7355 (org-table-formula-to-user
7356 (format "%s formula %s%s="
7357 (if named "Field" "Column")
7358 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
7359 scol))
7360 (if stored (org-table-formula-to-user stored) "")
7361 'org-table-formula-history
7362 )))))
7363 mustsave)
7364 (when (not (string-match "\\S-" eq))
7365 ;; remove formula
7366 (setq stored-list (delq (assoc scol stored-list) stored-list))
7367 (org-table-store-formulas stored-list)
7368 (error "Formula removed"))
7369 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7370 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7371 (if (and name (not named))
7372 ;; We set the column equation, delete the named one.
7373 (setq stored-list (delq (assoc name stored-list) stored-list)
7374 mustsave t))
7375 (if stored
7376 (setcdr (assoc scol stored-list) eq)
7377 (setq stored-list (cons (cons scol eq) stored-list)))
7378 (if (or mustsave (not (equal stored eq)))
7379 (org-table-store-formulas stored-list))
7380 eq))
7382 (defun org-table-store-formulas (alist)
7383 "Store the list of formulas below the current table."
7384 (setq alist (sort alist 'org-table-formula-less-p))
7385 (save-excursion
7386 (goto-char (org-table-end))
7387 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
7388 (progn
7389 ;; don't overwrite TBLFM, we might use text properties to store stuff
7390 (goto-char (match-beginning 2))
7391 (delete-region (match-beginning 2) (match-end 0)))
7392 (insert "#+TBLFM:"))
7393 (insert " "
7394 (mapconcat (lambda (x)
7395 (concat
7396 (if (equal (string-to-char (car x)) ?@) "" "$")
7397 (car x) "=" (cdr x)))
7398 alist "::")
7399 "\n")))
7401 (defsubst org-table-formula-make-cmp-string (a)
7402 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
7403 (concat
7404 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
7405 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
7406 (if (match-end 5) (concat "@@" (match-string 5 a))))))
7408 (defun org-table-formula-less-p (a b)
7409 "Compare two formulas for sorting."
7410 (let ((as (org-table-formula-make-cmp-string (car a)))
7411 (bs (org-table-formula-make-cmp-string (car b))))
7412 (and as bs (string< as bs))))
7414 (defun org-table-get-stored-formulas (&optional noerror)
7415 "Return an alist with the stored formulas directly after current table."
7416 (interactive)
7417 (let (scol eq eq-alist strings string seen)
7418 (save-excursion
7419 (goto-char (org-table-end))
7420 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7421 (setq strings (org-split-string (match-string 2) " *:: *"))
7422 (while (setq string (pop strings))
7423 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
7424 (setq scol (if (match-end 2)
7425 (match-string 2 string)
7426 (match-string 1 string))
7427 eq (match-string 3 string)
7428 eq-alist (cons (cons scol eq) eq-alist))
7429 (if (member scol seen)
7430 (if noerror
7431 (progn
7432 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7433 (ding)
7434 (sit-for 2))
7435 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
7436 (push scol seen))))))
7437 (nreverse eq-alist)))
7439 (defun org-table-fix-formulas (key replace &optional limit delta remove)
7440 "Modify the equations after the table structure has been edited.
7441 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
7442 For all numbers larger than LIMIT, shift them by DELTA."
7443 (save-excursion
7444 (goto-char (org-table-end))
7445 (when (looking-at "#\\+TBLFM:")
7446 (let ((re (concat key "\\([0-9]+\\)"))
7447 (re2
7448 (when remove
7449 (if (equal key "$")
7450 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
7451 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
7452 s n a)
7453 (when remove
7454 (while (re-search-forward re2 (point-at-eol) t)
7455 (replace-match "")))
7456 (while (re-search-forward re (point-at-eol) t)
7457 (setq s (match-string 1) n (string-to-number s))
7458 (cond
7459 ((setq a (assoc s replace))
7460 (replace-match (concat key (cdr a)) t t))
7461 ((and limit (> n limit))
7462 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
7464 (defun org-table-get-specials ()
7465 "Get the column names and local parameters for this table."
7466 (save-excursion
7467 (let ((beg (org-table-begin)) (end (org-table-end))
7468 names name fields fields1 field cnt
7469 c v l line col types dlines hlines)
7470 (setq org-table-column-names nil
7471 org-table-local-parameters nil
7472 org-table-named-field-locations nil
7473 org-table-current-begin-line nil
7474 org-table-current-begin-pos nil
7475 org-table-current-line-types nil)
7476 (goto-char beg)
7477 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7478 (setq names (org-split-string (match-string 1) " *| *")
7479 cnt 1)
7480 (while (setq name (pop names))
7481 (setq cnt (1+ cnt))
7482 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7483 (push (cons name (int-to-string cnt)) org-table-column-names))))
7484 (setq org-table-column-names (nreverse org-table-column-names))
7485 (setq org-table-column-name-regexp
7486 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7487 (goto-char beg)
7488 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7489 (setq fields (org-split-string (match-string 1) " *| *"))
7490 (while (setq field (pop fields))
7491 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7492 (push (cons (match-string 1 field) (match-string 2 field))
7493 org-table-local-parameters))))
7494 (goto-char beg)
7495 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7496 (setq c (match-string 1)
7497 fields (org-split-string (match-string 2) " *| *"))
7498 (save-excursion
7499 (beginning-of-line (if (equal c "_") 2 0))
7500 (setq line (org-current-line) col 1)
7501 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7502 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7503 (while (and fields1 (setq field (pop fields)))
7504 (setq v (pop fields1) col (1+ col))
7505 (when (and (stringp field) (stringp v)
7506 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7507 (push (cons field v) org-table-local-parameters)
7508 (push (list field line col) org-table-named-field-locations))))
7509 ;; Analyse the line types
7510 (goto-char beg)
7511 (setq org-table-current-begin-line (org-current-line)
7512 org-table-current-begin-pos (point)
7513 l org-table-current-begin-line)
7514 (while (looking-at "[ \t]*|\\(-\\)?")
7515 (push (if (match-end 1) 'hline 'dline) types)
7516 (if (match-end 1) (push l hlines) (push l dlines))
7517 (beginning-of-line 2)
7518 (setq l (1+ l)))
7519 (setq org-table-current-line-types (apply 'vector (nreverse types))
7520 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
7521 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
7523 (defun org-table-maybe-eval-formula ()
7524 "Check if the current field starts with \"=\" or \":=\".
7525 If yes, store the formula and apply it."
7526 ;; We already know we are in a table. Get field will only return a formula
7527 ;; when appropriate. It might return a separator line, but no problem.
7528 (when org-table-formula-evaluate-inline
7529 (let* ((field (org-trim (or (org-table-get-field) "")))
7530 named eq)
7531 (when (string-match "^:?=\\(.*\\)" field)
7532 (setq named (equal (string-to-char field) ?:)
7533 eq (match-string 1 field))
7534 (if (or (fboundp 'calc-eval)
7535 (equal (substring eq 0 (min 2 (length eq))) "'("))
7536 (org-table-eval-formula (if named '(4) nil)
7537 (org-table-formula-from-user eq))
7538 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
7540 (defvar org-recalc-commands nil
7541 "List of commands triggering the recalculation of a line.
7542 Will be filled automatically during use.")
7544 (defvar org-recalc-marks
7545 '((" " . "Unmarked: no special line, no automatic recalculation")
7546 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7547 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7548 ("!" . "Column name definition line. Reference in formula as $name.")
7549 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7550 ("_" . "Names for values in row below this one.")
7551 ("^" . "Names for values in row above this one.")))
7553 (defun org-table-rotate-recalc-marks (&optional newchar)
7554 "Rotate the recalculation mark in the first column.
7555 If in any row, the first field is not consistent with a mark,
7556 insert a new column for the markers.
7557 When there is an active region, change all the lines in the region,
7558 after prompting for the marking character.
7559 After each change, a message will be displayed indicating the meaning
7560 of the new mark."
7561 (interactive)
7562 (unless (org-at-table-p) (error "Not at a table"))
7563 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7564 (beg (org-table-begin))
7565 (end (org-table-end))
7566 (l (org-current-line))
7567 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7568 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7569 (have-col
7570 (save-excursion
7571 (goto-char beg)
7572 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7573 (col (org-table-current-column))
7574 (forcenew (car (assoc newchar org-recalc-marks)))
7575 epos new)
7576 (when l1
7577 (message "Change region to what mark? Type # * ! $ or SPC: ")
7578 (setq newchar (char-to-string (read-char-exclusive))
7579 forcenew (car (assoc newchar org-recalc-marks))))
7580 (if (and newchar (not forcenew))
7581 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7582 newchar))
7583 (if l1 (goto-line l1))
7584 (save-excursion
7585 (beginning-of-line 1)
7586 (unless (looking-at org-table-dataline-regexp)
7587 (error "Not at a table data line")))
7588 (unless have-col
7589 (org-table-goto-column 1)
7590 (org-table-insert-column)
7591 (org-table-goto-column (1+ col)))
7592 (setq epos (point-at-eol))
7593 (save-excursion
7594 (beginning-of-line 1)
7595 (org-table-get-field
7596 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7597 (concat " "
7598 (setq new (or forcenew
7599 (cadr (member (match-string 1) marks))))
7600 " ")
7601 " # ")))
7602 (if (and l1 l2)
7603 (progn
7604 (goto-line l1)
7605 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7606 (and (looking-at org-table-dataline-regexp)
7607 (org-table-get-field 1 (concat " " new " "))))
7608 (goto-line l1)))
7609 (if (not (= epos (point-at-eol))) (org-table-align))
7610 (goto-line l)
7611 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7613 (defun org-table-maybe-recalculate-line ()
7614 "Recompute the current line if marked for it, and if we haven't just done it."
7615 (interactive)
7616 (and org-table-allow-automatic-line-recalculation
7617 (not (and (memq last-command org-recalc-commands)
7618 (equal org-last-recalc-line (org-current-line))))
7619 (save-excursion (beginning-of-line 1)
7620 (looking-at org-table-auto-recalculate-regexp))
7621 (org-table-recalculate) t))
7623 (defvar org-table-formula-debug nil
7624 "Non-nil means, debug table formulas.
7625 When nil, simply write \"#ERROR\" in corrupted fields.")
7626 (make-variable-buffer-local 'org-table-formula-debug)
7628 (defvar modes)
7629 (defsubst org-set-calc-mode (var &optional value)
7630 (if (stringp var)
7631 (setq var (assoc var '(("D" calc-angle-mode deg)
7632 ("R" calc-angle-mode rad)
7633 ("F" calc-prefer-frac t)
7634 ("S" calc-symbolic-mode t)))
7635 value (nth 2 var) var (nth 1 var)))
7636 (if (memq var modes)
7637 (setcar (cdr (memq var modes)) value)
7638 (cons var (cons value modes)))
7639 modes)
7641 (defun org-table-eval-formula (&optional arg equation
7642 suppress-align suppress-const
7643 suppress-store suppress-analysis)
7644 "Replace the table field value at the cursor by the result of a calculation.
7646 This function makes use of Dave Gillespie's Calc package, in my view the
7647 most exciting program ever written for GNU Emacs. So you need to have Calc
7648 installed in order to use this function.
7650 In a table, this command replaces the value in the current field with the
7651 result of a formula. It also installs the formula as the \"current\" column
7652 formula, by storing it in a special line below the table. When called
7653 with a `C-u' prefix, the current field must ba a named field, and the
7654 formula is installed as valid in only this specific field.
7656 When called with two `C-u' prefixes, insert the active equation
7657 for the field back into the current field, so that it can be
7658 edited there. This is useful in order to use \\[org-table-show-reference]
7659 to check the referenced fields.
7661 When called, the command first prompts for a formula, which is read in
7662 the minibuffer. Previously entered formulas are available through the
7663 history list, and the last used formula is offered as a default.
7664 These stored formulas are adapted correctly when moving, inserting, or
7665 deleting columns with the corresponding commands.
7667 The formula can be any algebraic expression understood by the Calc package.
7668 For details, see the Org-mode manual.
7670 This function can also be called from Lisp programs and offers
7671 additional arguments: EQUATION can be the formula to apply. If this
7672 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7673 used to speed-up recursive calls by by-passing unnecessary aligns.
7674 SUPPRESS-CONST suppresses the interpretation of constants in the
7675 formula, assuming that this has been done already outside the function.
7676 SUPPRESS-STORE means the formula should not be stored, either because
7677 it is already stored, or because it is a modified equation that should
7678 not overwrite the stored one."
7679 (interactive "P")
7680 (org-table-check-inside-data-field)
7681 (or suppress-analysis (org-table-get-specials))
7682 (if (equal arg '(16))
7683 (let ((eq (org-table-current-field-formula)))
7684 (or eq (error "No equation active for current field"))
7685 (org-table-get-field nil eq)
7686 (org-table-align)
7687 (setq org-table-may-need-update t))
7688 (let* (fields
7689 (ndown (if (integerp arg) arg 1))
7690 (org-table-automatic-realign nil)
7691 (case-fold-search nil)
7692 (down (> ndown 1))
7693 (formula (if (and equation suppress-store)
7694 equation
7695 (org-table-get-formula equation (equal arg '(4)))))
7696 (n0 (org-table-current-column))
7697 (modes (copy-sequence org-calc-default-modes))
7698 (numbers nil) ; was a variable, now fixed default
7699 (keep-empty nil)
7700 n form form0 bw fmt x ev orig c lispp)
7701 ;; Parse the format string. Since we have a lot of modes, this is
7702 ;; a lot of work. However, I think calc still uses most of the time.
7703 (if (string-match ";" formula)
7704 (let ((tmp (org-split-string formula ";")))
7705 (setq formula (car tmp)
7706 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7707 (nth 1 tmp)))
7708 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
7709 (setq c (string-to-char (match-string 1 fmt))
7710 n (string-to-number (match-string 2 fmt)))
7711 (if (= c ?p)
7712 (setq modes (org-set-calc-mode 'calc-internal-prec n))
7713 (setq modes (org-set-calc-mode
7714 'calc-float-format
7715 (list (cdr (assoc c '((?n . float) (?f . fix)
7716 (?s . sci) (?e . eng))))
7717 n))))
7718 (setq fmt (replace-match "" t t fmt)))
7719 (if (string-match "[NT]" fmt)
7720 (setq numbers (equal (match-string 0 fmt) "N")
7721 fmt (replace-match "" t t fmt)))
7722 (if (string-match "E" fmt)
7723 (setq keep-empty t
7724 fmt (replace-match "" t t fmt)))
7725 (while (string-match "[DRFS]" fmt)
7726 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7727 (setq fmt (replace-match "" t t fmt)))
7728 (unless (string-match "\\S-" fmt)
7729 (setq fmt nil))))
7730 (if (and (not suppress-const) org-table-formula-use-constants)
7731 (setq formula (org-table-formula-substitute-names formula)))
7732 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7733 (while (> ndown 0)
7734 (setq fields (org-split-string
7735 (org-no-properties
7736 (buffer-substring (point-at-bol) (point-at-eol)))
7737 " *| *"))
7738 (if numbers
7739 (setq fields (mapcar
7740 (lambda (x) (number-to-string (string-to-number x)))
7741 fields)))
7742 (setq ndown (1- ndown))
7743 (setq form (copy-sequence formula)
7744 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
7745 ;; Check for old vertical references
7746 (setq form (org-rewrite-old-row-references form))
7747 ;; Insert complex ranges
7748 (while (string-match org-table-range-regexp form)
7749 (setq form
7750 (replace-match
7751 (save-match-data
7752 (org-table-make-reference
7753 (org-table-get-range (match-string 0 form) nil n0)
7754 keep-empty numbers lispp))
7755 t t form)))
7756 ;; Insert simple ranges
7757 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
7758 (setq form
7759 (replace-match
7760 (save-match-data
7761 (org-table-make-reference
7762 (org-sublist
7763 fields (string-to-number (match-string 1 form))
7764 (string-to-number (match-string 2 form)))
7765 keep-empty numbers lispp))
7766 t t form)))
7767 (setq form0 form)
7768 ;; Insert the references to fields in same row
7769 (while (string-match "\\$\\([0-9]+\\)" form)
7770 (setq n (string-to-number (match-string 1 form))
7771 x (nth (1- (if (= n 0) n0 n)) fields))
7772 (unless x (error "Invalid field specifier \"%s\""
7773 (match-string 0 form)))
7774 (setq form (replace-match
7775 (save-match-data
7776 (org-table-make-reference x nil numbers lispp))
7777 t t form)))
7779 (if lispp
7780 (setq ev (condition-case nil
7781 (eval (eval (read form)))
7782 (error "#ERROR"))
7783 ev (if (numberp ev) (number-to-string ev) ev))
7784 (or (fboundp 'calc-eval)
7785 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
7786 (setq ev (calc-eval (cons form modes)
7787 (if numbers 'num))))
7789 (when org-table-formula-debug
7790 (with-output-to-temp-buffer "*Substitution History*"
7791 (princ (format "Substitution history of formula
7792 Orig: %s
7793 $xyz-> %s
7794 @r$c-> %s
7795 $1-> %s\n" orig formula form0 form))
7796 (if (listp ev)
7797 (princ (format " %s^\nError: %s"
7798 (make-string (car ev) ?\-) (nth 1 ev)))
7799 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7800 ev (or fmt "NONE")
7801 (if fmt (format fmt (string-to-number ev)) ev)))))
7802 (setq bw (get-buffer-window "*Substitution History*"))
7803 (shrink-window-if-larger-than-buffer bw)
7804 (unless (and (interactive-p) (not ndown))
7805 (unless (let (inhibit-redisplay)
7806 (y-or-n-p "Debugging Formula. Continue to next? "))
7807 (org-table-align)
7808 (error "Abort"))
7809 (delete-window bw)
7810 (message "")))
7811 (if (listp ev) (setq fmt nil ev "#ERROR"))
7812 (org-table-justify-field-maybe
7813 (if fmt (format fmt (string-to-number ev)) ev))
7814 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7815 (call-interactively 'org-return)
7816 (setq ndown 0)))
7817 (and down (org-table-maybe-recalculate-line))
7818 (or suppress-align (and org-table-may-need-update
7819 (org-table-align))))))
7821 (defun org-table-get-range (desc &optional tbeg col highlight)
7822 "Get a calc vector from a column, accorting to descriptor DESC.
7823 Optional arguments TBEG and COL can give the beginning of the table and
7824 the current column, to avoid unnecessary parsing.
7825 HIGHLIGHT means, just highlight the range."
7826 (if (not (equal (string-to-char desc) ?@))
7827 (setq desc (concat "@" desc)))
7828 (save-excursion
7829 (or tbeg (setq tbeg (org-table-begin)))
7830 (or col (setq col (org-table-current-column)))
7831 (let ((thisline (org-current-line))
7832 beg end c1 c2 r1 r2 rangep tmp)
7833 (unless (string-match org-table-range-regexp desc)
7834 (error "Invalid table range specifier `%s'" desc))
7835 (setq rangep (match-end 3)
7836 r1 (and (match-end 1) (match-string 1 desc))
7837 r2 (and (match-end 4) (match-string 4 desc))
7838 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
7839 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
7841 (and c1 (setq c1 (+ (string-to-number c1)
7842 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
7843 (and c2 (setq c2 (+ (string-to-number c2)
7844 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
7845 (if (equal r1 "") (setq r1 nil))
7846 (if (equal r2 "") (setq r2 nil))
7847 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
7848 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
7849 ; (setq r2 (or r2 r1) c2 (or c2 c1))
7850 (if (not r1) (setq r1 thisline))
7851 (if (not r2) (setq r2 thisline))
7852 (if (not c1) (setq c1 col))
7853 (if (not c2) (setq c2 col))
7854 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
7855 ;; just one field
7856 (progn
7857 (goto-line r1)
7858 (while (not (looking-at org-table-dataline-regexp))
7859 (beginning-of-line 2))
7860 (prog1 (org-table-get-field c1)
7861 (if highlight (org-table-highlight-rectangle (point) (point)))))
7862 ;; A range, return a vector
7863 ;; First sort the numbers to get a regular ractangle
7864 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
7865 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
7866 (goto-line r1)
7867 (while (not (looking-at org-table-dataline-regexp))
7868 (beginning-of-line 2))
7869 (org-table-goto-column c1)
7870 (setq beg (point))
7871 (goto-line r2)
7872 (while (not (looking-at org-table-dataline-regexp))
7873 (beginning-of-line 0))
7874 (org-table-goto-column c2)
7875 (setq end (point))
7876 (if highlight
7877 (org-table-highlight-rectangle
7878 beg (progn (skip-chars-forward "^|\n") (point))))
7879 ;; return string representation of calc vector
7880 (apply 'append (org-table-copy-region beg end))))))
7882 (defun org-table-get-descriptor-line (desc &optional cline bline table)
7883 "Analyze descriptor DESC and retrieve the corresponding line number.
7884 The cursor is currently in line CLINE, the table begins in line BLINE,
7885 and TABLE is a vector with line types."
7886 (if (string-match "^[0-9]+$" desc)
7887 (aref org-table-dlines (string-to-number desc))
7888 (setq cline (or cline (org-current-line))
7889 bline (or bline org-table-current-begin-line)
7890 table (or table org-table-current-line-types))
7891 (if (or
7892 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
7893 ;; 1 2 3 4 5 6
7894 (and (not (match-end 3)) (not (match-end 6)))
7895 (and (match-end 3) (match-end 6) (not (match-end 5))))
7896 (error "invalid row descriptor `%s'" desc))
7897 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
7898 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
7899 (odir (and (match-end 5) (match-string 5 desc)))
7900 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
7901 (i (- cline bline))
7902 (rel (and (match-end 6)
7903 (or (and (match-end 1) (not (match-end 3)))
7904 (match-end 5)))))
7905 (if (and hn (not hdir))
7906 (progn
7907 (setq i 0 hdir "+")
7908 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
7909 (if (and (not hn) on (not odir))
7910 (error "should never happen");;(aref org-table-dlines on) FIXME
7911 (if (and hn (> hn 0))
7912 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
7913 (if on
7914 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
7915 (+ bline i)))))
7917 (defun org-find-row-type (table i type backwards relative n)
7918 (let ((l (length table)))
7919 (while (> n 0)
7920 (while (and (setq i (+ i (if backwards -1 1)))
7921 (>= i 0) (< i l)
7922 (not (eq (aref table i) type))
7923 (if (and relative (eq (aref table i) 'hline))
7924 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
7925 t)))
7926 (setq n (1- n)))
7927 (if (or (< i 0) (>= i l))
7928 (error "Row descriptior leads outside table")
7929 i)))
7931 (defun org-rewrite-old-row-references (s)
7932 (if (string-match "&[-+0-9I]" s)
7933 (error "Formula contains old &row reference, please rewrite using @-syntax")
7936 (defun org-table-make-reference (elements keep-empty numbers lispp)
7937 "Convert list ELEMENTS to something appropriate to insert into formula.
7938 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
7939 NUMBERS indicates that everything should be converted to numbers.
7940 LISPP means to return something appropriate for a Lisp list."
7941 (if (stringp elements) ; just a single val
7942 (if lispp
7943 (prin1-to-string (if numbers (string-to-number elements) elements))
7944 (if (equal elements "") (setq elements "0"))
7945 (if numbers (number-to-string (string-to-number elements)) elements))
7946 (unless keep-empty
7947 (setq elements
7948 (delq nil
7949 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
7950 elements))))
7951 (setq elements (or elements '("0")))
7952 (if lispp
7953 (mapconcat 'prin1-to-string
7954 (if numbers (mapcar 'string-to-number elements) elements)
7955 " ")
7956 (concat "[" (mapconcat
7957 (lambda (x)
7958 (if numbers (number-to-string (string-to-number x)) x))
7959 elements
7960 ",") "]"))))
7962 (defun org-table-recalculate (&optional all noalign)
7963 "Recalculate the current table line by applying all stored formulas.
7964 With prefix arg ALL, do this for all lines in the table."
7965 (interactive "P")
7966 (or (memq this-command org-recalc-commands)
7967 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7968 (unless (org-at-table-p) (error "Not at a table"))
7969 (if (equal all '(16))
7970 (org-table-iterate)
7971 (org-table-get-specials)
7972 (let* ((eqlist (sort (org-table-get-stored-formulas)
7973 (lambda (a b) (string< (car a) (car b)))))
7974 (inhibit-redisplay (not debug-on-error))
7975 (line-re org-table-dataline-regexp)
7976 (thisline (org-current-line))
7977 (thiscol (org-table-current-column))
7978 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7979 ;; Insert constants in all formulas
7980 (setq eqlist
7981 (mapcar (lambda (x)
7982 (setcdr x (org-table-formula-substitute-names (cdr x)))
7984 eqlist))
7985 ;; Split the equation list
7986 (while (setq eq (pop eqlist))
7987 (if (<= (string-to-char (car eq)) ?9)
7988 (push eq eqlnum)
7989 (push eq eqlname)))
7990 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7991 (if all
7992 (progn
7993 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7994 (goto-char (setq beg (org-table-begin)))
7995 (if (re-search-forward org-table-calculate-mark-regexp end t)
7996 ;; This is a table with marked lines, compute selected lines
7997 (setq line-re org-table-recalculate-regexp)
7998 ;; Move forward to the first non-header line
7999 (if (and (re-search-forward org-table-dataline-regexp end t)
8000 (re-search-forward org-table-hline-regexp end t)
8001 (re-search-forward org-table-dataline-regexp end t))
8002 (setq beg (match-beginning 0))
8003 nil))) ;; just leave beg where it is
8004 (setq beg (point-at-bol)
8005 end (move-marker (make-marker) (1+ (point-at-eol)))))
8006 (goto-char beg)
8007 (and all (message "Re-applying formulas to full table..."))
8008 (while (re-search-forward line-re end t)
8009 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
8010 ;; Unprotected line, recalculate
8011 (and all (message "Re-applying formulas to full table...(line %d)"
8012 (setq cnt (1+ cnt))))
8013 (setq org-last-recalc-line (org-current-line))
8014 (setq eql eqlnum)
8015 (while (setq entry (pop eql))
8016 (goto-line org-last-recalc-line)
8017 (org-table-goto-column (string-to-number (car entry)) nil 'force)
8018 (org-table-eval-formula nil (cdr entry)
8019 'noalign 'nocst 'nostore 'noanalysis))))
8020 (goto-line thisline)
8021 (org-table-goto-column thiscol)
8022 (or noalign (and org-table-may-need-update (org-table-align))
8023 (and all (message "Re-applying formulas to %d lines...done" cnt)))
8024 ;; Now do the named fields
8025 (while (setq eq (pop eqlname))
8026 (setq name (car eq)
8027 a (assoc name org-table-named-field-locations))
8028 (and (not a)
8029 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
8030 (setq a
8031 (list
8032 name
8033 (aref org-table-dlines
8034 (string-to-number (match-string 1 name)))
8035 (string-to-number (match-string 2 name)))))
8036 (when (and a (or all (equal (nth 1 a) thisline)))
8037 (message "Re-applying formula to field: %s" name)
8038 (goto-line (nth 1 a))
8039 (org-table-goto-column (nth 2 a))
8040 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
8041 'nostore 'noanalysis)))
8042 ;; back to initial position
8043 (message "Re-applying formulas...done")
8044 (goto-line thisline)
8045 (org-table-goto-column thiscol)
8046 (or noalign (and org-table-may-need-update (org-table-align))
8047 (and all (message "Re-applying formulas...done"))))))
8049 (defun org-table-iterate (&optional arg)
8050 "Recalculate the table until it does not change anymore."
8051 (interactive "P")
8052 (let ((imax (if arg (prefix-numeric-value arg) 10))
8053 (i 0)
8054 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
8055 thistbl)
8056 (catch 'exit
8057 (while (< i imax)
8058 (setq i (1+ i))
8059 (org-table-recalculate 'all)
8060 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
8061 (if (not (string= lasttbl thistbl))
8062 (setq lasttbl thistbl)
8063 (if (> i 1)
8064 (message "Convergence after %d iterations" i)
8065 (message "Table was already stable"))
8066 (throw 'exit t)))
8067 (error "No convergence after %d iterations" i))))
8069 (defun org-table-formula-substitute-names (f)
8070 "Replace $const with values in string F."
8071 (let ((start 0) a (f1 f))
8072 ;; First, check for column names
8073 (while (setq start (string-match org-table-column-name-regexp f start))
8074 (setq start (1+ start))
8075 (setq a (assoc (match-string 1 f) org-table-column-names))
8076 (setq f (replace-match (concat "$" (cdr a)) t t f)))
8077 ;; Parameters and constants
8078 (setq start 0)
8079 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
8080 (setq start (1+ start))
8081 (if (setq a (save-match-data
8082 (org-table-get-constant (match-string 1 f))))
8083 (setq f (replace-match (concat "(" a ")") t t f))))
8084 (if org-table-formula-debug
8085 (put-text-property 0 (length f) :orig-formula f1 f))
8088 (defun org-table-get-constant (const)
8089 "Find the value for a parameter or constant in a formula.
8090 Parameters get priority."
8091 (or (cdr (assoc const org-table-local-parameters))
8092 (cdr (assoc const org-table-formula-constants))
8093 (and (fboundp 'constants-get) (constants-get const))
8094 "#UNDEFINED_NAME"))
8096 (defvar org-table-fedit-map (make-sparse-keymap))
8097 (define-key org-table-fedit-map "\C-x\C-s" 'org-table-fedit-finish)
8098 (define-key org-table-fedit-map "\C-c\C-s" 'org-table-fedit-finish)
8099 (define-key org-table-fedit-map "\C-c\C-c" 'org-table-fedit-finish)
8100 (define-key org-table-fedit-map "\C-c\C-q" 'org-table-fedit-abort)
8101 (define-key org-table-fedit-map "\C-c?" 'org-table-show-reference)
8102 (define-key org-table-fedit-map [(meta shift up)] 'org-table-fedit-line-up)
8103 (define-key org-table-fedit-map [(meta shift down)] 'org-table-fedit-line-down)
8104 (define-key org-table-fedit-map [(shift up)] 'org-table-fedit-ref-up)
8105 (define-key org-table-fedit-map [(shift down)] 'org-table-fedit-ref-down)
8106 (define-key org-table-fedit-map [(shift left)] 'org-table-fedit-ref-left)
8107 (define-key org-table-fedit-map [(shift right)] 'org-table-fedit-ref-right)
8108 (define-key org-table-fedit-map [(meta up)] 'org-table-fedit-scroll-down)
8109 (define-key org-table-fedit-map [(meta down)] 'org-table-fedit-scroll)
8110 (define-key org-table-fedit-map [(meta tab)] 'lisp-complete-symbol)
8111 (define-key org-table-fedit-map "\M-\C-i" 'lisp-complete-symbol)
8112 (define-key org-table-fedit-map [(tab)] 'org-table-fedit-lisp-indent)
8113 (define-key org-table-fedit-map "\C-i" 'org-table-fedit-lisp-indent)
8114 (define-key org-table-fedit-map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
8115 (define-key org-table-fedit-map "\C-c}" 'org-table-fedit-toggle-coordinates)
8117 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
8118 '("Edit-Formulas"
8119 ["Finish and Install" org-table-fedit-finish t]
8120 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
8121 ["Abort" org-table-fedit-abort t]
8122 "--"
8123 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
8124 ["Complete Lisp Symbol" lisp-complete-symbol t]
8125 "--"
8126 "Shift Reference at Point"
8127 ["Up" org-table-fedit-ref-up t]
8128 ["Down" org-table-fedit-ref-down t]
8129 ["Left" org-table-fedit-ref-left t]
8130 ["Right" org-table-fedit-ref-right t]
8132 "Change Test Row for Column Formulas"
8133 ["Up" org-table-fedit-line-up t]
8134 ["Down" org-table-fedit-line-down t]
8135 "--"
8136 ["Scroll Table Window" org-table-fedit-scroll t]
8137 ["Scroll Table Window down" org-table-fedit-scroll-down t]
8138 ["Show Table Grid" org-table-fedit-toggle-coordinates
8139 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
8140 org-table-overlay-coordinates)]
8141 "--"
8142 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
8143 :style toggle :selected org-table-buffer-is-an]))
8145 (defvar org-pos)
8147 (defun org-table-edit-formulas ()
8148 "Edit the formulas of the current table in a separate buffer."
8149 (interactive)
8150 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
8151 (beginning-of-line 0))
8152 (unless (org-at-table-p) (error "Not at a table"))
8153 (org-table-get-specials)
8154 (let ((key (org-table-current-field-formula 'key 'noerror))
8155 (eql (sort (org-table-get-stored-formulas 'noerror)
8156 'org-table-formula-less-p))
8157 (pos (move-marker (make-marker) (point)))
8158 (startline 1)
8159 (wc (current-window-configuration))
8160 (titles '((column . "# Column Formulas\n")
8161 (field . "# Field Formulas\n")
8162 (named . "# Named Field Formulas\n")))
8163 entry s type title)
8164 (switch-to-buffer-other-window "*Edit Formulas*")
8165 (erase-buffer)
8166 ;; Keep global-font-lock-mode from turning on font-lock-mode
8167 (let ((font-lock-global-modes '(not fundamental-mode)))
8168 (fundamental-mode))
8169 (org-set-local 'font-lock-global-modes (list 'not major-mode))
8170 (org-set-local 'org-pos pos)
8171 (org-set-local 'org-window-configuration wc)
8172 (use-local-map org-table-fedit-map)
8173 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
8174 (easy-menu-add org-table-fedit-menu)
8175 (setq startline (org-current-line))
8176 (while (setq entry (pop eql))
8177 (setq type (cond
8178 ((equal (string-to-char (car entry)) ?@) 'field)
8179 ((string-match "^[0-9]" (car entry)) 'column)
8180 (t 'named)))
8181 (when (setq title (assq type titles))
8182 (or (bobp) (insert "\n"))
8183 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
8184 (setq titles (delq title titles)))
8185 (if (equal key (car entry)) (setq startline (org-current-line)))
8186 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
8187 (car entry) " = " (cdr entry) "\n"))
8188 (remove-text-properties 0 (length s) '(face nil) s)
8189 (insert s))
8190 (if (eq org-table-use-standard-references t)
8191 (org-table-fedit-toggle-ref-type))
8192 (goto-line startline)
8193 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
8195 (defun org-table-fedit-post-command ()
8196 (when (not (memq this-command '(lisp-complete-symbol)))
8197 (let ((win (selected-window)))
8198 (save-excursion
8199 (condition-case nil
8200 (org-table-show-reference)
8201 (error nil))
8202 (select-window win)))))
8204 (defun org-table-formula-to-user (s)
8205 "Convert a formula from internal to user representation."
8206 (if (eq org-table-use-standard-references t)
8207 (org-table-convert-refs-to-an s)
8210 (defun org-table-formula-from-user (s)
8211 "Convert a formula from user to internal representation."
8212 (if org-table-use-standard-references
8213 (org-table-convert-refs-to-rc s)
8216 (defun org-table-convert-refs-to-rc (s)
8217 "Convert spreadsheet references from AB7 to @7$28.
8218 Works for single references, but also for entire formulas and even the
8219 full TBLFM line."
8220 (let ((start 0))
8221 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
8222 (if (match-end 3)
8223 ;; format match, just advance
8224 (setq start (match-end 0))
8225 (setq start (match-beginning 0)
8226 s (replace-match
8227 (if (equal (match-string 2 s) "&")
8228 (format "$%d" (org-letters-to-number (match-string 1 s)))
8229 (format "@%d$%d"
8230 (string-to-number (match-string 2 s))
8231 (org-letters-to-number (match-string 1 s))))
8232 t t s))))
8235 (defun org-table-convert-refs-to-an (s)
8236 "Convert spreadsheet references from to @7$28 to AB7.
8237 Works for single references, but also for entire formulas and even the
8238 full TBLFM line."
8239 (while (string-match "@\\([0-9]+\\)$\\([0-9]+\\)" s)
8240 (setq s (replace-match
8241 (format "%s%d"
8242 (org-number-to-letters
8243 (string-to-number (match-string 2 s)))
8244 (string-to-number (match-string 1 s)))
8245 t t s)))
8246 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
8247 (setq s (replace-match (concat "\\1"
8248 (org-number-to-letters
8249 (string-to-number (match-string 2 s))) "&")
8250 t nil s)))
8253 (defun org-letters-to-number (s)
8254 "Convert a base 26 number represented by letters into an integer.
8255 For example: AB -> 28."
8256 (let ((n 0))
8257 (setq s (upcase s))
8258 (while (> (length s) 0)
8259 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
8260 s (substring s 1)))
8263 (defun org-number-to-letters (n)
8264 "Convert an integer into a base 26 number represented by letters.
8265 For example: 28 -> AB."
8266 (let ((s ""))
8267 (while (> n 0)
8268 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
8269 n (/ (1- n) 26)))
8272 (defun org-table-fedit-convert-buffer (function)
8273 "Convert all references in this buffer, using FUNTION."
8274 (let ((line (org-current-line)))
8275 (goto-char (point-min))
8276 (while (not (eobp))
8277 (insert (funcall function (buffer-substring (point) (point-at-eol))))
8278 (delete-region (point) (point-at-eol))
8279 (or (eobp) (forward-char 1)))
8280 (goto-line line)))
8282 (defun org-table-fedit-toggle-ref-type ()
8283 "Convert all references in the buffer from B3 to @3$2 and back."
8284 (interactive)
8285 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
8286 (org-table-fedit-convert-buffer
8287 (if org-table-buffer-is-an
8288 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
8289 (message "Reference type switched to %s"
8290 (if org-table-buffer-is-an "A1 etc" "@row$column")))
8292 (defun org-table-fedit-ref-up ()
8293 "Shift the reference at point one row/hline up."
8294 (interactive)
8295 (org-table-fedit-shift-reference 'up))
8296 (defun org-table-fedit-ref-down ()
8297 "Shift the reference at point one row/hline down."
8298 (interactive)
8299 (org-table-fedit-shift-reference 'down))
8300 (defun org-table-fedit-ref-left ()
8301 "Shift the reference at point one field to the left."
8302 (interactive)
8303 (org-table-fedit-shift-reference 'left))
8304 (defun org-table-fedit-ref-right ()
8305 "Shift the reference at point one field to the right."
8306 (interactive)
8307 (org-table-fedit-shift-reference 'right))
8309 (defun org-table-fedit-shift-reference (dir)
8310 (cond
8311 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
8312 (if (memq dir '(left right))
8313 (org-rematch-and-replace 1 (eq dir 'left))
8314 (error "Cannot shift reference in this direction")))
8315 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
8316 ;; A B3-like reference
8317 (if (memq dir '(up down))
8318 (org-rematch-and-replace 2 (eq dir 'up))
8319 (org-rematch-and-replace 1 (eq dir 'left))))
8320 ((org-at-regexp-p
8321 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
8322 ;; An internal reference
8323 (if (memq dir '(up down))
8324 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
8325 (org-rematch-and-replace 5 (eq dir 'left))))))
8327 (defun org-rematch-and-replace (n &optional decr hline)
8328 "Re-match the group N, and replace it with the shifted refrence."
8329 (or (match-end n) (error "Cannot shift reference in this direction"))
8330 (goto-char (match-beginning n))
8331 (and (looking-at (regexp-quote (match-string n)))
8332 (replace-match (org-shift-refpart (match-string 0) decr hline)
8333 t t)))
8335 (defun org-shift-refpart (ref &optional decr hline)
8336 "Shift a refrence part REF.
8337 If DECR is set, decrease the references row/column, else increase.
8338 If HLINE is set, this may be a hline reference, it certainly is not
8339 a translation reference."
8340 (save-match-data
8341 (let* ((sign (string-match "^[-+]" ref)) n)
8343 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
8344 (cond
8345 ((and hline (string-match "^I+" ref))
8346 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
8347 (setq n (+ n (if decr -1 1)))
8348 (if (= n 0) (setq n (+ n (if decr -1 1))))
8349 (if sign
8350 (setq sign (if (< n 0) "-" "+") n (abs n))
8351 (setq n (max 1 n)))
8352 (concat sign (make-string n ?I)))
8354 ((string-match "^[0-9]+" ref)
8355 (setq n (string-to-number (concat sign ref)))
8356 (setq n (+ n (if decr -1 1)))
8357 (if sign
8358 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
8359 (number-to-string (max 1 n))))
8361 ((string-match "^[a-zA-Z]+" ref)
8362 (org-number-to-letters
8363 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
8365 (t (error "Cannot shift reference"))))))
8367 (defun org-table-fedit-toggle-coordinates ()
8368 "Toggle the display of coordinates in the refrenced table."
8369 (interactive)
8370 (let ((pos (marker-position org-pos)))
8371 (with-current-buffer (marker-buffer org-pos)
8372 (save-excursion
8373 (goto-char pos)
8374 (org-table-toggle-coordinate-overlays)))))
8376 (defun org-table-fedit-finish (&optional arg)
8377 "Parse the buffer for formula definitions and install them.
8378 With prefix ARG, apply the new formulas to the table."
8379 (interactive "P")
8380 (org-table-remove-rectangle-highlight)
8381 (if org-table-use-standard-references
8382 (progn
8383 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
8384 (setq org-table-buffer-is-an nil)))
8385 (let ((pos org-pos) eql var form)
8386 (goto-char (point-min))
8387 (while (re-search-forward
8388 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
8389 nil t)
8390 (setq var (if (match-end 2) (match-string 2) (match-string 1))
8391 form (match-string 3))
8392 (setq form (org-trim form))
8393 (when (not (equal form ""))
8394 (while (string-match "[ \t]*\n[ \t]*" form)
8395 (setq form (replace-match " " t t form)))
8396 (when (assoc var eql)
8397 (error "Double formulas for %s" var))
8398 (push (cons var form) eql)))
8399 (setq org-pos nil)
8400 (set-window-configuration org-window-configuration)
8401 (select-window (get-buffer-window (marker-buffer pos)))
8402 (goto-char pos)
8403 (unless (org-at-table-p)
8404 (error "Lost table position - cannot install formulae"))
8405 (org-table-store-formulas eql)
8406 (move-marker pos nil)
8407 (kill-buffer "*Edit Formulas*")
8408 (if arg
8409 (org-table-recalculate 'all)
8410 (message "New formulas installed - press C-u C-c C-c to apply."))))
8412 (defun org-table-fedit-abort ()
8413 "Abort editing formulas, without installing the changes."
8414 (interactive)
8415 (org-table-remove-rectangle-highlight)
8416 (let ((pos org-pos))
8417 (set-window-configuration org-window-configuration)
8418 (select-window (get-buffer-window (marker-buffer pos)))
8419 (goto-char pos)
8420 (move-marker pos nil)
8421 (message "Formula editing aborted without installing changes")))
8423 (defun org-table-fedit-lisp-indent ()
8424 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
8425 (interactive)
8426 (let ((pos (point)) beg end ind)
8427 (beginning-of-line 1)
8428 (cond
8429 ((looking-at "[ \t]")
8430 (goto-char pos)
8431 (call-interactively 'lisp-indent-line))
8432 ((looking-at "[$@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
8433 ((not (fboundp 'pp-buffer))
8434 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
8435 ((looking-at "[$@0-9a-zA-Z]+ *= *'(")
8436 (goto-char (- (match-end 0) 2))
8437 (setq beg (point))
8438 (setq ind (make-string (current-column) ?\ ))
8439 (condition-case nil (forward-sexp 1)
8440 (error
8441 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
8442 (setq end (point))
8443 (save-restriction
8444 (narrow-to-region beg end)
8445 (if (eq last-command this-command)
8446 (progn
8447 (goto-char (point-min))
8448 (setq this-command nil)
8449 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
8450 (replace-match " ")))
8451 (pp-buffer)
8452 (untabify (point-min) (point-max))
8453 (goto-char (1+ (point-min)))
8454 (while (re-search-forward "^." nil t)
8455 (beginning-of-line 1)
8456 (insert ind))
8457 (goto-char (point-max))
8458 (backward-delete-char 1)))
8459 (goto-char beg))
8460 (t nil))))
8462 (defvar org-show-positions nil)
8464 (defun org-table-show-reference (&optional local)
8465 "Show the location/value of the $ expression at point."
8466 (interactive)
8467 (org-table-remove-rectangle-highlight)
8468 (catch 'exit
8469 (let ((pos (if local (point) org-pos))
8470 (face2 'highlight)
8471 (org-inhibit-highlight-removal t)
8472 (win (selected-window))
8473 (org-show-positions nil)
8474 var name e what match dest)
8475 (if local (org-table-get-specials))
8476 (setq what (cond
8477 ((or (org-at-regexp-p org-table-range-regexp2)
8478 (org-at-regexp-p org-table-translate-regexp)
8479 (org-at-regexp-p org-table-range-regexp))
8480 (setq match
8481 (save-match-data
8482 (org-table-convert-refs-to-rc (match-string 0))))
8483 'range)
8484 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
8485 ((org-at-regexp-p "\\$[0-9]+") 'column)
8486 ((not local) nil)
8487 (t (error "No reference at point")))
8488 match (and what (or match (match-string 0))))
8489 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
8490 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
8491 'secondary-selection))
8492 (org-add-hook 'before-change-functions
8493 'org-table-remove-rectangle-highlight)
8494 (if (eq what 'name) (setq var (substring match 1)))
8495 (when (eq what 'range)
8496 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
8497 (setq match (org-table-formula-substitute-names match)))
8498 (unless local
8499 (save-excursion
8500 (end-of-line 1)
8501 (re-search-backward "^\\S-" nil t)
8502 (beginning-of-line 1)
8503 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
8504 (setq dest
8505 (save-match-data
8506 (org-table-convert-refs-to-rc (match-string 1))))
8507 (org-table-add-rectangle-overlay
8508 (match-beginning 1) (match-end 1) face2))))
8509 (if (and (markerp pos) (marker-buffer pos))
8510 (if (get-buffer-window (marker-buffer pos))
8511 (select-window (get-buffer-window (marker-buffer pos)))
8512 (switch-to-buffer-other-window (get-buffer-window
8513 (marker-buffer pos)))))
8514 (goto-char pos)
8515 (org-table-force-dataline)
8516 (when dest
8517 (setq name (substring dest 1))
8518 (cond
8519 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
8520 (setq e (assoc name org-table-named-field-locations))
8521 (goto-line (nth 1 e))
8522 (org-table-goto-column (nth 2 e)))
8523 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
8524 (let ((l (string-to-number (match-string 1 dest)))
8525 (c (string-to-number (match-string 2 dest))))
8526 (goto-line (aref org-table-dlines l))
8527 (org-table-goto-column c)))
8528 (t (org-table-goto-column (string-to-number name))))
8529 (move-marker pos (point))
8530 (org-table-highlight-rectangle nil nil face2))
8531 (cond
8532 ((equal dest match))
8533 ((not match))
8534 ((eq what 'range)
8535 (condition-case nil
8536 (save-excursion
8537 (org-table-get-range match nil nil 'highlight))
8538 (error nil)))
8539 ((setq e (assoc var org-table-named-field-locations))
8540 (goto-line (nth 1 e))
8541 (org-table-goto-column (nth 2 e))
8542 (org-table-highlight-rectangle (point) (point))
8543 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
8544 ((setq e (assoc var org-table-column-names))
8545 (org-table-goto-column (string-to-number (cdr e)))
8546 (org-table-highlight-rectangle (point) (point))
8547 (goto-char (org-table-begin))
8548 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
8549 (org-table-end) t)
8550 (progn
8551 (goto-char (match-beginning 1))
8552 (org-table-highlight-rectangle)
8553 (message "Named column (column %s)" (cdr e)))
8554 (error "Column name not found")))
8555 ((eq what 'column)
8556 ;; column number
8557 (org-table-goto-column (string-to-number (substring match 1)))
8558 (org-table-highlight-rectangle (point) (point))
8559 (message "Column %s" (substring match 1)))
8560 ((setq e (assoc var org-table-local-parameters))
8561 (goto-char (org-table-begin))
8562 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
8563 (progn
8564 (goto-char (match-beginning 1))
8565 (org-table-highlight-rectangle)
8566 (message "Local parameter."))
8567 (error "Parameter not found")))
8569 (cond
8570 ((not var) (error "No reference at point"))
8571 ((setq e (assoc var org-table-formula-constants))
8572 (message "Constant: $%s=%s in `org-table-formula-constants'."
8573 var (cdr e)))
8574 ((setq e (and (fboundp 'constants-get) (constants-get var)))
8575 (message "Constant: $%s=%s, from `constants.el'%s."
8576 var e (format " (%s units)" constants-unit-system)))
8577 (t (error "Undefined name $%s" var)))))
8578 (goto-char pos)
8579 (when (and org-show-positions
8580 (not (memq this-command '(org-table-fedit-scroll
8581 org-table-fedit-scroll-down))))
8582 (push pos org-show-positions)
8583 (push org-table-current-begin-pos org-show-positions)
8584 (let ((min (apply 'min org-show-positions))
8585 (max (apply 'max org-show-positions)))
8586 (goto-char min) (recenter 0)
8587 (goto-char max)
8588 (or (pos-visible-in-window-p max) (recenter -1))))
8589 (select-window win))))
8591 (defun org-table-force-dataline ()
8592 "Make sure the cursor is in a dataline in a table."
8593 (unless (save-excursion
8594 (beginning-of-line 1)
8595 (looking-at org-table-dataline-regexp))
8596 (let* ((re org-table-dataline-regexp)
8597 (p1 (save-excursion (re-search-forward re nil 'move)))
8598 (p2 (save-excursion (re-search-backward re nil 'move))))
8599 (cond ((and p1 p2)
8600 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
8601 p1 p2)))
8602 ((or p1 p2) (goto-char (or p1 p2)))
8603 (t (error "No table dataline around here"))))))
8605 (defun org-table-fedit-line-up ()
8606 "Move cursor one line up in the window showing the table."
8607 (interactive)
8608 (org-table-fedit-move 'previous-line))
8610 (defun org-table-fedit-line-down ()
8611 "Move cursor one line down in the window showing the table."
8612 (interactive)
8613 (org-table-fedit-move 'next-line))
8615 (defun org-table-fedit-move (command)
8616 "Move the cursor in the window shoinw the table.
8617 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
8618 (let ((org-table-allow-automatic-line-recalculation nil)
8619 (pos org-pos) (win (selected-window)) p)
8620 (select-window (get-buffer-window (marker-buffer org-pos)))
8621 (setq p (point))
8622 (call-interactively command)
8623 (while (and (org-at-table-p)
8624 (org-at-table-hline-p))
8625 (call-interactively command))
8626 (or (org-at-table-p) (goto-char p))
8627 (move-marker pos (point))
8628 (select-window win)))
8630 (defun org-table-fedit-scroll (N)
8631 (interactive "p")
8632 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
8633 (scroll-other-window N)))
8635 (defun org-table-fedit-scroll-down (N)
8636 (interactive "p")
8637 (org-table-fedit-scroll (- N)))
8639 (defvar org-table-rectangle-overlays nil)
8641 (defun org-table-add-rectangle-overlay (beg end &optional face)
8642 "Add a new overlay."
8643 (let ((ov (org-make-overlay beg end)))
8644 (org-overlay-put ov 'face (or face 'secondary-selection))
8645 (push ov org-table-rectangle-overlays)))
8647 (defun org-table-highlight-rectangle (&optional beg end face)
8648 "Highlight rectangular region in a table."
8649 (setq beg (or beg (point)) end (or end (point)))
8650 (let ((b (min beg end))
8651 (e (max beg end))
8652 l1 c1 l2 c2 tmp)
8653 (and (boundp 'org-show-positions)
8654 (setq org-show-positions (cons b (cons e org-show-positions))))
8655 (goto-char (min beg end))
8656 (setq l1 (org-current-line)
8657 c1 (org-table-current-column))
8658 (goto-char (max beg end))
8659 (setq l2 (org-current-line)
8660 c2 (org-table-current-column))
8661 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
8662 (goto-line l1)
8663 (beginning-of-line 1)
8664 (loop for line from l1 to l2 do
8665 (when (looking-at org-table-dataline-regexp)
8666 (org-table-goto-column c1)
8667 (skip-chars-backward "^|\n") (setq beg (point))
8668 (org-table-goto-column c2)
8669 (skip-chars-forward "^|\n") (setq end (point))
8670 (org-table-add-rectangle-overlay beg end face))
8671 (beginning-of-line 2))
8672 (goto-char b))
8673 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
8675 (defun org-table-remove-rectangle-highlight (&rest ignore)
8676 "Remove the rectangle overlays."
8677 (unless org-inhibit-highlight-removal
8678 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
8679 (mapc 'org-delete-overlay org-table-rectangle-overlays)
8680 (setq org-table-rectangle-overlays nil)))
8682 (defvar org-table-coordinate-overlays nil
8683 "Collects the cooordinate grid overlays, so that they can be removed.")
8684 (make-variable-buffer-local 'org-table-coordinate-overlays)
8686 (defun org-table-overlay-coordinates ()
8687 "Add overlays to the table at point, to show row/column coordinates."
8688 (interactive)
8689 (mapc 'org-delete-overlay org-table-coordinate-overlays)
8690 (setq org-table-coordinate-overlays nil)
8691 (save-excursion
8692 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
8693 (goto-char (org-table-begin))
8694 (while (org-at-table-p)
8695 (setq eol (point-at-eol))
8696 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
8697 (push ov org-table-coordinate-overlays)
8698 (setq hline (looking-at org-table-hline-regexp))
8699 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
8700 (format "%4d" (setq id (1+ id)))))
8701 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
8702 (when hline
8703 (setq ic 0)
8704 (while (re-search-forward "[+|]\\(-+\\)" eol t)
8705 (setq beg (1+ (match-beginning 0))
8706 ic (1+ ic)
8707 s1 (concat "$" (int-to-string ic))
8708 s2 (org-number-to-letters ic)
8709 str (if org-table-use-standard-references s2 s1))
8710 (setq ov (org-make-overlay beg (+ beg (length str))))
8711 (push ov org-table-coordinate-overlays)
8712 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
8713 (beginning-of-line 2)))))
8715 (defun org-table-toggle-coordinate-overlays ()
8716 "Toggle the display of Row/Column numbers in tables."
8717 (interactive)
8718 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
8719 (message "Row/Column number display turned %s"
8720 (if org-table-overlay-coordinates "on" "off"))
8721 (if (and (org-at-table-p) org-table-overlay-coordinates)
8722 (org-table-align))
8723 (unless org-table-overlay-coordinates
8724 (mapc 'org-delete-overlay org-table-coordinate-overlays)
8725 (setq org-table-coordinate-overlays nil)))
8727 (defun org-table-toggle-formula-debugger ()
8728 "Toggle the formula debugger in tables."
8729 (interactive)
8730 (setq org-table-formula-debug (not org-table-formula-debug))
8731 (message "Formula debugging has been turned %s"
8732 (if org-table-formula-debug "on" "off")))
8734 ;;; The orgtbl minor mode
8736 ;; Define a minor mode which can be used in other modes in order to
8737 ;; integrate the org-mode table editor.
8739 ;; This is really a hack, because the org-mode table editor uses several
8740 ;; keys which normally belong to the major mode, for example the TAB and
8741 ;; RET keys. Here is how it works: The minor mode defines all the keys
8742 ;; necessary to operate the table editor, but wraps the commands into a
8743 ;; function which tests if the cursor is currently inside a table. If that
8744 ;; is the case, the table editor command is executed. However, when any of
8745 ;; those keys is used outside a table, the function uses `key-binding' to
8746 ;; look up if the key has an associated command in another currently active
8747 ;; keymap (minor modes, major mode, global), and executes that command.
8748 ;; There might be problems if any of the keys used by the table editor is
8749 ;; otherwise used as a prefix key.
8751 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8752 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8753 ;; addresses this by checking explicitly for both bindings.
8755 ;; The optimized version (see variable `orgtbl-optimized') takes over
8756 ;; all keys which are bound to `self-insert-command' in the *global map*.
8757 ;; Some modes bind other commands to simple characters, for example
8758 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
8759 ;; active, this binding is ignored inside tables and replaced with a
8760 ;; modified self-insert.
8762 (defvar orgtbl-mode nil
8763 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
8764 table editor in arbitrary modes.")
8765 (make-variable-buffer-local 'orgtbl-mode)
8767 (defvar orgtbl-mode-map (make-keymap)
8768 "Keymap for `orgtbl-mode'.")
8770 ;;;###autoload
8771 (defun turn-on-orgtbl ()
8772 "Unconditionally turn on `orgtbl-mode'."
8773 (orgtbl-mode 1))
8775 (defvar org-old-auto-fill-inhibit-regexp nil
8776 "Local variable used by `orgtbl-mode'")
8778 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
8779 "Matches a line belonging to an orgtbl.")
8781 (defconst orgtbl-extra-font-lock-keywords
8782 (list (list (concat "^" orgtbl-line-start-regexp ".*")
8783 0 (quote 'org-table) 'prepend))
8784 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
8786 ;;;###autoload
8787 (defun orgtbl-mode (&optional arg)
8788 "The `org-mode' table editor as a minor mode for use in other modes."
8789 (interactive)
8790 (if (org-mode-p)
8791 ;; Exit without error, in case some hook functions calls this
8792 ;; by accident in org-mode.
8793 (message "Orgtbl-mode is not useful in org-mode, command ignored")
8794 (setq orgtbl-mode
8795 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
8796 (if orgtbl-mode
8797 (progn
8798 (and (orgtbl-setup) (defun orgtbl-setup () nil))
8799 ;; Make sure we are first in minor-mode-map-alist
8800 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
8801 (and c (setq minor-mode-map-alist
8802 (cons c (delq c minor-mode-map-alist)))))
8803 (org-set-local (quote org-table-may-need-update) t)
8804 (org-add-hook 'before-change-functions 'org-before-change-function
8805 nil 'local)
8806 (org-set-local 'org-old-auto-fill-inhibit-regexp
8807 auto-fill-inhibit-regexp)
8808 (org-set-local 'auto-fill-inhibit-regexp
8809 (if auto-fill-inhibit-regexp
8810 (concat orgtbl-line-start-regexp "\\|"
8811 auto-fill-inhibit-regexp)
8812 orgtbl-line-start-regexp))
8813 (org-add-to-invisibility-spec '(org-cwidth))
8814 (when (fboundp 'font-lock-add-keywords)
8815 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
8816 (org-restart-font-lock))
8817 (easy-menu-add orgtbl-mode-menu)
8818 (run-hooks 'orgtbl-mode-hook))
8819 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
8820 (org-cleanup-narrow-column-properties)
8821 (org-remove-from-invisibility-spec '(org-cwidth))
8822 (remove-hook 'before-change-functions 'org-before-change-function t)
8823 (when (fboundp 'font-lock-remove-keywords)
8824 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
8825 (org-restart-font-lock))
8826 (easy-menu-remove orgtbl-mode-menu)
8827 (force-mode-line-update 'all))))
8829 (defun org-cleanup-narrow-column-properties ()
8830 "Remove all properties related to narrow-column invisibility."
8831 (let ((s 1))
8832 (while (setq s (text-property-any s (point-max)
8833 'display org-narrow-column-arrow))
8834 (remove-text-properties s (1+ s) '(display t)))
8835 (setq s 1)
8836 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
8837 (remove-text-properties s (1+ s) '(org-cwidth t)))
8838 (setq s 1)
8839 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
8840 (remove-text-properties s (1+ s) '(invisible t)))))
8842 ;; Install it as a minor mode.
8843 (put 'orgtbl-mode :included t)
8844 (put 'orgtbl-mode :menu-tag "Org Table Mode")
8845 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
8847 (defun orgtbl-make-binding (fun n &rest keys)
8848 "Create a function for binding in the table minor mode.
8849 FUN is the command to call inside a table. N is used to create a unique
8850 command name. KEYS are keys that should be checked in for a command
8851 to execute outside of tables."
8852 (eval
8853 (list 'defun
8854 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
8855 '(arg)
8856 (concat "In tables, run `" (symbol-name fun) "'.\n"
8857 "Outside of tables, run the binding of `"
8858 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8859 "'.")
8860 '(interactive "p")
8861 (list 'if
8862 '(org-at-table-p)
8863 (list 'call-interactively (list 'quote fun))
8864 (list 'let '(orgtbl-mode)
8865 (list 'call-interactively
8866 (append '(or)
8867 (mapcar (lambda (k)
8868 (list 'key-binding k))
8869 keys)
8870 '('orgtbl-error))))))))
8872 (defun orgtbl-error ()
8873 "Error when there is no default binding for a table key."
8874 (interactive)
8875 (error "This key is has no function outside tables"))
8877 (defun orgtbl-setup ()
8878 "Setup orgtbl keymaps."
8879 (let ((nfunc 0)
8880 (bindings
8881 (list
8882 '([(meta shift left)] org-table-delete-column)
8883 '([(meta left)] org-table-move-column-left)
8884 '([(meta right)] org-table-move-column-right)
8885 '([(meta shift right)] org-table-insert-column)
8886 '([(meta shift up)] org-table-kill-row)
8887 '([(meta shift down)] org-table-insert-row)
8888 '([(meta up)] org-table-move-row-up)
8889 '([(meta down)] org-table-move-row-down)
8890 '("\C-c\C-w" org-table-cut-region)
8891 '("\C-c\M-w" org-table-copy-region)
8892 '("\C-c\C-y" org-table-paste-rectangle)
8893 '("\C-c-" org-table-insert-hline)
8894 '("\C-c}" org-table-toggle-coordinate-overlays)
8895 '("\C-c{" org-table-toggle-formula-debugger)
8896 '("\C-m" org-table-next-row)
8897 (list (org-key 'S-return) 'org-table-copy-down)
8898 '("\C-c\C-q" org-table-wrap-region)
8899 '("\C-c?" org-table-field-info)
8900 '("\C-c " org-table-blank-field)
8901 '("\C-c+" org-table-sum)
8902 '("\C-c=" org-table-eval-formula)
8903 '("\C-c'" org-table-edit-formulas)
8904 '("\C-c`" org-table-edit-field)
8905 '("\C-c*" org-table-recalculate)
8906 '("\C-c|" org-table-create-or-convert-from-region)
8907 '("\C-c^" org-table-sort-lines)
8908 '([(control ?#)] org-table-rotate-recalc-marks)))
8909 elt key fun cmd)
8910 (while (setq elt (pop bindings))
8911 (setq nfunc (1+ nfunc))
8912 (setq key (car elt)
8913 fun (nth 1 elt)
8914 cmd (orgtbl-make-binding fun nfunc key))
8915 (define-key orgtbl-mode-map key cmd))
8917 ;; Special treatment needed for TAB and RET
8918 (define-key orgtbl-mode-map [(return)]
8919 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
8920 (define-key orgtbl-mode-map "\C-m"
8921 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
8923 (define-key orgtbl-mode-map [(tab)]
8924 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
8925 (define-key orgtbl-mode-map "\C-i"
8926 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
8928 (define-key orgtbl-mode-map [(shift tab)]
8929 (orgtbl-make-binding 'org-table-previous-field 104
8930 [(shift tab)] [(tab)] "\C-i"))
8932 (define-key orgtbl-mode-map "\M-\C-m"
8933 (orgtbl-make-binding 'org-table-wrap-region 105
8934 "\M-\C-m" [(meta return)]))
8935 (define-key orgtbl-mode-map [(meta return)]
8936 (orgtbl-make-binding 'org-table-wrap-region 106
8937 [(meta return)] "\M-\C-m"))
8939 (define-key orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
8940 (when orgtbl-optimized
8941 ;; If the user wants maximum table support, we need to hijack
8942 ;; some standard editing functions
8943 (org-remap orgtbl-mode-map
8944 'self-insert-command 'orgtbl-self-insert-command
8945 'delete-char 'org-delete-char
8946 'delete-backward-char 'org-delete-backward-char)
8947 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8948 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8949 '("OrgTbl"
8950 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8951 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8952 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8953 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8954 "--"
8955 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8956 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
8957 ["Copy Field from Above"
8958 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8959 "--"
8960 ("Column"
8961 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8962 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8963 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8964 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
8965 ("Row"
8966 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8967 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8968 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8969 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8970 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
8971 "--"
8972 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8973 ("Rectangle"
8974 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
8975 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
8976 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
8977 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
8978 "--"
8979 ("Radio tables"
8980 ["Insert table template" orgtbl-insert-radio-table
8981 (assq major-mode orgtbl-radio-table-templates)]
8982 ["Comment/uncomment table" orgtbl-toggle-comment t])
8983 "--"
8984 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8985 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8986 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8987 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8988 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8989 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
8990 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8991 ["Sum Column/Rectangle" org-table-sum
8992 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8993 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8994 ["Debug Formulas"
8995 org-table-toggle-formula-debugger :active (org-at-table-p)
8996 :keys "C-c {"
8997 :style toggle :selected org-table-formula-debug]
8998 ["Show Col/Row Numbers"
8999 org-table-toggle-coordinate-overlays :active (org-at-table-p)
9000 :keys "C-c }"
9001 :style toggle :selected org-table-overlay-coordinates]
9005 (defun orgtbl-ctrl-c-ctrl-c (arg)
9006 "If the cursor is inside a table, realign the table.
9007 It it is a table to be sent away to a receiver, do it.
9008 With prefix arg, also recompute table."
9009 (interactive "P")
9010 (let ((pos (point)) action)
9011 (save-excursion
9012 (beginning-of-line 1)
9013 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
9014 ((looking-at "[ \t]*|") pos)
9015 ((looking-at "#\\+TBLFM:") 'recalc))))
9016 (cond
9017 ((integerp action)
9018 (goto-char action)
9019 (org-table-maybe-eval-formula)
9020 (if arg
9021 (call-interactively 'org-table-recalculate)
9022 (org-table-maybe-recalculate-line))
9023 (call-interactively 'org-table-align)
9024 (orgtbl-send-table 'maybe))
9025 ((eq action 'recalc)
9026 (save-excursion
9027 (beginning-of-line 1)
9028 (skip-chars-backward " \r\n\t")
9029 (if (org-at-table-p)
9030 (org-call-with-arg 'org-table-recalculate t))))
9031 (t (let (orgtbl-mode)
9032 (call-interactively (key-binding "\C-c\C-c")))))))
9034 (defun orgtbl-tab (arg)
9035 "Justification and field motion for `orgtbl-mode'."
9036 (interactive "P")
9037 (if arg (org-table-edit-field t)
9038 (org-table-justify-field-maybe)
9039 (org-table-next-field)))
9041 (defun orgtbl-ret ()
9042 "Justification and field motion for `orgtbl-mode'."
9043 (interactive)
9044 (org-table-justify-field-maybe)
9045 (org-table-next-row))
9047 (defun orgtbl-self-insert-command (N)
9048 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9049 If the cursor is in a table looking at whitespace, the whitespace is
9050 overwritten, and the table is not marked as requiring realignment."
9051 (interactive "p")
9052 (if (and (org-at-table-p)
9054 (and org-table-auto-blank-field
9055 (member last-command
9056 '(orgtbl-hijacker-command-100
9057 orgtbl-hijacker-command-101
9058 orgtbl-hijacker-command-102
9059 orgtbl-hijacker-command-103
9060 orgtbl-hijacker-command-104
9061 orgtbl-hijacker-command-105))
9062 (org-table-blank-field))
9064 (eq N 1)
9065 (looking-at "[^|\n]* +|"))
9066 (let (org-table-may-need-update)
9067 (goto-char (1- (match-end 0)))
9068 (delete-backward-char 1)
9069 (goto-char (match-beginning 0))
9070 (self-insert-command N))
9071 (setq org-table-may-need-update t)
9072 (let (orgtbl-mode)
9073 (call-interactively (key-binding (vector last-input-event))))))
9075 (defun org-force-self-insert (N)
9076 "Needed to enforce self-insert under remapping."
9077 (interactive "p")
9078 (self-insert-command N))
9080 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
9081 "Regula expression matching exponentials as produced by calc.")
9083 (defvar org-table-clean-did-remove-column-1 nil)
9085 (defun orgtbl-send-table (&optional maybe)
9086 "Send a tranformed version of this table to the receiver position.
9087 With argument MAYBE, fail quietly if no transformation is defined for
9088 this table."
9089 (interactive)
9090 (catch 'exit
9091 (unless (org-at-table-p) (error "Not at a table"))
9092 ;; when non-interactive, we assume align has just happened.
9093 (when (interactive-p) (org-table-align))
9094 (save-excursion
9095 (goto-char (org-table-begin))
9096 (beginning-of-line 0)
9097 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
9098 (if maybe
9099 (throw 'exit nil)
9100 (error "Don't know how to transform this table."))))
9101 (let* ((name (match-string 1))
9103 (transform (intern (match-string 2)))
9104 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
9105 (skip (plist-get params :skip))
9106 (skipcols (plist-get params :skipcols))
9107 (txt (buffer-substring-no-properties
9108 (org-table-begin) (org-table-end)))
9109 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
9110 (lines (org-table-clean-before-export lines))
9111 (i0 (if org-table-clean-did-remove-column-1 2 1))
9112 (table (mapcar
9113 (lambda (x)
9114 (if (string-match org-table-hline-regexp x)
9115 'hline
9116 (org-remove-by-index
9117 (org-split-string (org-trim x) "\\s-*|\\s-*")
9118 skipcols i0)))
9119 lines))
9120 (fun (if (= i0 2) 'cdr 'identity))
9121 (org-table-last-alignment
9122 (org-remove-by-index (funcall fun org-table-last-alignment)
9123 skipcols i0))
9124 (org-table-last-column-widths
9125 (org-remove-by-index (funcall fun org-table-last-column-widths)
9126 skipcols i0)))
9128 (unless (fboundp transform)
9129 (error "No such transformation function %s" transform))
9130 (setq txt (funcall transform table params))
9131 ;; Find the insertion place
9132 (save-excursion
9133 (goto-char (point-min))
9134 (unless (re-search-forward
9135 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
9136 (error "Don't know where to insert translated table"))
9137 (goto-char (match-beginning 0))
9138 (beginning-of-line 2)
9139 (setq beg (point))
9140 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
9141 (error "Cannot find end of insertion region"))
9142 (beginning-of-line 1)
9143 (delete-region beg (point))
9144 (goto-char beg)
9145 (insert txt "\n"))
9146 (message "Table converted and installed at receiver location"))))
9148 (defun org-remove-by-index (list indices &optional i0)
9149 "Remove the elements in LIST with indices in INDICES.
9150 First element has index 0, or I0 if given."
9151 (if (not indices)
9152 list
9153 (if (integerp indices) (setq indices (list indices)))
9154 (setq i0 (1- (or i0 0)))
9155 (delq :rm (mapcar (lambda (x)
9156 (setq i0 (1+ i0))
9157 (if (memq i0 indices) :rm x))
9158 list))))
9160 (defun orgtbl-toggle-comment ()
9161 "Comment or uncomment the orgtbl at point."
9162 (interactive)
9163 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
9164 (re2 (concat "^" orgtbl-line-start-regexp))
9165 (commented (save-excursion (beginning-of-line 1)
9166 (cond ((looking-at re1) t)
9167 ((looking-at re2) nil)
9168 (t (error "Not at an org table")))))
9169 (re (if commented re1 re2))
9170 beg end)
9171 (save-excursion
9172 (beginning-of-line 1)
9173 (while (looking-at re) (beginning-of-line 0))
9174 (beginning-of-line 2)
9175 (setq beg (point))
9176 (while (looking-at re) (beginning-of-line 2))
9177 (setq end (point)))
9178 (comment-region beg end (if commented '(4) nil))))
9180 (defun orgtbl-insert-radio-table ()
9181 "Insert a radio table template appropriate for this major mode."
9182 (interactive)
9183 (let* ((e (assq major-mode orgtbl-radio-table-templates))
9184 (txt (nth 1 e))
9185 name pos)
9186 (unless e (error "No radio table setup defined for %s" major-mode))
9187 (setq name (read-string "Table name: "))
9188 (while (string-match "%n" txt)
9189 (setq txt (replace-match name t t txt)))
9190 (or (bolp) (insert "\n"))
9191 (setq pos (point))
9192 (insert txt)
9193 (goto-char pos)))
9195 (defun org-get-param (params header i sym &optional hsym)
9196 "Get parameter value for symbol SYM.
9197 If this is a header line, actually get the value for the symbol with an
9198 additional \"h\" inserted after the colon.
9199 If the value is a protperty list, get the element for the current column.
9200 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
9201 (let ((val (plist-get params sym)))
9202 (and hsym header (setq val (or (plist-get params hsym) val)))
9203 (if (consp val) (plist-get val i) val)))
9205 (defun orgtbl-to-generic (table params)
9206 "Convert the orgtbl-mode TABLE to some other format.
9207 This generic routine can be used for many standard cases.
9208 TABLE is a list, each entry either the symbol `hline' for a horizontal
9209 separator line, or a list of fields for that line.
9210 PARAMS is a property list of parameters that can influence the conversion.
9211 For the generic converter, some parameters are obligatory: You need to
9212 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
9213 :splice, you must have :tstart and :tend.
9215 Valid parameters are
9217 :tstart String to start the table. Ignored when :splice is t.
9218 :tend String to end the table. Ignored when :splice is t.
9220 :splice When set to t, return only table body lines, don't wrap
9221 them into :tstart and :tend. Default is nil.
9223 :hline String to be inserted on horizontal separation lines.
9224 May be nil to ignore hlines.
9226 :lstart String to start a new table line.
9227 :lend String to end a table line
9228 :sep Separator between two fields
9229 :lfmt Format for entire line, with enough %s to capture all fields.
9230 If this is present, :lstart, :lend, and :sep are ignored.
9231 :fmt A format to be used to wrap the field, should contain
9232 %s for the original field value. For example, to wrap
9233 everything in dollars, you could use :fmt \"$%s$\".
9234 This may also be a property list with column numbers and
9235 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
9237 :hlstart :hlend :hlsep :hlfmt :hfmt
9238 Same as above, specific for the header lines in the table.
9239 All lines before the first hline are treated as header.
9240 If any of these is not present, the data line value is used.
9242 :efmt Use this format to print numbers with exponentials.
9243 The format should have %s twice for inserting mantissa
9244 and exponent, for example \"%s\\\\times10^{%s}\". This
9245 may also be a property list with column numbers and
9246 formats. :fmt will still be applied after :efmt.
9248 In addition to this, the parameters :skip and :skipcols are always handled
9249 directly by `orgtbl-send-table'. See manual."
9250 (interactive)
9251 (let* ((p params)
9252 (splicep (plist-get p :splice))
9253 (hline (plist-get p :hline))
9254 rtn line i fm efm lfmt h)
9256 ;; Do we have a header?
9257 (if (and (not splicep) (listp (car table)) (memq 'hline table))
9258 (setq h t))
9260 ;; Put header
9261 (unless splicep
9262 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
9264 ;; Now loop over all lines
9265 (while (setq line (pop table))
9266 (if (eq line 'hline)
9267 ;; A horizontal separator line
9268 (progn (if hline (push hline rtn))
9269 (setq h nil)) ; no longer in header
9270 ;; A normal line. Convert the fields, push line onto the result list
9271 (setq i 0)
9272 (setq line
9273 (mapcar
9274 (lambda (f)
9275 (setq i (1+ i)
9276 fm (org-get-param p h i :fmt :hfmt)
9277 efm (org-get-param p h i :efmt))
9278 (if (and efm (string-match orgtbl-exp-regexp f))
9279 (setq f (format
9280 efm (match-string 1 f) (match-string 2 f))))
9281 (if fm (setq f (format fm f)))
9283 line))
9284 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
9285 (push (apply 'format lfmt line) rtn)
9286 (push (concat
9287 (org-get-param p h i :lstart :hlstart)
9288 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
9289 (org-get-param p h i :lend :hlend))
9290 rtn))))
9292 (unless splicep
9293 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
9295 (mapconcat 'identity (nreverse rtn) "\n")))
9297 (defun orgtbl-to-latex (table params)
9298 "Convert the orgtbl-mode TABLE to LaTeX.
9299 TABLE is a list, each entry either the symbol `hline' for a horizontal
9300 separator line, or a list of fields for that line.
9301 PARAMS is a property list of parameters that can influence the conversion.
9302 Supports all parameters from `orgtbl-to-generic'. Most important for
9303 LaTeX are:
9305 :splice When set to t, return only table body lines, don't wrap
9306 them into a tabular environment. Default is nil.
9308 :fmt A format to be used to wrap the field, should contain %s for the
9309 original field value. For example, to wrap everything in dollars,
9310 use :fmt \"$%s$\". This may also be a property list with column
9311 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
9313 :efmt Format for transforming numbers with exponentials. The format
9314 should have %s twice for inserting mantissa and exponent, for
9315 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
9316 This may also be a property list with column numbers and formats.
9318 The general parameters :skip and :skipcols have already been applied when
9319 this function is called."
9320 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
9321 org-table-last-alignment ""))
9322 (params2
9323 (list
9324 :tstart (concat "\\begin{tabular}{" alignment "}")
9325 :tend "\\end{tabular}"
9326 :lstart "" :lend " \\\\" :sep " & "
9327 :efmt "%s\\,(%s)" :hline "\\hline")))
9328 (orgtbl-to-generic table (org-combine-plists params2 params))))
9330 (defun orgtbl-to-html (table params)
9331 "Convert the orgtbl-mode TABLE to LaTeX.
9332 TABLE is a list, each entry either the symbol `hline' for a horizontal
9333 separator line, or a list of fields for that line.
9334 PARAMS is a property list of parameters that can influence the conversion.
9335 Currently this function recognizes the following parameters:
9337 :splice When set to t, return only table body lines, don't wrap
9338 them into a <table> environment. Default is nil.
9340 The general parameters :skip and :skipcols have already been applied when
9341 this function is called. The function does *not* use `orgtbl-to-generic',
9342 so you cannot specify parameters for it."
9343 (let* ((splicep (plist-get params :splice))
9344 html)
9345 ;; Just call the formatter we already have
9346 ;; We need to make text lines for it, so put the fields back together.
9347 (setq html (org-format-org-table-html
9348 (mapcar
9349 (lambda (x)
9350 (if (eq x 'hline)
9351 "|----+----|"
9352 (concat "| " (mapconcat 'identity x " | ") " |")))
9353 table)
9354 splicep))
9355 (if (string-match "\n+\\'" html)
9356 (setq html (replace-match "" t t html)))
9357 html))
9359 (defun orgtbl-to-texinfo (table params)
9360 "Convert the orgtbl-mode TABLE to TeXInfo.
9361 TABLE is a list, each entry either the symbol `hline' for a horizontal
9362 separator line, or a list of fields for that line.
9363 PARAMS is a property list of parameters that can influence the conversion.
9364 Supports all parameters from `orgtbl-to-generic'. Most important for
9365 TeXInfo are:
9367 :splice nil/t When set to t, return only table body lines, don't wrap
9368 them into a multitable environment. Default is nil.
9370 :fmt fmt A format to be used to wrap the field, should contain
9371 %s for the original field value. For example, to wrap
9372 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
9373 This may also be a property list with column numbers and
9374 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
9376 :cf \"f1 f2..\" The column fractions for the table. Bye default these
9377 are computed automatically from the width of the columns
9378 under org-mode.
9380 The general parameters :skip and :skipcols have already been applied when
9381 this function is called."
9382 (let* ((total (float (apply '+ org-table-last-column-widths)))
9383 (colfrac (or (plist-get params :cf)
9384 (mapconcat
9385 (lambda (x) (format "%.3f" (/ (float x) total)))
9386 org-table-last-column-widths " ")))
9387 (params2
9388 (list
9389 :tstart (concat "@multitable @columnfractions " colfrac)
9390 :tend "@end multitable"
9391 :lstart "@item " :lend "" :sep " @tab "
9392 :hlstart "@headitem ")))
9393 (orgtbl-to-generic table (org-combine-plists params2 params))))
9395 ;;;; Link Stuff
9397 ;;; Link abbreviations
9399 (defun org-link-expand-abbrev (link)
9400 "Apply replacements as defined in `org-link-abbrev-alist."
9401 (if (string-match "^\\([a-zA-Z]+\\)\\(::?\\(.*\\)\\)?$" link)
9402 (let* ((key (match-string 1 link))
9403 (as (or (assoc key org-link-abbrev-alist-local)
9404 (assoc key org-link-abbrev-alist)))
9405 (tag (and (match-end 2) (match-string 3 link)))
9406 rpl)
9407 (if (not as)
9408 link
9409 (setq rpl (cdr as))
9410 (cond
9411 ((symbolp rpl) (funcall rpl tag))
9412 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9413 (t (concat rpl tag)))))
9414 link))
9416 ;;; Storing and inserting links
9418 (defvar org-insert-link-history nil
9419 "Minibuffer history for links inserted with `org-insert-link'.")
9421 (defvar org-stored-links nil
9422 "Contains the links stored with `org-store-link'.")
9424 (defvar org-store-link-plist nil
9425 "Plist with info about the most recently link created with `org-store-link'.")
9427 ;;;###autoload
9428 (defun org-store-link (arg)
9429 "\\<org-mode-map>Store an org-link to the current location.
9430 This link can later be inserted into an org-buffer with
9431 \\[org-insert-link].
9432 For some link types, a prefix arg is interpreted:
9433 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9434 For file links, arg negates `org-context-in-file-links'."
9435 (interactive "P")
9436 (setq org-store-link-plist nil) ; reset
9437 (let (link cpltxt desc description search txt)
9438 (cond
9440 ((eq major-mode 'bbdb-mode)
9441 (let ((name (bbdb-record-name (bbdb-current-record)))
9442 (company (bbdb-record-company (bbdb-current-record))))
9443 (setq cpltxt (concat "bbdb:" (or name company))
9444 link (org-make-link cpltxt))
9445 (org-store-link-props :type "bbdb" :name name :company company)))
9447 ((eq major-mode 'Info-mode)
9448 (setq link (org-make-link "info:"
9449 (file-name-nondirectory Info-current-file)
9450 ":" Info-current-node))
9451 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9452 ":" Info-current-node))
9453 (org-store-link-props :type "info" :file Info-current-file
9454 :node Info-current-node))
9456 ((eq major-mode 'calendar-mode)
9457 (let ((cd (calendar-cursor-to-date)))
9458 (setq link
9459 (format-time-string
9460 (car org-time-stamp-formats)
9461 (apply 'encode-time
9462 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9463 nil nil nil))))
9464 (org-store-link-props :type "calendar" :date cd)))
9466 ((or (eq major-mode 'vm-summary-mode)
9467 (eq major-mode 'vm-presentation-mode))
9468 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9469 (vm-follow-summary-cursor)
9470 (save-excursion
9471 (vm-select-folder-buffer)
9472 (let* ((message (car vm-message-pointer))
9473 (folder buffer-file-name)
9474 (subject (vm-su-subject message))
9475 (to (vm-get-header-contents message "To"))
9476 (from (vm-get-header-contents message "From"))
9477 (message-id (vm-su-message-id message)))
9478 (org-store-link-props :type "vm" :from from :to to :subject subject
9479 :message-id message-id)
9480 (setq message-id (org-remove-angle-brackets message-id))
9481 (setq folder (abbreviate-file-name folder))
9482 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9483 folder)
9484 (setq folder (replace-match "" t t folder)))
9485 (setq cpltxt (org-email-link-description))
9486 (setq link (org-make-link "vm:" folder "#" message-id)))))
9488 ((eq major-mode 'wl-summary-mode)
9489 (let* ((msgnum (wl-summary-message-number))
9490 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9491 msgnum 'message-id))
9492 (wl-message-entity
9493 (if (fboundp 'elmo-message-entity)
9494 (elmo-message-entity
9495 wl-summary-buffer-elmo-folder msgnum)
9496 (elmo-msgdb-overview-get-entity
9497 msgnum (wl-summary-buffer-msgdb))))
9498 (from (wl-summary-line-from))
9499 (to (car (elmo-message-entity-field wl-message-entity 'to)))
9500 (subject (let (wl-thr-indent-string wl-parent-message-entity)
9501 (wl-summary-line-subject))))
9502 (org-store-link-props :type "wl" :from from :to to
9503 :subject subject :message-id message-id)
9504 (setq message-id (org-remove-angle-brackets message-id))
9505 (setq cpltxt (org-email-link-description))
9506 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9507 "#" message-id))))
9509 ((or (equal major-mode 'mh-folder-mode)
9510 (equal major-mode 'mh-show-mode))
9511 (let ((from (org-mhe-get-header "From:"))
9512 (to (org-mhe-get-header "To:"))
9513 (message-id (org-mhe-get-header "Message-Id:"))
9514 (subject (org-mhe-get-header "Subject:")))
9515 (org-store-link-props :type "mh" :from from :to to
9516 :subject subject :message-id message-id)
9517 (setq cpltxt (org-email-link-description))
9518 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9519 (org-remove-angle-brackets message-id)))))
9521 ((eq major-mode 'rmail-mode)
9522 (save-excursion
9523 (save-restriction
9524 (rmail-narrow-to-non-pruned-header)
9525 (let ((folder buffer-file-name)
9526 (message-id (mail-fetch-field "message-id"))
9527 (from (mail-fetch-field "from"))
9528 (to (mail-fetch-field "to"))
9529 (subject (mail-fetch-field "subject")))
9530 (org-store-link-props
9531 :type "rmail" :from from :to to
9532 :subject subject :message-id message-id)
9533 (setq message-id (org-remove-angle-brackets message-id))
9534 (setq cpltxt (org-email-link-description))
9535 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9537 ((eq major-mode 'gnus-group-mode)
9538 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9539 (gnus-group-group-name)) ; version
9540 ((fboundp 'gnus-group-name)
9541 (gnus-group-name))
9542 (t "???"))))
9543 (unless group (error "Not on a group"))
9544 (org-store-link-props :type "gnus" :group group)
9545 (setq cpltxt (concat
9546 (if (org-xor arg org-usenet-links-prefer-google)
9547 "http://groups.google.com/groups?group="
9548 "gnus:")
9549 group)
9550 link (org-make-link cpltxt))))
9552 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9553 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9554 (let* ((group gnus-newsgroup-name)
9555 (article (gnus-summary-article-number))
9556 (header (gnus-summary-article-header article))
9557 (from (mail-header-from header))
9558 (message-id (mail-header-id header))
9559 (date (mail-header-date header))
9560 (subject (gnus-summary-subject-string)))
9561 (org-store-link-props :type "gnus" :from from :subject subject
9562 :message-id message-id :group group)
9563 (setq cpltxt (org-email-link-description))
9564 (if (org-xor arg org-usenet-links-prefer-google)
9565 (setq link
9566 (concat
9567 cpltxt "\n "
9568 (format "http://groups.google.com/groups?as_umsgid=%s"
9569 (org-fixup-message-id-for-http message-id))))
9570 (setq link (org-make-link "gnus:" group
9571 "#" (number-to-string article))))))
9573 ((eq major-mode 'w3-mode)
9574 (setq cpltxt (url-view-url t)
9575 link (org-make-link cpltxt))
9576 (org-store-link-props :type "w3" :url (url-view-url t)))
9578 ((eq major-mode 'w3m-mode)
9579 (setq cpltxt (or w3m-current-title w3m-current-url)
9580 link (org-make-link w3m-current-url))
9581 (org-store-link-props :type "w3m" :url (url-view-url t)))
9583 ((setq search (run-hook-with-args-until-success
9584 'org-create-file-search-functions))
9585 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9586 "::" search))
9587 (setq cpltxt (or description link)))
9589 ((eq major-mode 'image-mode)
9590 (setq cpltxt (concat "file:"
9591 (abbreviate-file-name buffer-file-name))
9592 link (org-make-link cpltxt))
9593 (org-store-link-props :type "image" :file buffer-file-name))
9595 ((eq major-mode 'dired-mode)
9596 ;; link to the file in the current line
9597 (setq cpltxt (concat "file:"
9598 (abbreviate-file-name
9599 (expand-file-name
9600 (dired-get-filename nil t))))
9601 link (org-make-link cpltxt)))
9603 ((and buffer-file-name (org-mode-p))
9604 ;; Just link to current headline
9605 (setq cpltxt (concat "file:"
9606 (abbreviate-file-name buffer-file-name)))
9607 ;; Add a context search string
9608 (when (org-xor org-context-in-file-links arg)
9609 ;; Check if we are on a target
9610 (if (org-in-regexp "<<\\(.*?\\)>>")
9611 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9612 (setq txt (cond
9613 ((org-on-heading-p) nil)
9614 ((org-region-active-p)
9615 (buffer-substring (region-beginning) (region-end)))
9616 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9617 (when (or (null txt) (string-match "\\S-" txt))
9618 (setq cpltxt
9619 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9620 desc "NONE"))))
9621 (if (string-match "::\\'" cpltxt)
9622 (setq cpltxt (substring cpltxt 0 -2)))
9623 (setq link (org-make-link cpltxt)))
9625 (buffer-file-name
9626 ;; Just link to this file here.
9627 (setq cpltxt (concat "file:"
9628 (abbreviate-file-name buffer-file-name)))
9629 ;; Add a context string
9630 (when (org-xor org-context-in-file-links arg)
9631 (setq txt (if (org-region-active-p)
9632 (buffer-substring (region-beginning) (region-end))
9633 (buffer-substring (point-at-bol) (point-at-eol))))
9634 ;; Only use search option if there is some text.
9635 (when (string-match "\\S-" txt)
9636 (setq cpltxt
9637 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9638 desc "NONE")))
9639 (setq link (org-make-link cpltxt)))
9641 ((interactive-p)
9642 (error "Cannot link to a buffer which is not visiting a file"))
9644 (t (setq link nil)))
9646 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9647 (setq link (or link cpltxt)
9648 desc (or desc cpltxt))
9649 (if (equal desc "NONE") (setq desc nil))
9651 (if (and (interactive-p) link)
9652 (progn
9653 (setq org-stored-links
9654 (cons (list cpltxt link desc) org-stored-links))
9655 (message "Stored: %s" (or cpltxt link)))
9656 (org-make-link-string link desc))))
9658 (defun org-store-link-props (&rest plist)
9659 "Store link properties, extract names and addresses."
9660 (let (x adr)
9661 (when (setq x (plist-get plist :from))
9662 (setq adr (mail-extract-address-components x))
9663 (plist-put plist :fromname (car adr))
9664 (plist-put plist :fromaddress (nth 1 adr)))
9665 (when (setq x (plist-get plist :to))
9666 (setq adr (mail-extract-address-components x))
9667 (plist-put plist :toname (car adr))
9668 (plist-put plist :toaddress (nth 1 adr))))
9669 (let ((from (plist-get plist :from))
9670 (to (plist-get plist :to)))
9671 (when (and from to org-from-is-user-regexp)
9672 (plist-put plist :fromto
9673 (if (string-match org-from-is-user-regexp from)
9674 (concat "to %t")
9675 (concat "from %f")))))
9676 (setq org-store-link-plist plist))
9678 (defun org-email-link-description (&optional fmt)
9679 "Return the description part of an email link.
9680 This takes information from `org-store-link-plist' and formats it
9681 according to FMT (default from `org-email-link-description-format')."
9682 (setq fmt (or fmt org-email-link-description-format))
9683 (let* ((p org-store-link-plist)
9684 (to (plist-get p :toaddress))
9685 (from (plist-get p :fromaddress))
9686 (table
9687 (list
9688 (cons "%c" (plist-get p :fromto))
9689 (cons "%F" (plist-get p :from))
9690 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9691 (cons "%T" (plist-get p :to))
9692 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9693 (cons "%s" (plist-get p :subject))
9694 (cons "%m" (plist-get p :message-id)))))
9695 (when (string-match "%c" fmt)
9696 ;; Check if the user wrote this message
9697 (if (and org-from-is-user-regexp from to
9698 (save-match-data (string-match org-from-is-user-regexp from)))
9699 (setq fmt (replace-match "to %t" t t fmt))
9700 (setq fmt (replace-match "from %f" t t fmt))))
9701 (org-replace-escapes fmt table)))
9703 (defun org-make-org-heading-search-string (&optional string heading)
9704 "Make search string for STRING or current headline."
9705 (interactive)
9706 (let ((s (or string (org-get-heading))))
9707 (unless (and string (not heading))
9708 ;; We are using a headline, clean up garbage in there.
9709 (if (string-match org-todo-regexp s)
9710 (setq s (replace-match "" t t s)))
9711 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9712 (setq s (replace-match "" t t s)))
9713 (setq s (org-trim s))
9714 (if (string-match (concat "^\\(" org-quote-string "\\|"
9715 org-comment-string "\\)") s)
9716 (setq s (replace-match "" t t s)))
9717 (while (string-match org-ts-regexp s)
9718 (setq s (replace-match "" t t s))))
9719 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9720 (setq s (replace-match " " t t s)))
9721 (or string (setq s (concat "*" s))) ; Add * for headlines
9722 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9724 (defun org-make-link (&rest strings)
9725 "Concatenate STRINGS, format resulting string with `org-link-format'."
9726 (apply 'concat strings))
9728 (defun org-make-link-string (link &optional description)
9729 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9730 (when (stringp description)
9731 ;; Remove brackets from the description, they are fatal.
9732 (while (string-match "\\[\\|\\]" description)
9733 (setq description (replace-match "" t t description))))
9734 (when (equal (org-link-escape link) description)
9735 ;; No description needed, it is identical
9736 (setq description nil))
9737 (when (and (not description)
9738 (not (equal link (org-link-escape link))))
9739 (setq description link))
9740 (concat "[[" (org-link-escape link) "]"
9741 (if description (concat "[" description "]") "")
9742 "]"))
9744 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9745 "Association list of escapes for some characters problematic in links.")
9747 (defun org-link-escape (text)
9748 "Escape charaters in TEXT that are problematic for links."
9749 (when text
9750 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9751 org-link-escape-chars "\\|")))
9752 (while (string-match re text)
9753 (setq text
9754 (replace-match
9755 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9756 t t text)))
9757 text)))
9759 (defun org-link-unescape (text)
9760 "Reverse the action of `org-link-escape'."
9761 (when text
9762 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9763 org-link-escape-chars "\\|")))
9764 (while (string-match re text)
9765 (setq text
9766 (replace-match
9767 (car (rassoc (match-string 0 text) org-link-escape-chars))
9768 t t text)))
9769 text)))
9771 (defun org-xor (a b)
9772 "Exclusive or."
9773 (if a (not b) b))
9775 (defun org-get-header (header)
9776 "Find a header field in the current buffer."
9777 (save-excursion
9778 (goto-char (point-min))
9779 (let ((case-fold-search t) s)
9780 (cond
9781 ((eq header 'from)
9782 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
9783 (setq s (match-string 1)))
9784 (while (string-match "\"" s)
9785 (setq s (replace-match "" t t s)))
9786 (if (string-match "[<(].*" s)
9787 (setq s (replace-match "" t t s))))
9788 ((eq header 'message-id)
9789 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
9790 (setq s (match-string 1))))
9791 ((eq header 'subject)
9792 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
9793 (setq s (match-string 1)))))
9794 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
9795 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
9796 s)))
9799 (defun org-fixup-message-id-for-http (s)
9800 "Replace special characters in a message id, so it can be used in an http query."
9801 (while (string-match "<" s)
9802 (setq s (replace-match "%3C" t t s)))
9803 (while (string-match ">" s)
9804 (setq s (replace-match "%3E" t t s)))
9805 (while (string-match "@" s)
9806 (setq s (replace-match "%40" t t s)))
9809 (defun org-insert-link (&optional complete-file)
9810 "Insert a link. At the prompt, enter the link.
9812 Completion can be used to select a link previously stored with
9813 `org-store-link'. When the empty string is entered (i.e. if you just
9814 press RET at the prompt), the link defaults to the most recently
9815 stored link. As SPC triggers completion in the minibuffer, you need to
9816 use M-SPC or C-q SPC to force the insertion of a space character.
9818 You will also be prompted for a description, and if one is given, it will
9819 be displayed in the buffer instead of the link.
9821 If there is already a link at point, this command will allow you to edit link
9822 and description parts.
9824 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
9825 selected using completion. The path to the file will be relative to
9826 the current directory if the file is in the current directory or a
9827 subdirectory. Otherwise, the link will be the absolute path as
9828 completed in the minibuffer (i.e. normally ~/path/to/file).
9830 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
9831 is in the current directory or below.
9832 With three \\[universal-argument] prefixes, negate the meaning of
9833 `org-keep-stored-link-after-insertion'."
9834 (interactive "P")
9835 (let ((region (if (org-region-active-p)
9836 (prog1 (buffer-substring (region-beginning) (region-end))
9837 (delete-region (region-beginning) (region-end)))))
9838 tmphist ; byte-compile incorrectly complains about this
9839 link desc entry remove file)
9840 (cond
9841 ((org-in-regexp org-bracket-link-regexp 1)
9842 ;; We do have a link at point, and we are going to edit it.
9843 (setq remove (list (match-beginning 0) (match-end 0)))
9844 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9845 (setq link (read-string "Link: "
9846 (org-link-unescape
9847 (org-match-string-no-properties 1)))))
9848 ((or (org-in-regexp org-angle-link-re)
9849 (org-in-regexp org-plain-link-re))
9850 ;; Convert to bracket link
9851 (setq remove (list (match-beginning 0) (match-end 0))
9852 link (read-string "Link: "
9853 (org-remove-angle-brackets (match-string 0)))))
9854 ((equal complete-file '(4))
9855 ;; Completing read for file names.
9856 (setq file (read-file-name "File: "))
9857 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9858 (pwd1 (file-name-as-directory (abbreviate-file-name
9859 (expand-file-name ".")))))
9860 (cond
9861 ((equal complete-file '(16))
9862 (setq link (org-make-link
9863 "file:"
9864 (abbreviate-file-name (expand-file-name file)))))
9865 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9866 (setq link (org-make-link "file:" (match-string 1 file))))
9867 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9868 (expand-file-name file))
9869 (setq link (org-make-link
9870 "file:" (match-string 1 (expand-file-name file)))))
9871 (t (setq link (org-make-link "file:" file))))))
9873 ;; Read link, with completion for stored links.
9874 ;; Fake a link history
9875 (setq tmphist (append (mapcar 'car org-stored-links)
9876 org-insert-link-history))
9877 (setq link (org-completing-read
9878 "Link: " org-stored-links nil nil nil
9879 'tmphist
9880 (or (car (car org-stored-links)))))
9881 (setq entry (assoc link org-stored-links))
9882 (or entry (push link org-insert-link-history))
9883 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9884 (not org-keep-stored-link-after-insertion))
9885 (setq org-stored-links (delq (assoc link org-stored-links)
9886 org-stored-links)))
9887 (setq link (if entry (nth 1 entry) link)
9888 desc (or region desc (nth 2 entry)))))
9890 (if (string-match org-plain-link-re link)
9891 ;; URL-like link, normalize the use of angular brackets.
9892 (setq link (org-make-link (org-remove-angle-brackets link))))
9894 ;; Check if we are linking to the current file with a search option
9895 ;; If yes, simplify the link by using only the search option.
9896 (when (and buffer-file-name
9897 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
9898 (let* ((path (match-string 1 link))
9899 (case-fold-search nil)
9900 (search (match-string 2 link)))
9901 (save-match-data
9902 (if (equal (file-truename buffer-file-name) (file-truename path))
9903 ;; We are linking to this same file, with a search option
9904 (setq link search)))))
9906 ;; Check if we can/should use a relative path. If yes, simplify the link
9907 (when (string-match "\\<file:\\(.*\\)" link)
9908 (let* ((path (match-string 1 link))
9909 (case-fold-search nil))
9910 (cond
9911 ((eq org-link-file-path-type 'absolute)
9912 (setq path (abbreviate-file-name (expand-file-name path))))
9913 ((eq org-link-file-path-type 'noabbrev)
9914 (setq path (expand-file-name path)))
9915 ((eq org-link-file-path-type 'relative)
9916 (setq path (file-relative-name path)))
9918 (save-match-data
9919 (if (string-match (concat "^" (regexp-quote
9920 (file-name-as-directory
9921 (expand-file-name "."))))
9922 (expand-file-name path))
9923 ;; We are linking a file with relative path name.
9924 (setq path (substring (expand-file-name path)
9925 (match-end 0)))))))
9926 (setq link (concat "file:" path))))
9928 (setq desc (read-string "Description: " desc))
9929 (unless (string-match "\\S-" desc) (setq desc nil))
9930 (if remove (apply 'delete-region remove))
9931 (insert (org-make-link-string link desc))))
9933 (defun org-completing-read (&rest args)
9934 (let ((minibuffer-local-completion-map
9935 (copy-keymap minibuffer-local-completion-map)))
9936 (define-key minibuffer-local-completion-map " " 'self-insert-command)
9937 (apply 'completing-read args)))
9939 ;;; Opening/following a link
9940 (defvar org-link-search-failed nil)
9942 (defun org-next-link ()
9943 "Move forward to the next link.
9944 If the link is in hidden text, expose it."
9945 (interactive)
9946 (when (and org-link-search-failed (eq this-command last-command))
9947 (goto-char (point-min))
9948 (message "Link search wrapped back to beginning of buffer"))
9949 (setq org-link-search-failed nil)
9950 (let* ((pos (point))
9951 (ct (org-context))
9952 (a (assoc :link ct)))
9953 (if a (goto-char (nth 2 a)))
9954 (if (re-search-forward org-any-link-re nil t)
9955 (progn
9956 (goto-char (match-beginning 0))
9957 (if (org-invisible-p) (org-show-context)))
9958 (goto-char pos)
9959 (setq org-link-search-failed t)
9960 (error "No further link found"))))
9962 (defun org-previous-link ()
9963 "Move backward to the previous link.
9964 If the link is in hidden text, expose it."
9965 (interactive)
9966 (when (and org-link-search-failed (eq this-command last-command))
9967 (goto-char (point-max))
9968 (message "Link search wrapped back to end of buffer"))
9969 (setq org-link-search-failed nil)
9970 (let* ((pos (point))
9971 (ct (org-context))
9972 (a (assoc :link ct)))
9973 (if a (goto-char (nth 1 a)))
9974 (if (re-search-backward org-any-link-re nil t)
9975 (progn
9976 (goto-char (match-beginning 0))
9977 (if (org-invisible-p) (org-show-context)))
9978 (goto-char pos)
9979 (setq org-link-search-failed t)
9980 (error "No further link found"))))
9982 (defun org-find-file-at-mouse (ev)
9983 "Open file link or URL at mouse."
9984 (interactive "e")
9985 (mouse-set-point ev)
9986 (org-open-at-point 'in-emacs))
9988 (defun org-open-at-mouse (ev)
9989 "Open file link or URL at mouse."
9990 (interactive "e")
9991 (mouse-set-point ev)
9992 (org-open-at-point))
9994 (defvar org-window-config-before-follow-link nil
9995 "The window configuration before following a link.
9996 This is saved in case the need arises to restore it.")
9998 (defvar org-open-link-marker (make-marker)
9999 "Marker pointing to the location where `org-open-at-point; was called.")
10001 (defun org-open-at-point (&optional in-emacs)
10002 "Open link at or after point.
10003 If there is no link at point, this function will search forward up to
10004 the end of the current subtree.
10005 Normally, files will be opened by an appropriate application. If the
10006 optional argument IN-EMACS is non-nil, Emacs will visit the file."
10007 (interactive "P")
10008 (move-marker org-open-link-marker (point))
10009 (setq org-window-config-before-follow-link (current-window-configuration))
10010 (org-remove-occur-highlights nil nil t)
10011 (if (org-at-timestamp-p t)
10012 (org-follow-timestamp-link)
10013 (let (type path link line search (pos (point)))
10014 (catch 'match
10015 (save-excursion
10016 (skip-chars-forward "^]\n\r")
10017 (when (org-in-regexp org-bracket-link-regexp)
10018 (setq link (org-link-unescape (org-match-string-no-properties 1)))
10019 (while (string-match " *\n *" link)
10020 (setq link (replace-match " " t t link)))
10021 (setq link (org-link-expand-abbrev link))
10022 (if (string-match org-link-re-with-space2 link)
10023 (setq type (match-string 1 link) path (match-string 2 link))
10024 (setq type "thisfile" path link))
10025 (throw 'match t)))
10027 (when (get-text-property (point) 'org-linked-text)
10028 (setq type "thisfile"
10029 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10030 (1+ (point)) (point))
10031 path (buffer-substring
10032 (previous-single-property-change pos 'org-linked-text)
10033 (next-single-property-change pos 'org-linked-text)))
10034 (throw 'match t))
10036 (save-excursion
10037 (when (or (org-in-regexp org-angle-link-re)
10038 (org-in-regexp org-plain-link-re))
10039 (setq type (match-string 1) path (match-string 2))
10040 (throw 'match t)))
10041 (save-excursion
10042 (when (org-in-regexp "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
10043 (setq type "tags"
10044 path (match-string 1))
10045 (while (string-match ":" path)
10046 (setq path (replace-match "+" t t path)))
10047 (throw 'match t))))
10048 (unless path
10049 (error "No link found"))
10050 ;; Remove any trailing spaces in path
10051 (if (string-match " +\\'" path)
10052 (setq path (replace-match "" t t path)))
10054 (cond
10056 ((equal type "mailto")
10057 (let ((cmd (car org-link-mailto-program))
10058 (args (cdr org-link-mailto-program)) args1
10059 (address path) (subject "") a)
10060 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10061 (setq address (match-string 1 path)
10062 subject (org-link-escape (match-string 2 path))))
10063 (while args
10064 (cond
10065 ((not (stringp (car args))) (push (pop args) args1))
10066 (t (setq a (pop args))
10067 (if (string-match "%a" a)
10068 (setq a (replace-match address t t a)))
10069 (if (string-match "%s" a)
10070 (setq a (replace-match subject t t a)))
10071 (push a args1))))
10072 (apply cmd (nreverse args1))))
10074 ((member type '("http" "https" "ftp" "news"))
10075 (browse-url (concat type ":" path)))
10077 ((string= type "tags")
10078 (org-tags-view in-emacs path))
10079 ((string= type "thisfile")
10080 (if in-emacs
10081 (switch-to-buffer-other-window
10082 (org-get-buffer-for-internal-link (current-buffer)))
10083 (org-mark-ring-push))
10084 (org-link-search
10085 path
10086 (cond ((equal in-emacs '(4)) 'occur)
10087 ((equal in-emacs '(16)) 'org-occur)
10088 (t nil))
10089 pos))
10091 ((string= type "file")
10092 (if (string-match "::\\([0-9]+\\)\\'" path)
10093 (setq line (string-to-number (match-string 1 path))
10094 path (substring path 0 (match-beginning 0)))
10095 (if (string-match "::\\(.+\\)\\'" path)
10096 (setq search (match-string 1 path)
10097 path (substring path 0 (match-beginning 0)))))
10098 (org-open-file path in-emacs line search))
10100 ((string= type "news")
10101 (org-follow-gnus-link path))
10103 ((string= type "bbdb")
10104 (org-follow-bbdb-link path))
10106 ((string= type "info")
10107 (org-follow-info-link path))
10109 ((string= type "gnus")
10110 (let (group article)
10111 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10112 (error "Error in Gnus link"))
10113 (setq group (match-string 1 path)
10114 article (match-string 3 path))
10115 (org-follow-gnus-link group article)))
10117 ((string= type "vm")
10118 (let (folder article)
10119 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10120 (error "Error in VM link"))
10121 (setq folder (match-string 1 path)
10122 article (match-string 3 path))
10123 ;; in-emacs is the prefix arg, will be interpreted as read-only
10124 (org-follow-vm-link folder article in-emacs)))
10126 ((string= type "wl")
10127 (let (folder article)
10128 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10129 (error "Error in Wanderlust link"))
10130 (setq folder (match-string 1 path)
10131 article (match-string 3 path))
10132 (org-follow-wl-link folder article)))
10134 ((string= type "mhe")
10135 (let (folder article)
10136 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10137 (error "Error in MHE link"))
10138 (setq folder (match-string 1 path)
10139 article (match-string 3 path))
10140 (org-follow-mhe-link folder article)))
10142 ((string= type "rmail")
10143 (let (folder article)
10144 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10145 (error "Error in RMAIL link"))
10146 (setq folder (match-string 1 path)
10147 article (match-string 3 path))
10148 (org-follow-rmail-link folder article)))
10150 ((string= type "shell")
10151 (let ((cmd path))
10152 ;; FIXME: the following is only for backward compatibility
10153 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
10154 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
10155 (if (or (not org-confirm-shell-link-function)
10156 (funcall org-confirm-shell-link-function
10157 (format "Execute \"%s\" in shell? "
10158 (org-add-props cmd nil
10159 'face 'org-warning))))
10160 (progn
10161 (message "Executing %s" cmd)
10162 (shell-command cmd))
10163 (error "Abort"))))
10165 ((string= type "elisp")
10166 (let ((cmd path))
10167 (if (or (not org-confirm-elisp-link-function)
10168 (funcall org-confirm-elisp-link-function
10169 (format "Execute \"%s\" as elisp? "
10170 (org-add-props cmd nil
10171 'face 'org-warning))))
10172 (message "%s => %s" cmd (eval (read cmd)))
10173 (error "Abort"))))
10176 (browse-url-at-point)))))
10177 (move-marker org-open-link-marker nil))
10180 ;;; File search
10182 (defvar org-create-file-search-functions nil
10183 "List of functions to construct the right search string for a file link.
10184 These functions are called in turn with point at the location to
10185 which the link should point.
10187 A function in the hook should first test if it would like to
10188 handle this file type, for example by checking the major-mode or
10189 the file extension. If it decides not to handle this file, it
10190 should just return nil to give other functions a chance. If it
10191 does handle the file, it must return the search string to be used
10192 when following the link. The search string will be part of the
10193 file link, given after a double colon, and `org-open-at-point'
10194 will automatically search for it. If special measures must be
10195 taken to make the search successful, another function should be
10196 added to the companion hook `org-execute-file-search-functions',
10197 which see.
10199 A function in this hook may also use `setq' to set the variable
10200 `description' to provide a suggestion for the descriptive text to
10201 be used for this link when it gets inserted into an Org-mode
10202 buffer with \\[org-insert-link].")
10204 (defvar org-execute-file-search-functions nil
10205 "List of functions to execute a file search triggered by a link.
10207 Functions added to this hook must accept a single argument, the
10208 search string that was part of the file link, the part after the
10209 double colon. The function must first check if it would like to
10210 handle this search, for example by checking the major-mode or the
10211 file extension. If it decides not to handle this search, it
10212 should just return nil to give other functions a chance. If it
10213 does handle the search, it must return a non-nil value to keep
10214 other functions from trying.
10216 Each function can access the current prefix argument through the
10217 variable `current-prefix-argument'. Note that a single prefix is
10218 used to force opening a link in Emacs, so it may be good to only
10219 use a numeric or double prefix to guide the search function.
10221 In case this is needed, a function in this hook can also restore
10222 the window configuration before `org-open-at-point' was called using:
10224 (set-window-configuration org-window-config-before-follow-link)")
10226 (defun org-link-search (s &optional type avoid-pos)
10227 "Search for a link search option.
10228 If S is surrounded by forward slashes, it is interpreted as a
10229 regular expression. In org-mode files, this will create an `org-occur'
10230 sparse tree. In ordinary files, `occur' will be used to list matches.
10231 If the current buffer is in `dired-mode', grep will be used to search
10232 in all files. If AVOID-POS is given, ignore matches near that position."
10233 (let ((case-fold-search t)
10234 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10235 (pos (point))
10236 (pre "") (post "")
10237 words re0 re1 re2 re3 re4 re5 re2a reall)
10238 (cond
10239 ;; First check if there are any special
10240 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10241 ;; Now try the builtin stuff
10242 ((save-excursion
10243 (goto-char (point-min))
10244 (and
10245 (re-search-forward
10246 (concat "<<" (regexp-quote s0) ">>") nil t)
10247 (setq pos (match-beginning 0))))
10248 ;; There is an exact target for this
10249 (goto-char pos))
10250 ((string-match "^/\\(.*\\)/$" s)
10251 ;; A regular expression
10252 (cond
10253 ((org-mode-p)
10254 (org-occur (match-string 1 s)))
10255 ;;((eq major-mode 'dired-mode)
10256 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10257 (t (org-do-occur (match-string 1 s)))))
10259 ;; A normal search string
10260 (when (equal (string-to-char s) ?*)
10261 ;; Anchor on headlines, post may include tags.
10262 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
10263 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
10264 s (substring s 1)))
10265 (remove-text-properties
10266 0 (length s)
10267 '(face nil mouse-face nil keymap nil fontified nil) s)
10268 ;; Make a series of regular expressions to find a match
10269 (setq words (org-split-string s "[ \n\r\t]+")
10270 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10271 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
10272 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10273 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10274 re1 (concat pre re2 post)
10275 re3 (concat pre re4 post)
10276 re5 (concat pre ".*" re4)
10277 re2 (concat pre re2)
10278 re2a (concat pre re2a)
10279 re4 (concat pre re4)
10280 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10281 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10282 re5 "\\)"
10284 (cond
10285 ((eq type 'org-occur) (org-occur reall))
10286 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10287 (t (goto-char (point-min))
10288 (if (or (org-search-not-self 1 re0 nil t)
10289 (org-search-not-self 1 re1 nil t)
10290 (org-search-not-self 1 re2 nil t)
10291 (org-search-not-self 1 re2a nil t)
10292 (org-search-not-self 1 re3 nil t)
10293 (org-search-not-self 1 re4 nil t)
10294 (org-search-not-self 1 re5 nil t)
10296 (goto-char (match-beginning 1))
10297 (goto-char pos)
10298 (error "No match")))))
10300 ;; Normal string-search
10301 (goto-char (point-min))
10302 (if (search-forward s nil t)
10303 (goto-char (match-beginning 0))
10304 (error "No match"))))
10305 (and (org-mode-p) (org-show-context 'link-search))))
10307 (defun org-search-not-self (group &rest args)
10308 "Execute `re-search-forward', but only accept matches that do not
10309 enclose the position of `org-open-link-marker'."
10310 (let ((m org-open-link-marker))
10311 (catch 'exit
10312 (while (apply 're-search-forward args)
10313 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10314 (goto-char (match-end group))
10315 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10316 (> (match-beginning 0) (marker-position m))
10317 (< (match-end 0) (marker-position m)))
10318 (save-match-data
10319 (or (not (org-in-regexp
10320 org-bracket-link-analytic-regexp 1))
10321 (not (match-end 4)) ; no description
10322 (and (<= (match-beginning 4) (point))
10323 (>= (match-end 4) (point))))))
10324 (throw 'exit (point))))))))
10326 (defun org-get-buffer-for-internal-link (buffer)
10327 "Return a buffer to be used for displaying the link target of internal links."
10328 (cond
10329 ((not org-display-internal-link-with-indirect-buffer)
10330 buffer)
10331 ((string-match "(Clone)$" (buffer-name buffer))
10332 (message "Buffer is already a clone, not making another one")
10333 ;; we also do not modify visibility in this case
10334 buffer)
10335 (t ; make a new indirect buffer for displaying the link
10336 (let* ((bn (buffer-name buffer))
10337 (ibn (concat bn "(Clone)"))
10338 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10339 (with-current-buffer ib (org-overview))
10340 ib))))
10342 (defun org-do-occur (regexp &optional cleanup)
10343 "Call the Emacs command `occur'.
10344 If CLEANUP is non-nil, remove the printout of the regular expression
10345 in the *Occur* buffer. This is useful if the regex is long and not useful
10346 to read."
10347 (occur regexp)
10348 (when cleanup
10349 (let ((cwin (selected-window)) win beg end)
10350 (when (setq win (get-buffer-window "*Occur*"))
10351 (select-window win))
10352 (goto-char (point-min))
10353 (when (re-search-forward "match[a-z]+" nil t)
10354 (setq beg (match-end 0))
10355 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10356 (setq end (1- (match-beginning 0)))))
10357 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
10358 (goto-char (point-min))
10359 (select-window cwin))))
10361 ;;; The mark ring for links jumps
10363 (defvar org-mark-ring nil
10364 "Mark ring for positions before jumps in Org-mode.")
10365 (defvar org-mark-ring-last-goto nil
10366 "Last position in the mark ring used to go back.")
10367 ;; Fill and close the ring
10368 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10369 (loop for i from 1 to org-mark-ring-length do
10370 (push (make-marker) org-mark-ring))
10371 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10372 org-mark-ring)
10374 (defun org-mark-ring-push (&optional pos buffer)
10375 "Put the current position or POS into the mark ring and rotate it."
10376 (interactive)
10377 (setq pos (or pos (point)))
10378 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10379 (move-marker (car org-mark-ring)
10380 (or pos (point))
10381 (or buffer (current-buffer)))
10382 (message
10383 (substitute-command-keys
10384 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10386 (defun org-mark-ring-goto (&optional n)
10387 "Jump to the previous position in the mark ring.
10388 With prefix arg N, jump back that many stored positions. When
10389 called several times in succession, walk through the entire ring.
10390 Org-mode commands jumping to a different position in the current file,
10391 or to another Org-mode file, automatically push the old position
10392 onto the ring."
10393 (interactive "p")
10394 (let (p m)
10395 (if (eq last-command this-command)
10396 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10397 (setq p org-mark-ring))
10398 (setq org-mark-ring-last-goto p)
10399 (setq m (car p))
10400 (switch-to-buffer (marker-buffer m))
10401 (goto-char m)
10402 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10404 (defun org-remove-angle-brackets (s)
10405 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10406 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10408 (defun org-add-angle-brackets (s)
10409 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10410 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10413 ;;; Following specific links
10415 (defun org-follow-timestamp-link ()
10416 (cond
10417 ((org-at-date-range-p t)
10418 (let ((org-agenda-start-on-weekday)
10419 (t1 (match-string 1))
10420 (t2 (match-string 2)))
10421 (setq t1 (time-to-days (org-time-string-to-time t1))
10422 t2 (time-to-days (org-time-string-to-time t2)))
10423 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10424 ((org-at-timestamp-p t)
10425 (org-agenda-list nil (time-to-days (org-time-string-to-time
10426 (substring (match-string 1) 0 10)))
10428 (t (error "This should not happen"))))
10431 (defun org-follow-bbdb-link (name)
10432 "Follow a BBDB link to NAME."
10433 (require 'bbdb)
10434 (let ((inhibit-redisplay (not debug-on-error))
10435 (bbdb-electric-p nil))
10436 (catch 'exit
10437 ;; Exact match on name
10438 (bbdb-name (concat "\\`" name "\\'") nil)
10439 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10440 ;; Exact match on name
10441 (bbdb-company (concat "\\`" name "\\'") nil)
10442 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10443 ;; Partial match on name
10444 (bbdb-name name nil)
10445 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10446 ;; Partial match on company
10447 (bbdb-company name nil)
10448 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10449 ;; General match including network address and notes
10450 (bbdb name nil)
10451 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10452 (delete-window (get-buffer-window "*BBDB*"))
10453 (error "No matching BBDB record")))))
10455 (defun org-follow-info-link (name)
10456 "Follow an info file & node link to NAME."
10457 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10458 (string-match "\\(.*\\)" name))
10459 (progn
10460 (require 'info)
10461 (if (match-string 2 name) ; If there isn't a node, choose "Top"
10462 (Info-find-node (match-string 1 name) (match-string 2 name))
10463 (Info-find-node (match-string 1 name) "Top")))
10464 (message (concat "Could not open: " name))))
10466 (defun org-follow-gnus-link (&optional group article)
10467 "Follow a Gnus link to GROUP and ARTICLE."
10468 (require 'gnus)
10469 (funcall (cdr (assq 'gnus org-link-frame-setup)))
10470 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10471 (cond ((and group article)
10472 (gnus-group-read-group 0 nil group)
10473 (gnus-summary-goto-article (string-to-number article) nil t))
10474 (group (gnus-group-jump-to-group group))))
10476 (defun org-follow-vm-link (&optional folder article readonly)
10477 "Follow a VM link to FOLDER and ARTICLE."
10478 (require 'vm)
10479 (setq article (org-add-angle-brackets article))
10480 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
10481 ;; ange-ftp or efs or tramp access
10482 (let ((user (or (match-string 1 folder) (user-login-name)))
10483 (host (match-string 2 folder))
10484 (file (match-string 3 folder)))
10485 (cond
10486 ((featurep 'tramp)
10487 ;; use tramp to access the file
10488 (if (featurep 'xemacs)
10489 (setq folder (format "[%s@%s]%s" user host file))
10490 (setq folder (format "/%s@%s:%s" user host file))))
10492 ;; use ange-ftp or efs
10493 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
10494 (setq folder (format "/%s@%s:%s" user host file))))))
10495 (when folder
10496 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
10497 (sit-for 0.1)
10498 (when article
10499 (vm-select-folder-buffer)
10500 (widen)
10501 (let ((case-fold-search t))
10502 (goto-char (point-min))
10503 (if (not (re-search-forward
10504 (concat "^" "message-id: *" (regexp-quote article))))
10505 (error "Could not find the specified message in this folder"))
10506 (vm-isearch-update)
10507 (vm-isearch-narrow)
10508 (vm-beginning-of-message)
10509 (vm-summarize)))))
10511 (defun org-follow-wl-link (folder article)
10512 "Follow a Wanderlust link to FOLDER and ARTICLE."
10513 (if (and (string= folder "%")
10514 article
10515 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
10516 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
10517 ;; Thus, we recompose folder and article ids.
10518 (setq folder (format "%s#%s" folder (match-string 1 article))
10519 article (match-string 3 article)))
10520 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
10521 (error "No such folder: %s" folder))
10522 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
10523 (and article
10524 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
10525 (wl-summary-redisplay)))
10527 (defun org-follow-rmail-link (folder article)
10528 "Follow an RMAIL link to FOLDER and ARTICLE."
10529 (setq article (org-add-angle-brackets article))
10530 (let (message-number)
10531 (save-excursion
10532 (save-window-excursion
10533 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10534 (setq message-number
10535 (save-restriction
10536 (widen)
10537 (goto-char (point-max))
10538 (if (re-search-backward
10539 (concat "^Message-ID:\\s-+" (regexp-quote
10540 (or article "")))
10541 nil t)
10542 (rmail-what-message))))))
10543 (if message-number
10544 (progn
10545 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10546 (rmail-show-message message-number)
10547 message-number)
10548 (error "Message not found"))))
10550 ;;; mh-e integration based on planner-mode
10551 (defun org-mhe-get-message-real-folder ()
10552 "Return the name of the current message real folder, so if you use
10553 sequences, it will now work."
10554 (save-excursion
10555 (let* ((folder
10556 (if (equal major-mode 'mh-folder-mode)
10557 mh-current-folder
10558 ;; Refer to the show buffer
10559 mh-show-folder-buffer))
10560 (end-index
10561 (if (boundp 'mh-index-folder)
10562 (min (length mh-index-folder) (length folder))))
10564 ;; a simple test on mh-index-data does not work, because
10565 ;; mh-index-data is always nil in a show buffer.
10566 (if (and (boundp 'mh-index-folder)
10567 (string= mh-index-folder (substring folder 0 end-index)))
10568 (if (equal major-mode 'mh-show-mode)
10569 (save-window-excursion
10570 (when (buffer-live-p (get-buffer folder))
10571 (progn
10572 (pop-to-buffer folder)
10573 (org-mhe-get-message-folder-from-index)
10576 (org-mhe-get-message-folder-from-index)
10578 folder
10582 (defun org-mhe-get-message-folder-from-index ()
10583 "Returns the name of the message folder in a index folder buffer."
10584 (save-excursion
10585 (mh-index-previous-folder)
10586 (re-search-forward "^\\(+.*\\)$" nil t)
10587 (message (match-string 1))))
10589 (defun org-mhe-get-message-folder ()
10590 "Return the name of the current message folder. Be careful if you
10591 use sequences."
10592 (save-excursion
10593 (if (equal major-mode 'mh-folder-mode)
10594 mh-current-folder
10595 ;; Refer to the show buffer
10596 mh-show-folder-buffer)))
10598 (defun org-mhe-get-message-num ()
10599 "Return the number of the current message. Be careful if you
10600 use sequences."
10601 (save-excursion
10602 (if (equal major-mode 'mh-folder-mode)
10603 (mh-get-msg-num nil)
10604 ;; Refer to the show buffer
10605 (mh-show-buffer-message-number))))
10607 (defun org-mhe-get-header (header)
10608 "Return a header of the message in folder mode. This will create a
10609 show buffer for the corresponding message. If you have a more clever
10610 idea..."
10611 (let* ((folder (org-mhe-get-message-folder))
10612 (num (org-mhe-get-message-num))
10613 (buffer (get-buffer-create (concat "show-" folder)))
10614 (header-field))
10615 (with-current-buffer buffer
10616 (mh-display-msg num folder)
10617 (if (equal major-mode 'mh-folder-mode)
10618 (mh-header-display)
10619 (mh-show-header-display))
10620 (set-buffer buffer)
10621 (setq header-field (mh-get-header-field header))
10622 (if (equal major-mode 'mh-folder-mode)
10623 (mh-show)
10624 (mh-show-show))
10625 header-field)))
10627 (defun org-follow-mhe-link (folder article)
10628 "Follow an MHE link to FOLDER and ARTICLE.
10629 If ARTICLE is nil FOLDER is shown. If the configuration variable
10630 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
10631 ARTICLE is searched in all folders. Indexed searches (swish++,
10632 namazu, and others supported by MH-E) will always search in all
10633 folders."
10634 (require 'mh-e)
10635 (require 'mh-search)
10636 (require 'mh-utils)
10637 (mh-find-path)
10638 (if (not article)
10639 (mh-visit-folder (mh-normalize-folder-name folder))
10640 (setq article (org-add-angle-brackets article))
10641 (mh-search-choose)
10642 (if (equal mh-searcher 'pick)
10643 (progn
10644 (mh-search folder (list "--message-id" article))
10645 (when (and org-mhe-search-all-folders
10646 (not (org-mhe-get-message-real-folder)))
10647 (kill-this-buffer)
10648 (mh-search "+" (list "--message-id" article))))
10649 (mh-search "+" article))
10650 (if (org-mhe-get-message-real-folder)
10651 (mh-show-msg 1)
10652 (kill-this-buffer)
10653 (error "Message not found"))))
10655 ;;; BibTeX links
10657 ;; Use the custom search meachnism to construct and use search strings for
10658 ;; file links to BibTeX database entries.
10660 (defun org-create-file-search-in-bibtex ()
10661 "Create the search string and description for a BibTeX database entry."
10662 (when (eq major-mode 'bibtex-mode)
10663 ;; yes, we want to construct this search string.
10664 ;; Make a good description for this entry, using names, year and the title
10665 ;; Put it into the `description' variable which is dynamically scoped.
10666 (let ((bibtex-autokey-names 1)
10667 (bibtex-autokey-names-stretch 1)
10668 (bibtex-autokey-name-case-convert-function 'identity)
10669 (bibtex-autokey-name-separator " & ")
10670 (bibtex-autokey-additional-names " et al.")
10671 (bibtex-autokey-year-length 4)
10672 (bibtex-autokey-name-year-separator " ")
10673 (bibtex-autokey-titlewords 3)
10674 (bibtex-autokey-titleword-separator " ")
10675 (bibtex-autokey-titleword-case-convert-function 'identity)
10676 (bibtex-autokey-titleword-length 'infty)
10677 (bibtex-autokey-year-title-separator ": "))
10678 (setq description (bibtex-generate-autokey)))
10679 ;; Now parse the entry, get the key and return it.
10680 (save-excursion
10681 (bibtex-beginning-of-entry)
10682 (cdr (assoc "=key=" (bibtex-parse-entry))))))
10684 (defun org-execute-file-search-in-bibtex (s)
10685 "Find the link search string S as a key for a database entry."
10686 (when (eq major-mode 'bibtex-mode)
10687 ;; Yes, we want to do the search in this file.
10688 ;; We construct a regexp that searches for "@entrytype{" followed by the key
10689 (goto-char (point-min))
10690 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
10691 (regexp-quote s) "[ \t\n]*,") nil t)
10692 (goto-char (match-beginning 0)))
10693 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
10694 ;; Use double prefix to indicate that any web link should be browsed
10695 (let ((b (current-buffer)) (p (point)))
10696 ;; Restore the window configuration because we just use the web link
10697 (set-window-configuration org-window-config-before-follow-link)
10698 (save-excursion (set-buffer b) (goto-char p)
10699 (bibtex-url)))
10700 (recenter 0)) ; Move entry start to beginning of window
10701 ;; return t to indicate that the search is done.
10704 ;; Finally add the functions to the right hooks.
10705 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10706 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10708 ;; end of Bibtex link setup
10710 ;;; Following file links
10712 (defun org-open-file (path &optional in-emacs line search)
10713 "Open the file at PATH.
10714 First, this expands any special file name abbreviations. Then the
10715 configuration variable `org-file-apps' is checked if it contains an
10716 entry for this file type, and if yes, the corresponding command is launched.
10717 If no application is found, Emacs simply visits the file.
10718 With optional argument IN-EMACS, Emacs will visit the file.
10719 Optional LINE specifies a line to go to, optional SEARCH a string to
10720 search for. If LINE or SEARCH is given, the file will always be
10721 opened in Emacs.
10722 If the file does not exist, an error is thrown."
10723 (setq in-emacs (or in-emacs line search))
10724 (let* ((file (if (equal path "")
10725 buffer-file-name
10726 (substitute-in-file-name (expand-file-name path))))
10727 (apps (append org-file-apps (org-default-apps)))
10728 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10729 (dirp (if remp nil (file-directory-p file)))
10730 (dfile (downcase file))
10731 (old-buffer (current-buffer))
10732 (old-pos (point))
10733 (old-mode major-mode)
10734 ext cmd)
10735 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10736 (setq ext (match-string 1 dfile))
10737 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10738 (setq ext (match-string 1 dfile))))
10739 (if in-emacs
10740 (setq cmd 'emacs)
10741 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10742 (and dirp (cdr (assoc 'directory apps)))
10743 (cdr (assoc ext apps))
10744 (cdr (assoc t apps)))))
10745 (when (eq cmd 'mailcap)
10746 (require 'mailcap)
10747 (mailcap-parse-mailcaps)
10748 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10749 (command (mailcap-mime-info mime-type)))
10750 (if (stringp command)
10751 (setq cmd command)
10752 (setq cmd 'emacs))))
10753 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10754 (not (file-exists-p file))
10755 (not org-open-non-existing-files))
10756 (error "No such file: %s" file))
10757 (cond
10758 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10759 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10760 (if (string-match "['\"]%s['\"]" cmd)
10761 (setq cmd (replace-match "%s" t t cmd)))
10762 (setq cmd (format cmd (shell-quote-argument file)))
10763 (save-window-excursion
10764 (shell-command (concat cmd " &"))))
10765 ((or (stringp cmd)
10766 (eq cmd 'emacs))
10767 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10768 (if line (goto-line line)
10769 (if search (org-link-search search))))
10770 ((consp cmd)
10771 (eval cmd))
10772 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10773 (and (org-mode-p) (eq old-mode 'org-mode)
10774 (or (not (equal old-buffer (current-buffer)))
10775 (not (equal old-pos (point))))
10776 (org-mark-ring-push old-pos old-buffer))))
10778 (defun org-default-apps ()
10779 "Return the default applications for this operating system."
10780 (cond
10781 ((eq system-type 'darwin)
10782 org-file-apps-defaults-macosx)
10783 ((eq system-type 'windows-nt)
10784 org-file-apps-defaults-windowsnt)
10785 (t org-file-apps-defaults-gnu)))
10787 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10788 (defun org-file-remote-p (file)
10789 "Test whether FILE specifies a location on a remote system.
10790 Return non-nil if the location is indeed remote.
10792 For example, the filename \"/user@host:/foo\" specifies a location
10793 on the system \"/user@host:\"."
10794 (cond ((fboundp 'file-remote-p)
10795 (file-remote-p file))
10796 ((fboundp 'tramp-handle-file-remote-p)
10797 (tramp-handle-file-remote-p file))
10798 ((and (boundp 'ange-ftp-name-format)
10799 (string-match (car ange-ftp-name-format) file))
10801 (t nil)))
10804 ;;;; Hooks for remember.el
10806 ;;;###autoload
10807 (defun org-remember-annotation ()
10808 "Return a link to the current location as an annotation for remember.el.
10809 If you are using Org-mode files as target for data storage with
10810 remember.el, then the annotations should include a link compatible with the
10811 conventions in Org-mode. This function returns such a link."
10812 (org-store-link nil))
10814 (defconst org-remember-help
10815 "Select a destination location for the note.
10816 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10817 RET at beg-of-buf -> Append to file as level 2 headline
10818 RET on headline -> Store as sublevel entry to current headline
10819 <left>/<right> -> before/after current headline, same headings level")
10821 ;;;###autoload
10822 (defun org-remember-apply-template (&optional use-char skip-interactive)
10823 "Initialize *remember* buffer with template, invoke `org-mode'.
10824 This function should be placed into `remember-mode-hook' and in fact requires
10825 to be run from that hook to fucntion properly."
10826 (if org-remember-templates
10828 (let* ((char (or use-char
10829 (if (= (length org-remember-templates) 1)
10830 (caar org-remember-templates)
10831 (message "Select template: %s"
10832 (mapconcat
10833 (lambda (x) (char-to-string (car x)))
10834 org-remember-templates " "))
10835 (read-char-exclusive))))
10836 (entry (cdr (assoc char org-remember-templates)))
10837 (tpl (car entry))
10838 (plist-p (if org-store-link-plist t nil))
10839 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
10840 (string-match "\\S-" (nth 1 entry)))
10841 (nth 1 entry)
10842 org-default-notes-file))
10843 (headline (nth 2 entry))
10844 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10845 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10846 (v-u (concat "[" (substring v-t 1 -1) "]"))
10847 (v-U (concat "[" (substring v-T 1 -1) "]"))
10848 (v-i initial) ; defined in `remember-mode'
10849 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
10850 (v-n user-full-name)
10851 (org-startup-folded nil)
10852 org-time-was-given x prompt char time)
10853 (setq org-store-link-plist
10854 (append (list :annotation v-a :initial v-i)))
10855 (unless tpl (setq tpl "") (message "No template") (ding))
10856 (erase-buffer)
10857 (insert (substitute-command-keys
10858 (format
10859 "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
10860 ## Target file \"%s\", headline \"%s\"
10861 ## To switch templates, use `\\[org-remember]'.\n\n"
10862 (abbreviate-file-name (or file org-default-notes-file))
10863 (or headline ""))))
10864 (insert tpl) (goto-char (point-min))
10865 ;; Simple %-escapes
10866 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
10867 (when (and initial (equal (match-string 0) "%i"))
10868 (save-match-data
10869 (let* ((lead (buffer-substring
10870 (point-at-bol) (match-beginning 0))))
10871 (setq v-i (mapconcat 'identity
10872 (org-split-string initial "\n")
10873 (concat "\n" lead))))))
10874 (replace-match
10875 (or (eval (intern (concat "v-" (match-string 1)))) "")
10876 t t))
10877 ;; From the property list
10878 (when plist-p
10879 (goto-char (point-min))
10880 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
10881 (and (setq x (plist-get org-store-link-plist
10882 (intern (match-string 1))))
10883 (replace-match x t t))))
10884 ;; Turn on org-mode in the remember buffer, set local variables
10885 (org-mode)
10886 (org-set-local 'org-finish-function 'remember-buffer)
10887 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10888 (org-set-local 'org-default-notes-file file))
10889 (if (and headline (stringp headline) (string-match "\\S-" headline))
10890 (org-set-local 'org-remember-default-headline headline))
10891 ;; Interactive template entries
10892 (goto-char (point-min))
10893 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([uUtT]\\)?" nil t)
10894 (setq char (if (match-end 3) (match-string 3))
10895 prompt (if (match-end 2) (match-string 2)))
10896 (goto-char (match-beginning 0))
10897 (replace-match "")
10898 (if char
10899 (progn
10900 (setq org-time-was-given (equal (upcase char) char))
10901 (setq time (org-read-date (equal (upcase char) "U") t nil
10902 prompt))
10903 (org-insert-time-stamp time org-time-was-given
10904 (member char '("u" "U"))))
10905 (insert (read-string
10906 (if prompt (concat prompt ": ") "Enter string")))))
10907 (goto-char (point-min))
10908 (if (re-search-forward "%\\?" nil t)
10909 (replace-match "")
10910 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
10911 (org-mode)
10912 (org-set-local 'org-finish-function 'remember-buffer)))
10914 ;;;###autoload
10915 (defun org-remember ()
10916 "Call `remember'. If this is already a remember buffer, re-apply template.
10917 If there is an active region, make sure remember uses it as initial content
10918 of the remember buffer."
10919 (interactive)
10920 (if (eq org-finish-function 'remember-buffer)
10921 (progn
10922 (when (< (length org-remember-templates) 2)
10923 (error "No other template available"))
10924 (erase-buffer)
10925 (let ((annotation (plist-get org-store-link-plist :annotation))
10926 (initial (plist-get org-store-link-plist :initial)))
10927 (org-remember-apply-template))
10928 (message "Press C-c C-c to remember data"))
10929 (if (org-region-active-p)
10930 (remember (buffer-substring (point) (mark)))
10931 (call-interactively 'remember))))
10933 ;;;###autoload
10934 (defun org-remember-handler ()
10935 "Store stuff from remember.el into an org file.
10936 First prompts for an org file. If the user just presses return, the value
10937 of `org-default-notes-file' is used.
10938 Then the command offers the headings tree of the selected file in order to
10939 file the text at a specific location.
10940 You can either immediately press RET to get the note appended to the
10941 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10942 find a better place. Then press RET or <left> or <right> in insert the note.
10944 Key Cursor position Note gets inserted
10945 -----------------------------------------------------------------------------
10946 RET buffer-start as level 2 heading at end of file
10947 RET on headline as sublevel of the heading at cursor
10948 RET no heading at cursor position, level taken from context.
10949 Or use prefix arg to specify level manually.
10950 <left> on headline as same level, before current heading
10951 <right> on headline as same level, after current heading
10953 So the fastest way to store the note is to press RET RET to append it to
10954 the default file. This way your current train of thought is not
10955 interrupted, in accordance with the principles of remember.el. But with
10956 little extra effort, you can push it directly to the correct location.
10958 Before being stored away, the function ensures that the text has a
10959 headline, i.e. a first line that starts with a \"*\". If not, a headline
10960 is constructed from the current date and some additional data.
10962 If the variable `org-adapt-indentation' is non-nil, the entire text is
10963 also indented so that it starts in the same column as the headline
10964 \(i.e. after the stars).
10966 See also the variable `org-reverse-note-order'."
10967 (goto-char (point-min))
10968 (while (looking-at "^[ \t]*\n\\|^##.*\n")
10969 (replace-match ""))
10970 (catch 'quit
10971 (let* ((txt (buffer-substring (point-min) (point-max)))
10972 (fastp current-prefix-arg)
10973 (file (if fastp org-default-notes-file (org-get-org-file)))
10974 (heading org-remember-default-headline)
10975 (visiting (org-find-base-buffer-visiting file))
10976 (org-startup-folded nil)
10977 (org-startup-align-all-tables nil)
10978 (org-goto-start-pos 1)
10979 spos level indent reversed)
10980 ;; Modify text so that it becomes a nice subtree which can be inserted
10981 ;; into an org tree.
10982 (let* ((lines (split-string txt "\n"))
10983 first)
10984 (setq first (car lines) lines (cdr lines))
10985 (if (string-match "^\\*+" first)
10986 ;; Is already a headline
10987 (setq indent nil)
10988 ;; We need to add a headline: Use time and first buffer line
10989 (setq lines (cons first lines)
10990 first (concat "* " (current-time-string)
10991 " (" (remember-buffer-desc) ")")
10992 indent " "))
10993 (if (and org-adapt-indentation indent)
10994 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10995 (setq txt (concat first "\n"
10996 (mapconcat 'identity lines "\n"))))
10997 ;; Find the file
10998 (if (not visiting) (find-file-noselect file))
10999 (with-current-buffer (or visiting (get-file-buffer file))
11000 (save-excursion (and (goto-char (point-min))
11001 (not (re-search-forward "^\\* " nil t))
11002 (insert "\n* Notes\n")))
11003 (setq reversed (org-notes-order-reversed-p))
11004 (save-excursion
11005 (save-restriction
11006 (widen)
11008 ;; Find the default location
11009 (when (and heading (stringp heading) (string-match "\\S-" heading))
11010 (goto-char (point-min))
11011 (if (re-search-forward
11012 (concat "^\\*+[ \t]+" (regexp-quote heading)
11013 "\\([ \t]+:[@a-zA-Z0-9_:]*\\)?[ \t]*$")
11014 nil t)
11015 (setq org-goto-start-pos (match-beginning 0))))
11017 ;; Ask the User for a location
11018 (setq spos (if fastp
11019 org-goto-start-pos
11020 (org-get-location (current-buffer) org-remember-help)))
11021 (if (not spos) (throw 'quit nil)) ; return nil to show we did
11022 ; not handle this note
11023 (goto-char spos)
11024 (cond ((and (bobp) (not reversed))
11025 ;; Put it at the end, one level below level 1
11026 (save-restriction
11027 (widen)
11028 (goto-char (point-max))
11029 (if (not (bolp)) (newline))
11030 (org-paste-subtree (org-get-legal-level 1 1) txt)))
11031 ((and (bobp) reversed)
11032 ;; Put it at the start, as level 1
11033 (save-restriction
11034 (widen)
11035 (goto-char (point-min))
11036 (re-search-forward "^\\*" nil t)
11037 (beginning-of-line 1)
11038 (org-paste-subtree 1 txt)))
11039 ((and (org-on-heading-p nil) (not current-prefix-arg))
11040 ;; Put it below this entry, at the beg/end of the subtree
11041 (org-back-to-heading t)
11042 (setq level (funcall outline-level))
11043 (if reversed
11044 (outline-end-of-heading)
11045 (org-end-of-subtree t))
11046 (if (not (bolp)) (newline))
11047 (beginning-of-line 1)
11048 (org-paste-subtree (org-get-legal-level level 1) txt))
11050 ;; Put it right there, with automatic level determined by
11051 ;; org-paste-subtree or from prefix arg
11052 (org-paste-subtree current-prefix-arg txt)))
11053 (when remember-save-after-remembering
11054 (save-buffer)
11055 (if (not visiting) (kill-buffer (current-buffer)))))))))
11056 t) ;; return t to indicate that we took care of this note.
11058 (defun org-get-org-file ()
11059 "Read a filename, with default directory `org-directory'."
11060 (let ((default (or org-default-notes-file remember-data-file)))
11061 (read-file-name (format "File name [%s]: " default)
11062 (file-name-as-directory org-directory)
11063 default)))
11065 (defun org-notes-order-reversed-p ()
11066 "Check if the current file should receive notes in reversed order."
11067 (cond
11068 ((not org-reverse-note-order) nil)
11069 ((eq t org-reverse-note-order) t)
11070 ((not (listp org-reverse-note-order)) nil)
11071 (t (catch 'exit
11072 (let ((all org-reverse-note-order)
11073 entry)
11074 (while (setq entry (pop all))
11075 (if (string-match (car entry) buffer-file-name)
11076 (throw 'exit (cdr entry))))
11077 nil)))))
11079 ;;;; Dynamic blocks
11081 (defun org-find-dblock (name)
11082 "Find the first dynamic block with name NAME in the buffer.
11083 If not found, stay at current position and return nil."
11084 (let (pos)
11085 (save-excursion
11086 (goto-char (point-min))
11087 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
11088 nil t)
11089 (match-beginning 0))))
11090 (if pos (goto-char pos))
11091 pos))
11093 (defconst org-dblock-start-re
11094 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11095 "Matches the startline of a dynamic block, with parameters.")
11097 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
11098 "Matches the end of a dyhamic block.")
11100 (defun org-create-dblock (plist)
11101 "Create a dynamic block section, with parameters taken from PLIST.
11102 PLIST must containe a :name entry which is used as name of the block."
11103 (unless (bolp) (newline))
11104 (let ((name (plist-get plist :name)))
11105 (insert "#+BEGIN: " name)
11106 (while plist
11107 (if (eq (car plist) :name)
11108 (setq plist (cddr plist))
11109 (insert " " (prin1-to-string (pop plist)))))
11110 (insert "\n\n#+END:\n")
11111 (beginning-of-line -2)))
11113 (defun org-prepare-dblock ()
11114 "Prepare dynamic block for refresh.
11115 This empties the block, puts the cursor at the insert position and returns
11116 the property list including an extra property :name with the block name."
11117 (unless (looking-at org-dblock-start-re)
11118 (error "Not at a dynamic block"))
11119 (let* ((begdel (1+ (match-end 0)))
11120 (name (match-string 1))
11121 (params (append (list :name name)
11122 (read (concat "(" (match-string 3) ")")))))
11123 (unless (re-search-forward org-dblock-end-re nil t)
11124 (error "Dynamic block not terminated"))
11125 (delete-region begdel (match-beginning 0))
11126 (goto-char begdel)
11127 (open-line 1)
11128 params))
11130 (defun org-map-dblocks (&optional command)
11131 "Apply COMMAND to all dynamic blocks in the current buffer.
11132 If COMMAND is not given, use `org-update-dblock'."
11133 (let ((cmd (or command 'org-update-dblock))
11134 pos)
11135 (save-excursion
11136 (goto-char (point-min))
11137 (while (re-search-forward org-dblock-start-re nil t)
11138 (goto-char (setq pos (match-beginning 0)))
11139 (condition-case nil
11140 (funcall cmd)
11141 (error (message "Error during update of dynamic block")))
11142 (goto-char pos)
11143 (unless (re-search-forward org-dblock-end-re nil t)
11144 (error "Dynamic block not terminated"))))))
11146 (defun org-dblock-update (&optional arg)
11147 "User command for updating dynamic blocks.
11148 Update the dynamic block at point. With prefix ARG, update all dynamic
11149 blocks in the buffer."
11150 (interactive "P")
11151 (if arg
11152 (org-update-all-dblocks)
11153 (or (looking-at org-dblock-start-re)
11154 (org-beginning-of-dblock))
11155 (org-update-dblock)))
11157 (defun org-update-dblock ()
11158 "Update the dynamic block at point
11159 This means to empty the block, parse for parameters and then call
11160 the correct writing function."
11161 (let* ((pos (point))
11162 (params (org-prepare-dblock))
11163 (name (plist-get params :name))
11164 (cmd (intern (concat "org-dblock-write:" name))))
11165 (funcall cmd params)
11166 (goto-char pos)))
11168 (defun org-beginning-of-dblock ()
11169 "Find the beginning of the dynamic block at point.
11170 Error if there is no scuh block at point."
11171 (let ((pos (point))
11172 beg)
11173 (end-of-line 1)
11174 (if (and (re-search-backward org-dblock-start-re nil t)
11175 (setq beg (match-beginning 0))
11176 (re-search-forward org-dblock-end-re nil t)
11177 (> (match-end 0) pos))
11178 (goto-char beg)
11179 (goto-char pos)
11180 (error "Not in a dynamic block"))))
11182 (defun org-update-all-dblocks ()
11183 "Update all dynamic blocks in the buffer.
11184 This function can be used in a hook."
11185 (when (org-mode-p)
11186 (org-map-dblocks 'org-update-dblock)))
11189 ;;;; Completion
11191 (defun org-complete (&optional arg)
11192 "Perform completion on word at point.
11193 At the beginning of a headline, this completes TODO keywords as given in
11194 `org-todo-keywords'.
11195 If the current word is preceded by a backslash, completes the TeX symbols
11196 that are supported for HTML support.
11197 If the current word is preceded by \"#+\", completes special words for
11198 setting file options.
11199 In the line after \"#+STARTUP:, complete valid keywords.\"
11200 At all other locations, this simply calls `ispell-complete-word'."
11201 (interactive "P")
11202 (catch 'exit
11203 (let* ((end (point))
11204 (beg1 (save-excursion
11205 (skip-chars-backward "a-zA-Z_@0-9")
11206 (point)))
11207 (beg (save-excursion
11208 (skip-chars-backward "a-zA-Z0-9_:$")
11209 (point)))
11210 (confirm (lambda (x) (stringp (car x))))
11211 (searchhead (equal (char-before beg) ?*))
11212 (tag (equal (char-before beg1) ?:))
11213 (texp (equal (char-before beg) ?\\))
11214 (link (equal (char-before beg) ?\[))
11215 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
11216 beg)
11217 "#+"))
11218 (startup (string-match "^#\\+STARTUP:.*"
11219 (buffer-substring (point-at-bol) (point))))
11220 (completion-ignore-case opt)
11221 (type nil)
11222 (tbl nil)
11223 (table (cond
11224 (opt
11225 (setq type :opt)
11226 (mapcar (lambda (x)
11227 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
11228 (cons (match-string 2 x) (match-string 1 x)))
11229 (org-split-string (org-get-current-options) "\n")))
11230 (startup
11231 (setq type :startup)
11232 org-startup-options)
11233 (link (append org-link-abbrev-alist-local
11234 org-link-abbrev-alist))
11235 (texp
11236 (setq type :tex)
11237 org-html-entities)
11238 ((string-match "\\`\\*+[ \t]*\\'"
11239 (buffer-substring (point-at-bol) beg))
11240 (setq type :todo)
11241 (mapcar 'list org-todo-keywords-1))
11242 (searchhead
11243 (setq type :searchhead)
11244 (save-excursion
11245 (goto-char (point-min))
11246 (while (re-search-forward org-todo-line-regexp nil t)
11247 (push (list
11248 (org-make-org-heading-search-string
11249 (match-string 3) t))
11250 tbl)))
11251 tbl)
11252 (tag (setq type :tag beg beg1)
11253 (or org-tag-alist (org-get-buffer-tags)))
11254 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
11255 (pattern (buffer-substring-no-properties beg end))
11256 (completion (try-completion pattern table confirm)))
11257 (cond ((eq completion t)
11258 (if (equal type :opt)
11259 (insert (substring (cdr (assoc (upcase pattern) table))
11260 (length pattern)))
11261 (if (equal type :tag) (insert ":"))))
11262 ((null completion)
11263 (message "Can't find completion for \"%s\"" pattern)
11264 (ding))
11265 ((not (string= pattern completion))
11266 (delete-region beg end)
11267 (if (string-match " +$" completion)
11268 (setq completion (replace-match "" t t completion)))
11269 (insert completion)
11270 (if (get-buffer-window "*Completions*")
11271 (delete-window (get-buffer-window "*Completions*")))
11272 (if (assoc completion table)
11273 (if (eq type :todo) (insert " ")
11274 (if (eq type :tag) (insert ":"))))
11275 (if (and (equal type :opt) (assoc completion table))
11276 (message "%s" (substitute-command-keys
11277 "Press \\[org-complete] again to insert example settings"))))
11279 (message "Making completion list...")
11280 (let ((list (sort (all-completions pattern table confirm)
11281 'string<)))
11282 (with-output-to-temp-buffer "*Completions*"
11283 (condition-case nil
11284 ;; Protection needed for XEmacs and emacs 21
11285 (display-completion-list list pattern)
11286 (error (display-completion-list list)))))
11287 (message "Making completion list...%s" "done"))))))
11289 ;;;; TODO, DEADLINE, Comments
11291 (defun org-toggle-comment ()
11292 "Change the COMMENT state of an entry."
11293 (interactive)
11294 (save-excursion
11295 (org-back-to-heading)
11296 (if (looking-at (concat outline-regexp
11297 "\\( +\\<" org-comment-string "\\>\\)"))
11298 (replace-match "" t t nil 1)
11299 (if (looking-at outline-regexp)
11300 (progn
11301 (goto-char (match-end 0))
11302 (insert " " org-comment-string))))))
11304 (defvar org-last-todo-state-is-todo nil
11305 "This is non-nil when the last TODO state change led to a TODO state.
11306 If the last change removed the TODO tag or switched to DONE, then
11307 this is nil.")
11309 (defun org-todo (&optional arg)
11310 "Change the TODO state of an item.
11311 The state of an item is given by a keyword at the start of the heading,
11312 like
11313 *** TODO Write paper
11314 *** DONE Call mom
11316 The different keywords are specified in the variable `org-todo-keywords'.
11317 By default the available states are \"TODO\" and \"DONE\".
11318 So for this example: when the item starts with TODO, it is changed to DONE.
11319 When it starts with DONE, the DONE is removed. And when neither TODO nor
11320 DONE are present, add TODO at the beginning of the heading.
11322 With C-u prefix arg, use completion to determine the new state.
11323 With numeric prefix arg, switch to that state.
11325 For calling through lisp, arg is also interpreted in the following way:
11326 'none -> empty state
11327 \"\"(empty string) -> switch to empty state
11328 'done -> switch to DONE
11329 'nextset -> switch to the next set of keywords
11330 'previousset -> switch to the previous set of keywords
11331 \"WAITING\" -> switch to the specified keyword, but only if it
11332 really is a member of `org-todo-keywords'."
11333 (interactive "P")
11334 (save-excursion
11335 (org-back-to-heading)
11336 (if (looking-at outline-regexp) (goto-char (match-end 0)))
11337 (or (looking-at (concat " +" org-todo-regexp " *"))
11338 (looking-at " *"))
11339 (let* ((this (match-string 1))
11340 (head (org-get-todo-sequence-head this))
11341 (ass (assoc head org-todo-kwd-alist))
11342 (interpret (nth 1 ass))
11343 (done-word (nth 3 ass))
11344 (final-done-word (nth 4 ass))
11345 (last-state (or this ""))
11346 (completion-ignore-case t)
11347 (member (member this org-todo-keywords-1))
11348 (tail (cdr member))
11349 (state (cond
11350 ((equal arg '(4))
11351 ;; Read a state with completion
11352 (completing-read "State: " (mapcar (lambda(x) (list x))
11353 org-todo-keywords-1)
11354 nil t))
11355 ((eq arg 'right)
11356 (if this
11357 (if tail (car tail) nil)
11358 (car org-todo-keywords-1)))
11359 ((eq arg 'left)
11360 (if (equal member org-todo-keywords-1)
11362 (if this
11363 (nth (- (length org-todo-keywords-1) (length tail) 2)
11364 org-todo-keywords-1)
11365 (org-last org-todo-keywords-1))))
11366 (arg
11367 ;; user or caller requests a specific state
11368 (cond
11369 ((equal arg "") nil)
11370 ((eq arg 'none) nil)
11371 ((eq arg 'done) (or done-word (car org-done-keywords)))
11372 ((eq arg 'nextset)
11373 (or (car (cdr (member head org-todo-heads)))
11374 (car org-todo-heads)))
11375 ((eq arg 'previousset)
11376 (let ((org-todo-heads (reverse org-todo-heads)))
11377 (or (car (cdr (member head org-todo-heads)))
11378 (car org-todo-heads))))
11379 ((car (member arg org-todo-keywords-1)))
11380 ((nth (1- (prefix-numeric-value arg))
11381 org-todo-keywords-1))))
11382 ((null member) (or head (car org-todo-keywords-1)))
11383 ((equal this final-done-word) nil) ;; -> make empty
11384 ((null tail) nil) ;; -> first entry
11385 ((eq interpret 'sequence)
11386 (car tail))
11387 ((memq interpret '(type priority))
11388 (if (eq this-command last-command)
11389 (car tail)
11390 (if (> (length tail) 0)
11391 (or done-word (car org-done-keywords))
11392 nil)))
11393 (t nil)))
11394 (next (if state (concat " " state " ") " "))
11395 dostates)
11396 (replace-match next t t)
11397 (when (memq arg '(nextset previousset))
11398 (message "Keyword set: %s"
11399 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11400 (setq org-last-todo-state-is-todo
11401 (not (member state org-done-keywords)))
11402 (when (and org-log-done (not (memq arg '(nextset previousset))))
11403 (setq dostates (and (eq interpret 'sequence)
11404 (listp org-log-done) (memq 'state org-log-done)))
11405 (cond
11406 ((and state (not this))
11407 (org-add-planning-info nil nil 'closed)
11408 (and dostates (org-add-log-maybe 'state state 'findpos)))
11409 ((and state dostates)
11410 (org-add-log-maybe 'state state 'findpos))
11411 ((member state org-done-keywords)
11412 ;; Planning info calls the note-setting command.
11413 (org-add-planning-info 'closed (org-current-time)
11414 (if (org-get-repeat) nil 'scheduled))
11415 (org-add-log-maybe 'done state 'findpos))))
11416 ;; Fixup tag positioning
11417 (and org-auto-align-tags (org-set-tags nil t))
11418 (run-hooks 'org-after-todo-state-change-hook)
11419 (and (member state org-done-keywords) (org-auto-repeat-maybe))
11420 (if (and arg (not (member state org-done-keywords)))
11421 (setq head (org-get-todo-sequence-head state)))
11422 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
11423 ;; Fixup cursor location if close to the keyword
11424 (if (and (outline-on-heading-p)
11425 (not (bolp))
11426 (save-excursion (beginning-of-line 1)
11427 (looking-at org-todo-line-regexp))
11428 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11429 (progn
11430 (goto-char (or (match-end 2) (match-end 1)))
11431 (just-one-space))))
11433 (defun org-get-todo-sequence-head (kwd)
11434 "Return the head of the TODO sequence to which KWD belongs.
11435 If KWD is not set, check if there is a text property remembering the
11436 right sequence."
11437 (let (p)
11438 (cond
11439 ((not kwd)
11440 (or (get-text-property (point-at-bol) 'org-todo-head)
11441 (progn
11442 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11443 nil (point-at-eol)))
11444 (get-text-property p 'org-todo-head))))
11445 ((not (member kwd org-todo-keywords-1))
11446 (car org-todo-keywords-1))
11447 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11449 (defun org-get-repeat ()
11450 "Return the REPEAT statement of this entry."
11451 (save-match-data
11452 (save-excursion
11453 (org-back-to-heading t)
11454 (if (re-search-forward
11455 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
11456 (match-string 1)))))
11458 (defvar org-last-changed-timestamp)
11459 (defvar org-log-post-message)
11460 (defun org-auto-repeat-maybe ()
11461 "Check if the current headline contains a REPEAT key.
11462 If yes, set TODO state back to what it was and change any SCHEDULED
11463 or DEADLINE times the new date.
11464 This function should be run in the `org-after-todo-state-change-hook'."
11465 ;; last-state is dynamically scoped into this function
11466 (let* ((repeat (org-get-repeat))
11467 (aa (assoc last-state org-todo-kwd-alist))
11468 (interpret (nth 1 aa))
11469 (head (nth 2 aa))
11470 (done-word (nth 3 aa))
11471 (whata '(("d" . day) ("m" . month) ("y" . year)))
11472 (msg "Entry repeats: ")
11473 (org-log-done)
11474 re type n what start)
11475 (when repeat
11476 (org-todo (if (eq interpret 'type) last-state head))
11477 (when (and org-log-repeat
11478 (not (memq 'org-add-log-note
11479 (default-value 'post-command-hook))))
11480 ;; Make sure a note is taken
11481 (let ((org-log-done '(done)))
11482 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
11483 'findpos)))
11484 (org-back-to-heading t)
11485 (org-add-planning-info nil nil 'closed)
11486 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11487 org-deadline-time-regexp "\\)"))
11488 (while (re-search-forward
11489 re (save-excursion (outline-next-heading) (point)) t)
11490 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
11491 start 0)
11492 (while (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" repeat start)
11493 (setq start (match-end 0)
11494 n (string-to-number (match-string 1 repeat))
11495 what (match-string 2 repeat))
11496 (if (equal what "w") (setq n (* n 7) what "d"))
11497 (org-timestamp-change n (cdr (assoc what whata))))
11498 (setq msg (concat msg type org-last-changed-timestamp " ")))
11499 (setq org-log-post-message msg)
11500 (message msg))))
11502 (defun org-show-todo-tree (arg)
11503 "Make a compact tree which shows all headlines marked with TODO.
11504 The tree will show the lines where the regexp matches, and all higher
11505 headlines above the match.
11506 With \\[universal-argument] prefix, also show the DONE entries.
11507 With a numeric prefix N, construct a sparse tree for the Nth element
11508 of `org-todo-keywords-1'."
11509 (interactive "P")
11510 (let ((case-fold-search nil)
11511 (kwd-re
11512 (cond ((null arg) org-not-done-regexp)
11513 ((equal arg '(4))
11514 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
11515 (mapcar 'list org-todo-keywords-1))))
11516 (concat "\\("
11517 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11518 "\\)\\>")))
11519 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11520 (regexp-quote (nth (1- (prefix-numeric-value arg))
11521 org-todo-keywords-1)))
11522 (t (error "Invalid prefix argument: %s" arg)))))
11523 (message "%d TODO entries found"
11524 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
11526 (defun org-deadline ()
11527 "Insert the DEADLINE: string to make a deadline.
11528 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11529 to modify it to the correct date."
11530 (interactive)
11531 (org-add-planning-info 'deadline nil 'closed))
11533 (defun org-schedule ()
11534 "Insert the SCHEDULED: string to schedule a TODO item.
11535 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11536 to modify it to the correct date."
11537 (interactive)
11538 (org-add-planning-info 'scheduled nil 'closed))
11540 (defun org-add-planning-info (what &optional time &rest remove)
11541 "Insert new timestamp with keyword in the line directly after the headline.
11542 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11543 If non is given, the user is prompted for a date.
11544 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11545 be removed."
11546 (interactive)
11547 (let (org-time-was-given)
11548 (when what (setq time (or time (org-read-date nil 'to-time))))
11549 (when (and org-insert-labeled-timestamps-at-point
11550 (member what '(scheduled deadline)))
11551 (insert
11552 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11553 (org-insert-time-stamp time org-time-was-given)
11554 (setq what nil))
11555 (save-excursion
11556 (save-restriction
11557 (let (col list elt ts buffer-invisibility-spec)
11558 (org-back-to-heading t)
11559 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11560 (goto-char (match-end 1))
11561 (setq col (current-column))
11562 (goto-char (1+ (match-end 0)))
11563 (if (and (not (looking-at outline-regexp))
11564 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11565 "[^\r\n]*"))
11566 (not (equal (match-string 1) org-clock-string)))
11567 (narrow-to-region (match-beginning 0) (match-end 0))
11568 (insert "\n")
11569 (backward-char 1)
11570 (narrow-to-region (point) (point))
11571 (indent-to-column col))
11572 ;; Check if we have to remove something.
11573 (setq list (cons what remove))
11574 (while list
11575 (setq elt (pop list))
11576 (goto-char (point-min))
11577 (when (or (and (eq elt 'scheduled)
11578 (re-search-forward org-scheduled-time-regexp nil t))
11579 (and (eq elt 'deadline)
11580 (re-search-forward org-deadline-time-regexp nil t))
11581 (and (eq elt 'closed)
11582 (re-search-forward org-closed-time-regexp nil t)))
11583 (replace-match "")
11584 (if (looking-at "--+<[^>]+>") (replace-match ""))
11585 (if (looking-at " +") (replace-match ""))))
11586 (goto-char (point-max))
11587 (when what
11588 (insert
11589 (if (not (equal (char-before) ?\ )) " " "")
11590 (cond ((eq what 'scheduled) org-scheduled-string)
11591 ((eq what 'deadline) org-deadline-string)
11592 ((eq what 'closed) org-closed-string))
11593 " ")
11594 (org-insert-time-stamp time
11595 (or org-time-was-given (eq what 'closed))
11596 (eq what 'closed))
11597 (end-of-line 1))
11598 (goto-char (point-min))
11599 (widen)
11600 (if (looking-at "[ \t]+\r?\n")
11601 (replace-match ""))
11602 ts)))))
11604 (defvar org-log-note-marker (make-marker))
11605 (defvar org-log-note-purpose nil)
11606 (defvar org-log-note-state nil)
11607 (defvar org-log-note-window-configuration nil)
11608 (defvar org-log-note-return-to (make-marker))
11609 (defvar org-log-post-message nil
11610 "Message to be displayed after a log note has been stored.
11611 The auto-repeater uses this.")
11613 (defun org-add-log-maybe (&optional purpose state findpos)
11614 (save-excursion
11615 (when (and (listp org-log-done)
11616 (memq purpose org-log-done))
11617 (when findpos
11618 (org-back-to-heading t)
11619 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11620 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11621 "[^\r\n]*\\)?"))
11622 (goto-char (match-end 0)))
11623 (move-marker org-log-note-marker (point))
11624 (setq org-log-note-purpose purpose)
11625 (setq org-log-note-state state)
11626 (add-hook 'post-command-hook 'org-add-log-note 'append))))
11628 (defun org-add-log-note (&optional purpose)
11629 "Pop up a window for taking a note, and add this note later at point."
11630 (remove-hook 'post-command-hook 'org-add-log-note)
11631 (setq org-log-note-window-configuration (current-window-configuration))
11632 (delete-other-windows)
11633 (move-marker org-log-note-return-to (point))
11634 (switch-to-buffer (marker-buffer org-log-note-marker))
11635 (goto-char org-log-note-marker)
11636 (switch-to-buffer-other-window "*Org Note*")
11637 (erase-buffer)
11638 (let ((org-inhibit-startup t)) (org-mode))
11639 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
11640 (cond
11641 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11642 ((eq org-log-note-purpose 'done) "closed todo item")
11643 ((eq org-log-note-purpose 'state) "state change")
11644 (t (error "This should not happen")))))
11645 (org-set-local 'org-finish-function 'org-store-log-note))
11647 (defun org-store-log-note ()
11648 "Finish taking a log note, and insert it to where it belongs."
11649 (let ((txt (buffer-string))
11650 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11651 lines ind)
11652 (kill-buffer (current-buffer))
11653 (if (string-match "^#.*\n[ \t\n]*" txt)
11654 (setq txt (replace-match "" t t txt)))
11655 (if (string-match "\\s-+\\'" txt)
11656 (setq txt (replace-match "" t t txt)))
11657 (setq lines (org-split-string txt "\n"))
11658 (when (and note (string-match "\\S-" note))
11659 (setq note
11660 (org-replace-escapes
11661 note
11662 (list (cons "%u" (user-login-name))
11663 (cons "%U" user-full-name)
11664 (cons "%t" (format-time-string
11665 (org-time-stamp-format 'long 'inactive)
11666 (current-time)))
11667 (cons "%s" (if org-log-note-state
11668 (concat "\"" org-log-note-state "\"")
11669 "")))))
11670 (if lines (setq note (concat note " \\\\")))
11671 (push note lines))
11672 (save-excursion
11673 (set-buffer (marker-buffer org-log-note-marker))
11674 (save-excursion
11675 (goto-char org-log-note-marker)
11676 (move-marker org-log-note-marker nil)
11677 (end-of-line 1)
11678 (if (not (bolp)) (insert "\n")) (indent-relative nil)
11679 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
11680 (insert " - " (pop lines))
11681 (while lines
11682 (insert "\n" ind (pop lines))))))
11683 (set-window-configuration org-log-note-window-configuration)
11684 (with-current-buffer (marker-buffer org-log-note-return-to)
11685 (goto-char org-log-note-return-to))
11686 (move-marker org-log-note-return-to nil)
11687 (and org-log-post-message (message org-log-post-message)))
11689 (defvar org-occur-highlights nil)
11690 (make-variable-buffer-local 'org-occur-highlights)
11692 (defun org-occur (regexp &optional keep-previous callback)
11693 "Make a compact tree which shows all matches of REGEXP.
11694 The tree will show the lines where the regexp matches, and all higher
11695 headlines above the match. It will also show the heading after the match,
11696 to make sure editing the matching entry is easy.
11697 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11698 call to `org-occur' will be kept, to allow stacking of calls to this
11699 command.
11700 If CALLBACK is non-nil, it is a function which is called to confirm
11701 that the match should indeed be shown."
11702 (interactive "sRegexp: \nP")
11703 (or keep-previous (org-remove-occur-highlights nil nil t))
11704 (let ((cnt 0))
11705 (save-excursion
11706 (goto-char (point-min))
11707 (if (or (not keep-previous) ; do not want to keep
11708 (not org-occur-highlights)) ; no previous matches
11709 ;; hide everything
11710 (org-overview))
11711 (while (re-search-forward regexp nil t)
11712 (when (or (not callback)
11713 (save-match-data (funcall callback)))
11714 (setq cnt (1+ cnt))
11715 (org-highlight-new-match (match-beginning 0) (match-end 0))
11716 (org-show-context 'occur-tree))))
11717 (when org-remove-highlights-with-change
11718 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11719 nil 'local))
11720 (unless org-sparse-tree-open-archived-trees
11721 (org-hide-archived-subtrees (point-min) (point-max)))
11722 (run-hooks 'org-occur-hook)
11723 (if (interactive-p)
11724 (message "%d match(es) for regexp %s" cnt regexp))
11725 cnt))
11727 (defun org-show-context (&optional key)
11728 "Make sure point and context and visible.
11729 How much context is shown depends upon the variables
11730 `org-show-hierarchy-above', `org-show-following-heading'. and
11731 `org-show-siblings'."
11732 (let ((heading-p (org-on-heading-p t))
11733 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11734 (following-p (org-get-alist-option org-show-following-heading key))
11735 (siblings-p (org-get-alist-option org-show-siblings key)))
11736 (catch 'exit
11737 ;; Show heading or entry text
11738 (if heading-p
11739 (org-flag-heading nil) ; only show the heading
11740 (and (or (org-invisible-p) (org-invisible-p2))
11741 (org-show-hidden-entry))) ; show entire entry
11742 (when following-p
11743 ;; Show next sibling, or heading below text
11744 (save-excursion
11745 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11746 (org-flag-heading nil))))
11747 (when siblings-p (org-show-siblings))
11748 (when hierarchy-p
11749 ;; show all higher headings, possibly with siblings
11750 (save-excursion
11751 (while (and (condition-case nil
11752 (progn (org-up-heading-all 1) t)
11753 (error nil))
11754 (not (bobp)))
11755 (org-flag-heading nil)
11756 (when siblings-p (org-show-siblings))))))))
11758 (defun org-reveal (&optional siblings)
11759 "Show current entry, hierarchy above it, and the following headline.
11760 This can be used to show a consistent set of context around locations
11761 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11762 not t for the search context.
11764 With optional argument SIBLINGS, on each level of the hierarchy all
11765 siblings are shown. This repairs the tree structure to what it would
11766 look like when opened with hierarchical calls to `org-cycle'."
11767 (interactive "P")
11768 (let ((org-show-hierarchy-above t)
11769 (org-show-following-heading t)
11770 (org-show-siblings (if siblings t org-show-siblings)))
11771 (org-show-context nil)))
11773 (defun org-highlight-new-match (beg end)
11774 "Highlight from BEG to END and mark the highlight is an occur headline."
11775 (let ((ov (org-make-overlay beg end)))
11776 (org-overlay-put ov 'face 'secondary-selection)
11777 (push ov org-occur-highlights)))
11779 (defun org-remove-occur-highlights (&optional beg end noremove)
11780 "Remove the occur highlights from the buffer.
11781 BEG and END are ignored. If NOREMOVE is nil, remove this function
11782 from the `before-change-functions' in the current buffer."
11783 (interactive)
11784 (unless org-inhibit-highlight-removal
11785 (mapc 'org-delete-overlay org-occur-highlights)
11786 (setq org-occur-highlights nil)
11787 (unless noremove
11788 (remove-hook 'before-change-functions
11789 'org-remove-occur-highlights 'local))))
11791 ;;;; Priorities
11793 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
11794 "Regular expression matching the priority indicator.")
11796 (defvar org-remove-priority-next-time nil)
11798 (defun org-priority-up ()
11799 "Increase the priority of the current item."
11800 (interactive)
11801 (org-priority 'up))
11803 (defun org-priority-down ()
11804 "Decrease the priority of the current item."
11805 (interactive)
11806 (org-priority 'down))
11808 (defun org-priority (&optional action)
11809 "Change the priority of an item by ARG.
11810 ACTION can be set, up, or down."
11811 (interactive)
11812 (setq action (or action 'set))
11813 (let (current new news have remove)
11814 (save-excursion
11815 (org-back-to-heading)
11816 (if (looking-at org-priority-regexp)
11817 (setq current (string-to-char (match-string 2))
11818 have t)
11819 (setq current org-default-priority))
11820 (cond
11821 ((eq action 'set)
11822 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
11823 (setq new (read-char-exclusive))
11824 (cond ((equal new ?\ ) (setq remove t))
11825 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
11826 (error "Priority must be between `%c' and `%c'"
11827 ?A org-lowest-priority))))
11828 ((eq action 'up)
11829 (setq new (1- current)))
11830 ((eq action 'down)
11831 (setq new (1+ current)))
11832 (t (error "Invalid action")))
11833 (setq new (min (max ?A (upcase new)) org-lowest-priority))
11834 (setq news (format "%c" new))
11835 (if have
11836 (if remove
11837 (replace-match "" t t nil 1)
11838 (replace-match news t t nil 2))
11839 (if remove
11840 (error "No priority cookie found in line")
11841 (looking-at org-todo-line-regexp)
11842 (if (match-end 2)
11843 (progn
11844 (goto-char (match-end 2))
11845 (insert " [#" news "]"))
11846 (goto-char (match-beginning 3))
11847 (insert "[#" news "] ")))))
11848 (if remove
11849 (message "Priority removed")
11850 (message "Priority of current item set to %s" news))))
11853 (defun org-get-priority (s)
11854 "Find priority cookie and return priority."
11855 (save-match-data
11856 (if (not (string-match org-priority-regexp s))
11857 (* 1000 (- org-lowest-priority org-default-priority))
11858 (* 1000 (- org-lowest-priority
11859 (string-to-char (match-string 2 s)))))))
11861 ;;;; Tags
11863 (defun org-scan-tags (action matcher &optional todo-only)
11864 "Scan headline tags with inheritance and produce output ACTION.
11865 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
11866 evaluated, testing if a given set of tags qualifies a headline for
11867 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
11868 are included in the output."
11869 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
11870 (mapconcat 'regexp-quote
11871 (nreverse (cdr (reverse org-todo-keywords-1)))
11872 "\\|")
11873 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
11874 (props (list 'face nil
11875 'done-face 'org-done
11876 'undone-face nil
11877 'mouse-face 'highlight
11878 'org-not-done-regexp org-not-done-regexp
11879 'keymap org-agenda-keymap
11880 'help-echo
11881 (format "mouse-2 or RET jump to org file %s"
11882 (abbreviate-file-name buffer-file-name))))
11883 (case-fold-search nil)
11884 lspos
11885 tags tags-list tags-alist (llast 0) rtn level category i txt
11886 todo marker entry priority)
11887 (save-excursion
11888 (goto-char (point-min))
11889 (when (eq action 'sparse-tree) (org-overview))
11890 (while (re-search-forward re nil t)
11891 (catch :skip
11892 (setq todo (if (match-end 1) (match-string 2))
11893 tags (if (match-end 4) (match-string 4)))
11894 (goto-char (setq lspos (1+ (match-beginning 0))))
11895 (setq level (funcall outline-level)
11896 category (org-get-category))
11897 (setq i llast llast level)
11898 ;; remove tag lists from same and sublevels
11899 (while (>= i level)
11900 (when (setq entry (assoc i tags-alist))
11901 (setq tags-alist (delete entry tags-alist)))
11902 (setq i (1- i)))
11903 ;; add the nex tags
11904 (when tags
11905 (setq tags (mapcar 'downcase (org-split-string tags ":"))
11906 tags-alist
11907 (cons (cons level tags) tags-alist)))
11908 ;; compile tags for current headline
11909 (setq tags-list
11910 (if org-use-tag-inheritance
11911 (apply 'append (mapcar 'cdr tags-alist))
11912 tags))
11913 (when (and (or (not todo-only) todo)
11914 (eval matcher)
11915 (or (not org-agenda-skip-archived-trees)
11916 (not (member org-archive-tag tags-list))))
11917 (and (eq action 'agenda) (org-agenda-skip))
11918 ;; list this headline
11919 (if (eq action 'sparse-tree)
11920 (progn
11921 (org-show-context 'tags-tree))
11922 (setq txt (org-format-agenda-item
11924 (concat
11925 (if org-tags-match-list-sublevels
11926 (make-string (1- level) ?.) "")
11927 (org-get-heading))
11928 category tags-list)
11929 priority (org-get-priority txt))
11930 (goto-char lspos)
11931 (setq marker (org-agenda-new-marker))
11932 (org-add-props txt props
11933 'org-marker marker 'org-hd-marker marker 'org-category category
11934 'priority priority)
11935 (push txt rtn))
11936 ;; if we are to skip sublevels, jump to end of subtree
11937 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
11938 (when (and (eq action 'sparse-tree)
11939 (not org-sparse-tree-open-archived-trees))
11940 (org-hide-archived-subtrees (point-min) (point-max)))
11941 (nreverse rtn)))
11943 (defvar todo-only) ;; dynamically scoped
11945 (defun org-tags-sparse-tree (&optional todo-only match)
11946 "Create a sparse tree according to tags string MATCH.
11947 MATCH can contain positive and negative selection of tags, like
11948 \"+WORK+URGENT-WITHBOSS\".
11949 If optional argument TODO_ONLY is non-nil, only select lines that are
11950 also TODO lines."
11951 (interactive "P")
11952 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11954 (defun org-make-tags-matcher (match)
11955 "Create the TAGS//TODO matcher form for the selection string MATCH."
11956 ;; todo-only is scoped dynamically into this function, and the function
11957 ;; may change it it the matcher asksk for it.
11958 (unless match
11959 ;; Get a new match request, with completion
11960 (setq org-last-tags-completion-table
11961 (or org-tag-alist
11962 org-last-tags-completion-table))
11963 (setq match (completing-read
11964 "Match: " 'org-tags-completion-function nil nil nil
11965 'org-tags-history)))
11967 ;; Parse the string and create a lisp form
11968 (let ((match0 match)
11969 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[A-Za-z_@0-9]+\\)")
11970 minus tag mm
11971 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11972 orterms term orlist re-p level-p)
11973 (if (string-match "/+" match)
11974 ;; match contains also a todo-matching request
11975 (progn
11976 (setq tagsmatch (substring match 0 (match-beginning 0))
11977 todomatch (substring match (match-end 0)))
11978 (if (string-match "^!" todomatch)
11979 (setq todo-only t todomatch (substring todomatch 1)))
11980 (if (string-match "^\\s-*$" todomatch)
11981 (setq todomatch nil)))
11982 ;; only matching tags
11983 (setq tagsmatch match todomatch nil))
11985 ;; Make the tags matcher
11986 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11987 (setq tagsmatcher t)
11988 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11989 (while (setq term (pop orterms))
11990 (while (and (equal (substring term -1) "\\") orterms)
11991 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11992 (while (string-match re term)
11993 (setq minus (and (match-end 1)
11994 (equal (match-string 1 term) "-"))
11995 tag (match-string 2 term)
11996 re-p (equal (string-to-char tag) ?{)
11997 level-p (match-end 3)
11998 mm (cond
11999 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12000 (level-p `(= level ,(string-to-number
12001 (match-string 3 term))))
12002 (t `(member ,(downcase tag) tags-list)))
12003 mm (if minus (list 'not mm) mm)
12004 term (substring term (match-end 0)))
12005 (push mm tagsmatcher))
12006 (push (if (> (length tagsmatcher) 1)
12007 (cons 'and tagsmatcher)
12008 (car tagsmatcher))
12009 orlist)
12010 (setq tagsmatcher nil))
12011 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
12013 ;; Make the todo matcher
12014 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12015 (setq todomatcher t)
12016 (setq orterms (org-split-string todomatch "|") orlist nil)
12017 (while (setq term (pop orterms))
12018 (while (string-match re term)
12019 (setq minus (and (match-end 1)
12020 (equal (match-string 1 term) "-"))
12021 kwd (match-string 2 term)
12022 re-p (equal (string-to-char kwd) ?{)
12023 term (substring term (match-end 0))
12024 mm (if re-p
12025 `(string-match ,(substring kwd 1 -1) todo)
12026 (list 'equal 'todo kwd))
12027 mm (if minus (list 'not mm) mm))
12028 (push mm todomatcher))
12029 (push (if (> (length todomatcher) 1)
12030 (cons 'and todomatcher)
12031 (car todomatcher))
12032 orlist)
12033 (setq todomatcher nil))
12034 (setq todomatcher (if (> (length orlist) 1)
12035 (cons 'or orlist) (car orlist))))
12037 ;; Return the string and lisp forms of the matcher
12038 (setq matcher (if todomatcher
12039 (list 'and tagsmatcher todomatcher)
12040 tagsmatcher))
12041 (cons match0 matcher)))
12043 (defun org-match-any-p (re list)
12044 "Does re match any element of list?"
12045 (setq list (mapcar (lambda (x) (string-match re x)) list))
12046 (delq nil list))
12048 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
12049 (defvar org-tags-overlay (org-make-overlay 1 1))
12050 (org-detach-overlay org-tags-overlay)
12052 (defun org-set-tags (&optional arg just-align)
12053 "Set the tags for the current headline.
12054 With prefix ARG, realign all tags in headings in the current buffer."
12055 (interactive "P")
12056 (let* ((re (concat "^" outline-regexp))
12057 (current (org-get-tags))
12058 table current-tags inherited-tags ; computed below when needed
12059 tags p0 c0 c1 rpl)
12060 (if arg
12061 (save-excursion
12062 (goto-char (point-min))
12063 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12064 (while (re-search-forward re nil t)
12065 (org-set-tags nil t)
12066 (end-of-line 1)))
12067 (message "All tags realigned to column %d" org-tags-column))
12068 (if just-align
12069 (setq tags current)
12070 ;; Get a new set of tags from the user
12071 (save-excursion
12072 (setq table (or org-tag-alist (org-get-buffer-tags))
12073 org-last-tags-completion-table table
12074 current-tags (org-split-string current ":")
12075 inherited-tags (nreverse
12076 (nthcdr (length current-tags)
12077 (nreverse (org-get-tags-at))))
12078 tags
12079 (if (or (eq t org-use-fast-tag-selection)
12080 (and org-use-fast-tag-selection
12081 (delq nil (mapcar 'cdr table))))
12082 (org-fast-tag-selection current-tags inherited-tags table)
12083 (let ((org-add-colon-after-tag-completion t))
12084 (org-trim
12085 (completing-read "Tags: " 'org-tags-completion-function
12086 nil nil current 'org-tags-history))))))
12087 (while (string-match "[-+&]+" tags)
12088 ;; No boolean logic, just a list
12089 (setq tags (replace-match ":" t t tags))))
12091 (if (string-match "\\`[\t ]*\\'" tags)
12092 (setq tags "")
12093 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12094 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12096 ;; Insert new tags at the correct column
12097 (beginning-of-line 1)
12098 (if (re-search-forward
12099 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12100 (point-at-eol) t)
12101 (progn
12102 (if (equal tags "")
12103 (setq rpl "")
12104 (goto-char (match-beginning 0))
12105 (setq c0 (current-column) p0 (point)
12106 c1 (max (1+ c0) (if (> org-tags-column 0)
12107 org-tags-column
12108 (- (- org-tags-column) (length tags))))
12109 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12110 (replace-match rpl t t)
12111 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
12112 tags)
12113 (error "Tags alignment failed")))))
12115 (defun org-tags-completion-function (string predicate &optional flag)
12116 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12117 (confirm (lambda (x) (stringp (car x)))))
12118 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12119 (setq s1 (match-string 1 string)
12120 s2 (match-string 2 string))
12121 (setq s1 "" s2 string))
12122 (cond
12123 ((eq flag nil)
12124 ;; try completion
12125 (setq rtn (try-completion s2 ctable confirm))
12126 (if (stringp rtn)
12127 (concat s1 s2 (substring rtn (length s2))
12128 (if (and org-add-colon-after-tag-completion
12129 (assoc rtn ctable))
12130 ":" "")))
12132 ((eq flag t)
12133 ;; all-completions
12134 (all-completions s2 ctable confirm)
12136 ((eq flag 'lambda)
12137 ;; exact match?
12138 (assoc s2 ctable)))
12141 (defun org-fast-tag-insert (kwd tags face &optional end)
12142 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
12143 (insert (format "%-12s" (concat kwd ":"))
12144 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12145 (or end "")))
12147 (defun org-fast-tag-show-exit (flag)
12148 (save-excursion
12149 (goto-line 3)
12150 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12151 (replace-match ""))
12152 (when flag
12153 (end-of-line 1)
12154 (move-to-column (- (window-width) 19) t)
12155 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12157 (defun org-set-current-tags-overlay (current prefix)
12158 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12159 (if (featurep 'xemacs)
12160 (org-overlay-display org-tags-overlay (concat prefix s)
12161 'secondary-selection)
12162 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12163 (org-overlay-display org-tags-overlay (concat prefix s)))))
12165 (defun org-fast-tag-selection (current inherited table)
12166 "Fast tag selection with single keys.
12167 CURRENT is the current list of tags in the headline, INHERITED is the
12168 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12169 possibly with grouping information.
12170 If the keys are nil, a-z are automatically assigned.
12171 Returns the new tags string, or nil to not change the current settings."
12172 (let* ((maxlen (apply 'max (mapcar
12173 (lambda (x)
12174 (if (stringp (car x)) (string-width (car x)) 0))
12175 table)))
12176 (buf (current-buffer))
12177 (expert (eq org-fast-tag-selection-single-key 'expert))
12178 (buffer-tags nil)
12179 (fwidth (+ maxlen 3 1 3))
12180 (ncol (/ (- (window-width) 4) fwidth))
12181 (i-face 'org-done)
12182 (c-face 'org-tag)
12183 tg cnt e c char c1 c2 ntable tbl rtn
12184 ov-start ov-end ov-prefix
12185 (exit-after-next org-fast-tag-selection-single-key)
12186 groups ingroup)
12187 (save-excursion
12188 (beginning-of-line 1)
12189 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
12190 (setq ov-start (match-beginning 1)
12191 ov-end (match-end 1)
12192 ov-prefix "")
12193 (setq ov-start (1- (point-at-eol))
12194 ov-end (1+ ov-start))
12195 (skip-chars-forward "^\n\r")
12196 (setq ov-prefix
12197 (concat
12198 (buffer-substring (1- (point)) (point))
12199 (if (> (current-column) org-tags-column)
12201 (make-string (- org-tags-column (current-column)) ?\ ))))))
12202 (org-move-overlay org-tags-overlay ov-start ov-end)
12203 (save-window-excursion
12204 (if expert
12205 (set-buffer (get-buffer-create " *Org tags*"))
12206 (delete-other-windows)
12207 (split-window-vertically)
12208 (switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12209 (erase-buffer)
12210 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12211 (org-fast-tag-insert "Current" current c-face "\n\n")
12212 (org-fast-tag-show-exit exit-after-next)
12213 (org-set-current-tags-overlay current ov-prefix)
12214 (setq tbl table char ?a cnt 0)
12215 (while (setq e (pop tbl))
12216 (cond
12217 ((equal e '(:startgroup))
12218 (push '() groups) (setq ingroup t)
12219 (when (not (= cnt 0))
12220 (setq cnt 0)
12221 (insert "\n"))
12222 (insert "{ "))
12223 ((equal e '(:endgroup))
12224 (setq ingroup nil cnt 0)
12225 (insert "}\n"))
12227 (setq tg (car e) c2 nil)
12228 (if (cdr e)
12229 (setq c (cdr e))
12230 ;; automatically assign a character.
12231 (setq c1 (string-to-char
12232 (downcase (substring
12233 tg (if (= (string-to-char tg) ?@) 1 0)))))
12234 (if (or (rassoc c1 ntable) (rassoc c1 table))
12235 (while (or (rassoc char ntable) (rassoc char table))
12236 (setq char (1+ char)))
12237 (setq c2 c1))
12238 (setq c (or c2 char)))
12239 (if ingroup (push tg (car groups)))
12240 (setq tg (org-add-props tg nil 'face
12241 (cond
12242 ((member tg current) c-face)
12243 ((member tg inherited) i-face)
12244 (t nil))))
12245 (if (and (= cnt 0) (not ingroup)) (insert " "))
12246 (insert "[" c "] " tg (make-string
12247 (- fwidth 4 (length tg)) ?\ ))
12248 (push (cons tg c) ntable)
12249 (when (= (setq cnt (1+ cnt)) ncol)
12250 (insert "\n")
12251 (if ingroup (insert " "))
12252 (setq cnt 0)))))
12253 (setq ntable (nreverse ntable))
12254 (insert "\n")
12255 (goto-char (point-min))
12256 (if (and (not expert) (fboundp 'fit-window-to-buffer))
12257 (fit-window-to-buffer))
12258 (setq rtn
12259 (catch 'exit
12260 (while t
12261 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
12262 (if groups " [!] no groups" " [!]groups")
12263 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12264 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12265 (cond
12266 ((= c ?\r) (throw 'exit t))
12267 ((= c ?!)
12268 (setq groups (not groups))
12269 (goto-char (point-min))
12270 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12271 ((= c ?\C-c)
12272 (if (not expert)
12273 (org-fast-tag-show-exit
12274 (setq exit-after-next (not exit-after-next)))
12275 (setq expert nil)
12276 (delete-other-windows)
12277 (split-window-vertically)
12278 (switch-to-buffer-other-window " *Org tags*")
12279 (and (fboundp 'fit-window-to-buffer)
12280 (fit-window-to-buffer))))
12281 ((or (= c ?\C-g)
12282 (and (= c ?q) (not (rassoc c ntable))))
12283 (org-detach-overlay org-tags-overlay)
12284 (setq quit-flag t))
12285 ((= c ?\ )
12286 (setq current nil)
12287 (if exit-after-next (setq exit-after-next 'now)))
12288 ((= c ?\t)
12289 (condition-case nil
12290 (setq tg (completing-read
12291 "Tag: "
12292 (or buffer-tags
12293 (with-current-buffer buf
12294 (org-get-buffer-tags)))))
12295 (quit (setq tg "")))
12296 (when (string-match "\\S-" tg)
12297 (add-to-list 'buffer-tags (list tg))
12298 (if (member tg current)
12299 (setq current (delete tg current))
12300 (push tg current)))
12301 (if exit-after-next (setq exit-after-next 'now)))
12302 ((setq e (rassoc c ntable) tg (car e))
12303 (if (member tg current)
12304 (setq current (delete tg current))
12305 (loop for g in groups do
12306 (if (member tg g)
12307 (mapcar (lambda (x)
12308 (setq current (delete x current)))
12309 g)))
12310 (push tg current))
12311 (if exit-after-next (setq exit-after-next 'now))))
12313 ;; Create a sorted list
12314 (setq current
12315 (sort current
12316 (lambda (a b)
12317 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12318 (if (eq exit-after-next 'now) (throw 'exit t))
12319 (goto-char (point-min))
12320 (beginning-of-line 2)
12321 (delete-region (point) (point-at-eol))
12322 (org-fast-tag-insert "Current" current c-face)
12323 (org-set-current-tags-overlay current ov-prefix)
12324 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
12325 (setq tg (match-string 1))
12326 (add-text-properties (match-beginning 1) (match-end 1)
12327 (list 'face
12328 (cond
12329 ((member tg current) c-face)
12330 ((member tg inherited) i-face)
12331 (t nil)))))
12332 (goto-char (point-min)))))
12333 (org-detach-overlay org-tags-overlay)
12334 (if rtn
12335 (mapconcat 'identity current ":")
12336 nil))))
12338 (defun org-get-tags ()
12339 "Get the TAGS string in the current headline."
12340 (unless (org-on-heading-p t)
12341 (error "Not on a heading"))
12342 (save-excursion
12343 (beginning-of-line 1)
12344 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
12345 (org-match-string-no-properties 1)
12346 "")))
12348 (defun org-get-buffer-tags ()
12349 "Get a table of all tags used in the buffer, for completion."
12350 (let (tags)
12351 (save-excursion
12352 (goto-char (point-min))
12353 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
12354 (mapc (lambda (x) (add-to-list 'tags x))
12355 (org-split-string (org-match-string-no-properties 1) ":"))))
12356 (mapcar 'list tags)))
12358 ;;;; Timestamps
12360 (defvar org-last-changed-timestamp nil)
12361 (defvar org-time-was-given) ; dynamically scoped parameter
12362 (defvar org-ts-what) ; dynamically scoped parameter
12364 (defun org-time-stamp (arg)
12365 "Prompt for a date/time and insert a time stamp.
12366 If the user specifies a time like HH:MM, or if this command is called
12367 with a prefix argument, the time stamp will contain date and time.
12368 Otherwise, only the date will be included. All parts of a date not
12369 specified by the user will be filled in from the current date/time.
12370 So if you press just return without typing anything, the time stamp
12371 will represent the current date/time. If there is already a timestamp
12372 at the cursor, it will be modified."
12373 (interactive "P")
12374 (let (org-time-was-given time)
12375 (cond
12376 ((and (org-at-timestamp-p)
12377 (eq last-command 'org-time-stamp)
12378 (eq this-command 'org-time-stamp))
12379 (insert "--")
12380 (setq time (let ((this-command this-command))
12381 (org-read-date arg 'totime)))
12382 (org-insert-time-stamp time (or org-time-was-given arg)))
12383 ((org-at-timestamp-p)
12384 (setq time (let ((this-command this-command))
12385 (org-read-date arg 'totime)))
12386 (when (org-at-timestamp-p) ; just to get the match data
12387 (replace-match "")
12388 (setq org-last-changed-timestamp
12389 (org-insert-time-stamp time (or org-time-was-given arg))))
12390 (message "Timestamp updated"))
12392 (setq time (let ((this-command this-command))
12393 (org-read-date arg 'totime)))
12394 (org-insert-time-stamp time (or org-time-was-given arg))))))
12396 (defun org-time-stamp-inactive (&optional arg)
12397 "Insert an inactive time stamp.
12398 An inactive time stamp is enclosed in square brackets instead of angle
12399 brackets. It is inactive in the sense that it does not trigger agenda entries,
12400 does not link to the calendar and cannot be changed with the S-cursor keys.
12401 So these are more for recording a certain time/date."
12402 (interactive "P")
12403 (let (org-time-was-given time)
12404 (setq time (org-read-date arg 'totime))
12405 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
12407 (defvar org-date-ovl (org-make-overlay 1 1))
12408 (org-overlay-put org-date-ovl 'face 'org-warning)
12409 (org-detach-overlay org-date-ovl)
12411 (defvar org-ans1) ; dynamically scoped parameter
12412 (defvar org-ans2) ; dynamically scoped parameter
12414 (defun org-read-date (&optional with-time to-time from-string prompt)
12415 "Read a date and make things smooth for the user.
12416 The prompt will suggest to enter an ISO date, but you can also enter anything
12417 which will at least partially be understood by `parse-time-string'.
12418 Unrecognized parts of the date will default to the current day, month, year,
12419 hour and minute. For example,
12420 3-2-5 --> 2003-02-05
12421 feb 15 --> currentyear-02-15
12422 sep 12 9 --> 2009-09-12
12423 12:45 --> today 12:45
12424 22 sept 0:34 --> currentyear-09-22 0:34
12425 12 --> currentyear-currentmonth-12
12426 Fri --> nearest Friday (today or later)
12427 +4 --> four days from today (only if +N is the only thing given)
12428 etc.
12429 The function understands only English month and weekday abbreviations,
12430 but this can be configured with the variables `parse-time-months' and
12431 `parse-time-weekdays'.
12433 While prompting, a calendar is popped up - you can also select the
12434 date with the mouse (button 1). The calendar shows a period of three
12435 months. To scroll it to other months, use the keys `>' and `<'.
12436 If you don't like the calendar, turn it off with
12437 \(setq org-popup-calendar-for-date-prompt nil)
12439 With optional argument TO-TIME, the date will immediately be converted
12440 to an internal time.
12441 With an optional argument WITH-TIME, the prompt will suggest to also
12442 insert a time. Note that when WITH-TIME is not set, you can still
12443 enter a time, and this function will inform the calling routine about
12444 this change. The calling routine may then choose to change the format
12445 used to insert the time stamp into the buffer to include the time."
12446 (require 'parse-time)
12447 (let* ((org-time-stamp-rounding-minutes
12448 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
12449 (ct (org-current-time))
12450 (default-time
12451 ;; Default time is either today, or, when entering a range,
12452 ;; the range start.
12453 (if (save-excursion
12454 (re-search-backward
12455 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12456 (- (point) 20) t))
12457 (apply
12458 'encode-time
12459 (mapcar (lambda(x) (or x 0))
12460 (parse-time-string (match-string 1))))
12461 ct))
12462 (calendar-move-hook nil)
12463 (view-diary-entries-initially nil)
12464 (view-calendar-holidays-initially nil)
12465 (timestr (format-time-string
12466 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
12467 (prompt (concat (if prompt (concat prompt " ") "")
12468 (format "Date and/or time (default [%s]): " timestr)))
12469 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
12470 second minute hour day month year tl wday wday1 pm)
12472 (cond
12473 (from-string (setq ans from-string))
12474 (org-popup-calendar-for-date-prompt
12475 (save-excursion
12476 (save-window-excursion
12477 (calendar)
12478 (calendar-forward-day (- (time-to-days default-time)
12479 (calendar-absolute-from-gregorian
12480 (calendar-current-date))))
12481 (org-eval-in-calendar nil)
12482 (let* ((old-map (current-local-map))
12483 (map (copy-keymap calendar-mode-map))
12484 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12485 (define-key map (kbd "RET") 'org-calendar-select)
12486 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
12487 'org-calendar-select-mouse)
12488 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
12489 'org-calendar-select-mouse)
12490 (define-key minibuffer-local-map [(meta shift left)]
12491 (lambda () (interactive)
12492 (org-eval-in-calendar '(calendar-backward-month 1))))
12493 (define-key minibuffer-local-map [(meta shift right)]
12494 (lambda () (interactive)
12495 (org-eval-in-calendar '(calendar-forward-month 1))))
12496 (define-key minibuffer-local-map [(shift up)]
12497 (lambda () (interactive)
12498 (org-eval-in-calendar '(calendar-backward-week 1))))
12499 (define-key minibuffer-local-map [(shift down)]
12500 (lambda () (interactive)
12501 (org-eval-in-calendar '(calendar-forward-week 1))))
12502 (define-key minibuffer-local-map [(shift left)]
12503 (lambda () (interactive)
12504 (org-eval-in-calendar '(calendar-backward-day 1))))
12505 (define-key minibuffer-local-map [(shift right)]
12506 (lambda () (interactive)
12507 (org-eval-in-calendar '(calendar-forward-day 1))))
12508 (define-key minibuffer-local-map ">"
12509 (lambda () (interactive)
12510 (org-eval-in-calendar '(scroll-calendar-left 1))))
12511 (define-key minibuffer-local-map "<"
12512 (lambda () (interactive)
12513 (org-eval-in-calendar '(scroll-calendar-right 1))))
12514 (unwind-protect
12515 (progn
12516 (use-local-map map)
12517 (setq org-ans0 (read-string prompt "" nil nil))
12518 ;; org-ans0: from prompt
12519 ;; org-ans1: from mouse click
12520 ;; org-ans2: from calendar motion
12521 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12522 (use-local-map old-map))))))
12523 (t ; Naked prompt only
12524 (setq ans (read-string prompt "" nil timestr))))
12525 (org-detach-overlay org-date-ovl)
12527 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
12528 (setq deltadays (string-to-number ans) ans ""))
12530 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12531 (when (string-match
12532 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12533 (setq year (if (match-end 2)
12534 (string-to-number (match-string 2 ans))
12535 (string-to-number (format-time-string "%Y")))
12536 month (string-to-number (match-string 3 ans))
12537 day (string-to-number (match-string 4 ans)))
12538 (if (< year 100) (setq year (+ 2000 year)))
12539 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12540 t nil ans)))
12541 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12542 ;; If there is a time with am/pm, and *no* time without it, we convert
12543 ;; convert so that matching will be successful.
12544 (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12545 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12546 (setq hour (string-to-number (match-string 1 ans))
12547 minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
12548 pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
12549 (if (and (= hour 12) (not pm))
12550 (setq hour 0)
12551 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12552 (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
12554 (setq tl (parse-time-string ans)
12555 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
12556 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
12557 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
12558 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
12559 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
12560 second (or (nth 0 tl) 0)
12561 wday (nth 6 tl))
12562 (setq day (+ day deltadays))
12563 (when (and wday (not (nth 3 tl)))
12564 ;; Weekday was given, but no day, so pick that day in the week
12565 ;; on or after the derived date.
12566 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12567 (unless (equal wday wday1)
12568 (setq day (+ day (% (- wday wday1 -7) 7)))))
12569 (if (and (boundp 'org-time-was-given)
12570 (nth 2 tl))
12571 (setq org-time-was-given t))
12572 (if (< year 100) (setq year (+ 2000 year)))
12573 (if to-time
12574 (encode-time second minute hour day month year)
12575 (if (or (nth 1 tl) (nth 2 tl))
12576 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
12577 (format "%04d-%02d-%02d" year month day)))))
12579 (defun org-eval-in-calendar (form)
12580 "Eval FORM in the calendar window and return to current window.
12581 Also, store the cursor date in variable org-ans2."
12582 (let ((sw (selected-window)))
12583 (select-window (get-buffer-window "*Calendar*"))
12584 (eval form)
12585 (when (calendar-cursor-to-date)
12586 (let* ((date (calendar-cursor-to-date))
12587 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12588 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12589 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12590 (select-window sw)
12591 ;; Update the prompt to show new default date
12592 (save-excursion
12593 (goto-char (point-min))
12594 (when (and (re-search-forward "\\[[-0-9]+\\]" nil t)
12595 (get-text-property (match-end 0) 'field))
12596 (let ((inhibit-read-only t))
12597 (replace-match (concat "[" org-ans2 "]") t t)
12598 (add-text-properties (point-min) (1+ (match-end 0))
12599 (text-properties-at (1+ (point-min)))))))))
12601 (defun org-calendar-select ()
12602 "Return to `org-read-date' with the date currently selected.
12603 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12604 (interactive)
12605 (when (calendar-cursor-to-date)
12606 (let* ((date (calendar-cursor-to-date))
12607 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12608 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12609 (if (active-minibuffer-window) (exit-minibuffer))))
12611 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
12612 "Insert a date stamp for the date given by the internal TIME.
12613 WITH-HM means, use the stamp format that includes the time of the day.
12614 INACTIVE means use square brackets instead of angular ones, so that the
12615 stamp will not contribute to the agenda.
12616 PRE and POST are optional strings to be inserted before and after the
12617 stamp.
12618 The command returns the inserted time stamp."
12619 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12620 stamp)
12621 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12622 (insert (or pre ""))
12623 (insert (setq stamp (format-time-string fmt time)))
12624 (insert (or post ""))
12625 stamp))
12627 (defun org-toggle-time-stamp-overlays ()
12628 "Toggle the use of custom time stamp formats."
12629 (interactive)
12630 (setq org-display-custom-times (not org-display-custom-times))
12631 (unless org-display-custom-times
12632 (let ((p (point-min)) (bmp (buffer-modified-p)))
12633 (while (setq p (next-single-property-change p 'display))
12634 (if (and (get-text-property p 'display)
12635 (eq (get-text-property p 'face) 'org-date))
12636 (remove-text-properties
12637 p (setq p (next-single-property-change p 'display))
12638 '(display t))))
12639 (set-buffer-modified-p bmp)))
12640 (if (featurep 'xemacs)
12641 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12642 (org-restart-font-lock)
12643 (setq org-table-may-need-update t)
12644 (if org-display-custom-times
12645 (message "Time stamps are overlayed with custom format")
12646 (message "Time stamp overlays removed")))
12648 (defun org-display-custom-time (beg end)
12649 "Overlay modified time stamp format over timestamp between BED and END."
12650 (let* ((t1 (save-match-data
12651 (org-parse-time-string (buffer-substring beg end) t)))
12652 (w1 (- end beg))
12653 (with-hm (and (nth 1 t1) (nth 2 t1)))
12654 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
12655 (time (org-fix-decoded-time t1))
12656 (str (org-add-props
12657 (format-time-string
12658 (substring tf 1 -1) (apply 'encode-time time))
12659 nil 'mouse-face 'highlight))
12660 (w2 (length str)))
12661 (if (not (= w2 w1))
12662 (add-text-properties (1+ beg) (+ 2 beg)
12663 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12664 (if (featurep 'xemacs)
12665 (progn
12666 (put-text-property beg end 'invisible t)
12667 (put-text-property beg end 'end-glyph (make-glyph str)))
12668 (put-text-property beg end 'display str))))
12670 (defun org-translate-time (string)
12671 "Translate all timestamps in STRING to custom format.
12672 But do this only if the variable `org-display-custom-times' is set."
12673 (when org-display-custom-times
12674 (save-match-data
12675 (let* ((start 0)
12676 (re org-ts-regexp-both)
12677 t1 with-hm inactive tf time str beg end)
12678 (while (setq start (string-match re string start))
12679 (setq beg (match-beginning 0)
12680 end (match-end 0)
12681 t1 (save-match-data
12682 (org-parse-time-string (substring string beg end) t))
12683 with-hm (and (nth 1 t1) (nth 2 t1))
12684 inactive (equal (substring string beg (1+ beg)) "[")
12685 tf (funcall (if with-hm 'cdr 'car)
12686 org-time-stamp-custom-formats)
12687 time (org-fix-decoded-time t1)
12688 str (format-time-string
12689 (concat
12690 (if inactive "[" "<") (substring tf 1 -1)
12691 (if inactive "]" ">"))
12692 (apply 'encode-time time))
12693 string (replace-match str t t string)
12694 start (+ start (length str)))))))
12695 string)
12697 (defun org-fix-decoded-time (time)
12698 "Set 0 instead of nil for the first 6 elements of time.
12699 Don't touch the rest."
12700 (let ((n 0))
12701 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12703 (defun org-days-to-time (timestamp-string)
12704 "Difference between TIMESTAMP-STRING and now in days."
12705 (- (time-to-days (org-time-string-to-time timestamp-string))
12706 (time-to-days (current-time))))
12708 (defun org-deadline-close (timestamp-string &optional ndays)
12709 "Is the time in TIMESTAMP-STRING close to the current date?"
12710 (and (< (org-days-to-time timestamp-string)
12711 (or ndays org-deadline-warning-days))
12712 (not (org-entry-is-done-p))))
12714 (defun org-calendar-select-mouse (ev)
12715 "Return to `org-read-date' with the date currently selected.
12716 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12717 (interactive "e")
12718 (mouse-set-point ev)
12719 (when (calendar-cursor-to-date)
12720 (let* ((date (calendar-cursor-to-date))
12721 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12722 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12723 (if (active-minibuffer-window) (exit-minibuffer))))
12725 (defun org-check-deadlines (ndays)
12726 "Check if there are any deadlines due or past due.
12727 A deadline is considered due if it happens within `org-deadline-warning-days'
12728 days from today's date. If the deadline appears in an entry marked DONE,
12729 it is not shown. The prefix arg NDAYS can be used to test that many
12730 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12731 (interactive "P")
12732 (let* ((org-warn-days
12733 (cond
12734 ((equal ndays '(4)) 100000)
12735 (ndays (prefix-numeric-value ndays))
12736 (t org-deadline-warning-days)))
12737 (case-fold-search nil)
12738 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12739 (callback
12740 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12742 (message "%d deadlines past-due or due within %d days"
12743 (org-occur regexp nil callback)
12744 org-warn-days)))
12746 (defun org-evaluate-time-range (&optional to-buffer)
12747 "Evaluate a time range by computing the difference between start and end.
12748 Normally the result is just printed in the echo area, but with prefix arg
12749 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12750 If the time range is actually in a table, the result is inserted into the
12751 next column.
12752 For time difference computation, a year is assumed to be exactly 365
12753 days in order to avoid rounding problems."
12754 (interactive "P")
12756 (org-clock-update-time-maybe)
12757 (save-excursion
12758 (unless (org-at-date-range-p)
12759 (goto-char (point-at-bol))
12760 (re-search-forward org-tr-regexp (point-at-eol) t))
12761 (if (not (org-at-date-range-p))
12762 (error "Not at a time-stamp range, and none found in current line")))
12763 (let* ((ts1 (match-string 1))
12764 (ts2 (match-string 2))
12765 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12766 (match-end (match-end 0))
12767 (time1 (org-time-string-to-time ts1))
12768 (time2 (org-time-string-to-time ts2))
12769 (t1 (time-to-seconds time1))
12770 (t2 (time-to-seconds time2))
12771 (diff (abs (- t2 t1)))
12772 (negative (< (- t2 t1) 0))
12773 ;; (ys (floor (* 365 24 60 60)))
12774 (ds (* 24 60 60))
12775 (hs (* 60 60))
12776 (fy "%dy %dd %02d:%02d")
12777 (fy1 "%dy %dd")
12778 (fd "%dd %02d:%02d")
12779 (fd1 "%dd")
12780 (fh "%02d:%02d")
12781 y d h m align)
12782 (if havetime
12783 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12785 d (floor (/ diff ds)) diff (mod diff ds)
12786 h (floor (/ diff hs)) diff (mod diff hs)
12787 m (floor (/ diff 60)))
12788 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12790 d (floor (+ (/ diff ds) 0.5))
12791 h 0 m 0))
12792 (if (not to-buffer)
12793 (message (org-make-tdiff-string y d h m))
12794 (when (org-at-table-p)
12795 (goto-char match-end)
12796 (setq align t)
12797 (and (looking-at " *|") (goto-char (match-end 0))))
12798 (if (looking-at
12799 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12800 (replace-match ""))
12801 (if negative (insert " -"))
12802 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12803 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12804 (insert " " (format fh h m))))
12805 (if align (org-table-align))
12806 (message "Time difference inserted")))))
12808 (defun org-make-tdiff-string (y d h m)
12809 (let ((fmt "")
12810 (l nil))
12811 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12812 l (push y l)))
12813 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12814 l (push d l)))
12815 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12816 l (push h l)))
12817 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12818 l (push m l)))
12819 (apply 'format fmt (nreverse l))))
12821 (defun org-time-string-to-time (s)
12822 (apply 'encode-time (org-parse-time-string s)))
12824 (defun org-parse-time-string (s &optional nodefault)
12825 "Parse the standard Org-mode time string.
12826 This should be a lot faster than the normal `parse-time-string'.
12827 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12828 hour and minute fields will be nil if not given."
12829 (if (string-match org-ts-regexp1 s)
12830 (list 0
12831 (if (or (match-beginning 8) (not nodefault))
12832 (string-to-number (or (match-string 8 s) "0")))
12833 (if (or (match-beginning 7) (not nodefault))
12834 (string-to-number (or (match-string 7 s) "0")))
12835 (string-to-number (match-string 4 s))
12836 (string-to-number (match-string 3 s))
12837 (string-to-number (match-string 2 s))
12838 nil nil nil)
12839 (make-list 9 0)))
12841 (defun org-timestamp-up (&optional arg)
12842 "Increase the date item at the cursor by one.
12843 If the cursor is on the year, change the year. If it is on the month or
12844 the day, change that.
12845 With prefix ARG, change by that many units."
12846 (interactive "p")
12847 (org-timestamp-change (prefix-numeric-value arg)))
12849 (defun org-timestamp-down (&optional arg)
12850 "Decrease the date item at the cursor by one.
12851 If the cursor is on the year, change the year. If it is on the month or
12852 the day, change that.
12853 With prefix ARG, change by that many units."
12854 (interactive "p")
12855 (org-timestamp-change (- (prefix-numeric-value arg))))
12857 (defun org-timestamp-up-day (&optional arg)
12858 "Increase the date in the time stamp by one day.
12859 With prefix ARG, change that many days."
12860 (interactive "p")
12861 (if (and (not (org-at-timestamp-p t))
12862 (org-on-heading-p))
12863 (org-todo 'up)
12864 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12866 (defun org-timestamp-down-day (&optional arg)
12867 "Decrease the date in the time stamp by one day.
12868 With prefix ARG, change that many days."
12869 (interactive "p")
12870 (if (and (not (org-at-timestamp-p t))
12871 (org-on-heading-p))
12872 (org-todo 'down)
12873 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12875 (defsubst org-pos-in-match-range (pos n)
12876 (and (match-beginning n)
12877 (<= (match-beginning n) pos)
12878 (>= (match-end n) pos)))
12880 (defun org-at-timestamp-p (&optional inactive-ok)
12881 "Determine if the cursor is in or at a timestamp."
12882 (interactive)
12883 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12884 (pos (point))
12885 (ans (or (looking-at tsr)
12886 (save-excursion
12887 (skip-chars-backward "^[<\n\r\t")
12888 (if (> (point) 1) (backward-char 1))
12889 (and (looking-at tsr)
12890 (> (- (match-end 0) pos) -1))))))
12891 (and (boundp 'org-ts-what)
12892 (setq org-ts-what
12893 (cond
12894 ((org-pos-in-match-range pos 2) 'year)
12895 ((org-pos-in-match-range pos 3) 'month)
12896 ((org-pos-in-match-range pos 7) 'hour)
12897 ((org-pos-in-match-range pos 8) 'minute)
12898 ((or (org-pos-in-match-range pos 4)
12899 (org-pos-in-match-range pos 5)) 'day)
12900 (t 'day))))
12901 ans))
12903 (defun org-timestamp-change (n &optional what)
12904 "Change the date in the time stamp at point.
12905 The date will be changed by N times WHAT. WHAT can be `day', `month',
12906 `year', `minute', `second'. If WHAT is not given, the cursor position
12907 in the timestamp determines what will be changed."
12908 (let ((pos (point))
12909 with-hm inactive
12910 org-ts-what
12911 ts time time0)
12912 (if (not (org-at-timestamp-p t))
12913 (error "Not at a timestamp"))
12914 (if (and (not what) (not (eq org-ts-what 'day))
12915 org-display-custom-times
12916 (get-text-property (point) 'display)
12917 (not (get-text-property (1- (point)) 'display)))
12918 (setq org-ts-what 'day))
12919 (setq org-ts-what (or what org-ts-what)
12920 with-hm (<= (abs (- (cdr org-ts-lengths)
12921 (- (match-end 0) (match-beginning 0))))
12923 inactive (= (char-after (match-beginning 0)) ?\[)
12924 ts (match-string 0))
12925 (replace-match "")
12926 (setq time0 (org-parse-time-string ts))
12927 (setq time
12928 (apply 'encode-time
12929 (append
12930 (list (or (car time0) 0))
12931 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
12932 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
12933 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
12934 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
12935 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
12936 (nthcdr 6 time0))))
12937 (if (eq what 'calendar)
12938 (let ((cal-date
12939 (save-excursion
12940 (save-match-data
12941 (set-buffer "*Calendar*")
12942 (calendar-cursor-to-date)))))
12943 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12944 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12945 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12946 (setcar time0 (or (car time0) 0))
12947 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12948 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
12949 (setq time (apply 'encode-time time0))))
12950 (setq org-last-changed-timestamp
12951 (org-insert-time-stamp time with-hm inactive))
12952 (org-clock-update-time-maybe)
12953 (goto-char pos)
12954 ;; Try to recenter the calendar window, if any
12955 (if (and org-calendar-follow-timestamp-change
12956 (get-buffer-window "*Calendar*" t)
12957 (memq org-ts-what '(day month year)))
12958 (org-recenter-calendar (time-to-days time)))))
12960 (defun org-recenter-calendar (date)
12961 "If the calendar is visible, recenter it to DATE."
12962 (let* ((win (selected-window))
12963 (cwin (get-buffer-window "*Calendar*" t))
12964 (calendar-move-hook nil))
12965 (when cwin
12966 (select-window cwin)
12967 (calendar-goto-date (if (listp date) date
12968 (calendar-gregorian-from-absolute date)))
12969 (select-window win))))
12971 (defun org-goto-calendar (&optional arg)
12972 "Go to the Emacs calendar at the current date.
12973 If there is a time stamp in the current line, go to that date.
12974 A prefix ARG can be used to force the current date."
12975 (interactive "P")
12976 (let ((tsr org-ts-regexp) diff
12977 (calendar-move-hook nil)
12978 (view-calendar-holidays-initially nil)
12979 (view-diary-entries-initially nil))
12980 (if (or (org-at-timestamp-p)
12981 (save-excursion
12982 (beginning-of-line 1)
12983 (looking-at (concat ".*" tsr))))
12984 (let ((d1 (time-to-days (current-time)))
12985 (d2 (time-to-days
12986 (org-time-string-to-time (match-string 1)))))
12987 (setq diff (- d2 d1))))
12988 (calendar)
12989 (calendar-goto-today)
12990 (if (and diff (not arg)) (calendar-forward-day diff))))
12992 (defun org-date-from-calendar ()
12993 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12994 If there is already a time stamp at the cursor position, update it."
12995 (interactive)
12996 (org-timestamp-change 0 'calendar))
12998 ;;; The clock for measuring work time.
13000 (defvar org-clock-marker (make-marker)
13001 "Marker recording the last clock-in.")
13003 (defun org-clock-in ()
13004 "Start the clock on the current item.
13005 If necessary, clock-out of the currently active clock."
13006 (interactive)
13007 (org-clock-out t)
13008 (let (ts)
13009 (save-excursion
13010 (org-back-to-heading t)
13011 (beginning-of-line 2)
13012 (when (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
13013 (not (equal (match-string 1) org-clock-string)))
13014 ;; First line hast scheduling info, move one further
13015 (beginning-of-line 2)
13016 (or (bolp) (newline)))
13017 (insert "\n") (backward-char 1)
13018 (indent-relative)
13019 (insert org-clock-string " ")
13020 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
13021 (move-marker org-clock-marker (point) (buffer-base-buffer))
13022 (message "Clock started at %s" ts))))
13024 (defun org-clock-out (&optional fail-quietly)
13025 "Stop the currently running clock.
13026 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
13027 (interactive)
13028 (catch 'exit
13029 (if (not (marker-buffer org-clock-marker))
13030 (if fail-quietly (throw 'exit t) (error "No active clock")))
13031 (let (ts te s h m)
13032 (save-excursion
13033 (set-buffer (marker-buffer org-clock-marker))
13034 (goto-char org-clock-marker)
13035 (beginning-of-line 1)
13036 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
13037 (equal (match-string 1) org-clock-string))
13038 (setq ts (match-string 2))
13039 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
13040 (goto-char org-clock-marker)
13041 (insert "--")
13042 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
13043 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
13044 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
13045 h (floor (/ s 3600))
13046 s (- s (* 3600 h))
13047 m (floor (/ s 60))
13048 s (- s (* 60 s)))
13049 (insert " => " (format "%2d:%02d" h m))
13050 (move-marker org-clock-marker nil)
13051 (org-add-log-maybe 'clock-out)
13052 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
13054 (defun org-clock-cancel ()
13055 "Cancel the running clock be removing the start timestamp."
13056 (interactive)
13057 (if (not (marker-buffer org-clock-marker))
13058 (error "No active clock"))
13059 (save-excursion
13060 (set-buffer (marker-buffer org-clock-marker))
13061 (goto-char org-clock-marker)
13062 (delete-region (1- (point-at-bol)) (point-at-eol)))
13063 (message "Clock canceled"))
13065 (defvar org-clock-file-total-minutes nil
13066 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
13067 (make-variable-buffer-local 'org-clock-file-total-minutes)
13069 (defun org-clock-sum (&optional tstart tend)
13070 "Sum the times for each subtree.
13071 Puts the resulting times in minutes as a text property on each headline."
13072 (interactive)
13073 (let* ((bmp (buffer-modified-p))
13074 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
13075 org-clock-string
13076 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
13077 (lmax 30)
13078 (ltimes (make-vector lmax 0))
13079 (t1 0)
13080 (level 0)
13081 ts te dt
13082 time)
13083 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
13084 (save-excursion
13085 (goto-char (point-max))
13086 (while (re-search-backward re nil t)
13087 (if (match-end 2)
13088 ;; A time
13089 (setq ts (match-string 2)
13090 te (match-string 3)
13091 ts (time-to-seconds
13092 (apply 'encode-time (org-parse-time-string ts)))
13093 te (time-to-seconds
13094 (apply 'encode-time (org-parse-time-string te)))
13095 ts (if tstart (max ts tstart) ts)
13096 te (if tend (min te tend) te)
13097 dt (- te ts)
13098 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
13099 ;; A headline
13100 (setq level (- (match-end 1) (match-beginning 1)))
13101 (when (or (> t1 0) (> (aref ltimes level) 0))
13102 (loop for l from 0 to level do
13103 (aset ltimes l (+ (aref ltimes l) t1)))
13104 (setq t1 0 time (aref ltimes level))
13105 (loop for l from level to (1- lmax) do
13106 (aset ltimes l 0))
13107 (goto-char (match-beginning 0))
13108 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
13109 (setq org-clock-file-total-minutes (aref ltimes 0)))
13110 (set-buffer-modified-p bmp)))
13112 (defun org-clock-display (&optional total-only)
13113 "Show subtree times in the entire buffer.
13114 If TOTAL-ONLY is non-nil, only show the total time for the entire file
13115 in the echo area."
13116 (interactive)
13117 (org-remove-clock-overlays)
13118 (let (time h m p)
13119 (org-clock-sum)
13120 (unless total-only
13121 (save-excursion
13122 (goto-char (point-min))
13123 (while (setq p (next-single-property-change (point) :org-clock-minutes))
13124 (goto-char p)
13125 (when (setq time (get-text-property p :org-clock-minutes))
13126 (org-put-clock-overlay time (funcall outline-level))))
13127 (setq h (/ org-clock-file-total-minutes 60)
13128 m (- org-clock-file-total-minutes (* 60 h)))
13129 ;; Arrange to remove the overlays upon next change.
13130 (when org-remove-highlights-with-change
13131 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
13132 nil 'local))))
13133 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
13135 (defvar org-clock-overlays nil)
13136 (make-variable-buffer-local 'org-clock-overlays)
13138 (defun org-put-clock-overlay (time &optional level)
13139 "Put an overlays on the current line, displaying TIME.
13140 If LEVEL is given, prefix time with a corresponding number of stars.
13141 This creates a new overlay and stores it in `org-clock-overlays', so that it
13142 will be easy to remove."
13143 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
13144 (l (if level (org-get-legal-level level 0) 0))
13145 (off 0)
13146 ov tx)
13147 (move-to-column c)
13148 (unless (eolp) (skip-chars-backward "^ \t"))
13149 (skip-chars-backward " \t")
13150 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
13151 tx (concat (buffer-substring (1- (point)) (point))
13152 (make-string (+ off (max 0 (- c (current-column)))) ?.)
13153 (org-add-props (format "%s %2d:%02d%s"
13154 (make-string l ?*) h m
13155 (make-string (- 10 l) ?\ ))
13156 '(face secondary-selection))
13157 ""))
13158 (if (not (featurep 'xemacs))
13159 (org-overlay-put ov 'display tx)
13160 (org-overlay-put ov 'invisible t)
13161 (org-overlay-put ov 'end-glyph (make-glyph tx)))
13162 (push ov org-clock-overlays)))
13164 (defun org-remove-clock-overlays (&optional beg end noremove)
13165 "Remove the occur highlights from the buffer.
13166 BEG and END are ignored. If NOREMOVE is nil, remove this function
13167 from the `before-change-functions' in the current buffer."
13168 (interactive)
13169 (unless org-inhibit-highlight-removal
13170 (mapc 'org-delete-overlay org-clock-overlays)
13171 (setq org-clock-overlays nil)
13172 (unless noremove
13173 (remove-hook 'before-change-functions
13174 'org-remove-clock-overlays 'local))))
13176 (defun org-clock-out-if-current ()
13177 "Clock out if the current entry contains the running clock.
13178 This is used to stop the clock after a TODO entry is marked DONE."
13179 (when (and (member state org-done-keywords)
13180 (equal (marker-buffer org-clock-marker) (current-buffer))
13181 (< (point) org-clock-marker)
13182 (> (save-excursion (outline-next-heading) (point))
13183 org-clock-marker))
13184 ;; Clock out, but don't accept a logging message for this.
13185 (let ((org-log-done (if (and (listp org-log-done)
13186 (member 'clock-out org-log-done))
13187 '(done)
13188 org-log-done)))
13189 (org-clock-out))))
13191 (add-hook 'org-after-todo-state-change-hook
13192 'org-clock-out-if-current)
13194 (defun org-check-running-clock ()
13195 "Check if the current buffer contains the running clock.
13196 If yes, offer to stop it and to save the buffer with the changes."
13197 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
13198 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
13199 (buffer-name))))
13200 (org-clock-out)
13201 (when (y-or-n-p "Save changed buffer?")
13202 (save-buffer))))
13204 (defun org-clock-report ()
13205 "Create a table containing a report about clocked time.
13206 If the buffer contains lines
13207 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
13209 #+END: clocktable
13210 then the table will be inserted between these lines, replacing whatever
13211 is was there before. If these lines are not in the buffer, the table
13212 is inserted at point, surrounded by the special lines.
13213 The BEGIN line can contain parameters. Allowed are:
13214 :maxlevel The maximum level to be included in the table. Default is 3.
13215 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
13216 (interactive)
13217 (org-remove-clock-overlays)
13218 (unless (org-find-dblock "clocktable")
13219 (org-create-dblock (list :name "clocktable"
13220 :maxlevel 2 :emphasize nil)))
13221 (org-update-dblock))
13223 (defun org-clock-update-time-maybe ()
13224 "If this is a CLOCK line, update it and return t.
13225 Otherwise, return nil."
13226 (interactive)
13227 (save-excursion
13228 (beginning-of-line 1)
13229 (skip-chars-forward " \t")
13230 (when (looking-at org-clock-string)
13231 (let ((re (concat "[ \t]*" org-clock-string
13232 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
13233 "\\([ \t]*=>.*\\)?"))
13234 ts te h m s)
13235 (if (not (looking-at re))
13237 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
13238 (end-of-line 1)
13239 (setq ts (match-string 1)
13240 te (match-string 2))
13241 (setq s (- (time-to-seconds
13242 (apply 'encode-time (org-parse-time-string te)))
13243 (time-to-seconds
13244 (apply 'encode-time (org-parse-time-string ts))))
13245 h (floor (/ s 3600))
13246 s (- s (* 3600 h))
13247 m (floor (/ s 60))
13248 s (- s (* 60 s)))
13249 (insert " => " (format "%2d:%02d" h m))
13250 t)))))
13252 (defun org-clock-special-range (key &optional time as-strings)
13253 "Return two times bordering a special time range.
13254 Key is a symbol specifying the range and can be one of `today', `yesterday',
13255 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
13256 A week starts Monday 0:00 and ends Sunday 24:00.
13257 The range is determined relative to TIME. TIME defaults to the current time.
13258 The return value is a cons cell with two internal times like the ones
13259 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
13260 the returned times will be formatted strings."
13261 (let* ((tm (decode-time (or time (current-time))))
13262 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
13263 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
13264 (dow (nth 6 tm))
13265 s1 m1 h1 d1 month1 y1 diff ts te fm)
13266 (cond
13267 ((eq key 'today)
13268 (setq h 0 m 0 h1 24 m1 0))
13269 ((eq key 'yesterday)
13270 (setq d (1- d) h 0 m 0 h1 24 m1 0))
13271 ((eq key 'thisweek)
13272 (setq diff (if (= dow 0) 6 (1- dow))
13273 m 0 h 0 d (- d diff) d1 (+ 7 d)))
13274 ((eq key 'lastweek)
13275 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
13276 m 0 h 0 d (- d diff) d1 (+ 7 d)))
13277 ((eq key 'thismonth)
13278 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
13279 ((eq key 'lastmonth)
13280 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
13281 ((eq key 'thisyear)
13282 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
13283 ((eq key 'lastyear)
13284 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
13285 (t (error "No such time block %s" key)))
13286 (setq ts (encode-time s m h d month y)
13287 te (encode-time (or s1 s) (or m1 m) (or h1 h)
13288 (or d1 d) (or month1 month) (or y1 y)))
13289 (setq fm (cdr org-time-stamp-formats))
13290 (if as-strings
13291 (cons (format-time-string fm ts) (format-time-string fm te))
13292 (cons ts te))))
13294 (defun org-dblock-write:clocktable (params)
13295 "Write the standard clocktable."
13296 (let ((hlchars '((1 . "*") (2 . ?/)))
13297 (emph nil)
13298 (ins (make-marker))
13299 ipos time h m p level hlc hdl maxlevel
13300 ts te cc block)
13301 (setq maxlevel (or (plist-get params :maxlevel) 3)
13302 emph (plist-get params :emphasize)
13303 ts (plist-get params :tstart)
13304 te (plist-get params :tend)
13305 block (plist-get params :block))
13306 (when block
13307 (setq cc (org-clock-special-range block nil t)
13308 ts (car cc) te (cdr cc)))
13309 (if ts (setq ts (time-to-seconds
13310 (apply 'encode-time (org-parse-time-string ts)))))
13311 (if te (setq te (time-to-seconds
13312 (apply 'encode-time (org-parse-time-string te)))))
13313 (move-marker ins (point))
13314 (setq ipos (point))
13315 (insert-before-markers "Clock summary at ["
13316 (substring
13317 (format-time-string (cdr org-time-stamp-formats))
13318 1 -1)
13319 "]."
13320 (if block
13321 (format " Considered range is /%s/." block)
13323 "\n\n|L|Headline|Time|\n")
13324 (org-clock-sum ts te)
13325 (setq h (/ org-clock-file-total-minutes 60)
13326 m (- org-clock-file-total-minutes (* 60 h)))
13327 (insert-before-markers "|-\n|0|" "*Total file time*| "
13328 (format "*%d:%02d*" h m)
13329 "|\n")
13330 (goto-char (point-min))
13331 (while (setq p (next-single-property-change (point) :org-clock-minutes))
13332 (goto-char p)
13333 (when (setq time (get-text-property p :org-clock-minutes))
13334 (save-excursion
13335 (beginning-of-line 1)
13336 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
13337 (setq level (- (match-end 1) (match-beginning 1)))
13338 (<= level maxlevel))
13339 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
13340 hdl (match-string 2)
13341 h (/ time 60)
13342 m (- time (* 60 h)))
13343 (goto-char ins)
13344 (if (= level 1) (insert-before-markers "|-\n"))
13345 (insert-before-markers
13346 "| " (int-to-string level) "|" hlc hdl hlc " |"
13347 (make-string (1- level) ?|)
13349 (format "%d:%02d" h m)
13351 " |\n")))))
13352 (goto-char ins)
13353 (backward-delete-char 1)
13354 (goto-char ipos)
13355 (skip-chars-forward "^|")
13356 (org-table-align)))
13358 ;; FIXME: I don't think anybody uses this, ask David
13359 (defun org-collect-clock-time-entries ()
13360 "Return an internal list with clocking information.
13361 This list has one entry for each CLOCK interval.
13362 FIXME: describe the elements."
13363 (interactive)
13364 (let ((re (concat "^[ \t]*" org-clock-string
13365 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
13366 rtn beg end next cont level title total closedp leafp
13367 clockpos titlepos h m donep)
13368 (save-excursion
13369 (org-clock-sum)
13370 (goto-char (point-min))
13371 (while (re-search-forward re nil t)
13372 (setq clockpos (match-beginning 0)
13373 beg (match-string 1) end (match-string 2)
13374 cont (match-end 0))
13375 (setq beg (apply 'encode-time (org-parse-time-string beg))
13376 end (apply 'encode-time (org-parse-time-string end)))
13377 (org-back-to-heading t)
13378 (setq donep (org-entry-is-done-p))
13379 (setq titlepos (point)
13380 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
13381 h (/ total 60) m (- total (* 60 h))
13382 total (cons h m))
13383 (looking-at "\\(\\*+\\) +\\(.*\\)")
13384 (setq level (- (match-end 1) (match-beginning 1))
13385 title (org-match-string-no-properties 2))
13386 (save-excursion (outline-next-heading) (setq next (point)))
13387 (setq closedp (re-search-forward org-closed-time-regexp next t))
13388 (goto-char next)
13389 (setq leafp (and (looking-at "^\\*+ ")
13390 (<= (- (match-end 0) (point)) level)))
13391 (push (list beg end clockpos closedp donep
13392 total title titlepos level leafp)
13393 rtn)
13394 (goto-char cont)))
13395 (nreverse rtn)))
13397 ;;;; Agenda, and Diary Integration
13399 ;;; Define the Org-agenda-mode
13401 (defvar org-agenda-mode-map (make-sparse-keymap)
13402 "Keymap for `org-agenda-mode'.")
13404 (defvar org-agenda-menu) ; defined later in this file.
13405 (defvar org-agenda-follow-mode nil)
13406 (defvar org-agenda-show-log nil)
13407 (defvar org-agenda-redo-command nil)
13408 (defvar org-agenda-mode-hook nil)
13409 (defvar org-agenda-type nil)
13410 (defvar org-agenda-force-single-file nil)
13412 (defun org-agenda-mode ()
13413 "Mode for time-sorted view on action items in Org-mode files.
13415 The following commands are available:
13417 \\{org-agenda-mode-map}"
13418 (interactive)
13419 (kill-all-local-variables)
13420 (setq org-agenda-undo-list nil
13421 org-agenda-pending-undo-list nil)
13422 (setq major-mode 'org-agenda-mode)
13423 ;; Keep global-font-lock-mode from turning on font-lock-mode
13424 (org-set-local 'font-lock-global-modes (list 'not major-mode))
13425 (setq mode-name "Org-Agenda")
13426 (use-local-map org-agenda-mode-map)
13427 (easy-menu-add org-agenda-menu)
13428 (if org-startup-truncated (setq truncate-lines t))
13429 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
13430 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
13431 ;; Make sure properties are removed when copying text
13432 (when (boundp 'buffer-substring-filters)
13433 (org-set-local 'buffer-substring-filters
13434 (cons (lambda (x)
13435 (set-text-properties 0 (length x) nil x) x)
13436 buffer-substring-filters)))
13437 (unless org-agenda-keep-modes
13438 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
13439 org-agenda-show-log nil))
13440 (easy-menu-change
13441 '("Agenda") "Agenda Files"
13442 (append
13443 (list
13444 (vector
13445 (if (get 'org-agenda-files 'org-restrict)
13446 "Restricted to single file"
13447 "Edit File List")
13448 '(org-edit-agenda-file-list)
13449 (not (get 'org-agenda-files 'org-restrict)))
13450 "--")
13451 (mapcar 'org-file-menu-entry (org-agenda-files))))
13452 (org-agenda-set-mode-name)
13453 (apply
13454 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
13455 (list 'org-agenda-mode-hook)))
13457 (substitute-key-definition 'undo 'org-agenda-undo
13458 org-agenda-mode-map global-map)
13459 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
13460 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
13461 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
13462 (define-key org-agenda-mode-map "\C-k" 'org-agenda-kill)
13463 (define-key org-agenda-mode-map "\C-c$" 'org-agenda-archive)
13464 (define-key org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
13465 (define-key org-agenda-mode-map "$" 'org-agenda-archive)
13466 (define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
13467 (define-key org-agenda-mode-map " " 'org-agenda-show)
13468 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
13469 (define-key org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
13470 (define-key org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
13471 (define-key org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
13472 (define-key org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
13473 (define-key org-agenda-mode-map "o" 'delete-other-windows)
13474 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
13475 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
13476 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
13477 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
13478 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
13479 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
13480 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
13481 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
13482 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
13483 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
13484 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
13486 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
13487 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
13488 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
13489 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
13490 (while l (define-key org-agenda-mode-map
13491 (int-to-string (pop l)) 'digit-argument)))
13493 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
13494 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
13495 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
13496 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
13497 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
13498 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
13499 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
13500 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
13501 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
13502 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
13503 (define-key org-agenda-mode-map "n" 'next-line)
13504 (define-key org-agenda-mode-map "p" 'previous-line)
13505 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
13506 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
13507 (define-key org-agenda-mode-map "," 'org-agenda-priority)
13508 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
13509 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
13510 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
13511 (eval-after-load "calendar"
13512 '(define-key calendar-mode-map org-calendar-to-agenda-key
13513 'org-calendar-goto-agenda))
13514 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
13515 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
13516 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
13517 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
13518 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
13519 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
13520 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
13521 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
13522 (define-key org-agenda-mode-map "O" 'org-agenda-clock-out)
13523 (define-key org-agenda-mode-map "X" 'org-agenda-clock-cancel)
13524 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
13525 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
13526 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
13527 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
13528 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
13529 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
13530 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
13531 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
13532 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
13533 "Local keymap for agenda entries from Org-mode.")
13535 (define-key org-agenda-keymap
13536 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
13537 (define-key org-agenda-keymap
13538 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
13539 (when org-agenda-mouse-1-follows-link
13540 (define-key org-agenda-keymap [follow-link] 'mouse-face))
13541 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
13542 '("Agenda"
13543 ("Agenda Files")
13544 "--"
13545 ["Show" org-agenda-show t]
13546 ["Go To (other window)" org-agenda-goto t]
13547 ["Go To (this window)" org-agenda-switch-to t]
13548 ["Follow Mode" org-agenda-follow-mode
13549 :style toggle :selected org-agenda-follow-mode :active t]
13550 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
13551 "--"
13552 ["Cycle TODO" org-agenda-todo t]
13553 ["Archive subtree" org-agenda-archive t]
13554 ["Delete subtree" org-agenda-kill t]
13555 "--"
13556 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
13557 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
13558 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
13559 "--"
13560 ("Tags"
13561 ["Show all Tags" org-agenda-show-tags t]
13562 ["Set Tags" org-agenda-set-tags t])
13563 ("Date/Schedule"
13564 ["Schedule" org-agenda-schedule t]
13565 ["Set Deadline" org-agenda-deadline t]
13566 "--"
13567 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
13568 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
13569 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
13570 ("Priority"
13571 ["Set Priority" org-agenda-priority t]
13572 ["Increase Priority" org-agenda-priority-up t]
13573 ["Decrease Priority" org-agenda-priority-down t]
13574 ["Show Priority" org-agenda-show-priority t])
13575 ("Calendar/Diary"
13576 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
13577 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
13578 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
13579 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
13580 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
13581 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
13582 "--"
13583 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
13584 "--"
13585 ("View"
13586 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
13587 :style radio :selected (equal org-agenda-ndays 1)]
13588 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
13589 :style radio :selected (equal org-agenda-ndays 7)]
13590 "--"
13591 ["Show Logbook entries" org-agenda-log-mode
13592 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
13593 ["Include Diary" org-agenda-toggle-diary
13594 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
13595 ["Use Time Grid" org-agenda-toggle-time-grid
13596 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
13597 ["Rebuild buffer" org-agenda-redo t]
13598 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
13599 "--"
13600 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
13601 "--"
13602 ["Quit" org-agenda-quit t]
13603 ["Exit and Release Buffers" org-agenda-exit t]
13606 ;;; Agenda undo
13608 (defvar org-agenda-allow-remote-undo t
13609 "Non-nil means, allow remote undo from the agenda buffer.")
13610 (defvar org-agenda-undo-list nil
13611 "List of undoable operations in the agenda since last refresh.")
13612 (defvar org-agenda-undo-has-started-in nil
13613 "Buffers that have already seen `undo-start' in the current undo sequence.")
13614 (defvar org-agenda-pending-undo-list nil
13615 "In a series of undo commands, this is the list of remaning undo items.")
13617 (defmacro org-if-unprotected (&rest body)
13618 "Execute BODY if ther is no `org-protected' text property at point."
13619 (declare (debug t))
13620 `(unless (get-text-property (point) 'org-protected)
13621 ,@body))
13623 (defmacro org-with-remote-undo (_buffer &rest _body)
13624 "Execute BODY while recording undo information in two buffers."
13625 (declare (indent 1) (debug t))
13626 `(let ((_cline (org-current-line))
13627 (_cmd this-command)
13628 (_buf1 (current-buffer))
13629 (_buf2 ,_buffer)
13630 (_undo1 buffer-undo-list)
13631 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
13632 _c1 _c2)
13633 ,@_body
13634 (when org-agenda-allow-remote-undo
13635 (setq _c1 (org-verify-change-for-undo
13636 _undo1 (with-current-buffer _buf1 buffer-undo-list))
13637 _c2 (org-verify-change-for-undo
13638 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
13639 (when (or _c1 _c2)
13640 ;; make sure there are undo boundaries
13641 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
13642 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
13643 ;; remember which buffer to undo
13644 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
13645 org-agenda-undo-list)))))
13647 (defun org-agenda-undo ()
13648 "Undo a remote editing step in the agenda.
13649 This undoes changes both in the agenda buffer and in the remote buffer
13650 that have been changed along."
13651 (interactive)
13652 (or org-agenda-allow-remote-undo
13653 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
13654 (if (not (eq this-command last-command))
13655 (setq org-agenda-undo-has-started-in nil
13656 org-agenda-pending-undo-list org-agenda-undo-list))
13657 (if (not org-agenda-pending-undo-list)
13658 (error "No further undo information"))
13659 (let* ((entry (pop org-agenda-pending-undo-list))
13660 buf line cmd rembuf)
13661 (setq cmd (pop entry) line (pop entry))
13662 (setq rembuf (nth 2 entry))
13663 (org-with-remote-undo rembuf
13664 (while (bufferp (setq buf (pop entry)))
13665 (if (pop entry)
13666 (with-current-buffer buf
13667 (let ((last-undo-buffer buf)
13668 buffer-read-only)
13669 (unless (memq buf org-agenda-undo-has-started-in)
13670 (push buf org-agenda-undo-has-started-in)
13671 (make-local-variable 'pending-undo-list)
13672 (undo-start))
13673 (while (and pending-undo-list
13674 (listp pending-undo-list)
13675 (not (car pending-undo-list)))
13676 (pop pending-undo-list))
13677 (undo-more 1))))))
13678 (goto-line line)
13679 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
13681 (defun org-verify-change-for-undo (l1 l2)
13682 "Verify that a real change occurred between the undo lists L1 and L2."
13683 (while (and l1 (listp l1) (null (car l1))) (pop l1))
13684 (while (and l2 (listp l2) (null (car l2))) (pop l2))
13685 (not (eq l1 l2)))
13687 ;;; Agenda dispatch
13689 (defvar org-agenda-restrict nil)
13690 (defvar org-agenda-restrict-begin (make-marker))
13691 (defvar org-agenda-restrict-end (make-marker))
13692 (defvar org-agenda-last-dispatch-buffer nil)
13694 ;;;###autoload
13695 (defun org-agenda (arg)
13696 "Dispatch agenda commands to collect entries to the agenda buffer.
13697 Prompts for a character to select a command. Any prefix arg will be passed
13698 on to the selected command. The default selections are:
13700 a Call `org-agenda-list' to display the agenda for current day or week.
13701 t Call `org-todo-list' to display the global todo list.
13702 T Call `org-todo-list' to display the global todo list, select only
13703 entries with a specific TODO keyword (the user gets a prompt).
13704 m Call `org-tags-view' to display headlines with tags matching
13705 a condition (the user is prompted for the condition).
13706 M Like `m', but select only TODO entries, no ordinary headlines.
13707 l Create a timeeline for the current buffer.
13709 More commands can be added by configuring the variable
13710 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
13711 searches can be pre-defined in this way.
13713 If the current buffer is in Org-mode and visiting a file, you can also
13714 first press `1' to indicate that the agenda should be temporarily (until the
13715 next use of \\[org-agenda]) restricted to the current file."
13716 (interactive "P")
13717 (catch 'exit
13718 (let* ((buf (current-buffer))
13719 (bfn (buffer-file-name (buffer-base-buffer)))
13720 (restrict-ok (and bfn (org-mode-p)))
13721 (custom org-agenda-custom-commands)
13722 c entry key type match lprops)
13723 ;; Turn off restriction
13724 (put 'org-agenda-files 'org-restrict nil)
13725 (setq org-agenda-restrict nil)
13726 (move-marker org-agenda-restrict-begin nil)
13727 (move-marker org-agenda-restrict-end nil)
13728 ;; Remember where this call originated
13729 (setq org-agenda-last-dispatch-buffer (current-buffer))
13730 (save-window-excursion
13731 (delete-other-windows)
13732 (switch-to-buffer-other-window " *Agenda Commands*")
13733 (erase-buffer)
13734 (insert (eval-when-compile
13735 (let ((header
13736 "Press key for an agenda command:
13737 -------------------------------- C Configure custom agenda commands
13738 a Agenda for current week or day
13739 t List of all TODO entries T Entries with special TODO kwd
13740 m Match a TAGS query M Like m, but only TODO entries
13741 L Timeline for current buffer # List stuck projects (!=configure)
13743 (start 0))
13744 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
13745 (setq start (match-end 0))
13746 (add-text-properties (match-beginning 2) (match-end 2)
13747 '(face bold) header))
13748 header)))
13749 (while (setq entry (pop custom))
13750 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
13751 (insert (format "\n%-4s%-14s: %s"
13752 (org-add-props (copy-sequence key)
13753 '(face bold))
13754 (cond
13755 ((stringp type) type)
13756 ((eq type 'todo) "TODO keyword")
13757 ((eq type 'tags) "Tags query")
13758 ((eq type 'tags-todo) "Tags (TODO)")
13759 ((eq type 'tags-tree) "Tags tree")
13760 ((eq type 'todo-tree) "TODO kwd tree")
13761 ((eq type 'occur-tree) "Occur tree")
13762 ((functionp type) (symbol-name type))
13763 (t "???"))
13764 (if (stringp match)
13765 (org-add-props match nil 'face 'org-warning)
13766 (format "set of %d commands" (length match))))))
13767 (if restrict-ok
13768 (insert "\n"
13769 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
13770 (goto-char (point-min))
13771 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
13772 (message "Press key for agenda command%s"
13773 (if restrict-ok ", or [1] or [0] to restrict" ""))
13774 (setq c (read-char-exclusive))
13775 (message "")
13776 (when (memq c '(?L ?1 ?0))
13777 (if restrict-ok
13778 (put 'org-agenda-files 'org-restrict (list bfn))
13779 (error "Cannot restrict agenda to current buffer"))
13780 (with-current-buffer " *Agenda Commands*"
13781 (goto-char (point-max))
13782 (delete-region (point-at-bol) (point))
13783 (goto-char (point-min)))
13784 (when (eq c ?0)
13785 (setq org-agenda-restrict t)
13786 (with-current-buffer buf
13787 (if (org-region-active-p)
13788 (progn
13789 (move-marker org-agenda-restrict-begin (region-beginning))
13790 (move-marker org-agenda-restrict-end (region-end)))
13791 (save-excursion
13792 (org-back-to-heading t)
13793 (move-marker org-agenda-restrict-begin (point))
13794 (move-marker org-agenda-restrict-end
13795 (progn (org-end-of-subtree t)))))))
13796 (unless (eq c ?L)
13797 (message "Press key for agenda command%s"
13798 (if restrict-ok " (restricted to current file)" ""))
13799 (setq c (read-char-exclusive)))
13800 (message "")))
13801 (require 'calendar) ; FIXME: can we avoid this for some commands?
13802 ;; For example the todo list should not need it (but does...)
13803 (cond
13804 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
13805 (if (symbolp (nth 1 entry))
13806 (progn
13807 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
13808 lprops (nth 3 entry))
13809 (cond
13810 ((eq type 'tags)
13811 (org-let lprops '(org-tags-view current-prefix-arg match)))
13812 ((eq type 'tags-todo)
13813 (org-let lprops '(org-tags-view '(4) match)))
13814 ((eq type 'todo)
13815 (org-let lprops '(org-todo-list match)))
13816 ((eq type 'tags-tree)
13817 (org-check-for-org-mode)
13818 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
13819 ((eq type 'todo-tree)
13820 (org-check-for-org-mode)
13821 (org-let lprops
13822 '(org-occur (concat "^" outline-regexp "[ \t]*"
13823 (regexp-quote match) "\\>"))))
13824 ((eq type 'occur-tree)
13825 (org-check-for-org-mode)
13826 (org-let lprops '(org-occur match)))
13827 ((fboundp type)
13828 (org-let lprops '(funcall type match)))
13829 (t (error "Invalid custom agenda command type %s" type))))
13830 (org-run-agenda-series (cddr entry))))
13831 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
13832 ((equal c ?a) (call-interactively 'org-agenda-list))
13833 ((equal c ?t) (call-interactively 'org-todo-list))
13834 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
13835 ((equal c ?m) (call-interactively 'org-tags-view))
13836 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
13837 ((equal c ?L)
13838 (unless restrict-ok
13839 (error "This is not an Org-mode file"))
13840 (org-call-with-arg 'org-timeline arg))
13841 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
13842 ((equal c ?!) (customize-variable 'org-stuck-projects))
13843 (t (error "Invalid key"))))))
13845 (defun org-run-agenda-series (series)
13846 (org-prepare-agenda)
13847 (let* ((org-agenda-multi t)
13848 (redo (list 'org-run-agenda-series (list 'quote series)))
13849 (cmds (car series))
13850 (gprops (nth 1 series))
13851 match ;; The byte compiler incorrectly complains about this. Keep it!
13852 cmd type lprops)
13853 (while (setq cmd (pop cmds))
13854 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
13855 (cond
13856 ((eq type 'agenda)
13857 (call-interactively 'org-agenda-list))
13858 ((eq type 'alltodo)
13859 (call-interactively 'org-todo-list))
13860 ((eq type 'stuck)
13861 (call-interactively 'org-agenda-list-stuck-projects))
13862 ((eq type 'tags)
13863 (org-let2 gprops lprops
13864 '(org-tags-view current-prefix-arg match)))
13865 ((eq type 'tags-todo)
13866 (org-let2 gprops lprops
13867 '(org-tags-view '(4) match)))
13868 ((eq type 'todo)
13869 (org-let2 gprops lprops
13870 '(org-todo-list match)))
13871 ((fboundp type)
13872 (org-let2 gprops lprops
13873 '(funcall type match)))
13874 (t (error "Invalid type in command series"))))
13875 (widen)
13876 (setq org-agenda-redo-command redo)
13877 (goto-char (point-min)))
13878 (org-finalize-agenda))
13880 ;;;###autoload
13881 (defmacro org-batch-agenda (cmd-key &rest parameters)
13882 "Run an agenda command in batch mode, send result to STDOUT.
13883 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
13884 Paramters are alternating variable names and values that will be bound
13885 before running the agenda command."
13886 (let (pars)
13887 (while parameters
13888 (push (list (pop parameters) (if parameters (pop parameters))) pars))
13889 (flet ((read-char-exclusive () (string-to-char cmd-key)))
13890 (eval (list 'let (nreverse pars) '(org-agenda nil))))
13891 (set-buffer "*Org Agenda*")
13892 (princ (buffer-string))))
13894 (defmacro org-no-read-only (&rest body)
13895 "Inhibit read-only for BODY."
13896 `(let ((inhibit-read-only t)) ,@body))
13898 (defun org-check-for-org-mode ()
13899 "Make sure current buffer is in org-mode. Error if not."
13900 (or (org-mode-p)
13901 (error "Cannot execute org-mode agenda command on buffer in %s."
13902 major-mode)))
13904 (defun org-fit-agenda-window ()
13905 "Fit the window to the buffer size."
13906 (and (memq org-agenda-window-setup '(reorganize-frame))
13907 (fboundp 'fit-window-to-buffer)
13908 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
13909 (/ (frame-height) 2))))
13911 ;;; Agenda file list
13913 (defun org-agenda-files (&optional unrestricted)
13914 "Get the list of agenda files.
13915 Optional UNRESTRICTED means return the full list even if a restriction
13916 is currently in place."
13917 (cond
13918 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13919 ((stringp org-agenda-files) (org-read-agenda-file-list))
13920 ((listp org-agenda-files) org-agenda-files)
13921 (t (error "Invalid value of `org-agenda-files'"))))
13923 (defun org-edit-agenda-file-list ()
13924 "Edit the list of agenda files.
13925 Depending on setup, this either uses customize to edit the variable
13926 `org-agenda-files', or it visits the file that is holding the list. In the
13927 latter case, the buffer is set up in a way that saving it automatically kills
13928 the buffer and restores the previous window configuration."
13929 (interactive)
13930 (if (stringp org-agenda-files)
13931 (let ((cw (current-window-configuration)))
13932 (find-file org-agenda-files)
13933 (org-set-local 'org-window-configuration cw)
13934 (org-add-hook 'after-save-hook
13935 (lambda ()
13936 (set-window-configuration
13937 (prog1 org-window-configuration
13938 (kill-buffer (current-buffer))))
13939 (org-install-agenda-files-menu)
13940 (message "New agenda file list installed"))
13941 nil 'local)
13942 (message (substitute-command-keys
13943 "Edit list and finish with \\[save-buffer]")))
13944 (customize-variable 'org-agenda-files)))
13946 (defun org-store-new-agenda-file-list (list)
13947 "Set new value for the agenda file list and save it correcly."
13948 (if (stringp org-agenda-files)
13949 (let ((f org-agenda-files) b)
13950 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13951 (with-temp-file f
13952 (insert (mapconcat 'identity list "\n") "\n")))
13953 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13954 (setq org-agenda-files list)
13955 (customize-save-variable 'org-agenda-files org-agenda-files))))
13957 (defun org-read-agenda-file-list ()
13958 "Read the list of agenda files from a file."
13959 (when (stringp org-agenda-files)
13960 (with-temp-buffer
13961 (insert-file-contents org-agenda-files)
13962 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13965 ;;;###autoload
13966 (defun org-cycle-agenda-files ()
13967 "Cycle through the files in `org-agenda-files'.
13968 If the current buffer visits an agenda file, find the next one in the list.
13969 If the current buffer does not, find the first agenda file."
13970 (interactive)
13971 (let* ((fs (org-agenda-files t))
13972 (files (append fs (list (car fs))))
13973 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13974 file)
13975 (unless files (error "No agenda files"))
13976 (catch 'exit
13977 (while (setq file (pop files))
13978 (if (equal (file-truename file) tcf)
13979 (when (car files)
13980 (find-file (car files))
13981 (throw 'exit t))))
13982 (find-file (car fs)))
13983 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13985 (defun org-agenda-file-to-front (&optional to-end)
13986 "Move/add the current file to the top of the agenda file list.
13987 If the file is not present in the list, it is added to the front. If it is
13988 present, it is moved there. With optional argument TO-END, add/move to the
13989 end of the list."
13990 (interactive "P")
13991 (let ((file-alist (mapcar (lambda (x)
13992 (cons (file-truename x) x))
13993 (org-agenda-files t)))
13994 (ctf (file-truename buffer-file-name))
13995 x had)
13996 (setq x (assoc ctf file-alist) had x)
13998 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13999 (if to-end
14000 (setq file-alist (append (delq x file-alist) (list x)))
14001 (setq file-alist (cons x (delq x file-alist))))
14002 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14003 (org-install-agenda-files-menu)
14004 (message "File %s to %s of agenda file list"
14005 (if had "moved" "added") (if to-end "end" "front"))))
14007 (defun org-remove-file (&optional file)
14008 "Remove current file from the list of files in variable `org-agenda-files'.
14009 These are the files which are being checked for agenda entries.
14010 Optional argument FILE means, use this file instead of the current."
14011 (interactive)
14012 (let* ((file (or file buffer-file-name))
14013 (true-file (file-truename file))
14014 (afile (abbreviate-file-name file))
14015 (files (delq nil (mapcar
14016 (lambda (x)
14017 (if (equal true-file
14018 (file-truename x))
14019 nil x))
14020 (org-agenda-files t)))))
14021 (if (not (= (length files) (length (org-agenda-files t))))
14022 (progn
14023 (org-store-new-agenda-file-list files)
14024 (org-install-agenda-files-menu)
14025 (message "Removed file: %s" afile))
14026 (message "File was not in list: %s" afile))))
14028 (defun org-file-menu-entry (file)
14029 (vector file (list 'find-file file) t))
14031 (defun org-check-agenda-file (file)
14032 "Make sure FILE exists. If not, ask user what to do."
14033 (when (not (file-exists-p file))
14034 (message "non-existent file %s. [R]emove from list or [A]bort?"
14035 (abbreviate-file-name file))
14036 (let ((r (downcase (read-char-exclusive))))
14037 (cond
14038 ((equal r ?r)
14039 (org-remove-file file)
14040 (throw 'nextfile t))
14041 (t (error "Abort"))))))
14043 ;;; Agenda prepare and finalize
14045 (defvar org-agenda-multi nil) ; dynammically scoped
14046 (defvar org-agenda-buffer-name "*Org Agenda*")
14047 (defvar org-pre-agenda-window-conf nil)
14048 (defun org-prepare-agenda ()
14049 (if org-agenda-multi
14050 (progn
14051 (setq buffer-read-only nil)
14052 (goto-char (point-max))
14053 (unless (= (point) 1)
14054 (insert "\n" (make-string (window-width) ?=) "\n"))
14055 (narrow-to-region (point) (point-max)))
14056 (org-agenda-maybe-reset-markers 'force)
14057 (org-prepare-agenda-buffers (org-agenda-files))
14058 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
14059 (awin (get-buffer-window abuf)))
14060 (cond
14061 ((equal (current-buffer) abuf) nil)
14062 (awin (select-window awin))
14063 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
14064 ((equal org-agenda-window-setup 'current-window)
14065 (switch-to-buffer abuf))
14066 ((equal org-agenda-window-setup 'other-window)
14067 (switch-to-buffer-other-window abuf))
14068 ((equal org-agenda-window-setup 'other-frame)
14069 (switch-to-buffer-other-frame abuf))
14070 ((equal org-agenda-window-setup 'reorganize-frame)
14071 (delete-other-windows)
14072 (switch-to-buffer-other-window abuf))))
14073 (setq buffer-read-only nil)
14074 (erase-buffer)
14075 (org-agenda-mode))
14076 (setq buffer-read-only nil))
14078 (defun org-finalize-agenda ()
14079 "Finishing touch for the agenda buffer, called just before displaying it."
14080 (unless org-agenda-multi
14081 (org-agenda-align-tags)
14082 (save-excursion
14083 (let ((buffer-read-only))
14084 (goto-char (point-min))
14085 (while (org-activate-bracket-links (point-max))
14086 (add-text-properties (match-beginning 0) (match-end 0)
14087 '(face org-link))))
14088 (run-hooks 'org-finalize-agenda-hook))))
14090 (defun org-prepare-agenda-buffers (files)
14091 "Create buffers for all agenda files, protect archived trees and comments."
14092 (interactive)
14093 (let ((pa '(:org-archived t))
14094 (pc '(:org-comment t))
14095 (pall '(:org-archived t :org-comment t))
14096 (rea (concat ":" org-archive-tag ":"))
14097 bmp file re)
14098 (save-excursion
14099 (save-restriction
14100 (while (setq file (pop files))
14101 (org-check-agenda-file file)
14102 (set-buffer (org-get-agenda-file-buffer file))
14103 (widen)
14104 (setq bmp (buffer-modified-p))
14105 (save-excursion
14106 (remove-text-properties (point-min) (point-max) pall)
14107 (when org-agenda-skip-archived-trees
14108 (goto-char (point-min))
14109 (while (re-search-forward rea nil t)
14110 (if (org-on-heading-p t)
14111 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14112 (goto-char (point-min))
14113 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14114 (while (re-search-forward re nil t)
14115 (add-text-properties
14116 (match-beginning 0) (org-end-of-subtree t) pc)))
14117 (set-buffer-modified-p bmp))))))
14119 (defvar org-agenda-skip-function nil
14120 "Function to be called at each match during agenda construction.
14121 If this function return nil, the current match should not be skipped.
14122 Otherwise, the function must return a position from where the search
14123 should be continued.
14124 Never set this variable using `setq' or so, because then it will apply
14125 to all future agenda commands. Instead, bind it with `let' to scope
14126 it dynamically into the agenda-constructing command.")
14128 (defun org-agenda-skip ()
14129 "Throw to `:skip' in places that should be skipped.
14130 Also moves point to the end of the skipped region, so that search can
14131 continue from there."
14132 (let ((p (point-at-bol)) to)
14133 (and org-agenda-skip-archived-trees
14134 (get-text-property p :org-archived)
14135 (org-end-of-subtree t)
14136 (throw :skip t))
14137 (and (get-text-property p :org-comment)
14138 (org-end-of-subtree t)
14139 (throw :skip t))
14140 (if (equal (char-after p) ?#) (throw :skip t))
14141 (when (and (functionp org-agenda-skip-function)
14142 (setq to (save-excursion
14143 (save-match-data
14144 (funcall org-agenda-skip-function)))))
14145 (goto-char to)
14146 (throw :skip t))))
14148 (defvar org-agenda-markers nil
14149 "List of all currently active markers created by `org-agenda'.")
14150 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
14151 "Creation time of the last agenda marker.")
14153 (defun org-agenda-new-marker (&optional pos)
14154 "Return a new agenda marker.
14155 Org-mode keeps a list of these markers and resets them when they are
14156 no longer in use."
14157 (let ((m (copy-marker (or pos (point)))))
14158 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
14159 (push m org-agenda-markers)
14162 (defun org-agenda-maybe-reset-markers (&optional force)
14163 "Reset markers created by `org-agenda'. But only if they are old enough."
14164 (if (or (and force (not org-agenda-multi))
14165 (> (- (time-to-seconds (current-time))
14166 org-agenda-last-marker-time)
14168 (while org-agenda-markers
14169 (move-marker (pop org-agenda-markers) nil))))
14171 (defvar org-agenda-new-buffers nil
14172 "Buffers created to visit agenda files.")
14174 (defun org-get-agenda-file-buffer (file)
14175 "Get a buffer visiting FILE. If the buffer needs to be created, add
14176 it to the list of buffers which might be released later."
14177 (let ((buf (org-find-base-buffer-visiting file)))
14178 (if buf
14179 buf ; just return it
14180 ;; Make a new buffer and remember it
14181 (setq buf (find-file-noselect file))
14182 (if buf (push buf org-agenda-new-buffers))
14183 buf)))
14185 (defun org-release-buffers (blist)
14186 "Release all buffers in list, asking the user for confirmation when needed.
14187 When a buffer is unmodified, it is just killed. When modified, it is saved
14188 \(if the user agrees) and then killed."
14189 (let (buf file)
14190 (while (setq buf (pop blist))
14191 (setq file (buffer-file-name buf))
14192 (when (and (buffer-modified-p buf)
14193 file
14194 (y-or-n-p (format "Save file %s? " file)))
14195 (with-current-buffer buf (save-buffer)))
14196 (kill-buffer buf))))
14198 (defvar org-category-table nil)
14199 (defun org-get-category-table ()
14200 "Get the table of categories and positions in current buffer."
14201 (let (tbl)
14202 (save-excursion
14203 (save-restriction
14204 (widen)
14205 (goto-char (point-min))
14206 (while (re-search-forward "^#\\+CATEGORY:[ \t]*\\(.*\\)"
14207 nil t)
14208 (push (cons (match-beginning 1)
14209 (org-trim (match-string 1))) tbl))))
14210 tbl))
14212 (defun org-get-category (&optional pos)
14213 "Get the category applying to position POS."
14214 (if (not org-category-table)
14215 (cond
14216 ((null org-category)
14217 (setq org-category
14218 (if buffer-file-name
14219 (file-name-sans-extension
14220 (file-name-nondirectory buffer-file-name))
14221 "???")))
14222 ((symbolp org-category) (symbol-name org-category))
14223 (t org-category))
14224 (let ((tbl org-category-table)
14225 (pos (or pos (point))))
14226 (while (and tbl (> (caar tbl) pos))
14227 (pop tbl))
14228 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
14229 org-category-table))))))
14230 ;;; Agenda timeline
14232 (defun org-timeline (&optional include-all)
14233 "Show a time-sorted view of the entries in the current org file.
14234 Only entries with a time stamp of today or later will be listed. With
14235 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
14236 under the current date.
14237 If the buffer contains an active region, only check the region for
14238 dates."
14239 (interactive "P")
14240 (require 'calendar)
14241 (org-compile-prefix-format 'timeline)
14242 (org-set-sorting-strategy 'timeline)
14243 (let* ((dopast t)
14244 (dotodo include-all)
14245 (doclosed org-agenda-show-log)
14246 (entry buffer-file-name)
14247 (date (calendar-current-date))
14248 (beg (if (org-region-active-p) (region-beginning) (point-min)))
14249 (end (if (org-region-active-p) (region-end) (point-max)))
14250 (day-numbers (org-get-all-dates beg end 'no-ranges
14251 t doclosed ; always include today
14252 org-timeline-show-empty-dates))
14253 (today (time-to-days (current-time)))
14254 (past t)
14255 args
14256 s e rtn d emptyp)
14257 (setq org-agenda-redo-command
14258 (list 'progn
14259 (list 'switch-to-buffer-other-window (current-buffer))
14260 (list 'org-timeline (list 'quote include-all))))
14261 (if (not dopast)
14262 ;; Remove past dates from the list of dates.
14263 (setq day-numbers (delq nil (mapcar (lambda(x)
14264 (if (>= x today) x nil))
14265 day-numbers))))
14266 (org-prepare-agenda)
14267 (if doclosed (push :closed args))
14268 (push :timestamp args)
14269 (if dotodo (push :todo args))
14270 (while (setq d (pop day-numbers))
14271 (if (and (listp d) (eq (car d) :omitted))
14272 (progn
14273 (setq s (point))
14274 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
14275 (put-text-property s (1- (point)) 'face 'org-level-3))
14276 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
14277 (if (and (>= d today)
14278 dopast
14279 past)
14280 (progn
14281 (setq past nil)
14282 (insert (make-string 79 ?-) "\n")))
14283 (setq date (calendar-gregorian-from-absolute d))
14284 (setq s (point))
14285 (setq rtn (and (not emptyp)
14286 (apply 'org-agenda-get-day-entries
14287 entry date args)))
14288 (if (or rtn (equal d today) org-timeline-show-empty-dates)
14289 (progn
14290 (insert (calendar-day-name date) " "
14291 (number-to-string (extract-calendar-day date)) " "
14292 (calendar-month-name (extract-calendar-month date)) " "
14293 (number-to-string (extract-calendar-year date)) "\n")
14294 ; FIXME: this gives a timezone problem
14295 ; (insert (format-time-string org-agenda-date-format
14296 ; (calendar-time-from-absolute d 0))
14297 ; "\n")
14298 (put-text-property s (1- (point)) 'face 'org-level-3)
14299 (put-text-property s (1- (point)) 'org-date-line t)
14300 (if (equal d today)
14301 (put-text-property s (1- (point)) 'org-today t))
14302 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
14303 (put-text-property s (1- (point)) 'day d)))))
14304 (goto-char (point-min))
14305 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
14306 (point-min)))
14307 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
14308 (org-finalize-agenda)
14309 (setq buffer-read-only t)))
14311 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
14312 "Return a list of all relevant day numbers from BEG to END buffer positions.
14313 If NO-RANGES is non-nil, include only the start and end dates of a range,
14314 not every single day in the range. If FORCE-TODAY is non-nil, make
14315 sure that TODAY is included in the list. If INACTIVE is non-nil, also
14316 inactive time stamps (those in square brackets) are included.
14317 When EMPTY is non-nil, also include days without any entries."
14318 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
14319 dates dates1 date day day1 day2 ts1 ts2)
14320 (if force-today
14321 (setq dates (list (time-to-days (current-time)))))
14322 (save-excursion
14323 (goto-char beg)
14324 (while (re-search-forward re end t)
14325 (setq day (time-to-days (org-time-string-to-time
14326 (substring (match-string 1) 0 10))))
14327 (or (memq day dates) (push day dates)))
14328 (unless no-ranges
14329 (goto-char beg)
14330 (while (re-search-forward org-tr-regexp end t)
14331 (setq ts1 (substring (match-string 1) 0 10)
14332 ts2 (substring (match-string 2) 0 10)
14333 day1 (time-to-days (org-time-string-to-time ts1))
14334 day2 (time-to-days (org-time-string-to-time ts2)))
14335 (while (< (setq day1 (1+ day1)) day2)
14336 (or (memq day1 dates) (push day1 dates)))))
14337 (setq dates (sort dates '<))
14338 (when empty
14339 (while (setq day (pop dates))
14340 (setq day2 (car dates))
14341 (push day dates1)
14342 (when (and day2 empty)
14343 (if (or (eq empty t)
14344 (and (numberp empty) (<= (- day2 day) empty)))
14345 (while (< (setq day (1+ day)) day2)
14346 (push (list day) dates1))
14347 (push (cons :omitted (- day2 day)) dates1))))
14348 (setq dates (nreverse dates1)))
14349 dates)))
14351 ;;; Agenda Daily/Weekly
14353 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
14354 (defvar org-agenda-last-arguments nil
14355 "The arguments of the previous call to org-agenda")
14356 (defvar org-starting-day nil) ; local variable in the agenda buffer
14357 (defvar org-include-all-loc nil) ; local variable
14360 ;;;###autoload
14361 (defun org-agenda-list (&optional include-all start-day ndays)
14362 "Produce a weekly view from all files in variable `org-agenda-files'.
14363 The view will be for the current week, but from the overview buffer you
14364 will be able to go to other weeks.
14365 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
14366 also be shown, under the current date.
14367 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
14368 on the days are also shown. See the variable `org-log-done' for how
14369 to turn on logging.
14370 START-DAY defaults to TODAY, or to the most recent match for the weekday
14371 given in `org-agenda-start-on-weekday'.
14372 NDAYS defaults to `org-agenda-ndays'."
14373 (interactive "P")
14374 (if org-agenda-overriding-arguments
14375 (setq include-all (car org-agenda-overriding-arguments)
14376 start-day (nth 1 org-agenda-overriding-arguments)
14377 ndays (nth 2 org-agenda-overriding-arguments)))
14378 (setq org-agenda-last-arguments (list include-all start-day ndays))
14379 (org-compile-prefix-format 'agenda)
14380 (org-set-sorting-strategy 'agenda)
14381 (require 'calendar)
14382 (let* ((org-agenda-start-on-weekday
14383 (if (or (equal ndays 1)
14384 (and (null ndays) (equal 1 org-agenda-ndays)))
14385 nil org-agenda-start-on-weekday))
14386 (thefiles (org-agenda-files))
14387 (files thefiles)
14388 (today (time-to-days (current-time)))
14389 (sd (or start-day today))
14390 (start (if (or (null org-agenda-start-on-weekday)
14391 (< org-agenda-ndays 7))
14393 (let* ((nt (calendar-day-of-week
14394 (calendar-gregorian-from-absolute sd)))
14395 (n1 org-agenda-start-on-weekday)
14396 (d (- nt n1)))
14397 (- sd (+ (if (< d 0) 7 0) d)))))
14398 (day-numbers (list start))
14399 (inhibit-redisplay (not debug-on-error))
14400 s e rtn rtnall file date d start-pos end-pos todayp nd)
14401 (setq org-agenda-redo-command
14402 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
14403 ;; Make the list of days
14404 (setq ndays (or ndays org-agenda-ndays)
14405 nd ndays)
14406 (while (> ndays 1)
14407 (push (1+ (car day-numbers)) day-numbers)
14408 (setq ndays (1- ndays)))
14409 (setq day-numbers (nreverse day-numbers))
14410 (org-prepare-agenda)
14411 (org-set-local 'org-starting-day (car day-numbers))
14412 (org-set-local 'org-include-all-loc include-all)
14413 (when (and (or include-all org-agenda-include-all-todo)
14414 (member today day-numbers))
14415 (setq files thefiles
14416 rtnall nil)
14417 (while (setq file (pop files))
14418 (catch 'nextfile
14419 (org-check-agenda-file file)
14420 (setq date (calendar-gregorian-from-absolute today)
14421 rtn (org-agenda-get-day-entries
14422 file date :todo))
14423 (setq rtnall (append rtnall rtn))))
14424 (when rtnall
14425 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
14426 (add-text-properties (point-min) (1- (point))
14427 (list 'face 'org-level-3))
14428 (insert (org-finalize-agenda-entries rtnall) "\n")))
14429 (setq s (point))
14430 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
14431 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
14432 (while (setq d (pop day-numbers))
14433 (setq date (calendar-gregorian-from-absolute d)
14434 s (point))
14435 (if (or (setq todayp (= d today))
14436 (and (not start-pos) (= d sd)))
14437 (setq start-pos (point))
14438 (if (and start-pos (not end-pos))
14439 (setq end-pos (point))))
14440 (setq files thefiles
14441 rtnall nil)
14442 (while (setq file (pop files))
14443 (catch 'nextfile
14444 (org-check-agenda-file file)
14445 (if org-agenda-show-log
14446 (setq rtn (org-agenda-get-day-entries
14447 file date
14448 :deadline :scheduled :timestamp :closed))
14449 (setq rtn (org-agenda-get-day-entries
14450 file date
14451 :deadline :scheduled :timestamp)))
14452 (setq rtnall (append rtnall rtn))))
14453 (if org-agenda-include-diary
14454 (progn
14455 (require 'diary-lib)
14456 (setq rtn (org-get-entries-from-diary date))
14457 (setq rtnall (append rtnall rtn))))
14458 (if (or rtnall org-agenda-show-all-dates)
14459 (progn
14460 (insert (format "%-9s %2d %s %4d\n"
14461 (calendar-day-name date)
14462 (extract-calendar-day date)
14463 (calendar-month-name (extract-calendar-month date))
14464 (extract-calendar-year date)))
14465 ; FIXME: this gives a timezone problem
14466 ; (insert (format-time-string org-agenda-date-format
14467 ; (calendar-time-from-absolute d 0)) "\n")
14468 (put-text-property s (1- (point)) 'face 'org-level-3)
14469 (put-text-property s (1- (point)) 'org-date-line t)
14470 (if todayp (put-text-property s (1- (point)) 'org-today t))
14471 (if rtnall (insert
14472 (org-finalize-agenda-entries
14473 (org-agenda-add-time-grid-maybe
14474 rtnall nd todayp))
14475 "\n"))
14476 (put-text-property s (1- (point)) 'day d))))
14477 (goto-char (point-min))
14478 (org-fit-agenda-window)
14479 (unless (and (pos-visible-in-window-p (point-min))
14480 (pos-visible-in-window-p (point-max)))
14481 (goto-char (1- (point-max)))
14482 (recenter -1)
14483 (if (not (pos-visible-in-window-p (or start-pos 1)))
14484 (progn
14485 (goto-char (or start-pos 1))
14486 (recenter 1))))
14487 (goto-char (or start-pos 1))
14488 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
14489 (org-finalize-agenda)
14490 (setq buffer-read-only t)
14491 (message "")))
14493 ;;; Agenda TODO list
14495 (defvar org-select-this-todo-keyword nil)
14496 (defvar org-last-arg nil)
14498 ;;;###autoload
14499 (defun org-todo-list (arg)
14500 "Show all TODO entries from all agenda file in a single list.
14501 The prefix arg can be used to select a specific TODO keyword and limit
14502 the list to these. When using \\[universal-argument], you will be prompted
14503 for a keyword. A numeric prefix directly selects the Nth keyword in
14504 `org-todo-keywords-1'."
14505 (interactive "P")
14506 (require 'calendar)
14507 (org-compile-prefix-format 'todo)
14508 (org-set-sorting-strategy 'todo)
14509 (let* ((today (time-to-days (current-time)))
14510 (date (calendar-gregorian-from-absolute today))
14511 (kwds org-todo-keywords-1)
14512 (completion-ignore-case t)
14513 (org-select-this-todo-keyword
14514 (if (stringp arg) arg
14515 (and arg (integerp arg) (> arg 0)
14516 (nth (1- arg) org-todo-keywords-1))))
14517 rtn rtnall files file pos)
14518 (when (equal arg '(4))
14519 (setq org-select-this-todo-keyword
14520 (completing-read "Keyword (or KWD1|K2D2|...): "
14521 (mapcar 'list org-todo-keywords-1)
14522 nil nil)))
14523 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
14524 (org-prepare-agenda)
14525 (org-set-local 'org-last-arg arg)
14526 (org-set-local 'org-todo-keywords-1 kwds)
14527 (setq org-agenda-redo-command
14528 '(org-todo-list (or current-prefix-arg org-last-arg)))
14529 (setq files (org-agenda-files)
14530 rtnall nil)
14531 (while (setq file (pop files))
14532 (catch 'nextfile
14533 (org-check-agenda-file file)
14534 (setq rtn (org-agenda-get-day-entries file date :todo))
14535 (setq rtnall (append rtnall rtn))))
14536 (if org-agenda-overriding-header
14537 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
14538 nil 'face 'org-level-3) "\n")
14539 (insert "Global list of TODO items of type: ")
14540 (add-text-properties (point-min) (1- (point))
14541 (list 'face 'org-level-3))
14542 (setq pos (point))
14543 (insert (or org-select-this-todo-keyword "ALL") "\n")
14544 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14545 (setq pos (point))
14546 (unless org-agenda-multi
14547 (insert
14548 "Available with `N r': (0)ALL "
14549 (let ((n 0))
14550 (mapconcat (lambda (x)
14551 (format "(%d)%s" (setq n (1+ n)) x))
14552 org-todo-keywords-1 " "))
14553 "\n"))
14554 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14555 (when rtnall
14556 (insert (org-finalize-agenda-entries rtnall) "\n"))
14557 (goto-char (point-min))
14558 (org-fit-agenda-window)
14559 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
14560 (org-finalize-agenda)
14561 (setq buffer-read-only t)))
14563 ;;; Agenda tags match
14565 ;;;###autoload
14566 (defun org-tags-view (&optional todo-only match)
14567 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
14568 The prefix arg TODO-ONLY limits the search to TODO entries."
14569 (interactive "P")
14570 (org-compile-prefix-format 'tags)
14571 (org-set-sorting-strategy 'tags)
14572 (let* ((org-tags-match-list-sublevels
14573 (if todo-only t org-tags-match-list-sublevels))
14574 (completion-ignore-case t)
14575 rtn rtnall files file pos matcher
14576 buffer)
14577 (setq matcher (org-make-tags-matcher match)
14578 match (car matcher) matcher (cdr matcher))
14579 (org-prepare-agenda)
14580 (setq org-agenda-redo-command
14581 (list 'org-tags-view (list 'quote todo-only)
14582 (list 'if 'current-prefix-arg nil match)))
14583 (setq files (org-agenda-files)
14584 rtnall nil)
14585 (while (setq file (pop files))
14586 (catch 'nextfile
14587 (org-check-agenda-file file)
14588 (setq buffer (if (file-exists-p file)
14589 (org-get-agenda-file-buffer file)
14590 (error "No such file %s" file)))
14591 (if (not buffer)
14592 ;; If file does not exist, merror message to agenda
14593 (setq rtn (list
14594 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14595 rtnall (append rtnall rtn))
14596 (with-current-buffer buffer
14597 (unless (org-mode-p)
14598 (error "Agenda file %s is not in `org-mode'" file))
14599 (setq org-category-table (org-get-category-table))
14600 (save-excursion
14601 (save-restriction
14602 (if org-agenda-restrict
14603 (narrow-to-region org-agenda-restrict-begin
14604 org-agenda-restrict-end)
14605 (widen))
14606 (setq rtn (org-scan-tags 'agenda matcher todo-only))
14607 (setq rtnall (append rtnall rtn))))))))
14608 (if org-agenda-overriding-header
14609 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
14610 nil 'face 'org-level-3) "\n")
14611 (insert "Headlines with TAGS match: ")
14612 (add-text-properties (point-min) (1- (point))
14613 (list 'face 'org-level-3))
14614 (setq pos (point))
14615 (insert match "\n")
14616 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14617 (setq pos (point))
14618 (unless org-agenda-multi
14619 (insert "Press `C-u r' to search again with new search string\n"))
14620 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14621 (when rtnall
14622 (insert (org-finalize-agenda-entries rtnall) "\n"))
14623 (goto-char (point-min))
14624 (org-fit-agenda-window)
14625 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
14626 (org-finalize-agenda)
14627 (setq buffer-read-only t)))
14629 ;;; Agenda Finding stuck projects
14631 (defvar org-agenda-skip-regexp nil
14632 "Regular expression used in skipping subtrees for the agenda.
14633 This is basically a temporary global variable that can be set and then
14634 used by user-defined selections using `org-agenda-skip-function'.")
14636 (defvar org-agenda-overriding-header nil
14637 "When this is set during todo and tags searches, will replace header.")
14639 (defun org-agenda-skip-subtree-when-regexp-matches ()
14640 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
14641 If yes, it returns the end position of this tree, causing agenda commands
14642 to skip this subtree. This is a function that can be put into
14643 `org-agenda-skip-function' for the duration of a command."
14644 (save-match-data
14645 (let ((end (save-excursion (org-end-of-subtree t)))
14646 skip)
14647 (save-excursion
14648 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
14649 (and skip end))))
14651 (defun org-agenda-list-stuck-projects (&rest ignore)
14652 "Create agenda view for projects that are stuck.
14653 Stuck projects are project that have no next actions. For the definitions
14654 of what a project is and how to check if it stuck, customize the variable
14655 `org-stuck-projects'.
14656 MATCH is being ignored."
14657 (interactive)
14658 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
14659 (org-agenda-overriding-header "List of stuck projects: ")
14660 (matcher (nth 0 org-stuck-projects))
14661 (todo (nth 1 org-stuck-projects))
14662 (tags (nth 2 org-stuck-projects))
14663 (todo-re (concat "^\\*+[ \t]+\\("
14664 (mapconcat 'identity todo "\\|")
14665 "\\)\\>"))
14666 (tags-re (concat "^\\*+.*:\\("
14667 (mapconcat 'identity tags "\\|")
14668 "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
14670 (setq org-agenda-skip-regexp
14671 (cond
14672 ((and todo tags)
14673 (concat todo-re "\\|" tags-re))
14674 (todo todo-re)
14675 (tags tags-re)
14676 (t (error "No information how to identify unstuck projects"))))
14677 (org-tags-view nil matcher)
14678 (with-current-buffer org-agenda-buffer-name
14679 (setq org-agenda-redo-command
14680 '(org-agenda-list-stuck-projects
14681 (or current-prefix-arg org-last-arg))))))
14683 ;;; Diary integration
14685 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
14687 (defun org-get-entries-from-diary (date)
14688 "Get the (Emacs Calendar) diary entries for DATE."
14689 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
14690 (diary-display-hook '(fancy-diary-display))
14691 (list-diary-entries-hook
14692 (cons 'org-diary-default-entry list-diary-entries-hook))
14693 (diary-file-name-prefix-function nil) ; turn this feature off
14694 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
14695 entries
14696 (org-disable-agenda-to-diary t))
14697 (save-excursion
14698 (save-window-excursion
14699 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
14700 (if (not (get-buffer fancy-diary-buffer))
14701 (setq entries nil)
14702 (with-current-buffer fancy-diary-buffer
14703 (setq buffer-read-only nil)
14704 (if (= (point-max) 1)
14705 ;; No entries
14706 (setq entries nil)
14707 ;; Omit the date and other unnecessary stuff
14708 (org-agenda-cleanup-fancy-diary)
14709 ;; Add prefix to each line and extend the text properties
14710 (if (= (point-max) 1)
14711 (setq entries nil)
14712 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
14713 (set-buffer-modified-p nil)
14714 (kill-buffer fancy-diary-buffer)))
14715 (when entries
14716 (setq entries (org-split-string entries "\n"))
14717 (setq entries
14718 (mapcar
14719 (lambda (x)
14720 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
14721 ;; Extend the text properties to the beginning of the line
14722 (org-add-props x (text-properties-at (1- (length x)) x)))
14723 entries)))))
14725 (defun org-agenda-cleanup-fancy-diary ()
14726 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
14727 This gets rid of the date, the underline under the date, and
14728 the dummy entry installed by `org-mode' to ensure non-empty diary for each
14729 date. It also removes lines that contain only whitespace."
14730 (goto-char (point-min))
14731 (if (looking-at ".*?:[ \t]*")
14732 (progn
14733 (replace-match "")
14734 (re-search-forward "\n=+$" nil t)
14735 (replace-match "")
14736 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
14737 (re-search-forward "\n=+$" nil t)
14738 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
14739 (goto-char (point-min))
14740 (while (re-search-forward "^ +\n" nil t)
14741 (replace-match ""))
14742 (goto-char (point-min))
14743 (if (re-search-forward "^Org-mode dummy\n?" nil t)
14744 (replace-match "")))
14746 ;; Make sure entries from the diary have the right text properties.
14747 (eval-after-load "diary-lib"
14748 '(if (boundp 'diary-modify-entry-list-string-function)
14749 ;; We can rely on the hook, nothing to do
14751 ;; Hook not avaiable, must use advice to make this work
14752 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
14753 "Make the position visible."
14754 (if (and org-disable-agenda-to-diary ;; called from org-agenda
14755 (stringp string)
14756 buffer-file-name)
14757 (setq string (org-modify-diary-entry-string string))))))
14759 (defun org-modify-diary-entry-string (string)
14760 "Add text properties to string, allowing org-mode to act on it."
14761 (org-add-props string nil
14762 'mouse-face 'highlight
14763 'keymap org-agenda-keymap
14764 'help-echo (format "mouse-2 or RET jump to diary file %s"
14765 (abbreviate-file-name buffer-file-name))
14766 'org-agenda-diary-link t
14767 'org-marker (org-agenda-new-marker (point-at-bol))))
14769 (defun org-diary-default-entry ()
14770 "Add a dummy entry to the diary.
14771 Needed to avoid empty dates which mess up holiday display."
14772 ;; Catch the error if dealing with the new add-to-diary-alist
14773 (when org-disable-agenda-to-diary
14774 (condition-case nil
14775 (add-to-diary-list original-date "Org-mode dummy" "")
14776 (error
14777 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
14779 ;;;###autoload
14780 (defun org-diary (&rest args)
14781 "Return diary information from org-files.
14782 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
14783 It accesses org files and extracts information from those files to be
14784 listed in the diary. The function accepts arguments specifying what
14785 items should be listed. The following arguments are allowed:
14787 :timestamp List the headlines of items containing a date stamp or
14788 date range matching the selected date. Deadlines will
14789 also be listed, on the expiration day.
14791 :deadline List any deadlines past due, or due within
14792 `org-deadline-warning-days'. The listing occurs only
14793 in the diary for *today*, not at any other date. If
14794 an entry is marked DONE, it is no longer listed.
14796 :scheduled List all items which are scheduled for the given date.
14797 The diary for *today* also contains items which were
14798 scheduled earlier and are not yet marked DONE.
14800 :todo List all TODO items from the org-file. This may be a
14801 long list - so this is not turned on by default.
14802 Like deadlines, these entries only show up in the
14803 diary for *today*, not at any other date.
14805 The call in the diary file should look like this:
14807 &%%(org-diary) ~/path/to/some/orgfile.org
14809 Use a separate line for each org file to check. Or, if you omit the file name,
14810 all files listed in `org-agenda-files' will be checked automatically:
14812 &%%(org-diary)
14814 If you don't give any arguments (as in the example above), the default
14815 arguments (:deadline :scheduled :timestamp) are used. So the example above may
14816 also be written as
14818 &%%(org-diary :deadline :timestamp :scheduled)
14820 The function expects the lisp variables `entry' and `date' to be provided
14821 by the caller, because this is how the calendar works. Don't use this
14822 function from a program - use `org-agenda-get-day-entries' instead."
14823 (org-agenda-maybe-reset-markers)
14824 (org-compile-prefix-format 'agenda)
14825 (org-set-sorting-strategy 'agenda)
14826 (setq args (or args '(:deadline :scheduled :timestamp)))
14827 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
14828 (list entry)
14829 (org-agenda-files t)))
14830 file rtn results)
14831 ;; If this is called during org-agenda, don't return any entries to
14832 ;; the calendar. Org Agenda will list these entries itself.
14833 (if org-disable-agenda-to-diary (setq files nil))
14834 (while (setq file (pop files))
14835 (setq rtn (apply 'org-agenda-get-day-entries file date args))
14836 (setq results (append results rtn)))
14837 (if results
14838 (concat (org-finalize-agenda-entries results) "\n"))))
14840 ;;; Agenda entry finders
14842 (defun org-agenda-get-day-entries (file date &rest args)
14843 "Does the work for `org-diary' and `org-agenda'.
14844 FILE is the path to a file to be checked for entries. DATE is date like
14845 the one returned by `calendar-current-date'. ARGS are symbols indicating
14846 which kind of entries should be extracted. For details about these, see
14847 the documentation of `org-diary'."
14848 (setq args (or args '(:deadline :scheduled :timestamp)))
14849 (let* ((org-startup-folded nil)
14850 (org-startup-align-all-tables nil)
14851 (buffer (if (file-exists-p file)
14852 (org-get-agenda-file-buffer file)
14853 (error "No such file %s" file)))
14854 arg results rtn)
14855 (if (not buffer)
14856 ;; If file does not exist, make sure an error message ends up in diary
14857 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14858 (with-current-buffer buffer
14859 (unless (org-mode-p)
14860 (error "Agenda file %s is not in `org-mode'" file))
14861 (setq org-category-table (org-get-category-table))
14862 (let ((case-fold-search nil))
14863 (save-excursion
14864 (save-restriction
14865 (if org-agenda-restrict
14866 (narrow-to-region org-agenda-restrict-begin
14867 org-agenda-restrict-end)
14868 (widen))
14869 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
14870 (while (setq arg (pop args))
14871 (cond
14872 ((and (eq arg :todo)
14873 (equal date (calendar-current-date)))
14874 (setq rtn (org-agenda-get-todos))
14875 (setq results (append results rtn)))
14876 ((eq arg :timestamp)
14877 (setq rtn (org-agenda-get-blocks))
14878 (setq results (append results rtn))
14879 (setq rtn (org-agenda-get-timestamps))
14880 (setq results (append results rtn)))
14881 ((eq arg :scheduled)
14882 (setq rtn (org-agenda-get-scheduled))
14883 (setq results (append results rtn)))
14884 ((eq arg :closed)
14885 (setq rtn (org-agenda-get-closed))
14886 (setq results (append results rtn)))
14887 ((and (eq arg :deadline)
14888 (equal date (calendar-current-date)))
14889 (setq rtn (org-agenda-get-deadlines))
14890 (setq results (append results rtn))))))))
14891 results))))
14893 (defun org-entry-is-done-p ()
14894 "Is the current entry marked DONE?"
14895 (save-excursion
14896 (and (re-search-backward "[\r\n]\\*" nil t)
14897 (looking-at org-nl-done-regexp))))
14899 (defun org-at-date-range-p (&optional inactive-ok)
14900 "Is the cursor inside a date range?"
14901 (interactive)
14902 (save-excursion
14903 (catch 'exit
14904 (let ((pos (point)))
14905 (skip-chars-backward "^[<\r\n")
14906 (skip-chars-backward "<[")
14907 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
14908 (>= (match-end 0) pos)
14909 (throw 'exit t))
14910 (skip-chars-backward "^<[\r\n")
14911 (skip-chars-backward "<[")
14912 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
14913 (>= (match-end 0) pos)
14914 (throw 'exit t)))
14915 nil)))
14917 (defun org-agenda-get-todos ()
14918 "Return the TODO information for agenda display."
14919 (let* ((props (list 'face nil
14920 'done-face 'org-done
14921 'org-not-done-regexp org-not-done-regexp
14922 'mouse-face 'highlight
14923 'keymap org-agenda-keymap
14924 'help-echo
14925 (format "mouse-2 or RET jump to org file %s"
14926 (abbreviate-file-name buffer-file-name))))
14927 ;; FIXME: get rid of the \n at some point but watch out
14928 (regexp (concat "[\n\r]\\*+ *\\("
14929 (if org-select-this-todo-keyword
14930 (concat "\\<\\("
14931 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
14932 "\\)\\>")
14933 org-not-done-regexp)
14934 "[^\n\r]*\\)"))
14935 marker priority category tags
14936 ee txt beg end)
14937 (goto-char (point-min))
14938 (while (re-search-forward regexp nil t)
14939 (catch :skip
14940 (save-match-data
14941 (beginning-of-line)
14942 (setq beg (point) end (progn (outline-next-heading) (point)))
14943 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
14944 (re-search-forward org-scheduled-time-regexp end t))
14945 (and org-agenda-todo-ignore-deadlines (goto-char beg)
14946 (re-search-forward org-deadline-time-regexp end t)
14947 (org-deadline-close (match-string 1))))
14948 (goto-char beg)
14949 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
14950 (throw :skip nil)))
14951 (goto-char beg)
14952 (org-agenda-skip)
14953 (goto-char (match-beginning 1))
14954 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
14955 category (org-get-category)
14956 tags (org-get-tags-at (point))
14957 txt (org-format-agenda-item "" (match-string 1) category tags)
14958 priority (1+ (org-get-priority txt)))
14959 (org-add-props txt props
14960 'org-marker marker 'org-hd-marker marker
14961 'priority priority 'org-category category)
14962 (push txt ee)
14963 (if org-agenda-todo-list-sublevels
14964 (goto-char (match-end 1))
14965 (org-end-of-subtree 'invisible))))
14966 (nreverse ee)))
14968 (defconst org-agenda-no-heading-message
14969 "No heading for this item in buffer or region.")
14971 (defun org-agenda-get-timestamps ()
14972 "Return the date stamp information for agenda display."
14973 (let* ((props (list 'face nil
14974 'org-not-done-regexp org-not-done-regexp
14975 'mouse-face 'highlight
14976 'keymap org-agenda-keymap
14977 'help-echo
14978 (format "mouse-2 or RET jump to org file %s"
14979 (abbreviate-file-name buffer-file-name))))
14980 (regexp (regexp-quote
14981 (substring
14982 (format-time-string
14983 (car org-time-stamp-formats)
14984 (apply 'encode-time ; DATE bound by calendar
14985 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
14986 0 11)))
14987 marker hdmarker deadlinep scheduledp donep tmp priority category
14988 ee txt timestr tags)
14989 (goto-char (point-min))
14990 (while (re-search-forward regexp nil t)
14991 (catch :skip
14992 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
14993 (org-agenda-skip)
14994 (setq marker (org-agenda-new-marker (match-beginning 0))
14995 category (org-get-category (match-beginning 0))
14996 tmp (buffer-substring (max (point-min)
14997 (- (match-beginning 0)
14998 org-ds-keyword-length))
14999 (match-beginning 0))
15000 timestr (buffer-substring (match-beginning 0) (point-at-eol))
15001 deadlinep (string-match org-deadline-regexp tmp)
15002 scheduledp (string-match org-scheduled-regexp tmp)
15003 donep (org-entry-is-done-p))
15004 (and org-agenda-skip-scheduled-if-done
15005 scheduledp donep
15006 (throw :skip t))
15007 (if (string-match ">" timestr)
15008 ;; substring should only run to end of time stamp
15009 (setq timestr (substring timestr 0 (match-end 0))))
15010 (save-excursion
15011 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
15012 (progn
15013 (goto-char (match-end 1))
15014 (setq hdmarker (org-agenda-new-marker)
15015 tags (org-get-tags-at))
15016 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
15017 (setq txt (org-format-agenda-item
15018 (format "%s%s"
15019 (if deadlinep "Deadline: " "")
15020 (if scheduledp "Scheduled: " ""))
15021 (match-string 1) category tags timestr)))
15022 (setq txt org-agenda-no-heading-message))
15023 (setq priority (org-get-priority txt))
15024 (org-add-props txt props
15025 'org-marker marker 'org-hd-marker hdmarker)
15026 (if deadlinep
15027 (org-add-props txt nil
15028 'face (if donep 'org-done 'org-warning)
15029 'undone-face 'org-warning 'done-face 'org-done
15030 'org-category category 'priority (+ 100 priority))
15031 (if scheduledp
15032 (org-add-props txt nil
15033 'face 'org-scheduled-today
15034 'undone-face 'org-scheduled-today 'done-face 'org-done
15035 'org-category category 'priority (+ 99 priority))
15036 (org-add-props txt nil 'priority priority 'org-category category)))
15037 (push txt ee))
15038 (outline-next-heading)))
15039 (nreverse ee)))
15041 (defun org-agenda-get-closed ()
15042 "Return the logged TODO entries for agenda display."
15043 (let* ((props (list 'mouse-face 'highlight
15044 'org-not-done-regexp org-not-done-regexp
15045 'keymap org-agenda-keymap
15046 'help-echo
15047 (format "mouse-2 or RET jump to org file %s"
15048 (abbreviate-file-name buffer-file-name))))
15049 (regexp (concat
15050 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
15051 (regexp-quote
15052 (substring
15053 (format-time-string
15054 (car org-time-stamp-formats)
15055 (apply 'encode-time ; DATE bound by calendar
15056 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
15057 1 11))))
15058 marker hdmarker priority category tags closedp
15059 ee txt timestr)
15060 (goto-char (point-min))
15061 (while (re-search-forward regexp nil t)
15062 (catch :skip
15063 (org-agenda-skip)
15064 (setq marker (org-agenda-new-marker (match-beginning 0))
15065 closedp (equal (match-string 1) org-closed-string)
15066 category (org-get-category (match-beginning 0))
15067 timestr (buffer-substring (match-beginning 0) (point-at-eol))
15068 ;; donep (org-entry-is-done-p)
15070 (if (string-match "\\]" timestr)
15071 ;; substring should only run to end of time stamp
15072 (setq timestr (substring timestr 0 (match-end 0))))
15073 (save-excursion
15074 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
15075 (progn
15076 (goto-char (match-end 1))
15077 (setq hdmarker (org-agenda-new-marker)
15078 tags (org-get-tags-at))
15079 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
15080 (setq txt (org-format-agenda-item
15081 (if closedp "Closed: " "Clocked: ")
15082 (match-string 1) category tags timestr)))
15083 (setq txt org-agenda-no-heading-message))
15084 (setq priority 100000)
15085 (org-add-props txt props
15086 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
15087 'priority priority 'org-category category
15088 'undone-face 'org-warning 'done-face 'org-done)
15089 (push txt ee))
15090 (outline-next-heading)))
15091 (nreverse ee)))
15093 (defun org-agenda-get-deadlines ()
15094 "Return the deadline information for agenda display."
15095 (let* ((wdays org-deadline-warning-days)
15096 (props (list 'mouse-face 'highlight
15097 'org-not-done-regexp org-not-done-regexp
15098 'keymap org-agenda-keymap
15099 'help-echo
15100 (format "mouse-2 or RET jump to org file %s"
15101 (abbreviate-file-name buffer-file-name))))
15102 (regexp org-deadline-time-regexp)
15103 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
15104 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
15105 d2 diff pos pos1 category tags
15106 ee txt head face)
15107 (goto-char (point-min))
15108 (while (re-search-forward regexp nil t)
15109 (catch :skip
15110 (org-agenda-skip)
15111 (setq pos (1- (match-beginning 1))
15112 d2 (time-to-days
15113 (org-time-string-to-time (match-string 1)))
15114 diff (- d2 d1))
15115 ;; When to show a deadline in the calendar:
15116 ;; If the expiration is within wdays warning time.
15117 ;; Past-due deadlines are only shown on the current date
15118 (if (and (< diff wdays) todayp (not (= diff 0)))
15119 (save-excursion
15120 (setq category (org-get-category))
15121 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
15122 (progn
15123 (goto-char (match-end 0))
15124 (setq pos1 (match-end 1))
15125 (setq tags (org-get-tags-at pos1))
15126 (setq head (buffer-substring-no-properties
15127 (point)
15128 (progn (skip-chars-forward "^\r\n")
15129 (point))))
15130 (if (string-match org-looking-at-done-regexp head)
15131 (setq txt nil)
15132 (setq txt (org-format-agenda-item
15133 (format "In %3d d.: " diff) head category tags))))
15134 (setq txt org-agenda-no-heading-message))
15135 (when txt
15136 (setq face (cond ((<= diff 0) 'org-warning)
15137 ((<= diff 5) 'org-upcoming-deadline)
15138 (t nil)))
15139 (org-add-props txt props
15140 'org-marker (org-agenda-new-marker pos)
15141 'org-hd-marker (org-agenda-new-marker pos1)
15142 'priority (+ (- 10 diff) (org-get-priority txt))
15143 'org-category category
15144 'face face 'undone-face face 'done-face 'org-done)
15145 (push txt ee))))))
15146 ee))
15148 (defun org-agenda-get-scheduled ()
15149 "Return the scheduled information for agenda display."
15150 (let* ((props (list 'face 'org-scheduled-previously
15151 'org-not-done-regexp org-not-done-regexp
15152 'undone-face 'org-scheduled-previously
15153 'done-face 'org-done
15154 'mouse-face 'highlight
15155 'keymap org-agenda-keymap
15156 'help-echo
15157 (format "mouse-2 or RET jump to org file %s"
15158 (abbreviate-file-name buffer-file-name))))
15159 (regexp org-scheduled-time-regexp)
15160 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
15161 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
15162 d2 diff pos pos1 category tags
15163 ee txt head)
15164 (goto-char (point-min))
15165 (while (re-search-forward regexp nil t)
15166 (catch :skip
15167 (org-agenda-skip)
15168 (setq pos (1- (match-beginning 1))
15169 d2 (time-to-days
15170 (org-time-string-to-time (match-string 1)))
15171 diff (- d2 d1))
15172 ;; When to show a scheduled item in the calendar:
15173 ;; If it is on or past the date.
15174 (if (and (< diff 0) todayp)
15175 (save-excursion
15176 (setq category (org-get-category))
15177 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
15178 (progn
15179 (goto-char (match-end 0))
15180 (setq pos1 (match-end 1))
15181 (setq tags (org-get-tags-at))
15182 (setq head (buffer-substring-no-properties
15183 (point)
15184 (progn (skip-chars-forward "^\r\n") (point))))
15185 (if (string-match org-looking-at-done-regexp head)
15186 (setq txt nil)
15187 (setq txt (org-format-agenda-item
15188 (format "Sched.%2dx: " (- 1 diff)) head
15189 category tags))))
15190 (setq txt org-agenda-no-heading-message))
15191 (when txt
15192 (org-add-props txt props
15193 'org-marker (org-agenda-new-marker pos)
15194 'org-hd-marker (org-agenda-new-marker pos1)
15195 'priority (+ (- 5 diff) (org-get-priority txt))
15196 'org-category category)
15197 (push txt ee))))))
15198 ee))
15200 (defun org-agenda-get-blocks ()
15201 "Return the date-range information for agenda display."
15202 (let* ((props (list 'face nil
15203 'org-not-done-regexp org-not-done-regexp
15204 'mouse-face 'highlight
15205 'keymap org-agenda-keymap
15206 'help-echo
15207 (format "mouse-2 or RET jump to org file %s"
15208 (abbreviate-file-name buffer-file-name))))
15209 (regexp org-tr-regexp)
15210 (d0 (calendar-absolute-from-gregorian date))
15211 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
15212 (goto-char (point-min))
15213 (while (re-search-forward regexp nil t)
15214 (catch :skip
15215 (org-agenda-skip)
15216 (setq pos (point))
15217 (setq timestr (match-string 0)
15218 s1 (match-string 1)
15219 s2 (match-string 2)
15220 d1 (time-to-days (org-time-string-to-time s1))
15221 d2 (time-to-days (org-time-string-to-time s2)))
15222 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
15223 ;; Only allow days between the limits, because the normal
15224 ;; date stamps will catch the limits.
15225 (save-excursion
15226 (setq marker (org-agenda-new-marker (point)))
15227 (setq category (org-get-category))
15228 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
15229 (progn
15230 (setq hdmarker (org-agenda-new-marker (match-end 1)))
15231 (goto-char (match-end 1))
15232 (setq tags (org-get-tags-at))
15233 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
15234 (setq txt (org-format-agenda-item
15235 (format (if (= d1 d2) "" "(%d/%d): ")
15236 (1+ (- d0 d1)) (1+ (- d2 d1)))
15237 (match-string 1) category tags
15238 (if (= d0 d1) timestr))))
15239 (setq txt org-agenda-no-heading-message))
15240 (org-add-props txt props
15241 'org-marker marker 'org-hd-marker hdmarker
15242 'priority (org-get-priority txt) 'org-category category)
15243 (push txt ee)))
15244 (goto-char pos)))
15245 ;; Sort the entries by expiration date.
15246 (nreverse ee)))
15248 ;;; Agenda presentation and sorting
15250 ;; FIXME: should I allow spaces around the dash?
15251 (defconst org-plain-time-of-day-regexp
15252 (concat
15253 "\\(\\<[012]?[0-9]"
15254 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
15255 "\\(--?"
15256 "\\(\\<[012]?[0-9]"
15257 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
15258 "\\)?")
15259 "Regular expression to match a plain time or time range.
15260 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
15261 groups carry important information:
15262 0 the full match
15263 1 the first time, range or not
15264 8 the second time, if it is a range.")
15266 (defconst org-stamp-time-of-day-regexp
15267 (concat
15268 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
15269 "\\([012][0-9]:[0-5][0-9]\\)>"
15270 "\\(--?"
15271 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
15272 "Regular expression to match a timestamp time or time range.
15273 After a match, the following groups carry important information:
15274 0 the full match
15275 1 date plus weekday, for backreferencing to make sure both times on same day
15276 2 the first time, range or not
15277 4 the second time, if it is a range.")
15279 (defvar org-prefix-has-time nil
15280 "A flag, set by `org-compile-prefix-format'.
15281 The flag is set if the currently compiled format contains a `%t'.")
15282 (defvar org-prefix-has-tag nil
15283 "A flag, set by `org-compile-prefix-format'.
15284 The flag is set if the currently compiled format contains a `%T'.")
15286 (defun org-format-agenda-item (extra txt &optional category tags dotime
15287 noprefix)
15288 "Format TXT to be inserted into the agenda buffer.
15289 In particular, it adds the prefix and corresponding text properties. EXTRA
15290 must be a string and replaces the `%s' specifier in the prefix format.
15291 CATEGORY (string, symbol or nil) may be used to overrule the default
15292 category taken from local variable or file name. It will replace the `%c'
15293 specifier in the format. DOTIME, when non-nil, indicates that a
15294 time-of-day should be extracted from TXT for sorting of this entry, and for
15295 the `%t' specifier in the format. When DOTIME is a string, this string is
15296 searched for a time before TXT is. NOPREFIX is a flag and indicates that
15297 only the correctly processes TXT should be returned - this is used by
15298 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
15299 (save-match-data
15300 ;; Diary entries sometimes have extra whitespace at the beginning
15301 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
15302 (let* ((category (or category
15303 org-category
15304 (if buffer-file-name
15305 (file-name-sans-extension
15306 (file-name-nondirectory buffer-file-name))
15307 "")))
15308 (tag (if tags (nth (1- (length tags)) tags) ""))
15309 time ; time and tag are needed for the eval of the prefix format
15310 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
15311 (time-of-day (and dotime (org-get-time-of-day ts)))
15312 stamp plain s0 s1 s2 rtn)
15313 (when (and dotime time-of-day org-prefix-has-time)
15314 ;; Extract starting and ending time and move them to prefix
15315 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
15316 (setq plain (string-match org-plain-time-of-day-regexp ts)))
15317 (setq s0 (match-string 0 ts)
15318 s1 (match-string (if plain 1 2) ts)
15319 s2 (match-string (if plain 8 4) ts))
15321 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
15322 ;; them, we might want to remove them there to avoid duplication.
15323 ;; The user can turn this off with a variable.
15324 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
15325 (string-match (concat (regexp-quote s0) " *") txt)
15326 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
15327 (= (match-beginning 0) 0)
15329 (setq txt (replace-match "" nil nil txt))))
15330 ;; Normalize the time(s) to 24 hour
15331 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
15332 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
15334 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
15335 ;; Tags are in the string
15336 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
15337 (and org-agenda-remove-tags-when-in-prefix
15338 org-prefix-has-tag))
15339 (setq txt (replace-match "" t t txt))
15340 (setq txt (replace-match
15341 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
15342 (match-string 2 txt))
15343 t t txt))))
15345 ;; Create the final string
15346 (if noprefix
15347 (setq rtn txt)
15348 ;; Prepare the variables needed in the eval of the compiled format
15349 (setq time (cond (s2 (concat s1 "-" s2))
15350 (s1 (concat s1 "......"))
15351 (t ""))
15352 extra (or extra "")
15353 category (if (symbolp category) (symbol-name category) category))
15354 ;; Evaluate the compiled format
15355 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
15357 ;; And finally add the text properties
15358 (org-add-props rtn nil
15359 'org-category (downcase category) 'tags tags
15360 'prefix-length (- (length rtn) (length txt))
15361 'time-of-day time-of-day
15362 'dotime dotime))))
15364 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
15365 (defvar org-agenda-sorting-strategy-selected nil)
15367 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
15368 (catch 'exit
15369 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
15370 ((and todayp (member 'today (car org-agenda-time-grid))))
15371 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
15372 ((member 'weekly (car org-agenda-time-grid)))
15373 (t (throw 'exit list)))
15374 (let* ((have (delq nil (mapcar
15375 (lambda (x) (get-text-property 1 'time-of-day x))
15376 list)))
15377 (string (nth 1 org-agenda-time-grid))
15378 (gridtimes (nth 2 org-agenda-time-grid))
15379 (req (car org-agenda-time-grid))
15380 (remove (member 'remove-match req))
15381 new time)
15382 (if (and (member 'require-timed req) (not have))
15383 ;; don't show empty grid
15384 (throw 'exit list))
15385 (while (setq time (pop gridtimes))
15386 (unless (and remove (member time have))
15387 (setq time (int-to-string time))
15388 (push (org-format-agenda-item
15389 nil string "" nil
15390 (concat (substring time 0 -2) ":" (substring time -2)))
15391 new)
15392 (put-text-property
15393 1 (length (car new)) 'face 'org-time-grid (car new))))
15394 (if (member 'time-up org-agenda-sorting-strategy-selected)
15395 (append new list)
15396 (append list new)))))
15398 (defun org-compile-prefix-format (key)
15399 "Compile the prefix format into a Lisp form that can be evaluated.
15400 The resulting form is returned and stored in the variable
15401 `org-prefix-format-compiled'."
15402 (setq org-prefix-has-time nil org-prefix-has-tag nil)
15403 (let ((s (cond
15404 ((stringp org-agenda-prefix-format)
15405 org-agenda-prefix-format)
15406 ((assq key org-agenda-prefix-format)
15407 (cdr (assq key org-agenda-prefix-format)))
15408 (t " %-12:c%?-12t% s")))
15409 (start 0)
15410 varform vars var e c f opt)
15411 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
15412 s start)
15413 (setq var (cdr (assoc (match-string 4 s)
15414 '(("c" . category) ("t" . time) ("s" . extra)
15415 ("T" . tag))))
15416 c (or (match-string 3 s) "")
15417 opt (match-beginning 1)
15418 start (1+ (match-beginning 0)))
15419 (if (equal var 'time) (setq org-prefix-has-time t))
15420 (if (equal var 'tag) (setq org-prefix-has-tag t))
15421 (setq f (concat "%" (match-string 2 s) "s"))
15422 (if opt
15423 (setq varform
15424 `(if (equal "" ,var)
15426 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
15427 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
15428 (setq s (replace-match "%s" t nil s))
15429 (push varform vars))
15430 (setq vars (nreverse vars))
15431 (setq org-prefix-format-compiled `(format ,s ,@vars))))
15433 (defun org-set-sorting-strategy (key)
15434 (if (symbolp (car org-agenda-sorting-strategy))
15435 ;; the old format
15436 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
15437 (setq org-agenda-sorting-strategy-selected
15438 (or (cdr (assq key org-agenda-sorting-strategy))
15439 (cdr (assq 'agenda org-agenda-sorting-strategy))
15440 '(time-up category-keep priority-down)))))
15442 (defun org-get-time-of-day (s &optional string mod24)
15443 "Check string S for a time of day.
15444 If found, return it as a military time number between 0 and 2400.
15445 If not found, return nil.
15446 The optional STRING argument forces conversion into a 5 character wide string
15447 HH:MM."
15448 (save-match-data
15449 (when
15451 (string-match
15452 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
15453 (string-match
15454 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
15455 (let* ((h (string-to-number (match-string 1 s)))
15456 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
15457 (ampm (if (match-end 4) (downcase (match-string 4 s))))
15458 (am-p (equal ampm "am"))
15459 (h1 (cond ((not ampm) h)
15460 ((= h 12) (if am-p 0 12))
15461 (t (+ h (if am-p 0 12)))))
15462 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
15463 (mod h1 24) h1))
15464 (t0 (+ (* 100 h2) m))
15465 (t1 (concat (if (>= h1 24) "+" " ")
15466 (if (< t0 100) "0" "")
15467 (if (< t0 10) "0" "")
15468 (int-to-string t0))))
15469 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
15471 (defun org-finalize-agenda-entries (list &optional nosort)
15472 "Sort and concatenate the agenda items."
15473 (setq list (mapcar 'org-agenda-highlight-todo list))
15474 (if nosort
15475 list
15476 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
15478 (defun org-agenda-highlight-todo (x)
15479 (let (re pl)
15480 (if (eq x 'line)
15481 (save-excursion
15482 (beginning-of-line 1)
15483 (setq re (get-text-property (point) 'org-not-done-regexp))
15484 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
15485 (and (looking-at (concat "[ \t]*\\.*" re))
15486 (add-text-properties (match-beginning 0) (match-end 0)
15487 '(face org-todo))))
15488 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
15489 pl (get-text-property 0 'prefix-length x))
15490 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
15491 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
15492 '(face org-todo) x))
15493 x)))
15495 (defsubst org-cmp-priority (a b)
15496 "Compare the priorities of string A and B."
15497 (let ((pa (or (get-text-property 1 'priority a) 0))
15498 (pb (or (get-text-property 1 'priority b) 0)))
15499 (cond ((> pa pb) +1)
15500 ((< pa pb) -1)
15501 (t nil))))
15503 (defsubst org-cmp-category (a b)
15504 "Compare the string values of categories of strings A and B."
15505 (let ((ca (or (get-text-property 1 'category a) ""))
15506 (cb (or (get-text-property 1 'category b) "")))
15507 (cond ((string-lessp ca cb) -1)
15508 ((string-lessp cb ca) +1)
15509 (t nil))))
15511 (defsubst org-cmp-tag (a b)
15512 "Compare the string values of categories of strings A and B."
15513 (let ((ta (car (last (get-text-property 1 'tags a))))
15514 (tb (car (last (get-text-property 1 'tags b)))))
15515 (cond ((not ta) +1)
15516 ((not tb) -1)
15517 ((string-lessp ta tb) -1)
15518 ((string-lessp tb ta) +1)
15519 (t nil))))
15521 (defsubst org-cmp-time (a b)
15522 "Compare the time-of-day values of strings A and B."
15523 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
15524 (ta (or (get-text-property 1 'time-of-day a) def))
15525 (tb (or (get-text-property 1 'time-of-day b) def)))
15526 (cond ((< ta tb) -1)
15527 ((< tb ta) +1)
15528 (t nil))))
15530 (defun org-entries-lessp (a b)
15531 "Predicate for sorting agenda entries."
15532 ;; The following variables will be used when the form is evaluated.
15533 ;; So even though the compiler complains, keep them.
15534 (let* ((time-up (org-cmp-time a b))
15535 (time-down (if time-up (- time-up) nil))
15536 (priority-up (org-cmp-priority a b))
15537 (priority-down (if priority-up (- priority-up) nil))
15538 (category-up (org-cmp-category a b))
15539 (category-down (if category-up (- category-up) nil))
15540 (category-keep (if category-up +1 nil))
15541 (tag-up (org-cmp-tag a b))
15542 (tag-down (if tag-up (- tag-up) nil)))
15543 (cdr (assoc
15544 (eval (cons 'or org-agenda-sorting-strategy-selected))
15545 '((-1 . t) (1 . nil) (nil . nil))))))
15547 ;;; Agenda commands
15549 (defun org-agenda-check-type (error &rest types)
15550 "Check if agenda buffer is of allowed type.
15551 If ERROR is non-nil, throw an error, otherwise just return nil."
15552 (if (memq org-agenda-type types)
15554 (if error
15555 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
15556 nil)))
15558 (defun org-agenda-quit ()
15559 "Exit agenda by removing the window or the buffer."
15560 (interactive)
15561 (let ((buf (current-buffer)))
15562 (if (not (one-window-p)) (delete-window))
15563 (kill-buffer buf)
15564 (org-agenda-maybe-reset-markers 'force))
15565 ;; Maybe restore the pre-agenda window configuration.
15566 (and org-agenda-restore-windows-after-quit
15567 (not (eq org-agenda-window-setup 'other-frame))
15568 org-pre-agenda-window-conf
15569 (set-window-configuration org-pre-agenda-window-conf)))
15571 (defun org-agenda-exit ()
15572 "Exit agenda by removing the window or the buffer.
15573 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
15574 Org-mode buffers visited directly by the user will not be touched."
15575 (interactive)
15576 (org-release-buffers org-agenda-new-buffers)
15577 (setq org-agenda-new-buffers nil)
15578 (org-agenda-quit))
15580 (defun org-save-all-org-buffers ()
15581 "Save all Org-mode buffers without user confirmation."
15582 (interactive)
15583 (message "Saving all Org-mode buffers...")
15584 (save-some-buffers t 'org-mode-p)
15585 (message "Saving all Org-mode buffers... done"))
15587 (defun org-agenda-redo ()
15588 "Rebuild Agenda.
15589 When this is the global TODO list, a prefix argument will be interpreted."
15590 (interactive)
15591 (let* ((org-agenda-keep-modes t)
15592 (line (org-current-line))
15593 (window-line (- line (org-current-line (window-start)))))
15594 (message "Rebuilding agenda buffer...")
15595 (eval org-agenda-redo-command)
15596 (setq org-agenda-undo-list nil
15597 org-agenda-pending-undo-list nil)
15598 (message "Rebuilding agenda buffer...done")
15599 (goto-line line)
15600 (recenter window-line)))
15602 (defun org-agenda-goto-today ()
15603 "Go to today."
15604 (interactive)
15605 (org-agenda-check-type t 'timeline 'agenda)
15606 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
15607 (cond
15608 (tdpos (goto-char tdpos))
15609 ((eq org-agenda-type 'agenda)
15610 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
15611 (setf (nth 1 org-agenda-overriding-arguments) nil)
15612 (org-agenda-redo)
15613 (org-agenda-find-today-or-agenda)))
15614 (t (error "Cannot find today")))))
15616 (defun org-agenda-find-today-or-agenda ()
15617 (goto-char
15618 (or (text-property-any (point-min) (point-max) 'org-today t)
15619 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
15620 (point-min))))
15622 (defun org-agenda-later (arg)
15623 "Go forward in time by `org-agenda-ndays' days.
15624 With prefix ARG, go forward that many times `org-agenda-ndays'."
15625 (interactive "p")
15626 (org-agenda-check-type t 'agenda)
15627 (let ((org-agenda-overriding-arguments
15628 (list (car org-agenda-last-arguments)
15629 (+ org-starting-day (* arg org-agenda-ndays))
15630 nil t)))
15631 (org-agenda-redo)
15632 (org-agenda-find-today-or-agenda)))
15634 (defun org-agenda-earlier (arg)
15635 "Go back in time by `org-agenda-ndays' days.
15636 With prefix ARG, go back that many times `org-agenda-ndays'."
15637 (interactive "p")
15638 (org-agenda-check-type t 'agenda)
15639 (let ((org-agenda-overriding-arguments
15640 (list (car org-agenda-last-arguments)
15641 (- org-starting-day (* arg org-agenda-ndays))
15642 nil t)))
15643 (org-agenda-redo)
15644 (org-agenda-find-today-or-agenda)))
15646 (defun org-agenda-week-view ()
15647 "Switch to weekly view for agenda."
15648 (interactive)
15649 (org-agenda-check-type t 'agenda)
15650 (if (= org-agenda-ndays 7)
15651 (error "This is already the week view"))
15652 (setq org-agenda-ndays 7)
15653 (let ((org-agenda-overriding-arguments
15654 (list (car org-agenda-last-arguments)
15655 (or (get-text-property (point) 'day)
15656 org-starting-day)
15657 nil t)))
15658 (org-agenda-redo)
15659 (org-agenda-find-today-or-agenda))
15660 (org-agenda-set-mode-name)
15661 (message "Switched to week view"))
15663 (defun org-agenda-day-view ()
15664 "Switch to daily view for agenda."
15665 (interactive)
15666 (org-agenda-check-type t 'agenda)
15667 (if (= org-agenda-ndays 1)
15668 (error "This is already the day view"))
15669 (setq org-agenda-ndays 1)
15670 (let ((org-agenda-overriding-arguments
15671 (list (car org-agenda-last-arguments)
15672 (or (get-text-property (point) 'day)
15673 org-starting-day)
15674 nil t)))
15675 (org-agenda-redo)
15676 (org-agenda-find-today-or-agenda))
15677 (org-agenda-set-mode-name)
15678 (message "Switched to day view"))
15680 ;; FIXME: this no longer works if user make date format that starts with a blank
15681 (defun org-agenda-next-date-line (&optional arg)
15682 "Jump to the next line indicating a date in agenda buffer."
15683 (interactive "p")
15684 (org-agenda-check-type t 'agenda 'timeline)
15685 (beginning-of-line 1)
15686 (if (looking-at "^\\S-") (forward-char 1))
15687 (if (not (re-search-forward "^\\S-" nil t arg))
15688 (progn
15689 (backward-char 1)
15690 (error "No next date after this line in this buffer")))
15691 (goto-char (match-beginning 0)))
15693 (defun org-agenda-previous-date-line (&optional arg)
15694 "Jump to the previous line indicating a date in agenda buffer."
15695 (interactive "p")
15696 (org-agenda-check-type t 'agenda 'timeline)
15697 (beginning-of-line 1)
15698 (if (not (re-search-backward "^\\S-" nil t arg))
15699 (error "No previous date before this line in this buffer")))
15701 ;; Initialize the highlight
15702 (defvar org-hl (org-make-overlay 1 1))
15703 (org-overlay-put org-hl 'face 'highlight)
15705 (defun org-highlight (begin end &optional buffer)
15706 "Highlight a region with overlay."
15707 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
15708 org-hl begin end (or buffer (current-buffer))))
15710 (defun org-unhighlight ()
15711 "Detach overlay INDEX."
15712 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
15714 ;; FIXME this is currently not used.
15715 (defun org-highlight-until-next-command (beg end &optional buffer)
15716 (org-highlight beg end buffer)
15717 (add-hook 'pre-command-hook 'org-unhighlight-once))
15719 (defun org-unhighlight-once ()
15720 (remove-hook 'pre-command-hook 'org-unhighlight-once)
15721 (org-unhighlight))
15723 (defun org-agenda-follow-mode ()
15724 "Toggle follow mode in an agenda buffer."
15725 (interactive)
15726 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
15727 (org-agenda-set-mode-name)
15728 (message "Follow mode is %s"
15729 (if org-agenda-follow-mode "on" "off")))
15731 (defun org-agenda-log-mode ()
15732 "Toggle log mode in an agenda buffer."
15733 (interactive)
15734 (org-agenda-check-type t 'agenda 'timeline)
15735 (setq org-agenda-show-log (not org-agenda-show-log))
15736 (org-agenda-set-mode-name)
15737 (org-agenda-redo)
15738 (message "Log mode is %s"
15739 (if org-agenda-show-log "on" "off")))
15741 (defun org-agenda-toggle-diary ()
15742 "Toggle diary inclusion in an agenda buffer."
15743 (interactive)
15744 (org-agenda-check-type t 'agenda)
15745 (setq org-agenda-include-diary (not org-agenda-include-diary))
15746 (org-agenda-redo)
15747 (org-agenda-set-mode-name)
15748 (message "Diary inclusion turned %s"
15749 (if org-agenda-include-diary "on" "off")))
15751 (defun org-agenda-toggle-time-grid ()
15752 "Toggle time grid in an agenda buffer."
15753 (interactive)
15754 (org-agenda-check-type t 'agenda)
15755 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
15756 (org-agenda-redo)
15757 (org-agenda-set-mode-name)
15758 (message "Time-grid turned %s"
15759 (if org-agenda-use-time-grid "on" "off")))
15761 (defun org-agenda-set-mode-name ()
15762 "Set the mode name to indicate all the small mode settings."
15763 (setq mode-name
15764 (concat "Org-Agenda"
15765 (if (equal org-agenda-ndays 1) " Day" "")
15766 (if (equal org-agenda-ndays 7) " Week" "")
15767 (if org-agenda-follow-mode " Follow" "")
15768 (if org-agenda-include-diary " Diary" "")
15769 (if org-agenda-use-time-grid " Grid" "")
15770 (if org-agenda-show-log " Log" "")))
15771 (force-mode-line-update))
15773 (defun org-agenda-post-command-hook ()
15774 (and (eolp) (not (bolp)) (backward-char 1))
15775 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
15776 (if (and org-agenda-follow-mode
15777 (get-text-property (point) 'org-marker))
15778 (org-agenda-show)))
15780 (defun org-agenda-show-priority ()
15781 "Show the priority of the current item.
15782 This priority is composed of the main priority given with the [#A] cookies,
15783 and by additional input from the age of a schedules or deadline entry."
15784 (interactive)
15785 (let* ((pri (get-text-property (point-at-bol) 'priority)))
15786 (message "Priority is %d" (if pri pri -1000))))
15788 (defun org-agenda-show-tags ()
15789 "Show the tags applicable to the current item."
15790 (interactive)
15791 (let* ((tags (get-text-property (point-at-bol) 'tags)))
15792 (if tags
15793 (message "Tags are :%s:"
15794 (org-no-properties (mapconcat 'identity tags ":")))
15795 (message "No tags associated with this line"))))
15797 (defun org-agenda-goto (&optional highlight)
15798 "Go to the Org-mode file which contains the item at point."
15799 (interactive)
15800 (let* ((marker (or (get-text-property (point) 'org-marker)
15801 (org-agenda-error)))
15802 (buffer (marker-buffer marker))
15803 (pos (marker-position marker)))
15804 (switch-to-buffer-other-window buffer)
15805 (widen)
15806 (goto-char pos)
15807 (when (org-mode-p)
15808 (org-show-context 'agenda)
15809 (save-excursion
15810 (and (outline-next-heading)
15811 (org-flag-heading nil)))) ; show the next heading
15812 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
15814 (defun org-agenda-kill ()
15815 "Kill the entry or subtree belonging to the current agenda entry."
15816 (interactive)
15817 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15818 (let* ((marker (or (get-text-property (point) 'org-marker)
15819 (org-agenda-error)))
15820 (buffer (marker-buffer marker))
15821 (pos (marker-position marker))
15822 dbeg dend (n 0) conf)
15823 (org-with-remote-undo buffer
15824 (with-current-buffer buffer
15825 (save-excursion
15826 (goto-char pos)
15827 (if (org-mode-p)
15828 (setq dbeg (progn (org-back-to-heading t) (point))
15829 dend (org-end-of-subtree t))
15830 (setq dbeg (point-at-bol)
15831 dend (min (point-max) (1+ (point-at-eol)))))
15832 (goto-char dbeg)
15833 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
15834 (setq conf (or (eq t org-agenda-confirm-kill)
15835 (and (numberp org-agenda-confirm-kill)
15836 (> n org-agenda-confirm-kill))))
15837 (and conf
15838 (not (y-or-n-p
15839 (format "Delete entry with %d lines in buffer \"%s\"? "
15840 n (buffer-name buffer))))
15841 (error "Abort"))
15842 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
15843 (with-current-buffer buffer (delete-region dbeg dend))
15844 (message "Agenda item and source killed"))))
15846 (defun org-agenda-archive ()
15847 "Kill the entry or subtree belonging to the current agenda entry."
15848 (interactive)
15849 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15850 (let* ((marker (or (get-text-property (point) 'org-marker)
15851 (org-agenda-error)))
15852 (buffer (marker-buffer marker))
15853 (pos (marker-position marker)))
15854 (org-with-remote-undo buffer
15855 (with-current-buffer buffer
15856 (if (org-mode-p)
15857 (save-excursion
15858 (goto-char pos)
15859 (org-remove-subtree-entries-from-agenda)
15860 (org-back-to-heading t)
15861 (org-archive-subtree))
15862 (error "Archiving works only in Org-mode files"))))))
15864 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
15865 "Remove all lines in the agenda that correspond to a given subtree.
15866 The subtree is the one in buffer BUF, starting at BEG and ending at END.
15867 If this information is not given, the function uses the tree at point."
15868 (let ((buf (or buf (current-buffer))) m p)
15869 (save-excursion
15870 (unless (and beg end)
15871 (org-back-to-heading t)
15872 (setq beg (point))
15873 (org-end-of-subtree t)
15874 (setq end (point)))
15875 (set-buffer (get-buffer org-agenda-buffer-name))
15876 (save-excursion
15877 (goto-char (point-max))
15878 (beginning-of-line 1)
15879 (while (not (bobp))
15880 (when (and (setq m (get-text-property (point) 'org-marker))
15881 (equal buf (marker-buffer m))
15882 (setq p (marker-position m))
15883 (>= p beg)
15884 (<= p end))
15885 (let (buffer-read-only)
15886 (delete-region (point-at-bol) (1+ (point-at-eol)))))
15887 (beginning-of-line 0))))))
15889 (defun org-agenda-open-link ()
15890 "Follow the link in the current line, if any."
15891 (interactive)
15892 (let ((eol (point-at-eol)))
15893 (save-excursion
15894 (if (or (re-search-forward org-bracket-link-regexp eol t)
15895 (re-search-forward org-angle-link-re eol t)
15896 (re-search-forward org-plain-link-re eol t))
15897 (call-interactively 'org-open-at-point)
15898 (error "No link in current line")))))
15900 (defun org-agenda-switch-to (&optional delete-other-windows)
15901 "Go to the Org-mode file which contains the item at point."
15902 (interactive)
15903 (let* ((marker (or (get-text-property (point) 'org-marker)
15904 (org-agenda-error)))
15905 (buffer (marker-buffer marker))
15906 (pos (marker-position marker)))
15907 (switch-to-buffer buffer)
15908 (and delete-other-windows (delete-other-windows))
15909 (widen)
15910 (goto-char pos)
15911 (when (org-mode-p)
15912 (org-show-context 'agenda)
15913 (save-excursion
15914 (and (outline-next-heading)
15915 (org-flag-heading nil)))))) ; show the next heading
15917 (defun org-agenda-goto-mouse (ev)
15918 "Go to the Org-mode file which contains the item at the mouse click."
15919 (interactive "e")
15920 (mouse-set-point ev)
15921 (org-agenda-goto))
15923 (defun org-agenda-show ()
15924 "Display the Org-mode file which contains the item at point."
15925 (interactive)
15926 (let ((win (selected-window)))
15927 (org-agenda-goto t)
15928 (select-window win)))
15930 (defun org-agenda-recenter (arg)
15931 "Display the Org-mode file which contains the item at point and recenter."
15932 (interactive "P")
15933 (let ((win (selected-window)))
15934 (org-agenda-goto t)
15935 (recenter arg)
15936 (select-window win)))
15938 (defun org-agenda-show-mouse (ev)
15939 "Display the Org-mode file which contains the item at the mouse click."
15940 (interactive "e")
15941 (mouse-set-point ev)
15942 (org-agenda-show))
15944 (defun org-agenda-check-no-diary ()
15945 "Check if the entry is a diary link and abort if yes."
15946 (if (get-text-property (point) 'org-agenda-diary-link)
15947 (org-agenda-error)))
15949 (defun org-agenda-error ()
15950 (error "Command not allowed in this line"))
15952 (defun org-agenda-tree-to-indirect-buffer ()
15953 "Show the subtree corresponding to the current entry in an indirect buffer.
15954 This calls the command `org-tree-to-indirect-buffer' from the original
15955 Org-mode buffer.
15956 With numerical prefix arg ARG, go up to this level and then take that tree.
15957 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
15958 dedicated frame)."
15959 (interactive)
15960 (org-agenda-check-no-diary)
15961 (let* ((marker (or (get-text-property (point) 'org-marker)
15962 (org-agenda-error)))
15963 (buffer (marker-buffer marker))
15964 (pos (marker-position marker)))
15965 (with-current-buffer buffer
15966 (save-excursion
15967 (goto-char pos)
15968 (call-interactively 'org-tree-to-indirect-buffer)))))
15970 (defvar org-last-heading-marker (make-marker)
15971 "Marker pointing to the headline that last changed its TODO state
15972 by a remote command from the agenda.")
15974 (defun org-agenda-todo-nextset ()
15975 "Switch TODO entry to next sequence."
15976 (interactive)
15977 (org-agenda-todo 'nextset))
15979 (defun org-agenda-todo-previousset ()
15980 "Switch TODO entry to previous sequence."
15981 (interactive)
15982 (org-agenda-todo 'previousset))
15984 (defun org-agenda-todo (&optional arg)
15985 "Cycle TODO state of line at point, also in Org-mode file.
15986 This changes the line at point, all other lines in the agenda referring to
15987 the same tree node, and the headline of the tree node in the Org-mode file."
15988 (interactive "P")
15989 (org-agenda-check-no-diary)
15990 (let* ((col (current-column))
15991 (marker (or (get-text-property (point) 'org-marker)
15992 (org-agenda-error)))
15993 (buffer (marker-buffer marker))
15994 (pos (marker-position marker))
15995 (hdmarker (get-text-property (point) 'org-hd-marker))
15996 (buffer-read-only nil)
15997 newhead)
15998 (org-with-remote-undo buffer
15999 (with-current-buffer buffer
16000 (widen)
16001 (goto-char pos)
16002 (org-show-context 'agenda)
16003 (save-excursion
16004 (and (outline-next-heading)
16005 (org-flag-heading nil))) ; show the next heading
16006 (org-todo arg)
16007 (and (bolp) (forward-char 1))
16008 (setq newhead (org-get-heading))
16009 (save-excursion
16010 (org-back-to-heading)
16011 (move-marker org-last-heading-marker (point))))
16012 (beginning-of-line 1)
16013 (save-excursion
16014 (org-agenda-change-all-lines newhead hdmarker 'fixface))
16015 (move-to-column col))))
16017 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
16018 "Change all lines in the agenda buffer which match HDMARKER.
16019 The new content of the line will be NEWHEAD (as modified by
16020 `org-format-agenda-item'). HDMARKER is checked with
16021 `equal' against all `org-hd-marker' text properties in the file.
16022 If FIXFACE is non-nil, the face of each item is modified acording to
16023 the new TODO state."
16024 (let* ((buffer-read-only nil)
16025 props m pl undone-face done-face finish new dotime cat tags)
16026 (save-excursion
16027 (goto-char (point-max))
16028 (beginning-of-line 1)
16029 (while (not finish)
16030 (setq finish (bobp))
16031 (when (and (setq m (get-text-property (point) 'org-hd-marker))
16032 (equal m hdmarker))
16033 (setq props (text-properties-at (point))
16034 dotime (get-text-property (point) 'dotime)
16035 cat (get-text-property (point) 'org-category)
16036 tags (get-text-property (point) 'tags)
16037 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
16038 pl (get-text-property (point) 'prefix-length)
16039 undone-face (get-text-property (point) 'undone-face)
16040 done-face (get-text-property (point) 'done-face))
16041 (move-to-column pl)
16042 (cond
16043 ((equal new "")
16044 (beginning-of-line 1)
16045 (and (looking-at ".*\n?") (replace-match "")))
16046 ((looking-at ".*")
16047 (replace-match new t t)
16048 (beginning-of-line 1)
16049 (add-text-properties (point-at-bol) (point-at-eol) props)
16050 (when fixface
16051 (add-text-properties
16052 (point-at-bol) (point-at-eol)
16053 (list 'face
16054 (if org-last-todo-state-is-todo
16055 undone-face done-face))))
16056 (org-agenda-highlight-todo 'line)
16057 (beginning-of-line 1))
16058 (t (error "Line update did not work"))))
16059 (beginning-of-line 0)))
16060 (org-finalize-agenda)))
16062 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
16063 ;; See the code in set-tags for the way to do this.
16064 (defun org-agenda-align-tags (&optional line)
16065 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
16066 (let ((buffer-read-only))
16067 (save-excursion
16068 (goto-char (if line (point-at-bol) (point-min)))
16069 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
16070 (if line (point-at-eol) nil) t)
16071 (delete-region (match-beginning 1) (match-end 1))
16072 (goto-char (match-beginning 1))
16073 (insert (org-add-props
16074 (make-string (max 1 (- org-agenda-align-tags-to-column
16075 (current-column))) ?\ )
16076 (text-properties-at (point))))))))
16078 (defun org-agenda-priority-up ()
16079 "Increase the priority of line at point, also in Org-mode file."
16080 (interactive)
16081 (org-agenda-priority 'up))
16083 (defun org-agenda-priority-down ()
16084 "Decrease the priority of line at point, also in Org-mode file."
16085 (interactive)
16086 (org-agenda-priority 'down))
16088 (defun org-agenda-priority (&optional force-direction)
16089 "Set the priority of line at point, also in Org-mode file.
16090 This changes the line at point, all other lines in the agenda referring to
16091 the same tree node, and the headline of the tree node in the Org-mode file."
16092 (interactive)
16093 (org-agenda-check-no-diary)
16094 (let* ((marker (or (get-text-property (point) 'org-marker)
16095 (org-agenda-error)))
16096 (buffer (marker-buffer marker))
16097 (pos (marker-position marker))
16098 (hdmarker (get-text-property (point) 'org-hd-marker))
16099 (buffer-read-only nil)
16100 newhead)
16101 (org-with-remote-undo buffer
16102 (with-current-buffer buffer
16103 (widen)
16104 (goto-char pos)
16105 (org-show-context 'agenda)
16106 (save-excursion
16107 (and (outline-next-heading)
16108 (org-flag-heading nil))) ; show the next heading
16109 (funcall 'org-priority force-direction)
16110 (end-of-line 1)
16111 (setq newhead (org-get-heading)))
16112 (org-agenda-change-all-lines newhead hdmarker)
16113 (beginning-of-line 1))))
16115 (defun org-get-tags-at (&optional pos)
16116 "Get a list of all headline tags applicable at POS.
16117 POS defaults to point. If tags are inherited, the list contains
16118 the targets in the same sequence as the headlines appear, i.e.
16119 the tags of the current headline come last."
16120 (interactive)
16121 (let (tags)
16122 (save-excursion
16123 (save-restriction
16124 (widen)
16125 (goto-char (or pos (point)))
16126 (save-match-data
16127 (org-back-to-heading t)
16128 (condition-case nil
16129 (while t
16130 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
16131 (setq tags (append (org-split-string
16132 (org-match-string-no-properties 1) ":")
16133 tags)))
16134 (or org-use-tag-inheritance (error ""))
16135 (org-up-heading-all 1))
16136 (error nil))))
16137 tags)))
16139 ;; FIXME: should fix the tags property of the agenda line.
16140 (defun org-agenda-set-tags ()
16141 "Set tags for the current headline."
16142 (interactive)
16143 (org-agenda-check-no-diary)
16144 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
16145 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
16146 (org-agenda-error)))
16147 (buffer (marker-buffer hdmarker))
16148 (pos (marker-position hdmarker))
16149 (buffer-read-only nil)
16150 newhead)
16151 (org-with-remote-undo buffer
16152 (with-current-buffer buffer
16153 (widen)
16154 (goto-char pos)
16155 (save-excursion
16156 (org-show-context 'agenda))
16157 (save-excursion
16158 (and (outline-next-heading)
16159 (org-flag-heading nil))) ; show the next heading
16160 (goto-char pos)
16161 (call-interactively 'org-set-tags)
16162 (end-of-line 1)
16163 (setq newhead (org-get-heading)))
16164 (org-agenda-change-all-lines newhead hdmarker)
16165 (beginning-of-line 1))))
16167 (defun org-agenda-toggle-archive-tag ()
16168 "Toggle the archive tag for the current entry."
16169 (interactive)
16170 (org-agenda-check-no-diary)
16171 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
16172 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
16173 (org-agenda-error)))
16174 (buffer (marker-buffer hdmarker))
16175 (pos (marker-position hdmarker))
16176 (buffer-read-only nil)
16177 newhead)
16178 (org-with-remote-undo buffer
16179 (with-current-buffer buffer
16180 (widen)
16181 (goto-char pos)
16182 (org-show-context 'agenda)
16183 (save-excursion
16184 (and (outline-next-heading)
16185 (org-flag-heading nil))) ; show the next heading
16186 (call-interactively 'org-toggle-archive-tag)
16187 (end-of-line 1)
16188 (setq newhead (org-get-heading)))
16189 (org-agenda-change-all-lines newhead hdmarker)
16190 (beginning-of-line 1))))
16192 (defun org-agenda-date-later (arg &optional what)
16193 "Change the date of this item to one day later."
16194 (interactive "p")
16195 (org-agenda-check-type t 'agenda 'timeline)
16196 (org-agenda-check-no-diary)
16197 (let* ((marker (or (get-text-property (point) 'org-marker)
16198 (org-agenda-error)))
16199 (buffer (marker-buffer marker))
16200 (pos (marker-position marker)))
16201 (org-with-remote-undo buffer
16202 (with-current-buffer buffer
16203 (widen)
16204 (goto-char pos)
16205 (if (not (org-at-timestamp-p))
16206 (error "Cannot find time stamp"))
16207 (org-timestamp-change arg (or what 'day)))
16208 (org-agenda-show-new-time marker org-last-changed-timestamp))
16209 (message "Time stamp changed to %s" org-last-changed-timestamp)))
16211 (defun org-agenda-date-earlier (arg &optional what)
16212 "Change the date of this item to one day earlier."
16213 (interactive "p")
16214 (org-agenda-date-later (- arg) what))
16216 (defun org-agenda-show-new-time (marker stamp)
16217 "Show new date stamp via text properties."
16218 ;; We use text properties to make this undoable
16219 (let ((buffer-read-only nil))
16220 (setq stamp (concat " => " stamp))
16221 (save-excursion
16222 (goto-char (point-max))
16223 (while (not (bobp))
16224 (when (equal marker (get-text-property (point) 'org-marker))
16225 (move-to-column (- (window-width) (length stamp)) t)
16226 (if (featurep 'xemacs)
16227 ;; Use `duplicable' property to trigger undo recording
16228 (let ((ex (make-extent nil nil))
16229 (gl (make-glyph stamp)))
16230 (set-glyph-face gl 'secondary-selection)
16231 (set-extent-properties
16232 ex (list 'invisible t 'end-glyph gl 'duplicable t))
16233 (insert-extent ex (1- (point)) (point-at-eol)))
16234 (add-text-properties
16235 (1- (point)) (point-at-eol)
16236 (list 'display (org-add-props stamp nil
16237 'face 'secondary-selection))))
16238 (beginning-of-line 1))
16239 (beginning-of-line 0)))))
16241 (defun org-agenda-date-prompt (arg)
16242 "Change the date of this item. Date is prompted for, with default today.
16243 The prefix ARG is passed to the `org-time-stamp' command and can therefore
16244 be used to request time specification in the time stamp."
16245 (interactive "P")
16246 (org-agenda-check-type t 'agenda 'timeline)
16247 (org-agenda-check-no-diary)
16248 (let* ((marker (or (get-text-property (point) 'org-marker)
16249 (org-agenda-error)))
16250 (buffer (marker-buffer marker))
16251 (pos (marker-position marker)))
16252 (org-with-remote-undo buffer
16253 (with-current-buffer buffer
16254 (widen)
16255 (goto-char pos)
16256 (if (not (org-at-timestamp-p))
16257 (error "Cannot find time stamp"))
16258 (org-time-stamp arg)
16259 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
16261 (defun org-agenda-schedule (arg)
16262 "Schedule the item at point."
16263 (interactive "P")
16264 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
16265 (org-agenda-check-no-diary)
16266 (let* ((marker (or (get-text-property (point) 'org-marker)
16267 (org-agenda-error)))
16268 (buffer (marker-buffer marker))
16269 (pos (marker-position marker))
16270 (org-insert-labeled-timestamps-at-point nil)
16272 (org-with-remote-undo buffer
16273 (with-current-buffer buffer
16274 (widen)
16275 (goto-char pos)
16276 (setq ts (org-schedule))
16277 (message "Item scheduled for %s" ts)))))
16279 (defun org-agenda-deadline (arg)
16280 "Schedule the item at point."
16281 (interactive "P")
16282 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
16283 (org-agenda-check-no-diary)
16284 (let* ((marker (or (get-text-property (point) 'org-marker)
16285 (org-agenda-error)))
16286 (buffer (marker-buffer marker))
16287 (pos (marker-position marker))
16288 (org-insert-labeled-timestamps-at-point nil)
16290 (org-with-remote-undo buffer
16291 (with-current-buffer buffer
16292 (widen)
16293 (goto-char pos)
16294 (setq ts (org-deadline))
16295 (message "Deadline for this item set to %s" ts)))))
16297 (defun org-get-heading ()
16298 "Return the heading of the current entry, without the stars."
16299 (save-excursion
16300 (org-back-to-heading t)
16301 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
16303 (defun org-agenda-clock-in (&optional arg)
16304 "Start the clock on the currently selected item."
16305 (interactive "P")
16306 (org-agenda-check-no-diary)
16307 (let* ((marker (or (get-text-property (point) 'org-marker)
16308 (org-agenda-error)))
16309 (pos (marker-position marker)))
16310 (org-with-remote-undo (marker-buffer marker)
16311 (with-current-buffer (marker-buffer marker)
16312 (widen)
16313 (goto-char pos)
16314 (org-clock-in)))))
16316 (defun org-agenda-clock-out (&optional arg)
16317 "Stop the currently running clock."
16318 (interactive "P")
16319 (unless (marker-buffer org-clock-marker)
16320 (error "No running clock"))
16321 (org-with-remote-undo (marker-buffer org-clock-marker)
16322 (org-clock-out)))
16324 (defun org-agenda-clock-cancel (&optional arg)
16325 "Cancel the currently running clock."
16326 (interactive "P")
16327 (unless (marker-buffer org-clock-marker)
16328 (error "No running clock"))
16329 (org-with-remote-undo (marker-buffer org-clock-marker)
16330 (org-clock-cancel)))
16332 (defun org-agenda-diary-entry ()
16333 "Make a diary entry, like the `i' command from the calendar.
16334 All the standard commands work: block, weekly etc."
16335 (interactive)
16336 (org-agenda-check-type t 'agenda 'timeline)
16337 (require 'diary-lib)
16338 (let* ((char (progn
16339 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
16340 (read-char-exclusive)))
16341 (cmd (cdr (assoc char
16342 '((?d . insert-diary-entry)
16343 (?w . insert-weekly-diary-entry)
16344 (?m . insert-monthly-diary-entry)
16345 (?y . insert-yearly-diary-entry)
16346 (?a . insert-anniversary-diary-entry)
16347 (?b . insert-block-diary-entry)
16348 (?c . insert-cyclic-diary-entry)))))
16349 (oldf (symbol-function 'calendar-cursor-to-date))
16350 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
16351 (point (point))
16352 (mark (or (mark t) (point))))
16353 (unless cmd
16354 (error "No command associated with <%c>" char))
16355 (unless (and (get-text-property point 'day)
16356 (or (not (equal ?b char))
16357 (get-text-property mark 'day)))
16358 (error "Don't know which date to use for diary entry"))
16359 ;; We implement this by hacking the `calendar-cursor-to-date' function
16360 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
16361 (let ((calendar-mark-ring
16362 (list (calendar-gregorian-from-absolute
16363 (or (get-text-property mark 'day)
16364 (get-text-property point 'day))))))
16365 (unwind-protect
16366 (progn
16367 (fset 'calendar-cursor-to-date
16368 (lambda (&optional error)
16369 (calendar-gregorian-from-absolute
16370 (get-text-property point 'day))))
16371 (call-interactively cmd))
16372 (fset 'calendar-cursor-to-date oldf)))))
16375 (defun org-agenda-execute-calendar-command (cmd)
16376 "Execute a calendar command from the agenda, with the date associated to
16377 the cursor position."
16378 (org-agenda-check-type t 'agenda 'timeline)
16379 (require 'diary-lib)
16380 (unless (get-text-property (point) 'day)
16381 (error "Don't know which date to use for calendar command"))
16382 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
16383 (point (point))
16384 (date (calendar-gregorian-from-absolute
16385 (get-text-property point 'day)))
16386 ;; the following 3 vars are needed in the calendar
16387 (displayed-day (extract-calendar-day date))
16388 (displayed-month (extract-calendar-month date))
16389 (displayed-year (extract-calendar-year date)))
16390 (unwind-protect
16391 (progn
16392 (fset 'calendar-cursor-to-date
16393 (lambda (&optional error)
16394 (calendar-gregorian-from-absolute
16395 (get-text-property point 'day))))
16396 (call-interactively cmd))
16397 (fset 'calendar-cursor-to-date oldf))))
16399 (defun org-agenda-phases-of-moon ()
16400 "Display the phases of the moon for the 3 months around the cursor date."
16401 (interactive)
16402 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
16404 (defun org-agenda-holidays ()
16405 "Display the holidays for the 3 months around the cursor date."
16406 (interactive)
16407 (org-agenda-execute-calendar-command 'list-calendar-holidays))
16409 (defun org-agenda-sunrise-sunset (arg)
16410 "Display sunrise and sunset for the cursor date.
16411 Latitude and longitude can be specified with the variables
16412 `calendar-latitude' and `calendar-longitude'. When called with prefix
16413 argument, latitude and longitude will be prompted for."
16414 (interactive "P")
16415 (let ((calendar-longitude (if arg nil calendar-longitude))
16416 (calendar-latitude (if arg nil calendar-latitude))
16417 (calendar-location-name
16418 (if arg "the given coordinates" calendar-location-name)))
16419 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
16421 (defun org-agenda-goto-calendar ()
16422 "Open the Emacs calendar with the date at the cursor."
16423 (interactive)
16424 (org-agenda-check-type t 'agenda 'timeline)
16425 (let* ((day (or (get-text-property (point) 'day)
16426 (error "Don't know which date to open in calendar")))
16427 (date (calendar-gregorian-from-absolute day))
16428 (calendar-move-hook nil)
16429 (view-calendar-holidays-initially nil)
16430 (view-diary-entries-initially nil))
16431 (calendar)
16432 (calendar-goto-date date)))
16434 (defun org-calendar-goto-agenda ()
16435 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
16436 This is a command that has to be installed in `calendar-mode-map'."
16437 (interactive)
16438 (org-agenda-list nil (calendar-absolute-from-gregorian
16439 (calendar-cursor-to-date))
16440 nil))
16442 (defun org-agenda-convert-date ()
16443 (interactive)
16444 (org-agenda-check-type t 'agenda 'timeline)
16445 (let ((day (get-text-property (point) 'day))
16446 date s)
16447 (unless day
16448 (error "Don't know which date to convert"))
16449 (setq date (calendar-gregorian-from-absolute day))
16450 (setq s (concat
16451 "Gregorian: " (calendar-date-string date) "\n"
16452 "ISO: " (calendar-iso-date-string date) "\n"
16453 "Day of Yr: " (calendar-day-of-year-string date) "\n"
16454 "Julian: " (calendar-julian-date-string date) "\n"
16455 "Astron. JD: " (calendar-astro-date-string date)
16456 " (Julian date number at noon UTC)\n"
16457 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
16458 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
16459 "French: " (calendar-french-date-string date) "\n"
16460 "Mayan: " (calendar-mayan-date-string date) "\n"
16461 "Coptic: " (calendar-coptic-date-string date) "\n"
16462 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
16463 "Persian: " (calendar-persian-date-string date) "\n"
16464 "Chinese: " (calendar-chinese-date-string date) "\n"))
16465 (with-output-to-temp-buffer "*Dates*"
16466 (princ s))
16467 (if (fboundp 'fit-window-to-buffer)
16468 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
16471 ;;;; Embedded LaTeX
16473 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16474 "Keymap for the minor `org-cdlatex-mode'.")
16476 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16477 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16478 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16479 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16480 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16482 (defvar org-cdlatex-texmathp-advice-is-done nil
16483 "Flag remembering if we have applied the advice to texmathp already.")
16485 (define-minor-mode org-cdlatex-mode
16486 "Toggle the minor `org-cdlatex-mode'.
16487 This mode supports entering LaTeX environment and math in LaTeX fragments
16488 in Org-mode.
16489 \\{org-cdlatex-mode-map}"
16490 nil " OCDL" nil
16491 (when org-cdlatex-mode (require 'cdlatex))
16492 (unless org-cdlatex-texmathp-advice-is-done
16493 (setq org-cdlatex-texmathp-advice-is-done t)
16494 (defadvice texmathp (around org-math-always-on activate)
16495 "Always return t in org-mode buffers.
16496 This is because we want to insert math symbols without dollars even outside
16497 the LaTeX math segments. If Orgmode thinks that point is actually inside
16498 en embedded LaTeX fragement, let texmathp do its job.
16499 \\[org-cdlatex-mode-map]"
16500 (interactive)
16501 (let (p)
16502 (cond
16503 ((not (org-mode-p)) ad-do-it)
16504 ((eq this-command 'cdlatex-math-symbol)
16505 (setq ad-return-value t
16506 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16508 (let ((p (org-inside-LaTeX-fragment-p)))
16509 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16510 (setq ad-return-value t
16511 texmathp-why '("Org-mode embedded math" . 0))
16512 (if p ad-do-it)))))))))
16514 (defun turn-on-org-cdlatex ()
16515 "Unconditionally turn on `org-cdlatex-mode'."
16516 (org-cdlatex-mode 1))
16518 (defun org-inside-LaTeX-fragment-p ()
16519 "Test if point is inside a LaTeX fragment.
16520 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16521 sequence appearing also before point.
16522 Even though the matchers for math are configurable, this function assumes
16523 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16524 delimiters are skipped when they have been removed by customization.
16525 The return value is nil, or a cons cell with the delimiter and
16526 and the position of this delimiter.
16528 This function does a reasonably good job, but can locally be fooled by
16529 for example currency specifications. For example it will assume being in
16530 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16531 fragments that are properly closed, but during editing, we have to live
16532 with the uncertainty caused by missing closing delimiters. This function
16533 looks only before point, not after."
16534 (catch 'exit
16535 (let ((pos (point))
16536 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16537 (lim (progn
16538 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16539 (point)))
16540 dd-on str (start 0) m re)
16541 (goto-char pos)
16542 (when dodollar
16543 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16544 re (nth 1 (assoc "$" org-latex-regexps)))
16545 (while (string-match re str start)
16546 (cond
16547 ((= (match-end 0) (length str))
16548 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
16549 ((= (match-end 0) (- (length str) 5))
16550 (throw 'exit nil))
16551 (t (setq start (match-end 0))))))
16552 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16553 (goto-char pos)
16554 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16555 (and (match-beginning 2) (throw 'exit nil))
16556 ;; count $$
16557 (while (re-search-backward "\\$\\$" lim t)
16558 (setq dd-on (not dd-on)))
16559 (goto-char pos)
16560 (if dd-on (cons "$$" m))))))
16563 (defun org-try-cdlatex-tab ()
16564 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16565 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16566 - inside a LaTeX fragment, or
16567 - after the first word in a line, where an abbreviation expansion could
16568 insert a LaTeX environment."
16569 (when org-cdlatex-mode
16570 (cond
16571 ((save-excursion
16572 (skip-chars-backward "a-zA-Z0-9*")
16573 (skip-chars-backward " \t")
16574 (bolp))
16575 (cdlatex-tab) t)
16576 ((org-inside-LaTeX-fragment-p)
16577 (cdlatex-tab) t)
16578 (t nil))))
16580 (defun org-cdlatex-underscore-caret (&optional arg)
16581 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16582 Revert to the normal definition outside of these fragments."
16583 (interactive "P")
16584 (if (org-inside-LaTeX-fragment-p)
16585 (call-interactively 'cdlatex-sub-superscript)
16586 (let (org-cdlatex-mode)
16587 (call-interactively (key-binding (vector last-input-event))))))
16589 (defun org-cdlatex-math-modify (&optional arg)
16590 "Execute `cdlatex-math-modify' in LaTeX fragments.
16591 Revert to the normal definition outside of these fragments."
16592 (interactive "P")
16593 (if (org-inside-LaTeX-fragment-p)
16594 (call-interactively 'cdlatex-math-modify)
16595 (let (org-cdlatex-mode)
16596 (call-interactively (key-binding (vector last-input-event))))))
16598 (defvar org-latex-fragment-image-overlays nil
16599 "List of overlays carrying the images of latex fragments.")
16600 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16602 (defun org-remove-latex-fragment-image-overlays ()
16603 "Remove all overlays with LaTeX fragment images in current buffer."
16604 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
16605 (setq org-latex-fragment-image-overlays nil))
16607 (defun org-preview-latex-fragment (&optional subtree)
16608 "Preview the LaTeX fragment at point, or all locally or globally.
16609 If the cursor is in a LaTeX fragment, create the image and overlay
16610 it over the source code. If there is no fragment at point, display
16611 all fragments in the current text, from one headline to the next. With
16612 prefix SUBTREE, display all fragments in the current subtree. With a
16613 double prefix `C-u C-u', or when the cursor is before the first headline,
16614 display all fragments in the buffer.
16615 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16616 (interactive "P")
16617 (org-remove-latex-fragment-image-overlays)
16618 (save-excursion
16619 (save-restriction
16620 (let (beg end at msg)
16621 (cond
16622 ((or (equal subtree '(16))
16623 (not (save-excursion
16624 (re-search-backward (concat "^" outline-regexp) nil t))))
16625 (setq beg (point-min) end (point-max)
16626 msg "Creating images for buffer...%s"))
16627 ((equal subtree '(4))
16628 (org-back-to-heading)
16629 (setq beg (point) end (org-end-of-subtree t)
16630 msg "Creating images for subtree...%s"))
16632 (if (setq at (org-inside-LaTeX-fragment-p))
16633 (goto-char (max (point-min) (- (cdr at) 2)))
16634 (org-back-to-heading))
16635 (setq beg (point) end (progn (outline-next-heading) (point))
16636 msg (if at "Creating image...%s"
16637 "Creating images for entry...%s"))))
16638 (message msg "")
16639 (narrow-to-region beg end)
16640 (org-format-latex
16641 (concat "ltxpng/" (file-name-sans-extension
16642 (file-name-nondirectory
16643 buffer-file-name)))
16644 default-directory 'overlays msg at)
16645 (message msg "done. Use `C-c C-c' to remove images.")))))
16647 (defvar org-latex-regexps
16648 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16649 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16650 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16651 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
16652 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16653 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
16654 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
16655 "Regular expressions for matching embedded LaTeX.")
16657 (defun org-format-latex (prefix &optional dir overlays msg at)
16658 "Replace LaTeX fragments with links to an image, and produce images."
16659 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16660 (let* ((prefixnodir (file-name-nondirectory prefix))
16661 (absprefix (expand-file-name prefix dir))
16662 (todir (file-name-directory absprefix))
16663 (opt org-format-latex-options)
16664 (matchers (plist-get opt :matchers))
16665 (re-list org-latex-regexps)
16666 (cnt 0) txt link beg end re e checkdir
16667 m n block linkfile movefile ov)
16668 ;; Check if there are old images files with this prefix, and remove them
16669 (when (file-directory-p todir)
16670 (mapc 'delete-file
16671 (directory-files
16672 todir 'full
16673 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
16674 ;; Check the different regular expressions
16675 (while (setq e (pop re-list))
16676 (setq m (car e) re (nth 1 e) n (nth 2 e)
16677 block (if (nth 3 e) "\n\n" ""))
16678 (when (member m matchers)
16679 (goto-char (point-min))
16680 (while (re-search-forward re nil t)
16681 (when (or (not at) (equal (cdr at) (match-beginning n)))
16682 (setq txt (match-string n)
16683 beg (match-beginning n) end (match-end n)
16684 cnt (1+ cnt)
16685 linkfile (format "%s_%04d.png" prefix cnt)
16686 movefile (format "%s_%04d.png" absprefix cnt)
16687 link (concat block "[[file:" linkfile "]]" block))
16688 (if msg (message msg cnt))
16689 (goto-char beg)
16690 (unless checkdir ; make sure the directory exists
16691 (setq checkdir t)
16692 (or (file-directory-p todir) (make-directory todir)))
16693 (org-create-formula-image
16694 txt movefile opt)
16695 (if overlays
16696 (progn
16697 (setq ov (org-make-overlay beg end))
16698 (if (featurep 'xemacs)
16699 (progn
16700 (org-overlay-put ov 'invisible t)
16701 (org-overlay-put
16702 ov 'end-glyph
16703 (make-glyph (vector 'png :file movefile))))
16704 (org-overlay-put
16705 ov 'display
16706 (list 'image :type 'png :file movefile :ascent 'center)))
16707 (push ov org-latex-fragment-image-overlays)
16708 (goto-char end))
16709 (delete-region beg end)
16710 (insert link))))))))
16712 ;; This function borrows from Ganesh Swami's latex2png.el
16713 (defun org-create-formula-image (string tofile options)
16714 (let* ((tmpdir (if (featurep 'xemacs)
16715 (temp-directory)
16716 temporary-file-directory))
16717 (texfilebase (make-temp-name
16718 (expand-file-name "orgtex" tmpdir)))
16720 ;(texfilebase (make-temp-file "orgtex"))
16721 ; (dummy (delete-file texfilebase))
16722 (texfile (concat texfilebase ".tex"))
16723 (dvifile (concat texfilebase ".dvi"))
16724 (pngfile (concat texfilebase ".png"))
16725 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
16726 (fg (or (plist-get options :foreground) "Black"))
16727 (bg (or (plist-get options :background) "Transparent")))
16728 (with-temp-file texfile
16729 (insert "\\documentclass{article}
16730 \\usepackage{fullpage}
16731 \\usepackage{amssymb}
16732 \\usepackage[usenames]{color}
16733 \\usepackage{amsmath}
16734 \\usepackage{latexsym}
16735 \\usepackage[mathscr]{eucal}
16736 \\pagestyle{empty}
16737 \\begin{document}\n" string "\n\\end{document}\n"))
16738 (let ((dir default-directory))
16739 (condition-case nil
16740 (progn
16741 (cd tmpdir)
16742 (call-process "latex" nil nil nil texfile))
16743 (error nil))
16744 (cd dir))
16745 (if (not (file-exists-p dvifile))
16746 (progn (message "Failed to create dvi file from %s" texfile) nil)
16747 (call-process "dvipng" nil nil nil
16748 "-E" "-fg" fg "-bg" bg
16749 "-x" scale "-y" scale "-T" "tight"
16750 "-o" pngfile
16751 dvifile)
16752 (if (not (file-exists-p pngfile))
16753 (progn (message "Failed to create png file from %s" texfile) nil)
16754 ;; Use the requested file name and clean up
16755 (copy-file pngfile tofile 'replace)
16756 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16757 (delete-file (concat texfilebase e)))
16758 pngfile))))
16760 ;;;; Exporting
16762 ;;; Variables, constants, and parameter plists
16764 (defconst org-level-max 20)
16766 (defvar org-export-html-preamble nil
16767 "Preamble, to be inserted just after <body>. Set by publishing functions.")
16768 (defvar org-export-html-postamble nil
16769 "Preamble, to be inserted just before </body>. Set by publishing functions.")
16770 (defvar org-export-html-auto-preamble t
16771 "Should default preamble be inserted? Set by publishing functions.")
16772 (defvar org-export-html-auto-postamble t
16773 "Should default postamble be inserted? Set by publishing functions.")
16774 (defvar org-current-export-file nil) ; dynamically scoped parameter
16775 (defvar org-current-export-dir nil) ; dynamically scoped parameter
16778 (defconst org-export-plist-vars
16779 '((:language . org-export-default-language)
16780 (:customtime . org-display-custom-times)
16781 (:headline-levels . org-export-headline-levels)
16782 (:section-numbers . org-export-with-section-numbers)
16783 (:table-of-contents . org-export-with-toc)
16784 (:archived-trees . org-export-with-archived-trees)
16785 (:emphasize . org-export-with-emphasize)
16786 (:sub-superscript . org-export-with-sub-superscripts)
16787 (:TeX-macros . org-export-with-TeX-macros)
16788 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
16789 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
16790 (:fixed-width . org-export-with-fixed-width)
16791 (:timestamps . org-export-with-timestamps)
16792 (:tables . org-export-with-tables)
16793 (:table-auto-headline . org-export-highlight-first-table-line)
16794 (:style . org-export-html-style)
16795 (:convert-org-links . org-export-html-link-org-files-as-html)
16796 (:inline-images . org-export-html-inline-images)
16797 (:expand-quoted-html . org-export-html-expand)
16798 (:timestamp . org-export-html-with-timestamp)
16799 (:publishing-directory . org-export-publishing-directory)
16800 (:preamble . org-export-html-preamble)
16801 (:postamble . org-export-html-postamble)
16802 (:auto-preamble . org-export-html-auto-preamble)
16803 (:auto-postamble . org-export-html-auto-postamble)
16804 (:author . user-full-name)
16805 (:email . user-mail-address)))
16807 (defun org-default-export-plist ()
16808 "Return the property list with default settings for the export variables."
16809 (let ((l org-export-plist-vars) rtn e)
16810 (while (setq e (pop l))
16811 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
16812 rtn))
16814 (defun org-infile-export-plist ()
16815 "Return the property list with file-local settings for export."
16816 (save-excursion
16817 (goto-char 0)
16818 (let ((re (org-make-options-regexp
16819 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
16820 p key val text options)
16821 (while (re-search-forward re nil t)
16822 (setq key (org-match-string-no-properties 1)
16823 val (org-match-string-no-properties 2))
16824 (cond
16825 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
16826 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
16827 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
16828 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
16829 ((string-equal key "TEXT")
16830 (setq text (if text (concat text "\n" val) val)))
16831 ((string-equal key "OPTIONS") (setq options val))))
16832 (setq p (plist-put p :text text))
16833 (when options
16834 (let ((op '(("H" . :headline-levels)
16835 ("num" . :section-numbers)
16836 ("toc" . :table-of-contents)
16837 ("\\n" . :preserve-breaks)
16838 ("@" . :expand-quoted-html)
16839 (":" . :fixed-width)
16840 ("|" . :tables)
16841 ("^" . :sub-superscript)
16842 ("*" . :emphasize)
16843 ("TeX" . :TeX-macros)
16844 ("LaTeX" . :LaTeX-fragments)
16845 ("skip" . :skip-before-1st-heading)))
16847 (while (setq o (pop op))
16848 (if (string-match (concat (regexp-quote (car o))
16849 ":\\([^ \t\n\r;,.]*\\)")
16850 options)
16851 (setq p (plist-put p (cdr o)
16852 (car (read-from-string
16853 (match-string 1 options)))))))))
16854 p)))
16856 (defun org-export-directory (type plist)
16857 (let* ((val (plist-get plist :publishing-directory))
16858 (dir (if (listp val)
16859 (or (cdr (assoc type val)) ".")
16860 val)))
16861 dir))
16863 (defun org-skip-comments (lines)
16864 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
16865 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
16866 (re2 "^\\(\\*+\\)[ \t\n\r]")
16867 rtn line level)
16868 (while (setq line (pop lines))
16869 (cond
16870 ((and (string-match re1 line)
16871 (setq level (- (match-end 1) (match-beginning 1))))
16872 ;; Beginning of a COMMENT subtree. Skip it.
16873 (while (and (setq line (pop lines))
16874 (or (not (string-match re2 line))
16875 (> (- (match-end 1) (match-beginning 1)) level))))
16876 (setq lines (cons line lines)))
16877 ((string-match "^#" line)
16878 ;; an ordinary comment line
16880 ((and org-export-table-remove-special-lines
16881 (string-match "^[ \t]*|" line)
16882 (or (string-match "^[ \t]*| *[!_^] *|" line)
16883 (and (string-match "| *<[0-9]+> *|" line)
16884 (not (string-match "| *[^ <|]" line)))))
16885 ;; a special table line that should be removed
16887 (t (setq rtn (cons line rtn)))))
16888 (nreverse rtn)))
16890 (defun org-export (&optional arg)
16891 (interactive)
16892 (let ((help "[t] insert the export option template
16893 \[v] limit export to visible part of outline tree
16895 \[a] export as ASCII
16896 \[h] export as HTML
16897 \[H] export as HTML to temporary buffer
16898 \[b] export as HTML and browse immediately
16899 \[x] export as XOXO
16901 \[i] export current file as iCalendar file
16902 \[I] export all agenda files as iCalendar files
16903 \[c] export agenda files into combined iCalendar file
16905 \[F] publish current file
16906 \[P] publish current project
16907 \[X] publish... (project will be prompted for)
16908 \[A] publish all projects")
16909 (cmds
16910 '((?t . org-insert-export-options-template)
16911 (?v . org-export-visible)
16912 (?a . org-export-as-ascii)
16913 (?h . org-export-as-html)
16914 (?b . org-export-as-html-and-open)
16915 (?H . org-export-as-html-to-buffer)
16916 (?x . org-export-as-xoxo)
16917 (?i . org-export-icalendar-this-file)
16918 (?I . org-export-icalendar-all-agenda-files)
16919 (?c . org-export-icalendar-combine-agenda-files)
16920 (?F . org-publish-current-file)
16921 (?P . org-publish-current-project)
16922 (?X . org-publish)
16923 (?A . org-publish-all)))
16924 r1 r2 ass)
16925 (save-window-excursion
16926 (delete-other-windows)
16927 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
16928 (princ help))
16929 (message "Select command: ")
16930 (setq r1 (read-char-exclusive)))
16931 (setq r2 (if (< r1 27) (+ r1 96) r1))
16932 (if (setq ass (assq r2 cmds))
16933 (call-interactively (cdr ass))
16934 (error "No command associated with key %c" r1))))
16936 (defconst org-html-entities
16937 '(("nbsp")
16938 ("iexcl")
16939 ("cent")
16940 ("pound")
16941 ("curren")
16942 ("yen")
16943 ("brvbar")
16944 ("sect")
16945 ("uml")
16946 ("copy")
16947 ("ordf")
16948 ("laquo")
16949 ("not")
16950 ("shy")
16951 ("reg")
16952 ("macr")
16953 ("deg")
16954 ("plusmn")
16955 ("sup2")
16956 ("sup3")
16957 ("acute")
16958 ("micro")
16959 ("para")
16960 ("middot")
16961 ("odot"."o")
16962 ("star"."*")
16963 ("cedil")
16964 ("sup1")
16965 ("ordm")
16966 ("raquo")
16967 ("frac14")
16968 ("frac12")
16969 ("frac34")
16970 ("iquest")
16971 ("Agrave")
16972 ("Aacute")
16973 ("Acirc")
16974 ("Atilde")
16975 ("Auml")
16976 ("Aring") ("AA"."&Aring;")
16977 ("AElig")
16978 ("Ccedil")
16979 ("Egrave")
16980 ("Eacute")
16981 ("Ecirc")
16982 ("Euml")
16983 ("Igrave")
16984 ("Iacute")
16985 ("Icirc")
16986 ("Iuml")
16987 ("ETH")
16988 ("Ntilde")
16989 ("Ograve")
16990 ("Oacute")
16991 ("Ocirc")
16992 ("Otilde")
16993 ("Ouml")
16994 ("times")
16995 ("Oslash")
16996 ("Ugrave")
16997 ("Uacute")
16998 ("Ucirc")
16999 ("Uuml")
17000 ("Yacute")
17001 ("THORN")
17002 ("szlig")
17003 ("agrave")
17004 ("aacute")
17005 ("acirc")
17006 ("atilde")
17007 ("auml")
17008 ("aring")
17009 ("aelig")
17010 ("ccedil")
17011 ("egrave")
17012 ("eacute")
17013 ("ecirc")
17014 ("euml")
17015 ("igrave")
17016 ("iacute")
17017 ("icirc")
17018 ("iuml")
17019 ("eth")
17020 ("ntilde")
17021 ("ograve")
17022 ("oacute")
17023 ("ocirc")
17024 ("otilde")
17025 ("ouml")
17026 ("divide")
17027 ("oslash")
17028 ("ugrave")
17029 ("uacute")
17030 ("ucirc")
17031 ("uuml")
17032 ("yacute")
17033 ("thorn")
17034 ("yuml")
17035 ("fnof")
17036 ("Alpha")
17037 ("Beta")
17038 ("Gamma")
17039 ("Delta")
17040 ("Epsilon")
17041 ("Zeta")
17042 ("Eta")
17043 ("Theta")
17044 ("Iota")
17045 ("Kappa")
17046 ("Lambda")
17047 ("Mu")
17048 ("Nu")
17049 ("Xi")
17050 ("Omicron")
17051 ("Pi")
17052 ("Rho")
17053 ("Sigma")
17054 ("Tau")
17055 ("Upsilon")
17056 ("Phi")
17057 ("Chi")
17058 ("Psi")
17059 ("Omega")
17060 ("alpha")
17061 ("beta")
17062 ("gamma")
17063 ("delta")
17064 ("epsilon")
17065 ("varepsilon"."&epsilon;")
17066 ("zeta")
17067 ("eta")
17068 ("theta")
17069 ("iota")
17070 ("kappa")
17071 ("lambda")
17072 ("mu")
17073 ("nu")
17074 ("xi")
17075 ("omicron")
17076 ("pi")
17077 ("rho")
17078 ("sigmaf") ("varsigma"."&sigmaf;")
17079 ("sigma")
17080 ("tau")
17081 ("upsilon")
17082 ("phi")
17083 ("chi")
17084 ("psi")
17085 ("omega")
17086 ("thetasym") ("vartheta"."&thetasym;")
17087 ("upsih")
17088 ("piv")
17089 ("bull") ("bullet"."&bull;")
17090 ("hellip") ("dots"."&hellip;")
17091 ("prime")
17092 ("Prime")
17093 ("oline")
17094 ("frasl")
17095 ("weierp")
17096 ("image")
17097 ("real")
17098 ("trade")
17099 ("alefsym")
17100 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
17101 ("uarr") ("uparrow"."&uarr;")
17102 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
17103 ("darr")("downarrow"."&darr;")
17104 ("harr") ("leftrightarrow"."&harr;")
17105 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
17106 ("lArr") ("Leftarrow"."&lArr;")
17107 ("uArr") ("Uparrow"."&uArr;")
17108 ("rArr") ("Rightarrow"."&rArr;")
17109 ("dArr") ("Downarrow"."&dArr;")
17110 ("hArr") ("Leftrightarrow"."&hArr;")
17111 ("forall")
17112 ("part") ("partial"."&part;")
17113 ("exist") ("exists"."&exist;")
17114 ("empty") ("emptyset"."&empty;")
17115 ("nabla")
17116 ("isin") ("in"."&isin;")
17117 ("notin")
17118 ("ni")
17119 ("prod")
17120 ("sum")
17121 ("minus")
17122 ("lowast") ("ast"."&lowast;")
17123 ("radic")
17124 ("prop") ("proptp"."&prop;")
17125 ("infin") ("infty"."&infin;")
17126 ("ang") ("angle"."&ang;")
17127 ("and") ("vee"."&and;")
17128 ("or") ("wedge"."&or;")
17129 ("cap")
17130 ("cup")
17131 ("int")
17132 ("there4")
17133 ("sim")
17134 ("cong") ("simeq"."&cong;")
17135 ("asymp")("approx"."&asymp;")
17136 ("ne") ("neq"."&ne;")
17137 ("equiv")
17138 ("le")
17139 ("ge")
17140 ("sub") ("subset"."&sub;")
17141 ("sup") ("supset"."&sup;")
17142 ("nsub")
17143 ("sube")
17144 ("supe")
17145 ("oplus")
17146 ("otimes")
17147 ("perp")
17148 ("sdot") ("cdot"."&sdot;")
17149 ("lceil")
17150 ("rceil")
17151 ("lfloor")
17152 ("rfloor")
17153 ("lang")
17154 ("rang")
17155 ("loz") ("Diamond"."&loz;")
17156 ("spades") ("spadesuit"."&spades;")
17157 ("clubs") ("clubsuit"."&clubs;")
17158 ("hearts") ("diamondsuit"."&hearts;")
17159 ("diams") ("diamondsuit"."&diams;")
17160 ("quot")
17161 ("amp")
17162 ("lt")
17163 ("gt")
17164 ("OElig")
17165 ("oelig")
17166 ("Scaron")
17167 ("scaron")
17168 ("Yuml")
17169 ("circ")
17170 ("tilde")
17171 ("ensp")
17172 ("emsp")
17173 ("thinsp")
17174 ("zwnj")
17175 ("zwj")
17176 ("lrm")
17177 ("rlm")
17178 ("ndash")
17179 ("mdash")
17180 ("lsquo")
17181 ("rsquo")
17182 ("sbquo")
17183 ("ldquo")
17184 ("rdquo")
17185 ("bdquo")
17186 ("dagger")
17187 ("Dagger")
17188 ("permil")
17189 ("lsaquo")
17190 ("rsaquo")
17191 ("euro")
17193 ("arccos"."arccos")
17194 ("arcsin"."arcsin")
17195 ("arctan"."arctan")
17196 ("arg"."arg")
17197 ("cos"."cos")
17198 ("cosh"."cosh")
17199 ("cot"."cot")
17200 ("coth"."coth")
17201 ("csc"."csc")
17202 ("deg"."deg")
17203 ("det"."det")
17204 ("dim"."dim")
17205 ("exp"."exp")
17206 ("gcd"."gcd")
17207 ("hom"."hom")
17208 ("inf"."inf")
17209 ("ker"."ker")
17210 ("lg"."lg")
17211 ("lim"."lim")
17212 ("liminf"."liminf")
17213 ("limsup"."limsup")
17214 ("ln"."ln")
17215 ("log"."log")
17216 ("max"."max")
17217 ("min"."min")
17218 ("Pr"."Pr")
17219 ("sec"."sec")
17220 ("sin"."sin")
17221 ("sinh"."sinh")
17222 ("sup"."sup")
17223 ("tan"."tan")
17224 ("tanh"."tanh")
17226 "Entities for TeX->HTML translation.
17227 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
17228 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
17229 In that case, \"\\ent\" will be translated to \"&other;\".
17230 The list contains HTML entities for Latin-1, Greek and other symbols.
17231 It is supplemented by a number of commonly used TeX macros with appropriate
17232 translations. There is currently no way for users to extend this.")
17234 ;;; General functions for all backends
17236 (defun org-cleaned-string-for-export (string &rest parameters)
17237 "Cleanup a buffer substring so that links can be created safely."
17238 (interactive)
17239 (let* ((re-radio (and org-target-link-regexp
17240 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
17241 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
17242 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
17243 (re-archive (concat ":" org-archive-tag ":"))
17244 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
17245 (htmlp (plist-get parameters :for-html))
17246 (outline-regexp "\\*+")
17247 rtn p)
17248 (save-excursion
17249 (set-buffer (get-buffer-create " org-mode-tmp"))
17250 (erase-buffer)
17251 (insert string)
17252 ;; Remove license-to-kill stuff
17253 (while (setq p (text-property-any (point-min) (point-max)
17254 :org-license-to-kill t))
17255 (delete-region p (next-single-property-change p :org-license-to-kill)))
17257 (let ((org-inhibit-startup t)) (org-mode))
17258 (untabify (point-min) (point-max))
17260 ;; Get the correct stuff before the first headline
17261 (when (plist-get parameters :skip-before-1st-heading)
17262 (goto-char (point-min))
17263 (when (re-search-forward "^\\*+[ \t]" nil t)
17264 (delete-region (point-min) (match-beginning 0))
17265 (goto-char (point-min))
17266 (insert "\n")))
17267 (when (plist-get parameters :add-text)
17268 (goto-char (point-min))
17269 (insert (plist-get parameters :add-text) "\n"))
17271 ;; Get rid of archived trees
17272 (when (not (eq org-export-with-archived-trees t))
17273 (goto-char (point-min))
17274 (while (re-search-forward re-archive nil t)
17275 (if (not (org-on-heading-p t))
17276 (org-end-of-subtree t)
17277 (beginning-of-line 1)
17278 (delete-region
17279 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
17280 (org-end-of-subtree t)))))
17282 ;; Protect stuff from HTML processing
17283 (goto-char (point-min))
17284 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
17285 (add-text-properties (match-beginning 0) (match-end 0)
17286 '(org-protected t)))
17287 (when htmlp
17288 (goto-char (point-min))
17289 (while (re-search-forward "^#\\+HTML:[ \t]*\\(.*\\)" nil t)
17290 (replace-match "\\1" t)
17291 (add-text-properties
17292 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
17293 '(org-protected t))))
17294 (goto-char (point-min))
17295 (while (re-search-forward
17296 "^#\\+BEGIN_HTML\\>.*\\(\\(\n.*\\)*?\n\\)#\\+END_HTML\\>.*\n?" nil t)
17297 (if htmlp
17298 (add-text-properties (match-beginning 1) (1+ (match-end 1))
17299 '(org-protected t))
17300 (delete-region (match-beginning 0) (match-end 0))))
17301 (goto-char (point-min))
17302 (while (re-search-forward re-quote nil t)
17303 (goto-char (match-beginning 0))
17304 (end-of-line 1)
17305 (add-text-properties (point) (org-end-of-subtree t)
17306 '(org-protected t)))
17308 ;; Find targets in comments and move them out of comments,
17309 ;; but mark them as targets that should be invisible
17310 (goto-char (point-min))
17311 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
17312 (replace-match "\\1(INVISIBLE)"))
17314 ;; Remove comments
17315 (goto-char (point-min))
17316 (while (re-search-forward "^#.*\n?" nil t)
17317 (replace-match ""))
17319 ;; Find matches for radio targets and turn them into internal links
17320 (goto-char (point-min))
17321 (when re-radio
17322 (while (re-search-forward re-radio nil t)
17323 (org-if-unprotected
17324 (replace-match "\\1[[\\2]]"))))
17326 ;; Find all links that contain a newline and put them into a single line
17327 (goto-char (point-min))
17328 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
17329 (org-if-unprotected
17330 (replace-match "\\1 \\3")
17331 (goto-char (match-beginning 0))))
17333 ;; Convert LaTeX fragments to images
17334 (when (plist-get parameters :LaTeX-fragments)
17335 (org-format-latex
17336 (concat "ltxpng/" (file-name-sans-extension
17337 (file-name-nondirectory
17338 org-current-export-file)))
17339 org-current-export-dir nil "Creating LaTeX image %s"))
17340 (message "Exporting...")
17342 ;; Normalize links: Convert angle and plain links into bracket links
17343 ;; Expand link abbreviations
17344 (goto-char (point-min))
17345 (while (re-search-forward re-plain-link nil t)
17346 (org-if-unprotected
17347 (replace-match
17348 (concat
17349 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
17350 t t)))
17351 (goto-char (point-min))
17352 (while (re-search-forward re-angle-link nil t)
17353 (org-if-unprotected
17354 (replace-match
17355 (concat
17356 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
17357 t t)))
17358 (goto-char (point-min))
17359 (while (re-search-forward org-bracket-link-regexp nil t)
17360 (org-if-unprotected
17361 (replace-match
17362 (concat "[[" (save-match-data
17363 (org-link-expand-abbrev (match-string 1)))
17365 (if (match-end 3)
17366 (match-string 2)
17367 (concat "[" (match-string 1) "]"))
17368 "]")
17369 t t)))
17371 ;; Find multiline emphasis and put them into single line
17372 (when (plist-get parameters :emph-multiline)
17373 (goto-char (point-min))
17374 (while (re-search-forward org-emph-re nil t)
17375 (org-if-unprotected
17376 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
17377 (goto-char (1- (match-end 0))))))
17379 (setq rtn (buffer-string)))
17380 (kill-buffer " org-mode-tmp")
17381 rtn))
17383 (defun org-export-grab-title-from-buffer ()
17384 "Get a title for the current document, from looking at the buffer."
17385 (save-excursion
17386 (goto-char (point-min))
17387 (let ((end (save-excursion (outline-next-heading) (point))))
17388 (when (re-search-forward "^[ \t]*[^# \t\r\n].*\n" end t)
17389 ;; Mark the line so that it will not be exported as normal text.
17390 (add-text-properties (match-beginning 0) (match-end 0)
17391 (list :org-license-to-kill t))
17392 ;; Return the title string
17393 (org-trim (match-string 0))))))
17395 (defun org-solidify-link-text (s &optional alist)
17396 "Take link text and make a safe target out of it."
17397 (save-match-data
17398 (let* ((rtn
17399 (mapconcat
17400 'identity
17401 (org-split-string s "[ \t\r\n]+") "--"))
17402 (a (assoc rtn alist)))
17403 (or (cdr a) rtn))))
17405 ;; Variable holding the vector with section numbers
17406 (defvar org-section-numbers (make-vector org-level-max 0))
17408 (defun org-init-section-numbers ()
17409 "Initialize the vector for the section numbers."
17410 (let* ((level -1)
17411 (numbers (nreverse (org-split-string "" "\\.")))
17412 (depth (1- (length org-section-numbers)))
17413 (i depth) number-string)
17414 (while (>= i 0)
17415 (if (> i level)
17416 (aset org-section-numbers i 0)
17417 (setq number-string (or (car numbers) "0"))
17418 (if (string-match "\\`[A-Z]\\'" number-string)
17419 (aset org-section-numbers i
17420 (- (string-to-char number-string) ?A -1))
17421 (aset org-section-numbers i (string-to-number number-string)))
17422 (pop numbers))
17423 (setq i (1- i)))))
17425 (defun org-section-number (&optional level)
17426 "Return a string with the current section number.
17427 When LEVEL is non-nil, increase section numbers on that level."
17428 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
17429 (when level
17430 (when (> level -1)
17431 (aset org-section-numbers
17432 level (1+ (aref org-section-numbers level))))
17433 (setq idx (1+ level))
17434 (while (<= idx depth)
17435 (if (not (= idx 1))
17436 (aset org-section-numbers idx 0))
17437 (setq idx (1+ idx))))
17438 (setq idx 0)
17439 (while (<= idx depth)
17440 (setq n (aref org-section-numbers idx))
17441 (setq string (concat string (if (not (string= string "")) "." "")
17442 (int-to-string n)))
17443 (setq idx (1+ idx)))
17444 (save-match-data
17445 (if (string-match "\\`\\([@0]\\.\\)+" string)
17446 (setq string (replace-match "" t nil string)))
17447 (if (string-match "\\(\\.0\\)+\\'" string)
17448 (setq string (replace-match "" t nil string))))
17449 string))
17451 ;;; ASCII export
17453 (defvar org-last-level nil) ; dynamically scoped variable
17454 (defvar org-levels-open nil) ; dynamically scoped parameter
17455 (defvar org-ascii-current-indentation nil) ; For communication
17457 (defun org-export-as-ascii (arg)
17458 "Export the outline as a pretty ASCII file.
17459 If there is an active region, export only the region.
17460 The prefix ARG specifies how many levels of the outline should become
17461 underlined headlines. The default is 3."
17462 (interactive "P")
17463 (setq-default org-todo-line-regexp org-todo-line-regexp)
17464 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17465 (org-infile-export-plist)))
17466 (region
17467 (buffer-substring
17468 (if (org-region-active-p) (region-beginning) (point-min))
17469 (if (org-region-active-p) (region-end) (point-max))))
17470 (custom-times org-display-custom-times)
17471 (org-ascii-current-indentation '(0 . 0))
17472 (level 0) line txt
17473 (umax nil)
17474 (umax-toc nil)
17475 (case-fold-search nil)
17476 (filename (concat (file-name-as-directory
17477 (org-export-directory :ascii opt-plist))
17478 (file-name-sans-extension
17479 (file-name-nondirectory buffer-file-name))
17480 ".txt"))
17481 (buffer (find-file-noselect filename))
17482 (org-levels-open (make-vector org-level-max nil))
17483 (odd org-odd-levels-only)
17484 (date (format-time-string "%Y/%m/%d" (current-time)))
17485 (time (format-time-string "%X" (org-current-time)))
17486 (author (plist-get opt-plist :author))
17487 (title (or (plist-get opt-plist :title)
17488 (and (not
17489 (plist-get opt-plist :skip-before-1st-heading))
17490 (org-export-grab-title-from-buffer))
17491 (file-name-sans-extension
17492 (file-name-nondirectory buffer-file-name))))
17493 (email (plist-get opt-plist :email))
17494 (language (plist-get opt-plist :language))
17495 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
17496 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
17497 (todo nil)
17498 (lang-words nil)
17499 (lines (org-skip-comments
17500 (org-split-string
17501 (org-cleaned-string-for-export
17502 region
17503 :skip-before-1st-heading
17504 (plist-get opt-plist :skip-before-1st-heading)
17505 :add-text (plist-get opt-plist :text))
17506 "[\r\n]")))
17507 thetoc have-headings first-heading-pos)
17509 (remove-text-properties (point-min) (point-max) '(:org-license-to-kill t))
17511 (setq org-last-level 1)
17512 (org-init-section-numbers)
17514 (find-file-noselect filename)
17516 (setq lang-words (or (assoc language org-export-language-setup)
17517 (assoc "en" org-export-language-setup)))
17518 (switch-to-buffer-other-window buffer)
17519 (erase-buffer)
17520 (fundamental-mode)
17521 ;; create local variables for all options, to make sure all called
17522 ;; functions get the correct information
17523 (mapcar (lambda (x)
17524 (set (make-local-variable (cdr x))
17525 (plist-get opt-plist (car x))))
17526 org-export-plist-vars)
17527 (org-set-local 'org-odd-levels-only odd)
17528 (setq umax (if arg (prefix-numeric-value arg)
17529 org-export-headline-levels))
17530 (setq umax-toc (if (integerp org-export-with-toc)
17531 (min org-export-with-toc umax)
17532 umax))
17534 ;; File header
17535 (if title (org-insert-centered title ?=))
17536 (insert "\n")
17537 (if (or author email)
17538 (insert (concat (nth 1 lang-words) ": " (or author "")
17539 (if email (concat " <" email ">") "")
17540 "\n")))
17541 (if (and date time)
17542 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
17544 (insert "\n\n")
17546 (if org-export-with-toc
17547 (progn
17548 (push (concat (nth 3 lang-words) "\n") thetoc)
17549 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
17550 (mapcar '(lambda (line)
17551 (if (string-match org-todo-line-regexp
17552 line)
17553 ;; This is a headline
17554 (progn
17555 (setq have-headings t)
17556 (setq level (- (match-end 1) (match-beginning 1))
17557 level (org-tr-level level)
17558 txt (match-string 3 line)
17559 todo
17560 (or (and org-export-mark-todo-in-toc
17561 (match-beginning 2)
17562 (not (member (match-string 2 line)
17563 org-done-keywords)))
17564 ; TODO, not DONE
17565 (and org-export-mark-todo-in-toc
17566 (= level umax-toc)
17567 (org-search-todo-below
17568 line lines level))))
17569 (setq txt (org-html-expand-for-ascii txt))
17571 (if (and (memq org-export-with-tags '(not-in-toc nil))
17572 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
17573 (setq txt (replace-match "" t t txt)))
17574 (if (string-match quote-re0 txt)
17575 (setq txt (replace-match "" t t txt)))
17577 (if org-export-with-section-numbers
17578 (setq txt (concat (org-section-number level)
17579 " " txt)))
17580 (if (<= level umax-toc)
17581 (progn
17582 (push
17583 (concat
17584 (make-string (* (1- level) 4) ?\ )
17585 (format (if todo "%s (*)\n" "%s\n") txt))
17586 thetoc)
17587 (setq org-last-level level))
17588 ))))
17589 lines)
17590 (setq thetoc (if have-headings (nreverse thetoc) nil))))
17592 (org-init-section-numbers)
17593 (while (setq line (pop lines))
17594 ;; Remove the quoted HTML tags.
17595 (setq line (org-html-expand-for-ascii line))
17596 ;; Remove targets
17597 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
17598 (setq line (replace-match "" t t line)))
17599 ;; Replace internal links
17600 (while (string-match org-bracket-link-regexp line)
17601 (setq line (replace-match
17602 (if (match-end 3) "[\\3]" "[\\1]")
17603 t nil line)))
17604 (when custom-times
17605 (setq line (org-translate-time line)))
17606 (cond
17607 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
17608 ;; a Headline
17609 (setq first-heading-pos (or first-heading-pos (point)))
17610 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
17611 txt (match-string 2 line))
17612 (org-ascii-level-start level txt umax lines))
17614 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
17615 (normal-mode)
17617 ;; insert the table of contents
17618 (when thetoc
17619 (goto-char (point-min))
17620 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
17621 (progn
17622 (goto-char (match-beginning 0))
17623 (replace-match ""))
17624 (goto-char first-heading-pos))
17625 (mapc 'insert thetoc)
17626 (or (looking-at "[ \t]*\n[ \t]*\n")
17627 (insert "\n\n")))
17629 (save-buffer)
17630 ;; remove display and invisible chars
17631 (let (beg end)
17632 (goto-char (point-min))
17633 (while (setq beg (next-single-property-change (point) 'display))
17634 (setq end (next-single-property-change beg 'display))
17635 (delete-region beg end)
17636 (goto-char beg)
17637 (insert "=>"))
17638 (goto-char (point-min))
17639 (while (setq beg (next-single-property-change (point) 'org-cwidth))
17640 (setq end (next-single-property-change beg 'org-cwidth))
17641 (delete-region beg end)
17642 (goto-char beg)))
17643 (goto-char (point-min))))
17645 (defun org-search-todo-below (line lines level)
17646 "Search the subtree below LINE for any TODO entries."
17647 (let ((rest (cdr (memq line lines)))
17648 (re org-todo-line-regexp)
17649 line lv todo)
17650 (catch 'exit
17651 (while (setq line (pop rest))
17652 (if (string-match re line)
17653 (progn
17654 (setq lv (- (match-end 1) (match-beginning 1))
17655 todo (and (match-beginning 2)
17656 (not (member (match-string 2 line)
17657 org-done-keywords))))
17658 ; TODO, not DONE
17659 (if (<= lv level) (throw 'exit nil))
17660 (if todo (throw 'exit t))))))))
17662 (defun org-html-expand-for-ascii (line)
17663 "Handle quoted HTML for ASCII export."
17664 (if org-export-html-expand
17665 (while (string-match "@<[^<>\n]*>" line)
17666 ;; We just remove the tags for now.
17667 (setq line (replace-match "" nil nil line))))
17668 line)
17670 (defun org-insert-centered (s &optional underline)
17671 "Insert the string S centered and underline it with character UNDERLINE."
17672 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
17673 (insert (make-string ind ?\ ) s "\n")
17674 (if underline
17675 (insert (make-string ind ?\ )
17676 (make-string (string-width s) underline)
17677 "\n"))))
17679 (defun org-ascii-level-start (level title umax &optional lines)
17680 "Insert a new level in ASCII export."
17681 (let (char (n (- level umax 1)) (ind 0))
17682 (if (> level umax)
17683 (progn
17684 (insert (make-string (* 2 n) ?\ )
17685 (char-to-string (nth (% n (length org-export-ascii-bullets))
17686 org-export-ascii-bullets))
17687 " " title "\n")
17688 ;; find the indentation of the next non-empty line
17689 (catch 'stop
17690 (while lines
17691 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
17692 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
17693 (throw 'stop (setq ind (org-get-indentation (car lines)))))
17694 (pop lines)))
17695 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
17696 (if (or (not (equal (char-before) ?\n))
17697 (not (equal (char-before (1- (point))) ?\n)))
17698 (insert "\n"))
17699 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
17700 (unless org-export-with-tags
17701 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
17702 (setq title (replace-match "" t t title))))
17703 (if org-export-with-section-numbers
17704 (setq title (concat (org-section-number level) " " title)))
17705 (insert title "\n" (make-string (string-width title) char) "\n")
17706 (setq org-ascii-current-indentation '(0 . 0)))))
17708 (defun org-export-visible (type arg)
17709 "Create a copy of the visible part of the current buffer, and export it.
17710 The copy is created in a temporary buffer and removed after use.
17711 TYPE is the final key (as a string) that also select the export command in
17712 the `C-c C-e' export dispatcher.
17713 As a special case, if the you type SPC at the prompt, the temporary
17714 org-mode file will not be removed but presented to you so that you can
17715 continue to use it. The prefix arg ARG is passed through to the exporting
17716 command."
17717 (interactive
17718 (list (progn
17719 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H]uffer with HTML [x]OXO [ ]keep buffer")
17720 (read-char-exclusive))
17721 current-prefix-arg))
17722 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
17723 (error "Invalid export key"))
17724 (let* ((binding (cdr (assoc type
17725 '((?a . org-export-as-ascii)
17726 (?\C-a . org-export-as-ascii)
17727 (?b . org-export-as-html-and-open)
17728 (?\C-b . org-export-as-html-and-open)
17729 (?h . org-export-as-html)
17730 (?H . org-export-as-html-to-buffer)
17731 (?x . org-export-as-xoxo)))))
17732 (keepp (equal type ?\ ))
17733 (file buffer-file-name)
17734 (buffer (get-buffer-create "*Org Export Visible*"))
17735 s e)
17736 (with-current-buffer buffer (erase-buffer))
17737 (save-excursion
17738 (setq s (goto-char (point-min)))
17739 (while (not (= (point) (point-max)))
17740 (goto-char (org-find-invisible))
17741 (append-to-buffer buffer s (point))
17742 (setq s (goto-char (org-find-visible))))
17743 (goto-char (point-min))
17744 (unless keepp
17745 ;; Copy all comment lines to the end, to make sure #+ settings are
17746 ;; still available for the second export step. Kind of a hack, but
17747 ;; does do the trick.
17748 (if (looking-at "#[^\r\n]*")
17749 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
17750 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
17751 (append-to-buffer buffer (1+ (match-beginning 0))
17752 (min (point-max) (1+ (match-end 0))))))
17753 (set-buffer buffer)
17754 (let ((buffer-file-name file)
17755 (org-inhibit-startup t))
17756 (org-mode)
17757 (show-all)
17758 (unless keepp (funcall binding arg))))
17759 (if (not keepp)
17760 (kill-buffer buffer)
17761 (switch-to-buffer-other-window buffer)
17762 (goto-char (point-min)))))
17764 (defun org-find-visible ()
17765 (let ((s (point)))
17766 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17767 (get-char-property s 'invisible)))
17769 (defun org-find-invisible ()
17770 (let ((s (point)))
17771 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17772 (not (get-char-property s 'invisible))))
17775 ;;; HTML export
17777 (defun org-get-current-options ()
17778 "Return a string with current options as keyword options.
17779 Does include HTML export options as well as TODO and CATEGORY stuff."
17780 (format
17781 "#+TITLE: %s
17782 #+AUTHOR: %s
17783 #+EMAIL: %s
17784 #+LANGUAGE: %s
17785 #+TEXT: Some descriptive text to be emitted. Several lines OK.
17786 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s skip:%s
17787 #+CATEGORY: %s
17788 #+SEQ_TODO: %s
17789 #+TYP_TODO: %s
17790 #+STARTUP: %s %s %s %s %s
17791 #+TAGS: %s
17792 #+ARCHIVE: %s
17793 #+LINK: %s
17795 (buffer-name) (user-full-name) user-mail-address org-export-default-language
17796 org-export-headline-levels
17797 org-export-with-section-numbers
17798 org-export-with-toc
17799 org-export-preserve-breaks
17800 org-export-html-expand
17801 org-export-with-fixed-width
17802 org-export-with-tables
17803 org-export-with-sub-superscripts
17804 org-export-with-emphasize
17805 org-export-with-TeX-macros
17806 org-export-with-LaTeX-fragments
17807 org-export-skip-text-before-1st-heading
17808 (file-name-nondirectory buffer-file-name)
17809 "TODO FEEDBACK VERIFY DONE"
17810 "Me Jason Marie DONE"
17811 (cdr (assoc org-startup-folded
17812 '((nil . "showall") (t . "overview") (content . "content"))))
17813 (if org-odd-levels-only "odd" "oddeven")
17814 (if org-hide-leading-stars "hidestars" "showstars")
17815 (if org-startup-align-all-tables "align" "noalign")
17816 (cond ((eq t org-log-done) "logdone")
17817 ((not org-log-done) "nologging")
17818 ((listp org-log-done)
17819 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
17820 org-log-done " ")))
17821 (or (mapconcat (lambda (x)
17822 (cond
17823 ((equal '(:startgroup) x) "{")
17824 ((equal '(:endgroup) x) "}")
17825 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
17826 (t (car x))))
17827 (or org-tag-alist (org-get-buffer-tags)) " ") "")
17828 org-archive-location
17829 "org file:~/org/%s.org"
17832 (defun org-insert-export-options-template ()
17833 "Insert into the buffer a template with information for exporting."
17834 (interactive)
17835 (if (not (bolp)) (newline))
17836 (let ((s (org-get-current-options)))
17837 (and (string-match "#\\+CATEGORY" s)
17838 (setq s (substring s 0 (match-beginning 0))))
17839 (insert s)))
17841 (defun org-toggle-fixed-width-section (arg)
17842 "Toggle the fixed-width export.
17843 If there is no active region, the QUOTE keyword at the current headline is
17844 inserted or removed. When present, it causes the text between this headline
17845 and the next to be exported as fixed-width text, and unmodified.
17846 If there is an active region, this command adds or removes a colon as the
17847 first character of this line. If the first character of a line is a colon,
17848 this line is also exported in fixed-width font."
17849 (interactive "P")
17850 (let* ((cc 0)
17851 (regionp (org-region-active-p))
17852 (beg (if regionp (region-beginning) (point)))
17853 (end (if regionp (region-end)))
17854 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17855 (re "[ \t]*\\(:\\)")
17856 off)
17857 (if regionp
17858 (save-excursion
17859 (goto-char beg)
17860 (setq cc (current-column))
17861 (beginning-of-line 1)
17862 (setq off (looking-at re))
17863 (while (> nlines 0)
17864 (setq nlines (1- nlines))
17865 (beginning-of-line 1)
17866 (cond
17867 (arg
17868 (move-to-column cc t)
17869 (insert ":\n")
17870 (forward-line -1))
17871 ((and off (looking-at re))
17872 (replace-match "" t t nil 1))
17873 ((not off) (move-to-column cc t) (insert ":")))
17874 (forward-line 1)))
17875 (save-excursion
17876 (org-back-to-heading)
17877 (if (looking-at (concat outline-regexp
17878 "\\( +\\<" org-quote-string "\\>\\)"))
17879 (replace-match "" t t nil 1)
17880 (if (looking-at outline-regexp)
17881 (progn
17882 (goto-char (match-end 0))
17883 (insert " " org-quote-string))))))))
17885 (defun org-export-as-html-and-open (arg)
17886 "Export the outline as HTML and immediately open it with a browser.
17887 If there is an active region, export only the region.
17888 The prefix ARG specifies how many levels of the outline should become
17889 headlines. The default is 3. Lower levels will become bulleted lists."
17890 (interactive "P")
17891 (org-export-as-html arg 'hidden)
17892 (org-open-file buffer-file-name))
17894 (defun org-export-as-html-batch ()
17895 "Call `org-export-as-html', may be used in batch processing as
17896 emacs --batch
17897 --load=$HOME/lib/emacs/org.el
17898 --eval \"(setq org-export-headline-levels 2)\"
17899 --visit=MyFile --funcall org-export-as-html-batch"
17900 (org-export-as-html org-export-headline-levels 'hidden))
17902 (defun org-export-as-html-to-buffer (arg)
17903 "Call `org-exort-as-html` with output to a temporary buffer.
17904 No file is created. The prefix ARG is passed through to `org-export-as-html'."
17905 (interactive "P")
17906 (org-export-as-html arg nil nil t)
17907 (switch-to-buffer-other-window "*Org HTML Export*"))
17909 (defun org-export-as-html (arg &optional hidden ext-plist temp-buffer-only)
17910 "Export the outline as a pretty HTML file.
17911 If there is an active region, export only the region. The prefix
17912 ARG specifies how many levels of the outline should become
17913 headlines. The default is 3. Lower levels will become bulleted
17914 lists. When HIDDEN is non-nil, don't display the HTML buffer.
17915 EXT-PLIST is a property list with external parameters overriding
17916 org-mode's default settings, but still inferior to file-local
17917 settings. Wehn TEMP-BUFFER-ONLY is non-nil, export to a buffer not
17918 associated with a file."
17919 (interactive "P")
17920 (message "Exporting...")
17921 (setq-default org-todo-line-regexp org-todo-line-regexp)
17922 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
17923 (setq-default org-done-keywords org-done-keywords)
17924 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
17925 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17926 ext-plist
17927 (org-infile-export-plist)))
17929 (style (plist-get opt-plist :style))
17930 (link-validate (plist-get opt-plist :link-validation-function))
17931 valid thetoc have-headings first-heading-pos
17932 (odd org-odd-levels-only)
17933 (region-p (org-region-active-p))
17934 (region
17935 (buffer-substring
17936 (if region-p (region-beginning) (point-min))
17937 (if region-p (region-end) (point-max))))
17938 ;; The following two are dynamically scoped into other
17939 ;; routines below.
17940 (org-current-export-dir (org-export-directory :html opt-plist))
17941 (org-current-export-file buffer-file-name)
17942 (level 0) (line "") (origline "") txt todo
17943 (umax nil)
17944 (umax-toc nil)
17945 (filename (concat (file-name-as-directory
17946 (org-export-directory :html opt-plist))
17947 (file-name-sans-extension
17948 (file-name-nondirectory buffer-file-name))
17949 ".html"))
17950 (current-dir (file-name-directory buffer-file-name))
17951 (buffer (if temp-buffer-only
17952 (get-buffer-create "*Org HTML Export*")
17953 (find-file-noselect filename)))
17954 (org-levels-open (make-vector org-level-max nil))
17955 (date (format-time-string "%Y/%m/%d" (current-time)))
17956 (time (format-time-string "%X" (org-current-time)))
17957 (author (plist-get opt-plist :author))
17958 (title (or (plist-get opt-plist :title)
17959 (and (not
17960 (plist-get opt-plist :skip-before-1st-heading))
17961 (org-export-grab-title-from-buffer))
17962 (file-name-sans-extension
17963 (file-name-nondirectory buffer-file-name))))
17964 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
17965 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
17966 (inquote nil)
17967 (infixed nil)
17968 (in-local-list nil)
17969 (local-list-num nil)
17970 (local-list-indent nil)
17971 (llt org-plain-list-ordered-item-terminator)
17972 (email (plist-get opt-plist :email))
17973 (language (plist-get opt-plist :language))
17974 (lang-words nil)
17975 (target-alist nil) tg
17976 (head-count 0) cnt
17977 (start 0)
17978 (coding-system (and (boundp 'buffer-file-coding-system)
17979 buffer-file-coding-system))
17980 (coding-system-for-write coding-system)
17981 (save-buffer-coding-system coding-system)
17982 (charset (and coding-system
17983 (fboundp 'coding-system-get)
17984 (coding-system-get coding-system 'mime-charset)))
17985 (lines
17986 (org-skip-comments (org-split-string
17987 (org-cleaned-string-for-export
17988 region
17989 :emph-multiline t
17990 :for-html t
17991 :skip-before-1st-heading
17992 (plist-get opt-plist :skip-before-1st-heading)
17993 :add-text
17994 (plist-get opt-plist :text)
17995 :LaTeX-fragments
17996 (plist-get opt-plist :LaTeX-fragments))
17997 "[\r\n]")))
17998 table-open type
17999 table-buffer table-orig-buffer
18000 ind start-is-num starter didclose
18001 rpl path desc descp desc1 desc2 link
18004 (remove-text-properties (point-min) (point-max) '(:org-license-to-kill t))
18006 (message "Exporting...")
18008 (setq org-last-level 1)
18009 (org-init-section-numbers)
18011 ;; Get the language-dependent settings
18012 (setq lang-words (or (assoc language org-export-language-setup)
18013 (assoc "en" org-export-language-setup)))
18015 ;; Switch to the output buffer
18016 (if (or hidden t)
18017 (set-buffer buffer)
18018 (switch-to-buffer-other-window buffer))
18019 (erase-buffer)
18020 (fundamental-mode)
18021 (let ((case-fold-search nil)
18022 (org-odd-levels-only odd))
18023 ;; create local variables for all options, to make sure all called
18024 ;; functions get the correct information
18025 (mapcar (lambda (x)
18026 (set (make-local-variable (cdr x))
18027 (plist-get opt-plist (car x))))
18028 org-export-plist-vars)
18029 (setq umax (if arg (prefix-numeric-value arg)
18030 org-export-headline-levels))
18031 (setq umax-toc (if (integerp org-export-with-toc)
18032 (min org-export-with-toc umax)
18033 umax))
18034 ;; File header
18035 (insert (format
18036 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
18037 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
18038 <html xmlns=\"http://www.w3.org/1999/xhtml\"
18039 lang=\"%s\" xml:lang=\"%s\">
18040 <head>
18041 <title>%s</title>
18042 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
18043 <meta name=\"generator\" content=\"Org-mode\"/>
18044 <meta name=\"generated\" content=\"%s %s\"/>
18045 <meta name=\"author\" content=\"%s\"/>
18047 </head><body>
18049 language language (org-html-expand title) (or charset "iso-8859-1")
18050 date time author style))
18053 (insert (or (plist-get opt-plist :preamble) ""))
18055 (when (plist-get opt-plist :auto-preamble)
18056 (if title (insert (format org-export-html-title-format
18057 (org-html-expand title)))))
18059 (if org-export-with-toc
18060 (progn
18061 (push (format "<h%d>%s</h%d>\n"
18062 org-export-html-toplevel-hlevel
18063 (nth 3 lang-words)
18064 org-export-html-toplevel-hlevel)
18065 thetoc)
18066 (push "<ul>\n<li>" thetoc)
18067 (setq lines
18068 (mapcar '(lambda (line)
18069 (if (string-match org-todo-line-regexp line)
18070 ;; This is a headline
18071 (progn
18072 (setq have-headings t)
18073 (setq level (- (match-end 1) (match-beginning 1))
18074 level (org-tr-level level)
18075 txt (save-match-data
18076 (org-html-expand
18077 (org-export-cleanup-toc-line
18078 (match-string 3 line))))
18079 todo
18080 (or (and org-export-mark-todo-in-toc
18081 (match-beginning 2)
18082 (not (member (match-string 2 line)
18083 org-done-keywords)))
18084 ; TODO, not DONE
18085 (and org-export-mark-todo-in-toc
18086 (= level umax-toc)
18087 (org-search-todo-below
18088 line lines level))))
18089 (if (and (memq org-export-with-tags '(not-in-toc nil))
18090 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
18091 (setq txt (replace-match "" t t txt)))
18092 (if (string-match quote-re0 txt)
18093 (setq txt (replace-match "" t t txt)))
18094 (if org-export-with-section-numbers
18095 (setq txt (concat (org-section-number level)
18096 " " txt)))
18097 (if (<= level umax-toc)
18098 (progn
18099 (setq head-count (+ head-count 1))
18100 (if (> level org-last-level)
18101 (progn
18102 (setq cnt (- level org-last-level))
18103 (while (>= (setq cnt (1- cnt)) 0)
18104 (push "\n<ul>\n<li>" thetoc))
18105 (push "\n" thetoc)))
18106 (if (< level org-last-level)
18107 (progn
18108 (setq cnt (- org-last-level level))
18109 (while (>= (setq cnt (1- cnt)) 0)
18110 (push "</li>\n</ul>" thetoc))
18111 (push "\n" thetoc)))
18112 ;; Check for targets
18113 (while (string-match org-target-regexp line)
18114 (setq tg (match-string 1 line)
18115 line (replace-match
18116 (concat "@<span class=\"target\">" tg "@</span> ")
18117 t t line))
18118 (push (cons (org-solidify-link-text tg)
18119 (format "sec-%d" head-count))
18120 target-alist))
18121 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
18122 (setq txt (replace-match "" t t txt)))
18123 (push
18124 (format
18125 (if todo
18126 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
18127 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
18128 head-count txt) thetoc)
18130 (setq org-last-level level))
18132 line)
18133 lines))
18134 (while (> org-last-level 0)
18135 (setq org-last-level (1- org-last-level))
18136 (push "</li>\n</ul>\n" thetoc))
18137 (setq thetoc (if have-headings (nreverse thetoc) nil))))
18138 (setq head-count 0)
18139 (org-init-section-numbers)
18141 (while (setq line (pop lines) origline line)
18142 (catch 'nextline
18144 ;; end of quote section?
18145 (when (and inquote (string-match "^\\*+" line))
18146 (insert "</pre>\n")
18147 (setq inquote nil))
18148 ;; inside a quote section?
18149 (when inquote
18150 (insert (org-html-protect line) "\n")
18151 (throw 'nextline nil))
18153 ;; verbatim lines
18154 (when (and org-export-with-fixed-width
18155 (string-match "^[ \t]*:\\(.*\\)" line))
18156 (when (not infixed)
18157 (setq infixed t)
18158 (insert "<pre>\n"))
18159 (insert (org-html-protect (match-string 1 line)) "\n")
18160 (when (and lines
18161 (not (string-match "^[ \t]*\\(:.*\\)"
18162 (car lines))))
18163 (setq infixed nil)
18164 (insert "</pre>\n"))
18165 (throw 'nextline nil))
18167 ;; Protected HTML
18168 (when (get-text-property 0 'org-protected line)
18169 (let (par)
18170 (when (re-search-backward
18171 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
18172 (setq par (match-string 1))
18173 (replace-match "\\2\n"))
18174 (insert line "\n")
18175 (while (and lines
18176 (get-text-property 0 'org-protected (car lines)))
18177 (insert (pop lines) "\n"))
18178 (and par (insert "<p>\n")))
18179 (throw 'nextline nil))
18181 ;; Horizontal line
18182 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
18183 (insert "\n<hr/>\n")
18184 (throw 'nextline nil))
18186 ;; make targets to anchors
18187 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
18188 (cond
18189 ((match-end 2)
18190 (setq line (replace-match
18191 (concat "@<a name=\""
18192 (org-solidify-link-text (match-string 1 line))
18193 "\">\\nbsp@</a>")
18194 t t line)))
18195 ((and org-export-with-toc (equal (string-to-char line) ?*))
18196 (setq line (replace-match
18197 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
18198 ; (concat "@<i>" (match-string 1 line) "@</i> ")
18199 t t line)))
18201 (setq line (replace-match
18202 (concat "@<a name=\""
18203 (org-solidify-link-text (match-string 1 line))
18204 "\" class=\"target\">" (match-string 1 line) "@</a> ")
18205 t t line)))))
18207 (setq line (org-html-handle-time-stamps line))
18209 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
18210 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
18211 ;; Also handle sub_superscripts and checkboxes
18212 (setq line (org-html-expand line))
18214 ;; Format the links
18215 (setq start 0)
18216 (while (string-match org-bracket-link-analytic-regexp line start)
18217 (setq start (match-beginning 0))
18218 (setq type (if (match-end 2) (match-string 2 line) "internal"))
18219 (setq path (match-string 3 line))
18220 (setq desc1 (if (match-end 5) (match-string 5 line))
18221 desc2 (if (match-end 2) (concat type ":" path) path)
18222 descp (and desc1 (not (equal desc1 desc2)))
18223 desc (or desc1 desc2))
18224 ;; Make an image out of the description if that is so wanted
18225 (when (and descp (org-file-image-p desc))
18226 (save-match-data
18227 (if (string-match "^file:" desc)
18228 (setq desc (substring desc (match-end 0)))))
18229 (setq desc (concat "<img src=\"" desc "\"/>")))
18230 ;; FIXME: do we need to unescape here somewhere?
18231 (cond
18232 ((equal type "internal")
18233 (setq rpl
18234 (concat
18235 "<a href=\"#"
18236 (org-solidify-link-text path target-alist)
18237 "\">" desc "</a>")))
18238 ((member type '("http" "https")) ; FIXME: need to test this.
18239 ;; standard URL, just check if we need to inline an image
18240 (if (and (or (eq t org-export-html-inline-images)
18241 (and org-export-html-inline-images (not descp)))
18242 (org-file-image-p path))
18243 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
18244 (setq link (concat type ":" path))
18245 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
18246 ((member type '("ftp" "mailto" "news"))
18247 ;; standard URL
18248 (setq link (concat type ":" path))
18249 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
18250 ((string= type "file")
18251 ;; FILE link
18252 (let* ((filename path)
18253 (abs-p (file-name-absolute-p filename))
18254 thefile file-is-image-p search)
18255 (save-match-data
18256 (if (string-match "::\\(.*\\)" filename)
18257 (setq search (match-string 1 filename)
18258 filename (replace-match "" t nil filename)))
18259 (setq valid
18260 (if (functionp link-validate)
18261 (funcall link-validate filename current-dir)
18263 (setq file-is-image-p (org-file-image-p filename))
18264 (setq thefile (if abs-p (expand-file-name filename) filename))
18265 (when (and org-export-html-link-org-files-as-html
18266 (string-match "\\.org$" thefile))
18267 (setq thefile (concat (substring thefile 0
18268 (match-beginning 0))
18269 ".html"))
18270 (if (and search
18271 ;; make sure this is can be used as target search
18272 (not (string-match "^[0-9]*$" search))
18273 (not (string-match "^\\*" search))
18274 (not (string-match "^/.*/$" search)))
18275 (setq thefile (concat thefile "#"
18276 (org-solidify-link-text
18277 (org-link-unescape search)))))
18278 (when (string-match "^file:" desc)
18279 (setq desc (replace-match "" t t desc))
18280 (if (string-match "\\.org$" desc)
18281 (setq desc (replace-match "" t t desc))))))
18282 (setq rpl (if (and file-is-image-p
18283 (or (eq t org-export-html-inline-images)
18284 (and org-export-html-inline-images
18285 (not descp))))
18286 (concat "<img src=\"" thefile "\"/>")
18287 (concat "<a href=\"" thefile "\">" desc "</a>")))
18288 (if (not valid) (setq rpl desc))))
18289 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
18290 (setq rpl (concat "<i>&lt;" type ":"
18291 (save-match-data (org-link-unescape path))
18292 "&gt;</i>"))))
18293 (setq line (replace-match rpl t t line)
18294 start (+ start (length rpl))))
18295 ;; TODO items
18296 (if (and (string-match org-todo-line-regexp line)
18297 (match-beginning 2))
18298 (if (member (match-string 2 line) org-done-keywords)
18299 (setq line (replace-match
18300 "<span class=\"done\">\\2</span>"
18301 t nil line 2))
18302 (setq line (replace-match "<span class=\"todo\">\\2</span>"
18303 t nil line 2))))
18305 (cond
18306 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
18307 ;; This is a headline
18308 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
18309 txt (match-string 2 line))
18310 (if (string-match quote-re0 txt)
18311 (setq txt (replace-match "" t t txt)))
18312 (if (<= level umax) (setq head-count (+ head-count 1)))
18313 (when in-local-list
18314 ;; Close any local lists before inserting a new header line
18315 (while local-list-num
18316 (org-close-li)
18317 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
18318 (pop local-list-num))
18319 (setq local-list-indent nil
18320 in-local-list nil))
18321 (setq first-heading-pos (or first-heading-pos (point)))
18322 (org-html-level-start level txt umax
18323 (and org-export-with-toc (<= level umax))
18324 head-count)
18325 ;; QUOTES
18326 (when (string-match quote-re line)
18327 (insert "<pre>")
18328 (setq inquote t)))
18330 ((and org-export-with-tables
18331 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
18332 (if (not table-open)
18333 ;; New table starts
18334 (setq table-open t table-buffer nil table-orig-buffer nil))
18335 ;; Accumulate lines
18336 (setq table-buffer (cons line table-buffer)
18337 table-orig-buffer (cons origline table-orig-buffer))
18338 (when (or (not lines)
18339 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
18340 (car lines))))
18341 (setq table-open nil
18342 table-buffer (nreverse table-buffer)
18343 table-orig-buffer (nreverse table-orig-buffer))
18344 (org-close-par-maybe)
18345 (insert (org-format-table-html table-buffer table-orig-buffer))))
18347 ;; Normal lines
18348 (when (string-match
18349 (cond
18350 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
18351 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
18352 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
18353 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
18354 line)
18355 (setq ind (org-get-string-indentation line)
18356 start-is-num (match-beginning 4)
18357 starter (if (match-beginning 2)
18358 (substring (match-string 2 line) 0 -1))
18359 line (substring line (match-beginning 5)))
18360 (unless (string-match "[^ \t]" line)
18361 ;; empty line. Pretend indentation is large.
18362 (setq ind (if org-empty-line-terminates-plain-lists
18364 (1+ (or (car local-list-indent) 1)))))
18365 (setq didclose nil)
18366 (while (and in-local-list
18367 (or (and (= ind (car local-list-indent))
18368 (not starter))
18369 (< ind (car local-list-indent))))
18370 (setq didclose t)
18371 (org-close-li)
18372 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
18373 (pop local-list-num) (pop local-list-indent)
18374 (setq in-local-list local-list-indent))
18375 (cond
18376 ((and starter
18377 (or (not in-local-list)
18378 (> ind (car local-list-indent))))
18379 ;; Start new (level of) list
18380 (org-close-par-maybe)
18381 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
18382 (push start-is-num local-list-num)
18383 (push ind local-list-indent)
18384 (setq in-local-list t))
18385 (starter
18386 ;; continue current list
18387 (org-close-li)
18388 (insert "<li>\n"))
18389 (didclose
18390 ;; we did close a list, normal text follows: need <p>
18391 (org-open-par)))
18392 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
18393 (setq line
18394 (replace-match
18395 (if (equal (match-string 1 line) "X")
18396 "<b>[X]</b>"
18397 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
18398 t t line))))
18400 ;; Empty lines start a new paragraph. If hand-formatted lists
18401 ;; are not fully interpreted, lines starting with "-", "+", "*"
18402 ;; also start a new paragraph.
18403 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
18405 ;; Check if the line break needs to be conserved
18406 (cond
18407 ((string-match "\\\\\\\\[ \t]*$" line)
18408 (setq line (replace-match "<br/>" t t line)))
18409 (org-export-preserve-breaks
18410 (setq line (concat line "<br/>"))))
18412 (insert line "\n")))))
18414 ;; Properly close all local lists and other lists
18415 (when inquote (insert "</pre>\n"))
18416 (when in-local-list
18417 ;; Close any local lists before inserting a new header line
18418 (while local-list-num
18419 (org-close-li)
18420 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
18421 (pop local-list-num))
18422 (setq local-list-indent nil
18423 in-local-list nil))
18424 (org-html-level-start 1 nil umax
18425 (and org-export-with-toc (<= level umax))
18426 head-count)
18428 (when (plist-get opt-plist :auto-postamble)
18429 (when author
18430 (insert "<p class=\"author\"> "
18431 (nth 1 lang-words) ": " author "\n")
18432 (when email
18433 (insert "<a href=\"mailto:" email "\">&lt;"
18434 email "&gt;</a>\n"))
18435 (insert "</p>\n"))
18436 (when (and date time)
18437 (insert "<p class=\"date\"> "
18438 (nth 2 lang-words) ": "
18439 date " " time "</p>\n")))
18441 (if org-export-html-with-timestamp
18442 (insert org-export-html-html-helper-timestamp))
18443 (insert (or (plist-get opt-plist :postamble) ""))
18444 (insert "</body>\n</html>\n")
18445 (normal-mode)
18446 ;; insert the table of contents
18447 (goto-char (point-min))
18448 (when thetoc
18449 (if (or (re-search-forward
18450 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
18451 (re-search-forward
18452 "\\[TABLE-OF-CONTENTS\\]" nil t))
18453 (progn
18454 (goto-char (match-beginning 0))
18455 (replace-match ""))
18456 (goto-char first-heading-pos)
18457 (when (looking-at "\\s-*</p>")
18458 (goto-char (match-end 0))
18459 (insert "\n")))
18460 (mapc 'insert thetoc))
18461 ;; remove empty paragraphs and lists
18462 (goto-char (point-min))
18463 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
18464 (replace-match ""))
18465 (goto-char (point-min))
18466 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
18467 (replace-match ""))
18468 (or temp-buffer-only (save-buffer))
18469 (goto-char (point-min))
18470 (message "Exporting... done"))))
18472 (defun org-format-table-html (lines olines)
18473 "Find out which HTML converter to use and return the HTML code."
18474 (if (string-match "^[ \t]*|" (car lines))
18475 ;; A normal org table
18476 (org-format-org-table-html lines)
18477 ;; Table made by table.el - test for spanning
18478 (let* ((hlines (delq nil (mapcar
18479 (lambda (x)
18480 (if (string-match "^[ \t]*\\+-" x) x
18481 nil))
18482 lines)))
18483 (first (car hlines))
18484 (ll (and (string-match "\\S-+" first)
18485 (match-string 0 first)))
18486 (re (concat "^[ \t]*" (regexp-quote ll)))
18487 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
18488 hlines))))
18489 (if (and (not spanning)
18490 (not org-export-prefer-native-exporter-for-tables))
18491 ;; We can use my own converter with HTML conversions
18492 (org-format-table-table-html lines)
18493 ;; Need to use the code generator in table.el, with the original text.
18494 (org-format-table-table-html-using-table-generate-source olines)))))
18496 (defun org-format-org-table-html (lines &optional splice)
18497 "Format a table into HTML."
18498 ;; Get rid of hlines at beginning and end
18499 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
18500 (setq lines (nreverse lines))
18501 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
18502 (setq lines (nreverse lines))
18503 (when org-export-table-remove-special-lines
18504 ;; Check if the table has a marking column. If yes remove the
18505 ;; column and the special lines
18506 (setq lines (org-table-clean-before-export lines)))
18508 (let ((head (and org-export-highlight-first-table-line
18509 (delq nil (mapcar
18510 (lambda (x) (string-match "^[ \t]*|-" x))
18511 (cdr lines)))))
18512 (nlines 0) fnum i
18513 tbopen line fields html)
18514 (if splice (setq head nil))
18515 (unless splice (push (if head "<thead>" "<tbody>") html))
18516 (setq tbopen t)
18517 (while (setq line (pop lines))
18518 (catch 'next-line
18519 (if (string-match "^[ \t]*|-" line)
18520 (progn
18521 (unless splice
18522 (push (if head "</thead>" "</tbody>") html)
18523 (if lines (push "<tbody>" html) (setq tbopen nil)))
18524 (setq head nil) ;; head ends here, first time around
18525 ;; ignore this line
18526 (throw 'next-line t)))
18527 ;; Break the line into fields
18528 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
18529 (unless fnum (setq fnum (make-vector (length fields) 0)))
18530 (setq nlines (1+ nlines) i -1)
18531 (push (concat "<tr>"
18532 (mapconcat
18533 (lambda (x)
18534 (setq i (1+ i))
18535 (if (and (< i nlines)
18536 (string-match org-table-number-regexp x))
18537 (incf (aref fnum i)))
18538 (if head
18539 (concat "<th>" x "</th>")
18540 (concat "<td>" x "</td>")))
18541 fields "")
18542 "</tr>")
18543 html)))
18544 (unless splice (if tbopen (push "</tbody>" html)))
18545 (unless splice (push "</table>\n" html))
18546 (setq html (nreverse html))
18547 (unless splice
18548 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
18549 (push (mapconcat
18550 (lambda (x)
18551 (format "<COL align=\"%s\">"
18552 (if (> (/ (float x) nlines) org-table-number-fraction)
18553 "right" "left")))
18554 fnum "")
18555 html)
18556 (push org-export-html-table-tag html))
18557 (concat (mapconcat 'identity html "\n") "\n")))
18559 (defun org-table-clean-before-export (lines)
18560 "Check if the table has a marking column.
18561 If yes remove the column and the special lines."
18562 (if (memq nil
18563 (mapcar
18564 (lambda (x) (or (string-match "^[ \t]*|-" x)
18565 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
18566 lines))
18567 (progn
18568 (setq org-table-clean-did-remove-column-1 nil)
18569 lines)
18570 (setq org-table-clean-did-remove-column-1 t)
18571 (delq nil
18572 (mapcar
18573 (lambda (x) (if (string-match "^[ \t]*| *[!_^/] *|" x)
18574 nil ; ignore this line
18575 (and (or (string-match "^[ \t]*|-+\\+" x)
18576 (string-match "^[ \t]*|[^|]*|" x))
18577 (replace-match "|" t t x))))
18578 lines))))
18580 (defun org-format-table-table-html (lines)
18581 "Format a table generated by table.el into HTML.
18582 This conversion does *not* use `table-generate-source' from table.el.
18583 This has the advantage that Org-mode's HTML conversions can be used.
18584 But it has the disadvantage, that no cell- or row-spanning is allowed."
18585 (let (line field-buffer
18586 (head org-export-highlight-first-table-line)
18587 fields html empty)
18588 (setq html (concat org-export-html-table-tag "\n"))
18589 (while (setq line (pop lines))
18590 (setq empty "&nbsp;")
18591 (catch 'next-line
18592 (if (string-match "^[ \t]*\\+-" line)
18593 (progn
18594 (if field-buffer
18595 (progn
18596 (setq html (concat
18597 html
18598 "<tr>"
18599 (mapconcat
18600 (lambda (x)
18601 (if (equal x "") (setq x empty))
18602 (if head
18603 (concat "<th>" x "</th>\n")
18604 (concat "<td>" x "</td>\n")))
18605 field-buffer "\n")
18606 "</tr>\n"))
18607 (setq head nil)
18608 (setq field-buffer nil)))
18609 ;; Ignore this line
18610 (throw 'next-line t)))
18611 ;; Break the line into fields and store the fields
18612 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
18613 (if field-buffer
18614 (setq field-buffer (mapcar
18615 (lambda (x)
18616 (concat x "<br/>" (pop fields)))
18617 field-buffer))
18618 (setq field-buffer fields))))
18619 (setq html (concat html "</table>\n"))
18620 html))
18622 (defun org-format-table-table-html-using-table-generate-source (lines)
18623 "Format a table into html, using `table-generate-source' from table.el.
18624 This has the advantage that cell- or row-spanning is allowed.
18625 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
18626 (require 'table)
18627 (with-current-buffer (get-buffer-create " org-tmp1 ")
18628 (erase-buffer)
18629 (insert (mapconcat 'identity lines "\n"))
18630 (goto-char (point-min))
18631 (if (not (re-search-forward "|[^+]" nil t))
18632 (error "Error processing table"))
18633 (table-recognize-table)
18634 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
18635 (table-generate-source 'html " org-tmp2 ")
18636 (set-buffer " org-tmp2 ")
18637 (buffer-substring (point-min) (point-max))))
18639 (defun org-html-handle-time-stamps (s)
18640 "Format time stamps in string S, or remove them."
18641 (catch 'exit
18642 (let (r b)
18643 (while (string-match org-maybe-keyword-time-regexp s)
18644 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
18645 ;; never export CLOCK
18646 (throw 'exit ""))
18647 (or b (setq b (substring s 0 (match-beginning 0))))
18648 (if (not org-export-with-timestamps)
18649 (setq r (concat r (substring s 0 (match-beginning 0)))
18650 s (substring s (match-end 0)))
18651 (setq r (concat
18652 r (substring s 0 (match-beginning 0))
18653 (if (match-end 1)
18654 (format "@<span class=\"timestamp-kwd\">%s @</span>"
18655 (match-string 1 s)))
18656 (format " @<span class=\"timestamp\">%s@</span>"
18657 (substring
18658 (org-translate-time (match-string 3 s)) 1 -1)))
18659 s (substring s (match-end 0)))))
18660 ;; Line break if line started and ended with time stamp stuff
18661 (if (not r)
18663 (setq r (concat r s))
18664 (unless (string-match "\\S-" (concat b s))
18665 (setq r (concat r "@<br/>")))
18666 r))))
18668 (defun org-html-protect (s)
18669 ;; convert & to &amp;, < to &lt; and > to &gt;
18670 (let ((start 0))
18671 (while (string-match "&" s start)
18672 (setq s (replace-match "&amp;" t t s)
18673 start (1+ (match-beginning 0))))
18674 (while (string-match "<" s)
18675 (setq s (replace-match "&lt;" t t s)))
18676 (while (string-match ">" s)
18677 (setq s (replace-match "&gt;" t t s))))
18680 (defun org-export-cleanup-toc-line (s)
18681 "Remove tags and time staps from lines going into the toc."
18682 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
18683 (setq s (replace-match "" t t s)))
18684 (when org-export-remove-timestamps-from-toc
18685 (while (string-match org-maybe-keyword-time-regexp s)
18686 (setq s (replace-match "" t t s))))
18689 (defun org-html-expand (string)
18690 "Prepare STRING for HTML export. Applies all active conversions.
18691 If there are links in the string, don't modify these."
18692 (let* (m s l res)
18693 (while (setq m (string-match org-bracket-link-regexp string))
18694 (setq s (substring string 0 m)
18695 l (match-string 0 string)
18696 string (substring string (match-end 0)))
18697 (push (org-html-do-expand s) res)
18698 (push l res))
18699 (push (org-html-do-expand string) res)
18700 (apply 'concat (nreverse res))))
18702 (defun org-html-do-expand (s)
18703 "Apply all active conversions to translate special ASCII to HTML."
18704 (setq s (org-html-protect s))
18705 (if org-export-html-expand
18706 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
18707 (setq s (replace-match "<\\1>" t nil s))))
18708 (if org-export-with-emphasize
18709 (setq s (org-export-html-convert-emphasize s)))
18710 (if org-export-with-sub-superscripts
18711 (setq s (org-export-html-convert-sub-super s)))
18712 (if org-export-with-TeX-macros
18713 (let ((start 0) wd ass)
18714 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
18715 (setq wd (match-string 1 s))
18716 (if (setq ass (assoc wd org-html-entities))
18717 (setq s (replace-match (or (cdr ass)
18718 (concat "&" (car ass) ";"))
18719 t t s))
18720 (setq start (+ start (length wd)))))))
18723 (defun org-create-multibrace-regexp (left right n)
18724 "Create a regular expression which will match a balanced sexp.
18725 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
18726 as single character strings.
18727 The regexp returned will match the entire expression including the
18728 delimiters. It will also define a single group which contains the
18729 match except for the outermost delimiters. The maximum depth of
18730 stacked delimiters is N. Escaping delimiters is not possible."
18731 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
18732 (or "\\|")
18733 (re nothing)
18734 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
18735 (while (> n 1)
18736 (setq n (1- n)
18737 re (concat re or next)
18738 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
18739 (concat left "\\(" re "\\)" right)))
18741 (defvar org-match-substring-regexp
18742 (concat
18743 "\\([^\\]\\)\\([_^]\\)\\("
18744 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
18745 "\\|"
18746 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
18747 "\\|"
18748 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
18749 "The regular expression matching a sub- or superscript.")
18751 (defun org-export-html-convert-sub-super (string)
18752 "Convert sub- and superscripts in STRING to HTML."
18753 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
18754 (while (string-match org-match-substring-regexp string s)
18755 (if (and requireb (match-end 8))
18756 (setq s (match-end 2))
18757 (setq s (match-end 1)
18758 key (if (string= (match-string 2 string) "_") "sub" "sup")
18759 c (or (match-string 8 string)
18760 (match-string 6 string)
18761 (match-string 5 string))
18762 string (replace-match
18763 (concat (match-string 1 string)
18764 "<" key ">" c "</" key ">")
18765 t t string)))
18766 (while (string-match "\\\\\\([_^]\\)" string)
18767 (setq string (replace-match (match-string 1 string) t t string))))
18768 string))
18770 (defun org-export-html-convert-emphasize (string)
18771 "Apply emphasis."
18772 (while (string-match org-emph-re string)
18773 (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)))
18774 string)
18776 (defvar org-par-open nil)
18777 (defun org-open-par ()
18778 "Insert <p>, but first close previous paragraph if any."
18779 (org-close-par-maybe)
18780 (insert "\n<p>")
18781 (setq org-par-open t))
18782 (defun org-close-par-maybe ()
18783 "Close paragraph if there is one open."
18784 (when org-par-open
18785 (insert "</p>")
18786 (setq org-par-open nil)))
18787 (defun org-close-li ()
18788 "Close <li> if necessary."
18789 (org-close-par-maybe)
18790 (insert "</li>\n"))
18792 (defun org-html-level-start (level title umax with-toc head-count)
18793 "Insert a new level in HTML export.
18794 When TITLE is nil, just close all open levels."
18795 (org-close-par-maybe)
18796 (let ((l (1+ (max level umax))))
18797 (while (<= l org-level-max)
18798 (if (aref org-levels-open (1- l))
18799 (progn
18800 (org-html-level-close l)
18801 (aset org-levels-open (1- l) nil)))
18802 (setq l (1+ l)))
18803 (when title
18804 ;; If title is nil, this means this function is called to close
18805 ;; all levels, so the rest is done only if title is given
18806 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
18807 (setq title (replace-match
18808 (if org-export-with-tags
18809 (save-match-data
18810 (concat
18811 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
18812 (mapconcat 'identity (org-split-string
18813 (match-string 1 title) ":")
18814 "&nbsp;")
18815 "</span>"))
18817 t t title)))
18818 (if (> level umax)
18819 (progn
18820 (if (aref org-levels-open (1- level))
18821 (progn
18822 (org-close-li)
18823 (insert "<li>" title "<br/>\n"))
18824 (aset org-levels-open (1- level) t)
18825 (org-close-par-maybe)
18826 (insert "<ul>\n<li>" title "<br/>\n")))
18827 (if org-export-with-section-numbers
18828 (setq title (concat (org-section-number level) " " title)))
18829 (setq level (+ level org-export-html-toplevel-hlevel -1))
18830 (if with-toc
18831 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
18832 level head-count title level))
18833 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
18834 (org-open-par)))))
18836 (defun org-html-level-close (&rest args)
18837 "Terminate one level in HTML export."
18838 (org-close-li)
18839 (insert "</ul>\n"))
18841 ;;; iCalendar export
18843 ;;;###autoload
18844 (defun org-export-icalendar-this-file ()
18845 "Export current file as an iCalendar file.
18846 The iCalendar file will be located in the same directory as the Org-mode
18847 file, but with extension `.ics'."
18848 (interactive)
18849 (org-export-icalendar nil buffer-file-name))
18851 ;;;###autoload
18852 (defun org-export-icalendar-all-agenda-files ()
18853 "Export all files in `org-agenda-files' to iCalendar .ics files.
18854 Each iCalendar file will be located in the same directory as the Org-mode
18855 file, but with extension `.ics'."
18856 (interactive)
18857 (apply 'org-export-icalendar nil (org-agenda-files t)))
18859 ;;;###autoload
18860 (defun org-export-icalendar-combine-agenda-files ()
18861 "Export all files in `org-agenda-files' to a single combined iCalendar file.
18862 The file is stored under the name `org-combined-agenda-icalendar-file'."
18863 (interactive)
18864 (apply 'org-export-icalendar t (org-agenda-files t)))
18866 (defun org-export-icalendar (combine &rest files)
18867 "Create iCalendar files for all elements of FILES.
18868 If COMBINE is non-nil, combine all calendar entries into a single large
18869 file and store it under the name `org-combined-agenda-icalendar-file'."
18870 (save-excursion
18871 (let* ((dir (org-export-directory
18872 :ical (list :publishing-directory
18873 org-export-publishing-directory)))
18874 file ical-file ical-buffer category started org-agenda-new-buffers)
18876 (when combine
18877 (setq ical-file
18878 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
18879 org-combined-agenda-icalendar-file
18880 (expand-file-name org-combined-agenda-icalendar-file dir))
18881 ical-buffer (org-get-agenda-file-buffer ical-file))
18882 (set-buffer ical-buffer) (erase-buffer))
18883 (while (setq file (pop files))
18884 (catch 'nextfile
18885 (org-check-agenda-file file)
18886 (set-buffer (org-get-agenda-file-buffer file))
18887 (unless combine
18888 (setq ical-file (concat (file-name-as-directory dir)
18889 (file-name-sans-extension
18890 (file-name-nondirectory buffer-file-name))
18891 ".ics"))
18892 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
18893 (with-current-buffer ical-buffer (erase-buffer)))
18894 (setq category (or org-category
18895 (file-name-sans-extension
18896 (file-name-nondirectory buffer-file-name))))
18897 (if (symbolp category) (setq category (symbol-name category)))
18898 (let ((standard-output ical-buffer))
18899 (if combine
18900 (and (not started) (setq started t)
18901 (org-start-icalendar-file org-icalendar-combined-name))
18902 (org-start-icalendar-file category))
18903 (org-print-icalendar-entries combine)
18904 (when (or (and combine (not files)) (not combine))
18905 (org-finish-icalendar-file)
18906 (set-buffer ical-buffer)
18907 (save-buffer)
18908 (run-hooks 'org-after-save-iCalendar-file-hook)))))
18909 (org-release-buffers org-agenda-new-buffers))))
18911 (defvar org-after-save-iCalendar-file-hook nil
18912 "Hook run after an iCalendar file has been saved.
18913 The iCalendar buffer is still current when this hook is run.
18914 A good way to use this is to tell a desktop calenndar application to re-read
18915 the iCalendar file.")
18917 (defun org-print-icalendar-entries (&optional combine)
18918 "Print iCalendar entries for the current Org-mode file to `standard-output'.
18919 When COMBINE is non nil, add the category to each line."
18920 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
18921 (org-category-table (org-get-category-table))
18922 (dts (org-ical-ts-to-string
18923 (format-time-string (cdr org-time-stamp-formats) (current-time))
18924 "DTSTART"))
18925 hd ts ts2 state status (inc t) pos
18926 scheduledp deadlinep tmp pri category)
18927 (save-excursion
18928 (goto-char (point-min))
18929 (while (re-search-forward org-ts-regexp nil t)
18930 (setq pos (match-beginning 0)
18931 ts (match-string 0)
18932 inc t
18933 hd (org-get-heading)
18934 category (org-get-category))
18935 (if (looking-at re2)
18936 (progn
18937 (goto-char (match-end 0))
18938 (setq ts2 (match-string 1) inc nil))
18939 (setq ts2 ts
18940 tmp (buffer-substring (max (point-min)
18941 (- pos org-ds-keyword-length))
18942 pos)
18943 deadlinep (string-match org-deadline-regexp tmp)
18944 scheduledp (string-match org-scheduled-regexp tmp)
18945 ;; donep (org-entry-is-done-p)
18947 (if (or (string-match org-tr-regexp hd)
18948 (string-match org-ts-regexp hd))
18949 (setq hd (replace-match "" t t hd)))
18950 (if (string-match org-bracket-link-regexp hd)
18951 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
18952 (match-string 1 hd))
18953 t t hd)))
18954 (if deadlinep (setq hd (concat "DL: " hd)))
18955 (if scheduledp (setq hd (concat "S: " hd)))
18956 (princ (format "BEGIN:VEVENT
18959 SUMMARY:%s
18960 CATEGORIES:%s
18961 END:VEVENT\n"
18962 (org-ical-ts-to-string ts "DTSTART")
18963 (org-ical-ts-to-string ts2 "DTEND" inc)
18964 hd category)))
18965 (when org-icalendar-include-todo
18966 (goto-char (point-min))
18967 (while (re-search-forward org-todo-line-regexp nil t)
18968 (setq state (match-string 2))
18969 (setq status (if (member state org-done-keywords)
18970 "COMPLETED" "NEEDS-ACTION"))
18971 (when (and state
18972 (or (not (member state org-done-keywords))
18973 (eq org-icalendar-include-todo 'all)))
18974 (setq hd (match-string 3))
18975 (if (string-match org-bracket-link-regexp hd)
18976 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
18977 (match-string 1 hd))
18978 t t hd)))
18979 (if (string-match org-priority-regexp hd)
18980 (setq pri (string-to-char (match-string 2 hd))
18981 hd (concat (substring hd 0 (match-beginning 1))
18982 (substring hd (match-end 1))))
18983 (setq pri org-default-priority))
18984 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
18985 (- org-lowest-priority ?A))))))
18987 (princ (format "BEGIN:VTODO
18989 SUMMARY:%s
18990 CATEGORIES:%s
18991 SEQUENCE:1
18992 PRIORITY:%d
18993 STATUS:%s
18994 END:VTODO\n"
18995 dts hd category pri status))))))))
18997 (defun org-start-icalendar-file (name)
18998 "Start an iCalendar file by inserting the header."
18999 (let ((user user-full-name)
19000 (name (or name "unknown"))
19001 (timezone (cadr (current-time-zone))))
19002 (princ
19003 (format "BEGIN:VCALENDAR
19004 VERSION:2.0
19005 X-WR-CALNAME:%s
19006 PRODID:-//%s//Emacs with Org-mode//EN
19007 X-WR-TIMEZONE:%s
19008 CALSCALE:GREGORIAN\n" name user timezone))))
19010 (defun org-finish-icalendar-file ()
19011 "Finish an iCalendar file by inserting the END statement."
19012 (princ "END:VCALENDAR\n"))
19014 (defun org-ical-ts-to-string (s keyword &optional inc)
19015 "Take a time string S and convert it to iCalendar format.
19016 KEYWORD is added in front, to make a complete line like DTSTART....
19017 When INC is non-nil, increase the hour by two (if time string contains
19018 a time), or the day by one (if it does not contain a time)."
19019 (let ((t1 (org-parse-time-string s 'nodefault))
19020 t2 fmt have-time time)
19021 (if (and (car t1) (nth 1 t1) (nth 2 t1))
19022 (setq t2 t1 have-time t)
19023 (setq t2 (org-parse-time-string s)))
19024 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
19025 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
19026 (when inc
19027 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
19028 (setq time (encode-time s mi h d m y)))
19029 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
19030 (concat keyword (format-time-string fmt time))))
19032 ;;; XOXO export
19034 (defun org-export-as-xoxo-insert-into (buffer &rest output)
19035 (with-current-buffer buffer
19036 (apply 'insert output)))
19037 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
19039 (defun org-export-as-xoxo (&optional buffer)
19040 "Export the org buffer as XOXO.
19041 The XOXO buffer is named *xoxo-<source buffer name>*"
19042 (interactive (list (current-buffer)))
19043 ;; A quickie abstraction
19045 ;; Output everything as XOXO
19046 (with-current-buffer (get-buffer buffer)
19047 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
19048 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
19049 (org-infile-export-plist)))
19050 (filename (concat (file-name-as-directory
19051 (org-export-directory :xoxo opt-plist))
19052 (file-name-sans-extension
19053 (file-name-nondirectory buffer-file-name))
19054 ".html"))
19055 (out (find-file-noselect filename))
19056 (last-level 1)
19057 (hanging-li nil))
19058 ;; Check the output buffer is empty.
19059 (with-current-buffer out (erase-buffer))
19060 ;; Kick off the output
19061 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
19062 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
19063 (let* ((hd (match-string-no-properties 1))
19064 (level (length hd))
19065 (text (concat
19066 (match-string-no-properties 2)
19067 (save-excursion
19068 (goto-char (match-end 0))
19069 (let ((str ""))
19070 (catch 'loop
19071 (while 't
19072 (forward-line)
19073 (if (looking-at "^[ \t]\\(.*\\)")
19074 (setq str (concat str (match-string-no-properties 1)))
19075 (throw 'loop str)))))))))
19077 ;; Handle level rendering
19078 (cond
19079 ((> level last-level)
19080 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
19082 ((< level last-level)
19083 (dotimes (- (- last-level level) 1)
19084 (if hanging-li
19085 (org-export-as-xoxo-insert-into out "</li>\n"))
19086 (org-export-as-xoxo-insert-into out "</ol>\n"))
19087 (when hanging-li
19088 (org-export-as-xoxo-insert-into out "</li>\n")
19089 (setq hanging-li nil)))
19091 ((equal level last-level)
19092 (if hanging-li
19093 (org-export-as-xoxo-insert-into out "</li>\n")))
19096 (setq last-level level)
19098 ;; And output the new li
19099 (setq hanging-li 't)
19100 (if (equal ?+ (elt text 0))
19101 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
19102 (org-export-as-xoxo-insert-into out "<li>" text))))
19104 ;; Finally finish off the ol
19105 (dotimes (- last-level 1)
19106 (if hanging-li
19107 (org-export-as-xoxo-insert-into out "</li>\n"))
19108 (org-export-as-xoxo-insert-into out "</ol>\n"))
19110 ;; Finish the buffer off and clean it up.
19111 (switch-to-buffer-other-window out)
19112 (indent-region (point-min) (point-max) nil)
19113 (save-buffer)
19114 (goto-char (point-min))
19118 ;;;; Key bindings
19120 ;; Make `C-c C-x' a prefix key
19121 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
19123 ;; TAB key with modifiers
19124 (define-key org-mode-map "\C-i" 'org-cycle)
19125 (define-key org-mode-map [(tab)] 'org-cycle)
19126 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
19127 (define-key org-mode-map [(meta tab)] 'org-complete)
19128 (define-key org-mode-map "\M-\t" 'org-complete)
19129 (define-key org-mode-map "\M-\C-i" 'org-complete)
19130 ;; The following line is necessary under Suse GNU/Linux
19131 (unless (featurep 'xemacs)
19132 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
19133 (define-key org-mode-map [(shift tab)] 'org-shifttab)
19135 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
19136 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19137 (define-key org-mode-map [(meta return)] 'org-meta-return)
19139 ;; Cursor keys with modifiers
19140 (define-key org-mode-map [(meta left)] 'org-metaleft)
19141 (define-key org-mode-map [(meta right)] 'org-metaright)
19142 (define-key org-mode-map [(meta up)] 'org-metaup)
19143 (define-key org-mode-map [(meta down)] 'org-metadown)
19145 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19146 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
19147 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
19148 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
19150 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
19151 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
19152 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
19153 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
19155 (define-key org-mode-map [(control shift right)] 'org-shiftcontrolright)
19156 (define-key org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19158 ;;; Extra keys for tty access.
19159 ;; We only set them when really needed because otherwise the
19160 ;; menus don't show the simple keys
19162 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19163 (not window-system))
19164 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19165 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19166 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return)
19167 (define-key org-mode-map [?\e (return)] 'org-meta-return)
19168 (define-key org-mode-map [?\e (left)] 'org-metaleft)
19169 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft)
19170 (define-key org-mode-map [?\e (right)] 'org-metaright)
19171 (define-key org-mode-map "\C-c\C-xr" 'org-metaright)
19172 (define-key org-mode-map [?\e (up)] 'org-metaup)
19173 (define-key org-mode-map "\C-c\C-xu" 'org-metaup)
19174 (define-key org-mode-map [?\e (down)] 'org-metadown)
19175 (define-key org-mode-map "\C-c\C-xd" 'org-metadown)
19176 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19177 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19178 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19179 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19180 (define-key org-mode-map [?\C-c (up)] 'org-shiftup)
19181 (define-key org-mode-map [?\C-c (down)] 'org-shiftdown)
19182 (define-key org-mode-map [?\C-c (left)] 'org-shiftleft)
19183 (define-key org-mode-map [?\C-c (right)] 'org-shiftright)
19184 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19185 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
19187 ;; All the other keys
19189 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19190 (define-key org-mode-map "\C-c\C-r" 'org-reveal)
19191 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
19192 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
19193 (define-key org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19194 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
19195 (define-key org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19196 (define-key org-mode-map "\C-c\C-j" 'org-goto)
19197 (define-key org-mode-map "\C-c\C-t" 'org-todo)
19198 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
19199 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
19200 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
19201 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
19202 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
19203 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
19204 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
19205 (define-key org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19206 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
19207 (define-key org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19208 (define-key org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19209 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
19210 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
19211 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
19212 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
19213 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
19214 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19215 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19216 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19217 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19218 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
19219 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
19220 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19221 (define-key org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19222 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
19223 (define-key org-mode-map "\C-c]" 'org-remove-file)
19224 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
19225 (define-key org-mode-map "\C-c^" 'org-sort)
19226 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19227 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
19228 (define-key org-mode-map "\C-m" 'org-return)
19229 (define-key org-mode-map "\C-c?" 'org-table-field-info)
19230 (define-key org-mode-map "\C-c " 'org-table-blank-field)
19231 (define-key org-mode-map "\C-c+" 'org-table-sum)
19232 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
19233 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
19234 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
19235 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19236 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
19237 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19238 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
19239 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
19240 (define-key org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19241 (define-key org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19242 (define-key org-mode-map "\C-c\C-e" 'org-export)
19243 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19245 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
19246 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19247 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19248 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19250 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19251 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19252 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19253 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
19254 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19255 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19256 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19257 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19258 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19260 (when (featurep 'xemacs)
19261 (define-key org-mode-map 'button3 'popup-mode-menu))
19263 (defsubst org-table-p () (org-at-table-p))
19265 (defun org-self-insert-command (N)
19266 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19267 If the cursor is in a table looking at whitespace, the whitespace is
19268 overwritten, and the table is not marked as requiring realignment."
19269 (interactive "p")
19270 (if (and (org-table-p)
19271 (progn
19272 ;; check if we blank the field, and if that triggers align
19273 (and org-table-auto-blank-field
19274 (member last-command
19275 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19276 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19277 ;; got extra space, this field does not determine column width
19278 (let (org-table-may-need-update) (org-table-blank-field))
19279 ;; no extra space, this field may determine column width
19280 (org-table-blank-field)))
19282 (eq N 1)
19283 (looking-at "[^|\n]* |"))
19284 (let (org-table-may-need-update)
19285 (goto-char (1- (match-end 0)))
19286 (delete-backward-char 1)
19287 (goto-char (match-beginning 0))
19288 (self-insert-command N))
19289 (setq org-table-may-need-update t)
19290 (self-insert-command N)))
19292 (defun org-delete-backward-char (N)
19293 "Like `delete-backward-char', insert whitespace at field end in tables.
19294 When deleting backwards, in tables this function will insert whitespace in
19295 front of the next \"|\" separator, to keep the table aligned. The table will
19296 still be marked for re-alignment if the field did fill the entire column,
19297 because, in this case the deletion might narrow the column."
19298 (interactive "p")
19299 (if (and (org-table-p)
19300 (eq N 1)
19301 (string-match "|" (buffer-substring (point-at-bol) (point)))
19302 (looking-at ".*?|"))
19303 (let ((pos (point))
19304 (noalign (looking-at "[^|\n\r]* |"))
19305 (c org-table-may-need-update))
19306 (backward-delete-char N)
19307 (skip-chars-forward "^|")
19308 (insert " ")
19309 (goto-char (1- pos))
19310 ;; noalign: if there were two spaces at the end, this field
19311 ;; does not determine the width of the column.
19312 (if noalign (setq org-table-may-need-update c)))
19313 (backward-delete-char N)))
19315 (defun org-delete-char (N)
19316 "Like `delete-char', but insert whitespace at field end in tables.
19317 When deleting characters, in tables this function will insert whitespace in
19318 front of the next \"|\" separator, to keep the table aligned. The table will
19319 still be marked for re-alignment if the field did fill the entire column,
19320 because, in this case the deletion might narrow the column."
19321 (interactive "p")
19322 (if (and (org-table-p)
19323 (not (bolp))
19324 (not (= (char-after) ?|))
19325 (eq N 1))
19326 (if (looking-at ".*?|")
19327 (let ((pos (point))
19328 (noalign (looking-at "[^|\n\r]* |"))
19329 (c org-table-may-need-update))
19330 (replace-match (concat
19331 (substring (match-string 0) 1 -1)
19332 " |"))
19333 (goto-char pos)
19334 ;; noalign: if there were two spaces at the end, this field
19335 ;; does not determine the width of the column.
19336 (if noalign (setq org-table-may-need-update c)))
19337 (delete-char N))
19338 (delete-char N)))
19340 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19341 (put 'org-self-insert-command 'delete-selection t)
19342 (put 'orgtbl-self-insert-command 'delete-selection t)
19343 (put 'org-delete-char 'delete-selection 'supersede)
19344 (put 'org-delete-backward-char 'delete-selection 'supersede)
19346 ;; Make `flyspell-mode' delay after some commands
19347 (put 'org-self-insert-command 'flyspell-delayed t)
19348 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19349 (put 'org-delete-char 'flyspell-delayed t)
19350 (put 'org-delete-backward-char 'flyspell-delayed t)
19352 ;; How to do this: Measure non-white length of current string
19353 ;; If equal to column width, we should realign.
19355 (defun org-remap (map &rest commands)
19356 "In MAP, remap the functions given in COMMANDS.
19357 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19358 (let (new old)
19359 (while commands
19360 (setq old (pop commands) new (pop commands))
19361 (if (fboundp 'command-remapping)
19362 (define-key map (vector 'remap old) new)
19363 (substitute-key-definition old new map global-map)))))
19365 (when (eq org-enable-table-editor 'optimized)
19366 ;; If the user wants maximum table support, we need to hijack
19367 ;; some standard editing functions
19368 (org-remap org-mode-map
19369 'self-insert-command 'org-self-insert-command
19370 'delete-char 'org-delete-char
19371 'delete-backward-char 'org-delete-backward-char)
19372 (define-key org-mode-map "|" 'org-force-self-insert))
19374 (defun org-shiftcursor-error ()
19375 "Throw an error because Shift-Cursor command was applied in wrong context."
19376 (error "This command is active in special context like tables, headlines or timestamps"))
19378 (defun org-shifttab (&optional arg)
19379 "Global visibility cycling or move to previous table field.
19380 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19381 on context.
19382 See the individual commands for more information."
19383 (interactive "P")
19384 (cond
19385 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19386 (arg (message "Content view to level: ")
19387 (org-content (prefix-numeric-value arg))
19388 (setq org-cycle-global-status 'overview))
19389 (t (call-interactively 'org-global-cycle))))
19391 (defun org-shiftmetaleft ()
19392 "Promote subtree or delete table column.
19393 Calls `org-promote-subtree', `org-outdent-item',
19394 or `org-table-delete-column', depending on context.
19395 See the individual commands for more information."
19396 (interactive)
19397 (cond
19398 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19399 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
19400 ((org-at-item-p) (call-interactively 'org-outdent-item))
19401 (t (org-shiftcursor-error))))
19403 (defun org-shiftmetaright ()
19404 "Demote subtree or insert table column.
19405 Calls `org-demote-subtree', `org-indent-item',
19406 or `org-table-insert-column', depending on context.
19407 See the individual commands for more information."
19408 (interactive)
19409 (cond
19410 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19411 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
19412 ((org-at-item-p) (call-interactively 'org-indent-item))
19413 (t (org-shiftcursor-error))))
19415 (defun org-shiftmetaup (&optional arg)
19416 "Move subtree up or kill table row.
19417 Calls `org-move-subtree-up' or `org-table-kill-row' or
19418 `org-move-item-up' depending on context. See the individual commands
19419 for more information."
19420 (interactive "P")
19421 (cond
19422 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19423 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
19424 ((org-at-item-p) (call-interactively 'org-move-item-up))
19425 (t (org-shiftcursor-error))))
19426 (defun org-shiftmetadown (&optional arg)
19427 "Move subtree down or insert table row.
19428 Calls `org-move-subtree-down' or `org-table-insert-row' or
19429 `org-move-item-down', depending on context. See the individual
19430 commands for more information."
19431 (interactive "P")
19432 (cond
19433 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19434 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
19435 ((org-at-item-p) (call-interactively 'org-move-item-down))
19436 (t (org-shiftcursor-error))))
19438 (defun org-metaleft (&optional arg)
19439 "Promote heading or move table column to left.
19440 Calls `org-do-promote' or `org-table-move-column', depending on context.
19441 With no specific context, calls the Emacs default `backward-word'.
19442 See the individual commands for more information."
19443 (interactive "P")
19444 (cond
19445 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19446 ((or (org-on-heading-p) (org-region-active-p))
19447 (call-interactively 'org-do-promote))
19448 ((org-at-item-p) (call-interactively 'org-outdent-item))
19449 (t (call-interactively 'backward-word))))
19451 (defun org-metaright (&optional arg)
19452 "Demote subtree or move table column to right.
19453 Calls `org-do-demote' or `org-table-move-column', depending on context.
19454 With no specific context, calls the Emacs default `forward-word'.
19455 See the individual commands for more information."
19456 (interactive "P")
19457 (cond
19458 ((org-at-table-p) (call-interactively 'org-table-move-column))
19459 ((or (org-on-heading-p) (org-region-active-p))
19460 (call-interactively 'org-do-demote))
19461 ((org-at-item-p) (call-interactively 'org-indent-item))
19462 (t (call-interactively 'forward-word))))
19464 (defun org-metaup (&optional arg)
19465 "Move subtree up or move table row up.
19466 Calls `org-move-subtree-up' or `org-table-move-row' or
19467 `org-move-item-up', depending on context. See the individual commands
19468 for more information."
19469 (interactive "P")
19470 (cond
19471 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19472 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
19473 ((org-at-item-p) (call-interactively 'org-move-item-up))
19474 (t (org-shiftcursor-error))))
19476 (defun org-metadown (&optional arg)
19477 "Move subtree down or move table row down.
19478 Calls `org-move-subtree-down' or `org-table-move-row' or
19479 `org-move-item-down', depending on context. See the individual
19480 commands for more information."
19481 (interactive "P")
19482 (cond
19483 ((org-at-table-p) (call-interactively 'org-table-move-row))
19484 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
19485 ((org-at-item-p) (call-interactively 'org-move-item-down))
19486 (t (org-shiftcursor-error))))
19488 (defun org-shiftup (&optional arg)
19489 "Increase item in timestamp or increase priority of current headline.
19490 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19491 depending on context. See the individual commands for more information."
19492 (interactive "P")
19493 (cond
19494 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
19495 ((org-on-heading-p) (call-interactively 'org-priority-up))
19496 ((org-at-item-p) (call-interactively 'org-previous-item))
19497 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
19499 (defun org-shiftdown (&optional arg)
19500 "Decrease item in timestamp or decrease priority of current headline.
19501 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19502 depending on context. See the individual commands for more information."
19503 (interactive "P")
19504 (cond
19505 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
19506 ((org-on-heading-p) (call-interactively 'org-priority-down))
19507 (t (call-interactively 'org-next-item))))
19509 (defun org-shiftright ()
19510 "Next TODO keyword or timestamp one day later, depending on context."
19511 (interactive)
19512 (cond
19513 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19514 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
19515 (t (org-shiftcursor-error))))
19517 (defun org-shiftleft ()
19518 "Previous TODO keyword or timestamp one day earlier, depending on context."
19519 (interactive)
19520 (cond
19521 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19522 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
19523 (t (org-shiftcursor-error))))
19525 (defun org-shiftcontrolright ()
19526 "Switch to next TODO set."
19527 (interactive)
19528 (cond
19529 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
19530 (t (org-shiftcursor-error))))
19532 (defun org-shiftcontrolleft ()
19533 "Switch to previous TODO set."
19534 (interactive)
19535 (cond
19536 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
19537 (t (org-shiftcursor-error))))
19539 (defun org-ctrl-c-ret ()
19540 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19541 (interactive)
19542 (cond
19543 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19544 (t (call-interactively 'org-insert-heading))))
19546 (defun org-copy-special ()
19547 "Copy region in table or copy current subtree.
19548 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19549 See the individual commands for more information."
19550 (interactive)
19551 (call-interactively
19552 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19554 (defun org-cut-special ()
19555 "Cut region in table or cut current subtree.
19556 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19557 See the individual commands for more information."
19558 (interactive)
19559 (call-interactively
19560 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19562 (defun org-paste-special (arg)
19563 "Paste rectangular region into table, or past subtree relative to level.
19564 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19565 See the individual commands for more information."
19566 (interactive "P")
19567 (if (org-at-table-p)
19568 (org-table-paste-rectangle)
19569 (org-paste-subtree arg)))
19571 (defun org-ctrl-c-ctrl-c (&optional arg)
19572 "Set tags in headline, or update according to changed information at point.
19574 This command does many different things, depending on context:
19576 - If the cursor is in a headline, prompt for tags and insert them
19577 into the current line, aligned to `org-tags-column'. When called
19578 with prefix arg, realign all tags in the current buffer.
19580 - If the cursor is in one of the special #+KEYWORD lines, this
19581 triggers scanning the buffer for these lines and updating the
19582 information.
19584 - If the cursor is inside a table, realign the table. This command
19585 works even if the automatic table editor has been turned off.
19587 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19588 the entire table.
19590 - If the cursor is inside a table created by the table.el package,
19591 activate that table.
19593 - If the current buffer is a remember buffer, close note and file it.
19594 with a prefix argument, file it without further interaction to the default
19595 location.
19597 - If the cursor is on a <<<target>>>, update radio targets and corresponding
19598 links in this buffer.
19600 - If the cursor is on a numbered item in a plain list, renumber the
19601 ordered list."
19602 (interactive "P")
19603 (let ((org-enable-table-editor t))
19604 (cond
19605 ((or org-clock-overlays
19606 org-occur-highlights
19607 org-latex-fragment-image-overlays)
19608 (org-remove-clock-overlays)
19609 (org-remove-occur-highlights)
19610 (org-remove-latex-fragment-image-overlays)
19611 (message "Temporary highlights/overlays removed from current buffer"))
19612 ((and (local-variable-p 'org-finish-function (current-buffer))
19613 (fboundp org-finish-function))
19614 (funcall org-finish-function))
19615 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
19616 ((org-on-heading-p) (call-interactively 'org-set-tags))
19617 ((org-at-table.el-p)
19618 (require 'table)
19619 (beginning-of-line 1)
19620 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
19621 (call-interactively 'table-recognize-table))
19622 ((org-at-table-p)
19623 (org-table-maybe-eval-formula)
19624 (if arg
19625 (call-interactively 'org-table-recalculate)
19626 (org-table-maybe-recalculate-line))
19627 (call-interactively 'org-table-align))
19628 ((org-at-item-checkbox-p)
19629 (call-interactively 'org-toggle-checkbox))
19630 ((org-at-item-p)
19631 (call-interactively 'org-renumber-ordered-list))
19632 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
19633 (cond
19634 ((equal (match-string 1) "TBLFM")
19635 ;; Recalculate the table before this line
19636 (save-excursion
19637 (beginning-of-line 1)
19638 (skip-chars-backward " \r\n\t")
19639 (if (org-at-table-p)
19640 (org-call-with-arg 'org-table-recalculate t))))
19642 (call-interactively 'org-mode-restart))))
19643 (t (error "C-c C-c can do nothing useful at this location.")))))
19645 (defun org-mode-restart ()
19646 "Restart Org-mode, to scan again for special lines.
19647 Also updates the keyword regular expressions."
19648 (interactive)
19649 (let ((org-inhibit-startup t)) (org-mode))
19650 (message "Org-mode restarted to refresh keyword and special line setup"))
19652 (defun org-return ()
19653 "Goto next table row or insert a newline.
19654 Calls `org-table-next-row' or `newline', depending on context.
19655 See the individual commands for more information."
19656 (interactive)
19657 (cond
19658 ((org-at-table-p)
19659 (org-table-justify-field-maybe)
19660 (call-interactively 'org-table-next-row))
19661 (t (newline))))
19663 (defun org-meta-return (&optional arg)
19664 "Insert a new heading or wrap a region in a table.
19665 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19666 See the individual commands for more information."
19667 (interactive "P")
19668 (cond
19669 ((org-at-table-p)
19670 (call-interactively 'org-table-wrap-region))
19671 (t (call-interactively 'org-insert-heading))))
19673 ;;; Menu entries
19675 ;; Define the Org-mode menus
19676 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19677 '("Tbl"
19678 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
19679 ["Next Field" org-cycle (org-at-table-p)]
19680 ["Previous Field" org-shifttab (org-at-table-p)]
19681 ["Next Row" org-return (org-at-table-p)]
19682 "--"
19683 ["Blank Field" org-table-blank-field (org-at-table-p)]
19684 ["Edit Field" org-table-edit-field (org-at-table-p)]
19685 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19686 "--"
19687 ("Column"
19688 ["Move Column Left" org-metaleft (org-at-table-p)]
19689 ["Move Column Right" org-metaright (org-at-table-p)]
19690 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19691 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19692 ("Row"
19693 ["Move Row Up" org-metaup (org-at-table-p)]
19694 ["Move Row Down" org-metadown (org-at-table-p)]
19695 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19696 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19697 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19698 "--"
19699 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
19700 ("Rectangle"
19701 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19702 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19703 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19704 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19705 "--"
19706 ("Calculate"
19707 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19708 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19709 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
19710 "--"
19711 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19712 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19713 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19714 "--"
19715 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19716 "--"
19717 ["Sum Column/Rectangle" org-table-sum
19718 (or (org-at-table-p) (org-region-active-p))]
19719 ["Which Column?" org-table-current-column (org-at-table-p)])
19720 ["Debug Formulas"
19721 org-table-toggle-formula-debugger
19722 :style toggle :selected org-table-formula-debug]
19723 ["Show Col/Row Numbers"
19724 org-table-toggle-coordinate-overlays
19725 :style toggle :selected org-table-overlay-coordinates]
19726 "--"
19727 ["Create" org-table-create (and (not (org-at-table-p))
19728 org-enable-table-editor)]
19729 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19730 ["Import from File" org-table-import (not (org-at-table-p))]
19731 ["Export to File" org-table-export (org-at-table-p)]
19732 "--"
19733 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19735 (easy-menu-define org-org-menu org-mode-map "Org menu"
19736 '("Org"
19737 ("Show/Hide"
19738 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
19739 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
19740 ["Sparse Tree" org-occur t]
19741 ["Reveal Context" org-reveal t]
19742 ["Show All" show-all t]
19743 "--"
19744 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19745 "--"
19746 ["New Heading" org-insert-heading t]
19747 ("Navigate Headings"
19748 ["Up" outline-up-heading t]
19749 ["Next" outline-next-visible-heading t]
19750 ["Previous" outline-previous-visible-heading t]
19751 ["Next Same Level" outline-forward-same-level t]
19752 ["Previous Same Level" outline-backward-same-level t]
19753 "--"
19754 ["Jump" org-goto t])
19755 ("Edit Structure"
19756 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19757 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19758 "--"
19759 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19760 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19761 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19762 "--"
19763 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19764 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19765 ["Demote Heading" org-metaright (not (org-at-table-p))]
19766 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19767 "--"
19768 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19769 "--"
19770 ["Convert to odd levels" org-convert-to-odd-levels t]
19771 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19772 ("Archive"
19773 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19774 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
19775 ; :active t :keys "C-u C-c C-x C-a"]
19776 ["Sparse trees open ARCHIVE trees"
19777 (setq org-sparse-tree-open-archived-trees
19778 (not org-sparse-tree-open-archived-trees))
19779 :style toggle :selected org-sparse-tree-open-archived-trees]
19780 ["Cycling opens ARCHIVE trees"
19781 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
19782 :style toggle :selected org-cycle-open-archived-trees]
19783 ["Agenda includes ARCHIVE trees"
19784 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
19785 :style toggle :selected (not org-agenda-skip-archived-trees)]
19786 "--"
19787 ["Move Subtree to Archive" org-advertized-archive-subtree t]
19788 ; ["Check and Move Children" (org-archive-subtree '(4))
19789 ; :active t :keys "C-u C-c C-x C-s"]
19791 "--"
19792 ("TODO Lists"
19793 ["TODO/DONE/-" org-todo t]
19794 ("Select keyword"
19795 ["Next keyword" org-shiftright (org-on-heading-p)]
19796 ["Previous keyword" org-shiftleft (org-on-heading-p)]
19797 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
19798 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
19799 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
19800 ["Show TODO Tree" org-show-todo-tree t]
19801 ["Global TODO list" org-todo-list t]
19802 "--"
19803 ["Set Priority" org-priority t]
19804 ["Priority Up" org-shiftup t]
19805 ["Priority Down" org-shiftdown t]
19806 "--"
19807 ;; FIXME: why is this still here????
19808 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
19809 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
19810 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
19811 ; (or (org-on-heading-p) (org-at-item-p))]
19812 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
19813 ; (or (org-on-heading-p) (org-at-item-p))]
19814 ; ["Update Statistics" org-update-checkbox-count t]
19816 ("Dates and Scheduling"
19817 ["Timestamp" org-time-stamp t]
19818 ["Timestamp (inactive)" org-time-stamp-inactive t]
19819 ("Change Date"
19820 ["1 Day Later" org-shiftright t]
19821 ["1 Day Earlier" org-shiftleft t]
19822 ["1 ... Later" org-shiftup t]
19823 ["1 ... Earlier" org-shiftdown t])
19824 ["Compute Time Range" org-evaluate-time-range t]
19825 ["Schedule Item" org-schedule t]
19826 ["Deadline" org-deadline t]
19827 "--"
19828 ["Custom time format" org-toggle-time-stamp-overlays
19829 :style radio :selected org-display-custom-times]
19830 "--"
19831 ["Goto Calendar" org-goto-calendar t]
19832 ["Date from Calendar" org-date-from-calendar t])
19833 ("Logging work"
19834 ["Clock in" org-clock-in t]
19835 ["Clock out" org-clock-out t]
19836 ["Clock cancel" org-clock-cancel t]
19837 ["Display times" org-clock-display t]
19838 ["Create clock table" org-clock-report t]
19839 "--"
19840 ["Record DONE time"
19841 (progn (setq org-log-done (not org-log-done))
19842 (message "Switching to %s will %s record a timestamp"
19843 (car org-done-keywords)
19844 (if org-log-done "automatically" "not")))
19845 :style toggle :selected org-log-done])
19846 "--"
19847 ["Agenda Command..." org-agenda t]
19848 ("File List for Agenda")
19849 ("Special views current file"
19850 ["TODO Tree" org-show-todo-tree t]
19851 ["Check Deadlines" org-check-deadlines t]
19852 ["Timeline" org-timeline t]
19853 ["Tags Tree" org-tags-sparse-tree t])
19854 "--"
19855 ("Hyperlinks"
19856 ["Store Link (Global)" org-store-link t]
19857 ["Insert Link" org-insert-link t]
19858 ["Follow Link" org-open-at-point t]
19859 "--"
19860 ["Next link" org-next-link t]
19861 ["Previous link" org-previous-link t]
19862 "--"
19863 ["Descriptive Links"
19864 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
19865 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
19866 ["Literal Links"
19867 (progn
19868 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
19869 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
19870 "--"
19871 ["Export/Publish..." org-export t]
19872 ("LaTeX"
19873 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19874 :selected org-cdlatex-mode]
19875 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19876 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19877 ["Modify math symbol" org-cdlatex-math-modify
19878 (org-inside-LaTeX-fragment-p)]
19879 ["Export LaTeX fragments as images"
19880 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
19881 :style toggle :selected org-export-with-LaTeX-fragments])
19882 "--"
19883 ("Documentation"
19884 ["Show Version" org-version t]
19885 ["Info Documentation" org-info t])
19886 ("Customize"
19887 ["Browse Org Group" org-customize t]
19888 "--"
19889 ["Expand This Menu" org-create-customize-menu
19890 (fboundp 'customize-menu-create)])
19891 "--"
19892 ["Refresh setup" org-mode-restart t]
19895 (defun org-info (&optional node)
19896 "Read documentation for Org-mode in the info system.
19897 With optional NODE, go directly to that node."
19898 (interactive)
19899 (require 'info)
19900 (Info-goto-node (format "(org)%s" (or node ""))))
19902 (defun org-install-agenda-files-menu ()
19903 (let ((bl (buffer-list)))
19904 (save-excursion
19905 (while bl
19906 (set-buffer (pop bl))
19907 (if (org-mode-p) (setq bl nil)))
19908 (when (org-mode-p)
19909 (easy-menu-change
19910 '("Org") "File List for Agenda"
19911 (append
19912 (list
19913 ["Edit File List" (org-edit-agenda-file-list) t]
19914 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19915 ["Remove Current File from List" org-remove-file t]
19916 ["Cycle through agenda files" org-cycle-agenda-files t]
19917 "--")
19918 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19920 ;;;; Documentation
19922 (defun org-customize ()
19923 "Call the customize function with org as argument."
19924 (interactive)
19925 (customize-browse 'org))
19927 (defun org-create-customize-menu ()
19928 "Create a full customization menu for Org-mode, insert it into the menu."
19929 (interactive)
19930 (if (fboundp 'customize-menu-create)
19931 (progn
19932 (easy-menu-change
19933 '("Org") "Customize"
19934 `(["Browse Org group" org-customize t]
19935 "--"
19936 ,(customize-menu-create 'org)
19937 ["Set" Custom-set t]
19938 ["Save" Custom-save t]
19939 ["Reset to Current" Custom-reset-current t]
19940 ["Reset to Saved" Custom-reset-saved t]
19941 ["Reset to Standard Settings" Custom-reset-standard t]))
19942 (message "\"Org\"-menu now contains full customization menu"))
19943 (error "Cannot expand menu (outdated version of cus-edit.el)")))
19945 ;;;; Miscellaneous stuff
19948 ;;; Generally useful functions
19950 (defun org-context ()
19951 "Return a list of contexts of the current cursor position.
19952 If several contexts apply, all are returned.
19953 Each context entry is a list with a symbol naming the context, and
19954 two positions indicating start and end of the context. Possible
19955 contexts are:
19957 :headline anywhere in a headline
19958 :headline-stars on the leading stars in a headline
19959 :todo-keyword on a TODO keyword (including DONE) in a headline
19960 :tags on the TAGS in a headline
19961 :priority on the priority cookie in a headline
19962 :item on the first line of a plain list item
19963 :item-bullet on the bullet/number of a plain list item
19964 :checkbox on the checkbox in a plain list item
19965 :table in an org-mode table
19966 :table-special on a special filed in a table
19967 :table-table in a table.el table
19968 :link on a hyperlink
19969 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
19970 :target on a <<target>>
19971 :radio-target on a <<<radio-target>>>
19972 :latex-fragment on a LaTeX fragment
19973 :latex-preview on a LaTeX fragment with overlayed preview image
19975 This function expects the position to be visible because it uses font-lock
19976 faces as a help to recognize the following contexts: :table-special, :link,
19977 and :keyword."
19978 (let* ((f (get-text-property (point) 'face))
19979 (faces (if (listp f) f (list f)))
19980 (p (point)) clist o)
19981 ;; First the large context
19982 (cond
19983 ((org-on-heading-p t)
19984 (push (list :headline (point-at-bol) (point-at-eol)) clist)
19985 (when (progn
19986 (beginning-of-line 1)
19987 (looking-at org-todo-line-tags-regexp))
19988 (push (org-point-in-group p 1 :headline-stars) clist)
19989 (push (org-point-in-group p 2 :todo-keyword) clist)
19990 (push (org-point-in-group p 4 :tags) clist))
19991 (goto-char p)
19992 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
19993 (if (looking-at "\\[#[A-Z]\\]")
19994 (push (org-point-in-group p 0 :priority) clist)))
19996 ((org-at-item-p)
19997 (push (org-point-in-group p 2 :item-bullet) clist)
19998 (push (list :item (point-at-bol)
19999 (save-excursion (org-end-of-item) (point)))
20000 clist)
20001 (and (org-at-item-checkbox-p)
20002 (push (org-point-in-group p 0 :checkbox) clist)))
20004 ((org-at-table-p)
20005 (push (list :table (org-table-begin) (org-table-end)) clist)
20006 (if (memq 'org-formula faces)
20007 (push (list :table-special
20008 (previous-single-property-change p 'face)
20009 (next-single-property-change p 'face)) clist)))
20010 ((org-at-table-p 'any)
20011 (push (list :table-table) clist)))
20012 (goto-char p)
20014 ;; Now the small context
20015 (cond
20016 ((org-at-timestamp-p)
20017 (push (org-point-in-group p 0 :timestamp) clist))
20018 ((memq 'org-link faces)
20019 (push (list :link
20020 (previous-single-property-change p 'face)
20021 (next-single-property-change p 'face)) clist))
20022 ((memq 'org-special-keyword faces)
20023 (push (list :keyword
20024 (previous-single-property-change p 'face)
20025 (next-single-property-change p 'face)) clist))
20026 ((org-on-target-p)
20027 (push (org-point-in-group p 0 :target) clist)
20028 (goto-char (1- (match-beginning 0)))
20029 (if (looking-at org-radio-target-regexp)
20030 (push (org-point-in-group p 0 :radio-target) clist))
20031 (goto-char p))
20032 ((setq o (car (delq nil
20033 (mapcar
20034 (lambda (x)
20035 (if (memq x org-latex-fragment-image-overlays) x))
20036 (org-overlays-at (point))))))
20037 (push (list :latex-fragment
20038 (org-overlay-start o) (org-overlay-end o)) clist)
20039 (push (list :latex-preview
20040 (org-overlay-start o) (org-overlay-end o)) clist))
20041 ((org-inside-LaTeX-fragment-p)
20042 ;; FIXME: positions wrong.
20043 (push (list :latex-fragment (point) (point)) clist)))
20045 (setq clist (nreverse (delq nil clist)))
20046 clist))
20048 ;; FIXME Compare with at-regexp-p
20049 (defun org-in-regexp (re &optional nlines visually)
20050 "Check if point is inside a match of regexp.
20051 Normally only the current line is checked, but you can include NLINES extra
20052 lines both before and after point into the search.
20053 If VISUALLY is set, require that the cursor is not after the match but
20054 really on, so that the block visually is on the match."
20055 (catch 'exit
20056 (let ((pos (point))
20057 (eol (point-at-eol (+ 1 (or nlines 0))))
20058 (inc (if visually 1 0)))
20059 (save-excursion
20060 (beginning-of-line (- 1 (or nlines 0)))
20061 (while (re-search-forward re eol t)
20062 (if (and (<= (match-beginning 0) pos)
20063 (>= (+ inc (match-end 0)) pos))
20064 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20066 (defun org-at-regexp-p (regexp)
20067 "Is point inside a match of REGEXP in the current line?"
20068 (catch 'exit
20069 (save-excursion
20070 (let ((pos (point)) (end (point-at-eol)))
20071 (beginning-of-line 1)
20072 (while (re-search-forward regexp end t)
20073 (if (and (<= (match-beginning 0) pos)
20074 (>= (match-end 0) pos))
20075 (throw 'exit t)))
20076 nil))))
20078 (defun org-delete-all (elts list)
20079 "Remove all elements in ELTS from LIST."
20080 (while elts
20081 (setq list (delete (pop elts) list)))
20082 list)
20084 (defun org-point-in-group (point group &optional context)
20085 "Check if POINT is in match-group GROUP.
20086 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20087 match. If the match group does ot exist or point is not inside it,
20088 return nil."
20089 (and (match-beginning group)
20090 (>= point (match-beginning group))
20091 (<= point (match-end group))
20092 (if context
20093 (list context (match-beginning group) (match-end group))
20094 t)))
20096 (defun org-combine-plists (&rest plists)
20097 "Create a single property list from all plists in PLISTS.
20098 The process starts by copying the first list, and then setting properties
20099 from the other lists. Settings in the last list are the most significant
20100 ones and overrule settings in the other lists."
20101 (let ((rtn (copy-sequence (pop plists)))
20102 p v ls)
20103 (while plists
20104 (setq ls (pop plists))
20105 (while ls
20106 (setq p (pop ls) v (pop ls))
20107 (setq rtn (plist-put rtn p v))))
20108 rtn))
20110 (defun org-move-line-down (arg)
20111 "Move the current line down. With prefix argument, move it past ARG lines."
20112 (interactive "p")
20113 (let ((col (current-column))
20114 beg end pos)
20115 (beginning-of-line 1) (setq beg (point))
20116 (beginning-of-line 2) (setq end (point))
20117 (beginning-of-line (+ 1 arg))
20118 (setq pos (move-marker (make-marker) (point)))
20119 (insert (delete-and-extract-region beg end))
20120 (goto-char pos)
20121 (move-to-column col)))
20123 (defun org-move-line-up (arg)
20124 "Move the current line up. With prefix argument, move it past ARG lines."
20125 (interactive "p")
20126 (let ((col (current-column))
20127 beg end pos)
20128 (beginning-of-line 1) (setq beg (point))
20129 (beginning-of-line 2) (setq end (point))
20130 (beginning-of-line (- arg))
20131 (setq pos (move-marker (make-marker) (point)))
20132 (insert (delete-and-extract-region beg end))
20133 (goto-char pos)
20134 (move-to-column col)))
20136 (defun org-replace-escapes (string table)
20137 "Replace %-escapes in STRING with values in TABLE.
20138 TABLE is an association list with keys line \"%a\" and string values.
20139 The sequences in STRING may contain normal field width and padding information,
20140 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20141 so values can contain further %-escapes if they are define later in TABLE."
20142 (let ((case-fold-search nil)
20143 e re rpl)
20144 (while (setq e (pop table))
20145 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20146 (while (string-match re string)
20147 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20148 (cdr e)))
20149 (setq string (replace-match rpl t t string))))
20150 string))
20153 (defun org-sublist (list start end)
20154 "Return a section of LIST, from START to END.
20155 Counting starts at 1."
20156 (let (rtn (c start))
20157 (setq list (nthcdr (1- start) list))
20158 (while (and list (<= c end))
20159 (push (pop list) rtn)
20160 (setq c (1+ c)))
20161 (nreverse rtn)))
20163 (defun org-find-base-buffer-visiting (file)
20164 "Like `find-buffer-visiting' but alway return the base buffer and
20165 not an indirect buffer"
20166 (let ((buf (find-buffer-visiting file)))
20167 (or (buffer-base-buffer buf) buf)))
20169 (defun org-image-file-name-regexp ()
20170 "Return regexp matching the file names of images."
20171 (if (fboundp 'image-file-name-regexp)
20172 (image-file-name-regexp)
20173 (let ((image-file-name-extensions
20174 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20175 "xbm" "xpm" "pbm" "pgm" "ppm")))
20176 (concat "\\."
20177 (regexp-opt (nconc (mapcar 'upcase
20178 image-file-name-extensions)
20179 image-file-name-extensions)
20181 "\\'"))))
20183 (defun org-file-image-p (file)
20184 "Return non-nil if FILE is an image."
20185 (save-match-data
20186 (string-match (org-image-file-name-regexp) file)))
20188 ;;; Paragraph filling stuff.
20189 ;; We want this to be just right, so use the full arsenal.
20191 (defun org-indent-line-function ()
20192 "Indent line like previous, but further if previous was headline or item."
20193 (interactive)
20194 (let ((column (save-excursion
20195 (beginning-of-line)
20196 (if (looking-at "#") 0
20197 (skip-chars-backward "\n \t")
20198 (beginning-of-line)
20199 (if (or (looking-at "\\*+[ \t]+")
20200 (looking-at "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)"))
20201 (progn (goto-char (match-end 0)) (current-column))
20202 (current-indentation))))))
20203 (if (<= (current-column) (current-indentation))
20204 (indent-line-to column)
20205 (save-excursion (indent-line-to column)))))
20207 (defun org-set-autofill-regexps ()
20208 (interactive)
20209 ;; In the paragraph separator we include headlines, because filling
20210 ;; text in a line directly attached to a headline would otherwise
20211 ;; fill the headline as well.
20212 (org-set-local 'comment-start-skip "^#+[ \t]*")
20213 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
20214 ;; The paragraph starter includes hand-formatted lists.
20215 (org-set-local 'paragraph-start
20216 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
20217 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20218 ;; But only if the user has not turned off tables or fixed-width regions
20219 (org-set-local
20220 'auto-fill-inhibit-regexp
20221 (concat "\\*\\|#\\+"
20222 "\\|[ \t]*" org-keyword-time-regexp
20223 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20224 (concat
20225 "\\|[ \t]*["
20226 (if org-enable-table-editor "|" "")
20227 (if org-enable-fixed-width-editor ":" "")
20228 "]"))))
20229 ;; We use our own fill-paragraph function, to make sure that tables
20230 ;; and fixed-width regions are not wrapped. That function will pass
20231 ;; through to `fill-paragraph' when appropriate.
20232 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20233 ; Adaptive filling: To get full control, first make sure that
20234 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20235 (org-set-local 'adaptive-fill-regexp "\000")
20236 (org-set-local 'adaptive-fill-function
20237 'org-adaptive-fill-function))
20239 (defun org-fill-paragraph (&optional justify)
20240 "Re-align a table, pass through to fill-paragraph if no table."
20241 (let ((table-p (org-at-table-p))
20242 (table.el-p (org-at-table.el-p)))
20243 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
20244 (table.el-p t) ; skip table.el tables
20245 (table-p (org-table-align) t) ; align org-mode tables
20246 (t nil)))) ; call paragraph-fill
20248 ;; For reference, this is the default value of adaptive-fill-regexp
20249 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20251 (defun org-adaptive-fill-function ()
20252 "Return a fill prefix for org-mode files.
20253 In particular, this makes sure hanging paragraphs for hand-formatted lists
20254 work correctly."
20255 (cond ((looking-at "#[ \t]+")
20256 (match-string 0))
20257 ((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
20258 (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
20259 (t nil)))
20261 ;;;; Functions extending outline functionality
20263 ;; C-a should go to the beginning of a *visible* line, also in the
20264 ;; new outline.el. I guess this should be patched into Emacs?
20265 (defun org-beginning-of-line ()
20266 "Go to the beginning of the current line. If that is invisible, continue
20267 to a visible line beginning. This makes the function of C-a more intuitive."
20268 (interactive)
20269 (beginning-of-line 1)
20270 (if (bobp)
20272 (backward-char 1)
20273 (if (org-invisible-p)
20274 (while (and (not (bobp)) (org-invisible-p))
20275 (backward-char 1)
20276 (beginning-of-line 1))
20277 (forward-char 1))))
20279 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20281 (defun org-invisible-p ()
20282 "Check if point is at a character currently not visible."
20283 ;; Early versions of noutline don't have `outline-invisible-p'.
20284 (if (fboundp 'outline-invisible-p)
20285 (outline-invisible-p)
20286 (get-char-property (point) 'invisible)))
20288 (defun org-invisible-p2 ()
20289 "Check if point is at a character currently not visible."
20290 (save-excursion
20291 (if (and (eolp) (not (bobp))) (backward-char 1))
20292 ;; Early versions of noutline don't have `outline-invisible-p'.
20293 (if (fboundp 'outline-invisible-p)
20294 (outline-invisible-p)
20295 (get-char-property (point) 'invisible))))
20297 (defalias 'org-back-to-heading 'outline-back-to-heading)
20298 (defalias 'org-on-heading-p 'outline-on-heading-p)
20299 (defalias 'org-at-heading-p 'outline-on-heading-p)
20300 (defun org-at-heading-or-item-p ()
20301 (or (org-on-heading-p) (org-at-item-p)))
20303 (defun org-on-target-p ()
20304 (or (org-in-regexp org-radio-target-regexp)
20305 (org-in-regexp org-target-regexp)))
20307 (defun org-up-heading-all (arg)
20308 "Move to the heading line of which the present line is a subheading.
20309 This function considers both visible and invisible heading lines.
20310 With argument, move up ARG levels."
20311 (if (fboundp 'outline-up-heading-all)
20312 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20313 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20315 (defun org-goto-sibling (&optional previous)
20316 "Goto the next sibling, even if it is invisible.
20317 When PREVIOUS is set, go to the previous sibling instead. Returns t
20318 when a sibling was found. When none is found, return nil and don't
20319 move point."
20320 (let ((fun (if previous 're-search-backward 're-search-forward))
20321 (pos (point))
20322 (re (concat "^" outline-regexp))
20323 level l)
20324 (org-back-to-heading t)
20325 (setq level (funcall outline-level))
20326 (catch 'exit
20327 (or previous (forward-char 1))
20328 (while (funcall fun re nil t)
20329 (setq l (funcall outline-level))
20330 (when (< l level) (goto-char pos) (throw 'exit nil))
20331 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20332 (goto-char pos)
20333 nil)))
20335 (defun org-show-siblings ()
20336 "Show all siblings of the current headline."
20337 (save-excursion
20338 (while (org-goto-sibling) (org-flag-heading nil)))
20339 (save-excursion
20340 (while (org-goto-sibling 'previous)
20341 (org-flag-heading nil))))
20343 (defun org-show-hidden-entry ()
20344 "Show an entry where even the heading is hidden."
20345 (save-excursion
20346 (org-show-entry)))
20348 (defun org-flag-heading (flag &optional entry)
20349 "Flag the current heading. FLAG non-nil means make invisible.
20350 When ENTRY is non-nil, show the entire entry."
20351 (save-excursion
20352 (org-back-to-heading t)
20353 ;; Check if we should show the entire entry
20354 (if entry
20355 (progn
20356 (org-show-entry)
20357 (save-excursion
20358 (and (outline-next-heading)
20359 (org-flag-heading nil))))
20360 (outline-flag-region (max 1 (1- (point)))
20361 (save-excursion (outline-end-of-heading) (point))
20362 flag))))
20364 (defun org-end-of-subtree (&optional invisible-OK)
20365 ;; This is an exact copy of the original function, but it uses
20366 ;; `org-back-to-heading', to make it work also in invisible
20367 ;; trees. And is uses an invisible-OK argument.
20368 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20369 (org-back-to-heading invisible-OK)
20370 (let ((first t)
20371 (level (funcall outline-level)))
20372 (while (and (not (eobp))
20373 (or first (> (funcall outline-level) level)))
20374 (setq first nil)
20375 (outline-next-heading))
20376 (if (memq (preceding-char) '(?\n ?\^M))
20377 (progn
20378 ;; Go to end of line before heading
20379 (forward-char -1)
20380 (if (memq (preceding-char) '(?\n ?\^M))
20381 ;; leave blank line before heading
20382 (forward-char -1)))))
20383 (point))
20385 (defun org-show-subtree ()
20386 "Show everything after this heading at deeper levels."
20387 (outline-flag-region
20388 (point)
20389 (save-excursion
20390 (outline-end-of-subtree) (outline-next-heading) (point))
20391 nil))
20393 (defun org-show-entry ()
20394 "Show the body directly following this heading.
20395 Show the heading too, if it is currently invisible."
20396 (interactive)
20397 (save-excursion
20398 (org-back-to-heading t)
20399 (outline-flag-region
20400 (max 1 (1- (point)))
20401 (save-excursion
20402 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
20403 (or (match-beginning 1) (point-max)))
20404 nil)))
20406 (defun org-make-options-regexp (kwds)
20407 "Make a regular expression for keyword lines."
20408 (concat
20410 "#?[ \t]*\\+\\("
20411 (mapconcat 'regexp-quote kwds "\\|")
20412 "\\):[ \t]*"
20413 "\\(.+\\)"))
20415 ;; Make isearch reveal the necessary context
20416 (defun org-isearch-end ()
20417 "Reveal context after isearch exits."
20418 (when isearch-success ; only if search was successful
20419 (if (featurep 'xemacs)
20420 ;; Under XEmacs, the hook is run in the correct place,
20421 ;; we directly show the context.
20422 (org-show-context 'isearch)
20423 ;; In Emacs the hook runs *before* restoring the overlays.
20424 ;; So we have to use a one-time post-command-hook to do this.
20425 ;; (Emacs 22 has a special variable, see function `org-mode')
20426 (unless (and (boundp 'isearch-mode-end-hook-quit)
20427 isearch-mode-end-hook-quit)
20428 ;; Only when the isearch was not quitted.
20429 (org-add-hook 'post-command-hook 'org-isearch-post-command
20430 'append 'local)))))
20432 (defun org-isearch-post-command ()
20433 "Remove self from hook, and show context."
20434 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20435 (org-show-context 'isearch))
20438 ;;;; Address problems with some other packages
20440 ;; Make flyspell not check words in links, to not mess up our keymap
20441 (defun org-mode-flyspell-verify ()
20442 "Don't let flyspell put overlays at active buttons."
20443 (not (get-text-property (point) 'keymap)))
20445 ;; Make `bookmark-jump' show the jump location if it was hidden.
20446 (eval-after-load "bookmark"
20447 '(if (boundp 'bookmark-after-jump-hook)
20448 ;; We can use the hook
20449 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20450 ;; Hook not available, use advice
20451 (defadvice bookmark-jump (after org-make-visible activate)
20452 "Make the position visible."
20453 (org-bookmark-jump-unhide))))
20455 (defun org-bookmark-jump-unhide ()
20456 "Unhide the current position, to show the bookmark location."
20457 (and (org-mode-p)
20458 (or (org-invisible-p)
20459 (save-excursion (goto-char (max (point-min) (1- (point))))
20460 (org-invisible-p)))
20461 (org-show-context 'bookmark-jump)))
20463 ;; Make session.el ignore our circular variable
20464 (eval-after-load "session"
20465 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20467 ;;;; Experimental code
20469 ;;;; Finish up
20471 (provide 'org)
20473 (run-hooks 'org-load-hook)
20475 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20476 ;;; org.el ends here