Release 4.61
[org-mode/org-tableheadings.git] / org.el
blobd97bab496cc53098bc4b99144ae942b0638b6cdc
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.61
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://staff.science.uva.nl/~dominik/Tools/org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; Recent changes
63 ;; --------------
64 ;; Version 4.61
65 ;; - Avoiding keybinding clashes with flyspell
66 ;; - Archiving is now also on `C-C C-x C-s' (was just `C-c $')
67 ;; - Cycling through agenda files is now also on "C-'" (was just "C-,")
68 ;; - Colon is considered part of number, to align times in clock tables.
69 ;; - Fixed bug for list of stuck projects.
70 ;; - Fixed several bugs/problems concerning linking to gnus.
71 ;; - Block agendas can contain the list of stuck projects.
72 ;; - #+ARCHIVE may now appear several times in the buffer.
73 ;; - More bug fixes.
75 ;; Version 4.60
76 ;; - HTML export: inlining images, clickable images (manual 10.2.4).
77 ;; - Incremental search now shows proper context when exiting.
78 ;; - Tables calculation and Calc package.
79 ;; - Calc is no longer needed when using only elisp formulas.
80 ;; - Proper error messages when calc is needed and not available.
81 ;; - Tracking TODO state changes with time stamps and notes.
82 ;; - Empty entries go full circle.
83 ;; - Links in iCalendar export cleaned up.
84 ;; - Bug fixes.
86 ;; Version 4.59
87 ;; - Cleanup code, bug fixes.
89 ;; Version 4.58
90 ;; - Full undo support in the agenda buffer.
91 ;; - Listing stuck GTD projects (projects without any NEXT ACTIONS).
92 ;; Configure `org-stuck-projects' before using it.
93 ;; - C-c C-x b shows the current subtree in an indirect buffer, in
94 ;; another, dedicated frame.
95 ;; - Custom agenda commands take precedence over builtin commands.
96 ;; - auto-fill for comments works on the Emacs side, XEmacs not yet.
98 ;; Version 4.57
99 ;; - Sorting of outline items on same level.
100 ;; - Sorting tables automatically selects line range between hlines.
101 ;; - Changes in Agenda buffer
102 ;; - `C-c C-o' follows a link in the current line.
103 ;; - `C-c $' archives the subtree corresponding to the line.
104 ;; - Changing dates with S-left and S-right show new date in agenda,
105 ;; but still do not move the entry to the new date.
106 ;; - new option `org-agenda-skip-scheduled-if-done'.
107 ;; - Agenda and sparse tree construction using tag matches can now
108 ;; use regular expressions.
109 ;; - When prompted for a date/time, entering "+7" indicates a date
110 ;; 7 days from now - but only this is the only thing you give.
111 ;; - Custom time formats also apply to exported html and ascii.
112 ;; - Bug fixes.
114 ;; Version 4.56
115 ;; - `C-k' in agenda kills current line and corresponding subtree in file.
116 ;; - XEmacs compatibility issues fixed, in particular tag alignment.
117 ;; - M-left/right now in/outdents plain list items, no Shift needed.
118 ;; - Bug fixes.
120 ;;; Code:
122 ;;;; Require other packages
124 (eval-when-compile
125 (require 'cl)
126 (require 'gnus-sum)
127 (require 'calendar))
128 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
129 ;; the file noutline.el being loaded.
130 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
131 ;; We require noutline, which might be provided in outline.el
132 (require 'outline) (require 'noutline)
133 ;; Other stuff we need.
134 (require 'time-date)
135 (require 'easymenu)
137 ;;;; Customization variables
139 ;;; Version
141 (defvar org-version "4.61"
142 "The version number of the file org.el.")
143 (defun org-version ()
144 (interactive)
145 (message "Org-mode version %s" org-version))
147 ;;; Compatibility constants
148 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
149 (defconst org-format-transports-properties-p
150 (let ((x "a"))
151 (add-text-properties 0 1 '(test t) x)
152 (get-text-property 0 'test (format "%s" x)))
153 "Does format transport text properties?")
155 ;;; The custom variables
157 (defgroup org nil
158 "Outline-based notes management and organizer."
159 :tag "Org"
160 :group 'outlines
161 :group 'hypermedia
162 :group 'calendar)
164 (defgroup org-startup nil
165 "Options concerning startup of Org-mode."
166 :tag "Org Startup"
167 :group 'org)
169 (defcustom org-startup-folded t
170 "Non-nil means, entering Org-mode will switch to OVERVIEW.
171 This can also be configured on a per-file basis by adding one of
172 the following lines anywhere in the buffer:
174 #+STARTUP: fold
175 #+STARTUP: nofold
176 #+STARTUP: content"
177 :group 'org-startup
178 :type '(choice
179 (const :tag "nofold: show all" nil)
180 (const :tag "fold: overview" t)
181 (const :tag "content: all headlines" content)))
183 (defcustom org-startup-truncated t
184 "Non-nil means, entering Org-mode will set `truncate-lines'.
185 This is useful since some lines containing links can be very long and
186 uninteresting. Also tables look terrible when wrapped."
187 :group 'org-startup
188 :type 'boolean)
190 (defcustom org-startup-align-all-tables nil
191 "Non-nil means, align all tables when visiting a file.
192 This is useful when the column width in tables is forced with <N> cookies
193 in table fields. Such tables will look correct only after the first re-align.
194 This can also be configured on a per-file basis by adding one of
195 the following lines anywhere in the buffer:
196 #+STARTUP: align
197 #+STARTUP: noalign"
198 :group 'org-startup
199 :type 'boolean)
201 (defcustom org-startup-with-deadline-check nil
202 "Non-nil means, entering Org-mode will run the deadline check.
203 This means, if you start editing an org file, you will get an
204 immediate reminder of any due deadlines.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
207 #+STARTUP: dlcheck
208 #+STARTUP: nodlcheck"
209 :group 'org-startup
210 :type 'boolean)
212 (defcustom org-insert-mode-line-in-empty-file nil
213 "Non-nil means insert the first line setting Org-mode in empty files.
214 When the function `org-mode' is called interactively in an empty file, this
215 normally means that the file name does not automatically trigger Org-mode.
216 To ensure that the file will always be in Org-mode in the future, a
217 line enforcing Org-mode will be inserted into the buffer, if this option
218 has been set."
219 :group 'org-startup
220 :type 'boolean)
222 (defcustom org-CUA-compatible nil
223 "Non-nil means use alternative key bindings for S-<cursor movement>.
224 Org-mode used S-<cursor movement> for changing timestamps and priorities.
225 S-<cursor movement> is also used for example by `CUA-mode' to select text.
226 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
227 alternative bindings. Setting this variable to t will replace the following
228 keys both in Org-mode and in the Org-agenda buffer.
230 S-RET -> C-S-RET
231 S-up -> M-p
232 S-down -> M-n
233 S-left -> M--
234 S-right -> M-+
236 If you do not like the alternative keys, take a look at the variable
237 `org-disputed-keys'.
239 This option is only relevant at load-time of Org-mode, and must be set
240 *before* org.el is loaded. Changing it requires a restart of Emacs to
241 become effective."
242 :group 'org-startup
243 :type 'boolean)
245 (defvar org-disputed-keys
246 '((S-up [(shift up)] [(meta ?p)])
247 (S-down [(shift down)] [(meta ?n)])
248 (S-left [(shift left)] [(meta ?-)])
249 (S-right [(shift right)] [(meta ?+)])
250 (S-return [(shift return)] [(control shift return)]))
251 "Keys for which Org-mode and other modes compete.
252 This is an alist, cars are symbols for lookup, 1st element is the default key,
253 second element will be used when `org-CUA-compatible' is t.")
255 (defun org-key (key)
256 "Select a key according to `org-CUA-compatible'."
257 (nth (if org-CUA-compatible 2 1)
258 (or (assq key org-disputed-keys)
259 (error "Invalid Key %s in `org-key'" key))))
261 (defcustom org-ellipsis nil
262 "The ellipsis to use in the Org-mode outline.
263 When nil, just use the standard three dots. When a string, use that instead,
264 and just in Org-mode (which will then use its own display table).
265 Changing this requires executing `M-x org-mode' in a buffer to become
266 effective."
267 :group 'org-startup
268 :type '(choice (const :tag "Default" nil)
269 (string :tag "String" :value "...#")))
271 (defvar org-display-table nil
272 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
274 (defgroup org-keywords nil
275 "Keywords in Org-mode."
276 :tag "Org Keywords"
277 :group 'org)
279 (defcustom org-deadline-string "DEADLINE:"
280 "String to mark deadline entries.
281 A deadline is this string, followed by a time stamp. Should be a word,
282 terminated by a colon. You can insert a schedule keyword and
283 a timestamp with \\[org-deadline].
284 Changes become only effective after restarting Emacs."
285 :group 'org-keywords
286 :type 'string)
288 (defcustom org-scheduled-string "SCHEDULED:"
289 "String to mark scheduled TODO entries.
290 A schedule is this string, followed by a time stamp. Should be a word,
291 terminated by a colon. You can insert a schedule keyword and
292 a timestamp with \\[org-schedule].
293 Changes become only effective after restarting Emacs."
294 :group 'org-keywords
295 :type 'string)
297 (defcustom org-closed-string "CLOSED:"
298 "String used as the prefix for timestamps logging closing a TODO entry."
299 :group 'org-keywords
300 :type 'string)
302 (defcustom org-clock-string "CLOCK:"
303 "String used as prefix for timestamps clocking work hours on an item."
304 :group 'org-keywords
305 :type 'string)
307 (defcustom org-comment-string "COMMENT"
308 "Entries starting with this keyword will never be exported.
309 An entry can be toggled between COMMENT and normal with
310 \\[org-toggle-comment].
311 Changes become only effective after restarting Emacs."
312 :group 'org-keywords
313 :type 'string)
315 (defcustom org-quote-string "QUOTE"
316 "Entries starting with this keyword will be exported in fixed-width font.
317 Quoting applies only to the text in the entry following the headline, and does
318 not extend beyond the next headline, even if that is lower level.
319 An entry can be toggled between QUOTE and normal with
320 \\[org-toggle-fixed-width-section]."
321 :group 'org-keywords
322 :type 'string)
324 (defvar org-repeat-re "\\<REPEAT(\\([-+ 0-9dwmy]+\\))"
325 "Regular expression for specifying repeated events.
326 After a match, group 1 contains the repeat expression.")
328 (defgroup org-structure nil
329 "Options concerning the general structure of Org-mode files."
330 :tag "Org Structure"
331 :group 'org)
333 (defgroup org-reveal-location nil
334 "Options about how to make context of a location visible."
335 :tag "Org Reveal Location"
336 :group 'org-structure)
338 (defcustom org-show-hierarchy-above '((default . t))
339 "Non-nil means, show full hierarchy when revealing a location.
340 Org-mode often shows locations in an org-mode file which might have
341 been invisible before. When this is set, the hierarchy of headings
342 above the exposed location is shown.
343 Turning this off for example for sparse trees makes them very compact.
344 Instead of t, this can also be an alist specifying this option for different
345 contexts. Valid contexts are
346 agenda when exposing an entry from the agenda
347 org-goto when using the command `org-goto' on key C-c C-j
348 occur-tree when using the command `org-occur' on key C-c /
349 tags-tree when constructing a sparse tree based on tags matches
350 link-search when exposing search matches associated with a link
351 mark-goto when exposing the jump goal of a mark
352 bookmark-jump when exposing a bookmark location
353 isearch when exiting from an incremental search
354 default default for all contexts not set explicitly"
355 :group 'org-reveal-location
356 :type '(choice
357 (const :tag "Always" t)
358 (const :tag "Never" nil)
359 (repeat :greedy t :tag "Individual contexts"
360 (cons
361 (choice :tag "Context"
362 (const agenda)
363 (const org-goto)
364 (const occur-tree)
365 (const tags-tree)
366 (const link-search)
367 (const mark-goto)
368 (const bookmark-jump)
369 (const isearch)
370 (const default))
371 (boolean)))))
373 (defcustom org-show-following-heading '((default . t))
374 "Non-nil means, show following heading when revealing a location.
375 Org-mode often shows locations in an org-mode file which might have
376 been invisible before. When this is set, the heading following the
377 match is shown.
378 Turning this off for example for sparse trees makes them very compact,
379 but makes it harder to edit the location of the match. In such a case,
380 use the command \\[org-reveal] to show more context.
381 Instead of t, this can also be an alist specifying this option for different
382 contexts. See `org-show-hierarchy-above' for valid contexts."
383 :group 'org-reveal-location
384 :type '(choice
385 (const :tag "Always" t)
386 (const :tag "Never" nil)
387 (repeat :greedy t :tag "Individual contexts"
388 (cons
389 (choice :tag "Context"
390 (const agenda)
391 (const org-goto)
392 (const occur-tree)
393 (const tags-tree)
394 (const link-search)
395 (const mark-goto)
396 (const bookmark-jump)
397 (const isearch)
398 (const default))
399 (boolean)))))
401 (defcustom org-show-siblings '((default . nil) (isearch t))
402 "Non-nil means, show all sibling heading when revealing a location.
403 Org-mode often shows locations in an org-mode file which might have
404 been invisible before. When this is set, the sibling of the current entry
405 heading are all made visible. If `org-show-hierarchy-above' is t,
406 the same happens on each level of the hierarchy above the current entry.
408 By default this is on for the isearch context, off for all other contexts.
409 Turning this off for example for sparse trees makes them very compact,
410 but makes it harder to edit the location of the match. In such a case,
411 use the command \\[org-reveal] to show more context.
412 Instead of t, this can also be an alist specifying this option for different
413 contexts. See `org-show-hierarchy-above' for valid contexts."
414 :group 'org-reveal-location
415 :type '(choice
416 (const :tag "Always" t)
417 (const :tag "Never" nil)
418 (repeat :greedy t :tag "Individual contexts"
419 (cons
420 (choice :tag "Context"
421 (const agenda)
422 (const org-goto)
423 (const occur-tree)
424 (const tags-tree)
425 (const link-search)
426 (const mark-goto)
427 (const bookmark-jump)
428 (const isearch)
429 (const default))
430 (boolean)))))
432 (defgroup org-cycle nil
433 "Options concerning visibility cycling in Org-mode."
434 :tag "Org Cycle"
435 :group 'org-structure)
437 (defcustom org-cycle-global-at-bob t
438 "Cycle globally if cursor is at beginning of buffer and not at a headline.
439 This makes it possible to do global cycling without having to use S-TAB or
440 C-u TAB. For this special case to work, the first line of the buffer
441 must not be a headline - it may be empty ot some other text. When used in
442 this way, `org-cycle-hook' is disables temporarily, to make sure the
443 cursor stays at the beginning of the buffer.
444 When this option is nil, don't do anything special at the beginning
445 of the buffer."
446 :group 'org-cycle
447 :type 'boolean)
449 (defcustom org-cycle-emulate-tab t
450 "Where should `org-cycle' emulate TAB.
451 nil Never
452 white Only in completely white lines
453 whitestart Only at the beginning of lines, before the first non-white char.
454 t Everywhere except in headlines
455 If TAB is used in a place where it does not emulate TAB, the current subtree
456 visibility is cycled."
457 :group 'org-cycle
458 :type '(choice (const :tag "Never" nil)
459 (const :tag "Only in completely white lines" white)
460 (const :tag "Before first char in a line" whitestart)
461 (const :tag "Everywhere except in headlines" t)
464 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
465 org-optimize-window-after-visibility-change)
466 "Hook that is run after `org-cycle' has changed the buffer visibility.
467 The function(s) in this hook must accept a single argument which indicates
468 the new state that was set by the most recent `org-cycle' command. The
469 argument is a symbol. After a global state change, it can have the values
470 `overview', `content', or `all'. After a local state change, it can have
471 the values `folded', `children', or `subtree'."
472 :group 'org-cycle
473 :type 'hook)
476 (defgroup org-edit-structure nil
477 "Options concerning structure editing in Org-mode."
478 :tag "Org Edit Structure"
479 :group 'org-structure)
481 (defcustom org-odd-levels-only nil
482 "Non-nil means, skip even levels and only use odd levels for the outline.
483 This has the effect that two stars are being added/taken away in
484 promotion/demotion commands. It also influences how levels are
485 handled by the exporters.
486 Changing it requires restart of `font-lock-mode' to become effective
487 for fontification also in regions already fontified.
488 You may also set this on a per-file basis by adding one of the following
489 lines to the buffer:
491 #+STARTUP: odd
492 #+STARTUP: oddeven"
493 :group 'org-edit-structure
494 :group 'org-font-lock
495 :type 'boolean)
497 (defcustom org-adapt-indentation t
498 "Non-nil means, adapt indentation when promoting and demoting.
499 When this is set and the *entire* text in an entry is indented, the
500 indentation is increased by one space in a demotion command, and
501 decreased by one in a promotion command. If any line in the entry
502 body starts at column 0, indentation is not changed at all."
503 :group 'org-edit-structure
504 :type 'boolean)
506 (defcustom org-blank-before-new-entry '((heading . nil)
507 (plain-list-item . nil))
508 "Should `org-insert-heading' leave a blank line before new heading/item?
509 The value is an alist, with `heading' and `plain-list-item' as car,
510 and a boolean flag as cdr."
511 :group 'org-edit-structure
512 :type '(list
513 (cons (const heading) (boolean))
514 (cons (const plain-list-item) (boolean))))
516 (defcustom org-insert-heading-hook nil
517 "Hook being run after inserting a new heading."
518 :group 'org-edit-structure
519 :type 'boolean)
521 (defcustom org-enable-fixed-width-editor t
522 "Non-nil means, lines starting with \":\" are treated as fixed-width.
523 This currently only means, they are never auto-wrapped.
524 When nil, such lines will be treated like ordinary lines.
525 See also the QUOTE keyword."
526 :group 'org-edit-structure
527 :type 'boolean)
529 (defgroup org-sparse-trees nil
530 "Options concerning sparse trees in Org-mode."
531 :tag "Org Sparse Trees"
532 :group 'org-structure)
534 (defcustom org-highlight-sparse-tree-matches t
535 "Non-nil means, highlight all matches that define a sparse tree.
536 The highlights will automatically disappear the next time the buffer is
537 changed by an edit command."
538 :group 'org-sparse-trees
539 :type 'boolean)
541 (defcustom org-remove-highlights-with-change t
542 "Non-nil means, any change to the buffer will remove temporary highlights.
543 Such highlights are created by `org-occur' and `org-clock-display'.
544 When nil, `C-c C-c needs to be used to get rid of the highlights.
545 The highlights created by `org-preview-latex-fragment' always need
546 `C-c C-c' to be removed."
547 :group 'org-sparse-trees
548 :group 'org-time
549 :type 'boolean)
552 (defcustom org-occur-hook '(org-first-headline-recenter)
553 "Hook that is run after `org-occur' has constructed a sparse tree.
554 This can be used to recenter the window to show as much of the structure
555 as possible."
556 :group 'org-sparse-trees
557 :type 'hook)
559 (defgroup org-plain-lists nil
560 "Options concerning plain lists in Org-mode."
561 :tag "Org Plain lists"
562 :group 'org-structure)
564 (defcustom org-cycle-include-plain-lists nil
565 "Non-nil means, include plain lists into visibility cycling.
566 This means that during cycling, plain list items will *temporarily* be
567 interpreted as outline headlines with a level given by 1000+i where i is the
568 indentation of the bullet. In all other operations, plain list items are
569 not seen as headlines. For example, you cannot assign a TODO keyword to
570 such an item."
571 :group 'org-plain-lists
572 :type 'boolean)
574 (defcustom org-plain-list-ordered-item-terminator t
575 "The character that makes a line with leading number an ordered list item.
576 Valid values are ?. and ?\). To get both terminators, use t. While
577 ?. may look nicer, it creates the danger that a line with leading
578 number may be incorrectly interpreted as an item. ?\) therefore is
579 the safe choice."
580 :group 'org-plain-lists
581 :type '(choice (const :tag "dot like in \"2.\"" ?.)
582 (const :tag "paren like in \"2)\"" ?\))
583 (const :tab "both" t)))
585 (defcustom org-auto-renumber-ordered-lists t
586 "Non-nil means, automatically renumber ordered plain lists.
587 Renumbering happens when the sequence have been changed with
588 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
589 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
590 :group 'org-plain-lists
591 :type 'boolean)
593 (defcustom org-provide-checkbox-statistics t
594 "Non-nil means, update checkbox statistics after insert and toggle.
595 When this is set, checkbox statistics is updated each time you either insert
596 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
597 with \\[org-ctrl-c-ctrl-c\\]."
598 :group 'org-plain-lists
599 :type 'boolean)
601 (defgroup org-archive nil
602 "Options concerning archiving in Org-mode."
603 :tag "Org Archive"
604 :group 'org-structure)
606 (defcustom org-archive-tag "ARCHIVE"
607 "The tag that marks a subtree as archived.
608 An archived subtree does not open during visibility cycling, and does
609 not contribute to the agenda listings."
610 :group 'org-archive
611 :group 'org-keywords
612 :type 'string)
614 (defcustom org-agenda-skip-archived-trees t
615 "Non-nil means, the agenda will skip any items located in archived trees.
616 An archived tree is a tree marked with the tag ARCHIVE."
617 :group 'org-archive
618 :group 'org-agenda-skip
619 :type 'boolean)
621 (defcustom org-cycle-open-archived-trees nil
622 "Non-nil means, `org-cycle' will open archived trees.
623 An archived tree is a tree marked with the tag ARCHIVE.
624 When nil, archived trees will stay folded. You can still open them with
625 normal outline commands like `show-all', but not with the cycling commands."
626 :group 'org-archive
627 :group 'org-cycle
628 :type 'boolean)
630 (defcustom org-sparse-tree-open-archived-trees nil
631 "Non-nil means sparse tree construction shows matches in archived trees.
632 When nil, matches in these trees are highlighted, but the trees are kept in
633 collapsed state."
634 :group 'org-archive
635 :group 'org-sparse-trees
636 :type 'boolean)
638 (defcustom org-archive-location "%s_archive::"
639 "The location where subtrees should be archived.
640 This string consists of two parts, separated by a double-colon.
642 The first part is a file name - when omitted, archiving happens in the same
643 file. %s will be replaced by the current file name (without directory part).
644 Archiving to a different file is useful to keep archived entries from
645 contributing to the Org-mode Agenda.
647 The part after the double colon is a headline. The archived entries will be
648 filed under that headline. When omitted, the subtrees are simply filed away
649 at the end of the file, as top-level entries.
651 Here are a few examples:
652 \"%s_archive::\"
653 If the current file is Projects.org, archive in file
654 Projects.org_archive, as top-level trees. This is the default.
656 \"::* Archived Tasks\"
657 Archive in the current file, under the top-level headline
658 \"* Archived Tasks\".
660 \"~/org/archive.org::\"
661 Archive in file ~/org/archive.org (absolute path), as top-level trees.
663 \"basement::** Finished Tasks\"
664 Archive in file ./basement (relative path), as level 3 trees
665 below the level 2 heading \"** Finished Tasks\".
667 You may set this option on a per-file basis by adding to the buffer a
668 line like
670 #+ARCHIVE: basement::** Finished Tasks"
671 :group 'org-archive
672 :type 'string)
674 (defcustom org-archive-mark-done t
675 "Non-nil means, mark entries as DONE when they are moved to the archive file."
676 :group 'org-archive
677 :type 'boolean)
679 (defcustom org-archive-stamp-time t
680 "Non-nil means, add a time stamp to entries moved to an archive file.
681 The time stamp will be added directly after the TODO state keyword in the
682 first line, so it is probably best to use this in combinations with
683 `org-archive-mark-done'."
684 :group 'org-archive
685 :type 'boolean)
687 (defgroup org-table nil
688 "Options concerning tables in Org-mode."
689 :tag "Org Table"
690 :group 'org)
692 (defcustom org-enable-table-editor 'optimized
693 "Non-nil means, lines starting with \"|\" are handled by the table editor.
694 When nil, such lines will be treated like ordinary lines.
696 When equal to the symbol `optimized', the table editor will be optimized to
697 do the following:
698 - Automatic overwrite mode in front of whitespace in table fields.
699 This makes the structure of the table stay in tact as long as the edited
700 field does not exceed the column width.
701 - Minimize the number of realigns. Normally, the table is aligned each time
702 TAB or RET are pressed to move to another field. With optimization this
703 happens only if changes to a field might have changed the column width.
704 Optimization requires replacing the functions `self-insert-command',
705 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
706 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
707 very good at guessing when a re-align will be necessary, but you can always
708 force one with \\[org-ctrl-c-ctrl-c].
710 If you would like to use the optimized version in Org-mode, but the
711 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
713 This variable can be used to turn on and off the table editor during a session,
714 but in order to toggle optimization, a restart is required.
716 See also the variable `org-table-auto-blank-field'."
717 :group 'org-table
718 :type '(choice
719 (const :tag "off" nil)
720 (const :tag "on" t)
721 (const :tag "on, optimized" optimized)))
723 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
724 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
725 In the optimized version, the table editor takes over all simple keys that
726 normally just insert a character. In tables, the characters are inserted
727 in a way to minimize disturbing the table structure (i.e. in overwrite mode
728 for empty fields). Outside tables, the correct binding of the keys is
729 restored.
731 The default for this option is t if the optimized version is also used in
732 Org-mode. See the variable `org-enable-table-editor' for details. Changing
733 this variable requires a restart of Emacs to become effective."
734 :group 'org-table
735 :type 'boolean)
737 (defgroup org-table-settings nil
738 "Settings for tables in Org-mode."
739 :tag "Org Table Settings"
740 :group 'org-table)
742 (defcustom org-table-default-size "5x2"
743 "The default size for newly created tables, Columns x Rows."
744 :group 'org-table-settings
745 :type 'string)
747 (defcustom org-table-number-regexp
748 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$"
749 "Regular expression for recognizing numbers in table columns.
750 If a table column contains mostly numbers, it will be aligned to the
751 right. If not, it will be aligned to the left.
753 The default value of this option is a regular expression which allows
754 anything which looks remotely like a number as used in scientific
755 context. For example, all of the following will be considered a
756 number:
757 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
759 Other options offered by the customize interface are more restrictive."
760 :group 'org-table-settings
761 :type '(choice
762 (const :tag "Positive Integers"
763 "^[0-9]+$")
764 (const :tag "Integers"
765 "^[-+]?[0-9]+$")
766 (const :tag "Floating Point Numbers"
767 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
768 (const :tag "Floating Point Number or Integer"
769 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
770 (const :tag "Exponential, Floating point, Integer"
771 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
772 (const :tag "Very General Number-Like, including hex"
773 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$")
774 (string :tag "Regexp:")))
776 (defcustom org-table-number-fraction 0.5
777 "Fraction of numbers in a column required to make the column align right.
778 In a column all non-white fields are considered. If at least this
779 fraction of fields is matched by `org-table-number-fraction',
780 alignment to the right border applies."
781 :group 'org-table-settings
782 :type 'number)
784 (defgroup org-table-editing nil
785 "Bahavior of tables during editing in Org-mode."
786 :tag "Org Table Editing"
787 :group 'org-table)
789 (defcustom org-table-automatic-realign t
790 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
791 When nil, aligning is only done with \\[org-table-align], or after column
792 removal/insertion."
793 :group 'org-table-editing
794 :type 'boolean)
796 (defcustom org-table-limit-column-width t ;kw
797 "Non-nil means, allow to limit the width of table columns with <N> fields."
798 :group 'org-table-editing
799 :type 'boolean)
801 (defcustom org-table-auto-blank-field t
802 "Non-nil means, automatically blank table field when starting to type into it.
803 This only happens when typing immediately after a field motion
804 command (TAB, S-TAB or RET).
805 Only relevant when `org-enable-table-editor' is equal to `optimized'."
806 :group 'org-table-editing
807 :type 'boolean)
809 (defcustom org-table-tab-jumps-over-hlines t
810 "Non-nil means, tab in the last column of a table with jump over a hline.
811 If a horizontal separator line is following the current line,
812 `org-table-next-field' can either create a new row before that line, or jump
813 over the line. When this option is nil, a new line will be created before
814 this line."
815 :group 'org-table-editing
816 :type 'boolean)
818 (defcustom org-table-tab-recognizes-table.el t
819 "Non-nil means, TAB will automatically notice a table.el table.
820 When it sees such a table, it moves point into it and - if necessary -
821 calls `table-recognize-table'."
822 :group 'org-table-editing
823 :type 'boolean)
825 (defgroup org-table-calculation nil
826 "Options concerning tables in Org-mode."
827 :tag "Org Table Calculation"
828 :group 'org-table)
830 (defcustom org-table-copy-increment t
831 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
832 :group 'org-table-calculation
833 :type 'boolean)
835 (defcustom org-calc-default-modes
836 '(calc-internal-prec 12
837 calc-float-format (float 5)
838 calc-angle-mode deg
839 calc-prefer-frac nil
840 calc-symbolic-mode nil
841 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
842 calc-display-working-message t
844 "List with Calc mode settings for use in calc-eval for table formulas.
845 The list must contain alternating symbols (Calc modes variables and values).
846 Don't remove any of the default settings, just change the values. Org-mode
847 relies on the variables to be present in the list."
848 :group 'org-table-calculation
849 :type 'plist)
851 (defcustom org-table-formula-evaluate-inline t
852 "Non-nil means, TAB and RET evaluate a formula in current table field.
853 If the current field starts with an equal sign, it is assumed to be a formula
854 which should be evaluated as described in the manual and in the documentation
855 string of the command `org-table-eval-formula'. This feature requires the
856 Emacs calc package.
857 When this variable is nil, formula calculation is only available through
858 the command \\[org-table-eval-formula]."
859 :group 'org-table-calculation
860 :type 'boolean)
863 (defcustom org-table-formula-use-constants t
864 "Non-nil means, interpret constants in formulas in tables.
865 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
866 by the value given in `org-table-formula-constants', or by a value obtained
867 from the `constants.el' package."
868 :group 'org-table-calculation
869 :type 'boolean)
871 (defcustom org-table-formula-constants nil
872 "Alist with constant names and values, for use in table formulas.
873 The car of each element is a name of a constant, without the `$' before it.
874 The cdr is the value as a string. For example, if you'd like to use the
875 speed of light in a formula, you would configure
877 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
879 and then use it in an equation like `$1*$c'."
880 :group 'org-table-calculation
881 :type '(repeat
882 (cons (string :tag "name")
883 (string :tag "value"))))
885 (defcustom org-table-formula-numbers-only nil
886 "Non-nil means, calculate only with numbers in table formulas.
887 Then all input fields will be converted to a number, and the result
888 must also be a number. When nil, calc's full potential is available
889 in table calculations, including symbolics etc."
890 :group 'org-table-calculation
891 :type 'boolean)
893 (defcustom org-table-allow-automatic-line-recalculation t
894 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
895 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
896 :group 'org-table-calculation
897 :type 'boolean)
899 (defgroup org-link nil
900 "Options concerning links in Org-mode."
901 :tag "Org Link"
902 :group 'org)
904 (defvar org-link-abbrev-alist-local nil
905 "buffer-local version of `org-link-abbrev-alist', which see.
906 The value of this is taken from the #+LINK lines.")
907 (make-variable-buffer-local 'org-link-abbrev-alist-local)
909 (defcustom org-link-abbrev-alist nil
910 "Alist of link abbreviations.
911 The car of each element is a string, to be replaced at the start of a link.
912 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
913 links in Org-mode buffers can have an optional tag after a double colon, e.g.
915 [[linkkey::tag][description]]
917 If REPLACE is a string, the tag will simply be appended to create the link.
918 If the string contains \"%s\", the tag will be inserted there. REPLACE may
919 also be a function that will be called with the tag as the only argument to
920 create the link. See the manual for examples."
921 :group 'org-link
922 :type 'alist)
924 (defcustom org-descriptive-links t
925 "Non-nil means, hide link part and only show description of bracket links.
926 Bracket links are like [[link][descritpion]]. This variable sets the initial
927 state in new org-mode buffers. The setting can then be toggled on a
928 per-buffer basis from the Org->Hyperlinks menu."
929 :group 'org-link
930 :type 'boolean)
932 (defcustom org-link-style 'bracket
933 "The style of links to be inserted with \\[org-insert-link].
934 Possible values are:
935 bracket [[link][description]]. This is recommended
936 plain Description \\n link. The old way, no longer recommended."
937 :group 'org-link
938 :type '(choice
939 (const :tag "Bracket (recommended)" bracket)
940 (const :tag "Plain (no longer recommended)" plain)))
942 (defcustom org-link-format "%s"
943 "Default format for external, URL-like linkes in the buffer.
944 This is a format string for printf, %s will be replaced by the link text.
945 The recommended value is just \"%s\", since links will be protected by
946 enclosing them in double brackets. If you prefer plain links (see variable
947 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
948 additional URL: prefix, so the format would be \"<URL:%s>\"."
949 :group 'org-link
950 :type '(choice
951 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
952 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
953 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
954 (string :tag "Other" :value "<%s>")))
956 (defcustom org-link-file-path-type 'adaptive
957 "How the path name in file links should be stored.
958 Valid values are:
960 relative relative to the current directory, i.e. the directory of the file
961 into which the link is being inserted.
962 absolute absolute path, if possible with ~ for home directory.
963 noabbrev absolute path, no abbreviation of home directory.
964 adaptive Use relative path for files in the current directory and sub-
965 directories of it. For other files, use an absolute path."
966 :group 'org-link
967 :type '(choice
968 (const relative)
969 (const absolute)
970 (const noabbrev)
971 (const adaptive)))
973 (defcustom org-activate-links '(bracket angle plain radio tag date)
974 "Types of links that should be activated in Org-mode files.
975 This is a list of symbols, each leading to the activation of a certain link
976 type. In principle, it does not hurt to turn on most link types - there may
977 be a small gain when turning off unused link types. The types are:
979 bracket The recommended [[link][description]] or [[link]] links with hiding.
980 angular Links in angular brackes that may contain whitespace like
981 <bbdb:Carsten Dominik>.
982 plain Plain links in normal text, no whitespace, like http://google.com.
983 radio Text that is matched by a radio target, see manual for details.
984 tag Tag settings in a headline (link to tag search).
985 date Time stamps (link to calendar).
986 camel CamelCase words defining text searches.
988 Changing this variable requires a restart of Emacs to become effective."
989 :group 'org-link
990 :type '(set (const :tag "Double bracket links (new style)" bracket)
991 (const :tag "Angular bracket links (old style)" angular)
992 (const :tag "plain text links" plain)
993 (const :tag "Radio target matches" radio)
994 (const :tag "Tags" tag)
995 (const :tag "Timestamps" date)
996 (const :tag "CamelCase words" camel)))
998 (defgroup org-link-store nil
999 "Options concerning storing links in Org-mode"
1000 :tag "Org Store Link"
1001 :group 'org-link)
1003 (defcustom org-context-in-file-links t
1004 "Non-nil means, file links from `org-store-link' contain context.
1005 A search string will be added to the file name with :: as separator and
1006 used to find the context when the link is activated by the command
1007 `org-open-at-point'.
1008 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1009 negates this setting for the duration of the command."
1010 :group 'org-link-store
1011 :type 'boolean)
1013 (defcustom org-file-link-context-use-camel-case nil
1014 "Non-nil means, use CamelCase to store a search context in a file link.
1015 When nil, the search string simply consists of the words of the string.
1016 CamelCase is deprecated, and support for it may be dropped in the future."
1017 :group 'org-link-store
1018 :type 'boolean)
1020 (defcustom org-keep-stored-link-after-insertion nil
1021 "Non-nil means, keep link in list for entire session.
1023 The command `org-store-link' adds a link pointing to the current
1024 location to an internal list. These links accumulate during a session.
1025 The command `org-insert-link' can be used to insert links into any
1026 Org-mode file (offering completion for all stored links). When this
1027 option is nil, every link which has been inserted once using \\[org-insert-link]
1028 will be removed from the list, to make completing the unused links
1029 more efficient."
1030 :group 'org-link-store
1031 :type 'boolean)
1033 (defcustom org-usenet-links-prefer-google nil
1034 "Non-nil means, `org-store-link' will create web links to Google groups.
1035 When nil, Gnus will be used for such links.
1036 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1037 negates this setting for the duration of the command."
1038 :group 'org-link-store
1039 :type 'boolean)
1041 (defgroup org-link-follow nil
1042 "Options concerning following links in Org-mode"
1043 :tag "Org Follow Link"
1044 :group 'org-link)
1046 (defcustom org-tab-follows-link nil
1047 "Non-nil means, on links TAB will follow the link.
1048 Needs to be set before org.el is loaded."
1049 :group 'org-link-follow
1050 :type 'boolean)
1052 (defcustom org-return-follows-link nil
1053 "Non-nil means, on links RET will follow the link.
1054 Needs to be set before org.el is loaded."
1055 :group 'org-link-follow
1056 :type 'boolean)
1058 (defcustom org-mouse-1-follows-link t
1059 "Non-nil means, mouse-1 on a link will follow the link.
1060 A longer mouse click will still set point. Does not wortk on XEmacs.
1061 Needs to be set before org.el is loaded."
1062 :group 'org-link-follow
1063 :type 'boolean)
1065 (defcustom org-mark-ring-length 4
1066 "Number of different positions to be recorded in the ring
1067 Changing this requires a restart of Emacs to work correctly."
1068 :group 'org-link-follow
1069 :type 'interger)
1071 (defcustom org-link-frame-setup
1072 '((vm . vm-visit-folder-other-frame)
1073 (gnus . gnus-other-frame)
1074 (file . find-file-other-window))
1075 "Setup the frame configuration for following links.
1076 When following a link with Emacs, it may often be useful to display
1077 this link in another window or frame. This variable can be used to
1078 set this up for the different types of links.
1079 For VM, use any of
1080 `vm-visit-folder'
1081 `vm-visit-folder-other-frame'
1082 For Gnus, use any of
1083 `gnus'
1084 `gnus-other-frame'
1085 For FILE, use any of
1086 `find-file'
1087 `find-file-other-window'
1088 `find-file-other-frame'
1089 For the calendar, use the variable `calendar-setup'.
1090 For BBDB, it is currently only possible to display the matches in
1091 another window."
1092 :group 'org-link-follow
1093 :type '(list
1094 (cons (const vm)
1095 (choice
1096 (const vm-visit-folder)
1097 (const vm-visit-folder-other-window)
1098 (const vm-visit-folder-other-frame)))
1099 (cons (const gnus)
1100 (choice
1101 (const gnus)
1102 (const gnus-other-frame)))
1103 (cons (const file)
1104 (choice
1105 (const find-file)
1106 (const find-file-other-window)
1107 (const find-file-other-frame)))))
1109 (defcustom org-display-internal-link-with-indirect-buffer nil
1110 "Non-nil means, use indirect buffer to display infile links.
1111 Activating internal links (from one location in a file to another location
1112 in the same file) normally just jumps to the location. When the link is
1113 activated with a C-u prefix (or with mouse-3), the link is displayed in
1114 another window. When this option is set, the other window actually displays
1115 an indirect buffer clone of the current buffer, to avoid any visibility
1116 changes to the current buffer."
1117 :group 'org-link-follow
1118 :type 'boolean)
1121 (defcustom org-open-non-existing-files nil
1122 "Non-nil means, `org-open-file' will open non-existing file.
1123 When nil, an error will be generated."
1124 :group 'org-link-follow
1125 :type 'boolean)
1127 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1128 "Function and arguments to call for following mailto links.
1129 This is a list with the first element being a lisp function, and the
1130 remaining elements being arguments to the function. In string arguments,
1131 %a will be replaced by the address, and %s will be replaced by the subject
1132 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1133 :group 'org-link-follow
1134 :type '(choice
1135 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1136 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1137 (const :tag "message-mail" (message-mail "%a" "%s"))
1138 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1140 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1141 "Non-nil means, ask for confirmation before executing shell links.
1142 Shell links can be dangerous, just thing about a link
1144 [[shell:rm -rf ~/*][Google Search]]
1146 This link would show up in your Org-mode document as \"Google Search\"
1147 but really it would remove your entire home directory.
1148 Therefore I *definitely* advise against setting this variable to nil.
1149 Just change it to `y-or-n-p' of you want to confirm with a single key press
1150 rather than having to type \"yes\"."
1151 :group 'org-link-follow
1152 :type '(choice
1153 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1154 (const :tag "with y-or-n (faster)" y-or-n-p)
1155 (const :tag "no confirmation (dangerous)" nil)))
1157 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1158 "Non-nil means, ask for confirmation before executing elisp links.
1159 Elisp links can be dangerous, just think about a link
1161 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1163 This link would show up in your Org-mode document as \"Google Search\"
1164 but really it would remove your entire home directory.
1165 Therefore I *definitely* advise against setting this variable to nil.
1166 Just change it to `y-or-n-p' of you want to confirm with a single key press
1167 rather than having to type \"yes\"."
1168 :group 'org-link-follow
1169 :type '(choice
1170 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1171 (const :tag "with y-or-n (faster)" y-or-n-p)
1172 (const :tag "no confirmation (dangerous)" nil)))
1174 (defconst org-file-apps-defaults-gnu
1175 '((remote . emacs)
1176 (t . mailcap))
1177 "Default file applications on a UNIX or GNU/Linux system.
1178 See `org-file-apps'.")
1180 (defconst org-file-apps-defaults-macosx
1181 '((remote . emacs)
1182 (t . "open %s")
1183 ("ps" . "gv %s")
1184 ("ps.gz" . "gv %s")
1185 ("eps" . "gv %s")
1186 ("eps.gz" . "gv %s")
1187 ("dvi" . "xdvi %s")
1188 ("fig" . "xfig %s"))
1189 "Default file applications on a MacOS X system.
1190 The system \"open\" is known as a default, but we use X11 applications
1191 for some files for which the OS does not have a good default.
1192 See `org-file-apps'.")
1194 (defconst org-file-apps-defaults-windowsnt
1195 (list
1196 '(remote . emacs)
1197 (cons t
1198 (list (if (featurep 'xemacs)
1199 'mswindows-shell-execute
1200 'w32-shell-execute)
1201 "open" 'file)))
1202 "Default file applications on a Windows NT system.
1203 The system \"open\" is used for most files.
1204 See `org-file-apps'.")
1206 (defcustom org-file-apps
1208 ("txt" . emacs)
1209 ("tex" . emacs)
1210 ("ltx" . emacs)
1211 ("org" . emacs)
1212 ("el" . emacs)
1213 ("bib" . emacs)
1215 "External applications for opening `file:path' items in a document.
1216 Org-mode uses system defaults for different file types, but
1217 you can use this variable to set the application for a given file
1218 extension. The entries in this list are cons cells where the car identifies
1219 files and the cdr the corresponding command. Possible values for the
1220 file identifier are
1221 \"ext\" A string identifying an extension
1222 `directory' Matches a directory
1223 `remote' Matches a remote file, accessible through tramp or efs.
1224 Remote files most likely should be visited through Emacs
1225 because external applications cannot handle such paths.
1226 t Default for all remaining files
1228 Possible values for the command are:
1229 `emacs' The file will be visited by the current Emacs process.
1230 `default' Use the default application for this file type.
1231 string A command to be executed by a shell; %s will be replaced
1232 by the path to the file.
1233 sexp A Lisp form which will be evaluated. The file path will
1234 be available in the Lisp variable `file'.
1235 For more examples, see the system specific constants
1236 `org-file-apps-defaults-macosx'
1237 `org-file-apps-defaults-windowsnt'
1238 `org-file-apps-defaults-gnu'."
1239 :group 'org-link-follow
1240 :type '(repeat
1241 (cons (choice :value ""
1242 (string :tag "Extension")
1243 (const :tag "Default for unrecognized files" t)
1244 (const :tag "Remote file" remote)
1245 (const :tag "Links to a directory" directory))
1246 (choice :value ""
1247 (const :tag "Visit with Emacs" emacs)
1248 (const :tag "Use system default" default)
1249 (string :tag "Command")
1250 (sexp :tag "Lisp form")))))
1252 (defcustom org-mhe-search-all-folders nil
1253 "Non-nil means, that the search for the mh-message will be extended to
1254 all folders if the message cannot be found in the folder given in the link.
1255 Searching all folders is very effective with one of the search engines
1256 supported by MH-E, but will be slow with pick."
1257 :group 'org-link-follow
1258 :type 'boolean)
1260 (defgroup org-remember nil
1261 "Options concerning interaction with remember.el."
1262 :tag "Org Remember"
1263 :group 'org)
1265 (defcustom org-directory "~/org"
1266 "Directory with org files.
1267 This directory will be used as default to prompt for org files.
1268 Used by the hooks for remember.el."
1269 :group 'org-remember
1270 :type 'directory)
1272 (defcustom org-default-notes-file "~/.notes"
1273 "Default target for storing notes.
1274 Used by the hooks for remember.el. This can be a string, or nil to mean
1275 the value of `remember-data-file'."
1276 :group 'org-remember
1277 :type '(choice
1278 (const :tag "Default from remember-data-file" nil)
1279 file))
1281 (defcustom org-remember-templates nil
1282 "Templates for the creation of remember buffers.
1283 When nil, just let remember make the buffer.
1284 When not nil, this is a list of 3-element lists. In each entry, the first
1285 element is a character, a unique key to select this template.
1286 The second element is the template. The third element is optional and can
1287 specify a destination file for remember items created with this template.
1288 The default file is given by `org-default-notes-file'.
1290 The template specifies the structure of the remember buffer. It should have
1291 a first line starting with a star, to act as the org-mode headline.
1292 Furthermore, the following %-escapes will be replaced with content:
1293 %t time stamp, date only
1294 %T time stamp with date and time
1295 %u inactive time stamp, date only
1296 %U inactive time stamp with date and time
1297 %n user name
1298 %a annotation, normally the link created with org-store-link
1299 %i initial content, the region when remember is called with C-u.
1300 If %i is indented, the entire inserted text will be indented as well.
1301 %? This will be removed, and the cursor placed at this position."
1302 :group 'org-remember
1303 :type '(repeat :tag "enabled"
1304 (list :value (?a "\n" nil)
1305 (character :tag "Selection Key")
1306 (string :tag "Template")
1307 (file :tag "Destination file (optional)"))))
1309 (defcustom org-reverse-note-order nil
1310 "Non-nil means, store new notes at the beginning of a file or entry.
1311 When nil, new notes will be filed to the end of a file or entry."
1312 :group 'org-remember
1313 :type '(choice
1314 (const :tag "Reverse always" t)
1315 (const :tag "Reverse never" nil)
1316 (repeat :tag "By file name regexp"
1317 (cons regexp boolean))))
1319 (defgroup org-todo nil
1320 "Options concerning TODO items in Org-mode."
1321 :tag "Org TODO"
1322 :group 'org)
1324 (defgroup org-progress nil
1325 "Options concerning Progress logging in Org-mode."
1326 :tag "Org Progress"
1327 :group 'org-time)
1329 (defcustom org-todo-keywords '("TODO" "DONE")
1330 "List of TODO entry keywords.
1331 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1332 considered to mean that the entry is \"done\". All the other mean that
1333 action is required, and will make the entry show up in todo lists, diaries
1334 etc.
1335 The command \\[org-todo] cycles an entry through these states, and an
1336 additional state where no keyword is present. For details about this
1337 cycling, see also the variable `org-todo-interpretation'
1338 Changes become only effective after restarting Emacs."
1339 :group 'org-todo
1340 :group 'org-keywords
1341 :type '(repeat (string :tag "Keyword")))
1343 (defcustom org-todo-interpretation 'sequence
1344 "Controls how TODO keywords are interpreted.
1345 This variable is only relevant if `org-todo-keywords' contains more than two
1346 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1348 When `sequence', \\[org-todo] will always switch to the next state in the
1349 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1350 to state when executed several times in direct succession. Otherwise, it
1351 switches directly to DONE from any state.
1352 See the manual for more information."
1353 :group 'org-todo
1354 :group 'org-keywords
1355 :type '(choice (const sequence)
1356 (const type)))
1358 (defcustom org-after-todo-state-change-hook nil
1359 "Hook which is run after the state of a TODO item was changed.
1360 The new state (a string with a TODO keyword, or nil) is available in the
1361 Lisp variable `state'."
1362 :group 'org-todo
1363 :type 'hook)
1365 (defcustom org-log-done nil
1366 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1367 When the state of an entry is changed from nothing to TODO, remove a previous
1368 closing date.
1370 This can also be a list of symbols indicating under which conditions
1371 the time stamp recording the action should be annotated with a short note.
1372 Valid members of this list are
1374 done Offer to record a note when marking entries done
1375 state Offer to record a note whenever changing the TODO state
1376 of an item. This is only relevant if TODO keywords are
1377 interpreted as sequence, see variable `org-todo-interpretation'.
1378 When `state' is set, this includes tracking `done'.
1379 clock-out Offer to record a note when clocking out of an item.
1381 A separate window will then pop up and allow you to type a note.
1382 After finishing with C-c C-c, the note will be added directly after the
1383 timestamp, as a plain list item. See also the variable
1384 `org-log-note-headings'.
1386 Logging can also be configured on a per-file basis by adding one of
1387 the following lines anywhere in the buffer:
1389 #+STARTUP: logdone
1390 #+STARTUP: nologging
1391 #+STARTUP: lognotedone
1392 #+STARTUP: lognotestate
1393 #+STARTUP: lognoteclock-out"
1394 :group 'org-todo
1395 :group 'org-progress
1396 :type '(choice
1397 (const :tag "off" nil)
1398 (const :tag "on" t)
1399 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1400 (const :tag "when item is marked DONE" done)
1401 (const :tag "when TODO state changes" state)
1402 (const :tag "when clocking out" clock-out))))
1404 (defcustom org-log-note-headings
1405 '((done . "CLOSING NOTE %t")
1406 (state . "State %-12s %t")
1407 (clock-out . ""))
1408 "Headings for notes added when clocking out or closing TODO items.
1409 The value is an alist, with the car being a sympol indicating the note
1410 context, and the cdr is the heading to be used. The heading may also be the
1411 empty string.
1412 %t in the heading will be replaced by a time stamp.
1413 %s will be replaced by the new TODO state, in double quotes.
1414 %u will be replaced by the user name.
1415 %U will be replaced by the full user name."
1416 :group 'org-todo
1417 :group 'org-progress
1418 :type '(list :greedy t
1419 (cons (const :tag "Heading when closing an item" done) string)
1420 (cons (const :tag
1421 "Heading when changing todo state (todo sequence only)"
1422 state) string)
1423 (cons (const :tag "Heading when clocking out" clock-out) string)))
1425 (defgroup org-priorities nil
1426 "Priorities in Org-mode."
1427 :tag "Org Priorities"
1428 :group 'org-todo)
1430 (defcustom org-default-priority ?B
1431 "The default priority of TODO items.
1432 This is the priority an item get if no explicit priority is given."
1433 :group 'org-priorities
1434 :type 'character)
1436 (defcustom org-lowest-priority ?C
1437 "The lowest priority of TODO items. A character like ?A, ?B etc."
1438 :group 'org-priorities
1439 :type 'character)
1441 (defgroup org-time nil
1442 "Options concerning time stamps and deadlines in Org-mode."
1443 :tag "Org Time"
1444 :group 'org)
1446 (defcustom org-insert-labeled-timestamps-at-point nil
1447 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1448 When nil, these labeled time stamps are forces into the second line of an
1449 entry, just after the headline. When scheduling from the global TODO list,
1450 the time stamp will always be forced into the second line."
1451 :group 'org-time
1452 :type 'boolean)
1454 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1455 "Formats for `format-time-string' which are used for time stamps.
1456 It is not recommended to change this constant.")
1458 (defcustom org-time-stamp-rounding-minutes 0
1459 "Number of minutes to round time stamps to upon insertion.
1460 When zero, insert the time unmodified. Useful rounding numbers
1461 should be factors of 60, so for example 5, 10, 15.
1462 When this is not zero, you can still force an exact time-stamp by using
1463 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1464 :group 'org-time
1465 :type 'integer)
1467 (defcustom org-display-custom-times nil
1468 "Non-nil means, overlay custom formats over all time stamps.
1469 The formats are defined through the variable `org-time-stamp-custom-formats'.
1470 To turn this on on a per-file basis, insert anywhere in the file:
1471 #+STARTUP: customtime"
1472 :group 'org-time
1473 :set 'set-default
1474 :type 'sexp)
1475 (make-variable-buffer-local 'org-display-custom-times)
1477 (defcustom org-time-stamp-custom-formats
1478 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1479 "Custom formats for time stamps. See `format-time-string' for the syntax.
1480 These are overlayed over the default ISO format if the variable
1481 `org-display-custom-times' is set."
1482 :group 'org-time
1483 :type 'sexp)
1485 (defun org-time-stamp-format (&optional long inactive)
1486 "Get the right format for a time string."
1487 (let ((f (if long (cdr org-time-stamp-formats)
1488 (car org-time-stamp-formats))))
1489 (if inactive
1490 (concat "[" (substring f 1 -1) "]")
1491 f)))
1493 (defcustom org-deadline-warning-days 30
1494 "No. of days before expiration during which a deadline becomes active.
1495 This variable governs the display in sparse trees and in the agenda."
1496 :group 'org-time
1497 :type 'number)
1499 (defcustom org-popup-calendar-for-date-prompt t
1500 "Non-nil means, pop up a calendar when prompting for a date.
1501 In the calendar, the date can be selected with mouse-1. However, the
1502 minibuffer will also be active, and you can simply enter the date as well.
1503 When nil, only the minibuffer will be available."
1504 :group 'org-time
1505 :type 'boolean)
1507 (defcustom org-calendar-follow-timestamp-change t
1508 "Non-nil means, make the calendar window follow timestamp changes.
1509 When a timestamp is modified and the calendar window is visible, it will be
1510 moved to the new date."
1511 :group 'org-time
1512 :type 'boolean)
1514 (defgroup org-tags nil
1515 "Options concerning tags in Org-mode."
1516 :tag "Org Tags"
1517 :group 'org)
1519 (defcustom org-tag-alist nil
1520 "List of tags allowed in Org-mode files.
1521 When this list is nil, Org-mode will base TAG input on what is already in the
1522 buffer.
1523 The value of this variable is an alist, the car may be (and should) be a
1524 character that is used to select that tag through the fast-tag-selection
1525 interface. See the manual for details."
1526 :group 'org-tags
1527 :type '(repeat
1528 (choice
1529 (cons (string :tag "Tag name")
1530 (character :tag "Access char"))
1531 (const :tag "Start radio group" (:startgroup))
1532 (const :tag "End radio group" (:endgroup)))))
1534 (defcustom org-use-fast-tag-selection 'auto
1535 "Non-nil means, use fast tag selection scheme.
1536 This is a special interface to select and deselect tags with single keys.
1537 When nil, fast selection is never used.
1538 When the symbol `auto', fast selection is used if and only if selection
1539 characters for tags have been configured, either through the variable
1540 `org-tag-alist' or through a #+TAGS line in the buffer.
1541 When t, fast selection is always used and selection keys are assigned
1542 automatically if necessary."
1543 :group 'org-tags
1544 :type '(choice
1545 (const :tag "Always" t)
1546 (const :tag "Never" nil)
1547 (const :tag "When selection characters are configured" 'auto)))
1549 (defcustom org-fast-tag-selection-single-key nil
1550 "Non-nil means, fast tag selection exits after first change.
1551 When nil, you have to press RET to exit it.
1552 During fast tag selection, you can toggle this flag with `C-c'."
1553 :group 'org-tags
1554 :type 'boolean)
1556 (defcustom org-tags-column 48
1557 "The column to which tags should be indented in a headline.
1558 If this number is positive, it specifies the column. If it is negative,
1559 it means that the tags should be flushright to that column. For example,
1560 -79 works well for a normal 80 character screen."
1561 :group 'org-tags
1562 :type 'integer)
1564 (defcustom org-auto-align-tags t
1565 "Non-nil means, realign tags after pro/demotion of TODO state change.
1566 These operations change the length of a headline and therefore shift
1567 the tags around. With this options turned on, after each such operation
1568 the tags are again aligned to `org-tags-column'."
1569 :group 'org-tags
1570 :type 'boolean)
1572 (defcustom org-use-tag-inheritance t
1573 "Non-nil means, tags in levels apply also for sublevels.
1574 When nil, only the tags directly given in a specific line apply there.
1575 If you turn off this option, you very likely want to turn on the
1576 companion option `org-tags-match-list-sublevels'."
1577 :group 'org-tags
1578 :type 'boolean)
1580 (defcustom org-tags-match-list-sublevels nil
1581 "Non-nil means list also sublevels of headlines matching tag search.
1582 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1583 the sublevels of a headline matching a tag search often also match
1584 the same search. Listing all of them can create very long lists.
1585 Setting this variable to nil causes subtrees of a match to be skipped.
1586 This option is off by default, because inheritance in on. If you turn
1587 inheritance off, you very likely want to turn this option on.
1589 As a special case, if the tag search is restricted to TODO items, the
1590 value of this variable is ignored and sublevels are always checked, to
1591 make sure all corresponding TODO items find their way into the list."
1592 :group 'org-tags
1593 :type 'boolean)
1595 (defvar org-tags-history nil
1596 "History of minibuffer reads for tags.")
1597 (defvar org-last-tags-completion-table nil
1598 "The last used completion table for tags.")
1600 (defgroup org-agenda nil
1601 "Options concerning agenda views in Org-mode."
1602 :tag "Org Agenda"
1603 :group 'org)
1605 (defvar org-category nil
1606 "Variable used by org files to set a category for agenda display.
1607 Such files should use a file variable to set it, for example
1609 -*- mode: org; org-category: \"ELisp\"
1611 or contain a special line
1613 #+CATEGORY: ELisp
1615 If the file does not specify a category, then file's base name
1616 is used instead.")
1617 (make-variable-buffer-local 'org-category)
1619 (defcustom org-agenda-files nil
1620 "The files to be used for agenda display.
1621 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1622 \\[org-remove-file]. You can also use customize to edit the list.
1624 If the value of the variable is not a list but a single file name, then
1625 the list of agenda files is actually stored and maintained in that file, one
1626 agenda file per line."
1627 :group 'org-agenda
1628 :type '(choice
1629 (repeat :tag "List of files" file)
1630 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1633 (defcustom org-agenda-confirm-kill 1
1634 "When set, remote killing from the agenda buffer needs confirmation.
1635 When t, a confirmation is always needed. When a number N, confirmation is
1636 only needed when the text to be killed contains more than N non-white lines."
1637 :group 'org-agenda
1638 :type '(choice
1639 (const :tag "Never" nil)
1640 (const :tag "Always" t)
1641 (number :tag "When more than N lines")))
1643 (defcustom org-calendar-to-agenda-key [?c]
1644 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1645 The command `org-calendar-goto-agenda' will be bound to this key. The
1646 default is the character `c' because then `c' can be used to switch back and
1647 forth between agenda and calendar."
1648 :group 'org-agenda
1649 :type 'sexp)
1651 (defgroup org-agenda-custom-commands nil
1652 "Options concerning agenda views in Org-mode."
1653 :tag "Org Agenda Custom Commands"
1654 :group 'org-agenda)
1656 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1657 "Custom commands for the agenda.
1658 These commands will be offered on the splash screen displayed by the
1659 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1661 (key type match options)
1663 key The key (a single char as a string) to be associated with the command.
1664 type The command type, any of the following symbols:
1665 todo Entries with a specific TODO keyword, in all agenda files.
1666 tags Tags match in all agenda files.
1667 tags-todo Tags match in all agenda files, TODO entries only.
1668 todo-tree Sparse tree of specific TODO keyword in *current* file.
1669 tags-tree Sparse tree with all tags matches in *current* file.
1670 occur-tree Occur sparse tree for *current* file.
1671 match What to search for:
1672 - a single keyword for TODO keyword searches
1673 - a tags match expression for tags searches
1674 - a regular expression for occur searches
1675 options A list of option setttings, similar to that in a let form, so like
1676 this: ((opt1 val1) (opt2 val2) ...)
1678 You can also define a set of commands, to create a composite agenda buffer.
1679 In this case, an entry looks like this:
1681 (key desc (cmd1 cmd2 ...) general-options)
1683 where
1685 desc A description string to be displayed in the dispatcher menu.
1686 cmd An agenda command, similar to the above. However, tree commands
1687 are no allowed, but instead you can get agenda and global todo list.
1688 So valid commands for a set are:
1689 (agenda)
1690 (alltodo)
1691 (stuck)
1692 (todo \"match\" options)
1693 (tags \"match\" options )
1694 (tags-todo \"match\" options)
1696 Each command can carry a list of options, and another set of options can be
1697 given for the whole set of commands. Individual command options take
1698 precedence over the general options."
1699 :group 'org-agenda-custom-commands
1700 :type '(repeat
1701 (choice
1702 (list :tag "Single command"
1703 (string :tag "Key")
1704 (choice
1705 (const :tag "Tags search (all agenda files)" tags)
1706 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1707 (const :tag "TODO keyword search (all agenda files)" todo)
1708 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1709 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1710 (const :tag "Occur tree (current buffer)" occur-tree)
1711 (symbol :tag "Other, user-defined function"))
1712 (string :tag "Match")
1713 (repeat :tag "Local options"
1714 (list (variable :tag "Option") (sexp :tag "Value"))))
1715 (list :tag "Command series, all agenda files"
1716 (string :tag "Key")
1717 (string :tag "Description")
1718 (repeat
1719 (choice
1720 (const :tag "Agenda" (agenda))
1721 (const :tag "TODO list" (alltodo))
1722 (const :tag "Stuck projects" (stuck))
1723 (list :tag "Tags search"
1724 (const :format "" tags)
1725 (string :tag "Match")
1726 (repeat :tag "Local options"
1727 (list (variable :tag "Option")
1728 (sexp :tag "Value"))))
1730 (list :tag "Tags search, TODO entries only"
1731 (const :format "" tags-todo)
1732 (string :tag "Match")
1733 (repeat :tag "Local options"
1734 (list (variable :tag "Option")
1735 (sexp :tag "Value"))))
1737 (list :tag "TODO keyword search"
1738 (const :format "" todo)
1739 (string :tag "Match")
1740 (repeat :tag "Local options"
1741 (list (variable :tag "Option")
1742 (sexp :tag "Value"))))
1744 (list :tag "Other, user-defined function"
1745 (symbol :tag "function")
1746 (string :tag "Match")
1747 (repeat :tag "Local options"
1748 (list (variable :tag "Option")
1749 (sexp :tag "Value"))))))
1751 (repeat :tag "General options"
1752 (list (variable :tag "Option")
1753 (sexp :tag "Value")))))))
1755 (defcustom org-stuck-projects
1756 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil)
1757 "How to identify stuck projects.
1758 This is a list of three items:
1759 1. A tags/todo matcher string that is used to identify a project.
1760 The entire tree below a headline matched by this is considered a project.
1761 2. A list of TODO keywords itentifying non-stuck projects.
1762 If the project subtree contains any headline with one of these todo
1763 keywords, the project is consitered to be not stuck.
1764 3. A list of tags identifying non-stuck projects.
1765 If the project subtree contains any headline with one of these tags,
1766 the project is consitered to be not stuck.
1768 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1769 or `C-c a #' to produce the list."
1770 :group 'org-agenda-custom-commands
1771 :type '(list
1772 (string :tag "Tags/TODO match to identify a project")
1773 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1774 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))))
1777 (defgroup org-agenda-skip nil
1778 "Options concerning skipping parts of agenda files."
1779 :tag "Org Agenda Skip"
1780 :group 'org-agenda)
1782 (defcustom org-agenda-todo-list-sublevels t
1783 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1784 When nil, the sublevels of a TODO entry are not checked, resulting in
1785 potentially much shorter TODO lists."
1786 :group 'org-agenda-skip
1787 :group 'org-todo
1788 :type 'boolean)
1790 (defcustom org-agenda-todo-ignore-scheduled nil
1791 "Non-nil means, don't show scheduled entries in the global todo list.
1792 The idea behind this is that by scheduling it, you have already taken care
1793 of this item."
1794 :group 'org-agenda-skip
1795 :group 'org-todo
1796 :type 'boolean)
1798 (defcustom org-agenda-todo-ignore-deadlines nil
1799 "Non-nil means, don't show near deadline entries in the global todo list.
1800 Near means closer than `org-deadline-warning-days' days.
1801 The idea behind this is that such items will appear in the agenda anyway."
1802 :group 'org-agenda-skip
1803 :group 'org-todo
1804 :type 'boolean)
1806 (defcustom org-agenda-skip-scheduled-if-done nil
1807 "Non-nil means don't show scheduled items in agenda when they are done.
1808 This is relevant for the daily/weekly agenda, not for the TODO list."
1809 :group 'org-agenda-skip
1810 :type 'boolean)
1812 (defcustom org-timeline-show-empty-dates 3
1813 "Non-nil means, `org-timeline' also shows dates without an entry.
1814 When nil, only the days which actually have entries are shown.
1815 When t, all days between the first and the last date are shown.
1816 When an integer, show also empty dates, but if there is a gap of more than
1817 N days, just insert a special line indicating the size of the gap."
1818 :group 'org-agenda-skip ; FIXME: not quite the right group...
1819 :type '(choice
1820 (const :tag "None" nil)
1821 (const :tag "All" t)
1822 (number :tag "at most")))
1825 (defgroup org-agenda-startup nil
1826 "Options concerning initial settings in the Agenda in Org Mode."
1827 :tag "Org Agenda Startup"
1828 :group 'org-agenda)
1830 (defcustom org-finalize-agenda-hook nil
1831 "Hook run just before displaying an agenda buffer."
1832 :group 'org-agenda-startup
1833 :type 'hook)
1835 (defcustom org-agenda-mouse-1-follows-link nil
1836 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1837 A longer mouse click will still set point. Does not wortk on XEmacs.
1838 Needs to be set before org.el is loaded."
1839 :group 'org-agenda-startup
1840 :type 'boolean)
1842 (defcustom org-agenda-start-with-follow-mode nil
1843 "The initial value of follwo-mode in a newly created agenda window."
1844 :group 'org-agenda-startup
1845 :type 'boolean)
1847 (defgroup org-agenda-windows nil
1848 "Options concerning the windows used by the Agenda in Org Mode."
1849 :tag "Org Agenda Windows"
1850 :group 'org-agenda)
1852 (defcustom org-agenda-window-setup 'reorganize-frame
1853 "How the agenda buffer should be displayed.
1854 Possible values for this option are:
1856 current-window Show agenda in the current window, keeping all other windows.
1857 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1858 other-window Use `switch-to-buffer-other-window' to display agenda.
1859 reorganize-frame Show only two windows on the current frame, the current
1860 window and the agenda. Also, if the option
1861 `org-fit-agenda-window' is set, resize the agenda window to
1862 try to show as much as possible of the buffer content.
1863 See also the variable `org-agenda-restore-windows-after-quit'."
1864 :group 'org-agenda-windows
1865 :type '(choice
1866 (const current-window)
1867 (const other-frame)
1868 (const other-window)
1869 (const reorganize-frame)))
1871 (defcustom org-agenda-restore-windows-after-quit nil
1872 "Non-nil means, restore window configuration open exiting agenda.
1873 Before the window configuration is changed for displaying the agenda,
1874 the current status is recorded. When the agenda is exited with
1875 `q' or `x' and this option is set, the old state is restored. If
1876 `org-agenda-window-setup' is `other-frame', the value of this
1877 option will be ignored.."
1878 :group 'org-agenda-windows
1879 :type 'boolean)
1881 ;; FIXME: I think this variable could be removed, default set to t
1882 (defcustom org-select-agenda-window t
1883 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1884 When nil, cursor will remain in the current window."
1885 :group 'org-agenda-windows
1886 :type 'boolean)
1888 ;; FIXME: I think this variable could be removed, default set to t
1889 (defcustom org-fit-agenda-window t
1890 "Non-nil means, change window size of agenda to fit content.
1891 This is only effective if `org-agenda-window-setup' is `reorganize-frame'."
1892 :group 'org-agenda-windows
1893 :type 'boolean)
1895 (defcustom org-indirect-buffer-display 'other-window
1896 "How should indirect tree buffers be displayed?
1897 This applies to indirect buffers created with the commands
1898 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1899 Valid values are:
1900 current-window Display in the current window
1901 other-window Just display in another window.
1902 dedicated-frame Create one new frame, and re-use it each time.
1903 new-frame Make a new frame each time."
1904 :group 'org-structure
1905 :group 'org-agenda-windows
1906 :type '(choice
1907 (const :tag "In current window" current-window)
1908 (const :tag "In current frame, other window" other-window)
1909 (const :tag "Each time a new frame" new-frame)
1910 (const :tag "One dedicated frame" dedicated-frame)))
1912 (defgroup org-agenda-daily/weekly nil
1913 "Options concerning the daily/weekly agenda."
1914 :tag "Org Agenda Daily/Weekly"
1915 :group 'org-agenda)
1917 (defcustom org-agenda-ndays 7
1918 "Number of days to include in overview display.
1919 Should be 1 or 7."
1920 :group 'org-agenda-daily/weekly
1921 :type 'number)
1923 (defcustom org-agenda-start-on-weekday 1
1924 "Non-nil means, start the overview always on the specified weekday.
1925 0 denotes Sunday, 1 denotes Monday etc.
1926 When nil, always start on the current day."
1927 :group 'org-agenda-daily/weekly
1928 :type '(choice (const :tag "Today" nil)
1929 (number :tag "Weekday No.")))
1930 (defcustom org-agenda-show-all-dates t
1931 "Non-nil means, `org-agenda' shows every day in the selected range.
1932 When nil, only the days which actually have entries are shown."
1933 :group 'org-agenda-daily/weekly
1934 :type 'boolean)
1936 (defcustom org-agenda-include-diary nil
1937 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1938 :group 'org-agenda-daily/weekly
1939 :type 'boolean)
1941 ;; FIXME: This variable could be removed
1942 (defcustom org-agenda-include-all-todo nil
1943 "Set means weekly/daily agenda will always contain all TODO entries.
1944 The TODO entries will be listed at the top of the agenda, before
1945 the entries for specific days."
1946 :group 'org-agenda-daily/weekly
1947 :type 'boolean)
1949 (defgroup org-agenda-time-grid nil
1950 "Options concerning the time grid in the Org-mode Agenda."
1951 :tag "Org Agenda Time Grid"
1952 :group 'org-agenda)
1954 (defcustom org-agenda-use-time-grid t
1955 "Non-nil means, show a time grid in the agenda schedule.
1956 A time grid is a set of lines for specific times (like every two hours between
1957 8:00 and 20:00). The items scheduled for a day at specific times are
1958 sorted in between these lines.
1959 For details about when the grid will be shown, and what it will look like, see
1960 the variable `org-agenda-time-grid'."
1961 :group 'org-agenda-time-grid
1962 :type 'boolean)
1964 (defcustom org-agenda-time-grid
1965 '((daily today require-timed)
1966 "----------------"
1967 (800 1000 1200 1400 1600 1800 2000))
1969 "The settings for time grid for agenda display.
1970 This is a list of three items. The first item is again a list. It contains
1971 symbols specifying conditions when the grid should be displayed:
1973 daily if the agenda shows a single day
1974 weekly if the agenda shows an entire week
1975 today show grid on current date, independent of daily/weekly display
1976 require-timed show grid only if at least one item has a time specification
1978 The second item is a string which will be places behing the grid time.
1980 The third item is a list of integers, indicating the times that should have
1981 a grid line."
1982 :group 'org-agenda-time-grid
1983 :type
1984 '(list
1985 (set :greedy t :tag "Grid Display Options"
1986 (const :tag "Show grid in single day agenda display" daily)
1987 (const :tag "Show grid in weekly agenda display" weekly)
1988 (const :tag "Always show grid for today" today)
1989 (const :tag "Show grid only if any timed entries are present"
1990 require-timed)
1991 (const :tag "Skip grid times already present in an entry"
1992 remove-match))
1993 (string :tag "Grid String")
1994 (repeat :tag "Grid Times" (integer :tag "Time"))))
1996 (defgroup org-agenda-sorting nil
1997 "Options concerning sorting in the Org-mode Agenda."
1998 :tag "Org Agenda Sorting"
1999 :group 'org-agenda)
2001 (let ((sorting-choice
2002 '(choice
2003 (const time-up) (const time-down)
2004 (const category-keep) (const category-up) (const category-down)
2005 (const tag-down) (const tag-up)
2006 (const priority-up) (const priority-down))))
2008 (defcustom org-agenda-sorting-strategy
2009 '((agenda time-up category-keep priority-down)
2010 (todo category-keep priority-down)
2011 (tags category-keep))
2012 "Sorting structure for the agenda items of a single day.
2013 This is a list of symbols which will be used in sequence to determine
2014 if an entry should be listed before another entry. The following
2015 symbols are recognized:
2017 time-up Put entries with time-of-day indications first, early first
2018 time-down Put entries with time-of-day indications first, late first
2019 category-keep Keep the default order of categories, corresponding to the
2020 sequence in `org-agenda-files'.
2021 category-up Sort alphabetically by category, A-Z.
2022 category-down Sort alphabetically by category, Z-A.
2023 tag-up Sort alphabetically by last tag, A-Z.
2024 tag-down Sort alphabetically by last tag, Z-A.
2025 priority-up Sort numerically by priority, high priority last.
2026 priority-down Sort numerically by priority, high priority first.
2028 The different possibilities will be tried in sequence, and testing stops
2029 if one comparison returns a \"not-equal\". For example, the default
2030 '(time-up category-keep priority-down)
2031 means: Pull out all entries having a specified time of day and sort them,
2032 in order to make a time schedule for the current day the first thing in the
2033 agenda listing for the day. Of the entries without a time indication, keep
2034 the grouped in categories, don't sort the categories, but keep them in
2035 the sequence given in `org-agenda-files'. Within each category sort by
2036 priority.
2038 Leaving out `category-keep' would mean that items will be sorted across
2039 categories by priority."
2040 :group 'org-agenda-sorting
2041 :type `(choice
2042 (repeat :tag "General" ,sorting-choice)
2043 (list :tag "Individually"
2044 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2045 (repeat ,sorting-choice))
2046 (cons (const :tag "Strategy for TODO lists" todo)
2047 (repeat ,sorting-choice))
2048 (cons (const :tag "Strategy for Tags matches" tags)
2049 (repeat ,sorting-choice))))))
2051 (defcustom org-sort-agenda-notime-is-late t
2052 "Non-nil means, items without time are considered late.
2053 This is only relevant for sorting. When t, items which have no explicit
2054 time like 15:30 will be considered as 99:01, i.e. later than any items which
2055 do have a time. When nil, the default time is before 0:00. You can use this
2056 option to decide if the schedule for today should come before or after timeless
2057 agenda entries."
2058 :group 'org-agenda-sorting
2059 :type 'boolean)
2061 (defgroup org-agenda-prefix nil
2062 "Options concerning the entry prefix in the Org-mode agenda display."
2063 :tag "Org Agenda Prefix"
2064 :group 'org-agenda)
2066 (defcustom org-agenda-prefix-format
2067 '((agenda . " %-12:c%?-12t% s")
2068 (timeline . " % s")
2069 (todo . " %-12:c")
2070 (tags . " %-12:c"))
2071 "Format specifications for the prefix of items in the agenda views.
2072 An alist with four entries, for the different agenda types. The keys to the
2073 sublists are `agenda', `timeline', `todo', and `tags'. The values
2074 are format strings.
2075 This format works similar to a printf format, with the following meaning:
2077 %c the category of the item, \"Diary\" for entries from the diary, or
2078 as given by the CATEGORY keyword or derived from the file name.
2079 %T the *last* tag of the item. Last because inherited tags come
2080 first in the list.
2081 %t the time-of-day specification if one applies to the entry, in the
2082 format HH:MM
2083 %s Scheduling/Deadline information, a short string
2085 All specifiers work basically like the standard `%s' of printf, but may
2086 contain two additional characters: A question mark just after the `%' and
2087 a whitespace/punctuation character just before the final letter.
2089 If the first character after `%' is a question mark, the entire field
2090 will only be included if the corresponding value applies to the
2091 current entry. This is useful for fields which should have fixed
2092 width when present, but zero width when absent. For example,
2093 \"%?-12t\" will result in a 12 character time field if a time of the
2094 day is specified, but will completely disappear in entries which do
2095 not contain a time.
2097 If there is punctuation or whitespace character just before the final
2098 format letter, this character will be appended to the field value if
2099 the value is not empty. For example, the format \"%-12:c\" leads to
2100 \"Diary: \" if the category is \"Diary\". If the category were be
2101 empty, no additional colon would be interted.
2103 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2104 - Indent the line with two space characters
2105 - Give the category in a 12 chars wide field, padded with whitespace on
2106 the right (because of `-'). Append a colon if there is a category
2107 (because of `:').
2108 - If there is a time-of-day, put it into a 12 chars wide field. If no
2109 time, don't put in an empty field, just skip it (because of '?').
2110 - Finally, put the scheduling information and append a whitespace.
2112 As another example, if you don't want the time-of-day of entries in
2113 the prefix, you could use:
2115 (setq org-agenda-prefix-format \" %-11:c% s\")
2117 See also the variables `org-agenda-remove-times-when-in-prefix' and
2118 `org-agenda-remove-tags-when-in-prefix'."
2119 :type '(choice
2120 (string :tag "General format")
2121 (list :greedy t :tag "View dependent"
2122 (cons (const agenda) (string :tag "Format"))
2123 (cons (const timeline) (string :tag "Format"))
2124 (cons (const todo) (string :tag "Format"))
2125 (cons (const tags) (string :tag "Format"))))
2126 :group 'org-agenda-prefix)
2128 (defvar org-prefix-format-compiled nil
2129 "The compiled version of the most recently used prefix format.
2130 See the variable `org-agenda-prefix-format'.")
2132 (defcustom org-agenda-remove-times-when-in-prefix t
2133 "Non-nil means, remove duplicate time specifications in agenda items.
2134 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2135 time-of-day specification in a headline or diary entry is extracted and
2136 placed into the prefix. If this option is non-nil, the original specification
2137 \(a timestamp or -range, or just a plain time(range) specification like
2138 11:30-4pm) will be removed for agenda display. This makes the agenda less
2139 cluttered.
2140 The option can be t or nil. It may also be the symbol `beg', indicating
2141 that the time should only be removed what it is located at the beginning of
2142 the headline/diary entry."
2143 :group 'org-agenda-prefix
2144 :type '(choice
2145 (const :tag "Always" t)
2146 (const :tag "Never" nil)
2147 (const :tag "When at beginning of entry" beg)))
2149 (defcustom org-agenda-remove-tags-when-in-prefix nil
2150 "Non-nil means, remove the tags from the headline copy in the agenda.
2151 When this is the symbol `prefix', only remove tags when
2152 `org-agenda-prefix-format' contains a `%T' specifier."
2153 :group 'org-agenda-prefix
2154 :type '(choice
2155 (const :tag "Always" t)
2156 (const :tag "Never" nil)
2157 (const :tag "When prefix format contains %T" prefix)))
2159 (defcustom org-agenda-align-tags-to-column 65
2160 "Shift tags in agenda items to this column."
2161 :group 'org-agenda-prefix
2162 :type 'integer)
2164 (defgroup org-latex nil
2165 "Options for embedding LaTeX code into Org-mode"
2166 :tag "Org LaTeX"
2167 :group 'org)
2169 (defcustom org-format-latex-options
2170 '(:foreground "Black" :background "Transparent" :scale 1.0
2171 :matchers ("begin" "$" "$$" "\\(" "\\["))
2172 "Options for creating images from LaTeX fragments.
2173 This is a property list with the following properties:
2174 :foreground the foreground color, for example \"Black\".
2175 :background the background color, or \"Transparent\".
2176 :scale a scaling factor for the size of the images
2177 :matchers a list indicating which matchers should be used to
2178 find LaTeX fragments. Valid members of this list are:
2179 \"begin\" find environments
2180 \"$\" find math expressions surrounded by $...$
2181 \"$$\" find math expressions surrounded by $$....$$
2182 \"\\(\" find math expressions surrounded by \\(...\\)
2183 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2184 :group 'org-latex
2185 :type 'plist)
2187 (defgroup org-export nil
2188 "Options for exporting org-listings."
2189 :tag "Org Export"
2190 :group 'org)
2192 (defgroup org-export-general nil
2193 "General options for exporting Org-mode files."
2194 :tag "Org Export General"
2195 :group 'org-export)
2197 (defcustom org-export-publishing-directory "."
2198 "Path to the location where exported files should be located.
2199 This path may be relative to the directory where the Org-mode file lives.
2200 The default is to put them into the same directory as the Org-mode file.
2201 The variable may also be an alist with export types `:html', `:ascii',
2202 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2203 is relative, it is interpreted relative to the directory where the exported
2204 Org-mode files lives."
2205 :group 'org-export-general
2206 :type '(choice
2207 (directory)
2208 (repeat
2209 (cons
2210 (choice :tag "Type"
2211 (const :html) (const :ascii) (const :ical) (const :xoxo))
2212 (directory)))))
2214 (defcustom org-export-language-setup
2215 '(("en" "Author" "Date" "Table of Contents")
2216 ("cs" "Autor" "Datum" "Obsah")
2217 ("da" "Ophavsmand" "Dato" "Indhold")
2218 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2219 ("es" "Autor" "Fecha" "\xccndice")
2220 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2221 ("it" "Autore" "Data" "Indice")
2222 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2223 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2224 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2225 "Terms used in export text, translated to different languages.
2226 Use the variable `org-export-default-language' to set the language,
2227 or use the +OPTION lines for a per-file setting."
2228 :group 'org-export-general
2229 :type '(repeat
2230 (list
2231 (string :tag "HTML language tag")
2232 (string :tag "Author")
2233 (string :tag "Date")
2234 (string :tag "Table of Contents"))))
2236 (defcustom org-export-default-language "en"
2237 "The default language of HTML export, as a string.
2238 This should have an association in `org-export-language-setup'."
2239 :group 'org-export-general
2240 :type 'string)
2242 (defcustom org-export-headline-levels 3
2243 "The last level which is still exported as a headline.
2244 Inferior levels will produce itemize lists when exported.
2245 Note that a numeric prefix argument to an exporter function overrides
2246 this setting.
2248 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2249 :group 'org-export-general
2250 :type 'number)
2252 (defcustom org-export-with-section-numbers t
2253 "Non-nil means, add section numbers to headlines when exporting.
2255 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2256 :group 'org-export-general
2257 :type 'boolean)
2259 (defcustom org-export-with-toc t
2260 "Non-nil means, create a table of contents in exported files.
2261 The TOC contains headlines with levels up to`org-export-headline-levels'.
2263 Headlines which contain any TODO items will be marked with \"(*)\" in
2264 ASCII export, and with red color in HTML output.
2266 In HTML output, the TOC will be clickable.
2268 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
2269 :group 'org-export-general
2270 :type 'boolean)
2272 (defcustom org-export-mark-todo-in-toc nil
2273 "Non-nil means, mark TOC lines that contain any open TODO items."
2274 :group 'org-export-general
2275 :type 'boolean)
2277 (defcustom org-export-preserve-breaks nil
2278 "Non-nil means, preserve all line breaks when exporting.
2279 Normally, in HTML output paragraphs will be reformatted. In ASCII
2280 export, line breaks will always be preserved, regardless of this variable.
2282 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2283 :group 'org-export-general
2284 :type 'boolean)
2286 (defcustom org-export-with-archived-trees 'headline
2287 "Whether subtrees with the ARCHIVE tag should be exported.
2288 This can have three different values
2289 nil Do not export, pretend this tree is not present
2290 t Do export the entire tree
2291 headline Only export the headline, but skip the tree below it."
2292 :group 'org-export-general
2293 :group 'org-archive
2294 :type '(choice
2295 (const :tag "not at all" nil)
2296 (const :tag "headline only" 'headline)
2297 (const :tag "entirely" t)))
2299 (defcustom org-export-with-timestamps t
2300 "If nil, do not export time stamps and associated keywords."
2301 :group 'org-export-general
2302 :type 'boolean)
2304 (defcustom org-export-remove-timestamps-from-toc t
2305 "If nil, remove timestamps from the table of contents entries."
2306 :group 'org-export-general
2307 :type 'boolean)
2309 (defcustom org-export-with-tags 'not-in-toc
2310 "If nil, do not export tags, just remove them from headlines.
2311 If this is the symbol `not-in-toc', tags will be removed from table of
2312 contents entries, but still be shown in the headlines of the document."
2313 :group 'org-export-general
2314 :type '(choice
2315 (const :tag "Off" nil)
2316 (const :tag "Not in TOC" not-in-toc)
2317 (const :tag "On" t)))
2319 (defgroup org-export-translation nil
2320 "Options for translating special ascii sequences for the export backends."
2321 :tag "Org Export Translation"
2322 :group 'org-export)
2324 (defcustom org-export-with-emphasize t
2325 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2326 If the export target supports emphasizing text, the word will be
2327 typeset in bold, italic, or underlined, respectively. Works only for
2328 single words, but you can say: I *really* *mean* *this*.
2329 Not all export backends support this.
2331 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2332 :group 'org-export-translation
2333 :type 'boolean)
2335 (defcustom org-export-with-sub-superscripts t
2336 "Non-nil means, interpret \"_\" and \"^\" for export.
2337 When this option is turned on, you can use TeX-like syntax for sub- and
2338 superscripts. Several characters after \"_\" or \"^\" will be
2339 considered as a single item - so grouping with {} is normally not
2340 needed. For example, the following things will be parsed as single
2341 sub- or superscripts.
2343 10^24 or 10^tau several digits will be considered 1 item.
2344 10^-12 or 10^-tau a leading sign with digits or a word
2345 x^2-y^3 will be read as x^2 - y^3, because items are
2346 terminated by almost any nonword/nondigit char.
2347 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2349 Still, ambiguity is possible - so when in doubt use {} to enclose the
2350 sub/superscript.
2351 Not all export backends support this, but HTML does.
2353 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2354 :group 'org-export-translation
2355 :type 'boolean)
2357 (defcustom org-export-with-TeX-macros t
2358 "Non-nil means, interpret simple TeX-like macros when exporting.
2359 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2360 No only real TeX macros will work here, but the standard HTML entities
2361 for math can be used as macro names as well. For a list of supported
2362 names in HTML export, see the constant `org-html-entities'.
2363 Not all export backends support this.
2365 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2366 :group 'org-export-translation
2367 :group 'org-latex
2368 :type 'boolean)
2370 (defcustom org-export-with-LaTeX-fragments nil
2371 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2372 When set, the exporter will find LaTeX environments if the \\begin line is
2373 the first non-white thing on a line. It will also find the math delimiters
2374 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2375 display math.
2377 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2378 :group 'org-export-translation
2379 :group 'org-latex
2380 :type 'boolean)
2382 (defcustom org-export-with-fixed-width t
2383 "Non-nil means, lines starting with \":\" will be in fixed width font.
2384 This can be used to have pre-formatted text, fragments of code etc. For
2385 example:
2386 : ;; Some Lisp examples
2387 : (while (defc cnt)
2388 : (ding))
2389 will be looking just like this in also HTML. See also the QUOTE keyword.
2390 Not all export backends support this.
2392 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2393 :group 'org-export-translation
2394 :type 'boolean)
2396 (defcustom org-match-sexp-depth 3
2397 "Number of stacked braces for sub/superscript matching.
2398 This has to be set before loading org.el to be effective."
2399 :group 'org-export-translation
2400 :type 'integer)
2402 (defgroup org-export-tables nil
2403 "Options for exporting tables in Org-mode."
2404 :tag "Org Export Tables"
2405 :group 'org-export)
2407 (defcustom org-export-with-tables t
2408 "If non-nil, lines starting with \"|\" define a table.
2409 For example:
2411 | Name | Address | Birthday |
2412 |-------------+----------+-----------|
2413 | Arthur Dent | England | 29.2.2100 |
2415 Not all export backends support this.
2417 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2418 :group 'org-export-tables
2419 :type 'boolean)
2421 (defcustom org-export-highlight-first-table-line t
2422 "Non-nil means, highlight the first table line.
2423 In HTML export, this means use <th> instead of <td>.
2424 In tables created with table.el, this applies to the first table line.
2425 In Org-mode tables, all lines before the first horizontal separator
2426 line will be formatted with <th> tags."
2427 :group 'org-export-tables
2428 :type 'boolean)
2430 (defcustom org-export-table-remove-special-lines t
2431 "Remove special lines and marking characters in calculating tables.
2432 This removes the special marking character column from tables that are set
2433 up for spreadsheet calculations. It also removes the entire lines
2434 marked with `!', `_', or `^'. The lines with `$' are kept, because
2435 the values of constants may be useful to have."
2436 :group 'org-export-tables
2437 :type 'boolean)
2439 (defcustom org-export-prefer-native-exporter-for-tables nil
2440 "Non-nil means, always export tables created with table.el natively.
2441 Natively means, use the HTML code generator in table.el.
2442 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2443 the table does not use row- or column-spanning). This has the
2444 advantage, that the automatic HTML conversions for math symbols and
2445 sub/superscripts can be applied. Org-mode's HTML generator is also
2446 much faster."
2447 :group 'org-export-tables
2448 :type 'boolean)
2450 (defgroup org-export-ascii nil
2451 "Options specific for ASCII export of Org-mode files."
2452 :tag "Org Export ASCII"
2453 :group 'org-export)
2455 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2456 "Characters for underlining headings in ASCII export.
2457 In the given sequence, these characters will be used for level 1, 2, ..."
2458 :group 'org-export-ascii
2459 :type '(repeat character))
2461 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2462 "Bullet characters for headlines converted to lists in ASCII export.
2463 The first character is is used for the first lest level generated in this
2464 way, and so on. If there are more levels than characters given here,
2465 the list will be repeated.
2466 Note that plain lists will keep the same bullets as the have in the
2467 Org-mode file."
2468 :group 'org-export-ascii
2469 :type '(repeat character))
2471 (defcustom org-export-ascii-show-new-buffer t
2472 "Non-nil means, popup buffer containing the exported ASCII text.
2473 Otherwise the buffer will just be saved to a file and stay hidden."
2474 :group 'org-export-ascii
2475 :type 'boolean)
2477 (defgroup org-export-xml nil
2478 "Options specific for XML export of Org-mode files."
2479 :tag "Org Export XML"
2480 :group 'org-export)
2482 (defgroup org-export-html nil
2483 "Options specific for HTML export of Org-mode files."
2484 :tag "Org Export HTML"
2485 :group 'org-export)
2487 (defcustom org-export-html-style
2488 "<style type=\"text/css\">
2489 html {
2490 font-family: Times, serif;
2491 font-size: 12pt;
2493 .title { text-align: center; }
2494 .todo { color: red; }
2495 .done { color: green; }
2496 .timestamp { color: grey }
2497 .timestamp-kwd { color: CadetBlue }
2498 .tag { background-color:lightblue; font-weight:normal }
2499 .target { background-color: lavender; }
2500 pre {
2501 border: 1pt solid #AEBDCC;
2502 background-color: #F3F5F7;
2503 padding: 5pt;
2504 font-family: courier, monospace;
2506 table { border-collapse: collapse; }
2507 td, th {
2508 vertical-align: top;
2509 border: 1pt solid #ADB9CC;
2511 </style>"
2512 "The default style specification for exported HTML files.
2513 Since there are different ways of setting style information, this variable
2514 needs to contain the full HTML structure to provide a style, including the
2515 surrounding HTML tags. The style specifications should include definitions
2516 for new classes todo, done, title, and deadline. For example, legal values
2517 would be:
2519 <style type=\"text/css\">
2520 p { font-weight: normal; color: gray; }
2521 h1 { color: black; }
2522 .title { text-align: center; }
2523 .todo, .deadline { color: red; }
2524 .done { color: green; }
2525 </style>
2527 or, if you want to keep the style in a file,
2529 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2531 As the value of this option simply gets inserted into the HTML <head> header,
2532 you can \"misuse\" it to add arbitrary text to the header."
2533 :group 'org-export-html
2534 :type 'string)
2536 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2537 "Format for typesetting the document title in HTML export."
2538 :group 'org-export-html
2539 :type 'string)
2541 (defcustom org-export-html-toplevel-hlevel 2
2542 "The <H> level for level 1 headings in HTML export."
2543 :group 'org-export-html
2544 :type 'string)
2546 (defcustom org-export-html-link-org-files-as-html t
2547 "Non-nil means, make file links to `file.org' point to `file.html'.
2548 When org-mode is exporting an org-mode file to HTML, links to
2549 non-html files are directly put into a href tag in HTML.
2550 However, links to other Org-mode files (recognized by the
2551 extension `.org.) should become links to the corresponding html
2552 file, assuming that the linked org-mode file will also be
2553 converted to HTML.
2554 When nil, the links still point to the plain `.org' file."
2555 :group 'org-export-html
2556 :type 'boolean)
2558 (defcustom org-export-html-inline-images 'maybe
2559 "Non-nil means, inline images into exported HTML pages.
2560 This is done using an <img> tag. When nil, an anchor with href is used to
2561 link to the image. If this option is `maybe', then images in links with
2562 an empty description will be inlined, while images with a description will
2563 be linked only."
2564 :group 'org-export-html
2565 :type '(choice (const :tag "Never" nil)
2566 (const :tag "Always" t)
2567 (const :tag "When there is no description" maybe)))
2569 (defcustom org-export-html-expand t
2570 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2571 When nil, these tags will be exported as plain text and therefore
2572 not be interpreted by a browser.
2574 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2575 :group 'org-export-html
2576 :type 'boolean)
2578 (defcustom org-export-html-table-tag
2579 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2580 "The HTML tag used to start a table.
2581 This must be a <table> tag, but you may change the options like
2582 borders and spacing."
2583 :group 'org-export-html
2584 :type 'string)
2586 (defcustom org-export-html-with-timestamp nil
2587 "If non-nil, write `org-export-html-html-helper-timestamp'
2588 into the exported HTML text. Otherwise, the buffer will just be saved
2589 to a file."
2590 :group 'org-export-html
2591 :type 'boolean)
2593 (defcustom org-export-html-html-helper-timestamp
2594 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2595 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2596 :group 'org-export-html
2597 :type 'string)
2599 (defcustom org-export-html-show-new-buffer nil
2600 "Non-nil means, popup buffer containing the exported html text.
2601 Otherwise, the buffer will just be saved to a file and stay hidden."
2602 :group 'org-export-html
2603 :type 'boolean)
2605 (defgroup org-export-icalendar nil
2606 "Options specific for iCalendar export of Org-mode files."
2607 :tag "Org Export iCalendar"
2608 :group 'org-export)
2610 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2611 "The file name for the iCalendar file covering all agenda files.
2612 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2613 The file name should be absolute."
2614 :group 'org-export-icalendar
2615 :type 'file)
2617 (defcustom org-icalendar-include-todo nil
2618 "Non-nil means, export to iCalendar files should also cover TODO items."
2619 :group 'org-export-icalendar
2620 :type 'boolean)
2622 (defcustom org-icalendar-combined-name "OrgMode"
2623 "Calendar name for the combined iCalendar representing all agenda files."
2624 :group 'org-export-icalendar
2625 :type 'string)
2627 (defgroup org-font-lock nil
2628 "Font-lock settings for highlighting in Org-mode."
2629 :tag "Org Font Lock"
2630 :group 'org)
2632 (defcustom org-level-color-stars-only nil
2633 "Non-nil means fontify only the stars in each headline.
2634 When nil, the entire headline is fontified.
2635 Changing it requires restart of `font-lock-mode' to become effective
2636 also in regions already fontified."
2637 :group 'org-font-lock
2638 :type 'boolean)
2640 (defcustom org-hide-leading-stars nil
2641 "Non-nil means, hide the first N-1 stars in a headline.
2642 This works by using the face `org-hide' for these stars. This
2643 face is white for a light background, and black for a dark
2644 background. You may have to customize the face `org-hide' to
2645 make this work.
2646 Changing it requires restart of `font-lock-mode' to become effective
2647 also in regions already fontified.
2648 You may also set this on a per-file basis by adding one of the following
2649 lines to the buffer:
2651 #+STARTUP: hidestars
2652 #+STARTUP: showstars"
2653 :group 'org-font-lock
2654 :type 'boolean)
2656 (defcustom org-fontify-done-headline nil
2657 "Non-nil means, change the face of a headline if it is marked DONE.
2658 Normally, only the TODO/DONE keyword indicates the state of a headline.
2659 When this is non-nil, the headline after the keyword is set to the
2660 `org-headline-done' as an additional indication."
2661 :group 'org-font-lock
2662 :type 'boolean)
2664 (defcustom org-fontify-emphasized-text t
2665 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2666 Changing this variable requires a restart of Emacs to take effect."
2667 :group 'org-font-lock
2668 :type 'boolean)
2670 (defvar org-emph-re nil
2671 "Regular expression for matching emphasis.")
2672 (defvar org-emphasis-regexp-components) ; defined just below
2673 (defvar org-emphasis-alist) ; defined just below
2674 (defun org-set-emph-re (var val)
2675 "Set variable and compute the emphasis regular expression."
2676 (set var val)
2677 (when (and (boundp 'org-emphasis-alist)
2678 (boundp 'org-emphasis-regexp-components)
2679 org-emphasis-alist org-emphasis-regexp-components)
2680 (let* ((e org-emphasis-regexp-components)
2681 (pre (car e))
2682 (post (nth 1 e))
2683 (border (nth 2 e))
2684 (body (nth 3 e))
2685 (nl (nth 4 e))
2686 (stacked (nth 5 e))
2687 (body1 (concat body "*?"))
2688 (markers (mapconcat 'car org-emphasis-alist "")))
2689 ;; make sure special characters appear at the right position in the class
2690 (if (string-match "\\^" markers)
2691 (setq markers (concat (replace-match "" t t markers) "^")))
2692 (if (string-match "-" markers)
2693 (setq markers (concat (replace-match "" t t markers) "-")))
2694 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2695 ; (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\\(?:\n?" body "*?\\)?")))
2696 (if (> nl 0)
2697 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2698 (int-to-string nl) "\\}")))
2699 ;; Make the regexp
2700 (setq org-emph-re
2701 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2702 "\\("
2703 "\\([" markers "]\\)"
2704 "\\("
2705 "[^" border markers "]"
2706 body1
2707 "[^" border markers "]"
2708 "\\)"
2709 "\\3\\)"
2710 "\\([" post (if stacked markers) "]\\|$\\)")))))
2712 (defcustom org-emphasis-regexp-components
2713 '(" \t('\"" " \t.,?;'\")" " \t\r\n," "." 1 nil)
2714 "Components used to build the reqular expression for emphasis.
2715 This is a list with 6 entries. Terminology: In an emphasis string
2716 like \" *strong word* \", we call the initial space PREMATCH, the final
2717 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2718 and \"trong wor\" is the body. The different components in this variable
2719 specify what is allowed/forbidden in each part:
2721 pre Chars allowed as prematch. Beginning of line will be allowed too.
2722 post Chars allowed as postmatch. End of line will be allowed too.
2723 border The chars *forbidden* as border characters. In addition to the
2724 characters given here, all marker characters are forbidden too.
2725 body-regexp A regexp like \".\" to match a body character. Don't use
2726 non-shy groups here, and don't allow newline here.
2727 newline The maximum number of newlines allowed in an emphasis exp.
2728 stacked Non-nil means, allow stacked styles. This works only in HTML
2729 export. When this is set, all marker characters (as given in
2730 `org-emphasis-alist') will be allowed as pre/post, aiding
2731 inside-out matching.
2732 Use customize to modify this, or restart Emacs after changing it."
2733 :group 'org-font-lock
2734 :set 'org-set-emph-re
2735 :type '(list
2736 (sexp :tag "Allowed chars in pre ")
2737 (sexp :tag "Allowed chars in post ")
2738 (sexp :tag "Forbidden chars in border ")
2739 (sexp :tag "Regexp for body ")
2740 (integer :tag "number of newlines allowed")
2741 (boolean :tag "Stacking allowed ")))
2743 (defcustom org-emphasis-alist
2744 '(("*" bold "<b>" "</b>")
2745 ("/" italic "<i>" "</i>")
2746 ("_" underline "<u>" "</u>")
2747 ("=" shadow "<code>" "</code>")
2748 ("+" (:strike-through t) "<del>" "</del>")
2750 "Special syntax for emphasized text.
2751 Text starting and ending with a special character will be emphasized, for
2752 example *bold*, _underlined_ and /italic/. This variable sets the marker
2753 characters, the face to bbe used by font-lock for highlighting in Org-mode
2754 Emacs buffers, and the HTML tags to be used for this.
2755 Use customize to modify this, or restart Emacs after changing it."
2756 :group 'org-font-lock
2757 :set 'org-set-emph-re
2758 :type '(repeat
2759 (list
2760 (string :tag "Marker character")
2761 (choice
2762 (face :tag "Font-lock-face")
2763 (plist :tag "Face property list"))
2764 (string :tag "HTML start tag")
2765 (string :tag "HTML end tag"))))
2767 ;;; The faces
2769 (defgroup org-faces nil
2770 "Faces in Org-mode."
2771 :tag "Org Faces"
2772 :group 'org-font-lock)
2774 (defun org-compatible-face (specs)
2775 "Make a compatible face specification.
2776 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2777 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2778 to the top of the list. The `min-colors' attribute will be removed from
2779 any other entries, and any resulting duplicates will be removed entirely."
2780 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2781 (let (r e a)
2782 (while (setq e (pop specs))
2783 (cond
2784 ((memq (car e) '(t default)) (push e r))
2785 ((setq a (member '(min-colors 8) (car e)))
2786 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2787 (cdr e)))))
2788 ((setq a (assq 'min-colors (car e)))
2789 (setq e (cons (delq a (car e)) (cdr e)))
2790 (or (assoc (car e) r) (push e r)))
2791 (t (or (assoc (car e) r) (push e r)))))
2792 (nreverse r))
2793 specs))
2795 (defface org-hide
2796 '((((background light)) (:foreground "white"))
2797 (((background dark)) (:foreground "black")))
2798 "Face used to hide leading stars in headlines.
2799 The forground color of this face should be equal to the background
2800 color of the frame."
2801 :group 'org-faces)
2803 (defface org-level-1 ;; font-lock-function-name-face
2804 (org-compatible-face
2805 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2806 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2807 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2808 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2809 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2810 (t (:bold t))))
2811 "Face used for level 1 headlines."
2812 :group 'org-faces)
2814 (defface org-level-2 ;; font-lock-variable-name-face
2815 (org-compatible-face
2816 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2817 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2818 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2819 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2820 (t (:bold t))))
2821 "Face used for level 2 headlines."
2822 :group 'org-faces)
2824 (defface org-level-3 ;; font-lock-keyword-face
2825 (org-compatible-face
2826 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2827 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2828 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2829 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2830 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2831 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2832 (t (:bold t))))
2833 "Face used for level 3 headlines."
2834 :group 'org-faces)
2836 (defface org-level-4 ;; font-lock-comment-face
2837 (org-compatible-face
2838 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2839 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2840 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2841 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2842 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2843 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2844 (t (:bold t))))
2845 "Face used for level 4 headlines."
2846 :group 'org-faces)
2848 (defface org-level-5 ;; font-lock-type-face
2849 (org-compatible-face
2850 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2851 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2852 (((class color) (min-colors 8)) (:foreground "green"))))
2853 "Face used for level 5 headlines."
2854 :group 'org-faces)
2856 (defface org-level-6 ;; font-lock-constant-face
2857 (org-compatible-face
2858 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2859 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2860 (((class color) (min-colors 8)) (:foreground "magenta"))))
2861 "Face used for level 6 headlines."
2862 :group 'org-faces)
2864 (defface org-level-7 ;; font-lock-builtin-face
2865 (org-compatible-face
2866 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2867 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2868 (((class color) (min-colors 8)) (:foreground "blue"))))
2869 "Face used for level 7 headlines."
2870 :group 'org-faces)
2872 (defface org-level-8 ;; font-lock-string-face
2873 (org-compatible-face
2874 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2875 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2876 (((class color) (min-colors 8)) (:foreground "green"))))
2877 "Face used for level 8 headlines."
2878 :group 'org-faces)
2880 (defface org-special-keyword ;; font-lock-string-face
2881 (org-compatible-face
2882 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2883 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2884 (t (:italic t))))
2885 "Face used for special keywords."
2886 :group 'org-faces)
2888 (defface org-warning ;; font-lock-warning-face
2889 (org-compatible-face
2890 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2891 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2892 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2893 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2894 (t (:bold t))))
2895 "Face for deadlines and TODO keywords."
2896 :group 'org-faces)
2898 (defface org-headline-done ;; font-lock-string-face
2899 (org-compatible-face
2900 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2901 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2902 (((class color) (min-colors 8) (background light)) (:bold nil))))
2903 "Face used to indicate that a headline is DONE.
2904 This face is only used if `org-fontify-done-headline' is set."
2905 :group 'org-faces)
2907 (defface org-archived ; similar to shadow
2908 (org-compatible-face
2909 '((((class color grayscale) (min-colors 88) (background light))
2910 (:foreground "grey50"))
2911 (((class color grayscale) (min-colors 88) (background dark))
2912 (:foreground "grey70"))
2913 (((class color) (min-colors 8) (background light))
2914 (:foreground "green"))
2915 (((class color) (min-colors 8) (background dark))
2916 (:foreground "yellow"))))
2917 "Face for headline with the ARCHIVE tag."
2918 :group 'org-faces)
2920 (defface org-link
2921 '((((class color) (background light)) (:foreground "Purple" :underline t))
2922 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2923 (t (:underline t)))
2924 "Face for links."
2925 :group 'org-faces)
2927 (defface org-date
2928 '((((class color) (background light)) (:foreground "Purple" :underline t))
2929 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2930 (t (:underline t)))
2931 "Face for links."
2932 :group 'org-faces)
2934 (defface org-tag
2935 '((t (:bold t)))
2936 "Face for tags."
2937 :group 'org-faces)
2939 (defface org-todo ;; font-lock-warning-face
2940 (org-compatible-face
2941 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2942 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2943 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2944 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2945 (t (:inverse-video t :bold t))))
2946 "Face for TODO keywords."
2947 :group 'org-faces)
2949 (defface org-done ;; font-lock-type-face
2950 (org-compatible-face
2951 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2952 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2953 (((class color) (min-colors 8)) (:foreground "green"))
2954 (t (:bold t))))
2955 "Face used for DONE."
2956 :group 'org-faces)
2958 (defface org-table ;; font-lock-function-name-face
2959 (org-compatible-face
2960 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2961 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2962 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2963 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2964 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2965 (((class color) (min-colors 8) (background dark)))))
2966 "Face used for tables."
2967 :group 'org-faces)
2969 (defface org-formula
2970 (org-compatible-face
2971 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2972 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2973 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2974 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2975 (t (:bold t :italic t))))
2976 "Face for formulas."
2977 :group 'org-faces)
2979 (defface org-scheduled-today
2980 (org-compatible-face
2981 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2982 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2983 (((class color) (min-colors 8)) (:foreground "green"))
2984 (t (:bold t :italic t))))
2985 "Face for items scheduled for a certain day."
2986 :group 'org-faces)
2988 (defface org-scheduled-previously
2989 (org-compatible-face
2990 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2991 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2992 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2993 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2994 (t (:bold t))))
2995 "Face for items scheduled previously, and not yet done."
2996 :group 'org-faces)
2998 (defface org-upcoming-deadline
2999 (org-compatible-face
3000 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3001 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3002 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3003 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3004 (t (:bold t))))
3005 "Face for items scheduled previously, and not yet done."
3006 :group 'org-faces)
3008 (defface org-time-grid ;; font-lock-variable-name-face
3009 (org-compatible-face
3010 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3011 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3012 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3013 "Face used for time grids."
3014 :group 'org-faces)
3016 (defconst org-level-faces
3017 '(org-level-1 org-level-2 org-level-3 org-level-4
3018 org-level-5 org-level-6 org-level-7 org-level-8
3020 (defconst org-n-levels (length org-level-faces))
3023 ;;; Variables for pre-computed regular expressions, all buffer local
3025 (defvar org-done-string nil
3026 "The last string in `org-todo-keywords', indicating an item is DONE.")
3027 (make-variable-buffer-local 'org-done-string)
3028 (defvar org-todo-regexp nil
3029 "Matches any of the TODO state keywords.")
3030 (make-variable-buffer-local 'org-todo-regexp)
3031 (defvar org-not-done-regexp nil
3032 "Matches any of the TODO state keywords except the last one.")
3033 (make-variable-buffer-local 'org-not-done-regexp)
3034 (defvar org-todo-line-regexp nil
3035 "Matches a headline and puts TODO state into group 2 if present.")
3036 (make-variable-buffer-local 'org-todo-line-regexp)
3037 (defvar org-todo-line-tags-regexp nil
3038 "Matches a headline and puts TODO state into group 2 if present.
3039 Also put tags into group 4 if tags are present.")
3040 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3041 (defvar org-nl-done-regexp nil
3042 "Matches newline followed by a headline with the DONE keyword.")
3043 (make-variable-buffer-local 'org-nl-done-regexp)
3044 (defvar org-looking-at-done-regexp nil
3045 "Matches the DONE keyword a point.")
3046 (make-variable-buffer-local 'org-looking-at-done-regexp)
3047 (defvar org-todo-kwd-priority-p nil
3048 "Do TODO items have priorities?")
3049 (make-variable-buffer-local 'org-todo-kwd-priority-p)
3050 (defvar org-todo-kwd-max-priority nil
3051 "Maximum priority of TODO items.")
3052 (make-variable-buffer-local 'org-todo-kwd-max-priority)
3053 (defvar org-ds-keyword-length 12
3054 "Maximum length of the Deadline and SCHEDULED keywords.")
3055 (make-variable-buffer-local 'org-ds-keyword-length)
3056 (defvar org-deadline-regexp nil
3057 "Matches the DEADLINE keyword.")
3058 (make-variable-buffer-local 'org-deadline-regexp)
3059 (defvar org-deadline-time-regexp nil
3060 "Matches the DEADLINE keyword together with a time stamp.")
3061 (make-variable-buffer-local 'org-deadline-time-regexp)
3062 (defvar org-deadline-line-regexp nil
3063 "Matches the DEADLINE keyword and the rest of the line.")
3064 (make-variable-buffer-local 'org-deadline-line-regexp)
3065 (defvar org-scheduled-regexp nil
3066 "Matches the SCHEDULED keyword.")
3067 (make-variable-buffer-local 'org-scheduled-regexp)
3068 (defvar org-scheduled-time-regexp nil
3069 "Matches the SCHEDULED keyword together with a time stamp.")
3070 (make-variable-buffer-local 'org-scheduled-time-regexp)
3071 (defvar org-closed-time-regexp nil
3072 "Matches the CLOSED keyword together with a time stamp.")
3073 (make-variable-buffer-local 'org-closed-time-regexp)
3075 (defvar org-keyword-time-regexp nil
3076 "Matches any of the 4 keywords, together with the time stamp.")
3077 (make-variable-buffer-local 'org-keyword-time-regexp)
3078 (defvar org-keyword-time-not-clock-regexp nil
3079 "Matches any of the 3 keywords, together with the time stamp.")
3080 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3081 (defvar org-maybe-keyword-time-regexp nil
3082 "Matches a timestamp, possibly preceeded by a keyword.")
3083 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3085 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3086 rear-nonsticky t mouse-map t)
3087 "Properties to remove when a string without properties is wanted.")
3089 (defsubst org-match-string-no-properties (num &optional string)
3090 (if (featurep 'xemacs)
3091 (let ((s (match-string num string)))
3092 (remove-text-properties 0 (length s) org-rm-props s)
3094 (match-string-no-properties num string)))
3096 (defsubst org-no-properties (s)
3097 (remove-text-properties 0 (length s) org-rm-props s)
3100 (defsubst org-get-alist-option (option key)
3101 (cond ((eq key t) t)
3102 ((eq option t) t)
3103 ((assoc key option) (cdr (assoc key option)))
3104 (t (cdr (assq 'default option)))))
3106 (defsubst org-set-local (var value)
3107 "Make VAR local in current buffer and set it to VALUE."
3108 (set (make-variable-buffer-local var) value))
3110 (defsubst org-mode-p ()
3111 "Check if the current buffer is in Org-mode."
3112 (eq major-mode 'org-mode))
3114 (defsubst org-last (list)
3115 "Return the last element of LIST."
3116 (car (last list)))
3118 (defun org-let (list &rest body)
3119 (eval (cons 'let (cons list body))))
3120 (put 'org-let 'lisp-indent-function 1)
3122 (defun org-let2 (list1 list2 &rest body)
3123 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3124 (put 'org-let2 'lisp-indent-function 2)
3125 ;; FIXME: document this, in particular the push argument.
3126 (defconst org-startup-options
3127 '(("fold" org-startup-folded t)
3128 ("overview" org-startup-folded t)
3129 ("nofold" org-startup-folded nil)
3130 ("showall" org-startup-folded nil)
3131 ("content" org-startup-folded content)
3132 ("hidestars" org-hide-leading-stars t)
3133 ("showstars" org-hide-leading-stars nil)
3134 ("odd" org-odd-levels-only t)
3135 ("oddeven" org-odd-levels-only nil)
3136 ("align" org-startup-align-all-tables t)
3137 ("noalign" org-startup-align-all-tables nil)
3138 ("customtime" org-display-custom-times t)
3139 ("logging" org-log-done t)
3140 ("logdone" org-log-done t)
3141 ("nologging" org-log-done nil)
3142 ("lognotedone" org-log-done done push)
3143 ("lognotestate" org-log-done state push)
3144 ("lognoteclock-out" org-log-done clock-out push)
3145 ("dlcheck" org-startup-with-deadline-check t)
3146 ("nodlcheck" org-startup-with-deadline-check nil)))
3148 (defun org-set-regexps-and-options ()
3149 "Precompute regular expressions for current buffer."
3150 (when (org-mode-p)
3151 (let ((re (org-make-options-regexp
3152 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3153 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
3154 (splitre "[ \t]+")
3155 kwds int key value cat arch tags links)
3156 (save-excursion
3157 (save-restriction
3158 (widen)
3159 (goto-char (point-min))
3160 (while (re-search-forward re nil t)
3161 (setq key (match-string 1) value (org-match-string-no-properties 2))
3162 (cond
3163 ((equal key "CATEGORY")
3164 (if (string-match "[ \t]+$" value)
3165 (setq value (replace-match "" t t value)))
3166 (setq cat (intern value)))
3167 ((equal key "SEQ_TODO")
3168 (setq int 'sequence
3169 kwds (append kwds (org-split-string value splitre))))
3170 ((equal key "PRI_TODO")
3171 (setq int 'priority
3172 kwds (append kwds (org-split-string value splitre))))
3173 ((equal key "TYP_TODO")
3174 (setq int 'type
3175 kwds (append kwds (org-split-string value splitre))))
3176 ((equal key "TAGS")
3177 (setq tags (append tags (org-split-string value splitre))))
3178 ((equal key "LINK")
3179 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3180 (push (cons (match-string 1 value)
3181 (org-trim (match-string 2 value)))
3182 links)))
3183 ((equal key "STARTUP")
3184 (let ((opts (org-split-string value splitre))
3185 l var val)
3186 (while (setq l (assoc (pop opts) org-startup-options))
3187 (setq var (nth 1 l) val (nth 2 l))
3188 (if (not (nth 3 l))
3189 (set (make-local-variable var) val)
3190 (if (not (listp (symbol-value var)))
3191 (set (make-local-variable var) nil))
3192 (set (make-local-variable var) (symbol-value var))
3193 (add-to-list var val)))))
3194 ((equal key "ARCHIVE")
3195 (string-match " *$" value)
3196 (setq arch (replace-match "" t t value))
3197 (remove-text-properties 0 (length arch)
3198 '(face t fontified t) arch)))
3200 (and cat (org-set-local 'org-category cat))
3201 (and kwds (org-set-local 'org-todo-keywords kwds))
3202 (and arch (org-set-local 'org-archive-location arch))
3203 (and int (org-set-local 'org-todo-interpretation int))
3204 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3205 (when tags
3206 (let (e tgs)
3207 (while (setq e (pop tags))
3208 (cond
3209 ((equal e "{") (push '(:startgroup) tgs))
3210 ((equal e "}") (push '(:endgroup) tgs))
3211 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3212 (push (cons (match-string 1 e)
3213 (string-to-char (match-string 2 e)))
3214 tgs))
3215 (t (push (list e) tgs))))
3216 (org-set-local 'org-tag-alist nil)
3217 (while (setq e (pop tgs))
3218 (or (and (stringp (car e))
3219 (assoc (car e) org-tag-alist))
3220 (push e org-tag-alist))))))
3222 ;; Compute the regular expressions and other local variables
3223 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
3224 org-todo-kwd-max-priority (1- (length org-todo-keywords))
3225 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3226 (length org-scheduled-string)))
3227 org-done-string
3228 (nth (1- (length org-todo-keywords)) org-todo-keywords)
3229 org-todo-regexp
3230 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
3231 "\\|") "\\)\\>")
3232 org-not-done-regexp
3233 (concat "\\<\\("
3234 (mapconcat 'regexp-quote
3235 (nreverse (cdr (reverse org-todo-keywords)))
3236 "\\|")
3237 "\\)\\>")
3238 org-todo-line-regexp
3239 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3240 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3241 "\\)\\>\\)? *\\(.*\\)")
3242 org-nl-done-regexp
3243 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
3244 org-todo-line-tags-regexp
3245 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3246 (mapconcat 'regexp-quote org-todo-keywords "\\|")
3247 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3248 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
3249 org-deadline-regexp (concat "\\<" org-deadline-string)
3250 org-deadline-time-regexp
3251 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3252 org-deadline-line-regexp
3253 (concat "\\<\\(" org-deadline-string "\\).*")
3254 org-scheduled-regexp
3255 (concat "\\<" org-scheduled-string)
3256 org-scheduled-time-regexp
3257 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3258 org-closed-time-regexp
3259 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3260 org-keyword-time-regexp
3261 (concat "\\<\\(" org-scheduled-string
3262 "\\|" org-deadline-string
3263 "\\|" org-closed-string
3264 "\\|" org-clock-string "\\)"
3265 " *[[<]\\([^]>]+\\)[]>]")
3266 org-keyword-time-not-clock-regexp
3267 (concat "\\<\\(" org-scheduled-string
3268 "\\|" org-deadline-string
3269 "\\|" org-closed-string "\\)"
3270 " *[[<]\\([^]>]+\\)[]>]")
3271 org-maybe-keyword-time-regexp
3272 (concat "\\(\\<\\(" org-scheduled-string
3273 "\\|" org-deadline-string
3274 "\\|" org-closed-string
3275 "\\|" org-clock-string "\\)\\)?"
3276 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3278 (org-set-font-lock-defaults)))
3281 ;;; Some variables ujsed in various places
3283 (defvar org-window-configuration nil
3284 "Used in various places to store a window configuration.")
3285 (defvar org-finish-function nil
3286 "Function to be called when `C-c C-c' is used.
3287 This is for getting out of special buffers like remember.")
3289 ;;; Foreign variables, to inform the compiler
3291 ;; XEmacs only
3292 (defvar outline-mode-menu-heading)
3293 (defvar outline-mode-menu-show)
3294 (defvar outline-mode-menu-hide)
3295 (defvar zmacs-regions) ; XEmacs regions
3296 ;; Emacs only
3297 (defvar mark-active)
3299 ;; Packages that org-mode interacts with
3300 (defvar calc-embedded-close-formula)
3301 (defvar calc-embedded-open-formula)
3302 (defvar font-lock-unfontify-region-function)
3303 (defvar org-goto-start-pos)
3304 (defvar vm-message-pointer)
3305 (defvar vm-folder-directory)
3306 (defvar wl-summary-buffer-elmo-folder)
3307 (defvar wl-summary-buffer-folder-name)
3308 (defvar gnus-other-frame-object)
3309 (defvar gnus-group-name)
3310 (defvar gnus-article-current)
3311 (defvar w3m-current-url)
3312 (defvar w3m-current-title)
3313 (defvar mh-progs)
3314 (defvar mh-current-folder)
3315 (defvar mh-show-folder-buffer)
3316 (defvar mh-index-folder)
3317 (defvar mh-searcher)
3318 (defvar calendar-mode-map)
3319 (defvar Info-current-file)
3320 (defvar Info-current-node)
3321 (defvar texmathp-why)
3322 (defvar remember-save-after-remembering)
3323 (defvar remember-data-file)
3324 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3325 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3326 (defvar org-latex-regexps)
3328 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3330 ;; FIXME: Occasionally check by commenting these, to make sure
3331 ;; no other functions uses these, forgetting to let-bind them.
3332 (defvar entry)
3333 (defvar state)
3334 (defvar last-state)
3335 (defvar date)
3336 (defvar description)
3339 ;; Defined somewhere in this file, but used before definition.
3340 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3341 (defvar org-agenda-undo-list)
3342 (defvar org-agenda-pending-undo-list)
3343 (defvar org-agenda-overriding-header)
3344 (defvar orgtbl-mode)
3345 (defvar org-html-entities)
3346 (defvar org-struct-menu)
3347 (defvar org-org-menu)
3348 (defvar org-tbl-menu)
3349 (defvar org-agenda-keymap)
3350 (defvar org-category-table)
3352 ;;;; Emacs/XEmacs compatibility
3354 ;; Overlay compatibility functions
3355 (defun org-make-overlay (beg end &optional buffer)
3356 (if (featurep 'xemacs)
3357 (make-extent beg end buffer)
3358 (make-overlay beg end buffer)))
3359 (defun org-delete-overlay (ovl)
3360 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3361 (defun org-detach-overlay (ovl)
3362 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3363 (defun org-move-overlay (ovl beg end &optional buffer)
3364 (if (featurep 'xemacs)
3365 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3366 (move-overlay ovl beg end buffer)))
3367 (defun org-overlay-put (ovl prop value)
3368 (if (featurep 'xemacs)
3369 (set-extent-property ovl prop value)
3370 (overlay-put ovl prop value)))
3371 (defun org-overlay-display (ovl text &optional face)
3372 "Make overlay OVL display TEXT with face FACE."
3373 (if (featurep 'xemacs)
3374 (let ((gl (make-glyph text)))
3375 (and face (set-glyph-face gl face))
3376 (set-extent-property ovl 'invisible t)
3377 (set-extent-property ovl 'end-glyph gl))
3378 (overlay-put ovl 'display text)
3379 (if face (overlay-put ovl 'face face))))
3380 (defun org-overlay-get (ovl prop)
3381 (if (featurep 'xemacs)
3382 (extent-property ovl prop)
3383 (overlay-get ovl prop)))
3384 (defun org-overlays-at (pos)
3385 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3386 (defun org-overlays-in (&optional start end)
3387 (if (featurep 'xemacs)
3388 (extent-list nil start end)
3389 (overlays-in start end)))
3390 (defun org-overlay-start (o)
3391 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3392 (defun org-overlay-end (o)
3393 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3394 (defun org-find-overlays (prop &optional pos delete)
3395 "Find all overlays specifying PROP at POS or point.
3396 If DELETE is non-nil, delete all those overlays."
3397 (let ((overlays (org-overlays-at (or pos (point))))
3398 ov found)
3399 (while (setq ov (pop overlays))
3400 (if (org-overlay-get ov prop)
3401 (if delete (org-delete-overlay ov) (push ov found))))
3402 found))
3404 ;; Region compatibility
3406 (defun org-add-hook (hook function &optional append local)
3407 "Add-hook, compatible with both Emacsen."
3408 (if (and local (featurep 'xemacs))
3409 (add-local-hook hook function append)
3410 (add-hook hook function append local)))
3412 (defvar org-ignore-region nil
3413 "To temporarily disable the active region.")
3415 (defun org-region-active-p ()
3416 "Is `transient-mark-mode' on and the region active?
3417 Works on both Emacs and XEmacs."
3418 (if org-ignore-region
3420 (if (featurep 'xemacs)
3421 (and zmacs-regions (region-active-p))
3422 (and transient-mark-mode mark-active))))
3424 ;; Invisibility compatibility
3426 (defun org-add-to-invisibility-spec (arg)
3427 "Add elements to `buffer-invisibility-spec'.
3428 See documentation for `buffer-invisibility-spec' for the kind of elements
3429 that can be added."
3430 (cond
3431 ((fboundp 'add-to-invisibility-spec)
3432 (add-to-invisibility-spec arg))
3433 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3434 (setq buffer-invisibility-spec (list arg)))
3436 (setq buffer-invisibility-spec
3437 (cons arg buffer-invisibility-spec)))))
3439 (defun org-remove-from-invisibility-spec (arg)
3440 "Remove elements from `buffer-invisibility-spec'."
3441 (if (fboundp 'remove-from-invisibility-spec)
3442 (remove-from-invisibility-spec arg)
3443 (if (consp buffer-invisibility-spec)
3444 (setq buffer-invisibility-spec
3445 (delete arg buffer-invisibility-spec)))))
3447 (defun org-in-invisibility-spec-p (arg)
3448 "Is ARG a member of `buffer-invisibility-spec'?"
3449 (if (consp buffer-invisibility-spec)
3450 (member arg buffer-invisibility-spec)
3451 nil))
3453 ;;;; Define the Org-mode
3455 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3456 (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."))
3459 ;; We use a before-change function to check if a table might need
3460 ;; an update.
3461 (defvar org-table-may-need-update t
3462 "Indicates that a table might need an update.
3463 This variable is set by `org-before-change-function'.
3464 `org-table-align' sets it back to nil.")
3465 (defvar org-mode-map)
3466 (defvar org-mode-hook nil)
3467 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3468 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3471 ;;;###autoload
3472 (define-derived-mode org-mode outline-mode "Org"
3473 "Outline-based notes management and organizer, alias
3474 \"Carsten's outline-mode for keeping track of everything.\"
3476 Org-mode develops organizational tasks around a NOTES file which
3477 contains information about projects as plain text. Org-mode is
3478 implemented on top of outline-mode, which is ideal to keep the content
3479 of large files well structured. It supports ToDo items, deadlines and
3480 time stamps, which magically appear in the diary listing of the Emacs
3481 calendar. Tables are easily created with a built-in table editor.
3482 Plain text URL-like links connect to websites, emails (VM), Usenet
3483 messages (Gnus), BBDB entries, and any files related to the project.
3484 For printing and sharing of notes, an Org-mode file (or a part of it)
3485 can be exported as a structured ASCII or HTML file.
3487 The following commands are available:
3489 \\{org-mode-map}"
3491 ;; Get rid of Outline menus, they are not needed
3492 ;; Need to do this here because define-derived-mode sets up
3493 ;; the keymap so late. Still, it is a waste to call this each time
3494 ;; we switch another buffer into org-mode.
3495 (if (featurep 'xemacs)
3496 (when (boundp 'outline-mode-menu-heading)
3497 ;; Assume this is Greg's port, it used easymenu
3498 (easy-menu-remove outline-mode-menu-heading)
3499 (easy-menu-remove outline-mode-menu-show)
3500 (easy-menu-remove outline-mode-menu-hide))
3501 (define-key org-mode-map [menu-bar headings] 'undefined)
3502 (define-key org-mode-map [menu-bar hide] 'undefined)
3503 (define-key org-mode-map [menu-bar show] 'undefined))
3505 (easy-menu-add org-org-menu)
3506 (easy-menu-add org-tbl-menu)
3507 (org-install-agenda-files-menu)
3508 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3509 (org-add-to-invisibility-spec '(org-cwidth))
3510 (when (featurep 'xemacs)
3511 (org-set-local 'line-move-ignore-invisible t))
3512 (setq outline-regexp "\\*+")
3513 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
3514 (setq outline-level 'org-outline-level)
3515 (when (and org-ellipsis (stringp org-ellipsis))
3516 (unless org-display-table
3517 (setq org-display-table (make-display-table)))
3518 (set-display-table-slot org-display-table
3519 4 (string-to-vector org-ellipsis))
3520 (setq buffer-display-table org-display-table))
3521 (org-set-regexps-and-options)
3522 ;; Calc embedded
3523 (org-set-local 'calc-embedded-open-mode "# ")
3524 (modify-syntax-entry ?# "<")
3525 (if org-startup-truncated (setq truncate-lines t))
3526 (org-set-local 'font-lock-unfontify-region-function
3527 'org-unfontify-region)
3528 ;; Activate before-change-function
3529 (org-set-local 'org-table-may-need-update t)
3530 (org-add-hook 'before-change-functions 'org-before-change-function nil
3531 'local)
3532 ;; Check for running clock before killing a buffer
3533 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3534 ;; Paragraphs and auto-filling
3535 (org-set-autofill-regexps)
3536 (org-update-radio-target-regexp)
3538 ;; Comment characters
3539 (org-set-local 'comment-start "#")
3540 (org-set-local 'comment-padding " ")
3542 ;; Make isearch reveal context
3543 (if (or (featurep 'xemacs)
3544 (not (boundp 'outline-isearch-open-invisible-function)))
3545 ;; Emacs 21 and XEmacs make use of the hook
3546 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3547 ;; Emacs 22 deals with this through a special variable
3548 (org-set-local 'outline-isearch-open-invisible-function
3549 (lambda (&rest ignore) (org-show-context 'isearch))))
3551 ;; If empty file that did not turn on org-mode automatically, make it to.
3552 (if (and org-insert-mode-line-in-empty-file
3553 (interactive-p)
3554 (= (point-min) (point-max)))
3555 (insert " -*- mode: org -*-\n\n"))
3557 (unless org-inhibit-startup
3558 (when org-startup-align-all-tables
3559 (let ((bmp (buffer-modified-p)))
3560 (org-table-map-tables 'org-table-align)
3561 (set-buffer-modified-p bmp)))
3562 (if org-startup-with-deadline-check
3563 (call-interactively 'org-check-deadlines)
3564 (cond
3565 ((eq org-startup-folded t)
3566 (org-cycle '(4)))
3567 ((eq org-startup-folded 'content)
3568 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3569 (org-cycle '(4)) (org-cycle '(4))))))))
3571 (defsubst org-call-with-arg (command arg)
3572 "Call COMMAND interactively, but pretend prefix are was ARG."
3573 (let ((current-prefix-arg arg)) (call-interactively command)))
3575 (defsubst org-current-line (&optional pos)
3576 (save-excursion
3577 (and pos (goto-char pos))
3578 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
3580 (defun org-current-time ()
3581 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3582 (if (> org-time-stamp-rounding-minutes 0)
3583 (let ((r org-time-stamp-rounding-minutes)
3584 (time (decode-time)))
3585 (apply 'encode-time
3586 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3587 (nthcdr 2 time))))
3588 (current-time)))
3590 (defun org-add-props (string plist &rest props)
3591 "Add text properties to entire string, from beginning to end.
3592 PLIST may be a list of properties, PROPS are individual properties and values
3593 that will be added to PLIST. Returns the string that was modified."
3594 (add-text-properties
3595 0 (length string) (if props (append plist props) plist) string)
3596 string)
3597 (put 'org-add-props 'lisp-indent-function 2)
3600 ;;;; Font-Lock stuff, including the activators
3602 (defvar org-mouse-map (make-sparse-keymap))
3603 (define-key org-mouse-map
3604 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3605 (define-key org-mouse-map
3606 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3607 (when org-mouse-1-follows-link
3608 (define-key org-mouse-map [follow-link] 'mouse-face))
3609 (when org-tab-follows-link
3610 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3611 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3612 (when org-return-follows-link
3613 (define-key org-mouse-map [(return)] 'org-open-at-point)
3614 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3616 (require 'font-lock)
3618 (defconst org-non-link-chars "]\t\n\r<>")
3619 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3620 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3621 (defconst org-link-re-with-space
3622 (concat
3623 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3624 "\\([^" org-non-link-chars " ]"
3625 "[^" org-non-link-chars "]*"
3626 "[^" org-non-link-chars " ]\\)>?")
3627 "Matches a link with spaces, optional angular brackets around it.")
3629 (defconst org-link-re-with-space2
3630 (concat
3631 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3632 "\\([^" org-non-link-chars " ]"
3633 "[^]\t\n\r]*"
3634 "[^" org-non-link-chars " ]\\)>?")
3635 "Matches a link with spaces, optional angular brackets around it.")
3637 (defconst org-angle-link-re
3638 (concat
3639 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3640 "\\([^" org-non-link-chars " ]"
3641 "[^" org-non-link-chars "]*"
3642 "\\)>")
3643 "Matches link with angular brackets, spaces are allowed.")
3644 (defconst org-plain-link-re
3645 (concat
3646 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3647 "\\([^]\t\n\r<>,;() ]+\\)")
3648 "Matches plain link, without spaces.")
3650 (defconst org-bracket-link-regexp
3651 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3652 "Matches a link in double brackets.")
3654 (defconst org-bracket-link-analytic-regexp
3655 (concat
3656 "\\[\\["
3657 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3658 "\\([^]]+\\)"
3659 "\\]"
3660 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3661 "\\]"))
3662 ; 1: http:
3663 ; 2: http
3664 ; 3: path
3665 ; 4: [desc]
3666 ; 5: desc
3668 (defconst org-ts-lengths
3669 (cons (length (format-time-string (car org-time-stamp-formats)))
3670 (length (format-time-string (cdr org-time-stamp-formats))))
3671 "This holds the lengths of the two different time formats.")
3672 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3673 "Regular expression for fast time stamp matching.")
3674 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3675 "Regular expression for fast time stamp matching.")
3676 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3677 "Regular expression matching time strings for analysis.")
3678 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3679 "Regular expression matching time stamps, with groups.")
3680 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3681 "Regular expression matching time stamps (also [..]), with groups.")
3682 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3683 "Regular expression matching a time stamp range.")
3684 (defconst org-tr-regexp-both
3685 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3686 "Regular expression matching a time stamp range.")
3687 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3688 org-ts-regexp "\\)?")
3689 "Regular expression matching a time stamp or time stamp range.")
3690 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3691 org-ts-regexp-both "\\)?")
3692 "Regular expression matching a time stamp or time stamp range.
3693 The time stamps may be either active or inactive.")
3695 (defvar org-emph-face nil)
3697 (defun org-do-emphasis-faces (limit)
3698 "Run through the buffer and add overlays to links."
3699 (if (re-search-forward org-emph-re limit t)
3700 (progn
3701 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3702 'face
3703 (nth 1 (assoc (match-string 3)
3704 org-emphasis-alist)))
3705 (add-text-properties (match-beginning 2) (match-end 2)
3706 '(font-lock-multiline t))
3707 (backward-char 1)
3708 t)))
3710 (defun org-activate-plain-links (limit)
3711 "Run through the buffer and add overlays to links."
3712 (if (re-search-forward org-plain-link-re limit t)
3713 (progn
3714 (add-text-properties (match-beginning 0) (match-end 0)
3715 (list 'mouse-face 'highlight
3716 'rear-nonsticky t
3717 'keymap org-mouse-map
3719 t)))
3721 (defun org-activate-angle-links (limit)
3722 "Run through the buffer and add overlays to links."
3723 (if (re-search-forward org-angle-link-re limit t)
3724 (progn
3725 (add-text-properties (match-beginning 0) (match-end 0)
3726 (list 'mouse-face 'highlight
3727 'rear-nonsticky t
3728 'keymap org-mouse-map
3730 t)))
3732 (defmacro org-maybe-intangible (props)
3733 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3734 In emacs 21, invisible text is not avoided by the command loop, so the
3735 intangible property is needed to make sure point skips this text.
3736 In Emacs 22, this is not necessary. The intangible text property has
3737 led to problems with flyspell. These problems are fixed in flyspell.el,
3738 but we still avoid setting the property in Emacs 22 and later.
3739 We use a macro so that the test can happen at compilation time."
3740 (if (< emacs-major-version 22)
3741 `(append '(intangible t) ,props)
3742 props))
3744 (defun org-activate-bracket-links (limit)
3745 "Run through the buffer and add overlays to bracketed links."
3746 (if (re-search-forward org-bracket-link-regexp limit t)
3747 (let* ((help (concat "LINK: "
3748 (org-match-string-no-properties 1)))
3749 ;; FIXME: above we should remove the escapes.
3750 ;; but that requires another match, protecting match data,
3751 ;; a lot of overhead for font-lock.
3752 (ip (org-maybe-intangible
3753 (list 'invisible 'org-link 'rear-nonsticky t
3754 'keymap org-mouse-map 'mouse-face 'highlight
3755 'help-echo help)))
3756 (vp (list 'rear-nonsticky t
3757 'keymap org-mouse-map 'mouse-face 'highlight
3758 'help-echo help)))
3759 ;; We need to remove the invisible property here. Table narrowing
3760 ;; may have made some of this invisible.
3761 (remove-text-properties (match-beginning 0) (match-end 0)
3762 '(invisible nil))
3763 (if (match-end 3)
3764 (progn
3765 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3766 (add-text-properties (match-beginning 3) (match-end 3) vp)
3767 (add-text-properties (match-end 3) (match-end 0) ip))
3768 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3769 (add-text-properties (match-beginning 1) (match-end 1) vp)
3770 (add-text-properties (match-end 1) (match-end 0) ip))
3771 t)))
3773 (defun org-activate-dates (limit)
3774 "Run through the buffer and add overlays to dates."
3775 (if (re-search-forward org-tsr-regexp-both limit t)
3776 (progn
3777 (add-text-properties (match-beginning 0) (match-end 0)
3778 (list 'mouse-face 'highlight
3779 'rear-nonsticky t
3780 'keymap org-mouse-map))
3781 (when org-display-custom-times
3782 (if (match-end 3)
3783 (org-display-custom-time (match-beginning 3) (match-end 3)))
3784 (org-display-custom-time (match-beginning 1) (match-end 1)))
3785 t)))
3787 (defvar org-target-link-regexp nil
3788 "Regular expression matching radio targets in plain text.")
3789 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3790 "Regular expression matching a link target.")
3791 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3792 "Regular expression matching a link target.")
3794 (defun org-activate-target-links (limit)
3795 "Run through the buffer and add overlays to target matches."
3796 (when org-target-link-regexp
3797 (let ((case-fold-search t))
3798 (if (re-search-forward org-target-link-regexp limit t)
3799 (progn
3800 (add-text-properties (match-beginning 0) (match-end 0)
3801 (list 'mouse-face 'highlight
3802 'rear-nonsticky t
3803 'keymap org-mouse-map
3804 'help-echo "Radio target link"
3805 'org-linked-text t))
3806 t)))))
3808 (defun org-update-radio-target-regexp ()
3809 "Find all radio targets in this file and update the regular expression."
3810 (interactive)
3811 (when (memq 'radio org-activate-links)
3812 (setq org-target-link-regexp
3813 (org-make-target-link-regexp (org-all-targets 'radio)))
3814 (org-restart-font-lock)))
3816 (defun org-hide-wide-columns (limit)
3817 (let (s e)
3818 (setq s (text-property-any (point) (or limit (point-max))
3819 'org-cwidth t))
3820 (when s
3821 (setq e (next-single-property-change s 'org-cwidth))
3822 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3823 (goto-char e)
3824 t)))
3826 (defun org-restart-font-lock ()
3827 "Restart font-lock-mode, to force refontification."
3828 (when (and (boundp 'font-lock-mode) font-lock-mode)
3829 (font-lock-mode -1)
3830 (font-lock-mode 1)))
3832 (defun org-all-targets (&optional radio)
3833 "Return a list of all targets in this file.
3834 With optional argument RADIO, only find radio targets."
3835 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3836 rtn)
3837 (save-excursion
3838 (goto-char (point-min))
3839 (while (re-search-forward re nil t)
3840 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3841 rtn)))
3843 (defun org-make-target-link-regexp (targets)
3844 "Make regular expression matching all strings in TARGETS.
3845 The regular expression finds the targets also if there is a line break
3846 between words."
3847 (and targets
3848 (concat
3849 "\\<\\("
3850 (mapconcat
3851 (lambda (x)
3852 (while (string-match " +" x)
3853 (setq x (replace-match "\\s-+" t t x)))
3855 targets
3856 "\\|")
3857 "\\)\\>")))
3859 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3860 "Matches CamelCase words, possibly with a star before it.")
3862 (defun org-activate-camels (limit)
3863 "Run through the buffer and add overlays to dates."
3864 (if (re-search-forward org-camel-regexp limit t)
3865 (progn
3866 (add-text-properties (match-beginning 0) (match-end 0)
3867 (list 'mouse-face 'highlight
3868 'rear-nonsticky t
3869 'keymap org-mouse-map))
3870 t)))
3872 (defun org-activate-tags (limit)
3873 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3874 (progn
3875 (add-text-properties (match-beginning 1) (match-end 1)
3876 (list 'mouse-face 'highlight
3877 'rear-nonsticky t
3878 'keymap org-mouse-map))
3879 t)))
3881 (defun org-font-lock-level ()
3882 (save-excursion
3883 (org-back-to-heading t)
3884 (- (match-end 0) (match-beginning 0))))
3886 (defun org-outline-level ()
3887 (save-excursion
3888 (looking-at outline-regexp)
3889 (if (match-beginning 1)
3890 (+ (org-get-string-indentation (match-string 1)) 1000)
3891 (- (match-end 0) (match-beginning 0)))))
3893 (defvar org-font-lock-keywords nil)
3895 (defun org-set-font-lock-defaults ()
3896 (let* ((em org-fontify-emphasized-text)
3897 (lk org-activate-links)
3898 (org-font-lock-extra-keywords
3899 ;; Headlines
3900 (list
3901 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3902 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3903 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3904 (1 'org-table))
3905 ;; Links
3906 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3907 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3908 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3909 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3910 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3911 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3912 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3913 (if org-table-limit-column-width
3914 '(org-hide-wide-columns (0 nil append)))
3915 ;; TODO lines
3916 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3917 '(1 'org-todo t))
3918 ;; Priorities
3919 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3920 ;; Special keywords
3921 (list org-repeat-re '(0 'org-special-keyword t))
3922 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3923 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3924 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3925 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3926 ;; Emphasis
3927 (if em
3928 (if (featurep 'xemacs)
3929 '(org-do-emphasis-faces (0 nil append))
3930 '(org-do-emphasis-faces)))
3931 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3932 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3933 2 'bold prepend)
3934 (if org-provide-checkbox-statistics
3935 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3936 (0 (org-get-checkbox-statistics-face) t)))
3937 ;; COMMENT
3938 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3939 "\\|" org-quote-string "\\)\\>")
3940 '(1 'org-special-keyword t))
3941 '("^#.*" (0 'font-lock-comment-face t))
3942 ;; DONE
3943 (if org-fontify-done-headline
3944 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3945 '(1 'org-done t) '(2 'org-headline-done t))
3946 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3947 '(1 'org-done t)))
3948 ;; Table stuff
3949 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3950 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3951 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3952 (if org-format-transports-properties-p
3953 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3954 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3956 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3957 ;; Now set the full font-lock-keywords
3958 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3959 (org-set-local 'font-lock-defaults
3960 '(org-font-lock-keywords t nil nil backward-paragraph))
3961 (kill-local-variable 'font-lock-keywords) nil))
3963 (defvar org-m nil)
3964 (defvar org-l nil)
3965 (defvar org-f nil)
3966 (defun org-get-level-face (n)
3967 "Get the right face for match N in font-lock matching of healdines."
3968 (setq org-l (- (match-end 2) (match-beginning 1)))
3969 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3970 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3971 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3972 (cond
3973 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3974 ((eq n 2) org-f)
3975 (t (if org-level-color-stars-only nil org-f))))
3977 (defun org-unfontify-region (beg end &optional maybe_loudly)
3978 "Remove fontification and activation overlays from links."
3979 (font-lock-default-unfontify-region beg end)
3980 (let* ((buffer-undo-list t)
3981 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3982 (inhibit-modification-hooks t)
3983 deactivate-mark buffer-file-name buffer-file-truename)
3984 (remove-text-properties beg end
3985 '(mouse-face t keymap t org-linked-text t
3986 rear-nonsticky t
3987 invisible t intangible t))))
3989 ;;;; Visibility cycling, including org-goto and indirect buffer
3991 ;;; Cycling
3993 (defvar org-cycle-global-status nil)
3994 (make-variable-buffer-local 'org-cycle-global-status)
3995 (defvar org-cycle-subtree-status nil)
3996 (make-variable-buffer-local 'org-cycle-subtree-status)
3998 ;;;###autoload
3999 (defun org-cycle (&optional arg)
4000 "Visibility cycling for Org-mode.
4002 - When this function is called with a prefix argument, rotate the entire
4003 buffer through 3 states (global cycling)
4004 1. OVERVIEW: Show only top-level headlines.
4005 2. CONTENTS: Show all headlines of all levels, but no body text.
4006 3. SHOW ALL: Show everything.
4008 - When point is at the beginning of a headline, rotate the subtree started
4009 by this line through 3 different states (local cycling)
4010 1. FOLDED: Only the main headline is shown.
4011 2. CHILDREN: The main headline and the direct children are shown.
4012 From this state, you can move to one of the children
4013 and zoom in further.
4014 3. SUBTREE: Show the entire subtree, including body text.
4016 - When there is a numeric prefix, go up to a heading with level ARG, do
4017 a `show-subtree' and return to the previous cursor position. If ARG
4018 is negative, go up that many levels.
4020 - When point is not at the beginning of a headline, execute
4021 `indent-relative', like TAB normally does. See the option
4022 `org-cycle-emulate-tab' for details.
4024 - Special case: if point is the the beginning of the buffer and there is
4025 no headline in line 1, this function will act as if called with prefix arg."
4026 (interactive "P")
4027 (let* ((outline-regexp
4028 (if (and (org-mode-p) org-cycle-include-plain-lists)
4029 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4030 outline-regexp))
4031 (bob-special (and org-cycle-global-at-bob (bobp)
4032 (not (looking-at outline-regexp))))
4033 (org-cycle-hook
4034 (if bob-special
4035 (delq 'org-optimize-window-after-visibility-change
4036 (copy-sequence org-cycle-hook))
4037 org-cycle-hook))
4038 (pos (point)))
4040 (if (or bob-special (equal arg '(4)))
4041 ;; special case: use global cycling
4042 (setq arg t))
4044 (cond
4046 ((org-at-table-p 'any)
4047 ;; Enter the table or move to the next field in the table
4048 (or (org-table-recognize-table.el)
4049 (progn
4050 (if arg (org-table-edit-field t)
4051 (org-table-justify-field-maybe)
4052 (call-interactively 'org-table-next-field)))))
4054 ((eq arg t) ;; Global cycling
4056 (cond
4057 ((and (eq last-command this-command)
4058 (eq org-cycle-global-status 'overview))
4059 ;; We just created the overview - now do table of contents
4060 ;; This can be slow in very large buffers, so indicate action
4061 (message "CONTENTS...")
4062 (org-content)
4063 (message "CONTENTS...done")
4064 (setq org-cycle-global-status 'contents)
4065 (run-hook-with-args 'org-cycle-hook 'contents))
4067 ((and (eq last-command this-command)
4068 (eq org-cycle-global-status 'contents))
4069 ;; We just showed the table of contents - now show everything
4070 (show-all)
4071 (message "SHOW ALL")
4072 (setq org-cycle-global-status 'all)
4073 (run-hook-with-args 'org-cycle-hook 'all))
4076 ;; Default action: go to overview
4077 (org-overview)
4078 (message "OVERVIEW")
4079 (setq org-cycle-global-status 'overview)
4080 (run-hook-with-args 'org-cycle-hook 'overview))))
4082 ((integerp arg)
4083 ;; Show-subtree, ARG levels up from here.
4084 (save-excursion
4085 (org-back-to-heading)
4086 (outline-up-heading (if (< arg 0) (- arg)
4087 (- (funcall outline-level) arg)))
4088 (org-show-subtree)))
4090 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4091 ;; At a heading: rotate between three different views
4092 (org-back-to-heading)
4093 (let ((goal-column 0) eoh eol eos)
4094 ;; First, some boundaries
4095 (save-excursion
4096 (org-back-to-heading)
4097 (save-excursion
4098 (beginning-of-line 2)
4099 (while (and (not (eobp)) ;; this is like `next-line'
4100 (get-char-property (1- (point)) 'invisible))
4101 (beginning-of-line 2)) (setq eol (point)))
4102 (outline-end-of-heading) (setq eoh (point))
4103 (org-end-of-subtree t)
4104 (skip-chars-forward " \t\n")
4105 (setq eos (1- (point))))
4106 ;; Find out what to do next and set `this-command'
4107 (cond
4108 ((= eos eoh)
4109 ;; Nothing is hidden behind this heading
4110 (message "EMPTY ENTRY")
4111 (setq org-cycle-subtree-status nil))
4112 ((>= eol eos)
4113 ;; Entire subtree is hidden in one line: open it
4114 (org-show-entry)
4115 (show-children)
4116 (message "CHILDREN")
4117 (setq org-cycle-subtree-status 'children)
4118 (run-hook-with-args 'org-cycle-hook 'children))
4119 ((and (eq last-command this-command)
4120 (eq org-cycle-subtree-status 'children))
4121 ;; We just showed the children, now show everything.
4122 (org-show-subtree)
4123 (message "SUBTREE")
4124 (setq org-cycle-subtree-status 'subtree)
4125 (run-hook-with-args 'org-cycle-hook 'subtree))
4127 ;; Default action: hide the subtree.
4128 (hide-subtree)
4129 (message "FOLDED")
4130 (setq org-cycle-subtree-status 'folded)
4131 (run-hook-with-args 'org-cycle-hook 'folded)))))
4133 ;; TAB emulation
4134 (buffer-read-only (org-back-to-heading))
4136 ((org-try-cdlatex-tab))
4138 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4139 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4140 (or (and (eq org-cycle-emulate-tab 'white)
4141 (= (match-end 0) (point-at-eol)))
4142 (and (eq org-cycle-emulate-tab 'whitestart)
4143 (>= (match-end 0) pos))))
4145 (eq org-cycle-emulate-tab t))
4146 (if (and (looking-at "[ \n\r\t]")
4147 (string-match "^[ \t]*$" (buffer-substring
4148 (point-at-bol) (point))))
4149 (progn
4150 (beginning-of-line 1)
4151 (and (looking-at "[ \t]+") (replace-match ""))))
4152 (indent-relative))
4154 (t (save-excursion
4155 (org-back-to-heading)
4156 (org-cycle))))))
4158 ;;;###autoload
4159 (defun org-global-cycle (&optional arg)
4160 "Cycle the global visibility. For details see `org-cycle'."
4161 (interactive "P")
4162 (let ((org-cycle-include-plain-lists
4163 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4164 (if (integerp arg)
4165 (progn
4166 (show-all)
4167 (hide-sublevels arg)
4168 (setq org-cycle-global-status 'contents))
4169 (org-cycle '(4)))))
4171 (defun org-overview ()
4172 "Switch to overview mode, shoing only top-level headlines.
4173 Really, this shows all headlines with level equal or greater than the level
4174 of the first headline in the buffer. This is important, because if the
4175 first headline is not level one, then (hide-sublevels 1) gives confusing
4176 results."
4177 (interactive)
4178 (hide-sublevels (save-excursion
4179 (goto-char (point-min))
4180 (if (re-search-forward (concat "^" outline-regexp) nil t)
4181 (progn
4182 (goto-char (match-beginning 0))
4183 (funcall outline-level))
4184 1))))
4186 ;; FIXME: allow an argument to give a limiting level for this.
4187 (defun org-content ()
4188 "Show all headlines in the buffer, like a table of contents"
4189 (interactive)
4190 (save-excursion
4191 ;; Visit all headings and show their offspring
4192 (goto-char (point-max))
4193 (catch 'exit
4194 (while (and (progn (condition-case nil
4195 (outline-previous-visible-heading 1)
4196 (error (goto-char (point-min))))
4198 (looking-at outline-regexp))
4199 (show-branches)
4200 (if (bobp) (throw 'exit nil))))))
4203 (defun org-optimize-window-after-visibility-change (state)
4204 "Adjust the window after a change in outline visibility.
4205 This function is the default value of the hook `org-cycle-hook'."
4206 (when (get-buffer-window (current-buffer))
4207 (cond
4208 ((eq state 'overview) (org-first-headline-recenter 1))
4209 ((eq state 'content) nil)
4210 ((eq state 'all) nil)
4211 ((eq state 'folded) nil)
4212 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4213 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4215 (defun org-subtree-end-visible-p ()
4216 "Is the end of the current subtree visible?"
4217 (pos-visible-in-window-p
4218 (save-excursion (org-end-of-subtree t) (point))))
4220 (defun org-first-headline-recenter (&optional N)
4221 "Move cursor to the first headline and recenter the headline.
4222 Optional argument N means, put the headline into the Nth line of the window."
4223 (goto-char (point-min))
4224 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4225 (beginning-of-line)
4226 (recenter (prefix-numeric-value N))))
4228 ;;; Org-goto
4230 (defvar org-goto-window-configuration nil)
4231 (defvar org-goto-marker nil)
4232 (defvar org-goto-map (make-sparse-keymap))
4233 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4234 (while (setq cmd (pop cmds))
4235 (substitute-key-definition cmd cmd org-goto-map global-map)))
4236 (define-key org-goto-map "\C-m" 'org-goto-ret)
4237 (define-key org-goto-map [(left)] 'org-goto-left)
4238 (define-key org-goto-map [(right)] 'org-goto-right)
4239 (define-key org-goto-map [(?q)] 'org-goto-quit)
4240 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
4241 (define-key org-goto-map "\C-i" 'org-cycle)
4242 (define-key org-goto-map [(tab)] 'org-cycle)
4243 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
4244 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
4245 (define-key org-goto-map "n" 'outline-next-visible-heading)
4246 (define-key org-goto-map "p" 'outline-previous-visible-heading)
4247 (define-key org-goto-map "f" 'outline-forward-same-level)
4248 (define-key org-goto-map "b" 'outline-backward-same-level)
4249 (define-key org-goto-map "u" 'outline-up-heading)
4250 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4251 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4252 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4253 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4254 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
4255 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4256 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
4258 (defconst org-goto-help
4259 "Select a location to jump to, press RET
4260 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4262 (defun org-goto ()
4263 "Go to a different location of the document, keeping current visibility.
4265 When you want to go to a different location in a document, the fastest way
4266 is often to fold the entire buffer and then dive into the tree. This
4267 method has the disadvantage, that the previous location will be folded,
4268 which may not be what you want.
4270 This command works around this by showing a copy of the current buffer in
4271 overview mode. You can dive into the tree in that copy, to find the
4272 location you want to reach. When pressing RET, the command returns to the
4273 original buffer in which the visibility is still unchanged. It then jumps
4274 to the new location, making it and the headline hierarchy above it visible."
4275 (interactive)
4276 (let* ((org-goto-start-pos (point))
4277 (selected-point
4278 (org-get-location (current-buffer) org-goto-help)))
4279 (if selected-point
4280 (progn
4281 (org-mark-ring-push org-goto-start-pos)
4282 (goto-char selected-point)
4283 (if (or (org-invisible-p) (org-invisible-p2))
4284 (org-show-context 'org-goto)))
4285 (error "Quit"))))
4287 (defvar org-selected-point nil) ; dynamically scoped parameter
4289 (defun org-get-location (buf help)
4290 "Let the user select a location in the Org-mode buffer BUF.
4291 This function uses a recursive edit. It returns the selected position
4292 or nil."
4293 (let (org-selected-point)
4294 (save-excursion
4295 (save-window-excursion
4296 (delete-other-windows)
4297 (switch-to-buffer (get-buffer-create "*org-goto*"))
4298 (with-output-to-temp-buffer "*Help*"
4299 (princ help))
4300 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4301 (setq buffer-read-only nil)
4302 (erase-buffer)
4303 (insert-buffer-substring buf)
4304 (let ((org-startup-truncated t)
4305 (org-startup-folded t)
4306 (org-startup-align-all-tables nil)
4307 (org-startup-with-deadline-check nil))
4308 (org-mode))
4309 (setq buffer-read-only t)
4310 (if (boundp 'org-goto-start-pos)
4311 (goto-char org-goto-start-pos)
4312 (goto-char (point-min)))
4313 (org-beginning-of-line)
4314 (message "Select location and press RET")
4315 ;; now we make sure that during selection, ony very few keys work
4316 ;; and that it is impossible to switch to another window.
4317 (let ((gm (current-global-map))
4318 (overriding-local-map org-goto-map))
4319 (unwind-protect
4320 (progn
4321 (use-global-map org-goto-map)
4322 (recursive-edit))
4323 (use-global-map gm)))))
4324 (kill-buffer "*org-goto*")
4325 org-selected-point))
4327 (defun org-goto-ret (&optional arg)
4328 "Finish `org-goto' by going to the new location."
4329 (interactive "P")
4330 (setq org-selected-point (point)
4331 current-prefix-arg arg)
4332 (throw 'exit nil))
4334 (defun org-goto-left ()
4335 "Finish `org-goto' by going to the new location."
4336 (interactive)
4337 (if (org-on-heading-p)
4338 (progn
4339 (beginning-of-line 1)
4340 (setq org-selected-point (point)
4341 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4342 (throw 'exit nil))
4343 (error "Not on a heading")))
4345 (defun org-goto-right ()
4346 "Finish `org-goto' by going to the new location."
4347 (interactive)
4348 (if (org-on-heading-p)
4349 (progn
4350 (outline-end-of-subtree)
4351 (or (eobp) (forward-char 1))
4352 (setq org-selected-point (point)
4353 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4354 (throw 'exit nil))
4355 (error "Not on a heading")))
4357 (defun org-goto-quit ()
4358 "Finish `org-goto' without cursor motion."
4359 (interactive)
4360 (setq org-selected-point nil)
4361 (throw 'exit nil))
4363 ;;; Indirect buffer display of subtrees
4365 (defvar org-indirect-dedicated-frame nil
4366 "This is the frame being used for indirect tree display.")
4367 (defvar org-last-indirect-buffer nil)
4369 (defun org-tree-to-indirect-buffer (&optional arg)
4370 "Create indirect buffer and narrow it to current subtree.
4371 With numerical prefix ARG, go up to this level and then take that tree.
4372 If ARG is negative, go up that many levels.
4373 Normally this command removes the indirect buffer previously made
4374 with this command. However, when called with a C-u prefix, the last buffer
4375 is kept so that you can work with several indirect buffers at the same time.
4376 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4377 requests that a new frame be made for the new buffer, so that the dedicated
4378 frame is not changed."
4379 (interactive "P")
4380 (let ((cbuf (current-buffer))
4381 (cwin (selected-window))
4382 (pos (point))
4383 (bname (buffer-name (current-buffer)))
4384 beg end level heading ibuf)
4385 (save-excursion
4386 (org-back-to-heading t)
4387 (when (numberp arg)
4388 (setq level (org-outline-level))
4389 (if (< arg 0) (setq arg (+ level arg)))
4390 (while (> (setq level (org-outline-level)) arg)
4391 (outline-up-heading 1 t)))
4392 (setq beg (point)
4393 heading (org-get-heading))
4394 (org-end-of-subtree t) (setq end (point)))
4395 (if (and (not arg)
4396 (buffer-live-p org-last-indirect-buffer))
4397 (kill-buffer org-last-indirect-buffer))
4398 (setq ibuf (org-get-indirect-buffer cbuf)
4399 org-last-indirect-buffer ibuf)
4400 (cond
4401 ((or (eq org-indirect-buffer-display 'new-frame)
4402 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4403 (select-frame (make-frame))
4404 (delete-other-windows)
4405 (switch-to-buffer ibuf)
4406 (org-set-frame-title heading))
4407 ((eq org-indirect-buffer-display 'dedicated-frame)
4408 (raise-frame
4409 (select-frame (or (and org-indirect-dedicated-frame
4410 (frame-live-p org-indirect-dedicated-frame)
4411 org-indirect-dedicated-frame)
4412 (setq org-indirect-dedicated-frame (make-frame)))))
4413 (delete-other-windows)
4414 (switch-to-buffer ibuf)
4415 (org-set-frame-title (concat "Indirect: " heading)))
4416 ((eq org-indirect-buffer-display 'current-window)
4417 (switch-to-buffer ibuf))
4418 ((eq org-indirect-buffer-display 'other-window)
4419 (pop-to-buffer ibuf))
4420 (t (error "Invalid value.")))
4421 (if (featurep 'xemacs)
4422 (save-excursion (org-mode) (turn-on-font-lock)))
4423 (narrow-to-region beg end)
4424 (show-all)
4425 (goto-char pos)
4426 (and (window-live-p cwin) (select-window cwin))))
4428 (defun org-get-indirect-buffer (&optional buffer)
4429 (setq buffer (or buffer (current-buffer)))
4430 (let ((n 1) (base (buffer-name buffer)) bname)
4431 (while (buffer-live-p
4432 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4433 (setq n (1+ n)))
4434 (condition-case nil
4435 (make-indirect-buffer buffer bname 'clone)
4436 (error (make-indirect-buffer buffer bname)))))
4438 (defun org-set-frame-title (title)
4439 "Set the title of the current frame to the string TITLE."
4440 ;; FIXME: how to name a single frame in XEmacs???
4441 (unless (featurep 'xemacs)
4442 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4444 ;;;; Structure editing
4446 ;;; Inserting headlines
4448 (defun org-insert-heading (&optional force-heading)
4449 "Insert a new heading or item with same depth at point.
4450 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4451 If point is at the beginning of a headline, insert a sibling before the
4452 current headline. If point is in the middle of a headline, split the headline
4453 at that position and make the rest of the headline part of the sibling below
4454 the current headline."
4455 (interactive "P")
4456 (if (= (buffer-size) 0)
4457 (insert "\n* ")
4458 (when (or force-heading (not (org-insert-item)))
4459 (let* ((head (save-excursion
4460 (condition-case nil
4461 (progn
4462 (org-back-to-heading)
4463 (match-string 0))
4464 (error "*"))))
4465 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4466 pos)
4467 (cond
4468 ((and (org-on-heading-p) (bolp)
4469 (save-excursion (backward-char 1) (not (org-invisible-p))))
4470 (open-line (if blank 2 1)))
4471 ((and (bolp) (save-excursion
4472 (backward-char 1) (not (org-invisible-p))))
4473 nil)
4474 (t (newline (if blank 2 1))))
4475 (insert head) (just-one-space)
4476 (setq pos (point))
4477 (end-of-line 1)
4478 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4479 (run-hooks 'org-insert-heading-hook)))))
4482 (defun org-insert-todo-heading (arg)
4483 "Insert a new heading with the same level and TODO state as current heading.
4484 If the heading has no TODO state, or if the state is DONE, use the first
4485 state (TODO by default). Also with prefix arg, force first state."
4486 (interactive "P")
4487 (when (not (org-insert-item 'checkbox))
4488 (org-insert-heading)
4489 (save-excursion
4490 (org-back-to-heading)
4491 (outline-previous-heading)
4492 (looking-at org-todo-line-regexp))
4493 (if (or arg
4494 (not (match-beginning 2))
4495 (equal (match-string 2) org-done-string))
4496 (insert (car org-todo-keywords) " ")
4497 (insert (match-string 2) " "))))
4499 ;;; Promotion and Demotion
4501 (defun org-promote-subtree ()
4502 "Promote the entire subtree.
4503 See also `org-promote'."
4504 (interactive)
4505 (save-excursion
4506 (org-map-tree 'org-promote))
4507 (org-fix-position-after-promote))
4509 (defun org-demote-subtree ()
4510 "Demote the entire subtree. See `org-demote'.
4511 See also `org-promote'."
4512 (interactive)
4513 (save-excursion
4514 (org-map-tree 'org-demote))
4515 (org-fix-position-after-promote))
4518 (defun org-do-promote ()
4519 "Promote the current heading higher up the tree.
4520 If the region is active in `transient-mark-mode', promote all headings
4521 in the region."
4522 (interactive)
4523 (save-excursion
4524 (if (org-region-active-p)
4525 (org-map-region 'org-promote (region-beginning) (region-end))
4526 (org-promote)))
4527 (org-fix-position-after-promote))
4529 (defun org-do-demote ()
4530 "Demote the current heading lower down the tree.
4531 If the region is active in `transient-mark-mode', demote all headings
4532 in the region."
4533 (interactive)
4534 (save-excursion
4535 (if (org-region-active-p)
4536 (org-map-region 'org-demote (region-beginning) (region-end))
4537 (org-demote)))
4538 (org-fix-position-after-promote))
4540 ;; FIXME: check and remove
4541 ;(defun org-fix-position-after-promote ()
4542 ; "Make sure that after pro/demotion cursor position is right."
4543 ; (if (and (or (eobp) (equal (char-after) ?\n))
4544 ; (save-excursion
4545 ; (skip-chars-backward "a-zA-Z0-9_@")
4546 ; (looking-at org-todo-regexp)))
4547 ; (insert " "))
4548 ; (and (equal (char-after) ?\ )
4549 ; (equal (char-before) ?*)
4550 ; (forward-char 1)))
4552 (defun org-fix-position-after-promote ()
4553 "Make sure that after pro/demotion cursor position is right."
4554 (let ((pos (point)))
4555 (when (save-excursion
4556 (beginning-of-line 1)
4557 (looking-at org-todo-line-regexp)
4558 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4559 (cond ((eobp) (insert " "))
4560 ((eolp) (insert " "))
4561 ((equal (char-after) ?\ ) (forward-char 1))))))
4563 (defun org-get-legal-level (level &optional change)
4564 "Rectify a level change under the influence of `org-odd-levels-only'
4565 LEVEL is a current level, CHANGE is by how much the level should be
4566 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4567 even level numbers will become the next higher odd number."
4568 (if org-odd-levels-only
4569 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4570 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4571 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4572 (max 1 (+ level change))))
4574 (defun org-promote ()
4575 "Promote the current heading higher up the tree.
4576 If the region is active in `transient-mark-mode', promote all headings
4577 in the region."
4578 (org-back-to-heading t)
4579 (let* ((level (save-match-data (funcall outline-level)))
4580 (up-head (make-string (org-get-legal-level level -1) ?*))
4581 (diff (abs (- level (length up-head)))))
4582 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4583 (replace-match up-head nil t)
4584 ;; Fixup tag positioning
4585 (and org-auto-align-tags (org-set-tags nil t))
4586 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4588 (defun org-demote ()
4589 "Demote the current heading lower down the tree.
4590 If the region is active in `transient-mark-mode', demote all headings
4591 in the region."
4592 (org-back-to-heading t)
4593 (let* ((level (save-match-data (funcall outline-level)))
4594 (down-head (make-string (org-get-legal-level level 1) ?*))
4595 (diff (abs (- level (length down-head)))))
4596 (replace-match down-head nil t)
4597 ;; Fixup tag positioning
4598 (and org-auto-align-tags (org-set-tags nil t))
4599 (if org-adapt-indentation (org-fixup-indentation diff))))
4601 (defun org-map-tree (fun)
4602 "Call FUN for every heading underneath the current one."
4603 (org-back-to-heading)
4604 (let ((level (funcall outline-level)))
4605 (save-excursion
4606 (funcall fun)
4607 (while (and (progn
4608 (outline-next-heading)
4609 (> (funcall outline-level) level))
4610 (not (eobp)))
4611 (funcall fun)))))
4613 (defun org-map-region (fun beg end)
4614 "Call FUN for every heading between BEG and END."
4615 (let ((org-ignore-region t))
4616 (save-excursion
4617 (setq end (copy-marker end))
4618 (goto-char beg)
4619 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4620 (< (point) end))
4621 (funcall fun))
4622 (while (and (progn
4623 (outline-next-heading)
4624 (< (point) end))
4625 (not (eobp)))
4626 (funcall fun)))))
4628 (defun org-fixup-indentation (diff)
4629 "Change the indentation in the current entry by DIFF
4630 However, if any line in the current entry has no indentation, or if it
4631 would end up with no indentation after the change, nothing at all is done."
4632 (save-excursion
4633 (let ((end (save-excursion (outline-next-heading)
4634 (point-marker)))
4635 (prohibit (if (> diff 0)
4636 "^\\S-"
4637 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4638 col)
4639 (unless (save-excursion (re-search-forward prohibit end t))
4640 (while (re-search-forward "^[ \t]+" end t)
4641 (goto-char (match-end 0))
4642 (setq col (current-column))
4643 (if (< diff 0) (replace-match ""))
4644 (indent-to (+ diff col))))
4645 (move-marker end nil))))
4647 (defun org-convert-to-odd-levels ()
4648 "Convert an org-mode file with all levels allowed to one with odd levels.
4649 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4650 level 5 etc."
4651 (interactive)
4652 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4653 (let ((org-odd-levels-only nil) n)
4654 (save-excursion
4655 (goto-char (point-min))
4656 (while (re-search-forward "^\\*\\*+" nil t)
4657 (setq n (1- (length (match-string 0))))
4658 (while (>= (setq n (1- n)) 0)
4659 (org-demote))
4660 (end-of-line 1))))))
4663 (defun org-convert-to-oddeven-levels ()
4664 "Convert an org-mode file with only odd levels to one with odd and even levels.
4665 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4666 section with an even level, conversion would destroy the structure of the file. An error
4667 is signaled in this case."
4668 (interactive)
4669 (goto-char (point-min))
4670 ;; First check if there are no even levels
4671 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
4672 (org-show-context t)
4673 (error "Not all levels are odd in this file. Conversion not possible."))
4674 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4675 (let ((org-odd-levels-only nil) n)
4676 (save-excursion
4677 (goto-char (point-min))
4678 (while (re-search-forward "^\\*\\*+" nil t)
4679 (setq n (/ (length (match-string 0)) 2))
4680 (while (>= (setq n (1- n)) 0)
4681 (org-promote))
4682 (end-of-line 1))))))
4684 (defun org-tr-level (n)
4685 "Make N odd if required."
4686 (if org-odd-levels-only (1+ (/ n 2)) n))
4688 ;;; Vertical tree motion, cutting and pasting of subtrees
4690 (defun org-move-subtree-up (&optional arg)
4691 "Move the current subtree up past ARG headlines of the same level."
4692 (interactive "p")
4693 (org-move-subtree-down (- (prefix-numeric-value arg))))
4695 (defun org-move-subtree-down (&optional arg)
4696 "Move the current subtree down past ARG headlines of the same level."
4697 (interactive "p")
4698 (setq arg (prefix-numeric-value arg))
4699 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4700 'outline-get-last-sibling))
4701 (ins-point (make-marker))
4702 (cnt (abs arg))
4703 beg end txt folded)
4704 ;; Select the tree
4705 (org-back-to-heading)
4706 (setq beg (point))
4707 (save-match-data
4708 (save-excursion (outline-end-of-heading)
4709 (setq folded (org-invisible-p)))
4710 (outline-end-of-subtree))
4711 (outline-next-heading)
4712 (setq end (point))
4713 ;; Find insertion point, with error handling
4714 (goto-char beg)
4715 (while (> cnt 0)
4716 (or (and (funcall movfunc) (looking-at outline-regexp))
4717 (progn (goto-char beg)
4718 (error "Cannot move past superior level or buffer limit")))
4719 (setq cnt (1- cnt)))
4720 (if (> arg 0)
4721 ;; Moving forward - still need to move over subtree
4722 (progn (outline-end-of-subtree)
4723 (outline-next-heading)
4724 (if (not (or (looking-at (concat "^" outline-regexp))
4725 (bolp)))
4726 (newline))))
4727 (move-marker ins-point (point))
4728 (setq txt (buffer-substring beg end))
4729 (delete-region beg end)
4730 (insert txt)
4731 (goto-char ins-point)
4732 (if folded (hide-subtree))
4733 (move-marker ins-point nil)))
4735 (defvar org-subtree-clip ""
4736 "Clipboard for cut and paste of subtrees.
4737 This is actually only a copy of the kill, because we use the normal kill
4738 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4740 (defvar org-subtree-clip-folded nil
4741 "Was the last copied subtree folded?
4742 This is used to fold the tree back after pasting.")
4744 (defun org-cut-subtree ()
4745 "Cut the current subtree into the clipboard.
4746 This is a short-hand for marking the subtree and then cutting it."
4747 (interactive)
4748 (org-copy-subtree 'cut))
4750 (defun org-copy-subtree (&optional cut)
4751 "Cut the current subtree into the clipboard.
4752 This is a short-hand for marking the subtree and then copying it.
4753 If CUT is non-nil, actually cut the subtree."
4754 (interactive)
4755 (let (beg end folded)
4756 (org-back-to-heading)
4757 (setq beg (point))
4758 (save-match-data
4759 (save-excursion (outline-end-of-heading)
4760 (setq folded (org-invisible-p)))
4761 (outline-end-of-subtree))
4762 (if (equal (char-after) ?\n) (forward-char 1))
4763 (setq end (point))
4764 (goto-char beg)
4765 (when (> end beg)
4766 (setq org-subtree-clip-folded folded)
4767 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4768 (setq org-subtree-clip (current-kill 0))
4769 (message "%s: Subtree with %d characters"
4770 (if cut "Cut" "Copied")
4771 (length org-subtree-clip)))))
4773 (defun org-paste-subtree (&optional level tree)
4774 "Paste the clipboard as a subtree, with modification of headline level.
4775 The entire subtree is promoted or demoted in order to match a new headline
4776 level. By default, the new level is derived from the visible headings
4777 before and after the insertion point, and taken to be the inferior headline
4778 level of the two. So if the previous visible heading is level 3 and the
4779 next is level 4 (or vice versa), level 4 will be used for insertion.
4780 This makes sure that the subtree remains an independent subtree and does
4781 not swallow low level entries.
4783 You can also force a different level, either by using a numeric prefix
4784 argument, or by inserting the heading marker by hand. For example, if the
4785 cursor is after \"*****\", then the tree will be shifted to level 5.
4787 If you want to insert the tree as is, just use \\[yank].
4789 If optional TREE is given, use this text instead of the kill ring."
4790 (interactive "P")
4791 (unless (org-kill-is-subtree-p tree)
4792 (error
4793 (substitute-command-keys
4794 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4795 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4796 (^re (concat "^\\(" outline-regexp "\\)"))
4797 (re (concat "\\(" outline-regexp "\\)"))
4798 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4800 (old-level (if (string-match ^re txt)
4801 (- (match-end 0) (match-beginning 0))
4802 -1))
4803 (force-level (cond (level (prefix-numeric-value level))
4804 ((string-match
4805 ^re_ (buffer-substring (point-at-bol) (point)))
4806 (- (match-end 0) (match-beginning 0)))
4807 (t nil)))
4808 (previous-level (save-excursion
4809 (condition-case nil
4810 (progn
4811 (outline-previous-visible-heading 1)
4812 (if (looking-at re)
4813 (- (match-end 0) (match-beginning 0))
4815 (error 1))))
4816 (next-level (save-excursion
4817 (condition-case nil
4818 (progn
4819 (outline-next-visible-heading 1)
4820 (if (looking-at re)
4821 (- (match-end 0) (match-beginning 0))
4823 (error 1))))
4824 (new-level (or force-level (max previous-level next-level)))
4825 (shift (if (or (= old-level -1)
4826 (= new-level -1)
4827 (= old-level new-level))
4829 (- new-level old-level)))
4830 (shift1 shift)
4831 (delta (if (> shift 0) -1 1))
4832 (func (if (> shift 0) 'org-demote 'org-promote))
4833 (org-odd-levels-only nil)
4834 beg end)
4835 ;; Remove the forces level indicator
4836 (if force-level
4837 (delete-region (point-at-bol) (point)))
4838 ;; Make sure we start at the beginning of an empty line
4839 (if (not (bolp)) (insert "\n"))
4840 (if (not (looking-at "[ \t]*$"))
4841 (progn (insert "\n") (backward-char 1)))
4842 ;; Paste
4843 (setq beg (point))
4844 (if (string-match "[ \t\r\n]+\\'" txt)
4845 (setq txt (replace-match "\n" t t txt)))
4846 (insert txt)
4847 (setq end (point))
4848 (if (looking-at "[ \t\r\n]+")
4849 (replace-match "\n"))
4850 (goto-char beg)
4851 ;; Shift if necessary
4852 (if (= shift 0)
4853 (message "Pasted at level %d, without shift" new-level)
4854 (save-restriction
4855 (narrow-to-region beg end)
4856 (while (not (= shift 0))
4857 (org-map-region func (point-min) (point-max))
4858 (setq shift (+ delta shift)))
4859 (goto-char (point-min))
4860 (message "Pasted at level %d, with shift by %d levels"
4861 new-level shift1)))
4862 (if (and kill-ring
4863 (eq org-subtree-clip (current-kill 0))
4864 org-subtree-clip-folded)
4865 ;; The tree was folded before it was killed/copied
4866 (hide-subtree))))
4868 (defun org-kill-is-subtree-p (&optional txt)
4869 "Check if the current kill is an outline subtree, or a set of trees.
4870 Returns nil if kill does not start with a headline, or if the first
4871 headline level is not the largest headline level in the tree.
4872 So this will actually accept several entries of equal levels as well,
4873 which is OK for `org-paste-subtree'.
4874 If optional TXT is given, check this string instead of the current kill."
4875 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4876 (start-level (and kill
4877 (string-match (concat "\\`" outline-regexp) kill)
4878 (- (match-end 0) (match-beginning 0))))
4879 (re (concat "^" outline-regexp))
4880 (start 1))
4881 (if (not start-level)
4882 nil ;; does not even start with a heading
4883 (catch 'exit
4884 (while (setq start (string-match re kill (1+ start)))
4885 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4886 (throw 'exit nil)))
4887 t))))
4889 (defun org-narrow-to-subtree ()
4890 "Narrow buffer to the current subtree."
4891 (interactive)
4892 (save-excursion
4893 (narrow-to-region
4894 (progn (org-back-to-heading) (point))
4895 (progn (org-end-of-subtree t) (point)))))
4898 ;;; Outline Sorting
4900 (defun org-sort (with-case)
4901 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
4902 (interactive "P")
4903 (if (org-at-table-p)
4904 (org-call-with-arg 'org-table-sort-lines with-case)
4905 (org-call-with-arg 'org-sort-entries with-case)))
4907 (defun org-sort-entries (&optional with-case sorting-type)
4908 "Sort entries on a certain level of an outline tree.
4909 If there is an active region, the entries in the region are sorted.
4910 If not, the children of the entry at point are sorted.
4912 Sorting can be alphabetically, numerically, and by date/time as given by
4913 the first time stamp in the entry. The command prompts for the sorting
4914 type unless it has been given to the function through the SORTING-TYPE
4915 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
4917 Comparing entries ignores case by default. However, with an optional argument
4918 WITH-CASE, the sorting considers case as well. With two prefix arguments
4919 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
4920 (interactive "P")
4921 (let ((unique (equal with-case '(16)))
4922 start beg end entries stars re re2 p nentries (nremoved 0) last txt)
4924 ;; Find beginning and end of region to sort
4925 (if (org-region-active-p)
4926 (progn
4927 ;; we will sort the region
4928 (setq end (region-end))
4929 (goto-char (1- (setq start (region-beginning)))))
4930 ;; we will sort the children of the current headline
4931 (setq start (point) end (org-end-of-subtree))
4932 (goto-char start)
4933 (show-subtree))
4934 (outline-next-heading) ; this is the first heading to be included
4935 (setq beg (point))
4936 (if (>= (point) end) (error "Nothing to sort"))
4937 (looking-at "\\(\\*+\\)")
4938 (setq stars (match-string 1)
4939 re (concat "^" (regexp-quote stars) " +")
4940 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4941 txt (buffer-substring beg end))
4942 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4943 (if (string-match re2 txt)
4944 (error "Region to sort contains a level above the first entry"))
4945 ;; Make a list that can be sorted.
4946 ;; The car is the string for comparison, the cdr is the subtree
4947 (message "Sorting entries...")
4948 (setq entries
4949 (mapcar
4950 (lambda (x)
4951 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
4952 (cons (match-string 0 x) x))
4953 (org-split-string txt re)))
4955 ;; Sort the list
4956 (setq entries (org-do-sort
4957 entries
4958 (if (org-region-active-p) "region" "children")
4959 with-case sorting-type))
4961 ;; Delete the old stuff
4962 (goto-char beg)
4963 (kill-region beg end)
4964 (setq nentries (length entries))
4965 ;; Insert the sorted entries, and remove duplicates if this is required
4966 (while (setq p (pop entries))
4967 (if (and unique (equal last (setq last (org-trim (cdr p)))))
4968 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
4969 (insert stars " " (cdr p))))
4970 (goto-char start)
4971 (message "Sorting entries...done (%d entries%s)"
4972 nentries
4973 (if unique (format ", %d duplicates removed" nremoved) ""))))
4975 (defun org-do-sort (table what &optional with-case sorting-type)
4976 "Sort TABLE of WHAT according to SORTING-TYPE.
4977 The user will be prompted for the SORTING-TYPE if the call to this
4978 function does not specify it. WHAT is only for the prompt, to indicate
4979 what is being sorted. The sorting key will be extracted from
4980 the car of the elements of the table.
4981 If WITH-CASE is non-nil, the sorting will be case-sensitive."
4982 (unless sorting-type
4983 (message
4984 "Sort %s:[a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
4985 what)
4986 (setq sorting-type (read-char-exclusive)))
4987 (let ((dcst (downcase sorting-type))
4988 extractfun comparefun)
4989 ;; Define the appropriate functions
4990 (cond
4991 ((= dcst ?n)
4992 (setq extractfun 'string-to-number
4993 comparefun (if (= dcst sorting-type) '< '>)))
4994 ((= dcst ?a)
4995 (setq extractfun (if with-case 'identity 'downcase)
4996 comparefun (if (= dcst sorting-type)
4997 'string<
4998 (lambda (a b) (and (not (string< a b))
4999 (not (string= a b)))))))
5000 ((= dcst ?t)
5001 (setq extractfun
5002 (lambda (x)
5003 (if (string-match org-ts-regexp x)
5004 (time-to-seconds
5005 (org-time-string-to-time (match-string 0 x)))
5007 comparefun (if (= dcst sorting-type) '< '>)))
5008 (t (error "Invalid sorting type `%c'" sorting-type)))
5010 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5011 table)
5012 (lambda (a b) (funcall comparefun (car a) (car b))))))
5014 ;;;; Plain list items, including checkboxes
5016 ;;; Plain list items
5018 (defun org-at-item-p ()
5019 "Is point in a line starting a hand-formatted item?"
5020 (let ((llt org-plain-list-ordered-item-terminator))
5021 (save-excursion
5022 (goto-char (point-at-bol))
5023 (looking-at
5024 (cond
5025 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5026 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5027 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5028 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5031 (defun org-in-item-p ()
5032 "It the cursor inside a plain list item.
5033 Does not have to be the first line."
5034 (save-excursion
5035 (condition-case nil
5036 (progn
5037 (org-beginning-of-item)
5038 (org-at-item-p)
5040 (error nil))))
5042 (defun org-insert-item (&optional checkbox)
5043 "Insert a new item at the current level.
5044 Return t when things worked, nil when we are not in an item."
5045 (when (save-excursion
5046 (condition-case nil
5047 (progn
5048 (org-beginning-of-item)
5049 (org-at-item-p)
5050 (if (org-invisible-p) (error "Invisible item"))
5052 (error nil)))
5053 (let* ((bul (match-string 0))
5054 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5055 (match-end 0)))
5056 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5057 pos)
5058 (cond
5059 ((and (org-at-item-p) (<= (point) eow))
5060 ;; before the bullet
5061 (beginning-of-line 1)
5062 (open-line (if blank 2 1)))
5063 ((<= (point) eow)
5064 (beginning-of-line 1))
5065 (t (newline (if blank 2 1))))
5066 (insert bul (if checkbox "[ ]" ""))
5067 (just-one-space)
5068 (setq pos (point))
5069 (end-of-line 1)
5070 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5071 (org-maybe-renumber-ordered-list)
5072 (and checkbox (org-update-checkbox-count-maybe))
5075 ;;; Checkboxes
5077 (defun org-at-item-checkbox-p ()
5078 "Is point at a line starting a plain-list item with a checklet?"
5079 (and (org-at-item-p)
5080 (save-excursion
5081 (goto-char (match-end 0))
5082 (skip-chars-forward " \t")
5083 (looking-at "\\[[ X]\\]"))))
5085 (defun org-toggle-checkbox (&optional arg)
5086 "Toggle the checkbox in the current line."
5087 (interactive "P")
5088 (catch 'exit
5089 (let (beg end status (firstnew 'unknown))
5090 (cond
5091 ((org-region-active-p)
5092 (setq beg (region-beginning) end (region-end)))
5093 ((org-on-heading-p)
5094 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5095 ((org-at-item-checkbox-p)
5096 (save-excursion
5097 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
5098 (throw 'exit t))
5099 (t (error "Not at a checkbox or heading, and no active region")))
5100 (save-excursion
5101 (goto-char beg)
5102 (while (< (point) end)
5103 (when (org-at-item-checkbox-p)
5104 (setq status (equal (match-string 0) "[X]"))
5105 (when (eq firstnew 'unknown)
5106 (setq firstnew (not status)))
5107 (replace-match
5108 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5109 (beginning-of-line 2)))))
5110 (org-update-checkbox-count-maybe))
5112 (defun org-update-checkbox-count-maybe ()
5113 "Update checkbox statistics unless turned off by user."
5114 (when org-provide-checkbox-statistics
5115 (org-update-checkbox-count)))
5117 (defun org-update-checkbox-count (&optional all)
5118 "Update the checkbox statistics in the current section.
5119 This will find all statistic cookies like [57%] and [6/12] and update them
5120 with the current numbers. With optional prefix argument ALL, do this for
5121 the whole buffer."
5122 (interactive "P")
5123 (save-excursion
5124 (let* ((buffer-invisibility-spec nil) ; Emacs 21 compatibility
5125 (beg (progn (outline-back-to-heading) (point)))
5126 (end (move-marker (make-marker)
5127 (progn (outline-next-heading) (point))))
5128 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5129 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
5130 b1 e1 f1 c-on c-off lim (cstat 0))
5131 (when all
5132 (goto-char (point-min))
5133 (outline-next-heading)
5134 (setq beg (point) end (point-max)))
5135 (goto-char beg)
5136 (while (re-search-forward re end t)
5137 (setq cstat (1+ cstat)
5138 b1 (match-beginning 0)
5139 e1 (match-end 0)
5140 f1 (match-beginning 1)
5141 lim (cond
5142 ((org-on-heading-p) (outline-next-heading) (point))
5143 ((org-at-item-p) (org-end-of-item) (point))
5144 (t nil))
5145 c-on 0 c-off 0)
5146 (goto-char e1)
5147 (when lim
5148 (while (re-search-forward re-box lim t)
5149 (if (equal (match-string 2) "[ ]")
5150 (setq c-off (1+ c-off))
5151 (setq c-on (1+ c-on))))
5152 (delete-region b1 e1)
5153 (goto-char b1)
5154 (insert (if f1
5155 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5156 (format "[%d/%d]" c-on (+ c-on c-off))))))
5157 (when (interactive-p)
5158 (message "Checkbox satistics updated %s (%d places)"
5159 (if all "in entire file" "in current outline entry") cstat)))))
5161 (defun org-get-checkbox-statistics-face ()
5162 "Select the face for checkbox statistics.
5163 The face will be `org-done' when all relevant boxes are checked. Otherwise
5164 it will be `org-todo'."
5165 (if (match-end 1)
5166 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5167 (if (and (> (match-end 2) (match-beginning 2))
5168 (equal (match-string 2) (match-string 3)))
5169 'org-done
5170 'org-todo)))
5172 (defun org-get-indentation (&optional line)
5173 "Get the indentation of the current line, interpreting tabs.
5174 When LINE is given, assume it represents a line and compute its indentation."
5175 (if line
5176 (if (string-match "^ *" (org-remove-tabs line))
5177 (match-end 0))
5178 (save-excursion
5179 (beginning-of-line 1)
5180 (skip-chars-forward " \t")
5181 (current-column))))
5183 (defun org-remove-tabs (s &optional width)
5184 "Replace tabulators in S with spaces.
5185 Assumes that s is a single line, starting in column 0."
5186 (setq width (or width tab-width))
5187 (while (string-match "\t" s)
5188 (setq s (replace-match
5189 (make-string
5190 (- (* width (/ (+ (match-beginning 0) width) width))
5191 (match-beginning 0)) ?\ )
5192 t t s)))
5195 (defun org-fix-indentation (line ind)
5196 "Fix indentation in LINE.
5197 IND is a cons cell with target and minimum indentation.
5198 If the current indenation in LINE is smaller than the minimum,
5199 leave it alone. If it is larger than ind, set it to the target."
5200 (let* ((l (org-remove-tabs line))
5201 (i (org-get-indentation l))
5202 (i1 (car ind)) (i2 (cdr ind)))
5203 (if (>= i i2) (setq l (substring line i2)))
5204 (if (> i1 0)
5205 (concat (make-string i1 ?\ ) l)
5206 l)))
5208 (defun org-beginning-of-item ()
5209 "Go to the beginning of the current hand-formatted item.
5210 If the cursor is not in an item, throw an error."
5211 (interactive)
5212 (let ((pos (point))
5213 (limit (save-excursion (org-back-to-heading)
5214 (beginning-of-line 2) (point)))
5215 ind ind1)
5216 (if (org-at-item-p)
5217 (beginning-of-line 1)
5218 (beginning-of-line 1)
5219 (skip-chars-forward " \t")
5220 (setq ind (current-column))
5221 (if (catch 'exit
5222 (while t
5223 (beginning-of-line 0)
5224 (if (< (point) limit) (throw 'exit nil))
5225 (unless (looking-at "[ \t]*$")
5226 (skip-chars-forward " \t")
5227 (setq ind1 (current-column))
5228 (if (< ind1 ind)
5229 (throw 'exit (org-at-item-p))))))
5231 (goto-char pos)
5232 (error "Not in an item")))))
5234 (defun org-end-of-item ()
5235 "Go to the end of the current hand-formatted item.
5236 If the cursor is not in an item, throw an error."
5237 (interactive)
5238 (let ((pos (point))
5239 (limit (save-excursion (outline-next-heading) (point)))
5240 (ind (save-excursion
5241 (org-beginning-of-item)
5242 (skip-chars-forward " \t")
5243 (current-column)))
5244 ind1)
5245 (if (catch 'exit
5246 (while t
5247 (beginning-of-line 2)
5248 (if (>= (point) limit) (throw 'exit t))
5249 (unless (looking-at "[ \t]*$")
5250 (skip-chars-forward " \t")
5251 (setq ind1 (current-column))
5252 (if (<= ind1 ind) (throw 'exit t)))))
5253 (beginning-of-line 1)
5254 (goto-char pos)
5255 (error "Not in an item"))))
5257 (defun org-next-item ()
5258 "Move to the beginning of the next item in the current plain list.
5259 Error if not at a plain list, or if this is the last item in the list."
5260 (interactive)
5261 (let (ind ind1 (pos (point)))
5262 (org-beginning-of-item)
5263 (setq ind (org-get-indentation))
5264 (org-end-of-item)
5265 (setq ind1 (org-get-indentation))
5266 (unless (and (org-at-item-p) (= ind ind1))
5267 (goto-char pos)
5268 (error "On last item"))))
5270 (defun org-previous-item ()
5271 "Move to the beginning of the previous item in the current plain list.
5272 Error if not at a plain list, or if this is the last item in the list."
5273 (interactive)
5274 (let (beg ind (pos (point)))
5275 (org-beginning-of-item)
5276 (setq beg (point))
5277 (setq ind (org-get-indentation))
5278 (goto-char beg)
5279 (catch 'exit
5280 (while t
5281 (beginning-of-line 0)
5282 (if (looking-at "[ \t]*$")
5284 (if (<= (org-get-indentation) ind)
5285 (throw 'exit t)))))
5286 (condition-case nil
5287 (org-beginning-of-item)
5288 (error (goto-char pos)
5289 (error "On first item")))))
5291 (defun org-move-item-down ()
5292 "Move the plain list item at point down, i.e. swap with following item.
5293 Subitems (items with larger indentation) are considered part of the item,
5294 so this really moves item trees."
5295 (interactive)
5296 (let (beg end ind ind1 (pos (point)) txt)
5297 (org-beginning-of-item)
5298 (setq beg (point))
5299 (setq ind (org-get-indentation))
5300 (org-end-of-item)
5301 (setq end (point))
5302 (setq ind1 (org-get-indentation))
5303 (if (and (org-at-item-p) (= ind ind1))
5304 (progn
5305 (org-end-of-item)
5306 (setq txt (buffer-substring beg end))
5307 (save-excursion
5308 (delete-region beg end))
5309 (setq pos (point))
5310 (insert txt)
5311 (goto-char pos)
5312 (org-maybe-renumber-ordered-list))
5313 (goto-char pos)
5314 (error "Cannot move this item further down"))))
5316 (defun org-move-item-up (arg)
5317 "Move the plain list item at point up, i.e. swap with previous item.
5318 Subitems (items with larger indentation) are considered part of the item,
5319 so this really moves item trees."
5320 (interactive "p")
5321 (let (beg end ind ind1 (pos (point)) txt)
5322 (org-beginning-of-item)
5323 (setq beg (point))
5324 (setq ind (org-get-indentation))
5325 (org-end-of-item)
5326 (setq end (point))
5327 (goto-char beg)
5328 (catch 'exit
5329 (while t
5330 (beginning-of-line 0)
5331 (if (looking-at "[ \t]*$")
5333 (if (<= (setq ind1 (org-get-indentation)) ind)
5334 (throw 'exit t)))))
5335 (condition-case nil
5336 (org-beginning-of-item)
5337 (error (goto-char beg)
5338 (error "Cannot move this item further up")))
5339 (setq ind1 (org-get-indentation))
5340 (if (and (org-at-item-p) (= ind ind1))
5341 (progn
5342 (setq txt (buffer-substring beg end))
5343 (save-excursion
5344 (delete-region beg end))
5345 (setq pos (point))
5346 (insert txt)
5347 (goto-char pos)
5348 (org-maybe-renumber-ordered-list))
5349 (goto-char pos)
5350 (error "Cannot move this item further up"))))
5352 (defun org-maybe-renumber-ordered-list ()
5353 "Renumber the ordered list at point if setup allows it.
5354 This tests the user option `org-auto-renumber-ordered-lists' before
5355 doing the renumbering."
5356 (and org-auto-renumber-ordered-lists
5357 (org-at-item-p)
5358 (match-beginning 3)
5359 (org-renumber-ordered-list 1)))
5361 (defun org-get-string-indentation (s)
5362 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5363 (let ((n -1) (i 0) (w tab-width) c)
5364 (catch 'exit
5365 (while (< (setq n (1+ n)) (length s))
5366 (setq c (aref s n))
5367 (cond ((= c ?\ ) (setq i (1+ i)))
5368 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5369 (t (throw 'exit t)))))
5372 (defun org-renumber-ordered-list (arg)
5373 "Renumber an ordered plain list.
5374 Cursor needs to be in the first line of an item, the line that starts
5375 with something like \"1.\" or \"2)\"."
5376 (interactive "p")
5377 (unless (and (org-at-item-p)
5378 (match-beginning 3))
5379 (error "This is not an ordered list"))
5380 (let ((line (org-current-line))
5381 (col (current-column))
5382 (ind (org-get-string-indentation
5383 (buffer-substring (point-at-bol) (match-beginning 3))))
5384 ;; (term (substring (match-string 3) -1))
5385 ind1 (n (1- arg)))
5386 ;; find where this list begins
5387 (catch 'exit
5388 (while t
5389 (catch 'next
5390 (beginning-of-line 0)
5391 (if (looking-at "[ \t]*$") (throw 'next t))
5392 (skip-chars-forward " \t") (setq ind1 (current-column))
5393 (if (or (< ind1 ind)
5394 (and (= ind1 ind)
5395 (not (org-at-item-p))))
5396 (throw 'exit t)))))
5397 ;; Walk forward and replace these numbers
5398 (catch 'exit
5399 (while t
5400 (catch 'next
5401 (beginning-of-line 2)
5402 (if (eobp) (throw 'exit nil))
5403 (if (looking-at "[ \t]*$") (throw 'next nil))
5404 (skip-chars-forward " \t") (setq ind1 (current-column))
5405 (if (> ind1 ind) (throw 'next t))
5406 (if (< ind1 ind) (throw 'exit t))
5407 (if (not (org-at-item-p)) (throw 'exit nil))
5408 (if (not (match-beginning 3))
5409 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
5410 (delete-region (match-beginning 3) (1- (match-end 3)))
5411 (goto-char (match-beginning 3))
5412 (insert (format "%d" (setq n (1+ n)))))))
5413 (goto-line line)
5414 (move-to-column col)))
5416 (defvar org-last-indent-begin-marker (make-marker))
5417 (defvar org-last-indent-end-marker (make-marker))
5419 (defun org-outdent-item (arg)
5420 "Outdent a local list item."
5421 (interactive "p")
5422 (org-indent-item (- arg)))
5424 (defun org-indent-item (arg)
5425 "Indent a local list item."
5426 (interactive "p")
5427 (unless (org-at-item-p)
5428 (error "Not on an item"))
5429 (save-excursion
5430 (let (beg end ind ind1)
5431 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5432 (setq beg org-last-indent-begin-marker
5433 end org-last-indent-end-marker)
5434 (org-beginning-of-item)
5435 (setq beg (move-marker org-last-indent-begin-marker (point)))
5436 (org-end-of-item)
5437 (setq end (move-marker org-last-indent-end-marker (point))))
5438 (goto-char beg)
5439 (skip-chars-forward " \t") (setq ind (current-column))
5440 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
5441 (while (< (point) end)
5442 (beginning-of-line 1)
5443 (skip-chars-forward " \t") (setq ind1 (current-column))
5444 (delete-region (point-at-bol) (point))
5445 (indent-to-column (+ ind1 arg))
5446 (beginning-of-line 2)))))
5448 ;;;; Archiving
5450 (defun org-archive-subtree (&optional find-done)
5451 "Move the current subtree to the archive.
5452 The archive can be a certain top-level heading in the current file, or in
5453 a different file. The tree will be moved to that location, the subtree
5454 heading be marked DONE, and the current time will be added.
5456 When called with prefix argument FIND-DONE, find whole trees without any
5457 open TODO items and archive them (after getting confirmation from the user).
5458 If the cursor is not at a headline when this comand is called, try all level
5459 1 trees. If the cursor is on a headline, only try the direct children of
5460 this heading. "
5461 (interactive "P")
5462 (if find-done
5463 (org-archive-all-done)
5464 ;; Save all relevant TODO keyword-relatex variables
5466 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5467 (tr-org-todo-keywords org-todo-keywords)
5468 (tr-org-todo-interpretation org-todo-interpretation)
5469 (tr-org-done-string org-done-string)
5470 (tr-org-todo-regexp org-todo-regexp)
5471 (tr-org-todo-line-regexp org-todo-line-regexp)
5472 (this-buffer (current-buffer))
5473 (org-archive-location org-archive-location)
5474 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
5475 file heading buffer level newfile-p)
5477 ;; Try to find a local archive location
5478 (save-excursion
5479 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
5480 (setq org-archive-location (match-string 1))))
5482 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5483 (progn
5484 (setq file (format (match-string 1 org-archive-location)
5485 (file-name-nondirectory buffer-file-name))
5486 heading (match-string 2 org-archive-location)))
5487 (error "Invalid `org-archive-location'"))
5488 (if (> (length file) 0)
5489 (setq newfile-p (not (file-exists-p file))
5490 buffer (find-file-noselect file))
5491 (setq buffer (current-buffer)))
5492 (unless buffer
5493 (error "Cannot access file \"%s\"" file))
5494 (if (and (> (length heading) 0)
5495 (string-match "^\\*+" heading))
5496 (setq level (match-end 0))
5497 (setq heading nil level 0))
5498 (save-excursion
5499 ;; We first only copy, in case something goes wrong
5500 ;; we need to protect this-command, to avoid kill-region sets it,
5501 ;; which would lead to duplication of subtrees
5502 (let (this-command) (org-copy-subtree))
5503 (set-buffer buffer)
5504 ;; Enforce org-mode for the archive buffer
5505 (if (not (org-mode-p))
5506 ;; Force the mode for future visits.
5507 (let ((org-insert-mode-line-in-empty-file t))
5508 (call-interactively 'org-mode)))
5509 (when newfile-p
5510 (goto-char (point-max))
5511 (insert (format "\nArchived entries from file %s\n\n"
5512 (buffer-file-name this-buffer))))
5513 ;; Force the TODO keywords of the original buffer
5514 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
5515 (org-todo-keywords tr-org-todo-keywords)
5516 (org-todo-interpretation tr-org-todo-interpretation)
5517 (org-done-string tr-org-done-string)
5518 (org-todo-regexp tr-org-todo-regexp)
5519 (org-todo-line-regexp tr-org-todo-line-regexp))
5520 (goto-char (point-min))
5521 (if heading
5522 (progn
5523 (if (re-search-forward
5524 (concat "\\(^\\|\r\\)"
5525 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
5526 nil t)
5527 (goto-char (match-end 0))
5528 ;; Heading not found, just insert it at the end
5529 (goto-char (point-max))
5530 (or (bolp) (insert "\n"))
5531 (insert "\n" heading "\n")
5532 (end-of-line 0))
5533 ;; Make the subtree visible
5534 (show-subtree)
5535 (org-end-of-subtree t)
5536 (skip-chars-backward " \t\r\n")
5537 (and (looking-at "[ \t\r\n]*")
5538 (replace-match "\n\n")))
5539 ;; No specific heading, just go to end of file.
5540 (goto-char (point-max)) (insert "\n"))
5541 ;; Paste
5542 (org-paste-subtree (1+ level))
5543 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
5544 (if org-archive-mark-done
5545 (let (org-log-done)
5546 (org-todo (length org-todo-keywords))))
5547 ;; Move cursor to right after the TODO keyword
5548 (when org-archive-stamp-time
5549 (beginning-of-line 1)
5550 (looking-at org-todo-line-regexp)
5551 (goto-char (or (match-end 2) (match-beginning 3)))
5552 (org-insert-time-stamp (org-current-time) t t "(" ")"))
5553 ;; Save the buffer, if it is not the same buffer.
5554 (if (not (eq this-buffer buffer)) (save-buffer))))
5555 ;; Here we are back in the original buffer. Everything seems to have
5556 ;; worked. So now cut the tree and finish up.
5557 (let (this-command) (org-cut-subtree))
5558 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5559 (message "Subtree archived %s"
5560 (if (eq this-buffer buffer)
5561 (concat "under heading: " heading)
5562 (concat "in file: " (abbreviate-file-name file)))))))
5564 (defun org-archive-all-done (&optional tag)
5565 "Archive sublevels of the current tree without open TODO items.
5566 If the cursor is not on a headline, try all level 1 trees. If
5567 it is on a headline, try all direct children.
5568 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5569 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5570 (rea (concat ".*:" org-archive-tag ":"))
5571 (begm (make-marker))
5572 (endm (make-marker))
5573 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
5574 "Move subtree to archive (no open TODO items)? "))
5575 beg end (cntarch 0))
5576 (if (org-on-heading-p)
5577 (progn
5578 (setq re1 (concat "^" (regexp-quote
5579 (make-string
5580 (1+ (- (match-end 0) (match-beginning 0)))
5581 ?*))
5582 " "))
5583 (move-marker begm (point))
5584 (move-marker endm (org-end-of-subtree t)))
5585 (setq re1 "^* ")
5586 (move-marker begm (point-min))
5587 (move-marker endm (point-max)))
5588 (save-excursion
5589 (goto-char begm)
5590 (while (re-search-forward re1 endm t)
5591 (setq beg (match-beginning 0)
5592 end (save-excursion (org-end-of-subtree t) (point)))
5593 (goto-char beg)
5594 (if (re-search-forward re end t)
5595 (goto-char end)
5596 (goto-char beg)
5597 (if (and (or (not tag) (not (looking-at rea)))
5598 (y-or-n-p question))
5599 (progn
5600 (if tag
5601 (org-toggle-tag org-archive-tag 'on)
5602 (org-archive-subtree))
5603 (setq cntarch (1+ cntarch)))
5604 (goto-char end)))))
5605 (message "%d trees archived" cntarch)))
5607 (defun org-cycle-hide-archived-subtrees (state)
5608 "Re-hide all archived subtrees after a visibility state change."
5609 (when (and (not org-cycle-open-archived-trees)
5610 (not (memq state '(overview folded))))
5611 (save-excursion
5612 (let* ((globalp (memq state '(contents all)))
5613 (beg (if globalp (point-min) (point)))
5614 (end (if globalp (point-max) (org-end-of-subtree t))))
5615 (org-hide-archived-subtrees beg end)
5616 (goto-char beg)
5617 (if (looking-at (concat ".*:" org-archive-tag ":"))
5618 (message (substitute-command-keys
5619 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5621 (defun org-force-cycle-archived ()
5622 "Cycle subtree even if it is archived."
5623 (interactive)
5624 (setq this-command 'org-cycle)
5625 (let ((org-cycle-open-archived-trees t))
5626 (call-interactively 'org-cycle)))
5628 (defun org-hide-archived-subtrees (beg end)
5629 "Re-hide all archived subtrees after a visibility state change."
5630 (save-excursion
5631 (let* ((re (concat ":" org-archive-tag ":")))
5632 (goto-char beg)
5633 (while (re-search-forward re end t)
5634 (and (org-on-heading-p) (hide-subtree))
5635 (org-end-of-subtree t)))))
5637 (defun org-toggle-tag (tag &optional onoff)
5638 "Toggle the tag TAG for the current line.
5639 If ONOFF is `on' or `off', don't toggle but set to this state."
5640 (unless (org-on-heading-p) (error "Not on headling"))
5641 (let (res current)
5642 (save-excursion
5643 (beginning-of-line)
5644 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5645 (point-at-eol) t)
5646 (progn
5647 (setq current (match-string 1))
5648 (replace-match ""))
5649 (setq current ""))
5650 (setq current (nreverse (org-split-string current ":")))
5651 (cond
5652 ((eq onoff 'on)
5653 (setq res t)
5654 (or (member tag current) (push tag current)))
5655 ((eq onoff 'off)
5656 (or (not (member tag current)) (setq current (delete tag current))))
5657 (t (if (member tag current)
5658 (setq current (delete tag current))
5659 (setq res t)
5660 (push tag current))))
5661 (end-of-line 1)
5662 (when current
5663 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5664 (org-set-tags nil t))
5665 res))
5667 (defun org-toggle-archive-tag (&optional arg)
5668 "Toggle the archive tag for the current headline.
5669 With prefix ARG, check all children of current headline and offer tagging
5670 the children that do not contain any open TODO items."
5671 (interactive "P")
5672 (if arg
5673 (org-archive-all-done 'tag)
5674 (let (set)
5675 (save-excursion
5676 (org-back-to-heading t)
5677 (setq set (org-toggle-tag org-archive-tag))
5678 (when set (hide-subtree)))
5679 (and set (beginning-of-line 1))
5680 (message "Subtree %s" (if set "archived" "unarchived")))))
5683 ;;;; Tables
5685 ;;; The table editor
5687 ;; Watch out: Here we are talking about two different kind of tables.
5688 ;; Most of the code is for the tables created with the Org-mode table editor.
5689 ;; Sometimes, we talk about tables created and edited with the table.el
5690 ;; Emacs package. We call the former org-type tables, and the latter
5691 ;; table.el-type tables.
5693 (defun org-before-change-function (beg end)
5694 "Every change indicates that a table might need an update."
5695 (setq org-table-may-need-update t))
5697 (defconst org-table-line-regexp "^[ \t]*|"
5698 "Detects an org-type table line.")
5699 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5700 "Detects an org-type table line.")
5701 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5702 "Detects a table line marked for automatic recalculation.")
5703 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5704 "Detects a table line marked for automatic recalculation.")
5705 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5706 "Detects a table line marked for automatic recalculation.")
5707 (defconst org-table-hline-regexp "^[ \t]*|-"
5708 "Detects an org-type table hline.")
5709 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5710 "Detects a table-type table hline.")
5711 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5712 "Detects an org-type or table-type table.")
5713 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5714 "Searching from within a table (any type) this finds the first line
5715 outside the table.")
5716 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5717 "Searching from within a table (any type) this finds the first line
5718 outside the table.")
5720 (defun org-table-create-with-table.el ()
5721 "Use the table.el package to insert a new table.
5722 If there is already a table at point, convert between Org-mode tables
5723 and table.el tables."
5724 (interactive)
5725 (require 'table)
5726 (cond
5727 ((org-at-table.el-p)
5728 (if (y-or-n-p "Convert table to Org-mode table? ")
5729 (org-table-convert)))
5730 ((org-at-table-p)
5731 (if (y-or-n-p "Convert table to table.el table? ")
5732 (org-table-convert)))
5733 (t (call-interactively 'table-insert))))
5735 (defun org-table-create-or-convert-from-region (arg)
5736 "Convert region to table, or create an empty table.
5737 If there is an active region, convert it to a table. If there is no such
5738 region, create an empty table."
5739 (interactive "P")
5740 (if (org-region-active-p)
5741 (org-table-convert-region (region-beginning) (region-end) arg)
5742 (org-table-create arg)))
5744 (defun org-table-create (&optional size)
5745 "Query for a size and insert a table skeleton.
5746 SIZE is a string Columns x Rows like for example \"3x2\"."
5747 (interactive "P")
5748 (unless size
5749 (setq size (read-string
5750 (concat "Table size Columns x Rows [e.g. "
5751 org-table-default-size "]: ")
5752 "" nil org-table-default-size)))
5754 (let* ((pos (point))
5755 (indent (make-string (current-column) ?\ ))
5756 (split (org-split-string size " *x *"))
5757 (rows (string-to-number (nth 1 split)))
5758 (columns (string-to-number (car split)))
5759 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5760 "\n")))
5761 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5762 (point-at-bol) (point)))
5763 (beginning-of-line 1)
5764 (newline))
5765 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5766 (dotimes (i rows) (insert line))
5767 (goto-char pos)
5768 (if (> rows 1)
5769 ;; Insert a hline after the first row.
5770 (progn
5771 (end-of-line 1)
5772 (insert "\n|-")
5773 (goto-char pos)))
5774 (org-table-align)))
5776 (defun org-table-convert-region (beg0 end0 &optional nspace)
5777 "Convert region to a table.
5778 The region goes from BEG0 to END0, but these borders will be moved
5779 slightly, to make sure a beginning of line in the first line is included.
5780 When NSPACE is non-nil, it indicates the minimum number of spaces that
5781 separate columns (default: just one space)."
5782 (interactive "rP")
5783 (let* ((beg (min beg0 end0))
5784 (end (max beg0 end0))
5785 (tabsep t)
5787 (goto-char beg)
5788 (beginning-of-line 1)
5789 (setq beg (move-marker (make-marker) (point)))
5790 (goto-char end)
5791 (if (bolp) (backward-char 1) (end-of-line 1))
5792 (setq end (move-marker (make-marker) (point)))
5793 ;; Lets see if this is tab-separated material. If every nonempty line
5794 ;; contains a tab, we will assume that it is tab-separated material
5795 (if nspace
5796 (setq tabsep nil)
5797 (goto-char beg)
5798 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5799 (if nspace (setq tabsep nil))
5800 (if tabsep
5801 (setq re "^\\|\t")
5802 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5803 (max 1 (prefix-numeric-value nspace)))))
5804 (goto-char beg)
5805 (while (re-search-forward re end t)
5806 (replace-match "| " t t))
5807 (goto-char beg)
5808 (insert " ")
5809 (org-table-align)))
5811 (defun org-table-import (file arg)
5812 "Import FILE as a table.
5813 The file is assumed to be tab-separated. Such files can be produced by most
5814 spreadsheet and database applications. If no tabs (at least one per line)
5815 are found, lines will be split on whitespace into fields."
5816 (interactive "f\nP")
5817 (or (bolp) (newline))
5818 (let ((beg (point))
5819 (pm (point-max)))
5820 (insert-file-contents file)
5821 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5823 (defun org-table-export ()
5824 "Export table as a tab-separated file.
5825 Such a file can be imported into a spreadsheet program like Excel."
5826 (interactive)
5827 (let* ((beg (org-table-begin))
5828 (end (org-table-end))
5829 (table (buffer-substring beg end))
5830 (file (read-file-name "Export table to: "))
5831 buf)
5832 (unless (or (not (file-exists-p file))
5833 (y-or-n-p (format "Overwrite file %s? " file)))
5834 (error "Abort"))
5835 (with-current-buffer (find-file-noselect file)
5836 (setq buf (current-buffer))
5837 (erase-buffer)
5838 (fundamental-mode)
5839 (insert table)
5840 (goto-char (point-min))
5841 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5842 (replace-match "" t t)
5843 (end-of-line 1))
5844 (goto-char (point-min))
5845 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5846 (replace-match "" t t)
5847 (goto-char (min (1+ (point)) (point-max))))
5848 (goto-char (point-min))
5849 (while (re-search-forward "^-[-+]*$" nil t)
5850 (replace-match "")
5851 (if (looking-at "\n")
5852 (delete-char 1)))
5853 (goto-char (point-min))
5854 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5855 (replace-match "\t" t t))
5856 (save-buffer))
5857 (kill-buffer buf)))
5859 (defvar org-table-aligned-begin-marker (make-marker)
5860 "Marker at the beginning of the table last aligned.
5861 Used to check if cursor still is in that table, to minimize realignment.")
5862 (defvar org-table-aligned-end-marker (make-marker)
5863 "Marker at the end of the table last aligned.
5864 Used to check if cursor still is in that table, to minimize realignment.")
5865 (defvar org-table-last-alignment nil
5866 "List of flags for flushright alignment, from the last re-alignment.
5867 This is being used to correctly align a single field after TAB or RET.")
5868 (defvar org-table-last-column-widths nil
5869 "List of max width of fields in each column.
5870 This is being used to correctly align a single field after TAB or RET.")
5872 (defvar org-last-recalc-line nil)
5873 (defconst org-narrow-column-arrow "=>"
5874 "Used as display property in narrowed table columns.")
5876 (defun org-table-align ()
5877 "Align the table at point by aligning all vertical bars."
5878 (interactive)
5879 (let* (
5880 ;; Limits of table
5881 (beg (org-table-begin))
5882 (end (org-table-end))
5883 ;; Current cursor position
5884 (linepos (org-current-line))
5885 (colpos (org-table-current-column))
5886 (winstart (window-start))
5887 (winstartline (org-current-line (min winstart (1- (point-max)))))
5888 lines (new "") lengths l typenums ty fields maxfields i
5889 column
5890 (indent "") cnt frac
5891 rfmt hfmt
5892 (spaces '(1 . 1))
5893 (sp1 (car spaces))
5894 (sp2 (cdr spaces))
5895 (rfmt1 (concat
5896 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
5897 (hfmt1 (concat
5898 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
5899 emptystrings links dates narrow fmax f1 len c e)
5900 (untabify beg end)
5901 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
5902 ;; Check if we have links or dates
5903 (goto-char beg)
5904 (setq links (re-search-forward org-bracket-link-regexp end t))
5905 (goto-char beg)
5906 (setq dates (and org-display-custom-times
5907 (re-search-forward org-ts-regexp-both end t)))
5908 ;; Make sure the link properties are right
5909 (when links (goto-char beg) (while (org-activate-bracket-links end)))
5910 ;; Make sure the date properties are right
5911 (when dates (goto-char beg) (while (org-activate-dates end)))
5913 ;; Check if we are narrowing any columns
5914 (goto-char beg)
5915 (setq narrow (and org-format-transports-properties-p
5916 (re-search-forward "<[0-9]+>" end t)))
5917 ;; Get the rows
5918 (setq lines (org-split-string
5919 (buffer-substring beg end) "\n"))
5920 ;; Store the indentation of the first line
5921 (if (string-match "^ *" (car lines))
5922 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
5923 ;; Mark the hlines by setting the corresponding element to nil
5924 ;; At the same time, we remove trailing space.
5925 (setq lines (mapcar (lambda (l)
5926 (if (string-match "^ *|-" l)
5928 (if (string-match "[ \t]+$" l)
5929 (substring l 0 (match-beginning 0))
5930 l)))
5931 lines))
5932 ;; Get the data fields by splitting the lines.
5933 (setq fields (mapcar
5934 (lambda (l)
5935 (org-split-string l " *| *"))
5936 (delq nil (copy-sequence lines))))
5937 ;; How many fields in the longest line?
5938 (condition-case nil
5939 (setq maxfields (apply 'max (mapcar 'length fields)))
5940 (error
5941 (kill-region beg end)
5942 (org-table-create org-table-default-size)
5943 (error "Empty table - created default table")))
5944 ;; A list of empty strings to fill any short rows on output
5945 (setq emptystrings (make-list maxfields ""))
5946 ;; Check for special formatting.
5947 (setq i -1)
5948 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
5949 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
5950 ;; Check if there is an explicit width specified
5951 (when (and org-table-limit-column-width narrow)
5952 (setq c column fmax nil)
5953 (while c
5954 (setq e (pop c))
5955 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
5956 (setq fmax (string-to-number (match-string 1 e)) c nil)))
5957 ;; Find fields that are wider than fmax, and shorten them
5958 (when fmax
5959 (loop for xx in column do
5960 (when (and (stringp xx)
5961 (> (org-string-width xx) fmax))
5962 (org-add-props xx nil
5963 'help-echo
5964 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
5965 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
5966 (unless (> f1 1)
5967 (error "Cannot narrow field starting with wide link \"%s\""
5968 (match-string 0 xx)))
5969 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
5970 (add-text-properties (- f1 2) f1
5971 (list 'display org-narrow-column-arrow)
5972 xx)))))
5973 ;; Get the maximum width for each column
5974 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
5975 ;; Get the fraction of numbers, to decide about alignment of the column
5976 (setq cnt 0 frac 0.0)
5977 (loop for x in column do
5978 (if (equal x "")
5980 (setq frac ( / (+ (* frac cnt)
5981 (if (string-match org-table-number-regexp x) 1 0))
5982 (setq cnt (1+ cnt))))))
5983 (push (>= frac org-table-number-fraction) typenums))
5984 (setq lengths (nreverse lengths) typenums (nreverse typenums))
5986 ;; Store the alignment of this table, for later editing of single fields
5987 (setq org-table-last-alignment typenums
5988 org-table-last-column-widths lengths)
5990 ;; With invisible characters, `format' does not get the field width right
5991 ;; So we need to make these fields wide by hand.
5992 (when links
5993 (loop for i from 0 upto (1- maxfields) do
5994 (setq len (nth i lengths))
5995 (loop for j from 0 upto (1- (length fields)) do
5996 (setq c (nthcdr i (car (nthcdr j fields))))
5997 (if (and (stringp (car c))
5998 (string-match org-bracket-link-regexp (car c))
5999 (< (org-string-width (car c)) len))
6000 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
6002 ;; Compute the formats needed for output of the table
6003 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6004 (while (setq l (pop lengths))
6005 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6006 (setq rfmt (concat rfmt (format rfmt1 ty l))
6007 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6008 (setq rfmt (concat rfmt "\n")
6009 hfmt (concat (substring hfmt 0 -1) "|\n"))
6011 (setq new (mapconcat
6012 (lambda (l)
6013 (if l (apply 'format rfmt
6014 (append (pop fields) emptystrings))
6015 hfmt))
6016 lines ""))
6017 ;; Replace the old one
6018 (delete-region beg end)
6019 (move-marker end nil)
6020 (move-marker org-table-aligned-begin-marker (point))
6021 (insert new)
6022 (move-marker org-table-aligned-end-marker (point))
6023 (when (and orgtbl-mode (not (org-mode-p)))
6024 (goto-char org-table-aligned-begin-marker)
6025 (while (org-hide-wide-columns org-table-aligned-end-marker)))
6026 ;; Try to move to the old location
6027 (goto-line winstartline)
6028 (setq winstart (point-at-bol))
6029 (goto-line linepos)
6030 (set-window-start (selected-window) winstart 'noforce)
6031 (org-table-goto-column colpos)
6032 (setq org-table-may-need-update nil)
6035 (defun org-string-width (s)
6036 "Compute width of string, ignoring invisible characters.
6037 This ignores character with invisibility property `org-link', and also
6038 characters with property `org-cwidth', because these will become invisible
6039 upon the next fontification round."
6040 (let (b l)
6041 (when (or (eq t buffer-invisibility-spec)
6042 (assq 'org-link buffer-invisibility-spec))
6043 (while (setq b (text-property-any 0 (length s)
6044 'invisible 'org-link s))
6045 (setq s (concat (substring s 0 b)
6046 (substring s (or (next-single-property-change
6047 b 'invisible s) (length s)))))))
6048 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
6049 (setq s (concat (substring s 0 b)
6050 (substring s (or (next-single-property-change
6051 b 'org-cwidth s) (length s))))))
6052 (setq l (string-width s) b -1)
6053 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
6054 (setq l (- l (get-text-property b 'org-dwidth-n s))))
6057 (defun org-table-begin (&optional table-type)
6058 "Find the beginning of the table and return its position.
6059 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6060 (save-excursion
6061 (if (not (re-search-backward
6062 (if table-type org-table-any-border-regexp
6063 org-table-border-regexp)
6064 nil t))
6065 (progn (goto-char (point-min)) (point))
6066 (goto-char (match-beginning 0))
6067 (beginning-of-line 2)
6068 (point))))
6070 (defun org-table-end (&optional table-type)
6071 "Find the end of the table and return its position.
6072 With argument TABLE-TYPE, go to the end of a table.el-type table."
6073 (save-excursion
6074 (if (not (re-search-forward
6075 (if table-type org-table-any-border-regexp
6076 org-table-border-regexp)
6077 nil t))
6078 (goto-char (point-max))
6079 (goto-char (match-beginning 0)))
6080 (point-marker)))
6082 (defun org-table-justify-field-maybe (&optional new)
6083 "Justify the current field, text to left, number to right.
6084 Optional argument NEW may specify text to replace the current field content."
6085 (cond
6086 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6087 ((org-at-table-hline-p))
6088 ((and (not new)
6089 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6090 (current-buffer)))
6091 (< (point) org-table-aligned-begin-marker)
6092 (>= (point) org-table-aligned-end-marker)))
6093 ;; This is not the same table, force a full re-align
6094 (setq org-table-may-need-update t))
6095 (t ;; realign the current field, based on previous full realign
6096 (let* ((pos (point)) s
6097 (col (org-table-current-column))
6098 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
6099 l f n o e)
6100 (when (> col 0)
6101 (skip-chars-backward "^|\n")
6102 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6103 (progn
6104 (setq s (match-string 1)
6105 o (match-string 0)
6106 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6107 e (not (= (match-beginning 2) (match-end 2))))
6108 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6109 l (if e "|" (setq org-table-may-need-update t) ""))
6110 n (format f s))
6111 (if new
6112 (if (<= (length new) l) ;; FIXME: length -> str-width?
6113 (setq n (format f new))
6114 (setq n (concat new "|") org-table-may-need-update t)))
6115 (or (equal n o)
6116 (let (org-table-may-need-update)
6117 (replace-match n))))
6118 (setq org-table-may-need-update t))
6119 (goto-char pos))))))
6121 (defun org-table-next-field ()
6122 "Go to the next field in the current table, creating new lines as needed.
6123 Before doing so, re-align the table if necessary."
6124 (interactive)
6125 (org-table-maybe-eval-formula)
6126 (org-table-maybe-recalculate-line)
6127 (if (and org-table-automatic-realign
6128 org-table-may-need-update)
6129 (org-table-align))
6130 (let ((end (org-table-end)))
6131 (if (org-at-table-hline-p)
6132 (end-of-line 1))
6133 (condition-case nil
6134 (progn
6135 (re-search-forward "|" end)
6136 (if (looking-at "[ \t]*$")
6137 (re-search-forward "|" end))
6138 (if (and (looking-at "-")
6139 org-table-tab-jumps-over-hlines
6140 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
6141 (goto-char (match-beginning 1)))
6142 (if (looking-at "-")
6143 (progn
6144 (beginning-of-line 0)
6145 (org-table-insert-row 'below))
6146 (if (looking-at " ") (forward-char 1))))
6147 (error
6148 (org-table-insert-row 'below)))))
6150 (defun org-table-previous-field ()
6151 "Go to the previous field in the table.
6152 Before doing so, re-align the table if necessary."
6153 (interactive)
6154 (org-table-justify-field-maybe)
6155 (org-table-maybe-recalculate-line)
6156 (if (and org-table-automatic-realign
6157 org-table-may-need-update)
6158 (org-table-align))
6159 (if (org-at-table-hline-p)
6160 (end-of-line 1))
6161 (re-search-backward "|" (org-table-begin))
6162 (re-search-backward "|" (org-table-begin))
6163 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6164 (re-search-backward "|" (org-table-begin)))
6165 (if (looking-at "| ?")
6166 (goto-char (match-end 0))))
6168 (defun org-table-next-row ()
6169 "Go to the next row (same column) in the current table.
6170 Before doing so, re-align the table if necessary."
6171 (interactive)
6172 (org-table-maybe-eval-formula)
6173 (org-table-maybe-recalculate-line)
6174 (if (or (looking-at "[ \t]*$")
6175 (save-excursion (skip-chars-backward " \t") (bolp)))
6176 (newline)
6177 (if (and org-table-automatic-realign
6178 org-table-may-need-update)
6179 (org-table-align))
6180 (let ((col (org-table-current-column)))
6181 (beginning-of-line 2)
6182 (if (or (not (org-at-table-p))
6183 (org-at-table-hline-p))
6184 (progn
6185 (beginning-of-line 0)
6186 (org-table-insert-row 'below)))
6187 (org-table-goto-column col)
6188 (skip-chars-backward "^|\n\r")
6189 (if (looking-at " ") (forward-char 1)))))
6191 (defun org-table-copy-down (n)
6192 "Copy a field down in the current column.
6193 If the field at the cursor is empty, copy into it the content of the nearest
6194 non-empty field above. With argument N, use the Nth non-empty field.
6195 If the current field is not empty, it is copied down to the next row, and
6196 the cursor is moved with it. Therefore, repeating this command causes the
6197 column to be filled row-by-row.
6198 If the variable `org-table-copy-increment' is non-nil and the field is an
6199 integer, it will be incremented while copying."
6200 (interactive "p")
6201 (let* ((colpos (org-table-current-column))
6202 (field (org-table-get-field))
6203 (non-empty (string-match "[^ \t]" field))
6204 (beg (org-table-begin))
6205 txt)
6206 (org-table-check-inside-data-field)
6207 (if non-empty
6208 (progn
6209 (setq txt (org-trim field))
6210 (org-table-next-row)
6211 (org-table-blank-field))
6212 (save-excursion
6213 (setq txt
6214 (catch 'exit
6215 (while (progn (beginning-of-line 1)
6216 (re-search-backward org-table-dataline-regexp
6217 beg t))
6218 (org-table-goto-column colpos t)
6219 (if (and (looking-at
6220 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6221 (= (setq n (1- n)) 0))
6222 (throw 'exit (match-string 1))))))))
6223 (if txt
6224 (progn
6225 (if (and org-table-copy-increment
6226 (string-match "^[0-9]+$" txt))
6227 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6228 (insert txt)
6229 (org-table-maybe-recalculate-line)
6230 (org-table-align))
6231 (error "No non-empty field found"))))
6233 (defun org-table-check-inside-data-field ()
6234 "Is point inside a table data field?
6235 I.e. not on a hline or before the first or after the last column?
6236 This actually throws an error, so it aborts the current command."
6237 (if (or (not (org-at-table-p))
6238 (= (org-table-current-column) 0)
6239 (org-at-table-hline-p)
6240 (looking-at "[ \t]*$"))
6241 (error "Not in table data field")))
6243 (defvar org-table-clip nil
6244 "Clipboard for table regions.")
6246 (defun org-table-blank-field ()
6247 "Blank the current table field or active region."
6248 (interactive)
6249 (org-table-check-inside-data-field)
6250 (if (and (interactive-p) (org-region-active-p))
6251 (let (org-table-clip)
6252 (org-table-cut-region (region-beginning) (region-end)))
6253 (skip-chars-backward "^|")
6254 (backward-char 1)
6255 (if (looking-at "|[^|\n]+")
6256 (let* ((pos (match-beginning 0))
6257 (match (match-string 0))
6258 (len (org-string-width match)))
6259 (replace-match (concat "|" (make-string (1- len) ?\ )))
6260 (goto-char (+ 2 pos))
6261 (substring match 1)))))
6263 (defun org-table-get-field (&optional n replace)
6264 "Return the value of the field in column N of current row.
6265 N defaults to current field.
6266 If REPLACE is a string, replace field with this value. The return value
6267 is always the old value."
6268 (and n (org-table-goto-column n))
6269 (skip-chars-backward "^|\n")
6270 (backward-char 1)
6271 (if (looking-at "|[^|\r\n]*")
6272 (let* ((pos (match-beginning 0))
6273 (val (buffer-substring (1+ pos) (match-end 0))))
6274 (if replace
6275 (replace-match (concat "|" replace)))
6276 (goto-char (min (point-at-eol) (+ 2 pos)))
6277 val)
6278 (forward-char 1) ""))
6280 (defun org-table-field-info ()
6281 (interactive)
6282 (let ((current (org-table-get-field))
6283 (col (org-table-current-column))
6284 (line (org-table-current-line)))
6285 (message "Table data line %d, column %d" line col)))
6287 (defun org-table-current-column ()
6288 "Find out which column we are in.
6289 When called interactively, column is also displayed in echo area."
6290 (interactive)
6291 (if (interactive-p) (org-table-check-inside-data-field))
6292 (save-excursion
6293 (let ((cnt 0) (pos (point)))
6294 (beginning-of-line 1)
6295 (while (search-forward "|" pos t)
6296 (setq cnt (1+ cnt)))
6297 (if (interactive-p) (message "This is table column %d" cnt))
6298 cnt)))
6300 (defun org-table-current-line ()
6301 "Find out what table line we are in.
6302 Only datalins count for this."
6303 (interactive)
6304 (if (interactive-p) (org-table-check-inside-data-field))
6305 (save-excursion
6306 (let ((cnt 0) (pos (point)))
6307 (goto-char (org-table-begin))
6308 (while (< (point) pos)
6309 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
6310 (beginning-of-line 2))
6311 (if (interactive-p) (message "This is table line %d" cnt))
6312 cnt)))
6314 (defun org-table-goto-column (n &optional on-delim force)
6315 "Move the cursor to the Nth column in the current table line.
6316 With optional argument ON-DELIM, stop with point before the left delimiter
6317 of the field.
6318 If there are less than N fields, just go to after the last delimiter.
6319 However, when FORCE is non-nil, create new columns if necessary."
6320 (interactive "p")
6321 (let ((pos (point-at-eol)))
6322 (beginning-of-line 1)
6323 (when (> n 0)
6324 (while (and (> (setq n (1- n)) -1)
6325 (or (search-forward "|" pos t)
6326 (and force
6327 (progn (end-of-line 1)
6328 (skip-chars-backward "^|")
6329 (insert " | "))))))
6330 ; (backward-char 2) t)))))
6331 (when (and force (not (looking-at ".*|")))
6332 (save-excursion (end-of-line 1) (insert " | ")))
6333 (if on-delim
6334 (backward-char 1)
6335 (if (looking-at " ") (forward-char 1))))))
6337 (defun org-at-table-p (&optional table-type)
6338 "Return t if the cursor is inside an org-type table.
6339 If TABLE-TYPE is non-nil, also check for table.el-type tables."
6340 (if org-enable-table-editor
6341 (save-excursion
6342 (beginning-of-line 1)
6343 (looking-at (if table-type org-table-any-line-regexp
6344 org-table-line-regexp)))
6345 nil))
6347 (defun org-at-table.el-p ()
6348 "Return t if and only if we are at a table.el table."
6349 (and (org-at-table-p 'any)
6350 (save-excursion
6351 (goto-char (org-table-begin 'any))
6352 (looking-at org-table1-hline-regexp))))
6354 (defun org-table-recognize-table.el ()
6355 "If there is a table.el table nearby, recognize it and move into it."
6356 (if org-table-tab-recognizes-table.el
6357 (if (org-at-table.el-p)
6358 (progn
6359 (beginning-of-line 1)
6360 (if (looking-at org-table-dataline-regexp)
6362 (if (looking-at org-table1-hline-regexp)
6363 (progn
6364 (beginning-of-line 2)
6365 (if (looking-at org-table-any-border-regexp)
6366 (beginning-of-line -1)))))
6367 (if (re-search-forward "|" (org-table-end t) t)
6368 (progn
6369 (require 'table)
6370 (if (table--at-cell-p (point))
6372 (message "recognizing table.el table...")
6373 (table-recognize-table)
6374 (message "recognizing table.el table...done")))
6375 (error "This should not happen..."))
6377 nil)
6378 nil))
6380 (defun org-at-table-hline-p ()
6381 "Return t if the cursor is inside a hline in a table."
6382 (if org-enable-table-editor
6383 (save-excursion
6384 (beginning-of-line 1)
6385 (looking-at org-table-hline-regexp))
6386 nil))
6388 (defun org-table-insert-column ()
6389 "Insert a new column into the table."
6390 (interactive)
6391 (if (not (org-at-table-p))
6392 (error "Not at a table"))
6393 (org-table-find-dataline)
6394 (let* ((col (max 1 (org-table-current-column)))
6395 (beg (org-table-begin))
6396 (end (org-table-end))
6397 ;; Current cursor position
6398 (linepos (org-current-line))
6399 (colpos col))
6400 (goto-char beg)
6401 (while (< (point) end)
6402 (if (org-at-table-hline-p)
6404 (org-table-goto-column col t)
6405 (insert "| "))
6406 (beginning-of-line 2))
6407 (move-marker end nil)
6408 (goto-line linepos)
6409 (org-table-goto-column colpos)
6410 (org-table-align)
6411 (org-table-modify-formulas 'insert col)))
6413 (defun org-table-find-dataline ()
6414 "Find a dataline in the current table, which is needed for column commands."
6415 (if (and (org-at-table-p)
6416 (not (org-at-table-hline-p)))
6418 (let ((col (current-column))
6419 (end (org-table-end)))
6420 (move-to-column col)
6421 (while (and (< (point) end)
6422 (or (not (= (current-column) col))
6423 (org-at-table-hline-p)))
6424 (beginning-of-line 2)
6425 (move-to-column col))
6426 (if (and (org-at-table-p)
6427 (not (org-at-table-hline-p)))
6429 (error
6430 "Please position cursor in a data line for column operations")))))
6432 (defun org-table-delete-column ()
6433 "Delete a column from the table."
6434 (interactive)
6435 (if (not (org-at-table-p))
6436 (error "Not at a table"))
6437 (org-table-find-dataline)
6438 (org-table-check-inside-data-field)
6439 (let* ((col (org-table-current-column))
6440 (beg (org-table-begin))
6441 (end (org-table-end))
6442 ;; Current cursor position
6443 (linepos (org-current-line))
6444 (colpos col))
6445 (goto-char beg)
6446 (while (< (point) end)
6447 (if (org-at-table-hline-p)
6449 (org-table-goto-column col t)
6450 (and (looking-at "|[^|\n]+|")
6451 (replace-match "|")))
6452 (beginning-of-line 2))
6453 (move-marker end nil)
6454 (goto-line linepos)
6455 (org-table-goto-column colpos)
6456 (org-table-align)
6457 (org-table-modify-formulas 'remove col)))
6459 (defun org-table-move-column-right ()
6460 "Move column to the right."
6461 (interactive)
6462 (org-table-move-column nil))
6463 (defun org-table-move-column-left ()
6464 "Move column to the left."
6465 (interactive)
6466 (org-table-move-column 'left))
6468 (defun org-table-move-column (&optional left)
6469 "Move the current column to the right. With arg LEFT, move to the left."
6470 (interactive "P")
6471 (if (not (org-at-table-p))
6472 (error "Not at a table"))
6473 (org-table-find-dataline)
6474 (org-table-check-inside-data-field)
6475 (let* ((col (org-table-current-column))
6476 (col1 (if left (1- col) col))
6477 (beg (org-table-begin))
6478 (end (org-table-end))
6479 ;; Current cursor position
6480 (linepos (org-current-line))
6481 (colpos (if left (1- col) (1+ col))))
6482 (if (and left (= col 1))
6483 (error "Cannot move column further left"))
6484 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6485 (error "Cannot move column further right"))
6486 (goto-char beg)
6487 (while (< (point) end)
6488 (if (org-at-table-hline-p)
6490 (org-table-goto-column col1 t)
6491 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6492 (replace-match "|\\2|\\1|")))
6493 (beginning-of-line 2))
6494 (move-marker end nil)
6495 (goto-line linepos)
6496 (org-table-goto-column colpos)
6497 (org-table-align)
6498 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6500 (defun org-table-move-row-down ()
6501 "Move table row down."
6502 (interactive)
6503 (org-table-move-row nil))
6504 (defun org-table-move-row-up ()
6505 "Move table row up."
6506 (interactive)
6507 (org-table-move-row 'up))
6509 (defun org-table-move-row (&optional up)
6510 "Move the current table line down. With arg UP, move it up."
6511 (interactive "P")
6512 (let ((col (current-column))
6513 (pos (point))
6514 (tonew (if up 0 2))
6515 txt)
6516 (beginning-of-line tonew)
6517 (if (not (org-at-table-p))
6518 (progn
6519 (goto-char pos)
6520 (error "Cannot move row further")))
6521 (goto-char pos)
6522 (beginning-of-line 1)
6523 (setq pos (point))
6524 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6525 (delete-region (point) (1+ (point-at-eol)))
6526 (beginning-of-line tonew)
6527 (insert txt)
6528 (beginning-of-line 0)
6529 (move-to-column col)))
6531 (defun org-table-insert-row (&optional arg)
6532 "Insert a new row above the current line into the table.
6533 With prefix ARG, insert below the current line."
6534 (interactive "P")
6535 (if (not (org-at-table-p))
6536 (error "Not at a table"))
6537 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
6538 (new (org-table-clean-line line)))
6539 ;; Fix the first field if necessary
6540 (if (string-match "^[ \t]*| *[#$] *|" line)
6541 (setq new (replace-match (match-string 0 line) t t new)))
6542 (beginning-of-line (if arg 2 1))
6543 (let (org-table-may-need-update) (insert-before-markers new "\n"))
6544 (beginning-of-line 0)
6545 (re-search-forward "| ?" (point-at-eol) t)
6546 (and org-table-may-need-update (org-table-align))))
6548 (defun org-table-insert-hline (&optional arg)
6549 "Insert a horizontal-line below the current line into the table.
6550 With prefix ARG, insert above the current line."
6551 (interactive "P")
6552 (if (not (org-at-table-p))
6553 (error "Not at a table"))
6554 (let ((line (org-table-clean-line
6555 (buffer-substring (point-at-bol) (point-at-eol))))
6556 (col (current-column)))
6557 (while (string-match "|\\( +\\)|" line)
6558 (setq line (replace-match
6559 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
6560 ?-) "|") t t line)))
6561 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
6562 (beginning-of-line (if arg 1 2))
6563 (insert line "\n")
6564 (beginning-of-line (if arg 1 -1))
6565 (move-to-column col)))
6567 (defun org-table-clean-line (s)
6568 "Convert a table line S into a string with only \"|\" and space.
6569 In particular, this does handle wide and invisible characters."
6570 (if (string-match "^[ \t]*|-" s)
6571 ;; It's a hline, just map the characters
6572 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
6573 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
6574 (setq s (replace-match
6575 (concat "|" (make-string (org-string-width (match-string 1 s))
6576 ?\ ) "|")
6577 t t s)))
6580 (defun org-table-kill-row ()
6581 "Delete the current row or horizontal line from the table."
6582 (interactive)
6583 (if (not (org-at-table-p))
6584 (error "Not at a table"))
6585 (let ((col (current-column)))
6586 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6587 (if (not (org-at-table-p)) (beginning-of-line 0))
6588 (move-to-column col)))
6590 (defun org-table-sort-lines (with-case &optional sorting-type)
6591 "Sort table lines according to the column at point.
6593 The position of point indicates the column to be used for
6594 sorting, and the range of lines is the range between the nearest
6595 horizontal separator lines, or the entire table of no such lines
6596 exist. If point is before the first column, you will be prompted
6597 for the sorting column. If there is an active region, the mark
6598 specifies the first line and the sorting column, while point
6599 should be in the last line to be included into the sorting.
6601 The command then prompts for the sorting type which can be
6602 alphabetically, numerically, or by time (as given in a time stamp
6603 in the field). Sorting in reverse order is also possible.
6605 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
6607 If SORTING-TYPE is specified when this function is called from a Lisp
6608 program, no prompting will take place. SORTING-TYPE must be a character,
6609 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
6610 should be done in reverse order."
6611 (interactive "P")
6612 (let* ((thisline (org-current-line))
6613 (thiscol (org-table-current-column))
6614 beg end bcol ecol tend tbeg column lns pos)
6615 (when (equal thiscol 0)
6616 (if (interactive-p)
6617 (setq thiscol
6618 (string-to-number
6619 (read-string "Use column N for sorting: ")))
6620 (setq thiscol 1))
6621 (org-table-goto-column thiscol))
6622 (org-table-check-inside-data-field)
6623 (if (org-region-active-p)
6624 (progn
6625 (setq beg (region-beginning) end (region-end))
6626 (goto-char beg)
6627 (setq column (org-table-current-column)
6628 beg (point-at-bol))
6629 (goto-char end)
6630 (setq end (point-at-bol 2)))
6631 (setq column (org-table-current-column)
6632 pos (point)
6633 tbeg (org-table-begin)
6634 tend (org-table-end))
6635 (if (re-search-backward org-table-hline-regexp tbeg t)
6636 (setq beg (point-at-bol 2))
6637 (goto-char tbeg)
6638 (setq beg (point-at-bol 1)))
6639 (goto-char pos)
6640 (if (re-search-forward org-table-hline-regexp tend t)
6641 (setq beg (point-at-bol 0))
6642 (goto-char tend)
6643 (setq end (point-at-bol))))
6644 (setq beg (move-marker (make-marker) beg)
6645 end (move-marker (make-marker) end))
6646 (untabify beg end)
6647 (goto-char beg)
6648 (org-table-goto-column column)
6649 (skip-chars-backward "^|")
6650 (setq bcol (current-column))
6651 (org-table-goto-column (1+ column))
6652 (skip-chars-backward "^|")
6653 (setq ecol (1- (current-column)))
6654 (org-table-goto-column column)
6655 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
6656 (org-split-string (buffer-substring beg end) "\n")))
6657 (setq lns (org-do-sort lns "Table" with-case sorting-type))
6658 (delete-region beg end)
6659 (move-marker beg nil)
6660 (move-marker end nil)
6661 (insert (mapconcat 'cdr lns "\n") "\n")
6662 (goto-line thisline)
6663 (org-table-goto-column thiscol)
6664 (message "%d lines sorted, based on column %d" (length lns) column)))
6666 (defun org-table-cut-region (beg end)
6667 "Copy region in table to the clipboard and blank all relevant fields."
6668 (interactive "r")
6669 (org-table-copy-region beg end 'cut))
6671 (defun org-table-copy-region (beg end &optional cut)
6672 "Copy rectangular region in table to clipboard.
6673 A special clipboard is used which can only be accessed
6674 with `org-table-paste-rectangle'."
6675 (interactive "rP")
6676 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6677 region cols
6678 (rpl (if cut " " nil)))
6679 (goto-char beg)
6680 (org-table-check-inside-data-field)
6681 (setq l01 (org-current-line)
6682 c01 (org-table-current-column))
6683 (goto-char end)
6684 (org-table-check-inside-data-field)
6685 (setq l02 (org-current-line)
6686 c02 (org-table-current-column))
6687 (setq l1 (min l01 l02) l2 (max l01 l02)
6688 c1 (min c01 c02) c2 (max c01 c02))
6689 (catch 'exit
6690 (while t
6691 (catch 'nextline
6692 (if (> l1 l2) (throw 'exit t))
6693 (goto-line l1)
6694 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6695 (setq cols nil ic1 c1 ic2 c2)
6696 (while (< ic1 (1+ ic2))
6697 (push (org-table-get-field ic1 rpl) cols)
6698 (setq ic1 (1+ ic1)))
6699 (push (nreverse cols) region)
6700 (setq l1 (1+ l1)))))
6701 (setq org-table-clip (nreverse region))
6702 (if cut (org-table-align))
6703 org-table-clip))
6705 (defun org-table-paste-rectangle ()
6706 "Paste a rectangular region into a table.
6707 The upper right corner ends up in the current field. All involved fields
6708 will be overwritten. If the rectangle does not fit into the present table,
6709 the table is enlarged as needed. The process ignores horizontal separator
6710 lines."
6711 (interactive)
6712 (unless (and org-table-clip (listp org-table-clip))
6713 (error "First cut/copy a region to paste!"))
6714 (org-table-check-inside-data-field)
6715 (let* ((clip org-table-clip)
6716 (line (org-current-line))
6717 (col (org-table-current-column))
6718 (org-enable-table-editor t)
6719 (org-table-automatic-realign nil)
6720 c cols field)
6721 (while (setq cols (pop clip))
6722 (while (org-at-table-hline-p) (beginning-of-line 2))
6723 (if (not (org-at-table-p))
6724 (progn (end-of-line 0) (org-table-next-field)))
6725 (setq c col)
6726 (while (setq field (pop cols))
6727 (org-table-goto-column c nil 'force)
6728 (org-table-get-field nil field)
6729 (setq c (1+ c)))
6730 (beginning-of-line 2))
6731 (goto-line line)
6732 (org-table-goto-column col)
6733 (org-table-align)))
6735 (defun org-table-convert ()
6736 "Convert from `org-mode' table to table.el and back.
6737 Obviously, this only works within limits. When an Org-mode table is
6738 converted to table.el, all horizontal separator lines get lost, because
6739 table.el uses these as cell boundaries and has no notion of horizontal lines.
6740 A table.el table can be converted to an Org-mode table only if it does not
6741 do row or column spanning. Multiline cells will become multiple cells.
6742 Beware, Org-mode does not test if the table can be successfully converted - it
6743 blindly applies a recipe that works for simple tables."
6744 (interactive)
6745 (require 'table)
6746 (if (org-at-table.el-p)
6747 ;; convert to Org-mode table
6748 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6749 (end (move-marker (make-marker) (org-table-end t))))
6750 (table-unrecognize-region beg end)
6751 (goto-char beg)
6752 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6753 (replace-match ""))
6754 (goto-char beg))
6755 (if (org-at-table-p)
6756 ;; convert to table.el table
6757 (let ((beg (move-marker (make-marker) (org-table-begin)))
6758 (end (move-marker (make-marker) (org-table-end))))
6759 ;; first, get rid of all horizontal lines
6760 (goto-char beg)
6761 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6762 (replace-match ""))
6763 ;; insert a hline before first
6764 (goto-char beg)
6765 (org-table-insert-hline 'above)
6766 (beginning-of-line -1)
6767 ;; insert a hline after each line
6768 (while (progn (beginning-of-line 3) (< (point) end))
6769 (org-table-insert-hline))
6770 (goto-char beg)
6771 (setq end (move-marker end (org-table-end)))
6772 ;; replace "+" at beginning and ending of hlines
6773 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6774 (replace-match "\\1+-"))
6775 (goto-char beg)
6776 (while (re-search-forward "-|[ \t]*$" end t)
6777 (replace-match "-+"))
6778 (goto-char beg)))))
6780 (defun org-table-wrap-region (arg)
6781 "Wrap several fields in a column like a paragraph.
6782 This is useful if you'd like to spread the contents of a field over several
6783 lines, in order to keep the table compact.
6785 If there is an active region, and both point and mark are in the same column,
6786 the text in the column is wrapped to minimum width for the given number of
6787 lines. Generally, this makes the table more compact. A prefix ARG may be
6788 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6789 formats the selected text to two lines. If the region was longer than two
6790 lines, the remaining lines remain empty. A negative prefix argument reduces
6791 the current number of lines by that amount. The wrapped text is pasted back
6792 into the table. If you formatted it to more lines than it was before, fields
6793 further down in the table get overwritten - so you might need to make space in
6794 the table first.
6796 If there is no region, the current field is split at the cursor position and
6797 the text fragment to the right of the cursor is prepended to the field one
6798 line down.
6800 If there is no region, but you specify a prefix ARG, the current field gets
6801 blank, and the content is appended to the field above."
6802 (interactive "P")
6803 (org-table-check-inside-data-field)
6804 (if (org-region-active-p)
6805 ;; There is a region: fill as a paragraph
6806 (let ((beg (region-beginning))
6807 nlines)
6808 (org-table-cut-region (region-beginning) (region-end))
6809 (if (> (length (car org-table-clip)) 1)
6810 (error "Region must be limited to single column"))
6811 (setq nlines (if arg
6812 (if (< arg 1)
6813 (+ (length org-table-clip) arg)
6814 arg)
6815 (length org-table-clip)))
6816 (setq org-table-clip
6817 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6818 nil nlines)))
6819 (goto-char beg)
6820 (org-table-paste-rectangle))
6821 ;; No region, split the current field at point
6822 (if arg
6823 ;; combine with field above
6824 (let ((s (org-table-blank-field))
6825 (col (org-table-current-column)))
6826 (beginning-of-line 0)
6827 (while (org-at-table-hline-p) (beginning-of-line 0))
6828 (org-table-goto-column col)
6829 (skip-chars-forward "^|")
6830 (skip-chars-backward " ")
6831 (insert " " (org-trim s))
6832 (org-table-align))
6833 ;; split field
6834 (when (looking-at "\\([^|]+\\)+|")
6835 (let ((s (match-string 1)))
6836 (replace-match " |")
6837 (goto-char (match-beginning 0))
6838 (org-table-next-row)
6839 (insert (org-trim s) " ")
6840 (org-table-align))))))
6842 (defvar org-field-marker nil)
6844 (defun org-table-edit-field (arg)
6845 "Edit table field in a different window.
6846 This is mainly useful for fields that contain hidden parts.
6847 When called with a \\[universal-argument] prefix, just make the full field visible so that
6848 it can be edited in place."
6849 (interactive "P")
6850 (if arg
6851 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
6852 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
6853 (remove-text-properties b e '(org-cwidth t invisible t
6854 display t intangible t))
6855 (if (and (boundp 'font-lock-mode) font-lock-mode)
6856 (font-lock-fontify-block)))
6857 (let ((pos (move-marker (make-marker) (point)))
6858 (field (org-table-get-field))
6859 (cw (current-window-configuration))
6861 (switch-to-buffer-other-window "*Org tmp*")
6862 (erase-buffer)
6863 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
6864 (org-mode)
6865 (goto-char (setq p (point-max)))
6866 (insert (org-trim field))
6867 (remove-text-properties p (point-max)
6868 '(invisible t org-cwidth t display t
6869 intangible t))
6870 (goto-char p)
6871 (org-set-local 'org-finish-function
6872 'org-table-finish-edit-field)
6873 (org-set-local 'org-window-configuration cw)
6874 (org-set-local 'org-field-marker pos)
6875 (message "Edit and finish with C-c C-c"))))
6877 (defun org-table-finish-edit-field ()
6878 "Finish editing a table data field.
6879 Remove all newline characters, insert the result into the table, realign
6880 the table and kill the editing buffer."
6881 (let ((pos org-field-marker)
6882 (cw org-window-configuration)
6883 (cb (current-buffer))
6884 text)
6885 (goto-char (point-min))
6886 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
6887 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
6888 (replace-match " "))
6889 (setq text (org-trim (buffer-string)))
6890 (set-window-configuration cw)
6891 (kill-buffer cb)
6892 (select-window (get-buffer-window (marker-buffer pos)))
6893 (goto-char pos)
6894 (move-marker pos nil)
6895 (org-table-check-inside-data-field)
6896 (org-table-get-field nil text)
6897 (org-table-align)
6898 (message "New field value inserted")))
6900 (defun org-trim (s)
6901 "Remove whitespace at beginning and end of string."
6902 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6903 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6906 (defun org-wrap (string &optional width lines)
6907 "Wrap string to either a number of lines, or a width in characters.
6908 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6909 that costs. If there is a word longer than WIDTH, the text is actually
6910 wrapped to the length of that word.
6911 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6912 many lines, whatever width that takes.
6913 The return value is a list of lines, without newlines at the end."
6914 (let* ((words (org-split-string string "[ \t\n]+"))
6915 (maxword (apply 'max (mapcar 'org-string-width words)))
6916 w ll)
6917 (cond (width
6918 (org-do-wrap words (max maxword width)))
6919 (lines
6920 (setq w maxword)
6921 (setq ll (org-do-wrap words maxword))
6922 (if (<= (length ll) lines)
6924 (setq ll words)
6925 (while (> (length ll) lines)
6926 (setq w (1+ w))
6927 (setq ll (org-do-wrap words w)))
6928 ll))
6929 (t (error "Cannot wrap this")))))
6932 (defun org-do-wrap (words width)
6933 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6934 (let (lines line)
6935 (while words
6936 (setq line (pop words))
6937 (while (and words (< (+ (length line) (length (car words))) width))
6938 (setq line (concat line " " (pop words))))
6939 (setq lines (push line lines)))
6940 (nreverse lines)))
6942 (defun org-split-string (string &optional separators)
6943 "Splits STRING into substrings at SEPARATORS.
6944 No empty strings are returned if there are matches at the beginning
6945 and end of string."
6946 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6947 (start 0)
6948 notfirst
6949 (list nil))
6950 (while (and (string-match rexp string
6951 (if (and notfirst
6952 (= start (match-beginning 0))
6953 (< start (length string)))
6954 (1+ start) start))
6955 (< (match-beginning 0) (length string)))
6956 (setq notfirst t)
6957 (or (eq (match-beginning 0) 0)
6958 (and (eq (match-beginning 0) (match-end 0))
6959 (eq (match-beginning 0) start))
6960 (setq list
6961 (cons (substring string start (match-beginning 0))
6962 list)))
6963 (setq start (match-end 0)))
6964 (or (eq start (length string))
6965 (setq list
6966 (cons (substring string start)
6967 list)))
6968 (nreverse list)))
6970 (defun org-table-map-tables (function)
6971 "Apply FUNCTION to the start of all tables in the buffer."
6972 (save-excursion
6973 (save-restriction
6974 (widen)
6975 (goto-char (point-min))
6976 (while (re-search-forward org-table-any-line-regexp nil t)
6977 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6978 (beginning-of-line 1)
6979 (if (looking-at org-table-line-regexp)
6980 (save-excursion (funcall function)))
6981 (re-search-forward org-table-any-border-regexp nil 1))))
6982 (message "Mapping tables: done"))
6984 (defvar org-timecnt) ; dynamically scoped parameter
6986 (defun org-table-sum (&optional beg end nlast)
6987 "Sum numbers in region of current table column.
6988 The result will be displayed in the echo area, and will be available
6989 as kill to be inserted with \\[yank].
6991 If there is an active region, it is interpreted as a rectangle and all
6992 numbers in that rectangle will be summed. If there is no active
6993 region and point is located in a table column, sum all numbers in that
6994 column.
6996 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6997 numbers are assumed to be times as well (in decimal hours) and the
6998 numbers are added as such.
7000 If NLAST is a number, only the NLAST fields will actually be summed."
7001 (interactive)
7002 (save-excursion
7003 (let (col (org-timecnt 0) diff h m s org-table-clip)
7004 (cond
7005 ((and beg end)) ; beg and end given explicitly
7006 ((org-region-active-p)
7007 (setq beg (region-beginning) end (region-end)))
7009 (setq col (org-table-current-column))
7010 (goto-char (org-table-begin))
7011 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7012 (error "No table data"))
7013 (org-table-goto-column col)
7014 ;not needed? (skip-chars-backward "^|")
7015 (setq beg (point))
7016 (goto-char (org-table-end))
7017 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7018 (error "No table data"))
7019 (org-table-goto-column col)
7020 ;not needed? (skip-chars-forward "^|")
7021 (setq end (point))))
7022 (let* ((items (apply 'append (org-table-copy-region beg end)))
7023 (items1 (cond ((not nlast) items)
7024 ((>= nlast (length items)) items)
7025 (t (setq items (reverse items))
7026 (setcdr (nthcdr (1- nlast) items) nil)
7027 (nreverse items))))
7028 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7029 items1)))
7030 (res (apply '+ numbers))
7031 (sres (if (= org-timecnt 0)
7032 (format "%g" res)
7033 (setq diff (* 3600 res)
7034 h (floor (/ diff 3600)) diff (mod diff 3600)
7035 m (floor (/ diff 60)) diff (mod diff 60)
7036 s diff)
7037 (format "%d:%02d:%02d" h m s))))
7038 (kill-new sres)
7039 (if (interactive-p)
7040 (message "%s"
7041 (substitute-command-keys
7042 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7043 (length numbers) sres))))
7044 sres))))
7046 (defun org-table-get-number-for-summing (s)
7047 (let (n)
7048 (if (string-match "^ *|? *" s)
7049 (setq s (replace-match "" nil nil s)))
7050 (if (string-match " *|? *$" s)
7051 (setq s (replace-match "" nil nil s)))
7052 (setq n (string-to-number s))
7053 (cond
7054 ((and (string-match "0" s)
7055 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7056 ((string-match "\\`[ \t]+\\'" s) nil)
7057 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7058 (let ((h (string-to-number (or (match-string 1 s) "0")))
7059 (m (string-to-number (or (match-string 2 s) "0")))
7060 (s (string-to-number (or (match-string 4 s) "0"))))
7061 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
7062 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7063 ((equal n 0) nil)
7064 (t n))))
7066 (defun org-table-get-vertical-vector (desc &optional tbeg col)
7067 "Get a calc vector from a column, accorting to descriptor DESC.
7068 Optional arguments TBEG and COL can give the beginning of the table and
7069 the current column, to avoid unnecessary parsing."
7070 (save-excursion
7071 (or tbeg (setq tbeg (org-table-begin)))
7072 (or col (setq col (org-table-current-column)))
7073 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7074 (cond
7075 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7076 (setq n1 (- (match-end 1) (match-beginning 1)))
7077 (if (match-beginning 3)
7078 (setq n2 (- (match-end 2) (match-beginning 3))))
7079 (setq n (if n2 (max n1 n2) n1))
7080 (setq n1 (if n2 (min n1 n2)))
7081 (setq nn n)
7082 (while (and (> nn 0)
7083 (re-search-backward org-table-hline-regexp tbeg t))
7084 (push (org-current-line) hline-list)
7085 (setq nn (1- nn)))
7086 (setq hline-list (nreverse hline-list))
7087 (goto-line (nth (1- n) hline-list))
7088 (when (re-search-forward org-table-dataline-regexp)
7089 (org-table-goto-column col)
7090 (setq beg (point)))
7091 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7092 (when (re-search-backward org-table-dataline-regexp)
7093 (org-table-goto-column col)
7094 (setq end (point)))
7095 (setq l (apply 'append (org-table-copy-region beg end)))
7096 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7097 (if (equal x "") "0" x))
7098 l ",") "]"))
7099 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7100 (setq n1 (string-to-number (match-string 1 desc))
7101 n2 (string-to-number (match-string 2 desc)))
7102 (beginning-of-line 1)
7103 (save-excursion
7104 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7105 (org-table-goto-column col)
7106 (setq beg (point))))
7107 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7108 (org-table-goto-column col)
7109 (setq end (point)))
7110 (setq l (apply 'append (org-table-copy-region beg end)))
7111 (concat "[" (mapconcat
7112 (lambda (x) (setq x (org-trim x))
7113 (if (equal x "") "0" x))
7114 l ",") "]"))
7115 ((string-match "\\([0-9]+\\)" desc)
7116 (beginning-of-line 1)
7117 (when (re-search-backward org-table-dataline-regexp tbeg t
7118 (string-to-number (match-string 0 desc)))
7119 (org-table-goto-column col)
7120 (org-trim (org-table-get-field))))))))
7122 (defvar org-table-formula-history nil)
7124 (defvar org-table-column-names nil
7125 "Alist with column names, derived from the `!' line.")
7126 (defvar org-table-column-name-regexp nil
7127 "Regular expression matching the current column names.")
7128 (defvar org-table-local-parameters nil
7129 "Alist with parameter names, derived from the `$' line.")
7130 (defvar org-table-named-field-locations nil
7131 "Alist with locations of named fields.")
7133 (defun org-table-current-field-formula ()
7134 "Return the formula active for the current field.
7135 Assumes that specials are in place."
7136 (let* ((name (car (rassoc (list (org-current-line)
7137 (org-table-current-column))
7138 org-table-named-field-locations)))
7139 (scol (if name name
7140 (int-to-string (org-table-current-column))))
7141 (stored-list (org-table-get-stored-formulas))
7142 (stored (cdr (assoc scol stored-list))))
7143 (if stored (concat (if name ":=" "=") stored))))
7145 (defun org-table-get-formula (&optional equation named)
7146 "Read a formula from the minibuffer, offer stored formula as default.
7147 When NAMED is non-nil, look for a named equation.
7148 When JUST-RETURN is non-nil, return equation without prompting."
7149 (let* ((name (car (rassoc (list (org-current-line)
7150 (org-table-current-column))
7151 org-table-named-field-locations)))
7152 (scol (if named
7153 (if name name
7154 (error "Not in a named field"))
7155 (int-to-string (org-table-current-column))))
7156 (dummy (and name (not named)
7157 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7158 (error "Abort")))
7159 (org-table-may-need-update nil)
7160 (stored-list (org-table-get-stored-formulas))
7161 (stored (cdr (assoc scol stored-list)))
7162 (eq (cond
7163 ((and stored equation (string-match "^ *=? *$" equation))
7164 stored)
7165 ((stringp equation)
7166 equation)
7167 (t (read-string
7168 (format "%s formula $%s=" (if named "Field" "Column") scol)
7169 (or stored "") 'org-table-formula-history
7170 ;stored
7171 ))))
7172 mustsave)
7173 (when (not (string-match "\\S-" eq))
7174 ;; remove formula
7175 (setq stored-list (delq (assoc scol stored-list) stored-list))
7176 (org-table-store-formulas stored-list)
7177 (error "Formula removed"))
7178 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7179 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7180 (if (and name (not named))
7181 ;; We set the column equation, delete the named one.
7182 (setq stored-list (delq (assoc name stored-list) stored-list)
7183 mustsave t))
7184 (if stored
7185 (setcdr (assoc scol stored-list) eq)
7186 (setq stored-list (cons (cons scol eq) stored-list)))
7187 (if (or mustsave (not (equal stored eq)))
7188 (org-table-store-formulas stored-list))
7189 eq))
7191 (defun org-table-store-formulas (alist)
7192 "Store the list of formulas below the current table."
7193 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7194 (save-excursion
7195 (goto-char (org-table-end))
7196 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7197 (delete-region (point) (match-end 0)))
7198 (insert "#+TBLFM: "
7199 (mapconcat (lambda (x)
7200 (concat "$" (car x) "=" (cdr x)))
7201 alist "::")
7202 "\n")))
7204 (defun org-table-get-stored-formulas ()
7205 "Return an alist with the stored formulas directly after current table."
7206 (interactive)
7207 (let (scol eq eq-alist strings string seen)
7208 (save-excursion
7209 (goto-char (org-table-end))
7210 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7211 (setq strings (org-split-string (match-string 2) " *:: *"))
7212 (while (setq string (pop strings))
7213 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7214 (setq scol (match-string 1 string)
7215 eq (match-string 2 string)
7216 eq-alist (cons (cons scol eq) eq-alist))
7217 (if (member scol seen)
7218 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7219 (push scol seen))))))
7220 (nreverse eq-alist)))
7222 (defun org-table-modify-formulas (action &rest columns)
7223 "Modify the formulas stored below the current table.
7224 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7225 expected, for the other actions only a single column number is needed."
7226 (let ((list (org-table-get-stored-formulas))
7227 (nmax (length (org-split-string
7228 (buffer-substring (point-at-bol) (point-at-eol))
7229 "|")))
7230 col col1 col2 scol si sc1 sc2)
7231 (cond
7232 ((null list)) ; No action needed if there are no stored formulas
7233 ((eq action 'remove)
7234 (setq col (car columns)
7235 scol (int-to-string col))
7236 (org-table-replace-in-formulas list scol "INVALID")
7237 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
7238 (loop for i from (1+ col) upto nmax by 1 do
7239 (setq si (int-to-string i))
7240 (org-table-replace-in-formulas list si (int-to-string (1- i)))
7241 (if (assoc si list) (setcar (assoc si list)
7242 (int-to-string (1- i))))))
7243 ((eq action 'insert)
7244 (setq col (car columns))
7245 (loop for i from nmax downto col by 1 do
7246 (setq si (int-to-string i))
7247 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
7248 (if (assoc si list) (setcar (assoc si list)
7249 (int-to-string (1+ i))))))
7250 ((eq action 'swap)
7251 (setq col1 (car columns) col2 (nth 1 columns)
7252 sc1 (int-to-string col1) sc2 (int-to-string col2))
7253 ;; Hopefully, ZqZtZ will never be a name in a table
7254 (org-table-replace-in-formulas list sc1 "ZqZtZ")
7255 (org-table-replace-in-formulas list sc2 sc1)
7256 (org-table-replace-in-formulas list "ZqZtZ" sc2)
7257 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
7258 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
7259 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
7260 (t (error "Invalid action in `org-table-modify-formulas'")))
7261 (if list (org-table-store-formulas list))))
7263 (defun org-table-replace-in-formulas (list s1 s2)
7264 (let (elt re s)
7265 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7266 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7267 re (concat (regexp-quote s1) "\\>"))
7268 (while (setq elt (pop list))
7269 (setq s (cdr elt))
7270 (while (string-match re s)
7271 (setq s (replace-match s2 t t s)))
7272 (setcdr elt s))))
7274 (defun org-table-get-specials ()
7275 "Get the column names and local parameters for this table."
7276 (save-excursion
7277 (let ((beg (org-table-begin)) (end (org-table-end))
7278 names name fields fields1 field cnt c v line col)
7279 (setq org-table-column-names nil
7280 org-table-local-parameters nil
7281 org-table-named-field-locations nil)
7282 (goto-char beg)
7283 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7284 (setq names (org-split-string (match-string 1) " *| *")
7285 cnt 1)
7286 (while (setq name (pop names))
7287 (setq cnt (1+ cnt))
7288 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7289 (push (cons name (int-to-string cnt)) org-table-column-names))))
7290 (setq org-table-column-names (nreverse org-table-column-names))
7291 (setq org-table-column-name-regexp
7292 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7293 (goto-char beg)
7294 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7295 (setq fields (org-split-string (match-string 1) " *| *"))
7296 (while (setq field (pop fields))
7297 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7298 (push (cons (match-string 1 field) (match-string 2 field))
7299 org-table-local-parameters))))
7300 (goto-char beg)
7301 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7302 (setq c (match-string 1)
7303 fields (org-split-string (match-string 2) " *| *"))
7304 (save-excursion
7305 (beginning-of-line (if (equal c "_") 2 0))
7306 (setq line (org-current-line) col 1)
7307 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7308 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7309 (while (and fields1 (setq field (pop fields)))
7310 (setq v (pop fields1) col (1+ col))
7311 (when (and (stringp field) (stringp v)
7312 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7313 (push (cons field v) org-table-local-parameters)
7314 (push (list field line col) org-table-named-field-locations)))))))
7316 (defun org-this-word ()
7317 ;; Get the current word
7318 (save-excursion
7319 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7320 (end (progn (skip-chars-forward "^ \t\n") (point))))
7321 (buffer-substring-no-properties beg end))))
7323 (defun org-table-maybe-eval-formula ()
7324 "Check if the current field starts with \"=\" or \":=\".
7325 If yes, store the formula and apply it."
7326 ;; We already know we are in a table. Get field will only return a formula
7327 ;; when appropriate. It might return a separator line, but no problem.
7328 (when org-table-formula-evaluate-inline
7329 (let* ((field (org-trim (or (org-table-get-field) "")))
7330 named eq)
7331 (when (string-match "^:?=\\(.*\\)" field)
7332 (setq named (equal (string-to-char field) ?:)
7333 eq (match-string 1 field))
7334 (if (or (fboundp 'calc-eval)
7335 (equal (substring eq 0 (min 2 (length eq))) "'("))
7336 (org-table-eval-formula (if named '(4) nil) eq)
7337 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
7339 (defvar org-recalc-commands nil
7340 "List of commands triggering the recalculation of a line.
7341 Will be filled automatically during use.")
7343 (defvar org-recalc-marks
7344 '((" " . "Unmarked: no special line, no automatic recalculation")
7345 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7346 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7347 ("!" . "Column name definition line. Reference in formula as $name.")
7348 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7349 ("_" . "Names for values in row below this one.")
7350 ("^" . "Names for values in row above this one.")))
7352 (defun org-table-rotate-recalc-marks (&optional newchar)
7353 "Rotate the recalculation mark in the first column.
7354 If in any row, the first field is not consistent with a mark,
7355 insert a new column for the markers.
7356 When there is an active region, change all the lines in the region,
7357 after prompting for the marking character.
7358 After each change, a message will be displayed indicating the meaning
7359 of the new mark."
7360 (interactive)
7361 (unless (org-at-table-p) (error "Not at a table"))
7362 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7363 (beg (org-table-begin))
7364 (end (org-table-end))
7365 (l (org-current-line))
7366 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7367 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7368 (have-col
7369 (save-excursion
7370 (goto-char beg)
7371 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7372 (col (org-table-current-column))
7373 (forcenew (car (assoc newchar org-recalc-marks)))
7374 epos new)
7375 (when l1
7376 (message "Change region to what mark? Type # * ! $ or SPC: ")
7377 (setq newchar (char-to-string (read-char-exclusive))
7378 forcenew (car (assoc newchar org-recalc-marks))))
7379 (if (and newchar (not forcenew))
7380 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7381 newchar))
7382 (if l1 (goto-line l1))
7383 (save-excursion
7384 (beginning-of-line 1)
7385 (unless (looking-at org-table-dataline-regexp)
7386 (error "Not at a table data line")))
7387 (unless have-col
7388 (org-table-goto-column 1)
7389 (org-table-insert-column)
7390 (org-table-goto-column (1+ col)))
7391 (setq epos (point-at-eol))
7392 (save-excursion
7393 (beginning-of-line 1)
7394 (org-table-get-field
7395 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7396 (concat " "
7397 (setq new (or forcenew
7398 (cadr (member (match-string 1) marks))))
7399 " ")
7400 " # ")))
7401 (if (and l1 l2)
7402 (progn
7403 (goto-line l1)
7404 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7405 (and (looking-at org-table-dataline-regexp)
7406 (org-table-get-field 1 (concat " " new " "))))
7407 (goto-line l1)))
7408 (if (not (= epos (point-at-eol))) (org-table-align))
7409 (goto-line l)
7410 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7412 (defun org-table-maybe-recalculate-line ()
7413 "Recompute the current line if marked for it, and if we haven't just done it."
7414 (interactive)
7415 (and org-table-allow-automatic-line-recalculation
7416 (not (and (memq last-command org-recalc-commands)
7417 (equal org-last-recalc-line (org-current-line))))
7418 (save-excursion (beginning-of-line 1)
7419 (looking-at org-table-auto-recalculate-regexp))
7420 ;; (fboundp 'calc-eval) ;; FIXME: correct to remove this?
7421 (org-table-recalculate) t))
7423 (defvar org-table-formula-debug nil
7424 "Non-nil means, debug table formulas.
7425 When nil, simply write \"#ERROR\" in corrupted fields.")
7427 (defvar modes)
7428 (defsubst org-set-calc-mode (var &optional value)
7429 (if (stringp var)
7430 (setq var (assoc var '(("D" calc-angle-mode deg)
7431 ("R" calc-angle-mode rad)
7432 ("F" calc-prefer-frac t)
7433 ("S" calc-symbolic-mode t)))
7434 value (nth 2 var) var (nth 1 var)))
7435 (if (memq var modes)
7436 (setcar (cdr (memq var modes)) value)
7437 (cons var (cons value modes)))
7438 modes)
7440 (defun org-table-eval-formula (&optional arg equation
7441 suppress-align suppress-const
7442 suppress-store)
7443 "Replace the table field value at the cursor by the result of a calculation.
7445 This function makes use of Dave Gillespie's Calc package, in my view the
7446 most exciting program ever written for GNU Emacs. So you need to have Calc
7447 installed in order to use this function.
7449 In a table, this command replaces the value in the current field with the
7450 result of a formula. It also installs the formula as the \"current\" column
7451 formula, by storing it in a special line below the table. When called
7452 with a `C-u' prefix, the current field must ba a named field, and the
7453 formula is installed as valid in only this specific field.
7455 When called with two `C-u' prefixes, insert the active equation
7456 for the field back into the current field, so that it can be
7457 edited there. This is useful in order to use \\[org-show-variable] to check
7458 the referenced fields.
7460 When called, the command first prompts for a formula, which is read in
7461 the minibuffer. Previously entered formulas are available through the
7462 history list, and the last used formula is offered as a default.
7463 These stored formulas are adapted correctly when moving, inserting, or
7464 deleting columns with the corresponding commands.
7466 The formula can be any algebraic expression understood by the Calc package.
7467 For details, see the Org-mode manual.
7469 This function can also be called from Lisp programs and offers
7470 additional arguments: EQUATION can be the formula to apply. If this
7471 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7472 used to speed-up recursive calls by by-passing unnecessary aligns.
7473 SUPPRESS-CONST suppresses the interpretation of constants in the
7474 formula, assuming that this has been done already outside the function.
7475 SUPPRESS-STORE means the formula should not be stored, either because
7476 it is already stored, or because it is a modified equation that should
7477 not overwrite the stored one."
7478 (interactive "P")
7479 (org-table-check-inside-data-field)
7480 (org-table-get-specials)
7481 (if (equal arg '(16))
7482 (let ((eq (org-table-current-field-formula)))
7483 (or eq (error "No equation active for current field"))
7484 (org-table-get-field nil eq)
7485 (org-table-align)
7486 (setq org-table-may-need-update t))
7487 (let* (fields
7488 (ndown (if (integerp arg) arg 1))
7489 (org-table-automatic-realign nil)
7490 (case-fold-search nil)
7491 (down (> ndown 1))
7492 (formula (if (and equation suppress-store)
7493 equation
7494 (org-table-get-formula equation (equal arg '(4)))))
7495 (n0 (org-table-current-column))
7496 (modes (copy-sequence org-calc-default-modes))
7497 n form fmt x ev orig c lispp)
7498 ;; Parse the format string. Since we have a lot of modes, this is
7499 ;; a lot of work. However, I think calc still uses most of the time.
7500 (if (string-match ";" formula)
7501 (let ((tmp (org-split-string formula ";")))
7502 (setq formula (car tmp)
7503 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7504 (nth 1 tmp)))
7505 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
7506 (setq c (string-to-char (match-string 1 fmt))
7507 n (string-to-number (match-string 2 fmt)))
7508 (if (= c ?p)
7509 (setq modes (org-set-calc-mode 'calc-internal-prec n))
7510 (setq modes (org-set-calc-mode
7511 'calc-float-format
7512 (list (cdr (assoc c '((?n . float) (?f . fix)
7513 (?s . sci) (?e . eng))))
7514 n))))
7515 (setq fmt (replace-match "" t t fmt)))
7516 (while (string-match "[DRFS]" fmt)
7517 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7518 (setq fmt (replace-match "" t t fmt)))
7519 (unless (string-match "\\S-" fmt)
7520 (setq fmt nil))))
7521 (if (and (not suppress-const) org-table-formula-use-constants)
7522 (setq formula (org-table-formula-substitute-names formula)))
7523 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7524 (while (> ndown 0)
7525 (setq fields (org-split-string
7526 (buffer-substring
7527 (point-at-bol) (point-at-eol)) " *| *"))
7528 (if org-table-formula-numbers-only
7529 (setq fields (mapcar
7530 (lambda (x) (number-to-string (string-to-number x)))
7531 fields)))
7532 (setq ndown (1- ndown))
7533 (setq form (copy-sequence formula)
7534 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
7535 ;; Insert the references to fields in same row
7536 (while (string-match "\\$\\([0-9]+\\)?" form)
7537 (setq n (if (match-beginning 1)
7538 (string-to-number (match-string 1 form))
7540 x (nth (1- n) fields))
7541 (unless x (error "Invalid field specifier \"%s\""
7542 (match-string 0 form)))
7543 (if (equal x "") (setq x "0"))
7544 (setq form (replace-match
7545 (if lispp x (concat "(" x ")"))
7546 t t form)))
7547 ;; Insert ranges in current column
7548 (while (string-match "\\&[-I0-9]+" form)
7549 (setq form (replace-match
7550 (save-match-data
7551 (org-table-get-vertical-vector (match-string 0 form)
7552 nil n0))
7553 t t form)))
7554 (if lispp
7555 (setq ev (eval (eval (read form)))
7556 ev (if (numberp ev) (number-to-string ev) ev))
7557 (or (fboundp 'calc-eval)
7558 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
7559 (setq ev (calc-eval (cons form modes)
7560 (if org-table-formula-numbers-only 'num))))
7562 (when org-table-formula-debug
7563 (with-output-to-temp-buffer "*Help*"
7564 (princ (format "Substitution history of formula
7565 Orig: %s
7566 $xyz-> %s
7567 $1-> %s\n" orig formula form))
7568 (if (listp ev)
7569 (princ (format " %s^\nError: %s"
7570 (make-string (car ev) ?\-) (nth 1 ev)))
7571 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7572 ev (or fmt "NONE")
7573 (if fmt (format fmt (string-to-number ev)) ev)))))
7574 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7575 (unless (and (interactive-p) (not ndown))
7576 (unless (let (inhibit-redisplay)
7577 (y-or-n-p "Debugging Formula. Continue to next? "))
7578 (org-table-align)
7579 (error "Abort"))
7580 (delete-window (get-buffer-window "*Help*"))
7581 (message "")))
7582 (if (listp ev) (setq fmt nil ev "#ERROR"))
7583 (org-table-justify-field-maybe
7584 (if fmt (format fmt (string-to-number ev)) ev))
7585 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7586 (call-interactively 'org-return)
7587 (setq ndown 0)))
7588 (and down (org-table-maybe-recalculate-line))
7589 (or suppress-align (and org-table-may-need-update
7590 (org-table-align))))))
7592 (defun org-table-recalculate (&optional all noalign)
7593 "Recalculate the current table line by applying all stored formulas.
7594 With prefix arg ALL, do this for all lines in the table."
7595 (interactive "P")
7596 (or (memq this-command org-recalc-commands)
7597 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7598 (unless (org-at-table-p) (error "Not at a table"))
7599 (org-table-get-specials)
7600 (let* ((eqlist (sort (org-table-get-stored-formulas)
7601 (lambda (a b) (string< (car a) (car b)))))
7602 (inhibit-redisplay t)
7603 (line-re org-table-dataline-regexp)
7604 (thisline (org-current-line))
7605 (thiscol (org-table-current-column))
7606 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7607 ;; Insert constants in all formulas
7608 (setq eqlist
7609 (mapcar (lambda (x)
7610 (setcdr x (org-table-formula-substitute-names (cdr x)))
7612 eqlist))
7613 ;; Split the equation list
7614 (while (setq eq (pop eqlist))
7615 (if (<= (string-to-char (car eq)) ?9)
7616 (push eq eqlnum)
7617 (push eq eqlname)))
7618 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7619 (if all
7620 (progn
7621 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7622 (goto-char (setq beg (org-table-begin)))
7623 (if (re-search-forward org-table-calculate-mark-regexp end t)
7624 ;; This is a table with marked lines, only compute selected lines
7625 (setq line-re org-table-recalculate-regexp)
7626 ;; Move forward to the first non-header line
7627 (if (and (re-search-forward org-table-dataline-regexp end t)
7628 (re-search-forward org-table-hline-regexp end t)
7629 (re-search-forward org-table-dataline-regexp end t))
7630 (setq beg (match-beginning 0))
7631 nil))) ;; just leave beg where it is
7632 (setq beg (point-at-bol)
7633 end (move-marker (make-marker) (1+ (point-at-eol)))))
7634 (goto-char beg)
7635 (and all (message "Re-applying formulas to full table..."))
7636 (while (re-search-forward line-re end t)
7637 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7638 ;; Unprotected line, recalculate
7639 (and all (message "Re-applying formulas to full table...(line %d)"
7640 (setq cnt (1+ cnt))))
7641 (setq org-last-recalc-line (org-current-line))
7642 (setq eql eqlnum)
7643 (while (setq entry (pop eql))
7644 (goto-line org-last-recalc-line)
7645 (org-table-goto-column (string-to-number (car entry)) nil 'force)
7646 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7647 (goto-line thisline)
7648 (org-table-goto-column thiscol)
7649 (or noalign (and org-table-may-need-update (org-table-align))
7650 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7651 ;; Now do the names fields
7652 (while (setq eq (pop eqlname))
7653 (setq name (car eq)
7654 a (assoc name org-table-named-field-locations))
7655 (when a
7656 (message "Re-applying formula to named field: %s" name)
7657 (goto-line (nth 1 a))
7658 (org-table-goto-column (nth 2 a))
7659 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
7660 ;; back to initial position
7661 (goto-line thisline)
7662 (org-table-goto-column thiscol)
7663 (or noalign (and org-table-may-need-update (org-table-align))
7664 (and all (message "Re-applying formulas...done")))))
7666 (defun org-table-formula-substitute-names (f)
7667 "Replace $const with values in string F."
7668 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7669 ;; First, check for column names
7670 (while (setq start (string-match org-table-column-name-regexp f start))
7671 (setq start (1+ start))
7672 (setq a (assoc (match-string 1 f) org-table-column-names))
7673 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7674 ;; Expand ranges to vectors
7675 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7676 (setq n1 (string-to-number (match-string 1 f))
7677 n2 (string-to-number (match-string 2 f))
7678 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7679 s (concat "[($" (number-to-string (1- nn1)) ")"))
7680 (loop for i from nn1 upto nn2 do
7681 (setq s (concat s ",($" (int-to-string i) ")")))
7682 (setq s (concat s "]"))
7683 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7684 (setq f (replace-match s t t f)))
7685 ;; Parameters and constants
7686 (setq start 0)
7687 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7688 (setq start (1+ start))
7689 (if (setq a (save-match-data
7690 (org-table-get-constant (match-string 1 f))))
7691 (setq f (replace-match (concat "(" a ")") t t f))))
7692 (if org-table-formula-debug
7693 (put-text-property 0 (length f) :orig-formula f1 f))
7696 (defun org-table-get-constant (const)
7697 "Find the value for a parameter or constant in a formula.
7698 Parameters get priority."
7699 (or (cdr (assoc const org-table-local-parameters))
7700 (cdr (assoc const org-table-formula-constants))
7701 (and (fboundp 'constants-get) (constants-get const))
7702 "#UNDEFINED_NAME"))
7704 (defvar org-edit-formulas-map (make-sparse-keymap))
7705 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7706 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7707 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
7709 (defvar org-pos)
7711 (defun org-table-edit-formulas ()
7712 "Edit the formulas of the current table in a separate buffer."
7713 (interactive)
7714 (unless (org-at-table-p) (error "Not at a table"))
7715 (org-table-get-specials)
7716 (let ((eql (org-table-get-stored-formulas))
7717 (pos (move-marker (make-marker) (point)))
7718 (wc (current-window-configuration))
7719 entry loc s)
7720 (switch-to-buffer-other-window "*Edit Formulas*")
7721 (erase-buffer)
7722 (fundamental-mode)
7723 (org-set-local 'org-pos pos)
7724 (org-set-local 'org-window-configuration wc)
7725 (use-local-map org-edit-formulas-map)
7726 (setq s "# Edit formulas and finish with `C-c C-c'.
7727 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
7728 # Use `C-c ?' to get information about $name at point.
7729 # To cancel editing, press `C-c C-q'.\n")
7730 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7731 (insert s)
7732 (while (setq entry (pop eql))
7733 (when (setq loc (assoc (car entry) org-table-named-field-locations))
7734 (setq s (format "# Named formula, referring to column %d in line %d\n"
7735 (nth 2 loc) (nth 1 loc)))
7736 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7737 (insert s))
7738 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
7739 (remove-text-properties 0 (length s) '(face nil) s)
7740 (insert s))
7741 (goto-char (point-min))
7742 (message "Edit formulas and finish with `C-c C-c'.")))
7744 ;; FIXME: make this work in fields, directly highlighting the referenced fields
7745 (defun org-show-variable ()
7746 "Show the location/value of the $ expression at point."
7747 (interactive)
7748 (let (var (pos org-pos) (win (selected-window)) e)
7749 (save-excursion
7750 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
7751 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
7752 (setq var (match-string 1))
7753 (error "No variable at point")))
7754 (cond
7755 ((setq e (assoc var org-table-named-field-locations))
7756 (switch-to-buffer-other-window (marker-buffer pos))
7757 (goto-line (nth 1 e))
7758 (org-table-goto-column (nth 2 e))
7759 (select-window win)
7760 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
7761 ((setq e (assoc var org-table-column-names))
7762 (switch-to-buffer-other-window (marker-buffer pos))
7763 (goto-char pos)
7764 (goto-char (org-table-begin))
7765 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
7766 (org-table-end) t)
7767 (progn
7768 (goto-char (match-beginning 1))
7769 (message "Named column (column %s)" (cdr e)))
7770 (error "Column name not found"))
7771 (select-window win))
7772 ((string-match "^[0-9]$" var)
7773 ;; column number
7774 (switch-to-buffer-other-window (marker-buffer pos))
7775 (goto-char pos)
7776 (goto-char (org-table-begin))
7777 (recenter 1)
7778 (if (re-search-forward org-table-dataline-regexp
7779 (org-table-end) t)
7780 (progn
7781 (goto-char (match-beginning 0))
7782 (org-table-goto-column (string-to-number var))
7783 (message "Column %s" var))
7784 (error "Column name not found"))
7785 (select-window win))
7786 ((setq e (assoc var org-table-local-parameters))
7787 (switch-to-buffer-other-window (marker-buffer pos))
7788 (goto-char pos)
7789 (goto-char (org-table-begin))
7790 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
7791 (progn
7792 (goto-char (match-beginning 1))
7793 (message "Local parameter."))
7794 (error "Parameter not found"))
7795 (select-window win))
7797 (cond
7798 ((setq e (assoc var org-table-formula-constants))
7799 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
7800 ((setq e (and (fboundp 'constants-get) (constants-get var)))
7801 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
7802 (t (error "Undefined name $%s" var)))))))
7804 (defun org-finish-edit-formulas (&optional arg)
7805 "Parse the buffer for formula definitions and install them.
7806 With prefix ARG, apply the new formulas to the table."
7807 (interactive "P")
7808 (let ((pos org-pos) eql)
7809 (goto-char (point-min))
7810 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
7811 (push (cons (match-string 1) (match-string 2)) eql))
7812 (set-window-configuration org-window-configuration)
7813 (select-window (get-buffer-window (marker-buffer pos)))
7814 (goto-char pos)
7815 (unless (org-at-table-p)
7816 (error "Lost table position - cannot install formulae"))
7817 (org-table-store-formulas eql)
7818 (move-marker pos nil)
7819 (kill-buffer "*Edit Formulas*")
7820 (if arg
7821 (org-table-recalculate 'all)
7822 (message "New formulas installed - press C-u C-c C-c to apply."))))
7824 (defun org-abort-edit-formulas ()
7825 "Abort editing formulas, without installing the changes."
7826 (interactive)
7827 (let ((pos org-pos))
7828 (set-window-configuration org-window-configuration)
7829 (select-window (get-buffer-window (marker-buffer pos)))
7830 (goto-char pos)
7831 (message "Formula editing aborted without installing changes")))
7833 ;;; The orgtbl minor mode
7835 ;; Define a minor mode which can be used in other modes in order to
7836 ;; integrate the org-mode table editor.
7838 ;; This is really a hack, because the org-mode table editor uses several
7839 ;; keys which normally belong to the major mode, for example the TAB and
7840 ;; RET keys. Here is how it works: The minor mode defines all the keys
7841 ;; necessary to operate the table editor, but wraps the commands into a
7842 ;; function which tests if the cursor is currently inside a table. If that
7843 ;; is the case, the table editor command is executed. However, when any of
7844 ;; those keys is used outside a table, the function uses `key-binding' to
7845 ;; look up if the key has an associated command in another currently active
7846 ;; keymap (minor modes, major mode, global), and executes that command.
7847 ;; There might be problems if any of the keys used by the table editor is
7848 ;; otherwise used as a prefix key.
7850 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7851 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7852 ;; addresses this by checking explicitly for both bindings.
7854 ;; The optimized version (see variable `orgtbl-optimized') takes over
7855 ;; all keys which are bound to `self-insert-command' in the *global map*.
7856 ;; Some modes bind other commands to simple characters, for example
7857 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7858 ;; active, this binding is ignored inside tables and replaced with a
7859 ;; modified self-insert.
7861 (defvar orgtbl-mode nil
7862 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7863 table editor in arbitrary modes.")
7864 (make-variable-buffer-local 'orgtbl-mode)
7866 (defvar orgtbl-mode-map (make-keymap)
7867 "Keymap for `orgtbl-mode'.")
7869 ;;;###autoload
7870 (defun turn-on-orgtbl ()
7871 "Unconditionally turn on `orgtbl-mode'."
7872 (orgtbl-mode 1))
7874 (defvar org-old-auto-fill-inhibit-regexp nil
7875 "Local variable used by `orgtbl-mode'")
7877 ;;;###autoload
7878 (defun orgtbl-mode (&optional arg)
7879 "The `org-mode' table editor as a minor mode for use in other modes."
7880 (interactive)
7881 (if (org-mode-p)
7882 ;; Exit without error, in case some hook functions calls this
7883 ;; by accident in org-mode.
7884 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7885 (setq orgtbl-mode
7886 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7887 (if orgtbl-mode
7888 (progn
7889 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7890 ;; Make sure we are first in minor-mode-map-alist
7891 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7892 (and c (setq minor-mode-map-alist
7893 (cons c (delq c minor-mode-map-alist)))))
7894 (org-set-local (quote org-table-may-need-update) t)
7895 (org-add-hook 'before-change-functions 'org-before-change-function
7896 nil 'local)
7897 (org-set-local 'org-old-auto-fill-inhibit-regexp
7898 auto-fill-inhibit-regexp)
7899 (org-set-local 'auto-fill-inhibit-regexp
7900 (if auto-fill-inhibit-regexp
7901 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7902 "[ \t]*|"))
7903 (org-add-to-invisibility-spec '(org-cwidth))
7904 (easy-menu-add orgtbl-mode-menu)
7905 (run-hooks 'orgtbl-mode-hook))
7906 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7907 (org-cleanup-narrow-column-properties)
7908 (org-remove-from-invisibility-spec '(org-cwidth))
7909 (remove-hook 'before-change-functions 'org-before-change-function t)
7910 (easy-menu-remove orgtbl-mode-menu)
7911 (force-mode-line-update 'all))))
7913 (defun org-cleanup-narrow-column-properties ()
7914 "Remove all properties related to narrow-column invisibility."
7915 (let ((s 1))
7916 (while (setq s (text-property-any s (point-max)
7917 'display org-narrow-column-arrow))
7918 (remove-text-properties s (1+ s) '(display t)))
7919 (setq s 1)
7920 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
7921 (remove-text-properties s (1+ s) '(org-cwidth t)))
7922 (setq s 1)
7923 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
7924 (remove-text-properties s (1+ s) '(invisible t)))))
7926 ;; Install it as a minor mode.
7927 (put 'orgtbl-mode :included t)
7928 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7929 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7931 (defun orgtbl-make-binding (fun n &rest keys)
7932 "Create a function for binding in the table minor mode.
7933 FUN is the command to call inside a table. N is used to create a unique
7934 command name. KEYS are keys that should be checked in for a command
7935 to execute outside of tables."
7936 (eval
7937 (list 'defun
7938 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7939 '(arg)
7940 (concat "In tables, run `" (symbol-name fun) "'.\n"
7941 "Outside of tables, run the binding of `"
7942 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7943 "'.")
7944 '(interactive "p")
7945 (list 'if
7946 '(org-at-table-p)
7947 (list 'call-interactively (list 'quote fun))
7948 (list 'let '(orgtbl-mode)
7949 (list 'call-interactively
7950 (append '(or)
7951 (mapcar (lambda (k)
7952 (list 'key-binding k))
7953 keys)
7954 '('orgtbl-error))))))))
7956 (defun orgtbl-error ()
7957 "Error when there is no default binding for a table key."
7958 (interactive)
7959 (error "This key is has no function outside tables"))
7961 (defun orgtbl-setup ()
7962 "Setup orgtbl keymaps."
7963 (let ((nfunc 0)
7964 (bindings
7965 (list
7966 '([(meta shift left)] org-table-delete-column)
7967 '([(meta left)] org-table-move-column-left)
7968 '([(meta right)] org-table-move-column-right)
7969 '([(meta shift right)] org-table-insert-column)
7970 '([(meta shift up)] org-table-kill-row)
7971 '([(meta shift down)] org-table-insert-row)
7972 '([(meta up)] org-table-move-row-up)
7973 '([(meta down)] org-table-move-row-down)
7974 '("\C-c\C-w" org-table-cut-region)
7975 '("\C-c\M-w" org-table-copy-region)
7976 '("\C-c\C-y" org-table-paste-rectangle)
7977 '("\C-c-" org-table-insert-hline)
7978 ; '([(shift tab)] org-table-previous-field)
7979 '("\C-m" org-table-next-row)
7980 (list (org-key 'S-return) 'org-table-copy-down)
7981 '([(meta return)] org-table-wrap-region)
7982 '("\C-c\C-q" org-table-wrap-region)
7983 '("\C-c?" org-table-field-info)
7984 '("\C-c " org-table-blank-field)
7985 '("\C-c+" org-table-sum)
7986 '("\C-c=" org-table-eval-formula)
7987 '("\C-c'" org-table-edit-formulas)
7988 '("\C-c`" org-table-edit-field)
7989 '("\C-c*" org-table-recalculate)
7990 '("\C-c|" org-table-create-or-convert-from-region)
7991 '("\C-c^" org-table-sort-lines)
7992 '([(control ?#)] org-table-rotate-recalc-marks)))
7993 elt key fun cmd)
7994 (while (setq elt (pop bindings))
7995 (setq nfunc (1+ nfunc))
7996 (setq key (car elt)
7997 fun (nth 1 elt)
7998 cmd (orgtbl-make-binding fun nfunc key))
7999 (define-key orgtbl-mode-map key cmd))
8000 ;; Special treatment needed for TAB and RET
8001 (define-key orgtbl-mode-map [(return)]
8002 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
8003 (define-key orgtbl-mode-map "\C-m"
8004 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
8005 (define-key orgtbl-mode-map [(tab)]
8006 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
8007 (define-key orgtbl-mode-map "\C-i"
8008 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
8009 (define-key orgtbl-mode-map "\C-i"
8010 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
8011 (define-key orgtbl-mode-map "\C-c\C-c"
8012 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
8013 (when orgtbl-optimized
8014 ;; If the user wants maximum table support, we need to hijack
8015 ;; some standard editing functions
8016 (org-remap orgtbl-mode-map
8017 'self-insert-command 'orgtbl-self-insert-command
8018 'delete-char 'org-delete-char
8019 'delete-backward-char 'org-delete-backward-char)
8020 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
8021 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
8022 '("OrgTbl"
8023 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
8024 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
8025 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
8026 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
8027 "--"
8028 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
8029 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
8030 ["Copy Field from Above"
8031 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
8032 "--"
8033 ("Column"
8034 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
8035 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
8036 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
8037 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
8038 "--"
8039 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :active (org-at-table-p) :selected org-table-limit-column-width :style toggle])
8040 ("Row"
8041 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
8042 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
8043 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
8044 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
8045 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
8046 "--"
8047 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
8048 ("Rectangle"
8049 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
8050 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
8051 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
8052 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
8053 "--"
8054 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
8055 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
8056 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
8057 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
8058 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
8059 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
8060 ["Sum Column/Rectangle" org-table-sum
8061 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
8062 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
8063 ["Debug Formulas"
8064 (setq org-table-formula-debug (not org-table-formula-debug))
8065 :style toggle :selected org-table-formula-debug]
8069 (defun orgtbl-tab (arg)
8070 "Justification and field motion for `orgtbl-mode'."
8071 (interactive "P")
8072 (if arg (org-table-edit-field t)
8073 (org-table-justify-field-maybe)
8074 (org-table-next-field)))
8076 (defun orgtbl-ret ()
8077 "Justification and field motion for `orgtbl-mode'."
8078 (interactive)
8079 (org-table-justify-field-maybe)
8080 (org-table-next-row))
8082 (defun orgtbl-self-insert-command (N)
8083 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
8084 If the cursor is in a table looking at whitespace, the whitespace is
8085 overwritten, and the table is not marked as requiring realignment."
8086 (interactive "p")
8087 (if (and (org-at-table-p)
8089 (and org-table-auto-blank-field
8090 (member last-command
8091 '(orgtbl-hijacker-command-100
8092 orgtbl-hijacker-command-101
8093 orgtbl-hijacker-command-102
8094 orgtbl-hijacker-command-103
8095 orgtbl-hijacker-command-104
8096 orgtbl-hijacker-command-105))
8097 (org-table-blank-field))
8099 (eq N 1)
8100 (looking-at "[^|\n]* +|"))
8101 (let (org-table-may-need-update)
8102 (goto-char (1- (match-end 0)))
8103 (delete-backward-char 1)
8104 (goto-char (match-beginning 0))
8105 (self-insert-command N))
8106 (setq org-table-may-need-update t)
8107 (let (orgtbl-mode)
8108 (call-interactively (key-binding (vector last-input-event))))))
8110 (defun org-force-self-insert (N)
8111 "Needed to enforce self-insert under remapping."
8112 (interactive "p")
8113 (self-insert-command N))
8115 ;;;; Link Stuff
8117 ;;; Link abbreviations
8119 (defun org-link-expand-abbrev (link)
8120 "Apply replacements as defined in `org-link-abbrev-alist."
8121 (if (string-match "^\\([a-zA-Z]+\\)\\(::\\(.*\\)\\)?$" link)
8122 (let* ((key (match-string 1 link))
8123 (as (or (assoc key org-link-abbrev-alist-local)
8124 (assoc key org-link-abbrev-alist)))
8125 (tag (and (match-end 2) (match-string 3 link)))
8126 rpl)
8127 (if (not as)
8128 link
8129 (setq rpl (cdr as))
8130 (cond
8131 ((symbolp rpl) (funcall rpl tag))
8132 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8133 (t (concat rpl tag)))))
8134 link))
8136 ;;; Storing and inserting links
8138 (defvar org-insert-link-history nil
8139 "Minibuffer history for links inserted with `org-insert-link'.")
8141 (defvar org-stored-links nil
8142 "Contains the links stored with `org-store-link'.")
8144 ;;;###autoload
8145 (defun org-store-link (arg)
8146 "\\<org-mode-map>Store an org-link to the current location.
8147 This link can later be inserted into an org-buffer with
8148 \\[org-insert-link].
8149 For some link types, a prefix arg is interpreted:
8150 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
8151 For file links, arg negates `org-context-in-file-links'."
8152 (interactive "P")
8153 (let (link cpltxt desc description search txt (pos (point)))
8154 (cond
8156 ((eq major-mode 'bbdb-mode)
8157 (setq cpltxt (concat
8158 "bbdb:"
8159 (or (bbdb-record-name (bbdb-current-record))
8160 (bbdb-record-company (bbdb-current-record))))
8161 link (org-make-link cpltxt)))
8163 ((eq major-mode 'Info-mode)
8164 (setq link (org-make-link "info:"
8165 (file-name-nondirectory Info-current-file)
8166 ":" Info-current-node))
8167 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
8168 ":" Info-current-node)))
8170 ((eq major-mode 'calendar-mode)
8171 (let ((cd (calendar-cursor-to-date)))
8172 (setq link
8173 (format-time-string
8174 (car org-time-stamp-formats)
8175 (apply 'encode-time
8176 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8177 nil nil nil))))))
8179 ((or (eq major-mode 'vm-summary-mode)
8180 (eq major-mode 'vm-presentation-mode))
8181 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
8182 (vm-follow-summary-cursor)
8183 (save-excursion
8184 (vm-select-folder-buffer)
8185 (let* ((message (car vm-message-pointer))
8186 (folder buffer-file-name)
8187 (subject (vm-su-subject message))
8188 (author (vm-su-full-name message))
8189 (message-id (vm-su-message-id message)))
8190 (setq message-id (org-remove-angle-brackets message-id))
8191 (setq folder (abbreviate-file-name folder))
8192 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
8193 folder)
8194 (setq folder (replace-match "" t t folder)))
8195 (setq cpltxt (concat author " on: " subject))
8196 (setq link (org-make-link "vm:" folder "#" message-id)))))
8198 ((eq major-mode 'wl-summary-mode)
8199 (let* ((msgnum (wl-summary-message-number))
8200 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
8201 msgnum 'message-id))
8202 (wl-message-entity
8203 (if (fboundp 'elmo-message-entity)
8204 (elmo-message-entity
8205 wl-summary-buffer-elmo-folder msgnum)
8206 (elmo-msgdb-overview-get-entity
8207 msgnum (wl-summary-buffer-msgdb))))
8208 ;; FIXME: How to get author and subject in wl???
8209 (author (wl-summary-line-from)) ; ?
8210 (subject "???"))
8211 (setq message-id (org-remove-angle-brackets message-id))
8212 (setq cpltxt (concat author " on: " subject))
8213 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
8214 "#" message-id))))
8216 ((or (equal major-mode 'mh-folder-mode)
8217 (equal major-mode 'mh-show-mode))
8218 (let ((from-header (org-mhe-get-header "From:"))
8219 (to-header (org-mhe-get-header "To:"))
8220 (subject (org-mhe-get-header "Subject:")))
8221 (setq cpltxt (concat from-header " on: " subject))
8222 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
8223 (org-remove-angle-brackets
8224 (org-mhe-get-header "Message-Id:"))))))
8226 ((eq major-mode 'rmail-mode)
8227 (save-excursion
8228 (save-restriction
8229 (rmail-narrow-to-non-pruned-header)
8230 (let ((folder buffer-file-name)
8231 (message-id (mail-fetch-field "message-id"))
8232 (author (mail-fetch-field "from"))
8233 (subject (mail-fetch-field "subject")))
8234 (setq message-id (org-remove-angle-brackets message-id))
8235 (setq cpltxt (concat author " on: " subject))
8236 (setq link (org-make-link "rmail:" folder "#" message-id))))))
8238 ((eq major-mode 'gnus-group-mode)
8239 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
8240 (gnus-group-group-name)) ; version
8241 ((fboundp 'gnus-group-name)
8242 (gnus-group-name))
8243 (t "???"))))
8244 (unless group (error "Not on a group"))
8245 (setq cpltxt (concat
8246 (if (org-xor arg org-usenet-links-prefer-google)
8247 "http://groups.google.com/groups?group="
8248 "gnus:")
8249 group)
8250 link (org-make-link cpltxt))))
8252 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
8253 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
8254 (let* ((group gnus-newsgroup-name)
8255 (article (gnus-summary-article-number))
8256 (header (gnus-summary-article-header article))
8257 (author (mail-header-from header))
8258 (message-id (mail-header-id header))
8259 (date (mail-header-date header))
8260 (subject (gnus-summary-subject-string)))
8261 (setq cpltxt (concat author " on: " subject))
8262 (if (org-xor arg org-usenet-links-prefer-google)
8263 (setq link
8264 (concat
8265 cpltxt "\n "
8266 (format "http://groups.google.com/groups?as_umsgid=%s"
8267 (org-fixup-message-id-for-http message-id))))
8268 (setq link (org-make-link "gnus:" group
8269 "#" (number-to-string article))))))
8271 ((eq major-mode 'w3-mode)
8272 (setq cpltxt (url-view-url t)
8273 link (org-make-link cpltxt)))
8274 ((eq major-mode 'w3m-mode)
8275 (setq cpltxt (or w3m-current-title w3m-current-url)
8276 link (org-make-link w3m-current-url)))
8278 ((setq search (run-hook-with-args-until-success
8279 'org-create-file-search-functions))
8280 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8281 "::" search))
8282 (setq cpltxt (or description link)))
8284 ((eq major-mode 'image-mode)
8285 (setq cpltxt (concat "file:"
8286 (abbreviate-file-name buffer-file-name))
8287 link (org-make-link cpltxt)))
8289 ((eq major-mode 'dired-mode)
8290 ;; link to the file in the current line
8291 (setq cpltxt (concat "file:"
8292 (abbreviate-file-name
8293 (expand-file-name
8294 (dired-get-filename nil t))))
8295 link (org-make-link cpltxt)))
8297 ((and buffer-file-name (org-mode-p))
8298 ;; Just link to current headline
8299 (setq cpltxt (concat "file:"
8300 (abbreviate-file-name buffer-file-name)))
8301 ;; Add a context search string
8302 (when (org-xor org-context-in-file-links arg)
8303 ;; Check if we are on a target
8304 (if (save-excursion
8305 (skip-chars-forward "^>\n\r")
8306 (and (re-search-backward "<<" nil t)
8307 (looking-at "<<\\(.*?\\)>>")
8308 (<= (match-beginning 0) pos)
8309 (>= (match-end 0) pos)))
8310 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8311 (setq txt (cond
8312 ((org-on-heading-p) nil)
8313 ((org-region-active-p)
8314 (buffer-substring (region-beginning) (region-end)))
8315 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8316 (when (or (null txt) (string-match "\\S-" txt))
8317 (setq cpltxt
8318 (concat cpltxt "::"
8319 (if org-file-link-context-use-camel-case
8320 (org-make-org-heading-camel txt)
8321 (org-make-org-heading-search-string txt)))
8322 desc "NONE"))))
8323 (if (string-match "::\\'" cpltxt)
8324 (setq cpltxt (substring cpltxt 0 -2)))
8325 (setq link (org-make-link cpltxt)))
8327 (buffer-file-name
8328 ;; Just link to this file here.
8329 (setq cpltxt (concat "file:"
8330 (abbreviate-file-name buffer-file-name)))
8331 ;; Add a context string
8332 (when (org-xor org-context-in-file-links arg)
8333 (setq txt (if (org-region-active-p)
8334 (buffer-substring (region-beginning) (region-end))
8335 (buffer-substring (point-at-bol) (point-at-eol))))
8336 ;; Only use search option if there is some text.
8337 (when (string-match "\\S-" txt)
8338 (setq cpltxt
8339 (concat cpltxt "::"
8340 (if org-file-link-context-use-camel-case
8341 (org-make-org-heading-camel txt)
8342 (org-make-org-heading-search-string txt)))
8343 desc "NONE")))
8344 (setq link (org-make-link cpltxt)))
8346 ((interactive-p)
8347 (error "Cannot link to a buffer which is not visiting a file"))
8349 (t (setq link nil)))
8351 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8352 (setq link (or link cpltxt)
8353 desc (or desc cpltxt))
8354 (if (equal desc "NONE") (setq desc nil))
8356 (if (and (interactive-p) link)
8357 (progn
8358 (setq org-stored-links
8359 (cons (list cpltxt link desc) org-stored-links))
8360 (message "Stored: %s" (or cpltxt link)))
8361 (org-make-link-string link desc))))
8363 (defun org-make-org-heading-search-string (&optional string heading)
8364 "Make search string for STRING or current headline."
8365 (interactive)
8366 (let ((s (or string (org-get-heading))))
8367 (unless (and string (not heading))
8368 ;; We are using a headline, clean up garbage in there.
8369 (if (string-match org-todo-regexp s)
8370 (setq s (replace-match "" t t s)))
8371 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8372 (setq s (replace-match "" t t s)))
8373 (setq s (org-trim s))
8374 (if (string-match (concat "^\\(" org-quote-string "\\|"
8375 org-comment-string "\\)") s)
8376 (setq s (replace-match "" t t s)))
8377 (while (string-match org-ts-regexp s)
8378 (setq s (replace-match "" t t s))))
8379 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8380 (setq s (replace-match " " t t s)))
8381 (or string (setq s (concat "*" s))) ; Add * for headlines
8382 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8384 (defun org-make-org-heading-camel (&optional string heading)
8385 "Make a CamelCase string for STRING or the current headline."
8386 (interactive)
8387 (let ((s (or string (org-get-heading))))
8388 (unless (and string (not heading))
8389 ;; We are using a headline, clean up garbage in there.
8390 (if (string-match org-todo-regexp s)
8391 (setq s (replace-match "" t t s)))
8392 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8393 (setq s (replace-match "" t t s)))
8394 (setq s (org-trim s))
8395 (if (string-match (concat "^\\(" org-quote-string "\\|"
8396 org-comment-string "\\)") s)
8397 (setq s (replace-match "" t t s)))
8398 (while (string-match org-ts-regexp s)
8399 (setq s (replace-match "" t t s))))
8400 (while (string-match "[^a-zA-Z_ \t]+" s)
8401 (setq s (replace-match " " t t s)))
8402 (or string (setq s (concat "*" s))) ; Add * for headlines
8403 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8405 (defun org-make-link (&rest strings)
8406 "Concatenate STRINGS, format resulting string with `org-link-format'."
8407 (format org-link-format (apply 'concat strings)))
8409 (defun org-make-link-string (link &optional description)
8410 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8411 (if (eq org-link-style 'plain)
8412 (if (equal description link)
8413 link
8414 (concat description "\n" link))
8415 (when (stringp description)
8416 ;; Remove brackets from the description, they are fatal.
8417 (while (string-match "\\[\\|\\]" description)
8418 (setq description (replace-match "" t t description))))
8419 (when (equal (org-link-escape link) description)
8420 ;; No description needed, it is identical
8421 (setq description nil))
8422 (when (and (not description)
8423 (not (equal link (org-link-escape link))))
8424 (setq description link))
8425 (concat "[[" (org-link-escape link) "]"
8426 (if description (concat "[" description "]") "")
8427 "]")))
8429 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8430 "Association list of escapes for some characters problematic in links.")
8432 (defun org-link-escape (text)
8433 "Escape charaters in TEXT that are problematic for links."
8434 (when text
8435 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8436 org-link-escape-chars "\\|")))
8437 (while (string-match re text)
8438 (setq text
8439 (replace-match
8440 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8441 t t text)))
8442 text)))
8444 (defun org-link-unescape (text)
8445 "Reverse the action of `org-link-escape'."
8446 (when text
8447 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8448 org-link-escape-chars "\\|")))
8449 (while (string-match re text)
8450 (setq text
8451 (replace-match
8452 (car (rassoc (match-string 0 text) org-link-escape-chars))
8453 t t text)))
8454 text)))
8456 (defun org-xor (a b)
8457 "Exclusive or."
8458 (if a (not b) b))
8460 (defun org-get-header (header)
8461 "Find a header field in the current buffer."
8462 (save-excursion
8463 (goto-char (point-min))
8464 (let ((case-fold-search t) s)
8465 (cond
8466 ((eq header 'from)
8467 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8468 (setq s (match-string 1)))
8469 (while (string-match "\"" s)
8470 (setq s (replace-match "" t t s)))
8471 (if (string-match "[<(].*" s)
8472 (setq s (replace-match "" t t s))))
8473 ((eq header 'message-id)
8474 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8475 (setq s (match-string 1))))
8476 ((eq header 'subject)
8477 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8478 (setq s (match-string 1)))))
8479 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8480 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8481 s)))
8484 (defun org-fixup-message-id-for-http (s)
8485 "Replace special characters in a message id, so it can be used in an http query."
8486 (while (string-match "<" s)
8487 (setq s (replace-match "%3C" t t s)))
8488 (while (string-match ">" s)
8489 (setq s (replace-match "%3E" t t s)))
8490 (while (string-match "@" s)
8491 (setq s (replace-match "%40" t t s)))
8494 (defun org-insert-link (&optional complete-file)
8495 "Insert a link. At the prompt, enter the link.
8497 Completion can be used to select a link previously stored with
8498 `org-store-link'. When the empty string is entered (i.e. if you just
8499 press RET at the prompt), the link defaults to the most recently
8500 stored link. As SPC triggers completion in the minibuffer, you need to
8501 use M-SPC or C-q SPC to force the insertion of a space character.
8503 You will also be prompted for a description, and if one is given, it will
8504 be displayed in the buffer instead of the link.
8506 If there is already a link at point, this command will allow you to edit link
8507 and description parts.
8509 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8510 selected using completion. The path to the file will be relative to
8511 the current directory if the file is in the current directory or a
8512 subdirectory. Otherwise, the link will be the absolute path as
8513 completed in the minibuffer (i.e. normally ~/path/to/file).
8515 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8516 is in the current directory or below.
8517 With three \\[universal-argument] prefixes, negate the meaning of
8518 `org-keep-stored-link-after-insertion'."
8519 (interactive "P")
8520 (let (link desc entry remove file (pos (point)))
8521 (cond
8522 ((save-excursion
8523 (skip-chars-forward "^]\n\r")
8524 (and (re-search-backward "\\[\\[" nil t)
8525 (looking-at org-bracket-link-regexp)
8526 (<= (match-beginning 0) pos)
8527 (>= (match-end 0) pos)))
8528 ;; We do have a link at point, and we are going to edit it.
8529 (setq remove (list (match-beginning 0) (match-end 0)))
8530 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8531 (setq link (read-string "Link: "
8532 (org-link-unescape
8533 (org-match-string-no-properties 1)))))
8534 ((equal complete-file '(4))
8535 ;; Completing read for file names.
8536 (setq file (read-file-name "File: "))
8537 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8538 (pwd1 (file-name-as-directory (abbreviate-file-name
8539 (expand-file-name ".")))))
8540 (cond
8541 ((equal complete-file '(16))
8542 (setq link (org-make-link
8543 "file:"
8544 (abbreviate-file-name (expand-file-name file)))))
8545 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8546 (setq link (org-make-link "file:" (match-string 1 file))))
8547 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8548 (expand-file-name file))
8549 (setq link (org-make-link
8550 "file:" (match-string 1 (expand-file-name file)))))
8551 (t (setq link (org-make-link "file:" file))))))
8553 ;; Read link, with completion for stored links.
8554 (setq link (org-completing-read
8555 "Link: " org-stored-links nil nil nil
8556 org-insert-link-history
8557 (or (car (car org-stored-links)))))
8558 (setq entry (assoc link org-stored-links))
8559 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8560 (not org-keep-stored-link-after-insertion))
8561 (setq org-stored-links (delq (assoc link org-stored-links)
8562 org-stored-links)))
8563 (setq link (if entry (nth 1 entry) link)
8564 desc (or desc (nth 2 entry)))))
8566 (if (string-match org-plain-link-re link)
8567 ;; URL-like link, normalize the use of angular brackets.
8568 (setq link (org-make-link (org-remove-angle-brackets link))))
8570 ;; Check if we are linking to the current file with a search option
8571 ;; If yes, simplify the link by using only the search option.
8572 (when (and buffer-file-name
8573 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
8574 (let* ((path (match-string 1 link))
8575 (case-fold-search nil)
8576 (search (match-string 2 link)))
8577 (save-match-data
8578 (if (equal (file-truename buffer-file-name) (file-truename path))
8579 ;; We are linking to this same file, with a search option
8580 (setq link search)))))
8582 ;; Check if we can/should use a relative path. If yes, simplify the link
8583 (when (string-match "\\<file:\\(.*\\)" link)
8584 (let* ((path (match-string 1 link))
8585 (case-fold-search nil))
8586 (cond
8587 ((eq org-link-file-path-type 'absolute)
8588 (setq path (abbreviate-file-name (expand-file-name path))))
8589 ((eq org-link-file-path-type 'noabbrev)
8590 (setq path (expand-file-name path)))
8591 ((eq org-link-file-path-type 'relative)
8592 (setq path (file-relative-name path)))
8594 (save-match-data
8595 (if (string-match (concat "^" (regexp-quote
8596 (file-name-as-directory
8597 (expand-file-name "."))))
8598 (expand-file-name path))
8599 ;; We are linking a file with relative path name.
8600 (setq path (substring (expand-file-name path)
8601 (match-end 0)))))))
8602 (setq link (concat "file:" path))))
8604 (setq desc (read-string "Description: " desc))
8605 (unless (string-match "\\S-" desc) (setq desc nil))
8606 (if remove (apply 'delete-region remove))
8607 (insert (org-make-link-string link desc))))
8609 (defun org-completing-read (&rest args)
8610 (let ((minibuffer-local-completion-map
8611 (copy-keymap minibuffer-local-completion-map)))
8612 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8613 (apply 'completing-read args)))
8615 ;;; Opening/following a link
8617 (defun org-find-file-at-mouse (ev)
8618 "Open file link or URL at mouse."
8619 (interactive "e")
8620 (mouse-set-point ev)
8621 (org-open-at-point 'in-emacs))
8623 (defun org-open-at-mouse (ev)
8624 "Open file link or URL at mouse."
8625 (interactive "e")
8626 (mouse-set-point ev)
8627 (org-open-at-point))
8629 (defvar org-window-config-before-follow-link nil
8630 "The window configuration before following a link.
8631 This is saved in case the need arises to restore it.")
8633 ;; FIXME: IN-EMACS is used for many purposes, maybe rename this argument???
8634 (defun org-open-at-point (&optional in-emacs)
8635 "Open link at or after point.
8636 If there is no link at point, this function will search forward up to
8637 the end of the current subtree.
8638 Normally, files will be opened by an appropriate application. If the
8639 optional argument IN-EMACS is non-nil, Emacs will visit the file."
8640 (interactive "P")
8641 (setq org-window-config-before-follow-link (current-window-configuration))
8642 (org-remove-occur-highlights nil nil t)
8643 (if (org-at-timestamp-p t)
8644 (org-follow-timestamp-link)
8645 (let (type path link line search (pos (point)))
8646 (catch 'match
8647 (save-excursion
8648 (skip-chars-forward "^]\n\r")
8649 (when (and (re-search-backward "\\[\\[" nil t)
8650 (looking-at org-bracket-link-regexp)
8651 (<= (match-beginning 0) pos)
8652 (>= (match-end 0) pos))
8653 (setq link (org-link-unescape (org-match-string-no-properties 1)))
8654 (while (string-match " *\n *" link)
8655 (setq link (replace-match " " t t link)))
8656 (setq link (org-link-expand-abbrev link))
8657 (if (string-match org-link-re-with-space2 link)
8658 (setq type (match-string 1 link)
8659 path (match-string 2 link))
8660 (setq type "thisfile"
8661 path link))
8662 (throw 'match t)))
8664 (when (get-text-property (point) 'org-linked-text)
8665 (setq type "thisfile"
8666 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8667 (1+ (point)) (point))
8668 path (buffer-substring
8669 (previous-single-property-change pos 'org-linked-text)
8670 (next-single-property-change pos 'org-linked-text)))
8671 (throw 'match t))
8673 (save-excursion
8674 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
8675 (if (equal (char-before) ?<) (backward-char 1))
8676 (when (or (looking-at org-angle-link-re)
8677 (looking-at org-plain-link-re)
8678 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
8679 (re-search-forward org-plain-link-re (point-at-eol) t))
8680 (<= (match-beginning 0) pos)
8681 (>= (match-end 0) pos)))
8682 (setq type (match-string 1)
8683 path (match-string 2))
8684 (throw 'match t)))
8685 (save-excursion
8686 (skip-chars-backward "^ \t\n\r")
8687 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
8688 (setq type "tags"
8689 path (match-string 1))
8690 (while (string-match ":" path)
8691 (setq path (replace-match "+" t t path)))
8692 (throw 'match t)))
8693 (save-excursion
8694 (skip-chars-backward "a-zA-Z_")
8695 (when (and (memq 'camel org-activate-links)
8696 (looking-at org-camel-regexp))
8697 (setq type "camel" path (match-string 0))
8698 (if (equal (char-before) ?*)
8699 (setq path (concat "*" path))))
8700 (throw 'match t)))
8701 (unless path
8702 (error "No link found"))
8703 ;; Remove any trailing spaces in path
8704 (if (string-match " +\\'" path)
8705 (setq path (replace-match "" t t path)))
8707 (cond
8709 ((equal type "mailto")
8710 (let ((cmd (car org-link-mailto-program))
8711 (args (cdr org-link-mailto-program)) args1
8712 (address path) (subject "") a)
8713 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8714 (setq address (match-string 1 path)
8715 subject (org-link-escape (match-string 2 path))))
8716 (while args
8717 (cond
8718 ((not (stringp (car args))) (push (pop args) args1))
8719 (t (setq a (pop args))
8720 (if (string-match "%a" a)
8721 (setq a (replace-match address t t a)))
8722 (if (string-match "%s" a)
8723 (setq a (replace-match subject t t a)))
8724 (push a args1))))
8725 (apply cmd (nreverse args1))))
8727 ((member type '("http" "https" "ftp" "news"))
8728 (browse-url (concat type ":" path)))
8730 ((string= type "tags")
8731 (org-tags-view in-emacs path))
8732 ((or (string= type "camel")
8733 (string= type "thisfile"))
8734 (if in-emacs
8735 (switch-to-buffer-other-window
8736 (org-get-buffer-for-internal-link (current-buffer)))
8737 (org-mark-ring-push))
8738 (org-link-search
8739 path
8740 (cond ((equal in-emacs '(4)) 'occur)
8741 ((equal in-emacs '(16)) 'org-occur)
8742 (t nil))))
8744 ((string= type "file")
8745 (if (string-match "::\\([0-9]+\\)\\'" path)
8746 (setq line (string-to-number (match-string 1 path))
8747 path (substring path 0 (match-beginning 0)))
8748 (if (string-match "::\\(.+\\)\\'" path)
8749 (setq search (match-string 1 path)
8750 path (substring path 0 (match-beginning 0)))))
8751 (org-open-file path in-emacs line search))
8753 ((string= type "news")
8754 (org-follow-gnus-link path))
8756 ((string= type "bbdb")
8757 (org-follow-bbdb-link path))
8759 ((string= type "info")
8760 (org-follow-info-link path))
8762 ((string= type "gnus")
8763 (let (group article)
8764 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8765 (error "Error in Gnus link"))
8766 (setq group (match-string 1 path)
8767 article (match-string 3 path))
8768 (org-follow-gnus-link group article)))
8770 ((string= type "vm")
8771 (let (folder article)
8772 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8773 (error "Error in VM link"))
8774 (setq folder (match-string 1 path)
8775 article (match-string 3 path))
8776 ;; in-emacs is the prefix arg, will be interpreted as read-only
8777 (org-follow-vm-link folder article in-emacs)))
8779 ((string= type "wl")
8780 (let (folder article)
8781 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8782 (error "Error in Wanderlust link"))
8783 (setq folder (match-string 1 path)
8784 article (match-string 3 path))
8785 (org-follow-wl-link folder article)))
8787 ((string= type "mhe")
8788 (let (folder article)
8789 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8790 (error "Error in MHE link"))
8791 (setq folder (match-string 1 path)
8792 article (match-string 3 path))
8793 (org-follow-mhe-link folder article)))
8795 ((string= type "rmail")
8796 (let (folder article)
8797 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8798 (error "Error in RMAIL link"))
8799 (setq folder (match-string 1 path)
8800 article (match-string 3 path))
8801 (org-follow-rmail-link folder article)))
8803 ((string= type "shell")
8804 (let ((cmd path))
8805 ;; FIXME: the following is only for backward compatibility
8806 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
8807 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
8808 (if (or (not org-confirm-shell-link-function)
8809 (funcall org-confirm-shell-link-function
8810 (format "Execute \"%s\" in shell? "
8811 (org-add-props cmd nil
8812 'face 'org-warning))))
8813 (progn
8814 (message "Executing %s" cmd)
8815 (shell-command cmd))
8816 (error "Abort"))))
8818 ((string= type "elisp")
8819 (let ((cmd path))
8820 (if (or (not org-confirm-elisp-link-function)
8821 (funcall org-confirm-elisp-link-function
8822 (format "Execute \"%s\" as elisp? "
8823 (org-add-props cmd nil
8824 'face 'org-warning))))
8825 (message "%s => %s" cmd (eval (read cmd)))
8826 (error "Abort"))))
8829 (browse-url-at-point))))))
8831 ;;; File search
8833 (defvar org-create-file-search-functions nil
8834 "List of functions to construct the right search string for a file link.
8835 These functions are called in turn with point at the location to
8836 which the link should point.
8838 A function in the hook should first test if it would like to
8839 handle this file type, for example by checking the major-mode or
8840 the file extension. If it decides not to handle this file, it
8841 should just return nil to give other functions a chance. If it
8842 does handle the file, it must return the search string to be used
8843 when following the link. The search string will be part of the
8844 file link, given after a double colon, and `org-open-at-point'
8845 will automatically search for it. If special measures must be
8846 taken to make the search successful, another function should be
8847 added to the companion hook `org-execute-file-search-functions',
8848 which see.
8850 A function in this hook may also use `setq' to set the variable
8851 `description' to provide a suggestion for the descriptive text to
8852 be used for this link when it gets inserted into an Org-mode
8853 buffer with \\[org-insert-link].")
8855 (defvar org-execute-file-search-functions nil
8856 "List of functions to execute a file search triggered by a link.
8858 Functions added to this hook must accept a single argument, the
8859 search string that was part of the file link, the part after the
8860 double colon. The function must first check if it would like to
8861 handle this search, for example by checking the major-mode or the
8862 file extension. If it decides not to handle this search, it
8863 should just return nil to give other functions a chance. If it
8864 does handle the search, it must return a non-nil value to keep
8865 other functions from trying.
8867 Each function can access the current prefix argument through the
8868 variable `current-prefix-argument'. Note that a single prefix is
8869 used to force opening a link in Emacs, so it may be good to only
8870 use a numeric or double prefix to guide the search function.
8872 In case this is needed, a function in this hook can also restore
8873 the window configuration before `org-open-at-point' was called using:
8875 (set-window-configuration org-window-config-before-follow-link)")
8877 (defun org-link-search (s &optional type)
8878 "Search for a link search option.
8879 When S is a CamelCaseWord, search for a target, or for a sentence containing
8880 the words. If S is surrounded by forward slashes, it is interpreted as a
8881 regular expression. In org-mode files, this will create an `org-occur'
8882 sparse tree. In ordinary files, `occur' will be used to list matches.
8883 If the current buffer is in `dired-mode', grep will be used to search
8884 in all files."
8885 (let ((case-fold-search t)
8886 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8887 (pos (point))
8888 (pre "") (post "")
8889 words re0 re1 re2 re3 re4 re5 re2a reall camel)
8890 (cond
8891 ;; First check if there are any special
8892 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8893 ;; Now try the builtin stuff
8894 ((save-excursion
8895 (goto-char (point-min))
8896 (and
8897 (re-search-forward
8898 (concat "<<" (regexp-quote s0) ">>") nil t)
8899 (setq pos (match-beginning 0))))
8900 ;; There is an exact target for this
8901 (goto-char pos))
8902 ((string-match "^/\\(.*\\)/$" s)
8903 ;; A regular expression
8904 (cond
8905 ((org-mode-p)
8906 (org-occur (match-string 1 s)))
8907 ;;((eq major-mode 'dired-mode)
8908 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8909 (t (org-do-occur (match-string 1 s)))))
8910 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
8912 ;; A camel or a normal search string
8913 (when (equal (string-to-char s) ?*)
8914 ;; Anchor on headlines, post may include tags.
8915 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
8916 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
8917 s (substring s 1)))
8918 (remove-text-properties
8919 0 (length s)
8920 '(face nil mouse-face nil keymap nil fontified nil) s)
8921 ;; Make a series of regular expressions to find a match
8922 (setq words
8923 (if camel
8924 (org-camel-to-words s)
8925 (org-split-string s "[ \n\r\t]+"))
8926 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8927 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
8928 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8929 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8930 re1 (concat pre re2 post)
8931 re3 (concat pre re4 post)
8932 re5 (concat pre ".*" re4)
8933 re2 (concat pre re2)
8934 re2a (concat pre re2a)
8935 re4 (concat pre re4)
8936 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8937 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8938 re5 "\\)"
8940 (cond
8941 ((eq type 'org-occur) (org-occur reall))
8942 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8943 (t (goto-char (point-min))
8944 (if (or (org-search-not-link re0 nil t)
8945 (org-search-not-link re1 nil t)
8946 (org-search-not-link re2 nil t)
8947 (org-search-not-link re2a nil t)
8948 (org-search-not-link re3 nil t)
8949 (org-search-not-link re4 nil t)
8950 (org-search-not-link re5 nil t)
8952 (goto-char (match-beginning 1))
8953 (goto-char pos)
8954 (error "No match")))))
8956 ;; Normal string-search
8957 (goto-char (point-min))
8958 (if (search-forward s nil t)
8959 (goto-char (match-beginning 0))
8960 (error "No match"))))
8961 (and (org-mode-p) (org-show-context 'link-search))))
8963 (defun org-search-not-link (&rest args)
8964 "Execute `re-search-forward', but only accept matches that are not a link."
8965 (catch 'exit
8966 (let (p1)
8967 (while (apply 're-search-forward args)
8968 (setq p1 (point))
8969 (if (not (save-match-data
8970 (and (re-search-backward "\\[\\[" nil t)
8971 (looking-at org-bracket-link-regexp)
8972 (<= (match-beginning 0) p1)
8973 (>= (match-end 0) p1))))
8974 (progn (goto-char (match-end 0))
8975 (throw 'exit (point)))
8976 (goto-char (match-end 0)))))))
8978 (defun org-get-buffer-for-internal-link (buffer)
8979 "Return a buffer to be used for displaying the link target of internal links."
8980 (cond
8981 ((not org-display-internal-link-with-indirect-buffer)
8982 buffer)
8983 ((string-match "(Clone)$" (buffer-name buffer))
8984 (message "Buffer is already a clone, not making another one")
8985 ;; we also do not modify visibility in this case
8986 buffer)
8987 (t ; make a new indirect buffer for displaying the link
8988 (let* ((bn (buffer-name buffer))
8989 (ibn (concat bn "(Clone)"))
8990 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8991 (with-current-buffer ib (org-overview))
8992 ib))))
8994 (defun org-do-occur (regexp &optional cleanup)
8995 "Call the Emacs command `occur'.
8996 If CLEANUP is non-nil, remove the printout of the regular expression
8997 in the *Occur* buffer. This is useful if the regex is long and not useful
8998 to read."
8999 (occur regexp)
9000 (when cleanup
9001 (let ((cwin (selected-window)) win beg end)
9002 (when (setq win (get-buffer-window "*Occur*"))
9003 (select-window win))
9004 (goto-char (point-min))
9005 (when (re-search-forward "match[a-z]+" nil t)
9006 (setq beg (match-end 0))
9007 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9008 (setq end (1- (match-beginning 0)))))
9009 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9010 (goto-char (point-min))
9011 (select-window cwin))))
9013 ;;; The mark ring for links jumps
9015 (defvar org-mark-ring nil
9016 "Mark ring for positions before jumps in Org-mode.")
9017 (defvar org-mark-ring-last-goto nil
9018 "Last position in the mark ring used to go back.")
9019 ;; Fill and close the ring
9020 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9021 (loop for i from 1 to org-mark-ring-length do
9022 (push (make-marker) org-mark-ring))
9023 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9024 org-mark-ring)
9026 (defun org-mark-ring-push (&optional pos buffer)
9027 "Put the current position or POS into the mark ring and rotate it."
9028 (interactive)
9029 (setq pos (or pos (point)))
9030 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9031 (move-marker (car org-mark-ring)
9032 (or pos (point))
9033 (or buffer (current-buffer)))
9034 (message
9035 (substitute-command-keys
9036 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9038 (defun org-mark-ring-goto (&optional n)
9039 "Jump to the previous position in the mark ring.
9040 With prefix arg N, jump back that many stored positions. When
9041 called several times in succession, walk through the entire ring.
9042 Org-mode commands jumping to a different position in the current file,
9043 or to another Org-mode file, automatically push the old position
9044 onto the ring."
9045 (interactive "p")
9046 (let (p m)
9047 (if (eq last-command this-command)
9048 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9049 (setq p org-mark-ring))
9050 (setq org-mark-ring-last-goto p)
9051 (setq m (car p))
9052 (switch-to-buffer (marker-buffer m))
9053 (goto-char m)
9054 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9056 (defun org-camel-to-words (s)
9057 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9058 (let ((case-fold-search nil)
9059 words)
9060 (while (string-match "[a-z][A-Z]" s)
9061 (push (substring s 0 (1+ (match-beginning 0))) words)
9062 (setq s (substring s (1+ (match-beginning 0)))))
9063 (nreverse (cons s words))))
9065 (defun org-remove-angle-brackets (s)
9066 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9067 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9069 (defun org-add-angle-brackets (s)
9070 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9071 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9074 ;;; Following specific links
9076 (defun org-follow-timestamp-link ()
9077 (cond
9078 ((org-at-date-range-p t)
9079 (let ((org-agenda-start-on-weekday)
9080 (t1 (match-string 1))
9081 (t2 (match-string 2)))
9082 (setq t1 (time-to-days (org-time-string-to-time t1))
9083 t2 (time-to-days (org-time-string-to-time t2)))
9084 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9085 ((org-at-timestamp-p t)
9086 (org-agenda-list nil (time-to-days (org-time-string-to-time
9087 (substring (match-string 1) 0 10)))
9089 (t (error "This should not happen"))))
9092 (defun org-follow-bbdb-link (name)
9093 "Follow a BBDB link to NAME."
9094 (require 'bbdb)
9095 (let ((inhibit-redisplay t)
9096 (bbdb-electric-p nil))
9097 (catch 'exit
9098 ;; Exact match on name
9099 (bbdb-name (concat "\\`" name "\\'") nil)
9100 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9101 ;; Exact match on name
9102 (bbdb-company (concat "\\`" name "\\'") nil)
9103 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9104 ;; Partial match on name
9105 (bbdb-name name nil)
9106 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9107 ;; Partial match on company
9108 (bbdb-company name nil)
9109 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9110 ;; General match including network address and notes
9111 (bbdb name nil)
9112 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9113 (delete-window (get-buffer-window "*BBDB*"))
9114 (error "No matching BBDB record")))))
9116 (defun org-follow-info-link (name)
9117 "Follow an info file & node link to NAME."
9118 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9119 (string-match "\\(.*\\)" name))
9120 (progn
9121 (require 'info)
9122 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9123 (Info-find-node (match-string 1 name) (match-string 2 name))
9124 (Info-find-node (match-string 1 name) "Top")))
9125 (message (concat "Could not open: " name))))
9127 (defun org-follow-gnus-link (&optional group article)
9128 "Follow a Gnus link to GROUP and ARTICLE."
9129 (require 'gnus)
9130 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9131 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
9132 (cond ((and group article)
9133 (gnus-group-read-group t nil group (list (string-to-number article)))
9134 (gnus-summary-select-article))
9135 (group (gnus-group-jump-to-group group))))
9137 (defun org-follow-vm-link (&optional folder article readonly)
9138 "Follow a VM link to FOLDER and ARTICLE."
9139 (require 'vm)
9140 (setq article (org-add-angle-brackets article))
9141 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9142 ;; ange-ftp or efs or tramp access
9143 (let ((user (or (match-string 1 folder) (user-login-name)))
9144 (host (match-string 2 folder))
9145 (file (match-string 3 folder)))
9146 (cond
9147 ((featurep 'tramp)
9148 ;; use tramp to access the file
9149 (if (featurep 'xemacs)
9150 (setq folder (format "[%s@%s]%s" user host file))
9151 (setq folder (format "/%s@%s:%s" user host file))))
9153 ;; use ange-ftp or efs
9154 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9155 (setq folder (format "/%s@%s:%s" user host file))))))
9156 (when folder
9157 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9158 (sit-for 0.1)
9159 (when article
9160 (vm-select-folder-buffer)
9161 (widen)
9162 (let ((case-fold-search t))
9163 (goto-char (point-min))
9164 (if (not (re-search-forward
9165 (concat "^" "message-id: *" (regexp-quote article))))
9166 (error "Could not find the specified message in this folder"))
9167 (vm-isearch-update)
9168 (vm-isearch-narrow)
9169 (vm-beginning-of-message)
9170 (vm-summarize)))))
9172 (defun org-follow-wl-link (folder article)
9173 "Follow a Wanderlust link to FOLDER and ARTICLE."
9174 (setq article (org-add-angle-brackets article))
9175 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
9176 (if article (wl-summary-jump-to-msg-by-message-id article))
9177 (wl-summary-redisplay))
9179 (defun org-follow-rmail-link (folder article)
9180 "Follow an RMAIL link to FOLDER and ARTICLE."
9181 (setq article (org-add-angle-brackets article))
9182 (let (message-number)
9183 (save-excursion
9184 (save-window-excursion
9185 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9186 (setq message-number
9187 (save-restriction
9188 (widen)
9189 (goto-char (point-max))
9190 (if (re-search-backward
9191 (concat "^Message-ID:\\s-+" (regexp-quote
9192 (or article "")))
9193 nil t)
9194 (rmail-what-message))))))
9195 (if message-number
9196 (progn
9197 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9198 (rmail-show-message message-number)
9199 message-number)
9200 (error "Message not found"))))
9202 ;;; mh-e integration based on planner-mode
9203 (defun org-mhe-get-message-real-folder ()
9204 "Return the name of the current message real folder, so if you use
9205 sequences, it will now work."
9206 (save-excursion
9207 (let* ((folder
9208 (if (equal major-mode 'mh-folder-mode)
9209 mh-current-folder
9210 ;; Refer to the show buffer
9211 mh-show-folder-buffer))
9212 (end-index
9213 (if (boundp 'mh-index-folder)
9214 (min (length mh-index-folder) (length folder))))
9216 ;; a simple test on mh-index-data does not work, because
9217 ;; mh-index-data is always nil in a show buffer.
9218 (if (and (boundp 'mh-index-folder)
9219 (string= mh-index-folder (substring folder 0 end-index)))
9220 (if (equal major-mode 'mh-show-mode)
9221 (save-window-excursion
9222 (when (buffer-live-p (get-buffer folder))
9223 (progn
9224 (pop-to-buffer folder)
9225 (org-mhe-get-message-folder-from-index)
9228 (org-mhe-get-message-folder-from-index)
9230 folder
9234 (defun org-mhe-get-message-folder-from-index ()
9235 "Returns the name of the message folder in a index folder buffer."
9236 (save-excursion
9237 (mh-index-previous-folder)
9238 (re-search-forward "^\\(+.*\\)$" nil t)
9239 (message (match-string 1))))
9241 (defun org-mhe-get-message-folder ()
9242 "Return the name of the current message folder. Be careful if you
9243 use sequences."
9244 (save-excursion
9245 (if (equal major-mode 'mh-folder-mode)
9246 mh-current-folder
9247 ;; Refer to the show buffer
9248 mh-show-folder-buffer)))
9250 (defun org-mhe-get-message-num ()
9251 "Return the number of the current message. Be careful if you
9252 use sequences."
9253 (save-excursion
9254 (if (equal major-mode 'mh-folder-mode)
9255 (mh-get-msg-num nil)
9256 ;; Refer to the show buffer
9257 (mh-show-buffer-message-number))))
9259 (defun org-mhe-get-header (header)
9260 "Return a header of the message in folder mode. This will create a
9261 show buffer for the corresponding message. If you have a more clever
9262 idea..."
9263 (let* ((folder (org-mhe-get-message-folder))
9264 (num (org-mhe-get-message-num))
9265 (buffer (get-buffer-create (concat "show-" folder)))
9266 (header-field))
9267 (with-current-buffer buffer
9268 (mh-display-msg num folder)
9269 (if (equal major-mode 'mh-folder-mode)
9270 (mh-header-display)
9271 (mh-show-header-display))
9272 (set-buffer buffer)
9273 (setq header-field (mh-get-header-field header))
9274 (if (equal major-mode 'mh-folder-mode)
9275 (mh-show)
9276 (mh-show-show))
9277 header-field)))
9279 (defun org-follow-mhe-link (folder article)
9280 "Follow an MHE link to FOLDER and ARTICLE.
9281 If ARTICLE is nil FOLDER is shown. If the configuration variable
9282 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9283 ARTICLE is searched in all folders. Indexed searches (swish++,
9284 namazu, and others supported by MH-E) will always search in all
9285 folders."
9286 (require 'mh-e)
9287 (require 'mh-search)
9288 (require 'mh-utils)
9289 (mh-find-path)
9290 (if (not article)
9291 (mh-visit-folder (mh-normalize-folder-name folder))
9292 (setq article (org-add-angle-brackets article))
9293 (mh-search-choose)
9294 (if (equal mh-searcher 'pick)
9295 (progn
9296 (mh-search folder (list "--message-id" article))
9297 (when (and org-mhe-search-all-folders
9298 (not (org-mhe-get-message-real-folder)))
9299 (kill-this-buffer)
9300 (mh-search "+" (list "--message-id" article))))
9301 (mh-search "+" article))
9302 (if (org-mhe-get-message-real-folder)
9303 (mh-show-msg 1)
9304 (kill-this-buffer)
9305 (error "Message not found"))))
9307 ;;; BibTeX links
9309 ;; Use the custom search meachnism to construct and use search strings for
9310 ;; file links to BibTeX database entries.
9312 (defun org-create-file-search-in-bibtex ()
9313 "Create the search string and description for a BibTeX database entry."
9314 (when (eq major-mode 'bibtex-mode)
9315 ;; yes, we want to construct this search string.
9316 ;; Make a good description for this entry, using names, year and the title
9317 ;; Put it into the `description' variable which is dynamically scoped.
9318 (let ((bibtex-autokey-names 1)
9319 (bibtex-autokey-names-stretch 1)
9320 (bibtex-autokey-name-case-convert-function 'identity)
9321 (bibtex-autokey-name-separator " & ")
9322 (bibtex-autokey-additional-names " et al.")
9323 (bibtex-autokey-year-length 4)
9324 (bibtex-autokey-name-year-separator " ")
9325 (bibtex-autokey-titlewords 3)
9326 (bibtex-autokey-titleword-separator " ")
9327 (bibtex-autokey-titleword-case-convert-function 'identity)
9328 (bibtex-autokey-titleword-length 'infty)
9329 (bibtex-autokey-year-title-separator ": "))
9330 (setq description (bibtex-generate-autokey)))
9331 ;; Now parse the entry, get the key and return it.
9332 (save-excursion
9333 (bibtex-beginning-of-entry)
9334 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9336 (defun org-execute-file-search-in-bibtex (s)
9337 "Find the link search string S as a key for a database entry."
9338 (when (eq major-mode 'bibtex-mode)
9339 ;; Yes, we want to do the search in this file.
9340 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9341 (goto-char (point-min))
9342 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9343 (regexp-quote s) "[ \t\n]*,") nil t)
9344 (goto-char (match-beginning 0)))
9345 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9346 ;; Use double prefix to indicate that any web link should be browsed
9347 (let ((b (current-buffer)) (p (point)))
9348 ;; Restore the window configuration because we just use the web link
9349 (set-window-configuration org-window-config-before-follow-link)
9350 (save-excursion (set-buffer b) (goto-char p)
9351 (bibtex-url)))
9352 (recenter 0)) ; Move entry start to beginning of window
9353 ;; return t to indicate that the search is done.
9356 ;; Finally add the functions to the right hooks.
9357 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9358 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9360 ;; end of Bibtex link setup
9362 ;;; Following file links
9364 (defun org-open-file (path &optional in-emacs line search)
9365 "Open the file at PATH.
9366 First, this expands any special file name abbreviations. Then the
9367 configuration variable `org-file-apps' is checked if it contains an
9368 entry for this file type, and if yes, the corresponding command is launched.
9369 If no application is found, Emacs simply visits the file.
9370 With optional argument IN-EMACS, Emacs will visit the file.
9371 Optional LINE specifies a line to go to, optional SEARCH a string to
9372 search for. If LINE or SEARCH is given, the file will always be
9373 opened in Emacs.
9374 If the file does not exist, an error is thrown."
9375 (setq in-emacs (or in-emacs line search))
9376 (let* ((file (if (equal path "")
9377 buffer-file-name
9378 (substitute-in-file-name (expand-file-name path))))
9379 (apps (append org-file-apps (org-default-apps)))
9380 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9381 (dirp (if remp nil (file-directory-p file)))
9382 (dfile (downcase file))
9383 (old-buffer (current-buffer))
9384 (old-pos (point))
9385 (old-mode major-mode)
9386 ext cmd)
9387 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9388 (setq ext (match-string 1 dfile))
9389 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9390 (setq ext (match-string 1 dfile))))
9391 (if in-emacs
9392 (setq cmd 'emacs)
9393 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9394 (and dirp (cdr (assoc 'directory apps)))
9395 (cdr (assoc ext apps))
9396 (cdr (assoc t apps)))))
9397 (when (eq cmd 'mailcap)
9398 (require 'mailcap)
9399 (mailcap-parse-mailcaps)
9400 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9401 (command (mailcap-mime-info mime-type)))
9402 (if (stringp command)
9403 (setq cmd command)
9404 (setq cmd 'emacs))))
9405 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9406 (not (file-exists-p file))
9407 (not org-open-non-existing-files))
9408 (error "No such file: %s" file))
9409 (cond
9410 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9411 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9412 (if (string-match "['\"]%s['\"]" cmd)
9413 (setq cmd (replace-match "%s" t t cmd)))
9414 (setq cmd (format cmd (shell-quote-argument file)))
9415 (save-window-excursion
9416 (shell-command (concat cmd " &"))))
9417 ((or (stringp cmd)
9418 (eq cmd 'emacs))
9419 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9420 (if line (goto-line line)
9421 (if search (org-link-search search))))
9422 ((consp cmd)
9423 (eval cmd))
9424 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9425 (and (org-mode-p) (eq old-mode 'org-mode)
9426 (or (not (equal old-buffer (current-buffer)))
9427 (not (equal old-pos (point))))
9428 (org-mark-ring-push old-pos old-buffer))))
9430 (defun org-default-apps ()
9431 "Return the default applications for this operating system."
9432 (cond
9433 ((eq system-type 'darwin)
9434 org-file-apps-defaults-macosx)
9435 ((eq system-type 'windows-nt)
9436 org-file-apps-defaults-windowsnt)
9437 (t org-file-apps-defaults-gnu)))
9439 (defun org-expand-file-name (path)
9440 "Replace special path abbreviations and expand the file name."
9441 (expand-file-name path))
9443 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9444 (defun org-file-remote-p (file)
9445 "Test whether FILE specifies a location on a remote system.
9446 Return non-nil if the location is indeed remote.
9448 For example, the filename \"/user@host:/foo\" specifies a location
9449 on the system \"/user@host:\"."
9450 (cond ((fboundp 'file-remote-p)
9451 (file-remote-p file))
9452 ((fboundp 'tramp-handle-file-remote-p)
9453 (tramp-handle-file-remote-p file))
9454 ((and (boundp 'ange-ftp-name-format)
9455 (string-match (car ange-ftp-name-format) file))
9457 (t nil)))
9460 ;;;; Hooks for remember.el
9462 ;;;###autoload
9463 (defun org-remember-annotation ()
9464 "Return a link to the current location as an annotation for remember.el.
9465 If you are using Org-mode files as target for data storage with
9466 remember.el, then the annotations should include a link compatible with the
9467 conventions in Org-mode. This function returns such a link."
9468 (org-store-link nil))
9470 (defconst org-remember-help
9471 "Select a destination location for the note.
9472 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
9473 RET at beg-of-buf -> Append to file as level 2 headline
9474 RET on headline -> Store as sublevel entry to current headline
9475 <left>/<right> -> before/after current headline, same headings level")
9477 ;;;###autoload
9478 (defun org-remember-apply-template ()
9479 "Initialize *remember* buffer with template, invoke `org-mode'.
9480 This function should be placed into `remember-mode-hook' and in fact requires
9481 to be run from that hook to fucntion properly."
9482 (if org-remember-templates
9484 (let* ((entry (if (= (length org-remember-templates) 1)
9485 (cdar org-remember-templates)
9486 (message "Select template: %s"
9487 (mapconcat
9488 (lambda (x) (char-to-string (car x)))
9489 org-remember-templates " "))
9490 (cdr (assoc (read-char-exclusive) org-remember-templates))))
9491 (tpl (car entry))
9492 (file (if (consp (cdr entry)) (nth 1 entry)))
9493 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
9494 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
9495 (v-u (concat "[" (substring v-t 1 -1) "]"))
9496 (v-U (concat "[" (substring v-T 1 -1) "]"))
9497 (v-a annotation) ; defined in `remember-mode'
9498 (v-i initial) ; defined in `remember-mode'
9499 (v-n user-full-name)
9501 (unless tpl (setq tpl "") (message "No template") (ding))
9502 (insert tpl) (goto-char (point-min))
9503 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
9504 (when (and initial (equal (match-string 0) "%i"))
9505 (save-match-data
9506 (let* ((lead (buffer-substring
9507 (point-at-bol) (match-beginning 0))))
9508 (setq v-i (mapconcat 'identity
9509 (org-split-string initial "\n")
9510 (concat "\n" lead))))))
9511 (replace-match
9512 (or (eval (intern (concat "v-" (match-string 1)))) "")
9513 t t))
9514 (let ((org-startup-folded nil)
9515 (org-startup-with-deadline-check nil))
9516 (org-mode))
9517 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
9518 (org-set-local 'org-default-notes-file file))
9519 (goto-char (point-min))
9520 (if (re-search-forward "%\\?" nil t) (replace-match "")))
9521 (let ((org-startup-folded nil)
9522 (org-startup-with-deadline-check nil))
9523 (org-mode)))
9524 (org-set-local 'org-finish-function 'remember-buffer))
9526 ;;;###autoload
9527 (defun org-remember-handler ()
9528 "Store stuff from remember.el into an org file.
9529 First prompts for an org file. If the user just presses return, the value
9530 of `org-default-notes-file' is used.
9531 Then the command offers the headings tree of the selected file in order to
9532 file the text at a specific location.
9533 You can either immediately press RET to get the note appended to the
9534 file, or you can use vertical cursor motion and visibility cycling (TAB) to
9535 find a better place. Then press RET or <left> or <right> in insert the note.
9537 Key Cursor position Note gets inserted
9538 -----------------------------------------------------------------------------
9539 RET buffer-start as level 2 heading at end of file
9540 RET on headline as sublevel of the heading at cursor
9541 RET no heading at cursor position, level taken from context.
9542 Or use prefix arg to specify level manually.
9543 <left> on headline as same level, before current heading
9544 <right> on headline as same level, after current heading
9546 So the fastest way to store the note is to press RET RET to append it to
9547 the default file. This way your current train of thought is not
9548 interrupted, in accordance with the principles of remember.el. But with
9549 little extra effort, you can push it directly to the correct location.
9551 Before being stored away, the function ensures that the text has a
9552 headline, i.e. a first line that starts with a \"*\". If not, a headline
9553 is constructed from the current date and some additional data.
9555 If the variable `org-adapt-indentation' is non-nil, the entire text is
9556 also indented so that it starts in the same column as the headline
9557 \(i.e. after the stars).
9559 See also the variable `org-reverse-note-order'."
9560 (catch 'quit
9561 (let* ((txt (buffer-substring (point-min) (point-max)))
9562 (fastp current-prefix-arg)
9563 (file (if fastp org-default-notes-file (org-get-org-file)))
9564 (visiting (find-buffer-visiting file))
9565 (org-startup-with-deadline-check nil)
9566 (org-startup-folded nil)
9567 (org-startup-align-all-tables nil)
9568 spos level indent reversed)
9569 ;; Modify text so that it becomes a nice subtree which can be inserted
9570 ;; into an org tree.
9571 (let* ((lines (split-string txt "\n"))
9572 first)
9573 ;; remove empty lines at the beginning
9574 (while (and lines (string-match "^[ \t]*\n" (car lines)))
9575 (setq lines (cdr lines)))
9576 (setq first (car lines) lines (cdr lines))
9577 (if (string-match "^\\*+" first)
9578 ;; Is already a headline
9579 (setq indent nil)
9580 ;; We need to add a headline: Use time and first buffer line
9581 (setq lines (cons first lines)
9582 first (concat "* " (current-time-string)
9583 " (" (remember-buffer-desc) ")")
9584 indent " "))
9585 (if (and org-adapt-indentation indent)
9586 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
9587 (setq txt (concat first "\n"
9588 (mapconcat 'identity lines "\n"))))
9589 ;; Find the file
9590 (if (not visiting)
9591 (find-file-noselect file))
9592 (with-current-buffer (get-file-buffer file)
9593 (save-excursion (and (goto-char (point-min))
9594 (not (re-search-forward "^\\* " nil t))
9595 (insert "\n* Notes\n")))
9596 (setq reversed (org-notes-order-reversed-p))
9597 (save-excursion
9598 (save-restriction
9599 (widen)
9600 ;; Ask the User for a location
9601 (setq spos (if fastp 1 (org-get-location
9602 (current-buffer)
9603 org-remember-help)))
9604 (if (not spos) (throw 'quit nil)) ; return nil to show we did
9605 ; not handle this note
9606 (goto-char spos)
9607 (cond ((and (bobp) (not reversed))
9608 ;; Put it at the end, as level 2
9609 (save-restriction
9610 (widen)
9611 (goto-char (point-max))
9612 (if (not (bolp)) (newline))
9613 (org-paste-subtree 2 txt)))
9614 ((and (bobp) reversed)
9615 ;; Put it at the start, as level 1
9616 (save-restriction
9617 (widen)
9618 (goto-char (point-min))
9619 (re-search-forward "^\\*" nil t)
9620 (beginning-of-line 1)
9621 (org-paste-subtree 1 txt)))
9622 ((and (org-on-heading-p nil) (not current-prefix-arg))
9623 ;; Put it below this entry, at the beg/end of the subtree
9624 (org-back-to-heading)
9625 (setq level (funcall outline-level))
9626 (if reversed
9627 (outline-end-of-heading)
9628 (outline-end-of-subtree))
9629 (if (not (bolp)) (newline))
9630 (beginning-of-line 1)
9631 (org-paste-subtree (org-get-legal-level level 1) txt))
9633 ;; Put it right there, with automatic level determined by
9634 ;; org-paste-subtree or from prefix arg
9635 (org-paste-subtree current-prefix-arg txt)))
9636 (when remember-save-after-remembering
9637 (save-buffer)
9638 (if (not visiting) (kill-buffer (current-buffer)))))))))
9639 t) ;; return t to indicate that we took care of this note.
9641 (defun org-get-org-file ()
9642 "Read a filename, with default directory `org-directory'."
9643 (let ((default (or org-default-notes-file remember-data-file)))
9644 (read-file-name (format "File name [%s]: " default)
9645 (file-name-as-directory org-directory)
9646 default)))
9648 (defun org-notes-order-reversed-p ()
9649 "Check if the current file should receive notes in reversed order."
9650 (cond
9651 ((not org-reverse-note-order) nil)
9652 ((eq t org-reverse-note-order) t)
9653 ((not (listp org-reverse-note-order)) nil)
9654 (t (catch 'exit
9655 (let ((all org-reverse-note-order)
9656 entry)
9657 (while (setq entry (pop all))
9658 (if (string-match (car entry) buffer-file-name)
9659 (throw 'exit (cdr entry))))
9660 nil)))))
9662 ;;;; Dynamic blocks
9664 (defun org-find-dblock (name)
9665 "Find the first dynamic block with name NAME in the buffer.
9666 If not found, stay at current position and return nil."
9667 (let (pos)
9668 (save-excursion
9669 (goto-char (point-min))
9670 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9671 nil t)
9672 (match-beginning 0))))
9673 (if pos (goto-char pos))
9674 pos))
9676 (defconst org-dblock-start-re
9677 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9678 "Matches the startline of a dynamic block, with parameters.")
9680 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
9681 "Matches the end of a dyhamic block.")
9683 (defun org-create-dblock (plist)
9684 "Create a dynamic block section, with parameters taken from PLIST.
9685 PLIST must containe a :name entry which is used as name of the block."
9686 (unless (bolp) (newline))
9687 (let ((name (plist-get plist :name)))
9688 (insert "#+BEGIN: " name)
9689 (while plist
9690 (if (eq (car plist) :name)
9691 (setq plist (cddr plist))
9692 (insert " " (prin1-to-string (pop plist)))))
9693 (insert "\n\n#+END:\n")
9694 (beginning-of-line -2)))
9696 (defun org-prepare-dblock ()
9697 "Prepare dynamic block for refresh.
9698 This empties the block, puts the cursor at the insert position and returns
9699 the property list including an extra property :name with the block name."
9700 (unless (looking-at org-dblock-start-re)
9701 (error "Not at a dynamic block"))
9702 (let* ((begdel (1+ (match-end 0)))
9703 (name (match-string 1))
9704 (params (append (list :name name)
9705 (read (concat "(" (match-string 3) ")")))))
9706 (unless (re-search-forward org-dblock-end-re nil t)
9707 (error "Dynamic block not terminated"))
9708 (delete-region begdel (match-beginning 0))
9709 (goto-char begdel)
9710 (open-line 1)
9711 params))
9713 (defun org-map-dblocks (&optional command)
9714 "Apply COMMAND to all dynamic blocks in the current buffer.
9715 If COMMAND is not given, use `org-update-dblock'."
9716 (let ((cmd (or command 'org-update-dblock))
9717 pos)
9718 (save-excursion
9719 (goto-char (point-min))
9720 (while (re-search-forward org-dblock-start-re nil t)
9721 (goto-char (setq pos (match-beginning 0)))
9722 (condition-case nil
9723 (funcall cmd)
9724 (error (message "Error during update of dynamic block")))
9725 (goto-char pos)
9726 (unless (re-search-forward org-dblock-end-re nil t)
9727 (error "Dynamic block not terminated"))))))
9729 (defun org-dblock-update (&optional arg)
9730 "User command for updating dynamic blocks.
9731 Update the dynamic block at point. With prefix ARG, update all dynamic
9732 blocks in the buffer."
9733 (interactive "P")
9734 (if arg
9735 (org-update-all-dblocks)
9736 (or (looking-at org-dblock-start-re)
9737 (org-beginning-of-dblock))
9738 (org-update-dblock)))
9740 (defun org-update-dblock ()
9741 "Update the dynamic block at point
9742 This means to empty the block, parse for parameters and then call
9743 the correct writing function."
9744 (let* ((pos (point))
9745 (params (org-prepare-dblock))
9746 (name (plist-get params :name))
9747 (cmd (intern (concat "org-dblock-write:" name))))
9748 (funcall cmd params)
9749 (goto-char pos)))
9751 (defun org-beginning-of-dblock ()
9752 "Find the beginning of the dynamic block at point.
9753 Error if there is no scuh block at point."
9754 (let ((pos (point))
9755 beg)
9756 (end-of-line 1)
9757 (if (and (re-search-backward org-dblock-start-re nil t)
9758 (setq beg (match-beginning 0))
9759 (re-search-forward org-dblock-end-re nil t)
9760 (> (match-end 0) pos))
9761 (goto-char beg)
9762 (goto-char pos)
9763 (error "Not in a dynamic block"))))
9765 (defun org-update-all-dblocks ()
9766 "Update all dynamic blocks in the buffer.
9767 This function can be used in a hook."
9768 (when (org-mode-p)
9769 (org-map-dblocks 'org-update-dblock)))
9772 ;;;; Completion
9774 (defun org-complete (&optional arg)
9775 "Perform completion on word at point.
9776 At the beginning of a headline, this completes TODO keywords as given in
9777 `org-todo-keywords'.
9778 If the current word is preceded by a backslash, completes the TeX symbols
9779 that are supported for HTML support.
9780 If the current word is preceded by \"#+\", completes special words for
9781 setting file options.
9782 In the line after \"#+STARTUP:, complete valid keywords.\"
9783 At all other locations, this simply calls `ispell-complete-word'."
9784 (interactive "P")
9785 (catch 'exit
9786 (let* ((end (point))
9787 (beg1 (save-excursion
9788 (skip-chars-backward "a-zA-Z_@0-9")
9789 (point)))
9790 (beg (save-excursion
9791 (skip-chars-backward "a-zA-Z0-9_:$")
9792 (point)))
9793 (confirm (lambda (x) (stringp (car x))))
9794 (camel (equal (char-before beg) ?*))
9795 (tag (equal (char-before beg1) ?:))
9796 (texp (equal (char-before beg) ?\\))
9797 (link (equal (char-before beg) ?\[))
9798 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9799 beg)
9800 "#+"))
9801 (startup (string-match "^#\\+STARTUP:.*"
9802 (buffer-substring (point-at-bol) (point))))
9803 (completion-ignore-case opt)
9804 (type nil)
9805 (tbl nil)
9806 (table (cond
9807 (opt
9808 (setq type :opt)
9809 (mapcar (lambda (x)
9810 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9811 (cons (match-string 2 x) (match-string 1 x)))
9812 (org-split-string (org-get-current-options) "\n")))
9813 (startup
9814 (setq type :startup)
9815 org-startup-options)
9816 (link (append org-link-abbrev-alist-local
9817 org-link-abbrev-alist))
9818 (texp
9819 (setq type :tex)
9820 org-html-entities)
9821 ((string-match "\\`\\*+[ \t]*\\'"
9822 (buffer-substring (point-at-bol) beg))
9823 (setq type :todo)
9824 (mapcar 'list org-todo-keywords))
9825 (camel
9826 (setq type :camel)
9827 (save-excursion
9828 (goto-char (point-min))
9829 (while (re-search-forward org-todo-line-regexp nil t)
9830 (push (list
9831 (if org-file-link-context-use-camel-case
9832 (org-make-org-heading-camel (match-string 3) t)
9833 (org-make-org-heading-search-string
9834 (match-string 3) t)))
9835 tbl)))
9836 tbl)
9837 (tag (setq type :tag beg beg1)
9838 (or org-tag-alist (org-get-buffer-tags)))
9839 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
9840 (pattern (buffer-substring-no-properties beg end))
9841 (completion (try-completion pattern table confirm)))
9842 (cond ((eq completion t)
9843 (if (equal type :opt)
9844 (insert (substring (cdr (assoc (upcase pattern) table))
9845 (length pattern)))
9846 (if (equal type :tag) (insert ":"))))
9847 ((null completion)
9848 (message "Can't find completion for \"%s\"" pattern)
9849 (ding))
9850 ((not (string= pattern completion))
9851 (delete-region beg end)
9852 (if (string-match " +$" completion)
9853 (setq completion (replace-match "" t t completion)))
9854 (insert completion)
9855 (if (get-buffer-window "*Completions*")
9856 (delete-window (get-buffer-window "*Completions*")))
9857 (if (assoc completion table)
9858 (if (eq type :todo) (insert " ")
9859 (if (eq type :tag) (insert ":"))))
9860 (if (and (equal type :opt) (assoc completion table))
9861 (message "%s" (substitute-command-keys
9862 "Press \\[org-complete] again to insert example settings"))))
9864 (message "Making completion list...")
9865 (let ((list (sort (all-completions pattern table confirm)
9866 'string<)))
9867 (with-output-to-temp-buffer "*Completions*"
9868 (condition-case nil
9869 ;; Protection needed for XEmacs and emacs 21
9870 (display-completion-list list pattern)
9871 (error (display-completion-list list)))))
9872 (message "Making completion list...%s" "done"))))))
9874 ;;;; TODO, DEADLINE, Comments
9876 (defun org-toggle-comment ()
9877 "Change the COMMENT state of an entry."
9878 (interactive)
9879 (save-excursion
9880 (org-back-to-heading)
9881 (if (looking-at (concat outline-regexp
9882 "\\( +\\<" org-comment-string "\\>\\)"))
9883 (replace-match "" t t nil 1)
9884 (if (looking-at outline-regexp)
9885 (progn
9886 (goto-char (match-end 0))
9887 (insert " " org-comment-string))))))
9889 (defvar org-last-todo-state-is-todo nil
9890 "This is non-nil when the last TODO state change led to a TODO state.
9891 If the last change removed the TODO tag or switched to DONE, then
9892 this is nil.")
9894 (defun org-todo (&optional arg)
9895 "Change the TODO state of an item.
9896 The state of an item is given by a keyword at the start of the heading,
9897 like
9898 *** TODO Write paper
9899 *** DONE Call mom
9901 The different keywords are specified in the variable `org-todo-keywords'.
9902 By default the available states are \"TODO\" and \"DONE\".
9903 So for this example: when the item starts with TODO, it is changed to DONE.
9904 When it starts with DONE, the DONE is removed. And when neither TODO nor
9905 DONE are present, add TODO at the beginning of the heading.
9907 With C-u prefix arg, use completion to determine the new state.
9908 With numeric prefix arg, switch to that state.
9910 For calling through lisp, arg is also interpreted in the following way:
9911 'none -> empty state
9912 \"\"(empty string) -> switch to empty state
9913 'done -> switch to DONE
9914 \"WAITING\" -> switch to the specified keyword, but only if it
9915 really is a member of `org-todo-keywords'."
9916 (interactive "P")
9917 (save-excursion
9918 (org-back-to-heading)
9919 (if (looking-at outline-regexp) (goto-char (match-end 0)))
9920 (or (looking-at (concat " +" org-todo-regexp " *"))
9921 (looking-at " *"))
9922 (let* ((this (match-string 1))
9923 (last-state (or this ""))
9924 (completion-ignore-case t)
9925 (member (member this org-todo-keywords))
9926 (tail (cdr member))
9927 (state (cond
9928 ((equal arg '(4))
9929 ;; Read a state with completion
9930 (completing-read "State: " (mapcar (lambda(x) (list x))
9931 org-todo-keywords)
9932 nil t))
9933 ((eq arg 'right)
9934 (if this
9935 (if tail (car tail) nil)
9936 (car org-todo-keywords)))
9937 ((eq arg 'left)
9938 (if (equal member org-todo-keywords)
9940 (if this
9941 (nth (- (length org-todo-keywords) (length tail) 2)
9942 org-todo-keywords)
9943 org-done-string)))
9944 (arg
9945 ;; user requests a specific state
9946 (cond
9947 ((equal arg "") nil)
9948 ((eq arg 'none) nil)
9949 ((eq arg 'done) (org-last org-todo-keywords))
9950 ((car (member arg org-todo-keywords)))
9951 ((nth (1- (prefix-numeric-value arg))
9952 org-todo-keywords))))
9953 ((null member) (car org-todo-keywords))
9954 ((null tail) nil) ;; -> first entry
9955 ((eq org-todo-interpretation 'sequence)
9956 (car tail))
9957 ((memq org-todo-interpretation '(type priority))
9958 (if (eq this-command last-command)
9959 (car tail)
9960 (if (> (length tail) 0) org-done-string nil)))
9961 (t nil)))
9962 (next (if state (concat " " state " ") " "))
9963 dostates)
9964 (replace-match next t t)
9965 (setq org-last-todo-state-is-todo
9966 (not (equal state org-done-string)))
9967 (when org-log-done
9968 (setq dostates (and (eq org-todo-interpretation 'sequence)
9969 (listp org-log-done) (memq 'state org-log-done)))
9970 (cond
9971 ((and state (not this))
9972 (org-add-planning-info nil nil 'closed)
9973 (and dostates (org-add-log-maybe 'state state 'findpos)))
9974 ((and state dostates)
9975 (org-add-log-maybe 'state state 'findpos))
9976 ((equal state org-done-string)
9977 ;; Planning info calls the note-setting command.
9978 (org-add-planning-info 'closed (org-current-time)
9979 (if (org-get-repeat) nil 'scheduled))
9980 (org-add-log-maybe 'done state 'findpos))))
9981 ;; Fixup tag positioning
9982 (and org-auto-align-tags (org-set-tags nil t))
9983 (run-hooks 'org-after-todo-state-change-hook)
9984 (and (equal state org-done-string) (org-auto-repeat-maybe))
9986 ;; Fixup cursor location if close to the keyword
9987 (if (and (outline-on-heading-p)
9988 (not (bolp))
9989 (save-excursion (beginning-of-line 1)
9990 (looking-at org-todo-line-regexp))
9991 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9992 (progn
9993 (goto-char (or (match-end 2) (match-end 1)))
9994 (just-one-space))))
9996 (defun org-get-repeat ()
9997 "Return the REPEAT statement of this entry."
9998 (save-match-data
9999 (save-excursion
10000 (org-back-to-heading t)
10001 (if (re-search-forward
10002 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
10003 (match-string 1)))))
10005 (defun org-show-todo-tree (arg)
10006 "Make a compact tree which shows all headlines marked with TODO.
10007 The tree will show the lines where the regexp matches, and all higher
10008 headlines above the match.
10009 With \\[universal-argument] prefix, also show the DONE entries.
10010 With a numeric prefix N, construct a sparse tree for the Nth element
10011 of `org-todo-keywords'."
10012 (interactive "P")
10013 (let ((case-fold-search nil)
10014 (kwd-re
10015 (cond ((null arg) org-not-done-regexp)
10016 ((equal arg '(4)) org-todo-regexp)
10017 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
10018 (regexp-quote (nth (1- (prefix-numeric-value arg))
10019 org-todo-keywords)))
10020 (t (error "Invalid prefix argument: %s" arg)))))
10021 (message "%d TODO entries found"
10022 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
10024 (defun org-deadline ()
10025 "Insert the DEADLINE: string to make a deadline.
10026 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
10027 to modify it to the correct date."
10028 (interactive)
10029 (org-add-planning-info 'deadline nil 'closed))
10031 (defun org-schedule ()
10032 "Insert the SCHEDULED: string to schedule a TODO item.
10033 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
10034 to modify it to the correct date."
10035 (interactive)
10036 (org-add-planning-info 'scheduled nil 'closed))
10038 (defun org-add-planning-info (what &optional time &rest remove)
10039 "Insert new timestamp with keyword in the line directly after the headline.
10040 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10041 If non is given, the user is prompted for a date.
10042 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10043 be removed."
10044 (interactive)
10045 (when what (setq time (or time (org-read-date nil 'to-time))))
10046 (when (and org-insert-labeled-timestamps-at-point
10047 (member what '(scheduled deadline)))
10048 (insert
10049 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10050 (org-insert-time-stamp time)
10051 (setq what nil))
10052 (save-excursion
10053 (save-restriction
10054 (let (col list elt ts buffer-invisibility-spec)
10055 (org-back-to-heading t)
10056 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10057 (goto-char (match-end 1))
10058 (setq col (current-column))
10059 (goto-char (1+ (match-end 0)))
10060 (if (and (not (looking-at outline-regexp))
10061 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10062 "[^\r\n]*"))
10063 (not (equal (match-string 1) org-clock-string)))
10064 (narrow-to-region (match-beginning 0) (match-end 0))
10065 (insert "\n")
10066 (backward-char 1)
10067 (narrow-to-region (point) (point))
10068 (indent-to-column col))
10069 ;; Check if we have to remove something.
10070 (setq list (cons what remove))
10071 (while list
10072 (setq elt (pop list))
10073 (goto-char (point-min))
10074 (when (or (and (eq elt 'scheduled)
10075 (re-search-forward org-scheduled-time-regexp nil t))
10076 (and (eq elt 'deadline)
10077 (re-search-forward org-deadline-time-regexp nil t))
10078 (and (eq elt 'closed)
10079 (re-search-forward org-closed-time-regexp nil t)))
10080 (replace-match "")
10081 (if (looking-at "--+<[^>]+>") (replace-match ""))
10082 (if (looking-at " +") (replace-match ""))))
10083 (goto-char (point-max))
10084 (when what
10085 (insert
10086 (if (not (equal (char-before) ?\ )) " " "")
10087 (cond ((eq what 'scheduled) org-scheduled-string)
10088 ((eq what 'deadline) org-deadline-string)
10089 ((eq what 'closed) org-closed-string))
10090 " ")
10091 (org-insert-time-stamp time nil (eq what 'closed))
10092 (end-of-line 1))
10093 (goto-char (point-min))
10094 (widen)
10095 (if (looking-at "[ \t]+\r?\n")
10096 (replace-match ""))
10097 ts))))
10099 (defvar org-log-note-marker (make-marker))
10100 (defvar org-log-note-purpose nil)
10101 (defvar org-log-note-state nil)
10102 (defvar org-log-note-window-configuration nil)
10103 (defvar org-log-note-return-to (make-marker))
10104 (defvar org-log-post-message nil
10105 "Message to be displayed after a log note has been stored.
10106 The auto-repeater uses this.")
10108 (defun org-add-log-maybe (&optional purpose state findpos)
10109 (save-excursion
10110 (when (and (listp org-log-done)
10111 (memq purpose org-log-done))
10112 (when findpos
10113 (org-back-to-heading t)
10114 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10115 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10116 "[^\r\n]*\\)?"))
10117 (goto-char (match-end 0)))
10118 (move-marker org-log-note-marker (point))
10119 (setq org-log-note-purpose purpose)
10120 (setq org-log-note-state state)
10121 (add-hook 'post-command-hook 'org-add-log-note 'append))))
10123 (defun org-add-log-note (&optional purpose)
10124 "Pop up a window for taking a note, and add this note later at point."
10125 (remove-hook 'post-command-hook 'org-add-log-note)
10126 (setq org-log-note-window-configuration (current-window-configuration))
10127 (delete-other-windows)
10128 (move-marker org-log-note-return-to (point))
10129 (switch-to-buffer (marker-buffer org-log-note-marker))
10130 (goto-char org-log-note-marker)
10131 (switch-to-buffer-other-window "*Org Note*")
10132 (erase-buffer)
10133 (let ((org-inhibit-startup t)) (org-mode))
10134 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
10135 (cond
10136 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10137 ((eq org-log-note-purpose 'done) "closed todo item")
10138 ((eq org-log-note-purpose 'state) "state change")
10139 (t (error "This should not happen")))))
10140 (org-set-local 'org-finish-function 'org-store-log-note))
10142 (defun org-store-log-note ()
10143 "Finish taking a log note, and insert it to where it belongs."
10144 (let ((txt (buffer-string))
10145 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10146 lines ind)
10147 (kill-buffer (current-buffer))
10148 (if (string-match "^#.*\n[ \t\n]*" txt)
10149 (setq txt (replace-match "" t t txt)))
10150 (if (string-match "\\s-+\\'" txt)
10151 (setq txt (replace-match "" t t txt)))
10152 (setq lines (org-split-string txt "\n"))
10153 (when (and note (string-match "\\S-" note))
10154 (setq note
10155 (org-replace-escapes
10156 note
10157 (list (cons "%u" (user-login-name))
10158 (cons "%U" user-full-name)
10159 (cons "%t" (format-time-string
10160 (org-time-stamp-format 'long 'inactive)
10161 (current-time)))
10162 (cons "%s" (if org-log-note-state
10163 (concat "\"" org-log-note-state "\"")
10164 "")))))
10165 (if lines (setq note (concat note " \\\\")))
10166 (push note lines))
10167 (save-excursion
10168 (set-buffer (marker-buffer org-log-note-marker))
10169 (save-excursion
10170 (goto-char org-log-note-marker)
10171 (move-marker org-log-note-marker nil)
10172 (end-of-line 1)
10173 (if (not (bolp)) (insert "\n")) (indent-relative nil)
10174 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
10175 (insert " - " (pop lines))
10176 (while lines
10177 (insert "\n" ind (pop lines))))))
10178 (set-window-configuration org-log-note-window-configuration)
10179 (with-current-buffer (marker-buffer org-log-note-return-to)
10180 (goto-char org-log-note-return-to))
10181 (move-marker org-log-note-return-to nil)
10182 (and org-log-post-message (message org-log-post-message)))
10184 (defvar org-occur-highlights nil)
10185 (make-variable-buffer-local 'org-occur-highlights)
10187 (defun org-occur (regexp &optional keep-previous callback)
10188 "Make a compact tree which shows all matches of REGEXP.
10189 The tree will show the lines where the regexp matches, and all higher
10190 headlines above the match. It will also show the heading after the match,
10191 to make sure editing the matching entry is easy.
10192 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10193 call to `org-occur' will be kept, to allow stacking of calls to this
10194 command.
10195 If CALLBACK is non-nil, it is a function which is called to confirm
10196 that the match should indeed be shown."
10197 (interactive "sRegexp: \nP")
10198 (or keep-previous (org-remove-occur-highlights nil nil t))
10199 (let ((cnt 0))
10200 (save-excursion
10201 (goto-char (point-min))
10202 (if (or (not keep-previous) ; do not want to keep
10203 (not org-occur-highlights)) ; no previous matches
10204 ;; hide everything
10205 (org-overview))
10206 (while (re-search-forward regexp nil t)
10207 (when (or (not callback)
10208 (save-match-data (funcall callback)))
10209 (setq cnt (1+ cnt))
10210 (org-highlight-new-match (match-beginning 0) (match-end 0))
10211 (org-show-context 'occur-tree))))
10212 (when org-remove-highlights-with-change
10213 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10214 nil 'local))
10215 (unless org-sparse-tree-open-archived-trees
10216 (org-hide-archived-subtrees (point-min) (point-max)))
10217 (run-hooks 'org-occur-hook)
10218 (if (interactive-p)
10219 (message "%d match(es) for regexp %s" cnt regexp))
10220 cnt))
10222 ;; FIXME: Remove the siblings argument, or add args for the others too?
10223 (defun org-show-context (&optional key siblings)
10224 "Make sure point and context and visible.
10225 How much context is shown depends upon the variables
10226 `org-show-hierarchy-above' and `org-show-following-heading'.
10227 When SIBLINGS is non-nil, show all siblings on each hierarchy level."
10228 (let ((heading-p (org-on-heading-p t))
10229 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10230 (following-p (org-get-alist-option org-show-following-heading key))
10231 (siblings-p (or siblings (org-get-alist-option org-show-siblings key))))
10232 (catch 'exit
10233 ;; Show heading or entry text
10234 (if heading-p
10235 (org-flag-heading nil) ; only show the heading
10236 (and (or (org-invisible-p) (org-invisible-p2))
10237 (org-show-hidden-entry))) ; show entire entry
10238 (when following-p
10239 ;; Show next sibling, or heading below text
10240 (save-excursion
10241 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10242 (org-flag-heading nil))))
10243 (when siblings-p (org-show-siblings))
10244 (when hierarchy-p
10245 ;; show all higher headings, possibly with siblings
10246 (save-excursion
10247 (while (and (condition-case nil
10248 (progn (org-up-heading-all 1) t)
10249 (error nil))
10250 (not (bobp)))
10251 (org-flag-heading nil)
10252 (when siblings-p (org-show-siblings))))))))
10254 (defun org-reveal (&optional siblings)
10255 "Show current entry, hierarchy above it, and the following headline.
10256 This can be used to show a consistent set of context around locations
10257 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10258 not t for the search context.
10260 With optional argument SIBLINGS, on each level of the hierarchy all
10261 siblings are shown. This repairs the tree structure to what it would
10262 look like when opened with hierarchical calls to `org-cycle'."
10263 (interactive "P")
10264 (let ((org-show-hierarchy-above t)
10265 (org-show-following-heading t))
10266 (org-show-context nil siblings)))
10268 (defun org-highlight-new-match (beg end)
10269 "Highlight from BEG to END and mark the highlight is an occur headline."
10270 (let ((ov (org-make-overlay beg end)))
10271 (org-overlay-put ov 'face 'secondary-selection)
10272 (push ov org-occur-highlights)))
10274 (defvar org-inhibit-highlight-removal nil)
10275 (defun org-remove-occur-highlights (&optional beg end noremove)
10276 "Remove the occur highlights from the buffer.
10277 BEG and END are ignored. If NOREMOVE is nil, remove this function
10278 from the `before-change-functions' in the current buffer."
10279 (interactive)
10280 (unless org-inhibit-highlight-removal
10281 (mapc 'org-delete-overlay org-occur-highlights)
10282 (setq org-occur-highlights nil)
10283 (unless noremove
10284 (remove-hook 'before-change-functions
10285 'org-remove-occur-highlights 'local))))
10287 ;;;; Priorities
10289 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
10290 "Regular expression matching the priority indicator.")
10292 (defvar org-remove-priority-next-time nil)
10294 (defun org-priority-up ()
10295 "Increase the priority of the current item."
10296 (interactive)
10297 (org-priority 'up))
10299 (defun org-priority-down ()
10300 "Decrease the priority of the current item."
10301 (interactive)
10302 (org-priority 'down))
10304 (defun org-priority (&optional action)
10305 "Change the priority of an item by ARG.
10306 ACTION can be set, up, or down."
10307 (interactive)
10308 (setq action (or action 'set))
10309 (let (current new news have remove)
10310 (save-excursion
10311 (org-back-to-heading)
10312 (if (looking-at org-priority-regexp)
10313 (setq current (string-to-char (match-string 2))
10314 have t)
10315 (setq current org-default-priority))
10316 (cond
10317 ((eq action 'set)
10318 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
10319 (setq new (read-char-exclusive))
10320 (cond ((equal new ?\ ) (setq remove t))
10321 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
10322 (error "Priority must be between `%c' and `%c'"
10323 ?A org-lowest-priority))))
10324 ((eq action 'up)
10325 (setq new (1- current)))
10326 ((eq action 'down)
10327 (setq new (1+ current)))
10328 (t (error "Invalid action")))
10329 (setq new (min (max ?A (upcase new)) org-lowest-priority))
10330 (setq news (format "%c" new))
10331 (if have
10332 (if remove
10333 (replace-match "" t t nil 1)
10334 (replace-match news t t nil 2))
10335 (if remove
10336 (error "No priority cookie found in line")
10337 (looking-at org-todo-line-regexp)
10338 (if (match-end 2)
10339 (progn
10340 (goto-char (match-end 2))
10341 (insert " [#" news "]"))
10342 (goto-char (match-beginning 3))
10343 (insert "[#" news "] ")))))
10344 (if remove
10345 (message "Priority removed")
10346 (message "Priority of current item set to %s" news))))
10349 (defun org-get-priority (s)
10350 "Find priority cookie and return priority."
10351 (save-match-data
10352 (if (not (string-match org-priority-regexp s))
10353 (* 1000 (- org-lowest-priority org-default-priority))
10354 (* 1000 (- org-lowest-priority
10355 (string-to-char (match-string 2 s)))))))
10357 ;;;; Tags
10359 (defun org-scan-tags (action matcher &optional todo-only)
10360 "Scan headline tags with inheritance and produce output ACTION.
10361 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
10362 evaluated, testing if a given set of tags qualifies a headline for
10363 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
10364 are included in the output."
10365 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
10366 (mapconcat 'regexp-quote
10367 (nreverse (cdr (reverse org-todo-keywords)))
10368 "\\|")
10369 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
10370 (props (list 'face nil
10371 'done-face 'org-done
10372 'undone-face nil
10373 'mouse-face 'highlight
10374 'org-not-done-regexp org-not-done-regexp
10375 'keymap org-agenda-keymap
10376 'help-echo
10377 (format "mouse-2 or RET jump to org file %s"
10378 (abbreviate-file-name buffer-file-name))))
10379 (case-fold-search nil)
10380 lspos
10381 tags tags-list tags-alist (llast 0) rtn level category i txt
10382 todo marker entry)
10383 (save-excursion
10384 (goto-char (point-min))
10385 (when (eq action 'sparse-tree) (org-overview))
10386 (while (re-search-forward re nil t)
10387 (catch :skip
10388 (setq todo (if (match-end 1) (match-string 2))
10389 tags (if (match-end 4) (match-string 4)))
10390 (goto-char (setq lspos (1+ (match-beginning 0))))
10391 (setq level (funcall outline-level)
10392 category (org-get-category))
10393 (setq i llast llast level)
10394 ;; remove tag lists from same and sublevels
10395 (while (>= i level)
10396 (when (setq entry (assoc i tags-alist))
10397 (setq tags-alist (delete entry tags-alist)))
10398 (setq i (1- i)))
10399 ;; add the nex tags
10400 (when tags
10401 (setq tags (mapcar 'downcase (org-split-string tags ":"))
10402 tags-alist
10403 (cons (cons level tags) tags-alist)))
10404 ;; compile tags for current headline
10405 (setq tags-list
10406 (if org-use-tag-inheritance
10407 (apply 'append (mapcar 'cdr tags-alist))
10408 tags))
10409 (when (and (or (not todo-only) todo)
10410 (eval matcher)
10411 (or (not org-agenda-skip-archived-trees)
10412 (not (member org-archive-tag tags-list))))
10413 (and (eq action 'agenda) (org-agenda-skip))
10414 ;; list this headline
10415 (if (eq action 'sparse-tree)
10416 (progn
10417 (org-show-context 'tags-tree))
10418 (setq txt (org-format-agenda-item
10420 (concat
10421 (if org-tags-match-list-sublevels
10422 (make-string (1- level) ?.) "")
10423 (org-get-heading))
10424 category tags-list))
10425 (goto-char lspos)
10426 (setq marker (org-agenda-new-marker))
10427 (org-add-props txt props
10428 'org-marker marker 'org-hd-marker marker 'category category)
10429 (push txt rtn))
10430 ;; if we are to skip sublevels, jump to end of subtree
10431 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
10432 (when (and (eq action 'sparse-tree)
10433 (not org-sparse-tree-open-archived-trees))
10434 (org-hide-archived-subtrees (point-min) (point-max)))
10435 (nreverse rtn)))
10437 (defvar todo-only) ;; dynamically scoped
10439 (defun org-tags-sparse-tree (&optional todo-only match)
10440 "Create a sparse tree according to tags string MATCH.
10441 MATCH can contain positive and negative selection of tags, like
10442 \"+WORK+URGENT-WITHBOSS\".
10443 If optional argument TODO_ONLY is non-nil, only select lines that are
10444 also TODO lines."
10445 (interactive "P")
10446 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10448 (defun org-make-tags-matcher (match)
10449 "Create the TAGS//TODO matcher form for the selection string MATCH."
10450 ;; todo-only is scoped dynamically into this function, and the function
10451 ;; may change it it the matcher asksk for it.
10452 (unless match
10453 ;; Get a new match request, with completion
10454 (setq org-last-tags-completion-table
10455 (or org-tag-alist
10456 org-last-tags-completion-table))
10457 (setq match (completing-read
10458 "Match: " 'org-tags-completion-function nil nil nil
10459 'org-tags-history))) ; FIXME: Separate history for this?
10461 ;; Parse the string and create a lisp form
10462 (let ((match0 match)
10463 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[A-Za-z_@0-9]+\\)")
10464 minus tag mm
10465 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10466 orterms term orlist re-p level-p)
10467 (if (string-match "/+" match)
10468 ;; match contains also a todo-matching request
10469 (progn
10470 (setq tagsmatch (substring match 0 (match-beginning 0))
10471 todomatch (substring match (match-end 0)))
10472 (if (string-match "^!" todomatch)
10473 (setq todo-only t todomatch (substring todomatch 1)))
10474 (if (string-match "^\\s-*$" todomatch)
10475 (setq todomatch nil)))
10476 ;; only matching tags
10477 (setq tagsmatch match todomatch nil))
10479 ;; Make the tags matcher
10480 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10481 (setq tagsmatcher t)
10482 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10483 (while (setq term (pop orterms))
10484 (while (and (equal (substring term -1) "\\") orterms)
10485 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10486 (while (string-match re term)
10487 (setq minus (and (match-end 1)
10488 (equal (match-string 1 term) "-"))
10489 tag (match-string 2 term)
10490 re-p (equal (string-to-char tag) ?{)
10491 level-p (match-end 3)
10492 mm (cond
10493 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10494 (level-p `(= level ,(string-to-number
10495 (match-string 3 term))))
10496 (t `(member ,(downcase tag) tags-list)))
10497 mm (if minus (list 'not mm) mm)
10498 term (substring term (match-end 0)))
10499 (push mm tagsmatcher))
10500 (push (if (> (length tagsmatcher) 1)
10501 (cons 'and tagsmatcher)
10502 (car tagsmatcher))
10503 orlist)
10504 (setq tagsmatcher nil))
10505 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
10507 ;; Make the todo matcher
10508 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10509 (setq todomatcher t)
10510 (setq orterms (org-split-string todomatch "|") orlist nil)
10511 (while (setq term (pop orterms))
10512 (while (string-match re term)
10513 (setq minus (and (match-end 1)
10514 (equal (match-string 1 term) "-"))
10515 kwd (match-string 2 term)
10516 re-p (equal (string-to-char kwd) ?{)
10517 term (substring term (match-end 0))
10518 mm (if re-p
10519 `(string-match ,(substring kwd 1 -1) todo)
10520 (list 'equal 'todo kwd))
10521 mm (if minus (list 'not mm) mm))
10522 (push mm todomatcher))
10523 (push (if (> (length todomatcher) 1)
10524 (cons 'and todomatcher)
10525 (car todomatcher))
10526 orlist)
10527 (setq todomatcher nil))
10528 (setq todomatcher (if (> (length orlist) 1)
10529 (cons 'or orlist) (car orlist))))
10531 ;; Return the string and lisp forms of the matcher
10532 (setq matcher (if todomatcher
10533 (list 'and tagsmatcher todomatcher)
10534 tagsmatcher))
10535 (cons match0 matcher)))
10537 (defun org-match-any-p (re list)
10538 "Does re match any element of list?"
10539 (setq list (mapcar (lambda (x) (string-match re x)) list))
10540 (delq nil list))
10542 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
10543 (defvar org-tags-overlay (org-make-overlay 1 1))
10544 (org-detach-overlay org-tags-overlay)
10546 (defun org-set-tags (&optional arg just-align)
10547 "Set the tags for the current headline.
10548 With prefix ARG, realign all tags in headings in the current buffer."
10549 (interactive "P")
10550 (let* ((re (concat "^" outline-regexp))
10551 (current (org-get-tags))
10552 table current-tags inherited-tags ; computed below when needed
10553 tags p0 c0 c1 rpl)
10554 (if arg
10555 (save-excursion
10556 (goto-char (point-min))
10557 (let (buffer-invisibility-spec) ; Emacs 21 compatibility
10558 (while (re-search-forward re nil t)
10559 (org-set-tags nil t)
10560 (end-of-line 1)))
10561 (message "All tags realigned to column %d" org-tags-column))
10562 (if just-align
10563 (setq tags current)
10564 ;; Get a new set of tags from the user
10565 (setq table (or org-tag-alist (org-get-buffer-tags))
10566 org-last-tags-completion-table table
10567 current-tags (org-split-string current ":")
10568 inherited-tags (nreverse
10569 (nthcdr (length current-tags)
10570 (nreverse (org-get-tags-at))))
10571 tags
10572 (if (or (eq t org-use-fast-tag-selection)
10573 (and org-use-fast-tag-selection
10574 (delq nil (mapcar 'cdr table))))
10575 (org-fast-tag-selection current-tags inherited-tags table)
10576 (let ((org-add-colon-after-tag-completion t))
10577 (org-trim
10578 (completing-read "Tags: " 'org-tags-completion-function
10579 nil nil current 'org-tags-history)))))
10580 (while (string-match "[-+&]+" tags)
10581 ;; No boolean logic, just a list
10582 (setq tags (replace-match ":" t t tags))))
10583 (if (string-match "\\`[\t ]*\\'" tags)
10584 (setq tags "")
10585 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10586 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10588 ;; Insert new tags at the correct column
10589 (beginning-of-line 1)
10590 (if (re-search-forward
10591 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10592 (point-at-eol) t)
10593 (progn
10594 (if (equal tags "")
10595 (setq rpl "")
10596 (goto-char (match-beginning 0))
10597 (setq c0 (current-column) p0 (point)
10598 c1 (max (1+ c0) (if (> org-tags-column 0)
10599 org-tags-column
10600 (- (- org-tags-column) (length tags))))
10601 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10602 (replace-match rpl)
10603 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
10604 tags)
10605 (error "Tags alignment failed")))))
10607 (defun org-tags-completion-function (string predicate &optional flag)
10608 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10609 (confirm (lambda (x) (stringp (car x)))))
10610 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10611 (setq s1 (match-string 1 string)
10612 s2 (match-string 2 string))
10613 (setq s1 "" s2 string))
10614 (cond
10615 ((eq flag nil)
10616 ;; try completion
10617 (setq rtn (try-completion s2 ctable confirm))
10618 (if (stringp rtn)
10619 (concat s1 s2 (substring rtn (length s2))
10620 (if (and org-add-colon-after-tag-completion
10621 (assoc rtn ctable))
10622 ":" "")))
10624 ((eq flag t)
10625 ;; all-completions
10626 (all-completions s2 ctable confirm)
10628 ((eq flag 'lambda)
10629 ;; exact match?
10630 (assoc s2 ctable)))
10633 (defun org-fast-tag-insert (kwd tags face &optional end)
10634 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
10635 (insert (format "%-12s" (concat kwd ":"))
10636 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10637 (or end "")))
10639 (defun org-fast-tag-show-exit (flag)
10640 (save-excursion
10641 (goto-line 3)
10642 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10643 (replace-match ""))
10644 (when flag
10645 (end-of-line 1)
10646 (move-to-column (- (window-width) 19) t)
10647 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10649 (defun org-set-current-tags-overlay (current prefix)
10650 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10651 (if (featurep 'xemacs)
10652 (org-overlay-display org-tags-overlay (concat prefix s)
10653 'secondary-selection)
10654 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10655 (org-overlay-display org-tags-overlay (concat prefix s)))))
10657 (defun org-fast-tag-selection (current inherited table)
10658 "Fast tag selection with single keys.
10659 CURRENT is the current list of tags in the headline, INHERITED is the
10660 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10661 possibly with grouping information.
10662 If the keys are nil, a-z are automatically assigned.
10663 Returns the new tags string, or nil to not change the current settings."
10664 (let* ((maxlen (apply 'max (mapcar
10665 (lambda (x)
10666 (if (stringp (car x)) (string-width (car x)) 0))
10667 table)))
10668 (buf (current-buffer))
10669 (buffer-tags nil)
10670 (fwidth (+ maxlen 3 1 3))
10671 (ncol (/ (- (window-width) 4) fwidth))
10672 (i-face 'org-done)
10673 (c-face 'org-tag)
10674 tg cnt e c char c1 c2 ntable tbl rtn
10675 ov-start ov-end ov-prefix
10676 (exit-after-next org-fast-tag-selection-single-key)
10677 groups ingroup)
10678 (save-excursion
10679 (beginning-of-line 1)
10680 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
10681 (setq ov-start (match-beginning 1)
10682 ov-end (match-end 1)
10683 ov-prefix "")
10684 (setq ov-start (1- (point-at-eol))
10685 ov-end (1+ ov-start))
10686 (skip-chars-forward "^\n\r")
10687 (setq ov-prefix
10688 (concat
10689 (buffer-substring (1- (point)) (point))
10690 (if (> (current-column) org-tags-column)
10692 (make-string (- org-tags-column (current-column)) ?\ ))))))
10693 (org-move-overlay org-tags-overlay ov-start ov-end)
10694 (save-window-excursion
10695 ;; FIXME: would it be better to keep the other windows?
10696 ;; How about fast tag selection keeping all windows? Expert mode?
10697 (delete-other-windows)
10698 (split-window-vertically)
10699 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
10700 (erase-buffer)
10701 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10702 (org-fast-tag-insert "Current" current c-face "\n\n")
10703 (org-fast-tag-show-exit exit-after-next)
10704 (org-set-current-tags-overlay current ov-prefix)
10705 (setq tbl table char ?a cnt 0)
10706 (while (setq e (pop tbl))
10707 (cond
10708 ((equal e '(:startgroup))
10709 (push '() groups) (setq ingroup t)
10710 (when (not (= cnt 0))
10711 (setq cnt 0)
10712 (insert "\n"))
10713 (insert "{ "))
10714 ((equal e '(:endgroup))
10715 (setq ingroup nil cnt 0)
10716 (insert "}\n"))
10718 (setq tg (car e) c2 nil)
10719 (if (cdr e)
10720 (setq c (cdr e))
10721 ;; automatically assign a character.
10722 (setq c1 (string-to-char
10723 (downcase (substring
10724 tg (if (= (string-to-char tg) ?@) 1 0)))))
10725 (if (or (rassoc c1 ntable) (rassoc c1 table))
10726 (while (or (rassoc char ntable) (rassoc char table))
10727 (setq char (1+ char)))
10728 (setq c2 c1))
10729 (setq c (or c2 char)))
10730 (if ingroup (push tg (car groups)))
10731 (setq tg (org-add-props tg nil 'face
10732 (cond
10733 ((member tg current) c-face)
10734 ((member tg inherited) i-face)
10735 (t nil))))
10736 (if (and (= cnt 0) (not ingroup)) (insert " "))
10737 (insert "[" c "] " tg (make-string
10738 (- fwidth 4 (length tg)) ?\ ))
10739 (push (cons tg c) ntable)
10740 (when (= (setq cnt (1+ cnt)) ncol)
10741 (insert "\n")
10742 (if ingroup (insert " "))
10743 (setq cnt 0)))))
10744 (setq ntable (nreverse ntable))
10745 (insert "\n")
10746 (goto-char (point-min))
10747 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
10748 (setq rtn
10749 (catch 'exit
10750 (while t
10751 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [C-c]: multi%s"
10752 (if groups " [!] no groups" ""))
10753 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10754 (cond
10755 ((= c ?\r) (throw 'exit t))
10756 ((= c ?!)
10757 (setq groups nil)
10758 (goto-char (point-min))
10759 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10760 ((= c ?\C-c)
10761 (org-fast-tag-show-exit
10762 (setq exit-after-next (not exit-after-next))))
10763 ((or (= c ?\C-g)
10764 (and (= c ?q) (not (rassoc c ntable))))
10765 (org-detach-overlay org-tags-overlay)
10766 (setq quit-flag t))
10767 ((= c ?\ )
10768 (setq current nil)
10769 (if exit-after-next (setq exit-after-next 'now)))
10770 ((= c ?\t)
10771 (condition-case nil
10772 (setq tg (completing-read
10773 "Tag: "
10774 (or buffer-tags
10775 (with-current-buffer buf
10776 (org-get-buffer-tags)))))
10777 (quit (setq tg "")))
10778 (when (string-match "\\S-" tg)
10779 (add-to-list 'buffer-tags (list tg))
10780 (if (member tg current)
10781 (setq current (delete tg current))
10782 (push tg current)))
10783 (if exit-after-next (setq exit-after-next 'now)))
10784 ((setq e (rassoc c ntable) tg (car e))
10785 (if (member tg current)
10786 (setq current (delete tg current))
10787 (loop for g in groups do
10788 (if (member tg g)
10789 (mapcar (lambda (x)
10790 (setq current (delete x current)))
10791 g)))
10792 (push tg current))
10793 (if exit-after-next (setq exit-after-next 'now))))
10795 ;; Create a sorted list
10796 (setq current
10797 (sort current
10798 (lambda (a b)
10799 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10800 (if (eq exit-after-next 'now) (throw 'exit t))
10801 (goto-char (point-min))
10802 (beginning-of-line 2)
10803 (delete-region (point) (point-at-eol))
10804 (org-fast-tag-insert "Current" current c-face)
10805 (org-set-current-tags-overlay current ov-prefix)
10806 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
10807 (setq tg (match-string 1))
10808 (add-text-properties (match-beginning 1) (match-end 1)
10809 (list 'face
10810 (cond
10811 ((member tg current) c-face)
10812 ((member tg inherited) i-face)
10813 (t nil)))))
10814 (goto-char (point-min)))))
10815 (org-detach-overlay org-tags-overlay)
10816 (if rtn
10817 (mapconcat 'identity current ":")
10818 nil))))
10820 (defun org-get-tags ()
10821 "Get the TAGS string in the current headline."
10822 (unless (org-on-heading-p t)
10823 (error "Not on a heading"))
10824 (save-excursion
10825 (beginning-of-line 1)
10826 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
10827 (org-match-string-no-properties 1)
10828 "")))
10830 (defun org-get-buffer-tags ()
10831 "Get a table of all tags used in the buffer, for completion."
10832 (let (tags)
10833 (save-excursion
10834 (goto-char (point-min))
10835 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
10836 (mapc (lambda (x) (add-to-list 'tags x))
10837 (org-split-string (org-match-string-no-properties 1) ":"))))
10838 (mapcar 'list tags)))
10840 ;;;; Timestamps
10842 (defvar org-last-changed-timestamp nil)
10843 (defvar org-time-was-given) ; dynamically scoped parameter
10844 (defvar org-ts-what) ; dynamically scoped parameter
10846 (defun org-time-stamp (arg)
10847 "Prompt for a date/time and insert a time stamp.
10848 If the user specifies a time like HH:MM, or if this command is called
10849 with a prefix argument, the time stamp will contain date and time.
10850 Otherwise, only the date will be included. All parts of a date not
10851 specified by the user will be filled in from the current date/time.
10852 So if you press just return without typing anything, the time stamp
10853 will represent the current date/time. If there is already a timestamp
10854 at the cursor, it will be modified."
10855 (interactive "P")
10856 (let (org-time-was-given time)
10857 (cond
10858 ((and (org-at-timestamp-p)
10859 (eq last-command 'org-time-stamp)
10860 (eq this-command 'org-time-stamp))
10861 (insert "--")
10862 (setq time (let ((this-command this-command))
10863 (org-read-date arg 'totime)))
10864 (org-insert-time-stamp time (or org-time-was-given arg)))
10865 ((org-at-timestamp-p)
10866 (setq time (let ((this-command this-command))
10867 (org-read-date arg 'totime)))
10868 (when (org-at-timestamp-p) ; just to get the match data
10869 (replace-match "")
10870 (setq org-last-changed-timestamp
10871 (org-insert-time-stamp time (or org-time-was-given arg))))
10872 (message "Timestamp updated"))
10874 (setq time (let ((this-command this-command))
10875 (org-read-date arg 'totime)))
10876 (org-insert-time-stamp time (or org-time-was-given arg))))))
10878 (defun org-time-stamp-inactive (&optional arg)
10879 "Insert an inactive time stamp.
10880 An inactive time stamp is enclosed in square brackets instead of angle
10881 brackets. It is inactive in the sense that it does not trigger agenda entries,
10882 does not link to the calendar and cannot be changed with the S-cursor keys.
10883 So these are more for recording a certain time/date."
10884 (interactive "P")
10885 (let (org-time-was-given time)
10886 (setq time (org-read-date arg 'totime))
10887 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
10889 (defvar org-date-ovl (org-make-overlay 1 1))
10890 (org-overlay-put org-date-ovl 'face 'org-warning)
10891 (org-detach-overlay org-date-ovl)
10893 (defvar org-ans1) ; dynamically scoped parameter
10894 (defvar org-ans2) ; dynamically scoped parameter
10896 (defun org-read-date (&optional with-time to-time from-string)
10897 "Read a date and make things smooth for the user.
10898 The prompt will suggest to enter an ISO date, but you can also enter anything
10899 which will at least partially be understood by `parse-time-string'.
10900 Unrecognized parts of the date will default to the current day, month, year,
10901 hour and minute. For example,
10902 3-2-5 --> 2003-02-05
10903 feb 15 --> currentyear-02-15
10904 sep 12 9 --> 2009-09-12
10905 12:45 --> today 12:45
10906 22 sept 0:34 --> currentyear-09-22 0:34
10907 12 --> currentyear-currentmonth-12
10908 Fri --> nearest Friday (today or later)
10909 +4 --> four days from today (only if +N is the only thing given)
10910 etc.
10911 The function understands only English month and weekday abbreviations,
10912 but this can be configured with the variables `parse-time-months' and
10913 `parse-time-weekdays'.
10915 While prompting, a calendar is popped up - you can also select the
10916 date with the mouse (button 1). The calendar shows a period of three
10917 months. To scroll it to other months, use the keys `>' and `<'.
10918 If you don't like the calendar, turn it off with
10919 \(setq org-popup-calendar-for-date-prompt nil)
10921 With optional argument TO-TIME, the date will immediately be converted
10922 to an internal time.
10923 With an optional argument WITH-TIME, the prompt will suggest to also
10924 insert a time. Note that when WITH-TIME is not set, you can still
10925 enter a time, and this function will inform the calling routine about
10926 this change. The calling routine may then choose to change the format
10927 used to insert the time stamp into the buffer to include the time."
10928 (require 'parse-time)
10929 (let* ((org-time-stamp-rounding-minutes
10930 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
10931 (ct (org-current-time))
10932 (default-time
10933 ;; Default time is either today, or, when entering a range,
10934 ;; the range start.
10935 (if (save-excursion
10936 (re-search-backward
10937 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10938 (- (point) 20) t))
10939 (apply
10940 'encode-time
10941 (mapcar (lambda(x) (or x 0))
10942 (parse-time-string (match-string 1))))
10943 ct))
10944 (calendar-move-hook nil)
10945 (view-diary-entries-initially nil)
10946 (view-calendar-holidays-initially nil)
10947 (timestr (format-time-string
10948 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
10949 (prompt (format "YYYY-MM-DD [%s]: " timestr))
10950 ans org-ans1 org-ans2 (deltadays 0)
10951 second minute hour day month year tl wday wday1)
10953 (cond
10954 (from-string (setq ans from-string))
10955 (org-popup-calendar-for-date-prompt
10956 (save-excursion
10957 (save-window-excursion
10958 (calendar)
10959 (calendar-forward-day (- (time-to-days default-time)
10960 (calendar-absolute-from-gregorian
10961 (calendar-current-date))))
10962 (org-eval-in-calendar nil)
10963 (let* ((old-map (current-local-map))
10964 (map (copy-keymap calendar-mode-map))
10965 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10966 (define-key map (kbd "RET") 'org-calendar-select)
10967 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
10968 'org-calendar-select-mouse)
10969 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
10970 'org-calendar-select-mouse)
10971 (define-key minibuffer-local-map [(meta shift left)]
10972 (lambda () (interactive)
10973 (org-eval-in-calendar '(calendar-backward-month 1))))
10974 (define-key minibuffer-local-map [(meta shift right)]
10975 (lambda () (interactive)
10976 (org-eval-in-calendar '(calendar-forward-month 1))))
10977 (define-key minibuffer-local-map [(shift up)]
10978 (lambda () (interactive)
10979 (org-eval-in-calendar '(calendar-backward-week 1))))
10980 (define-key minibuffer-local-map [(shift down)]
10981 (lambda () (interactive)
10982 (org-eval-in-calendar '(calendar-forward-week 1))))
10983 (define-key minibuffer-local-map [(shift left)]
10984 (lambda () (interactive)
10985 (org-eval-in-calendar '(calendar-backward-day 1))))
10986 (define-key minibuffer-local-map [(shift right)]
10987 (lambda () (interactive)
10988 (org-eval-in-calendar '(calendar-forward-day 1))))
10989 (define-key minibuffer-local-map ">"
10990 (lambda () (interactive)
10991 (org-eval-in-calendar '(scroll-calendar-left 1))))
10992 (define-key minibuffer-local-map "<"
10993 (lambda () (interactive)
10994 (org-eval-in-calendar '(scroll-calendar-right 1))))
10995 (unwind-protect
10996 (progn
10997 (use-local-map map)
10998 (setq ans (read-string prompt "" nil nil))
10999 (if (not (string-match "\\S-" ans)) (setq ans nil))
11000 (setq ans (or org-ans1 ans org-ans2)))
11001 (use-local-map old-map))))))
11002 (t ; Naked prompt only
11003 (setq ans (read-string prompt "" nil timestr))))
11004 (org-detach-overlay org-date-ovl)
11006 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" ans)
11007 (setq deltadays (string-to-number ans) ans ""))
11009 (if (string-match
11010 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11011 (progn
11012 (setq year (if (match-end 2)
11013 (string-to-number (match-string 2 ans))
11014 (string-to-number (format-time-string "%Y")))
11015 month (string-to-number (match-string 3 ans))
11016 day (string-to-number (match-string 4 ans)))
11017 (if (< year 100) (setq year (+ 2000 year)))
11018 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11019 t nil ans))))
11020 (setq tl (parse-time-string ans)
11021 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
11022 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
11023 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
11024 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
11025 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
11026 second (or (nth 0 tl) 0)
11027 wday (nth 6 tl))
11028 (setq day (+ day deltadays))
11029 (when (and wday (not (nth 3 tl)))
11030 ;; Weekday was given, but no day, so pick that day in the week
11031 ;; on or after the derived date.
11032 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11033 (unless (equal wday wday1)
11034 (setq day (+ day (% (- wday wday1 -7) 7)))))
11035 (if (and (boundp 'org-time-was-given)
11036 (nth 2 tl))
11037 (setq org-time-was-given t))
11038 (if (< year 100) (setq year (+ 2000 year)))
11039 (if to-time
11040 (encode-time second minute hour day month year)
11041 (if (or (nth 1 tl) (nth 2 tl))
11042 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
11043 (format "%04d-%02d-%02d" year month day)))))
11045 (defun org-eval-in-calendar (form)
11046 "Eval FORM in the calendar window and return to current window.
11047 Also, store the cursor date in variable org-ans2."
11048 (let ((sw (selected-window)))
11049 (select-window (get-buffer-window "*Calendar*"))
11050 (eval form)
11051 (when (calendar-cursor-to-date)
11052 (let* ((date (calendar-cursor-to-date))
11053 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11054 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11055 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11056 (select-window sw)))
11058 (defun org-calendar-select ()
11059 "Return to `org-read-date' with the date currently selected.
11060 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11061 (interactive)
11062 (when (calendar-cursor-to-date)
11063 (let* ((date (calendar-cursor-to-date))
11064 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11065 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11066 (if (active-minibuffer-window) (exit-minibuffer))))
11068 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
11069 "Insert a date stamp for the date given by the internal TIME.
11070 WITH-HM means, use the stamp format that includes the time of the day.
11071 INACTIVE means use square brackets instead of angular ones, so that the
11072 stamp will not contribute to the agenda.
11073 PRE and POST are optional strings to be inserted before and after the
11074 stamp.
11075 The command returns the inserted time stamp."
11076 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11077 stamp)
11078 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11079 (insert (or pre ""))
11080 (insert (setq stamp (format-time-string fmt time)))
11081 (insert (or post ""))
11082 stamp))
11084 (defun org-toggle-time-stamp-overlays ()
11085 "Toggle the use of custom time stamp formats."
11086 (interactive)
11087 (setq org-display-custom-times (not org-display-custom-times))
11088 (unless org-display-custom-times
11089 (let ((p (point-min)) (bmp (buffer-modified-p)))
11090 (while (setq p (next-single-property-change p 'display))
11091 (if (and (get-text-property p 'display)
11092 (eq (get-text-property p 'face) 'org-date))
11093 (remove-text-properties
11094 p (setq p (next-single-property-change p 'display))
11095 '(display t))))
11096 (set-buffer-modified-p bmp)))
11097 (if (featurep 'xemacs)
11098 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11099 (org-restart-font-lock)
11100 (setq org-table-may-need-update t)
11101 (if org-display-custom-times
11102 (message "Time stamps are overlayed with custom format")
11103 (message "Time stamp overlays removed")))
11105 (defun org-display-custom-time (beg end)
11106 "Overlay modified time stamp format over timestamp between BED and END."
11107 (let* ((t1 (save-match-data
11108 (org-parse-time-string (buffer-substring beg end) t)))
11109 (w1 (- end beg))
11110 (with-hm (and (nth 1 t1) (nth 2 t1)))
11111 (inactive (= (char-before (1- beg)) ?\[))
11112 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
11113 (time (org-fix-decoded-time t1))
11114 (str (org-add-props
11115 (format-time-string
11116 (substring tf 1 -1) (apply 'encode-time time))
11117 nil 'mouse-face 'highlight))
11118 (w2 (length str)))
11119 (if (not (= w2 w1))
11120 (add-text-properties (1+ beg) (+ 2 beg)
11121 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11122 (if (featurep 'xemacs)
11123 (progn
11124 (put-text-property beg end 'invisible t)
11125 (put-text-property beg end 'end-glyph (make-glyph str)))
11126 (put-text-property beg end 'display str))))
11128 (defun org-translate-time (string)
11129 "Translate all timestamps in STRING to custom format.
11130 But do this only if the variable `org-display-custom-times' is set."
11131 (when org-display-custom-times
11132 (save-match-data
11133 (let* ((start 0)
11134 (re org-ts-regexp-both)
11135 t1 with-hm inactive tf time str beg end)
11136 (while (setq start (string-match re string start))
11137 (setq beg (match-beginning 0)
11138 end (match-end 0)
11139 t1 (save-match-data
11140 (org-parse-time-string (substring string beg end) t))
11141 with-hm (and (nth 1 t1) (nth 2 t1))
11142 inactive (equal (substring string beg (1+ beg)) "[")
11143 tf (funcall (if with-hm 'cdr 'car)
11144 org-time-stamp-custom-formats)
11145 time (org-fix-decoded-time t1)
11146 str (format-time-string
11147 (concat
11148 (if inactive "[" "<") (substring tf 1 -1)
11149 (if inactive "]" ">"))
11150 (apply 'encode-time time))
11151 string (replace-match str t t string)
11152 start (+ start (length str)))))))
11153 string)
11155 (defun org-fix-decoded-time (time)
11156 "Set 0 instead of nil for the first 6 elements of time.
11157 Don't touch the rest."
11158 (let ((n 0))
11159 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11161 (defun org-days-to-time (timestamp-string)
11162 "Difference between TIMESTAMP-STRING and now in days."
11163 (- (time-to-days (org-time-string-to-time timestamp-string))
11164 (time-to-days (current-time))))
11166 (defun org-deadline-close (timestamp-string &optional ndays)
11167 "Is the time in TIMESTAMP-STRING close to the current date?"
11168 (and (< (org-days-to-time timestamp-string)
11169 (or ndays org-deadline-warning-days))
11170 (not (org-entry-is-done-p))))
11172 (defun org-calendar-select-mouse (ev)
11173 "Return to `org-read-date' with the date currently selected.
11174 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11175 (interactive "e")
11176 (mouse-set-point ev)
11177 (when (calendar-cursor-to-date)
11178 (let* ((date (calendar-cursor-to-date))
11179 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11180 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11181 (if (active-minibuffer-window) (exit-minibuffer))))
11183 (defun org-check-deadlines (ndays)
11184 "Check if there are any deadlines due or past due.
11185 A deadline is considered due if it happens within `org-deadline-warning-days'
11186 days from today's date. If the deadline appears in an entry marked DONE,
11187 it is not shown. The prefix arg NDAYS can be used to test that many
11188 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11189 (interactive "P")
11190 (let* ((org-warn-days
11191 (cond
11192 ((equal ndays '(4)) 100000)
11193 (ndays (prefix-numeric-value ndays))
11194 (t org-deadline-warning-days)))
11195 (case-fold-search nil)
11196 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11197 (callback
11198 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11200 (message "%d deadlines past-due or due within %d days"
11201 (org-occur regexp nil callback)
11202 org-warn-days)))
11204 (defun org-evaluate-time-range (&optional to-buffer)
11205 "Evaluate a time range by computing the difference between start and end.
11206 Normally the result is just printed in the echo area, but with prefix arg
11207 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11208 If the time range is actually in a table, the result is inserted into the
11209 next column.
11210 For time difference computation, a year is assumed to be exactly 365
11211 days in order to avoid rounding problems."
11212 (interactive "P")
11214 (org-clock-update-time-maybe)
11215 (save-excursion
11216 (unless (org-at-date-range-p)
11217 (goto-char (point-at-bol))
11218 (re-search-forward org-tr-regexp (point-at-eol) t))
11219 (if (not (org-at-date-range-p))
11220 (error "Not at a time-stamp range, and none found in current line")))
11221 (let* ((ts1 (match-string 1))
11222 (ts2 (match-string 2))
11223 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11224 (match-end (match-end 0))
11225 (time1 (org-time-string-to-time ts1))
11226 (time2 (org-time-string-to-time ts2))
11227 (t1 (time-to-seconds time1))
11228 (t2 (time-to-seconds time2))
11229 (diff (abs (- t2 t1)))
11230 (negative (< (- t2 t1) 0))
11231 ;; (ys (floor (* 365 24 60 60)))
11232 (ds (* 24 60 60))
11233 (hs (* 60 60))
11234 (fy "%dy %dd %02d:%02d")
11235 (fy1 "%dy %dd")
11236 (fd "%dd %02d:%02d")
11237 (fd1 "%dd")
11238 (fh "%02d:%02d")
11239 y d h m align)
11240 (if havetime
11241 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11243 d (floor (/ diff ds)) diff (mod diff ds)
11244 h (floor (/ diff hs)) diff (mod diff hs)
11245 m (floor (/ diff 60)))
11246 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11248 d (floor (+ (/ diff ds) 0.5))
11249 h 0 m 0))
11250 (if (not to-buffer)
11251 (message (org-make-tdiff-string y d h m))
11252 (when (org-at-table-p)
11253 (goto-char match-end)
11254 (setq align t)
11255 (and (looking-at " *|") (goto-char (match-end 0))))
11256 (if (looking-at
11257 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11258 (replace-match ""))
11259 (if negative (insert " -"))
11260 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11261 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11262 (insert " " (format fh h m))))
11263 (if align (org-table-align))
11264 (message "Time difference inserted")))))
11266 (defun org-make-tdiff-string (y d h m)
11267 (let ((fmt "")
11268 (l nil))
11269 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11270 l (push y l)))
11271 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11272 l (push d l)))
11273 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11274 l (push h l)))
11275 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11276 l (push m l)))
11277 (apply 'format fmt (nreverse l))))
11279 (defun org-time-string-to-time (s)
11280 (apply 'encode-time (org-parse-time-string s)))
11282 (defun org-parse-time-string (s &optional nodefault)
11283 "Parse the standard Org-mode time string.
11284 This should be a lot faster than the normal `parse-time-string'.
11285 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11286 hour and minute fields will be nil if not given."
11287 (if (string-match org-ts-regexp1 s)
11288 (list 0
11289 (if (or (match-beginning 8) (not nodefault))
11290 (string-to-number (or (match-string 8 s) "0")))
11291 (if (or (match-beginning 7) (not nodefault))
11292 (string-to-number (or (match-string 7 s) "0")))
11293 (string-to-number (match-string 4 s))
11294 (string-to-number (match-string 3 s))
11295 (string-to-number (match-string 2 s))
11296 nil nil nil)
11297 (make-list 9 0)))
11299 (defun org-timestamp-up (&optional arg)
11300 "Increase the date item at the cursor by one.
11301 If the cursor is on the year, change the year. If it is on the month or
11302 the day, change that.
11303 With prefix ARG, change by that many units."
11304 (interactive "p")
11305 (org-timestamp-change (prefix-numeric-value arg)))
11307 (defun org-timestamp-down (&optional arg)
11308 "Decrease the date item at the cursor by one.
11309 If the cursor is on the year, change the year. If it is on the month or
11310 the day, change that.
11311 With prefix ARG, change by that many units."
11312 (interactive "p")
11313 (org-timestamp-change (- (prefix-numeric-value arg))))
11315 (defun org-timestamp-up-day (&optional arg)
11316 "Increase the date in the time stamp by one day.
11317 With prefix ARG, change that many days."
11318 (interactive "p")
11319 (if (and (not (org-at-timestamp-p t))
11320 (org-on-heading-p))
11321 (org-todo 'up)
11322 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11324 (defun org-timestamp-down-day (&optional arg)
11325 "Decrease the date in the time stamp by one day.
11326 With prefix ARG, change that many days."
11327 (interactive "p")
11328 (if (and (not (org-at-timestamp-p t))
11329 (org-on-heading-p))
11330 (org-todo 'down)
11331 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11333 (defsubst org-pos-in-match-range (pos n)
11334 (and (match-beginning n)
11335 (<= (match-beginning n) pos)
11336 (>= (match-end n) pos)))
11338 (defun org-at-timestamp-p (&optional inactive-ok)
11339 "Determine if the cursor is in or at a timestamp."
11340 (interactive)
11341 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11342 (pos (point))
11343 (ans (or (looking-at tsr)
11344 (save-excursion
11345 (skip-chars-backward "^[<\n\r\t")
11346 (if (> (point) 1) (backward-char 1))
11347 (and (looking-at tsr)
11348 (> (- (match-end 0) pos) -1))))))
11349 (and (boundp 'org-ts-what)
11350 (setq org-ts-what
11351 (cond
11352 ((org-pos-in-match-range pos 2) 'year)
11353 ((org-pos-in-match-range pos 3) 'month)
11354 ((org-pos-in-match-range pos 7) 'hour)
11355 ((org-pos-in-match-range pos 8) 'minute)
11356 ((or (org-pos-in-match-range pos 4)
11357 (org-pos-in-match-range pos 5)) 'day)
11358 (t 'day))))
11359 ans))
11361 (defun org-timestamp-change (n &optional what)
11362 "Change the date in the time stamp at point.
11363 The date will be changed by N times WHAT. WHAT can be `day', `month',
11364 `year', `minute', `second'. If WHAT is not given, the cursor position
11365 in the timestamp determines what will be changed."
11366 (let ((pos (point))
11367 with-hm inactive
11368 org-ts-what
11369 ts time time0)
11370 (if (not (org-at-timestamp-p t))
11371 (error "Not at a timestamp"))
11372 (if (and (not what) (not (eq org-ts-what 'day))
11373 org-display-custom-times
11374 (get-text-property (point) 'display)
11375 (not (get-text-property (1- (point)) 'display)))
11376 (setq org-ts-what 'day))
11377 (setq org-ts-what (or what org-ts-what)
11378 with-hm (<= (abs (- (cdr org-ts-lengths)
11379 (- (match-end 0) (match-beginning 0))))
11381 inactive (= (char-after (match-beginning 0)) ?\[)
11382 ts (match-string 0))
11383 (replace-match "")
11384 (setq time0 (org-parse-time-string ts))
11385 (setq time
11386 (apply 'encode-time
11387 (append
11388 (list (or (car time0) 0))
11389 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
11390 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
11391 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
11392 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
11393 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
11394 (nthcdr 6 time0))))
11395 (if (eq what 'calendar)
11396 (let ((cal-date
11397 (save-excursion
11398 (save-match-data
11399 (set-buffer "*Calendar*")
11400 (calendar-cursor-to-date)))))
11401 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11402 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11403 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11404 (setcar time0 (or (car time0) 0))
11405 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11406 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
11407 (setq time (apply 'encode-time time0))))
11408 (setq org-last-changed-timestamp
11409 (org-insert-time-stamp time with-hm inactive))
11410 (org-clock-update-time-maybe)
11411 (goto-char pos)
11412 ;; Try to recenter the calendar window, if any
11413 (if (and org-calendar-follow-timestamp-change
11414 (get-buffer-window "*Calendar*" t)
11415 (memq org-ts-what '(day month year)))
11416 (org-recenter-calendar (time-to-days time)))))
11418 (defun org-recenter-calendar (date)
11419 "If the calendar is visible, recenter it to DATE."
11420 (let* ((win (selected-window))
11421 (cwin (get-buffer-window "*Calendar*" t))
11422 (calendar-move-hook nil))
11423 (when cwin
11424 (select-window cwin)
11425 (calendar-goto-date (if (listp date) date
11426 (calendar-gregorian-from-absolute date)))
11427 (select-window win))))
11429 (defun org-goto-calendar (&optional arg)
11430 "Go to the Emacs calendar at the current date.
11431 If there is a time stamp in the current line, go to that date.
11432 A prefix ARG can be used to force the current date."
11433 (interactive "P")
11434 (let ((tsr org-ts-regexp) diff
11435 (calendar-move-hook nil)
11436 (view-calendar-holidays-initially nil)
11437 (view-diary-entries-initially nil))
11438 (if (or (org-at-timestamp-p)
11439 (save-excursion
11440 (beginning-of-line 1)
11441 (looking-at (concat ".*" tsr))))
11442 (let ((d1 (time-to-days (current-time)))
11443 (d2 (time-to-days
11444 (org-time-string-to-time (match-string 1)))))
11445 (setq diff (- d2 d1))))
11446 (calendar)
11447 (calendar-goto-today)
11448 (if (and diff (not arg)) (calendar-forward-day diff))))
11450 (defun org-date-from-calendar ()
11451 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11452 If there is already a time stamp at the cursor position, update it."
11453 (interactive)
11454 (org-timestamp-change 0 'calendar))
11456 ;;; The clock for measuring work time.
11458 (defvar org-clock-marker (make-marker)
11459 "Marker recording the last clock-in.")
11461 (defun org-clock-in ()
11462 "Start the clock on the current item.
11463 If necessary, clock-out of the currently active clock."
11464 (interactive)
11465 (org-clock-out t)
11466 (let (ts)
11467 (save-excursion
11468 (org-back-to-heading t)
11469 (beginning-of-line 2)
11470 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
11471 (not (equal (match-string 1) org-clock-string)))
11472 (beginning-of-line 1))
11473 (insert "\n") (backward-char 1)
11474 (indent-relative)
11475 (insert org-clock-string " ")
11476 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
11477 (move-marker org-clock-marker (point) (buffer-base-buffer))
11478 (message "Clock started at %s" ts))))
11480 (defun org-clock-out (&optional fail-quietly)
11481 "Stop the currently running clock.
11482 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
11483 (interactive)
11484 (catch 'exit
11485 (if (not (marker-buffer org-clock-marker))
11486 (if fail-quietly (throw 'exit t) (error "No active clock")))
11487 (let (ts te s h m)
11488 (save-excursion
11489 (set-buffer (marker-buffer org-clock-marker))
11490 (goto-char org-clock-marker)
11491 (beginning-of-line 1)
11492 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
11493 (equal (match-string 1) org-clock-string))
11494 (setq ts (match-string 2))
11495 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
11496 (goto-char org-clock-marker)
11497 (insert "--")
11498 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
11499 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
11500 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
11501 h (floor (/ s 3600))
11502 s (- s (* 3600 h))
11503 m (floor (/ s 60))
11504 s (- s (* 60 s)))
11505 (insert " => " (format "%2d:%02d" h m))
11506 (move-marker org-clock-marker nil)
11507 (org-add-log-maybe 'clock-out)
11508 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
11510 (defun org-clock-cancel ()
11511 "Cancel the running clock be removing the start timestamp."
11512 (interactive)
11513 (if (not (marker-buffer org-clock-marker))
11514 (error "No active clock"))
11515 (save-excursion
11516 (set-buffer (marker-buffer org-clock-marker))
11517 (goto-char org-clock-marker)
11518 (delete-region (1- (point-at-bol)) (point-at-eol)))
11519 (message "Clock canceled"))
11521 (defvar org-clock-file-total-minutes nil
11522 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
11523 (make-variable-buffer-local 'org-clock-file-total-minutes)
11525 (defun org-clock-sum (&optional tstart tend)
11526 "Sum the times for each subtree.
11527 Puts the resulting times in minutes as a text property on each headline."
11528 (interactive)
11529 (let* ((bmp (buffer-modified-p))
11530 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
11531 org-clock-string
11532 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
11533 (lmax 30)
11534 (ltimes (make-vector lmax 0))
11535 (t1 0)
11536 (level 0)
11537 ts te dt
11538 time)
11539 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
11540 (save-excursion
11541 (goto-char (point-max))
11542 (while (re-search-backward re nil t)
11543 (if (match-end 2)
11544 ;; A time
11545 (setq ts (match-string 2)
11546 te (match-string 3)
11547 ts (time-to-seconds
11548 (apply 'encode-time (org-parse-time-string ts)))
11549 te (time-to-seconds
11550 (apply 'encode-time (org-parse-time-string te)))
11551 ts (if tstart (max ts tstart) ts)
11552 te (if tend (min te tend) te)
11553 dt (- te ts)
11554 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
11555 ;; A headline
11556 (setq level (- (match-end 1) (match-beginning 1)))
11557 (when (or (> t1 0) (> (aref ltimes level) 0))
11558 (loop for l from 0 to level do
11559 (aset ltimes l (+ (aref ltimes l) t1)))
11560 (setq t1 0 time (aref ltimes level))
11561 (loop for l from level to (1- lmax) do
11562 (aset ltimes l 0))
11563 (goto-char (match-beginning 0))
11564 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
11565 (setq org-clock-file-total-minutes (aref ltimes 0)))
11566 (set-buffer-modified-p bmp)))
11568 (defun org-clock-display (&optional total-only)
11569 "Show subtree times in the entire buffer.
11570 If TOTAL-ONLY is non-nil, only show the total time for the entire file
11571 in the echo area."
11572 (interactive)
11573 (org-remove-clock-overlays)
11574 (let (time h m p)
11575 (org-clock-sum)
11576 (unless total-only
11577 (save-excursion
11578 (goto-char (point-min))
11579 (while (setq p (next-single-property-change (point) :org-clock-minutes))
11580 (goto-char p)
11581 (when (setq time (get-text-property p :org-clock-minutes))
11582 (org-put-clock-overlay time (funcall outline-level))))
11583 (setq h (/ org-clock-file-total-minutes 60)
11584 m (- org-clock-file-total-minutes (* 60 h)))
11585 ;; Arrange to remove the overlays upon next change.
11586 (when org-remove-highlights-with-change
11587 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
11588 nil 'local))))
11589 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
11591 (defvar org-clock-overlays nil)
11592 (make-variable-buffer-local 'org-clock-overlays)
11594 (defun org-put-clock-overlay (time &optional level)
11595 "Put an overlays on the current line, displaying TIME.
11596 If LEVEL is given, prefix time with a corresponding number of stars.
11597 This creates a new overlay and stores it in `org-clock-overlays', so that it
11598 will be easy to remove."
11599 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
11600 (l (if level (org-get-legal-level level 0) 0))
11601 (off 0)
11602 ov tx)
11603 (move-to-column c)
11604 (unless (eolp) (skip-chars-backward "^ \t"))
11605 (skip-chars-backward " \t")
11606 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
11607 tx (concat (buffer-substring (1- (point)) (point))
11608 (make-string (+ off (max 0 (- c (current-column)))) ?.)
11609 (org-add-props (format "%s %2d:%02d%s"
11610 (make-string l ?*) h m
11611 (make-string (- 10 l) ?\ ))
11612 '(face secondary-selection))
11613 ""))
11614 (if (not (featurep 'xemacs))
11615 (org-overlay-put ov 'display tx)
11616 (org-overlay-put ov 'invisible t)
11617 (org-overlay-put ov 'end-glyph (make-glyph tx)))
11618 (push ov org-clock-overlays)))
11620 (defun org-remove-clock-overlays (&optional beg end noremove)
11621 "Remove the occur highlights from the buffer.
11622 BEG and END are ignored. If NOREMOVE is nil, remove this function
11623 from the `before-change-functions' in the current buffer."
11624 (interactive)
11625 (unless org-inhibit-highlight-removal
11626 (mapc 'org-delete-overlay org-clock-overlays)
11627 (setq org-clock-overlays nil)
11628 (unless noremove
11629 (remove-hook 'before-change-functions
11630 'org-remove-clock-overlays 'local))))
11632 (defun org-clock-out-if-current ()
11633 "Clock out if the current entry contains the running clock.
11634 This is used to stop the clock after a TODO entry is marked DONE."
11635 (when (and (equal state org-done-string)
11636 (equal (marker-buffer org-clock-marker) (current-buffer))
11637 (< (point) org-clock-marker)
11638 (> (save-excursion (outline-next-heading) (point))
11639 org-clock-marker))
11640 ;; Clock out, but don't accept a logging message for this.
11641 (let ((org-log-done (if (and (listp org-log-done)
11642 (member 'clock-out org-log-done))
11643 '(done)
11644 org-log-done)))
11645 (org-clock-out))))
11647 (add-hook 'org-after-todo-state-change-hook
11648 'org-clock-out-if-current)
11650 (defun org-check-running-clock ()
11651 "Check if the current buffer contains the running clock.
11652 If yes, offer to stop it and to save the buffer with the changes."
11653 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
11654 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
11655 (buffer-name))))
11656 (org-clock-out)
11657 (when (y-or-n-p "Save changed buffer?")
11658 (save-buffer))))
11660 (defun org-clock-report ()
11661 "Create a table containing a report about clocked time.
11662 If the buffer contains lines
11663 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
11665 #+END: clocktable
11666 then the table will be inserted between these lines, replacing whatever
11667 is was there before. If these lines are not in the buffer, the table
11668 is inserted at point, surrounded by the special lines.
11669 The BEGIN line can contain parameters. Allowed are:
11670 :maxlevel The maximum level to be included in the table. Default is 3.
11671 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
11672 (interactive)
11673 (org-remove-clock-overlays)
11674 (unless (org-find-dblock "clocktable")
11675 (org-create-dblock (list :name "clocktable"
11676 :maxlevel 2 :emphasize nil)))
11677 (org-update-dblock))
11679 (defun org-clock-update-time-maybe ()
11680 "If this is a CLOCK line, update it and return t.
11681 Otherwise, return nil."
11682 (interactive)
11683 (save-excursion
11684 (beginning-of-line 1)
11685 (skip-chars-forward " \t")
11686 (when (looking-at org-clock-string)
11687 (let ((re (concat "[ \t]*" org-clock-string
11688 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
11689 "\\([ \t]*=>.*\\)?"))
11690 ts te h m s)
11691 (if (not (looking-at re))
11693 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
11694 (end-of-line 1)
11695 (setq ts (match-string 1)
11696 te (match-string 2))
11697 (setq s (- (time-to-seconds
11698 (apply 'encode-time (org-parse-time-string te)))
11699 (time-to-seconds
11700 (apply 'encode-time (org-parse-time-string ts))))
11701 h (floor (/ s 3600))
11702 s (- s (* 3600 h))
11703 m (floor (/ s 60))
11704 s (- s (* 60 s)))
11705 (insert " => " (format "%2d:%02d" h m))
11706 t)))))
11708 (defun org-clock-special-range (key &optional time as-strings)
11709 "Return two times bordering a special time range.
11710 Key is a symbol specifying the range and can be one of `today', `yesterday',
11711 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
11712 A week starts Monday 0:00 and ends Sunday 24:00.
11713 The range is determined relative to TIME. TIME defaults to the current time.
11714 The return value is a cons cell with two internal times like the ones
11715 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
11716 the returned times will be formatted strings."
11717 (let* ((tm (decode-time (or time (current-time))))
11718 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
11719 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
11720 (dow (nth 6 tm))
11721 s1 m1 h1 d1 month1 y1 diff ts te fm)
11722 (cond
11723 ((eq key 'today)
11724 (setq h 0 m 0 h1 24 m1 0))
11725 ((eq key 'yesterday)
11726 (setq d (1- d) h 0 m 0 h1 24 m1 0))
11727 ((eq key 'thisweek)
11728 (setq diff (if (= dow 0) 6 (1- dow))
11729 m 0 h 0 d (- d diff) d1 (+ 7 d)))
11730 ((eq key 'lastweek)
11731 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
11732 m 0 h 0 d (- d diff) d1 (+ 7 d)))
11733 ((eq key 'thismonth)
11734 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
11735 ((eq key 'lastmonth)
11736 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
11737 ((eq key 'thisyear)
11738 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
11739 ((eq key 'lastyear)
11740 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
11741 (t (error "No such time block %s" key)))
11742 (setq ts (encode-time s m h d month y)
11743 te (encode-time (or s1 s) (or m1 m) (or h1 h)
11744 (or d1 d) (or month1 month) (or y1 y)))
11745 (setq fm (cdr org-time-stamp-formats))
11746 (if as-strings
11747 (cons (format-time-string fm ts) (format-time-string fm te))
11748 (cons ts te))))
11750 (defun org-dblock-write:clocktable (params)
11751 "Write the standard clocktable."
11752 (let ((hlchars '((1 . "*") (2 . ?/)))
11753 (emph nil)
11754 (ins (make-marker))
11755 ipos time h m p level hlc hdl maxlevel
11756 ts te cc block)
11757 (setq maxlevel (or (plist-get params :maxlevel) 3)
11758 emph (plist-get params :emphasize)
11759 ts (plist-get params :tstart)
11760 te (plist-get params :tend)
11761 block (plist-get params :block))
11762 (when block
11763 (setq cc (org-clock-special-range block nil t)
11764 ts (car cc) te (cdr cc)))
11765 (if ts (setq ts (time-to-seconds
11766 (apply 'encode-time (org-parse-time-string ts)))))
11767 (if te (setq te (time-to-seconds
11768 (apply 'encode-time (org-parse-time-string te)))))
11769 (move-marker ins (point))
11770 (setq ipos (point))
11771 ;; FIXME: does not yet use org-insert-time-stamp
11772 (insert-before-markers "Clock summary at ["
11773 (substring
11774 (format-time-string (cdr org-time-stamp-formats))
11775 1 -1)
11776 "]."
11777 (if block
11778 (format " Considered range is /%s/." block)
11780 "\n\n|L|Headline|Time|\n")
11781 (org-clock-sum ts te)
11782 (setq h (/ org-clock-file-total-minutes 60)
11783 m (- org-clock-file-total-minutes (* 60 h)))
11784 (insert-before-markers "|-\n|0|" "*Total file time*| "
11785 (format "*%d:%02d*" h m)
11786 "|\n")
11787 (goto-char (point-min))
11788 (while (setq p (next-single-property-change (point) :org-clock-minutes))
11789 (goto-char p)
11790 (when (setq time (get-text-property p :org-clock-minutes))
11791 (save-excursion
11792 (beginning-of-line 1)
11793 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
11794 (setq level (- (match-end 1) (match-beginning 1)))
11795 (<= level maxlevel))
11796 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
11797 hdl (match-string 2)
11798 h (/ time 60)
11799 m (- time (* 60 h)))
11800 (goto-char ins)
11801 (if (= level 1) (insert-before-markers "|-\n"))
11802 (insert-before-markers
11803 "| " (int-to-string level) "|" hlc hdl hlc " |"
11804 (make-string (1- level) ?|)
11806 (format "%d:%02d" h m)
11808 " |\n")))))
11809 (goto-char ins)
11810 (backward-delete-char 1)
11811 (goto-char ipos)
11812 (skip-chars-forward "^|")
11813 (org-table-align)))
11815 (defun org-collect-clock-time-entries ()
11816 "Return an internal list with clocking information.
11817 This list has one entry for each CLOCK interval.
11818 FIXME: describe the elements."
11819 (interactive)
11820 (let ((re (concat "^[ \t]*" org-clock-string
11821 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
11822 rtn beg end next cont level title total closedp leafp
11823 clockpos titlepos h m donep)
11824 (save-excursion
11825 (org-clock-sum)
11826 (goto-char (point-min))
11827 (while (re-search-forward re nil t)
11828 (setq clockpos (match-beginning 0)
11829 beg (match-string 1) end (match-string 2)
11830 cont (match-end 0))
11831 (setq beg (apply 'encode-time (org-parse-time-string beg))
11832 end (apply 'encode-time (org-parse-time-string end)))
11833 (org-back-to-heading t)
11834 (setq donep (org-entry-is-done-p))
11835 (setq titlepos (point)
11836 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
11837 h (/ total 60) m (- total (* 60 h))
11838 total (cons h m))
11839 (looking-at "\\(\\*+\\) +\\(.*\\)")
11840 (setq level (- (match-end 1) (match-beginning 1))
11841 title (org-match-string-no-properties 2))
11842 (save-excursion (outline-next-heading) (setq next (point)))
11843 (setq closedp (re-search-forward org-closed-time-regexp next t))
11844 (goto-char next)
11845 (setq leafp (and (looking-at "^\\*+ ")
11846 (<= (- (match-end 0) (point)) level)))
11847 (push (list beg end clockpos closedp donep
11848 total title titlepos level leafp)
11849 rtn)
11850 (goto-char cont)))
11851 (nreverse rtn)))
11853 ;;;; Agenda, and Diary Integration
11855 ;;; Define the Org-agenda-mode
11857 (defvar org-agenda-mode-map (make-sparse-keymap)
11858 "Keymap for `org-agenda-mode'.")
11860 (defvar org-agenda-menu) ; defined later in this file.
11861 (defvar org-agenda-follow-mode nil)
11862 (defvar org-agenda-show-log nil)
11863 (defvar org-agenda-redo-command nil)
11864 (defvar org-agenda-mode-hook nil)
11865 (defvar org-agenda-type nil)
11866 (defvar org-agenda-force-single-file nil)
11868 (defun org-agenda-mode ()
11869 "Mode for time-sorted view on action items in Org-mode files.
11871 The following commands are available:
11873 \\{org-agenda-mode-map}"
11874 (interactive)
11875 (kill-all-local-variables)
11876 (setq org-agenda-undo-list nil
11877 org-agenda-pending-undo-list nil)
11878 (setq major-mode 'org-agenda-mode)
11879 (setq mode-name "Org-Agenda")
11880 (use-local-map org-agenda-mode-map)
11881 (easy-menu-add org-agenda-menu)
11882 (if org-startup-truncated (setq truncate-lines t))
11883 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
11884 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
11885 (unless org-agenda-keep-modes
11886 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
11887 org-agenda-show-log nil))
11888 (easy-menu-change
11889 '("Agenda") "Agenda Files"
11890 (append
11891 (list
11892 (vector
11893 (if (get 'org-agenda-files 'org-restrict)
11894 "Restricted to single file"
11895 "Edit File List")
11896 '(org-edit-agenda-file-list)
11897 (not (get 'org-agenda-files 'org-restrict)))
11898 "--")
11899 (mapcar 'org-file-menu-entry (org-agenda-files))))
11900 (org-agenda-set-mode-name)
11901 (apply
11902 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
11903 (list 'org-agenda-mode-hook)))
11905 (substitute-key-definition 'undo 'org-agenda-undo
11906 org-agenda-mode-map global-map)
11907 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
11908 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
11909 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
11910 (define-key org-agenda-mode-map "\C-k" 'org-agenda-kill)
11911 (define-key org-agenda-mode-map "\C-c$" 'org-agenda-archive)
11912 (define-key org-agenda-mode-map "$" 'org-agenda-archive)
11913 (define-key org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
11914 (define-key org-agenda-mode-map " " 'org-agenda-show)
11915 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
11916 (define-key org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
11917 (define-key org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
11918 (define-key org-agenda-mode-map "o" 'delete-other-windows)
11919 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
11920 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
11921 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
11922 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
11923 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
11924 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
11925 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
11926 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
11927 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
11928 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
11929 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
11931 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
11932 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
11933 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
11934 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
11935 (while l (define-key org-agenda-mode-map
11936 (int-to-string (pop l)) 'digit-argument)))
11938 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
11939 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
11940 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
11941 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
11942 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
11943 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
11944 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
11945 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
11946 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
11947 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
11948 (define-key org-agenda-mode-map "n" 'next-line)
11949 (define-key org-agenda-mode-map "p" 'previous-line)
11950 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
11951 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
11952 (define-key org-agenda-mode-map "," 'org-agenda-priority)
11953 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
11954 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
11955 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
11956 (eval-after-load "calendar"
11957 '(define-key calendar-mode-map org-calendar-to-agenda-key
11958 'org-calendar-goto-agenda))
11959 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
11960 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
11961 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
11962 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
11963 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
11964 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
11965 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
11966 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
11967 (define-key org-agenda-mode-map "O" 'org-agenda-clock-out)
11968 (define-key org-agenda-mode-map "X" 'org-agenda-clock-cancel)
11969 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
11970 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
11971 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
11972 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
11973 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
11974 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
11975 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
11976 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11977 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
11978 "Local keymap for agenda entries from Org-mode.")
11980 (define-key org-agenda-keymap
11981 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
11982 (define-key org-agenda-keymap
11983 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
11984 (when org-agenda-mouse-1-follows-link
11985 (define-key org-agenda-keymap [follow-link] 'mouse-face))
11986 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
11987 '("Agenda"
11988 ("Agenda Files")
11989 "--"
11990 ["Show" org-agenda-show t]
11991 ["Go To (other window)" org-agenda-goto t]
11992 ["Go To (this window)" org-agenda-switch-to t]
11993 ["Follow Mode" org-agenda-follow-mode
11994 :style toggle :selected org-agenda-follow-mode :active t]
11995 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
11996 "--"
11997 ["Cycle TODO" org-agenda-todo t]
11998 ["Archive subtree" org-agenda-archive t]
11999 ["Delete subtree" org-agenda-kill t]
12000 "--"
12001 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
12002 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
12003 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
12004 "--"
12005 ("Tags"
12006 ["Show all Tags" org-agenda-show-tags t]
12007 ["Set Tags" org-agenda-set-tags t])
12008 ("Date/Schedule"
12009 ["Schedule" org-agenda-schedule t]
12010 ["Set Deadline" org-agenda-deadline t]
12011 "--"
12012 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
12013 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
12014 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
12015 ("Priority"
12016 ["Set Priority" org-agenda-priority t]
12017 ["Increase Priority" org-agenda-priority-up t]
12018 ["Decrease Priority" org-agenda-priority-down t]
12019 ["Show Priority" org-agenda-show-priority t])
12020 ("Calendar/Diary"
12021 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
12022 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
12023 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
12024 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
12025 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
12026 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
12027 "--"
12028 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
12029 "--"
12030 ("View"
12031 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
12032 :style radio :selected (equal org-agenda-ndays 1)]
12033 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
12034 :style radio :selected (equal org-agenda-ndays 7)]
12035 "--"
12036 ["Show Logbook entries" org-agenda-log-mode
12037 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
12038 ["Include Diary" org-agenda-toggle-diary
12039 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
12040 ["Use Time Grid" org-agenda-toggle-time-grid
12041 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
12042 ["Rebuild buffer" org-agenda-redo t]
12043 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
12044 "--"
12045 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
12046 "--"
12047 ["Quit" org-agenda-quit t]
12048 ["Exit and Release Buffers" org-agenda-exit t]
12051 ;;; Agenda undo
12053 (defvar org-agenda-allow-remote-undo t
12054 "Non-nil means, allow remote undo from the agenda buffer.")
12055 (defvar org-agenda-undo-list nil
12056 "List of undoable operations in the agenda since last refresh.")
12057 (defvar org-agenda-undo-has-started-in nil
12058 "Buffers that have already seen `undo-start' in the current undo sequence.")
12059 (defvar org-agenda-pending-undo-list nil
12060 "In a series of undo commands, this is the list of remaning undo items.")
12062 (defmacro org-with-remote-undo (_buffer &rest _body)
12063 "Execute BODY while recording undo information in two buffers."
12064 (declare (indent 1) (debug t))
12065 `(let ((_cline (org-current-line))
12066 (_cmd this-command)
12067 (_buf1 (current-buffer))
12068 (_buf2 ,_buffer)
12069 (_undo1 buffer-undo-list)
12070 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
12071 _c1 _c2)
12072 ,@_body
12073 (when org-agenda-allow-remote-undo
12074 (setq _c1 (org-verify-change-for-undo
12075 _undo1 (with-current-buffer _buf1 buffer-undo-list))
12076 _c2 (org-verify-change-for-undo
12077 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
12078 (when (or _c1 _c2)
12079 ;; make sure there are undo boundaries
12080 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
12081 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
12082 ;; remember which buffer to undo
12083 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
12084 org-agenda-undo-list)))))
12086 (defun org-agenda-undo ()
12087 "Undo a remote editing step in the agenda.
12088 This undoes changes both in the agenda buffer and in the remote buffer
12089 that have been changed along."
12090 (interactive)
12091 (or org-agenda-allow-remote-undo
12092 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
12093 (if (not (eq this-command last-command))
12094 (setq org-agenda-undo-has-started-in nil
12095 org-agenda-pending-undo-list org-agenda-undo-list))
12096 (if (not org-agenda-pending-undo-list)
12097 (error "No further undo information"))
12098 (let* ((entry (pop org-agenda-pending-undo-list))
12099 buf line cmd rembuf)
12100 (setq cmd (pop entry) line (pop entry))
12101 (setq rembuf (nth 2 entry))
12102 (org-with-remote-undo rembuf
12103 (while (bufferp (setq buf (pop entry)))
12104 (if (pop entry)
12105 (with-current-buffer buf
12106 (let ((last-undo-buffer buf)
12107 buffer-read-only)
12108 (unless (memq buf org-agenda-undo-has-started-in)
12109 (push buf org-agenda-undo-has-started-in)
12110 (make-local-variable 'pending-undo-list)
12111 (undo-start))
12112 (while (and pending-undo-list
12113 (listp pending-undo-list)
12114 (not (car pending-undo-list)))
12115 (pop pending-undo-list))
12116 (undo-more 1))))))
12117 (goto-line line)
12118 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
12120 (defun org-verify-change-for-undo (l1 l2)
12121 "Verify that a real change occurred between the undo lists L1 and L2."
12122 (while (and l1 (listp l1) (null (car l1))) (pop l1))
12123 (while (and l2 (listp l2) (null (car l2))) (pop l2))
12124 (not (eq l1 l2)))
12126 ;;; Agenda dispatch
12128 (defvar org-agenda-restrict nil)
12129 (defvar org-agenda-restrict-begin (make-marker))
12130 (defvar org-agenda-restrict-end (make-marker))
12131 (defvar org-agenda-last-dispatch-buffer nil)
12133 ;;;###autoload
12134 (defun org-agenda (arg)
12135 "Dispatch agenda commands to collect entries to the agenda buffer.
12136 Prompts for a character to select a command. Any prefix arg will be passed
12137 on to the selected command. The default selections are:
12139 a Call `org-agenda-list' to display the agenda for current day or week.
12140 t Call `org-todo-list' to display the global todo list.
12141 T Call `org-todo-list' to display the global todo list, select only
12142 entries with a specific TODO keyword (the user gets a prompt).
12143 m Call `org-tags-view' to display headlines with tags matching
12144 a condition (the user is prompted for the condition).
12145 M Like `m', but select only TODO entries, no ordinary headlines.
12146 l Create a timeeline for the current buffer.
12148 More commands can be added by configuring the variable
12149 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
12150 searches can be pre-defined in this way.
12152 If the current buffer is in Org-mode and visiting a file, you can also
12153 first press `1' to indicate that the agenda should be temporarily (until the
12154 next use of \\[org-agenda]) restricted to the current file."
12155 (interactive "P")
12156 (catch 'exit
12157 (let* ((buf (current-buffer))
12158 (bfn (buffer-file-name (buffer-base-buffer)))
12159 (restrict-ok (and bfn (org-mode-p)))
12160 (custom org-agenda-custom-commands)
12161 c entry key type match lprops header)
12162 ;; Turn off restriction
12163 (put 'org-agenda-files 'org-restrict nil)
12164 (setq org-agenda-restrict nil)
12165 (move-marker org-agenda-restrict-begin nil)
12166 (move-marker org-agenda-restrict-end nil)
12167 ;; Remember where this call originated
12168 (setq org-agenda-last-dispatch-buffer (current-buffer))
12169 (save-window-excursion
12170 (delete-other-windows)
12171 (switch-to-buffer-other-window " *Agenda Commands*")
12172 (erase-buffer)
12173 (insert (eval-when-compile
12174 (let ((header
12175 "Press key for an agenda command:
12176 -------------------------------- C Configure custom agenda commands
12177 a Agenda for current week or day
12178 t List of all TODO entries T Entries with special TODO kwd
12179 m Match a TAGS query M Like m, but only TODO entries
12180 L Timeline for current buffer # List stuck projects (!=configure)
12182 (start 0))
12183 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
12184 (setq start (match-end 0))
12185 (add-text-properties (match-beginning 2) (match-end 2)
12186 '(face bold) header))
12187 header)))
12188 (while (setq entry (pop custom))
12189 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
12190 (insert (format "\n%-4s%-14s: %s"
12191 (org-add-props (copy-sequence key)
12192 '(face bold))
12193 (cond
12194 ((stringp type) type)
12195 ((eq type 'todo) "TODO keyword")
12196 ((eq type 'tags) "Tags query")
12197 ((eq type 'tags-todo) "Tags (TODO)")
12198 ((eq type 'tags-tree) "Tags tree")
12199 ((eq type 'todo-tree) "TODO kwd tree")
12200 ((eq type 'occur-tree) "Occur tree")
12201 ((functionp type) (symbol-name type))
12202 (t "???"))
12203 (if (stringp match)
12204 (org-add-props match nil 'face 'org-warning)
12205 (format "set of %d commands" (length match))))))
12206 (if restrict-ok
12207 (insert "\n"
12208 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
12209 (goto-char (point-min))
12210 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
12211 (message "Press key for agenda command%s"
12212 (if restrict-ok ", or [1] or [0] to restrict" ""))
12213 (setq c (read-char-exclusive))
12214 (message "")
12215 (when (memq c '(?L ?1 ?0))
12216 (if restrict-ok
12217 (put 'org-agenda-files 'org-restrict (list bfn))
12218 (error "Cannot restrict agenda to current buffer"))
12219 (with-current-buffer " *Agenda Commands*"
12220 (goto-char (point-max))
12221 (delete-region (point-at-bol) (point))
12222 (goto-char (point-min)))
12223 (when (eq c ?0)
12224 (setq org-agenda-restrict t)
12225 (with-current-buffer buf
12226 (if (org-region-active-p)
12227 (progn
12228 (move-marker org-agenda-restrict-begin (region-beginning))
12229 (move-marker org-agenda-restrict-end (region-end)))
12230 (save-excursion
12231 (org-back-to-heading t)
12232 (move-marker org-agenda-restrict-begin (point))
12233 (move-marker org-agenda-restrict-end
12234 (progn (org-end-of-subtree t)))))))
12235 (unless (eq c ?L)
12236 (message "Press key for agenda command%s"
12237 (if restrict-ok " (restricted to current file)" ""))
12238 (setq c (read-char-exclusive)))
12239 (message "")))
12240 (require 'calendar) ; FIXME: can we avoid this for some commands?
12241 ;; For example the todo list should not need it (but does...)
12242 (cond
12243 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
12244 (if (symbolp (nth 1 entry))
12245 (progn
12246 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
12247 lprops (nth 3 entry))
12248 (cond
12249 ((eq type 'tags)
12250 (org-let lprops '(org-tags-view current-prefix-arg match)))
12251 ((eq type 'tags-todo)
12252 (org-let lprops '(org-tags-view '(4) match)))
12253 ((eq type 'todo)
12254 (org-let lprops '(org-todo-list match)))
12255 ((eq type 'tags-tree)
12256 (org-check-for-org-mode)
12257 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
12258 ((eq type 'todo-tree)
12259 (org-check-for-org-mode)
12260 (org-let lprops
12261 '(org-occur (concat "^" outline-regexp "[ \t]*"
12262 (regexp-quote match) "\\>"))))
12263 ((eq type 'occur-tree)
12264 (org-check-for-org-mode)
12265 (org-let lprops '(org-occur match)))
12266 ((fboundp type)
12267 (org-let lprops '(funcall type match)))
12268 (t (error "Invalid custom agenda command type %s" type))))
12269 (org-run-agenda-series (cddr entry))))
12270 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
12271 ((equal c ?a) (call-interactively 'org-agenda-list))
12272 ((equal c ?t) (call-interactively 'org-todo-list))
12273 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
12274 ((equal c ?m) (call-interactively 'org-tags-view))
12275 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
12276 ((equal c ?L)
12277 (unless restrict-ok
12278 (error "This is not an Org-mode file"))
12279 (org-call-with-arg 'org-timeline arg))
12280 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
12281 ((equal c ?!) (customize-variable 'org-stuck-projects))
12282 (t (error "Invalid key"))))))
12284 ;; FIXME: what is the meaning of WINDOW?????
12285 (defun org-run-agenda-series (series &optional window)
12286 (org-prepare-agenda)
12287 (let* ((org-agenda-multi t)
12288 (redo (list 'org-run-agenda-series (list 'quote series)))
12289 (org-select-agenda-window t)
12290 (cmds (car series))
12291 (gprops (nth 1 series))
12292 match ;; The byte compiler incorrectly complains about this. Keep it!
12293 cmd type lprops)
12294 (while (setq cmd (pop cmds))
12295 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
12296 (cond
12297 ((eq type 'agenda)
12298 (call-interactively 'org-agenda-list))
12299 ((eq type 'alltodo)
12300 (call-interactively 'org-todo-list))
12301 ((eq type 'stuck)
12302 (call-interactively 'org-agenda-list-stuck-projects))
12303 ((eq type 'tags)
12304 (org-let2 gprops lprops
12305 '(org-tags-view current-prefix-arg match)))
12306 ((eq type 'tags-todo)
12307 (org-let2 gprops lprops
12308 '(org-tags-view '(4) match)))
12309 ((eq type 'todo)
12310 (org-let2 gprops lprops
12311 '(org-todo-list match)))
12312 ((fboundp type)
12313 (org-let2 gprops lprops
12314 '(funcall type match)))
12315 (t (error "Invalid type in command series"))))
12316 (widen)
12317 (setq org-agenda-redo-command redo)
12318 (goto-char (point-min)))
12319 (org-finalize-agenda))
12321 ;;;###autoload
12322 (defmacro org-batch-agenda (cmd-key &rest parameters)
12323 "Run an agenda command in batch mode, send result to STDOUT.
12324 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
12325 Paramters are alternating variable names and values that will be bound
12326 before running the agenda command."
12327 (let (pars)
12328 (while parameters
12329 (push (list (pop parameters) (if parameters (pop parameters))) pars))
12330 (flet ((read-char-exclusive () (string-to-char cmd-key)))
12331 (eval (list 'let (nreverse pars) '(org-agenda nil))))
12332 (set-buffer "*Org Agenda*")
12333 (princ (buffer-string))))
12335 (defmacro org-no-read-only (&rest body)
12336 "Inhibit read-only for BODY."
12337 `(let ((inhibit-read-only t)) ,@body))
12339 (defun org-check-for-org-mode ()
12340 "Make sure current buffer is in org-mode. Error if not."
12341 (or (org-mode-p)
12342 (error "Cannot execute org-mode agenda command on buffer in %s."
12343 major-mode)))
12345 (defun org-fit-agenda-window ()
12346 "Fit the window to the buffer size."
12347 (and org-fit-agenda-window
12348 (memq org-agenda-window-setup '(reorganize-frame))
12349 (fboundp 'fit-window-to-buffer)
12350 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
12351 (/ (frame-height) 2))))
12353 ;;; Agenda file list
12355 (defun org-agenda-files (&optional unrestricted)
12356 "Get the list of agenda files.
12357 Optional UNRESTRICTED means return the full list even if a restriction
12358 is currently in place."
12359 (cond
12360 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12361 ((stringp org-agenda-files) (org-read-agenda-file-list))
12362 ((listp org-agenda-files) org-agenda-files)
12363 (t (error "Invalid value of `org-agenda-files'"))))
12365 (defun org-edit-agenda-file-list ()
12366 "Edit the list of agenda files.
12367 Depending on setup, this either uses customize to edit the variable
12368 `org-agenda-files', or it visits the file that is holding the list. In the
12369 latter case, the buffer is set up in a way that saving it automatically kills
12370 the buffer and restores the previous window configuration."
12371 (interactive)
12372 (if (stringp org-agenda-files)
12373 (let ((cw (current-window-configuration)))
12374 (find-file org-agenda-files)
12375 (org-set-local 'org-window-configuration cw)
12376 (org-add-hook 'after-save-hook
12377 (lambda ()
12378 (set-window-configuration
12379 (prog1 org-window-configuration
12380 (kill-buffer (current-buffer))))
12381 (org-install-agenda-files-menu)
12382 (message "New agenda file list installed"))
12383 nil 'local)
12384 (message (substitute-command-keys
12385 "Edit list and finish with \\[save-buffer]")))
12386 (customize-variable 'org-agenda-files)))
12388 (defun org-store-new-agenda-file-list (list)
12389 "Set new value for the agenda file list and save it correcly."
12390 (if (stringp org-agenda-files)
12391 (let ((f org-agenda-files) b)
12392 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12393 (with-temp-file f
12394 (insert (mapconcat 'identity list "\n") "\n")))
12395 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12396 (setq org-agenda-files list)
12397 (customize-save-variable 'org-agenda-files org-agenda-files))))
12399 (defun org-read-agenda-file-list ()
12400 "Read the list of agenda files from a file."
12401 (when (stringp org-agenda-files)
12402 (with-temp-buffer
12403 (insert-file-contents org-agenda-files)
12404 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12407 ;;;###autoload
12408 (defun org-cycle-agenda-files ()
12409 "Cycle through the files in `org-agenda-files'.
12410 If the current buffer visits an agenda file, find the next one in the list.
12411 If the current buffer does not, find the first agenda file."
12412 (interactive)
12413 (let* ((fs (org-agenda-files t))
12414 (files (append fs (list (car fs))))
12415 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12416 file)
12417 (unless files (error "No agenda files"))
12418 (catch 'exit
12419 (while (setq file (pop files))
12420 (if (equal (file-truename file) tcf)
12421 (when (car files)
12422 (find-file (car files))
12423 (throw 'exit t))))
12424 (find-file (car fs)))))
12426 (defun org-agenda-file-to-end ()
12427 "Move/add the current file to the end of the agenda file list.
12428 If the file is not present in the list, it is appended to the list. If it is
12429 present, it is moved there."
12430 (interactive)
12431 (org-agenda-file-to-front 'to-end))
12433 (defun org-agenda-file-to-front (&optional to-end)
12434 "Move/add the current file to the top of the agenda file list.
12435 If the file is not present in the list, it is added to the front. If it is
12436 present, it is moved there. With optional argument TO-END, add/move to the
12437 end of the list."
12438 (interactive "P")
12439 (let ((file-alist (mapcar (lambda (x)
12440 (cons (file-truename x) x))
12441 (org-agenda-files t)))
12442 (ctf (file-truename buffer-file-name))
12443 x had)
12444 (setq x (assoc ctf file-alist) had x)
12446 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12447 (if to-end
12448 (setq file-alist (append (delq x file-alist) (list x)))
12449 (setq file-alist (cons x (delq x file-alist))))
12450 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12451 (org-install-agenda-files-menu)
12452 (message "File %s to %s of agenda file list"
12453 (if had "moved" "added") (if to-end "end" "front"))))
12455 (defun org-remove-file (&optional file)
12456 "Remove current file from the list of files in variable `org-agenda-files'.
12457 These are the files which are being checked for agenda entries.
12458 Optional argument FILE means, use this file instead of the current."
12459 (interactive)
12460 (let* ((file (or file buffer-file-name))
12461 (true-file (file-truename file))
12462 (afile (abbreviate-file-name file))
12463 (files (delq nil (mapcar
12464 (lambda (x)
12465 (if (equal true-file
12466 (file-truename x))
12467 nil x))
12468 (org-agenda-files t)))))
12469 (if (not (= (length files) (length (org-agenda-files t))))
12470 (progn
12471 (org-store-new-agenda-file-list files)
12472 (org-install-agenda-files-menu)
12473 (message "Removed file: %s" afile))
12474 (message "File was not in list: %s" afile))))
12476 (defun org-file-menu-entry (file)
12477 (vector file (list 'find-file file) t))
12479 (defun org-check-agenda-file (file)
12480 "Make sure FILE exists. If not, ask user what to do."
12481 (when (not (file-exists-p file))
12482 (message "non-existent file %s. [R]emove from list or [A]bort?"
12483 (abbreviate-file-name file))
12484 (let ((r (downcase (read-char-exclusive))))
12485 (cond
12486 ((equal r ?r)
12487 (org-remove-file file)
12488 (throw 'nextfile t))
12489 (t (error "Abort"))))))
12491 ;;; Agenda prepare and finalize
12493 (defvar org-agenda-multi nil) ; dynammically scoped
12494 (defvar org-agenda-buffer-name "*Org Agenda*")
12495 (defvar org-pre-agenda-window-conf nil)
12496 (defun org-prepare-agenda ()
12497 (if org-agenda-multi
12498 (progn
12499 (setq buffer-read-only nil)
12500 (goto-char (point-max))
12501 (unless (= (point) 1)
12502 (insert "\n" (make-string (window-width) ?=) "\n"))
12503 (narrow-to-region (point) (point-max)))
12504 (org-agenda-maybe-reset-markers 'force)
12505 (org-prepare-agenda-buffers (org-agenda-files))
12506 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
12507 (awin (get-buffer-window abuf)))
12508 (cond
12509 ((equal (current-buffer) abuf) nil)
12510 (awin (select-window awin))
12511 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
12512 ((equal org-agenda-window-setup 'current-window)
12513 (switch-to-buffer abuf))
12514 ((equal org-agenda-window-setup 'other-window)
12515 (switch-to-buffer-other-window abuf))
12516 ((equal org-agenda-window-setup 'other-frame)
12517 (switch-to-buffer-other-frame abuf))
12518 ((equal org-agenda-window-setup 'reorganize-frame)
12519 (delete-other-windows)
12520 (switch-to-buffer-other-window abuf))))
12521 (setq buffer-read-only nil)
12522 (erase-buffer)
12523 (org-agenda-mode))
12524 (setq buffer-read-only nil))
12526 (defun org-finalize-agenda ()
12527 "Finishing touch for the agenda buffer, called just before displaying it."
12528 (unless org-agenda-multi
12529 (org-agenda-align-tags)
12530 (save-excursion
12531 (let ((buffer-read-only))
12532 (goto-char (point-min))
12533 (while (org-activate-bracket-links (point-max))
12534 (add-text-properties (match-beginning 0) (match-end 0)
12535 '(face org-link))))
12536 (run-hooks 'org-finalize-agenda-hook))))
12538 (defun org-prepare-agenda-buffers (files)
12539 "Create buffers for all agenda files, protect archived trees and comments."
12540 (interactive)
12541 (let ((pa '(:org-archived t))
12542 (pc '(:org-comment t))
12543 (pall '(:org-archived t :org-comment t))
12544 (rea (concat ":" org-archive-tag ":"))
12545 bmp file re)
12546 (save-excursion
12547 (while (setq file (pop files))
12548 (org-check-agenda-file file)
12549 (set-buffer (org-get-agenda-file-buffer file))
12550 (widen)
12551 (setq bmp (buffer-modified-p))
12552 (save-excursion
12553 (remove-text-properties (point-min) (point-max) pall)
12554 (when org-agenda-skip-archived-trees
12555 (goto-char (point-min))
12556 (while (re-search-forward rea nil t)
12557 (if (org-on-heading-p)
12558 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12559 (goto-char (point-min))
12560 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12561 (while (re-search-forward re nil t)
12562 (add-text-properties
12563 (match-beginning 0) (org-end-of-subtree t) pc)))
12564 (set-buffer-modified-p bmp)))))
12566 (defvar org-agenda-skip-function nil
12567 "Function to be called at each match during agenda construction.
12568 If this function return nil, the current match should not be skipped.
12569 Otherwise, the function must return a position from where the search
12570 should be continued.
12571 Never set this variable using `setq' or so, because then it will apply
12572 to all future agenda commands. Instead, bind it with `let' to scope
12573 it dynamically into the agenda-constructing command.")
12575 (defun org-agenda-skip ()
12576 "Throw to `:skip' in places that should be skipped.
12577 Also moves point to the end of the skipped region, so that search can
12578 continue from there."
12579 (let ((p (point-at-bol)) to)
12580 (and org-agenda-skip-archived-trees
12581 (get-text-property p :org-archived)
12582 (org-end-of-subtree t)
12583 (throw :skip t))
12584 (and (get-text-property p :org-comment)
12585 (org-end-of-subtree t)
12586 (throw :skip t))
12587 (if (equal (char-after p) ?#) (throw :skip t))
12588 (when (and (functionp org-agenda-skip-function)
12589 (setq to (save-excursion
12590 (save-match-data
12591 (funcall org-agenda-skip-function)))))
12592 (goto-char to)
12593 (throw :skip t))))
12595 (defvar org-agenda-markers nil
12596 "List of all currently active markers created by `org-agenda'.")
12597 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
12598 "Creation time of the last agenda marker.")
12600 (defun org-agenda-new-marker (&optional pos)
12601 "Return a new agenda marker.
12602 Org-mode keeps a list of these markers and resets them when they are
12603 no longer in use."
12604 (let ((m (copy-marker (or pos (point)))))
12605 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
12606 (push m org-agenda-markers)
12609 (defun org-agenda-maybe-reset-markers (&optional force)
12610 "Reset markers created by `org-agenda'. But only if they are old enough."
12611 (if (or (and force (not org-agenda-multi))
12612 (> (- (time-to-seconds (current-time))
12613 org-agenda-last-marker-time)
12615 (while org-agenda-markers
12616 (move-marker (pop org-agenda-markers) nil))))
12618 (defvar org-agenda-new-buffers nil
12619 "Buffers created to visit agenda files.")
12621 (defun org-get-agenda-file-buffer (file)
12622 "Get a buffer visiting FILE. If the buffer needs to be created, add
12623 it to the list of buffers which might be released later."
12624 (let ((buf (find-buffer-visiting file)))
12625 (if buf
12626 buf ; just return it
12627 ;; Make a new buffer and remember it
12628 (setq buf (find-file-noselect file))
12629 (if buf (push buf org-agenda-new-buffers))
12630 buf)))
12632 (defun org-release-buffers (blist)
12633 "Release all buffers in list, asking the user for confirmation when needed.
12634 When a buffer is unmodified, it is just killed. When modified, it is saved
12635 \(if the user agrees) and then killed."
12636 (let (buf file)
12637 (while (setq buf (pop blist))
12638 (setq file (buffer-file-name buf))
12639 (when (and (buffer-modified-p buf)
12640 file
12641 (y-or-n-p (format "Save file %s? " file)))
12642 (with-current-buffer buf (save-buffer)))
12643 (kill-buffer buf))))
12645 (defvar org-category-table nil)
12646 (defun org-get-category-table ()
12647 "Get the table of categories and positions in current buffer."
12648 (let (tbl)
12649 (save-excursion
12650 (goto-char (point-min))
12651 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
12652 (push (cons (point) (org-trim (match-string 2))) tbl)))
12653 tbl))
12655 (defun org-get-category (&optional pos)
12656 "Get the category applying to position POS."
12657 (if (not org-category-table)
12658 (cond
12659 ((null org-category)
12660 (setq org-category
12661 (if buffer-file-name
12662 (file-name-sans-extension
12663 (file-name-nondirectory buffer-file-name))
12664 "???")))
12665 ((symbolp org-category) (symbol-name org-category))
12666 (t org-category))
12667 (let ((tbl org-category-table)
12668 (pos (or pos (point))))
12669 (while (and tbl (> (caar tbl) pos))
12670 (pop tbl))
12671 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
12672 org-category-table))))))
12673 ;;; Agenda timeline
12675 (defun org-timeline (&optional include-all)
12676 "Show a time-sorted view of the entries in the current org file.
12677 Only entries with a time stamp of today or later will be listed. With
12678 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
12679 under the current date.
12680 If the buffer contains an active region, only check the region for
12681 dates."
12682 (interactive "P")
12683 (require 'calendar)
12684 (org-compile-prefix-format 'timeline)
12685 (org-set-sorting-strategy 'timeline)
12686 (let* ((dopast t)
12687 (dotodo include-all)
12688 (doclosed org-agenda-show-log)
12689 (entry buffer-file-name)
12690 (date (calendar-current-date))
12691 (win (selected-window))
12692 (pos1 (point))
12693 (beg (if (org-region-active-p) (region-beginning) (point-min)))
12694 (end (if (org-region-active-p) (region-end) (point-max)))
12695 (day-numbers (org-get-all-dates beg end 'no-ranges
12696 t doclosed ; always include today
12697 org-timeline-show-empty-dates))
12698 (today (time-to-days (current-time)))
12699 (past t)
12700 args
12701 s e rtn d emptyp)
12702 (setq org-agenda-redo-command
12703 (list 'progn
12704 (list 'switch-to-buffer-other-window (current-buffer))
12705 (list 'org-timeline (list 'quote include-all))))
12706 (if (not dopast)
12707 ;; Remove past dates from the list of dates.
12708 (setq day-numbers (delq nil (mapcar (lambda(x)
12709 (if (>= x today) x nil))
12710 day-numbers))))
12711 (org-prepare-agenda)
12712 (if doclosed (push :closed args))
12713 (push :timestamp args)
12714 (if dotodo (push :todo args))
12715 (while (setq d (pop day-numbers))
12716 (if (and (listp d) (eq (car d) :omitted))
12717 (progn
12718 (setq s (point))
12719 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
12720 (put-text-property s (1- (point)) 'face 'org-level-3))
12721 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
12722 (if (and (>= d today)
12723 dopast
12724 past)
12725 (progn
12726 (setq past nil)
12727 (insert (make-string 79 ?-) "\n")))
12728 (setq date (calendar-gregorian-from-absolute d))
12729 (setq s (point))
12730 (setq rtn (and (not emptyp)
12731 (apply 'org-agenda-get-day-entries
12732 entry date args)))
12733 (if (or rtn (equal d today) org-timeline-show-empty-dates)
12734 (progn
12735 (insert (calendar-day-name date) " "
12736 (number-to-string (extract-calendar-day date)) " "
12737 (calendar-month-name (extract-calendar-month date)) " "
12738 (number-to-string (extract-calendar-year date)) "\n")
12739 (put-text-property s (1- (point)) 'face
12740 'org-level-3)
12741 (if (equal d today)
12742 (put-text-property s (1- (point)) 'org-today t))
12743 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
12744 (put-text-property s (1- (point)) 'day d)))))
12745 (goto-char (point-min))
12746 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
12747 (point-min)))
12748 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
12749 (org-finalize-agenda)
12750 (setq buffer-read-only t)
12751 (when (not org-select-agenda-window)
12752 (select-window win)
12753 (goto-char pos1))))
12754 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
12755 "Return a list of all relevant day numbers from BEG to END buffer positions.
12756 If NO-RANGES is non-nil, include only the start and end dates of a range,
12757 not every single day in the range. If FORCE-TODAY is non-nil, make
12758 sure that TODAY is included in the list. If INACTIVE is non-nil, also
12759 inactive time stamps (those in square brackets) are included.
12760 When EMPTY is non-nil, also include days without any entries."
12761 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
12762 dates dates1 date day day1 day2 ts1 ts2)
12763 (if force-today
12764 (setq dates (list (time-to-days (current-time)))))
12765 (save-excursion
12766 (goto-char beg)
12767 (while (re-search-forward re end t)
12768 (setq day (time-to-days (org-time-string-to-time
12769 (substring (match-string 1) 0 10))))
12770 (or (memq day dates) (push day dates)))
12771 (unless no-ranges
12772 (goto-char beg)
12773 (while (re-search-forward org-tr-regexp end t)
12774 (setq ts1 (substring (match-string 1) 0 10)
12775 ts2 (substring (match-string 2) 0 10)
12776 day1 (time-to-days (org-time-string-to-time ts1))
12777 day2 (time-to-days (org-time-string-to-time ts2)))
12778 (while (< (setq day1 (1+ day1)) day2)
12779 (or (memq day1 dates) (push day1 dates)))))
12780 (setq dates (sort dates '<))
12781 (when empty
12782 (while (setq day (pop dates))
12783 (setq day2 (car dates))
12784 (push day dates1)
12785 (when (and day2 empty)
12786 (if (or (eq empty t)
12787 (and (numberp empty) (<= (- day2 day) empty)))
12788 (while (< (setq day (1+ day)) day2)
12789 (push (list day) dates1))
12790 (push (cons :omitted (- day2 day)) dates1))))
12791 (setq dates (nreverse dates1)))
12792 dates)))
12794 ;;; Agenda Daily/Weekly
12796 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
12797 (defvar org-agenda-last-arguments nil
12798 "The arguments of the previous call to org-agenda")
12799 (defvar org-starting-day nil) ; local variable in the agenda buffer
12800 (defvar org-include-all-loc nil) ; local variable
12803 ;;;###autoload
12804 (defun org-agenda-list (&optional include-all start-day ndays)
12805 "Produce a weekly view from all files in variable `org-agenda-files'.
12806 The view will be for the current week, but from the overview buffer you
12807 will be able to go to other weeks.
12808 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
12809 also be shown, under the current date.
12810 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
12811 on the days are also shown. See the variable `org-log-done' for how
12812 to turn on logging.
12813 START-DAY defaults to TODAY, or to the most recent match for the weekday
12814 given in `org-agenda-start-on-weekday'.
12815 NDAYS defaults to `org-agenda-ndays'."
12816 (interactive "P")
12817 (if org-agenda-overriding-arguments
12818 (setq include-all (car org-agenda-overriding-arguments)
12819 start-day (nth 1 org-agenda-overriding-arguments)
12820 ndays (nth 2 org-agenda-overriding-arguments)))
12821 (setq org-agenda-last-arguments (list include-all start-day ndays))
12822 (org-compile-prefix-format 'agenda)
12823 (org-set-sorting-strategy 'agenda)
12824 (require 'calendar)
12825 (let* ((org-agenda-start-on-weekday
12826 (if (or (equal ndays 1)
12827 (and (null ndays) (equal 1 org-agenda-ndays)))
12828 nil org-agenda-start-on-weekday))
12829 (thefiles (org-agenda-files))
12830 (files thefiles)
12831 (win (selected-window))
12832 (today (time-to-days (current-time)))
12833 (sd (or start-day today))
12834 (start (if (or (null org-agenda-start-on-weekday)
12835 (< org-agenda-ndays 7))
12837 (let* ((nt (calendar-day-of-week
12838 (calendar-gregorian-from-absolute sd)))
12839 (n1 org-agenda-start-on-weekday)
12840 (d (- nt n1)))
12841 (- sd (+ (if (< d 0) 7 0) d)))))
12842 (day-numbers (list start))
12843 (inhibit-redisplay t)
12844 s e rtn rtnall file date d start-pos end-pos todayp nd)
12845 (setq org-agenda-redo-command
12846 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
12847 ;; Make the list of days
12848 (setq ndays (or ndays org-agenda-ndays)
12849 nd ndays)
12850 (while (> ndays 1)
12851 (push (1+ (car day-numbers)) day-numbers)
12852 (setq ndays (1- ndays)))
12853 (setq day-numbers (nreverse day-numbers))
12854 (org-prepare-agenda)
12855 (org-set-local 'org-starting-day (car day-numbers))
12856 (org-set-local 'org-include-all-loc include-all)
12857 (when (and (or include-all org-agenda-include-all-todo)
12858 (member today day-numbers))
12859 (setq files thefiles
12860 rtnall nil)
12861 (while (setq file (pop files))
12862 (catch 'nextfile
12863 (org-check-agenda-file file)
12864 (setq date (calendar-gregorian-from-absolute today)
12865 rtn (org-agenda-get-day-entries
12866 file date :todo))
12867 (setq rtnall (append rtnall rtn))))
12868 (when rtnall
12869 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
12870 (add-text-properties (point-min) (1- (point))
12871 (list 'face 'org-level-3))
12872 (insert (org-finalize-agenda-entries rtnall) "\n")))
12873 (setq s (point))
12874 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
12875 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
12876 (while (setq d (pop day-numbers))
12877 (setq date (calendar-gregorian-from-absolute d)
12878 s (point))
12879 (if (or (setq todayp (= d today))
12880 (and (not start-pos) (= d sd)))
12881 (setq start-pos (point))
12882 (if (and start-pos (not end-pos))
12883 (setq end-pos (point))))
12884 (setq files thefiles
12885 rtnall nil)
12886 (while (setq file (pop files))
12887 (catch 'nextfile
12888 (org-check-agenda-file file)
12889 (if org-agenda-show-log
12890 (setq rtn (org-agenda-get-day-entries
12891 file date
12892 :deadline :scheduled :timestamp :closed))
12893 (setq rtn (org-agenda-get-day-entries
12894 file date
12895 :deadline :scheduled :timestamp)))
12896 (setq rtnall (append rtnall rtn))))
12897 (if org-agenda-include-diary
12898 (progn
12899 (require 'diary-lib)
12900 (setq rtn (org-get-entries-from-diary date))
12901 (setq rtnall (append rtnall rtn))))
12902 (if (or rtnall org-agenda-show-all-dates)
12903 (progn
12904 (insert (format "%-9s %2d %s %4d\n"
12905 (calendar-day-name date)
12906 (extract-calendar-day date)
12907 (calendar-month-name (extract-calendar-month date))
12908 (extract-calendar-year date)))
12909 (put-text-property s (1- (point)) 'face
12910 'org-level-3)
12911 (if todayp (put-text-property s (1- (point)) 'org-today t))
12913 (if rtnall (insert
12914 (org-finalize-agenda-entries
12915 (org-agenda-add-time-grid-maybe
12916 rtnall nd todayp))
12917 "\n"))
12918 (put-text-property s (1- (point)) 'day d))))
12919 (goto-char (point-min))
12920 (org-fit-agenda-window)
12921 (unless (and (pos-visible-in-window-p (point-min))
12922 (pos-visible-in-window-p (point-max)))
12923 (goto-char (1- (point-max)))
12924 (recenter -1)
12925 (if (not (pos-visible-in-window-p (or start-pos 1)))
12926 (progn
12927 (goto-char (or start-pos 1))
12928 (recenter 1))))
12929 (goto-char (or start-pos 1))
12930 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
12931 (org-finalize-agenda)
12932 (setq buffer-read-only t)
12933 (if (not org-select-agenda-window) (select-window win))
12934 (message "")))
12936 ;;; Agenda TODO list
12938 (defvar org-select-this-todo-keyword nil)
12939 (defvar org-last-arg nil)
12941 ;;;###autoload
12942 (defun org-todo-list (arg)
12943 "Show all TODO entries from all agenda file in a single list.
12944 The prefix arg can be used to select a specific TODO keyword and limit
12945 the list to these. When using \\[universal-argument], you will be prompted
12946 for a keyword. A numeric prefix directly selects the Nth keyword in
12947 `org-todo-keywords'."
12948 (interactive "P")
12949 (require 'calendar)
12950 (org-compile-prefix-format 'todo)
12951 (org-set-sorting-strategy 'todo)
12952 (let* ((today (time-to-days (current-time)))
12953 (date (calendar-gregorian-from-absolute today))
12954 (win (selected-window))
12955 (kwds org-todo-keywords)
12956 (completion-ignore-case t)
12957 (org-select-this-todo-keyword
12958 (if (stringp arg) arg
12959 (and arg (integerp arg) (> arg 0)
12960 (nth (1- arg) org-todo-keywords))))
12961 rtn rtnall files file pos)
12962 (when (equal arg '(4))
12963 (setq org-select-this-todo-keyword
12964 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
12965 nil t)))
12966 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
12967 (org-prepare-agenda)
12968 (org-set-local 'org-last-arg arg)
12969 (org-set-local 'org-todo-keywords kwds)
12970 (setq org-agenda-redo-command
12971 '(org-todo-list (or current-prefix-arg org-last-arg)))
12972 (setq files (org-agenda-files)
12973 rtnall nil)
12974 (while (setq file (pop files))
12975 (catch 'nextfile
12976 (org-check-agenda-file file)
12977 (setq rtn (org-agenda-get-day-entries file date :todo))
12978 (setq rtnall (append rtnall rtn))))
12979 (if org-agenda-overriding-header
12980 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
12981 nil 'face 'org-level-3) "\n")
12982 (insert "Global list of TODO items of type: ")
12983 (add-text-properties (point-min) (1- (point))
12984 (list 'face 'org-level-3))
12985 (setq pos (point))
12986 (insert (or org-select-this-todo-keyword "ALL") "\n")
12987 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
12988 (setq pos (point))
12989 (unless org-agenda-multi
12990 (insert
12991 "Available with `N r': (0)ALL "
12992 (let ((n 0))
12993 (mapconcat (lambda (x)
12994 (format "(%d)%s" (setq n (1+ n)) x))
12995 org-todo-keywords " "))
12996 "\n"))
12997 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
12998 (when rtnall
12999 (insert (org-finalize-agenda-entries rtnall) "\n"))
13000 (goto-char (point-min))
13001 (org-fit-agenda-window)
13002 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
13003 (org-finalize-agenda)
13004 (setq buffer-read-only t)
13005 (if (not org-select-agenda-window) (select-window win))))
13007 ;;; Agenda tags match
13009 ;;;###autoload
13010 (defun org-tags-view (&optional todo-only match)
13011 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
13012 The prefix arg TODO-ONLY limits the search to TODO entries."
13013 (interactive "P")
13014 (org-compile-prefix-format 'tags)
13015 (org-set-sorting-strategy 'tags)
13016 (let* ((org-tags-match-list-sublevels
13017 (if todo-only t org-tags-match-list-sublevels))
13018 (win (selected-window))
13019 (completion-ignore-case t)
13020 rtn rtnall files file pos matcher
13021 buffer)
13022 (setq matcher (org-make-tags-matcher match)
13023 match (car matcher) matcher (cdr matcher))
13024 (org-prepare-agenda)
13025 (setq org-agenda-redo-command
13026 (list 'org-tags-view (list 'quote todo-only)
13027 (list 'if 'current-prefix-arg nil match)))
13028 (setq files (org-agenda-files)
13029 rtnall nil)
13030 (while (setq file (pop files))
13031 (catch 'nextfile
13032 (org-check-agenda-file file)
13033 (setq buffer (if (file-exists-p file)
13034 (org-get-agenda-file-buffer file)
13035 (error "No such file %s" file)))
13036 (if (not buffer)
13037 ;; If file does not exist, merror message to agenda
13038 (setq rtn (list
13039 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
13040 rtnall (append rtnall rtn))
13041 (with-current-buffer buffer
13042 (unless (org-mode-p)
13043 (error "Agenda file %s is not in `org-mode'" file))
13044 (setq org-category-table (org-get-category-table))
13045 (save-excursion
13046 (save-restriction
13047 (if org-agenda-restrict
13048 (narrow-to-region org-agenda-restrict-begin
13049 org-agenda-restrict-end)
13050 (widen))
13051 (setq rtn (org-scan-tags 'agenda matcher todo-only))
13052 (setq rtnall (append rtnall rtn))))))))
13053 (if org-agenda-overriding-header
13054 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
13055 nil 'face 'org-level-3) "\n")
13056 (insert "Headlines with TAGS match: ")
13057 (add-text-properties (point-min) (1- (point))
13058 (list 'face 'org-level-3))
13059 (setq pos (point))
13060 (insert match "\n")
13061 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
13062 (setq pos (point))
13063 (unless org-agenda-multi
13064 (insert "Press `C-u r' to search again with new search string\n"))
13065 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
13066 (when rtnall
13067 (insert (org-finalize-agenda-entries rtnall) "\n"))
13068 (goto-char (point-min))
13069 (org-fit-agenda-window)
13070 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
13071 (org-finalize-agenda)
13072 (setq buffer-read-only t)
13073 (if (not org-select-agenda-window) (select-window win))))
13075 ;;; Agenda Finding stuck projects
13077 (defvar org-agenda-skip-regexp nil
13078 "Regular expression used in skipping subtrees for the agenda.
13079 This is basically a temporary global variable that can be set and then
13080 used by user-defined selections using `org-agenda-skip-function'.")
13082 (defvar org-agenda-overriding-header nil
13083 "When this is set during todo and tags searches, will replace header.")
13085 (defun org-agenda-skip-subtree-when-regexp-matches ()
13086 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
13087 If yes, it returns the end position of this tree, causing agenda commands
13088 to skip this subtree. This is a function that can be put into
13089 `org-agenda-skip-function' for the duration of a command."
13090 (save-match-data
13091 (let ((end (save-excursion (org-end-of-subtree t)))
13092 skip)
13093 (save-excursion
13094 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
13095 (and skip end))))
13097 (defun org-agenda-list-stuck-projects (&rest ignore)
13098 "Create agenda view for projects that are stuck.
13099 Stuck projects are project that have no next actions. For the definitions
13100 of what a project is and how to check if it stuck, customize the variable
13101 `org-stuck-projects'.
13102 MATCH is being ignored."
13103 (interactive)
13104 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
13105 (org-agenda-overriding-header "List of stuck projects: ")
13106 (matcher (nth 0 org-stuck-projects))
13107 (todo (nth 1 org-stuck-projects))
13108 (tags (nth 2 org-stuck-projects))
13109 (todo-re (concat "^\\*+[ \t]+\\("
13110 (mapconcat 'identity todo "\\|")
13111 "\\)\\>"))
13112 (tags-re (concat "^\\*+.*:\\("
13113 (mapconcat 'identity tags "\\|")
13114 "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
13116 (setq org-agenda-skip-regexp
13117 (cond
13118 ((and todo tags)
13119 (concat todo-re "\\|" tags-re))
13120 (todo todo-re)
13121 (tags tags-re)
13122 (t (error "No information how to identify unstuck projects"))))
13123 (org-tags-view nil matcher)
13124 (with-current-buffer org-agenda-buffer-name
13125 (setq org-agenda-redo-command
13126 '(org-agenda-list-stuck-projects
13127 (or current-prefix-arg org-last-arg))))))
13129 ;;; Diary integration
13131 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
13133 (defun org-get-entries-from-diary (date)
13134 "Get the (Emacs Calendar) diary entries for DATE."
13135 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
13136 (diary-display-hook '(fancy-diary-display))
13137 (list-diary-entries-hook
13138 (cons 'org-diary-default-entry list-diary-entries-hook))
13139 (diary-file-name-prefix-function nil) ; turn this feature off
13140 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
13141 entries
13142 (org-disable-agenda-to-diary t))
13143 (save-excursion
13144 (save-window-excursion
13145 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
13146 (if (not (get-buffer fancy-diary-buffer))
13147 (setq entries nil)
13148 (with-current-buffer fancy-diary-buffer
13149 (setq buffer-read-only nil)
13150 (if (= (point-max) 1)
13151 ;; No entries
13152 (setq entries nil)
13153 ;; Omit the date and other unnecessary stuff
13154 (org-agenda-cleanup-fancy-diary)
13155 ;; Add prefix to each line and extend the text properties
13156 (if (= (point-max) 1)
13157 (setq entries nil)
13158 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
13159 (set-buffer-modified-p nil)
13160 (kill-buffer fancy-diary-buffer)))
13161 (when entries
13162 (setq entries (org-split-string entries "\n"))
13163 (setq entries
13164 (mapcar
13165 (lambda (x)
13166 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
13167 ;; Extend the text properties to the beginning of the line
13168 (org-add-props x (text-properties-at (1- (length x)) x)))
13169 entries)))))
13171 (defun org-agenda-cleanup-fancy-diary ()
13172 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
13173 This gets rid of the date, the underline under the date, and
13174 the dummy entry installed by `org-mode' to ensure non-empty diary for each
13175 date. It also removes lines that contain only whitespace."
13176 (goto-char (point-min))
13177 (if (looking-at ".*?:[ \t]*")
13178 (progn
13179 (replace-match "")
13180 (re-search-forward "\n=+$" nil t)
13181 (replace-match "")
13182 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
13183 (re-search-forward "\n=+$" nil t)
13184 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
13185 (goto-char (point-min))
13186 (while (re-search-forward "^ +\n" nil t)
13187 (replace-match ""))
13188 (goto-char (point-min))
13189 (if (re-search-forward "^Org-mode dummy\n?" nil t)
13190 (replace-match "")))
13192 ;; Make sure entries from the diary have the right text properties.
13193 (eval-after-load "diary-lib"
13194 '(if (boundp 'diary-modify-entry-list-string-function)
13195 ;; We can rely on the hook, nothing to do
13197 ;; Hook not avaiable, must use advice to make this work
13198 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
13199 "Make the position visible."
13200 (if (and org-disable-agenda-to-diary ;; called from org-agenda
13201 (stringp string)
13202 buffer-file-name)
13203 (setq string (org-modify-diary-entry-string string))))))
13205 (defun org-modify-diary-entry-string (string)
13206 "Add text properties to string, allowing org-mode to act on it."
13207 (org-add-props string nil
13208 'mouse-face 'highlight
13209 'keymap org-agenda-keymap
13210 'help-echo (format "mouse-2 or RET jump to diary file %s"
13211 (abbreviate-file-name buffer-file-name))
13212 'org-agenda-diary-link t
13213 'org-marker (org-agenda-new-marker (point-at-bol))))
13215 (defun org-diary-default-entry ()
13216 "Add a dummy entry to the diary.
13217 Needed to avoid empty dates which mess up holiday display."
13218 ;; Catch the error if dealing with the new add-to-diary-alist
13219 (when org-disable-agenda-to-diary
13220 (condition-case nil
13221 (add-to-diary-list original-date "Org-mode dummy" "")
13222 (error
13223 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
13225 ;;;###autoload
13226 (defun org-diary (&rest args)
13227 "Return diary information from org-files.
13228 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
13229 It accesses org files and extracts information from those files to be
13230 listed in the diary. The function accepts arguments specifying what
13231 items should be listed. The following arguments are allowed:
13233 :timestamp List the headlines of items containing a date stamp or
13234 date range matching the selected date. Deadlines will
13235 also be listed, on the expiration day.
13237 :deadline List any deadlines past due, or due within
13238 `org-deadline-warning-days'. The listing occurs only
13239 in the diary for *today*, not at any other date. If
13240 an entry is marked DONE, it is no longer listed.
13242 :scheduled List all items which are scheduled for the given date.
13243 The diary for *today* also contains items which were
13244 scheduled earlier and are not yet marked DONE.
13246 :todo List all TODO items from the org-file. This may be a
13247 long list - so this is not turned on by default.
13248 Like deadlines, these entries only show up in the
13249 diary for *today*, not at any other date.
13251 The call in the diary file should look like this:
13253 &%%(org-diary) ~/path/to/some/orgfile.org
13255 Use a separate line for each org file to check. Or, if you omit the file name,
13256 all files listed in `org-agenda-files' will be checked automatically:
13258 &%%(org-diary)
13260 If you don't give any arguments (as in the example above), the default
13261 arguments (:deadline :scheduled :timestamp) are used. So the example above may
13262 also be written as
13264 &%%(org-diary :deadline :timestamp :scheduled)
13266 The function expects the lisp variables `entry' and `date' to be provided
13267 by the caller, because this is how the calendar works. Don't use this
13268 function from a program - use `org-agenda-get-day-entries' instead."
13269 (org-agenda-maybe-reset-markers)
13270 (org-compile-prefix-format 'agenda)
13271 (org-set-sorting-strategy 'agenda)
13272 (setq args (or args '(:deadline :scheduled :timestamp)))
13273 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
13274 (list entry)
13275 (org-agenda-files t)))
13276 file rtn results)
13277 ;; If this is called during org-agenda, don't return any entries to
13278 ;; the calendar. Org Agenda will list these entries itself.
13279 (if org-disable-agenda-to-diary (setq files nil))
13280 (while (setq file (pop files))
13281 (setq rtn (apply 'org-agenda-get-day-entries file date args))
13282 (setq results (append results rtn)))
13283 (if results
13284 (concat (org-finalize-agenda-entries results) "\n"))))
13286 ;;; Agenda entry finders
13288 (defun org-agenda-get-day-entries (file date &rest args)
13289 "Does the work for `org-diary' and `org-agenda'.
13290 FILE is the path to a file to be checked for entries. DATE is date like
13291 the one returned by `calendar-current-date'. ARGS are symbols indicating
13292 which kind of entries should be extracted. For details about these, see
13293 the documentation of `org-diary'."
13294 (setq args (or args '(:deadline :scheduled :timestamp)))
13295 (let* ((org-startup-with-deadline-check nil)
13296 (org-startup-folded nil)
13297 (org-startup-align-all-tables nil)
13298 (buffer (if (file-exists-p file)
13299 (org-get-agenda-file-buffer file)
13300 (error "No such file %s" file)))
13301 arg results rtn)
13302 (if (not buffer)
13303 ;; If file does not exist, make sure an error message ends up in diary
13304 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
13305 (with-current-buffer buffer
13306 (unless (org-mode-p)
13307 (error "Agenda file %s is not in `org-mode'" file))
13308 (setq org-category-table (org-get-category-table))
13309 (let ((case-fold-search nil))
13310 (save-excursion
13311 (save-restriction
13312 (if org-agenda-restrict
13313 (narrow-to-region org-agenda-restrict-begin
13314 org-agenda-restrict-end)
13315 (widen))
13316 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
13317 (while (setq arg (pop args))
13318 (cond
13319 ((and (eq arg :todo)
13320 (equal date (calendar-current-date)))
13321 (setq rtn (org-agenda-get-todos))
13322 (setq results (append results rtn)))
13323 ((eq arg :timestamp)
13324 (setq rtn (org-agenda-get-blocks))
13325 (setq results (append results rtn))
13326 (setq rtn (org-agenda-get-timestamps))
13327 (setq results (append results rtn)))
13328 ((eq arg :scheduled)
13329 (setq rtn (org-agenda-get-scheduled))
13330 (setq results (append results rtn)))
13331 ((eq arg :closed)
13332 (setq rtn (org-agenda-get-closed))
13333 (setq results (append results rtn)))
13334 ((and (eq arg :deadline)
13335 (equal date (calendar-current-date)))
13336 (setq rtn (org-agenda-get-deadlines))
13337 (setq results (append results rtn))))))))
13338 results))))
13340 (defun org-entry-is-done-p ()
13341 "Is the current entry marked DONE?"
13342 (save-excursion
13343 (and (re-search-backward "[\r\n]\\*" nil t)
13344 (looking-at org-nl-done-regexp))))
13346 (defun org-at-date-range-p (&optional inactive-ok)
13347 "Is the cursor inside a date range?"
13348 (interactive)
13349 (save-excursion
13350 (catch 'exit
13351 (let ((pos (point)))
13352 (skip-chars-backward "^[<\r\n")
13353 (skip-chars-backward "<[")
13354 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13355 (>= (match-end 0) pos)
13356 (throw 'exit t))
13357 (skip-chars-backward "^<[\r\n")
13358 (skip-chars-backward "<[")
13359 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13360 (>= (match-end 0) pos)
13361 (throw 'exit t)))
13362 nil)))
13364 (defun org-agenda-get-todos ()
13365 "Return the TODO information for agenda display."
13366 (let* ((props (list 'face nil
13367 'done-face 'org-done
13368 'org-not-done-regexp org-not-done-regexp
13369 'mouse-face 'highlight
13370 'keymap org-agenda-keymap
13371 'help-echo
13372 (format "mouse-2 or RET jump to org file %s"
13373 (abbreviate-file-name buffer-file-name))))
13374 (regexp (concat "[\n\r]\\*+ *\\("
13375 (if org-select-this-todo-keyword
13376 (concat "\\<\\(" org-select-this-todo-keyword
13377 "\\)\\>")
13378 org-not-done-regexp)
13379 "[^\n\r]*\\)"))
13380 (deadline-re (concat ".*\\(\n[^*].*\\)?" org-deadline-time-regexp))
13381 (sched-re (concat ".*\\(\n[^*].*\\)?" org-scheduled-time-regexp))
13382 marker priority category tags
13383 ee txt)
13384 (goto-char (point-min))
13385 (while (re-search-forward regexp nil t)
13386 (catch :skip
13387 (save-match-data
13388 (beginning-of-line)
13389 (when (or (and org-agenda-todo-ignore-scheduled
13390 (looking-at sched-re))
13391 (and org-agenda-todo-ignore-deadlines
13392 (looking-at deadline-re)
13393 (org-deadline-close (match-string 2))))
13395 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
13396 (throw :skip nil)))
13397 (org-agenda-skip)
13398 (goto-char (match-beginning 1))
13399 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
13400 category (org-get-category)
13401 tags (org-get-tags-at (point))
13402 txt (org-format-agenda-item "" (match-string 1) category tags)
13403 priority
13404 (+ (org-get-priority txt)
13405 (if org-todo-kwd-priority-p
13406 (- org-todo-kwd-max-priority -2
13407 (length
13408 (member (match-string 2) org-todo-keywords)))
13409 1)))
13410 (org-add-props txt props
13411 'org-marker marker 'org-hd-marker marker
13412 'priority priority 'category category)
13413 (push txt ee)
13414 (if org-agenda-todo-list-sublevels
13415 (goto-char (match-end 1))
13416 (org-end-of-subtree 'invisible))))
13417 (nreverse ee)))
13419 (defconst org-agenda-no-heading-message
13420 "No heading for this item in buffer or region.")
13422 (defun org-agenda-get-timestamps ()
13423 "Return the date stamp information for agenda display."
13424 (let* ((props (list 'face nil
13425 'org-not-done-regexp org-not-done-regexp
13426 'mouse-face 'highlight
13427 'keymap org-agenda-keymap
13428 'help-echo
13429 (format "mouse-2 or RET jump to org file %s"
13430 (abbreviate-file-name buffer-file-name))))
13431 (regexp (regexp-quote
13432 (substring
13433 (format-time-string
13434 (car org-time-stamp-formats)
13435 (apply 'encode-time ; DATE bound by calendar
13436 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
13437 0 11)))
13438 marker hdmarker deadlinep scheduledp donep tmp priority category
13439 ee txt timestr tags)
13440 (goto-char (point-min))
13441 (while (re-search-forward regexp nil t)
13442 (catch :skip
13443 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
13444 (org-agenda-skip)
13445 (setq marker (org-agenda-new-marker (match-beginning 0))
13446 category (org-get-category (match-beginning 0))
13447 tmp (buffer-substring (max (point-min)
13448 (- (match-beginning 0)
13449 org-ds-keyword-length))
13450 (match-beginning 0))
13451 timestr (buffer-substring (match-beginning 0) (point-at-eol))
13452 deadlinep (string-match org-deadline-regexp tmp)
13453 scheduledp (string-match org-scheduled-regexp tmp)
13454 donep (org-entry-is-done-p))
13455 (and org-agenda-skip-scheduled-if-done
13456 scheduledp donep
13457 (throw :skip t))
13458 (if (string-match ">" timestr)
13459 ;; substring should only run to end of time stamp
13460 (setq timestr (substring timestr 0 (match-end 0))))
13461 (save-excursion
13462 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
13463 (progn
13464 (goto-char (match-end 1))
13465 (setq hdmarker (org-agenda-new-marker)
13466 tags (org-get-tags-at))
13467 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
13468 (setq txt (org-format-agenda-item
13469 (format "%s%s"
13470 (if deadlinep "Deadline: " "")
13471 (if scheduledp "Scheduled: " ""))
13472 (match-string 1) category tags timestr)))
13473 (setq txt org-agenda-no-heading-message))
13474 (setq priority (org-get-priority txt))
13475 (org-add-props txt props
13476 'org-marker marker 'org-hd-marker hdmarker)
13477 (if deadlinep
13478 (org-add-props txt nil
13479 'face (if donep 'org-done 'org-warning)
13480 'undone-face 'org-warning 'done-face 'org-done
13481 'category category 'priority (+ 100 priority))
13482 (if scheduledp
13483 (org-add-props txt nil
13484 'face 'org-scheduled-today
13485 'undone-face 'org-scheduled-today 'done-face 'org-done
13486 'category category 'priority (+ 99 priority))
13487 (org-add-props txt nil 'priority priority 'category category)))
13488 (push txt ee))
13489 (outline-next-heading)))
13490 (nreverse ee)))
13492 (defun org-agenda-get-closed ()
13493 "Return the logged TODO entries for agenda display."
13494 (let* ((props (list 'mouse-face 'highlight
13495 'org-not-done-regexp org-not-done-regexp
13496 'keymap org-agenda-keymap
13497 'help-echo
13498 (format "mouse-2 or RET jump to org file %s"
13499 (abbreviate-file-name buffer-file-name))))
13500 (regexp (concat
13501 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
13502 (regexp-quote
13503 (substring
13504 (format-time-string
13505 (car org-time-stamp-formats)
13506 (apply 'encode-time ; DATE bound by calendar
13507 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
13508 1 11))))
13509 marker hdmarker priority category tags closedp
13510 ee txt timestr)
13511 (goto-char (point-min))
13512 (while (re-search-forward regexp nil t)
13513 (catch :skip
13514 (org-agenda-skip)
13515 (setq marker (org-agenda-new-marker (match-beginning 0))
13516 closedp (equal (match-string 1) org-closed-string)
13517 category (org-get-category (match-beginning 0))
13518 timestr (buffer-substring (match-beginning 0) (point-at-eol))
13519 ;; donep (org-entry-is-done-p)
13521 (if (string-match "\\]" timestr)
13522 ;; substring should only run to end of time stamp
13523 (setq timestr (substring timestr 0 (match-end 0))))
13524 (save-excursion
13525 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
13526 (progn
13527 (goto-char (match-end 1))
13528 (setq hdmarker (org-agenda-new-marker)
13529 tags (org-get-tags-at))
13530 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
13531 (setq txt (org-format-agenda-item
13532 (if closedp "Closed: " "Clocked: ")
13533 (match-string 1) category tags timestr)))
13534 (setq txt org-agenda-no-heading-message))
13535 (setq priority 100000)
13536 (org-add-props txt props
13537 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
13538 'priority priority 'category category
13539 'undone-face 'org-warning 'done-face 'org-done)
13540 (push txt ee))
13541 (outline-next-heading)))
13542 (nreverse ee)))
13544 (defun org-agenda-get-deadlines ()
13545 "Return the deadline information for agenda display."
13546 (let* ((wdays org-deadline-warning-days)
13547 (props (list 'mouse-face 'highlight
13548 'org-not-done-regexp org-not-done-regexp
13549 'keymap org-agenda-keymap
13550 'help-echo
13551 (format "mouse-2 or RET jump to org file %s"
13552 (abbreviate-file-name buffer-file-name))))
13553 (regexp org-deadline-time-regexp)
13554 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
13555 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
13556 d2 diff pos pos1 category tags
13557 ee txt head face)
13558 (goto-char (point-min))
13559 (while (re-search-forward regexp nil t)
13560 (catch :skip
13561 (org-agenda-skip)
13562 (setq pos (1- (match-beginning 1))
13563 d2 (time-to-days
13564 (org-time-string-to-time (match-string 1)))
13565 diff (- d2 d1))
13566 ;; When to show a deadline in the calendar:
13567 ;; If the expiration is within wdays warning time.
13568 ;; Past-due deadlines are only shown on the current date
13569 (if (and (< diff wdays) todayp (not (= diff 0)))
13570 (save-excursion
13571 (setq category (org-get-category))
13572 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
13573 (progn
13574 (goto-char (match-end 0))
13575 (setq pos1 (match-end 1))
13576 (setq tags (org-get-tags-at pos1))
13577 (setq head (buffer-substring-no-properties
13578 (point)
13579 (progn (skip-chars-forward "^\r\n")
13580 (point))))
13581 (if (string-match org-looking-at-done-regexp head)
13582 (setq txt nil)
13583 (setq txt (org-format-agenda-item
13584 (format "In %3d d.: " diff) head category tags))))
13585 (setq txt org-agenda-no-heading-message))
13586 (when txt
13587 (setq face (cond ((<= diff 0) 'org-warning)
13588 ((<= diff 5) 'org-upcoming-deadline)
13589 (t nil)))
13590 (org-add-props txt props
13591 'org-marker (org-agenda-new-marker pos)
13592 'org-hd-marker (org-agenda-new-marker pos1)
13593 'priority (+ (- 10 diff) (org-get-priority txt))
13594 'category category
13595 'face face 'undone-face face 'done-face 'org-done)
13596 (push txt ee))))))
13597 ee))
13599 (defun org-agenda-get-scheduled ()
13600 "Return the scheduled information for agenda display."
13601 (let* ((props (list 'face 'org-scheduled-previously
13602 'org-not-done-regexp org-not-done-regexp
13603 'undone-face 'org-scheduled-previously
13604 'done-face 'org-done
13605 'mouse-face 'highlight
13606 'keymap org-agenda-keymap
13607 'help-echo
13608 (format "mouse-2 or RET jump to org file %s"
13609 (abbreviate-file-name buffer-file-name))))
13610 (regexp org-scheduled-time-regexp)
13611 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
13612 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
13613 d2 diff pos pos1 category tags donep
13614 ee txt head)
13615 (goto-char (point-min))
13616 (while (re-search-forward regexp nil t)
13617 (catch :skip
13618 (org-agenda-skip)
13619 (setq pos (1- (match-beginning 1))
13620 d2 (time-to-days
13621 (org-time-string-to-time (match-string 1)))
13622 diff (- d2 d1))
13623 ;; When to show a scheduled item in the calendar:
13624 ;; If it is on or past the date.
13625 (if (and (< diff 0) todayp)
13626 (save-excursion
13627 (setq category (org-get-category))
13628 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
13629 (progn
13630 (goto-char (match-end 0))
13631 (setq pos1 (match-end 1))
13632 (setq tags (org-get-tags-at))
13633 (setq head (buffer-substring-no-properties
13634 (point)
13635 (progn (skip-chars-forward "^\r\n") (point))))
13636 (if (string-match org-looking-at-done-regexp head)
13637 (setq txt nil)
13638 (setq txt (org-format-agenda-item
13639 (format "Sched.%2dx: " (- 1 diff)) head
13640 category tags))))
13641 (setq txt org-agenda-no-heading-message))
13642 (when txt
13643 (org-add-props txt props
13644 'org-marker (org-agenda-new-marker pos)
13645 'org-hd-marker (org-agenda-new-marker pos1)
13646 'priority (+ (- 5 diff) (org-get-priority txt))
13647 'category category)
13648 (push txt ee))))))
13649 ee))
13651 (defun org-agenda-get-blocks ()
13652 "Return the date-range information for agenda display."
13653 (let* ((props (list 'face nil
13654 'org-not-done-regexp org-not-done-regexp
13655 'mouse-face 'highlight
13656 'keymap org-agenda-keymap
13657 'help-echo
13658 (format "mouse-2 or RET jump to org file %s"
13659 (abbreviate-file-name buffer-file-name))))
13660 (regexp org-tr-regexp)
13661 (d0 (calendar-absolute-from-gregorian date))
13662 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
13663 (goto-char (point-min))
13664 (while (re-search-forward regexp nil t)
13665 (catch :skip
13666 (org-agenda-skip)
13667 (setq pos (point))
13668 (setq timestr (match-string 0)
13669 s1 (match-string 1)
13670 s2 (match-string 2)
13671 d1 (time-to-days (org-time-string-to-time s1))
13672 d2 (time-to-days (org-time-string-to-time s2)))
13673 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
13674 ;; Only allow days between the limits, because the normal
13675 ;; date stamps will catch the limits.
13676 (save-excursion
13677 (setq marker (org-agenda-new-marker (point)))
13678 (setq category (org-get-category))
13679 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
13680 (progn
13681 (setq hdmarker (org-agenda-new-marker (match-end 1)))
13682 (goto-char (match-end 1))
13683 (setq tags (org-get-tags-at))
13684 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
13685 (setq txt (org-format-agenda-item
13686 (format (if (= d1 d2) "" "(%d/%d): ")
13687 (1+ (- d0 d1)) (1+ (- d2 d1)))
13688 (match-string 1) category tags
13689 (if (= d0 d1) timestr))))
13690 (setq txt org-agenda-no-heading-message))
13691 (org-add-props txt props
13692 'org-marker marker 'org-hd-marker hdmarker
13693 'priority (org-get-priority txt) 'category category)
13694 (push txt ee)))
13695 (goto-char pos)))
13696 ;; Sort the entries by expiration date.
13697 (nreverse ee)))
13699 ;;; Agenda presentation and sorting
13701 ;; FIXME: should I allow spaces around the dash?
13702 (defconst org-plain-time-of-day-regexp
13703 (concat
13704 "\\(\\<[012]?[0-9]"
13705 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
13706 "\\(--?"
13707 "\\(\\<[012]?[0-9]"
13708 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
13709 "\\)?")
13710 "Regular expression to match a plain time or time range.
13711 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
13712 groups carry important information:
13713 0 the full match
13714 1 the first time, range or not
13715 8 the second time, if it is a range.")
13717 (defconst org-stamp-time-of-day-regexp
13718 (concat
13719 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
13720 "\\([012][0-9]:[0-5][0-9]\\)>"
13721 "\\(--?"
13722 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
13723 "Regular expression to match a timestamp time or time range.
13724 After a match, the following groups carry important information:
13725 0 the full match
13726 1 date plus weekday, for backreferencing to make sure both times on same day
13727 2 the first time, range or not
13728 4 the second time, if it is a range.")
13730 (defvar org-prefix-has-time nil
13731 "A flag, set by `org-compile-prefix-format'.
13732 The flag is set if the currently compiled format contains a `%t'.")
13733 (defvar org-prefix-has-tag nil
13734 "A flag, set by `org-compile-prefix-format'.
13735 The flag is set if the currently compiled format contains a `%T'.")
13737 (defun org-format-agenda-item (extra txt &optional category tags dotime
13738 noprefix)
13739 "Format TXT to be inserted into the agenda buffer.
13740 In particular, it adds the prefix and corresponding text properties. EXTRA
13741 must be a string and replaces the `%s' specifier in the prefix format.
13742 CATEGORY (string, symbol or nil) may be used to overrule the default
13743 category taken from local variable or file name. It will replace the `%c'
13744 specifier in the format. DOTIME, when non-nil, indicates that a
13745 time-of-day should be extracted from TXT for sorting of this entry, and for
13746 the `%t' specifier in the format. When DOTIME is a string, this string is
13747 searched for a time before TXT is. NOPREFIX is a flag and indicates that
13748 only the correctly processes TXT should be returned - this is used by
13749 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
13750 (save-match-data
13751 ;; Diary entries sometimes have extra whitespace at the beginning
13752 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
13753 (let* ((category (or category
13754 org-category
13755 (if buffer-file-name
13756 (file-name-sans-extension
13757 (file-name-nondirectory buffer-file-name))
13758 "")))
13759 (tag (if tags (nth (1- (length tags)) tags) ""))
13760 time ;; needed for the eval of the prefix format
13761 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
13762 (time-of-day (and dotime (org-get-time-of-day ts)))
13763 stamp plain s0 s1 s2 rtn)
13764 (when (and dotime time-of-day org-prefix-has-time)
13765 ;; Extract starting and ending time and move them to prefix
13766 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
13767 (setq plain (string-match org-plain-time-of-day-regexp ts)))
13768 (setq s0 (match-string 0 ts)
13769 s1 (match-string (if plain 1 2) ts)
13770 s2 (match-string (if plain 8 4) ts))
13772 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
13773 ;; them, we might want to remove them there to avoid duplication.
13774 ;; The user can turn this off with a variable.
13775 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
13776 (string-match (concat (regexp-quote s0) " *") txt)
13777 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
13778 (= (match-beginning 0) 0)
13780 (setq txt (replace-match "" nil nil txt))))
13781 ;; Normalize the time(s) to 24 hour
13782 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
13783 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
13785 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
13786 ;; Tags are in the string
13787 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
13788 (and org-agenda-remove-tags-when-in-prefix
13789 org-prefix-has-tag))
13790 (setq txt (replace-match "" t t txt))
13791 (setq txt (replace-match
13792 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
13793 (match-string 2 txt))
13794 t t txt))))
13796 ;; Create the final string
13797 (if noprefix
13798 (setq rtn txt)
13799 ;; Prepare the variables needed in the eval of the compiled format
13800 (setq time (cond (s2 (concat s1 "-" s2))
13801 (s1 (concat s1 "......"))
13802 (t ""))
13803 extra (or extra "")
13804 category (if (symbolp category) (symbol-name category) category))
13805 ;; Evaluate the compiled format
13806 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
13808 ;; And finally add the text properties
13809 (org-add-props rtn nil
13810 'category (downcase category) 'tags tags
13811 'prefix-length (- (length rtn) (length txt))
13812 'time-of-day time-of-day
13813 'dotime dotime))))
13815 (defvar org-agenda-sorting-strategy)
13816 (defvar org-agenda-sorting-strategy-selected nil)
13818 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
13819 (catch 'exit
13820 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
13821 ((and todayp (member 'today (car org-agenda-time-grid))))
13822 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
13823 ((member 'weekly (car org-agenda-time-grid)))
13824 (t (throw 'exit list)))
13825 (let* ((have (delq nil (mapcar
13826 (lambda (x) (get-text-property 1 'time-of-day x))
13827 list)))
13828 (string (nth 1 org-agenda-time-grid))
13829 (gridtimes (nth 2 org-agenda-time-grid))
13830 (req (car org-agenda-time-grid))
13831 (remove (member 'remove-match req))
13832 new time)
13833 (if (and (member 'require-timed req) (not have))
13834 ;; don't show empty grid
13835 (throw 'exit list))
13836 (while (setq time (pop gridtimes))
13837 (unless (and remove (member time have))
13838 (setq time (int-to-string time))
13839 (push (org-format-agenda-item
13840 nil string "" nil
13841 (concat (substring time 0 -2) ":" (substring time -2)))
13842 new)
13843 (put-text-property
13844 1 (length (car new)) 'face 'org-time-grid (car new))))
13845 (if (member 'time-up org-agenda-sorting-strategy-selected)
13846 (append new list)
13847 (append list new)))))
13849 (defun org-compile-prefix-format (key)
13850 "Compile the prefix format into a Lisp form that can be evaluated.
13851 The resulting form is returned and stored in the variable
13852 `org-prefix-format-compiled'."
13853 (setq org-prefix-has-time nil org-prefix-has-tag nil)
13854 (let ((s (cond
13855 ((stringp org-agenda-prefix-format)
13856 org-agenda-prefix-format)
13857 ((assq key org-agenda-prefix-format)
13858 (cdr (assq key org-agenda-prefix-format)))
13859 (t " %-12:c%?-12t% s")))
13860 (start 0)
13861 varform vars var e c f opt)
13862 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
13863 s start)
13864 (setq var (cdr (assoc (match-string 4 s)
13865 '(("c" . category) ("t" . time) ("s" . extra)
13866 ("T" . tag))))
13867 c (or (match-string 3 s) "")
13868 opt (match-beginning 1)
13869 start (1+ (match-beginning 0)))
13870 (if (equal var 'time) (setq org-prefix-has-time t))
13871 (if (equal var 'tag) (setq org-prefix-has-tag t))
13872 (setq f (concat "%" (match-string 2 s) "s"))
13873 (if opt
13874 (setq varform
13875 `(if (equal "" ,var)
13877 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
13878 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
13879 (setq s (replace-match "%s" t nil s))
13880 (push varform vars))
13881 (setq vars (nreverse vars))
13882 (setq org-prefix-format-compiled `(format ,s ,@vars))))
13884 (defun org-set-sorting-strategy (key)
13885 (if (symbolp (car org-agenda-sorting-strategy))
13886 ;; the old format
13887 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
13888 (setq org-agenda-sorting-strategy-selected
13889 (or (cdr (assq key org-agenda-sorting-strategy))
13890 (cdr (assq 'agenda org-agenda-sorting-strategy))
13891 '(time-up category-keep priority-down)))))
13893 (defun org-get-time-of-day (s &optional string mod24)
13894 "Check string S for a time of day.
13895 If found, return it as a military time number between 0 and 2400.
13896 If not found, return nil.
13897 The optional STRING argument forces conversion into a 5 character wide string
13898 HH:MM."
13899 (save-match-data
13900 (when
13902 (string-match
13903 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
13904 (string-match
13905 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
13906 (let* ((h (string-to-number (match-string 1 s)))
13907 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
13908 (ampm (if (match-end 4) (downcase (match-string 4 s))))
13909 (am-p (equal ampm "am"))
13910 (h1 (cond ((not ampm) h)
13911 ((= h 12) (if am-p 0 12))
13912 (t (+ h (if am-p 0 12)))))
13913 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
13914 (mod h1 24) h1))
13915 (t0 (+ (* 100 h2) m))
13916 (t1 (concat (if (>= h1 24) "+" " ")
13917 (if (< t0 100) "0" "")
13918 (if (< t0 10) "0" "")
13919 (int-to-string t0))))
13920 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
13922 (defun org-finalize-agenda-entries (list &optional nosort)
13923 "Sort and concatenate the agenda items."
13924 (setq list (mapcar 'org-agenda-highlight-todo list))
13925 (if nosort
13926 list
13927 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
13929 (defun org-agenda-highlight-todo (x)
13930 (let (re pl)
13931 (if (eq x 'line)
13932 (save-excursion
13933 (beginning-of-line 1)
13934 (setq re (get-text-property (point) 'org-not-done-regexp))
13935 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
13936 (and (looking-at (concat "[ \t]*\\.*" re))
13937 (add-text-properties (match-beginning 0) (match-end 0)
13938 '(face org-todo))))
13939 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
13940 pl (get-text-property 0 'prefix-length x))
13941 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
13942 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
13943 '(face org-todo) x))
13944 x)))
13946 (defsubst org-cmp-priority (a b)
13947 "Compare the priorities of string A and B."
13948 (let ((pa (or (get-text-property 1 'priority a) 0))
13949 (pb (or (get-text-property 1 'priority b) 0)))
13950 (cond ((> pa pb) +1)
13951 ((< pa pb) -1)
13952 (t nil))))
13954 (defsubst org-cmp-category (a b)
13955 "Compare the string values of categories of strings A and B."
13956 (let ((ca (or (get-text-property 1 'category a) ""))
13957 (cb (or (get-text-property 1 'category b) "")))
13958 (cond ((string-lessp ca cb) -1)
13959 ((string-lessp cb ca) +1)
13960 (t nil))))
13962 (defsubst org-cmp-tag (a b)
13963 "Compare the string values of categories of strings A and B."
13964 (let ((ta (car (last (get-text-property 1 'tags a))))
13965 (tb (car (last (get-text-property 1 'tags b)))))
13966 (cond ((not ta) +1)
13967 ((not tb) -1)
13968 ((string-lessp ta tb) -1)
13969 ((string-lessp tb ta) +1)
13970 (t nil))))
13972 (defsubst org-cmp-time (a b)
13973 "Compare the time-of-day values of strings A and B."
13974 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
13975 (ta (or (get-text-property 1 'time-of-day a) def))
13976 (tb (or (get-text-property 1 'time-of-day b) def)))
13977 (cond ((< ta tb) -1)
13978 ((< tb ta) +1)
13979 (t nil))))
13981 (defun org-entries-lessp (a b)
13982 "Predicate for sorting agenda entries."
13983 ;; The following variables will be used when the form is evaluated.
13984 (let* ((time-up (org-cmp-time a b))
13985 (time-down (if time-up (- time-up) nil))
13986 (priority-up (org-cmp-priority a b))
13987 (priority-down (if priority-up (- priority-up) nil))
13988 (category-up (org-cmp-category a b))
13989 (category-down (if category-up (- category-up) nil))
13990 (category-keep (if category-up +1 nil))
13991 (tag-up (org-cmp-tag a b))
13992 (tag-down (if tag-up (- tag-up) nil)))
13993 (cdr (assoc
13994 (eval (cons 'or org-agenda-sorting-strategy-selected))
13995 '((-1 . t) (1 . nil) (nil . nil))))))
13997 ;;; Agenda commands
13999 (defun org-agenda-check-type (error &rest types)
14000 "Check if agenda buffer is of allowed type.
14001 If ERROR is non-nil, throw an error, otherwise just return nil."
14002 (if (memq org-agenda-type types)
14004 (if error
14005 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
14006 nil)))
14008 (defun org-agenda-quit ()
14009 "Exit agenda by removing the window or the buffer."
14010 (interactive)
14011 (let ((buf (current-buffer)))
14012 (if (not (one-window-p)) (delete-window))
14013 (kill-buffer buf)
14014 (org-agenda-maybe-reset-markers 'force))
14015 ;; Maybe restore the pre-agenda window configuration.
14016 (and org-agenda-restore-windows-after-quit
14017 (not (eq org-agenda-window-setup 'other-frame))
14018 org-pre-agenda-window-conf
14019 (set-window-configuration org-pre-agenda-window-conf)))
14021 (defun org-agenda-exit ()
14022 "Exit agenda by removing the window or the buffer.
14023 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
14024 Org-mode buffers visited directly by the user will not be touched."
14025 (interactive)
14026 (org-release-buffers org-agenda-new-buffers)
14027 (setq org-agenda-new-buffers nil)
14028 (org-agenda-quit))
14030 (defun org-save-all-org-buffers ()
14031 "Save all Org-mode buffers without user confirmation."
14032 (interactive)
14033 (message "Saving all Org-mode buffers...")
14034 (save-some-buffers t 'org-mode-p)
14035 (message "Saving all Org-mode buffers... done"))
14037 (defun org-agenda-redo ()
14038 "Rebuild Agenda.
14039 When this is the global TODO list, a prefix argument will be interpreted."
14040 (interactive)
14041 (let* ((org-agenda-keep-modes t)
14042 (line (org-current-line))
14043 (window-line (- line (org-current-line (window-start)))))
14044 (message "Rebuilding agenda buffer...")
14045 (eval org-agenda-redo-command)
14046 (setq org-agenda-undo-list nil
14047 org-agenda-pending-undo-list nil)
14048 (message "Rebuilding agenda buffer...done")
14049 (goto-line line)
14050 (recenter window-line)))
14052 (defun org-agenda-goto-today ()
14053 "Go to today."
14054 (interactive)
14055 (org-agenda-check-type t 'timeline 'agenda)
14056 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
14057 (cond
14058 (tdpos (goto-char tdpos))
14059 ((eq org-agenda-type 'agenda)
14060 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
14061 (setf (nth 1 org-agenda-overriding-arguments) nil)
14062 (org-agenda-redo)
14063 (org-agenda-find-today-or-agenda)))
14064 (t (error "Cannot find today")))))
14066 (defun org-agenda-find-today-or-agenda ()
14067 (goto-char
14068 (or (text-property-any (point-min) (point-max) 'org-today t)
14069 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
14070 (point-min))))
14072 (defun org-agenda-later (arg)
14073 "Go forward in time by `org-agenda-ndays' days.
14074 With prefix ARG, go forward that many times `org-agenda-ndays'."
14075 (interactive "p")
14076 (org-agenda-check-type t 'agenda)
14077 (let ((org-agenda-overriding-arguments
14078 (list (car org-agenda-last-arguments)
14079 (+ org-starting-day (* arg org-agenda-ndays))
14080 nil t)))
14081 (org-agenda-redo)
14082 (org-agenda-find-today-or-agenda)))
14084 (defun org-agenda-earlier (arg)
14085 "Go back in time by `org-agenda-ndays' days.
14086 With prefix ARG, go back that many times `org-agenda-ndays'."
14087 (interactive "p")
14088 (org-agenda-check-type t 'agenda)
14089 (let ((org-agenda-overriding-arguments
14090 (list (car org-agenda-last-arguments)
14091 (- org-starting-day (* arg org-agenda-ndays))
14092 nil t)))
14093 (org-agenda-redo)
14094 (org-agenda-find-today-or-agenda)))
14096 (defun org-agenda-week-view ()
14097 "Switch to weekly view for agenda."
14098 (interactive)
14099 (org-agenda-check-type t 'agenda)
14100 (if (= org-agenda-ndays 7)
14101 (error "This is already the week view"))
14102 (setq org-agenda-ndays 7)
14103 (let ((org-agenda-overriding-arguments
14104 (list (car org-agenda-last-arguments)
14105 (or (get-text-property (point) 'day)
14106 org-starting-day)
14107 nil t)))
14108 (org-agenda-redo)
14109 (org-agenda-find-today-or-agenda))
14110 (org-agenda-set-mode-name)
14111 (message "Switched to week view"))
14113 (defun org-agenda-day-view ()
14114 "Switch to daily view for agenda."
14115 (interactive)
14116 (org-agenda-check-type t 'agenda)
14117 (if (= org-agenda-ndays 1)
14118 (error "This is already the day view"))
14119 (setq org-agenda-ndays 1)
14120 (let ((org-agenda-overriding-arguments
14121 (list (car org-agenda-last-arguments)
14122 (or (get-text-property (point) 'day)
14123 org-starting-day)
14124 nil t)))
14125 (org-agenda-redo)
14126 (org-agenda-find-today-or-agenda))
14127 (org-agenda-set-mode-name)
14128 (message "Switched to day view"))
14130 (defun org-agenda-next-date-line (&optional arg)
14131 "Jump to the next line indicating a date in agenda buffer."
14132 (interactive "p")
14133 (org-agenda-check-type t 'agenda 'timeline)
14134 (beginning-of-line 1)
14135 (if (looking-at "^\\S-") (forward-char 1))
14136 (if (not (re-search-forward "^\\S-" nil t arg))
14137 (progn
14138 (backward-char 1)
14139 (error "No next date after this line in this buffer")))
14140 (goto-char (match-beginning 0)))
14142 (defun org-agenda-previous-date-line (&optional arg)
14143 "Jump to the previous line indicating a date in agenda buffer."
14144 (interactive "p")
14145 (org-agenda-check-type t 'agenda 'timeline)
14146 (beginning-of-line 1)
14147 (if (not (re-search-backward "^\\S-" nil t arg))
14148 (error "No previous date before this line in this buffer")))
14150 ;; Initialize the highlight
14151 (defvar org-hl (org-make-overlay 1 1))
14152 (org-overlay-put org-hl 'face 'highlight)
14154 (defun org-highlight (begin end &optional buffer)
14155 "Highlight a region with overlay."
14156 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
14157 org-hl begin end (or buffer (current-buffer))))
14159 (defun org-unhighlight ()
14160 "Detach overlay INDEX."
14161 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
14163 (defun org-highlight-until-next-command (beg end &optional buffer)
14164 (org-highlight beg end buffer)
14165 (add-hook 'pre-command-hook 'org-unhighlight-once))
14167 (defun org-unhighlight-once ()
14168 (remove-hook 'pre-command-hook 'org-unhighlight-once)
14169 (org-unhighlight))
14171 (defun org-agenda-follow-mode ()
14172 "Toggle follow mode in an agenda buffer."
14173 (interactive)
14174 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
14175 (org-agenda-set-mode-name)
14176 (message "Follow mode is %s"
14177 (if org-agenda-follow-mode "on" "off")))
14179 (defun org-agenda-log-mode ()
14180 "Toggle log mode in an agenda buffer."
14181 (interactive)
14182 (org-agenda-check-type t 'agenda 'timeline)
14183 (setq org-agenda-show-log (not org-agenda-show-log))
14184 (org-agenda-set-mode-name)
14185 (org-agenda-redo)
14186 (message "Log mode is %s"
14187 (if org-agenda-show-log "on" "off")))
14189 (defun org-agenda-toggle-diary ()
14190 "Toggle diary inclusion in an agenda buffer."
14191 (interactive)
14192 (org-agenda-check-type t 'agenda)
14193 (setq org-agenda-include-diary (not org-agenda-include-diary))
14194 (org-agenda-redo)
14195 (org-agenda-set-mode-name)
14196 (message "Diary inclusion turned %s"
14197 (if org-agenda-include-diary "on" "off")))
14199 (defun org-agenda-toggle-time-grid ()
14200 "Toggle time grid in an agenda buffer."
14201 (interactive)
14202 (org-agenda-check-type t 'agenda)
14203 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
14204 (org-agenda-redo)
14205 (org-agenda-set-mode-name)
14206 (message "Time-grid turned %s"
14207 (if org-agenda-use-time-grid "on" "off")))
14209 (defun org-agenda-set-mode-name ()
14210 "Set the mode name to indicate all the small mode settings."
14211 (setq mode-name
14212 (concat "Org-Agenda"
14213 (if (equal org-agenda-ndays 1) " Day" "")
14214 (if (equal org-agenda-ndays 7) " Week" "")
14215 (if org-agenda-follow-mode " Follow" "")
14216 (if org-agenda-include-diary " Diary" "")
14217 (if org-agenda-use-time-grid " Grid" "")
14218 (if org-agenda-show-log " Log" "")))
14219 (force-mode-line-update))
14221 (defun org-agenda-post-command-hook ()
14222 (and (eolp) (not (bolp)) (backward-char 1))
14223 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
14224 (if (and org-agenda-follow-mode
14225 (get-text-property (point) 'org-marker))
14226 (org-agenda-show)))
14228 (defun org-agenda-show-priority ()
14229 "Show the priority of the current item.
14230 This priority is composed of the main priority given with the [#A] cookies,
14231 and by additional input from the age of a schedules or deadline entry."
14232 (interactive)
14233 (let* ((pri (get-text-property (point-at-bol) 'priority)))
14234 (message "Priority is %d" (if pri pri -1000))))
14236 (defun org-agenda-show-tags ()
14237 "Show the tags applicable to the current item."
14238 (interactive)
14239 (let* ((tags (get-text-property (point-at-bol) 'tags)))
14240 (if tags
14241 (message "Tags are :%s:"
14242 (org-no-properties (mapconcat 'identity tags ":")))
14243 (message "No tags associated with this line"))))
14245 (defun org-agenda-goto (&optional highlight)
14246 "Go to the Org-mode file which contains the item at point."
14247 (interactive)
14248 (let* ((marker (or (get-text-property (point) 'org-marker)
14249 (org-agenda-error)))
14250 (buffer (marker-buffer marker))
14251 (pos (marker-position marker)))
14252 (switch-to-buffer-other-window buffer)
14253 (widen)
14254 (goto-char pos)
14255 (when (org-mode-p)
14256 (org-show-context 'agenda)
14257 (save-excursion
14258 (and (outline-next-heading)
14259 (org-flag-heading nil)))) ; show the next heading
14260 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
14262 (defun org-agenda-kill ()
14263 "Kill the entry or subtree belonging to the current agenda entry."
14264 (interactive)
14265 (let* ((marker (or (get-text-property (point) 'org-marker)
14266 (org-agenda-error)))
14267 (hdmarker (get-text-property (point) 'org-hd-marker))
14268 (buffer (marker-buffer marker))
14269 (pos (marker-position marker))
14270 dbeg dend (n 0) conf)
14271 (org-with-remote-undo buffer
14272 (with-current-buffer buffer
14273 (save-excursion
14274 (goto-char pos)
14275 (if (org-mode-p)
14276 (setq dbeg (progn (org-back-to-heading t) (point))
14277 dend (org-end-of-subtree t))
14278 (setq dbeg (point-at-bol)
14279 dend (min (point-max) (1+ (point-at-eol)))))
14280 (goto-char dbeg)
14281 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
14282 (setq conf (or (eq t org-agenda-confirm-kill)
14283 (and (numberp org-agenda-confirm-kill)
14284 (> n org-agenda-confirm-kill))))
14285 (and conf
14286 (not (y-or-n-p
14287 (format "Delete entry with %d lines in buffer \"%s\"? "
14288 n (buffer-name buffer))))
14289 (error "Abort"))
14290 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
14291 (with-current-buffer buffer (delete-region dbeg dend))
14292 (message "Agenda item and source killed"))))
14294 (defun org-agenda-archive ()
14295 "Kill the entry or subtree belonging to the current agenda entry."
14296 (interactive)
14297 (let* ((marker (or (get-text-property (point) 'org-marker)
14298 (org-agenda-error)))
14299 (hdmarker (get-text-property (point) 'org-hd-marker))
14300 (buffer (marker-buffer marker))
14301 (pos (marker-position marker))
14302 dbeg dend txt n conf)
14303 (org-with-remote-undo buffer
14304 (with-current-buffer buffer
14305 (if (org-mode-p)
14306 (save-excursion
14307 (goto-char pos)
14308 (org-remove-subtree-entries-from-agenda)
14309 (org-back-to-heading t)
14310 (org-archive-subtree))
14311 (error "Archiving works only in Org-mode files"))))))
14313 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
14314 "Remove all lines in the agenda that correspond to a given subtree.
14315 The subtree is the one in buffer BUF, starting at BEG and ending at END.
14316 If this information is not given, the function uses the tree at point."
14317 (let ((buf (or buf (current-buffer))) m p)
14318 (save-excursion
14319 (unless (and beg end)
14320 (org-back-to-heading t)
14321 (setq beg (point))
14322 (org-end-of-subtree t)
14323 (setq end (point)))
14324 (set-buffer (get-buffer org-agenda-buffer-name))
14325 (save-excursion
14326 (goto-char (point-max))
14327 (beginning-of-line 1)
14328 (while (not (bobp))
14329 (when (and (setq m (get-text-property (point) 'org-marker))
14330 (equal buf (marker-buffer m))
14331 (setq p (marker-position m))
14332 (>= p beg)
14333 (<= p end))
14334 (let (buffer-read-only)
14335 (delete-region (point-at-bol) (1+ (point-at-eol)))))
14336 (beginning-of-line 0))))))
14338 (defun org-agenda-open-link ()
14339 "Follow the link in the current line, if any."
14340 (interactive)
14341 (let ((eol (point-at-eol)))
14342 (save-excursion
14343 (if (or (re-search-forward org-bracket-link-regexp eol t)
14344 (re-search-forward org-angle-link-re eol t)
14345 (re-search-forward org-plain-link-re eol t))
14346 (call-interactively 'org-open-at-point)
14347 (error "No link in current line")))))
14349 (defun org-agenda-switch-to (&optional delete-other-windows)
14350 "Go to the Org-mode file which contains the item at point."
14351 (interactive)
14352 (let* ((marker (or (get-text-property (point) 'org-marker)
14353 (org-agenda-error)))
14354 (buffer (marker-buffer marker))
14355 (pos (marker-position marker)))
14356 (switch-to-buffer buffer)
14357 (and delete-other-windows (delete-other-windows))
14358 (widen)
14359 (goto-char pos)
14360 (when (org-mode-p)
14361 (org-show-context 'agenda)
14362 (save-excursion
14363 (and (outline-next-heading)
14364 (org-flag-heading nil)))))) ; show the next heading
14366 (defun org-agenda-goto-mouse (ev)
14367 "Go to the Org-mode file which contains the item at the mouse click."
14368 (interactive "e")
14369 (mouse-set-point ev)
14370 (org-agenda-goto))
14372 (defun org-agenda-show ()
14373 "Display the Org-mode file which contains the item at point."
14374 (interactive)
14375 (let ((win (selected-window)))
14376 (org-agenda-goto t)
14377 (select-window win)))
14379 (defun org-agenda-recenter (arg)
14380 "Display the Org-mode file which contains the item at point and recenter."
14381 (interactive "P")
14382 (let ((win (selected-window)))
14383 (org-agenda-goto t)
14384 (recenter arg)
14385 (select-window win)))
14387 (defun org-agenda-show-mouse (ev)
14388 "Display the Org-mode file which contains the item at the mouse click."
14389 (interactive "e")
14390 (mouse-set-point ev)
14391 (org-agenda-show))
14393 (defun org-agenda-check-no-diary ()
14394 "Check if the entry is a diary link and abort if yes."
14395 (if (get-text-property (point) 'org-agenda-diary-link)
14396 (org-agenda-error)))
14398 (defun org-agenda-error ()
14399 (error "Command not allowed in this line"))
14401 (defun org-agenda-tree-to-indirect-buffer ()
14402 "Show the subtree corresponding to the current entry in an indirect buffer.
14403 This calls the command `org-tree-to-indirect-buffer' from the original
14404 Org-mode buffer.
14405 With numerical prefix arg ARG, go up to this level and then take that tree.
14406 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
14407 dedicated frame)."
14408 (interactive)
14409 (org-agenda-check-no-diary)
14410 (let* ((marker (or (get-text-property (point) 'org-marker)
14411 (org-agenda-error)))
14412 (buffer (marker-buffer marker))
14413 (pos (marker-position marker)))
14414 (with-current-buffer buffer
14415 (save-excursion
14416 (goto-char pos)
14417 (call-interactively 'org-tree-to-indirect-buffer)))))
14419 (defvar org-last-heading-marker (make-marker)
14420 "Marker pointing to the headline that last changed its TODO state
14421 by a remote command from the agenda.")
14423 (defun org-agenda-todo (&optional arg)
14424 "Cycle TODO state of line at point, also in Org-mode file.
14425 This changes the line at point, all other lines in the agenda referring to
14426 the same tree node, and the headline of the tree node in the Org-mode file."
14427 (interactive "P")
14428 (org-agenda-check-no-diary)
14429 (let* ((col (current-column))
14430 (marker (or (get-text-property (point) 'org-marker)
14431 (org-agenda-error)))
14432 (buffer (marker-buffer marker))
14433 (pos (marker-position marker))
14434 (hdmarker (get-text-property (point) 'org-hd-marker))
14435 (buffer-read-only nil)
14436 newhead)
14437 (org-with-remote-undo buffer
14438 (with-current-buffer buffer
14439 (widen)
14440 (goto-char pos)
14441 (org-show-context 'agenda)
14442 (save-excursion
14443 (and (outline-next-heading)
14444 (org-flag-heading nil))) ; show the next heading
14445 (org-todo arg)
14446 (and (bolp) (forward-char 1))
14447 (setq newhead (org-get-heading))
14448 (save-excursion
14449 (org-back-to-heading)
14450 (move-marker org-last-heading-marker (point))))
14451 (beginning-of-line 1)
14452 (save-excursion
14453 (org-agenda-change-all-lines newhead hdmarker 'fixface))
14454 (move-to-column col))))
14456 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
14457 "Change all lines in the agenda buffer which match HDMARKER.
14458 The new content of the line will be NEWHEAD (as modified by
14459 `org-format-agenda-item'). HDMARKER is checked with
14460 `equal' against all `org-hd-marker' text properties in the file.
14461 If FIXFACE is non-nil, the face of each item is modified acording to
14462 the new TODO state."
14463 (let* ((buffer-read-only nil)
14464 props m pl undone-face done-face finish new dotime cat tags)
14465 (save-excursion
14466 (goto-char (point-max))
14467 (beginning-of-line 1)
14468 (while (not finish)
14469 (setq finish (bobp))
14470 (when (and (setq m (get-text-property (point) 'org-hd-marker))
14471 (equal m hdmarker))
14472 (setq props (text-properties-at (point))
14473 dotime (get-text-property (point) 'dotime)
14474 cat (get-text-property (point) 'category)
14475 tags (get-text-property (point) 'tags)
14476 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
14477 pl (get-text-property (point) 'prefix-length)
14478 undone-face (get-text-property (point) 'undone-face)
14479 done-face (get-text-property (point) 'done-face))
14480 (move-to-column pl)
14481 (cond
14482 ((equal new "")
14483 (beginning-of-line 1)
14484 (and (looking-at ".*\n?") (replace-match "")))
14485 ((looking-at ".*")
14486 (replace-match new t t)
14487 (beginning-of-line 1)
14488 (add-text-properties (point-at-bol) (point-at-eol) props)
14489 (when fixface
14490 (add-text-properties
14491 (point-at-bol) (point-at-eol)
14492 (list 'face
14493 (if org-last-todo-state-is-todo
14494 undone-face done-face))))
14495 (org-agenda-highlight-todo 'line)
14496 (beginning-of-line 1))
14497 (t (error "Line update did not work"))))
14498 (beginning-of-line 0)))
14499 (org-finalize-agenda)))
14501 (defun org-agenda-align-tags (&optional line)
14502 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
14503 (let ((buffer-read-only))
14504 (save-excursion
14505 (goto-char (if line (point-at-bol) (point-min)))
14506 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
14507 (if line (point-at-eol) nil) t)
14508 (delete-region (match-beginning 1) (match-end 1))
14509 (goto-char (match-beginning 1))
14510 (insert (org-add-props
14511 (make-string (max 1 (- org-agenda-align-tags-to-column
14512 (current-column))) ?\ )
14513 (text-properties-at (point))))))))
14515 (defun org-agenda-priority-up ()
14516 "Increase the priority of line at point, also in Org-mode file."
14517 (interactive)
14518 (org-agenda-priority 'up))
14520 (defun org-agenda-priority-down ()
14521 "Decrease the priority of line at point, also in Org-mode file."
14522 (interactive)
14523 (org-agenda-priority 'down))
14525 (defun org-agenda-priority (&optional force-direction)
14526 "Set the priority of line at point, also in Org-mode file.
14527 This changes the line at point, all other lines in the agenda referring to
14528 the same tree node, and the headline of the tree node in the Org-mode file."
14529 (interactive)
14530 (org-agenda-check-no-diary)
14531 (let* ((marker (or (get-text-property (point) 'org-marker)
14532 (org-agenda-error)))
14533 (buffer (marker-buffer marker))
14534 (pos (marker-position marker))
14535 (hdmarker (get-text-property (point) 'org-hd-marker))
14536 (buffer-read-only nil)
14537 newhead)
14538 (org-with-remote-undo buffer
14539 (with-current-buffer buffer
14540 (widen)
14541 (goto-char pos)
14542 (org-show-context 'agenda)
14543 (save-excursion
14544 (and (outline-next-heading)
14545 (org-flag-heading nil))) ; show the next heading
14546 (funcall 'org-priority force-direction)
14547 (end-of-line 1)
14548 (setq newhead (org-get-heading)))
14549 (org-agenda-change-all-lines newhead hdmarker)
14550 (beginning-of-line 1))))
14552 (defun org-get-tags-at (&optional pos)
14553 "Get a list of all headline tags applicable at POS.
14554 POS defaults to point. If tags are inherited, the list contains
14555 the targets in the same sequence as the headlines appear, i.e.
14556 the tags of the current headline come last."
14557 (interactive)
14558 (let (tags)
14559 (save-excursion
14560 (save-restriction
14561 (widen)
14562 (goto-char (or pos (point)))
14563 (save-match-data
14564 (org-back-to-heading t)
14565 (condition-case nil
14566 (while t
14567 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
14568 (setq tags (append (org-split-string
14569 (org-match-string-no-properties 1) ":")
14570 tags)))
14571 (or org-use-tag-inheritance (error ""))
14572 (org-up-heading-all 1))
14573 (error nil))))
14574 tags)))
14576 ;; FIXME: should fix the tags property of the agenda line.
14577 (defun org-agenda-set-tags ()
14578 "Set tags for the current headline."
14579 (interactive)
14580 (org-agenda-check-no-diary)
14581 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
14582 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
14583 (org-agenda-error)))
14584 (buffer (marker-buffer hdmarker))
14585 (pos (marker-position hdmarker))
14586 (buffer-read-only nil)
14587 newhead)
14588 (org-with-remote-undo buffer
14589 (with-current-buffer buffer
14590 (widen)
14591 (goto-char pos)
14592 (org-show-context 'agenda)
14593 (save-excursion
14594 (and (outline-next-heading)
14595 (org-flag-heading nil))) ; show the next heading
14596 (call-interactively 'org-set-tags)
14597 (end-of-line 1)
14598 (setq newhead (org-get-heading)))
14599 (org-agenda-change-all-lines newhead hdmarker)
14600 (beginning-of-line 1))))
14602 (defun org-agenda-toggle-archive-tag ()
14603 "Toggle the archive tag for the current entry."
14604 (interactive)
14605 (org-agenda-check-no-diary)
14606 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
14607 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
14608 (org-agenda-error)))
14609 (buffer (marker-buffer hdmarker))
14610 (pos (marker-position hdmarker))
14611 (buffer-read-only nil)
14612 newhead)
14613 (org-with-remote-undo buffer
14614 (with-current-buffer buffer
14615 (widen)
14616 (goto-char pos)
14617 (org-show-context 'agenda)
14618 (save-excursion
14619 (and (outline-next-heading)
14620 (org-flag-heading nil))) ; show the next heading
14621 (call-interactively 'org-toggle-archive-tag)
14622 (end-of-line 1)
14623 (setq newhead (org-get-heading)))
14624 (org-agenda-change-all-lines newhead hdmarker)
14625 (beginning-of-line 1))))
14627 (defun org-agenda-date-later (arg &optional what)
14628 "Change the date of this item to one day later."
14629 (interactive "p")
14630 (org-agenda-check-type t 'agenda 'timeline)
14631 (org-agenda-check-no-diary)
14632 (let* ((marker (or (get-text-property (point) 'org-marker)
14633 (org-agenda-error)))
14634 (buffer (marker-buffer marker))
14635 (pos (marker-position marker)))
14636 (org-with-remote-undo buffer
14637 (with-current-buffer buffer
14638 (widen)
14639 (goto-char pos)
14640 (if (not (org-at-timestamp-p))
14641 (error "Cannot find time stamp"))
14642 (org-timestamp-change arg (or what 'day)))
14643 (org-agenda-show-new-time marker org-last-changed-timestamp))
14644 (message "Time stamp changed to %s" org-last-changed-timestamp)))
14646 (defun org-agenda-date-earlier (arg &optional what)
14647 "Change the date of this item to one day earlier."
14648 (interactive "p")
14649 (org-agenda-date-later (- arg) what))
14651 (defun org-agenda-show-new-time (marker stamp)
14652 "Show new date stamp via text properties."
14653 ;; We use text properties to make this undoable
14654 (let ((buffer-read-only nil)
14655 ovs ov)
14656 (setq stamp (concat " => " stamp))
14657 (save-excursion
14658 (goto-char (point-max))
14659 (while (not (bobp))
14660 (when (equal marker (get-text-property (point) 'org-marker))
14661 (move-to-column (- (window-width) (length stamp)) t)
14662 (if (featurep 'xemacs)
14663 ;; Use `duplicable' property to trigger undo recording
14664 (let ((ex (make-extent nil nil))
14665 (gl (make-glyph stamp)))
14666 (set-glyph-face gl 'secondary-selection)
14667 (set-extent-properties
14668 ex (list 'invisible t 'end-glyph gl 'duplicable t))
14669 (insert-extent ex (1- (point)) (point-at-eol)))
14670 (add-text-properties
14671 (1- (point)) (point-at-eol)
14672 (list 'display (org-add-props stamp nil
14673 'face 'secondary-selection))))
14674 (beginning-of-line 1))
14675 (beginning-of-line 0)))))
14677 (defun org-agenda-date-prompt (arg)
14678 "Change the date of this item. Date is prompted for, with default today.
14679 The prefix ARG is passed to the `org-time-stamp' command and can therefore
14680 be used to request time specification in the time stamp."
14681 (interactive "P")
14682 (org-agenda-check-type t 'agenda 'timeline)
14683 (org-agenda-check-no-diary)
14684 (let* ((marker (or (get-text-property (point) 'org-marker)
14685 (org-agenda-error)))
14686 (buffer (marker-buffer marker))
14687 (pos (marker-position marker)))
14688 (org-with-remote-undo buffer
14689 (with-current-buffer buffer
14690 (widen)
14691 (goto-char pos)
14692 (if (not (org-at-timestamp-p))
14693 (error "Cannot find time stamp"))
14694 (org-time-stamp arg)
14695 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
14697 (defun org-agenda-schedule (arg)
14698 "Schedule the item at point."
14699 (interactive "P")
14700 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
14701 (org-agenda-check-no-diary)
14702 (let* ((marker (or (get-text-property (point) 'org-marker)
14703 (org-agenda-error)))
14704 (buffer (marker-buffer marker))
14705 (pos (marker-position marker))
14706 (org-insert-labeled-timestamps-at-point nil)
14708 (org-with-remote-undo buffer
14709 (with-current-buffer buffer
14710 (widen)
14711 (goto-char pos)
14712 (setq ts (org-schedule))
14713 (message "Item scheduled for %s" ts)))))
14715 (defun org-agenda-deadline (arg)
14716 "Schedule the item at point."
14717 (interactive "P")
14718 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
14719 (org-agenda-check-no-diary)
14720 (let* ((marker (or (get-text-property (point) 'org-marker)
14721 (org-agenda-error)))
14722 (buffer (marker-buffer marker))
14723 (pos (marker-position marker))
14724 (org-insert-labeled-timestamps-at-point nil)
14726 (org-with-remote-undo buffer
14727 (with-current-buffer buffer
14728 (widen)
14729 (goto-char pos)
14730 (setq ts (org-deadline))
14731 (message "Deadline for this item set to %s" ts)))))
14733 (defun org-get-heading ()
14734 "Return the heading of the current entry, without the stars."
14735 (save-excursion
14736 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
14737 (if (and (re-search-backward "[\r\n]\\*" nil t)
14738 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
14739 (match-string 1)
14740 "")))
14742 (defun org-agenda-clock-in (&optional arg)
14743 "Start the clock on the currently selected item."
14744 (interactive "P")
14745 (org-agenda-check-no-diary)
14746 (let* ((marker (or (get-text-property (point) 'org-marker)
14747 (org-agenda-error)))
14748 (pos (marker-position marker)))
14749 (org-with-remote-undo (marker-buffer marker)
14750 (with-current-buffer (marker-buffer marker)
14751 (widen)
14752 (goto-char pos)
14753 (org-clock-in)))))
14755 (defun org-agenda-clock-out (&optional arg)
14756 "Stop the currently running clock."
14757 (interactive "P")
14758 (unless (marker-buffer org-clock-marker)
14759 (error "No running clock"))
14760 (org-with-remote-undo (marker-buffer org-clock-marker)
14761 (org-clock-out)))
14763 (defun org-agenda-clock-cancel (&optional arg)
14764 "Cancel the currently running clock."
14765 (interactive "P")
14766 (unless (marker-buffer org-clock-marker)
14767 (error "No running clock"))
14768 (org-with-remote-undo (marker-buffer org-clock-marker)
14769 (org-clock-cancel)))
14771 (defun org-agenda-diary-entry ()
14772 "Make a diary entry, like the `i' command from the calendar.
14773 All the standard commands work: block, weekly etc."
14774 (interactive)
14775 (org-agenda-check-type t 'agenda 'timeline)
14776 (require 'diary-lib)
14777 (let* ((char (progn
14778 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
14779 (read-char-exclusive)))
14780 (cmd (cdr (assoc char
14781 '((?d . insert-diary-entry)
14782 (?w . insert-weekly-diary-entry)
14783 (?m . insert-monthly-diary-entry)
14784 (?y . insert-yearly-diary-entry)
14785 (?a . insert-anniversary-diary-entry)
14786 (?b . insert-block-diary-entry)
14787 (?c . insert-cyclic-diary-entry)))))
14788 (oldf (symbol-function 'calendar-cursor-to-date))
14789 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
14790 (point (point))
14791 (mark (or (mark t) (point))))
14792 (unless cmd
14793 (error "No command associated with <%c>" char))
14794 (unless (and (get-text-property point 'day)
14795 (or (not (equal ?b char))
14796 (get-text-property mark 'day)))
14797 (error "Don't know which date to use for diary entry"))
14798 ;; We implement this by hacking the `calendar-cursor-to-date' function
14799 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
14800 (let ((calendar-mark-ring
14801 (list (calendar-gregorian-from-absolute
14802 (or (get-text-property mark 'day)
14803 (get-text-property point 'day))))))
14804 (unwind-protect
14805 (progn
14806 (fset 'calendar-cursor-to-date
14807 (lambda (&optional error)
14808 (calendar-gregorian-from-absolute
14809 (get-text-property point 'day))))
14810 (call-interactively cmd))
14811 (fset 'calendar-cursor-to-date oldf)))))
14814 (defun org-agenda-execute-calendar-command (cmd)
14815 "Execute a calendar command from the agenda, with the date associated to
14816 the cursor position."
14817 (org-agenda-check-type t 'agenda 'timeline)
14818 (require 'diary-lib)
14819 (unless (get-text-property (point) 'day)
14820 (error "Don't know which date to use for calendar command"))
14821 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
14822 (point (point))
14823 (date (calendar-gregorian-from-absolute
14824 (get-text-property point 'day)))
14825 (displayed-day (extract-calendar-day date))
14826 (displayed-month (extract-calendar-month date))
14827 (displayed-year (extract-calendar-year date)))
14828 (unwind-protect
14829 (progn
14830 (fset 'calendar-cursor-to-date
14831 (lambda (&optional error)
14832 (calendar-gregorian-from-absolute
14833 (get-text-property point 'day))))
14834 (call-interactively cmd))
14835 (fset 'calendar-cursor-to-date oldf))))
14837 (defun org-agenda-phases-of-moon ()
14838 "Display the phases of the moon for the 3 months around the cursor date."
14839 (interactive)
14840 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
14842 (defun org-agenda-holidays ()
14843 "Display the holidays for the 3 months around the cursor date."
14844 (interactive)
14845 (org-agenda-execute-calendar-command 'list-calendar-holidays))
14847 (defun org-agenda-sunrise-sunset (arg)
14848 "Display sunrise and sunset for the cursor date.
14849 Latitude and longitude can be specified with the variables
14850 `calendar-latitude' and `calendar-longitude'. When called with prefix
14851 argument, latitude and longitude will be prompted for."
14852 (interactive "P")
14853 (let ((calendar-longitude (if arg nil calendar-longitude))
14854 (calendar-latitude (if arg nil calendar-latitude))
14855 (calendar-location-name
14856 (if arg "the given coordinates" calendar-location-name)))
14857 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
14859 (defun org-agenda-goto-calendar ()
14860 "Open the Emacs calendar with the date at the cursor."
14861 (interactive)
14862 (org-agenda-check-type t 'agenda 'timeline)
14863 (let* ((day (or (get-text-property (point) 'day)
14864 (error "Don't know which date to open in calendar")))
14865 (date (calendar-gregorian-from-absolute day))
14866 (calendar-move-hook nil)
14867 (view-calendar-holidays-initially nil)
14868 (view-diary-entries-initially nil))
14869 (calendar)
14870 (calendar-goto-date date)))
14872 (defun org-calendar-goto-agenda ()
14873 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
14874 This is a command that has to be installed in `calendar-mode-map'."
14875 (interactive)
14876 (org-agenda-list nil (calendar-absolute-from-gregorian
14877 (calendar-cursor-to-date))
14878 nil))
14880 (defun org-agenda-convert-date ()
14881 (interactive)
14882 (org-agenda-check-type t 'agenda 'timeline)
14883 (let ((day (get-text-property (point) 'day))
14884 date s)
14885 (unless day
14886 (error "Don't know which date to convert"))
14887 (setq date (calendar-gregorian-from-absolute day))
14888 (setq s (concat
14889 "Gregorian: " (calendar-date-string date) "\n"
14890 "ISO: " (calendar-iso-date-string date) "\n"
14891 "Day of Yr: " (calendar-day-of-year-string date) "\n"
14892 "Julian: " (calendar-julian-date-string date) "\n"
14893 "Astron. JD: " (calendar-astro-date-string date)
14894 " (Julian date number at noon UTC)\n"
14895 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
14896 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
14897 "French: " (calendar-french-date-string date) "\n"
14898 "Mayan: " (calendar-mayan-date-string date) "\n"
14899 "Coptic: " (calendar-coptic-date-string date) "\n"
14900 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
14901 "Persian: " (calendar-persian-date-string date) "\n"
14902 "Chinese: " (calendar-chinese-date-string date) "\n"))
14903 (with-output-to-temp-buffer "*Dates*"
14904 (princ s))
14905 (if (fboundp 'fit-window-to-buffer)
14906 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
14909 ;;;; Embedded LaTeX
14911 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14912 "Keymap for the minor `org-cdlatex-mode'.")
14914 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14915 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14916 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14917 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14918 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14920 (defvar org-cdlatex-texmathp-advice-is-done nil
14921 "Flag remembering if we have applied the advice to texmathp already.")
14923 (define-minor-mode org-cdlatex-mode
14924 "Toggle the minor `org-cdlatex-mode'.
14925 This mode supports entering LaTeX environment and math in LaTeX fragments
14926 in Org-mode.
14927 \\{org-cdlatex-mode-map}"
14928 nil " OCDL" nil
14929 (when org-cdlatex-mode (require 'cdlatex))
14930 (unless org-cdlatex-texmathp-advice-is-done
14931 (setq org-cdlatex-texmathp-advice-is-done t)
14932 (defadvice texmathp (around org-math-always-on activate)
14933 "Always return t in org-mode buffers.
14934 This is because we want to insert math symbols without dollars even outside
14935 the LaTeX math segments. If Orgmode thinks that point is actually inside
14936 en embedded LaTeX fragement, let texmathp do its job.
14937 \\[org-cdlatex-mode-map]"
14938 (interactive)
14939 (let (p)
14940 (cond
14941 ((not (org-mode-p)) ad-do-it)
14942 ((eq this-command 'cdlatex-math-symbol)
14943 (setq ad-return-value t
14944 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14946 (let ((p (org-inside-LaTeX-fragment-p)))
14947 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14948 (setq ad-return-value t
14949 texmathp-why '("Org-mode embedded math" . 0))
14950 (if p ad-do-it)))))))))
14952 (defun turn-on-org-cdlatex ()
14953 "Unconditionally turn on `org-cdlatex-mode'."
14954 (org-cdlatex-mode 1))
14956 (defun org-inside-LaTeX-fragment-p ()
14957 "Test if point is inside a LaTeX fragment.
14958 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14959 sequence appearing also before point.
14960 Even though the matchers for math are configurable, this function assumes
14961 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14962 delimiters are skipped when they have been removed by customization.
14963 The return value is nil, or a cons cell with the delimiter and
14964 and the position of this delimiter.
14966 This function does a reasonably good job, but can locally be fooled by
14967 for example currency specifications. For example it will assume being in
14968 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14969 fragments that are properly closed, but during editing, we have to live
14970 with the uncertainty caused by missing closing delimiters. This function
14971 looks only before point, not after."
14972 (catch 'exit
14973 (let ((pos (point))
14974 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14975 (lim (progn
14976 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14977 (point)))
14978 dd-on str (start 0) m re)
14979 (goto-char pos)
14980 (when dodollar
14981 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14982 re (nth 1 (assoc "$" org-latex-regexps)))
14983 (while (string-match re str start)
14984 (cond
14985 ((= (match-end 0) (length str))
14986 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
14987 ((= (match-end 0) (- (length str) 5))
14988 (throw 'exit nil))
14989 (t (setq start (match-end 0))))))
14990 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14991 (goto-char pos)
14992 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14993 (and (match-beginning 2) (throw 'exit nil))
14994 ;; count $$
14995 (while (re-search-backward "\\$\\$" lim t)
14996 (setq dd-on (not dd-on)))
14997 (goto-char pos)
14998 (if dd-on (cons "$$" m))))))
15001 (defun org-try-cdlatex-tab ()
15002 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15003 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15004 - inside a LaTeX fragment, or
15005 - after the first word in a line, where an abbreviation expansion could
15006 insert a LaTeX environment."
15007 (when org-cdlatex-mode
15008 (cond
15009 ((save-excursion
15010 (skip-chars-backward "a-zA-Z0-9*")
15011 (skip-chars-backward " \t")
15012 (bolp))
15013 (cdlatex-tab) t)
15014 ((org-inside-LaTeX-fragment-p)
15015 (cdlatex-tab) t)
15016 (t nil))))
15018 (defun org-cdlatex-underscore-caret (&optional arg)
15019 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15020 Revert to the normal definition outside of these fragments."
15021 (interactive "P")
15022 (if (org-inside-LaTeX-fragment-p)
15023 (call-interactively 'cdlatex-sub-superscript)
15024 (let (org-cdlatex-mode)
15025 (call-interactively (key-binding (vector last-input-event))))))
15027 (defun org-cdlatex-math-modify (&optional arg)
15028 "Execute `cdlatex-math-modify' in LaTeX fragments.
15029 Revert to the normal definition outside of these fragments."
15030 (interactive "P")
15031 (if (org-inside-LaTeX-fragment-p)
15032 (call-interactively 'cdlatex-math-modify)
15033 (let (org-cdlatex-mode)
15034 (call-interactively (key-binding (vector last-input-event))))))
15036 (defvar org-latex-fragment-image-overlays nil
15037 "List of overlays carrying the images of latex fragments.")
15038 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15040 (defun org-remove-latex-fragment-image-overlays ()
15041 "Remove all overlays with LaTeX fragment images in current buffer."
15042 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15043 (setq org-latex-fragment-image-overlays nil))
15045 (defun org-preview-latex-fragment (&optional subtree)
15046 "Preview the LaTeX fragment at point, or all locally or globally.
15047 If the cursor is in a LaTeX fragment, create the image and overlay
15048 it over the source code. If there is no fragment at point, display
15049 all fragments in the current text, from one headline to the next. With
15050 prefix SUBTREE, display all fragments in the current subtree. With a
15051 double prefix `C-u C-u', or when the cursor is before the first headline,
15052 display all fragments in the buffer.
15053 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15054 (interactive "P")
15055 (org-remove-latex-fragment-image-overlays)
15056 (save-excursion
15057 (save-restriction
15058 (let (beg end at msg)
15059 (cond
15060 ((or (equal subtree '(16))
15061 (not (save-excursion
15062 (re-search-backward (concat "^" outline-regexp) nil t))))
15063 (setq beg (point-min) end (point-max)
15064 msg "Creating images for buffer...%s"))
15065 ((equal subtree '(4))
15066 (org-back-to-heading)
15067 (setq beg (point) end (org-end-of-subtree t)
15068 msg "Creating images for subtree...%s"))
15070 (if (setq at (org-inside-LaTeX-fragment-p))
15071 (goto-char (max (point-min) (- (cdr at) 2)))
15072 (org-back-to-heading))
15073 (setq beg (point) end (progn (outline-next-heading) (point))
15074 msg (if at "Creating image...%s"
15075 "Creating images for entry...%s"))))
15076 (message msg "")
15077 (narrow-to-region beg end)
15078 (org-format-latex
15079 (concat "ltxpng/" (file-name-sans-extension
15080 (file-name-nondirectory
15081 buffer-file-name)))
15082 default-directory 'overlays msg at)
15083 (message msg "done. Use `C-c C-c' to remove images.")))))
15085 (defvar org-latex-regexps
15086 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15087 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15088 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15089 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15090 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15091 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15092 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15093 "Regular expressions for matching embedded LaTeX.")
15095 (defun org-format-latex (prefix &optional dir overlays msg at)
15096 "Replace LaTeX fragments with links to an image, and produce images."
15097 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15098 (let* ((prefixnodir (file-name-nondirectory prefix))
15099 (absprefix (expand-file-name prefix dir))
15100 (todir (file-name-directory absprefix))
15101 (opt org-format-latex-options)
15102 (matchers (plist-get opt :matchers))
15103 (re-list org-latex-regexps)
15104 (cnt 0) txt link beg end re e checkdir
15105 m n block linkfile movefile ov)
15106 ;; Check if there are old images files with this prefix, and remove them
15107 (when (file-directory-p todir)
15108 (mapc 'delete-file
15109 (directory-files
15110 todir 'full
15111 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
15112 ;; Check the different regular expressions
15113 (while (setq e (pop re-list))
15114 (setq m (car e) re (nth 1 e) n (nth 2 e)
15115 block (if (nth 3 e) "\n\n" ""))
15116 (when (member m matchers)
15117 (goto-char (point-min))
15118 (while (re-search-forward re nil t)
15119 (when (or (not at) (equal (cdr at) (match-beginning n)))
15120 (setq txt (match-string n)
15121 beg (match-beginning n) end (match-end n)
15122 cnt (1+ cnt)
15123 linkfile (format "%s_%04d.png" prefix cnt)
15124 movefile (format "%s_%04d.png" absprefix cnt)
15125 link (concat block "[[file:" linkfile "]]" block))
15126 (if msg (message msg cnt))
15127 (goto-char beg)
15128 (unless checkdir ; make sure the directory exists
15129 (setq checkdir t)
15130 (or (file-directory-p todir) (make-directory todir)))
15131 (org-create-formula-image
15132 txt movefile opt)
15133 (if overlays
15134 (progn
15135 (setq ov (org-make-overlay beg end))
15136 (if (featurep 'xemacs)
15137 (progn
15138 (org-overlay-put ov 'invisible t)
15139 (org-overlay-put
15140 ov 'end-glyph
15141 (make-glyph (vector 'png :file movefile))))
15142 (org-overlay-put
15143 ov 'display
15144 (list 'image :type 'png :file movefile :ascent 'center)))
15145 (push ov org-latex-fragment-image-overlays)
15146 (goto-char end))
15147 (delete-region beg end)
15148 (insert link))))))))
15150 ;; This function borrows from Ganesh Swami's latex2png.el
15151 (defun org-create-formula-image (string tofile options)
15152 (let* ((tmpdir (if (featurep 'xemacs)
15153 (temp-directory)
15154 temporary-file-directory))
15155 (texfilebase (make-temp-name
15156 (expand-file-name "orgtex" tmpdir)))
15158 ;(texfilebase (make-temp-file "orgtex"))
15159 ; (dummy (delete-file texfilebase))
15160 (texfile (concat texfilebase ".tex"))
15161 (dvifile (concat texfilebase ".dvi"))
15162 (pngfile (concat texfilebase ".png"))
15163 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15164 (fg (or (plist-get options :foreground) "Black"))
15165 (bg (or (plist-get options :background) "Transparent")))
15166 (with-temp-file texfile
15167 (insert "\\documentclass{article}
15168 \\usepackage{fullpage}
15169 \\usepackage{amssymb}
15170 \\usepackage[usenames]{color}
15171 \\usepackage{amsmath}
15172 \\usepackage{latexsym}
15173 \\usepackage[mathscr]{eucal}
15174 \\pagestyle{empty}
15175 \\begin{document}\n" string "\n\\end{document}\n"))
15176 (let ((dir default-directory))
15177 (condition-case nil
15178 (progn
15179 (cd tmpdir)
15180 (call-process "latex" nil nil nil texfile))
15181 (error nil))
15182 (cd dir))
15183 (if (not (file-exists-p dvifile))
15184 (progn (message "Failed to create dvi file from %s" texfile) nil)
15185 (call-process "dvipng" nil nil nil
15186 "-E" "-fg" fg "-bg" bg
15187 "-x" scale "-y" scale "-T" "tight"
15188 "-o" pngfile
15189 dvifile)
15190 (if (not (file-exists-p pngfile))
15191 (progn (message "Failed to create png file from %s" texfile) nil)
15192 ;; Use the requested file name and clean up
15193 (copy-file pngfile tofile 'replace)
15194 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15195 (delete-file (concat texfilebase e)))
15196 pngfile))))
15198 ;;;; Exporting
15200 ;;; Variables, constants, and parameter plists
15202 (defconst org-level-max 20)
15204 (defvar org-export-html-preamble nil
15205 "Preamble, to be inserted just after <body>. Set by publishing functions.")
15206 (defvar org-export-html-postamble nil
15207 "Preamble, to be inserted just before </body>. Set by publishing functions.")
15208 (defvar org-export-html-auto-preamble t
15209 "Should default preamble be inserted? Set by publishing functions.")
15210 (defvar org-export-html-auto-postamble t
15211 "Should default postamble be inserted? Set by publishing functions.")
15212 (defvar org-current-export-file nil) ; dynamically scoped parameter
15213 (defvar org-current-export-dir nil) ; dynamically scoped parameter
15216 (defconst org-export-plist-vars
15217 '((:language . org-export-default-language)
15218 (:customtime . org-display-custom-times)
15219 (:headline-levels . org-export-headline-levels)
15220 (:section-numbers . org-export-with-section-numbers)
15221 (:table-of-contents . org-export-with-toc)
15222 (:archived-trees . org-export-with-archived-trees)
15223 (:emphasize . org-export-with-emphasize)
15224 (:sub-superscript . org-export-with-sub-superscripts)
15225 (:TeX-macros . org-export-with-TeX-macros)
15226 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
15227 (:fixed-width . org-export-with-fixed-width)
15228 (:timestamps . org-export-with-timestamps)
15229 (:tables . org-export-with-tables)
15230 (:table-auto-headline . org-export-highlight-first-table-line)
15231 (:style . org-export-html-style)
15232 (:convert-org-links . org-export-html-link-org-files-as-html)
15233 (:inline-images . org-export-html-inline-images)
15234 (:expand-quoted-html . org-export-html-expand)
15235 (:timestamp . org-export-html-with-timestamp)
15236 (:publishing-directory . org-export-publishing-directory)
15237 (:preamble . org-export-html-preamble)
15238 (:postamble . org-export-html-postamble)
15239 (:auto-preamble . org-export-html-auto-preamble)
15240 (:auto-postamble . org-export-html-auto-postamble)
15241 (:author . user-full-name)
15242 (:email . user-mail-address)))
15244 (defun org-default-export-plist ()
15245 "Return the property list with default settings for the export variables."
15246 (let ((l org-export-plist-vars) rtn e)
15247 (while (setq e (pop l))
15248 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
15249 rtn))
15251 (defun org-infile-export-plist ()
15252 "Return the property list with file-local settings for export."
15253 (save-excursion
15254 (goto-char 0)
15255 (let ((re (org-make-options-regexp
15256 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
15257 p key val text options)
15258 (while (re-search-forward re nil t)
15259 (setq key (org-match-string-no-properties 1)
15260 val (org-match-string-no-properties 2))
15261 (cond
15262 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
15263 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
15264 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
15265 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
15266 ((string-equal key "TEXT")
15267 (setq text (if text (concat text "\n" val) val)))
15268 ((string-equal key "OPTIONS") (setq options val))))
15269 (setq p (plist-put p :text text))
15270 (when options
15271 (let ((op '(("H" . :headline-levels)
15272 ("num" . :section-numbers)
15273 ("toc" . :table-of-contents)
15274 ("\\n" . :preserve-breaks)
15275 ("@" . :expand-quoted-html)
15276 (":" . :fixed-width)
15277 ("|" . :tables)
15278 ("^" . :sub-superscript)
15279 ("*" . :emphasize)
15280 ("TeX" . :TeX-macros)
15281 ("LaTeX" . :LaTeX-fragments)))
15283 (while (setq o (pop op))
15284 (if (string-match (concat (regexp-quote (car o))
15285 ":\\([^ \t\n\r;,.]*\\)")
15286 options)
15287 (setq p (plist-put p (cdr o)
15288 (car (read-from-string
15289 (match-string 1 options)))))))))
15290 p)))
15292 (defun org-combine-plists (&rest plists)
15293 "Create a single property list from all plists in PLISTS.
15294 The process starts by copying the last list, and then setting properties
15295 from the other lists. Settings in the first list are the most significant
15296 ones and overrule settings in the other lists."
15297 (let ((rtn (copy-sequence (pop plists)))
15298 p v ls)
15299 (while plists
15300 (setq ls (pop plists))
15301 (while ls
15302 (setq p (pop ls) v (pop ls))
15303 (setq rtn (plist-put rtn p v))))
15304 rtn))
15306 (defun org-export-directory (type plist)
15307 (let* ((val (plist-get plist :publishing-directory))
15308 (dir (if (listp val)
15309 (or (cdr (assoc type val)) ".")
15310 val)))
15311 dir))
15313 (defun org-export-find-first-heading-line (list)
15314 "Remove all lines from LIST which are before the first headline."
15315 (let ((orig-list list)
15316 (re (concat "^" outline-regexp)))
15317 (while (and list
15318 (not (string-match re (car list))))
15319 (pop list))
15320 (or list orig-list)))
15322 (defun org-skip-comments (lines)
15323 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
15324 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
15325 (re2 "^\\(\\*+\\)[ \t\n\r]")
15326 rtn line level)
15327 (while (setq line (pop lines))
15328 (cond
15329 ((and (string-match re1 line)
15330 (setq level (- (match-end 1) (match-beginning 1))))
15331 ;; Beginning of a COMMENT subtree. Skip it.
15332 (while (and (setq line (pop lines))
15333 (or (not (string-match re2 line))
15334 (> (- (match-end 1) (match-beginning 1)) level))))
15335 (setq lines (cons line lines)))
15336 ((string-match "^#" line)
15337 ;; an ordinary comment line
15339 ((and org-export-table-remove-special-lines
15340 (string-match "^[ \t]*|" line)
15341 (or (string-match "^[ \t]*| *[!_^] *|" line)
15342 (and (string-match "| *<[0-9]+> *|" line)
15343 (not (string-match "| *[^ <|]" line)))))
15344 ;; a special table line that should be removed
15346 (t (setq rtn (cons line rtn)))))
15347 (nreverse rtn)))
15349 (defun org-export (&optional arg)
15350 (interactive)
15351 (let ((help "[t] insert the export option template
15352 \[v] limit export to visible part of outline tree
15354 \[a] export as ASCII
15355 \[h] export as HTML
15356 \[b] export as HTML and browse immediately
15357 \[x] export as XOXO
15359 \[i] export current file as iCalendar file
15360 \[I] export all agenda files as iCalendar files
15361 \[c] export agenda files into combined iCalendar file
15363 \[F] publish current file
15364 \[P] publish current project
15365 \[X] publish... (project will be prompted for)
15366 \[A] publish all projects")
15367 (cmds
15368 '((?t . org-insert-export-options-template)
15369 (?v . org-export-visible)
15370 (?a . org-export-as-ascii)
15371 (?h . org-export-as-html)
15372 (?b . org-export-as-html-and-open)
15373 (?x . org-export-as-xoxo)
15374 (?i . org-export-icalendar-this-file)
15375 (?I . org-export-icalendar-all-agenda-files)
15376 (?c . org-export-icalendar-combine-agenda-files)
15377 (?F . org-publish-current-file)
15378 (?P . org-publish-current-project)
15379 (?X . org-publish)
15380 (?A . org-publish-all)))
15381 r1 r2 ass)
15382 (save-window-excursion
15383 (delete-other-windows)
15384 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
15385 (princ help))
15386 (message "Select command: ")
15387 (setq r1 (read-char-exclusive)))
15388 (setq r2 (if (< r1 27) (+ r1 96) r1))
15389 (if (setq ass (assq r2 cmds))
15390 (call-interactively (cdr ass))
15391 (error "No command associated with key %c" r1))))
15393 (defconst org-html-entities
15394 '(("nbsp")
15395 ("iexcl")
15396 ("cent")
15397 ("pound")
15398 ("curren")
15399 ("yen")
15400 ("brvbar")
15401 ("sect")
15402 ("uml")
15403 ("copy")
15404 ("ordf")
15405 ("laquo")
15406 ("not")
15407 ("shy")
15408 ("reg")
15409 ("macr")
15410 ("deg")
15411 ("plusmn")
15412 ("sup2")
15413 ("sup3")
15414 ("acute")
15415 ("micro")
15416 ("para")
15417 ("middot")
15418 ("odot"."o")
15419 ("star"."*")
15420 ("cedil")
15421 ("sup1")
15422 ("ordm")
15423 ("raquo")
15424 ("frac14")
15425 ("frac12")
15426 ("frac34")
15427 ("iquest")
15428 ("Agrave")
15429 ("Aacute")
15430 ("Acirc")
15431 ("Atilde")
15432 ("Auml")
15433 ("Aring") ("AA"."&Aring;")
15434 ("AElig")
15435 ("Ccedil")
15436 ("Egrave")
15437 ("Eacute")
15438 ("Ecirc")
15439 ("Euml")
15440 ("Igrave")
15441 ("Iacute")
15442 ("Icirc")
15443 ("Iuml")
15444 ("ETH")
15445 ("Ntilde")
15446 ("Ograve")
15447 ("Oacute")
15448 ("Ocirc")
15449 ("Otilde")
15450 ("Ouml")
15451 ("times")
15452 ("Oslash")
15453 ("Ugrave")
15454 ("Uacute")
15455 ("Ucirc")
15456 ("Uuml")
15457 ("Yacute")
15458 ("THORN")
15459 ("szlig")
15460 ("agrave")
15461 ("aacute")
15462 ("acirc")
15463 ("atilde")
15464 ("auml")
15465 ("aring")
15466 ("aelig")
15467 ("ccedil")
15468 ("egrave")
15469 ("eacute")
15470 ("ecirc")
15471 ("euml")
15472 ("igrave")
15473 ("iacute")
15474 ("icirc")
15475 ("iuml")
15476 ("eth")
15477 ("ntilde")
15478 ("ograve")
15479 ("oacute")
15480 ("ocirc")
15481 ("otilde")
15482 ("ouml")
15483 ("divide")
15484 ("oslash")
15485 ("ugrave")
15486 ("uacute")
15487 ("ucirc")
15488 ("uuml")
15489 ("yacute")
15490 ("thorn")
15491 ("yuml")
15492 ("fnof")
15493 ("Alpha")
15494 ("Beta")
15495 ("Gamma")
15496 ("Delta")
15497 ("Epsilon")
15498 ("Zeta")
15499 ("Eta")
15500 ("Theta")
15501 ("Iota")
15502 ("Kappa")
15503 ("Lambda")
15504 ("Mu")
15505 ("Nu")
15506 ("Xi")
15507 ("Omicron")
15508 ("Pi")
15509 ("Rho")
15510 ("Sigma")
15511 ("Tau")
15512 ("Upsilon")
15513 ("Phi")
15514 ("Chi")
15515 ("Psi")
15516 ("Omega")
15517 ("alpha")
15518 ("beta")
15519 ("gamma")
15520 ("delta")
15521 ("epsilon")
15522 ("varepsilon"."&epsilon;")
15523 ("zeta")
15524 ("eta")
15525 ("theta")
15526 ("iota")
15527 ("kappa")
15528 ("lambda")
15529 ("mu")
15530 ("nu")
15531 ("xi")
15532 ("omicron")
15533 ("pi")
15534 ("rho")
15535 ("sigmaf") ("varsigma"."&sigmaf;")
15536 ("sigma")
15537 ("tau")
15538 ("upsilon")
15539 ("phi")
15540 ("chi")
15541 ("psi")
15542 ("omega")
15543 ("thetasym") ("vartheta"."&thetasym;")
15544 ("upsih")
15545 ("piv")
15546 ("bull") ("bullet"."&bull;")
15547 ("hellip") ("dots"."&hellip;")
15548 ("prime")
15549 ("Prime")
15550 ("oline")
15551 ("frasl")
15552 ("weierp")
15553 ("image")
15554 ("real")
15555 ("trade")
15556 ("alefsym")
15557 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
15558 ("uarr") ("uparrow"."&uarr;")
15559 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
15560 ("darr")("downarrow"."&darr;")
15561 ("harr") ("leftrightarrow"."&harr;")
15562 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
15563 ("lArr") ("Leftarrow"."&lArr;")
15564 ("uArr") ("Uparrow"."&uArr;")
15565 ("rArr") ("Rightarrow"."&rArr;")
15566 ("dArr") ("Downarrow"."&dArr;")
15567 ("hArr") ("Leftrightarrow"."&hArr;")
15568 ("forall")
15569 ("part") ("partial"."&part;")
15570 ("exist") ("exists"."&exist;")
15571 ("empty") ("emptyset"."&empty;")
15572 ("nabla")
15573 ("isin") ("in"."&isin;")
15574 ("notin")
15575 ("ni")
15576 ("prod")
15577 ("sum")
15578 ("minus")
15579 ("lowast") ("ast"."&lowast;")
15580 ("radic")
15581 ("prop") ("proptp"."&prop;")
15582 ("infin") ("infty"."&infin;")
15583 ("ang") ("angle"."&ang;")
15584 ("and") ("vee"."&and;")
15585 ("or") ("wedge"."&or;")
15586 ("cap")
15587 ("cup")
15588 ("int")
15589 ("there4")
15590 ("sim")
15591 ("cong") ("simeq"."&cong;")
15592 ("asymp")("approx"."&asymp;")
15593 ("ne") ("neq"."&ne;")
15594 ("equiv")
15595 ("le")
15596 ("ge")
15597 ("sub") ("subset"."&sub;")
15598 ("sup") ("supset"."&sup;")
15599 ("nsub")
15600 ("sube")
15601 ("supe")
15602 ("oplus")
15603 ("otimes")
15604 ("perp")
15605 ("sdot") ("cdot"."&sdot;")
15606 ("lceil")
15607 ("rceil")
15608 ("lfloor")
15609 ("rfloor")
15610 ("lang")
15611 ("rang")
15612 ("loz") ("Diamond"."&loz;")
15613 ("spades") ("spadesuit"."&spades;")
15614 ("clubs") ("clubsuit"."&clubs;")
15615 ("hearts") ("diamondsuit"."&hearts;")
15616 ("diams") ("diamondsuit"."&diams;")
15617 ("quot")
15618 ("amp")
15619 ("lt")
15620 ("gt")
15621 ("OElig")
15622 ("oelig")
15623 ("Scaron")
15624 ("scaron")
15625 ("Yuml")
15626 ("circ")
15627 ("tilde")
15628 ("ensp")
15629 ("emsp")
15630 ("thinsp")
15631 ("zwnj")
15632 ("zwj")
15633 ("lrm")
15634 ("rlm")
15635 ("ndash")
15636 ("mdash")
15637 ("lsquo")
15638 ("rsquo")
15639 ("sbquo")
15640 ("ldquo")
15641 ("rdquo")
15642 ("bdquo")
15643 ("dagger")
15644 ("Dagger")
15645 ("permil")
15646 ("lsaquo")
15647 ("rsaquo")
15648 ("euro")
15650 ("arccos"."arccos")
15651 ("arcsin"."arcsin")
15652 ("arctan"."arctan")
15653 ("arg"."arg")
15654 ("cos"."cos")
15655 ("cosh"."cosh")
15656 ("cot"."cot")
15657 ("coth"."coth")
15658 ("csc"."csc")
15659 ("deg"."deg")
15660 ("det"."det")
15661 ("dim"."dim")
15662 ("exp"."exp")
15663 ("gcd"."gcd")
15664 ("hom"."hom")
15665 ("inf"."inf")
15666 ("ker"."ker")
15667 ("lg"."lg")
15668 ("lim"."lim")
15669 ("liminf"."liminf")
15670 ("limsup"."limsup")
15671 ("ln"."ln")
15672 ("log"."log")
15673 ("max"."max")
15674 ("min"."min")
15675 ("Pr"."Pr")
15676 ("sec"."sec")
15677 ("sin"."sin")
15678 ("sinh"."sinh")
15679 ("sup"."sup")
15680 ("tan"."tan")
15681 ("tanh"."tanh")
15683 "Entities for TeX->HTML translation.
15684 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
15685 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
15686 In that case, \"\\ent\" will be translated to \"&other;\".
15687 The list contains HTML entities for Latin-1, Greek and other symbols.
15688 It is supplemented by a number of commonly used TeX macros with appropriate
15689 translations. There is currently no way for users to extend this.")
15691 ;;; General functions for all backends
15693 (defun org-cleaned-string-for-export (string &rest parameters)
15694 "Cleanup a buffer substring so that links can be created safely."
15695 (interactive)
15696 (let* ((re-radio (and org-target-link-regexp
15697 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
15698 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
15699 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
15700 (re-archive (concat ":" org-archive-tag ":"))
15701 rtn)
15702 (save-excursion
15703 (set-buffer (get-buffer-create " org-mode-tmp"))
15704 (erase-buffer)
15705 (insert string)
15706 (let ((org-inhibit-startup t)) (org-mode))
15707 (untabify (point-min) (point-max))
15709 ;; Get rid of archived trees
15710 (when (not (eq org-export-with-archived-trees t))
15711 (goto-char (point-min))
15712 (while (re-search-forward re-archive nil t)
15713 (if (not (org-on-heading-p))
15714 (org-end-of-subtree t)
15715 (beginning-of-line 1)
15716 (delete-region
15717 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
15718 (org-end-of-subtree t)))))
15720 ;; Find targets in comments and move them out of comments,
15721 ;; but mark them as targets that should be invisible
15722 (goto-char (point-min))
15723 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
15724 (replace-match "\\1(INVISIBLE)"))
15726 ;; Remove comments
15727 (goto-char (point-min))
15728 (while (re-search-forward "^#.*\n?" nil t)
15729 (replace-match ""))
15731 ;; Find matches for radio targets and turn them into internal links
15732 (goto-char (point-min))
15733 (when re-radio
15734 (while (re-search-forward re-radio nil t)
15735 (replace-match "\\1[[\\2]]")))
15737 ;; Find all links that contain a newline and put them into a single line
15738 (goto-char (point-min))
15739 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
15740 (replace-match "\\1 \\3")
15741 (goto-char (match-beginning 0)))
15743 ;; Convert LaTeX fragments to images
15744 (when (memq :LaTeX-fragments parameters)
15745 (org-format-latex
15746 (concat "ltxpng/" (file-name-sans-extension
15747 (file-name-nondirectory
15748 org-current-export-file)))
15749 org-current-export-dir nil "Creating LaTeX image %s"))
15750 (message "Exporting...")
15752 ;; Normalize links: Convert angle and plain links into bracket links
15753 ;; Expand link abbreviations
15754 (goto-char (point-min))
15755 (while (re-search-forward re-plain-link nil t)
15756 (replace-match
15757 (concat
15758 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
15759 t t))
15760 (goto-char (point-min))
15761 (while (re-search-forward re-angle-link nil t)
15762 (replace-match
15763 (concat
15764 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
15765 t t))
15766 (goto-char (point-min))
15767 (while (re-search-forward org-bracket-link-regexp nil t)
15768 (replace-match
15769 (concat "[[" (save-match-data
15770 (org-link-expand-abbrev (match-string 1)))
15772 (if (match-end 3)
15773 (match-string 2)
15774 (concat "[" (match-string 1) "]"))
15775 "]")
15776 t t))
15778 ;; Find multiline emphasis and put them into single line
15779 (when (memq :emph-multiline parameters)
15780 (goto-char (point-min))
15781 (while (re-search-forward org-emph-re nil t)
15782 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
15783 (goto-char (1- (match-end 0)))))
15785 (setq rtn (buffer-string)))
15786 (kill-buffer " org-mode-tmp")
15787 rtn))
15789 (defun org-solidify-link-text (s &optional alist)
15790 "Take link text and make a safe target out of it."
15791 (save-match-data
15792 (let* ((rtn
15793 (mapconcat
15794 'identity
15795 (org-split-string s "[ \t\r\n]+") "--"))
15796 (a (assoc rtn alist)))
15797 (or (cdr a) rtn))))
15799 ;; Variable holding the vector with section numbers
15800 (defvar org-section-numbers (make-vector org-level-max 0))
15802 (defun org-init-section-numbers ()
15803 "Initialize the vector for the section numbers."
15804 (let* ((level -1)
15805 (numbers (nreverse (org-split-string "" "\\.")))
15806 (depth (1- (length org-section-numbers)))
15807 (i depth) number-string)
15808 (while (>= i 0)
15809 (if (> i level)
15810 (aset org-section-numbers i 0)
15811 (setq number-string (or (car numbers) "0"))
15812 (if (string-match "\\`[A-Z]\\'" number-string)
15813 (aset org-section-numbers i
15814 (- (string-to-char number-string) ?A -1))
15815 (aset org-section-numbers i (string-to-number number-string)))
15816 (pop numbers))
15817 (setq i (1- i)))))
15819 (defun org-section-number (&optional level)
15820 "Return a string with the current section number.
15821 When LEVEL is non-nil, increase section numbers on that level."
15822 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
15823 (when level
15824 (when (> level -1)
15825 (aset org-section-numbers
15826 level (1+ (aref org-section-numbers level))))
15827 (setq idx (1+ level))
15828 (while (<= idx depth)
15829 (if (not (= idx 1))
15830 (aset org-section-numbers idx 0))
15831 (setq idx (1+ idx))))
15832 (setq idx 0)
15833 (while (<= idx depth)
15834 (setq n (aref org-section-numbers idx))
15835 (setq string (concat string (if (not (string= string "")) "." "")
15836 (int-to-string n)))
15837 (setq idx (1+ idx)))
15838 (save-match-data
15839 (if (string-match "\\`\\([@0]\\.\\)+" string)
15840 (setq string (replace-match "" t nil string)))
15841 (if (string-match "\\(\\.0\\)+\\'" string)
15842 (setq string (replace-match "" t nil string))))
15843 string))
15845 ;;; ASCII export
15847 (defvar org-last-level nil) ; dynamically scoped variable
15848 (defvar org-levels-open nil) ; dynamically scoped parameter
15849 (defvar org-ascii-current-indentation nil) ; For communication
15851 (defun org-export-as-ascii (arg)
15852 "Export the outline as a pretty ASCII file.
15853 If there is an active region, export only the region.
15854 The prefix ARG specifies how many levels of the outline should become
15855 underlined headlines. The default is 3."
15856 (interactive "P")
15857 (setq-default org-todo-line-regexp org-todo-line-regexp)
15858 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15859 (org-infile-export-plist)))
15860 (region
15861 (buffer-substring
15862 (if (org-region-active-p) (region-beginning) (point-min))
15863 (if (org-region-active-p) (region-end) (point-max))))
15864 (custom-times org-display-custom-times)
15865 (lines (org-export-find-first-heading-line
15866 (org-skip-comments
15867 (org-split-string
15868 (org-cleaned-string-for-export region)
15869 "[\r\n]"))))
15870 (org-ascii-current-indentation '(0 . 0))
15871 (org-startup-with-deadline-check nil)
15872 (level 0) line txt
15873 (umax nil)
15874 (case-fold-search nil)
15875 (filename (concat (file-name-as-directory
15876 (org-export-directory :ascii opt-plist))
15877 (file-name-sans-extension
15878 (file-name-nondirectory buffer-file-name))
15879 ".txt"))
15880 (buffer (find-file-noselect filename))
15881 (org-levels-open (make-vector org-level-max nil))
15882 (odd org-odd-levels-only)
15883 (date (format-time-string "%Y/%m/%d" (current-time)))
15884 (time (format-time-string "%X" (org-current-time)))
15885 (author (plist-get opt-plist :author))
15886 (title (or (plist-get opt-plist :title)
15887 (file-name-sans-extension
15888 (file-name-nondirectory buffer-file-name))))
15889 (email (plist-get opt-plist :email))
15890 (language (plist-get opt-plist :language))
15891 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
15892 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
15893 (text nil)
15894 (todo nil)
15895 (lang-words nil))
15897 (setq org-last-level 1)
15898 (org-init-section-numbers)
15900 (find-file-noselect filename)
15902 (setq lang-words (or (assoc language org-export-language-setup)
15903 (assoc "en" org-export-language-setup)))
15904 (if org-export-ascii-show-new-buffer
15905 (switch-to-buffer-other-window buffer)
15906 (set-buffer buffer))
15907 (erase-buffer)
15908 (fundamental-mode)
15909 ;; create local variables for all options, to make sure all called
15910 ;; functions get the correct information
15911 (mapcar (lambda (x)
15912 (set (make-local-variable (cdr x))
15913 (plist-get opt-plist (car x))))
15914 org-export-plist-vars)
15915 (org-set-local 'org-odd-levels-only odd)
15916 (setq umax (if arg (prefix-numeric-value arg)
15917 org-export-headline-levels))
15919 ;; File header
15920 (if title (org-insert-centered title ?=))
15921 (insert "\n")
15922 (if (or author email)
15923 (insert (concat (nth 1 lang-words) ": " (or author "")
15924 (if email (concat " <" email ">") "")
15925 "\n")))
15926 (if (and date time)
15927 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
15928 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
15930 (insert "\n\n")
15932 (if org-export-with-toc
15933 (progn
15934 (insert (nth 3 lang-words) "\n"
15935 (make-string (length (nth 3 lang-words)) ?=) "\n")
15936 (mapcar '(lambda (line)
15937 (if (string-match org-todo-line-regexp
15938 line)
15939 ;; This is a headline
15940 (progn
15941 (setq level (- (match-end 1) (match-beginning 1))
15942 level (org-tr-level level)
15943 txt (match-string 3 line)
15944 todo
15945 (or (and org-export-mark-todo-in-toc
15946 (match-beginning 2)
15947 (not (equal (match-string 2 line)
15948 org-done-string)))
15949 ; TODO, not DONE
15950 (and org-export-mark-todo-in-toc
15951 (= level umax)
15952 (org-search-todo-below
15953 line lines level))))
15954 (setq txt (org-html-expand-for-ascii txt))
15956 (if (and (memq org-export-with-tags '(not-in-toc nil))
15957 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
15958 (setq txt (replace-match "" t t txt)))
15959 (if (string-match quote-re0 txt)
15960 (setq txt (replace-match "" t t txt)))
15962 (if org-export-with-section-numbers
15963 (setq txt (concat (org-section-number level)
15964 " " txt)))
15965 (if (<= level umax)
15966 (progn
15967 (insert
15968 (make-string (* (1- level) 4) ?\ )
15969 (format (if todo "%s (*)\n" "%s\n") txt))
15970 (setq org-last-level level))
15971 ))))
15972 lines)))
15974 (org-init-section-numbers)
15975 (while (setq line (pop lines))
15976 ;; Remove the quoted HTML tags.
15977 (setq line (org-html-expand-for-ascii line))
15978 ;; Remove targets
15979 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
15980 (setq line (replace-match "" t t line)))
15981 ;; Replace internal links
15982 (while (string-match org-bracket-link-regexp line)
15983 (setq line (replace-match
15984 (if (match-end 3) "[\\3]" "[\\1]")
15985 t nil line)))
15986 (when custom-times
15987 (setq line (org-translate-time line)))
15988 (cond
15989 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
15990 ;; a Headline
15991 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
15992 txt (match-string 2 line))
15993 (org-ascii-level-start level txt umax lines))
15995 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
15996 (normal-mode)
15997 (save-buffer)
15998 ;; remove display and invisible chars
15999 (let (beg end)
16000 (goto-char (point-min))
16001 (while (setq beg (next-single-property-change (point) 'display))
16002 (setq end (next-single-property-change beg 'display))
16003 (delete-region beg end)
16004 (goto-char beg)
16005 (insert "=>"))
16006 (goto-char (point-min))
16007 (while (setq beg (next-single-property-change (point) 'org-cwidth))
16008 (setq end (next-single-property-change beg 'org-cwidth))
16009 (delete-region beg end)
16010 (goto-char beg)))
16011 (goto-char (point-min))))
16013 (defun org-search-todo-below (line lines level)
16014 "Search the subtree below LINE for any TODO entries."
16015 (let ((rest (cdr (memq line lines)))
16016 (re org-todo-line-regexp)
16017 line lv todo)
16018 (catch 'exit
16019 (while (setq line (pop rest))
16020 (if (string-match re line)
16021 (progn
16022 (setq lv (- (match-end 1) (match-beginning 1))
16023 todo (and (match-beginning 2)
16024 (not (equal (match-string 2 line)
16025 org-done-string))))
16026 ; TODO, not DONE
16027 (if (<= lv level) (throw 'exit nil))
16028 (if todo (throw 'exit t))))))))
16030 (defun org-html-expand-for-ascii (line)
16031 "Handle quoted HTML for ASCII export."
16032 (if org-export-html-expand
16033 (while (string-match "@<[^<>\n]*>" line)
16034 ;; We just remove the tags for now.
16035 (setq line (replace-match "" nil nil line))))
16036 line)
16038 (defun org-insert-centered (s &optional underline)
16039 "Insert the string S centered and underline it with character UNDERLINE."
16040 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
16041 (insert (make-string ind ?\ ) s "\n")
16042 (if underline
16043 (insert (make-string ind ?\ )
16044 (make-string (string-width s) underline)
16045 "\n"))))
16047 (defun org-ascii-level-start (level title umax &optional lines)
16048 "Insert a new level in ASCII export."
16049 (let (char (n (- level umax 1)) (ind 0))
16050 (if (> level umax)
16051 (progn
16052 (insert (make-string (* 2 n) ?\ )
16053 (char-to-string (nth (% n (length org-export-ascii-bullets))
16054 org-export-ascii-bullets))
16055 " " title "\n")
16056 ;; find the indentation of the next non-empty line
16057 (catch 'stop
16058 (while lines
16059 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
16060 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
16061 (throw 'stop (setq ind (org-get-indentation (car lines)))))
16062 (pop lines)))
16063 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
16064 (if (or (not (equal (char-before) ?\n))
16065 (not (equal (char-before (1- (point))) ?\n)))
16066 (insert "\n"))
16067 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
16068 (unless org-export-with-tags
16069 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
16070 (setq title (replace-match "" t t title))))
16071 (if org-export-with-section-numbers
16072 (setq title (concat (org-section-number level) " " title)))
16073 (insert title "\n" (make-string (string-width title) char) "\n")
16074 (setq org-ascii-current-indentation '(0 . 0)))))
16076 (defun org-export-visible (type arg)
16077 "Create a copy of the visible part of the current buffer, and export it.
16078 The copy is created in a temporary buffer and removed after use.
16079 TYPE is the final key (as a string) that also select the export command in
16080 the `C-c C-e' export dispatcher.
16081 As a special case, if the you type SPC at the prompt, the temporary
16082 org-mode file will not be removed but presented to you so that you can
16083 continue to use it. The prefix arg ARG is passed through to the exporting
16084 command."
16085 (interactive
16086 (list (progn
16087 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
16088 (read-char-exclusive))
16089 current-prefix-arg))
16090 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
16091 (error "Invalid export key"))
16092 (let* ((binding (cdr (assoc type
16093 '((?a . org-export-as-ascii)
16094 (?\C-a . org-export-as-ascii)
16095 (?b . org-export-as-html-and-open)
16096 (?\C-b . org-export-as-html-and-open)
16097 (?h . org-export-as-html)
16098 (?x . org-export-as-xoxo)))))
16099 (keepp (equal type ?\ ))
16100 (file buffer-file-name)
16101 (buffer (get-buffer-create "*Org Export Visible*"))
16102 s e)
16103 (with-current-buffer buffer (erase-buffer))
16104 (save-excursion
16105 (setq s (goto-char (point-min)))
16106 (while (not (= (point) (point-max)))
16107 (goto-char (org-find-invisible))
16108 (append-to-buffer buffer s (point))
16109 (setq s (goto-char (org-find-visible))))
16110 (goto-char (point-min))
16111 (unless keepp
16112 ;; Copy all comment lines to the end, to make sure #+ settings are
16113 ;; still available for the second export step. Kind of a hack, but
16114 ;; does do the trick.
16115 (if (looking-at "#[^\r\n]*")
16116 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
16117 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
16118 (append-to-buffer buffer (1+ (match-beginning 0))
16119 (min (point-max) (1+ (match-end 0))))))
16120 (set-buffer buffer)
16121 (let ((buffer-file-name file)
16122 (org-inhibit-startup t))
16123 (org-mode)
16124 (show-all)
16125 (unless keepp (funcall binding arg))))
16126 (if (not keepp)
16127 (kill-buffer buffer)
16128 (switch-to-buffer-other-window buffer)
16129 (goto-char (point-min)))))
16131 (defun org-find-visible ()
16132 (let ((s (point)))
16133 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
16134 (get-char-property s 'invisible)))
16136 (defun org-find-invisible ()
16137 (let ((s (point)))
16138 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
16139 (not (get-char-property s 'invisible))))
16142 ;;; HTML export
16144 (defun org-get-current-options ()
16145 "Return a string with current options as keyword options.
16146 Does include HTML export options as well as TODO and CATEGORY stuff."
16147 (format
16148 "#+TITLE: %s
16149 #+AUTHOR: %s
16150 #+EMAIL: %s
16151 #+LANGUAGE: %s
16152 #+TEXT: Some descriptive text to be emitted. Several lines OK.
16153 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
16154 #+CATEGORY: %s
16155 #+SEQ_TODO: %s
16156 #+TYP_TODO: %s
16157 #+STARTUP: %s %s %s %s %s %s
16158 #+TAGS: %s
16159 #+ARCHIVE: %s
16160 #+LINK: %s
16162 (buffer-name) (user-full-name) user-mail-address org-export-default-language
16163 org-export-headline-levels
16164 org-export-with-section-numbers
16165 org-export-with-toc
16166 org-export-preserve-breaks
16167 org-export-html-expand
16168 org-export-with-fixed-width
16169 org-export-with-tables
16170 org-export-with-sub-superscripts
16171 org-export-with-emphasize
16172 org-export-with-TeX-macros
16173 org-export-with-LaTeX-fragments
16174 (file-name-nondirectory buffer-file-name)
16175 (if (equal org-todo-interpretation 'sequence)
16176 (mapconcat 'identity org-todo-keywords " ")
16177 "TODO FEEDBACK VERIFY DONE")
16178 (if (equal org-todo-interpretation 'type)
16179 (mapconcat 'identity org-todo-keywords " ")
16180 "Me Jason Marie DONE")
16181 (cdr (assoc org-startup-folded
16182 '((nil . "showall") (t . "overview") (content . "content"))))
16183 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
16184 (if org-odd-levels-only "odd" "oddeven")
16185 (if org-hide-leading-stars "hidestars" "showstars")
16186 (if org-startup-align-all-tables "align" "noalign")
16187 (cond ((eq t org-log-done) "logdone")
16188 ((not org-log-done) "nologging")
16189 ((listp org-log-done)
16190 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
16191 org-log-done " ")))
16192 (or (mapconcat (lambda (x)
16193 (cond
16194 ((equal '(:startgroup) x) "{")
16195 ((equal '(:endgroup) x) "}")
16196 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
16197 (t (car x))))
16198 (or org-tag-alist (org-get-buffer-tags)) " ") "")
16199 org-archive-location
16200 "org file:~/org/%s.org"
16203 (defun org-insert-export-options-template ()
16204 "Insert into the buffer a template with information for exporting."
16205 (interactive)
16206 (if (not (bolp)) (newline))
16207 (let ((s (org-get-current-options)))
16208 (and (string-match "#\\+CATEGORY" s)
16209 (setq s (substring s 0 (match-beginning 0))))
16210 (insert s)))
16212 (defun org-toggle-fixed-width-section (arg)
16213 "Toggle the fixed-width export.
16214 If there is no active region, the QUOTE keyword at the current headline is
16215 inserted or removed. When present, it causes the text between this headline
16216 and the next to be exported as fixed-width text, and unmodified.
16217 If there is an active region, this command adds or removes a colon as the
16218 first character of this line. If the first character of a line is a colon,
16219 this line is also exported in fixed-width font."
16220 (interactive "P")
16221 (let* ((cc 0)
16222 (regionp (org-region-active-p))
16223 (beg (if regionp (region-beginning) (point)))
16224 (end (if regionp (region-end)))
16225 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16226 (re "[ \t]*\\(:\\)")
16227 off)
16228 (if regionp
16229 (save-excursion
16230 (goto-char beg)
16231 (setq cc (current-column))
16232 (beginning-of-line 1)
16233 (setq off (looking-at re))
16234 (while (> nlines 0)
16235 (setq nlines (1- nlines))
16236 (beginning-of-line 1)
16237 (cond
16238 (arg
16239 (move-to-column cc t)
16240 (insert ":\n")
16241 (forward-line -1))
16242 ((and off (looking-at re))
16243 (replace-match "" t t nil 1))
16244 ((not off) (move-to-column cc t) (insert ":")))
16245 (forward-line 1)))
16246 (save-excursion
16247 (org-back-to-heading)
16248 (if (looking-at (concat outline-regexp
16249 "\\( +\\<" org-quote-string "\\>\\)"))
16250 (replace-match "" t t nil 1)
16251 (if (looking-at outline-regexp)
16252 (progn
16253 (goto-char (match-end 0))
16254 (insert " " org-quote-string))))))))
16256 (defun org-export-as-html-and-open (arg)
16257 "Export the outline as HTML and immediately open it with a browser.
16258 If there is an active region, export only the region.
16259 The prefix ARG specifies how many levels of the outline should become
16260 headlines. The default is 3. Lower levels will become bulleted lists."
16261 (interactive "P")
16262 (org-export-as-html arg 'hidden)
16263 (org-open-file buffer-file-name))
16265 (defun org-export-as-html-batch ()
16266 "Call `org-export-as-html', may be used in batch processing as
16267 emacs --batch
16268 --load=$HOME/lib/emacs/org.el
16269 --eval \"(setq org-export-headline-levels 2)\"
16270 --visit=MyFile --funcall org-export-as-html-batch"
16271 (org-export-as-html org-export-headline-levels 'hidden))
16273 (defun org-export-as-html (arg &optional hidden ext-plist)
16274 "Export the outline as a pretty HTML file.
16275 If there is an active region, export only the region.
16276 The prefix ARG specifies how many levels of the outline should become
16277 headlines. The default is 3. Lower levels will become bulleted lists.
16278 When HIDDEN is non-nil, don't display the HTML buffer.
16279 EXT-PLIST is a property list with external parameters overriding
16280 org-mode's default settings, but still inferior to file-local settings."
16281 (interactive "P")
16282 (message "Exporting...")
16283 (setq-default org-todo-line-regexp org-todo-line-regexp)
16284 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
16285 (setq-default org-done-string org-done-string)
16286 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
16287 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
16288 ext-plist
16289 (org-infile-export-plist)))
16291 (style (plist-get opt-plist :style))
16292 (link-validate (plist-get opt-plist :link-validation-function))
16293 valid
16294 (odd org-odd-levels-only)
16295 (region-p (org-region-active-p))
16296 (region
16297 (buffer-substring
16298 (if region-p (region-beginning) (point-min))
16299 (if region-p (region-end) (point-max))))
16300 ;; The following two are dynamically scoped into other
16301 ;; routines below.
16302 (org-current-export-dir (org-export-directory :html opt-plist))
16303 (org-current-export-file buffer-file-name)
16304 (all_lines
16305 (org-skip-comments (org-split-string
16306 (org-cleaned-string-for-export
16307 region :emph-multiline
16308 (if (plist-get opt-plist :LaTeX-fragments)
16309 :LaTeX-fragments))
16310 "[\r\n]")))
16311 (lines (org-export-find-first-heading-line all_lines))
16312 (level 0) (line "") (origline "") txt todo
16313 (umax nil)
16314 (filename (concat (file-name-as-directory
16315 (org-export-directory :html opt-plist))
16316 (file-name-sans-extension
16317 (file-name-nondirectory buffer-file-name))
16318 ".html"))
16319 (current-dir (file-name-directory buffer-file-name))
16320 (buffer (find-file-noselect filename))
16321 (org-levels-open (make-vector org-level-max nil))
16322 (date (format-time-string "%Y/%m/%d" (current-time)))
16323 (time (format-time-string "%X" (org-current-time)))
16324 (author (plist-get opt-plist :author))
16325 (title (or (plist-get opt-plist :title)
16326 (file-name-sans-extension
16327 (file-name-nondirectory buffer-file-name))))
16328 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
16329 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
16330 (inquote nil)
16331 (infixed nil)
16332 (in-local-list nil)
16333 (local-list-num nil)
16334 (local-list-indent nil)
16335 (llt org-plain-list-ordered-item-terminator)
16336 (email (plist-get opt-plist :email))
16337 (language (plist-get opt-plist :language))
16338 (text (plist-get opt-plist :text))
16339 (lang-words nil)
16340 (target-alist nil) tg
16341 (head-count 0) cnt
16342 (start 0)
16343 (coding-system (and (boundp 'buffer-file-coding-system)
16344 buffer-file-coding-system))
16345 (coding-system-for-write coding-system)
16346 (save-buffer-coding-system coding-system)
16347 (charset (and coding-system
16348 (fboundp 'coding-system-get)
16349 (coding-system-get coding-system 'mime-charset)))
16350 table-open type
16351 table-buffer table-orig-buffer
16352 ind start-is-num starter
16353 rpl path desc descp desc1 desc2 link
16355 (message "Exporting...")
16357 (setq org-last-level 1)
16358 (org-init-section-numbers)
16360 ;; Get the language-dependent settings
16361 (setq lang-words (or (assoc language org-export-language-setup)
16362 (assoc "en" org-export-language-setup)))
16364 ;; Switch to the output buffer
16365 (if (or hidden (not org-export-html-show-new-buffer))
16366 (set-buffer buffer)
16367 (switch-to-buffer-other-window buffer))
16368 (erase-buffer)
16369 (fundamental-mode)
16370 (let ((case-fold-search nil)
16371 (org-odd-levels-only odd))
16372 ;; create local variables for all options, to make sure all called
16373 ;; functions get the correct information
16374 (mapcar (lambda (x)
16375 (set (make-local-variable (cdr x))
16376 (plist-get opt-plist (car x))))
16377 org-export-plist-vars)
16378 (setq umax (if arg (prefix-numeric-value arg)
16379 org-export-headline-levels))
16381 ;; File header
16382 (insert (format
16383 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
16384 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
16385 <html xmlns=\"http://www.w3.org/1999/xhtml\"
16386 lang=\"%s\" xml:lang=\"%s\">
16387 <head>
16388 <title>%s</title>
16389 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
16390 <meta name=\"generator\" content=\"Org-mode\"/>
16391 <meta name=\"generated\" content=\"%s %s\"/>
16392 <meta name=\"author\" content=\"%s\"/>
16394 </head><body>
16396 language language (org-html-expand title) (or charset "iso-8859-1")
16397 date time author style))
16400 (insert (or (plist-get opt-plist :preamble) ""))
16402 (when (plist-get opt-plist :auto-preamble)
16403 (if title (insert (format org-export-html-title-format
16404 (org-html-expand title))))
16405 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
16407 (if org-export-with-toc
16408 (progn
16409 (insert (format "<h%d>%s</h%d>\n"
16410 org-export-html-toplevel-hlevel
16411 (nth 3 lang-words)
16412 org-export-html-toplevel-hlevel))
16413 (insert "<ul>\n<li>")
16414 (setq lines
16415 (mapcar '(lambda (line)
16416 (if (string-match org-todo-line-regexp line)
16417 ;; This is a headline
16418 (progn
16419 (setq level (- (match-end 1) (match-beginning 1))
16420 level (org-tr-level level)
16421 txt (save-match-data
16422 (org-html-expand
16423 (org-export-cleanup-toc-line
16424 (match-string 3 line))))
16425 todo
16426 (or (and org-export-mark-todo-in-toc
16427 (match-beginning 2)
16428 (not (equal (match-string 2 line)
16429 org-done-string)))
16430 ; TODO, not DONE
16431 (and org-export-mark-todo-in-toc
16432 (= level umax)
16433 (org-search-todo-below
16434 line lines level))))
16435 (if (and (memq org-export-with-tags '(not-in-toc nil))
16436 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
16437 (setq txt (replace-match "" t t txt)))
16438 (if (string-match quote-re0 txt)
16439 (setq txt (replace-match "" t t txt)))
16440 (if org-export-with-section-numbers
16441 (setq txt (concat (org-section-number level)
16442 " " txt)))
16443 (if (<= level umax)
16444 (progn
16445 (setq head-count (+ head-count 1))
16446 (if (> level org-last-level)
16447 (progn
16448 (setq cnt (- level org-last-level))
16449 (while (>= (setq cnt (1- cnt)) 0)
16450 (insert "\n<ul>\n<li>"))
16451 (insert "\n")))
16452 (if (< level org-last-level)
16453 (progn
16454 (setq cnt (- org-last-level level))
16455 (while (>= (setq cnt (1- cnt)) 0)
16456 (insert "</li>\n</ul>"))
16457 (insert "\n")))
16458 ;; Check for targets
16459 (while (string-match org-target-regexp line)
16460 (setq tg (match-string 1 line)
16461 line (replace-match
16462 (concat "@<span class=\"target\">" tg "@</span> ")
16463 t t line))
16464 (push (cons (org-solidify-link-text tg)
16465 (format "sec-%d" head-count))
16466 target-alist))
16467 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
16468 (setq txt (replace-match "" t t txt)))
16469 (insert
16470 (format
16471 (if todo
16472 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
16473 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
16474 head-count txt))
16476 (setq org-last-level level))
16478 line)
16479 lines))
16480 (while (> org-last-level 0)
16481 (setq org-last-level (1- org-last-level))
16482 (insert "</li>\n</ul>\n"))
16484 (setq head-count 0)
16485 (org-init-section-numbers)
16487 (while (setq line (pop lines) origline line)
16488 (catch 'nextline
16490 ;; end of quote section?
16491 (when (and inquote (string-match "^\\*+" line))
16492 (insert "</pre>\n")
16493 (setq inquote nil))
16494 ;; inside a quote section?
16495 (when inquote
16496 (insert (org-html-protect line) "\n")
16497 (throw 'nextline nil))
16499 ;; verbatim lines
16500 (when (and org-export-with-fixed-width
16501 (string-match "^[ \t]*:\\(.*\\)" line))
16502 (when (not infixed)
16503 (setq infixed t)
16504 (insert "<pre>\n"))
16505 (insert (org-html-protect (match-string 1 line)) "\n")
16506 (when (and lines
16507 (not (string-match "^[ \t]*\\(:.*\\)"
16508 (car lines))))
16509 (setq infixed nil)
16510 (insert "</pre>\n"))
16511 (throw 'nextline nil))
16514 ;; make targets to anchors
16515 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
16516 (cond
16517 ((match-end 2)
16518 (setq line (replace-match
16519 (concat "@<a name=\""
16520 (org-solidify-link-text (match-string 1 line))
16521 "\">\\nbsp@</a>")
16522 t t line)))
16523 ((and org-export-with-toc (equal (string-to-char line) ?*))
16524 (setq line (replace-match
16525 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
16526 ; (concat "@<i>" (match-string 1 line) "@</i> ")
16527 t t line)))
16529 (setq line (replace-match
16530 (concat "@<a name=\""
16531 (org-solidify-link-text (match-string 1 line))
16532 "\" class=\"target\">" (match-string 1 line) "@</a> ")
16533 t t line)))))
16535 (setq line (org-html-handle-time-stamps line))
16537 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
16538 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
16539 ;; Also handle sub_superscripts and checkboxes
16540 (setq line (org-html-expand line))
16542 ;; Format the links
16543 (setq start 0)
16544 (while (string-match org-bracket-link-analytic-regexp line start)
16545 (setq start (match-beginning 0))
16546 (setq type (if (match-end 2) (match-string 2 line) "internal"))
16547 (setq path (match-string 3 line))
16548 (setq desc1 (if (match-end 5) (match-string 5 line))
16549 desc2 (if (match-end 2) (concat type ":" path) path)
16550 descp (and desc1 (not (equal desc1 desc2)))
16551 desc (or desc1 desc2))
16552 ;; Make an image out of the description if that is so wanted
16553 (when (and descp (org-file-image-p desc))
16554 (save-match-data
16555 (if (string-match "^file:" desc)
16556 (setq desc (substring desc (match-end 0)))))
16557 (setq desc (concat "<img src=\"" desc "\"/>")))
16558 ;; FIXME: do we need to unescape here somewhere?
16559 (cond
16560 ((equal type "internal")
16561 (setq rpl
16562 (concat
16563 "<a href=\"#"
16564 (org-solidify-link-text path target-alist)
16565 "\">" desc "</a>")))
16566 ((member type '("http" "https")) ; FIXME: need to test this.
16567 ;; standard URL, just check if we need to inline an image
16568 (if (and (or (eq t org-export-html-inline-images)
16569 (and org-export-html-inline-images (not descp)))
16570 (org-file-image-p path))
16571 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
16572 (setq link (concat type ":" path))
16573 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
16574 ((member type '("ftp" "mailto" "news"))
16575 ;; standard URL
16576 (setq link (concat type ":" path))
16577 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
16578 ((string= type "file")
16579 ;; FILE link
16580 (let* ((filename path)
16581 (abs-p (file-name-absolute-p filename))
16582 thefile file-is-image-p search)
16583 (save-match-data
16584 (if (string-match "::\\(.*\\)" filename)
16585 (setq search (match-string 1 filename)
16586 filename (replace-match "" t nil filename)))
16587 (setq valid
16588 (if (functionp link-validate)
16589 (funcall link-validate filename current-dir)
16591 (setq file-is-image-p (org-file-image-p filename))
16592 (setq thefile (if abs-p (expand-file-name filename) filename))
16593 (when (and org-export-html-link-org-files-as-html
16594 (string-match "\\.org$" thefile))
16595 (setq thefile (concat (substring thefile 0
16596 (match-beginning 0))
16597 ".html"))
16598 (if (and search
16599 ;; make sure this is can be used as target search
16600 (not (string-match "^[0-9]*$" search))
16601 (not (string-match "^\\*" search))
16602 (not (string-match "^/.*/$" search)))
16603 (setq thefile (concat thefile "#"
16604 (org-solidify-link-text
16605 (org-link-unescape search)))))
16606 (when (string-match "^file:" desc)
16607 (setq desc (replace-match "" t t desc))
16608 (if (string-match "\\.org$" desc)
16609 (setq desc (replace-match "" t t desc))))))
16610 (setq rpl (if (and file-is-image-p
16611 (or (eq t org-export-html-inline-images)
16612 (and org-export-html-inline-images
16613 (not descp))))
16614 (concat "<img src=\"" thefile "\"/>")
16615 (concat "<a href=\"" thefile "\">" desc "</a>")))
16616 (if (not valid) (setq rpl desc))))
16617 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
16618 (setq rpl (concat "<i>&lt;" type ":"
16619 (save-match-data (org-link-unescape path))
16620 "&gt;</i>"))))
16621 (setq line (replace-match rpl t t line)
16622 start (+ start (length rpl))))
16623 ;; TODO items
16624 (if (and (string-match org-todo-line-regexp line)
16625 (match-beginning 2))
16626 (if (equal (match-string 2 line) org-done-string)
16627 (setq line (replace-match
16628 "<span class=\"done\">\\2</span>"
16629 t nil line 2))
16630 (setq line (replace-match "<span class=\"todo\">\\2</span>"
16631 t nil line 2))))
16633 (cond
16634 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
16635 ;; This is a headline
16636 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
16637 txt (match-string 2 line))
16638 (if (string-match quote-re0 txt)
16639 (setq txt (replace-match "" t t txt)))
16640 (if (<= level umax) (setq head-count (+ head-count 1)))
16641 (when in-local-list
16642 ;; Close any local lists before inserting a new header line
16643 (while local-list-num
16644 (org-close-li)
16645 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
16646 (pop local-list-num))
16647 (setq local-list-indent nil
16648 in-local-list nil))
16649 (org-html-level-start level txt umax
16650 (and org-export-with-toc (<= level umax))
16651 head-count)
16652 ;; QUOTES
16653 (when (string-match quote-re line)
16654 (insert "<pre>")
16655 (setq inquote t)))
16657 ((and org-export-with-tables
16658 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
16659 (if (not table-open)
16660 ;; New table starts
16661 (setq table-open t table-buffer nil table-orig-buffer nil))
16662 ;; Accumulate lines
16663 (setq table-buffer (cons line table-buffer)
16664 table-orig-buffer (cons origline table-orig-buffer))
16665 (when (or (not lines)
16666 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
16667 (car lines))))
16668 (setq table-open nil
16669 table-buffer (nreverse table-buffer)
16670 table-orig-buffer (nreverse table-orig-buffer))
16671 (org-close-par-maybe)
16672 (insert (org-format-table-html table-buffer table-orig-buffer))))
16674 ;; Normal lines
16675 (when (string-match
16676 (cond
16677 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
16678 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
16679 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
16680 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
16681 line)
16682 (setq ind (org-get-string-indentation line)
16683 start-is-num (match-beginning 4)
16684 starter (if (match-beginning 2)
16685 (substring (match-string 2 line) 0 -1))
16686 line (substring line (match-beginning 5)))
16687 (unless (string-match "[^ \t]" line)
16688 ;; empty line. Pretend indentation is large.
16689 (setq ind (1+ (or (car local-list-indent) 1))))
16690 (while (and in-local-list
16691 (or (and (= ind (car local-list-indent))
16692 (not starter))
16693 (< ind (car local-list-indent))))
16694 (org-close-li)
16695 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
16696 (pop local-list-num) (pop local-list-indent)
16697 (setq in-local-list local-list-indent))
16698 (cond
16699 ((and starter
16700 (or (not in-local-list)
16701 (> ind (car local-list-indent))))
16702 ;; Start new (level of ) list
16703 (org-close-par-maybe)
16704 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
16705 (push start-is-num local-list-num)
16706 (push ind local-list-indent)
16707 (setq in-local-list t))
16708 (starter
16709 ;; continue current list
16710 (org-close-li)
16711 (insert "<li>\n")))
16712 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
16713 (setq line
16714 (replace-match
16715 (if (equal (match-string 1 line) "X")
16716 "<b>[X]</b>"
16717 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
16718 t t line))))
16720 ;; Empty lines start a new paragraph. If hand-formatted lists
16721 ;; are not fully interpreted, lines starting with "-", "+", "*"
16722 ;; also start a new paragraph.
16723 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
16725 ;; Check if the line break needs to be conserved
16726 (cond
16727 ((string-match "\\\\\\\\[ \t]*$" line)
16728 (setq line (replace-match "<br/>" t t line)))
16729 (org-export-preserve-breaks
16730 (setq line (concat line "<br/>"))))
16732 (insert line "\n")))))
16734 ;; Properly close all local lists and other lists
16735 (when inquote (insert "</pre>\n"))
16736 (when in-local-list
16737 ;; Close any local lists before inserting a new header line
16738 (while local-list-num
16739 (org-close-li)
16740 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
16741 (pop local-list-num))
16742 (setq local-list-indent nil
16743 in-local-list nil))
16744 (org-html-level-start 1 nil umax
16745 (and org-export-with-toc (<= level umax))
16746 head-count)
16748 (when (plist-get opt-plist :auto-postamble)
16749 (when author
16750 (insert "<p class=\"author\"> "
16751 (nth 1 lang-words) ": " author "\n")
16752 (when email
16753 (insert "<a href=\"mailto:" email "\">&lt;"
16754 email "&gt;</a>\n"))
16755 (insert "</p>\n"))
16756 (when (and date time)
16757 (insert "<p class=\"date\"> "
16758 (nth 2 lang-words) ": "
16759 date " " time "</p>\n")))
16761 (if org-export-html-with-timestamp
16762 (insert org-export-html-html-helper-timestamp))
16763 (insert (or (plist-get opt-plist :postamble) ""))
16764 (insert "</body>\n</html>\n")
16765 (normal-mode)
16766 ;; remove empty paragraphs and lists
16767 (goto-char (point-min))
16768 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
16769 (replace-match ""))
16770 (goto-char (point-min))
16771 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
16772 (replace-match ""))
16773 (save-buffer)
16774 (goto-char (point-min))
16775 (message "Exporting... done"))))
16778 (defun org-format-table-html (lines olines)
16779 "Find out which HTML converter to use and return the HTML code."
16780 (if (string-match "^[ \t]*|" (car lines))
16781 ;; A normal org table
16782 (org-format-org-table-html lines)
16783 ;; Table made by table.el - test for spanning
16784 (let* ((hlines (delq nil (mapcar
16785 (lambda (x)
16786 (if (string-match "^[ \t]*\\+-" x) x
16787 nil))
16788 lines)))
16789 (first (car hlines))
16790 (ll (and (string-match "\\S-+" first)
16791 (match-string 0 first)))
16792 (re (concat "^[ \t]*" (regexp-quote ll)))
16793 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
16794 hlines))))
16795 (if (and (not spanning)
16796 (not org-export-prefer-native-exporter-for-tables))
16797 ;; We can use my own converter with HTML conversions
16798 (org-format-table-table-html lines)
16799 ;; Need to use the code generator in table.el, with the original text.
16800 (org-format-table-table-html-using-table-generate-source olines)))))
16802 (defun org-format-org-table-html (lines)
16803 "Format a table into HTML."
16804 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
16805 (setq lines (nreverse lines))
16806 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
16807 (setq lines (nreverse lines))
16808 (when org-export-table-remove-special-lines
16809 ;; Check if the table has a marking column. If yes remove the
16810 ;; column and the special lines
16811 (let* ((special
16812 (not
16813 (memq nil
16814 (mapcar
16815 (lambda (x)
16816 (or (string-match "^[ \t]*|-" x)
16817 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
16818 lines)))))
16819 (if special
16820 (setq lines
16821 (delq nil
16822 (mapcar
16823 (lambda (x)
16824 (if (string-match "^[ \t]*| *[!_^] *|" x)
16825 nil ; ignore this line
16826 (and (or (string-match "^[ \t]*|-+\\+" x)
16827 (string-match "^[ \t]*|[^|]*|" x))
16828 (replace-match "|" t t x))))
16829 lines))))))
16831 (let ((head (and org-export-highlight-first-table-line
16832 (delq nil (mapcar
16833 (lambda (x) (string-match "^[ \t]*|-" x))
16834 (cdr lines)))))
16835 line fields html)
16836 (setq html (concat org-export-html-table-tag "\n"))
16837 (while (setq line (pop lines))
16838 (catch 'next-line
16839 (if (string-match "^[ \t]*|-" line)
16840 (progn
16841 (setq head nil) ;; head ends here, first time around
16842 ;; ignore this line
16843 (throw 'next-line t)))
16844 ;; Break the line into fields
16845 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
16846 (setq html (concat
16847 html
16848 "<tr>"
16849 (mapconcat (lambda (x)
16850 (if head
16851 (concat "<th>" x "</th>")
16852 (concat "<td>" x "</td>")))
16853 fields "")
16854 "</tr>\n"))))
16855 (setq html (concat html "</table>\n"))
16856 html))
16858 (defun org-fake-empty-table-line (line)
16859 "Replace everything except \"|\" with spaces."
16860 (let ((i (length line))
16861 (newstr (copy-sequence line)))
16862 (while (> i 0)
16863 (setq i (1- i))
16864 (if (not (eq (aref newstr i) ?|))
16865 (aset newstr i ?\ )))
16866 newstr))
16868 (defun org-format-table-table-html (lines)
16869 "Format a table generated by table.el into HTML.
16870 This conversion does *not* use `table-generate-source' from table.el.
16871 This has the advantage that Org-mode's HTML conversions can be used.
16872 But it has the disadvantage, that no cell- or row-spanning is allowed."
16873 (let (line field-buffer
16874 (head org-export-highlight-first-table-line)
16875 fields html empty)
16876 (setq html (concat org-export-html-table-tag "\n"))
16877 (while (setq line (pop lines))
16878 (setq empty "&nbsp;")
16879 (catch 'next-line
16880 (if (string-match "^[ \t]*\\+-" line)
16881 (progn
16882 (if field-buffer
16883 (progn
16884 (setq html (concat
16885 html
16886 "<tr>"
16887 (mapconcat
16888 (lambda (x)
16889 (if (equal x "") (setq x empty))
16890 (if head
16891 (concat "<th>" x "</th>\n")
16892 (concat "<td>" x "</td>\n")))
16893 field-buffer "\n")
16894 "</tr>\n"))
16895 (setq head nil)
16896 (setq field-buffer nil)))
16897 ;; Ignore this line
16898 (throw 'next-line t)))
16899 ;; Break the line into fields and store the fields
16900 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
16901 (if field-buffer
16902 (setq field-buffer (mapcar
16903 (lambda (x)
16904 (concat x "<br/>" (pop fields)))
16905 field-buffer))
16906 (setq field-buffer fields))))
16907 (setq html (concat html "</table>\n"))
16908 html))
16910 (defun org-format-table-table-html-using-table-generate-source (lines)
16911 "Format a table into html, using `table-generate-source' from table.el.
16912 This has the advantage that cell- or row-spanning is allowed.
16913 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
16914 (require 'table)
16915 (with-current-buffer (get-buffer-create " org-tmp1 ")
16916 (erase-buffer)
16917 (insert (mapconcat 'identity lines "\n"))
16918 (goto-char (point-min))
16919 (if (not (re-search-forward "|[^+]" nil t))
16920 (error "Error processing table"))
16921 (table-recognize-table)
16922 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
16923 (table-generate-source 'html " org-tmp2 ")
16924 (set-buffer " org-tmp2 ")
16925 (buffer-substring (point-min) (point-max))))
16927 (defun org-html-handle-time-stamps (s)
16928 "Format time stamps in string S, or remove them."
16929 (catch 'exit
16930 (let (r b)
16931 (while (string-match org-maybe-keyword-time-regexp s)
16932 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
16933 ;; never export CLOCK
16934 (throw 'exit ""))
16935 (or b (setq b (substring s 0 (match-beginning 0))))
16936 (if (not org-export-with-timestamps)
16937 (setq r (concat r (substring s 0 (match-beginning 0)))
16938 s (substring s (match-end 0)))
16939 (setq r (concat
16940 r (substring s 0 (match-beginning 0))
16941 (if (match-end 1)
16942 (format "@<span class=\"timestamp-kwd\">%s @</span>"
16943 (match-string 1 s)))
16944 (format " @<span class=\"timestamp\">%s@</span>"
16945 (substring
16946 (org-translate-time (match-string 3 s)) 1 -1)))
16947 s (substring s (match-end 0)))))
16948 ;; Line break if line started and ended with time stamp stuff
16949 (if (not r)
16951 (setq r (concat r s))
16952 (unless (string-match "\\S-" (concat b s))
16953 (setq r (concat r "@<br/>")))
16954 r))))
16956 (defun org-html-protect (s)
16957 ;; convert & to &amp;, < to &lt; and > to &gt;
16958 (let ((start 0))
16959 (while (string-match "&" s start)
16960 (setq s (replace-match "&amp;" t t s)
16961 start (1+ (match-beginning 0))))
16962 (while (string-match "<" s)
16963 (setq s (replace-match "&lt;" t t s)))
16964 (while (string-match ">" s)
16965 (setq s (replace-match "&gt;" t t s))))
16968 (defun org-export-cleanup-toc-line (s)
16969 "Remove tags and time staps from lines going into the toc."
16970 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
16971 (setq s (replace-match "" t t s)))
16972 (when org-export-remove-timestamps-from-toc
16973 (while (string-match org-maybe-keyword-time-regexp s)
16974 (setq s (replace-match "" t t s))))
16977 (defun org-html-expand (string)
16978 "Prepare STRING for HTML export. Applies all active conversions.
16979 If there are links in the string, don't modify these."
16980 (let* (m s l res)
16981 (while (setq m (string-match org-bracket-link-regexp string))
16982 (setq s (substring string 0 m)
16983 l (match-string 0 string)
16984 string (substring string (match-end 0)))
16985 (push (org-html-do-expand s) res)
16986 (push l res))
16987 (push (org-html-do-expand string) res)
16988 (apply 'concat (nreverse res))))
16990 (defun org-html-do-expand (s)
16991 "Apply all active conversions to translate special ASCII to HTML."
16992 (setq s (org-html-protect s))
16993 (if org-export-html-expand
16994 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
16995 (setq s (replace-match "<\\1>" t nil s))))
16996 (if org-export-with-emphasize
16997 (setq s (org-export-html-convert-emphasize s)))
16998 (if org-export-with-sub-superscripts
16999 (setq s (org-export-html-convert-sub-super s)))
17000 (if org-export-with-TeX-macros
17001 (let ((start 0) wd ass)
17002 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
17003 (setq wd (match-string 1 s))
17004 (if (setq ass (assoc wd org-html-entities))
17005 (setq s (replace-match (or (cdr ass)
17006 (concat "&" (car ass) ";"))
17007 t t s))
17008 (setq start (+ start (length wd)))))))
17011 (defun org-create-multibrace-regexp (left right n)
17012 "Create a regular expression which will match a balanced sexp.
17013 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
17014 as single character strings.
17015 The regexp returned will match the entire expression including the
17016 delimiters. It will also define a single group which contains the
17017 match except for the outermost delimiters. The maximum depth of
17018 stacked delimiters is N. Escaping delimiters is not possible."
17019 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
17020 (or "\\|")
17021 (re nothing)
17022 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
17023 (while (> n 1)
17024 (setq n (1- n)
17025 re (concat re or next)
17026 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
17027 (concat left "\\(" re "\\)" right)))
17029 (defvar org-match-substring-regexp
17030 (concat
17031 "\\([^\\]\\)\\([_^]\\)\\("
17032 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
17033 "\\|"
17034 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
17035 "\\|"
17036 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
17037 "The regular expression matching a sub- or superscript.")
17039 (defun org-export-html-convert-sub-super (string)
17040 "Convert sub- and superscripts in STRING to HTML."
17041 (let (key c)
17042 (while (string-match org-match-substring-regexp string)
17043 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
17044 (setq c (or (match-string 8 string)
17045 (match-string 6 string)
17046 (match-string 5 string)))
17047 (setq string (replace-match
17048 (concat (match-string 1 string)
17049 "<" key ">" c "</" key ">")
17050 t t string)))
17051 (while (string-match "\\\\\\([_^]\\)" string)
17052 (setq string (replace-match (match-string 1 string) t t string))))
17053 string)
17055 (defun org-export-html-convert-emphasize (string)
17056 "Apply emphasis."
17057 (while (string-match org-emph-re string)
17058 (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)))
17059 string)
17061 (defvar org-par-open nil)
17062 (defun org-open-par ()
17063 "Insert <p>, but first close previous paragraph if any."
17064 (org-close-par-maybe)
17065 (insert "\n<p>")
17066 (setq org-par-open t))
17067 (defun org-close-par-maybe ()
17068 "Close paragraph if there is one open."
17069 (when org-par-open
17070 (insert "</p>")
17071 (setq org-par-open nil)))
17072 (defun org-close-li ()
17073 "Close <li> if necessary."
17074 (org-close-par-maybe)
17075 (insert "</li>\n"))
17076 ; (when (save-excursion
17077 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
17078 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
17079 ; (insert "</li>"))))
17081 (defun org-html-level-start (level title umax with-toc head-count)
17082 "Insert a new level in HTML export.
17083 When TITLE is nil, just close all open levels."
17084 (org-close-par-maybe)
17085 (let ((l (1+ (max level umax))))
17086 (while (<= l org-level-max)
17087 (if (aref org-levels-open (1- l))
17088 (progn
17089 (org-html-level-close l)
17090 (aset org-levels-open (1- l) nil)))
17091 (setq l (1+ l)))
17092 (when title
17093 ;; If title is nil, this means this function is called to close
17094 ;; all levels, so the rest is done only if title is given
17095 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
17096 (setq title (replace-match
17097 (if org-export-with-tags
17098 (save-match-data
17099 (concat
17100 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
17101 (mapconcat 'identity (org-split-string
17102 (match-string 1 title) ":")
17103 "&nbsp;")
17104 "</span>"))
17106 t t title)))
17107 (if (> level umax)
17108 (progn
17109 (if (aref org-levels-open (1- level))
17110 (progn
17111 (org-close-li)
17112 (insert "<li>" title "<br/>\n"))
17113 (aset org-levels-open (1- level) t)
17114 (org-close-par-maybe)
17115 (insert "<ul>\n<li>" title "<br/>\n")))
17116 (if org-export-with-section-numbers
17117 (setq title (concat (org-section-number level) " " title)))
17118 (setq level (+ level org-export-html-toplevel-hlevel -1))
17119 (if with-toc
17120 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
17121 level head-count title level))
17122 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
17123 (org-open-par)))))
17125 (defun org-html-level-close (&rest args)
17126 "Terminate one level in HTML export."
17127 (org-close-li)
17128 (insert "</ul>"))
17130 ;;; iCalendar export
17132 ;;;###autoload
17133 (defun org-export-icalendar-this-file ()
17134 "Export current file as an iCalendar file.
17135 The iCalendar file will be located in the same directory as the Org-mode
17136 file, but with extension `.ics'."
17137 (interactive)
17138 (org-export-icalendar nil buffer-file-name))
17140 ;;;###autoload
17141 (defun org-export-icalendar-all-agenda-files ()
17142 "Export all files in `org-agenda-files' to iCalendar .ics files.
17143 Each iCalendar file will be located in the same directory as the Org-mode
17144 file, but with extension `.ics'."
17145 (interactive)
17146 (apply 'org-export-icalendar nil (org-agenda-files t)))
17148 ;;;###autoload
17149 (defun org-export-icalendar-combine-agenda-files ()
17150 "Export all files in `org-agenda-files' to a single combined iCalendar file.
17151 The file is stored under the name `org-combined-agenda-icalendar-file'."
17152 (interactive)
17153 (apply 'org-export-icalendar t (org-agenda-files t)))
17155 (defun org-export-icalendar (combine &rest files)
17156 "Create iCalendar files for all elements of FILES.
17157 If COMBINE is non-nil, combine all calendar entries into a single large
17158 file and store it under the name `org-combined-agenda-icalendar-file'."
17159 (save-excursion
17160 (let* ((dir (org-export-directory
17161 :ical (list :publishing-directory
17162 org-export-publishing-directory)))
17163 file ical-file ical-buffer category started org-agenda-new-buffers)
17165 (when combine
17166 (setq ical-file
17167 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
17168 org-combined-agenda-icalendar-file
17169 (expand-file-name org-combined-agenda-icalendar-file dir))
17170 ical-buffer (org-get-agenda-file-buffer ical-file))
17171 (set-buffer ical-buffer) (erase-buffer))
17172 (while (setq file (pop files))
17173 (catch 'nextfile
17174 (org-check-agenda-file file)
17175 (set-buffer (org-get-agenda-file-buffer file))
17176 (unless combine
17177 (setq ical-file (concat (file-name-as-directory dir)
17178 (file-name-sans-extension
17179 (file-name-nondirectory buffer-file-name))
17180 ".ics"))
17181 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
17182 (with-current-buffer ical-buffer (erase-buffer)))
17183 (setq category (or org-category
17184 (file-name-sans-extension
17185 (file-name-nondirectory buffer-file-name))))
17186 (if (symbolp category) (setq category (symbol-name category)))
17187 (let ((standard-output ical-buffer))
17188 (if combine
17189 (and (not started) (setq started t)
17190 (org-start-icalendar-file org-icalendar-combined-name))
17191 (org-start-icalendar-file category))
17192 (org-print-icalendar-entries combine)
17193 (when (or (and combine (not files)) (not combine))
17194 (org-finish-icalendar-file)
17195 (set-buffer ical-buffer)
17196 (save-buffer)
17197 (run-hooks 'org-after-save-iCalendar-file-hook)))))
17198 (org-release-buffers org-agenda-new-buffers))))
17200 (defvar org-after-save-iCalendar-file-hook nil
17201 "Hook run after an iCalendar file has been saved.
17202 The iCalendar buffer is still current when this hook is run.
17203 A good way to use this is to tell a desktop calenndar application to re-read
17204 the iCalendar file.")
17206 (defun org-print-icalendar-entries (&optional combine)
17207 "Print iCalendar entries for the current Org-mode file to `standard-output'.
17208 When COMBINE is non nil, add the category to each line."
17209 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
17210 (org-category-table (org-get-category-table))
17211 (dts (org-ical-ts-to-string
17212 (format-time-string (cdr org-time-stamp-formats) (current-time))
17213 "DTSTART"))
17214 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri category)
17215 (save-excursion
17216 (goto-char (point-min))
17217 (while (re-search-forward org-ts-regexp nil t)
17218 (setq pos (match-beginning 0)
17219 ts (match-string 0)
17220 inc t
17221 hd (org-get-heading)
17222 category (org-get-category))
17223 (if (looking-at re2)
17224 (progn
17225 (goto-char (match-end 0))
17226 (setq ts2 (match-string 1) inc nil))
17227 (setq ts2 ts
17228 tmp (buffer-substring (max (point-min)
17229 (- pos org-ds-keyword-length))
17230 pos)
17231 deadlinep (string-match org-deadline-regexp tmp)
17232 scheduledp (string-match org-scheduled-regexp tmp)
17233 ;; donep (org-entry-is-done-p)
17235 (if (or (string-match org-tr-regexp hd)
17236 (string-match org-ts-regexp hd))
17237 (setq hd (replace-match "" t t hd)))
17238 (if (string-match org-bracket-link-regexp hd)
17239 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
17240 (match-string 1 hd))
17241 t t hd)))
17242 (if deadlinep (setq hd (concat "DL: " hd)))
17243 (if scheduledp (setq hd (concat "S: " hd)))
17244 (princ (format "BEGIN:VEVENT
17247 SUMMARY:%s
17248 CATEGORIES:%s
17249 END:VEVENT\n"
17250 (org-ical-ts-to-string ts "DTSTART")
17251 (org-ical-ts-to-string ts2 "DTEND" inc)
17252 hd category)))
17253 (when org-icalendar-include-todo
17254 (goto-char (point-min))
17255 (while (re-search-forward org-todo-line-regexp nil t)
17256 (setq state (match-string 1))
17257 (unless (equal state org-done-string)
17258 (setq hd (match-string 3))
17259 (if (string-match org-priority-regexp hd)
17260 (setq pri (string-to-char (match-string 2 hd))
17261 hd (concat (substring hd 0 (match-beginning 1))
17262 (substring hd (- (match-end 1)))))
17263 (setq pri org-default-priority))
17264 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
17265 (- org-lowest-priority ?A))))))
17267 (princ (format "BEGIN:VTODO
17269 SUMMARY:%s
17270 CATEGORIES:%s
17271 SEQUENCE:1
17272 PRIORITY:%d
17273 END:VTODO\n"
17274 dts hd category pri))))))))
17276 (defun org-start-icalendar-file (name)
17277 "Start an iCalendar file by inserting the header."
17278 (let ((user user-full-name)
17279 (name (or name "unknown"))
17280 (timezone (cadr (current-time-zone))))
17281 (princ
17282 (format "BEGIN:VCALENDAR
17283 VERSION:2.0
17284 X-WR-CALNAME:%s
17285 PRODID:-//%s//Emacs with Org-mode//EN
17286 X-WR-TIMEZONE:%s
17287 CALSCALE:GREGORIAN\n" name user timezone))))
17289 (defun org-finish-icalendar-file ()
17290 "Finish an iCalendar file by inserting the END statement."
17291 (princ "END:VCALENDAR\n"))
17293 (defun org-ical-ts-to-string (s keyword &optional inc)
17294 "Take a time string S and convert it to iCalendar format.
17295 KEYWORD is added in front, to make a complete line like DTSTART....
17296 When INC is non-nil, increase the hour by two (if time string contains
17297 a time), or the day by one (if it does not contain a time)."
17298 (let ((t1 (org-parse-time-string s 'nodefault))
17299 t2 fmt have-time time)
17300 (if (and (car t1) (nth 1 t1) (nth 2 t1))
17301 (setq t2 t1 have-time t)
17302 (setq t2 (org-parse-time-string s)))
17303 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
17304 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
17305 (when inc
17306 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
17307 (setq time (encode-time s mi h d m y)))
17308 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
17309 (concat keyword (format-time-string fmt time))))
17311 ;;; XOXO export
17313 (defun org-export-as-xoxo-insert-into (buffer &rest output)
17314 (with-current-buffer buffer
17315 (apply 'insert output)))
17316 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
17318 (defun org-export-as-xoxo (&optional buffer)
17319 "Export the org buffer as XOXO.
17320 The XOXO buffer is named *xoxo-<source buffer name>*"
17321 (interactive (list (current-buffer)))
17322 ;; A quickie abstraction
17324 ;; Output everything as XOXO
17325 (with-current-buffer (get-buffer buffer)
17326 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
17327 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17328 (org-infile-export-plist)))
17329 (filename (concat (file-name-as-directory
17330 (org-export-directory :xoxo opt-plist))
17331 (file-name-sans-extension
17332 (file-name-nondirectory buffer-file-name))
17333 ".html"))
17334 (out (find-file-noselect filename))
17335 (last-level 1)
17336 (hanging-li nil))
17337 ;; Check the output buffer is empty.
17338 (with-current-buffer out (erase-buffer))
17339 ;; Kick off the output
17340 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
17341 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
17342 (let* ((hd (match-string-no-properties 1))
17343 (level (length hd))
17344 (text (concat
17345 (match-string-no-properties 2)
17346 (save-excursion
17347 (goto-char (match-end 0))
17348 (let ((str ""))
17349 (catch 'loop
17350 (while 't
17351 (forward-line)
17352 (if (looking-at "^[ \t]\\(.*\\)")
17353 (setq str (concat str (match-string-no-properties 1)))
17354 (throw 'loop str)))))))))
17356 ;; Handle level rendering
17357 (cond
17358 ((> level last-level)
17359 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
17361 ((< level last-level)
17362 (dotimes (- (- last-level level) 1)
17363 (if hanging-li
17364 (org-export-as-xoxo-insert-into out "</li>\n"))
17365 (org-export-as-xoxo-insert-into out "</ol>\n"))
17366 (when hanging-li
17367 (org-export-as-xoxo-insert-into out "</li>\n")
17368 (setq hanging-li nil)))
17370 ((equal level last-level)
17371 (if hanging-li
17372 (org-export-as-xoxo-insert-into out "</li>\n")))
17375 (setq last-level level)
17377 ;; And output the new li
17378 (setq hanging-li 't)
17379 (if (equal ?+ (elt text 0))
17380 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
17381 (org-export-as-xoxo-insert-into out "<li>" text))))
17383 ;; Finally finish off the ol
17384 (dotimes (- last-level 1)
17385 (if hanging-li
17386 (org-export-as-xoxo-insert-into out "</li>\n"))
17387 (org-export-as-xoxo-insert-into out "</ol>\n"))
17389 ;; Finish the buffer off and clean it up.
17390 (switch-to-buffer-other-window out)
17391 (indent-region (point-min) (point-max) nil)
17392 (save-buffer)
17393 (goto-char (point-min))
17397 ;;;; Key bindings
17399 ;; - Bindings in Org-mode map are currently
17400 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
17401 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
17402 ;; e (?) useful from outline-mode
17403 ;; i k @ expendable from outline-mode
17404 ;; 0123456789 % & ()_{} " ` free
17406 ;; Make `C-c C-x' a prefix key
17407 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
17409 ;; TAB key with modifiers
17410 (define-key org-mode-map "\C-i" 'org-cycle)
17411 (define-key org-mode-map [(tab)] 'org-cycle)
17412 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
17413 (define-key org-mode-map [(meta tab)] 'org-complete)
17414 (define-key org-mode-map "\M-\t" 'org-complete)
17415 (define-key org-mode-map "\M-\C-i" 'org-complete)
17416 ;; The following line is necessary under Suse GNU/Linux
17417 (unless (featurep 'xemacs)
17418 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
17419 (define-key org-mode-map [(shift tab)] 'org-shifttab)
17421 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
17422 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17423 (define-key org-mode-map [(meta return)] 'org-meta-return)
17425 ;; Cursor keys with modifiers
17426 (define-key org-mode-map [(meta left)] 'org-metaleft)
17427 (define-key org-mode-map [(meta right)] 'org-metaright)
17428 (define-key org-mode-map [(meta up)] 'org-metaup)
17429 (define-key org-mode-map [(meta down)] 'org-metadown)
17431 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17432 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
17433 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
17434 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
17436 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
17437 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
17438 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
17439 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
17441 ;;; Extra keys for tty access.
17442 ;; We only set them when really needed because otherwise the
17443 ;; menus don't show the simple keys
17445 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17446 (not window-system))
17447 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17448 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17449 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return)
17450 (define-key org-mode-map [?\e (return)] 'org-meta-return)
17451 (define-key org-mode-map [?\e (left)] 'org-metaleft)
17452 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft)
17453 (define-key org-mode-map [?\e (right)] 'org-metaright)
17454 (define-key org-mode-map "\C-c\C-xr" 'org-metaright)
17455 (define-key org-mode-map [?\e (up)] 'org-metaup)
17456 (define-key org-mode-map "\C-c\C-xu" 'org-metaup)
17457 (define-key org-mode-map [?\e (down)] 'org-metadown)
17458 (define-key org-mode-map "\C-c\C-xd" 'org-metadown)
17459 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17460 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17461 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17462 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17463 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
17464 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
17465 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
17466 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright))
17468 ;; All the other keys
17470 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17471 (define-key org-mode-map "\C-c\C-r" 'org-reveal)
17472 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
17473 (define-key org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
17474 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
17475 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
17476 (define-key org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
17477 (define-key org-mode-map "\C-c\C-j" 'org-goto)
17478 (define-key org-mode-map "\C-c\C-t" 'org-todo)
17479 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
17480 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
17481 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
17482 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
17483 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
17484 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
17485 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
17486 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
17487 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
17488 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
17489 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
17490 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
17491 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
17492 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
17493 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
17494 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
17495 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
17496 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
17497 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
17498 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
17499 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
17500 (define-key org-mode-map [(control ?\')] 'org-cycle-agenda-files)
17501 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
17502 (define-key org-mode-map "\C-c]" 'org-remove-file)
17503 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
17504 (define-key org-mode-map "\C-c^" 'org-sort)
17505 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
17506 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
17507 (define-key org-mode-map "\C-m" 'org-return)
17508 (define-key org-mode-map "\C-c?" 'org-table-field-info)
17509 (define-key org-mode-map "\C-c " 'org-table-blank-field)
17510 (define-key org-mode-map "\C-c+" 'org-table-sum)
17511 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
17512 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
17513 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
17514 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
17515 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
17516 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
17517 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
17518 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
17519 (define-key org-mode-map "\C-c\C-e" 'org-export)
17520 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
17522 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
17523 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
17524 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
17525 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
17527 (define-key org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
17528 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
17529 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
17530 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
17531 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
17532 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
17533 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
17534 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
17535 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
17537 (when (featurep 'xemacs)
17538 (define-key org-mode-map 'button3 'popup-mode-menu))
17540 (defsubst org-table-p () (org-at-table-p))
17542 (defun org-self-insert-command (N)
17543 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
17544 If the cursor is in a table looking at whitespace, the whitespace is
17545 overwritten, and the table is not marked as requiring realignment."
17546 (interactive "p")
17547 (if (and (org-table-p)
17548 (progn
17549 ;; check if we blank the field, and if that triggers align
17550 (and org-table-auto-blank-field
17551 (member last-command
17552 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
17553 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
17554 ;; got extra space, this field does not determine column width
17555 (let (org-table-may-need-update) (org-table-blank-field))
17556 ;; no extra space, this field may determine column width
17557 (org-table-blank-field)))
17559 (eq N 1)
17560 (looking-at "[^|\n]* |"))
17561 (let (org-table-may-need-update)
17562 (goto-char (1- (match-end 0)))
17563 (delete-backward-char 1)
17564 (goto-char (match-beginning 0))
17565 (self-insert-command N))
17566 (setq org-table-may-need-update t)
17567 (self-insert-command N)))
17569 (defun org-delete-backward-char (N)
17570 "Like `delete-backward-char', insert whitespace at field end in tables.
17571 When deleting backwards, in tables this function will insert whitespace in
17572 front of the next \"|\" separator, to keep the table aligned. The table will
17573 still be marked for re-alignment if the field did fill the entire column,
17574 because, in this case the deletion might narrow the column."
17575 (interactive "p")
17576 (if (and (org-table-p)
17577 (eq N 1)
17578 (string-match "|" (buffer-substring (point-at-bol) (point)))
17579 (looking-at ".*?|"))
17580 (let ((pos (point))
17581 (noalign (looking-at "[^|\n\r]* |"))
17582 (c org-table-may-need-update))
17583 (backward-delete-char N)
17584 (skip-chars-forward "^|")
17585 (insert " ")
17586 (goto-char (1- pos))
17587 ;; noalign: if there were two spaces at the end, this field
17588 ;; does not determine the width of the column.
17589 (if noalign (setq org-table-may-need-update c)))
17590 (backward-delete-char N)))
17592 (defun org-delete-char (N)
17593 "Like `delete-char', but insert whitespace at field end in tables.
17594 When deleting characters, in tables this function will insert whitespace in
17595 front of the next \"|\" separator, to keep the table aligned. The table will
17596 still be marked for re-alignment if the field did fill the entire column,
17597 because, in this case the deletion might narrow the column."
17598 (interactive "p")
17599 (if (and (org-table-p)
17600 (not (bolp))
17601 (not (= (char-after) ?|))
17602 (eq N 1))
17603 (if (looking-at ".*?|")
17604 (let ((pos (point))
17605 (noalign (looking-at "[^|\n\r]* |"))
17606 (c org-table-may-need-update))
17607 (replace-match (concat
17608 (substring (match-string 0) 1 -1)
17609 " |"))
17610 (goto-char pos)
17611 ;; noalign: if there were two spaces at the end, this field
17612 ;; does not determine the width of the column.
17613 (if noalign (setq org-table-may-need-update c)))
17614 (delete-char N))
17615 (delete-char N)))
17617 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
17618 (put 'org-self-insert-command 'delete-selection t)
17619 (put 'orgtbl-self-insert-command 'delete-selection t)
17620 (put 'org-delete-char 'delete-selection 'supersede)
17621 (put 'org-delete-backward-char 'delete-selection 'supersede)
17623 ;; How to do this: Measure non-white length of current string
17624 ;; If equal to column width, we should realign.
17626 (defun org-remap (map &rest commands)
17627 "In MAP, remap the functions given in COMMANDS.
17628 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
17629 (let (new old)
17630 (while commands
17631 (setq old (pop commands) new (pop commands))
17632 (if (fboundp 'command-remapping)
17633 (define-key map (vector 'remap old) new)
17634 (substitute-key-definition old new map global-map)))))
17636 (when (eq org-enable-table-editor 'optimized)
17637 ;; If the user wants maximum table support, we need to hijack
17638 ;; some standard editing functions
17639 (org-remap org-mode-map
17640 'self-insert-command 'org-self-insert-command
17641 'delete-char 'org-delete-char
17642 'delete-backward-char 'org-delete-backward-char)
17643 (define-key org-mode-map "|" 'org-force-self-insert))
17645 (defun org-shiftcursor-error ()
17646 "Throw an error because Shift-Cursor command was applied in wrong context."
17647 (error "This command is active in special context like tables, headlines or timestamps"))
17649 (defun org-shifttab (&optional arg)
17650 "Global visibility cycling or move to previous table field.
17651 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
17652 on context.
17653 See the individual commands for more information."
17654 (interactive "P")
17655 (cond
17656 ((org-at-table-p) (call-interactively 'org-table-previous-field))
17657 (t (call-interactively 'org-global-cycle))))
17659 (defun org-shiftmetaleft ()
17660 "Promote subtree or delete table column.
17661 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
17662 See the individual commands for more information."
17663 (interactive)
17664 (cond
17665 ((org-at-table-p) (call-interactively 'org-table-delete-column))
17666 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
17667 ((org-at-item-p) (call-interactively 'org-outdent-item))
17668 (t (org-shiftcursor-error))))
17670 (defun org-shiftmetaright ()
17671 "Demote subtree or insert table column.
17672 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
17673 See the individual commands for more information."
17674 (interactive)
17675 (cond
17676 ((org-at-table-p) (call-interactively 'org-table-insert-column))
17677 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
17678 ((org-at-item-p) (call-interactively 'org-indent-item))
17679 (t (org-shiftcursor-error))))
17681 (defun org-shiftmetaup (&optional arg)
17682 "Move subtree up or kill table row.
17683 Calls `org-move-subtree-up' or `org-table-kill-row' or
17684 `org-move-item-up' depending on context. See the individual commands
17685 for more information."
17686 (interactive "P")
17687 (cond
17688 ((org-at-table-p) (call-interactively 'org-table-kill-row))
17689 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17690 ((org-at-item-p) (call-interactively 'org-move-item-up))
17691 (t (org-shiftcursor-error))))
17692 (defun org-shiftmetadown (&optional arg)
17693 "Move subtree down or insert table row.
17694 Calls `org-move-subtree-down' or `org-table-insert-row' or
17695 `org-move-item-down', depending on context. See the individual
17696 commands for more information."
17697 (interactive "P")
17698 (cond
17699 ((org-at-table-p) (call-interactively 'org-table-insert-row))
17700 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17701 ((org-at-item-p) (call-interactively 'org-move-item-down))
17702 (t (org-shiftcursor-error))))
17704 (defun org-metaleft (&optional arg)
17705 "Promote heading or move table column to left.
17706 Calls `org-do-promote' or `org-table-move-column', depending on context.
17707 With no specific context, calls the Emacs default `backward-word'.
17708 See the individual commands for more information."
17709 (interactive "P")
17710 (cond
17711 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
17712 ((or (org-on-heading-p) (org-region-active-p))
17713 (call-interactively 'org-do-promote))
17714 ((org-at-item-p) (call-interactively 'org-outdent-item))
17715 (t (call-interactively 'backward-word))))
17717 (defun org-metaright (&optional arg)
17718 "Demote subtree or move table column to right.
17719 Calls `org-do-demote' or `org-table-move-column', depending on context.
17720 With no specific context, calls the Emacs default `forward-word'.
17721 See the individual commands for more information."
17722 (interactive "P")
17723 (cond
17724 ((org-at-table-p) (call-interactively 'org-table-move-column))
17725 ((or (org-on-heading-p) (org-region-active-p))
17726 (call-interactively 'org-do-demote))
17727 ((org-at-item-p) (call-interactively 'org-indent-item))
17728 (t (call-interactively 'forward-word))))
17730 (defun org-metaup (&optional arg)
17731 "Move subtree up or move table row up.
17732 Calls `org-move-subtree-up' or `org-table-move-row' or
17733 `org-move-item-up', depending on context. See the individual commands
17734 for more information."
17735 (interactive "P")
17736 (cond
17737 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
17738 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
17739 ((org-at-item-p) (call-interactively 'org-move-item-up))
17740 (t (org-shiftcursor-error))))
17742 (defun org-metadown (&optional arg)
17743 "Move subtree down or move table row down.
17744 Calls `org-move-subtree-down' or `org-table-move-row' or
17745 `org-move-item-down', depending on context. See the individual
17746 commands for more information."
17747 (interactive "P")
17748 (cond
17749 ((org-at-table-p) (call-interactively 'org-table-move-row))
17750 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
17751 ((org-at-item-p) (call-interactively 'org-move-item-down))
17752 (t (org-shiftcursor-error))))
17754 (defun org-shiftup (&optional arg)
17755 "Increase item in timestamp or increase priority of current headline.
17756 Calls `org-timestamp-up' or `org-priority-up', depending on context.
17757 See the individual commands for more information."
17758 (interactive "P")
17759 (cond
17760 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
17761 ((org-on-heading-p) (call-interactively 'org-priority-up))
17762 ((org-at-item-p) (call-interactively 'org-previous-item))
17763 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
17765 (defun org-shiftdown (&optional arg)
17766 "Decrease item in timestamp or decrease priority of current headline.
17767 Calls `org-timestamp-down' or `org-priority-down', depending on context.
17768 See the individual commands for more information."
17769 (interactive "P")
17770 (cond
17771 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
17772 ((org-on-heading-p) (call-interactively 'org-priority-down))
17773 (t (call-interactively 'org-next-item))))
17775 (defun org-shiftright ()
17776 "Next TODO keyword or timestamp one day later, depending on context."
17777 (interactive)
17778 (cond
17779 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
17780 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
17781 (t (org-shiftcursor-error))))
17783 (defun org-shiftleft ()
17784 "Previous TODO keyword or timestamp one day earlier, depending on context."
17785 (interactive)
17786 (cond
17787 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
17788 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
17789 (t (org-shiftcursor-error))))
17791 (defun org-copy-special ()
17792 "Copy region in table or copy current subtree.
17793 Calls `org-table-copy' or `org-copy-subtree', depending on context.
17794 See the individual commands for more information."
17795 (interactive)
17796 (call-interactively
17797 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
17799 (defun org-cut-special ()
17800 "Cut region in table or cut current subtree.
17801 Calls `org-table-copy' or `org-cut-subtree', depending on context.
17802 See the individual commands for more information."
17803 (interactive)
17804 (call-interactively
17805 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
17807 (defun org-paste-special (arg)
17808 "Paste rectangular region into table, or past subtree relative to level.
17809 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
17810 See the individual commands for more information."
17811 (interactive "P")
17812 (if (org-at-table-p)
17813 (org-table-paste-rectangle)
17814 (org-paste-subtree arg)))
17816 (defun org-ctrl-c-ctrl-c (&optional arg)
17817 "Set tags in headline, or update according to changed information at point.
17819 This command does many different things, depending on context:
17821 - If the cursor is in a headline, prompt for tags and insert them
17822 into the current line, aligned to `org-tags-column'. When called
17823 with prefix arg, realign all tags in the current buffer.
17825 - If the cursor is in one of the special #+KEYWORD lines, this
17826 triggers scanning the buffer for these lines and updating the
17827 information.
17829 - If the cursor is inside a table, realign the table. This command
17830 works even if the automatic table editor has been turned off.
17832 - If the cursor is on a #+TBLFM line, re-apply the formulas to
17833 the entire table.
17835 - If the cursor is inside a table created by the table.el package,
17836 activate that table.
17838 - If the current buffer is a remember buffer, close note and file it.
17839 with a prefix argument, file it without further interaction to the default
17840 location.
17842 - If the cursor is on a <<<target>>>, update radio targets and corresponding
17843 links in this buffer.
17845 - If the cursor is on a numbered item in a plain list, renumber the
17846 ordered list."
17847 (interactive "P")
17848 (let ((org-enable-table-editor t))
17849 (cond
17850 ((or org-clock-overlays
17851 org-occur-highlights
17852 org-latex-fragment-image-overlays)
17853 (org-remove-clock-overlays)
17854 (org-remove-occur-highlights)
17855 (org-remove-latex-fragment-image-overlays)
17856 (message "Temporary highlights/overlays removed from current buffer"))
17857 ((and (local-variable-p 'org-finish-function (current-buffer))
17858 (fboundp org-finish-function))
17859 (funcall org-finish-function))
17860 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
17861 ((org-on-heading-p) (call-interactively 'org-set-tags))
17862 ((org-at-table.el-p)
17863 (require 'table)
17864 (beginning-of-line 1)
17865 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
17866 (call-interactively 'table-recognize-table))
17867 ((org-at-table-p)
17868 (org-table-maybe-eval-formula)
17869 (if arg
17870 (call-interactively 'org-table-recalculate)
17871 (org-table-maybe-recalculate-line))
17872 (call-interactively 'org-table-align))
17873 ((org-at-item-checkbox-p)
17874 (call-interactively 'org-toggle-checkbox))
17875 ((org-at-item-p)
17876 (call-interactively 'org-renumber-ordered-list))
17877 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
17878 (cond
17879 ((equal (match-string 1) "TBLFM")
17880 ;; Recalculate the table before this line
17881 (save-excursion
17882 (beginning-of-line 1)
17883 (skip-chars-backward " \r\n\t")
17884 (if (org-at-table-p)
17885 (org-call-with-arg 'org-table-recalculate t))))
17887 (call-interactively 'org-mode-restart))))
17888 (t (error "C-c C-c can do nothing useful at this location.")))))
17890 (defun org-mode-restart ()
17891 "Restart Org-mode, to scan again for special lines.
17892 Also updates the keyword regular expressions."
17893 (interactive)
17894 (let ((org-inhibit-startup t)) (org-mode))
17895 (message "Org-mode restarted to refresh keyword and special line setup"))
17897 (defun org-return ()
17898 "Goto next table row or insert a newline.
17899 Calls `org-table-next-row' or `newline', depending on context.
17900 See the individual commands for more information."
17901 (interactive)
17902 (cond
17903 ((org-at-table-p)
17904 (org-table-justify-field-maybe)
17905 (call-interactively 'org-table-next-row))
17906 (t (newline))))
17908 (defun org-meta-return (&optional arg)
17909 "Insert a new heading or wrap a region in a table.
17910 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
17911 See the individual commands for more information."
17912 (interactive "P")
17913 (cond
17914 ((org-at-table-p)
17915 (call-interactively 'org-table-wrap-region))
17916 (t (call-interactively 'org-insert-heading))))
17918 ;;; Menu entries
17920 ;; Define the Org-mode menus
17921 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
17922 '("Tbl"
17923 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
17924 ["Next Field" org-cycle (org-at-table-p)]
17925 ["Previous Field" org-shifttab (org-at-table-p)]
17926 ["Next Row" org-return (org-at-table-p)]
17927 "--"
17928 ["Blank Field" org-table-blank-field (org-at-table-p)]
17929 ["Edit Field" org-table-edit-field (org-at-table-p)]
17930 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
17931 "--"
17932 ("Column"
17933 ["Move Column Left" org-metaleft (org-at-table-p)]
17934 ["Move Column Right" org-metaright (org-at-table-p)]
17935 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
17936 ["Insert Column" org-shiftmetaright (org-at-table-p)]
17937 "--"
17938 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :active (org-at-table-p) :selected org-table-limit-column-width :style toggle])
17939 ("Row"
17940 ["Move Row Up" org-metaup (org-at-table-p)]
17941 ["Move Row Down" org-metadown (org-at-table-p)]
17942 ["Delete Row" org-shiftmetaup (org-at-table-p)]
17943 ["Insert Row" org-shiftmetadown (org-at-table-p)]
17944 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
17945 "--"
17946 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
17947 ("Rectangle"
17948 ["Copy Rectangle" org-copy-special (org-at-table-p)]
17949 ["Cut Rectangle" org-cut-special (org-at-table-p)]
17950 ["Paste Rectangle" org-paste-special (org-at-table-p)]
17951 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
17952 "--"
17953 ("Calculate"
17954 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
17955 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
17956 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
17957 "--"
17958 ["Recalculate line" org-table-recalculate (org-at-table-p)]
17959 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
17960 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
17961 "--"
17962 ["Sum Column/Rectangle" org-table-sum
17963 (or (org-at-table-p) (org-region-active-p))]
17964 ["Which Column?" org-table-current-column (org-at-table-p)])
17965 ["Debug Formulas"
17966 (setq org-table-formula-debug (not org-table-formula-debug))
17967 :style toggle :selected org-table-formula-debug]
17968 "--"
17969 ["Create" org-table-create (and (not (org-at-table-p))
17970 org-enable-table-editor)]
17971 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
17972 ["Import from File" org-table-import (not (org-at-table-p))]
17973 ["Export to File" org-table-export (org-at-table-p)]
17974 "--"
17975 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
17977 (easy-menu-define org-org-menu org-mode-map "Org menu"
17978 '("Org"
17979 ("Show/Hide"
17980 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
17981 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
17982 ["Sparse Tree" org-occur t]
17983 ["Reveal Context" org-reveal t]
17984 ["Show All" show-all t]
17985 "--"
17986 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
17987 "--"
17988 ["New Heading" org-insert-heading t]
17989 ("Navigate Headings"
17990 ["Up" outline-up-heading t]
17991 ["Next" outline-next-visible-heading t]
17992 ["Previous" outline-previous-visible-heading t]
17993 ["Next Same Level" outline-forward-same-level t]
17994 ["Previous Same Level" outline-backward-same-level t]
17995 "--"
17996 ["Jump" org-goto t])
17997 ("Edit Structure"
17998 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
17999 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
18000 "--"
18001 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
18002 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
18003 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
18004 "--"
18005 ["Promote Heading" org-metaleft (not (org-at-table-p))]
18006 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
18007 ["Demote Heading" org-metaright (not (org-at-table-p))]
18008 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
18009 "--"
18010 ["Sort Region/Children" org-sort (not (org-at-table-p))]
18011 "--"
18012 ["Convert to odd levels" org-convert-to-odd-levels t]
18013 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
18014 ("Archive"
18015 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
18016 ["Check and Tag Children" (org-toggle-archive-tag (4))
18017 :active t :keys "C-u C-c C-x C-a"]
18018 ["Sparse trees open ARCHIVE trees"
18019 (setq org-sparse-tree-open-archived-trees
18020 (not org-sparse-tree-open-archived-trees))
18021 :style toggle :selected org-sparse-tree-open-archived-trees]
18022 ["Cycling opens ARCHIVE trees"
18023 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
18024 :style toggle :selected org-cycle-open-archived-trees]
18025 ["Agenda includes ARCHIVE trees"
18026 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
18027 :style toggle :selected (not org-agenda-skip-archived-trees)]
18028 "--"
18029 ["Move Subtree to Archive" org-archive-subtree t]
18030 ["Check and Move Children" (org-archive-subtree '(4))
18031 :active t :keys "C-u C-c $"])
18032 "--"
18033 ("TODO Lists"
18034 ["TODO/DONE/-" org-todo t]
18035 ("Select keyword"
18036 ["Next keyword" org-shiftright (org-on-heading-p)]
18037 ["Previous keyword" org-shiftleft (org-on-heading-p)]
18038 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
18039 ["Show TODO Tree" org-show-todo-tree t]
18040 ["Global TODO list" org-todo-list t]
18041 "--"
18042 ["Set Priority" org-priority t]
18043 ["Priority Up" org-shiftup t]
18044 ["Priority Down" org-shiftdown t]
18045 "--"
18046 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
18047 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
18048 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
18049 ; (or (org-on-heading-p) (org-at-item-p))]
18050 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
18051 ; (or (org-on-heading-p) (org-at-item-p))]
18052 ; ["Update Statistics" org-update-checkbox-count t]
18054 ("Dates and Scheduling"
18055 ["Timestamp" org-time-stamp t]
18056 ["Timestamp (inactive)" org-time-stamp-inactive t]
18057 ("Change Date"
18058 ["1 Day Later" org-shiftright t]
18059 ["1 Day Earlier" org-shiftleft t]
18060 ["1 ... Later" org-shiftup t]
18061 ["1 ... Earlier" org-shiftdown t])
18062 ["Compute Time Range" org-evaluate-time-range t]
18063 ["Schedule Item" org-schedule t]
18064 ["Deadline" org-deadline t]
18065 "--"
18066 ["Custom time format" org-toggle-time-stamp-overlays
18067 :style radio :selected org-display-custom-times]
18068 "--"
18069 ["Goto Calendar" org-goto-calendar t]
18070 ["Date from Calendar" org-date-from-calendar t])
18071 ("Logging work"
18072 ["Clock in" org-clock-in t]
18073 ["Clock out" org-clock-out t]
18074 ["Clock cancel" org-clock-cancel t]
18075 ["Display times" org-clock-display t]
18076 ["Create clock table" org-clock-report t]
18077 "--"
18078 ["Record DONE time"
18079 (progn (setq org-log-done (not org-log-done))
18080 (message "Switching to %s will %s record a timestamp"
18081 org-done-string
18082 (if org-log-done "automatically" "not")))
18083 :style toggle :selected org-log-done])
18084 "--"
18085 ["Agenda Command..." org-agenda t]
18086 ("File List for Agenda")
18087 ("Special views current file"
18088 ["TODO Tree" org-show-todo-tree t]
18089 ["Check Deadlines" org-check-deadlines t]
18090 ["Timeline" org-timeline t]
18091 ["Tags Tree" org-tags-sparse-tree t])
18092 "--"
18093 ("Hyperlinks"
18094 ["Store Link (Global)" org-store-link t]
18095 ["Insert Link" org-insert-link t]
18096 ["Follow Link" org-open-at-point t]
18097 "--"
18098 ["Descriptive Links"
18099 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
18100 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
18101 ["Literal Links"
18102 (progn
18103 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
18104 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
18105 "--"
18106 ["Export/Publish..." org-export t]
18107 ("LaTeX"
18108 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
18109 :selected org-cdlatex-mode]
18110 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
18111 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
18112 ["Modify math symbol" org-cdlatex-math-modify
18113 (org-inside-LaTeX-fragment-p)]
18114 ["Export LaTeX fragments as images"
18115 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
18116 :style toggle :selected org-export-with-LaTeX-fragments])
18117 "--"
18118 ("Documentation"
18119 ["Show Version" org-version t]
18120 ["Info Documentation" org-info t])
18121 ("Customize"
18122 ["Browse Org Group" org-customize t]
18123 "--"
18124 ["Expand This Menu" org-create-customize-menu
18125 (fboundp 'customize-menu-create)])
18126 "--"
18127 ["Refresh setup" org-mode-restart t]
18130 (defun org-toggle-log-option (type)
18131 (if (not (listp org-log-done)) (setq org-log-done nil))
18132 (if (memq type org-log-done)
18133 (setq org-log-done (delq type org-log-done))
18134 (add-to-list 'org-log-done type)))
18136 (defun org-check-log-option (type)
18137 (and (listp org-log-done) (memq type org-log-done)))
18139 (defun org-info (&optional node)
18140 "Read documentation for Org-mode in the info system.
18141 With optional NODE, go directly to that node."
18142 (interactive)
18143 (require 'info)
18144 (Info-goto-node (format "(org)%s" (or node ""))))
18146 (defun org-install-agenda-files-menu ()
18147 (let ((bl (buffer-list)))
18148 (save-excursion
18149 (while bl
18150 (set-buffer (pop bl))
18151 (if (org-mode-p) (setq bl nil)))
18152 (when (org-mode-p)
18153 (easy-menu-change
18154 '("Org") "File List for Agenda"
18155 (append
18156 (list
18157 ["Edit File List" (org-edit-agenda-file-list) t]
18158 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
18159 ["Remove Current File from List" org-remove-file t]
18160 ["Cycle through agenda files" org-cycle-agenda-files t]
18161 "--")
18162 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
18164 ;;;; Documentation
18166 (defun org-customize ()
18167 "Call the customize function with org as argument."
18168 (interactive)
18169 (customize-browse 'org))
18171 (defun org-create-customize-menu ()
18172 "Create a full customization menu for Org-mode, insert it into the menu."
18173 (interactive)
18174 (if (fboundp 'customize-menu-create)
18175 (progn
18176 (easy-menu-change
18177 '("Org") "Customize"
18178 `(["Browse Org group" org-customize t]
18179 "--"
18180 ,(customize-menu-create 'org)
18181 ["Set" Custom-set t]
18182 ["Save" Custom-save t]
18183 ["Reset to Current" Custom-reset-current t]
18184 ["Reset to Saved" Custom-reset-saved t]
18185 ["Reset to Standard Settings" Custom-reset-standard t]))
18186 (message "\"Org\"-menu now contains full customization menu"))
18187 (error "Cannot expand menu (outdated version of cus-edit.el)")))
18189 ;;;; Miscellaneous stuff
18192 ;;; Generally useful functions
18194 (defun org-context ()
18195 "Return a list of contexts of the current cursor position.
18196 If several contexts apply, all are returned.
18197 Each context entry is a list with a symbol naming the context, and
18198 two positions indicating start and end of the context. Possible
18199 contexts are:
18201 :headline anywhere in a headline
18202 :headline-stars on the leading stars in a headline
18203 :todo-keyword on a TODO keyword (including DONE) in a headline
18204 :tags on the TAGS in a headline
18205 :priority on the priority cookie in a headline
18206 :item on the first line of a plain list item
18207 :item-bullet on the bullet/number of a plain list item
18208 :checkbox on the checkbox in a plain list item
18209 :table in an org-mode table
18210 :table-special on a special filed in a table
18211 :table-table in a table.el table
18212 :link on a hyperline
18213 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
18214 :target on a <<target>>
18215 :radio-target on a <<<radio-target>>>
18216 :latex-fragment on a LaTeX fragment
18217 :latex-preview on a LaTeX fragment with overlayed preview image
18219 This function expects the position to be visible because it uses font-lock
18220 faces as a help to recognize the following contexts: :table-special, :link,
18221 and :keyword."
18222 (let* ((f (get-text-property (point) 'face))
18223 (faces (if (listp f) f (list f)))
18224 (p (point)) clist o)
18225 ;; First the large context
18226 (cond
18227 ((org-on-heading-p)
18228 (push (list :headline (point-at-bol) (point-at-eol)) clist)
18229 (when (progn
18230 (beginning-of-line 1)
18231 (looking-at org-todo-line-tags-regexp))
18232 (push (org-point-in-group p 1 :headline-stars) clist)
18233 (push (org-point-in-group p 2 :todo-keyword) clist)
18234 (push (org-point-in-group p 4 :tags) clist))
18235 (goto-char p)
18236 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
18237 (if (looking-at "\\[#[A-Z]\\]")
18238 (push (org-point-in-group p 0 :priority) clist)))
18240 ((org-at-item-p)
18241 (push (org-point-in-group p 2 :item-bullet) clist)
18242 (push (list :item (point-at-bol)
18243 (save-excursion (org-end-of-item) (point)))
18244 clist)
18245 (and (org-at-item-checkbox-p)
18246 (push (org-point-in-group p 0 :checkbox) clist)))
18248 ((org-at-table-p)
18249 (push (list :table (org-table-begin) (org-table-end)) clist)
18250 (if (memq 'org-formula faces)
18251 (push (list :table-special
18252 (previous-single-property-change p 'face)
18253 (next-single-property-change p 'face)) clist)))
18254 ((org-at-table-p 'any)
18255 (push (list :table-table) clist)))
18256 (goto-char p)
18258 ;; Now the small context
18259 (cond
18260 ((org-at-timestamp-p)
18261 (push (org-point-in-group p 0 :timestamp) clist))
18262 ((memq 'org-link faces)
18263 (push (list :link
18264 (previous-single-property-change p 'face)
18265 (next-single-property-change p 'face)) clist))
18266 ((memq 'org-special-keyword faces)
18267 (push (list :keyword
18268 (previous-single-property-change p 'face)
18269 (next-single-property-change p 'face)) clist))
18270 ((org-on-target-p)
18271 (push (org-point-in-group p 0 :target) clist)
18272 (goto-char (1- (match-beginning 0)))
18273 (if (looking-at org-radio-target-regexp)
18274 (push (org-point-in-group p 0 :radio-target) clist))
18275 (goto-char p))
18276 ((setq o (car (delq nil
18277 (mapcar
18278 (lambda (x)
18279 (if (memq x org-latex-fragment-image-overlays) x))
18280 (org-overlays-at (point))))))
18281 (push (list :latex-fragment
18282 (org-overlay-start o) (org-overlay-end o)) clist)
18283 (push (list :latex-preview
18284 (org-overlay-start o) (org-overlay-end o)) clist))
18285 ((org-inside-LaTeX-fragment-p)
18286 ;; FIXME: positions wrong.
18287 (push (list :latex-fragment (point) (point)) clist)))
18289 (setq clist (nreverse (delq nil clist)))
18290 clist))
18292 (defun org-point-in-group (point group &optional context)
18293 "Check if POINT is in match-group GROUP.
18294 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
18295 match. If the match group does ot exist or point is not inside it,
18296 return nil."
18297 (and (match-beginning group)
18298 (>= point (match-beginning group))
18299 (<= point (match-end group))
18300 (if context
18301 (list context (match-beginning group) (match-end group))
18302 t)))
18304 (defun org-move-line-down (arg)
18305 "Move the current line down. With prefix argument, move it past ARG lines."
18306 (interactive "p")
18307 (let ((col (current-column))
18308 beg end pos)
18309 (beginning-of-line 1) (setq beg (point))
18310 (beginning-of-line 2) (setq end (point))
18311 (beginning-of-line (+ 1 arg))
18312 (setq pos (move-marker (make-marker) (point)))
18313 (insert (delete-and-extract-region beg end))
18314 (goto-char pos)
18315 (move-to-column col)))
18317 (defun org-move-line-up (arg)
18318 "Move the current line up. With prefix argument, move it past ARG lines."
18319 (interactive "p")
18320 (let ((col (current-column))
18321 beg end pos)
18322 (beginning-of-line 1) (setq beg (point))
18323 (beginning-of-line 2) (setq end (point))
18324 (beginning-of-line (- arg))
18325 (setq pos (move-marker (make-marker) (point)))
18326 (insert (delete-and-extract-region beg end))
18327 (goto-char pos)
18328 (move-to-column col)))
18330 (defun org-replace-escapes (string table)
18331 ;; FIXME: document and make safer
18332 (let (e re rpl)
18333 (while (setq e (pop table))
18334 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
18335 (while (string-match re string)
18336 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
18337 (cdr e)))
18338 (setq string (replace-match rpl t t string))))
18339 string))
18341 ;;; Paragraph filling stuff.
18342 ;; We want this to be just right, so use the full arsenal.
18343 ;; FIXME: configure filladapt for XEmacs
18345 (defun org-set-autofill-regexps ()
18346 (interactive)
18347 ;; In the paragraph separator we include headlines, because filling
18348 ;; text in a line directly attached to a headline would otherwise
18349 ;; fill the headline as well.
18350 (org-set-local 'comment-start-skip "^#+[ \t]*")
18351 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
18352 ;; The paragraph starter includes hand-formatted lists.
18353 (org-set-local 'paragraph-start
18354 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
18355 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
18356 ;; But only if the user has not turned off tables or fixed-width regions
18357 (org-set-local
18358 'auto-fill-inhibit-regexp
18359 (concat "\\*\\|#\\+"
18360 "\\|[ \t]*" org-keyword-time-regexp
18361 (if (or org-enable-table-editor org-enable-fixed-width-editor)
18362 (concat
18363 "\\|[ \t]*["
18364 (if org-enable-table-editor "|" "")
18365 (if org-enable-fixed-width-editor ":" "")
18366 "]"))))
18367 ;; We use our own fill-paragraph function, to make sure that tables
18368 ;; and fixed-width regions are not wrapped. That function will pass
18369 ;; through to `fill-paragraph' when appropriate.
18370 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
18371 ; Adaptive filling: To get full control, first make sure that
18372 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
18373 (org-set-local 'adaptive-fill-regexp "\000")
18374 (org-set-local 'adaptive-fill-function
18375 'org-adaptive-fill-function))
18377 (defun org-fill-paragraph (&optional justify)
18378 "Re-align a table, pass through to fill-paragraph if no table."
18379 (let ((table-p (org-at-table-p))
18380 (table.el-p (org-at-table.el-p)))
18381 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
18382 (table.el-p t) ; skip table.el tables
18383 (table-p (org-table-align) t) ; align org-mode tables
18384 (t nil)))) ; call paragraph-fill
18386 ;; For reference, this is the default value of adaptive-fill-regexp
18387 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
18389 (defun org-adaptive-fill-function ()
18390 "Return a fill prefix for org-mode files.
18391 In particular, this makes sure hanging paragraphs for hand-formatted lists
18392 work correctly."
18393 (cond ((looking-at "#[ \t]+")
18394 (match-string 0))
18395 ((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
18396 (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
18397 (t nil)))
18400 (defun org-image-file-name-regexp ()
18401 "Return regexp matching the file names of images."
18402 (if (fboundp 'image-file-name-regexp)
18403 (image-file-name-regexp)
18404 (let ((image-file-name-extensions
18405 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
18406 "xbm" "xpm" "pbm" "pgm" "ppm")))
18407 (concat "\\."
18408 (regexp-opt (nconc (mapcar 'upcase
18409 image-file-name-extensions)
18410 image-file-name-extensions)
18412 "\\'"))))
18414 (defun org-file-image-p (file)
18415 "Return non-nil if FILE is an image."
18416 (save-match-data
18417 (string-match (org-image-file-name-regexp) file)))
18419 ;;;; Functions extending outline functionality
18421 ;; C-a should go to the beginning of a *visible* line, also in the
18422 ;; new outline.el. I guess this should be patched into Emacs?
18423 (defun org-beginning-of-line ()
18424 "Go to the beginning of the current line. If that is invisible, continue
18425 to a visible line beginning. This makes the function of C-a more intuitive."
18426 (interactive)
18427 (beginning-of-line 1)
18428 (if (bobp)
18430 (backward-char 1)
18431 (if (org-invisible-p)
18432 (while (and (not (bobp)) (org-invisible-p))
18433 (backward-char 1)
18434 (beginning-of-line 1))
18435 (forward-char 1))))
18437 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
18439 (defun org-invisible-p ()
18440 "Check if point is at a character currently not visible."
18441 ;; Early versions of noutline don't have `outline-invisible-p'.
18442 (if (fboundp 'outline-invisible-p)
18443 (outline-invisible-p)
18444 (get-char-property (point) 'invisible)))
18446 (defun org-invisible-p2 ()
18447 "Check if point is at a character currently not visible."
18448 (save-excursion
18449 (if (and (eolp) (not (bobp))) (backward-char 1))
18450 ;; Early versions of noutline don't have `outline-invisible-p'.
18451 (if (fboundp 'outline-invisible-p)
18452 (outline-invisible-p)
18453 (get-char-property (point) 'invisible))))
18455 (defalias 'org-back-to-heading 'outline-back-to-heading)
18456 (defalias 'org-on-heading-p 'outline-on-heading-p)
18458 (defun org-on-target-p ()
18459 (let ((pos (point)))
18460 (save-excursion
18461 (skip-chars-forward "<")
18462 (and (re-search-backward "<<" nil t)
18463 (or (looking-at org-radio-target-regexp)
18464 (looking-at org-target-regexp))
18465 (<= (match-beginning 0) pos)
18466 (>= (1+ (match-end 0)) pos)))))
18468 (defun org-up-heading-all (arg)
18469 "Move to the heading line of which the present line is a subheading.
18470 This function considers both visible and invisible heading lines.
18471 With argument, move up ARG levels."
18472 (if (fboundp 'outline-up-heading-all)
18473 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18474 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18476 (defun org-goto-sibling (&optional previous)
18477 "Goto the next sibling, even if it is invisible.
18478 When PREVIOUS is set, go to the previous sibling instead. Returns t
18479 when a sibling was found. When none is found, return nil and don't
18480 move point."
18481 (let ((fun (if previous 're-search-backward 're-search-forward))
18482 (pos (point))
18483 (re (concat "^" outline-regexp))
18484 level l)
18485 (org-back-to-heading t)
18486 (setq level (funcall outline-level))
18487 (catch 'exit
18488 (or previous (forward-char 1))
18489 (while (funcall fun re nil t)
18490 (setq l (funcall outline-level))
18491 (when (< l level) (goto-char pos) (throw 'exit nil))
18492 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18493 (goto-char pos)
18494 nil)))
18496 (defun org-show-siblings ()
18497 "Show all siblings of the current headline."
18498 (save-excursion
18499 (while (org-goto-sibling) (org-flag-heading nil)))
18500 (save-excursion
18501 (while (org-goto-sibling 'previous)
18502 (org-flag-heading nil))))
18504 (defun org-show-hidden-entry ()
18505 "Show an entry where even the heading is hidden."
18506 (save-excursion
18507 (org-show-entry)))
18509 (defun org-flag-heading (flag &optional entry)
18510 "Flag the current heading. FLAG non-nil means make invisible.
18511 When ENTRY is non-nil, show the entire entry."
18512 (save-excursion
18513 (org-back-to-heading t)
18514 ;; Check if we should show the entire entry
18515 (if entry
18516 (progn
18517 (org-show-entry)
18518 (save-excursion
18519 (and (outline-next-heading)
18520 (org-flag-heading nil))))
18521 (outline-flag-region (max 1 (1- (point)))
18522 (save-excursion (outline-end-of-heading) (point))
18523 flag))))
18525 (defun org-end-of-subtree (&optional invisible-OK)
18526 ;; This is an exact copy of the original function, but it uses
18527 ;; `org-back-to-heading', to make it work also in invisible
18528 ;; trees. And is uses an invisible-OK argument.
18529 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18530 (org-back-to-heading invisible-OK)
18531 (let ((first t)
18532 (level (funcall outline-level)))
18533 (while (and (not (eobp))
18534 (or first (> (funcall outline-level) level)))
18535 (setq first nil)
18536 (outline-next-heading))
18537 (if (memq (preceding-char) '(?\n ?\^M))
18538 (progn
18539 ;; Go to end of line before heading
18540 (forward-char -1)
18541 (if (memq (preceding-char) '(?\n ?\^M))
18542 ;; leave blank line before heading
18543 (forward-char -1)))))
18544 (point))
18546 (defun org-show-subtree ()
18547 "Show everything after this heading at deeper levels."
18548 (outline-flag-region
18549 (point)
18550 (save-excursion
18551 (outline-end-of-subtree) (outline-next-heading) (point))
18552 nil))
18554 (defun org-show-entry ()
18555 "Show the body directly following this heading.
18556 Show the heading too, if it is currently invisible."
18557 (interactive)
18558 (save-excursion
18559 (org-back-to-heading t)
18560 (outline-flag-region
18561 (max 1 (1- (point)))
18562 (save-excursion
18563 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
18564 (or (match-beginning 1) (point-max)))
18565 nil)))
18567 (defun org-make-options-regexp (kwds)
18568 "Make a regular expression for keyword lines."
18569 (concat
18571 "#?[ \t]*\\+\\("
18572 (mapconcat 'regexp-quote kwds "\\|")
18573 "\\):[ \t]*"
18574 "\\(.+\\)"))
18576 ;; Make isearch reveal the necessary context
18577 (defun org-isearch-end ()
18578 "Reveal context after isearch exits."
18579 (when isearch-success ; only if search was successful
18580 (if (featurep 'xemacs)
18581 ;; Under XEmacs, the hook is run in the correct place,
18582 ;; we directly show the context.
18583 (org-show-context 'isearch)
18584 ;; In Emacs the hook runs *before* restoring the overlays.
18585 ;; So we have to use a one-time post-command-hook to do this.
18586 ;; (Emacs 22 has a special variable, see function `org-mode')
18587 (unless (and (boundp 'isearch-mode-end-hook-quit)
18588 isearch-mode-end-hook-quit)
18589 ;; Only when the isearch was not quitted.
18590 (org-add-hook 'post-command-hook 'org-isearch-post-command
18591 'append 'local)))))
18593 (defun org-isearch-post-command ()
18594 "Remove self from hook, and show context."
18595 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18596 (org-show-context 'isearch))
18598 ;;;; Repair problems with some other packages
18600 ;; Make `bookmark-jump' show the jump location if it was hidden.
18601 (eval-after-load "bookmark"
18602 '(if (boundp 'bookmark-after-jump-hook)
18603 ;; We can use the hook
18604 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18605 ;; Hook not available, use advice
18606 (defadvice bookmark-jump (after org-make-visible activate)
18607 "Make the position visible."
18608 (org-bookmark-jump-unhide))))
18610 (defun org-bookmark-jump-unhide ()
18611 "Unhide the current position, to show the bookmark location."
18612 (and (org-mode-p)
18613 (or (org-invisible-p)
18614 (save-excursion (goto-char (max (point-min) (1- (point))))
18615 (org-invisible-p)))
18616 (org-show-context 'bookmark-jump)))
18618 ;; Make session.el ignore our circular variable
18619 (eval-after-load "session"
18620 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18622 ;;;; Experimental code
18624 (defcustom org-allow-auto-repeat t
18625 "Non-nil means, find REPEAT cookies in entries and apply them.
18626 A repeat cookie looks like REPEAT(+1m) and causes deadlines and schedules
18627 to repeat themselves shifted by a certain amount of time, each time an
18628 entry is marked DONE."
18629 :group 'org???
18630 :type 'boolean)
18632 (defun org-auto-repeat-maybe ()
18633 "Check if the current headline contains a REPEAT key.
18634 If yes, set TODO state back to what it was and change any SCHEDULED
18635 or DEADLINE times the new date.
18636 This function should be run in the `org-after-todo-state-change-hook'."
18637 ;; last-state is dynamically scoped into this function
18638 (let ((repeat (org-get-repeat))
18639 (whata '(("d" . day) ("m" . month) ("y" . year)))
18640 (msg "Entry repeats: ")
18641 (org-log-done)
18642 re type n what start)
18643 (when repeat
18644 (org-todo (if (eq 'org-todo-interpretation 'type)
18645 last-state
18646 (car org-todo-keywords)))
18647 (unless (memq 'org-add-log-note (default-value 'post-command-hook))
18648 ;; Make sure a note is taken
18649 (let ((org-log-done '(done)))
18650 (org-add-log-maybe 'done org-done-string 'findpos)))
18651 (org-back-to-heading t)
18652 (org-add-planning-info nil nil 'closed)
18653 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
18654 org-deadline-time-regexp "\\)"))
18655 (while (re-search-forward
18656 re (save-excursion (outline-next-heading) (point)) t)
18657 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
18658 start 0)
18659 (while (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" repeat start)
18660 (setq start (match-end 0)
18661 n (string-to-number (match-string 1 repeat))
18662 what (match-string 2 repeat))
18663 (if (equal what "w") (setq n (* n 7) what "d"))
18664 (org-timestamp-change n (cdr (assoc what whata))))
18665 (setq msg (concat msg type org-last-changed-timestamp " ")))
18666 (setq org-log-post-message msg)
18667 (message msg))))
18669 ;;;; Finish up
18671 (provide 'org)
18673 (run-hooks 'org-load-hook)
18675 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18676 ;;; org.el ends here