Release 5.10a
[org-mode.git] / org_xemacs.el
blobceb6eb47682d7300fab84312dabb1b24b8b91a0a
1 ;;; org.el --- Outline-based notes management and organizer
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.78
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://staff.science.uva.nl/~dominik/Tools/org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://www.astro.uva.nl/~dominik/Tools/org/Changes
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (require 'easymenu)
82 ;;;; Customization variables
84 ;;; Version
86 (defconst org-version "4.78"
87 "The version number of the file org.el.")
88 (defun org-version ()
89 (interactive)
90 (message "Org-mode version %s" org-version))
92 ;;; Compatibility constants
93 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
94 (defconst org-format-transports-properties-p
95 (let ((x "a"))
96 (add-text-properties 0 1 '(test t) x)
97 (get-text-property 0 'test (format "%s" x)))
98 "Does format transport text properties?")
100 ;;; The custom variables
102 (defgroup org nil
103 "Outline-based notes management and organizer."
104 :tag "Org"
105 :group 'outlines
106 :group 'hypermedia
107 :group 'calendar)
109 (defgroup org-startup nil
110 "Options concerning startup of Org-mode."
111 :tag "Org Startup"
112 :group 'org)
114 (defcustom org-startup-folded t
115 "Non-nil means, entering Org-mode will switch to OVERVIEW.
116 This can also be configured on a per-file basis by adding one of
117 the following lines anywhere in the buffer:
119 #+STARTUP: fold
120 #+STARTUP: nofold
121 #+STARTUP: content"
122 :group 'org-startup
123 :type '(choice
124 (const :tag "nofold: show all" nil)
125 (const :tag "fold: overview" t)
126 (const :tag "content: all headlines" content)))
128 (defcustom org-startup-truncated t
129 "Non-nil means, entering Org-mode will set `truncate-lines'.
130 This is useful since some lines containing links can be very long and
131 uninteresting. Also tables look terrible when wrapped."
132 :group 'org-startup
133 :type 'boolean)
135 (defcustom org-startup-align-all-tables nil
136 "Non-nil means, align all tables when visiting a file.
137 This is useful when the column width in tables is forced with <N> cookies
138 in table fields. Such tables will look correct only after the first re-align.
139 This can also be configured on a per-file basis by adding one of
140 the following lines anywhere in the buffer:
141 #+STARTUP: align
142 #+STARTUP: noalign"
143 :group 'org-startup
144 :type 'boolean)
146 (defcustom org-insert-mode-line-in-empty-file nil
147 "Non-nil means insert the first line setting Org-mode in empty files.
148 When the function `org-mode' is called interactively in an empty file, this
149 normally means that the file name does not automatically trigger Org-mode.
150 To ensure that the file will always be in Org-mode in the future, a
151 line enforcing Org-mode will be inserted into the buffer, if this option
152 has been set."
153 :group 'org-startup
154 :type 'boolean)
156 (defcustom org-replace-disputed-keys nil
157 "Non-nil means use alternative key bindings for some keys.
158 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
159 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
160 If you want to use Org-mode together with one of these other modes,
161 or more generally if you would like to move some Org-mode commands to
162 other keys, set this variable and configure the keys with the variable
163 `org-disputed-keys'.
165 This option is only relevant at load-time of Org-mode, and must be set
166 *before* org.el is loaded. Changing it requires a restart of Emacs to
167 become effective."
168 :group 'org-startup
169 :type 'boolean)
171 (if (fboundp 'defvaralias)
172 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
174 (defcustom org-disputed-keys
175 '(([(shift up)] . [(meta p)])
176 ([(shift down)] . [(meta n)])
177 ([(shift left)] . [(meta -)])
178 ([(shift right)] . [(meta +)])
179 ([(control shift right)] . [(meta shift +)])
180 ([(control shift left)] . [(meta shift -)]))
181 "Keys for which Org-mode and other modes compete.
182 This is an alist, cars are the default keys, second element specifies
183 the alternative to use when `org-replace-disputed-keys' is t.
185 Keys can be specified in any syntax supported by `define-key'.
186 The value of this option takes effect only at Org-mode's startup,
187 therefore you'll have to restart Emacs to apply it after changing."
188 :group 'org-startup
189 :type 'alist)
191 (defun org-key (key)
192 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
193 Or return the original if not disputed."
194 (if org-replace-disputed-keys
195 (let* ((nkey (key-description key))
196 (x (org-find-if (lambda (x)
197 (equal (key-description (car x)) nkey))
198 org-disputed-keys)))
199 (if x (cdr x) key))
200 key))
202 (defun org-find-if (predicate seq)
203 (catch 'exit
204 (while seq
205 (if (funcall predicate (car seq))
206 (throw 'exit (car seq))
207 (pop seq)))))
209 (defun org-defkey (keymap key def)
210 "Define a key, possibly translated, as returned by `org-key'."
211 (define-key keymap (org-key key) def))
213 (defcustom org-ellipsis nil
214 "The ellipsis to use in the Org-mode outline.
215 When nil, just use the standard three dots. When a string, use that instead,
216 and just in Org-mode (which will then use its own display table).
217 Changing this requires executing `M-x org-mode' in a buffer to become
218 effective."
219 :group 'org-startup
220 :type '(choice (const :tag "Default" nil)
221 (string :tag "String" :value "...#")))
223 (defvar org-display-table nil
224 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
226 (defgroup org-keywords nil
227 "Keywords in Org-mode."
228 :tag "Org Keywords"
229 :group 'org)
231 (defcustom org-deadline-string "DEADLINE:"
232 "String to mark deadline entries.
233 A deadline is this string, followed by a time stamp. Should be a word,
234 terminated by a colon. You can insert a schedule keyword and
235 a timestamp with \\[org-deadline].
236 Changes become only effective after restarting Emacs."
237 :group 'org-keywords
238 :type 'string)
240 (defcustom org-scheduled-string "SCHEDULED:"
241 "String to mark scheduled TODO entries.
242 A schedule is this string, followed by a time stamp. Should be a word,
243 terminated by a colon. You can insert a schedule keyword and
244 a timestamp with \\[org-schedule].
245 Changes become only effective after restarting Emacs."
246 :group 'org-keywords
247 :type 'string)
249 (defcustom org-closed-string "CLOSED:"
250 "String used as the prefix for timestamps logging closing a TODO entry."
251 :group 'org-keywords
252 :type 'string)
254 (defcustom org-clock-string "CLOCK:"
255 "String used as prefix for timestamps clocking work hours on an item."
256 :group 'org-keywords
257 :type 'string)
259 (defcustom org-comment-string "COMMENT"
260 "Entries starting with this keyword will never be exported.
261 An entry can be toggled between COMMENT and normal with
262 \\[org-toggle-comment].
263 Changes become only effective after restarting Emacs."
264 :group 'org-keywords
265 :type 'string)
267 (defcustom org-quote-string "QUOTE"
268 "Entries starting with this keyword will be exported in fixed-width font.
269 Quoting applies only to the text in the entry following the headline, and does
270 not extend beyond the next headline, even if that is lower level.
271 An entry can be toggled between QUOTE and normal with
272 \\[org-toggle-fixed-width-section]."
273 :group 'org-keywords
274 :type 'string)
276 (defconst org-repeat-re
277 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
278 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
279 "Regular expression for specifying repeated events.
280 After a match, group 1 contains the repeat expression.")
282 (defgroup org-structure nil
283 "Options concerning the general structure of Org-mode files."
284 :tag "Org Structure"
285 :group 'org)
287 (defgroup org-reveal-location nil
288 "Options about how to make context of a location visible."
289 :tag "Org Reveal Location"
290 :group 'org-structure)
292 (defcustom org-show-hierarchy-above '((default . t))
293 "Non-nil means, show full hierarchy when revealing a location.
294 Org-mode often shows locations in an org-mode file which might have
295 been invisible before. When this is set, the hierarchy of headings
296 above the exposed location is shown.
297 Turning this off for example for sparse trees makes them very compact.
298 Instead of t, this can also be an alist specifying this option for different
299 contexts. Valid contexts are
300 agenda when exposing an entry from the agenda
301 org-goto when using the command `org-goto' on key C-c C-j
302 occur-tree when using the command `org-occur' on key C-c /
303 tags-tree when constructing a sparse tree based on tags matches
304 link-search when exposing search matches associated with a link
305 mark-goto when exposing the jump goal of a mark
306 bookmark-jump when exposing a bookmark location
307 isearch when exiting from an incremental search
308 default default for all contexts not set explicitly"
309 :group 'org-reveal-location
310 :type '(choice
311 (const :tag "Always" t)
312 (const :tag "Never" nil)
313 (repeat :greedy t :tag "Individual contexts"
314 (cons
315 (choice :tag "Context"
316 (const agenda)
317 (const org-goto)
318 (const occur-tree)
319 (const tags-tree)
320 (const link-search)
321 (const mark-goto)
322 (const bookmark-jump)
323 (const isearch)
324 (const default))
325 (boolean)))))
327 (defcustom org-show-following-heading '((default . nil))
328 "Non-nil means, show following heading when revealing a location.
329 Org-mode often shows locations in an org-mode file which might have
330 been invisible before. When this is set, the heading following the
331 match is shown.
332 Turning this off for example for sparse trees makes them very compact,
333 but makes it harder to edit the location of the match. In such a case,
334 use the command \\[org-reveal] to show more context.
335 Instead of t, this can also be an alist specifying this option for different
336 contexts. See `org-show-hierarchy-above' for valid contexts."
337 :group 'org-reveal-location
338 :type '(choice
339 (const :tag "Always" t)
340 (const :tag "Never" nil)
341 (repeat :greedy t :tag "Individual contexts"
342 (cons
343 (choice :tag "Context"
344 (const agenda)
345 (const org-goto)
346 (const occur-tree)
347 (const tags-tree)
348 (const link-search)
349 (const mark-goto)
350 (const bookmark-jump)
351 (const isearch)
352 (const default))
353 (boolean)))))
355 (defcustom org-show-siblings '((default . nil) (isearch t))
356 "Non-nil means, show all sibling heading when revealing a location.
357 Org-mode often shows locations in an org-mode file which might have
358 been invisible before. When this is set, the sibling of the current entry
359 heading are all made visible. If `org-show-hierarchy-above' is t,
360 the same happens on each level of the hierarchy above the current entry.
362 By default this is on for the isearch context, off for all other contexts.
363 Turning this off for example for sparse trees makes them very compact,
364 but makes it harder to edit the location of the match. In such a case,
365 use the command \\[org-reveal] to show more context.
366 Instead of t, this can also be an alist specifying this option for different
367 contexts. See `org-show-hierarchy-above' for valid contexts."
368 :group 'org-reveal-location
369 :type '(choice
370 (const :tag "Always" t)
371 (const :tag "Never" nil)
372 (repeat :greedy t :tag "Individual contexts"
373 (cons
374 (choice :tag "Context"
375 (const agenda)
376 (const org-goto)
377 (const occur-tree)
378 (const tags-tree)
379 (const link-search)
380 (const mark-goto)
381 (const bookmark-jump)
382 (const isearch)
383 (const default))
384 (boolean)))))
386 (defgroup org-cycle nil
387 "Options concerning visibility cycling in Org-mode."
388 :tag "Org Cycle"
389 :group 'org-structure)
391 (defcustom org-cycle-global-at-bob t
392 "Cycle globally if cursor is at beginning of buffer and not at a headline.
393 This makes it possible to do global cycling without having to use S-TAB or
394 C-u TAB. For this special case to work, the first line of the buffer
395 must not be a headline - it may be empty ot some other text. When used in
396 this way, `org-cycle-hook' is disables temporarily, to make sure the
397 cursor stays at the beginning of the buffer.
398 When this option is nil, don't do anything special at the beginning
399 of the buffer."
400 :group 'org-cycle
401 :type 'boolean)
403 (defcustom org-cycle-emulate-tab t
404 "Where should `org-cycle' emulate TAB.
405 nil Never
406 white Only in completely white lines
407 whitestart Only at the beginning of lines, before the first non-white char.
408 t Everywhere except in headlines
409 exc-hl-bol Everywhere except at the start of a headline
410 If TAB is used in a place where it does not emulate TAB, the current subtree
411 visibility is cycled."
412 :group 'org-cycle
413 :type '(choice (const :tag "Never" nil)
414 (const :tag "Only in completely white lines" white)
415 (const :tag "Before first char in a line" whitestart)
416 (const :tag "Everywhere except in headlines" t)
417 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
420 (defcustom org-cycle-separator-lines 2
421 "Number of empty lines needed to keep an empty line between collapsed trees.
422 If you leave an empty line between the end of a subtree and the following
423 headline, this empty line is hidden when the subtree is folded.
424 Org-mode will leave (exactly) one empty line visible if the number of
425 empty lines is equal or larger to the number given in this variable.
426 So the default 2 means, at least 2 empty lines after the end of a subtree
427 are needed to produce free space between a collapsed subtree and the
428 following headline.
430 Special case: when 0, never leave empty lines in collapsed view."
431 :group 'org-cycle
432 :type 'integer)
434 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
435 org-cycle-show-empty-lines
436 org-optimize-window-after-visibility-change)
437 "Hook that is run after `org-cycle' has changed the buffer visibility.
438 The function(s) in this hook must accept a single argument which indicates
439 the new state that was set by the most recent `org-cycle' command. The
440 argument is a symbol. After a global state change, it can have the values
441 `overview', `content', or `all'. After a local state change, it can have
442 the values `folded', `children', or `subtree'."
443 :group 'org-cycle
444 :type 'hook)
446 (defgroup org-edit-structure nil
447 "Options concerning structure editing in Org-mode."
448 :tag "Org Edit Structure"
449 :group 'org-structure)
451 (defcustom org-special-ctrl-a nil
452 "Non-nil means `C-a' behaves specially in headlines.
453 When set, `C-a' will bring back the cursor to the beginning of the
454 headline text, i.e. after the stars and after a possible TODO keyword.
455 When the cursor is already at that position, another `C-a' will bring
456 it to the beginning of the line."
457 :group 'org-edit-structure
458 :type 'boolean)
460 (defcustom org-odd-levels-only nil
461 "Non-nil means, skip even levels and only use odd levels for the outline.
462 This has the effect that two stars are being added/taken away in
463 promotion/demotion commands. It also influences how levels are
464 handled by the exporters.
465 Changing it requires restart of `font-lock-mode' to become effective
466 for fontification also in regions already fontified.
467 You may also set this on a per-file basis by adding one of the following
468 lines to the buffer:
470 #+STARTUP: odd
471 #+STARTUP: oddeven"
472 :group 'org-edit-structure
473 :group 'org-font-lock
474 :type 'boolean)
476 (defcustom org-adapt-indentation t
477 "Non-nil means, adapt indentation when promoting and demoting.
478 When this is set and the *entire* text in an entry is indented, the
479 indentation is increased by one space in a demotion command, and
480 decreased by one in a promotion command. If any line in the entry
481 body starts at column 0, indentation is not changed at all."
482 :group 'org-edit-structure
483 :type 'boolean)
485 (defcustom org-blank-before-new-entry '((heading . nil)
486 (plain-list-item . nil))
487 "Should `org-insert-heading' leave a blank line before new heading/item?
488 The value is an alist, with `heading' and `plain-list-item' as car,
489 and a boolean flag as cdr."
490 :group 'org-edit-structure
491 :type '(list
492 (cons (const heading) (boolean))
493 (cons (const plain-list-item) (boolean))))
495 (defcustom org-insert-heading-hook nil
496 "Hook being run after inserting a new heading."
497 :group 'org-edit-structure
498 :type 'boolean)
500 (defcustom org-enable-fixed-width-editor t
501 "Non-nil means, lines starting with \":\" are treated as fixed-width.
502 This currently only means, they are never auto-wrapped.
503 When nil, such lines will be treated like ordinary lines.
504 See also the QUOTE keyword."
505 :group 'org-edit-structure
506 :type 'boolean)
508 (defgroup org-sparse-trees nil
509 "Options concerning sparse trees in Org-mode."
510 :tag "Org Sparse Trees"
511 :group 'org-structure)
513 (defcustom org-highlight-sparse-tree-matches t
514 "Non-nil means, highlight all matches that define a sparse tree.
515 The highlights will automatically disappear the next time the buffer is
516 changed by an edit command."
517 :group 'org-sparse-trees
518 :type 'boolean)
520 (defcustom org-remove-highlights-with-change t
521 "Non-nil means, any change to the buffer will remove temporary highlights.
522 Such highlights are created by `org-occur' and `org-clock-display'.
523 When nil, `C-c C-c needs to be used to get rid of the highlights.
524 The highlights created by `org-preview-latex-fragment' always need
525 `C-c C-c' to be removed."
526 :group 'org-sparse-trees
527 :group 'org-time
528 :type 'boolean)
531 (defcustom org-occur-hook '(org-first-headline-recenter)
532 "Hook that is run after `org-occur' has constructed a sparse tree.
533 This can be used to recenter the window to show as much of the structure
534 as possible."
535 :group 'org-sparse-trees
536 :type 'hook)
538 (defgroup org-plain-lists nil
539 "Options concerning plain lists in Org-mode."
540 :tag "Org Plain lists"
541 :group 'org-structure)
543 (defcustom org-cycle-include-plain-lists nil
544 "Non-nil means, include plain lists into visibility cycling.
545 This means that during cycling, plain list items will *temporarily* be
546 interpreted as outline headlines with a level given by 1000+i where i is the
547 indentation of the bullet. In all other operations, plain list items are
548 not seen as headlines. For example, you cannot assign a TODO keyword to
549 such an item."
550 :group 'org-plain-lists
551 :type 'boolean)
553 (defcustom org-plain-list-ordered-item-terminator t
554 "The character that makes a line with leading number an ordered list item.
555 Valid values are ?. and ?\). To get both terminators, use t. While
556 ?. may look nicer, it creates the danger that a line with leading
557 number may be incorrectly interpreted as an item. ?\) therefore is
558 the safe choice."
559 :group 'org-plain-lists
560 :type '(choice (const :tag "dot like in \"2.\"" ?.)
561 (const :tag "paren like in \"2)\"" ?\))
562 (const :tab "both" t)))
564 (defcustom org-auto-renumber-ordered-lists t
565 "Non-nil means, automatically renumber ordered plain lists.
566 Renumbering happens when the sequence have been changed with
567 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
568 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
569 :group 'org-plain-lists
570 :type 'boolean)
572 (defcustom org-provide-checkbox-statistics t
573 "Non-nil means, update checkbox statistics after insert and toggle.
574 When this is set, checkbox statistics is updated each time you either insert
575 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
576 with \\[org-ctrl-c-ctrl-c\\]."
577 :group 'org-plain-lists
578 :type 'boolean)
580 (defgroup org-archive nil
581 "Options concerning archiving in Org-mode."
582 :tag "Org Archive"
583 :group 'org-structure)
585 (defcustom org-archive-tag "ARCHIVE"
586 "The tag that marks a subtree as archived.
587 An archived subtree does not open during visibility cycling, and does
588 not contribute to the agenda listings."
589 :group 'org-archive
590 :group 'org-keywords
591 :type 'string)
593 (defcustom org-agenda-skip-archived-trees t
594 "Non-nil means, the agenda will skip any items located in archived trees.
595 An archived tree is a tree marked with the tag ARCHIVE."
596 :group 'org-archive
597 :group 'org-agenda-skip
598 :type 'boolean)
600 (defcustom org-cycle-open-archived-trees nil
601 "Non-nil means, `org-cycle' will open archived trees.
602 An archived tree is a tree marked with the tag ARCHIVE.
603 When nil, archived trees will stay folded. You can still open them with
604 normal outline commands like `show-all', but not with the cycling commands."
605 :group 'org-archive
606 :group 'org-cycle
607 :type 'boolean)
609 (defcustom org-sparse-tree-open-archived-trees nil
610 "Non-nil means sparse tree construction shows matches in archived trees.
611 When nil, matches in these trees are highlighted, but the trees are kept in
612 collapsed state."
613 :group 'org-archive
614 :group 'org-sparse-trees
615 :type 'boolean)
617 (defcustom org-archive-location "%s_archive::"
618 "The location where subtrees should be archived.
619 This string consists of two parts, separated by a double-colon.
621 The first part is a file name - when omitted, archiving happens in the same
622 file. %s will be replaced by the current file name (without directory part).
623 Archiving to a different file is useful to keep archived entries from
624 contributing to the Org-mode Agenda.
626 The part after the double colon is a headline. The archived entries will be
627 filed under that headline. When omitted, the subtrees are simply filed away
628 at the end of the file, as top-level entries.
630 Here are a few examples:
631 \"%s_archive::\"
632 If the current file is Projects.org, archive in file
633 Projects.org_archive, as top-level trees. This is the default.
635 \"::* Archived Tasks\"
636 Archive in the current file, under the top-level headline
637 \"* Archived Tasks\".
639 \"~/org/archive.org::\"
640 Archive in file ~/org/archive.org (absolute path), as top-level trees.
642 \"basement::** Finished Tasks\"
643 Archive in file ./basement (relative path), as level 3 trees
644 below the level 2 heading \"** Finished Tasks\".
646 You may set this option on a per-file basis by adding to the buffer a
647 line like
649 #+ARCHIVE: basement::** Finished Tasks"
650 :group 'org-archive
651 :type 'string)
653 (defcustom org-archive-mark-done t
654 "Non-nil means, mark entries as DONE when they are moved to the archive file."
655 :group 'org-archive
656 :type 'boolean)
658 (defcustom org-archive-stamp-time t
659 "Non-nil means, add a time stamp to entries moved to an archive file.
660 The time stamp will be added directly after the TODO state keyword in the
661 first line, so it is probably best to use this in combinations with
662 `org-archive-mark-done'."
663 :group 'org-archive
664 :type 'boolean)
666 (defgroup org-table nil
667 "Options concerning tables in Org-mode."
668 :tag "Org Table"
669 :group 'org)
671 (defcustom org-enable-table-editor 'optimized
672 "Non-nil means, lines starting with \"|\" are handled by the table editor.
673 When nil, such lines will be treated like ordinary lines.
675 When equal to the symbol `optimized', the table editor will be optimized to
676 do the following:
677 - Automatic overwrite mode in front of whitespace in table fields.
678 This makes the structure of the table stay in tact as long as the edited
679 field does not exceed the column width.
680 - Minimize the number of realigns. Normally, the table is aligned each time
681 TAB or RET are pressed to move to another field. With optimization this
682 happens only if changes to a field might have changed the column width.
683 Optimization requires replacing the functions `self-insert-command',
684 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
685 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
686 very good at guessing when a re-align will be necessary, but you can always
687 force one with \\[org-ctrl-c-ctrl-c].
689 If you would like to use the optimized version in Org-mode, but the
690 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
692 This variable can be used to turn on and off the table editor during a session,
693 but in order to toggle optimization, a restart is required.
695 See also the variable `org-table-auto-blank-field'."
696 :group 'org-table
697 :type '(choice
698 (const :tag "off" nil)
699 (const :tag "on" t)
700 (const :tag "on, optimized" optimized)))
702 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
703 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
704 In the optimized version, the table editor takes over all simple keys that
705 normally just insert a character. In tables, the characters are inserted
706 in a way to minimize disturbing the table structure (i.e. in overwrite mode
707 for empty fields). Outside tables, the correct binding of the keys is
708 restored.
710 The default for this option is t if the optimized version is also used in
711 Org-mode. See the variable `org-enable-table-editor' for details. Changing
712 this variable requires a restart of Emacs to become effective."
713 :group 'org-table
714 :type 'boolean)
716 (defcustom orgtbl-radio-table-templates
717 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
718 % END RECEIVE ORGTBL %n
719 \\begin{comment}
720 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
721 | | |
722 \\end{comment}\n")
723 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
724 @c END RECEIVE ORGTBL %n
725 @ignore
726 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
727 | | |
728 @end ignore\n")
729 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
730 <!-- END RECEIVE ORGTBL %n -->
731 <!--
732 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
733 | | |
734 -->\n"))
735 "Templates for radio tables in different major modes.
736 All occurrences of %n in a template will be replaced with the name of the
737 table, obtained by prompting the user."
738 :group 'org-table
739 :type '(repeat
740 (list (symbol :tag "Major mode")
741 (string :tag "Format"))))
743 (defgroup org-table-settings nil
744 "Settings for tables in Org-mode."
745 :tag "Org Table Settings"
746 :group 'org-table)
748 (defcustom org-table-default-size "5x2"
749 "The default size for newly created tables, Columns x Rows."
750 :group 'org-table-settings
751 :type 'string)
753 (defcustom org-table-number-regexp
754 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$"
755 "Regular expression for recognizing numbers in table columns.
756 If a table column contains mostly numbers, it will be aligned to the
757 right. If not, it will be aligned to the left.
759 The default value of this option is a regular expression which allows
760 anything which looks remotely like a number as used in scientific
761 context. For example, all of the following will be considered a
762 number:
763 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
765 Other options offered by the customize interface are more restrictive."
766 :group 'org-table-settings
767 :type '(choice
768 (const :tag "Positive Integers"
769 "^[0-9]+$")
770 (const :tag "Integers"
771 "^[-+]?[0-9]+$")
772 (const :tag "Floating Point Numbers"
773 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
774 (const :tag "Floating Point Number or Integer"
775 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
776 (const :tag "Exponential, Floating point, Integer"
777 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
778 (const :tag "Very General Number-Like, including hex"
779 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$")
780 (string :tag "Regexp:")))
782 (defcustom org-table-number-fraction 0.5
783 "Fraction of numbers in a column required to make the column align right.
784 In a column all non-white fields are considered. If at least this
785 fraction of fields is matched by `org-table-number-fraction',
786 alignment to the right border applies."
787 :group 'org-table-settings
788 :type 'number)
790 (defgroup org-table-editing nil
791 "Bahavior of tables during editing in Org-mode."
792 :tag "Org Table Editing"
793 :group 'org-table)
795 (defcustom org-table-automatic-realign t
796 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
797 When nil, aligning is only done with \\[org-table-align], or after column
798 removal/insertion."
799 :group 'org-table-editing
800 :type 'boolean)
802 (defcustom org-table-auto-blank-field t
803 "Non-nil means, automatically blank table field when starting to type into it.
804 This only happens when typing immediately after a field motion
805 command (TAB, S-TAB or RET).
806 Only relevant when `org-enable-table-editor' is equal to `optimized'."
807 :group 'org-table-editing
808 :type 'boolean)
810 (defcustom org-table-tab-jumps-over-hlines t
811 "Non-nil means, tab in the last column of a table with jump over a hline.
812 If a horizontal separator line is following the current line,
813 `org-table-next-field' can either create a new row before that line, or jump
814 over the line. When this option is nil, a new line will be created before
815 this line."
816 :group 'org-table-editing
817 :type 'boolean)
819 (defcustom org-table-tab-recognizes-table.el t
820 "Non-nil means, TAB will automatically notice a table.el table.
821 When it sees such a table, it moves point into it and - if necessary -
822 calls `table-recognize-table'."
823 :group 'org-table-editing
824 :type 'boolean)
826 (defgroup org-table-calculation nil
827 "Options concerning tables in Org-mode."
828 :tag "Org Table Calculation"
829 :group 'org-table)
831 (defcustom org-table-use-standard-references t
832 "Should org-mode work with table refrences like B3 instead of @3$2?
833 Possible values are:
834 nil never use them
835 from accept as input, do not present for editing
836 t: accept as input and present for editing"
837 :group 'org-table-calculation
838 :type '(choice
839 (const :tag "Never, don't even check unser input for them" nil)
840 (const :tag "Always, both as user input, and when editing" t)
841 (const :tag "Convert user input, don't offer during editing" 'from)))
843 (defcustom org-table-copy-increment t
844 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
845 :group 'org-table-calculation
846 :type 'boolean)
848 (defcustom org-calc-default-modes
849 '(calc-internal-prec 12
850 calc-float-format (float 5)
851 calc-angle-mode deg
852 calc-prefer-frac nil
853 calc-symbolic-mode nil
854 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
855 calc-display-working-message t
857 "List with Calc mode settings for use in calc-eval for table formulas.
858 The list must contain alternating symbols (Calc modes variables and values).
859 Don't remove any of the default settings, just change the values. Org-mode
860 relies on the variables to be present in the list."
861 :group 'org-table-calculation
862 :type 'plist)
864 (defcustom org-table-formula-evaluate-inline t
865 "Non-nil means, TAB and RET evaluate a formula in current table field.
866 If the current field starts with an equal sign, it is assumed to be a formula
867 which should be evaluated as described in the manual and in the documentation
868 string of the command `org-table-eval-formula'. This feature requires the
869 Emacs calc package.
870 When this variable is nil, formula calculation is only available through
871 the command \\[org-table-eval-formula]."
872 :group 'org-table-calculation
873 :type 'boolean)
875 (defcustom org-table-formula-use-constants t
876 "Non-nil means, interpret constants in formulas in tables.
877 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
878 by the value given in `org-table-formula-constants', or by a value obtained
879 from the `constants.el' package."
880 :group 'org-table-calculation
881 :type 'boolean)
883 ;; FIXME this is also a variable that makes Org-mode files non-portable
884 ;; Maybe I should have a #+ options for constants?
885 (defcustom org-table-formula-constants nil
886 "Alist with constant names and values, for use in table formulas.
887 The car of each element is a name of a constant, without the `$' before it.
888 The cdr is the value as a string. For example, if you'd like to use the
889 speed of light in a formula, you would configure
891 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
893 and then use it in an equation like `$1*$c'."
894 :group 'org-table-calculation
895 :type '(repeat
896 (cons (string :tag "name")
897 (string :tag "value"))))
899 (defcustom org-table-allow-automatic-line-recalculation t
900 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
901 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
902 :group 'org-table-calculation
903 :type 'boolean)
905 (defgroup org-link nil
906 "Options concerning links in Org-mode."
907 :tag "Org Link"
908 :group 'org)
910 (defvar org-link-abbrev-alist-local nil
911 "Buffer-local version of `org-link-abbrev-alist', which see.
912 The value of this is taken from the #+LINK lines.")
913 (make-variable-buffer-local 'org-link-abbrev-alist-local)
915 (defcustom org-link-abbrev-alist nil
916 "Alist of link abbreviations.
917 The car of each element is a string, to be replaced at the start of a link.
918 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
919 links in Org-mode buffers can have an optional tag after a double colon, e.g.
921 [[linkkey:tag][description]]
923 If REPLACE is a string, the tag will simply be appended to create the link.
924 If the string contains \"%s\", the tag will be inserted there. REPLACE may
925 also be a function that will be called with the tag as the only argument to
926 create the link. See the manual for examples."
927 :group 'org-link
928 :type 'alist)
930 (defcustom org-descriptive-links t
931 "Non-nil means, hide link part and only show description of bracket links.
932 Bracket links are like [[link][descritpion]]. This variable sets the initial
933 state in new org-mode buffers. The setting can then be toggled on a
934 per-buffer basis from the Org->Hyperlinks menu."
935 :group 'org-link
936 :type 'boolean)
938 (defcustom org-link-file-path-type 'adaptive
939 "How the path name in file links should be stored.
940 Valid values are:
942 relative relative to the current directory, i.e. the directory of the file
943 into which the link is being inserted.
944 absolute absolute path, if possible with ~ for home directory.
945 noabbrev absolute path, no abbreviation of home directory.
946 adaptive Use relative path for files in the current directory and sub-
947 directories of it. For other files, use an absolute path."
948 :group 'org-link
949 :type '(choice
950 (const relative)
951 (const absolute)
952 (const noabbrev)
953 (const adaptive)))
955 (defcustom org-activate-links '(bracket angle plain radio tag date)
956 "Types of links that should be activated in Org-mode files.
957 This is a list of symbols, each leading to the activation of a certain link
958 type. In principle, it does not hurt to turn on most link types - there may
959 be a small gain when turning off unused link types. The types are:
961 bracket The recommended [[link][description]] or [[link]] links with hiding.
962 angular Links in angular brackes that may contain whitespace like
963 <bbdb:Carsten Dominik>.
964 plain Plain links in normal text, no whitespace, like http://google.com.
965 radio Text that is matched by a radio target, see manual for details.
966 tag Tag settings in a headline (link to tag search).
967 date Time stamps (link to calendar).
969 Changing this variable requires a restart of Emacs to become effective."
970 :group 'org-link
971 :type '(set (const :tag "Double bracket links (new style)" bracket)
972 (const :tag "Angular bracket links (old style)" angular)
973 (const :tag "plain text links" plain)
974 (const :tag "Radio target matches" radio)
975 (const :tag "Tags" tag)
976 (const :tag "Tags" target)
977 (const :tag "Timestamps" date)))
979 (defgroup org-link-store nil
980 "Options concerning storing links in Org-mode"
981 :tag "Org Store Link"
982 :group 'org-link)
984 (defcustom org-email-link-description-format "Email %c: %.30s"
985 "Format of the description part of a link to an email or usenet message.
986 The following %-excapes will be replaced by corresponding information:
988 %F full \"From\" field
989 %f name, taken from \"From\" field, address if no name
990 %T full \"To\" field
991 %t first name in \"To\" field, address if no name
992 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
993 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
994 %s subject
995 %m message-id.
997 You may use normal field width specification between the % and the letter.
998 This is for example useful to limit the length of the subject.
1000 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1001 :group 'org-link-store
1002 :type 'string)
1004 (defcustom org-from-is-user-regexp
1005 (let (r1 r2)
1006 (when (and user-mail-address (not (string= user-mail-address "")))
1007 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1008 (when (and user-full-name (not (string= user-full-name "")))
1009 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1010 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1011 "Regexp mached against the \"From:\" header of an email or usenet message.
1012 It should match if the message is from the user him/herself."
1013 :group 'org-link-store
1014 :type 'regexp)
1016 (defcustom org-context-in-file-links t
1017 "Non-nil means, file links from `org-store-link' contain context.
1018 A search string will be added to the file name with :: as separator and
1019 used to find the context when the link is activated by the command
1020 `org-open-at-point'.
1021 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1022 negates this setting for the duration of the command."
1023 :group 'org-link-store
1024 :type 'boolean)
1026 (defcustom org-keep-stored-link-after-insertion nil
1027 "Non-nil means, keep link in list for entire session.
1029 The command `org-store-link' adds a link pointing to the current
1030 location to an internal list. These links accumulate during a session.
1031 The command `org-insert-link' can be used to insert links into any
1032 Org-mode file (offering completion for all stored links). When this
1033 option is nil, every link which has been inserted once using \\[org-insert-link]
1034 will be removed from the list, to make completing the unused links
1035 more efficient."
1036 :group 'org-link-store
1037 :type 'boolean)
1039 (defcustom org-usenet-links-prefer-google nil
1040 "Non-nil means, `org-store-link' will create web links to Google groups.
1041 When nil, Gnus will be used for such links.
1042 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1043 negates this setting for the duration of the command."
1044 :group 'org-link-store
1045 :type 'boolean)
1047 (defgroup org-link-follow nil
1048 "Options concerning following links in Org-mode"
1049 :tag "Org Follow Link"
1050 :group 'org-link)
1052 (defcustom org-tab-follows-link nil
1053 "Non-nil means, on links TAB 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-return-follows-link nil
1059 "Non-nil means, on links RET will follow the link.
1060 Needs to be set before org.el is loaded."
1061 :group 'org-link-follow
1062 :type 'boolean)
1064 (defcustom org-mouse-1-follows-link t
1065 "Non-nil means, mouse-1 on a link will follow the link.
1066 A longer mouse click will still set point. Does not wortk on XEmacs.
1067 Needs to be set before org.el is loaded."
1068 :group 'org-link-follow
1069 :type 'boolean)
1071 (defcustom org-mark-ring-length 4
1072 "Number of different positions to be recorded in the ring
1073 Changing this requires a restart of Emacs to work correctly."
1074 :group 'org-link-follow
1075 :type 'interger)
1077 (defcustom org-link-frame-setup
1078 '((vm . vm-visit-folder-other-frame)
1079 (gnus . gnus-other-frame)
1080 (file . find-file-other-window))
1081 "Setup the frame configuration for following links.
1082 When following a link with Emacs, it may often be useful to display
1083 this link in another window or frame. This variable can be used to
1084 set this up for the different types of links.
1085 For VM, use any of
1086 `vm-visit-folder'
1087 `vm-visit-folder-other-frame'
1088 For Gnus, use any of
1089 `gnus'
1090 `gnus-other-frame'
1091 For FILE, use any of
1092 `find-file'
1093 `find-file-other-window'
1094 `find-file-other-frame'
1095 For the calendar, use the variable `calendar-setup'.
1096 For BBDB, it is currently only possible to display the matches in
1097 another window."
1098 :group 'org-link-follow
1099 :type '(list
1100 (cons (const vm)
1101 (choice
1102 (const vm-visit-folder)
1103 (const vm-visit-folder-other-window)
1104 (const vm-visit-folder-other-frame)))
1105 (cons (const gnus)
1106 (choice
1107 (const gnus)
1108 (const gnus-other-frame)))
1109 (cons (const file)
1110 (choice
1111 (const find-file)
1112 (const find-file-other-window)
1113 (const find-file-other-frame)))))
1115 (defcustom org-display-internal-link-with-indirect-buffer nil
1116 "Non-nil means, use indirect buffer to display infile links.
1117 Activating internal links (from one location in a file to another location
1118 in the same file) normally just jumps to the location. When the link is
1119 activated with a C-u prefix (or with mouse-3), the link is displayed in
1120 another window. When this option is set, the other window actually displays
1121 an indirect buffer clone of the current buffer, to avoid any visibility
1122 changes to the current buffer."
1123 :group 'org-link-follow
1124 :type 'boolean)
1126 (defcustom org-open-non-existing-files nil
1127 "Non-nil means, `org-open-file' will open non-existing files.
1128 When nil, an error will be generated."
1129 :group 'org-link-follow
1130 :type 'boolean)
1132 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1133 "Function and arguments to call for following mailto links.
1134 This is a list with the first element being a lisp function, and the
1135 remaining elements being arguments to the function. In string arguments,
1136 %a will be replaced by the address, and %s will be replaced by the subject
1137 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1138 :group 'org-link-follow
1139 :type '(choice
1140 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1141 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1142 (const :tag "message-mail" (message-mail "%a" "%s"))
1143 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1145 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1146 "Non-nil means, ask for confirmation before executing shell links.
1147 Shell links can be dangerous, just thing about a link
1149 [[shell:rm -rf ~/*][Google Search]]
1151 This link would show up in your Org-mode document as \"Google Search\"
1152 but really it would remove your entire home directory.
1153 Therefore I *definitely* advise against setting this variable to nil.
1154 Just change it to `y-or-n-p' of you want to confirm with a single key press
1155 rather than having to type \"yes\"."
1156 :group 'org-link-follow
1157 :type '(choice
1158 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1159 (const :tag "with y-or-n (faster)" y-or-n-p)
1160 (const :tag "no confirmation (dangerous)" nil)))
1162 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1163 "Non-nil means, ask for confirmation before executing elisp links.
1164 Elisp links can be dangerous, just think about a link
1166 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1168 This link would show up in your Org-mode document as \"Google Search\"
1169 but really it would remove your entire home directory.
1170 Therefore I *definitely* advise against setting this variable to nil.
1171 Just change it to `y-or-n-p' of you want to confirm with a single key press
1172 rather than having to type \"yes\"."
1173 :group 'org-link-follow
1174 :type '(choice
1175 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1176 (const :tag "with y-or-n (faster)" y-or-n-p)
1177 (const :tag "no confirmation (dangerous)" nil)))
1179 (defconst org-file-apps-defaults-gnu
1180 '((remote . emacs)
1181 (t . mailcap))
1182 "Default file applications on a UNIX or GNU/Linux system.
1183 See `org-file-apps'.")
1185 (defconst org-file-apps-defaults-macosx
1186 '((remote . emacs)
1187 (t . "open %s")
1188 ("ps" . "gv %s")
1189 ("ps.gz" . "gv %s")
1190 ("eps" . "gv %s")
1191 ("eps.gz" . "gv %s")
1192 ("dvi" . "xdvi %s")
1193 ("fig" . "xfig %s"))
1194 "Default file applications on a MacOS X system.
1195 The system \"open\" is known as a default, but we use X11 applications
1196 for some files for which the OS does not have a good default.
1197 See `org-file-apps'.")
1199 (defconst org-file-apps-defaults-windowsnt
1200 (list
1201 '(remote . emacs)
1202 (cons t
1203 (list (if (featurep 'xemacs)
1204 'mswindows-shell-execute
1205 'w32-shell-execute)
1206 "open" 'file)))
1207 "Default file applications on a Windows NT system.
1208 The system \"open\" is used for most files.
1209 See `org-file-apps'.")
1211 (defcustom org-file-apps
1213 ("txt" . emacs)
1214 ("tex" . emacs)
1215 ("ltx" . emacs)
1216 ("org" . emacs)
1217 ("el" . emacs)
1218 ("bib" . emacs)
1220 "External applications for opening `file:path' items in a document.
1221 Org-mode uses system defaults for different file types, but
1222 you can use this variable to set the application for a given file
1223 extension. The entries in this list are cons cells where the car identifies
1224 files and the cdr the corresponding command. Possible values for the
1225 file identifier are
1226 \"ext\" A string identifying an extension
1227 `directory' Matches a directory
1228 `remote' Matches a remote file, accessible through tramp or efs.
1229 Remote files most likely should be visited through Emacs
1230 because external applications cannot handle such paths.
1231 t Default for all remaining files
1233 Possible values for the command are:
1234 `emacs' The file will be visited by the current Emacs process.
1235 `default' Use the default application for this file type.
1236 string A command to be executed by a shell; %s will be replaced
1237 by the path to the file.
1238 sexp A Lisp form which will be evaluated. The file path will
1239 be available in the Lisp variable `file'.
1240 For more examples, see the system specific constants
1241 `org-file-apps-defaults-macosx'
1242 `org-file-apps-defaults-windowsnt'
1243 `org-file-apps-defaults-gnu'."
1244 :group 'org-link-follow
1245 :type '(repeat
1246 (cons (choice :value ""
1247 (string :tag "Extension")
1248 (const :tag "Default for unrecognized files" t)
1249 (const :tag "Remote file" remote)
1250 (const :tag "Links to a directory" directory))
1251 (choice :value ""
1252 (const :tag "Visit with Emacs" emacs)
1253 (const :tag "Use system default" default)
1254 (string :tag "Command")
1255 (sexp :tag "Lisp form")))))
1257 (defcustom org-mhe-search-all-folders nil
1258 "Non-nil means, that the search for the mh-message will be extended to
1259 all folders if the message cannot be found in the folder given in the link.
1260 Searching all folders is very efficient with one of the search engines
1261 supported by MH-E, but will be slow with pick."
1262 :group 'org-link-follow
1263 :type 'boolean)
1265 (defgroup org-remember nil
1266 "Options concerning interaction with remember.el."
1267 :tag "Org Remember"
1268 :group 'org)
1270 (defcustom org-directory "~/org"
1271 "Directory with org files.
1272 This directory will be used as default to prompt for org files.
1273 Used by the hooks for remember.el."
1274 :group 'org-remember
1275 :type 'directory)
1277 (defcustom org-default-notes-file "~/.notes"
1278 "Default target for storing notes.
1279 Used by the hooks for remember.el. This can be a string, or nil to mean
1280 the value of `remember-data-file'.
1281 You can set this on a per-template basis with the variable
1282 `org-remember-templates'."
1283 :group 'org-remember
1284 :type '(choice
1285 (const :tag "Default from remember-data-file" nil)
1286 file))
1288 (defcustom org-remember-default-headline ""
1289 "The headline that should be the default location in the notes file.
1290 When filing remember notes, the cursor will start at that position.
1291 You can set this on a per-template basis with the variable
1292 `org-remember-templates'."
1293 :group 'org-remember
1294 :type 'string)
1296 (defcustom org-remember-templates nil
1297 "Templates for the creation of remember buffers.
1298 When nil, just let remember make the buffer.
1299 When not nil, this is a list of 4-element lists. In each entry, the first
1300 element is a character, a unique key to select this template.
1301 The second element is the template. The third element is optional and can
1302 specify a destination file for remember items created with this template.
1303 The default file is given by `org-default-notes-file'. An optional third
1304 element can specify the headline in that file that should be offered
1305 first when the user is asked to file the entry. The default headline is
1306 given in the variable `org-remember-default-headline'.
1308 The template specifies the structure of the remember buffer. It should have
1309 a first line starting with a star, to act as the org-mode headline.
1310 Furthermore, the following %-escapes will be replaced with content:
1312 %^{prompt} prompt the user for a string and replace this sequence with it.
1313 %t time stamp, date only
1314 %T time stamp with date and time
1315 %u, %U like the above, but inactive time stamps
1316 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1317 You may define a prompt like %^{Please specify birthday}t
1318 %n user name (taken from `user-full-name')
1319 %a annotation, normally the link created with org-store-link
1320 %i initial content, the region when remember is called with C-u.
1321 If %i is indented, the entire inserted text will be indented
1322 as well.
1324 %? After completing the template, position cursor here.
1326 Apart from these general escapes, you can access information specific to the
1327 link type that is created. For example, calling `remember' in emails or gnus
1328 will record the author and the subject of the message, which you can access
1329 with %:author and %:subject, respectively. Here is a complete list of what
1330 is recorded for each link type.
1332 Link type | Available information
1333 -------------------+------------------------------------------------------
1334 bbdb | %:type %:name %:company
1335 vm, wl, mh, rmail | %:type %:subject %:message-id
1336 | %:from %:fromname %:fromaddress
1337 | %:to %:toname %:toaddress
1338 | %:fromto (either \"to NAME\" or \"from NAME\")
1339 gnus | %:group, for messages also all email fields
1340 w3, w3m | %:type %:url
1341 info | %:type %:file %:node
1342 calendar | %:type %:date"
1343 :group 'org-remember
1344 :get (lambda (var) ; Make sure all entries have 4 elements
1345 (mapcar (lambda (x)
1346 (cond ((= (length x) 3) (append x '("")))
1347 ((= (length x) 2) (append x '("" "")))
1348 (t x)))
1349 (default-value var)))
1350 :type '(repeat
1351 :tag "enabled"
1352 (list :value (?a "\n" nil nil)
1353 (character :tag "Selection Key")
1354 (string :tag "Template")
1355 (file :tag "Destination file (optional)")
1356 (string :tag "Destination headline (optional)"))))
1358 (defcustom org-reverse-note-order nil
1359 "Non-nil means, store new notes at the beginning of a file or entry.
1360 When nil, new notes will be filed to the end of a file or entry."
1361 :group 'org-remember
1362 :type '(choice
1363 (const :tag "Reverse always" t)
1364 (const :tag "Reverse never" nil)
1365 (repeat :tag "By file name regexp"
1366 (cons regexp boolean))))
1368 (defgroup org-todo nil
1369 "Options concerning TODO items in Org-mode."
1370 :tag "Org TODO"
1371 :group 'org)
1373 (defgroup org-progress nil
1374 "Options concerning Progress logging in Org-mode."
1375 :tag "Org Progress"
1376 :group 'org-time)
1378 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1379 "List of TODO entry keyword sequences and their interpretation.
1380 \\<org-mode-map>This is a list of sequences.
1382 Each sequence starts with a symbol, either `sequence' or `type',
1383 indicating if the keywords should be interpreted as a sequence of
1384 action steps, or as different types of TODO items. The first
1385 keywords are states requiring action - these states will select a headline
1386 for inclusion into the global TODO list Org-mode produces. If one of
1387 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1388 signify that no further action is necessary. If \"|\" is not found,
1389 the last keyword is treated as the only DONE state of the sequence.
1391 The command \\[org-todo] cycles an entry through these states, and one
1392 additional state where no keyword is present. For details about this
1393 cycling, see the manual.
1395 TODO keywords and interpretation can also be set on a per-file basis with
1396 the special #+SEQ_TODO and #+TYP_TODO lines.
1398 For backward compatibility, this variable may also be just a list
1399 of keywords - in this case the interptetation (sequence or type) will be
1400 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1401 :group 'org-todo
1402 :group 'org-keywords
1403 :type '(choice
1404 (repeat :tag "Old syntax, just keywords"
1405 (string :tag "Keyword"))
1406 (repeat :tag "New syntax"
1407 (cons
1408 (choice
1409 :tag "Interpretation"
1410 (const :tag "Sequence (cycling hits every state)" sequence)
1411 (const :tag "Type (cycling directly to DONE)" type))
1412 (repeat
1413 (string :tag "Keyword"))))))
1415 (defvar org-todo-keywords-1 nil)
1416 (make-variable-buffer-local 'org-todo-keywords-1)
1417 (defvar org-todo-keywords-for-agenda nil)
1418 (defvar org-done-keywords-for-agenda nil)
1419 (defvar org-not-done-keywords nil)
1420 (make-variable-buffer-local 'org-not-done-keywords)
1421 (defvar org-done-keywords nil)
1422 (make-variable-buffer-local 'org-done-keywords)
1423 (defvar org-todo-heads nil)
1424 (make-variable-buffer-local 'org-todo-heads)
1425 (defvar org-todo-sets nil)
1426 (make-variable-buffer-local 'org-todo-sets)
1427 (defvar org-todo-kwd-alist nil)
1428 (make-variable-buffer-local 'org-todo-kwd-alist)
1430 (defcustom org-todo-interpretation 'sequence
1431 "Controls how TODO keywords are interpreted.
1432 This variable is in principle obsolete and is only used for
1433 backward compatibility, if the interpretation of todo keywords is
1434 not given already in `org-todo-keywords'. See that variable for
1435 more information."
1436 :group 'org-todo
1437 :group 'org-keywords
1438 :type '(choice (const sequence)
1439 (const type)))
1441 (defcustom org-after-todo-state-change-hook nil
1442 "Hook which is run after the state of a TODO item was changed.
1443 The new state (a string with a TODO keyword, or nil) is available in the
1444 Lisp variable `state'."
1445 :group 'org-todo
1446 :type 'hook)
1448 (defcustom org-log-done nil
1449 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1450 When the state of an entry is changed from nothing to TODO, remove a previous
1451 closing date.
1453 This can also be a list of symbols indicating under which conditions
1454 the time stamp recording the action should be annotated with a short note.
1455 Valid members of this list are
1457 done Offer to record a note when marking entries done
1458 state Offer to record a note whenever changing the TODO state
1459 of an item. This is only relevant if TODO keywords are
1460 interpreted as sequence, see variable `org-todo-interpretation'.
1461 When `state' is set, this includes tracking `done'.
1462 clock-out Offer to record a note when clocking out of an item.
1464 A separate window will then pop up and allow you to type a note.
1465 After finishing with C-c C-c, the note will be added directly after the
1466 timestamp, as a plain list item. See also the variable
1467 `org-log-note-headings'.
1469 Logging can also be configured on a per-file basis by adding one of
1470 the following lines anywhere in the buffer:
1472 #+STARTUP: logdone
1473 #+STARTUP: nologging
1474 #+STARTUP: lognotedone
1475 #+STARTUP: lognotestate
1476 #+STARTUP: lognoteclock-out"
1477 :group 'org-todo
1478 :group 'org-progress
1479 :type '(choice
1480 (const :tag "off" nil)
1481 (const :tag "on" t)
1482 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1483 (const :tag "when item is marked DONE" done)
1484 (const :tag "when TODO state changes" state)
1485 (const :tag "when clocking out" clock-out))))
1487 (defcustom org-log-done-with-time t
1488 "Non-nil means, the CLOSED time stamp will contain date and time.
1489 When nil, only the date will be recorded."
1490 :group 'org-progress
1491 :type 'boolean)
1493 (defcustom org-log-note-headings
1494 '((done . "CLOSING NOTE %t")
1495 (state . "State %-12s %t")
1496 (clock-out . ""))
1497 "Headings for notes added when clocking out or closing TODO items.
1498 The value is an alist, with the car being a sympol indicating the note
1499 context, and the cdr is the heading to be used. The heading may also be the
1500 empty string.
1501 %t in the heading will be replaced by a time stamp.
1502 %s will be replaced by the new TODO state, in double quotes.
1503 %u will be replaced by the user name.
1504 %U will be replaced by the full user name."
1505 :group 'org-todo
1506 :group 'org-progress
1507 :type '(list :greedy t
1508 (cons (const :tag "Heading when closing an item" done) string)
1509 (cons (const :tag
1510 "Heading when changing todo state (todo sequence only)"
1511 state) string)
1512 (cons (const :tag "Heading when clocking out" clock-out) string)))
1514 (defcustom org-log-repeat t
1515 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1516 When nil, no note will be taken."
1517 :group 'org-todo
1518 :group 'org-progress
1519 :type 'boolean)
1521 (defgroup org-priorities nil
1522 "Priorities in Org-mode."
1523 :tag "Org Priorities"
1524 :group 'org-todo)
1526 (defcustom org-highest-priority ?A
1527 "The highest priority of TODO items. A character like ?A, ?B etc.
1528 Must have a smaller ASCII number than `org-lowest-priority'."
1529 :group 'org-priorities
1530 :type 'character)
1532 (defcustom org-lowest-priority ?C
1533 "The lowest priority of TODO items. A character like ?A, ?B etc.
1534 Must have a larger ASCII number than `org-highest-priority'."
1535 :group 'org-priorities
1536 :type 'character)
1538 (defcustom org-default-priority ?B
1539 "The default priority of TODO items.
1540 This is the priority an item get if no explicit priority is given."
1541 :group 'org-priorities
1542 :type 'character)
1544 (defgroup org-time nil
1545 "Options concerning time stamps and deadlines in Org-mode."
1546 :tag "Org Time"
1547 :group 'org)
1549 (defcustom org-insert-labeled-timestamps-at-point nil
1550 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1551 When nil, these labeled time stamps are forces into the second line of an
1552 entry, just after the headline. When scheduling from the global TODO list,
1553 the time stamp will always be forced into the second line."
1554 :group 'org-time
1555 :type 'boolean)
1557 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1558 "Formats for `format-time-string' which are used for time stamps.
1559 It is not recommended to change this constant.")
1561 (defcustom org-time-stamp-rounding-minutes 0
1562 "Number of minutes to round time stamps to upon insertion.
1563 When zero, insert the time unmodified. Useful rounding numbers
1564 should be factors of 60, so for example 5, 10, 15.
1565 When this is not zero, you can still force an exact time-stamp by using
1566 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1567 :group 'org-time
1568 :type 'integer)
1570 (defcustom org-display-custom-times nil
1571 "Non-nil means, overlay custom formats over all time stamps.
1572 The formats are defined through the variable `org-time-stamp-custom-formats'.
1573 To turn this on on a per-file basis, insert anywhere in the file:
1574 #+STARTUP: customtime"
1575 :group 'org-time
1576 :set 'set-default
1577 :type 'sexp)
1578 (make-variable-buffer-local 'org-display-custom-times)
1580 (defcustom org-time-stamp-custom-formats
1581 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1582 "Custom formats for time stamps. See `format-time-string' for the syntax.
1583 These are overlayed over the default ISO format if the variable
1584 `org-display-custom-times' is set. Time like %H:%M should be at the
1585 end of the second format."
1586 :group 'org-time
1587 :type 'sexp)
1589 (defun org-time-stamp-format (&optional long inactive)
1590 "Get the right format for a time string."
1591 (let ((f (if long (cdr org-time-stamp-formats)
1592 (car org-time-stamp-formats))))
1593 (if inactive
1594 (concat "[" (substring f 1 -1) "]")
1595 f)))
1597 (defcustom org-deadline-warning-days 30
1598 "No. of days before expiration during which a deadline becomes active.
1599 This variable governs the display in sparse trees and in the agenda."
1600 :group 'org-time
1601 :type 'number)
1603 (defcustom org-popup-calendar-for-date-prompt t
1604 "Non-nil means, pop up a calendar when prompting for a date.
1605 In the calendar, the date can be selected with mouse-1. However, the
1606 minibuffer will also be active, and you can simply enter the date as well.
1607 When nil, only the minibuffer will be available."
1608 :group 'org-time
1609 :type 'boolean)
1611 (defcustom org-calendar-follow-timestamp-change t
1612 "Non-nil means, make the calendar window follow timestamp changes.
1613 When a timestamp is modified and the calendar window is visible, it will be
1614 moved to the new date."
1615 :group 'org-time
1616 :type 'boolean)
1618 (defgroup org-tags nil
1619 "Options concerning tags in Org-mode."
1620 :tag "Org Tags"
1621 :group 'org)
1623 (defcustom org-tag-alist nil
1624 "List of tags allowed in Org-mode files.
1625 When this list is nil, Org-mode will base TAG input on what is already in the
1626 buffer.
1627 The value of this variable is an alist, the car may be (and should) be a
1628 character that is used to select that tag through the fast-tag-selection
1629 interface. See the manual for details."
1630 :group 'org-tags
1631 :type '(repeat
1632 (choice
1633 (cons (string :tag "Tag name")
1634 (character :tag "Access char"))
1635 (const :tag "Start radio group" (:startgroup))
1636 (const :tag "End radio group" (:endgroup)))))
1638 (defcustom org-use-fast-tag-selection 'auto
1639 "Non-nil means, use fast tag selection scheme.
1640 This is a special interface to select and deselect tags with single keys.
1641 When nil, fast selection is never used.
1642 When the symbol `auto', fast selection is used if and only if selection
1643 characters for tags have been configured, either through the variable
1644 `org-tag-alist' or through a #+TAGS line in the buffer.
1645 When t, fast selection is always used and selection keys are assigned
1646 automatically if necessary."
1647 :group 'org-tags
1648 :type '(choice
1649 (const :tag "Always" t)
1650 (const :tag "Never" nil)
1651 (const :tag "When selection characters are configured" 'auto)))
1653 (defcustom org-fast-tag-selection-single-key nil
1654 "Non-nil means, fast tag selection exits after first change.
1655 When nil, you have to press RET to exit it.
1656 During fast tag selection, you can toggle this flag with `C-c'.
1657 This variable can also have the value `expert'. In this case, the window
1658 displaying the tags menu is not even shown, until you press C-c again."
1659 :group 'org-tags
1660 :type '(choice
1661 (const :tag "No" nil)
1662 (const :tag "Yes" t)
1663 (const :tag "Expert" expert)))
1665 (defcustom org-tags-column 48
1666 "The column to which tags should be indented in a headline.
1667 If this number is positive, it specifies the column. If it is negative,
1668 it means that the tags should be flushright to that column. For example,
1669 -79 works well for a normal 80 character screen."
1670 :group 'org-tags
1671 :type 'integer)
1673 (defcustom org-auto-align-tags t
1674 "Non-nil means, realign tags after pro/demotion of TODO state change.
1675 These operations change the length of a headline and therefore shift
1676 the tags around. With this options turned on, after each such operation
1677 the tags are again aligned to `org-tags-column'."
1678 :group 'org-tags
1679 :type 'boolean)
1681 (defcustom org-use-tag-inheritance t
1682 "Non-nil means, tags in levels apply also for sublevels.
1683 When nil, only the tags directly given in a specific line apply there.
1684 If you turn off this option, you very likely want to turn on the
1685 companion option `org-tags-match-list-sublevels'."
1686 :group 'org-tags
1687 :type 'boolean)
1689 (defcustom org-tags-match-list-sublevels nil
1690 "Non-nil means list also sublevels of headlines matching tag search.
1691 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1692 the sublevels of a headline matching a tag search often also match
1693 the same search. Listing all of them can create very long lists.
1694 Setting this variable to nil causes subtrees of a match to be skipped.
1695 This option is off by default, because inheritance in on. If you turn
1696 inheritance off, you very likely want to turn this option on.
1698 As a special case, if the tag search is restricted to TODO items, the
1699 value of this variable is ignored and sublevels are always checked, to
1700 make sure all corresponding TODO items find their way into the list."
1701 :group 'org-tags
1702 :type 'boolean)
1704 (defvar org-tags-history nil
1705 "History of minibuffer reads for tags.")
1706 (defvar org-last-tags-completion-table nil
1707 "The last used completion table for tags.")
1709 (defgroup org-agenda nil
1710 "Options concerning agenda views in Org-mode."
1711 :tag "Org Agenda"
1712 :group 'org)
1714 (defvar org-category nil
1715 "Variable used by org files to set a category for agenda display.
1716 Such files should use a file variable to set it, for example
1718 # -*- mode: org; org-category: \"ELisp\"
1720 or contain a special line
1722 #+CATEGORY: ELisp
1724 If the file does not specify a category, then file's base name
1725 is used instead.")
1726 (make-variable-buffer-local 'org-category)
1728 (defcustom org-agenda-files nil
1729 "The files to be used for agenda display.
1730 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1731 \\[org-remove-file]. You can also use customize to edit the list.
1733 If the value of the variable is not a list but a single file name, then
1734 the list of agenda files is actually stored and maintained in that file, one
1735 agenda file per line."
1736 :group 'org-agenda
1737 :type '(choice
1738 (repeat :tag "List of files" file)
1739 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1742 (defcustom org-agenda-confirm-kill 1
1743 "When set, remote killing from the agenda buffer needs confirmation.
1744 When t, a confirmation is always needed. When a number N, confirmation is
1745 only needed when the text to be killed contains more than N non-white lines."
1746 :group 'org-agenda
1747 :type '(choice
1748 (const :tag "Never" nil)
1749 (const :tag "Always" t)
1750 (number :tag "When more than N lines")))
1752 (defcustom org-calendar-to-agenda-key [?c]
1753 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1754 The command `org-calendar-goto-agenda' will be bound to this key. The
1755 default is the character `c' because then `c' can be used to switch back and
1756 forth between agenda and calendar."
1757 :group 'org-agenda
1758 :type 'sexp)
1760 (defgroup org-agenda-export nil
1761 "Options concerning exporting agenda views in Org-mode."
1762 :tag "Org Agenda Export"
1763 :group 'org-agenda)
1765 (defcustom org-agenda-with-colors t
1766 "Non-nil means, use colors in agenda views."
1767 :group 'org-agenda-export
1768 :type 'boolean)
1770 (defcustom org-agenda-exporter-settings nil
1771 "Alist of variable/value pairs that should be active during agenda export.
1772 This is a good place to set uptions for ps-print and for htmlize."
1773 :group 'org-agenda-export
1774 :type '(repeat
1775 (list
1776 (variable)
1777 (sexp :tag "Value"))))
1779 (defcustom org-agenda-export-html-style ""
1780 "The style specification for exported HTML Agenda files.
1781 If this variable contains a string, it will replace the default <style>
1782 section as produced by `htmlize'.
1783 Since there are different ways of setting style information, this variable
1784 needs to contain the full HTML structure to provide a style, including the
1785 surrounding HTML tags. The style specifications should include definitions
1786 the fonts used by the agenda, here is an example:
1788 <style type=\"text/css\">
1789 p { font-weight: normal; color: gray; }
1790 .org-agenda-structure {
1791 font-size: 110%;
1792 color: #003399;
1793 font-weight: 600;
1795 .org-todo {
1796 color: #cc6666;Week-agenda:
1797 font-weight: bold;
1799 .org-done {
1800 color: #339933;
1802 .title { text-align: center; }
1803 .todo, .deadline { color: red; }
1804 .done { color: green; }
1805 </style>
1807 or, if you want to keep the style in a file,
1809 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1811 As the value of this option simply gets inserted into the HTML <head> header,
1812 you can \"misuse\" it to also add other text to the header. However,
1813 <style>...</style> is required, if not present the variable will be ignored."
1814 :group 'org-agenda-export
1815 :group 'org-export-html
1816 :type 'string)
1818 (defgroup org-agenda-custom-commands nil
1819 "Options concerning agenda views in Org-mode."
1820 :tag "Org Agenda Custom Commands"
1821 :group 'org-agenda)
1823 (defcustom org-agenda-custom-commands nil
1824 "Custom commands for the agenda.
1825 These commands will be offered on the splash screen displayed by the
1826 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1828 (key type match options files)
1830 key The key (a single char as a string) to be associated with the command.
1831 type The command type, any of the following symbols:
1832 todo Entries with a specific TODO keyword, in all agenda files.
1833 tags Tags match in all agenda files.
1834 tags-todo Tags match in all agenda files, TODO entries only.
1835 todo-tree Sparse tree of specific TODO keyword in *current* file.
1836 tags-tree Sparse tree with all tags matches in *current* file.
1837 occur-tree Occur sparse tree for *current* file.
1838 match What to search for:
1839 - a single keyword for TODO keyword searches
1840 - a tags match expression for tags searches
1841 - a regular expression for occur searches
1842 options A list of option setttings, similar to that in a let form, so like
1843 this: ((opt1 val1) (opt2 val2) ...)
1844 files A list of files file to write the produced agenda buffer to
1845 with the command `org-store-agenda-views'.
1846 If a file name ends in \".html\", an HTML version of the buffer
1847 is written out. If it ends in \".ps\", a postscript version is
1848 produced. Otherwide, only the plain text is written to the file.
1850 You can also define a set of commands, to create a composite agenda buffer.
1851 In this case, an entry looks like this:
1853 (key desc (cmd1 cmd2 ...) general-options file)
1855 where
1857 desc A description string to be displayed in the dispatcher menu.
1858 cmd An agenda command, similar to the above. However, tree commands
1859 are no allowed, but instead you can get agenda and global todo list.
1860 So valid commands for a set are:
1861 (agenda)
1862 (alltodo)
1863 (stuck)
1864 (todo \"match\" options files)
1865 (tags \"match\" options files)
1866 (tags-todo \"match\" options files)
1868 Each command can carry a list of options, and another set of options can be
1869 given for the whole set of commands. Individual command options take
1870 precedence over the general options."
1871 :group 'org-agenda-custom-commands
1872 :type '(repeat
1873 (choice :value ("a" tags "" nil)
1874 (list :tag "Single command"
1875 (string :tag "Key")
1876 (choice
1877 (const :tag "Agenda" agenda)
1878 (const :tag "TODO list" alltodo)
1879 (const :tag "Stuck projects" stuck)
1880 (const :tag "Tags search (all agenda files)" tags)
1881 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1882 (const :tag "TODO keyword search (all agenda files)" todo)
1883 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1884 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1885 (const :tag "Occur tree (current buffer)" occur-tree)
1886 (symbol :tag "Other, user-defined function"))
1887 (string :tag "Match")
1888 (repeat :tag "Local options"
1889 (list (variable :tag "Option") (sexp :tag "Value")))
1890 (option (repeat :tag "Export" (file :tag "Export to"))))
1891 (list :tag "Command series, all agenda files"
1892 (string :tag "Key")
1893 (string :tag "Description")
1894 (repeat
1895 (choice
1896 (const :tag "Agenda" (agenda))
1897 (const :tag "TODO list" (alltodo))
1898 (const :tag "Stuck projects" (stuck))
1899 (list :tag "Tags search"
1900 (const :format "" tags)
1901 (string :tag "Match")
1902 (repeat :tag "Local options"
1903 (list (variable :tag "Option")
1904 (sexp :tag "Value"))))
1906 (list :tag "Tags search, TODO entries only"
1907 (const :format "" tags-todo)
1908 (string :tag "Match")
1909 (repeat :tag "Local options"
1910 (list (variable :tag "Option")
1911 (sexp :tag "Value"))))
1913 (list :tag "TODO keyword search"
1914 (const :format "" todo)
1915 (string :tag "Match")
1916 (repeat :tag "Local options"
1917 (list (variable :tag "Option")
1918 (sexp :tag "Value"))))
1920 (list :tag "Other, user-defined function"
1921 (symbol :tag "function")
1922 (string :tag "Match")
1923 (repeat :tag "Local options"
1924 (list (variable :tag "Option")
1925 (sexp :tag "Value"))))))
1927 (repeat :tag "General options"
1928 (list (variable :tag "Option")
1929 (sexp :tag "Value")))
1930 (option (repeat :tag "Export" (file :tag "Export to")))))))
1932 (defcustom org-stuck-projects
1933 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
1934 "How to identify stuck projects.
1935 This is a list of four items:
1936 1. A tags/todo matcher string that is used to identify a project.
1937 The entire tree below a headline matched by this is considered one project.
1938 2. A list of TODO keywords identifying non-stuck projects.
1939 If the project subtree contains any headline with one of these todo
1940 keywords, the project is considered to be not stuck. If you specify
1941 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
1942 3. A list of tags identifying non-stuck projects.
1943 If the project subtree contains any headline with one of these tags,
1944 the project is considered to be not stuck. If you specify \"*\" as
1945 a tag, any tag will mark the project unstuck.
1946 4. An arbitrary regular expression matching non-stuck projects.
1948 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1949 or `C-c a #' to produce the list."
1950 :group 'org-agenda-custom-commands
1951 :type '(list
1952 (string :tag "Tags/TODO match to identify a project")
1953 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1954 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
1955 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
1958 (defgroup org-agenda-skip nil
1959 "Options concerning skipping parts of agenda files."
1960 :tag "Org Agenda Skip"
1961 :group 'org-agenda)
1963 (defcustom org-agenda-todo-list-sublevels t
1964 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1965 When nil, the sublevels of a TODO entry are not checked, resulting in
1966 potentially much shorter TODO lists."
1967 :group 'org-agenda-skip
1968 :group 'org-todo
1969 :type 'boolean)
1971 (defcustom org-agenda-todo-ignore-scheduled nil
1972 "Non-nil means, don't show scheduled entries in the global todo list.
1973 The idea behind this is that by scheduling it, you have already taken care
1974 of this item."
1975 :group 'org-agenda-skip
1976 :group 'org-todo
1977 :type 'boolean)
1979 (defcustom org-agenda-todo-ignore-deadlines nil
1980 "Non-nil means, don't show near deadline entries in the global todo list.
1981 Near means closer than `org-deadline-warning-days' days.
1982 The idea behind this is that such items will appear in the agenda anyway."
1983 :group 'org-agenda-skip
1984 :group 'org-todo
1985 :type 'boolean)
1987 (defcustom org-agenda-skip-scheduled-if-done nil
1988 "Non-nil means don't show scheduled items in agenda when they are done.
1989 This is relevant for the daily/weekly agenda, not for the TODO list."
1990 :group 'org-agenda-skip
1991 :type 'boolean)
1993 (defcustom org-agenda-skip-deadline-if-done nil
1994 "Non-nil means don't show deadines when the corresponding item is done.
1995 When nil, the deadline is still shown and should give you a happy feeling.
1997 This is relevant for the daily/weekly agenda."
1998 :group 'org-agenda-skip
1999 :type 'boolean)
2001 (defcustom org-timeline-show-empty-dates 3
2002 "Non-nil means, `org-timeline' also shows dates without an entry.
2003 When nil, only the days which actually have entries are shown.
2004 When t, all days between the first and the last date are shown.
2005 When an integer, show also empty dates, but if there is a gap of more than
2006 N days, just insert a special line indicating the size of the gap."
2007 :group 'org-agenda-skip
2008 :type '(choice
2009 (const :tag "None" nil)
2010 (const :tag "All" t)
2011 (number :tag "at most")))
2014 (defgroup org-agenda-startup nil
2015 "Options concerning initial settings in the Agenda in Org Mode."
2016 :tag "Org Agenda Startup"
2017 :group 'org-agenda)
2019 (defcustom org-finalize-agenda-hook nil
2020 "Hook run just before displaying an agenda buffer."
2021 :group 'org-agenda-startup
2022 :type 'hook)
2024 (defcustom org-agenda-mouse-1-follows-link nil
2025 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2026 A longer mouse click will still set point. Does not wortk on XEmacs.
2027 Needs to be set before org.el is loaded."
2028 :group 'org-agenda-startup
2029 :type 'boolean)
2031 (defcustom org-agenda-start-with-follow-mode nil
2032 "The initial value of follow-mode in a newly created agenda window."
2033 :group 'org-agenda-startup
2034 :type 'boolean)
2036 (defgroup org-agenda-windows nil
2037 "Options concerning the windows used by the Agenda in Org Mode."
2038 :tag "Org Agenda Windows"
2039 :group 'org-agenda)
2041 (defcustom org-agenda-window-setup 'reorganize-frame
2042 "How the agenda buffer should be displayed.
2043 Possible values for this option are:
2045 current-window Show agenda in the current window, keeping all other windows.
2046 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2047 other-window Use `switch-to-buffer-other-window' to display agenda.
2048 reorganize-frame Show only two windows on the current frame, the current
2049 window and the agenda.
2050 See also the variable `org-agenda-restore-windows-after-quit'."
2051 :group 'org-agenda-windows
2052 :type '(choice
2053 (const current-window)
2054 (const other-frame)
2055 (const other-window)
2056 (const reorganize-frame)))
2058 (defcustom org-agenda-restore-windows-after-quit nil
2059 "Non-nil means, restore window configuration open exiting agenda.
2060 Before the window configuration is changed for displaying the agenda,
2061 the current status is recorded. When the agenda is exited with
2062 `q' or `x' and this option is set, the old state is restored. If
2063 `org-agenda-window-setup' is `other-frame', the value of this
2064 option will be ignored.."
2065 :group 'org-agenda-windows
2066 :type 'boolean)
2068 (defcustom org-indirect-buffer-display 'other-window
2069 "How should indirect tree buffers be displayed?
2070 This applies to indirect buffers created with the commands
2071 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2072 Valid values are:
2073 current-window Display in the current window
2074 other-window Just display in another window.
2075 dedicated-frame Create one new frame, and re-use it each time.
2076 new-frame Make a new frame each time."
2077 :group 'org-structure
2078 :group 'org-agenda-windows
2079 :type '(choice
2080 (const :tag "In current window" current-window)
2081 (const :tag "In current frame, other window" other-window)
2082 (const :tag "Each time a new frame" new-frame)
2083 (const :tag "One dedicated frame" dedicated-frame)))
2085 (defgroup org-agenda-daily/weekly nil
2086 "Options concerning the daily/weekly agenda."
2087 :tag "Org Agenda Daily/Weekly"
2088 :group 'org-agenda)
2090 (defcustom org-agenda-ndays 7
2091 "Number of days to include in overview display.
2092 Should be 1 or 7."
2093 :group 'org-agenda-daily/weekly
2094 :type 'number)
2096 (defcustom org-agenda-start-on-weekday 1
2097 "Non-nil means, start the overview always on the specified weekday.
2098 0 denotes Sunday, 1 denotes Monday etc.
2099 When nil, always start on the current day."
2100 :group 'org-agenda-daily/weekly
2101 :type '(choice (const :tag "Today" nil)
2102 (number :tag "Weekday No.")))
2104 (defcustom org-agenda-show-all-dates t
2105 "Non-nil means, `org-agenda' shows every day in the selected range.
2106 When nil, only the days which actually have entries are shown."
2107 :group 'org-agenda-daily/weekly
2108 :type 'boolean)
2110 (defcustom org-agenda-date-format "%A %d %B %Y"
2111 "Format string for displaying dates in the agenda.
2112 Used by the daily/weekly agenda and by the timeline. This should be
2113 a format string understood by `format-time-string'.
2114 FIXME: Not used currently, because of timezone problem."
2115 :group 'org-agenda-daily/weekly
2116 :type 'string)
2118 (defcustom org-agenda-include-diary nil
2119 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2120 :group 'org-agenda-daily/weekly
2121 :type 'boolean)
2123 (defcustom org-agenda-include-all-todo nil
2124 "Set means weekly/daily agenda will always contain all TODO entries.
2125 The TODO entries will be listed at the top of the agenda, before
2126 the entries for specific days."
2127 :group 'org-agenda-daily/weekly
2128 :type 'boolean)
2130 (defgroup org-agenda-time-grid nil
2131 "Options concerning the time grid in the Org-mode Agenda."
2132 :tag "Org Agenda Time Grid"
2133 :group 'org-agenda)
2135 (defcustom org-agenda-use-time-grid t
2136 "Non-nil means, show a time grid in the agenda schedule.
2137 A time grid is a set of lines for specific times (like every two hours between
2138 8:00 and 20:00). The items scheduled for a day at specific times are
2139 sorted in between these lines.
2140 For details about when the grid will be shown, and what it will look like, see
2141 the variable `org-agenda-time-grid'."
2142 :group 'org-agenda-time-grid
2143 :type 'boolean)
2145 (defcustom org-agenda-time-grid
2146 '((daily today require-timed)
2147 "----------------"
2148 (800 1000 1200 1400 1600 1800 2000))
2150 "The settings for time grid for agenda display.
2151 This is a list of three items. The first item is again a list. It contains
2152 symbols specifying conditions when the grid should be displayed:
2154 daily if the agenda shows a single day
2155 weekly if the agenda shows an entire week
2156 today show grid on current date, independent of daily/weekly display
2157 require-timed show grid only if at least one item has a time specification
2159 The second item is a string which will be places behing the grid time.
2161 The third item is a list of integers, indicating the times that should have
2162 a grid line."
2163 :group 'org-agenda-time-grid
2164 :type
2165 '(list
2166 (set :greedy t :tag "Grid Display Options"
2167 (const :tag "Show grid in single day agenda display" daily)
2168 (const :tag "Show grid in weekly agenda display" weekly)
2169 (const :tag "Always show grid for today" today)
2170 (const :tag "Show grid only if any timed entries are present"
2171 require-timed)
2172 (const :tag "Skip grid times already present in an entry"
2173 remove-match))
2174 (string :tag "Grid String")
2175 (repeat :tag "Grid Times" (integer :tag "Time"))))
2177 (defgroup org-agenda-sorting nil
2178 "Options concerning sorting in the Org-mode Agenda."
2179 :tag "Org Agenda Sorting"
2180 :group 'org-agenda)
2182 (let ((sorting-choice
2183 '(choice
2184 (const time-up) (const time-down)
2185 (const category-keep) (const category-up) (const category-down)
2186 (const tag-down) (const tag-up)
2187 (const priority-up) (const priority-down))))
2189 (defcustom org-agenda-sorting-strategy
2190 '((agenda time-up category-keep priority-down)
2191 (todo category-keep priority-down)
2192 (tags category-keep priority-down))
2193 "Sorting structure for the agenda items of a single day.
2194 This is a list of symbols which will be used in sequence to determine
2195 if an entry should be listed before another entry. The following
2196 symbols are recognized:
2198 time-up Put entries with time-of-day indications first, early first
2199 time-down Put entries with time-of-day indications first, late first
2200 category-keep Keep the default order of categories, corresponding to the
2201 sequence in `org-agenda-files'.
2202 category-up Sort alphabetically by category, A-Z.
2203 category-down Sort alphabetically by category, Z-A.
2204 tag-up Sort alphabetically by last tag, A-Z.
2205 tag-down Sort alphabetically by last tag, Z-A.
2206 priority-up Sort numerically by priority, high priority last.
2207 priority-down Sort numerically by priority, high priority first.
2209 The different possibilities will be tried in sequence, and testing stops
2210 if one comparison returns a \"not-equal\". For example, the default
2211 '(time-up category-keep priority-down)
2212 means: Pull out all entries having a specified time of day and sort them,
2213 in order to make a time schedule for the current day the first thing in the
2214 agenda listing for the day. Of the entries without a time indication, keep
2215 the grouped in categories, don't sort the categories, but keep them in
2216 the sequence given in `org-agenda-files'. Within each category sort by
2217 priority.
2219 Leaving out `category-keep' would mean that items will be sorted across
2220 categories by priority."
2221 :group 'org-agenda-sorting
2222 :type `(choice
2223 (repeat :tag "General" ,sorting-choice)
2224 (list :tag "Individually"
2225 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2226 (repeat ,sorting-choice))
2227 (cons (const :tag "Strategy for TODO lists" todo)
2228 (repeat ,sorting-choice))
2229 (cons (const :tag "Strategy for Tags matches" tags)
2230 (repeat ,sorting-choice))))))
2232 (defcustom org-sort-agenda-notime-is-late t
2233 "Non-nil means, items without time are considered late.
2234 This is only relevant for sorting. When t, items which have no explicit
2235 time like 15:30 will be considered as 99:01, i.e. later than any items which
2236 do have a time. When nil, the default time is before 0:00. You can use this
2237 option to decide if the schedule for today should come before or after timeless
2238 agenda entries."
2239 :group 'org-agenda-sorting
2240 :type 'boolean)
2242 (defgroup org-agenda-prefix nil
2243 "Options concerning the entry prefix in the Org-mode agenda display."
2244 :tag "Org Agenda Prefix"
2245 :group 'org-agenda)
2247 (defcustom org-agenda-prefix-format
2248 '((agenda . " %-12:c%?-12t% s")
2249 (timeline . " % s")
2250 (todo . " %-12:c")
2251 (tags . " %-12:c"))
2252 "Format specifications for the prefix of items in the agenda views.
2253 An alist with four entries, for the different agenda types. The keys to the
2254 sublists are `agenda', `timeline', `todo', and `tags'. The values
2255 are format strings.
2256 This format works similar to a printf format, with the following meaning:
2258 %c the category of the item, \"Diary\" for entries from the diary, or
2259 as given by the CATEGORY keyword or derived from the file name.
2260 %T the *last* tag of the item. Last because inherited tags come
2261 first in the list.
2262 %t the time-of-day specification if one applies to the entry, in the
2263 format HH:MM
2264 %s Scheduling/Deadline information, a short string
2266 All specifiers work basically like the standard `%s' of printf, but may
2267 contain two additional characters: A question mark just after the `%' and
2268 a whitespace/punctuation character just before the final letter.
2270 If the first character after `%' is a question mark, the entire field
2271 will only be included if the corresponding value applies to the
2272 current entry. This is useful for fields which should have fixed
2273 width when present, but zero width when absent. For example,
2274 \"%?-12t\" will result in a 12 character time field if a time of the
2275 day is specified, but will completely disappear in entries which do
2276 not contain a time.
2278 If there is punctuation or whitespace character just before the final
2279 format letter, this character will be appended to the field value if
2280 the value is not empty. For example, the format \"%-12:c\" leads to
2281 \"Diary: \" if the category is \"Diary\". If the category were be
2282 empty, no additional colon would be interted.
2284 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2285 - Indent the line with two space characters
2286 - Give the category in a 12 chars wide field, padded with whitespace on
2287 the right (because of `-'). Append a colon if there is a category
2288 (because of `:').
2289 - If there is a time-of-day, put it into a 12 chars wide field. If no
2290 time, don't put in an empty field, just skip it (because of '?').
2291 - Finally, put the scheduling information and append a whitespace.
2293 As another example, if you don't want the time-of-day of entries in
2294 the prefix, you could use:
2296 (setq org-agenda-prefix-format \" %-11:c% s\")
2298 See also the variables `org-agenda-remove-times-when-in-prefix' and
2299 `org-agenda-remove-tags'."
2300 :type '(choice
2301 (string :tag "General format")
2302 (list :greedy t :tag "View dependent"
2303 (cons (const agenda) (string :tag "Format"))
2304 (cons (const timeline) (string :tag "Format"))
2305 (cons (const todo) (string :tag "Format"))
2306 (cons (const tags) (string :tag "Format"))))
2307 :group 'org-agenda-prefix)
2309 (defvar org-prefix-format-compiled nil
2310 "The compiled version of the most recently used prefix format.
2311 See the variable `org-agenda-prefix-format'.")
2313 (defcustom org-agenda-remove-times-when-in-prefix t
2314 "Non-nil means, remove duplicate time specifications in agenda items.
2315 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2316 time-of-day specification in a headline or diary entry is extracted and
2317 placed into the prefix. If this option is non-nil, the original specification
2318 \(a timestamp or -range, or just a plain time(range) specification like
2319 11:30-4pm) will be removed for agenda display. This makes the agenda less
2320 cluttered.
2321 The option can be t or nil. It may also be the symbol `beg', indicating
2322 that the time should only be removed what it is located at the beginning of
2323 the headline/diary entry."
2324 :group 'org-agenda-prefix
2325 :type '(choice
2326 (const :tag "Always" t)
2327 (const :tag "Never" nil)
2328 (const :tag "When at beginning of entry" beg)))
2330 (defcustom org-agenda-remove-tags nil
2331 "Non-nil means, remove the tags from the headline copy in the agenda.
2332 When this is the symbol `prefix', only remove tags when
2333 `org-agenda-prefix-format' contains a `%T' specifier."
2334 :group 'org-agenda-prefix
2335 :type '(choice
2336 (const :tag "Always" t)
2337 (const :tag "Never" nil)
2338 (const :tag "When prefix format contains %T" prefix)))
2340 (if (fboundp 'defvaralias)
2341 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2342 'org-agenda-remove-tags))
2344 (defcustom org-agenda-align-tags-to-column 65
2345 "Shift tags in agenda items to this column."
2346 :group 'org-agenda-prefix
2347 :type 'integer)
2349 (defgroup org-latex nil
2350 "Options for embedding LaTeX code into Org-mode"
2351 :tag "Org LaTeX"
2352 :group 'org)
2354 (defcustom org-format-latex-options
2355 '(:foreground default :background default :scale 1.0
2356 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2357 :matchers ("begin" "$" "$$" "\\(" "\\["))
2358 "Options for creating images from LaTeX fragments.
2359 This is a property list with the following properties:
2360 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2361 `default' means use the forground of the default face.
2362 :background the background color, or \"Transparent\".
2363 `default' means use the background of the default face.
2364 :scale a scaling factor for the size of the images
2365 :html-foreground, :html-background, :html-scale
2366 The same numbers for HTML export.
2367 :matchers a list indicating which matchers should be used to
2368 find LaTeX fragments. Valid members of this list are:
2369 \"begin\" find environments
2370 \"$\" find math expressions surrounded by $...$
2371 \"$$\" find math expressions surrounded by $$....$$
2372 \"\\(\" find math expressions surrounded by \\(...\\)
2373 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2374 :group 'org-latex
2375 :type 'plist)
2377 (defcustom org-format-latex-header "\\documentclass{article}
2378 \\usepackage{fullpage} % do not remove
2379 \\usepackage{amssymb}
2380 \\usepackage[usenames]{color}
2381 \\usepackage{amsmath}
2382 \\usepackage{latexsym}
2383 \\usepackage[mathscr]{eucal}
2384 \\pagestyle{empty} % do not remove"
2385 "The document header used for processing LaTeX fragments."
2386 :group 'org-latex
2387 :type 'string)
2389 (defgroup org-export nil
2390 "Options for exporting org-listings."
2391 :tag "Org Export"
2392 :group 'org)
2394 (defgroup org-export-general nil
2395 "General options for exporting Org-mode files."
2396 :tag "Org Export General"
2397 :group 'org-export)
2399 (defcustom org-export-publishing-directory "."
2400 "Path to the location where exported files should be located.
2401 This path may be relative to the directory where the Org-mode file lives.
2402 The default is to put them into the same directory as the Org-mode file.
2403 The variable may also be an alist with export types `:html', `:ascii',
2404 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2405 is relative, it is interpreted relative to the directory where the exported
2406 Org-mode files lives."
2407 :group 'org-export-general
2408 :type '(choice
2409 (directory)
2410 (repeat
2411 (cons
2412 (choice :tag "Type"
2413 (const :html) (const :ascii) (const :ical) (const :xoxo))
2414 (directory)))))
2416 (defcustom org-export-language-setup
2417 '(("en" "Author" "Date" "Table of Contents")
2418 ("cs" "Autor" "Datum" "Obsah")
2419 ("da" "Ophavsmand" "Dato" "Indhold")
2420 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2421 ("es" "Autor" "Fecha" "\xccndice")
2422 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2423 ("it" "Autore" "Data" "Indice")
2424 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2425 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2426 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2427 "Terms used in export text, translated to different languages.
2428 Use the variable `org-export-default-language' to set the language,
2429 or use the +OPTION lines for a per-file setting."
2430 :group 'org-export-general
2431 :type '(repeat
2432 (list
2433 (string :tag "HTML language tag")
2434 (string :tag "Author")
2435 (string :tag "Date")
2436 (string :tag "Table of Contents"))))
2438 (defcustom org-export-default-language "en"
2439 "The default language of HTML export, as a string.
2440 This should have an association in `org-export-language-setup'."
2441 :group 'org-export-general
2442 :type 'string)
2444 (defcustom org-export-skip-text-before-1st-heading t
2445 "Non-nil means, skip all text before the first headline when exporting.
2446 When nil, that text is exported as well."
2447 :group 'org-export-general
2448 :type 'boolean)
2450 (defcustom org-export-headline-levels 3
2451 "The last level which is still exported as a headline.
2452 Inferior levels will produce itemize lists when exported.
2453 Note that a numeric prefix argument to an exporter function overrides
2454 this setting.
2456 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2457 :group 'org-export-general
2458 :type 'number)
2460 (defcustom org-export-with-section-numbers t
2461 "Non-nil means, add section numbers to headlines when exporting.
2463 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2464 :group 'org-export-general
2465 :type 'boolean)
2467 (defcustom org-export-with-toc t
2468 "Non-nil means, create a table of contents in exported files.
2469 The TOC contains headlines with levels up to`org-export-headline-levels'.
2470 When an integer, include levels up to N in the toc, this may then be
2471 different from `org-export-headline-levels', but it will not be allowed
2472 to be larger than the number of headline levels.
2473 When nil, no table of contents is made.
2475 Headlines which contain any TODO items will be marked with \"(*)\" in
2476 ASCII export, and with red color in HTML output, if the option
2477 `org-export-mark-todo-in-toc' is set.
2479 In HTML output, the TOC will be clickable.
2481 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2482 or \"toc:3\"."
2483 :group 'org-export-general
2484 :type '(choice
2485 (const :tag "No Table of Contents" nil)
2486 (const :tag "Full Table of Contents" t)
2487 (integer :tag "TOC to level")))
2489 (defcustom org-export-mark-todo-in-toc nil
2490 "Non-nil means, mark TOC lines that contain any open TODO items."
2491 :group 'org-export-general
2492 :type 'boolean)
2494 (defcustom org-export-preserve-breaks nil
2495 "Non-nil means, preserve all line breaks when exporting.
2496 Normally, in HTML output paragraphs will be reformatted. In ASCII
2497 export, line breaks will always be preserved, regardless of this variable.
2499 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2500 :group 'org-export-general
2501 :type 'boolean)
2503 (defcustom org-export-with-archived-trees 'headline
2504 "Whether subtrees with the ARCHIVE tag should be exported.
2505 This can have three different values
2506 nil Do not export, pretend this tree is not present
2507 t Do export the entire tree
2508 headline Only export the headline, but skip the tree below it."
2509 :group 'org-export-general
2510 :group 'org-archive
2511 :type '(choice
2512 (const :tag "not at all" nil)
2513 (const :tag "headline only" 'headline)
2514 (const :tag "entirely" t)))
2516 (defcustom org-export-with-timestamps t
2517 "If nil, do not export time stamps and associated keywords."
2518 :group 'org-export-general
2519 :type 'boolean)
2521 (defcustom org-export-remove-timestamps-from-toc t
2522 "If nil, remove timestamps from the table of contents entries."
2523 :group 'org-export-general
2524 :type 'boolean)
2526 (defcustom org-export-with-tags 'not-in-toc
2527 "If nil, do not export tags, just remove them from headlines.
2528 If this is the symbol `not-in-toc', tags will be removed from table of
2529 contents entries, but still be shown in the headlines of the document."
2530 :group 'org-export-general
2531 :type '(choice
2532 (const :tag "Off" nil)
2533 (const :tag "Not in TOC" not-in-toc)
2534 (const :tag "On" t)))
2536 (defgroup org-export-translation nil
2537 "Options for translating special ascii sequences for the export backends."
2538 :tag "Org Export Translation"
2539 :group 'org-export)
2541 (defcustom org-export-with-emphasize t
2542 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2543 If the export target supports emphasizing text, the word will be
2544 typeset in bold, italic, or underlined, respectively. Works only for
2545 single words, but you can say: I *really* *mean* *this*.
2546 Not all export backends support this.
2548 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2549 :group 'org-export-translation
2550 :type 'boolean)
2552 (defcustom org-export-with-sub-superscripts t
2553 "Non-nil means, interpret \"_\" and \"^\" for export.
2554 When this option is turned on, you can use TeX-like syntax for sub- and
2555 superscripts. Several characters after \"_\" or \"^\" will be
2556 considered as a single item - so grouping with {} is normally not
2557 needed. For example, the following things will be parsed as single
2558 sub- or superscripts.
2560 10^24 or 10^tau several digits will be considered 1 item.
2561 10^-12 or 10^-tau a leading sign with digits or a word
2562 x^2-y^3 will be read as x^2 - y^3, because items are
2563 terminated by almost any nonword/nondigit char.
2564 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2566 Still, ambiguity is possible - so when in doubt use {} to enclose the
2567 sub/superscript. If you set this variable to the symbol `{}',
2568 the braces are *required* in order to trigger interpretations as
2569 sub/superscript. This can be helpful in documents that need \"_\"
2570 frequently in plain text.
2572 Not all export backends support this, but HTML does.
2574 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2575 :group 'org-export-translation
2576 :type '(choice
2577 (const :tag "Always interpret" t)
2578 (const :tag "Only with braces" {})
2579 (const :tag "Never interpret" nil)))
2581 (defcustom org-export-with-TeX-macros t
2582 "Non-nil means, interpret simple TeX-like macros when exporting.
2583 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2584 No only real TeX macros will work here, but the standard HTML entities
2585 for math can be used as macro names as well. For a list of supported
2586 names in HTML export, see the constant `org-html-entities'.
2587 Not all export backends support this.
2589 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2590 :group 'org-export-translation
2591 :group 'org-latex
2592 :type 'boolean)
2594 (defcustom org-export-with-LaTeX-fragments nil
2595 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2596 When set, the exporter will find LaTeX environments if the \\begin line is
2597 the first non-white thing on a line. It will also find the math delimiters
2598 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2599 display math.
2601 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2602 :group 'org-export-translation
2603 :group 'org-latex
2604 :type 'boolean)
2606 (defcustom org-export-with-fixed-width t
2607 "Non-nil means, lines starting with \":\" will be in fixed width font.
2608 This can be used to have pre-formatted text, fragments of code etc. For
2609 example:
2610 : ;; Some Lisp examples
2611 : (while (defc cnt)
2612 : (ding))
2613 will be looking just like this in also HTML. See also the QUOTE keyword.
2614 Not all export backends support this.
2616 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2617 :group 'org-export-translation
2618 :type 'boolean)
2620 (defcustom org-match-sexp-depth 3
2621 "Number of stacked braces for sub/superscript matching.
2622 This has to be set before loading org.el to be effective."
2623 :group 'org-export-translation
2624 :type 'integer)
2626 (defgroup org-export-tables nil
2627 "Options for exporting tables in Org-mode."
2628 :tag "Org Export Tables"
2629 :group 'org-export)
2631 (defcustom org-export-with-tables t
2632 "If non-nil, lines starting with \"|\" define a table.
2633 For example:
2635 | Name | Address | Birthday |
2636 |-------------+----------+-----------|
2637 | Arthur Dent | England | 29.2.2100 |
2639 Not all export backends support this.
2641 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2642 :group 'org-export-tables
2643 :type 'boolean)
2645 (defcustom org-export-highlight-first-table-line t
2646 "Non-nil means, highlight the first table line.
2647 In HTML export, this means use <th> instead of <td>.
2648 In tables created with table.el, this applies to the first table line.
2649 In Org-mode tables, all lines before the first horizontal separator
2650 line will be formatted with <th> tags."
2651 :group 'org-export-tables
2652 :type 'boolean)
2654 (defcustom org-export-table-remove-special-lines t
2655 "Remove special lines and marking characters in calculating tables.
2656 This removes the special marking character column from tables that are set
2657 up for spreadsheet calculations. It also removes the entire lines
2658 marked with `!', `_', or `^'. The lines with `$' are kept, because
2659 the values of constants may be useful to have."
2660 :group 'org-export-tables
2661 :type 'boolean)
2663 (defcustom org-export-prefer-native-exporter-for-tables nil
2664 "Non-nil means, always export tables created with table.el natively.
2665 Natively means, use the HTML code generator in table.el.
2666 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2667 the table does not use row- or column-spanning). This has the
2668 advantage, that the automatic HTML conversions for math symbols and
2669 sub/superscripts can be applied. Org-mode's HTML generator is also
2670 much faster."
2671 :group 'org-export-tables
2672 :type 'boolean)
2674 (defgroup org-export-ascii nil
2675 "Options specific for ASCII export of Org-mode files."
2676 :tag "Org Export ASCII"
2677 :group 'org-export)
2679 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2680 "Characters for underlining headings in ASCII export.
2681 In the given sequence, these characters will be used for level 1, 2, ..."
2682 :group 'org-export-ascii
2683 :type '(repeat character))
2685 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2686 "Bullet characters for headlines converted to lists in ASCII export.
2687 The first character is is used for the first lest level generated in this
2688 way, and so on. If there are more levels than characters given here,
2689 the list will be repeated.
2690 Note that plain lists will keep the same bullets as the have in the
2691 Org-mode file."
2692 :group 'org-export-ascii
2693 :type '(repeat character))
2695 (defgroup org-export-xml nil
2696 "Options specific for XML export of Org-mode files."
2697 :tag "Org Export XML"
2698 :group 'org-export)
2700 (defgroup org-export-html nil
2701 "Options specific for HTML export of Org-mode files."
2702 :tag "Org Export HTML"
2703 :group 'org-export)
2705 (defcustom org-export-html-coding-system nil
2707 :group 'org-export-html
2708 :type 'coding-system)
2710 (defcustom org-export-html-style
2711 "<style type=\"text/css\">
2712 html {
2713 font-family: Times, serif;
2714 font-size: 12pt;
2716 .title { text-align: center; }
2717 .todo { color: red; }
2718 .done { color: green; }
2719 .timestamp { color: grey }
2720 .timestamp-kwd { color: CadetBlue }
2721 .tag { background-color:lightblue; font-weight:normal }
2722 .target { background-color: lavender; }
2723 pre {
2724 border: 1pt solid #AEBDCC;
2725 background-color: #F3F5F7;
2726 padding: 5pt;
2727 font-family: courier, monospace;
2729 table { border-collapse: collapse; }
2730 td, th {
2731 vertical-align: top;
2732 <!--border: 1pt solid #ADB9CC;-->
2734 </style>"
2735 "The default style specification for exported HTML files.
2736 Since there are different ways of setting style information, this variable
2737 needs to contain the full HTML structure to provide a style, including the
2738 surrounding HTML tags. The style specifications should include definitions
2739 for new classes todo, done, title, and deadline. For example, legal values
2740 would be:
2742 <style type=\"text/css\">
2743 p { font-weight: normal; color: gray; }
2744 h1 { color: black; }
2745 .title { text-align: center; }
2746 .todo, .deadline { color: red; }
2747 .done { color: green; }
2748 </style>
2750 or, if you want to keep the style in a file,
2752 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2754 As the value of this option simply gets inserted into the HTML <head> header,
2755 you can \"misuse\" it to add arbitrary text to the header."
2756 :group 'org-export-html
2757 :type 'string)
2760 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2761 "Format for typesetting the document title in HTML export."
2762 :group 'org-export-html
2763 :type 'string)
2765 (defcustom org-export-html-toplevel-hlevel 2
2766 "The <H> level for level 1 headings in HTML export."
2767 :group 'org-export-html
2768 :type 'string)
2770 (defcustom org-export-html-link-org-files-as-html t
2771 "Non-nil means, make file links to `file.org' point to `file.html'.
2772 When org-mode is exporting an org-mode file to HTML, links to
2773 non-html files are directly put into a href tag in HTML.
2774 However, links to other Org-mode files (recognized by the
2775 extension `.org.) should become links to the corresponding html
2776 file, assuming that the linked org-mode file will also be
2777 converted to HTML.
2778 When nil, the links still point to the plain `.org' file."
2779 :group 'org-export-html
2780 :type 'boolean)
2782 (defcustom org-export-html-inline-images 'maybe
2783 "Non-nil means, inline images into exported HTML pages.
2784 This is done using an <img> tag. When nil, an anchor with href is used to
2785 link to the image. If this option is `maybe', then images in links with
2786 an empty description will be inlined, while images with a description will
2787 be linked only."
2788 :group 'org-export-html
2789 :type '(choice (const :tag "Never" nil)
2790 (const :tag "Always" t)
2791 (const :tag "When there is no description" maybe)))
2793 ;; FIXME: rename
2794 (defcustom org-export-html-expand t
2795 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2796 When nil, these tags will be exported as plain text and therefore
2797 not be interpreted by a browser.
2799 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2800 :group 'org-export-html
2801 :type 'boolean)
2803 (defcustom org-export-html-table-tag
2804 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
2805 "The HTML tag that is used to start a table.
2806 This must be a <table> tag, but you may change the options like
2807 borders and spacing."
2808 :group 'org-export-html
2809 :type 'string)
2811 (defcustom org-export-table-header-tags '("<th>" . "</th>")
2812 "The opening tag for table header fields.
2813 This is customizable so that alignment options can be specified."
2814 :group 'org-export-tables
2815 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
2817 (defcustom org-export-table-data-tags '("<td>" . "</td>")
2818 "The opening tag for table data fields.
2819 This is customizable so that alignment options can be specified."
2820 :group 'org-export-tables
2821 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
2823 (defcustom org-export-html-with-timestamp nil
2824 "If non-nil, write `org-export-html-html-helper-timestamp'
2825 into the exported HTML text. Otherwise, the buffer will just be saved
2826 to a file."
2827 :group 'org-export-html
2828 :type 'boolean)
2830 (defcustom org-export-html-html-helper-timestamp
2831 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2832 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2833 :group 'org-export-html
2834 :type 'string)
2836 (defgroup org-export-icalendar nil
2837 "Options specific for iCalendar export of Org-mode files."
2838 :tag "Org Export iCalendar"
2839 :group 'org-export)
2841 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2842 "The file name for the iCalendar file covering all agenda files.
2843 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2844 The file name should be absolute."
2845 :group 'org-export-icalendar
2846 :type 'file)
2848 (defcustom org-icalendar-include-todo nil
2849 "Non-nil means, export to iCalendar files should also cover TODO items."
2850 :group 'org-export-icalendar
2851 :type '(choice
2852 (const :tag "None" nil)
2853 (const :tag "Unfinished" t)
2854 (const :tag "All" all)))
2856 (defcustom org-icalendar-include-sexps t
2857 "Non-nil means, export to iCalendar files should also cover sexp entries.
2858 These are entries like in the diary, but directly in an Org-mode file."
2859 :group 'org-export-icalendar
2860 :type 'boolean)
2862 (defcustom org-icalendar-combined-name "OrgMode"
2863 "Calendar name for the combined iCalendar representing all agenda files."
2864 :group 'org-export-icalendar
2865 :type 'string)
2867 (defgroup org-font-lock nil
2868 "Font-lock settings for highlighting in Org-mode."
2869 :tag "Org Font Lock"
2870 :group 'org)
2872 (defcustom org-level-color-stars-only nil
2873 "Non-nil means fontify only the stars in each headline.
2874 When nil, the entire headline is fontified.
2875 Changing it requires restart of `font-lock-mode' to become effective
2876 also in regions already fontified."
2877 :group 'org-font-lock
2878 :type 'boolean)
2880 (defcustom org-hide-leading-stars nil
2881 "Non-nil means, hide the first N-1 stars in a headline.
2882 This works by using the face `org-hide' for these stars. This
2883 face is white for a light background, and black for a dark
2884 background. You may have to customize the face `org-hide' to
2885 make this work.
2886 Changing it requires restart of `font-lock-mode' to become effective
2887 also in regions already fontified.
2888 You may also set this on a per-file basis by adding one of the following
2889 lines to the buffer:
2891 #+STARTUP: hidestars
2892 #+STARTUP: showstars"
2893 :group 'org-font-lock
2894 :type 'boolean)
2896 (defcustom org-fontify-done-headline nil
2897 "Non-nil means, change the face of a headline if it is marked DONE.
2898 Normally, only the TODO/DONE keyword indicates the state of a headline.
2899 When this is non-nil, the headline after the keyword is set to the
2900 `org-headline-done' as an additional indication."
2901 :group 'org-font-lock
2902 :type 'boolean)
2904 (defcustom org-fontify-emphasized-text t
2905 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2906 Changing this variable requires a restart of Emacs to take effect."
2907 :group 'org-font-lock
2908 :type 'boolean)
2910 (defvar org-emph-re nil
2911 "Regular expression for matching emphasis.")
2912 (defvar org-emphasis-regexp-components) ; defined just below
2913 (defvar org-emphasis-alist) ; defined just below
2914 (defun org-set-emph-re (var val)
2915 "Set variable and compute the emphasis regular expression."
2916 (set var val)
2917 (when (and (boundp 'org-emphasis-alist)
2918 (boundp 'org-emphasis-regexp-components)
2919 org-emphasis-alist org-emphasis-regexp-components)
2920 (let* ((e org-emphasis-regexp-components)
2921 (pre (car e))
2922 (post (nth 1 e))
2923 (border (nth 2 e))
2924 (body (nth 3 e))
2925 (nl (nth 4 e))
2926 (stacked (nth 5 e))
2927 (body1 (concat body "*?"))
2928 (markers (mapconcat 'car org-emphasis-alist "")))
2929 ;; make sure special characters appear at the right position in the class
2930 (if (string-match "\\^" markers)
2931 (setq markers (concat (replace-match "" t t markers) "^")))
2932 (if (string-match "-" markers)
2933 (setq markers (concat (replace-match "" t t markers) "-")))
2934 (if (> nl 0)
2935 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2936 (int-to-string nl) "\\}")))
2937 ;; Make the regexp
2938 (setq org-emph-re
2939 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2940 "\\("
2941 "\\([" markers "]\\)"
2942 "\\("
2943 "[^" border (if (and nil stacked) markers) "]"
2944 body1
2945 "[^" border (if (and nil stacked) markers) "]"
2946 "\\)"
2947 "\\3\\)"
2948 "\\([" post (if stacked markers) "]\\|$\\)")))))
2950 (defcustom org-emphasis-regexp-components
2951 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
2952 "Components used to build the reqular expression for emphasis.
2953 This is a list with 6 entries. Terminology: In an emphasis string
2954 like \" *strong word* \", we call the initial space PREMATCH, the final
2955 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2956 and \"trong wor\" is the body. The different components in this variable
2957 specify what is allowed/forbidden in each part:
2959 pre Chars allowed as prematch. Beginning of line will be allowed too.
2960 post Chars allowed as postmatch. End of line will be allowed too.
2961 border The chars *forbidden* as border characters.
2962 body-regexp A regexp like \".\" to match a body character. Don't use
2963 non-shy groups here, and don't allow newline here.
2964 newline The maximum number of newlines allowed in an emphasis exp.
2965 stacked Non-nil means, allow stacked styles. This works only in HTML
2966 export. When this is set, all marker characters (as given in
2967 `org-emphasis-alist') will be allowed as pre/post, aiding
2968 inside-out matching.
2969 Use customize to modify this, or restart Emacs after changing it."
2970 :group 'org-font-lock
2971 :set 'org-set-emph-re
2972 :type '(list
2973 (sexp :tag "Allowed chars in pre ")
2974 (sexp :tag "Allowed chars in post ")
2975 (sexp :tag "Forbidden chars in border ")
2976 (sexp :tag "Regexp for body ")
2977 (integer :tag "number of newlines allowed")
2978 (boolean :tag "Stacking allowed ")))
2980 (defcustom org-emphasis-alist
2981 '(("*" bold "<b>" "</b>")
2982 ("/" italic "<i>" "</i>")
2983 ("_" underline "<u>" "</u>")
2984 ("=" shadow "<code>" "</code>")
2985 ("+" (:strike-through t) "<del>" "</del>")
2987 "Special syntax for emphasized text.
2988 Text starting and ending with a special character will be emphasized, for
2989 example *bold*, _underlined_ and /italic/. This variable sets the marker
2990 characters, the face to be used by font-lock for highlighting in Org-mode
2991 Emacs buffers, and the HTML tags to be used for this.
2992 Use customize to modify this, or restart Emacs after changing it."
2993 :group 'org-font-lock
2994 :set 'org-set-emph-re
2995 :type '(repeat
2996 (list
2997 (string :tag "Marker character")
2998 (choice
2999 (face :tag "Font-lock-face")
3000 (plist :tag "Face property list"))
3001 (string :tag "HTML start tag")
3002 (string :tag "HTML end tag"))))
3004 ;;; The faces
3006 (defgroup org-faces nil
3007 "Faces in Org-mode."
3008 :tag "Org Faces"
3009 :group 'org-font-lock)
3011 (defun org-compatible-face (specs)
3012 "Make a compatible face specification.
3013 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3014 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3015 to the top of the list. The `min-colors' attribute will be removed from
3016 any other entries, and any resulting duplicates will be removed entirely."
3017 (if (or (featurep 'xemacs) (< emacs-major-version 22))
3018 (let (r e a)
3019 (while (setq e (pop specs))
3020 (cond
3021 ((memq (car e) '(t default)) (push e r))
3022 ((setq a (member '(min-colors 8) (car e)))
3023 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3024 (cdr e)))))
3025 ((setq a (assq 'min-colors (car e)))
3026 (setq e (cons (delq a (car e)) (cdr e)))
3027 (or (assoc (car e) r) (push e r)))
3028 (t (or (assoc (car e) r) (push e r)))))
3029 (nreverse r))
3030 specs))
3032 (defface org-hide
3033 '((((background light)) (:foreground "white"))
3034 (((background dark)) (:foreground "black")))
3035 "Face used to hide leading stars in headlines.
3036 The forground color of this face should be equal to the background
3037 color of the frame."
3038 :group 'org-faces)
3040 (defface org-level-1 ;; font-lock-function-name-face
3041 (org-compatible-face
3042 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3043 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3044 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3045 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3046 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3047 (t (:bold t))))
3048 "Face used for level 1 headlines."
3049 :group 'org-faces)
3051 (defface org-level-2 ;; font-lock-variable-name-face
3052 (org-compatible-face
3053 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3054 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3055 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3056 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3057 (t (:bold t))))
3058 "Face used for level 2 headlines."
3059 :group 'org-faces)
3061 (defface org-level-3 ;; font-lock-keyword-face
3062 (org-compatible-face
3063 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3064 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3065 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3066 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3067 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3068 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3069 (t (:bold t))))
3070 "Face used for level 3 headlines."
3071 :group 'org-faces)
3073 (defface org-level-4 ;; font-lock-comment-face
3074 (org-compatible-face
3075 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3076 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3077 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3078 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3079 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3080 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3081 (t (:bold t))))
3082 "Face used for level 4 headlines."
3083 :group 'org-faces)
3085 (defface org-level-5 ;; font-lock-type-face
3086 (org-compatible-face
3087 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3088 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3089 (((class color) (min-colors 8)) (:foreground "green"))))
3090 "Face used for level 5 headlines."
3091 :group 'org-faces)
3093 (defface org-level-6 ;; font-lock-constant-face
3094 (org-compatible-face
3095 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3096 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3097 (((class color) (min-colors 8)) (:foreground "magenta"))))
3098 "Face used for level 6 headlines."
3099 :group 'org-faces)
3101 (defface org-level-7 ;; font-lock-builtin-face
3102 (org-compatible-face
3103 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3104 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3105 (((class color) (min-colors 8)) (:foreground "blue"))))
3106 "Face used for level 7 headlines."
3107 :group 'org-faces)
3109 (defface org-level-8 ;; font-lock-string-face
3110 (org-compatible-face
3111 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3112 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3113 (((class color) (min-colors 8)) (:foreground "green"))))
3114 "Face used for level 8 headlines."
3115 :group 'org-faces)
3117 (defface org-special-keyword ;; font-lock-string-face
3118 (org-compatible-face
3119 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3120 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3121 (t (:italic t))))
3122 "Face used for special keywords."
3123 :group 'org-faces)
3125 (defface org-warning ;; font-lock-warning-face
3126 (org-compatible-face
3127 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3128 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3129 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3130 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3131 (t (:bold t))))
3132 "Face for deadlines and TODO keywords."
3133 :group 'org-faces)
3135 (defface org-archived ; similar to shadow
3136 (org-compatible-face
3137 '((((class color grayscale) (min-colors 88) (background light))
3138 (:foreground "grey50"))
3139 (((class color grayscale) (min-colors 88) (background dark))
3140 (:foreground "grey70"))
3141 (((class color) (min-colors 8) (background light))
3142 (:foreground "green"))
3143 (((class color) (min-colors 8) (background dark))
3144 (:foreground "yellow"))))
3145 "Face for headline with the ARCHIVE tag."
3146 :group 'org-faces)
3148 (defface org-link
3149 '((((class color) (background light)) (:foreground "Purple" :underline t))
3150 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3151 (t (:underline t)))
3152 "Face for links."
3153 :group 'org-faces)
3155 (defface org-target
3156 '((((class color) (background light)) (:underline t))
3157 (((class color) (background dark)) (:underline t))
3158 (t (:underline t)))
3159 "Face for links."
3160 :group 'org-faces)
3162 (defface org-date
3163 '((((class color) (background light)) (:foreground "Purple" :underline t))
3164 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3165 (t (:underline t)))
3166 "Face for links."
3167 :group 'org-faces)
3169 (defface org-sexp-date
3170 '((((class color) (background light)) (:foreground "Purple"))
3171 (((class color) (background dark)) (:foreground "Cyan"))
3172 (t (:underline t)))
3173 "Face for links."
3174 :group 'org-faces)
3176 (defface org-tag
3177 '((t (:bold t)))
3178 "Face for tags."
3179 :group 'org-faces)
3181 (defface org-todo ;; font-lock-warning-face
3182 (org-compatible-face
3183 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3184 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3185 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3186 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3187 (t (:inverse-video t :bold t))))
3188 "Face for TODO keywords."
3189 :group 'org-faces)
3191 (defface org-done ;; font-lock-type-face
3192 (org-compatible-face
3193 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3194 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3195 (((class color) (min-colors 8)) (:foreground "green"))
3196 (t (:bold t))))
3197 "Face used for todo keywords that indicate DONE items."
3198 :group 'org-faces)
3200 (defface org-headline-done ;; font-lock-string-face
3201 (org-compatible-face
3202 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3203 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3204 (((class color) (min-colors 8) (background light)) (:bold nil))))
3205 "Face used to indicate that a headline is DONE.
3206 This face is only used if `org-fontify-done-headline' is set. If applies
3207 to the part of the headline after the DONE keyword."
3208 :group 'org-faces)
3210 (defface org-table ;; font-lock-function-name-face
3211 (org-compatible-face
3212 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3213 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3214 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3215 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3216 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3217 (((class color) (min-colors 8) (background dark)))))
3218 "Face used for tables."
3219 :group 'org-faces)
3221 (defface org-formula
3222 (org-compatible-face
3223 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3224 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3225 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3226 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3227 (t (:bold t :italic t))))
3228 "Face for formulas."
3229 :group 'org-faces)
3231 (defface org-agenda-structure ;; font-lock-function-name-face
3232 (org-compatible-face
3233 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3234 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3235 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3236 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3237 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3238 (t (:bold t))))
3239 "Face used in agenda for captions and dates."
3240 :group 'org-faces)
3242 (defface org-scheduled-today
3243 (org-compatible-face
3244 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3245 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3246 (((class color) (min-colors 8)) (:foreground "green"))
3247 (t (:bold t :italic t))))
3248 "Face for items scheduled for a certain day."
3249 :group 'org-faces)
3251 (defface org-scheduled-previously
3252 (org-compatible-face
3253 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3254 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3255 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3256 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3257 (t (:bold t))))
3258 "Face for items scheduled previously, and not yet done."
3259 :group 'org-faces)
3261 (defface org-upcoming-deadline
3262 (org-compatible-face
3263 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3264 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3265 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3266 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3267 (t (:bold t))))
3268 "Face for items scheduled previously, and not yet done."
3269 :group 'org-faces)
3271 (defface org-time-grid ;; font-lock-variable-name-face
3272 (org-compatible-face
3273 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3274 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3275 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3276 "Face used for time grids."
3277 :group 'org-faces)
3279 (defconst org-level-faces
3280 '(org-level-1 org-level-2 org-level-3 org-level-4
3281 org-level-5 org-level-6 org-level-7 org-level-8
3283 (defconst org-n-levels (length org-level-faces))
3286 ;;; Variables for pre-computed regular expressions, all buffer local
3288 (defvar org-todo-regexp nil
3289 "Matches any of the TODO state keywords.")
3290 (make-variable-buffer-local 'org-todo-regexp)
3291 (defvar org-not-done-regexp nil
3292 "Matches any of the TODO state keywords except the last one.")
3293 (make-variable-buffer-local 'org-not-done-regexp)
3294 (defvar org-todo-line-regexp nil
3295 "Matches a headline and puts TODO state into group 2 if present.")
3296 (make-variable-buffer-local 'org-todo-line-regexp)
3297 (defvar org-todo-line-tags-regexp nil
3298 "Matches a headline and puts TODO state into group 2 if present.
3299 Also put tags into group 4 if tags are present.")
3300 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3301 (defvar org-nl-done-regexp nil
3302 "Matches newline followed by a headline with the DONE keyword.")
3303 (make-variable-buffer-local 'org-nl-done-regexp)
3304 (defvar org-looking-at-done-regexp nil
3305 "Matches the DONE keyword a point.")
3306 (make-variable-buffer-local 'org-looking-at-done-regexp)
3307 (defvar org-ds-keyword-length 12
3308 "Maximum length of the Deadline and SCHEDULED keywords.")
3309 (make-variable-buffer-local 'org-ds-keyword-length)
3310 (defvar org-deadline-regexp nil
3311 "Matches the DEADLINE keyword.")
3312 (make-variable-buffer-local 'org-deadline-regexp)
3313 (defvar org-deadline-time-regexp nil
3314 "Matches the DEADLINE keyword together with a time stamp.")
3315 (make-variable-buffer-local 'org-deadline-time-regexp)
3316 (defvar org-deadline-line-regexp nil
3317 "Matches the DEADLINE keyword and the rest of the line.")
3318 (make-variable-buffer-local 'org-deadline-line-regexp)
3319 (defvar org-scheduled-regexp nil
3320 "Matches the SCHEDULED keyword.")
3321 (make-variable-buffer-local 'org-scheduled-regexp)
3322 (defvar org-scheduled-time-regexp nil
3323 "Matches the SCHEDULED keyword together with a time stamp.")
3324 (make-variable-buffer-local 'org-scheduled-time-regexp)
3325 (defvar org-closed-time-regexp nil
3326 "Matches the CLOSED keyword together with a time stamp.")
3327 (make-variable-buffer-local 'org-closed-time-regexp)
3329 (defvar org-keyword-time-regexp nil
3330 "Matches any of the 4 keywords, together with the time stamp.")
3331 (make-variable-buffer-local 'org-keyword-time-regexp)
3332 (defvar org-keyword-time-not-clock-regexp nil
3333 "Matches any of the 3 keywords, together with the time stamp.")
3334 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3335 (defvar org-maybe-keyword-time-regexp nil
3336 "Matches a timestamp, possibly preceeded by a keyword.")
3337 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3338 (defvar org-planning-or-clock-line-re nil
3339 "Matches a line with planning or clock info.")
3340 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3342 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3343 rear-nonsticky t mouse-map t fontified t)
3344 "Properties to remove when a string without properties is wanted.")
3346 (defsubst org-match-string-no-properties (num &optional string)
3347 (if (featurep 'xemacs)
3348 (let ((s (match-string num string)))
3349 (remove-text-properties 0 (length s) org-rm-props s)
3351 (match-string-no-properties num string)))
3353 (defsubst org-no-properties (s)
3354 (remove-text-properties 0 (length s) org-rm-props s)
3357 (defsubst org-get-alist-option (option key)
3358 (cond ((eq key t) t)
3359 ((eq option t) t)
3360 ((assoc key option) (cdr (assoc key option)))
3361 (t (cdr (assq 'default option)))))
3363 (defsubst org-inhibit-invisibility ()
3364 "Modified `buffer-invisibility-spec' for Emacs 21.
3365 Some ops with invisible text do not work correctly on Emacs 21. For these
3366 we turn off invisibility temporarily. Use this in a `let' form."
3367 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3369 (defsubst org-set-local (var value)
3370 "Make VAR local in current buffer and set it to VALUE."
3371 (set (make-variable-buffer-local var) value))
3373 (defsubst org-mode-p ()
3374 "Check if the current buffer is in Org-mode."
3375 (eq major-mode 'org-mode))
3377 (defsubst org-last (list)
3378 "Return the last element of LIST."
3379 (car (last list)))
3381 (defun org-let (list &rest body)
3382 (eval (cons 'let (cons list body))))
3383 (put 'org-let 'lisp-indent-function 1)
3385 (defun org-let2 (list1 list2 &rest body)
3386 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3387 (put 'org-let2 'lisp-indent-function 2)
3388 (defconst org-startup-options
3389 '(("fold" org-startup-folded t)
3390 ("overview" org-startup-folded t)
3391 ("nofold" org-startup-folded nil)
3392 ("showall" org-startup-folded nil)
3393 ("content" org-startup-folded content)
3394 ("hidestars" org-hide-leading-stars t)
3395 ("showstars" org-hide-leading-stars nil)
3396 ("odd" org-odd-levels-only t)
3397 ("oddeven" org-odd-levels-only nil)
3398 ("align" org-startup-align-all-tables t)
3399 ("noalign" org-startup-align-all-tables nil)
3400 ("customtime" org-display-custom-times t)
3401 ("logging" org-log-done t)
3402 ("logdone" org-log-done t)
3403 ("nologging" org-log-done nil)
3404 ("lognotedone" org-log-done done push)
3405 ("lognotestate" org-log-done state push)
3406 ("lognoteclock-out" org-log-done clock-out push)
3407 ("logrepeat" org-log-repeat t)
3408 ("nologrepeat" org-log-repeat nil)
3409 ("constcgs" constants-unit-system cgs)
3410 ("constSI" constants-unit-system SI))
3411 "Variable associated with STARTUP options for org-mode.
3412 Each element is a list of three items: The startup options as written
3413 in the #+STARTUP line, the corresponding variable, and the value to
3414 set this variable to if the option is found. An optional forth element PUSH
3415 means to push this value onto the list in the variable.")
3417 (defun org-set-regexps-and-options ()
3418 "Precompute regular expressions for current buffer."
3419 (when (org-mode-p)
3420 (org-set-local 'org-todo-kwd-alist nil)
3421 (org-set-local 'org-todo-keywords-1 nil)
3422 (org-set-local 'org-done-keywords nil)
3423 (org-set-local 'org-todo-heads nil)
3424 (org-set-local 'org-todo-sets nil)
3425 (let ((re (org-make-options-regexp
3426 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3427 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES")))
3428 (splitre "[ \t]+")
3429 kwds key value cat arch tags links hw dws tail sep kws1 prio)
3430 (save-excursion
3431 (save-restriction
3432 (widen)
3433 (goto-char (point-min))
3434 (while (re-search-forward re nil t)
3435 (setq key (match-string 1) value (org-match-string-no-properties 2))
3436 (cond
3437 ((equal key "CATEGORY")
3438 (if (string-match "[ \t]+$" value)
3439 (setq value (replace-match "" t t value)))
3440 (setq cat (intern value)))
3441 ((equal key "SEQ_TODO")
3442 (push (cons 'sequence (org-split-string value splitre)) kwds))
3443 ((equal key "TYP_TODO")
3444 (push (cons 'type (org-split-string value splitre)) kwds))
3445 ((equal key "TAGS")
3446 (setq tags (append tags (org-split-string value splitre))))
3447 ((equal key "LINK")
3448 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3449 (push (cons (match-string 1 value)
3450 (org-trim (match-string 2 value)))
3451 links)))
3452 ((equal key "PRIORITIES")
3453 (setq prio (org-split-string value " +")))
3454 ((equal key "STARTUP")
3455 (let ((opts (org-split-string value splitre))
3456 l var val)
3457 (while (setq l (pop opts))
3458 (when (setq l (assoc l org-startup-options))
3459 (setq var (nth 1 l) val (nth 2 l))
3460 (if (not (nth 3 l))
3461 (set (make-local-variable var) val)
3462 (if (not (listp (symbol-value var)))
3463 (set (make-local-variable var) nil))
3464 (set (make-local-variable var) (symbol-value var))
3465 (add-to-list var val))))))
3466 ((equal key "ARCHIVE")
3467 (string-match " *$" value)
3468 (setq arch (replace-match "" t t value))
3469 (remove-text-properties 0 (length arch)
3470 '(face t fontified t) arch)))
3472 (and cat (org-set-local 'org-category cat))
3473 (when prio
3474 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3475 (setq prio (mapcar 'string-to-char prio))
3476 (org-set-local 'org-highest-priority (nth 0 prio))
3477 (org-set-local 'org-lowest-priority (nth 1 prio))
3478 (org-set-local 'org-default-priority (nth 2 prio)))
3479 (and arch (org-set-local 'org-archive-location arch))
3480 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3481 ;; Process the TODO keywords
3482 (unless kwds
3483 ;; Use the global values as if they had been given locally.
3484 (setq kwds (default-value 'org-todo-keywords))
3485 (if (stringp (car kwds))
3486 (setq kwds (list (cons org-todo-interpretation
3487 (default-value 'org-todo-keywords)))))
3488 (setq kwds (reverse kwds)))
3489 (setq kwds (nreverse kwds))
3490 (let (inter kws)
3491 (while (setq kws (pop kwds))
3492 (setq inter (pop kws) sep (member "|" kws)
3493 kws1 (delete "|" (copy-sequence kws))
3494 hw (car kws1)
3495 dws (if sep (cdr sep) (last kws1))
3496 tail (list inter hw (car dws) (org-last dws)))
3497 (add-to-list 'org-todo-heads hw 'append)
3498 (push kws1 org-todo-sets)
3499 (setq org-done-keywords (append org-done-keywords dws nil))
3500 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3501 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3502 (setq org-todo-sets (nreverse org-todo-sets)
3503 org-todo-kwd-alist (nreverse org-todo-kwd-alist)))
3504 ;; Process the tags.
3505 (when tags
3506 (let (e tgs)
3507 (while (setq e (pop tags))
3508 (cond
3509 ((equal e "{") (push '(:startgroup) tgs))
3510 ((equal e "}") (push '(:endgroup) tgs))
3511 ((string-match "^\\([a-zA-Z0-9_@]+\\)(\\(.\\))$" e)
3512 (push (cons (match-string 1 e)
3513 (string-to-char (match-string 2 e)))
3514 tgs))
3515 (t (push (list e) tgs))))
3516 (org-set-local 'org-tag-alist nil)
3517 (while (setq e (pop tgs))
3518 (or (and (stringp (car e))
3519 (assoc (car e) org-tag-alist))
3520 (push e org-tag-alist))))))
3522 ;; Compute the regular expressions and other local variables
3523 (if (not org-done-keywords)
3524 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3525 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3526 (length org-scheduled-string)))
3527 org-not-done-keywords
3528 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3529 org-todo-regexp
3530 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3531 "\\|") "\\)\\>")
3532 org-not-done-regexp
3533 (concat "\\<\\("
3534 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3535 "\\)\\>")
3536 org-todo-line-regexp
3537 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3538 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3539 "\\)\\>\\)? *\\(.*\\)")
3540 org-nl-done-regexp
3541 (concat "[\r\n]\\*+[ \t]+"
3542 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3543 "\\)" "\\>")
3544 org-todo-line-tags-regexp
3545 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3546 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3547 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3548 org-looking-at-done-regexp
3549 (concat "^" "\\(?:"
3550 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3551 "\\>")
3552 org-deadline-regexp (concat "\\<" org-deadline-string)
3553 org-deadline-time-regexp
3554 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3555 org-deadline-line-regexp
3556 (concat "\\<\\(" org-deadline-string "\\).*")
3557 org-scheduled-regexp
3558 (concat "\\<" org-scheduled-string)
3559 org-scheduled-time-regexp
3560 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3561 org-closed-time-regexp
3562 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3563 org-keyword-time-regexp
3564 (concat "\\<\\(" org-scheduled-string
3565 "\\|" org-deadline-string
3566 "\\|" org-closed-string
3567 "\\|" org-clock-string "\\)"
3568 " *[[<]\\([^]>]+\\)[]>]")
3569 org-keyword-time-not-clock-regexp
3570 (concat "\\<\\(" org-scheduled-string
3571 "\\|" org-deadline-string
3572 "\\|" org-closed-string "\\)"
3573 " *[[<]\\([^]>]+\\)[]>]")
3574 org-maybe-keyword-time-regexp
3575 (concat "\\(\\<\\(" org-scheduled-string
3576 "\\|" org-deadline-string
3577 "\\|" org-closed-string
3578 "\\|" org-clock-string "\\)\\)?"
3579 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3580 org-planning-or-clock-line-re
3581 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3582 "\\|" org-deadline-string
3583 "\\|" org-closed-string "\\|" org-clock-string "\\)\\>\\)")
3586 (org-set-font-lock-defaults)))
3589 ;;; Some variables ujsed in various places
3591 (defvar org-window-configuration nil
3592 "Used in various places to store a window configuration.")
3593 (defvar org-finish-function nil
3594 "Function to be called when `C-c C-c' is used.
3595 This is for getting out of special buffers like remember.")
3597 ;;; Foreign variables, to inform the compiler
3599 ;; XEmacs only
3600 (defvar outline-mode-menu-heading)
3601 (defvar outline-mode-menu-show)
3602 (defvar outline-mode-menu-hide)
3603 (defvar zmacs-regions) ; XEmacs regions
3604 ;; Emacs only
3605 (defvar mark-active)
3607 ;; Packages that org-mode interacts with
3608 (defvar calc-embedded-close-formula)
3609 (defvar calc-embedded-open-formula)
3610 (defvar font-lock-unfontify-region-function)
3611 (defvar org-goto-start-pos)
3612 (defvar vm-message-pointer)
3613 (defvar vm-folder-directory)
3614 (defvar wl-summary-buffer-elmo-folder)
3615 (defvar wl-summary-buffer-folder-name)
3616 (defvar gnus-other-frame-object)
3617 (defvar gnus-group-name)
3618 (defvar gnus-article-current)
3619 (defvar w3m-current-url)
3620 (defvar w3m-current-title)
3621 (defvar mh-progs)
3622 (defvar mh-current-folder)
3623 (defvar mh-show-folder-buffer)
3624 (defvar mh-index-folder)
3625 (defvar mh-searcher)
3626 (defvar calendar-mode-map)
3627 (defvar Info-current-file)
3628 (defvar Info-current-node)
3629 (defvar texmathp-why)
3630 (defvar remember-save-after-remembering)
3631 (defvar remember-data-file)
3632 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3633 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3634 (defvar org-latex-regexps)
3635 (defvar constants-unit-system)
3637 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3639 ;; FIXME: Occasionally check by commenting these, to make sure
3640 ;; no other functions uses these, forgetting to let-bind them.
3641 (defvar entry)
3642 (defvar state)
3643 (defvar last-state)
3644 (defvar date)
3645 (defvar description)
3648 ;; Defined somewhere in this file, but used before definition.
3649 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3650 (defvar org-agenda-undo-list)
3651 (defvar org-agenda-pending-undo-list)
3652 (defvar org-agenda-overriding-header)
3653 (defvar orgtbl-mode)
3654 (defvar org-html-entities)
3655 (defvar org-struct-menu)
3656 (defvar org-org-menu)
3657 (defvar org-tbl-menu)
3658 (defvar org-agenda-keymap)
3659 (defvar org-category-table)
3661 ;;;; Emacs/XEmacs compatibility
3663 ;; Overlay compatibility functions
3664 (defun org-make-overlay (beg end &optional buffer)
3665 (if (featurep 'xemacs)
3666 (make-extent beg end buffer)
3667 (make-overlay beg end buffer)))
3668 (defun org-delete-overlay (ovl)
3669 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3670 (defun org-detach-overlay (ovl)
3671 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3672 (defun org-move-overlay (ovl beg end &optional buffer)
3673 (if (featurep 'xemacs)
3674 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3675 (move-overlay ovl beg end buffer)))
3676 (defun org-overlay-put (ovl prop value)
3677 (if (featurep 'xemacs)
3678 (set-extent-property ovl prop value)
3679 (overlay-put ovl prop value)))
3680 (defun org-overlay-display (ovl text &optional face evap)
3681 "Make overlay OVL display TEXT with face FACE."
3682 (if (featurep 'xemacs)
3683 (let ((gl (make-glyph text)))
3684 (and face (set-glyph-face gl face))
3685 (set-extent-property ovl 'invisible t)
3686 (set-extent-property ovl 'end-glyph gl))
3687 (overlay-put ovl 'display text)
3688 (if face (overlay-put ovl 'face face))
3689 (if evap (overlay-put ovl 'evaporate t))))
3690 (defun org-overlay-before-string (ovl text &optional face evap)
3691 "Make overlay OVL display TEXT with face FACE."
3692 (if (featurep 'xemacs)
3693 (let ((gl (make-glyph text)))
3694 (and face (set-glyph-face gl face))
3695 (set-extent-property ovl 'begin-glyph gl))
3696 (if face (org-add-props text nil 'face face))
3697 (overlay-put ovl 'before-string text)
3698 (if evap (overlay-put ovl 'evaporate t))))
3699 (defun org-overlay-get (ovl prop)
3700 (if (featurep 'xemacs)
3701 (extent-property ovl prop)
3702 (overlay-get ovl prop)))
3703 (defun org-overlays-at (pos)
3704 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3705 ;; FIXME: this is currently not used
3706 (defun org-overlays-in (&optional start end)
3707 (if (featurep 'xemacs)
3708 (extent-list nil start end)
3709 (overlays-in start end)))
3710 (defun org-overlay-start (o)
3711 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3712 (defun org-overlay-end (o)
3713 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3714 ;; FIXME: this is currently not used
3715 (defun org-find-overlays (prop &optional pos delete)
3716 "Find all overlays specifying PROP at POS or point.
3717 If DELETE is non-nil, delete all those overlays."
3718 (let ((overlays (org-overlays-at (or pos (point))))
3719 ov found)
3720 (while (setq ov (pop overlays))
3721 (if (org-overlay-get ov prop)
3722 (if delete (org-delete-overlay ov) (push ov found))))
3723 found))
3725 ;; Region compatibility
3727 (defun org-add-hook (hook function &optional append local)
3728 "Add-hook, compatible with both Emacsen."
3729 (if (and local (featurep 'xemacs))
3730 (add-local-hook hook function append)
3731 (add-hook hook function append local)))
3733 (defvar org-ignore-region nil
3734 "To temporarily disable the active region.")
3736 (defun org-region-active-p ()
3737 "Is `transient-mark-mode' on and the region active?
3738 Works on both Emacs and XEmacs."
3739 (if org-ignore-region
3741 (if (featurep 'xemacs)
3742 (and zmacs-regions (region-active-p))
3743 (and transient-mark-mode mark-active))))
3745 ;; Invisibility compatibility
3747 (defun org-add-to-invisibility-spec (arg)
3748 "Add elements to `buffer-invisibility-spec'.
3749 See documentation for `buffer-invisibility-spec' for the kind of elements
3750 that can be added."
3751 (cond
3752 ((fboundp 'add-to-invisibility-spec)
3753 (add-to-invisibility-spec arg))
3754 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3755 (setq buffer-invisibility-spec (list arg)))
3757 (setq buffer-invisibility-spec
3758 (cons arg buffer-invisibility-spec)))))
3760 (defun org-remove-from-invisibility-spec (arg)
3761 "Remove elements from `buffer-invisibility-spec'."
3762 (if (fboundp 'remove-from-invisibility-spec)
3763 (remove-from-invisibility-spec arg)
3764 (if (consp buffer-invisibility-spec)
3765 (setq buffer-invisibility-spec
3766 (delete arg buffer-invisibility-spec)))))
3768 ;; FIXME: this is currently not used
3769 (defun org-in-invisibility-spec-p (arg)
3770 "Is ARG a member of `buffer-invisibility-spec'?"
3771 (if (consp buffer-invisibility-spec)
3772 (member arg buffer-invisibility-spec)
3773 nil))
3775 ;;;; Define the Org-mode
3777 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3778 (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."))
3781 ;; We use a before-change function to check if a table might need
3782 ;; an update.
3783 (defvar org-table-may-need-update t
3784 "Indicates that a table might need an update.
3785 This variable is set by `org-before-change-function'.
3786 `org-table-align' sets it back to nil.")
3787 (defvar org-mode-map)
3788 (defvar org-mode-hook nil)
3789 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3790 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3791 (defvar org-table-buffer-is-an nil)
3794 ;;;###autoload
3795 (define-derived-mode org-mode outline-mode "Org"
3796 "Outline-based notes management and organizer, alias
3797 \"Carsten's outline-mode for keeping track of everything.\"
3799 Org-mode develops organizational tasks around a NOTES file which
3800 contains information about projects as plain text. Org-mode is
3801 implemented on top of outline-mode, which is ideal to keep the content
3802 of large files well structured. It supports ToDo items, deadlines and
3803 time stamps, which magically appear in the diary listing of the Emacs
3804 calendar. Tables are easily created with a built-in table editor.
3805 Plain text URL-like links connect to websites, emails (VM), Usenet
3806 messages (Gnus), BBDB entries, and any files related to the project.
3807 For printing and sharing of notes, an Org-mode file (or a part of it)
3808 can be exported as a structured ASCII or HTML file.
3810 The following commands are available:
3812 \\{org-mode-map}"
3814 ;; Get rid of Outline menus, they are not needed
3815 ;; Need to do this here because define-derived-mode sets up
3816 ;; the keymap so late. Still, it is a waste to call this each time
3817 ;; we switch another buffer into org-mode.
3818 (if (featurep 'xemacs)
3819 (when (boundp 'outline-mode-menu-heading)
3820 ;; Assume this is Greg's port, it used easymenu
3821 (easy-menu-remove outline-mode-menu-heading)
3822 (easy-menu-remove outline-mode-menu-show)
3823 (easy-menu-remove outline-mode-menu-hide))
3824 (define-key org-mode-map [menu-bar headings] 'undefined)
3825 (define-key org-mode-map [menu-bar hide] 'undefined)
3826 (define-key org-mode-map [menu-bar show] 'undefined))
3828 (easy-menu-add org-org-menu)
3829 (easy-menu-add org-tbl-menu)
3830 (org-install-agenda-files-menu)
3831 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3832 (org-add-to-invisibility-spec '(org-cwidth))
3833 (when (featurep 'xemacs)
3834 (org-set-local 'line-move-ignore-invisible t))
3835 (setq outline-regexp "\\*+")
3836 (setq outline-level 'org-outline-level)
3837 (when (and org-ellipsis (stringp org-ellipsis)
3838 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
3839 (unless org-display-table
3840 (setq org-display-table (make-display-table)))
3841 (set-display-table-slot org-display-table
3842 4 (string-to-vector org-ellipsis))
3843 (setq buffer-display-table org-display-table))
3844 (org-set-regexps-and-options)
3845 ;; Calc embedded
3846 (org-set-local 'calc-embedded-open-mode "# ")
3847 (modify-syntax-entry ?# "<")
3848 (modify-syntax-entry ?@ "w")
3849 (if org-startup-truncated (setq truncate-lines t))
3850 (org-set-local 'font-lock-unfontify-region-function
3851 'org-unfontify-region)
3852 ;; Activate before-change-function
3853 (org-set-local 'org-table-may-need-update t)
3854 (org-add-hook 'before-change-functions 'org-before-change-function nil
3855 'local)
3856 ;; Check for running clock before killing a buffer
3857 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3858 ;; Paragraphs and auto-filling
3859 (org-set-autofill-regexps)
3860 (setq indent-line-function 'org-indent-line-function)
3861 (org-update-radio-target-regexp)
3863 ;; Comment characters
3864 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3865 (org-set-local 'comment-padding " ")
3867 ;; Make isearch reveal context
3868 (if (or (featurep 'xemacs)
3869 (not (boundp 'outline-isearch-open-invisible-function)))
3870 ;; Emacs 21 and XEmacs make use of the hook
3871 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3872 ;; Emacs 22 deals with this through a special variable
3873 (org-set-local 'outline-isearch-open-invisible-function
3874 (lambda (&rest ignore) (org-show-context 'isearch))))
3876 ;; If empty file that did not turn on org-mode automatically, make it to.
3877 (if (and org-insert-mode-line-in-empty-file
3878 (interactive-p)
3879 (= (point-min) (point-max)))
3880 (insert "# -*- mode: org -*-\n\n"))
3882 (unless org-inhibit-startup
3883 (when org-startup-align-all-tables
3884 (let ((bmp (buffer-modified-p)))
3885 (org-table-map-tables 'org-table-align)
3886 (set-buffer-modified-p bmp)))
3887 (cond
3888 ((eq org-startup-folded t)
3889 (org-cycle '(4)))
3890 ((eq org-startup-folded 'content)
3891 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3892 (org-cycle '(4)) (org-cycle '(4)))))))
3894 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3896 (defsubst org-call-with-arg (command arg)
3897 "Call COMMAND interactively, but pretend prefix are was ARG."
3898 (let ((current-prefix-arg arg)) (call-interactively command)))
3900 (defsubst org-current-line (&optional pos)
3901 (save-excursion
3902 (and pos (goto-char pos))
3903 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
3905 (defun org-current-time ()
3906 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3907 (if (> org-time-stamp-rounding-minutes 0)
3908 (let ((r org-time-stamp-rounding-minutes)
3909 (time (decode-time)))
3910 (apply 'encode-time
3911 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3912 (nthcdr 2 time))))
3913 (current-time)))
3915 (defun org-add-props (string plist &rest props)
3916 "Add text properties to entire string, from beginning to end.
3917 PLIST may be a list of properties, PROPS are individual properties and values
3918 that will be added to PLIST. Returns the string that was modified."
3919 (add-text-properties
3920 0 (length string) (if props (append plist props) plist) string)
3921 string)
3922 (put 'org-add-props 'lisp-indent-function 2)
3925 ;;;; Font-Lock stuff, including the activators
3927 (defvar org-mouse-map (make-sparse-keymap))
3928 (org-defkey org-mouse-map
3929 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3930 (org-defkey org-mouse-map
3931 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3932 (when org-mouse-1-follows-link
3933 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3934 (when org-tab-follows-link
3935 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3936 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3937 (when org-return-follows-link
3938 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3939 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3941 (require 'font-lock)
3943 (defconst org-non-link-chars "]\t\n\r<>")
3944 (defconst org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
3945 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3946 (defconst org-link-re-with-space
3947 (concat
3948 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3949 "\\([^" org-non-link-chars " ]"
3950 "[^" org-non-link-chars "]*"
3951 "[^" org-non-link-chars " ]\\)>?")
3952 "Matches a link with spaces, optional angular brackets around it.")
3954 (defconst org-link-re-with-space2
3955 (concat
3956 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3957 "\\([^" org-non-link-chars " ]"
3958 "[^]\t\n\r]*"
3959 "[^" org-non-link-chars " ]\\)>?")
3960 "Matches a link with spaces, optional angular brackets around it.")
3962 (defconst org-angle-link-re
3963 (concat
3964 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3965 "\\([^" org-non-link-chars " ]"
3966 "[^" org-non-link-chars "]*"
3967 "\\)>")
3968 "Matches link with angular brackets, spaces are allowed.")
3969 (defconst org-plain-link-re
3970 (concat
3971 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3972 "\\([^]\t\n\r<>,;() ]+\\)")
3973 "Matches plain link, without spaces.")
3975 (defconst org-bracket-link-regexp
3976 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3977 "Matches a link in double brackets.")
3979 (defconst org-bracket-link-analytic-regexp
3980 (concat
3981 "\\[\\["
3982 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3983 "\\([^]]+\\)"
3984 "\\]"
3985 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3986 "\\]"))
3987 ; 1: http:
3988 ; 2: http
3989 ; 3: path
3990 ; 4: [desc]
3991 ; 5: desc
3993 (defconst org-any-link-re
3994 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3995 org-angle-link-re "\\)\\|\\("
3996 org-plain-link-re "\\)")
3997 "Regular expression matching any link.")
3999 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4000 "Regular expression for fast time stamp matching.")
4001 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4002 "Regular expression for fast time stamp matching.")
4003 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4004 "Regular expression matching time strings for analysis.
4005 This one does not require the space after the date.")
4006 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4007 "Regular expression matching time strings for analysis.")
4008 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,11\\}>")
4009 "Regular expression matching time stamps, with groups.")
4010 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,11\\}[]>]")
4011 "Regular expression matching time stamps (also [..]), with groups.")
4012 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4013 "Regular expression matching a time stamp range.")
4014 (defconst org-tr-regexp-both
4015 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4016 "Regular expression matching a time stamp range.")
4017 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4018 org-ts-regexp "\\)?")
4019 "Regular expression matching a time stamp or time stamp range.")
4020 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4021 org-ts-regexp-both "\\)?")
4022 "Regular expression matching a time stamp or time stamp range.
4023 The time stamps may be either active or inactive.")
4025 (defvar org-emph-face nil)
4027 (defun org-do-emphasis-faces (limit)
4028 "Run through the buffer and add overlays to links."
4029 (let (rtn)
4030 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4031 (if (not (= (char-after (match-beginning 3))
4032 (char-after (match-beginning 4))))
4033 (progn
4034 (setq rtn t)
4035 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4036 'face
4037 (nth 1 (assoc (match-string 3)
4038 org-emphasis-alist)))
4039 (add-text-properties (match-beginning 2) (match-end 2)
4040 '(font-lock-multiline t))
4041 (backward-char 1))))
4042 rtn))
4044 (defun org-emphasize (&optional char)
4045 "Insert or change an emphasis, i.e. a font like bold or italic.
4046 If there is an active region, change that region to a new emphasis.
4047 If there is no region, just insert the marker characters and position
4048 the cursor between them.
4049 CHAR should be either the marker character, or the first character of the
4050 HTML tag associated with that emphasis. If CHAR is a space, the means
4051 to remove the emphasis of the selected region.
4052 If char is not given (for example in an interactive call) it
4053 will be prompted for."
4054 (interactive)
4055 (let ((eal org-emphasis-alist) e det
4056 (erc org-emphasis-regexp-components)
4057 (prompt "")
4058 (string "") beg end move tag c s)
4059 (if (org-region-active-p)
4060 (setq beg (region-beginning) end (region-end)
4061 string (buffer-substring beg end))
4062 (setq move t))
4064 (while (setq e (pop eal))
4065 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4066 c (aref tag 0))
4067 (push (cons c (string-to-char (car e))) det)
4068 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4069 (substring tag 1)))))
4070 (unless char
4071 (message "%s" (concat "Emphasis marker or tag:" prompt))
4072 (setq char (read-char-exclusive)))
4073 (setq char (or (cdr (assoc char det)) char))
4074 (if (equal char ?\ )
4075 (setq s "" move nil)
4076 (unless (assoc (char-to-string char) org-emphasis-alist)
4077 (error "No such emphasis marker: \"%c\"" char))
4078 (setq s (char-to-string char)))
4079 (while (and (> (length string) 1)
4080 (equal (substring string 0 1) (substring string -1))
4081 (assoc (substring string 0 1) org-emphasis-alist))
4082 (setq string (substring string 1 -1)))
4083 (setq string (concat s string s))
4084 (if beg (delete-region beg end))
4085 (unless (or (bolp)
4086 (string-match (concat "[" (nth 0 erc) "\n]")
4087 (char-to-string (char-before (point)))))
4088 (insert " "))
4089 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4090 (char-to-string (char-after (point))))
4091 (insert " ") (backward-char 1))
4092 (insert string)
4093 (and move (backward-char 1))))
4095 (defun org-activate-plain-links (limit)
4096 "Run through the buffer and add overlays to links."
4097 (catch 'exit
4098 (let (f)
4099 (while (re-search-forward org-plain-link-re limit t)
4100 (setq f (get-text-property (match-beginning 0) 'face))
4101 (if (or (eq f 'org-tag)
4102 (and (listp f) (memq 'org-tag f)))
4104 (add-text-properties (match-beginning 0) (match-end 0)
4105 (list 'mouse-face 'highlight
4106 'rear-nonsticky t
4107 'keymap org-mouse-map
4109 (throw 'exit t))))))
4111 (defun org-activate-angle-links (limit)
4112 "Run through the buffer and add overlays to links."
4113 (if (re-search-forward org-angle-link-re limit t)
4114 (progn
4115 (add-text-properties (match-beginning 0) (match-end 0)
4116 (list 'mouse-face 'highlight
4117 'rear-nonsticky t
4118 'keymap org-mouse-map
4120 t)))
4122 (defmacro org-maybe-intangible (props)
4123 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4124 In emacs 21, invisible text is not avoided by the command loop, so the
4125 intangible property is needed to make sure point skips this text.
4126 In Emacs 22, this is not necessary. The intangible text property has
4127 led to problems with flyspell. These problems are fixed in flyspell.el,
4128 but we still avoid setting the property in Emacs 22 and later.
4129 We use a macro so that the test can happen at compilation time."
4130 (if (< emacs-major-version 22)
4131 `(append '(intangible t) ,props)
4132 props))
4134 (defun org-activate-bracket-links (limit)
4135 "Run through the buffer and add overlays to bracketed links."
4136 (if (re-search-forward org-bracket-link-regexp limit t)
4137 (let* ((help (concat "LINK: "
4138 (org-match-string-no-properties 1)))
4139 ;; FIXME: above we should remove the escapes.
4140 ;; but that requires another match, protecting match data,
4141 ;; a lot of overhead for font-lock.
4142 (ip (org-maybe-intangible
4143 (list 'invisible 'org-link 'rear-nonsticky t
4144 'keymap org-mouse-map 'mouse-face 'highlight
4145 'help-echo help)))
4146 (vp (list 'rear-nonsticky t
4147 'keymap org-mouse-map 'mouse-face 'highlight
4148 'help-echo help)))
4149 ;; We need to remove the invisible property here. Table narrowing
4150 ;; may have made some of this invisible.
4151 (remove-text-properties (match-beginning 0) (match-end 0)
4152 '(invisible nil))
4153 (if (match-end 3)
4154 (progn
4155 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4156 (add-text-properties (match-beginning 3) (match-end 3) vp)
4157 (add-text-properties (match-end 3) (match-end 0) ip))
4158 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4159 (add-text-properties (match-beginning 1) (match-end 1) vp)
4160 (add-text-properties (match-end 1) (match-end 0) ip))
4161 t)))
4163 (defun org-activate-dates (limit)
4164 "Run through the buffer and add overlays to dates."
4165 (if (re-search-forward org-tsr-regexp-both limit t)
4166 (progn
4167 (add-text-properties (match-beginning 0) (match-end 0)
4168 (list 'mouse-face 'highlight
4169 'rear-nonsticky t
4170 'keymap org-mouse-map))
4171 (when org-display-custom-times
4172 (if (match-end 3)
4173 (org-display-custom-time (match-beginning 3) (match-end 3)))
4174 (org-display-custom-time (match-beginning 1) (match-end 1)))
4175 t)))
4177 (defvar org-target-link-regexp nil
4178 "Regular expression matching radio targets in plain text.")
4179 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4180 "Regular expression matching a link target.")
4181 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4182 "Regular expression matching a radio target.")
4183 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4184 "Regular expression matching any target.")
4186 (defun org-activate-target-links (limit)
4187 "Run through the buffer and add overlays to target matches."
4188 (when org-target-link-regexp
4189 (let ((case-fold-search t))
4190 (if (re-search-forward org-target-link-regexp limit t)
4191 (progn
4192 (add-text-properties (match-beginning 0) (match-end 0)
4193 (list 'mouse-face 'highlight
4194 'rear-nonsticky t
4195 'keymap org-mouse-map
4196 'help-echo "Radio target link"
4197 'org-linked-text t))
4198 t)))))
4200 (defun org-update-radio-target-regexp ()
4201 "Find all radio targets in this file and update the regular expression."
4202 (interactive)
4203 (when (memq 'radio org-activate-links)
4204 (setq org-target-link-regexp
4205 (org-make-target-link-regexp (org-all-targets 'radio)))
4206 (org-restart-font-lock)))
4208 (defun org-hide-wide-columns (limit)
4209 (let (s e)
4210 (setq s (text-property-any (point) (or limit (point-max))
4211 'org-cwidth t))
4212 (when s
4213 (setq e (next-single-property-change s 'org-cwidth))
4214 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4215 (goto-char e)
4216 t)))
4218 (defun org-restart-font-lock ()
4219 "Restart font-lock-mode, to force refontification."
4220 (when (and (boundp 'font-lock-mode) font-lock-mode)
4221 (font-lock-mode -1)
4222 (font-lock-mode 1)))
4224 (defun org-all-targets (&optional radio)
4225 "Return a list of all targets in this file.
4226 With optional argument RADIO, only find radio targets."
4227 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4228 rtn)
4229 (save-excursion
4230 (goto-char (point-min))
4231 (while (re-search-forward re nil t)
4232 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4233 rtn)))
4235 (defun org-make-target-link-regexp (targets)
4236 "Make regular expression matching all strings in TARGETS.
4237 The regular expression finds the targets also if there is a line break
4238 between words."
4239 (and targets
4240 (concat
4241 "\\<\\("
4242 (mapconcat
4243 (lambda (x)
4244 (while (string-match " +" x)
4245 (setq x (replace-match "\\s-+" t t x)))
4247 targets
4248 "\\|")
4249 "\\)\\>")))
4251 (defun org-activate-tags (limit)
4252 (if (re-search-forward "[ \t]\\(:[a-zA-Z0-9_@:]+:\\)[ \r\n]" limit t)
4253 (progn
4254 (add-text-properties (match-beginning 1) (match-end 1)
4255 (list 'mouse-face 'highlight
4256 'rear-nonsticky t
4257 'keymap org-mouse-map))
4258 t)))
4260 (defun org-outline-level ()
4261 (save-excursion
4262 (looking-at outline-regexp)
4263 (if (match-beginning 1)
4264 (+ (org-get-string-indentation (match-string 1)) 1000)
4265 (- (match-end 0) (match-beginning 0)))))
4267 (defvar org-font-lock-keywords nil)
4269 (defun org-set-font-lock-defaults ()
4270 (let* ((em org-fontify-emphasized-text)
4271 (lk org-activate-links)
4272 (org-font-lock-extra-keywords
4273 ;; Headlines
4274 (list
4275 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
4276 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4277 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4278 (1 'org-table))
4279 ;; Links
4280 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4281 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4282 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4283 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4284 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4285 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4286 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4287 '(org-hide-wide-columns (0 nil append))
4288 ;; TODO lines
4289 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
4290 '(1 'org-todo t))
4291 ;; Priorities
4292 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4293 ;; Special keywords
4294 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4295 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4296 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4297 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4298 ;; Emphasis
4299 (if em
4300 (if (featurep 'xemacs)
4301 '(org-do-emphasis-faces (0 nil append))
4302 '(org-do-emphasis-faces)))
4303 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
4304 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
4305 2 'bold prepend)
4306 (if org-provide-checkbox-statistics
4307 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4308 (0 (org-get-checkbox-statistics-face) t)))
4309 ;; COMMENT
4310 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
4311 "\\|" org-quote-string "\\)\\>")
4312 '(1 'org-special-keyword t))
4313 '("^#.*" (0 'font-lock-comment-face t))
4314 ;; DONE
4315 (if org-fontify-done-headline
4316 (list (concat "^[*]+ +\\<\\("
4317 (mapconcat 'regexp-quote org-done-keywords "\\|")
4318 "\\)\\(.*\\)")
4319 '(1 'org-done t) '(2 'org-headline-done t))
4320 (list (concat "^[*]+ +\\<\\("
4321 (mapconcat 'regexp-quote org-done-keywords "\\|")
4322 "\\)\\>")
4323 '(1 'org-done t)))
4324 ;; Table stuff
4325 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
4326 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4327 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
4328 (if org-format-transports-properties-p
4329 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4330 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4332 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4333 ;; Now set the full font-lock-keywords
4334 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4335 (org-set-local 'font-lock-defaults
4336 '(org-font-lock-keywords t nil nil backward-paragraph))
4337 (kill-local-variable 'font-lock-keywords) nil))
4339 (defvar org-m nil)
4340 (defvar org-l nil)
4341 (defvar org-f nil)
4342 (defun org-get-level-face (n)
4343 "Get the right face for match N in font-lock matching of healdines."
4344 (setq org-l (- (match-end 2) (match-beginning 1)))
4345 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4346 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
4347 (cond
4348 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4349 ((eq n 2) org-f)
4350 (t (if org-level-color-stars-only nil org-f))))
4352 (defun org-unfontify-region (beg end &optional maybe_loudly)
4353 "Remove fontification and activation overlays from links."
4354 (font-lock-default-unfontify-region beg end)
4355 (let* ((buffer-undo-list t)
4356 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4357 (inhibit-modification-hooks t)
4358 deactivate-mark buffer-file-name buffer-file-truename)
4359 (remove-text-properties beg end
4360 '(mouse-face t keymap t org-linked-text t
4361 rear-nonsticky t
4362 invisible t intangible t))))
4364 ;;;; Visibility cycling, including org-goto and indirect buffer
4366 ;;; Cycling
4368 (defvar org-cycle-global-status nil)
4369 (make-variable-buffer-local 'org-cycle-global-status)
4370 (defvar org-cycle-subtree-status nil)
4371 (make-variable-buffer-local 'org-cycle-subtree-status)
4373 ;;;###autoload
4374 (defun org-cycle (&optional arg)
4375 "Visibility cycling for Org-mode.
4377 - When this function is called with a prefix argument, rotate the entire
4378 buffer through 3 states (global cycling)
4379 1. OVERVIEW: Show only top-level headlines.
4380 2. CONTENTS: Show all headlines of all levels, but no body text.
4381 3. SHOW ALL: Show everything.
4383 - When point is at the beginning of a headline, rotate the subtree started
4384 by this line through 3 different states (local cycling)
4385 1. FOLDED: Only the main headline is shown.
4386 2. CHILDREN: The main headline and the direct children are shown.
4387 From this state, you can move to one of the children
4388 and zoom in further.
4389 3. SUBTREE: Show the entire subtree, including body text.
4391 - When there is a numeric prefix, go up to a heading with level ARG, do
4392 a `show-subtree' and return to the previous cursor position. If ARG
4393 is negative, go up that many levels.
4395 - When point is not at the beginning of a headline, execute
4396 `indent-relative', like TAB normally does. See the option
4397 `org-cycle-emulate-tab' for details.
4399 - Special case: if point is at the beginning of the buffer and there is
4400 no headline in line 1, this function will act as if called with prefix arg."
4401 (interactive "P")
4402 (let* ((outline-regexp
4403 (if (and (org-mode-p) org-cycle-include-plain-lists)
4404 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4405 outline-regexp))
4406 (bob-special (and org-cycle-global-at-bob (bobp)
4407 (not (looking-at outline-regexp))))
4408 (org-cycle-hook
4409 (if bob-special
4410 (delq 'org-optimize-window-after-visibility-change
4411 (copy-sequence org-cycle-hook))
4412 org-cycle-hook))
4413 (pos (point)))
4415 (if (or bob-special (equal arg '(4)))
4416 ;; special case: use global cycling
4417 (setq arg t))
4419 (cond
4421 ((org-at-table-p 'any)
4422 ;; Enter the table or move to the next field in the table
4423 (or (org-table-recognize-table.el)
4424 (progn
4425 (if arg (org-table-edit-field t)
4426 (org-table-justify-field-maybe)
4427 (call-interactively 'org-table-next-field)))))
4429 ((eq arg t) ;; Global cycling
4431 (cond
4432 ((and (eq last-command this-command)
4433 (eq org-cycle-global-status 'overview))
4434 ;; We just created the overview - now do table of contents
4435 ;; This can be slow in very large buffers, so indicate action
4436 (message "CONTENTS...")
4437 (org-content)
4438 (message "CONTENTS...done")
4439 (setq org-cycle-global-status 'contents)
4440 (run-hook-with-args 'org-cycle-hook 'contents))
4442 ((and (eq last-command this-command)
4443 (eq org-cycle-global-status 'contents))
4444 ;; We just showed the table of contents - now show everything
4445 (show-all)
4446 (message "SHOW ALL")
4447 (setq org-cycle-global-status 'all)
4448 (run-hook-with-args 'org-cycle-hook 'all))
4451 ;; Default action: go to overview
4452 (org-overview)
4453 (message "OVERVIEW")
4454 (setq org-cycle-global-status 'overview)
4455 (run-hook-with-args 'org-cycle-hook 'overview))))
4457 ((integerp arg)
4458 ;; Show-subtree, ARG levels up from here.
4459 (save-excursion
4460 (org-back-to-heading)
4461 (outline-up-heading (if (< arg 0) (- arg)
4462 (- (funcall outline-level) arg)))
4463 (org-show-subtree)))
4465 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4466 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4467 ;; At a heading: rotate between three different views
4468 (org-back-to-heading)
4469 (let ((goal-column 0) eoh eol eos)
4470 ;; First, some boundaries
4471 (save-excursion
4472 (org-back-to-heading)
4473 (save-excursion
4474 (beginning-of-line 2)
4475 (while (and (not (eobp)) ;; this is like `next-line'
4476 (get-char-property (1- (point)) 'invisible))
4477 (beginning-of-line 2)) (setq eol (point)))
4478 (outline-end-of-heading) (setq eoh (point))
4479 (org-end-of-subtree t)
4480 (unless (eobp)
4481 (skip-chars-forward " \t\n")
4482 (beginning-of-line 1) ; in case this is an item
4484 (setq eos (1- (point))))
4485 ;; Find out what to do next and set `this-command'
4486 (cond
4487 ((= eos eoh)
4488 ;; Nothing is hidden behind this heading
4489 (message "EMPTY ENTRY")
4490 (setq org-cycle-subtree-status nil)
4491 (save-excursion
4492 (goto-char eos)
4493 (outline-next-heading)
4494 (if (org-invisible-p) (org-flag-heading nil))))
4495 ((>= eol eos)
4496 ;; Entire subtree is hidden in one line: open it
4497 (org-show-entry)
4498 (show-children)
4499 (message "CHILDREN")
4500 (save-excursion
4501 (goto-char eos)
4502 (outline-next-heading)
4503 (if (org-invisible-p) (org-flag-heading nil)))
4504 (setq org-cycle-subtree-status 'children)
4505 (run-hook-with-args 'org-cycle-hook 'children))
4506 ((and (eq last-command this-command)
4507 (eq org-cycle-subtree-status 'children))
4508 ;; We just showed the children, now show everything.
4509 (org-show-subtree)
4510 (message "SUBTREE")
4511 (setq org-cycle-subtree-status 'subtree)
4512 (run-hook-with-args 'org-cycle-hook 'subtree))
4514 ;; Default action: hide the subtree.
4515 (hide-subtree)
4516 (message "FOLDED")
4517 (setq org-cycle-subtree-status 'folded)
4518 (run-hook-with-args 'org-cycle-hook 'folded)))))
4520 ;; TAB emulation
4521 (buffer-read-only (org-back-to-heading))
4523 ((org-try-cdlatex-tab))
4525 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4526 (or (not (bolp))
4527 (not (looking-at outline-regexp))))
4528 (call-interactively (global-key-binding "\t")))
4530 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4531 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4532 (or (and (eq org-cycle-emulate-tab 'white)
4533 (= (match-end 0) (point-at-eol)))
4534 (and (eq org-cycle-emulate-tab 'whitestart)
4535 (>= (match-end 0) pos))))
4537 (eq org-cycle-emulate-tab t))
4538 (if (and (looking-at "[ \n\r\t]")
4539 (string-match "^[ \t]*$" (buffer-substring
4540 (point-at-bol) (point))))
4541 (progn
4542 (beginning-of-line 1)
4543 (and (looking-at "[ \t]+") (replace-match ""))))
4544 (call-interactively (global-key-binding "\t")))
4546 (t (save-excursion
4547 (org-back-to-heading)
4548 (org-cycle))))))
4550 ;;;###autoload
4551 (defun org-global-cycle (&optional arg)
4552 "Cycle the global visibility. For details see `org-cycle'."
4553 (interactive "P")
4554 (let ((org-cycle-include-plain-lists
4555 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4556 (if (integerp arg)
4557 (progn
4558 (show-all)
4559 (hide-sublevels arg)
4560 (setq org-cycle-global-status 'contents))
4561 (org-cycle '(4)))))
4563 (defun org-overview ()
4564 "Switch to overview mode, shoing only top-level headlines.
4565 Really, this shows all headlines with level equal or greater than the level
4566 of the first headline in the buffer. This is important, because if the
4567 first headline is not level one, then (hide-sublevels 1) gives confusing
4568 results."
4569 (interactive)
4570 (let ((level (save-excursion
4571 (goto-char (point-min))
4572 (if (re-search-forward (concat "^" outline-regexp) nil t)
4573 (progn
4574 (goto-char (match-beginning 0))
4575 (funcall outline-level))))))
4576 (and level (hide-sublevels level))))
4578 (defun org-content (&optional arg)
4579 "Show all headlines in the buffer, like a table of contents.
4580 With numerical argument N, show content up to level N."
4581 (interactive "P")
4582 (save-excursion
4583 ;; Visit all headings and show their offspring
4584 (and (integerp arg) (org-overview))
4585 (goto-char (point-max))
4586 (catch 'exit
4587 (while (and (progn (condition-case nil
4588 (outline-previous-visible-heading 1)
4589 (error (goto-char (point-min))))
4591 (looking-at outline-regexp))
4592 (if (integerp arg)
4593 (show-children (1- arg))
4594 (show-branches))
4595 (if (bobp) (throw 'exit nil))))))
4598 (defun org-optimize-window-after-visibility-change (state)
4599 "Adjust the window after a change in outline visibility.
4600 This function is the default value of the hook `org-cycle-hook'."
4601 (when (get-buffer-window (current-buffer))
4602 (cond
4603 ; ((eq state 'overview) (org-first-headline-recenter 1))
4604 ; ((eq state 'overview) (org-beginning-of-line))
4605 ((eq state 'content) nil)
4606 ((eq state 'all) nil)
4607 ((eq state 'folded) nil)
4608 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4609 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4612 (defun org-cycle-show-empty-lines (state)
4613 "Show empty lines above all visible headlines.
4614 The region to be covered depends on STATE when called through
4615 `org-cycle-hook'. Lisp program can use t for STATE to get the
4616 entire buffer covered. Note that an empty line is only shown if there
4617 are at least `org-cycle-separator-lines' empty lines before the headeline."
4618 (when (> org-cycle-separator-lines 0)
4619 (save-excursion
4620 (let* ((n org-cycle-separator-lines)
4621 (re (cond
4622 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4623 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4624 (t (let ((ns (number-to-string (- n 2))))
4625 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4626 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4627 beg end)
4628 (cond
4629 ((memq state '(overview contents t))
4630 (setq beg (point-min) end (point-max)))
4631 ((memq state '(children folded))
4632 (setq beg (point) end (progn (org-end-of-subtree t t)
4633 (beginning-of-line 2)
4634 (point)))))
4635 (when beg
4636 (goto-char beg)
4637 (while (re-search-forward re end t)
4638 (if (not (get-char-property (match-end 1) 'invisible))
4639 (outline-flag-region
4640 (match-beginning 1) (match-end 1) nil)))))))
4641 ;; Never hide empty lines at the end of the file.
4642 (save-excursion
4643 (goto-char (point-max))
4644 (outline-previous-heading)
4645 (outline-end-of-heading)
4646 (if (and (looking-at "[ \t\n]+")
4647 (= (match-end 0) (point-max)))
4648 (outline-flag-region (point) (match-end 0) nil))))
4650 (defun org-subtree-end-visible-p ()
4651 "Is the end of the current subtree visible?"
4652 (pos-visible-in-window-p
4653 (save-excursion (org-end-of-subtree t) (point))))
4655 (defun org-first-headline-recenter (&optional N)
4656 "Move cursor to the first headline and recenter the headline.
4657 Optional argument N means, put the headline into the Nth line of the window."
4658 (goto-char (point-min))
4659 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4660 (beginning-of-line)
4661 (recenter (prefix-numeric-value N))))
4663 ;;; Org-goto
4665 (defvar org-goto-window-configuration nil)
4666 (defvar org-goto-marker nil)
4667 (defvar org-goto-map (make-sparse-keymap))
4668 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4669 (while (setq cmd (pop cmds))
4670 (substitute-key-definition cmd cmd org-goto-map global-map)))
4671 (org-defkey org-goto-map "\C-m" 'org-goto-ret)
4672 (org-defkey org-goto-map [(left)] 'org-goto-left)
4673 (org-defkey org-goto-map [(right)] 'org-goto-right)
4674 (org-defkey org-goto-map [(?q)] 'org-goto-quit)
4675 (org-defkey org-goto-map [(control ?g)] 'org-goto-quit)
4676 (org-defkey org-goto-map "\C-i" 'org-cycle)
4677 (org-defkey org-goto-map [(tab)] 'org-cycle)
4678 (org-defkey org-goto-map [(down)] 'outline-next-visible-heading)
4679 (org-defkey org-goto-map [(up)] 'outline-previous-visible-heading)
4680 (org-defkey org-goto-map "n" 'outline-next-visible-heading)
4681 (org-defkey org-goto-map "p" 'outline-previous-visible-heading)
4682 (org-defkey org-goto-map "f" 'outline-forward-same-level)
4683 (org-defkey org-goto-map "b" 'outline-backward-same-level)
4684 (org-defkey org-goto-map "u" 'outline-up-heading)
4685 (org-defkey org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4686 (org-defkey org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4687 (org-defkey org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4688 (org-defkey org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4689 (org-defkey org-goto-map "\C-c\C-u" 'outline-up-heading)
4690 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4691 (while l (org-defkey org-goto-map (int-to-string (pop l)) 'digit-argument)))
4693 (defconst org-goto-help
4694 "Select a location to jump to, press RET
4695 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4697 (defun org-goto ()
4698 "Go to a different location of the document, keeping current visibility.
4700 When you want to go to a different location in a document, the fastest way
4701 is often to fold the entire buffer and then dive into the tree. This
4702 method has the disadvantage, that the previous location will be folded,
4703 which may not be what you want.
4705 This command works around this by showing a copy of the current buffer in
4706 overview mode. You can dive into the tree in that copy, to find the
4707 location you want to reach. When pressing RET, the command returns to the
4708 original buffer in which the visibility is still unchanged. It then jumps
4709 to the new location, making it and the headline hierarchy above it visible."
4710 (interactive)
4711 (let* ((org-goto-start-pos (point))
4712 (selected-point
4713 (org-get-location (current-buffer) org-goto-help)))
4714 (if selected-point
4715 (progn
4716 (org-mark-ring-push org-goto-start-pos)
4717 (goto-char selected-point)
4718 (if (or (org-invisible-p) (org-invisible-p2))
4719 (org-show-context 'org-goto)))
4720 (error "Quit"))))
4722 (defvar org-selected-point nil) ; dynamically scoped parameter
4724 (defun org-get-location (buf help)
4725 "Let the user select a location in the Org-mode buffer BUF.
4726 This function uses a recursive edit. It returns the selected position
4727 or nil."
4728 (let (org-selected-point)
4729 (save-excursion
4730 (save-window-excursion
4731 (delete-other-windows)
4732 (switch-to-buffer (get-buffer-create "*org-goto*"))
4733 (with-output-to-temp-buffer "*Help*"
4734 (princ help))
4735 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4736 (setq buffer-read-only nil)
4737 (erase-buffer)
4738 (insert-buffer-substring buf)
4739 (let ((org-startup-truncated t)
4740 (org-startup-folded t)
4741 (org-startup-align-all-tables nil))
4742 (org-mode))
4743 (setq buffer-read-only t)
4744 (if (and (boundp 'org-goto-start-pos)
4745 (integer-or-marker-p org-goto-start-pos))
4746 (let ((org-show-hierarchy-above t)
4747 (org-show-siblings t)
4748 (org-show-following-heading t))
4749 (goto-char org-goto-start-pos)
4750 (and (org-invisible-p) (org-show-context)))
4751 (goto-char (point-min)))
4752 (org-beginning-of-line)
4753 (message "Select location and press RET")
4754 ;; now we make sure that during selection, ony very few keys work
4755 ;; and that it is impossible to switch to another window.
4756 (let ((gm (current-global-map))
4757 (overriding-local-map org-goto-map))
4758 (unwind-protect
4759 (progn
4760 (use-global-map org-goto-map)
4761 (recursive-edit))
4762 (use-global-map gm)))))
4763 (kill-buffer "*org-goto*")
4764 org-selected-point))
4766 (defun org-goto-ret (&optional arg)
4767 "Finish `org-goto' by going to the new location."
4768 (interactive "P")
4769 (setq org-selected-point (point)
4770 current-prefix-arg arg)
4771 (throw 'exit nil))
4773 (defun org-goto-left ()
4774 "Finish `org-goto' by going to the new location."
4775 (interactive)
4776 (if (org-on-heading-p)
4777 (progn
4778 (beginning-of-line 1)
4779 (setq org-selected-point (point)
4780 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4781 (throw 'exit nil))
4782 (error "Not on a heading")))
4784 (defun org-goto-right ()
4785 "Finish `org-goto' by going to the new location."
4786 (interactive)
4787 (if (org-on-heading-p)
4788 (progn
4789 (outline-end-of-subtree)
4790 (or (eobp) (forward-char 1))
4791 (setq org-selected-point (point)
4792 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4793 (throw 'exit nil))
4794 (error "Not on a heading")))
4796 (defun org-goto-quit ()
4797 "Finish `org-goto' without cursor motion."
4798 (interactive)
4799 (setq org-selected-point nil)
4800 (throw 'exit nil))
4802 ;;; Indirect buffer display of subtrees
4804 (defvar org-indirect-dedicated-frame nil
4805 "This is the frame being used for indirect tree display.")
4806 (defvar org-last-indirect-buffer nil)
4808 (defun org-tree-to-indirect-buffer (&optional arg)
4809 "Create indirect buffer and narrow it to current subtree.
4810 With numerical prefix ARG, go up to this level and then take that tree.
4811 If ARG is negative, go up that many levels.
4812 Normally this command removes the indirect buffer previously made
4813 with this command. However, when called with a C-u prefix, the last buffer
4814 is kept so that you can work with several indirect buffers at the same time.
4815 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4816 requests that a new frame be made for the new buffer, so that the dedicated
4817 frame is not changed."
4818 (interactive "P")
4819 (let ((cbuf (current-buffer))
4820 (cwin (selected-window))
4821 (pos (point))
4822 beg end level heading ibuf)
4823 (save-excursion
4824 (org-back-to-heading t)
4825 (when (numberp arg)
4826 (setq level (org-outline-level))
4827 (if (< arg 0) (setq arg (+ level arg)))
4828 (while (> (setq level (org-outline-level)) arg)
4829 (outline-up-heading 1 t)))
4830 (setq beg (point)
4831 heading (org-get-heading))
4832 (org-end-of-subtree t) (setq end (point)))
4833 (if (and (not arg)
4834 (buffer-live-p org-last-indirect-buffer))
4835 (kill-buffer org-last-indirect-buffer))
4836 (setq ibuf (org-get-indirect-buffer cbuf)
4837 org-last-indirect-buffer ibuf)
4838 (cond
4839 ((or (eq org-indirect-buffer-display 'new-frame)
4840 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4841 (select-frame (make-frame))
4842 (delete-other-windows)
4843 (switch-to-buffer ibuf)
4844 (org-set-frame-title heading))
4845 ((eq org-indirect-buffer-display 'dedicated-frame)
4846 (raise-frame
4847 (select-frame (or (and org-indirect-dedicated-frame
4848 (frame-live-p org-indirect-dedicated-frame)
4849 org-indirect-dedicated-frame)
4850 (setq org-indirect-dedicated-frame (make-frame)))))
4851 (delete-other-windows)
4852 (switch-to-buffer ibuf)
4853 (org-set-frame-title (concat "Indirect: " heading)))
4854 ((eq org-indirect-buffer-display 'current-window)
4855 (switch-to-buffer ibuf))
4856 ((eq org-indirect-buffer-display 'other-window)
4857 (pop-to-buffer ibuf))
4858 (t (error "Invalid value.")))
4859 (if (featurep 'xemacs)
4860 (save-excursion (org-mode) (turn-on-font-lock)))
4861 (narrow-to-region beg end)
4862 (show-all)
4863 (goto-char pos)
4864 (and (window-live-p cwin) (select-window cwin))))
4866 (defun org-get-indirect-buffer (&optional buffer)
4867 (setq buffer (or buffer (current-buffer)))
4868 (let ((n 1) (base (buffer-name buffer)) bname)
4869 (while (buffer-live-p
4870 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4871 (setq n (1+ n)))
4872 (condition-case nil
4873 (make-indirect-buffer buffer bname 'clone)
4874 (error (make-indirect-buffer buffer bname)))))
4876 (defun org-set-frame-title (title)
4877 "Set the title of the current frame to the string TITLE."
4878 ;; FIXME: how to name a single frame in XEmacs???
4879 (unless (featurep 'xemacs)
4880 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4882 ;;;; Structure editing
4884 ;;; Inserting headlines
4886 (defun org-insert-heading (&optional force-heading)
4887 "Insert a new heading or item with same depth at point.
4888 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4889 If point is at the beginning of a headline, insert a sibling before the
4890 current headline. If point is in the middle of a headline, split the headline
4891 at that position and make the rest of the headline part of the sibling below
4892 the current headline."
4893 (interactive "P")
4894 (if (= (buffer-size) 0)
4895 (insert "\n* ")
4896 (when (or force-heading (not (org-insert-item)))
4897 (let* ((head (save-excursion
4898 (condition-case nil
4899 (progn
4900 (org-back-to-heading)
4901 (match-string 0))
4902 (error "*"))))
4903 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4904 pos)
4905 (cond
4906 ((and (org-on-heading-p) (bolp)
4907 (or (bobp)
4908 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4909 (open-line (if blank 2 1)))
4910 ((and (bolp)
4911 (or (bobp)
4912 (save-excursion
4913 (backward-char 1) (not (org-invisible-p)))))
4914 nil)
4915 (t (newline (if blank 2 1))))
4916 (insert head) (just-one-space)
4917 (setq pos (point))
4918 (end-of-line 1)
4919 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4920 (run-hooks 'org-insert-heading-hook)))))
4923 (defun org-insert-todo-heading (arg)
4924 "Insert a new heading with the same level and TODO state as current heading.
4925 If the heading has no TODO state, or if the state is DONE, use the first
4926 state (TODO by default). Also with prefix arg, force first state."
4927 (interactive "P")
4928 (when (not (org-insert-item 'checkbox))
4929 (org-insert-heading)
4930 (save-excursion
4931 (org-back-to-heading)
4932 (outline-previous-heading)
4933 (looking-at org-todo-line-regexp))
4934 (if (or arg
4935 (not (match-beginning 2))
4936 (member (match-string 2) org-done-keywords))
4937 (insert (car org-todo-keywords-1) " ")
4938 (insert (match-string 2) " "))))
4940 ;;; Promotion and Demotion
4942 (defun org-promote-subtree ()
4943 "Promote the entire subtree.
4944 See also `org-promote'."
4945 (interactive)
4946 (save-excursion
4947 (org-map-tree 'org-promote))
4948 (org-fix-position-after-promote))
4950 (defun org-demote-subtree ()
4951 "Demote the entire subtree. See `org-demote'.
4952 See also `org-promote'."
4953 (interactive)
4954 (save-excursion
4955 (org-map-tree 'org-demote))
4956 (org-fix-position-after-promote))
4959 (defun org-do-promote ()
4960 "Promote the current heading higher up the tree.
4961 If the region is active in `transient-mark-mode', promote all headings
4962 in the region."
4963 (interactive)
4964 (save-excursion
4965 (if (org-region-active-p)
4966 (org-map-region 'org-promote (region-beginning) (region-end))
4967 (org-promote)))
4968 (org-fix-position-after-promote))
4970 (defun org-do-demote ()
4971 "Demote the current heading lower down the tree.
4972 If the region is active in `transient-mark-mode', demote all headings
4973 in the region."
4974 (interactive)
4975 (save-excursion
4976 (if (org-region-active-p)
4977 (org-map-region 'org-demote (region-beginning) (region-end))
4978 (org-demote)))
4979 (org-fix-position-after-promote))
4981 (defun org-fix-position-after-promote ()
4982 "Make sure that after pro/demotion cursor position is right."
4983 (let ((pos (point)))
4984 (when (save-excursion
4985 (beginning-of-line 1)
4986 (looking-at org-todo-line-regexp)
4987 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4988 (cond ((eobp) (insert " "))
4989 ((eolp) (insert " "))
4990 ((equal (char-after) ?\ ) (forward-char 1))))))
4992 (defun org-get-legal-level (level &optional change)
4993 "Rectify a level change under the influence of `org-odd-levels-only'
4994 LEVEL is a current level, CHANGE is by how much the level should be
4995 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4996 even level numbers will become the next higher odd number."
4997 (if org-odd-levels-only
4998 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4999 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5000 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5001 (max 1 (+ level change))))
5003 (defun org-promote ()
5004 "Promote the current heading higher up the tree.
5005 If the region is active in `transient-mark-mode', promote all headings
5006 in the region."
5007 (org-back-to-heading t)
5008 (let* ((level (save-match-data (funcall outline-level)))
5009 (up-head (make-string (org-get-legal-level level -1) ?*))
5010 (diff (abs (- level (length up-head)))))
5011 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5012 (replace-match up-head nil t)
5013 ;; Fixup tag positioning
5014 (and org-auto-align-tags (org-set-tags nil t))
5015 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5017 (defun org-demote ()
5018 "Demote the current heading lower down the tree.
5019 If the region is active in `transient-mark-mode', demote all headings
5020 in the region."
5021 (org-back-to-heading t)
5022 (let* ((level (save-match-data (funcall outline-level)))
5023 (down-head (make-string (org-get-legal-level level 1) ?*))
5024 (diff (abs (- level (length down-head)))))
5025 (replace-match down-head nil t)
5026 ;; Fixup tag positioning
5027 (and org-auto-align-tags (org-set-tags nil t))
5028 (if org-adapt-indentation (org-fixup-indentation diff))))
5030 (defun org-map-tree (fun)
5031 "Call FUN for every heading underneath the current one."
5032 (org-back-to-heading)
5033 (let ((level (funcall outline-level)))
5034 (save-excursion
5035 (funcall fun)
5036 (while (and (progn
5037 (outline-next-heading)
5038 (> (funcall outline-level) level))
5039 (not (eobp)))
5040 (funcall fun)))))
5042 (defun org-map-region (fun beg end)
5043 "Call FUN for every heading between BEG and END."
5044 (let ((org-ignore-region t))
5045 (save-excursion
5046 (setq end (copy-marker end))
5047 (goto-char beg)
5048 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5049 (< (point) end))
5050 (funcall fun))
5051 (while (and (progn
5052 (outline-next-heading)
5053 (< (point) end))
5054 (not (eobp)))
5055 (funcall fun)))))
5057 (defun org-fixup-indentation (diff)
5058 "Change the indentation in the current entry by DIFF
5059 However, if any line in the current entry has no indentation, or if it
5060 would end up with no indentation after the change, nothing at all is done."
5061 (save-excursion
5062 (let ((end (save-excursion (outline-next-heading)
5063 (point-marker)))
5064 (prohibit (if (> diff 0)
5065 "^\\S-"
5066 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5067 col)
5068 (unless (save-excursion (re-search-forward prohibit end t))
5069 (while (re-search-forward "^[ \t]+" end t)
5070 (goto-char (match-end 0))
5071 (setq col (current-column))
5072 (if (< diff 0) (replace-match ""))
5073 (indent-to (+ diff col))))
5074 (move-marker end nil))))
5076 (defun org-convert-to-odd-levels ()
5077 "Convert an org-mode file with all levels allowed to one with odd levels.
5078 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5079 level 5 etc."
5080 (interactive)
5081 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5082 (let ((org-odd-levels-only nil) n)
5083 (save-excursion
5084 (goto-char (point-min))
5085 (while (re-search-forward "^\\*\\*+" nil t)
5086 (setq n (1- (length (match-string 0))))
5087 (while (>= (setq n (1- n)) 0)
5088 (org-demote))
5089 (end-of-line 1))))))
5092 (defun org-convert-to-oddeven-levels ()
5093 "Convert an org-mode file with only odd levels to one with odd and even levels.
5094 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5095 section with an even level, conversion would destroy the structure of the file. An error
5096 is signaled in this case."
5097 (interactive)
5098 (goto-char (point-min))
5099 ;; First check if there are no even levels
5100 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
5101 (org-show-context t)
5102 (error "Not all levels are odd in this file. Conversion not possible."))
5103 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5104 (let ((org-odd-levels-only nil) n)
5105 (save-excursion
5106 (goto-char (point-min))
5107 (while (re-search-forward "^\\*\\*+" nil t)
5108 (setq n (/ (length (match-string 0)) 2))
5109 (while (>= (setq n (1- n)) 0)
5110 (org-promote))
5111 (end-of-line 1))))))
5113 (defun org-tr-level (n)
5114 "Make N odd if required."
5115 (if org-odd-levels-only (1+ (/ n 2)) n))
5117 ;;; Vertical tree motion, cutting and pasting of subtrees
5119 (defun org-move-subtree-up (&optional arg)
5120 "Move the current subtree up past ARG headlines of the same level."
5121 (interactive "p")
5122 (org-move-subtree-down (- (prefix-numeric-value arg))))
5124 (defun org-move-subtree-down (&optional arg)
5125 "Move the current subtree down past ARG headlines of the same level."
5126 (interactive "p")
5127 (setq arg (prefix-numeric-value arg))
5128 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5129 'outline-get-last-sibling))
5130 (ins-point (make-marker))
5131 (cnt (abs arg))
5132 beg end txt folded)
5133 ;; Select the tree
5134 (org-back-to-heading)
5135 (setq beg (point))
5136 (save-match-data
5137 (save-excursion (outline-end-of-heading)
5138 (setq folded (org-invisible-p)))
5139 (outline-end-of-subtree))
5140 (outline-next-heading)
5141 (setq end (point))
5142 ;; Find insertion point, with error handling
5143 (goto-char beg)
5144 (while (> cnt 0)
5145 (or (and (funcall movfunc) (looking-at outline-regexp))
5146 (progn (goto-char beg)
5147 (error "Cannot move past superior level or buffer limit")))
5148 (setq cnt (1- cnt)))
5149 (if (> arg 0)
5150 ;; Moving forward - still need to move over subtree
5151 (progn (outline-end-of-subtree)
5152 (outline-next-heading)
5153 (if (not (or (looking-at (concat "^" outline-regexp))
5154 (bolp)))
5155 (newline))))
5156 (move-marker ins-point (point))
5157 (setq txt (buffer-substring beg end))
5158 (delete-region beg end)
5159 (insert txt)
5160 (or (bolp) (insert "\n"))
5161 (goto-char ins-point)
5162 (if folded (hide-subtree))
5163 (move-marker ins-point nil)))
5165 (defvar org-subtree-clip ""
5166 "Clipboard for cut and paste of subtrees.
5167 This is actually only a copy of the kill, because we use the normal kill
5168 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5170 (defvar org-subtree-clip-folded nil
5171 "Was the last copied subtree folded?
5172 This is used to fold the tree back after pasting.")
5174 (defun org-cut-subtree ()
5175 "Cut the current subtree into the clipboard.
5176 This is a short-hand for marking the subtree and then cutting it."
5177 (interactive)
5178 (org-copy-subtree 'cut))
5180 (defun org-copy-subtree (&optional cut)
5181 "Cut the current subtree into the clipboard.
5182 This is a short-hand for marking the subtree and then copying it.
5183 If CUT is non-nil, actually cut the subtree."
5184 (interactive)
5185 (let (beg end folded)
5186 (if (interactive-p)
5187 (org-back-to-heading nil) ; take what looks like a subtree
5188 (org-back-to-heading t)) ; take what is really there
5189 (setq beg (point))
5190 (save-match-data
5191 (save-excursion (outline-end-of-heading)
5192 (setq folded (org-invisible-p)))
5193 (outline-end-of-subtree))
5194 (if (equal (char-after) ?\n) (forward-char 1))
5195 (setq end (point))
5196 (goto-char beg)
5197 (when (> end beg)
5198 (setq org-subtree-clip-folded folded)
5199 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5200 (setq org-subtree-clip (current-kill 0))
5201 (message "%s: Subtree with %d characters"
5202 (if cut "Cut" "Copied")
5203 (length org-subtree-clip)))))
5205 (defun org-paste-subtree (&optional level tree)
5206 "Paste the clipboard as a subtree, with modification of headline level.
5207 The entire subtree is promoted or demoted in order to match a new headline
5208 level. By default, the new level is derived from the visible headings
5209 before and after the insertion point, and taken to be the inferior headline
5210 level of the two. So if the previous visible heading is level 3 and the
5211 next is level 4 (or vice versa), level 4 will be used for insertion.
5212 This makes sure that the subtree remains an independent subtree and does
5213 not swallow low level entries.
5215 You can also force a different level, either by using a numeric prefix
5216 argument, or by inserting the heading marker by hand. For example, if the
5217 cursor is after \"*****\", then the tree will be shifted to level 5.
5219 If you want to insert the tree as is, just use \\[yank].
5221 If optional TREE is given, use this text instead of the kill ring."
5222 (interactive "P")
5223 (unless (org-kill-is-subtree-p tree)
5224 (error
5225 (substitute-command-keys
5226 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5227 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5228 (^re (concat "^\\(" outline-regexp "\\)"))
5229 (re (concat "\\(" outline-regexp "\\)"))
5230 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
5232 (old-level (if (string-match ^re txt)
5233 (- (match-end 0) (match-beginning 0))
5234 -1))
5235 (force-level (cond (level (prefix-numeric-value level))
5236 ((string-match
5237 ^re_ (buffer-substring (point-at-bol) (point)))
5238 (- (match-end 0) (match-beginning 0)))
5239 (t nil)))
5240 (previous-level (save-excursion
5241 (condition-case nil
5242 (progn
5243 (outline-previous-visible-heading 1)
5244 (if (looking-at re)
5245 (- (match-end 0) (match-beginning 0))
5247 (error 1))))
5248 (next-level (save-excursion
5249 (condition-case nil
5250 (progn
5251 (outline-next-visible-heading 1)
5252 (if (looking-at re)
5253 (- (match-end 0) (match-beginning 0))
5255 (error 1))))
5256 (new-level (or force-level (max previous-level next-level)))
5257 (shift (if (or (= old-level -1)
5258 (= new-level -1)
5259 (= old-level new-level))
5261 (- new-level old-level)))
5262 (shift1 shift)
5263 (delta (if (> shift 0) -1 1))
5264 (func (if (> shift 0) 'org-demote 'org-promote))
5265 (org-odd-levels-only nil)
5266 beg end)
5267 ;; Remove the forces level indicator
5268 (if force-level
5269 (delete-region (point-at-bol) (point)))
5270 ;; Make sure we start at the beginning of an empty line
5271 (if (not (bolp)) (insert "\n"))
5272 (if (not (looking-at "[ \t]*$"))
5273 (progn (insert "\n") (backward-char 1)))
5274 ;; Paste
5275 (setq beg (point))
5276 (if (string-match "[ \t\r\n]+\\'" txt)
5277 (setq txt (replace-match "\n" t t txt)))
5278 (insert txt)
5279 (setq end (point))
5280 (if (looking-at "[ \t\r\n]+")
5281 (replace-match "\n"))
5282 (goto-char beg)
5283 ;; Shift if necessary
5284 (if (= shift 0)
5285 (message "Pasted at level %d, without shift" new-level)
5286 (save-restriction
5287 (narrow-to-region beg end)
5288 (while (not (= shift 0))
5289 (org-map-region func (point-min) (point-max))
5290 (setq shift (+ delta shift)))
5291 (goto-char (point-min))
5292 (message "Pasted at level %d, with shift by %d levels"
5293 new-level shift1)))
5294 (if (and kill-ring
5295 (eq org-subtree-clip (current-kill 0))
5296 org-subtree-clip-folded)
5297 ;; The tree was folded before it was killed/copied
5298 (hide-subtree))))
5300 (defun org-kill-is-subtree-p (&optional txt)
5301 "Check if the current kill is an outline subtree, or a set of trees.
5302 Returns nil if kill does not start with a headline, or if the first
5303 headline level is not the largest headline level in the tree.
5304 So this will actually accept several entries of equal levels as well,
5305 which is OK for `org-paste-subtree'.
5306 If optional TXT is given, check this string instead of the current kill."
5307 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5308 (start-level (and kill
5309 (string-match (concat "\\`" outline-regexp) kill)
5310 (- (match-end 0) (match-beginning 0))))
5311 (re (concat "^" outline-regexp))
5312 (start 1))
5313 (if (not start-level)
5314 nil ;; does not even start with a heading
5315 (catch 'exit
5316 (while (setq start (string-match re kill (1+ start)))
5317 (if (< (- (match-end 0) (match-beginning 0)) start-level)
5318 (throw 'exit nil)))
5319 t))))
5321 (defun org-narrow-to-subtree ()
5322 "Narrow buffer to the current subtree."
5323 (interactive)
5324 (save-excursion
5325 (narrow-to-region
5326 (progn (org-back-to-heading) (point))
5327 (progn (org-end-of-subtree t t) (point)))))
5330 ;;; Outline Sorting
5332 (defun org-sort (with-case)
5333 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
5334 (interactive "P")
5335 (if (org-at-table-p)
5336 (org-call-with-arg 'org-table-sort-lines with-case)
5337 (org-call-with-arg 'org-sort-entries with-case)))
5339 (defun org-sort-entries (&optional with-case sorting-type)
5340 "Sort entries on a certain level of an outline tree.
5341 If there is an active region, the entries in the region are sorted.
5342 Else, if the cursor is before the first entry, sort the top-level items.
5343 Else, the children of the entry at point are sorted.
5345 Sorting can be alphabetically, numerically, and by date/time as given by
5346 the first time stamp in the entry. The command prompts for the sorting
5347 type unless it has been given to the function through the SORTING-TYPE
5348 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
5350 Comparing entries ignores case by default. However, with an optional argument
5351 WITH-CASE, the sorting considers case as well. With two prefix arguments
5352 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
5353 (interactive "P")
5354 (let ((unique (equal with-case '(16)))
5355 start beg end entries stars re re2 p nentries (nremoved 0)
5356 last txt what)
5357 ;; Find beginning and end of region to sort
5358 (cond
5359 ((org-region-active-p)
5360 ;; we will sort the region
5361 (setq end (region-end)
5362 what "region")
5363 (goto-char (region-beginning))
5364 (if (not (org-on-heading-p)) (outline-next-heading))
5365 (setq start (point)))
5366 ((or (org-on-heading-p)
5367 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5368 ;; we will sort the children of the current headline
5369 (org-back-to-heading)
5370 (setq start (point) end (org-end-of-subtree) what "children")
5371 (goto-char start)
5372 (show-subtree)
5373 (outline-next-heading))
5375 ;; we will sort the top-level entries in this file
5376 (goto-char (point-min))
5377 (or (org-on-heading-p) (outline-next-heading))
5378 (setq start (point) end (point-max) what "top-level")
5379 (goto-char start)
5380 (show-all)))
5381 (setq beg (point))
5382 (if (>= (point) end) (error "Nothing to sort"))
5383 (looking-at "\\(\\*+\\)")
5384 (setq stars (match-string 1)
5385 re (concat "^" (regexp-quote stars) " +")
5386 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5387 txt (buffer-substring beg end))
5388 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5389 (if (and (not (equal stars "*")) (string-match re2 txt))
5390 (error "Region to sort contains a level above the first entry"))
5391 ;; Make a list that can be sorted.
5392 ;; The car is the string for comparison, the cdr is the subtree
5393 (message "Sorting entries...")
5394 (setq entries
5395 (mapcar
5396 (lambda (x)
5397 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
5398 (cons (match-string 0 x) x))
5399 (org-split-string txt re)))
5401 ;; Sort the list
5402 (save-excursion
5403 (goto-char start)
5404 (setq entries (org-do-sort entries what with-case sorting-type)))
5406 ;; Delete the old stuff
5407 (goto-char beg)
5408 (kill-region beg end)
5409 (setq nentries (length entries))
5410 ;; Insert the sorted entries, and remove duplicates if this is required
5411 (while (setq p (pop entries))
5412 (if (and unique (equal last (setq last (org-trim (cdr p)))))
5413 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
5414 (insert stars " " (cdr p))))
5415 (goto-char start)
5416 (message "Sorting entries...done (%d entries%s)"
5417 nentries
5418 (if unique (format ", %d duplicates removed" nremoved) ""))))
5420 (defun org-do-sort (table what &optional with-case sorting-type)
5421 "Sort TABLE of WHAT according to SORTING-TYPE.
5422 The user will be prompted for the SORTING-TYPE if the call to this
5423 function does not specify it. WHAT is only for the prompt, to indicate
5424 what is being sorted. The sorting key will be extracted from
5425 the car of the elements of the table.
5426 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5427 (unless sorting-type
5428 (message
5429 "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
5430 what)
5431 (setq sorting-type (read-char-exclusive)))
5432 (let ((dcst (downcase sorting-type))
5433 extractfun comparefun)
5434 ;; Define the appropriate functions
5435 (cond
5436 ((= dcst ?n)
5437 (setq extractfun 'string-to-number
5438 comparefun (if (= dcst sorting-type) '< '>)))
5439 ((= dcst ?a)
5440 (setq extractfun (if with-case 'identity 'downcase)
5441 comparefun (if (= dcst sorting-type)
5442 'string<
5443 (lambda (a b) (and (not (string< a b))
5444 (not (string= a b)))))))
5445 ((= dcst ?t)
5446 (setq extractfun
5447 (lambda (x)
5448 (if (string-match org-ts-regexp x)
5449 (time-to-seconds
5450 (org-time-string-to-time (match-string 0 x)))
5452 comparefun (if (= dcst sorting-type) '< '>)))
5453 (t (error "Invalid sorting type `%c'" sorting-type)))
5455 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5456 table)
5457 (lambda (a b) (funcall comparefun (car a) (car b))))))
5459 ;;;; Plain list items, including checkboxes
5461 ;;; Plain list items
5463 (defun org-at-item-p ()
5464 "Is point in a line starting a hand-formatted item?"
5465 (let ((llt org-plain-list-ordered-item-terminator))
5466 (save-excursion
5467 (goto-char (point-at-bol))
5468 (looking-at
5469 (cond
5470 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5471 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5472 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5473 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5476 (defun org-in-item-p ()
5477 "It the cursor inside a plain list item.
5478 Does not have to be the first line."
5479 (save-excursion
5480 (condition-case nil
5481 (progn
5482 (org-beginning-of-item)
5483 (org-at-item-p)
5485 (error nil))))
5487 (defun org-insert-item (&optional checkbox)
5488 "Insert a new item at the current level.
5489 Return t when things worked, nil when we are not in an item."
5490 (when (save-excursion
5491 (condition-case nil
5492 (progn
5493 (org-beginning-of-item)
5494 (org-at-item-p)
5495 (if (org-invisible-p) (error "Invisible item"))
5497 (error nil)))
5498 (let* ((bul (match-string 0))
5499 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5500 (match-end 0)))
5501 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5502 pos)
5503 (cond
5504 ((and (org-at-item-p) (<= (point) eow))
5505 ;; before the bullet
5506 (beginning-of-line 1)
5507 (open-line (if blank 2 1)))
5508 ((<= (point) eow)
5509 (beginning-of-line 1))
5510 (t (newline (if blank 2 1))))
5511 (insert bul (if checkbox "[ ]" ""))
5512 (just-one-space)
5513 (setq pos (point))
5514 (end-of-line 1)
5515 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5516 (org-maybe-renumber-ordered-list)
5517 (and checkbox (org-update-checkbox-count-maybe))
5520 ;;; Checkboxes
5522 (defun org-at-item-checkbox-p ()
5523 "Is point at a line starting a plain-list item with a checklet?"
5524 (and (org-at-item-p)
5525 (save-excursion
5526 (goto-char (match-end 0))
5527 (skip-chars-forward " \t")
5528 (looking-at "\\[[ X]\\]"))))
5530 (defun org-toggle-checkbox (&optional arg)
5531 "Toggle the checkbox in the current line."
5532 (interactive "P")
5533 (catch 'exit
5534 (let (beg end status (firstnew 'unknown))
5535 (cond
5536 ((org-region-active-p)
5537 (setq beg (region-beginning) end (region-end)))
5538 ((org-on-heading-p)
5539 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5540 ((org-at-item-checkbox-p)
5541 (save-excursion
5542 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
5543 (throw 'exit t))
5544 (t (error "Not at a checkbox or heading, and no active region")))
5545 (save-excursion
5546 (goto-char beg)
5547 (while (< (point) end)
5548 (when (org-at-item-checkbox-p)
5549 (setq status (equal (match-string 0) "[X]"))
5550 (when (eq firstnew 'unknown)
5551 (setq firstnew (not status)))
5552 (replace-match
5553 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5554 (beginning-of-line 2)))))
5555 (org-update-checkbox-count-maybe))
5557 (defun org-update-checkbox-count-maybe ()
5558 "Update checkbox statistics unless turned off by user."
5559 (when org-provide-checkbox-statistics
5560 (org-update-checkbox-count)))
5562 (defun org-update-checkbox-count (&optional all)
5563 "Update the checkbox statistics in the current section.
5564 This will find all statistic cookies like [57%] and [6/12] and update them
5565 with the current numbers. With optional prefix argument ALL, do this for
5566 the whole buffer."
5567 (interactive "P")
5568 (save-excursion
5569 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5570 (beg (progn (outline-back-to-heading) (point)))
5571 (end (move-marker (make-marker)
5572 (progn (outline-next-heading) (point))))
5573 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5574 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
5575 b1 e1 f1 c-on c-off lim (cstat 0))
5576 (when all
5577 (goto-char (point-min))
5578 (outline-next-heading)
5579 (setq beg (point) end (point-max)))
5580 (goto-char beg)
5581 (while (re-search-forward re end t)
5582 (setq cstat (1+ cstat)
5583 b1 (match-beginning 0)
5584 e1 (match-end 0)
5585 f1 (match-beginning 1)
5586 lim (cond
5587 ((org-on-heading-p) (outline-next-heading) (point))
5588 ((org-at-item-p) (org-end-of-item) (point))
5589 (t nil))
5590 c-on 0 c-off 0)
5591 (goto-char e1)
5592 (when lim
5593 (while (re-search-forward re-box lim t)
5594 (if (equal (match-string 2) "[ ]")
5595 (setq c-off (1+ c-off))
5596 (setq c-on (1+ c-on))))
5597 (delete-region b1 e1)
5598 (goto-char b1)
5599 (insert (if f1
5600 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5601 (format "[%d/%d]" c-on (+ c-on c-off))))))
5602 (when (interactive-p)
5603 (message "Checkbox satistics updated %s (%d places)"
5604 (if all "in entire file" "in current outline entry") cstat)))))
5606 (defun org-get-checkbox-statistics-face ()
5607 "Select the face for checkbox statistics.
5608 The face will be `org-done' when all relevant boxes are checked. Otherwise
5609 it will be `org-todo'."
5610 (if (match-end 1)
5611 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5612 (if (and (> (match-end 2) (match-beginning 2))
5613 (equal (match-string 2) (match-string 3)))
5614 'org-done
5615 'org-todo)))
5617 (defun org-get-indentation (&optional line)
5618 "Get the indentation of the current line, interpreting tabs.
5619 When LINE is given, assume it represents a line and compute its indentation."
5620 (if line
5621 (if (string-match "^ *" (org-remove-tabs line))
5622 (match-end 0))
5623 (save-excursion
5624 (beginning-of-line 1)
5625 (skip-chars-forward " \t")
5626 (current-column))))
5628 (defun org-remove-tabs (s &optional width)
5629 "Replace tabulators in S with spaces.
5630 Assumes that s is a single line, starting in column 0."
5631 (setq width (or width tab-width))
5632 (while (string-match "\t" s)
5633 (setq s (replace-match
5634 (make-string
5635 (- (* width (/ (+ (match-beginning 0) width) width))
5636 (match-beginning 0)) ?\ )
5637 t t s)))
5640 (defun org-fix-indentation (line ind)
5641 "Fix indentation in LINE.
5642 IND is a cons cell with target and minimum indentation.
5643 If the current indenation in LINE is smaller than the minimum,
5644 leave it alone. If it is larger than ind, set it to the target."
5645 (let* ((l (org-remove-tabs line))
5646 (i (org-get-indentation l))
5647 (i1 (car ind)) (i2 (cdr ind)))
5648 (if (>= i i2) (setq l (substring line i2)))
5649 (if (> i1 0)
5650 (concat (make-string i1 ?\ ) l)
5651 l)))
5653 (defcustom org-empty-line-terminates-plain-lists nil
5654 "Non-nil means, an empty line ends all plain list levels.
5655 When nil, empty lines are part of the preceeding item."
5656 :group 'org-plain-lists
5657 :type 'boolean)
5659 (defun org-beginning-of-item ()
5660 "Go to the beginning of the current hand-formatted item.
5661 If the cursor is not in an item, throw an error."
5662 (interactive)
5663 (let ((pos (point))
5664 (limit (save-excursion
5665 (condition-case nil
5666 (progn
5667 (org-back-to-heading)
5668 (beginning-of-line 2) (point))
5669 (error (point-min)))))
5670 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5671 ind ind1)
5672 (if (org-at-item-p)
5673 (beginning-of-line 1)
5674 (beginning-of-line 1)
5675 (skip-chars-forward " \t")
5676 (setq ind (current-column))
5677 (if (catch 'exit
5678 (while t
5679 (beginning-of-line 0)
5680 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5682 (if (looking-at "[ \t]*$")
5683 (setq ind1 ind-empty)
5684 (skip-chars-forward " \t")
5685 (setq ind1 (current-column)))
5686 (if (< ind1 ind)
5687 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5689 (goto-char pos)
5690 (error "Not in an item")))))
5692 (defun org-end-of-item ()
5693 "Go to the end of the current hand-formatted item.
5694 If the cursor is not in an item, throw an error."
5695 (interactive)
5696 (let* ((pos (point))
5697 ind1
5698 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5699 (limit (save-excursion (outline-next-heading) (point)))
5700 (ind (save-excursion
5701 (org-beginning-of-item)
5702 (skip-chars-forward " \t")
5703 (current-column)))
5704 (end (catch 'exit
5705 (while t
5706 (beginning-of-line 2)
5707 (if (eobp) (throw 'exit (point)))
5708 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5709 (if (looking-at "[ \t]*$")
5710 (setq ind1 ind-empty)
5711 (skip-chars-forward " \t")
5712 (setq ind1 (current-column)))
5713 (if (<= ind1 ind)
5714 (throw 'exit (point-at-bol)))))))
5715 (if end
5716 (goto-char end)
5717 (goto-char pos)
5718 (error "Not in an item"))))
5720 (defun org-next-item ()
5721 "Move to the beginning of the next item in the current plain list.
5722 Error if not at a plain list, or if this is the last item in the list."
5723 (interactive)
5724 (let (ind ind1 (pos (point)))
5725 (org-beginning-of-item)
5726 (setq ind (org-get-indentation))
5727 (org-end-of-item)
5728 (setq ind1 (org-get-indentation))
5729 (unless (and (org-at-item-p) (= ind ind1))
5730 (goto-char pos)
5731 (error "On last item"))))
5733 (defun org-previous-item ()
5734 "Move to the beginning of the previous item in the current plain list.
5735 Error if not at a plain list, or if this is the first item in the list."
5736 (interactive)
5737 (let (beg ind ind1 (pos (point)))
5738 (org-beginning-of-item)
5739 (setq beg (point))
5740 (setq ind (org-get-indentation))
5741 (goto-char beg)
5742 (catch 'exit
5743 (while t
5744 (beginning-of-line 0)
5745 (if (looking-at "[ \t]*$")
5747 (if (<= (setq ind1 (org-get-indentation)) ind)
5748 (throw 'exit t)))))
5749 (condition-case nil
5750 (if (or (not (org-at-item-p))
5751 (< ind1 (1- ind)))
5752 (error "")
5753 (org-beginning-of-item))
5754 (error (goto-char pos)
5755 (error "On first item")))))
5757 (defun org-move-item-down ()
5758 "Move the plain list item at point down, i.e. swap with following item.
5759 Subitems (items with larger indentation) are considered part of the item,
5760 so this really moves item trees."
5761 (interactive)
5762 (let (beg end ind ind1 (pos (point)) txt)
5763 (org-beginning-of-item)
5764 (setq beg (point))
5765 (setq ind (org-get-indentation))
5766 (org-end-of-item)
5767 (setq end (point))
5768 (setq ind1 (org-get-indentation))
5769 (if (and (org-at-item-p) (= ind ind1))
5770 (progn
5771 (org-end-of-item)
5772 (setq txt (buffer-substring beg end))
5773 (save-excursion
5774 (delete-region beg end))
5775 (setq pos (point))
5776 (insert txt)
5777 (goto-char pos)
5778 (org-maybe-renumber-ordered-list))
5779 (goto-char pos)
5780 (error "Cannot move this item further down"))))
5782 (defun org-move-item-up (arg)
5783 "Move the plain list item at point up, i.e. swap with previous item.
5784 Subitems (items with larger indentation) are considered part of the item,
5785 so this really moves item trees."
5786 (interactive "p")
5787 (let (beg end ind ind1 (pos (point)) txt)
5788 (org-beginning-of-item)
5789 (setq beg (point))
5790 (setq ind (org-get-indentation))
5791 (org-end-of-item)
5792 (setq end (point))
5793 (goto-char beg)
5794 (catch 'exit
5795 (while t
5796 (beginning-of-line 0)
5797 (if (looking-at "[ \t]*$")
5798 (if org-empty-line-terminates-plain-lists
5799 (progn
5800 (goto-char pos)
5801 (error "Cannot move this item further up"))
5802 nil)
5803 (if (<= (setq ind1 (org-get-indentation)) ind)
5804 (throw 'exit t)))))
5805 (condition-case nil
5806 (org-beginning-of-item)
5807 (error (goto-char beg)
5808 (error "Cannot move this item further up")))
5809 (setq ind1 (org-get-indentation))
5810 (if (and (org-at-item-p) (= ind ind1))
5811 (progn
5812 (setq txt (buffer-substring beg end))
5813 (save-excursion
5814 (delete-region beg end))
5815 (setq pos (point))
5816 (insert txt)
5817 (goto-char pos)
5818 (org-maybe-renumber-ordered-list))
5819 (goto-char pos)
5820 (error "Cannot move this item further up"))))
5822 (defun org-maybe-renumber-ordered-list ()
5823 "Renumber the ordered list at point if setup allows it.
5824 This tests the user option `org-auto-renumber-ordered-lists' before
5825 doing the renumbering."
5826 (interactive)
5827 (when (and org-auto-renumber-ordered-lists
5828 (org-at-item-p))
5829 (if (match-beginning 3)
5830 (org-renumber-ordered-list 1)
5831 (org-fix-bullet-type 1))))
5833 (defun org-maybe-renumber-ordered-list-safe ()
5834 (condition-case nil
5835 (save-excursion
5836 (org-maybe-renumber-ordered-list))
5837 (error nil)))
5839 (defun org-get-string-indentation (s)
5840 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5841 (let ((n -1) (i 0) (w tab-width) c)
5842 (catch 'exit
5843 (while (< (setq n (1+ n)) (length s))
5844 (setq c (aref s n))
5845 (cond ((= c ?\ ) (setq i (1+ i)))
5846 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5847 (t (throw 'exit t)))))
5850 (defun org-renumber-ordered-list (arg)
5851 "Renumber an ordered plain list.
5852 Cursor needs to be in the first line of an item, the line that starts
5853 with something like \"1.\" or \"2)\"."
5854 (interactive "p")
5855 (unless (and (org-at-item-p)
5856 (match-beginning 3))
5857 (error "This is not an ordered list"))
5858 (let ((line (org-current-line))
5859 (col (current-column))
5860 (ind (org-get-string-indentation
5861 (buffer-substring (point-at-bol) (match-beginning 3))))
5862 ;; (term (substring (match-string 3) -1))
5863 ind1 (n (1- arg))
5864 fmt)
5865 ;; find where this list begins
5866 (org-beginning-of-item-list)
5867 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5868 (setq fmt (concat "%d" (match-string 1)))
5869 (beginning-of-line 0)
5870 ;; walk forward and replace these numbers
5871 (catch 'exit
5872 (while t
5873 (catch 'next
5874 (beginning-of-line 2)
5875 (if (eobp) (throw 'exit nil))
5876 (if (looking-at "[ \t]*$") (throw 'next nil))
5877 (skip-chars-forward " \t") (setq ind1 (current-column))
5878 (if (> ind1 ind) (throw 'next t))
5879 (if (< ind1 ind) (throw 'exit t))
5880 (if (not (org-at-item-p)) (throw 'exit nil))
5881 (delete-region (match-beginning 2) (match-end 2))
5882 (goto-char (match-beginning 2))
5883 (insert (format fmt (setq n (1+ n)))))))
5884 (goto-line line)
5885 (move-to-column col)))
5887 (defun org-fix-bullet-type (arg)
5888 "Renumber an ordered plain list.
5889 Cursor needs to be in the first line of an item, the line that starts
5890 with something like \"1.\" or \"2)\"."
5891 (interactive "p")
5892 (unless (org-at-item-p) (error "This is not a list"))
5893 (let ((line (org-current-line))
5894 (col (current-column))
5895 (ind (current-indentation))
5896 ind1 (n (1- arg))
5897 bullet)
5898 ;; find where this list begins
5899 (org-beginning-of-item-list)
5900 (beginning-of-line 1)
5901 ;; find out what the bullet type is
5902 (looking-at "[ \t]*\\(\\S-+\\)")
5903 (setq bullet (match-string 1))
5904 ;; walk forward and replace these numbers
5905 (beginning-of-line 0)
5906 (catch 'exit
5907 (while t
5908 (catch 'next
5909 (beginning-of-line 2)
5910 (if (eobp) (throw 'exit nil))
5911 (if (looking-at "[ \t]*$") (throw 'next nil))
5912 (skip-chars-forward " \t") (setq ind1 (current-column))
5913 (if (> ind1 ind) (throw 'next t))
5914 (if (< ind1 ind) (throw 'exit t))
5915 (if (not (org-at-item-p)) (throw 'exit nil))
5916 (skip-chars-forward " \t")
5917 (looking-at "\\S-+")
5918 (replace-match bullet))))
5919 (goto-line line)
5920 (move-to-column col)
5921 (if (string-match "[0-9]" bullet)
5922 (org-renumber-ordered-list 1))))
5924 (defun org-beginning-of-item-list ()
5925 "Go to the beginning of the current item list.
5926 I.e. to the first item in this list."
5927 (interactive)
5928 (org-beginning-of-item)
5929 (let ((pos (point-at-bol))
5930 (ind (org-get-indentation))
5931 ind1)
5932 ;; find where this list begins
5933 (catch 'exit
5934 (while t
5935 (catch 'next
5936 (beginning-of-line 0)
5937 (if (looking-at "[ \t]*$") (throw 'next t))
5938 (skip-chars-forward " \t") (setq ind1 (current-column))
5939 (if (or (< ind1 ind)
5940 (and (= ind1 ind)
5941 (not (org-at-item-p))))
5942 (throw 'exit t)
5943 (setq pos (point-at-bol))))))
5944 (goto-char pos)))
5946 (defvar org-last-indent-begin-marker (make-marker))
5947 (defvar org-last-indent-end-marker (make-marker))
5949 (defun org-outdent-item (arg)
5950 "Outdent a local list item."
5951 (interactive "p")
5952 (org-indent-item (- arg)))
5954 (defun org-indent-item (arg)
5955 "Indent a local list item."
5956 (interactive "p")
5957 (unless (org-at-item-p)
5958 (error "Not on an item"))
5959 (save-excursion
5960 (let (beg end ind ind1 tmp delta ind-down ind-up)
5961 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5962 (setq beg org-last-indent-begin-marker
5963 end org-last-indent-end-marker)
5964 (org-beginning-of-item)
5965 (setq beg (move-marker org-last-indent-begin-marker (point)))
5966 (org-end-of-item)
5967 (setq end (move-marker org-last-indent-end-marker (point))))
5968 (goto-char beg)
5969 (setq tmp (org-item-indent-positions)
5970 ind (car tmp)
5971 ind-down (nth 2 tmp)
5972 ind-up (nth 1 tmp)
5973 delta (if (> arg 0)
5974 (if ind-down (- ind-down ind) (+ 2 ind))
5975 (if ind-up (- ind-up ind) (- ind 2))))
5976 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5977 (while (< (point) end)
5978 (beginning-of-line 1)
5979 (skip-chars-forward " \t") (setq ind1 (current-column))
5980 (delete-region (point-at-bol) (point))
5981 (or (eolp) (indent-to-column (+ ind1 delta)))
5982 (beginning-of-line 2))))
5983 (org-maybe-renumber-ordered-list-safe)
5984 (save-excursion
5985 (beginning-of-line 0)
5986 (condition-case nil (org-beginning-of-item) (error nil))
5987 (org-maybe-renumber-ordered-list-safe)))
5990 (defun org-item-indent-positions ()
5991 "Assumes cursor in item line. FIXME"
5992 (let* ((bolpos (point-at-bol))
5993 (ind (org-get-indentation))
5994 ind-down ind-up pos)
5995 (save-excursion
5996 (org-beginning-of-item-list)
5997 (skip-chars-backward "\n\r \t")
5998 (when (org-in-item-p)
5999 (org-beginning-of-item)
6000 (setq ind-up (org-get-indentation))))
6001 (setq pos (point))
6002 (save-excursion
6003 (cond
6004 ((and (condition-case nil (progn (org-previous-item) t)
6005 (error nil))
6006 (or (forward-char 1) t)
6007 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6008 (setq ind-down (org-get-indentation)))
6009 ((and (goto-char pos)
6010 (org-at-item-p))
6011 (goto-char (match-end 0))
6012 (skip-chars-forward " \t")
6013 (setq ind-down (current-column)))))
6014 (list ind ind-up ind-down)))
6016 ;;;; Archiving
6018 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6020 (defun org-archive-subtree (&optional find-done)
6021 "Move the current subtree to the archive.
6022 The archive can be a certain top-level heading in the current file, or in
6023 a different file. The tree will be moved to that location, the subtree
6024 heading be marked DONE, and the current time will be added.
6026 When called with prefix argument FIND-DONE, find whole trees without any
6027 open TODO items and archive them (after getting confirmation from the user).
6028 If the cursor is not at a headline when this comand is called, try all level
6029 1 trees. If the cursor is on a headline, only try the direct children of
6030 this heading."
6031 (interactive "P")
6032 (if find-done
6033 (org-archive-all-done)
6034 ;; Save all relevant TODO keyword-relatex variables
6036 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6037 (tr-org-todo-keywords-1 org-todo-keywords-1)
6038 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6039 (tr-org-done-keywords org-done-keywords)
6040 (tr-org-todo-regexp org-todo-regexp)
6041 (tr-org-todo-line-regexp org-todo-line-regexp)
6042 (tr-org-odd-levels-only org-odd-levels-only)
6043 (this-buffer (current-buffer))
6044 (org-archive-location org-archive-location)
6045 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6046 file heading buffer level newfile-p)
6048 ;; Try to find a local archive location
6049 (save-excursion
6050 (save-restriction
6051 (widen)
6052 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
6053 (setq org-archive-location (match-string 1)))))
6055 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6056 (progn
6057 (setq file (format (match-string 1 org-archive-location)
6058 (file-name-nondirectory buffer-file-name))
6059 heading (match-string 2 org-archive-location)))
6060 (error "Invalid `org-archive-location'"))
6061 (if (> (length file) 0)
6062 (setq newfile-p (not (file-exists-p file))
6063 buffer (find-file-noselect file))
6064 (setq buffer (current-buffer)))
6065 (unless buffer
6066 (error "Cannot access file \"%s\"" file))
6067 (if (and (> (length heading) 0)
6068 (string-match "^\\*+" heading))
6069 (setq level (match-end 0))
6070 (setq heading nil level 0))
6071 (save-excursion
6072 ;; We first only copy, in case something goes wrong
6073 ;; we need to protect this-command, to avoid kill-region sets it,
6074 ;; which would lead to duplication of subtrees
6075 (let (this-command) (org-copy-subtree))
6076 (set-buffer buffer)
6077 ;; Enforce org-mode for the archive buffer
6078 (if (not (org-mode-p))
6079 ;; Force the mode for future visits.
6080 (let ((org-insert-mode-line-in-empty-file t)
6081 (org-inhibit-startup t))
6082 (call-interactively 'org-mode)))
6083 (when newfile-p
6084 (goto-char (point-max))
6085 (insert (format "\nArchived entries from file %s\n\n"
6086 (buffer-file-name this-buffer))))
6087 ;; Force the TODO keywords of the original buffer
6088 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
6089 (org-todo-keywords-1 tr-org-todo-keywords-1)
6090 (org-todo-kwd-alist tr-org-todo-kwd-alist)
6091 (org-done-keywords tr-org-done-keywords)
6092 (org-todo-regexp tr-org-todo-regexp)
6093 (org-todo-line-regexp tr-org-todo-line-regexp)
6094 (org-odd-levels-only
6095 (if (local-variable-p 'org-odd-levels-only (current-buffer))
6096 org-odd-levels-only
6097 tr-org-odd-levels-only)))
6098 (goto-char (point-min))
6099 (if heading
6100 (progn
6101 (if (re-search-forward
6102 (concat "\\(^\\|\r\\)"
6103 (regexp-quote heading) "[ \t]*\\(:[a-zA-Z0-9_@:]+:\\)?[ \t]*\\($\\|\r\\)")
6104 nil t)
6105 (goto-char (match-end 0))
6106 ;; Heading not found, just insert it at the end
6107 (goto-char (point-max))
6108 (or (bolp) (insert "\n"))
6109 (insert "\n" heading "\n")
6110 (end-of-line 0))
6111 ;; Make the subtree visible
6112 (show-subtree)
6113 (org-end-of-subtree t)
6114 (skip-chars-backward " \t\r\n")
6115 (and (looking-at "[ \t\r\n]*")
6116 (replace-match "\n\n")))
6117 ;; No specific heading, just go to end of file.
6118 (goto-char (point-max)) (insert "\n"))
6119 ;; Paste
6120 (org-paste-subtree (org-get-legal-level level 1))
6121 ;; Mark the entry as done, i.e. set to last word in org-todo-keywords-1 FIXME: not right anymore!!!!!!!
6122 (if org-archive-mark-done
6123 (let (org-log-done)
6124 (org-todo (length org-todo-keywords-1))))
6125 ;; Move cursor to right after the TODO keyword
6126 (when org-archive-stamp-time
6127 (beginning-of-line 1)
6128 (looking-at org-todo-line-regexp)
6129 (goto-char (or (match-end 2) (match-beginning 3)))
6130 (org-insert-time-stamp (org-current-time) t t "(" ")"))
6131 ;; Save the buffer, if it is not the same buffer.
6132 (if (not (eq this-buffer buffer)) (save-buffer))))
6133 ;; Here we are back in the original buffer. Everything seems to have
6134 ;; worked. So now cut the tree and finish up.
6135 (let (this-command) (org-cut-subtree))
6136 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
6137 (message "Subtree archived %s"
6138 (if (eq this-buffer buffer)
6139 (concat "under heading: " heading)
6140 (concat "in file: " (abbreviate-file-name file)))))))
6142 (defun org-archive-all-done (&optional tag)
6143 "Archive sublevels of the current tree without open TODO items.
6144 If the cursor is not on a headline, try all level 1 trees. If
6145 it is on a headline, try all direct children.
6146 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
6147 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
6148 (rea (concat ".*:" org-archive-tag ":"))
6149 (begm (make-marker))
6150 (endm (make-marker))
6151 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
6152 "Move subtree to archive (no open TODO items)? "))
6153 beg end (cntarch 0))
6154 (if (org-on-heading-p)
6155 (progn
6156 (setq re1 (concat "^" (regexp-quote
6157 (make-string
6158 (1+ (- (match-end 0) (match-beginning 0)))
6159 ?*))
6160 " "))
6161 (move-marker begm (point))
6162 (move-marker endm (org-end-of-subtree t)))
6163 (setq re1 "^* ")
6164 (move-marker begm (point-min))
6165 (move-marker endm (point-max)))
6166 (save-excursion
6167 (goto-char begm)
6168 (while (re-search-forward re1 endm t)
6169 (setq beg (match-beginning 0)
6170 end (save-excursion (org-end-of-subtree t) (point)))
6171 (goto-char beg)
6172 (if (re-search-forward re end t)
6173 (goto-char end)
6174 (goto-char beg)
6175 (if (and (or (not tag) (not (looking-at rea)))
6176 (y-or-n-p question))
6177 (progn
6178 (if tag
6179 (org-toggle-tag org-archive-tag 'on)
6180 (org-archive-subtree))
6181 (setq cntarch (1+ cntarch)))
6182 (goto-char end)))))
6183 (message "%d trees archived" cntarch)))
6185 (defun org-cycle-hide-archived-subtrees (state)
6186 "Re-hide all archived subtrees after a visibility state change."
6187 (when (and (not org-cycle-open-archived-trees)
6188 (not (memq state '(overview folded))))
6189 (save-excursion
6190 (let* ((globalp (memq state '(contents all)))
6191 (beg (if globalp (point-min) (point)))
6192 (end (if globalp (point-max) (org-end-of-subtree t))))
6193 (org-hide-archived-subtrees beg end)
6194 (goto-char beg)
6195 (if (looking-at (concat ".*:" org-archive-tag ":"))
6196 (message (substitute-command-keys
6197 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
6199 (defun org-force-cycle-archived ()
6200 "Cycle subtree even if it is archived."
6201 (interactive)
6202 (setq this-command 'org-cycle)
6203 (let ((org-cycle-open-archived-trees t))
6204 (call-interactively 'org-cycle)))
6206 (defun org-hide-archived-subtrees (beg end)
6207 "Re-hide all archived subtrees after a visibility state change."
6208 (save-excursion
6209 (let* ((re (concat ":" org-archive-tag ":")))
6210 (goto-char beg)
6211 (while (re-search-forward re end t)
6212 (and (org-on-heading-p) (hide-subtree))
6213 (org-end-of-subtree t)))))
6215 (defun org-toggle-tag (tag &optional onoff)
6216 "Toggle the tag TAG for the current line.
6217 If ONOFF is `on' or `off', don't toggle but set to this state."
6218 (unless (org-on-heading-p t) (error "Not on headling"))
6219 (let (res current)
6220 (save-excursion
6221 (beginning-of-line)
6222 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
6223 (point-at-eol) t)
6224 (progn
6225 (setq current (match-string 1))
6226 (replace-match ""))
6227 (setq current ""))
6228 (setq current (nreverse (org-split-string current ":")))
6229 (cond
6230 ((eq onoff 'on)
6231 (setq res t)
6232 (or (member tag current) (push tag current)))
6233 ((eq onoff 'off)
6234 (or (not (member tag current)) (setq current (delete tag current))))
6235 (t (if (member tag current)
6236 (setq current (delete tag current))
6237 (setq res t)
6238 (push tag current))))
6239 (end-of-line 1)
6240 (when current
6241 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
6242 (org-set-tags nil t))
6243 res))
6245 (defun org-toggle-archive-tag (&optional arg)
6246 "Toggle the archive tag for the current headline.
6247 With prefix ARG, check all children of current headline and offer tagging
6248 the children that do not contain any open TODO items."
6249 (interactive "P")
6250 (if arg
6251 (org-archive-all-done 'tag)
6252 (let (set)
6253 (save-excursion
6254 (org-back-to-heading t)
6255 (setq set (org-toggle-tag org-archive-tag))
6256 (when set (hide-subtree)))
6257 (and set (beginning-of-line 1))
6258 (message "Subtree %s" (if set "archived" "unarchived")))))
6261 ;;;; Tables
6263 ;;; The table editor
6265 ;; Watch out: Here we are talking about two different kind of tables.
6266 ;; Most of the code is for the tables created with the Org-mode table editor.
6267 ;; Sometimes, we talk about tables created and edited with the table.el
6268 ;; Emacs package. We call the former org-type tables, and the latter
6269 ;; table.el-type tables.
6271 (defun org-before-change-function (beg end)
6272 "Every change indicates that a table might need an update."
6273 (setq org-table-may-need-update t))
6275 (defconst org-table-line-regexp "^[ \t]*|"
6276 "Detects an org-type table line.")
6277 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
6278 "Detects an org-type table line.")
6279 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
6280 "Detects a table line marked for automatic recalculation.")
6281 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
6282 "Detects a table line marked for automatic recalculation.")
6283 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
6284 "Detects a table line marked for automatic recalculation.")
6285 (defconst org-table-hline-regexp "^[ \t]*|-"
6286 "Detects an org-type table hline.")
6287 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
6288 "Detects a table-type table hline.")
6289 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
6290 "Detects an org-type or table-type table.")
6291 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
6292 "Searching from within a table (any type) this finds the first line
6293 outside the table.")
6294 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
6295 "Searching from within a table (any type) this finds the first line
6296 outside the table.")
6298 (defvar org-table-last-highlighted-reference nil)
6299 (defvar org-table-formula-history nil)
6301 (defvar org-table-column-names nil
6302 "Alist with column names, derived from the `!' line.")
6303 (defvar org-table-column-name-regexp nil
6304 "Regular expression matching the current column names.")
6305 (defvar org-table-local-parameters nil
6306 "Alist with parameter names, derived from the `$' line.")
6307 (defvar org-table-named-field-locations nil
6308 "Alist with locations of named fields.")
6310 (defvar org-table-current-line-types nil
6311 "Table row types, non-nil only for the duration of a comand.")
6312 (defvar org-table-current-begin-line nil
6313 "Table begin line, non-nil only for the duration of a comand.")
6314 (defvar org-table-current-begin-pos nil
6315 "Table begin position, non-nil only for the duration of a comand.")
6316 (defvar org-table-dlines nil
6317 "Vector of data line line numbers in the current table.")
6318 (defvar org-table-hlines nil
6319 "Vector of hline line numbers in the current table.")
6321 (defconst org-table-range-regexp
6322 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
6323 ;; 1 2 3 4 5
6324 "Regular expression for matching ranges in formulas.")
6326 (defconst org-table-range-regexp2
6327 (concat
6328 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
6329 "\\.\\."
6330 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
6331 "Match a range for reference display.")
6333 (defconst org-table-translate-regexp
6334 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
6335 "Match a reference that needs translation, for reference display.")
6337 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
6339 (defun org-table-create-with-table.el ()
6340 "Use the table.el package to insert a new table.
6341 If there is already a table at point, convert between Org-mode tables
6342 and table.el tables."
6343 (interactive)
6344 (require 'table)
6345 (cond
6346 ((org-at-table.el-p)
6347 (if (y-or-n-p "Convert table to Org-mode table? ")
6348 (org-table-convert)))
6349 ((org-at-table-p)
6350 (if (y-or-n-p "Convert table to table.el table? ")
6351 (org-table-convert)))
6352 (t (call-interactively 'table-insert))))
6354 (defun org-table-create-or-convert-from-region (arg)
6355 "Convert region to table, or create an empty table.
6356 If there is an active region, convert it to a table, using the function
6357 `org-table-convert-region'.
6358 If there is no such region, create an empty table with `org-table-create'."
6359 (interactive "P")
6360 (if (org-region-active-p)
6361 (org-table-convert-region (region-beginning) (region-end) arg)
6362 (org-table-create arg)))
6364 (defun org-table-create (&optional size)
6365 "Query for a size and insert a table skeleton.
6366 SIZE is a string Columns x Rows like for example \"3x2\"."
6367 (interactive "P")
6368 (unless size
6369 (setq size (read-string
6370 (concat "Table size Columns x Rows [e.g. "
6371 org-table-default-size "]: ")
6372 "" nil org-table-default-size)))
6374 (let* ((pos (point))
6375 (indent (make-string (current-column) ?\ ))
6376 (split (org-split-string size " *x *"))
6377 (rows (string-to-number (nth 1 split)))
6378 (columns (string-to-number (car split)))
6379 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6380 "\n")))
6381 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6382 (point-at-bol) (point)))
6383 (beginning-of-line 1)
6384 (newline))
6385 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6386 (dotimes (i rows) (insert line))
6387 (goto-char pos)
6388 (if (> rows 1)
6389 ;; Insert a hline after the first row.
6390 (progn
6391 (end-of-line 1)
6392 (insert "\n|-")
6393 (goto-char pos)))
6394 (org-table-align)))
6396 (defun org-table-convert-region (beg0 end0 &optional nspace)
6397 "Convert region to a table.
6398 The region goes from BEG0 to END0, but these borders will be moved
6399 slightly, to make sure a beginning of line in the first line is included.
6400 When NSPACE is non-nil, it indicates the minimum number of spaces that
6401 separate columns. By default, the function first checks if every line
6402 contains at lease one TAB. If yes, it assumes that the material is TAB
6403 separated. If not, it assumes a single space as separator."
6404 (interactive "rP")
6405 (let* ((beg (min beg0 end0))
6406 (end (max beg0 end0))
6407 (tabsep t)
6409 (goto-char beg)
6410 (beginning-of-line 1)
6411 (setq beg (move-marker (make-marker) (point)))
6412 (goto-char end)
6413 (if (bolp) (backward-char 1) (end-of-line 1))
6414 (setq end (move-marker (make-marker) (point)))
6415 ;; Lets see if this is tab-separated material. If every nonempty line
6416 ;; contains a tab, we will assume that it is tab-separated material
6417 (if nspace
6418 (setq tabsep nil)
6419 (goto-char beg)
6420 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6421 (if nspace (setq tabsep nil))
6422 (if tabsep
6423 (setq re "^\\|\t")
6424 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6425 (max 1 (prefix-numeric-value nspace)))))
6426 (goto-char beg)
6427 (while (re-search-forward re end t)
6428 (replace-match "| " t t))
6429 (goto-char beg)
6430 (insert " ")
6431 (org-table-align)))
6433 (defun org-table-import (file arg)
6434 "Import FILE as a table.
6435 The file is assumed to be tab-separated. Such files can be produced by most
6436 spreadsheet and database applications. If no tabs (at least one per line)
6437 are found, lines will be split on whitespace into fields."
6438 (interactive "f\nP")
6439 (or (bolp) (newline))
6440 (let ((beg (point))
6441 (pm (point-max)))
6442 (insert-file-contents file)
6443 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
6445 (defun org-table-export ()
6446 "Export table as a tab-separated file.
6447 Such a file can be imported into a spreadsheet program like Excel."
6448 (interactive)
6449 (let* ((beg (org-table-begin))
6450 (end (org-table-end))
6451 (table (buffer-substring beg end))
6452 (file (read-file-name "Export table to: "))
6453 buf)
6454 (unless (or (not (file-exists-p file))
6455 (y-or-n-p (format "Overwrite file %s? " file)))
6456 (error "Abort"))
6457 (with-current-buffer (find-file-noselect file)
6458 (setq buf (current-buffer))
6459 (erase-buffer)
6460 (fundamental-mode)
6461 (insert table)
6462 (goto-char (point-min))
6463 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6464 (replace-match "" t t)
6465 (end-of-line 1))
6466 (goto-char (point-min))
6467 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6468 (replace-match "" t t)
6469 (goto-char (min (1+ (point)) (point-max))))
6470 (goto-char (point-min))
6471 (while (re-search-forward "^-[-+]*$" nil t)
6472 (replace-match "")
6473 (if (looking-at "\n")
6474 (delete-char 1)))
6475 (goto-char (point-min))
6476 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6477 (replace-match "\t" t t))
6478 (save-buffer))
6479 (kill-buffer buf)))
6481 (defvar org-table-aligned-begin-marker (make-marker)
6482 "Marker at the beginning of the table last aligned.
6483 Used to check if cursor still is in that table, to minimize realignment.")
6484 (defvar org-table-aligned-end-marker (make-marker)
6485 "Marker at the end of the table last aligned.
6486 Used to check if cursor still is in that table, to minimize realignment.")
6487 (defvar org-table-last-alignment nil
6488 "List of flags for flushright alignment, from the last re-alignment.
6489 This is being used to correctly align a single field after TAB or RET.")
6490 (defvar org-table-last-column-widths nil
6491 "List of max width of fields in each column.
6492 This is being used to correctly align a single field after TAB or RET.")
6493 (defvar org-table-overlay-coordinates nil
6494 "Overlay coordinates after each align of a table.")
6495 (make-variable-buffer-local 'org-table-overlay-coordinates)
6497 (defvar org-last-recalc-line nil)
6498 (defconst org-narrow-column-arrow "=>"
6499 "Used as display property in narrowed table columns.")
6501 (defun org-table-align ()
6502 "Align the table at point by aligning all vertical bars."
6503 (interactive)
6504 (let* (
6505 ;; Limits of table
6506 (beg (org-table-begin))
6507 (end (org-table-end))
6508 ;; Current cursor position
6509 (linepos (org-current-line))
6510 (colpos (org-table-current-column))
6511 (winstart (window-start))
6512 (winstartline (org-current-line (min winstart (1- (point-max)))))
6513 lines (new "") lengths l typenums ty fields maxfields i
6514 column
6515 (indent "") cnt frac
6516 rfmt hfmt
6517 (spaces '(1 . 1))
6518 (sp1 (car spaces))
6519 (sp2 (cdr spaces))
6520 (rfmt1 (concat
6521 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6522 (hfmt1 (concat
6523 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6524 emptystrings links dates narrow fmax f1 len c e)
6525 (untabify beg end)
6526 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
6527 ;; Check if we have links or dates
6528 (goto-char beg)
6529 (setq links (re-search-forward org-bracket-link-regexp end t))
6530 (goto-char beg)
6531 (setq dates (and org-display-custom-times
6532 (re-search-forward org-ts-regexp-both end t)))
6533 ;; Make sure the link properties are right
6534 (when links (goto-char beg) (while (org-activate-bracket-links end)))
6535 ;; Make sure the date properties are right
6536 (when dates (goto-char beg) (while (org-activate-dates end)))
6538 ;; Check if we are narrowing any columns
6539 (goto-char beg)
6540 (setq narrow (and org-format-transports-properties-p
6541 (re-search-forward "<[0-9]+>" end t)))
6542 ;; Get the rows
6543 (setq lines (org-split-string
6544 (buffer-substring beg end) "\n"))
6545 ;; Store the indentation of the first line
6546 (if (string-match "^ *" (car lines))
6547 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6548 ;; Mark the hlines by setting the corresponding element to nil
6549 ;; At the same time, we remove trailing space.
6550 (setq lines (mapcar (lambda (l)
6551 (if (string-match "^ *|-" l)
6553 (if (string-match "[ \t]+$" l)
6554 (substring l 0 (match-beginning 0))
6555 l)))
6556 lines))
6557 ;; Get the data fields by splitting the lines.
6558 (setq fields (mapcar
6559 (lambda (l)
6560 (org-split-string l " *| *"))
6561 (delq nil (copy-sequence lines))))
6562 ;; How many fields in the longest line?
6563 (condition-case nil
6564 (setq maxfields (apply 'max (mapcar 'length fields)))
6565 (error
6566 (kill-region beg end)
6567 (org-table-create org-table-default-size)
6568 (error "Empty table - created default table")))
6569 ;; A list of empty strings to fill any short rows on output
6570 (setq emptystrings (make-list maxfields ""))
6571 ;; Check for special formatting.
6572 (setq i -1)
6573 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6574 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6575 ;; Check if there is an explicit width specified
6576 (when narrow
6577 (setq c column fmax nil)
6578 (while c
6579 (setq e (pop c))
6580 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
6581 (setq fmax (string-to-number (match-string 1 e)) c nil)))
6582 ;; Find fields that are wider than fmax, and shorten them
6583 (when fmax
6584 (loop for xx in column do
6585 (when (and (stringp xx)
6586 (> (org-string-width xx) fmax))
6587 (org-add-props xx nil
6588 'help-echo
6589 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
6590 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
6591 (unless (> f1 1)
6592 (error "Cannot narrow field starting with wide link \"%s\""
6593 (match-string 0 xx)))
6594 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
6595 (add-text-properties (- f1 2) f1
6596 (list 'display org-narrow-column-arrow)
6597 xx)))))
6598 ;; Get the maximum width for each column
6599 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
6600 ;; Get the fraction of numbers, to decide about alignment of the column
6601 (setq cnt 0 frac 0.0)
6602 (loop for x in column do
6603 (if (equal x "")
6605 (setq frac ( / (+ (* frac cnt)
6606 (if (string-match org-table-number-regexp x) 1 0))
6607 (setq cnt (1+ cnt))))))
6608 (push (>= frac org-table-number-fraction) typenums))
6609 (setq lengths (nreverse lengths) typenums (nreverse typenums))
6611 ;; Store the alignment of this table, for later editing of single fields
6612 (setq org-table-last-alignment typenums
6613 org-table-last-column-widths lengths)
6615 ;; With invisible characters, `format' does not get the field width right
6616 ;; So we need to make these fields wide by hand.
6617 (when links
6618 (loop for i from 0 upto (1- maxfields) do
6619 (setq len (nth i lengths))
6620 (loop for j from 0 upto (1- (length fields)) do
6621 (setq c (nthcdr i (car (nthcdr j fields))))
6622 (if (and (stringp (car c))
6623 (string-match org-bracket-link-regexp (car c))
6624 (< (org-string-width (car c)) len))
6625 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
6627 ;; Compute the formats needed for output of the table
6628 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6629 (while (setq l (pop lengths))
6630 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6631 (setq rfmt (concat rfmt (format rfmt1 ty l))
6632 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6633 (setq rfmt (concat rfmt "\n")
6634 hfmt (concat (substring hfmt 0 -1) "|\n"))
6636 (setq new (mapconcat
6637 (lambda (l)
6638 (if l (apply 'format rfmt
6639 (append (pop fields) emptystrings))
6640 hfmt))
6641 lines ""))
6642 ;; Replace the old one
6643 (delete-region beg end)
6644 (move-marker end nil)
6645 (move-marker org-table-aligned-begin-marker (point))
6646 (insert new)
6647 (move-marker org-table-aligned-end-marker (point))
6648 (when (and orgtbl-mode (not (org-mode-p)))
6649 (goto-char org-table-aligned-begin-marker)
6650 (while (org-hide-wide-columns org-table-aligned-end-marker)))
6651 ;; Try to move to the old location
6652 (goto-line winstartline)
6653 (setq winstart (point-at-bol))
6654 (goto-line linepos)
6655 (set-window-start (selected-window) winstart 'noforce)
6656 (org-table-goto-column colpos)
6657 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
6658 (setq org-table-may-need-update nil)
6661 (defun org-string-width (s)
6662 "Compute width of string, ignoring invisible characters.
6663 This ignores character with invisibility property `org-link', and also
6664 characters with property `org-cwidth', because these will become invisible
6665 upon the next fontification round."
6666 (let (b l)
6667 (when (or (eq t buffer-invisibility-spec)
6668 (assq 'org-link buffer-invisibility-spec))
6669 (while (setq b (text-property-any 0 (length s)
6670 'invisible 'org-link s))
6671 (setq s (concat (substring s 0 b)
6672 (substring s (or (next-single-property-change
6673 b 'invisible s) (length s)))))))
6674 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
6675 (setq s (concat (substring s 0 b)
6676 (substring s (or (next-single-property-change
6677 b 'org-cwidth s) (length s))))))
6678 (setq l (string-width s) b -1)
6679 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
6680 (setq l (- l (get-text-property b 'org-dwidth-n s))))
6683 (defun org-table-begin (&optional table-type)
6684 "Find the beginning of the table and return its position.
6685 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6686 (save-excursion
6687 (if (not (re-search-backward
6688 (if table-type org-table-any-border-regexp
6689 org-table-border-regexp)
6690 nil t))
6691 (progn (goto-char (point-min)) (point))
6692 (goto-char (match-beginning 0))
6693 (beginning-of-line 2)
6694 (point))))
6696 (defun org-table-end (&optional table-type)
6697 "Find the end of the table and return its position.
6698 With argument TABLE-TYPE, go to the end of a table.el-type table."
6699 (save-excursion
6700 (if (not (re-search-forward
6701 (if table-type org-table-any-border-regexp
6702 org-table-border-regexp)
6703 nil t))
6704 (goto-char (point-max))
6705 (goto-char (match-beginning 0)))
6706 (point-marker)))
6708 (defun org-table-justify-field-maybe (&optional new)
6709 "Justify the current field, text to left, number to right.
6710 Optional argument NEW may specify text to replace the current field content."
6711 (cond
6712 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6713 ((org-at-table-hline-p))
6714 ((and (not new)
6715 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6716 (current-buffer)))
6717 (< (point) org-table-aligned-begin-marker)
6718 (>= (point) org-table-aligned-end-marker)))
6719 ;; This is not the same table, force a full re-align
6720 (setq org-table-may-need-update t))
6721 (t ;; realign the current field, based on previous full realign
6722 (let* ((pos (point)) s
6723 (col (org-table-current-column))
6724 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
6725 l f n o e)
6726 (when (> col 0)
6727 (skip-chars-backward "^|\n")
6728 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6729 (progn
6730 (setq s (match-string 1)
6731 o (match-string 0)
6732 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6733 e (not (= (match-beginning 2) (match-end 2))))
6734 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6735 l (if e "|" (setq org-table-may-need-update t) ""))
6736 n (format f s))
6737 (if new
6738 (if (<= (length new) l) ;; FIXME: length -> str-width?
6739 (setq n (format f new))
6740 (setq n (concat new "|") org-table-may-need-update t)))
6741 (or (equal n o)
6742 (let (org-table-may-need-update)
6743 (replace-match n))))
6744 (setq org-table-may-need-update t))
6745 (goto-char pos))))))
6747 (defun org-table-next-field ()
6748 "Go to the next field in the current table, creating new lines as needed.
6749 Before doing so, re-align the table if necessary."
6750 (interactive)
6751 (org-table-maybe-eval-formula)
6752 (org-table-maybe-recalculate-line)
6753 (if (and org-table-automatic-realign
6754 org-table-may-need-update)
6755 (org-table-align))
6756 (let ((end (org-table-end)))
6757 (if (org-at-table-hline-p)
6758 (end-of-line 1))
6759 (condition-case nil
6760 (progn
6761 (re-search-forward "|" end)
6762 (if (looking-at "[ \t]*$")
6763 (re-search-forward "|" end))
6764 (if (and (looking-at "-")
6765 org-table-tab-jumps-over-hlines
6766 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
6767 (goto-char (match-beginning 1)))
6768 (if (looking-at "-")
6769 (progn
6770 (beginning-of-line 0)
6771 (org-table-insert-row 'below))
6772 (if (looking-at " ") (forward-char 1))))
6773 (error
6774 (org-table-insert-row 'below)))))
6776 (defun org-table-previous-field ()
6777 "Go to the previous field in the table.
6778 Before doing so, re-align the table if necessary."
6779 (interactive)
6780 (org-table-justify-field-maybe)
6781 (org-table-maybe-recalculate-line)
6782 (if (and org-table-automatic-realign
6783 org-table-may-need-update)
6784 (org-table-align))
6785 (if (org-at-table-hline-p)
6786 (end-of-line 1))
6787 (re-search-backward "|" (org-table-begin))
6788 (re-search-backward "|" (org-table-begin))
6789 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6790 (re-search-backward "|" (org-table-begin)))
6791 (if (looking-at "| ?")
6792 (goto-char (match-end 0))))
6794 (defun org-table-next-row ()
6795 "Go to the next row (same column) in the current table.
6796 Before doing so, re-align the table if necessary."
6797 (interactive)
6798 (org-table-maybe-eval-formula)
6799 (org-table-maybe-recalculate-line)
6800 (if (or (looking-at "[ \t]*$")
6801 (save-excursion (skip-chars-backward " \t") (bolp)))
6802 (newline)
6803 (if (and org-table-automatic-realign
6804 org-table-may-need-update)
6805 (org-table-align))
6806 (let ((col (org-table-current-column)))
6807 (beginning-of-line 2)
6808 (if (or (not (org-at-table-p))
6809 (org-at-table-hline-p))
6810 (progn
6811 (beginning-of-line 0)
6812 (org-table-insert-row 'below)))
6813 (org-table-goto-column col)
6814 (skip-chars-backward "^|\n\r")
6815 (if (looking-at " ") (forward-char 1)))))
6817 (defun org-table-copy-down (n)
6818 "Copy a field down in the current column.
6819 If the field at the cursor is empty, copy into it the content of the nearest
6820 non-empty field above. With argument N, use the Nth non-empty field.
6821 If the current field is not empty, it is copied down to the next row, and
6822 the cursor is moved with it. Therefore, repeating this command causes the
6823 column to be filled row-by-row.
6824 If the variable `org-table-copy-increment' is non-nil and the field is an
6825 integer or a timestamp, it will be incremented while copying. In the case of
6826 a timestamp, if the cursor is on the year, change the year. If it is on the
6827 month or the day, change that. Point will stay on the current date field
6828 in order to easily repeat the interval."
6829 (interactive "p")
6830 (let* ((colpos (org-table-current-column))
6831 (col (current-column))
6832 (field (org-table-get-field))
6833 (non-empty (string-match "[^ \t]" field))
6834 (beg (org-table-begin))
6835 txt)
6836 (org-table-check-inside-data-field)
6837 (if non-empty
6838 (progn
6839 (setq txt (org-trim field))
6840 (org-table-next-row)
6841 (org-table-blank-field))
6842 (save-excursion
6843 (setq txt
6844 (catch 'exit
6845 (while (progn (beginning-of-line 1)
6846 (re-search-backward org-table-dataline-regexp
6847 beg t))
6848 (org-table-goto-column colpos t)
6849 (if (and (looking-at
6850 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6851 (= (setq n (1- n)) 0))
6852 (throw 'exit (match-string 1))))))))
6853 (if txt
6854 (progn
6855 (if (and org-table-copy-increment
6856 (string-match "^[0-9]+$" txt))
6857 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6858 (insert txt)
6859 (move-to-column col)
6860 (if (and org-table-copy-increment (org-at-timestamp-p t))
6861 (org-timestamp-up 1)
6862 (org-table-maybe-recalculate-line))
6863 (org-table-align)
6864 (move-to-column col))
6865 (error "No non-empty field found"))))
6867 (defun org-table-check-inside-data-field ()
6868 "Is point inside a table data field?
6869 I.e. not on a hline or before the first or after the last column?
6870 This actually throws an error, so it aborts the current command."
6871 (if (or (not (org-at-table-p))
6872 (= (org-table-current-column) 0)
6873 (org-at-table-hline-p)
6874 (looking-at "[ \t]*$"))
6875 (error "Not in table data field")))
6877 (defvar org-table-clip nil
6878 "Clipboard for table regions.")
6880 (defun org-table-blank-field ()
6881 "Blank the current table field or active region."
6882 (interactive)
6883 (org-table-check-inside-data-field)
6884 (if (and (interactive-p) (org-region-active-p))
6885 (let (org-table-clip)
6886 (org-table-cut-region (region-beginning) (region-end)))
6887 (skip-chars-backward "^|")
6888 (backward-char 1)
6889 (if (looking-at "|[^|\n]+")
6890 (let* ((pos (match-beginning 0))
6891 (match (match-string 0))
6892 (len (org-string-width match)))
6893 (replace-match (concat "|" (make-string (1- len) ?\ )))
6894 (goto-char (+ 2 pos))
6895 (substring match 1)))))
6897 (defun org-table-get-field (&optional n replace)
6898 "Return the value of the field in column N of current row.
6899 N defaults to current field.
6900 If REPLACE is a string, replace field with this value. The return value
6901 is always the old value."
6902 (and n (org-table-goto-column n))
6903 (skip-chars-backward "^|\n")
6904 (backward-char 1)
6905 (if (looking-at "|[^|\r\n]*")
6906 (let* ((pos (match-beginning 0))
6907 (val (buffer-substring (1+ pos) (match-end 0))))
6908 (if replace
6909 (replace-match (concat "|" replace) t t))
6910 (goto-char (min (point-at-eol) (+ 2 pos)))
6911 val)
6912 (forward-char 1) ""))
6915 (defun org-table-field-info (arg)
6916 "Show info about the current field, and highlight any reference at point."
6917 (interactive "P")
6918 (org-table-get-specials)
6919 (save-excursion
6920 (let* ((pos (point))
6921 (col (org-table-current-column))
6922 (cname (car (rassoc (int-to-string col) org-table-column-names)))
6923 (name (car (rassoc (list (org-current-line) col)
6924 org-table-named-field-locations)))
6925 (eql (org-table-get-stored-formulas))
6926 (dline (org-table-current-dline))
6927 (ref (format "@%d$%d" dline col))
6928 (ref1 (org-table-convert-refs-to-an ref))
6929 (fequation (or (assoc name eql) (assoc ref eql)))
6930 (cequation (assoc (int-to-string col) eql))
6931 (eqn (or fequation cequation)))
6932 (goto-char pos)
6933 (condition-case nil
6934 (org-table-show-reference 'local)
6935 (error nil))
6936 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
6937 dline col
6938 (if cname (concat " or $" cname) "")
6939 dline col ref1
6940 (if name (concat " or $" name) "")
6941 ;; FIXME: formula info not correct if special table line
6942 (if eqn
6943 (concat ", formula: "
6944 (org-table-formula-to-user
6945 (concat
6946 (if (string-match "^[$@]"(car eqn)) "" "$")
6947 (car eqn) "=" (cdr eqn))))
6948 "")))))
6950 (defun org-table-current-column ()
6951 "Find out which column we are in.
6952 When called interactively, column is also displayed in echo area."
6953 (interactive)
6954 (if (interactive-p) (org-table-check-inside-data-field))
6955 (save-excursion
6956 (let ((cnt 0) (pos (point)))
6957 (beginning-of-line 1)
6958 (while (search-forward "|" pos t)
6959 (setq cnt (1+ cnt)))
6960 (if (interactive-p) (message "This is table column %d" cnt))
6961 cnt)))
6963 (defun org-table-current-dline ()
6964 "Find out what table data line we are in.
6965 Only datalins count for this."
6966 (interactive)
6967 (if (interactive-p) (org-table-check-inside-data-field))
6968 (save-excursion
6969 (let ((cnt 0) (pos (point)))
6970 (goto-char (org-table-begin))
6971 (while (<= (point) pos)
6972 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
6973 (beginning-of-line 2))
6974 (if (interactive-p) (message "This is table line %d" cnt))
6975 cnt)))
6977 (defun org-table-goto-column (n &optional on-delim force)
6978 "Move the cursor to the Nth column in the current table line.
6979 With optional argument ON-DELIM, stop with point before the left delimiter
6980 of the field.
6981 If there are less than N fields, just go to after the last delimiter.
6982 However, when FORCE is non-nil, create new columns if necessary."
6983 (interactive "p")
6984 (let ((pos (point-at-eol)))
6985 (beginning-of-line 1)
6986 (when (> n 0)
6987 (while (and (> (setq n (1- n)) -1)
6988 (or (search-forward "|" pos t)
6989 (and force
6990 (progn (end-of-line 1)
6991 (skip-chars-backward "^|")
6992 (insert " | "))))))
6993 ; (backward-char 2) t)))))
6994 (when (and force (not (looking-at ".*|")))
6995 (save-excursion (end-of-line 1) (insert " | ")))
6996 (if on-delim
6997 (backward-char 1)
6998 (if (looking-at " ") (forward-char 1))))))
7000 (defun org-at-table-p (&optional table-type)
7001 "Return t if the cursor is inside an org-type table.
7002 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7003 (if org-enable-table-editor
7004 (save-excursion
7005 (beginning-of-line 1)
7006 (looking-at (if table-type org-table-any-line-regexp
7007 org-table-line-regexp)))
7008 nil))
7010 (defun org-at-table.el-p ()
7011 "Return t if and only if we are at a table.el table."
7012 (and (org-at-table-p 'any)
7013 (save-excursion
7014 (goto-char (org-table-begin 'any))
7015 (looking-at org-table1-hline-regexp))))
7017 (defun org-table-recognize-table.el ()
7018 "If there is a table.el table nearby, recognize it and move into it."
7019 (if org-table-tab-recognizes-table.el
7020 (if (org-at-table.el-p)
7021 (progn
7022 (beginning-of-line 1)
7023 (if (looking-at org-table-dataline-regexp)
7025 (if (looking-at org-table1-hline-regexp)
7026 (progn
7027 (beginning-of-line 2)
7028 (if (looking-at org-table-any-border-regexp)
7029 (beginning-of-line -1)))))
7030 (if (re-search-forward "|" (org-table-end t) t)
7031 (progn
7032 (require 'table)
7033 (if (table--at-cell-p (point))
7035 (message "recognizing table.el table...")
7036 (table-recognize-table)
7037 (message "recognizing table.el table...done")))
7038 (error "This should not happen..."))
7040 nil)
7041 nil))
7043 (defun org-at-table-hline-p ()
7044 "Return t if the cursor is inside a hline in a table."
7045 (if org-enable-table-editor
7046 (save-excursion
7047 (beginning-of-line 1)
7048 (looking-at org-table-hline-regexp))
7049 nil))
7051 (defun org-table-insert-column ()
7052 "Insert a new column into the table."
7053 (interactive)
7054 (if (not (org-at-table-p))
7055 (error "Not at a table"))
7056 (org-table-find-dataline)
7057 (let* ((col (max 1 (org-table-current-column)))
7058 (beg (org-table-begin))
7059 (end (org-table-end))
7060 ;; Current cursor position
7061 (linepos (org-current-line))
7062 (colpos col))
7063 (goto-char beg)
7064 (while (< (point) end)
7065 (if (org-at-table-hline-p)
7067 (org-table-goto-column col t)
7068 (insert "| "))
7069 (beginning-of-line 2))
7070 (move-marker end nil)
7071 (goto-line linepos)
7072 (org-table-goto-column colpos)
7073 (org-table-align)
7074 (org-table-fix-formulas "$" nil (1- col) 1)))
7076 (defun org-table-find-dataline ()
7077 "Find a dataline in the current table, which is needed for column commands."
7078 (if (and (org-at-table-p)
7079 (not (org-at-table-hline-p)))
7081 (let ((col (current-column))
7082 (end (org-table-end)))
7083 (move-to-column col)
7084 (while (and (< (point) end)
7085 (or (not (= (current-column) col))
7086 (org-at-table-hline-p)))
7087 (beginning-of-line 2)
7088 (move-to-column col))
7089 (if (and (org-at-table-p)
7090 (not (org-at-table-hline-p)))
7092 (error
7093 "Please position cursor in a data line for column operations")))))
7095 (defun org-table-delete-column ()
7096 "Delete a column from the table."
7097 (interactive)
7098 (if (not (org-at-table-p))
7099 (error "Not at a table"))
7100 (org-table-find-dataline)
7101 (org-table-check-inside-data-field)
7102 (let* ((col (org-table-current-column))
7103 (beg (org-table-begin))
7104 (end (org-table-end))
7105 ;; Current cursor position
7106 (linepos (org-current-line))
7107 (colpos col))
7108 (goto-char beg)
7109 (while (< (point) end)
7110 (if (org-at-table-hline-p)
7112 (org-table-goto-column col t)
7113 (and (looking-at "|[^|\n]+|")
7114 (replace-match "|")))
7115 (beginning-of-line 2))
7116 (move-marker end nil)
7117 (goto-line linepos)
7118 (org-table-goto-column colpos)
7119 (org-table-align)
7120 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
7121 col -1 col)))
7123 (defun org-table-move-column-right ()
7124 "Move column to the right."
7125 (interactive)
7126 (org-table-move-column nil))
7127 (defun org-table-move-column-left ()
7128 "Move column to the left."
7129 (interactive)
7130 (org-table-move-column 'left))
7132 (defun org-table-move-column (&optional left)
7133 "Move the current column to the right. With arg LEFT, move to the left."
7134 (interactive "P")
7135 (if (not (org-at-table-p))
7136 (error "Not at a table"))
7137 (org-table-find-dataline)
7138 (org-table-check-inside-data-field)
7139 (let* ((col (org-table-current-column))
7140 (col1 (if left (1- col) col))
7141 (beg (org-table-begin))
7142 (end (org-table-end))
7143 ;; Current cursor position
7144 (linepos (org-current-line))
7145 (colpos (if left (1- col) (1+ col))))
7146 (if (and left (= col 1))
7147 (error "Cannot move column further left"))
7148 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
7149 (error "Cannot move column further right"))
7150 (goto-char beg)
7151 (while (< (point) end)
7152 (if (org-at-table-hline-p)
7154 (org-table-goto-column col1 t)
7155 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
7156 (replace-match "|\\2|\\1|")))
7157 (beginning-of-line 2))
7158 (move-marker end nil)
7159 (goto-line linepos)
7160 (org-table-goto-column colpos)
7161 (org-table-align)
7162 (org-table-fix-formulas
7163 "$" (list (cons (number-to-string col) (number-to-string colpos))
7164 (cons (number-to-string colpos) (number-to-string col))))))
7166 (defun org-table-move-row-down ()
7167 "Move table row down."
7168 (interactive)
7169 (org-table-move-row nil))
7170 (defun org-table-move-row-up ()
7171 "Move table row up."
7172 (interactive)
7173 (org-table-move-row 'up))
7175 (defun org-table-move-row (&optional up)
7176 "Move the current table line down. With arg UP, move it up."
7177 (interactive "P")
7178 (let* ((col (current-column))
7179 (pos (point))
7180 (hline1p (save-excursion (beginning-of-line 1)
7181 (looking-at org-table-hline-regexp)))
7182 (dline1 (org-table-current-dline))
7183 (dline2 (+ dline1 (if up -1 1)))
7184 (tonew (if up 0 2))
7185 txt hline2p)
7186 (beginning-of-line tonew)
7187 (unless (org-at-table-p)
7188 (goto-char pos)
7189 (error "Cannot move row further"))
7190 (setq hline2p (looking-at org-table-hline-regexp))
7191 (goto-char pos)
7192 (beginning-of-line 1)
7193 (setq pos (point))
7194 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
7195 (delete-region (point) (1+ (point-at-eol)))
7196 (beginning-of-line tonew)
7197 (insert txt)
7198 (beginning-of-line 0)
7199 (move-to-column col)
7200 (unless (or hline1p hline2p)
7201 (org-table-fix-formulas
7202 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
7203 (cons (number-to-string dline2) (number-to-string dline1)))))))
7205 (defun org-table-insert-row (&optional arg)
7206 "Insert a new row above the current line into the table.
7207 With prefix ARG, insert below the current line."
7208 (interactive "P")
7209 (if (not (org-at-table-p))
7210 (error "Not at a table"))
7211 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
7212 (new (org-table-clean-line line)))
7213 ;; Fix the first field if necessary
7214 (if (string-match "^[ \t]*| *[#$] *|" line)
7215 (setq new (replace-match (match-string 0 line) t t new)))
7216 (beginning-of-line (if arg 2 1))
7217 (let (org-table-may-need-update) (insert-before-markers new "\n"))
7218 (beginning-of-line 0)
7219 (re-search-forward "| ?" (point-at-eol) t)
7220 (and (or org-table-may-need-update org-table-overlay-coordinates)
7221 (org-table-align))
7222 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
7224 (defun org-table-insert-hline (&optional above)
7225 "Insert a horizontal-line below the current line into the table.
7226 With prefix ABOVE, insert above the current line."
7227 (interactive "P")
7228 (if (not (org-at-table-p))
7229 (error "Not at a table"))
7230 (let ((line (org-table-clean-line
7231 (buffer-substring (point-at-bol) (point-at-eol))))
7232 (col (current-column)))
7233 (while (string-match "|\\( +\\)|" line)
7234 (setq line (replace-match
7235 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
7236 ?-) "|") t t line)))
7237 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
7238 (beginning-of-line (if above 1 2))
7239 (insert line "\n")
7240 (beginning-of-line (if above 1 -1))
7241 (move-to-column col)
7242 (and org-table-overlay-coordinates (org-table-align))))
7244 (defun org-table-hline-and-move (&optional same-column)
7245 "Insert a hline and move to the row below that line."
7246 (interactive "P")
7247 (let ((col (org-table-current-column)))
7248 (org-table-maybe-eval-formula)
7249 (org-table-maybe-recalculate-line)
7250 (org-table-insert-hline)
7251 (end-of-line 2)
7252 (if (looking-at "\n[ \t]*|-")
7253 (progn (insert "\n|") (org-table-align))
7254 (org-table-next-field))
7255 (if same-column (org-table-goto-column col))))
7257 (defun org-table-clean-line (s)
7258 "Convert a table line S into a string with only \"|\" and space.
7259 In particular, this does handle wide and invisible characters."
7260 (if (string-match "^[ \t]*|-" s)
7261 ;; It's a hline, just map the characters
7262 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
7263 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
7264 (setq s (replace-match
7265 (concat "|" (make-string (org-string-width (match-string 1 s))
7266 ?\ ) "|")
7267 t t s)))
7270 (defun org-table-kill-row ()
7271 "Delete the current row or horizontal line from the table."
7272 (interactive)
7273 (if (not (org-at-table-p))
7274 (error "Not at a table"))
7275 (let ((col (current-column))
7276 (dline (org-table-current-dline)))
7277 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
7278 (if (not (org-at-table-p)) (beginning-of-line 0))
7279 (move-to-column col)
7280 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
7281 dline -1 dline)))
7284 (defun org-table-sort-lines (with-case &optional sorting-type)
7285 "Sort table lines according to the column at point.
7287 The position of point indicates the column to be used for
7288 sorting, and the range of lines is the range between the nearest
7289 horizontal separator lines, or the entire table of no such lines
7290 exist. If point is before the first column, you will be prompted
7291 for the sorting column. If there is an active region, the mark
7292 specifies the first line and the sorting column, while point
7293 should be in the last line to be included into the sorting.
7295 The command then prompts for the sorting type which can be
7296 alphabetically, numerically, or by time (as given in a time stamp
7297 in the field). Sorting in reverse order is also possible.
7299 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
7301 If SORTING-TYPE is specified when this function is called from a Lisp
7302 program, no prompting will take place. SORTING-TYPE must be a character,
7303 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
7304 should be done in reverse order."
7305 (interactive "P")
7306 (let* ((thisline (org-current-line))
7307 (thiscol (org-table-current-column))
7308 beg end bcol ecol tend tbeg column lns pos)
7309 (when (equal thiscol 0)
7310 (if (interactive-p)
7311 (setq thiscol
7312 (string-to-number
7313 (read-string "Use column N for sorting: ")))
7314 (setq thiscol 1))
7315 (org-table-goto-column thiscol))
7316 (org-table-check-inside-data-field)
7317 (if (org-region-active-p)
7318 (progn
7319 (setq beg (region-beginning) end (region-end))
7320 (goto-char beg)
7321 (setq column (org-table-current-column)
7322 beg (point-at-bol))
7323 (goto-char end)
7324 (setq end (point-at-bol 2)))
7325 (setq column (org-table-current-column)
7326 pos (point)
7327 tbeg (org-table-begin)
7328 tend (org-table-end))
7329 (if (re-search-backward org-table-hline-regexp tbeg t)
7330 (setq beg (point-at-bol 2))
7331 (goto-char tbeg)
7332 (setq beg (point-at-bol 1)))
7333 (goto-char pos)
7334 (if (re-search-forward org-table-hline-regexp tend t)
7335 (setq end (point-at-bol 0))
7336 (goto-char tend)
7337 (setq end (point-at-bol))))
7338 (setq beg (move-marker (make-marker) beg)
7339 end (move-marker (make-marker) end))
7340 (untabify beg end)
7341 (goto-char beg)
7342 (org-table-goto-column column)
7343 (skip-chars-backward "^|")
7344 (setq bcol (current-column))
7345 (org-table-goto-column (1+ column))
7346 (skip-chars-backward "^|")
7347 (setq ecol (1- (current-column)))
7348 (org-table-goto-column column)
7349 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
7350 (org-split-string (buffer-substring beg end) "\n")))
7351 (setq lns (org-do-sort lns "Table" with-case sorting-type))
7352 (delete-region beg end)
7353 (move-marker beg nil)
7354 (move-marker end nil)
7355 (insert (mapconcat 'cdr lns "\n") "\n")
7356 (goto-line thisline)
7357 (org-table-goto-column thiscol)
7358 (message "%d lines sorted, based on column %d" (length lns) column)))
7360 (defun org-table-cut-region (beg end)
7361 "Copy region in table to the clipboard and blank all relevant fields."
7362 (interactive "r")
7363 (org-table-copy-region beg end 'cut))
7365 (defun org-table-copy-region (beg end &optional cut)
7366 "Copy rectangular region in table to clipboard.
7367 A special clipboard is used which can only be accessed
7368 with `org-table-paste-rectangle'."
7369 (interactive "rP")
7370 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
7371 region cols
7372 (rpl (if cut " " nil)))
7373 (goto-char beg)
7374 (org-table-check-inside-data-field)
7375 (setq l01 (org-current-line)
7376 c01 (org-table-current-column))
7377 (goto-char end)
7378 (org-table-check-inside-data-field)
7379 (setq l02 (org-current-line)
7380 c02 (org-table-current-column))
7381 (setq l1 (min l01 l02) l2 (max l01 l02)
7382 c1 (min c01 c02) c2 (max c01 c02))
7383 (catch 'exit
7384 (while t
7385 (catch 'nextline
7386 (if (> l1 l2) (throw 'exit t))
7387 (goto-line l1)
7388 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
7389 (setq cols nil ic1 c1 ic2 c2)
7390 (while (< ic1 (1+ ic2))
7391 (push (org-table-get-field ic1 rpl) cols)
7392 (setq ic1 (1+ ic1)))
7393 (push (nreverse cols) region)
7394 (setq l1 (1+ l1)))))
7395 (setq org-table-clip (nreverse region))
7396 (if cut (org-table-align))
7397 org-table-clip))
7399 (defun org-table-paste-rectangle ()
7400 "Paste a rectangular region into a table.
7401 The upper right corner ends up in the current field. All involved fields
7402 will be overwritten. If the rectangle does not fit into the present table,
7403 the table is enlarged as needed. The process ignores horizontal separator
7404 lines."
7405 (interactive)
7406 (unless (and org-table-clip (listp org-table-clip))
7407 (error "First cut/copy a region to paste!"))
7408 (org-table-check-inside-data-field)
7409 (let* ((clip org-table-clip)
7410 (line (org-current-line))
7411 (col (org-table-current-column))
7412 (org-enable-table-editor t)
7413 (org-table-automatic-realign nil)
7414 c cols field)
7415 (while (setq cols (pop clip))
7416 (while (org-at-table-hline-p) (beginning-of-line 2))
7417 (if (not (org-at-table-p))
7418 (progn (end-of-line 0) (org-table-next-field)))
7419 (setq c col)
7420 (while (setq field (pop cols))
7421 (org-table-goto-column c nil 'force)
7422 (org-table-get-field nil field)
7423 (setq c (1+ c)))
7424 (beginning-of-line 2))
7425 (goto-line line)
7426 (org-table-goto-column col)
7427 (org-table-align)))
7429 (defun org-table-convert ()
7430 "Convert from `org-mode' table to table.el and back.
7431 Obviously, this only works within limits. When an Org-mode table is
7432 converted to table.el, all horizontal separator lines get lost, because
7433 table.el uses these as cell boundaries and has no notion of horizontal lines.
7434 A table.el table can be converted to an Org-mode table only if it does not
7435 do row or column spanning. Multiline cells will become multiple cells.
7436 Beware, Org-mode does not test if the table can be successfully converted - it
7437 blindly applies a recipe that works for simple tables."
7438 (interactive)
7439 (require 'table)
7440 (if (org-at-table.el-p)
7441 ;; convert to Org-mode table
7442 (let ((beg (move-marker (make-marker) (org-table-begin t)))
7443 (end (move-marker (make-marker) (org-table-end t))))
7444 (table-unrecognize-region beg end)
7445 (goto-char beg)
7446 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
7447 (replace-match ""))
7448 (goto-char beg))
7449 (if (org-at-table-p)
7450 ;; convert to table.el table
7451 (let ((beg (move-marker (make-marker) (org-table-begin)))
7452 (end (move-marker (make-marker) (org-table-end))))
7453 ;; first, get rid of all horizontal lines
7454 (goto-char beg)
7455 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
7456 (replace-match ""))
7457 ;; insert a hline before first
7458 (goto-char beg)
7459 (org-table-insert-hline 'above)
7460 (beginning-of-line -1)
7461 ;; insert a hline after each line
7462 (while (progn (beginning-of-line 3) (< (point) end))
7463 (org-table-insert-hline))
7464 (goto-char beg)
7465 (setq end (move-marker end (org-table-end)))
7466 ;; replace "+" at beginning and ending of hlines
7467 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
7468 (replace-match "\\1+-"))
7469 (goto-char beg)
7470 (while (re-search-forward "-|[ \t]*$" end t)
7471 (replace-match "-+"))
7472 (goto-char beg)))))
7474 (defun org-table-wrap-region (arg)
7475 "Wrap several fields in a column like a paragraph.
7476 This is useful if you'd like to spread the contents of a field over several
7477 lines, in order to keep the table compact.
7479 If there is an active region, and both point and mark are in the same column,
7480 the text in the column is wrapped to minimum width for the given number of
7481 lines. Generally, this makes the table more compact. A prefix ARG may be
7482 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
7483 formats the selected text to two lines. If the region was longer than two
7484 lines, the remaining lines remain empty. A negative prefix argument reduces
7485 the current number of lines by that amount. The wrapped text is pasted back
7486 into the table. If you formatted it to more lines than it was before, fields
7487 further down in the table get overwritten - so you might need to make space in
7488 the table first.
7490 If there is no region, the current field is split at the cursor position and
7491 the text fragment to the right of the cursor is prepended to the field one
7492 line down.
7494 If there is no region, but you specify a prefix ARG, the current field gets
7495 blank, and the content is appended to the field above."
7496 (interactive "P")
7497 (org-table-check-inside-data-field)
7498 (if (org-region-active-p)
7499 ;; There is a region: fill as a paragraph
7500 (let* ((beg (region-beginning))
7501 (cline (save-excursion (goto-char beg) (org-current-line)))
7502 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
7503 nlines)
7504 (org-table-cut-region (region-beginning) (region-end))
7505 (if (> (length (car org-table-clip)) 1)
7506 (error "Region must be limited to single column"))
7507 (setq nlines (if arg
7508 (if (< arg 1)
7509 (+ (length org-table-clip) arg)
7510 arg)
7511 (length org-table-clip)))
7512 (setq org-table-clip
7513 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
7514 nil nlines)))
7515 (goto-line cline)
7516 (org-table-goto-column ccol)
7517 (org-table-paste-rectangle))
7518 ;; No region, split the current field at point
7519 (if arg
7520 ;; combine with field above
7521 (let ((s (org-table-blank-field))
7522 (col (org-table-current-column)))
7523 (beginning-of-line 0)
7524 (while (org-at-table-hline-p) (beginning-of-line 0))
7525 (org-table-goto-column col)
7526 (skip-chars-forward "^|")
7527 (skip-chars-backward " ")
7528 (insert " " (org-trim s))
7529 (org-table-align))
7530 ;; split field
7531 (when (looking-at "\\([^|]+\\)+|")
7532 (let ((s (match-string 1)))
7533 (replace-match " |")
7534 (goto-char (match-beginning 0))
7535 (org-table-next-row)
7536 (insert (org-trim s) " ")
7537 (org-table-align))))))
7539 (defvar org-field-marker nil)
7541 (defun org-table-edit-field (arg)
7542 "Edit table field in a different window.
7543 This is mainly useful for fields that contain hidden parts.
7544 When called with a \\[universal-argument] prefix, just make the full field visible so that
7545 it can be edited in place."
7546 (interactive "P")
7547 (if arg
7548 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
7549 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
7550 (remove-text-properties b e '(org-cwidth t invisible t
7551 display t intangible t))
7552 (if (and (boundp 'font-lock-mode) font-lock-mode)
7553 (font-lock-fontify-block)))
7554 (let ((pos (move-marker (make-marker) (point)))
7555 (field (org-table-get-field))
7556 (cw (current-window-configuration))
7558 (switch-to-buffer-other-window "*Org tmp*")
7559 (erase-buffer)
7560 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
7561 (let ((org-inhibit-startup t)) (org-mode))
7562 (goto-char (setq p (point-max)))
7563 (insert (org-trim field))
7564 (remove-text-properties p (point-max)
7565 '(invisible t org-cwidth t display t
7566 intangible t))
7567 (goto-char p)
7568 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
7569 (org-set-local 'org-window-configuration cw)
7570 (org-set-local 'org-field-marker pos)
7571 (message "Edit and finish with C-c C-c"))))
7573 (defun org-table-finish-edit-field ()
7574 "Finish editing a table data field.
7575 Remove all newline characters, insert the result into the table, realign
7576 the table and kill the editing buffer."
7577 (let ((pos org-field-marker)
7578 (cw org-window-configuration)
7579 (cb (current-buffer))
7580 text)
7581 (goto-char (point-min))
7582 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
7583 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
7584 (replace-match " "))
7585 (setq text (org-trim (buffer-string)))
7586 (set-window-configuration cw)
7587 (kill-buffer cb)
7588 (select-window (get-buffer-window (marker-buffer pos)))
7589 (goto-char pos)
7590 (move-marker pos nil)
7591 (org-table-check-inside-data-field)
7592 (org-table-get-field nil text)
7593 (org-table-align)
7594 (message "New field value inserted")))
7596 (defun org-trim (s)
7597 "Remove whitespace at beginning and end of string."
7598 (if (string-match "^[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
7599 (if (string-match "[ \t\n\r]+$" s) (setq s (replace-match "" t t s)))
7602 (defun org-wrap (string &optional width lines)
7603 "Wrap string to either a number of lines, or a width in characters.
7604 If WIDTH is non-nil, the string is wrapped to that width, however many lines
7605 that costs. If there is a word longer than WIDTH, the text is actually
7606 wrapped to the length of that word.
7607 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
7608 many lines, whatever width that takes.
7609 The return value is a list of lines, without newlines at the end."
7610 (let* ((words (org-split-string string "[ \t\n]+"))
7611 (maxword (apply 'max (mapcar 'org-string-width words)))
7612 w ll)
7613 (cond (width
7614 (org-do-wrap words (max maxword width)))
7615 (lines
7616 (setq w maxword)
7617 (setq ll (org-do-wrap words maxword))
7618 (if (<= (length ll) lines)
7620 (setq ll words)
7621 (while (> (length ll) lines)
7622 (setq w (1+ w))
7623 (setq ll (org-do-wrap words w)))
7624 ll))
7625 (t (error "Cannot wrap this")))))
7628 (defun org-do-wrap (words width)
7629 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
7630 (let (lines line)
7631 (while words
7632 (setq line (pop words))
7633 (while (and words (< (+ (length line) (length (car words))) width))
7634 (setq line (concat line " " (pop words))))
7635 (setq lines (push line lines)))
7636 (nreverse lines)))
7638 (defun org-split-string (string &optional separators)
7639 "Splits STRING into substrings at SEPARATORS.
7640 No empty strings are returned if there are matches at the beginning
7641 and end of string."
7642 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
7643 (start 0)
7644 notfirst
7645 (list nil))
7646 (while (and (string-match rexp string
7647 (if (and notfirst
7648 (= start (match-beginning 0))
7649 (< start (length string)))
7650 (1+ start) start))
7651 (< (match-beginning 0) (length string)))
7652 (setq notfirst t)
7653 (or (eq (match-beginning 0) 0)
7654 (and (eq (match-beginning 0) (match-end 0))
7655 (eq (match-beginning 0) start))
7656 (setq list
7657 (cons (substring string start (match-beginning 0))
7658 list)))
7659 (setq start (match-end 0)))
7660 (or (eq start (length string))
7661 (setq list
7662 (cons (substring string start)
7663 list)))
7664 (nreverse list)))
7666 (defun org-table-map-tables (function)
7667 "Apply FUNCTION to the start of all tables in the buffer."
7668 (save-excursion
7669 (save-restriction
7670 (widen)
7671 (goto-char (point-min))
7672 (while (re-search-forward org-table-any-line-regexp nil t)
7673 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7674 (beginning-of-line 1)
7675 (if (looking-at org-table-line-regexp)
7676 (save-excursion (funcall function)))
7677 (re-search-forward org-table-any-border-regexp nil 1))))
7678 (message "Mapping tables: done"))
7680 (defvar org-timecnt) ; dynamically scoped parameter
7682 (defun org-table-sum (&optional beg end nlast)
7683 "Sum numbers in region of current table column.
7684 The result will be displayed in the echo area, and will be available
7685 as kill to be inserted with \\[yank].
7687 If there is an active region, it is interpreted as a rectangle and all
7688 numbers in that rectangle will be summed. If there is no active
7689 region and point is located in a table column, sum all numbers in that
7690 column.
7692 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7693 numbers are assumed to be times as well (in decimal hours) and the
7694 numbers are added as such.
7696 If NLAST is a number, only the NLAST fields will actually be summed."
7697 (interactive)
7698 (save-excursion
7699 (let (col (org-timecnt 0) diff h m s org-table-clip)
7700 (cond
7701 ((and beg end)) ; beg and end given explicitly
7702 ((org-region-active-p)
7703 (setq beg (region-beginning) end (region-end)))
7705 (setq col (org-table-current-column))
7706 (goto-char (org-table-begin))
7707 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7708 (error "No table data"))
7709 (org-table-goto-column col)
7710 (setq beg (point))
7711 (goto-char (org-table-end))
7712 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7713 (error "No table data"))
7714 (org-table-goto-column col)
7715 (setq end (point))))
7716 (let* ((items (apply 'append (org-table-copy-region beg end)))
7717 (items1 (cond ((not nlast) items)
7718 ((>= nlast (length items)) items)
7719 (t (setq items (reverse items))
7720 (setcdr (nthcdr (1- nlast) items) nil)
7721 (nreverse items))))
7722 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7723 items1)))
7724 (res (apply '+ numbers))
7725 (sres (if (= org-timecnt 0)
7726 (format "%g" res)
7727 (setq diff (* 3600 res)
7728 h (floor (/ diff 3600)) diff (mod diff 3600)
7729 m (floor (/ diff 60)) diff (mod diff 60)
7730 s diff)
7731 (format "%d:%02d:%02d" h m s))))
7732 (kill-new sres)
7733 (if (interactive-p)
7734 (message "%s"
7735 (substitute-command-keys
7736 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7737 (length numbers) sres))))
7738 sres))))
7740 (defun org-table-get-number-for-summing (s)
7741 (let (n)
7742 (if (string-match "^ *|? *" s)
7743 (setq s (replace-match "" nil nil s)))
7744 (if (string-match " *|? *$" s)
7745 (setq s (replace-match "" nil nil s)))
7746 (setq n (string-to-number s))
7747 (cond
7748 ((and (string-match "0" s)
7749 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7750 ((string-match "\\`[ \t]+\\'" s) nil)
7751 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7752 (let ((h (string-to-number (or (match-string 1 s) "0")))
7753 (m (string-to-number (or (match-string 2 s) "0")))
7754 (s (string-to-number (or (match-string 4 s) "0"))))
7755 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
7756 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7757 ((equal n 0) nil)
7758 (t n))))
7760 (defun org-table-current-field-formula (&optional key noerror)
7761 "Return the formula active for the current field.
7762 Assumes that specials are in place.
7763 If KEY is given, return the key to this formula.
7764 Otherwise return the formula preceeded with \"=\" or \":=\"."
7765 (let* ((name (car (rassoc (list (org-current-line)
7766 (org-table-current-column))
7767 org-table-named-field-locations)))
7768 (col (org-table-current-column))
7769 (scol (int-to-string col))
7770 (ref (format "@%d$%d" (org-table-current-dline) col))
7771 (stored-list (org-table-get-stored-formulas noerror))
7772 (ass (or (assoc name stored-list)
7773 (assoc ref stored-list)
7774 (assoc scol stored-list))))
7775 (if key
7776 (car ass)
7777 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
7778 (cdr ass))))))
7780 (defun org-table-get-formula (&optional equation named)
7781 "Read a formula from the minibuffer, offer stored formula as default.
7782 When NAMED is non-nil, look for a named equation."
7783 (let* ((stored-list (org-table-get-stored-formulas))
7784 (name (car (rassoc (list (org-current-line)
7785 (org-table-current-column))
7786 org-table-named-field-locations)))
7787 (ref (format "@%d$%d" (org-table-current-dline)
7788 (org-table-current-column)))
7789 (refass (assoc ref stored-list))
7790 (scol (if named
7791 (if name name ref)
7792 (int-to-string (org-table-current-column))))
7793 (dummy (and (or name refass) (not named)
7794 (not (y-or-n-p "Replace field formula with column formula? " ))
7795 (error "Abort")))
7796 (name (or name ref))
7797 (org-table-may-need-update nil)
7798 (stored (cdr (assoc scol stored-list)))
7799 (eq (cond
7800 ((and stored equation (string-match "^ *=? *$" equation))
7801 stored)
7802 ((stringp equation)
7803 equation)
7804 (t (org-table-formula-from-user
7805 (read-string
7806 (org-table-formula-to-user
7807 (format "%s formula %s%s="
7808 (if named "Field" "Column")
7809 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
7810 scol))
7811 (if stored (org-table-formula-to-user stored) "")
7812 'org-table-formula-history
7813 )))))
7814 mustsave)
7815 (when (not (string-match "\\S-" eq))
7816 ;; remove formula
7817 (setq stored-list (delq (assoc scol stored-list) stored-list))
7818 (org-table-store-formulas stored-list)
7819 (error "Formula removed"))
7820 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7821 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7822 (if (and name (not named))
7823 ;; We set the column equation, delete the named one.
7824 (setq stored-list (delq (assoc name stored-list) stored-list)
7825 mustsave t))
7826 (if stored
7827 (setcdr (assoc scol stored-list) eq)
7828 (setq stored-list (cons (cons scol eq) stored-list)))
7829 (if (or mustsave (not (equal stored eq)))
7830 (org-table-store-formulas stored-list))
7831 eq))
7833 (defun org-table-store-formulas (alist)
7834 "Store the list of formulas below the current table."
7835 (setq alist (sort alist 'org-table-formula-less-p))
7836 (save-excursion
7837 (goto-char (org-table-end))
7838 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
7839 (progn
7840 ;; don't overwrite TBLFM, we might use text properties to store stuff
7841 (goto-char (match-beginning 2))
7842 (delete-region (match-beginning 2) (match-end 0)))
7843 (insert "#+TBLFM:"))
7844 (insert " "
7845 (mapconcat (lambda (x)
7846 (concat
7847 (if (equal (string-to-char (car x)) ?@) "" "$")
7848 (car x) "=" (cdr x)))
7849 alist "::")
7850 "\n")))
7852 (defsubst org-table-formula-make-cmp-string (a)
7853 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
7854 (concat
7855 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
7856 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
7857 (if (match-end 5) (concat "@@" (match-string 5 a))))))
7859 (defun org-table-formula-less-p (a b)
7860 "Compare two formulas for sorting."
7861 (let ((as (org-table-formula-make-cmp-string (car a)))
7862 (bs (org-table-formula-make-cmp-string (car b))))
7863 (and as bs (string< as bs))))
7865 (defun org-table-get-stored-formulas (&optional noerror)
7866 "Return an alist with the stored formulas directly after current table."
7867 (interactive)
7868 (let (scol eq eq-alist strings string seen)
7869 (save-excursion
7870 (goto-char (org-table-end))
7871 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7872 (setq strings (org-split-string (match-string 2) " *:: *"))
7873 (while (setq string (pop strings))
7874 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
7875 (setq scol (if (match-end 2)
7876 (match-string 2 string)
7877 (match-string 1 string))
7878 eq (match-string 3 string)
7879 eq-alist (cons (cons scol eq) eq-alist))
7880 (if (member scol seen)
7881 (if noerror
7882 (progn
7883 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7884 (ding)
7885 (sit-for 2))
7886 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
7887 (push scol seen))))))
7888 (nreverse eq-alist)))
7890 (defun org-table-fix-formulas (key replace &optional limit delta remove)
7891 "Modify the equations after the table structure has been edited.
7892 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
7893 For all numbers larger than LIMIT, shift them by DELTA."
7894 (save-excursion
7895 (goto-char (org-table-end))
7896 (when (looking-at "#\\+TBLFM:")
7897 (let ((re (concat key "\\([0-9]+\\)"))
7898 (re2
7899 (when remove
7900 (if (equal key "$")
7901 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
7902 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
7903 s n a)
7904 (when remove
7905 (while (re-search-forward re2 (point-at-eol) t)
7906 (replace-match "")))
7907 (while (re-search-forward re (point-at-eol) t)
7908 (setq s (match-string 1) n (string-to-number s))
7909 (cond
7910 ((setq a (assoc s replace))
7911 (replace-match (concat key (cdr a)) t t))
7912 ((and limit (> n limit))
7913 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
7915 (defun org-table-get-specials ()
7916 "Get the column names and local parameters for this table."
7917 (save-excursion
7918 (let ((beg (org-table-begin)) (end (org-table-end))
7919 names name fields fields1 field cnt
7920 c v l line col types dlines hlines)
7921 (setq org-table-column-names nil
7922 org-table-local-parameters nil
7923 org-table-named-field-locations nil
7924 org-table-current-begin-line nil
7925 org-table-current-begin-pos nil
7926 org-table-current-line-types nil)
7927 (goto-char beg)
7928 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7929 (setq names (org-split-string (match-string 1) " *| *")
7930 cnt 1)
7931 (while (setq name (pop names))
7932 (setq cnt (1+ cnt))
7933 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7934 (push (cons name (int-to-string cnt)) org-table-column-names))))
7935 (setq org-table-column-names (nreverse org-table-column-names))
7936 (setq org-table-column-name-regexp
7937 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7938 (goto-char beg)
7939 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7940 (setq fields (org-split-string (match-string 1) " *| *"))
7941 (while (setq field (pop fields))
7942 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7943 (push (cons (match-string 1 field) (match-string 2 field))
7944 org-table-local-parameters))))
7945 (goto-char beg)
7946 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7947 (setq c (match-string 1)
7948 fields (org-split-string (match-string 2) " *| *"))
7949 (save-excursion
7950 (beginning-of-line (if (equal c "_") 2 0))
7951 (setq line (org-current-line) col 1)
7952 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7953 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7954 (while (and fields1 (setq field (pop fields)))
7955 (setq v (pop fields1) col (1+ col))
7956 (when (and (stringp field) (stringp v)
7957 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7958 (push (cons field v) org-table-local-parameters)
7959 (push (list field line col) org-table-named-field-locations))))
7960 ;; Analyse the line types
7961 (goto-char beg)
7962 (setq org-table-current-begin-line (org-current-line)
7963 org-table-current-begin-pos (point)
7964 l org-table-current-begin-line)
7965 (while (looking-at "[ \t]*|\\(-\\)?")
7966 (push (if (match-end 1) 'hline 'dline) types)
7967 (if (match-end 1) (push l hlines) (push l dlines))
7968 (beginning-of-line 2)
7969 (setq l (1+ l)))
7970 (setq org-table-current-line-types (apply 'vector (nreverse types))
7971 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
7972 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
7974 (defun org-table-maybe-eval-formula ()
7975 "Check if the current field starts with \"=\" or \":=\".
7976 If yes, store the formula and apply it."
7977 ;; We already know we are in a table. Get field will only return a formula
7978 ;; when appropriate. It might return a separator line, but no problem.
7979 (when org-table-formula-evaluate-inline
7980 (let* ((field (org-trim (or (org-table-get-field) "")))
7981 named eq)
7982 (when (string-match "^:?=\\(.*\\)" field)
7983 (setq named (equal (string-to-char field) ?:)
7984 eq (match-string 1 field))
7985 (if (or (fboundp 'calc-eval)
7986 (equal (substring eq 0 (min 2 (length eq))) "'("))
7987 (org-table-eval-formula (if named '(4) nil)
7988 (org-table-formula-from-user eq))
7989 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
7991 (defvar org-recalc-commands nil
7992 "List of commands triggering the recalculation of a line.
7993 Will be filled automatically during use.")
7995 (defvar org-recalc-marks
7996 '((" " . "Unmarked: no special line, no automatic recalculation")
7997 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7998 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7999 ("!" . "Column name definition line. Reference in formula as $name.")
8000 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8001 ("_" . "Names for values in row below this one.")
8002 ("^" . "Names for values in row above this one.")))
8004 (defun org-table-rotate-recalc-marks (&optional newchar)
8005 "Rotate the recalculation mark in the first column.
8006 If in any row, the first field is not consistent with a mark,
8007 insert a new column for the markers.
8008 When there is an active region, change all the lines in the region,
8009 after prompting for the marking character.
8010 After each change, a message will be displayed indicating the meaning
8011 of the new mark."
8012 (interactive)
8013 (unless (org-at-table-p) (error "Not at a table"))
8014 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8015 (beg (org-table-begin))
8016 (end (org-table-end))
8017 (l (org-current-line))
8018 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8019 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8020 (have-col
8021 (save-excursion
8022 (goto-char beg)
8023 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8024 (col (org-table-current-column))
8025 (forcenew (car (assoc newchar org-recalc-marks)))
8026 epos new)
8027 (when l1
8028 (message "Change region to what mark? Type # * ! $ or SPC: ")
8029 (setq newchar (char-to-string (read-char-exclusive))
8030 forcenew (car (assoc newchar org-recalc-marks))))
8031 (if (and newchar (not forcenew))
8032 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8033 newchar))
8034 (if l1 (goto-line l1))
8035 (save-excursion
8036 (beginning-of-line 1)
8037 (unless (looking-at org-table-dataline-regexp)
8038 (error "Not at a table data line")))
8039 (unless have-col
8040 (org-table-goto-column 1)
8041 (org-table-insert-column)
8042 (org-table-goto-column (1+ col)))
8043 (setq epos (point-at-eol))
8044 (save-excursion
8045 (beginning-of-line 1)
8046 (org-table-get-field
8047 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8048 (concat " "
8049 (setq new (or forcenew
8050 (cadr (member (match-string 1) marks))))
8051 " ")
8052 " # ")))
8053 (if (and l1 l2)
8054 (progn
8055 (goto-line l1)
8056 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8057 (and (looking-at org-table-dataline-regexp)
8058 (org-table-get-field 1 (concat " " new " "))))
8059 (goto-line l1)))
8060 (if (not (= epos (point-at-eol))) (org-table-align))
8061 (goto-line l)
8062 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8064 (defun org-table-maybe-recalculate-line ()
8065 "Recompute the current line if marked for it, and if we haven't just done it."
8066 (interactive)
8067 (and org-table-allow-automatic-line-recalculation
8068 (not (and (memq last-command org-recalc-commands)
8069 (equal org-last-recalc-line (org-current-line))))
8070 (save-excursion (beginning-of-line 1)
8071 (looking-at org-table-auto-recalculate-regexp))
8072 (org-table-recalculate) t))
8074 (defvar org-table-formula-debug nil
8075 "Non-nil means, debug table formulas.
8076 When nil, simply write \"#ERROR\" in corrupted fields.")
8077 (make-variable-buffer-local 'org-table-formula-debug)
8079 (defvar modes)
8080 (defsubst org-set-calc-mode (var &optional value)
8081 (if (stringp var)
8082 (setq var (assoc var '(("D" calc-angle-mode deg)
8083 ("R" calc-angle-mode rad)
8084 ("F" calc-prefer-frac t)
8085 ("S" calc-symbolic-mode t)))
8086 value (nth 2 var) var (nth 1 var)))
8087 (if (memq var modes)
8088 (setcar (cdr (memq var modes)) value)
8089 (cons var (cons value modes)))
8090 modes)
8092 (defun org-table-eval-formula (&optional arg equation
8093 suppress-align suppress-const
8094 suppress-store suppress-analysis)
8095 "Replace the table field value at the cursor by the result of a calculation.
8097 This function makes use of Dave Gillespie's Calc package, in my view the
8098 most exciting program ever written for GNU Emacs. So you need to have Calc
8099 installed in order to use this function.
8101 In a table, this command replaces the value in the current field with the
8102 result of a formula. It also installs the formula as the \"current\" column
8103 formula, by storing it in a special line below the table. When called
8104 with a `C-u' prefix, the current field must ba a named field, and the
8105 formula is installed as valid in only this specific field.
8107 When called with two `C-u' prefixes, insert the active equation
8108 for the field back into the current field, so that it can be
8109 edited there. This is useful in order to use \\[org-table-show-reference]
8110 to check the referenced fields.
8112 When called, the command first prompts for a formula, which is read in
8113 the minibuffer. Previously entered formulas are available through the
8114 history list, and the last used formula is offered as a default.
8115 These stored formulas are adapted correctly when moving, inserting, or
8116 deleting columns with the corresponding commands.
8118 The formula can be any algebraic expression understood by the Calc package.
8119 For details, see the Org-mode manual.
8121 This function can also be called from Lisp programs and offers
8122 additional arguments: EQUATION can be the formula to apply. If this
8123 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8124 used to speed-up recursive calls by by-passing unnecessary aligns.
8125 SUPPRESS-CONST suppresses the interpretation of constants in the
8126 formula, assuming that this has been done already outside the function.
8127 SUPPRESS-STORE means the formula should not be stored, either because
8128 it is already stored, or because it is a modified equation that should
8129 not overwrite the stored one."
8130 (interactive "P")
8131 (org-table-check-inside-data-field)
8132 (or suppress-analysis (org-table-get-specials))
8133 (if (equal arg '(16))
8134 (let ((eq (org-table-current-field-formula)))
8135 (or eq (error "No equation active for current field"))
8136 (org-table-get-field nil eq)
8137 (org-table-align)
8138 (setq org-table-may-need-update t))
8139 (let* (fields
8140 (ndown (if (integerp arg) arg 1))
8141 (org-table-automatic-realign nil)
8142 (case-fold-search nil)
8143 (down (> ndown 1))
8144 (formula (if (and equation suppress-store)
8145 equation
8146 (org-table-get-formula equation (equal arg '(4)))))
8147 (n0 (org-table-current-column))
8148 (modes (copy-sequence org-calc-default-modes))
8149 (numbers nil) ; was a variable, now fixed default
8150 (keep-empty nil)
8151 n form form0 bw fmt x ev orig c lispp literal)
8152 ;; Parse the format string. Since we have a lot of modes, this is
8153 ;; a lot of work. However, I think calc still uses most of the time.
8154 (if (string-match ";" formula)
8155 (let ((tmp (org-split-string formula ";")))
8156 (setq formula (car tmp)
8157 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8158 (nth 1 tmp)))
8159 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
8160 (setq c (string-to-char (match-string 1 fmt))
8161 n (string-to-number (match-string 2 fmt)))
8162 (if (= c ?p)
8163 (setq modes (org-set-calc-mode 'calc-internal-prec n))
8164 (setq modes (org-set-calc-mode
8165 'calc-float-format
8166 (list (cdr (assoc c '((?n . float) (?f . fix)
8167 (?s . sci) (?e . eng))))
8168 n))))
8169 (setq fmt (replace-match "" t t fmt)))
8170 (if (string-match "[NT]" fmt)
8171 (setq numbers (equal (match-string 0 fmt) "N"))
8172 fmt (replace-match "" t t fmt))
8173 (if (string-match "L" fmt)
8174 (setq literal t
8175 fmt (replace-match "" t t fmt)))
8176 (if (string-match "E" fmt)
8177 (setq keep-empty t
8178 fmt (replace-match "" t t fmt)))
8179 (while (string-match "[DRFS]" fmt)
8180 (setq modes (org-set-calc-mode (match-string 0 fmt)))
8181 (setq fmt (replace-match "" t t fmt)))
8182 (unless (string-match "\\S-" fmt)
8183 (setq fmt nil))))
8184 (if (and (not suppress-const) org-table-formula-use-constants)
8185 (setq formula (org-table-formula-substitute-names formula)))
8186 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
8187 (while (> ndown 0)
8188 (setq fields (org-split-string
8189 (org-no-properties
8190 (buffer-substring (point-at-bol) (point-at-eol)))
8191 " *| *"))
8192 (if (eq numbers t)
8193 (setq fields (mapcar
8194 (lambda (x) (number-to-string (string-to-number x)))
8195 fields)))
8196 (setq ndown (1- ndown))
8197 (setq form (copy-sequence formula)
8198 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
8199 (if (and lispp literal) (setq lispp 'literal))
8200 ;; Check for old vertical references
8201 (setq form (org-rewrite-old-row-references form))
8202 ;; Insert complex ranges
8203 (while (string-match org-table-range-regexp form)
8204 (setq form
8205 (replace-match
8206 (save-match-data
8207 (org-table-make-reference
8208 (org-table-get-range (match-string 0 form) nil n0)
8209 keep-empty numbers lispp))
8210 t t form)))
8211 ;; Insert simple ranges
8212 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
8213 (setq form
8214 (replace-match
8215 (save-match-data
8216 (org-table-make-reference
8217 (org-sublist
8218 fields (string-to-number (match-string 1 form))
8219 (string-to-number (match-string 2 form)))
8220 keep-empty numbers lispp))
8221 t t form)))
8222 (setq form0 form)
8223 ;; Insert the references to fields in same row
8224 (while (string-match "\\$\\([0-9]+\\)" form)
8225 (setq n (string-to-number (match-string 1 form))
8226 x (nth (1- (if (= n 0) n0 n)) fields))
8227 (unless x (error "Invalid field specifier \"%s\""
8228 (match-string 0 form)))
8229 (setq form (replace-match
8230 (save-match-data
8231 (org-table-make-reference x nil numbers lispp))
8232 t t form)))
8234 (if lispp
8235 (setq ev (condition-case nil
8236 (eval (eval (read form)))
8237 (error "#ERROR"))
8238 ev (if (numberp ev) (number-to-string ev) ev))
8239 (or (fboundp 'calc-eval)
8240 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
8241 (setq ev (calc-eval (cons form modes)
8242 (if numbers 'num))))
8244 (when org-table-formula-debug
8245 (with-output-to-temp-buffer "*Substitution History*"
8246 (princ (format "Substitution history of formula
8247 Orig: %s
8248 $xyz-> %s
8249 @r$c-> %s
8250 $1-> %s\n" orig formula form0 form))
8251 (if (listp ev)
8252 (princ (format " %s^\nError: %s"
8253 (make-string (car ev) ?\-) (nth 1 ev)))
8254 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
8255 ev (or fmt "NONE")
8256 (if fmt (format fmt (string-to-number ev)) ev)))))
8257 (setq bw (get-buffer-window "*Substitution History*"))
8258 (shrink-window-if-larger-than-buffer bw)
8259 (unless (and (interactive-p) (not ndown))
8260 (unless (let (inhibit-redisplay)
8261 (y-or-n-p "Debugging Formula. Continue to next? "))
8262 (org-table-align)
8263 (error "Abort"))
8264 (delete-window bw)
8265 (message "")))
8266 (if (listp ev) (setq fmt nil ev "#ERROR"))
8267 (org-table-justify-field-maybe
8268 (if fmt (format fmt (string-to-number ev)) ev))
8269 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
8270 (call-interactively 'org-return)
8271 (setq ndown 0)))
8272 (and down (org-table-maybe-recalculate-line))
8273 (or suppress-align (and org-table-may-need-update
8274 (org-table-align))))))
8276 (defun org-table-get-range (desc &optional tbeg col highlight)
8277 "Get a calc vector from a column, accorting to descriptor DESC.
8278 Optional arguments TBEG and COL can give the beginning of the table and
8279 the current column, to avoid unnecessary parsing.
8280 HIGHLIGHT means, just highlight the range."
8281 (if (not (equal (string-to-char desc) ?@))
8282 (setq desc (concat "@" desc)))
8283 (save-excursion
8284 (or tbeg (setq tbeg (org-table-begin)))
8285 (or col (setq col (org-table-current-column)))
8286 (let ((thisline (org-current-line))
8287 beg end c1 c2 r1 r2 rangep tmp)
8288 (unless (string-match org-table-range-regexp desc)
8289 (error "Invalid table range specifier `%s'" desc))
8290 (setq rangep (match-end 3)
8291 r1 (and (match-end 1) (match-string 1 desc))
8292 r2 (and (match-end 4) (match-string 4 desc))
8293 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
8294 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
8296 (and c1 (setq c1 (+ (string-to-number c1)
8297 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
8298 (and c2 (setq c2 (+ (string-to-number c2)
8299 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
8300 (if (equal r1 "") (setq r1 nil))
8301 (if (equal r2 "") (setq r2 nil))
8302 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
8303 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
8304 ; (setq r2 (or r2 r1) c2 (or c2 c1))
8305 (if (not r1) (setq r1 thisline))
8306 (if (not r2) (setq r2 thisline))
8307 (if (not c1) (setq c1 col))
8308 (if (not c2) (setq c2 col))
8309 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
8310 ;; just one field
8311 (progn
8312 (goto-line r1)
8313 (while (not (looking-at org-table-dataline-regexp))
8314 (beginning-of-line 2))
8315 (prog1 (org-table-get-field c1)
8316 (if highlight (org-table-highlight-rectangle (point) (point)))))
8317 ;; A range, return a vector
8318 ;; First sort the numbers to get a regular ractangle
8319 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
8320 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
8321 (goto-line r1)
8322 (while (not (looking-at org-table-dataline-regexp))
8323 (beginning-of-line 2))
8324 (org-table-goto-column c1)
8325 (setq beg (point))
8326 (goto-line r2)
8327 (while (not (looking-at org-table-dataline-regexp))
8328 (beginning-of-line 0))
8329 (org-table-goto-column c2)
8330 (setq end (point))
8331 (if highlight
8332 (org-table-highlight-rectangle
8333 beg (progn (skip-chars-forward "^|\n") (point))))
8334 ;; return string representation of calc vector
8335 (apply 'append (org-table-copy-region beg end))))))
8337 (defun org-table-get-descriptor-line (desc &optional cline bline table)
8338 "Analyze descriptor DESC and retrieve the corresponding line number.
8339 The cursor is currently in line CLINE, the table begins in line BLINE,
8340 and TABLE is a vector with line types."
8341 (if (string-match "^[0-9]+$" desc)
8342 (aref org-table-dlines (string-to-number desc))
8343 (setq cline (or cline (org-current-line))
8344 bline (or bline org-table-current-begin-line)
8345 table (or table org-table-current-line-types))
8346 (if (or
8347 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
8348 ;; 1 2 3 4 5 6
8349 (and (not (match-end 3)) (not (match-end 6)))
8350 (and (match-end 3) (match-end 6) (not (match-end 5))))
8351 (error "invalid row descriptor `%s'" desc))
8352 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
8353 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
8354 (odir (and (match-end 5) (match-string 5 desc)))
8355 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
8356 (i (- cline bline))
8357 (rel (and (match-end 6)
8358 (or (and (match-end 1) (not (match-end 3)))
8359 (match-end 5)))))
8360 (if (and hn (not hdir))
8361 (progn
8362 (setq i 0 hdir "+")
8363 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
8364 (if (and (not hn) on (not odir))
8365 (error "should never happen");;(aref org-table-dlines on)
8366 (if (and hn (> hn 0))
8367 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
8368 (if on
8369 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
8370 (+ bline i)))))
8372 (defun org-find-row-type (table i type backwards relative n)
8373 (let ((l (length table)))
8374 (while (> n 0)
8375 (while (and (setq i (+ i (if backwards -1 1)))
8376 (>= i 0) (< i l)
8377 (not (eq (aref table i) type))
8378 (if (and relative (eq (aref table i) 'hline))
8379 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
8380 t)))
8381 (setq n (1- n)))
8382 (if (or (< i 0) (>= i l))
8383 (error "Row descriptior leads outside table")
8384 i)))
8386 (defun org-rewrite-old-row-references (s)
8387 (if (string-match "&[-+0-9I]" s)
8388 (error "Formula contains old &row reference, please rewrite using @-syntax")
8391 (defun org-table-make-reference (elements keep-empty numbers lispp)
8392 "Convert list ELEMENTS to something appropriate to insert into formula.
8393 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
8394 NUMBERS indicates that everything should be converted to numbers.
8395 LISPP means to return something appropriate for a Lisp list."
8396 (if (stringp elements) ; just a single val
8397 (if lispp
8398 (if (eq lispp 'literal)
8399 elements
8400 (prin1-to-string (if numbers (string-to-number elements) elements)))
8401 (if (equal elements "") (setq elements "0"))
8402 (if numbers (number-to-string (string-to-number elements)) elements))
8403 (unless keep-empty
8404 (setq elements
8405 (delq nil
8406 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
8407 elements))))
8408 (setq elements (or elements '("0")))
8409 (if lispp
8410 (mapconcat
8411 (lambda (x)
8412 (if (eq lispp 'literal)
8414 (prin1-to-string (if numbers (string-to-number x) x))))
8415 " ")
8416 (concat "[" (mapconcat
8417 (lambda (x)
8418 (if numbers (number-to-string (string-to-number x)) x))
8419 elements
8420 ",") "]"))))
8422 (defun org-table-recalculate (&optional all noalign)
8423 "Recalculate the current table line by applying all stored formulas.
8424 With prefix arg ALL, do this for all lines in the table."
8425 (interactive "P")
8426 (or (memq this-command org-recalc-commands)
8427 (setq org-recalc-commands (cons this-command org-recalc-commands)))
8428 (unless (org-at-table-p) (error "Not at a table"))
8429 (if (equal all '(16))
8430 (org-table-iterate)
8431 (org-table-get-specials)
8432 (let* ((eqlist (sort (org-table-get-stored-formulas)
8433 (lambda (a b) (string< (car a) (car b)))))
8434 (inhibit-redisplay (not debug-on-error))
8435 (line-re org-table-dataline-regexp)
8436 (thisline (org-current-line))
8437 (thiscol (org-table-current-column))
8438 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
8439 ;; Insert constants in all formulas
8440 (setq eqlist
8441 (mapcar (lambda (x)
8442 (setcdr x (org-table-formula-substitute-names (cdr x)))
8444 eqlist))
8445 ;; Split the equation list
8446 (while (setq eq (pop eqlist))
8447 (if (<= (string-to-char (car eq)) ?9)
8448 (push eq eqlnum)
8449 (push eq eqlname)))
8450 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
8451 (if all
8452 (progn
8453 (setq end (move-marker (make-marker) (1+ (org-table-end))))
8454 (goto-char (setq beg (org-table-begin)))
8455 (if (re-search-forward org-table-calculate-mark-regexp end t)
8456 ;; This is a table with marked lines, compute selected lines
8457 (setq line-re org-table-recalculate-regexp)
8458 ;; Move forward to the first non-header line
8459 (if (and (re-search-forward org-table-dataline-regexp end t)
8460 (re-search-forward org-table-hline-regexp end t)
8461 (re-search-forward org-table-dataline-regexp end t))
8462 (setq beg (match-beginning 0))
8463 nil))) ;; just leave beg where it is
8464 (setq beg (point-at-bol)
8465 end (move-marker (make-marker) (1+ (point-at-eol)))))
8466 (goto-char beg)
8467 (and all (message "Re-applying formulas to full table..."))
8468 (while (re-search-forward line-re end t)
8469 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
8470 ;; Unprotected line, recalculate
8471 (and all (message "Re-applying formulas to full table...(line %d)"
8472 (setq cnt (1+ cnt))))
8473 (setq org-last-recalc-line (org-current-line))
8474 (setq eql eqlnum)
8475 (while (setq entry (pop eql))
8476 (goto-line org-last-recalc-line)
8477 (org-table-goto-column (string-to-number (car entry)) nil 'force)
8478 (org-table-eval-formula nil (cdr entry)
8479 'noalign 'nocst 'nostore 'noanalysis))))
8480 (goto-line thisline)
8481 (org-table-goto-column thiscol)
8482 (or noalign (and org-table-may-need-update (org-table-align))
8483 (and all (message "Re-applying formulas to %d lines...done" cnt)))
8484 ;; Now do the named fields
8485 (while (setq eq (pop eqlname))
8486 (setq name (car eq)
8487 a (assoc name org-table-named-field-locations))
8488 (and (not a)
8489 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
8490 (setq a
8491 (list
8492 name
8493 (aref org-table-dlines
8494 (string-to-number (match-string 1 name)))
8495 (string-to-number (match-string 2 name)))))
8496 (when (and a (or all (equal (nth 1 a) thisline)))
8497 (message "Re-applying formula to field: %s" name)
8498 (goto-line (nth 1 a))
8499 (org-table-goto-column (nth 2 a))
8500 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
8501 'nostore 'noanalysis)))
8502 ;; back to initial position
8503 (message "Re-applying formulas...done")
8504 (goto-line thisline)
8505 (org-table-goto-column thiscol)
8506 (or noalign (and org-table-may-need-update (org-table-align))
8507 (and all (message "Re-applying formulas...done"))))))
8509 (defun org-table-iterate (&optional arg)
8510 "Recalculate the table until it does not change anymore."
8511 (interactive "P")
8512 (let ((imax (if arg (prefix-numeric-value arg) 10))
8513 (i 0)
8514 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
8515 thistbl)
8516 (catch 'exit
8517 (while (< i imax)
8518 (setq i (1+ i))
8519 (org-table-recalculate 'all)
8520 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
8521 (if (not (string= lasttbl thistbl))
8522 (setq lasttbl thistbl)
8523 (if (> i 1)
8524 (message "Convergence after %d iterations" i)
8525 (message "Table was already stable"))
8526 (throw 'exit t)))
8527 (error "No convergence after %d iterations" i))))
8529 (defun org-table-formula-substitute-names (f)
8530 "Replace $const with values in string F."
8531 (let ((start 0) a (f1 f))
8532 ;; First, check for column names
8533 (while (setq start (string-match org-table-column-name-regexp f start))
8534 (setq start (1+ start))
8535 (setq a (assoc (match-string 1 f) org-table-column-names))
8536 (setq f (replace-match (concat "$" (cdr a)) t t f)))
8537 ;; Parameters and constants
8538 (setq start 0)
8539 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
8540 (setq start (1+ start))
8541 (if (setq a (save-match-data
8542 (org-table-get-constant (match-string 1 f))))
8543 (setq f (replace-match (concat "(" a ")") t t f))))
8544 (if org-table-formula-debug
8545 (put-text-property 0 (length f) :orig-formula f1 f))
8548 (defun org-table-get-constant (const)
8549 "Find the value for a parameter or constant in a formula.
8550 Parameters get priority."
8551 (or (cdr (assoc const org-table-local-parameters))
8552 (cdr (assoc const org-table-formula-constants))
8553 (and (fboundp 'constants-get) (constants-get const))
8554 "#UNDEFINED_NAME"))
8556 (defvar org-table-fedit-map (make-sparse-keymap))
8557 (org-defkey org-table-fedit-map "\C-x\C-s" 'org-table-fedit-finish)
8558 (org-defkey org-table-fedit-map "\C-c\C-s" 'org-table-fedit-finish)
8559 (org-defkey org-table-fedit-map "\C-c\C-c" 'org-table-fedit-finish)
8560 (org-defkey org-table-fedit-map "\C-c\C-q" 'org-table-fedit-abort)
8561 (org-defkey org-table-fedit-map "\C-c?" 'org-table-show-reference)
8562 (org-defkey org-table-fedit-map [(meta shift up)] 'org-table-fedit-line-up)
8563 (org-defkey org-table-fedit-map [(meta shift down)] 'org-table-fedit-line-down)
8564 (org-defkey org-table-fedit-map [(shift up)] 'org-table-fedit-ref-up)
8565 (org-defkey org-table-fedit-map [(shift down)] 'org-table-fedit-ref-down)
8566 (org-defkey org-table-fedit-map [(shift left)] 'org-table-fedit-ref-left)
8567 (org-defkey org-table-fedit-map [(shift right)] 'org-table-fedit-ref-right)
8568 (org-defkey org-table-fedit-map [(meta up)] 'org-table-fedit-scroll-down)
8569 (org-defkey org-table-fedit-map [(meta down)] 'org-table-fedit-scroll)
8570 (org-defkey org-table-fedit-map [(meta tab)] 'lisp-complete-symbol)
8571 (org-defkey org-table-fedit-map "\M-\C-i" 'lisp-complete-symbol)
8572 (org-defkey org-table-fedit-map [(tab)] 'org-table-fedit-lisp-indent)
8573 (org-defkey org-table-fedit-map "\C-i" 'org-table-fedit-lisp-indent)
8574 (org-defkey org-table-fedit-map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
8575 (org-defkey org-table-fedit-map "\C-c}" 'org-table-fedit-toggle-coordinates)
8577 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
8578 '("Edit-Formulas"
8579 ["Finish and Install" org-table-fedit-finish t]
8580 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
8581 ["Abort" org-table-fedit-abort t]
8582 "--"
8583 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
8584 ["Complete Lisp Symbol" lisp-complete-symbol t]
8585 "--"
8586 "Shift Reference at Point"
8587 ["Up" org-table-fedit-ref-up t]
8588 ["Down" org-table-fedit-ref-down t]
8589 ["Left" org-table-fedit-ref-left t]
8590 ["Right" org-table-fedit-ref-right t]
8592 "Change Test Row for Column Formulas"
8593 ["Up" org-table-fedit-line-up t]
8594 ["Down" org-table-fedit-line-down t]
8595 "--"
8596 ["Scroll Table Window" org-table-fedit-scroll t]
8597 ["Scroll Table Window down" org-table-fedit-scroll-down t]
8598 ["Show Table Grid" org-table-fedit-toggle-coordinates
8599 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
8600 org-table-overlay-coordinates)]
8601 "--"
8602 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
8603 :style toggle :selected org-table-buffer-is-an]))
8605 (defvar org-pos)
8607 (defun org-table-edit-formulas ()
8608 "Edit the formulas of the current table in a separate buffer."
8609 (interactive)
8610 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
8611 (beginning-of-line 0))
8612 (unless (org-at-table-p) (error "Not at a table"))
8613 (org-table-get-specials)
8614 (let ((key (org-table-current-field-formula 'key 'noerror))
8615 (eql (sort (org-table-get-stored-formulas 'noerror)
8616 'org-table-formula-less-p))
8617 (pos (move-marker (make-marker) (point)))
8618 (startline 1)
8619 (wc (current-window-configuration))
8620 (titles '((column . "# Column Formulas\n")
8621 (field . "# Field Formulas\n")
8622 (named . "# Named Field Formulas\n")))
8623 entry s type title)
8624 (switch-to-buffer-other-window "*Edit Formulas*")
8625 (erase-buffer)
8626 ;; Keep global-font-lock-mode from turning on font-lock-mode
8627 (let ((font-lock-global-modes '(not fundamental-mode)))
8628 (fundamental-mode))
8629 (org-set-local 'font-lock-global-modes (list 'not major-mode))
8630 (org-set-local 'org-pos pos)
8631 (org-set-local 'org-window-configuration wc)
8632 (use-local-map org-table-fedit-map)
8633 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
8634 (easy-menu-add org-table-fedit-menu)
8635 (setq startline (org-current-line))
8636 (while (setq entry (pop eql))
8637 (setq type (cond
8638 ((equal (string-to-char (car entry)) ?@) 'field)
8639 ((string-match "^[0-9]" (car entry)) 'column)
8640 (t 'named)))
8641 (when (setq title (assq type titles))
8642 (or (bobp) (insert "\n"))
8643 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
8644 (setq titles (delq title titles)))
8645 (if (equal key (car entry)) (setq startline (org-current-line)))
8646 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
8647 (car entry) " = " (cdr entry) "\n"))
8648 (remove-text-properties 0 (length s) '(face nil) s)
8649 (insert s))
8650 (if (eq org-table-use-standard-references t)
8651 (org-table-fedit-toggle-ref-type))
8652 (goto-line startline)
8653 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
8655 (defun org-table-fedit-post-command ()
8656 (when (not (memq this-command '(lisp-complete-symbol)))
8657 (let ((win (selected-window)))
8658 (save-excursion
8659 (condition-case nil
8660 (org-table-show-reference)
8661 (error nil))
8662 (select-window win)))))
8664 (defun org-table-formula-to-user (s)
8665 "Convert a formula from internal to user representation."
8666 (if (eq org-table-use-standard-references t)
8667 (org-table-convert-refs-to-an s)
8670 (defun org-table-formula-from-user (s)
8671 "Convert a formula from user to internal representation."
8672 (if org-table-use-standard-references
8673 (org-table-convert-refs-to-rc s)
8676 (defun org-table-convert-refs-to-rc (s)
8677 "Convert spreadsheet references from AB7 to @7$28.
8678 Works for single references, but also for entire formulas and even the
8679 full TBLFM line."
8680 (let ((start 0))
8681 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
8682 (cond
8683 ((match-end 3)
8684 ;; format match, just advance
8685 (setq start (match-end 0)))
8686 ((and (> (match-beginning 0) 0)
8687 (equal ?. (aref s (max (1- (match-beginning 0)) 0))))
8688 ;; 3.e5 or something like this. FIXME: is this ok????
8689 (setq start (match-end 0)))
8691 (setq start (match-beginning 0)
8692 s (replace-match
8693 (if (equal (match-string 2 s) "&")
8694 (format "$%d" (org-letters-to-number (match-string 1 s)))
8695 (format "@%d$%d"
8696 (string-to-number (match-string 2 s))
8697 (org-letters-to-number (match-string 1 s))))
8698 t t s)))))
8701 (defun org-table-convert-refs-to-an (s)
8702 "Convert spreadsheet references from to @7$28 to AB7.
8703 Works for single references, but also for entire formulas and even the
8704 full TBLFM line."
8705 (while (string-match "@\\([0-9]+\\)$\\([0-9]+\\)" s)
8706 (setq s (replace-match
8707 (format "%s%d"
8708 (org-number-to-letters
8709 (string-to-number (match-string 2 s)))
8710 (string-to-number (match-string 1 s)))
8711 t t s)))
8712 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
8713 (setq s (replace-match (concat "\\1"
8714 (org-number-to-letters
8715 (string-to-number (match-string 2 s))) "&")
8716 t nil s)))
8719 (defun org-letters-to-number (s)
8720 "Convert a base 26 number represented by letters into an integer.
8721 For example: AB -> 28."
8722 (let ((n 0))
8723 (setq s (upcase s))
8724 (while (> (length s) 0)
8725 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
8726 s (substring s 1)))
8729 (defun org-number-to-letters (n)
8730 "Convert an integer into a base 26 number represented by letters.
8731 For example: 28 -> AB."
8732 (let ((s ""))
8733 (while (> n 0)
8734 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
8735 n (/ (1- n) 26)))
8738 (defun org-table-fedit-convert-buffer (function)
8739 "Convert all references in this buffer, using FUNTION."
8740 (let ((line (org-current-line)))
8741 (goto-char (point-min))
8742 (while (not (eobp))
8743 (insert (funcall function (buffer-substring (point) (point-at-eol))))
8744 (delete-region (point) (point-at-eol))
8745 (or (eobp) (forward-char 1)))
8746 (goto-line line)))
8748 (defun org-table-fedit-toggle-ref-type ()
8749 "Convert all references in the buffer from B3 to @3$2 and back."
8750 (interactive)
8751 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
8752 (org-table-fedit-convert-buffer
8753 (if org-table-buffer-is-an
8754 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
8755 (message "Reference type switched to %s"
8756 (if org-table-buffer-is-an "A1 etc" "@row$column")))
8758 (defun org-table-fedit-ref-up ()
8759 "Shift the reference at point one row/hline up."
8760 (interactive)
8761 (org-table-fedit-shift-reference 'up))
8762 (defun org-table-fedit-ref-down ()
8763 "Shift the reference at point one row/hline down."
8764 (interactive)
8765 (org-table-fedit-shift-reference 'down))
8766 (defun org-table-fedit-ref-left ()
8767 "Shift the reference at point one field to the left."
8768 (interactive)
8769 (org-table-fedit-shift-reference 'left))
8770 (defun org-table-fedit-ref-right ()
8771 "Shift the reference at point one field to the right."
8772 (interactive)
8773 (org-table-fedit-shift-reference 'right))
8775 (defun org-table-fedit-shift-reference (dir)
8776 (cond
8777 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
8778 (if (memq dir '(left right))
8779 (org-rematch-and-replace 1 (eq dir 'left))
8780 (error "Cannot shift reference in this direction")))
8781 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
8782 ;; A B3-like reference
8783 (if (memq dir '(up down))
8784 (org-rematch-and-replace 2 (eq dir 'up))
8785 (org-rematch-and-replace 1 (eq dir 'left))))
8786 ((org-at-regexp-p
8787 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
8788 ;; An internal reference
8789 (if (memq dir '(up down))
8790 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
8791 (org-rematch-and-replace 5 (eq dir 'left))))))
8793 (defun org-rematch-and-replace (n &optional decr hline)
8794 "Re-match the group N, and replace it with the shifted refrence."
8795 (or (match-end n) (error "Cannot shift reference in this direction"))
8796 (goto-char (match-beginning n))
8797 (and (looking-at (regexp-quote (match-string n)))
8798 (replace-match (org-shift-refpart (match-string 0) decr hline)
8799 t t)))
8801 (defun org-shift-refpart (ref &optional decr hline)
8802 "Shift a refrence part REF.
8803 If DECR is set, decrease the references row/column, else increase.
8804 If HLINE is set, this may be a hline reference, it certainly is not
8805 a translation reference."
8806 (save-match-data
8807 (let* ((sign (string-match "^[-+]" ref)) n)
8809 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
8810 (cond
8811 ((and hline (string-match "^I+" ref))
8812 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
8813 (setq n (+ n (if decr -1 1)))
8814 (if (= n 0) (setq n (+ n (if decr -1 1))))
8815 (if sign
8816 (setq sign (if (< n 0) "-" "+") n (abs n))
8817 (setq n (max 1 n)))
8818 (concat sign (make-string n ?I)))
8820 ((string-match "^[0-9]+" ref)
8821 (setq n (string-to-number (concat sign ref)))
8822 (setq n (+ n (if decr -1 1)))
8823 (if sign
8824 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
8825 (number-to-string (max 1 n))))
8827 ((string-match "^[a-zA-Z]+" ref)
8828 (org-number-to-letters
8829 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
8831 (t (error "Cannot shift reference"))))))
8833 (defun org-table-fedit-toggle-coordinates ()
8834 "Toggle the display of coordinates in the refrenced table."
8835 (interactive)
8836 (let ((pos (marker-position org-pos)))
8837 (with-current-buffer (marker-buffer org-pos)
8838 (save-excursion
8839 (goto-char pos)
8840 (org-table-toggle-coordinate-overlays)))))
8842 (defun org-table-fedit-finish (&optional arg)
8843 "Parse the buffer for formula definitions and install them.
8844 With prefix ARG, apply the new formulas to the table."
8845 (interactive "P")
8846 (org-table-remove-rectangle-highlight)
8847 (if org-table-use-standard-references
8848 (progn
8849 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
8850 (setq org-table-buffer-is-an nil)))
8851 (let ((pos org-pos) eql var form)
8852 (goto-char (point-min))
8853 (while (re-search-forward
8854 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
8855 nil t)
8856 (setq var (if (match-end 2) (match-string 2) (match-string 1))
8857 form (match-string 3))
8858 (setq form (org-trim form))
8859 (when (not (equal form ""))
8860 (while (string-match "[ \t]*\n[ \t]*" form)
8861 (setq form (replace-match " " t t form)))
8862 (when (assoc var eql)
8863 (error "Double formulas for %s" var))
8864 (push (cons var form) eql)))
8865 (setq org-pos nil)
8866 (set-window-configuration org-window-configuration)
8867 (select-window (get-buffer-window (marker-buffer pos)))
8868 (goto-char pos)
8869 (unless (org-at-table-p)
8870 (error "Lost table position - cannot install formulae"))
8871 (org-table-store-formulas eql)
8872 (move-marker pos nil)
8873 (kill-buffer "*Edit Formulas*")
8874 (if arg
8875 (org-table-recalculate 'all)
8876 (message "New formulas installed - press C-u C-c C-c to apply."))))
8878 (defun org-table-fedit-abort ()
8879 "Abort editing formulas, without installing the changes."
8880 (interactive)
8881 (org-table-remove-rectangle-highlight)
8882 (let ((pos org-pos))
8883 (set-window-configuration org-window-configuration)
8884 (select-window (get-buffer-window (marker-buffer pos)))
8885 (goto-char pos)
8886 (move-marker pos nil)
8887 (message "Formula editing aborted without installing changes")))
8889 (defun org-table-fedit-lisp-indent ()
8890 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
8891 (interactive)
8892 (let ((pos (point)) beg end ind)
8893 (beginning-of-line 1)
8894 (cond
8895 ((looking-at "[ \t]")
8896 (goto-char pos)
8897 (call-interactively 'lisp-indent-line))
8898 ((looking-at "[$@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
8899 ((not (fboundp 'pp-buffer))
8900 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
8901 ((looking-at "[$@0-9a-zA-Z]+ *= *'(")
8902 (goto-char (- (match-end 0) 2))
8903 (setq beg (point))
8904 (setq ind (make-string (current-column) ?\ ))
8905 (condition-case nil (forward-sexp 1)
8906 (error
8907 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
8908 (setq end (point))
8909 (save-restriction
8910 (narrow-to-region beg end)
8911 (if (eq last-command this-command)
8912 (progn
8913 (goto-char (point-min))
8914 (setq this-command nil)
8915 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
8916 (replace-match " ")))
8917 (pp-buffer)
8918 (untabify (point-min) (point-max))
8919 (goto-char (1+ (point-min)))
8920 (while (re-search-forward "^." nil t)
8921 (beginning-of-line 1)
8922 (insert ind))
8923 (goto-char (point-max))
8924 (backward-delete-char 1)))
8925 (goto-char beg))
8926 (t nil))))
8928 (defvar org-show-positions nil)
8930 (defun org-table-show-reference (&optional local)
8931 "Show the location/value of the $ expression at point."
8932 (interactive)
8933 (org-table-remove-rectangle-highlight)
8934 (catch 'exit
8935 (let ((pos (if local (point) org-pos))
8936 (face2 'highlight)
8937 (org-inhibit-highlight-removal t)
8938 (win (selected-window))
8939 (org-show-positions nil)
8940 var name e what match dest)
8941 (if local (org-table-get-specials))
8942 (setq what (cond
8943 ((or (org-at-regexp-p org-table-range-regexp2)
8944 (org-at-regexp-p org-table-translate-regexp)
8945 (org-at-regexp-p org-table-range-regexp))
8946 (setq match
8947 (save-match-data
8948 (org-table-convert-refs-to-rc (match-string 0))))
8949 'range)
8950 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
8951 ((org-at-regexp-p "\\$[0-9]+") 'column)
8952 ((not local) nil)
8953 (t (error "No reference at point")))
8954 match (and what (or match (match-string 0))))
8955 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
8956 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
8957 'secondary-selection))
8958 (org-add-hook 'before-change-functions
8959 'org-table-remove-rectangle-highlight)
8960 (if (eq what 'name) (setq var (substring match 1)))
8961 (when (eq what 'range)
8962 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
8963 (setq match (org-table-formula-substitute-names match)))
8964 (unless local
8965 (save-excursion
8966 (end-of-line 1)
8967 (re-search-backward "^\\S-" nil t)
8968 (beginning-of-line 1)
8969 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
8970 (setq dest
8971 (save-match-data
8972 (org-table-convert-refs-to-rc (match-string 1))))
8973 (org-table-add-rectangle-overlay
8974 (match-beginning 1) (match-end 1) face2))))
8975 (if (and (markerp pos) (marker-buffer pos))
8976 (if (get-buffer-window (marker-buffer pos))
8977 (select-window (get-buffer-window (marker-buffer pos)))
8978 (switch-to-buffer-other-window (get-buffer-window
8979 (marker-buffer pos)))))
8980 (goto-char pos)
8981 (org-table-force-dataline)
8982 (when dest
8983 (setq name (substring dest 1))
8984 (cond
8985 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
8986 (setq e (assoc name org-table-named-field-locations))
8987 (goto-line (nth 1 e))
8988 (org-table-goto-column (nth 2 e)))
8989 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
8990 (let ((l (string-to-number (match-string 1 dest)))
8991 (c (string-to-number (match-string 2 dest))))
8992 (goto-line (aref org-table-dlines l))
8993 (org-table-goto-column c)))
8994 (t (org-table-goto-column (string-to-number name))))
8995 (move-marker pos (point))
8996 (org-table-highlight-rectangle nil nil face2))
8997 (cond
8998 ((equal dest match))
8999 ((not match))
9000 ((eq what 'range)
9001 (condition-case nil
9002 (save-excursion
9003 (org-table-get-range match nil nil 'highlight))
9004 (error nil)))
9005 ((setq e (assoc var org-table-named-field-locations))
9006 (goto-line (nth 1 e))
9007 (org-table-goto-column (nth 2 e))
9008 (org-table-highlight-rectangle (point) (point))
9009 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9010 ((setq e (assoc var org-table-column-names))
9011 (org-table-goto-column (string-to-number (cdr e)))
9012 (org-table-highlight-rectangle (point) (point))
9013 (goto-char (org-table-begin))
9014 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9015 (org-table-end) t)
9016 (progn
9017 (goto-char (match-beginning 1))
9018 (org-table-highlight-rectangle)
9019 (message "Named column (column %s)" (cdr e)))
9020 (error "Column name not found")))
9021 ((eq what 'column)
9022 ;; column number
9023 (org-table-goto-column (string-to-number (substring match 1)))
9024 (org-table-highlight-rectangle (point) (point))
9025 (message "Column %s" (substring match 1)))
9026 ((setq e (assoc var org-table-local-parameters))
9027 (goto-char (org-table-begin))
9028 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9029 (progn
9030 (goto-char (match-beginning 1))
9031 (org-table-highlight-rectangle)
9032 (message "Local parameter."))
9033 (error "Parameter not found")))
9035 (cond
9036 ((not var) (error "No reference at point"))
9037 ((setq e (assoc var org-table-formula-constants))
9038 (message "Constant: $%s=%s in `org-table-formula-constants'."
9039 var (cdr e)))
9040 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9041 (message "Constant: $%s=%s, from `constants.el'%s."
9042 var e (format " (%s units)" constants-unit-system)))
9043 (t (error "Undefined name $%s" var)))))
9044 (goto-char pos)
9045 (when (and org-show-positions
9046 (not (memq this-command '(org-table-fedit-scroll
9047 org-table-fedit-scroll-down))))
9048 (push pos org-show-positions)
9049 (push org-table-current-begin-pos org-show-positions)
9050 (let ((min (apply 'min org-show-positions))
9051 (max (apply 'max org-show-positions)))
9052 (goto-char min) (recenter 0)
9053 (goto-char max)
9054 (or (pos-visible-in-window-p max) (recenter -1))))
9055 (select-window win))))
9057 (defun org-table-force-dataline ()
9058 "Make sure the cursor is in a dataline in a table."
9059 (unless (save-excursion
9060 (beginning-of-line 1)
9061 (looking-at org-table-dataline-regexp))
9062 (let* ((re org-table-dataline-regexp)
9063 (p1 (save-excursion (re-search-forward re nil 'move)))
9064 (p2 (save-excursion (re-search-backward re nil 'move))))
9065 (cond ((and p1 p2)
9066 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
9067 p1 p2)))
9068 ((or p1 p2) (goto-char (or p1 p2)))
9069 (t (error "No table dataline around here"))))))
9071 (defun org-table-fedit-line-up ()
9072 "Move cursor one line up in the window showing the table."
9073 (interactive)
9074 (org-table-fedit-move 'previous-line))
9076 (defun org-table-fedit-line-down ()
9077 "Move cursor one line down in the window showing the table."
9078 (interactive)
9079 (org-table-fedit-move 'next-line))
9081 (defun org-table-fedit-move (command)
9082 "Move the cursor in the window shoinw the table.
9083 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
9084 (let ((org-table-allow-automatic-line-recalculation nil)
9085 (pos org-pos) (win (selected-window)) p)
9086 (select-window (get-buffer-window (marker-buffer org-pos)))
9087 (setq p (point))
9088 (call-interactively command)
9089 (while (and (org-at-table-p)
9090 (org-at-table-hline-p))
9091 (call-interactively command))
9092 (or (org-at-table-p) (goto-char p))
9093 (move-marker pos (point))
9094 (select-window win)))
9096 (defun org-table-fedit-scroll (N)
9097 (interactive "p")
9098 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
9099 (scroll-other-window N)))
9101 (defun org-table-fedit-scroll-down (N)
9102 (interactive "p")
9103 (org-table-fedit-scroll (- N)))
9105 (defvar org-table-rectangle-overlays nil)
9107 (defun org-table-add-rectangle-overlay (beg end &optional face)
9108 "Add a new overlay."
9109 (let ((ov (org-make-overlay beg end)))
9110 (org-overlay-put ov 'face (or face 'secondary-selection))
9111 (push ov org-table-rectangle-overlays)))
9113 (defun org-table-highlight-rectangle (&optional beg end face)
9114 "Highlight rectangular region in a table."
9115 (setq beg (or beg (point)) end (or end (point)))
9116 (let ((b (min beg end))
9117 (e (max beg end))
9118 l1 c1 l2 c2 tmp)
9119 (and (boundp 'org-show-positions)
9120 (setq org-show-positions (cons b (cons e org-show-positions))))
9121 (goto-char (min beg end))
9122 (setq l1 (org-current-line)
9123 c1 (org-table-current-column))
9124 (goto-char (max beg end))
9125 (setq l2 (org-current-line)
9126 c2 (org-table-current-column))
9127 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
9128 (goto-line l1)
9129 (beginning-of-line 1)
9130 (loop for line from l1 to l2 do
9131 (when (looking-at org-table-dataline-regexp)
9132 (org-table-goto-column c1)
9133 (skip-chars-backward "^|\n") (setq beg (point))
9134 (org-table-goto-column c2)
9135 (skip-chars-forward "^|\n") (setq end (point))
9136 (org-table-add-rectangle-overlay beg end face))
9137 (beginning-of-line 2))
9138 (goto-char b))
9139 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
9141 (defun org-table-remove-rectangle-highlight (&rest ignore)
9142 "Remove the rectangle overlays."
9143 (unless org-inhibit-highlight-removal
9144 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
9145 (mapc 'org-delete-overlay org-table-rectangle-overlays)
9146 (setq org-table-rectangle-overlays nil)))
9148 (defvar org-table-coordinate-overlays nil
9149 "Collects the cooordinate grid overlays, so that they can be removed.")
9150 (make-variable-buffer-local 'org-table-coordinate-overlays)
9152 (defun org-table-overlay-coordinates ()
9153 "Add overlays to the table at point, to show row/column coordinates."
9154 (interactive)
9155 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9156 (setq org-table-coordinate-overlays nil)
9157 (save-excursion
9158 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
9159 (goto-char (org-table-begin))
9160 (while (org-at-table-p)
9161 (setq eol (point-at-eol))
9162 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
9163 (push ov org-table-coordinate-overlays)
9164 (setq hline (looking-at org-table-hline-regexp))
9165 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
9166 (format "%4d" (setq id (1+ id)))))
9167 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
9168 (when hline
9169 (setq ic 0)
9170 (while (re-search-forward "[+|]\\(-+\\)" eol t)
9171 (setq beg (1+ (match-beginning 0))
9172 ic (1+ ic)
9173 s1 (concat "$" (int-to-string ic))
9174 s2 (org-number-to-letters ic)
9175 str (if (eq org-table-use-standard-references t) s2 s1))
9176 (setq ov (org-make-overlay beg (+ beg (length str))))
9177 (push ov org-table-coordinate-overlays)
9178 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
9179 (beginning-of-line 2)))))
9181 (defun org-table-toggle-coordinate-overlays ()
9182 "Toggle the display of Row/Column numbers in tables."
9183 (interactive)
9184 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
9185 (message "Row/Column number display turned %s"
9186 (if org-table-overlay-coordinates "on" "off"))
9187 (if (and (org-at-table-p) org-table-overlay-coordinates)
9188 (org-table-align))
9189 (unless org-table-overlay-coordinates
9190 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9191 (setq org-table-coordinate-overlays nil)))
9193 (defun org-table-toggle-formula-debugger ()
9194 "Toggle the formula debugger in tables."
9195 (interactive)
9196 (setq org-table-formula-debug (not org-table-formula-debug))
9197 (message "Formula debugging has been turned %s"
9198 (if org-table-formula-debug "on" "off")))
9200 ;;; The orgtbl minor mode
9202 ;; Define a minor mode which can be used in other modes in order to
9203 ;; integrate the org-mode table editor.
9205 ;; This is really a hack, because the org-mode table editor uses several
9206 ;; keys which normally belong to the major mode, for example the TAB and
9207 ;; RET keys. Here is how it works: The minor mode defines all the keys
9208 ;; necessary to operate the table editor, but wraps the commands into a
9209 ;; function which tests if the cursor is currently inside a table. If that
9210 ;; is the case, the table editor command is executed. However, when any of
9211 ;; those keys is used outside a table, the function uses `key-binding' to
9212 ;; look up if the key has an associated command in another currently active
9213 ;; keymap (minor modes, major mode, global), and executes that command.
9214 ;; There might be problems if any of the keys used by the table editor is
9215 ;; otherwise used as a prefix key.
9217 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9218 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9219 ;; addresses this by checking explicitly for both bindings.
9221 ;; The optimized version (see variable `orgtbl-optimized') takes over
9222 ;; all keys which are bound to `self-insert-command' in the *global map*.
9223 ;; Some modes bind other commands to simple characters, for example
9224 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9225 ;; active, this binding is ignored inside tables and replaced with a
9226 ;; modified self-insert.
9228 (defvar orgtbl-mode nil
9229 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9230 table editor in arbitrary modes.")
9231 (make-variable-buffer-local 'orgtbl-mode)
9233 (defvar orgtbl-mode-map (make-keymap)
9234 "Keymap for `orgtbl-mode'.")
9236 ;;;###autoload
9237 (defun turn-on-orgtbl ()
9238 "Unconditionally turn on `orgtbl-mode'."
9239 (orgtbl-mode 1))
9241 (defvar org-old-auto-fill-inhibit-regexp nil
9242 "Local variable used by `orgtbl-mode'")
9244 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
9245 "Matches a line belonging to an orgtbl.")
9247 (defconst orgtbl-extra-font-lock-keywords
9248 (list (list (concat "^" orgtbl-line-start-regexp ".*")
9249 0 (quote 'org-table) 'prepend))
9250 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
9252 ;;;###autoload
9253 (defun orgtbl-mode (&optional arg)
9254 "The `org-mode' table editor as a minor mode for use in other modes."
9255 (interactive)
9256 (if (org-mode-p)
9257 ;; Exit without error, in case some hook functions calls this
9258 ;; by accident in org-mode.
9259 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9260 (setq orgtbl-mode
9261 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9262 (if orgtbl-mode
9263 (progn
9264 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9265 ;; Make sure we are first in minor-mode-map-alist
9266 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9267 (and c (setq minor-mode-map-alist
9268 (cons c (delq c minor-mode-map-alist)))))
9269 (org-set-local (quote org-table-may-need-update) t)
9270 (org-add-hook 'before-change-functions 'org-before-change-function
9271 nil 'local)
9272 (org-set-local 'org-old-auto-fill-inhibit-regexp
9273 auto-fill-inhibit-regexp)
9274 (org-set-local 'auto-fill-inhibit-regexp
9275 (if auto-fill-inhibit-regexp
9276 (concat orgtbl-line-start-regexp "\\|"
9277 auto-fill-inhibit-regexp)
9278 orgtbl-line-start-regexp))
9279 (org-add-to-invisibility-spec '(org-cwidth))
9280 (when (fboundp 'font-lock-add-keywords)
9281 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
9282 (org-restart-font-lock))
9283 (easy-menu-add orgtbl-mode-menu)
9284 (run-hooks 'orgtbl-mode-hook))
9285 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9286 (org-cleanup-narrow-column-properties)
9287 (org-remove-from-invisibility-spec '(org-cwidth))
9288 (remove-hook 'before-change-functions 'org-before-change-function t)
9289 (when (fboundp 'font-lock-remove-keywords)
9290 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
9291 (org-restart-font-lock))
9292 (easy-menu-remove orgtbl-mode-menu)
9293 (force-mode-line-update 'all))))
9295 (defun org-cleanup-narrow-column-properties ()
9296 "Remove all properties related to narrow-column invisibility."
9297 (let ((s 1))
9298 (while (setq s (text-property-any s (point-max)
9299 'display org-narrow-column-arrow))
9300 (remove-text-properties s (1+ s) '(display t)))
9301 (setq s 1)
9302 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
9303 (remove-text-properties s (1+ s) '(org-cwidth t)))
9304 (setq s 1)
9305 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
9306 (remove-text-properties s (1+ s) '(invisible t)))))
9308 ;; Install it as a minor mode.
9309 (put 'orgtbl-mode :included t)
9310 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9311 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9313 (defun orgtbl-make-binding (fun n &rest keys)
9314 "Create a function for binding in the table minor mode.
9315 FUN is the command to call inside a table. N is used to create a unique
9316 command name. KEYS are keys that should be checked in for a command
9317 to execute outside of tables."
9318 (eval
9319 (list 'defun
9320 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9321 '(arg)
9322 (concat "In tables, run `" (symbol-name fun) "'.\n"
9323 "Outside of tables, run the binding of `"
9324 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9325 "'.")
9326 '(interactive "p")
9327 (list 'if
9328 '(org-at-table-p)
9329 (list 'call-interactively (list 'quote fun))
9330 (list 'let '(orgtbl-mode)
9331 (list 'call-interactively
9332 (append '(or)
9333 (mapcar (lambda (k)
9334 (list 'key-binding k))
9335 keys)
9336 '('orgtbl-error))))))))
9338 (defun orgtbl-error ()
9339 "Error when there is no default binding for a table key."
9340 (interactive)
9341 (error "This key is has no function outside tables"))
9343 (defun orgtbl-setup ()
9344 "Setup orgtbl keymaps."
9345 (let ((nfunc 0)
9346 (bindings
9347 (list
9348 '([(meta shift left)] org-table-delete-column)
9349 '([(meta left)] org-table-move-column-left)
9350 '([(meta right)] org-table-move-column-right)
9351 '([(meta shift right)] org-table-insert-column)
9352 '([(meta shift up)] org-table-kill-row)
9353 '([(meta shift down)] org-table-insert-row)
9354 '([(meta up)] org-table-move-row-up)
9355 '([(meta down)] org-table-move-row-down)
9356 '("\C-c\C-w" org-table-cut-region)
9357 '("\C-c\M-w" org-table-copy-region)
9358 '("\C-c\C-y" org-table-paste-rectangle)
9359 '("\C-c-" org-table-insert-hline)
9360 '("\C-c}" org-table-toggle-coordinate-overlays)
9361 '("\C-c{" org-table-toggle-formula-debugger)
9362 '("\C-m" org-table-next-row)
9363 '([(shift return)] org-table-copy-down)
9364 '("\C-c\C-q" org-table-wrap-region)
9365 '("\C-c?" org-table-field-info)
9366 '("\C-c " org-table-blank-field)
9367 '("\C-c+" org-table-sum)
9368 '("\C-c=" org-table-eval-formula)
9369 '("\C-c'" org-table-edit-formulas)
9370 '("\C-c`" org-table-edit-field)
9371 '("\C-c*" org-table-recalculate)
9372 '("\C-c|" org-table-create-or-convert-from-region)
9373 '("\C-c^" org-table-sort-lines)
9374 '([(control ?#)] org-table-rotate-recalc-marks)))
9375 elt key fun cmd)
9376 (while (setq elt (pop bindings))
9377 (setq nfunc (1+ nfunc))
9378 (setq key (org-key (car elt))
9379 fun (nth 1 elt)
9380 cmd (orgtbl-make-binding fun nfunc key))
9381 (org-defkey orgtbl-mode-map key cmd))
9383 ;; Special treatment needed for TAB and RET
9384 (org-defkey orgtbl-mode-map [(return)]
9385 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9386 (org-defkey orgtbl-mode-map "\C-m"
9387 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9389 (org-defkey orgtbl-mode-map [(tab)]
9390 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9391 (org-defkey orgtbl-mode-map "\C-i"
9392 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
9394 (org-defkey orgtbl-mode-map [(shift tab)]
9395 (orgtbl-make-binding 'org-table-previous-field 104
9396 [(shift tab)] [(tab)] "\C-i"))
9398 (org-defkey orgtbl-mode-map "\M-\C-m"
9399 (orgtbl-make-binding 'org-table-wrap-region 105
9400 "\M-\C-m" [(meta return)]))
9401 (org-defkey orgtbl-mode-map [(meta return)]
9402 (orgtbl-make-binding 'org-table-wrap-region 106
9403 [(meta return)] "\M-\C-m"))
9405 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
9406 (when orgtbl-optimized
9407 ;; If the user wants maximum table support, we need to hijack
9408 ;; some standard editing functions
9409 (org-remap orgtbl-mode-map
9410 'self-insert-command 'orgtbl-self-insert-command
9411 'delete-char 'org-delete-char
9412 'delete-backward-char 'org-delete-backward-char)
9413 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
9414 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9415 '("OrgTbl"
9416 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9417 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9418 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9419 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9420 "--"
9421 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9422 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
9423 ["Copy Field from Above"
9424 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9425 "--"
9426 ("Column"
9427 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9428 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9429 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9430 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9431 ("Row"
9432 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9433 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9434 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9435 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9436 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9437 "--"
9438 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9439 ("Rectangle"
9440 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9441 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9442 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9443 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9444 "--"
9445 ("Radio tables"
9446 ["Insert table template" orgtbl-insert-radio-table
9447 (assq major-mode orgtbl-radio-table-templates)]
9448 ["Comment/uncomment table" orgtbl-toggle-comment t])
9449 "--"
9450 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9451 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9452 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9453 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9454 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9455 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
9456 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9457 ["Sum Column/Rectangle" org-table-sum
9458 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9459 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9460 ["Debug Formulas"
9461 org-table-toggle-formula-debugger :active (org-at-table-p)
9462 :keys "C-c {"
9463 :style toggle :selected org-table-formula-debug]
9464 ["Show Col/Row Numbers"
9465 org-table-toggle-coordinate-overlays :active (org-at-table-p)
9466 :keys "C-c }"
9467 :style toggle :selected org-table-overlay-coordinates]
9471 (defun orgtbl-ctrl-c-ctrl-c (arg)
9472 "If the cursor is inside a table, realign the table.
9473 It it is a table to be sent away to a receiver, do it.
9474 With prefix arg, also recompute table."
9475 (interactive "P")
9476 (let ((pos (point)) action)
9477 (save-excursion
9478 (beginning-of-line 1)
9479 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
9480 ((looking-at "[ \t]*|") pos)
9481 ((looking-at "#\\+TBLFM:") 'recalc))))
9482 (cond
9483 ((integerp action)
9484 (goto-char action)
9485 (org-table-maybe-eval-formula)
9486 (if arg
9487 (call-interactively 'org-table-recalculate)
9488 (org-table-maybe-recalculate-line))
9489 (call-interactively 'org-table-align)
9490 (orgtbl-send-table 'maybe))
9491 ((eq action 'recalc)
9492 (save-excursion
9493 (beginning-of-line 1)
9494 (skip-chars-backward " \r\n\t")
9495 (if (org-at-table-p)
9496 (org-call-with-arg 'org-table-recalculate t))))
9497 (t (let (orgtbl-mode)
9498 (call-interactively (key-binding "\C-c\C-c")))))))
9500 (defun orgtbl-tab (arg)
9501 "Justification and field motion for `orgtbl-mode'."
9502 (interactive "P")
9503 (if arg (org-table-edit-field t)
9504 (org-table-justify-field-maybe)
9505 (org-table-next-field)))
9507 (defun orgtbl-ret ()
9508 "Justification and field motion for `orgtbl-mode'."
9509 (interactive)
9510 (org-table-justify-field-maybe)
9511 (org-table-next-row))
9513 (defun orgtbl-self-insert-command (N)
9514 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9515 If the cursor is in a table looking at whitespace, the whitespace is
9516 overwritten, and the table is not marked as requiring realignment."
9517 (interactive "p")
9518 (if (and (org-at-table-p)
9520 (and org-table-auto-blank-field
9521 (member last-command
9522 '(orgtbl-hijacker-command-100
9523 orgtbl-hijacker-command-101
9524 orgtbl-hijacker-command-102
9525 orgtbl-hijacker-command-103
9526 orgtbl-hijacker-command-104
9527 orgtbl-hijacker-command-105))
9528 (org-table-blank-field))
9530 (eq N 1)
9531 (looking-at "[^|\n]* +|"))
9532 (let (org-table-may-need-update)
9533 (goto-char (1- (match-end 0)))
9534 (delete-backward-char 1)
9535 (goto-char (match-beginning 0))
9536 (self-insert-command N))
9537 (setq org-table-may-need-update t)
9538 (let (orgtbl-mode)
9539 (call-interactively (key-binding (vector last-input-event))))))
9541 (defun org-force-self-insert (N)
9542 "Needed to enforce self-insert under remapping."
9543 (interactive "p")
9544 (self-insert-command N))
9546 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
9547 "Regula expression matching exponentials as produced by calc.")
9549 (defvar org-table-clean-did-remove-column nil)
9551 (defun orgtbl-export (table target)
9552 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
9553 (lines (org-split-string table "[ \t]*\n[ \t]*"))
9554 org-table-last-alignment org-table-last-column-widths
9555 maxcol column)
9556 (if (not (fboundp func))
9557 (error "Cannot export orgtbl table to %s" target))
9558 (setq lines (org-table-clean-before-export lines))
9559 (setq table
9560 (mapcar
9561 (lambda (x)
9562 (if (string-match org-table-hline-regexp x)
9563 'hline
9564 (org-split-string (org-trim x) "\\s-*|\\s-*")))
9565 lines))
9566 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
9567 table)))
9568 (loop for i from (1- maxcol) downto 0 do
9569 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
9570 (setq column (delq nil column))
9571 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
9572 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
9573 (funcall func table nil)))
9575 (defun orgtbl-send-table (&optional maybe)
9576 "Send a tranformed version of this table to the receiver position.
9577 With argument MAYBE, fail quietly if no transformation is defined for
9578 this table."
9579 (interactive)
9580 (catch 'exit
9581 (unless (org-at-table-p) (error "Not at a table"))
9582 ;; when non-interactive, we assume align has just happened.
9583 (when (interactive-p) (org-table-align))
9584 (save-excursion
9585 (goto-char (org-table-begin))
9586 (beginning-of-line 0)
9587 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
9588 (if maybe
9589 (throw 'exit nil)
9590 (error "Don't know how to transform this table."))))
9591 (let* ((name (match-string 1))
9593 (transform (intern (match-string 2)))
9594 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
9595 (skip (plist-get params :skip))
9596 (skipcols (plist-get params :skipcols))
9597 (txt (buffer-substring-no-properties
9598 (org-table-begin) (org-table-end)))
9599 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
9600 (lines (org-table-clean-before-export lines))
9601 (i0 (if org-table-clean-did-remove-column 2 1))
9602 (table (mapcar
9603 (lambda (x)
9604 (if (string-match org-table-hline-regexp x)
9605 'hline
9606 (org-remove-by-index
9607 (org-split-string (org-trim x) "\\s-*|\\s-*")
9608 skipcols i0)))
9609 lines))
9610 (fun (if (= i0 2) 'cdr 'identity))
9611 (org-table-last-alignment
9612 (org-remove-by-index (funcall fun org-table-last-alignment)
9613 skipcols i0))
9614 (org-table-last-column-widths
9615 (org-remove-by-index (funcall fun org-table-last-column-widths)
9616 skipcols i0)))
9618 (unless (fboundp transform)
9619 (error "No such transformation function %s" transform))
9620 (setq txt (funcall transform table params))
9621 ;; Find the insertion place
9622 (save-excursion
9623 (goto-char (point-min))
9624 (unless (re-search-forward
9625 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
9626 (error "Don't know where to insert translated table"))
9627 (goto-char (match-beginning 0))
9628 (beginning-of-line 2)
9629 (setq beg (point))
9630 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
9631 (error "Cannot find end of insertion region"))
9632 (beginning-of-line 1)
9633 (delete-region beg (point))
9634 (goto-char beg)
9635 (insert txt "\n"))
9636 (message "Table converted and installed at receiver location"))))
9638 (defun org-remove-by-index (list indices &optional i0)
9639 "Remove the elements in LIST with indices in INDICES.
9640 First element has index 0, or I0 if given."
9641 (if (not indices)
9642 list
9643 (if (integerp indices) (setq indices (list indices)))
9644 (setq i0 (1- (or i0 0)))
9645 (delq :rm (mapcar (lambda (x)
9646 (setq i0 (1+ i0))
9647 (if (memq i0 indices) :rm x))
9648 list))))
9650 (defun orgtbl-toggle-comment ()
9651 "Comment or uncomment the orgtbl at point."
9652 (interactive)
9653 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
9654 (re2 (concat "^" orgtbl-line-start-regexp))
9655 (commented (save-excursion (beginning-of-line 1)
9656 (cond ((looking-at re1) t)
9657 ((looking-at re2) nil)
9658 (t (error "Not at an org table")))))
9659 (re (if commented re1 re2))
9660 beg end)
9661 (save-excursion
9662 (beginning-of-line 1)
9663 (while (looking-at re) (beginning-of-line 0))
9664 (beginning-of-line 2)
9665 (setq beg (point))
9666 (while (looking-at re) (beginning-of-line 2))
9667 (setq end (point)))
9668 (comment-region beg end (if commented '(4) nil))))
9670 (defun orgtbl-insert-radio-table ()
9671 "Insert a radio table template appropriate for this major mode."
9672 (interactive)
9673 (let* ((e (assq major-mode orgtbl-radio-table-templates))
9674 (txt (nth 1 e))
9675 name pos)
9676 (unless e (error "No radio table setup defined for %s" major-mode))
9677 (setq name (read-string "Table name: "))
9678 (while (string-match "%n" txt)
9679 (setq txt (replace-match name t t txt)))
9680 (or (bolp) (insert "\n"))
9681 (setq pos (point))
9682 (insert txt)
9683 (goto-char pos)))
9685 (defun org-get-param (params header i sym &optional hsym)
9686 "Get parameter value for symbol SYM.
9687 If this is a header line, actually get the value for the symbol with an
9688 additional \"h\" inserted after the colon.
9689 If the value is a protperty list, get the element for the current column.
9690 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
9691 (let ((val (plist-get params sym)))
9692 (and hsym header (setq val (or (plist-get params hsym) val)))
9693 (if (consp val) (plist-get val i) val)))
9695 (defun orgtbl-to-generic (table params)
9696 "Convert the orgtbl-mode TABLE to some other format.
9697 This generic routine can be used for many standard cases.
9698 TABLE is a list, each entry either the symbol `hline' for a horizontal
9699 separator line, or a list of fields for that line.
9700 PARAMS is a property list of parameters that can influence the conversion.
9701 For the generic converter, some parameters are obligatory: You need to
9702 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
9703 :splice, you must have :tstart and :tend.
9705 Valid parameters are
9707 :tstart String to start the table. Ignored when :splice is t.
9708 :tend String to end the table. Ignored when :splice is t.
9710 :splice When set to t, return only table body lines, don't wrap
9711 them into :tstart and :tend. Default is nil.
9713 :hline String to be inserted on horizontal separation lines.
9714 May be nil to ignore hlines.
9716 :lstart String to start a new table line.
9717 :lend String to end a table line
9718 :sep Separator between two fields
9719 :lfmt Format for entire line, with enough %s to capture all fields.
9720 If this is present, :lstart, :lend, and :sep are ignored.
9721 :fmt A format to be used to wrap the field, should contain
9722 %s for the original field value. For example, to wrap
9723 everything in dollars, you could use :fmt \"$%s$\".
9724 This may also be a property list with column numbers and
9725 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
9727 :hlstart :hlend :hlsep :hlfmt :hfmt
9728 Same as above, specific for the header lines in the table.
9729 All lines before the first hline are treated as header.
9730 If any of these is not present, the data line value is used.
9732 :efmt Use this format to print numbers with exponentials.
9733 The format should have %s twice for inserting mantissa
9734 and exponent, for example \"%s\\\\times10^{%s}\". This
9735 may also be a property list with column numbers and
9736 formats. :fmt will still be applied after :efmt.
9738 In addition to this, the parameters :skip and :skipcols are always handled
9739 directly by `orgtbl-send-table'. See manual."
9740 (interactive)
9741 (let* ((p params)
9742 (splicep (plist-get p :splice))
9743 (hline (plist-get p :hline))
9744 rtn line i fm efm lfmt h)
9746 ;; Do we have a header?
9747 (if (and (not splicep) (listp (car table)) (memq 'hline table))
9748 (setq h t))
9750 ;; Put header
9751 (unless splicep
9752 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
9754 ;; Now loop over all lines
9755 (while (setq line (pop table))
9756 (if (eq line 'hline)
9757 ;; A horizontal separator line
9758 (progn (if hline (push hline rtn))
9759 (setq h nil)) ; no longer in header
9760 ;; A normal line. Convert the fields, push line onto the result list
9761 (setq i 0)
9762 (setq line
9763 (mapcar
9764 (lambda (f)
9765 (setq i (1+ i)
9766 fm (org-get-param p h i :fmt :hfmt)
9767 efm (org-get-param p h i :efmt))
9768 (if (and efm (string-match orgtbl-exp-regexp f))
9769 (setq f (format
9770 efm (match-string 1 f) (match-string 2 f))))
9771 (if fm (setq f (format fm f)))
9773 line))
9774 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
9775 (push (apply 'format lfmt line) rtn)
9776 (push (concat
9777 (org-get-param p h i :lstart :hlstart)
9778 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
9779 (org-get-param p h i :lend :hlend))
9780 rtn))))
9782 (unless splicep
9783 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
9785 (mapconcat 'identity (nreverse rtn) "\n")))
9787 (defun orgtbl-to-latex (table params)
9788 "Convert the orgtbl-mode TABLE to LaTeX.
9789 TABLE is a list, each entry either the symbol `hline' for a horizontal
9790 separator line, or a list of fields for that line.
9791 PARAMS is a property list of parameters that can influence the conversion.
9792 Supports all parameters from `orgtbl-to-generic'. Most important for
9793 LaTeX are:
9795 :splice When set to t, return only table body lines, don't wrap
9796 them into a tabular environment. Default is nil.
9798 :fmt A format to be used to wrap the field, should contain %s for the
9799 original field value. For example, to wrap everything in dollars,
9800 use :fmt \"$%s$\". This may also be a property list with column
9801 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
9803 :efmt Format for transforming numbers with exponentials. The format
9804 should have %s twice for inserting mantissa and exponent, for
9805 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
9806 This may also be a property list with column numbers and formats.
9808 The general parameters :skip and :skipcols have already been applied when
9809 this function is called."
9810 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
9811 org-table-last-alignment ""))
9812 (params2
9813 (list
9814 :tstart (concat "\\begin{tabular}{" alignment "}")
9815 :tend "\\end{tabular}"
9816 :lstart "" :lend " \\\\" :sep " & "
9817 :efmt "%s\\,(%s)" :hline "\\hline")))
9818 (orgtbl-to-generic table (org-combine-plists params2 params))))
9820 (defun orgtbl-to-html (table params)
9821 "Convert the orgtbl-mode TABLE to LaTeX.
9822 TABLE is a list, each entry either the symbol `hline' for a horizontal
9823 separator line, or a list of fields for that line.
9824 PARAMS is a property list of parameters that can influence the conversion.
9825 Currently this function recognizes the following parameters:
9827 :splice When set to t, return only table body lines, don't wrap
9828 them into a <table> environment. Default is nil.
9830 The general parameters :skip and :skipcols have already been applied when
9831 this function is called. The function does *not* use `orgtbl-to-generic',
9832 so you cannot specify parameters for it."
9833 (let* ((splicep (plist-get params :splice))
9834 html)
9835 ;; Just call the formatter we already have
9836 ;; We need to make text lines for it, so put the fields back together.
9837 (setq html (org-format-org-table-html
9838 (mapcar
9839 (lambda (x)
9840 (if (eq x 'hline)
9841 "|----+----|"
9842 (concat "| " (mapconcat 'identity x " | ") " |")))
9843 table)
9844 splicep))
9845 (if (string-match "\n+\\'" html)
9846 (setq html (replace-match "" t t html)))
9847 html))
9849 (defun orgtbl-to-texinfo (table params)
9850 "Convert the orgtbl-mode TABLE to TeXInfo.
9851 TABLE is a list, each entry either the symbol `hline' for a horizontal
9852 separator line, or a list of fields for that line.
9853 PARAMS is a property list of parameters that can influence the conversion.
9854 Supports all parameters from `orgtbl-to-generic'. Most important for
9855 TeXInfo are:
9857 :splice nil/t When set to t, return only table body lines, don't wrap
9858 them into a multitable environment. Default is nil.
9860 :fmt fmt A format to be used to wrap the field, should contain
9861 %s for the original field value. For example, to wrap
9862 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
9863 This may also be a property list with column numbers and
9864 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
9866 :cf \"f1 f2..\" The column fractions for the table. Bye default these
9867 are computed automatically from the width of the columns
9868 under org-mode.
9870 The general parameters :skip and :skipcols have already been applied when
9871 this function is called."
9872 (let* ((total (float (apply '+ org-table-last-column-widths)))
9873 (colfrac (or (plist-get params :cf)
9874 (mapconcat
9875 (lambda (x) (format "%.3f" (/ (float x) total)))
9876 org-table-last-column-widths " ")))
9877 (params2
9878 (list
9879 :tstart (concat "@multitable @columnfractions " colfrac)
9880 :tend "@end multitable"
9881 :lstart "@item " :lend "" :sep " @tab "
9882 :hlstart "@headitem ")))
9883 (orgtbl-to-generic table (org-combine-plists params2 params))))
9885 ;;;; Link Stuff
9887 ;;; Link abbreviations
9889 (defun org-link-expand-abbrev (link)
9890 "Apply replacements as defined in `org-link-abbrev-alist."
9891 (if (string-match "^\\([a-zA-Z]+\\)\\(::?\\(.*\\)\\)?$" link)
9892 (let* ((key (match-string 1 link))
9893 (as (or (assoc key org-link-abbrev-alist-local)
9894 (assoc key org-link-abbrev-alist)))
9895 (tag (and (match-end 2) (match-string 3 link)))
9896 rpl)
9897 (if (not as)
9898 link
9899 (setq rpl (cdr as))
9900 (cond
9901 ((symbolp rpl) (funcall rpl tag))
9902 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9903 (t (concat rpl tag)))))
9904 link))
9906 ;;; Storing and inserting links
9908 (defvar org-insert-link-history nil
9909 "Minibuffer history for links inserted with `org-insert-link'.")
9911 (defvar org-stored-links nil
9912 "Contains the links stored with `org-store-link'.")
9914 (defvar org-store-link-plist nil
9915 "Plist with info about the most recently link created with `org-store-link'.")
9917 ;;;###autoload
9918 (defun org-store-link (arg)
9919 "\\<org-mode-map>Store an org-link to the current location.
9920 This link can later be inserted into an org-buffer with
9921 \\[org-insert-link].
9922 For some link types, a prefix arg is interpreted:
9923 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9924 For file links, arg negates `org-context-in-file-links'."
9925 (interactive "P")
9926 (setq org-store-link-plist nil) ; reset
9927 (let (link cpltxt desc description search txt)
9928 (cond
9930 ((eq major-mode 'bbdb-mode)
9931 (let ((name (bbdb-record-name (bbdb-current-record)))
9932 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
9933 (setq cpltxt (concat "bbdb:" (or name company))
9934 link (org-make-link cpltxt))
9935 (org-store-link-props :type "bbdb" :name name :company company)))
9937 ((eq major-mode 'Info-mode)
9938 (setq link (org-make-link "info:"
9939 (file-name-nondirectory Info-current-file)
9940 ":" Info-current-node))
9941 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9942 ":" Info-current-node))
9943 (org-store-link-props :type "info" :file Info-current-file
9944 :node Info-current-node))
9946 ((eq major-mode 'calendar-mode)
9947 (let ((cd (calendar-cursor-to-date)))
9948 (setq link
9949 (format-time-string
9950 (car org-time-stamp-formats)
9951 (apply 'encode-time
9952 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9953 nil nil nil))))
9954 (org-store-link-props :type "calendar" :date cd)))
9956 ((or (eq major-mode 'vm-summary-mode)
9957 (eq major-mode 'vm-presentation-mode))
9958 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9959 (vm-follow-summary-cursor)
9960 (save-excursion
9961 (vm-select-folder-buffer)
9962 (let* ((message (car vm-message-pointer))
9963 (folder buffer-file-name)
9964 (subject (vm-su-subject message))
9965 (to (vm-get-header-contents message "To"))
9966 (from (vm-get-header-contents message "From"))
9967 (message-id (vm-su-message-id message)))
9968 (org-store-link-props :type "vm" :from from :to to :subject subject
9969 :message-id message-id)
9970 (setq message-id (org-remove-angle-brackets message-id))
9971 (setq folder (abbreviate-file-name folder))
9972 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9973 folder)
9974 (setq folder (replace-match "" t t folder)))
9975 (setq cpltxt (org-email-link-description))
9976 (setq link (org-make-link "vm:" folder "#" message-id)))))
9978 ((eq major-mode 'wl-summary-mode)
9979 (let* ((msgnum (wl-summary-message-number))
9980 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9981 msgnum 'message-id))
9982 (wl-message-entity
9983 (if (fboundp 'elmo-message-entity)
9984 (elmo-message-entity
9985 wl-summary-buffer-elmo-folder msgnum)
9986 (elmo-msgdb-overview-get-entity
9987 msgnum (wl-summary-buffer-msgdb))))
9988 (from (wl-summary-line-from))
9989 (to (car (elmo-message-entity-field wl-message-entity 'to)))
9990 (subject (let (wl-thr-indent-string wl-parent-message-entity)
9991 (wl-summary-line-subject))))
9992 (org-store-link-props :type "wl" :from from :to to
9993 :subject subject :message-id message-id)
9994 (setq message-id (org-remove-angle-brackets message-id))
9995 (setq cpltxt (org-email-link-description))
9996 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9997 "#" message-id))))
9999 ((or (equal major-mode 'mh-folder-mode)
10000 (equal major-mode 'mh-show-mode))
10001 (let ((from (org-mhe-get-header "From:"))
10002 (to (org-mhe-get-header "To:"))
10003 (message-id (org-mhe-get-header "Message-Id:"))
10004 (subject (org-mhe-get-header "Subject:")))
10005 (org-store-link-props :type "mh" :from from :to to
10006 :subject subject :message-id message-id)
10007 (setq cpltxt (org-email-link-description))
10008 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10009 (org-remove-angle-brackets message-id)))))
10011 ((eq major-mode 'rmail-mode)
10012 (save-excursion
10013 (save-restriction
10014 (rmail-narrow-to-non-pruned-header)
10015 (let ((folder buffer-file-name)
10016 (message-id (mail-fetch-field "message-id"))
10017 (from (mail-fetch-field "from"))
10018 (to (mail-fetch-field "to"))
10019 (subject (mail-fetch-field "subject")))
10020 (org-store-link-props
10021 :type "rmail" :from from :to to
10022 :subject subject :message-id message-id)
10023 (setq message-id (org-remove-angle-brackets message-id))
10024 (setq cpltxt (org-email-link-description))
10025 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10027 ((eq major-mode 'gnus-group-mode)
10028 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10029 (gnus-group-group-name)) ; version
10030 ((fboundp 'gnus-group-name)
10031 (gnus-group-name))
10032 (t "???"))))
10033 (unless group (error "Not on a group"))
10034 (org-store-link-props :type "gnus" :group group)
10035 (setq cpltxt (concat
10036 (if (org-xor arg org-usenet-links-prefer-google)
10037 "http://groups.google.com/groups?group="
10038 "gnus:")
10039 group)
10040 link (org-make-link cpltxt))))
10042 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10043 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10044 (let* ((group gnus-newsgroup-name)
10045 (article (gnus-summary-article-number))
10046 (header (gnus-summary-article-header article))
10047 (from (mail-header-from header))
10048 (message-id (mail-header-id header))
10049 (date (mail-header-date header))
10050 (subject (gnus-summary-subject-string)))
10051 (org-store-link-props :type "gnus" :from from :subject subject
10052 :message-id message-id :group group)
10053 (setq cpltxt (org-email-link-description))
10054 (if (org-xor arg org-usenet-links-prefer-google)
10055 (setq link
10056 (concat
10057 cpltxt "\n "
10058 (format "http://groups.google.com/groups?as_umsgid=%s"
10059 (org-fixup-message-id-for-http message-id))))
10060 (setq link (org-make-link "gnus:" group
10061 "#" (number-to-string article))))))
10063 ((eq major-mode 'w3-mode)
10064 (setq cpltxt (url-view-url t)
10065 link (org-make-link cpltxt))
10066 (org-store-link-props :type "w3" :url (url-view-url t)))
10068 ((eq major-mode 'w3m-mode)
10069 (setq cpltxt (or w3m-current-title w3m-current-url)
10070 link (org-make-link w3m-current-url))
10071 (org-store-link-props :type "w3m" :url (url-view-url t)))
10073 ((setq search (run-hook-with-args-until-success
10074 'org-create-file-search-functions))
10075 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10076 "::" search))
10077 (setq cpltxt (or description link)))
10079 ((eq major-mode 'image-mode)
10080 (setq cpltxt (concat "file:"
10081 (abbreviate-file-name buffer-file-name))
10082 link (org-make-link cpltxt))
10083 (org-store-link-props :type "image" :file buffer-file-name))
10085 ((eq major-mode 'dired-mode)
10086 ;; link to the file in the current line
10087 (setq cpltxt (concat "file:"
10088 (abbreviate-file-name
10089 (expand-file-name
10090 (dired-get-filename nil t))))
10091 link (org-make-link cpltxt)))
10093 ((and buffer-file-name (org-mode-p))
10094 ;; Just link to current headline
10095 (setq cpltxt (concat "file:"
10096 (abbreviate-file-name buffer-file-name)))
10097 ;; Add a context search string
10098 (when (org-xor org-context-in-file-links arg)
10099 ;; Check if we are on a target
10100 (if (org-in-regexp "<<\\(.*?\\)>>")
10101 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10102 (setq txt (cond
10103 ((org-on-heading-p) nil)
10104 ((org-region-active-p)
10105 (buffer-substring (region-beginning) (region-end)))
10106 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10107 (when (or (null txt) (string-match "\\S-" txt))
10108 (setq cpltxt
10109 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10110 desc "NONE"))))
10111 (if (string-match "::\\'" cpltxt)
10112 (setq cpltxt (substring cpltxt 0 -2)))
10113 (setq link (org-make-link cpltxt)))
10115 (buffer-file-name
10116 ;; Just link to this file here.
10117 (setq cpltxt (concat "file:"
10118 (abbreviate-file-name buffer-file-name)))
10119 ;; Add a context string
10120 (when (org-xor org-context-in-file-links arg)
10121 (setq txt (if (org-region-active-p)
10122 (buffer-substring (region-beginning) (region-end))
10123 (buffer-substring (point-at-bol) (point-at-eol))))
10124 ;; Only use search option if there is some text.
10125 (when (string-match "\\S-" txt)
10126 (setq cpltxt
10127 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10128 desc "NONE")))
10129 (setq link (org-make-link cpltxt)))
10131 ((interactive-p)
10132 (error "Cannot link to a buffer which is not visiting a file"))
10134 (t (setq link nil)))
10136 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10137 (setq link (or link cpltxt)
10138 desc (or desc cpltxt))
10139 (if (equal desc "NONE") (setq desc nil))
10141 (if (and (interactive-p) link)
10142 (progn
10143 (setq org-stored-links
10144 (cons (list cpltxt link desc) org-stored-links))
10145 (message "Stored: %s" (or cpltxt link)))
10146 (org-make-link-string link desc))))
10148 (defun org-store-link-props (&rest plist)
10149 "Store link properties, extract names and addresses."
10150 (let (x adr)
10151 (when (setq x (plist-get plist :from))
10152 (setq adr (mail-extract-address-components x))
10153 (plist-put plist :fromname (car adr))
10154 (plist-put plist :fromaddress (nth 1 adr)))
10155 (when (setq x (plist-get plist :to))
10156 (setq adr (mail-extract-address-components x))
10157 (plist-put plist :toname (car adr))
10158 (plist-put plist :toaddress (nth 1 adr))))
10159 (let ((from (plist-get plist :from))
10160 (to (plist-get plist :to)))
10161 (when (and from to org-from-is-user-regexp)
10162 (plist-put plist :fromto
10163 (if (string-match org-from-is-user-regexp from)
10164 (concat "to %t")
10165 (concat "from %f")))))
10166 (setq org-store-link-plist plist))
10168 (defun org-email-link-description (&optional fmt)
10169 "Return the description part of an email link.
10170 This takes information from `org-store-link-plist' and formats it
10171 according to FMT (default from `org-email-link-description-format')."
10172 (setq fmt (or fmt org-email-link-description-format))
10173 (let* ((p org-store-link-plist)
10174 (to (plist-get p :toaddress))
10175 (from (plist-get p :fromaddress))
10176 (table
10177 (list
10178 (cons "%c" (plist-get p :fromto))
10179 (cons "%F" (plist-get p :from))
10180 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10181 (cons "%T" (plist-get p :to))
10182 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10183 (cons "%s" (plist-get p :subject))
10184 (cons "%m" (plist-get p :message-id)))))
10185 (when (string-match "%c" fmt)
10186 ;; Check if the user wrote this message
10187 (if (and org-from-is-user-regexp from to
10188 (save-match-data (string-match org-from-is-user-regexp from)))
10189 (setq fmt (replace-match "to %t" t t fmt))
10190 (setq fmt (replace-match "from %f" t t fmt))))
10191 (org-replace-escapes fmt table)))
10193 (defun org-make-org-heading-search-string (&optional string heading)
10194 "Make search string for STRING or current headline."
10195 (interactive)
10196 (let ((s (or string (org-get-heading))))
10197 (unless (and string (not heading))
10198 ;; We are using a headline, clean up garbage in there.
10199 (if (string-match org-todo-regexp s)
10200 (setq s (replace-match "" t t s)))
10201 (if (string-match ":[a-zA-Z0-9_@:]+:[ \t]*$" s)
10202 (setq s (replace-match "" t t s)))
10203 (setq s (org-trim s))
10204 (if (string-match (concat "^\\(" org-quote-string "\\|"
10205 org-comment-string "\\)") s)
10206 (setq s (replace-match "" t t s)))
10207 (while (string-match org-ts-regexp s)
10208 (setq s (replace-match "" t t s))))
10209 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10210 (setq s (replace-match " " t t s)))
10211 (or string (setq s (concat "*" s))) ; Add * for headlines
10212 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10214 (defun org-make-link (&rest strings)
10215 "Concatenate STRINGS, format resulting string with `org-link-format'."
10216 (apply 'concat strings))
10218 (defun org-make-link-string (link &optional description)
10219 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10220 (when (stringp description)
10221 ;; Remove brackets from the description, they are fatal.
10222 (while (string-match "\\[\\|\\]" description)
10223 (setq description (replace-match "" t t description))))
10224 (when (equal (org-link-escape link) description)
10225 ;; No description needed, it is identical
10226 (setq description nil))
10227 (when (and (not description)
10228 (not (equal link (org-link-escape link))))
10229 (setq description link))
10230 (concat "[[" (org-link-escape link) "]"
10231 (if description (concat "[" description "]") "")
10232 "]"))
10234 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
10235 "Association list of escapes for some characters problematic in links.")
10237 (defun org-link-escape (text)
10238 "Escape charaters in TEXT that are problematic for links."
10239 (when text
10240 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10241 org-link-escape-chars "\\|")))
10242 (while (string-match re text)
10243 (setq text
10244 (replace-match
10245 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10246 t t text)))
10247 text)))
10249 (defun org-link-unescape (text)
10250 "Reverse the action of `org-link-escape'."
10251 (when text
10252 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10253 org-link-escape-chars "\\|")))
10254 (while (string-match re text)
10255 (setq text
10256 (replace-match
10257 (car (rassoc (match-string 0 text) org-link-escape-chars))
10258 t t text)))
10259 text)))
10261 (defun org-xor (a b)
10262 "Exclusive or."
10263 (if a (not b) b))
10265 (defun org-get-header (header)
10266 "Find a header field in the current buffer."
10267 (save-excursion
10268 (goto-char (point-min))
10269 (let ((case-fold-search t) s)
10270 (cond
10271 ((eq header 'from)
10272 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10273 (setq s (match-string 1)))
10274 (while (string-match "\"" s)
10275 (setq s (replace-match "" t t s)))
10276 (if (string-match "[<(].*" s)
10277 (setq s (replace-match "" t t s))))
10278 ((eq header 'message-id)
10279 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10280 (setq s (match-string 1))))
10281 ((eq header 'subject)
10282 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10283 (setq s (match-string 1)))))
10284 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10285 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10286 s)))
10289 (defun org-fixup-message-id-for-http (s)
10290 "Replace special characters in a message id, so it can be used in an http query."
10291 (while (string-match "<" s)
10292 (setq s (replace-match "%3C" t t s)))
10293 (while (string-match ">" s)
10294 (setq s (replace-match "%3E" t t s)))
10295 (while (string-match "@" s)
10296 (setq s (replace-match "%40" t t s)))
10299 (defun org-insert-link (&optional complete-file)
10300 "Insert a link. At the prompt, enter the link.
10302 Completion can be used to select a link previously stored with
10303 `org-store-link'. When the empty string is entered (i.e. if you just
10304 press RET at the prompt), the link defaults to the most recently
10305 stored link. As SPC triggers completion in the minibuffer, you need to
10306 use M-SPC or C-q SPC to force the insertion of a space character.
10308 You will also be prompted for a description, and if one is given, it will
10309 be displayed in the buffer instead of the link.
10311 If there is already a link at point, this command will allow you to edit link
10312 and description parts.
10314 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10315 selected using completion. The path to the file will be relative to
10316 the current directory if the file is in the current directory or a
10317 subdirectory. Otherwise, the link will be the absolute path as
10318 completed in the minibuffer (i.e. normally ~/path/to/file).
10320 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10321 is in the current directory or below.
10322 With three \\[universal-argument] prefixes, negate the meaning of
10323 `org-keep-stored-link-after-insertion'."
10324 (interactive "P")
10325 (let ((wcf (current-window-configuration))
10326 (region (if (org-region-active-p)
10327 (prog1 (buffer-substring (region-beginning) (region-end))
10328 (delete-region (region-beginning) (region-end)))))
10329 tmphist ; byte-compile incorrectly complains about this
10330 link desc entry remove file)
10331 (cond
10332 ((org-in-regexp org-bracket-link-regexp 1)
10333 ;; We do have a link at point, and we are going to edit it.
10334 (setq remove (list (match-beginning 0) (match-end 0)))
10335 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10336 (setq link (read-string "Link: "
10337 (org-link-unescape
10338 (org-match-string-no-properties 1)))))
10339 ((or (org-in-regexp org-angle-link-re)
10340 (org-in-regexp org-plain-link-re))
10341 ;; Convert to bracket link
10342 (setq remove (list (match-beginning 0) (match-end 0))
10343 link (read-string "Link: "
10344 (org-remove-angle-brackets (match-string 0)))))
10345 ((equal complete-file '(4))
10346 ;; Completing read for file names.
10347 (setq file (read-file-name "File: "))
10348 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10349 (pwd1 (file-name-as-directory (abbreviate-file-name
10350 (expand-file-name ".")))))
10351 (cond
10352 ((equal complete-file '(16))
10353 (setq link (org-make-link
10354 "file:"
10355 (abbreviate-file-name (expand-file-name file)))))
10356 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10357 (setq link (org-make-link "file:" (match-string 1 file))))
10358 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10359 (expand-file-name file))
10360 (setq link (org-make-link
10361 "file:" (match-string 1 (expand-file-name file)))))
10362 (t (setq link (org-make-link "file:" file))))))
10364 ;; Read link, with completion for stored links.
10365 (with-output-to-temp-buffer "*Org Links*"
10366 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
10367 (when org-stored-links
10368 (princ "\nStored links are available with <up>/<down> (most recent with RET):\n\n")
10369 (princ (mapconcat 'car (reverse org-stored-links) "\n"))))
10370 (let ((cw (selected-window)))
10371 (select-window (get-buffer-window "*Org Links*"))
10372 (shrink-window-if-larger-than-buffer)
10373 (setq truncate-lines t)
10374 (select-window cw))
10375 ;; Fake a link history, containing the stored links.
10376 (setq tmphist (append (mapcar 'car org-stored-links)
10377 org-insert-link-history))
10378 (unwind-protect
10379 (setq link (org-completing-read
10380 "Link: "
10381 (append
10382 (mapcar (lambda (x) (concat (car x) ":"))
10383 (append org-link-abbrev-alist-local org-link-abbrev-alist))
10384 (mapcar (lambda (x) (concat x ":")) org-link-types))
10385 nil nil nil
10386 'tmphist
10387 (or (car (car org-stored-links)))))
10388 (set-window-configuration wcf)
10389 (kill-buffer "*Org Links*"))
10390 (setq entry (assoc link org-stored-links))
10391 (or entry (push link org-insert-link-history))
10392 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10393 (not org-keep-stored-link-after-insertion))
10394 (setq org-stored-links (delq (assoc link org-stored-links)
10395 org-stored-links)))
10396 (setq link (if entry (nth 1 entry) link)
10397 desc (or region desc (nth 2 entry)))))
10399 (if (string-match org-plain-link-re link)
10400 ;; URL-like link, normalize the use of angular brackets.
10401 (setq link (org-make-link (org-remove-angle-brackets link))))
10403 ;; Check if we are linking to the current file with a search option
10404 ;; If yes, simplify the link by using only the search option.
10405 (when (and buffer-file-name
10406 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
10407 (let* ((path (match-string 1 link))
10408 (case-fold-search nil)
10409 (search (match-string 2 link)))
10410 (save-match-data
10411 (if (equal (file-truename buffer-file-name) (file-truename path))
10412 ;; We are linking to this same file, with a search option
10413 (setq link search)))))
10415 ;; Check if we can/should use a relative path. If yes, simplify the link
10416 (when (string-match "\\<file:\\(.*\\)" link)
10417 (let* ((path (match-string 1 link))
10418 (case-fold-search nil))
10419 (cond
10420 ((eq org-link-file-path-type 'absolute)
10421 (setq path (abbreviate-file-name (expand-file-name path))))
10422 ((eq org-link-file-path-type 'noabbrev)
10423 (setq path (expand-file-name path)))
10424 ((eq org-link-file-path-type 'relative)
10425 (setq path (file-relative-name path)))
10427 (save-match-data
10428 (if (string-match (concat "^" (regexp-quote
10429 (file-name-as-directory
10430 (expand-file-name "."))))
10431 (expand-file-name path))
10432 ;; We are linking a file with relative path name.
10433 (setq path (substring (expand-file-name path)
10434 (match-end 0)))))))
10435 (setq link (concat "file:" path))))
10437 (setq desc (read-string "Description: " desc))
10438 (unless (string-match "\\S-" desc) (setq desc nil))
10439 (if remove (apply 'delete-region remove))
10440 (insert (org-make-link-string link desc))))
10442 (defun org-completing-read (&rest args)
10443 (let ((minibuffer-local-completion-map
10444 (copy-keymap minibuffer-local-completion-map)))
10445 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10446 (apply 'completing-read args)))
10448 ;;; Opening/following a link
10449 (defvar org-link-search-failed nil)
10451 (defun org-next-link ()
10452 "Move forward to the next link.
10453 If the link is in hidden text, expose it."
10454 (interactive)
10455 (when (and org-link-search-failed (eq this-command last-command))
10456 (goto-char (point-min))
10457 (message "Link search wrapped back to beginning of buffer"))
10458 (setq org-link-search-failed nil)
10459 (let* ((pos (point))
10460 (ct (org-context))
10461 (a (assoc :link ct)))
10462 (if a (goto-char (nth 2 a)))
10463 (if (re-search-forward org-any-link-re nil t)
10464 (progn
10465 (goto-char (match-beginning 0))
10466 (if (org-invisible-p) (org-show-context)))
10467 (goto-char pos)
10468 (setq org-link-search-failed t)
10469 (error "No further link found"))))
10471 (defun org-previous-link ()
10472 "Move backward to the previous link.
10473 If the link is in hidden text, expose it."
10474 (interactive)
10475 (when (and org-link-search-failed (eq this-command last-command))
10476 (goto-char (point-max))
10477 (message "Link search wrapped back to end of buffer"))
10478 (setq org-link-search-failed nil)
10479 (let* ((pos (point))
10480 (ct (org-context))
10481 (a (assoc :link ct)))
10482 (if a (goto-char (nth 1 a)))
10483 (if (re-search-backward org-any-link-re nil t)
10484 (progn
10485 (goto-char (match-beginning 0))
10486 (if (org-invisible-p) (org-show-context)))
10487 (goto-char pos)
10488 (setq org-link-search-failed t)
10489 (error "No further link found"))))
10491 (defun org-find-file-at-mouse (ev)
10492 "Open file link or URL at mouse."
10493 (interactive "e")
10494 (mouse-set-point ev)
10495 (org-open-at-point 'in-emacs))
10497 (defun org-open-at-mouse (ev)
10498 "Open file link or URL at mouse."
10499 (interactive "e")
10500 (mouse-set-point ev)
10501 (org-open-at-point))
10503 (defvar org-window-config-before-follow-link nil
10504 "The window configuration before following a link.
10505 This is saved in case the need arises to restore it.")
10507 (defvar org-open-link-marker (make-marker)
10508 "Marker pointing to the location where `org-open-at-point; was called.")
10510 (defun org-open-at-point (&optional in-emacs)
10511 "Open link at or after point.
10512 If there is no link at point, this function will search forward up to
10513 the end of the current subtree.
10514 Normally, files will be opened by an appropriate application. If the
10515 optional argument IN-EMACS is non-nil, Emacs will visit the file."
10516 (interactive "P")
10517 (move-marker org-open-link-marker (point))
10518 (setq org-window-config-before-follow-link (current-window-configuration))
10519 (org-remove-occur-highlights nil nil t)
10520 (if (org-at-timestamp-p t)
10521 (org-follow-timestamp-link)
10522 (let (type path link line search (pos (point)))
10523 (catch 'match
10524 (save-excursion
10525 (skip-chars-forward "^]\n\r")
10526 (when (org-in-regexp org-bracket-link-regexp)
10527 (setq link (org-link-unescape (org-match-string-no-properties 1)))
10528 (while (string-match " *\n *" link)
10529 (setq link (replace-match " " t t link)))
10530 (setq link (org-link-expand-abbrev link))
10531 (if (string-match org-link-re-with-space2 link)
10532 (setq type (match-string 1 link) path (match-string 2 link))
10533 (setq type "thisfile" path link))
10534 (throw 'match t)))
10536 (when (get-text-property (point) 'org-linked-text)
10537 (setq type "thisfile"
10538 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10539 (1+ (point)) (point))
10540 path (buffer-substring
10541 (previous-single-property-change pos 'org-linked-text)
10542 (next-single-property-change pos 'org-linked-text)))
10543 (throw 'match t))
10545 (save-excursion
10546 (when (or (org-in-regexp org-angle-link-re)
10547 (org-in-regexp org-plain-link-re))
10548 (setq type (match-string 1) path (match-string 2))
10549 (throw 'match t)))
10550 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
10551 (setq type "tree-match"
10552 path (match-string 1))
10553 (throw 'match t))
10554 (save-excursion
10555 (when (org-in-regexp "\\(:[a-zA-Z0-9_@:]+\\):[ \t]*$")
10556 (setq type "tags"
10557 path (match-string 1))
10558 (while (string-match ":" path)
10559 (setq path (replace-match "+" t t path)))
10560 (throw 'match t))))
10561 (unless path
10562 (error "No link found"))
10563 ;; Remove any trailing spaces in path
10564 (if (string-match " +\\'" path)
10565 (setq path (replace-match "" t t path)))
10567 (cond
10569 ((equal type "mailto")
10570 (let ((cmd (car org-link-mailto-program))
10571 (args (cdr org-link-mailto-program)) args1
10572 (address path) (subject "") a)
10573 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10574 (setq address (match-string 1 path)
10575 subject (org-link-escape (match-string 2 path))))
10576 (while args
10577 (cond
10578 ((not (stringp (car args))) (push (pop args) args1))
10579 (t (setq a (pop args))
10580 (if (string-match "%a" a)
10581 (setq a (replace-match address t t a)))
10582 (if (string-match "%s" a)
10583 (setq a (replace-match subject t t a)))
10584 (push a args1))))
10585 (apply cmd (nreverse args1))))
10587 ((member type '("http" "https" "ftp" "news"))
10588 (browse-url (concat type ":" path)))
10590 ((string= type "tags")
10591 (org-tags-view in-emacs path))
10592 ((string= type "thisfile")
10593 (if in-emacs
10594 (switch-to-buffer-other-window
10595 (org-get-buffer-for-internal-link (current-buffer)))
10596 (org-mark-ring-push))
10597 (org-link-search
10598 path
10599 (cond ((equal in-emacs '(4)) 'occur)
10600 ((equal in-emacs '(16)) 'org-occur)
10601 (t nil))
10602 pos))
10604 ((string= type "tree-match")
10605 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10607 ((string= type "file")
10608 (if (string-match "::\\([0-9]+\\)\\'" path)
10609 (setq line (string-to-number (match-string 1 path))
10610 path (substring path 0 (match-beginning 0)))
10611 (if (string-match "::\\(.+\\)\\'" path)
10612 (setq search (match-string 1 path)
10613 path (substring path 0 (match-beginning 0)))))
10614 (org-open-file path in-emacs line search))
10616 ((string= type "news")
10617 (org-follow-gnus-link path))
10619 ((string= type "bbdb")
10620 (org-follow-bbdb-link path))
10622 ((string= type "info")
10623 (org-follow-info-link path))
10625 ((string= type "gnus")
10626 (let (group article)
10627 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10628 (error "Error in Gnus link"))
10629 (setq group (match-string 1 path)
10630 article (match-string 3 path))
10631 (org-follow-gnus-link group article)))
10633 ((string= type "vm")
10634 (let (folder article)
10635 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10636 (error "Error in VM link"))
10637 (setq folder (match-string 1 path)
10638 article (match-string 3 path))
10639 ;; in-emacs is the prefix arg, will be interpreted as read-only
10640 (org-follow-vm-link folder article in-emacs)))
10642 ((string= type "wl")
10643 (let (folder article)
10644 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10645 (error "Error in Wanderlust link"))
10646 (setq folder (match-string 1 path)
10647 article (match-string 3 path))
10648 (org-follow-wl-link folder article)))
10650 ((string= type "mhe")
10651 (let (folder article)
10652 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10653 (error "Error in MHE link"))
10654 (setq folder (match-string 1 path)
10655 article (match-string 3 path))
10656 (org-follow-mhe-link folder article)))
10658 ((string= type "rmail")
10659 (let (folder article)
10660 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10661 (error "Error in RMAIL link"))
10662 (setq folder (match-string 1 path)
10663 article (match-string 3 path))
10664 (org-follow-rmail-link folder article)))
10666 ((string= type "shell")
10667 (let ((cmd path))
10668 ;; FIXME: the following is only for backward compatibility
10669 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
10670 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
10671 (if (or (not org-confirm-shell-link-function)
10672 (funcall org-confirm-shell-link-function
10673 (format "Execute \"%s\" in shell? "
10674 (org-add-props cmd nil
10675 'face 'org-warning))))
10676 (progn
10677 (message "Executing %s" cmd)
10678 (shell-command cmd))
10679 (error "Abort"))))
10681 ((string= type "elisp")
10682 (let ((cmd path))
10683 (if (or (not org-confirm-elisp-link-function)
10684 (funcall org-confirm-elisp-link-function
10685 (format "Execute \"%s\" as elisp? "
10686 (org-add-props cmd nil
10687 'face 'org-warning))))
10688 (message "%s => %s" cmd (eval (read cmd)))
10689 (error "Abort"))))
10692 (browse-url-at-point)))))
10693 (move-marker org-open-link-marker nil))
10696 ;;; File search
10698 (defvar org-create-file-search-functions nil
10699 "List of functions to construct the right search string for a file link.
10700 These functions are called in turn with point at the location to
10701 which the link should point.
10703 A function in the hook should first test if it would like to
10704 handle this file type, for example by checking the major-mode or
10705 the file extension. If it decides not to handle this file, it
10706 should just return nil to give other functions a chance. If it
10707 does handle the file, it must return the search string to be used
10708 when following the link. The search string will be part of the
10709 file link, given after a double colon, and `org-open-at-point'
10710 will automatically search for it. If special measures must be
10711 taken to make the search successful, another function should be
10712 added to the companion hook `org-execute-file-search-functions',
10713 which see.
10715 A function in this hook may also use `setq' to set the variable
10716 `description' to provide a suggestion for the descriptive text to
10717 be used for this link when it gets inserted into an Org-mode
10718 buffer with \\[org-insert-link].")
10720 (defvar org-execute-file-search-functions nil
10721 "List of functions to execute a file search triggered by a link.
10723 Functions added to this hook must accept a single argument, the
10724 search string that was part of the file link, the part after the
10725 double colon. The function must first check if it would like to
10726 handle this search, for example by checking the major-mode or the
10727 file extension. If it decides not to handle this search, it
10728 should just return nil to give other functions a chance. If it
10729 does handle the search, it must return a non-nil value to keep
10730 other functions from trying.
10732 Each function can access the current prefix argument through the
10733 variable `current-prefix-argument'. Note that a single prefix is
10734 used to force opening a link in Emacs, so it may be good to only
10735 use a numeric or double prefix to guide the search function.
10737 In case this is needed, a function in this hook can also restore
10738 the window configuration before `org-open-at-point' was called using:
10740 (set-window-configuration org-window-config-before-follow-link)")
10742 (defun org-link-search (s &optional type avoid-pos)
10743 "Search for a link search option.
10744 If S is surrounded by forward slashes, it is interpreted as a
10745 regular expression. In org-mode files, this will create an `org-occur'
10746 sparse tree. In ordinary files, `occur' will be used to list matches.
10747 If the current buffer is in `dired-mode', grep will be used to search
10748 in all files. If AVOID-POS is given, ignore matches near that position."
10749 (let ((case-fold-search t)
10750 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10751 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10752 (append '((" ") ("\t") ("\n"))
10753 org-emphasis-alist)
10754 "\\|") "\\)"))
10755 (pos (point))
10756 (pre "") (post "")
10757 words re0 re1 re2 re3 re4 re5 re2a reall)
10758 (cond
10759 ;; First check if there are any special
10760 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10761 ;; Now try the builtin stuff
10762 ((save-excursion
10763 (goto-char (point-min))
10764 (and
10765 (re-search-forward
10766 (concat "<<" (regexp-quote s0) ">>") nil t)
10767 (setq pos (match-beginning 0))))
10768 ;; There is an exact target for this
10769 (goto-char pos))
10770 ((string-match "^/\\(.*\\)/$" s)
10771 ;; A regular expression
10772 (cond
10773 ((org-mode-p)
10774 (org-occur (match-string 1 s)))
10775 ;;((eq major-mode 'dired-mode)
10776 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10777 (t (org-do-occur (match-string 1 s)))))
10779 ;; A normal search string
10780 (when (equal (string-to-char s) ?*)
10781 ;; Anchor on headlines, post may include tags.
10782 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
10783 post "[ \t]*\\(?:[ \t]+:[a-zA-Z0-9_@:+]:[ \t]*\\)?$"
10784 s (substring s 1)))
10785 (remove-text-properties
10786 0 (length s)
10787 '(face nil mouse-face nil keymap nil fontified nil) s)
10788 ;; Make a series of regular expressions to find a match
10789 (setq words (org-split-string s "[ \n\r\t]+")
10790 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10791 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10792 "\\)" markers)
10793 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10794 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10795 re1 (concat pre re2 post)
10796 re3 (concat pre re4 post)
10797 re5 (concat pre ".*" re4)
10798 re2 (concat pre re2)
10799 re2a (concat pre re2a)
10800 re4 (concat pre re4)
10801 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10802 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10803 re5 "\\)"
10805 (cond
10806 ((eq type 'org-occur) (org-occur reall))
10807 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10808 (t (goto-char (point-min))
10809 (if (or (org-search-not-self 1 re0 nil t)
10810 (org-search-not-self 1 re1 nil t)
10811 (org-search-not-self 1 re2 nil t)
10812 (org-search-not-self 1 re2a nil t)
10813 (org-search-not-self 1 re3 nil t)
10814 (org-search-not-self 1 re4 nil t)
10815 (org-search-not-self 1 re5 nil t)
10817 (goto-char (match-beginning 1))
10818 (goto-char pos)
10819 (error "No match")))))
10821 ;; Normal string-search
10822 (goto-char (point-min))
10823 (if (search-forward s nil t)
10824 (goto-char (match-beginning 0))
10825 (error "No match"))))
10826 (and (org-mode-p) (org-show-context 'link-search))))
10828 (defun org-search-not-self (group &rest args)
10829 "Execute `re-search-forward', but only accept matches that do not
10830 enclose the position of `org-open-link-marker'."
10831 (let ((m org-open-link-marker))
10832 (catch 'exit
10833 (while (apply 're-search-forward args)
10834 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10835 (goto-char (match-end group))
10836 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10837 (> (match-beginning 0) (marker-position m))
10838 (< (match-end 0) (marker-position m)))
10839 (save-match-data
10840 (or (not (org-in-regexp
10841 org-bracket-link-analytic-regexp 1))
10842 (not (match-end 4)) ; no description
10843 (and (<= (match-beginning 4) (point))
10844 (>= (match-end 4) (point))))))
10845 (throw 'exit (point))))))))
10847 (defun org-get-buffer-for-internal-link (buffer)
10848 "Return a buffer to be used for displaying the link target of internal links."
10849 (cond
10850 ((not org-display-internal-link-with-indirect-buffer)
10851 buffer)
10852 ((string-match "(Clone)$" (buffer-name buffer))
10853 (message "Buffer is already a clone, not making another one")
10854 ;; we also do not modify visibility in this case
10855 buffer)
10856 (t ; make a new indirect buffer for displaying the link
10857 (let* ((bn (buffer-name buffer))
10858 (ibn (concat bn "(Clone)"))
10859 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10860 (with-current-buffer ib (org-overview))
10861 ib))))
10863 (defun org-do-occur (regexp &optional cleanup)
10864 "Call the Emacs command `occur'.
10865 If CLEANUP is non-nil, remove the printout of the regular expression
10866 in the *Occur* buffer. This is useful if the regex is long and not useful
10867 to read."
10868 (occur regexp)
10869 (when cleanup
10870 (let ((cwin (selected-window)) win beg end)
10871 (when (setq win (get-buffer-window "*Occur*"))
10872 (select-window win))
10873 (goto-char (point-min))
10874 (when (re-search-forward "match[a-z]+" nil t)
10875 (setq beg (match-end 0))
10876 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10877 (setq end (1- (match-beginning 0)))))
10878 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
10879 (goto-char (point-min))
10880 (select-window cwin))))
10882 ;;; The mark ring for links jumps
10884 (defvar org-mark-ring nil
10885 "Mark ring for positions before jumps in Org-mode.")
10886 (defvar org-mark-ring-last-goto nil
10887 "Last position in the mark ring used to go back.")
10888 ;; Fill and close the ring
10889 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10890 (loop for i from 1 to org-mark-ring-length do
10891 (push (make-marker) org-mark-ring))
10892 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10893 org-mark-ring)
10895 (defun org-mark-ring-push (&optional pos buffer)
10896 "Put the current position or POS into the mark ring and rotate it."
10897 (interactive)
10898 (setq pos (or pos (point)))
10899 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10900 (move-marker (car org-mark-ring)
10901 (or pos (point))
10902 (or buffer (current-buffer)))
10903 (message
10904 (substitute-command-keys
10905 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10907 (defun org-mark-ring-goto (&optional n)
10908 "Jump to the previous position in the mark ring.
10909 With prefix arg N, jump back that many stored positions. When
10910 called several times in succession, walk through the entire ring.
10911 Org-mode commands jumping to a different position in the current file,
10912 or to another Org-mode file, automatically push the old position
10913 onto the ring."
10914 (interactive "p")
10915 (let (p m)
10916 (if (eq last-command this-command)
10917 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10918 (setq p org-mark-ring))
10919 (setq org-mark-ring-last-goto p)
10920 (setq m (car p))
10921 (switch-to-buffer (marker-buffer m))
10922 (goto-char m)
10923 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10925 (defun org-remove-angle-brackets (s)
10926 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10927 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10929 (defun org-add-angle-brackets (s)
10930 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10931 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10934 ;;; Following specific links
10936 (defun org-follow-timestamp-link ()
10937 (cond
10938 ((org-at-date-range-p t)
10939 (let ((org-agenda-start-on-weekday)
10940 (t1 (match-string 1))
10941 (t2 (match-string 2)))
10942 (setq t1 (time-to-days (org-time-string-to-time t1))
10943 t2 (time-to-days (org-time-string-to-time t2)))
10944 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10945 ((org-at-timestamp-p t)
10946 (org-agenda-list nil (time-to-days (org-time-string-to-time
10947 (substring (match-string 1) 0 10)))
10949 (t (error "This should not happen"))))
10952 (defun org-follow-bbdb-link (name)
10953 "Follow a BBDB link to NAME."
10954 (require 'bbdb)
10955 (let ((inhibit-redisplay (not debug-on-error))
10956 (bbdb-electric-p nil))
10957 (catch 'exit
10958 ;; Exact match on name
10959 (bbdb-name (concat "\\`" name "\\'") nil)
10960 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10961 ;; Exact match on name
10962 (bbdb-company (concat "\\`" name "\\'") nil)
10963 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10964 ;; Partial match on name
10965 (bbdb-name name nil)
10966 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10967 ;; Partial match on company
10968 (bbdb-company name nil)
10969 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10970 ;; General match including network address and notes
10971 (bbdb name nil)
10972 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10973 (delete-window (get-buffer-window "*BBDB*"))
10974 (error "No matching BBDB record")))))
10976 (defun org-follow-info-link (name)
10977 "Follow an info file & node link to NAME."
10978 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10979 (string-match "\\(.*\\)" name))
10980 (progn
10981 (require 'info)
10982 (if (match-string 2 name) ; If there isn't a node, choose "Top"
10983 (Info-find-node (match-string 1 name) (match-string 2 name))
10984 (Info-find-node (match-string 1 name) "Top")))
10985 (message (concat "Could not open: " name))))
10987 (defun org-follow-gnus-link (&optional group article)
10988 "Follow a Gnus link to GROUP and ARTICLE."
10989 (require 'gnus)
10990 (funcall (cdr (assq 'gnus org-link-frame-setup)))
10991 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10992 (cond ((and group article)
10993 (gnus-group-read-group 1 nil group)
10994 (gnus-summary-goto-article (string-to-number article) nil t))
10995 (group (gnus-group-jump-to-group group))))
10997 (defun org-follow-vm-link (&optional folder article readonly)
10998 "Follow a VM link to FOLDER and ARTICLE."
10999 (require 'vm)
11000 (setq article (org-add-angle-brackets article))
11001 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
11002 ;; ange-ftp or efs or tramp access
11003 (let ((user (or (match-string 1 folder) (user-login-name)))
11004 (host (match-string 2 folder))
11005 (file (match-string 3 folder)))
11006 (cond
11007 ((featurep 'tramp)
11008 ;; use tramp to access the file
11009 (if (featurep 'xemacs)
11010 (setq folder (format "[%s@%s]%s" user host file))
11011 (setq folder (format "/%s@%s:%s" user host file))))
11013 ;; use ange-ftp or efs
11014 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
11015 (setq folder (format "/%s@%s:%s" user host file))))))
11016 (when folder
11017 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
11018 (sit-for 0.1)
11019 (when article
11020 (vm-select-folder-buffer)
11021 (widen)
11022 (let ((case-fold-search t))
11023 (goto-char (point-min))
11024 (if (not (re-search-forward
11025 (concat "^" "message-id: *" (regexp-quote article))))
11026 (error "Could not find the specified message in this folder"))
11027 (vm-isearch-update)
11028 (vm-isearch-narrow)
11029 (vm-beginning-of-message)
11030 (vm-summarize)))))
11032 (defun org-follow-wl-link (folder article)
11033 "Follow a Wanderlust link to FOLDER and ARTICLE."
11034 (if (and (string= folder "%")
11035 article
11036 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
11037 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
11038 ;; Thus, we recompose folder and article ids.
11039 (setq folder (format "%s#%s" folder (match-string 1 article))
11040 article (match-string 3 article)))
11041 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
11042 (error "No such folder: %s" folder))
11043 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
11044 (and article
11045 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
11046 (wl-summary-redisplay)))
11048 (defun org-follow-rmail-link (folder article)
11049 "Follow an RMAIL link to FOLDER and ARTICLE."
11050 (setq article (org-add-angle-brackets article))
11051 (let (message-number)
11052 (save-excursion
11053 (save-window-excursion
11054 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11055 (setq message-number
11056 (save-restriction
11057 (widen)
11058 (goto-char (point-max))
11059 (if (re-search-backward
11060 (concat "^Message-ID:\\s-+" (regexp-quote
11061 (or article "")))
11062 nil t)
11063 (rmail-what-message))))))
11064 (if message-number
11065 (progn
11066 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11067 (rmail-show-message message-number)
11068 message-number)
11069 (error "Message not found"))))
11071 ;;; mh-e integration based on planner-mode
11072 (defun org-mhe-get-message-real-folder ()
11073 "Return the name of the current message real folder, so if you use
11074 sequences, it will now work."
11075 (save-excursion
11076 (let* ((folder
11077 (if (equal major-mode 'mh-folder-mode)
11078 mh-current-folder
11079 ;; Refer to the show buffer
11080 mh-show-folder-buffer))
11081 (end-index
11082 (if (boundp 'mh-index-folder)
11083 (min (length mh-index-folder) (length folder))))
11085 ;; a simple test on mh-index-data does not work, because
11086 ;; mh-index-data is always nil in a show buffer.
11087 (if (and (boundp 'mh-index-folder)
11088 (string= mh-index-folder (substring folder 0 end-index)))
11089 (if (equal major-mode 'mh-show-mode)
11090 (save-window-excursion
11091 (when (buffer-live-p (get-buffer folder))
11092 (progn
11093 (pop-to-buffer folder)
11094 (org-mhe-get-message-folder-from-index)
11097 (org-mhe-get-message-folder-from-index)
11099 folder
11103 (defun org-mhe-get-message-folder-from-index ()
11104 "Returns the name of the message folder in a index folder buffer."
11105 (save-excursion
11106 (mh-index-previous-folder)
11107 (re-search-forward "^\\(+.*\\)$" nil t)
11108 (message (match-string 1))))
11110 (defun org-mhe-get-message-folder ()
11111 "Return the name of the current message folder. Be careful if you
11112 use sequences."
11113 (save-excursion
11114 (if (equal major-mode 'mh-folder-mode)
11115 mh-current-folder
11116 ;; Refer to the show buffer
11117 mh-show-folder-buffer)))
11119 (defun org-mhe-get-message-num ()
11120 "Return the number of the current message. Be careful if you
11121 use sequences."
11122 (save-excursion
11123 (if (equal major-mode 'mh-folder-mode)
11124 (mh-get-msg-num nil)
11125 ;; Refer to the show buffer
11126 (mh-show-buffer-message-number))))
11128 (defun org-mhe-get-header (header)
11129 "Return a header of the message in folder mode. This will create a
11130 show buffer for the corresponding message. If you have a more clever
11131 idea..."
11132 (let* ((folder (org-mhe-get-message-folder))
11133 (num (org-mhe-get-message-num))
11134 (buffer (get-buffer-create (concat "show-" folder)))
11135 (header-field))
11136 (with-current-buffer buffer
11137 (mh-display-msg num folder)
11138 (if (equal major-mode 'mh-folder-mode)
11139 (mh-header-display)
11140 (mh-show-header-display))
11141 (set-buffer buffer)
11142 (setq header-field (mh-get-header-field header))
11143 (if (equal major-mode 'mh-folder-mode)
11144 (mh-show)
11145 (mh-show-show))
11146 header-field)))
11148 (defun org-follow-mhe-link (folder article)
11149 "Follow an MHE link to FOLDER and ARTICLE.
11150 If ARTICLE is nil FOLDER is shown. If the configuration variable
11151 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
11152 ARTICLE is searched in all folders. Indexed searches (swish++,
11153 namazu, and others supported by MH-E) will always search in all
11154 folders."
11155 (require 'mh-e)
11156 (require 'mh-search)
11157 (require 'mh-utils)
11158 (mh-find-path)
11159 (if (not article)
11160 (mh-visit-folder (mh-normalize-folder-name folder))
11161 (setq article (org-add-angle-brackets article))
11162 (mh-search-choose)
11163 (if (equal mh-searcher 'pick)
11164 (progn
11165 (mh-search folder (list "--message-id" article))
11166 (when (and org-mhe-search-all-folders
11167 (not (org-mhe-get-message-real-folder)))
11168 (kill-this-buffer)
11169 (mh-search "+" (list "--message-id" article))))
11170 (mh-search "+" article))
11171 (if (org-mhe-get-message-real-folder)
11172 (mh-show-msg 1)
11173 (kill-this-buffer)
11174 (error "Message not found"))))
11176 ;;; BibTeX links
11178 ;; Use the custom search meachnism to construct and use search strings for
11179 ;; file links to BibTeX database entries.
11181 (defun org-create-file-search-in-bibtex ()
11182 "Create the search string and description for a BibTeX database entry."
11183 (when (eq major-mode 'bibtex-mode)
11184 ;; yes, we want to construct this search string.
11185 ;; Make a good description for this entry, using names, year and the title
11186 ;; Put it into the `description' variable which is dynamically scoped.
11187 (let ((bibtex-autokey-names 1)
11188 (bibtex-autokey-names-stretch 1)
11189 (bibtex-autokey-name-case-convert-function 'identity)
11190 (bibtex-autokey-name-separator " & ")
11191 (bibtex-autokey-additional-names " et al.")
11192 (bibtex-autokey-year-length 4)
11193 (bibtex-autokey-name-year-separator " ")
11194 (bibtex-autokey-titlewords 3)
11195 (bibtex-autokey-titleword-separator " ")
11196 (bibtex-autokey-titleword-case-convert-function 'identity)
11197 (bibtex-autokey-titleword-length 'infty)
11198 (bibtex-autokey-year-title-separator ": "))
11199 (setq description (bibtex-generate-autokey)))
11200 ;; Now parse the entry, get the key and return it.
11201 (save-excursion
11202 (bibtex-beginning-of-entry)
11203 (cdr (assoc "=key=" (bibtex-parse-entry))))))
11205 (defun org-execute-file-search-in-bibtex (s)
11206 "Find the link search string S as a key for a database entry."
11207 (when (eq major-mode 'bibtex-mode)
11208 ;; Yes, we want to do the search in this file.
11209 ;; We construct a regexp that searches for "@entrytype{" followed by the key
11210 (goto-char (point-min))
11211 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
11212 (regexp-quote s) "[ \t\n]*,") nil t)
11213 (goto-char (match-beginning 0)))
11214 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
11215 ;; Use double prefix to indicate that any web link should be browsed
11216 (let ((b (current-buffer)) (p (point)))
11217 ;; Restore the window configuration because we just use the web link
11218 (set-window-configuration org-window-config-before-follow-link)
11219 (save-excursion (set-buffer b) (goto-char p)
11220 (bibtex-url)))
11221 (recenter 0)) ; Move entry start to beginning of window
11222 ;; return t to indicate that the search is done.
11225 ;; Finally add the functions to the right hooks.
11226 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
11227 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
11229 ;; end of Bibtex link setup
11231 ;;; Following file links
11233 (defun org-open-file (path &optional in-emacs line search)
11234 "Open the file at PATH.
11235 First, this expands any special file name abbreviations. Then the
11236 configuration variable `org-file-apps' is checked if it contains an
11237 entry for this file type, and if yes, the corresponding command is launched.
11238 If no application is found, Emacs simply visits the file.
11239 With optional argument IN-EMACS, Emacs will visit the file.
11240 Optional LINE specifies a line to go to, optional SEARCH a string to
11241 search for. If LINE or SEARCH is given, the file will always be
11242 opened in Emacs.
11243 If the file does not exist, an error is thrown."
11244 (setq in-emacs (or in-emacs line search))
11245 (let* ((file (if (equal path "")
11246 buffer-file-name
11247 (substitute-in-file-name (expand-file-name path))))
11248 (apps (append org-file-apps (org-default-apps)))
11249 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11250 (dirp (if remp nil (file-directory-p file)))
11251 (dfile (downcase file))
11252 (old-buffer (current-buffer))
11253 (old-pos (point))
11254 (old-mode major-mode)
11255 ext cmd)
11256 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11257 (setq ext (match-string 1 dfile))
11258 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11259 (setq ext (match-string 1 dfile))))
11260 (if in-emacs
11261 (setq cmd 'emacs)
11262 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11263 (and dirp (cdr (assoc 'directory apps)))
11264 (cdr (assoc ext apps))
11265 (cdr (assoc t apps)))))
11266 (when (eq cmd 'mailcap)
11267 (require 'mailcap)
11268 (mailcap-parse-mailcaps)
11269 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11270 (command (mailcap-mime-info mime-type)))
11271 (if (stringp command)
11272 (setq cmd command)
11273 (setq cmd 'emacs))))
11274 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11275 (not (file-exists-p file))
11276 (not org-open-non-existing-files))
11277 (error "No such file: %s" file))
11278 (cond
11279 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11280 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11281 (if (string-match "['\"]%s['\"]" cmd)
11282 (setq cmd (replace-match "%s" t t cmd)))
11283 (setq cmd (format cmd (shell-quote-argument file)))
11284 (save-window-excursion
11285 (shell-command (concat cmd " &"))))
11286 ((or (stringp cmd)
11287 (eq cmd 'emacs))
11288 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11289 (if line (goto-line line)
11290 (if search (org-link-search search))))
11291 ((consp cmd)
11292 (eval cmd))
11293 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11294 (and (org-mode-p) (eq old-mode 'org-mode)
11295 (or (not (equal old-buffer (current-buffer)))
11296 (not (equal old-pos (point))))
11297 (org-mark-ring-push old-pos old-buffer))))
11299 (defun org-default-apps ()
11300 "Return the default applications for this operating system."
11301 (cond
11302 ((eq system-type 'darwin)
11303 org-file-apps-defaults-macosx)
11304 ((eq system-type 'windows-nt)
11305 org-file-apps-defaults-windowsnt)
11306 (t org-file-apps-defaults-gnu)))
11308 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11309 (defun org-file-remote-p (file)
11310 "Test whether FILE specifies a location on a remote system.
11311 Return non-nil if the location is indeed remote.
11313 For example, the filename \"/user@host:/foo\" specifies a location
11314 on the system \"/user@host:\"."
11315 (cond ((fboundp 'file-remote-p)
11316 (file-remote-p file))
11317 ((fboundp 'tramp-handle-file-remote-p)
11318 (tramp-handle-file-remote-p file))
11319 ((and (boundp 'ange-ftp-name-format)
11320 (string-match (car ange-ftp-name-format) file))
11322 (t nil)))
11325 ;;;; Hooks for remember.el
11327 ;;;###autoload
11328 (defun org-remember-annotation ()
11329 "Return a link to the current location as an annotation for remember.el.
11330 If you are using Org-mode files as target for data storage with
11331 remember.el, then the annotations should include a link compatible with the
11332 conventions in Org-mode. This function returns such a link."
11333 (org-store-link nil))
11335 (defconst org-remember-help
11336 "Select a destination location for the note.
11337 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
11338 RET at beg-of-buf -> Append to file as level 2 headline
11339 RET on headline -> Store as sublevel entry to current headline
11340 <left>/<right> -> before/after current headline, same headings level")
11342 ;;;###autoload
11343 (defun org-remember-apply-template (&optional use-char skip-interactive)
11344 "Initialize *remember* buffer with template, invoke `org-mode'.
11345 This function should be placed into `remember-mode-hook' and in fact requires
11346 to be run from that hook to fucntion properly."
11347 (if org-remember-templates
11349 (let* ((char (or use-char
11350 (if (= (length org-remember-templates) 1)
11351 (caar org-remember-templates)
11352 (message "Select template: %s"
11353 (mapconcat
11354 (lambda (x) (char-to-string (car x)))
11355 org-remember-templates " "))
11356 (read-char-exclusive))))
11357 (entry (cdr (assoc char org-remember-templates)))
11358 (tpl (car entry))
11359 (plist-p (if org-store-link-plist t nil))
11360 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
11361 (string-match "\\S-" (nth 1 entry)))
11362 (nth 1 entry)
11363 org-default-notes-file))
11364 (headline (nth 2 entry))
11365 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
11366 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
11367 (v-u (concat "[" (substring v-t 1 -1) "]"))
11368 (v-U (concat "[" (substring v-T 1 -1) "]"))
11369 (v-i initial) ; defined in `remember-mode'
11370 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
11371 (v-n user-full-name)
11372 (org-startup-folded nil)
11373 org-time-was-given org-end-time-was-given x prompt char time)
11374 (setq org-store-link-plist
11375 (append (list :annotation v-a :initial v-i)))
11376 (unless tpl (setq tpl "") (message "No template") (ding))
11377 (erase-buffer)
11378 (insert (substitute-command-keys
11379 (format
11380 "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
11381 ## Target file \"%s\", headline \"%s\"
11382 ## To switch templates, use `\\[org-remember]'.\n\n"
11383 (abbreviate-file-name (or file org-default-notes-file))
11384 (or headline ""))))
11385 (insert tpl) (goto-char (point-min))
11386 ;; Simple %-escapes
11387 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
11388 (when (and initial (equal (match-string 0) "%i"))
11389 (save-match-data
11390 (let* ((lead (buffer-substring
11391 (point-at-bol) (match-beginning 0))))
11392 (setq v-i (mapconcat 'identity
11393 (org-split-string initial "\n")
11394 (concat "\n" lead))))))
11395 (replace-match
11396 (or (eval (intern (concat "v-" (match-string 1)))) "")
11397 t t))
11398 ;; From the property list
11399 (when plist-p
11400 (goto-char (point-min))
11401 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
11402 (and (setq x (plist-get org-store-link-plist
11403 (intern (match-string 1))))
11404 (replace-match x t t))))
11405 ;; Turn on org-mode in the remember buffer, set local variables
11406 (org-mode)
11407 (org-set-local 'org-finish-function 'remember-buffer)
11408 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
11409 (org-set-local 'org-default-notes-file file))
11410 (if (and headline (stringp headline) (string-match "\\S-" headline))
11411 (org-set-local 'org-remember-default-headline headline))
11412 ;; Interactive template entries
11413 (goto-char (point-min))
11414 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([uUtT]\\)?" nil t)
11415 (setq char (if (match-end 3) (match-string 3))
11416 prompt (if (match-end 2) (match-string 2)))
11417 (goto-char (match-beginning 0))
11418 (replace-match "")
11419 (if char
11420 (progn
11421 (setq org-time-was-given (equal (upcase char) char))
11422 (setq time (org-read-date (equal (upcase char) "U") t nil
11423 prompt))
11424 (org-insert-time-stamp time org-time-was-given
11425 (member char '("u" "U"))
11426 nil nil (list org-end-time-was-given)))
11427 (insert (read-string
11428 (if prompt (concat prompt ": ") "Enter string")))))
11429 (goto-char (point-min))
11430 (if (re-search-forward "%\\?" nil t)
11431 (replace-match "")
11432 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
11433 (org-mode)
11434 (org-set-local 'org-finish-function 'remember-buffer)))
11436 ;;;###autoload
11437 (defun org-remember ()
11438 "Call `remember'. If this is already a remember buffer, re-apply template.
11439 If there is an active region, make sure remember uses it as initial content
11440 of the remember buffer."
11441 (interactive)
11442 (if (eq org-finish-function 'remember-buffer)
11443 (progn
11444 (when (< (length org-remember-templates) 2)
11445 (error "No other template available"))
11446 (erase-buffer)
11447 (let ((annotation (plist-get org-store-link-plist :annotation))
11448 (initial (plist-get org-store-link-plist :initial)))
11449 (org-remember-apply-template))
11450 (message "Press C-c C-c to remember data"))
11451 (if (org-region-active-p)
11452 (remember (buffer-substring (point) (mark)))
11453 (call-interactively 'remember))))
11455 ;;;###autoload
11456 (defun org-remember-handler ()
11457 "Store stuff from remember.el into an org file.
11458 First prompts for an org file. If the user just presses return, the value
11459 of `org-default-notes-file' is used.
11460 Then the command offers the headings tree of the selected file in order to
11461 file the text at a specific location.
11462 You can either immediately press RET to get the note appended to the
11463 file, or you can use vertical cursor motion and visibility cycling (TAB) to
11464 find a better place. Then press RET or <left> or <right> in insert the note.
11466 Key Cursor position Note gets inserted
11467 -----------------------------------------------------------------------------
11468 RET buffer-start as level 2 heading at end of file
11469 RET on headline as sublevel of the heading at cursor
11470 RET no heading at cursor position, level taken from context.
11471 Or use prefix arg to specify level manually.
11472 <left> on headline as same level, before current heading
11473 <right> on headline as same level, after current heading
11475 So the fastest way to store the note is to press RET RET to append it to
11476 the default file. This way your current train of thought is not
11477 interrupted, in accordance with the principles of remember.el. But with
11478 little extra effort, you can push it directly to the correct location.
11480 Before being stored away, the function ensures that the text has a
11481 headline, i.e. a first line that starts with a \"*\". If not, a headline
11482 is constructed from the current date and some additional data.
11484 If the variable `org-adapt-indentation' is non-nil, the entire text is
11485 also indented so that it starts in the same column as the headline
11486 \(i.e. after the stars).
11488 See also the variable `org-reverse-note-order'."
11489 (goto-char (point-min))
11490 (while (looking-at "^[ \t]*\n\\|^##.*\n")
11491 (replace-match ""))
11492 (catch 'quit
11493 (let* ((txt (buffer-substring (point-min) (point-max)))
11494 (fastp (equal current-prefix-arg '(4)))
11495 (file (if fastp org-default-notes-file (org-get-org-file)))
11496 (heading org-remember-default-headline)
11497 (visiting (org-find-base-buffer-visiting file))
11498 (org-startup-folded nil)
11499 (org-startup-align-all-tables nil)
11500 (org-goto-start-pos 1)
11501 spos level indent reversed)
11502 (setq current-prefix-arg nil)
11503 ;; Modify text so that it becomes a nice subtree which can be inserted
11504 ;; into an org tree.
11505 (let* ((lines (split-string txt "\n"))
11506 first)
11507 (setq first (car lines) lines (cdr lines))
11508 (if (string-match "^\\*+" first)
11509 ;; Is already a headline
11510 (setq indent nil)
11511 ;; We need to add a headline: Use time and first buffer line
11512 (setq lines (cons first lines)
11513 first (concat "* " (current-time-string)
11514 " (" (remember-buffer-desc) ")")
11515 indent " "))
11516 (if (and org-adapt-indentation indent)
11517 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
11518 (setq txt (concat first "\n"
11519 (mapconcat 'identity lines "\n"))))
11520 ;; Find the file
11521 (if (not visiting) (find-file-noselect file))
11522 (with-current-buffer (or visiting (get-file-buffer file))
11523 (save-excursion
11524 (save-restriction
11525 (widen)
11526 (and (goto-char (point-min))
11527 (not (re-search-forward "^\\* " nil t))
11528 (insert "\n* Notes\n"))
11529 (setq reversed (org-notes-order-reversed-p))
11531 ;; Find the default location
11532 (when (and heading (stringp heading) (string-match "\\S-" heading))
11533 (goto-char (point-min))
11534 (if (re-search-forward
11535 (concat "^\\*+[ \t]+" (regexp-quote heading)
11536 "\\([ \t]+:[a-zA-Z0-9@_:]*\\)?[ \t]*$")
11537 nil t)
11538 (setq org-goto-start-pos (match-beginning 0))))
11540 ;; Ask the User for a location
11541 (setq spos (if fastp
11542 org-goto-start-pos
11543 (org-get-location (current-buffer) org-remember-help)))
11544 (if (not spos) (throw 'quit nil)) ; return nil to show we did
11545 ; not handle this note
11546 (goto-char spos)
11547 (cond ((and (bobp) (not reversed))
11548 ;; Put it at the end, one level below level 1
11549 (save-restriction
11550 (widen)
11551 (goto-char (point-max))
11552 (if (not (bolp)) (newline))
11553 (org-paste-subtree (org-get-legal-level 1 1) txt)))
11554 ((and (bobp) reversed)
11555 ;; Put it at the start, as level 1
11556 (save-restriction
11557 (widen)
11558 (goto-char (point-min))
11559 (re-search-forward "^\\*" nil t)
11560 (beginning-of-line 1)
11561 (org-paste-subtree 1 txt)))
11562 ((and (org-on-heading-p t) (not current-prefix-arg))
11563 ;; Put it below this entry, at the beg/end of the subtree
11564 (org-back-to-heading t)
11565 (setq level (funcall outline-level))
11566 (if reversed
11567 (outline-next-heading)
11568 (org-end-of-subtree t))
11569 (if (not (bolp)) (newline))
11570 (beginning-of-line 1)
11571 (org-paste-subtree (org-get-legal-level level 1) txt))
11573 ;; Put it right there, with automatic level determined by
11574 ;; org-paste-subtree or from prefix arg
11575 (org-paste-subtree
11576 (if (numberp current-prefix-arg) current-prefix-arg)
11577 txt)))
11578 (when remember-save-after-remembering
11579 (save-buffer)
11580 (if (not visiting) (kill-buffer (current-buffer)))))))))
11581 t) ;; return t to indicate that we took care of this note.
11583 (defun org-get-org-file ()
11584 "Read a filename, with default directory `org-directory'."
11585 (let ((default (or org-default-notes-file remember-data-file)))
11586 (read-file-name (format "File name [%s]: " default)
11587 (file-name-as-directory org-directory)
11588 default)))
11590 (defun org-notes-order-reversed-p ()
11591 "Check if the current file should receive notes in reversed order."
11592 (cond
11593 ((not org-reverse-note-order) nil)
11594 ((eq t org-reverse-note-order) t)
11595 ((not (listp org-reverse-note-order)) nil)
11596 (t (catch 'exit
11597 (let ((all org-reverse-note-order)
11598 entry)
11599 (while (setq entry (pop all))
11600 (if (string-match (car entry) buffer-file-name)
11601 (throw 'exit (cdr entry))))
11602 nil)))))
11604 ;;;; Dynamic blocks
11606 (defun org-find-dblock (name)
11607 "Find the first dynamic block with name NAME in the buffer.
11608 If not found, stay at current position and return nil."
11609 (let (pos)
11610 (save-excursion
11611 (goto-char (point-min))
11612 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
11613 nil t)
11614 (match-beginning 0))))
11615 (if pos (goto-char pos))
11616 pos))
11618 (defconst org-dblock-start-re
11619 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11620 "Matches the startline of a dynamic block, with parameters.")
11622 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
11623 "Matches the end of a dyhamic block.")
11625 (defun org-create-dblock (plist)
11626 "Create a dynamic block section, with parameters taken from PLIST.
11627 PLIST must containe a :name entry which is used as name of the block."
11628 (unless (bolp) (newline))
11629 (let ((name (plist-get plist :name)))
11630 (insert "#+BEGIN: " name)
11631 (while plist
11632 (if (eq (car plist) :name)
11633 (setq plist (cddr plist))
11634 (insert " " (prin1-to-string (pop plist)))))
11635 (insert "\n\n#+END:\n")
11636 (beginning-of-line -2)))
11638 (defun org-prepare-dblock ()
11639 "Prepare dynamic block for refresh.
11640 This empties the block, puts the cursor at the insert position and returns
11641 the property list including an extra property :name with the block name."
11642 (unless (looking-at org-dblock-start-re)
11643 (error "Not at a dynamic block"))
11644 (let* ((begdel (1+ (match-end 0)))
11645 (name (match-string 1))
11646 (params (append (list :name name)
11647 (read (concat "(" (match-string 3) ")")))))
11648 (unless (re-search-forward org-dblock-end-re nil t)
11649 (error "Dynamic block not terminated"))
11650 (delete-region begdel (match-beginning 0))
11651 (goto-char begdel)
11652 (open-line 1)
11653 params))
11655 (defun org-map-dblocks (&optional command)
11656 "Apply COMMAND to all dynamic blocks in the current buffer.
11657 If COMMAND is not given, use `org-update-dblock'."
11658 (let ((cmd (or command 'org-update-dblock))
11659 pos)
11660 (save-excursion
11661 (goto-char (point-min))
11662 (while (re-search-forward org-dblock-start-re nil t)
11663 (goto-char (setq pos (match-beginning 0)))
11664 (condition-case nil
11665 (funcall cmd)
11666 (error (message "Error during update of dynamic block")))
11667 (goto-char pos)
11668 (unless (re-search-forward org-dblock-end-re nil t)
11669 (error "Dynamic block not terminated"))))))
11671 (defun org-dblock-update (&optional arg)
11672 "User command for updating dynamic blocks.
11673 Update the dynamic block at point. With prefix ARG, update all dynamic
11674 blocks in the buffer."
11675 (interactive "P")
11676 (if arg
11677 (org-update-all-dblocks)
11678 (or (looking-at org-dblock-start-re)
11679 (org-beginning-of-dblock))
11680 (org-update-dblock)))
11682 (defun org-update-dblock ()
11683 "Update the dynamic block at point
11684 This means to empty the block, parse for parameters and then call
11685 the correct writing function."
11686 (let* ((pos (point))
11687 (params (org-prepare-dblock))
11688 (name (plist-get params :name))
11689 (cmd (intern (concat "org-dblock-write:" name))))
11690 (funcall cmd params)
11691 (goto-char pos)))
11693 (defun org-beginning-of-dblock ()
11694 "Find the beginning of the dynamic block at point.
11695 Error if there is no scuh block at point."
11696 (let ((pos (point))
11697 beg)
11698 (end-of-line 1)
11699 (if (and (re-search-backward org-dblock-start-re nil t)
11700 (setq beg (match-beginning 0))
11701 (re-search-forward org-dblock-end-re nil t)
11702 (> (match-end 0) pos))
11703 (goto-char beg)
11704 (goto-char pos)
11705 (error "Not in a dynamic block"))))
11707 (defun org-update-all-dblocks ()
11708 "Update all dynamic blocks in the buffer.
11709 This function can be used in a hook."
11710 (when (org-mode-p)
11711 (org-map-dblocks 'org-update-dblock)))
11714 ;;;; Completion
11716 (defun org-complete (&optional arg)
11717 "Perform completion on word at point.
11718 At the beginning of a headline, this completes TODO keywords as given in
11719 `org-todo-keywords'.
11720 If the current word is preceded by a backslash, completes the TeX symbols
11721 that are supported for HTML support.
11722 If the current word is preceded by \"#+\", completes special words for
11723 setting file options.
11724 In the line after \"#+STARTUP:, complete valid keywords.\"
11725 At all other locations, this simply calls `ispell-complete-word'."
11726 (interactive "P")
11727 (catch 'exit
11728 (let* ((end (point))
11729 (beg1 (save-excursion
11730 (skip-chars-backward "a-zA-Z0-9_@")
11731 (point)))
11732 (beg (save-excursion
11733 (skip-chars-backward "a-zA-Z0-9_:$")
11734 (point)))
11735 (confirm (lambda (x) (stringp (car x))))
11736 (searchhead (equal (char-before beg) ?*))
11737 (tag (equal (char-before beg1) ?:))
11738 (texp (equal (char-before beg) ?\\))
11739 (link (equal (char-before beg) ?\[))
11740 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
11741 beg)
11742 "#+"))
11743 (startup (string-match "^#\\+STARTUP:.*"
11744 (buffer-substring (point-at-bol) (point))))
11745 (completion-ignore-case opt)
11746 (type nil)
11747 (tbl nil)
11748 (table (cond
11749 (opt
11750 (setq type :opt)
11751 (mapcar (lambda (x)
11752 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
11753 (cons (match-string 2 x) (match-string 1 x)))
11754 (org-split-string (org-get-current-options) "\n")))
11755 (startup
11756 (setq type :startup)
11757 org-startup-options)
11758 (link (append org-link-abbrev-alist-local
11759 org-link-abbrev-alist))
11760 (texp
11761 (setq type :tex)
11762 org-html-entities)
11763 ((string-match "\\`\\*+[ \t]*\\'"
11764 (buffer-substring (point-at-bol) beg))
11765 (setq type :todo)
11766 (mapcar 'list org-todo-keywords-1))
11767 (searchhead
11768 (setq type :searchhead)
11769 (save-excursion
11770 (goto-char (point-min))
11771 (while (re-search-forward org-todo-line-regexp nil t)
11772 (push (list
11773 (org-make-org-heading-search-string
11774 (match-string 3) t))
11775 tbl)))
11776 tbl)
11777 (tag (setq type :tag beg beg1)
11778 (or org-tag-alist (org-get-buffer-tags)))
11779 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
11780 (pattern (buffer-substring-no-properties beg end))
11781 (completion (try-completion pattern table confirm)))
11782 (cond ((eq completion t)
11783 (if (equal type :opt)
11784 (insert (substring (cdr (assoc (upcase pattern) table))
11785 (length pattern)))
11786 (if (equal type :tag) (insert ":"))))
11787 ((null completion)
11788 (message "Can't find completion for \"%s\"" pattern)
11789 (ding))
11790 ((not (string= pattern completion))
11791 (delete-region beg end)
11792 (if (string-match " +$" completion)
11793 (setq completion (replace-match "" t t completion)))
11794 (insert completion)
11795 (if (get-buffer-window "*Completions*")
11796 (delete-window (get-buffer-window "*Completions*")))
11797 (if (assoc completion table)
11798 (if (eq type :todo) (insert " ")
11799 (if (eq type :tag) (insert ":"))))
11800 (if (and (equal type :opt) (assoc completion table))
11801 (message "%s" (substitute-command-keys
11802 "Press \\[org-complete] again to insert example settings"))))
11804 (message "Making completion list...")
11805 (let ((list (sort (all-completions pattern table confirm)
11806 'string<)))
11807 (with-output-to-temp-buffer "*Completions*"
11808 (condition-case nil
11809 ;; Protection needed for XEmacs and emacs 21
11810 (display-completion-list list pattern)
11811 (error (display-completion-list list)))))
11812 (message "Making completion list...%s" "done"))))))
11814 ;;;; TODO, DEADLINE, Comments
11816 (defun org-toggle-comment ()
11817 "Change the COMMENT state of an entry."
11818 (interactive)
11819 (save-excursion
11820 (org-back-to-heading)
11821 (if (looking-at (concat outline-regexp
11822 "\\( +\\<" org-comment-string "\\>\\)"))
11823 (replace-match "" t t nil 1)
11824 (if (looking-at outline-regexp)
11825 (progn
11826 (goto-char (match-end 0))
11827 (insert " " org-comment-string))))))
11829 (defvar org-last-todo-state-is-todo nil
11830 "This is non-nil when the last TODO state change led to a TODO state.
11831 If the last change removed the TODO tag or switched to DONE, then
11832 this is nil.")
11834 (defun org-todo (&optional arg)
11835 "Change the TODO state of an item.
11836 The state of an item is given by a keyword at the start of the heading,
11837 like
11838 *** TODO Write paper
11839 *** DONE Call mom
11841 The different keywords are specified in the variable `org-todo-keywords'.
11842 By default the available states are \"TODO\" and \"DONE\".
11843 So for this example: when the item starts with TODO, it is changed to DONE.
11844 When it starts with DONE, the DONE is removed. And when neither TODO nor
11845 DONE are present, add TODO at the beginning of the heading.
11847 With C-u prefix arg, use completion to determine the new state.
11848 With numeric prefix arg, switch to that state.
11850 For calling through lisp, arg is also interpreted in the following way:
11851 'none -> empty state
11852 \"\"(empty string) -> switch to empty state
11853 'done -> switch to DONE
11854 'nextset -> switch to the next set of keywords
11855 'previousset -> switch to the previous set of keywords
11856 \"WAITING\" -> switch to the specified keyword, but only if it
11857 really is a member of `org-todo-keywords'."
11858 (interactive "P")
11859 (save-excursion
11860 (org-back-to-heading)
11861 (if (looking-at outline-regexp) (goto-char (match-end 0)))
11862 (or (looking-at (concat " +" org-todo-regexp " *"))
11863 (looking-at " *"))
11864 (let* ((this (match-string 1))
11865 (head (org-get-todo-sequence-head this))
11866 (ass (assoc head org-todo-kwd-alist))
11867 (interpret (nth 1 ass))
11868 (done-word (nth 3 ass))
11869 (final-done-word (nth 4 ass))
11870 (last-state (or this ""))
11871 (completion-ignore-case t)
11872 (member (member this org-todo-keywords-1))
11873 (tail (cdr member))
11874 (state (cond
11875 ((equal arg '(4))
11876 ;; Read a state with completion
11877 (completing-read "State: " (mapcar (lambda(x) (list x))
11878 org-todo-keywords-1)
11879 nil t))
11880 ((eq arg 'right)
11881 (if this
11882 (if tail (car tail) nil)
11883 (car org-todo-keywords-1)))
11884 ((eq arg 'left)
11885 (if (equal member org-todo-keywords-1)
11887 (if this
11888 (nth (- (length org-todo-keywords-1) (length tail) 2)
11889 org-todo-keywords-1)
11890 (org-last org-todo-keywords-1))))
11891 (arg
11892 ;; user or caller requests a specific state
11893 (cond
11894 ((equal arg "") nil)
11895 ((eq arg 'none) nil)
11896 ((eq arg 'done) (or done-word (car org-done-keywords)))
11897 ((eq arg 'nextset)
11898 (or (car (cdr (member head org-todo-heads)))
11899 (car org-todo-heads)))
11900 ((eq arg 'previousset)
11901 (let ((org-todo-heads (reverse org-todo-heads)))
11902 (or (car (cdr (member head org-todo-heads)))
11903 (car org-todo-heads))))
11904 ((car (member arg org-todo-keywords-1)))
11905 ((nth (1- (prefix-numeric-value arg))
11906 org-todo-keywords-1))))
11907 ((null member) (or head (car org-todo-keywords-1)))
11908 ((equal this final-done-word) nil) ;; -> make empty
11909 ((null tail) nil) ;; -> first entry
11910 ((eq interpret 'sequence)
11911 (car tail))
11912 ((memq interpret '(type priority))
11913 (if (eq this-command last-command)
11914 (car tail)
11915 (if (> (length tail) 0)
11916 (or done-word (car org-done-keywords))
11917 nil)))
11918 (t nil)))
11919 (next (if state (concat " " state " ") " "))
11920 dostates)
11921 (replace-match next t t)
11922 (unless head
11923 (setq head (org-get-todo-sequence-head state)
11924 ass (assoc head org-todo-kwd-alist)
11925 interpret (nth 1 ass)
11926 done-word (nth 3 ass)
11927 final-done-word (nth 4 ass)))
11928 (when (memq arg '(nextset previousset))
11929 (message "Keyword set: %s"
11930 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11931 (setq org-last-todo-state-is-todo
11932 (not (member state org-done-keywords)))
11933 (when (and org-log-done (not (memq arg '(nextset previousset))))
11934 (setq dostates (and (eq interpret 'sequence)
11935 (listp org-log-done) (memq 'state org-log-done)))
11936 (cond
11937 ((and state (not this))
11938 (org-add-planning-info nil nil 'closed)
11939 (and dostates (org-add-log-maybe 'state state 'findpos)))
11940 ((and state dostates)
11941 (org-add-log-maybe 'state state 'findpos))
11942 ((member state org-done-keywords)
11943 ;; Planning info calls the note-setting command.
11944 (org-add-planning-info 'closed (org-current-time)
11945 (if (org-get-repeat) nil 'scheduled))
11946 (org-add-log-maybe 'done state 'findpos))))
11947 ;; Fixup tag positioning
11948 (and org-auto-align-tags (org-set-tags nil t))
11949 (run-hooks 'org-after-todo-state-change-hook)
11950 (and (member state org-done-keywords) (org-auto-repeat-maybe))
11951 (if (and arg (not (member state org-done-keywords)))
11952 (setq head (org-get-todo-sequence-head state)))
11953 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
11954 ;; Fixup cursor location if close to the keyword
11955 (if (and (outline-on-heading-p)
11956 (not (bolp))
11957 (save-excursion (beginning-of-line 1)
11958 (looking-at org-todo-line-regexp))
11959 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11960 (progn
11961 (goto-char (or (match-end 2) (match-end 1)))
11962 (just-one-space))))
11964 (defun org-get-todo-sequence-head (kwd)
11965 "Return the head of the TODO sequence to which KWD belongs.
11966 If KWD is not set, check if there is a text property remembering the
11967 right sequence."
11968 (let (p)
11969 (cond
11970 ((not kwd)
11971 (or (get-text-property (point-at-bol) 'org-todo-head)
11972 (progn
11973 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11974 nil (point-at-eol)))
11975 (get-text-property p 'org-todo-head))))
11976 ((not (member kwd org-todo-keywords-1))
11977 (car org-todo-keywords-1))
11978 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11980 (defun org-get-repeat ()
11981 "Check if tere is a deadline/schedule with repeater in this entry."
11982 (save-match-data
11983 (save-excursion
11984 (org-back-to-heading t)
11985 (if (re-search-forward
11986 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
11987 (match-string 1)))))
11989 (defvar org-last-changed-timestamp)
11990 (defvar org-log-post-message)
11991 (defun org-auto-repeat-maybe ()
11992 "Check if the current headline contains a repeated deadline/schedule.
11993 If yes, set TODO state back to what it was and change the base date
11994 of repeating deadline/scheduled time stamps to new date.
11995 This function should be run in the `org-after-todo-state-change-hook'."
11996 ;; last-state is dynamically scoped into this function
11997 (let* ((repeat (org-get-repeat))
11998 (aa (assoc last-state org-todo-kwd-alist))
11999 (interpret (nth 1 aa))
12000 (head (nth 2 aa))
12001 (done-word (nth 3 aa))
12002 (whata '(("d" . day) ("m" . month) ("y" . year)))
12003 (msg "Entry repeats: ")
12004 (org-log-done)
12005 re type n what ts)
12006 (when repeat
12007 (org-todo (if (eq interpret 'type) last-state head))
12008 (when (and org-log-repeat
12009 (not (memq 'org-add-log-note
12010 (default-value 'post-command-hook))))
12011 ;; Make sure a note is taken
12012 (let ((org-log-done '(done)))
12013 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
12014 'findpos)))
12015 (org-back-to-heading t)
12016 (org-add-planning-info nil nil 'closed)
12017 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12018 org-deadline-time-regexp "\\)"))
12019 (while (re-search-forward
12020 re (save-excursion (outline-next-heading) (point)) t)
12021 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
12022 ts (match-string (if (match-end 2) 2 4)))
12023 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
12024 (setq n (string-to-number (match-string 1 ts))
12025 what (match-string 2 ts))
12026 (if (equal what "w") (setq n (* n 7) what "d"))
12027 (org-timestamp-change n (cdr (assoc what whata))))
12028 (setq msg (concat msg type org-last-changed-timestamp " ")))
12029 (setq org-log-post-message msg)
12030 (message msg))))
12032 (defun org-show-todo-tree (arg)
12033 "Make a compact tree which shows all headlines marked with TODO.
12034 The tree will show the lines where the regexp matches, and all higher
12035 headlines above the match.
12036 With \\[universal-argument] prefix, also show the DONE entries.
12037 With a numeric prefix N, construct a sparse tree for the Nth element
12038 of `org-todo-keywords-1'."
12039 (interactive "P")
12040 (let ((case-fold-search nil)
12041 (kwd-re
12042 (cond ((null arg) org-not-done-regexp)
12043 ((equal arg '(4))
12044 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
12045 (mapcar 'list org-todo-keywords-1))))
12046 (concat "\\("
12047 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12048 "\\)\\>")))
12049 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12050 (regexp-quote (nth (1- (prefix-numeric-value arg))
12051 org-todo-keywords-1)))
12052 (t (error "Invalid prefix argument: %s" arg)))))
12053 (message "%d TODO entries found"
12054 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
12056 (defun org-deadline ()
12057 "Insert the DEADLINE: string to make a deadline.
12058 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12059 to modify it to the correct date."
12060 (interactive)
12061 (org-add-planning-info 'deadline nil 'closed))
12063 (defun org-schedule ()
12064 "Insert the SCHEDULED: string to schedule a TODO item.
12065 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12066 to modify it to the correct date."
12067 (interactive)
12068 (org-add-planning-info 'scheduled nil 'closed))
12070 (defun org-add-planning-info (what &optional time &rest remove)
12071 "Insert new timestamp with keyword in the line directly after the headline.
12072 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
12073 If non is given, the user is prompted for a date.
12074 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12075 be removed."
12076 (interactive)
12077 (let (org-time-was-given org-end-time-was-given)
12078 (when what (setq time (or time (org-read-date nil 'to-time))))
12079 (when (and org-insert-labeled-timestamps-at-point
12080 (member what '(scheduled deadline)))
12081 (insert
12082 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12083 (org-insert-time-stamp time org-time-was-given
12084 nil nil nil (list org-end-time-was-given))
12085 (setq what nil))
12086 (save-excursion
12087 (save-restriction
12088 (let (col list elt ts buffer-invisibility-spec)
12089 (org-back-to-heading t)
12090 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
12091 (goto-char (match-end 1))
12092 (setq col (current-column))
12093 (goto-char (1+ (match-end 0)))
12094 (if (and (not (looking-at outline-regexp))
12095 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12096 "[^\r\n]*"))
12097 (not (equal (match-string 1) org-clock-string)))
12098 (narrow-to-region (match-beginning 0) (match-end 0))
12099 (insert "\n")
12100 (backward-char 1)
12101 (narrow-to-region (point) (point))
12102 (indent-to-column col))
12103 ;; Check if we have to remove something.
12104 (setq list (cons what remove))
12105 (while list
12106 (setq elt (pop list))
12107 (goto-char (point-min))
12108 (when (or (and (eq elt 'scheduled)
12109 (re-search-forward org-scheduled-time-regexp nil t))
12110 (and (eq elt 'deadline)
12111 (re-search-forward org-deadline-time-regexp nil t))
12112 (and (eq elt 'closed)
12113 (re-search-forward org-closed-time-regexp nil t)))
12114 (replace-match "")
12115 (if (looking-at "--+<[^>]+>") (replace-match ""))
12116 (if (looking-at " +") (replace-match ""))))
12117 (goto-char (point-max))
12118 (when what
12119 (insert
12120 (if (not (equal (char-before) ?\ )) " " "")
12121 (cond ((eq what 'scheduled) org-scheduled-string)
12122 ((eq what 'deadline) org-deadline-string)
12123 ((eq what 'closed) org-closed-string))
12124 " ")
12125 (org-insert-time-stamp
12126 time
12127 (or org-time-was-given
12128 (and (eq what 'closed) org-log-done-with-time))
12129 (eq what 'closed)
12130 nil nil (list org-end-time-was-given))
12131 (end-of-line 1))
12132 (goto-char (point-min))
12133 (widen)
12134 (if (looking-at "[ \t]+\r?\n")
12135 (replace-match ""))
12136 ts)))))
12138 (defvar org-log-note-marker (make-marker))
12139 (defvar org-log-note-purpose nil)
12140 (defvar org-log-note-state nil)
12141 (defvar org-log-note-window-configuration nil)
12142 (defvar org-log-note-return-to (make-marker))
12143 (defvar org-log-post-message nil
12144 "Message to be displayed after a log note has been stored.
12145 The auto-repeater uses this.")
12147 (defun org-add-log-maybe (&optional purpose state findpos)
12148 "Set up the post command hook to take a note."
12149 (save-excursion
12150 (when (and (listp org-log-done)
12151 (memq purpose org-log-done))
12152 (when findpos
12153 (org-back-to-heading t)
12154 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
12155 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12156 "[^\r\n]*\\)?"))
12157 (goto-char (match-end 0)))
12158 (move-marker org-log-note-marker (point))
12159 (setq org-log-note-purpose purpose)
12160 (setq org-log-note-state state)
12161 (add-hook 'post-command-hook 'org-add-log-note 'append))))
12163 (defun org-add-log-note (&optional purpose)
12164 "Pop up a window for taking a note, and add this note later at point."
12165 (remove-hook 'post-command-hook 'org-add-log-note)
12166 (setq org-log-note-window-configuration (current-window-configuration))
12167 (delete-other-windows)
12168 (move-marker org-log-note-return-to (point))
12169 (switch-to-buffer (marker-buffer org-log-note-marker))
12170 (goto-char org-log-note-marker)
12171 (switch-to-buffer-other-window "*Org Note*")
12172 (erase-buffer)
12173 (let ((org-inhibit-startup t)) (org-mode))
12174 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
12175 (cond
12176 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12177 ((eq org-log-note-purpose 'done) "closed todo item")
12178 ((eq org-log-note-purpose 'state) "state change")
12179 (t (error "This should not happen")))))
12180 (org-set-local 'org-finish-function 'org-store-log-note))
12182 (defun org-store-log-note ()
12183 "Finish taking a log note, and insert it to where it belongs."
12184 (let ((txt (buffer-string))
12185 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12186 lines ind)
12187 (kill-buffer (current-buffer))
12188 (if (string-match "^#.*\n[ \t\n]*" txt)
12189 (setq txt (replace-match "" t t txt)))
12190 (if (string-match "\\s-+\\'" txt)
12191 (setq txt (replace-match "" t t txt)))
12192 (setq lines (org-split-string txt "\n"))
12193 (when (and note (string-match "\\S-" note))
12194 (setq note
12195 (org-replace-escapes
12196 note
12197 (list (cons "%u" (user-login-name))
12198 (cons "%U" user-full-name)
12199 (cons "%t" (format-time-string
12200 (org-time-stamp-format 'long 'inactive)
12201 (current-time)))
12202 (cons "%s" (if org-log-note-state
12203 (concat "\"" org-log-note-state "\"")
12204 "")))))
12205 (if lines (setq note (concat note " \\\\")))
12206 (push note lines))
12207 (when lines
12208 (save-excursion
12209 (set-buffer (marker-buffer org-log-note-marker))
12210 (save-excursion
12211 (goto-char org-log-note-marker)
12212 (move-marker org-log-note-marker nil)
12213 (end-of-line 1)
12214 (if (not (bolp)) (insert "\n")) (indent-relative nil)
12215 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
12216 (insert " - " (pop lines))
12217 (while lines
12218 (insert "\n" ind (pop lines)))))))
12219 (set-window-configuration org-log-note-window-configuration)
12220 (with-current-buffer (marker-buffer org-log-note-return-to)
12221 (goto-char org-log-note-return-to))
12222 (move-marker org-log-note-return-to nil)
12223 (and org-log-post-message (message org-log-post-message)))
12225 (defvar org-occur-highlights nil)
12226 (make-variable-buffer-local 'org-occur-highlights)
12228 (defun org-occur (regexp &optional keep-previous callback)
12229 "Make a compact tree which shows all matches of REGEXP.
12230 The tree will show the lines where the regexp matches, and all higher
12231 headlines above the match. It will also show the heading after the match,
12232 to make sure editing the matching entry is easy.
12233 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12234 call to `org-occur' will be kept, to allow stacking of calls to this
12235 command.
12236 If CALLBACK is non-nil, it is a function which is called to confirm
12237 that the match should indeed be shown."
12238 (interactive "sRegexp: \nP")
12239 (or keep-previous (org-remove-occur-highlights nil nil t))
12240 (let ((cnt 0))
12241 (save-excursion
12242 (goto-char (point-min))
12243 (if (or (not keep-previous) ; do not want to keep
12244 (not org-occur-highlights)) ; no previous matches
12245 ;; hide everything
12246 (org-overview))
12247 (while (re-search-forward regexp nil t)
12248 (when (or (not callback)
12249 (save-match-data (funcall callback)))
12250 (setq cnt (1+ cnt))
12251 (when org-highlight-sparse-tree-matches
12252 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12253 (org-show-context 'occur-tree))))
12254 (when org-remove-highlights-with-change
12255 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12256 nil 'local))
12257 (unless org-sparse-tree-open-archived-trees
12258 (org-hide-archived-subtrees (point-min) (point-max)))
12259 (run-hooks 'org-occur-hook)
12260 (if (interactive-p)
12261 (message "%d match(es) for regexp %s" cnt regexp))
12262 cnt))
12264 (defun org-show-context (&optional key)
12265 "Make sure point and context and visible.
12266 How much context is shown depends upon the variables
12267 `org-show-hierarchy-above', `org-show-following-heading'. and
12268 `org-show-siblings'."
12269 (let ((heading-p (org-on-heading-p t))
12270 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12271 (following-p (org-get-alist-option org-show-following-heading key))
12272 (siblings-p (org-get-alist-option org-show-siblings key)))
12273 (catch 'exit
12274 ;; Show heading or entry text
12275 (if heading-p
12276 (org-flag-heading nil) ; only show the heading
12277 (and (or (org-invisible-p) (org-invisible-p2))
12278 (org-show-hidden-entry))) ; show entire entry
12279 (when following-p
12280 ;; Show next sibling, or heading below text
12281 (save-excursion
12282 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12283 (org-flag-heading nil))))
12284 (when siblings-p (org-show-siblings))
12285 (when hierarchy-p
12286 ;; show all higher headings, possibly with siblings
12287 (save-excursion
12288 (while (and (condition-case nil
12289 (progn (org-up-heading-all 1) t)
12290 (error nil))
12291 (not (bobp)))
12292 (org-flag-heading nil)
12293 (when siblings-p (org-show-siblings))))))))
12295 (defun org-reveal (&optional siblings)
12296 "Show current entry, hierarchy above it, and the following headline.
12297 This can be used to show a consistent set of context around locations
12298 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12299 not t for the search context.
12301 With optional argument SIBLINGS, on each level of the hierarchy all
12302 siblings are shown. This repairs the tree structure to what it would
12303 look like when opened with hierarchical calls to `org-cycle'."
12304 (interactive "P")
12305 (let ((org-show-hierarchy-above t)
12306 (org-show-following-heading t)
12307 (org-show-siblings (if siblings t org-show-siblings)))
12308 (org-show-context nil)))
12310 (defun org-highlight-new-match (beg end)
12311 "Highlight from BEG to END and mark the highlight is an occur headline."
12312 (let ((ov (org-make-overlay beg end)))
12313 (org-overlay-put ov 'face 'secondary-selection)
12314 (push ov org-occur-highlights)))
12316 (defun org-remove-occur-highlights (&optional beg end noremove)
12317 "Remove the occur highlights from the buffer.
12318 BEG and END are ignored. If NOREMOVE is nil, remove this function
12319 from the `before-change-functions' in the current buffer."
12320 (interactive)
12321 (unless org-inhibit-highlight-removal
12322 (mapc 'org-delete-overlay org-occur-highlights)
12323 (setq org-occur-highlights nil)
12324 (unless noremove
12325 (remove-hook 'before-change-functions
12326 'org-remove-occur-highlights 'local))))
12328 ;;;; Priorities
12330 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12331 "Regular expression matching the priority indicator.")
12333 (defvar org-remove-priority-next-time nil)
12335 (defun org-priority-up ()
12336 "Increase the priority of the current item."
12337 (interactive)
12338 (org-priority 'up))
12340 (defun org-priority-down ()
12341 "Decrease the priority of the current item."
12342 (interactive)
12343 (org-priority 'down))
12345 (defun org-priority (&optional action)
12346 "Change the priority of an item by ARG.
12347 ACTION can be set, up, or down."
12348 (interactive)
12349 (setq action (or action 'set))
12350 (let (current new news have remove)
12351 (save-excursion
12352 (org-back-to-heading)
12353 (if (looking-at org-priority-regexp)
12354 (setq current (string-to-char (match-string 2))
12355 have t)
12356 (setq current org-default-priority))
12357 (cond
12358 ((eq action 'set)
12359 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
12360 (setq new (read-char-exclusive))
12361 (cond ((equal new ?\ ) (setq remove t))
12362 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12363 (error "Priority must be between `%c' and `%c'"
12364 org-highest-priority org-lowest-priority))))
12365 ((eq action 'up)
12366 (setq new (1- current)))
12367 ((eq action 'down)
12368 (setq new (1+ current)))
12369 (t (error "Invalid action")))
12370 (setq new (min (max org-highest-priority (upcase new)) org-lowest-priority))
12371 (setq news (format "%c" new))
12372 (if have
12373 (if remove
12374 (replace-match "" t t nil 1)
12375 (replace-match news t t nil 2))
12376 (if remove
12377 (error "No priority cookie found in line")
12378 (looking-at org-todo-line-regexp)
12379 (if (match-end 2)
12380 (progn
12381 (goto-char (match-end 2))
12382 (insert " [#" news "]"))
12383 (goto-char (match-beginning 3))
12384 (insert "[#" news "] ")))))
12385 (if remove
12386 (message "Priority removed")
12387 (message "Priority of current item set to %s" news))))
12390 (defun org-get-priority (s)
12391 "Find priority cookie and return priority."
12392 (save-match-data
12393 (if (not (string-match org-priority-regexp s))
12394 (* 1000 (- org-lowest-priority org-default-priority))
12395 (* 1000 (- org-lowest-priority
12396 (string-to-char (match-string 2 s)))))))
12398 ;;;; Tags
12400 (defun org-scan-tags (action matcher &optional todo-only)
12401 "Scan headline tags with inheritance and produce output ACTION.
12402 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
12403 evaluated, testing if a given set of tags qualifies a headline for
12404 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
12405 are included in the output."
12406 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
12407 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12408 "\\>\\)\\)? *\\(.*?\\)\\(:[a-zA-Z0-9_@:]+:\\)?[ \t]*$"))
12409 (props (list 'face nil
12410 'done-face 'org-done
12411 'undone-face nil
12412 'mouse-face 'highlight
12413 'org-not-done-regexp org-not-done-regexp
12414 'org-todo-regexp org-todo-regexp
12415 'keymap org-agenda-keymap
12416 'help-echo
12417 (format "mouse-2 or RET jump to org file %s"
12418 (abbreviate-file-name buffer-file-name))))
12419 (case-fold-search nil)
12420 lspos
12421 tags tags-list tags-alist (llast 0) rtn level category i txt
12422 todo marker entry priority)
12423 (save-excursion
12424 (goto-char (point-min))
12425 (when (eq action 'sparse-tree) (org-overview))
12426 (while (re-search-forward re nil t)
12427 (catch :skip
12428 (setq todo (if (match-end 1) (match-string 2))
12429 tags (if (match-end 4) (match-string 4)))
12430 (goto-char (setq lspos (1+ (match-beginning 0))))
12431 (setq level (funcall outline-level)
12432 category (org-get-category))
12433 (setq i llast llast level)
12434 ;; remove tag lists from same and sublevels
12435 (while (>= i level)
12436 (when (setq entry (assoc i tags-alist))
12437 (setq tags-alist (delete entry tags-alist)))
12438 (setq i (1- i)))
12439 ;; add the nex tags
12440 (when tags
12441 (setq tags (mapcar 'downcase (org-split-string tags ":"))
12442 tags-alist
12443 (cons (cons level tags) tags-alist)))
12444 ;; compile tags for current headline
12445 (setq tags-list
12446 (if org-use-tag-inheritance
12447 (apply 'append (mapcar 'cdr tags-alist))
12448 tags))
12449 (when (and (or (not todo-only) (member todo org-not-done-keywords))
12450 (eval matcher)
12451 (or (not org-agenda-skip-archived-trees)
12452 (not (member org-archive-tag tags-list))))
12453 (and (eq action 'agenda) (org-agenda-skip))
12454 ;; list this headline
12455 (if (eq action 'sparse-tree)
12456 (progn
12457 (org-show-context 'tags-tree))
12458 (setq txt (org-format-agenda-item
12460 (concat
12461 (if org-tags-match-list-sublevels
12462 (make-string (1- level) ?.) "")
12463 (org-get-heading))
12464 category tags-list)
12465 priority (org-get-priority txt))
12466 (goto-char lspos)
12467 (setq marker (org-agenda-new-marker))
12468 (org-add-props txt props
12469 'org-marker marker 'org-hd-marker marker 'org-category category
12470 'priority priority 'type "tagsmatch")
12471 (push txt rtn))
12472 ;; if we are to skip sublevels, jump to end of subtree
12473 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
12474 (when (and (eq action 'sparse-tree)
12475 (not org-sparse-tree-open-archived-trees))
12476 (org-hide-archived-subtrees (point-min) (point-max)))
12477 (nreverse rtn)))
12479 (defvar todo-only) ;; dynamically scoped
12481 (defun org-tags-sparse-tree (&optional todo-only match)
12482 "Create a sparse tree according to tags string MATCH.
12483 MATCH can contain positive and negative selection of tags, like
12484 \"+WORK+URGENT-WITHBOSS\".
12485 If optional argument TODO_ONLY is non-nil, only select lines that are
12486 also TODO lines."
12487 (interactive "P")
12488 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12490 (defun org-make-tags-matcher (match)
12491 "Create the TAGS//TODO matcher form for the selection string MATCH."
12492 ;; todo-only is scoped dynamically into this function, and the function
12493 ;; may change it it the matcher asksk for it.
12494 (unless match
12495 ;; Get a new match request, with completion
12496 (setq org-last-tags-completion-table
12497 (or org-tag-alist
12498 org-last-tags-completion-table))
12499 (setq match (completing-read
12500 "Match: " 'org-tags-completion-function nil nil nil
12501 'org-tags-history)))
12503 ;; Parse the string and create a lisp form
12504 (let ((match0 match)
12505 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[a-zA-Z0-9_@]+\\)")
12506 minus tag mm
12507 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12508 orterms term orlist re-p level-p)
12509 (if (string-match "/+" match)
12510 ;; match contains also a todo-matching request
12511 (progn
12512 (setq tagsmatch (substring match 0 (match-beginning 0))
12513 todomatch (substring match (match-end 0)))
12514 (if (string-match "^!" todomatch)
12515 (setq todo-only t todomatch (substring todomatch 1)))
12516 (if (string-match "^\\s-*$" todomatch)
12517 (setq todomatch nil)))
12518 ;; only matching tags
12519 (setq tagsmatch match todomatch nil))
12521 ;; Make the tags matcher
12522 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12523 (setq tagsmatcher t)
12524 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12525 (while (setq term (pop orterms))
12526 (while (and (equal (substring term -1) "\\") orterms)
12527 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12528 (while (string-match re term)
12529 (setq minus (and (match-end 1)
12530 (equal (match-string 1 term) "-"))
12531 tag (match-string 2 term)
12532 re-p (equal (string-to-char tag) ?{)
12533 level-p (match-end 3)
12534 mm (cond
12535 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12536 (level-p `(= level ,(string-to-number
12537 (match-string 3 term))))
12538 (t `(member ,(downcase tag) tags-list)))
12539 mm (if minus (list 'not mm) mm)
12540 term (substring term (match-end 0)))
12541 (push mm tagsmatcher))
12542 (push (if (> (length tagsmatcher) 1)
12543 (cons 'and tagsmatcher)
12544 (car tagsmatcher))
12545 orlist)
12546 (setq tagsmatcher nil))
12547 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
12549 ;; Make the todo matcher
12550 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12551 (setq todomatcher t)
12552 (setq orterms (org-split-string todomatch "|") orlist nil)
12553 (while (setq term (pop orterms))
12554 (while (string-match re term)
12555 (setq minus (and (match-end 1)
12556 (equal (match-string 1 term) "-"))
12557 kwd (match-string 2 term)
12558 re-p (equal (string-to-char kwd) ?{)
12559 term (substring term (match-end 0))
12560 mm (if re-p
12561 `(string-match ,(substring kwd 1 -1) todo)
12562 (list 'equal 'todo kwd))
12563 mm (if minus (list 'not mm) mm))
12564 (push mm todomatcher))
12565 (push (if (> (length todomatcher) 1)
12566 (cons 'and todomatcher)
12567 (car todomatcher))
12568 orlist)
12569 (setq todomatcher nil))
12570 (setq todomatcher (if (> (length orlist) 1)
12571 (cons 'or orlist) (car orlist))))
12573 ;; Return the string and lisp forms of the matcher
12574 (setq matcher (if todomatcher
12575 (list 'and tagsmatcher todomatcher)
12576 tagsmatcher))
12577 (cons match0 matcher)))
12579 (defun org-match-any-p (re list)
12580 "Does re match any element of list?"
12581 (setq list (mapcar (lambda (x) (string-match re x)) list))
12582 (delq nil list))
12584 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
12585 (defvar org-tags-overlay (org-make-overlay 1 1))
12586 (org-detach-overlay org-tags-overlay)
12588 (defun org-set-tags (&optional arg just-align)
12589 "Set the tags for the current headline.
12590 With prefix ARG, realign all tags in headings in the current buffer."
12591 (interactive "P")
12592 (let* ((re (concat "^" outline-regexp))
12593 (current (org-get-tags))
12594 table current-tags inherited-tags ; computed below when needed
12595 tags p0 c0 c1 rpl)
12596 (if arg
12597 (save-excursion
12598 (goto-char (point-min))
12599 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12600 (while (re-search-forward re nil t)
12601 (org-set-tags nil t)
12602 (end-of-line 1)))
12603 (message "All tags realigned to column %d" org-tags-column))
12604 (if just-align
12605 (setq tags current)
12606 ;; Get a new set of tags from the user
12607 (save-excursion
12608 (setq table (or org-tag-alist (org-get-buffer-tags))
12609 org-last-tags-completion-table table
12610 current-tags (org-split-string current ":")
12611 inherited-tags (nreverse
12612 (nthcdr (length current-tags)
12613 (nreverse (org-get-tags-at))))
12614 tags
12615 (if (or (eq t org-use-fast-tag-selection)
12616 (and org-use-fast-tag-selection
12617 (delq nil (mapcar 'cdr table))))
12618 (org-fast-tag-selection current-tags inherited-tags table)
12619 (let ((org-add-colon-after-tag-completion t))
12620 (org-trim
12621 (completing-read "Tags: " 'org-tags-completion-function
12622 nil nil current 'org-tags-history))))))
12623 (while (string-match "[-+&]+" tags)
12624 ;; No boolean logic, just a list
12625 (setq tags (replace-match ":" t t tags))))
12627 (if (string-match "\\`[\t ]*\\'" tags)
12628 (setq tags "")
12629 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12630 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12632 ;; Insert new tags at the correct column
12633 (beginning-of-line 1)
12634 (if (re-search-forward
12635 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12636 (point-at-eol) t)
12637 (progn
12638 (if (equal tags "")
12639 (setq rpl "")
12640 (goto-char (match-beginning 0))
12641 (setq c0 (current-column) p0 (point)
12642 c1 (max (1+ c0) (if (> org-tags-column 0)
12643 org-tags-column
12644 (- (- org-tags-column) (length tags))))
12645 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12646 (replace-match rpl t t)
12647 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
12648 tags)
12649 (error "Tags alignment failed")))))
12651 (defun org-tags-completion-function (string predicate &optional flag)
12652 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12653 (confirm (lambda (x) (stringp (car x)))))
12654 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12655 (setq s1 (match-string 1 string)
12656 s2 (match-string 2 string))
12657 (setq s1 "" s2 string))
12658 (cond
12659 ((eq flag nil)
12660 ;; try completion
12661 (setq rtn (try-completion s2 ctable confirm))
12662 (if (stringp rtn)
12663 (concat s1 s2 (substring rtn (length s2))
12664 (if (and org-add-colon-after-tag-completion
12665 (assoc rtn ctable))
12666 ":" "")))
12668 ((eq flag t)
12669 ;; all-completions
12670 (all-completions s2 ctable confirm)
12672 ((eq flag 'lambda)
12673 ;; exact match?
12674 (assoc s2 ctable)))
12677 (defun org-fast-tag-insert (kwd tags face &optional end)
12678 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
12679 (insert (format "%-12s" (concat kwd ":"))
12680 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12681 (or end "")))
12683 (defun org-fast-tag-show-exit (flag)
12684 (save-excursion
12685 (goto-line 3)
12686 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12687 (replace-match ""))
12688 (when flag
12689 (end-of-line 1)
12690 (move-to-column (- (window-width) 19) t)
12691 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12693 (defun org-set-current-tags-overlay (current prefix)
12694 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12695 (if (featurep 'xemacs)
12696 (org-overlay-display org-tags-overlay (concat prefix s)
12697 'secondary-selection)
12698 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12699 (org-overlay-display org-tags-overlay (concat prefix s)))))
12701 (defun org-fast-tag-selection (current inherited table)
12702 "Fast tag selection with single keys.
12703 CURRENT is the current list of tags in the headline, INHERITED is the
12704 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12705 possibly with grouping information.
12706 If the keys are nil, a-z are automatically assigned.
12707 Returns the new tags string, or nil to not change the current settings."
12708 (let* ((maxlen (apply 'max (mapcar
12709 (lambda (x)
12710 (if (stringp (car x)) (string-width (car x)) 0))
12711 table)))
12712 (buf (current-buffer))
12713 (expert (eq org-fast-tag-selection-single-key 'expert))
12714 (buffer-tags nil)
12715 (fwidth (+ maxlen 3 1 3))
12716 (ncol (/ (- (window-width) 4) fwidth))
12717 (i-face 'org-done)
12718 (c-face 'org-todo)
12719 tg cnt e c char c1 c2 ntable tbl rtn
12720 ov-start ov-end ov-prefix
12721 (exit-after-next org-fast-tag-selection-single-key)
12722 groups ingroup)
12723 (save-excursion
12724 (beginning-of-line 1)
12725 (if (looking-at ".*[ \t]\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*\\(\r\\|$\\)")
12726 (setq ov-start (match-beginning 1)
12727 ov-end (match-end 1)
12728 ov-prefix "")
12729 (setq ov-start (1- (point-at-eol))
12730 ov-end (1+ ov-start))
12731 (skip-chars-forward "^\n\r")
12732 (setq ov-prefix
12733 (concat
12734 (buffer-substring (1- (point)) (point))
12735 (if (> (current-column) org-tags-column)
12737 (make-string (- org-tags-column (current-column)) ?\ ))))))
12738 (org-move-overlay org-tags-overlay ov-start ov-end)
12739 (save-window-excursion
12740 (if expert
12741 (set-buffer (get-buffer-create " *Org tags*"))
12742 (delete-other-windows)
12743 (split-window-vertically)
12744 (switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12745 (erase-buffer)
12746 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12747 (org-fast-tag-insert "Current" current c-face "\n\n")
12748 (org-fast-tag-show-exit exit-after-next)
12749 (org-set-current-tags-overlay current ov-prefix)
12750 (setq tbl table char ?a cnt 0)
12751 (while (setq e (pop tbl))
12752 (cond
12753 ((equal e '(:startgroup))
12754 (push '() groups) (setq ingroup t)
12755 (when (not (= cnt 0))
12756 (setq cnt 0)
12757 (insert "\n"))
12758 (insert "{ "))
12759 ((equal e '(:endgroup))
12760 (setq ingroup nil cnt 0)
12761 (insert "}\n"))
12763 (setq tg (car e) c2 nil)
12764 (if (cdr e)
12765 (setq c (cdr e))
12766 ;; automatically assign a character.
12767 (setq c1 (string-to-char
12768 (downcase (substring
12769 tg (if (= (string-to-char tg) ?@) 1 0)))))
12770 (if (or (rassoc c1 ntable) (rassoc c1 table))
12771 (while (or (rassoc char ntable) (rassoc char table))
12772 (setq char (1+ char)))
12773 (setq c2 c1))
12774 (setq c (or c2 char)))
12775 (if ingroup (push tg (car groups)))
12776 (setq tg (org-add-props tg nil 'face
12777 (cond
12778 ((member tg current) c-face)
12779 ((member tg inherited) i-face)
12780 (t nil))))
12781 (if (and (= cnt 0) (not ingroup)) (insert " "))
12782 (insert "[" c "] " tg (make-string
12783 (- fwidth 4 (length tg)) ?\ ))
12784 (push (cons tg c) ntable)
12785 (when (= (setq cnt (1+ cnt)) ncol)
12786 (insert "\n")
12787 (if ingroup (insert " "))
12788 (setq cnt 0)))))
12789 (setq ntable (nreverse ntable))
12790 (insert "\n")
12791 (goto-char (point-min))
12792 (if (and (not expert) (fboundp 'fit-window-to-buffer))
12793 (fit-window-to-buffer))
12794 (setq rtn
12795 (catch 'exit
12796 (while t
12797 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
12798 (if groups " [!] no groups" " [!]groups")
12799 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12800 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12801 (cond
12802 ((= c ?\r) (throw 'exit t))
12803 ((= c ?!)
12804 (setq groups (not groups))
12805 (goto-char (point-min))
12806 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12807 ((= c ?\C-c)
12808 (if (not expert)
12809 (org-fast-tag-show-exit
12810 (setq exit-after-next (not exit-after-next)))
12811 (setq expert nil)
12812 (delete-other-windows)
12813 (split-window-vertically)
12814 (switch-to-buffer-other-window " *Org tags*")
12815 (and (fboundp 'fit-window-to-buffer)
12816 (fit-window-to-buffer))))
12817 ((or (= c ?\C-g)
12818 (and (= c ?q) (not (rassoc c ntable))))
12819 (org-detach-overlay org-tags-overlay)
12820 (setq quit-flag t))
12821 ((= c ?\ )
12822 (setq current nil)
12823 (if exit-after-next (setq exit-after-next 'now)))
12824 ((= c ?\t)
12825 (condition-case nil
12826 (setq tg (completing-read
12827 "Tag: "
12828 (or buffer-tags
12829 (with-current-buffer buf
12830 (org-get-buffer-tags)))))
12831 (quit (setq tg "")))
12832 (when (string-match "\\S-" tg)
12833 (add-to-list 'buffer-tags (list tg))
12834 (if (member tg current)
12835 (setq current (delete tg current))
12836 (push tg current)))
12837 (if exit-after-next (setq exit-after-next 'now)))
12838 ((setq e (rassoc c ntable) tg (car e))
12839 (if (member tg current)
12840 (setq current (delete tg current))
12841 (loop for g in groups do
12842 (if (member tg g)
12843 (mapcar (lambda (x)
12844 (setq current (delete x current)))
12845 g)))
12846 (push tg current))
12847 (if exit-after-next (setq exit-after-next 'now))))
12849 ;; Create a sorted list
12850 (setq current
12851 (sort current
12852 (lambda (a b)
12853 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12854 (if (eq exit-after-next 'now) (throw 'exit t))
12855 (goto-char (point-min))
12856 (beginning-of-line 2)
12857 (delete-region (point) (point-at-eol))
12858 (org-fast-tag-insert "Current" current c-face)
12859 (org-set-current-tags-overlay current ov-prefix)
12860 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
12861 (setq tg (match-string 1))
12862 (add-text-properties (match-beginning 1) (match-end 1)
12863 (list 'face
12864 (cond
12865 ((member tg current) c-face)
12866 ((member tg inherited) i-face)
12867 (t nil)))))
12868 (goto-char (point-min)))))
12869 (org-detach-overlay org-tags-overlay)
12870 (if rtn
12871 (mapconcat 'identity current ":")
12872 nil))))
12874 (defun org-get-tags ()
12875 "Get the TAGS string in the current headline."
12876 (unless (org-on-heading-p t)
12877 (error "Not on a heading"))
12878 (save-excursion
12879 (beginning-of-line 1)
12880 (if (looking-at ".*[ \t]\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*\\(\r\\|$\\)")
12881 (org-match-string-no-properties 1)
12882 "")))
12884 (defun org-get-buffer-tags ()
12885 "Get a table of all tags used in the buffer, for completion."
12886 (let (tags)
12887 (save-excursion
12888 (goto-char (point-min))
12889 (while (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t\r\n]" nil t)
12890 (mapc (lambda (x) (add-to-list 'tags x))
12891 (org-split-string (org-match-string-no-properties 1) ":"))))
12892 (mapcar 'list tags)))
12894 ;;;; Timestamps
12896 (defvar org-last-changed-timestamp nil)
12897 (defvar org-time-was-given) ; dynamically scoped parameter
12898 (defvar org-end-time-was-given) ; dynamically scoped parameter
12899 (defvar org-ts-what) ; dynamically scoped parameter
12901 (defun org-time-stamp (arg)
12902 "Prompt for a date/time and insert a time stamp.
12903 If the user specifies a time like HH:MM, or if this command is called
12904 with a prefix argument, the time stamp will contain date and time.
12905 Otherwise, only the date will be included. All parts of a date not
12906 specified by the user will be filled in from the current date/time.
12907 So if you press just return without typing anything, the time stamp
12908 will represent the current date/time. If there is already a timestamp
12909 at the cursor, it will be modified."
12910 (interactive "P")
12911 (let (org-time-was-given org-end-time-was-given time)
12912 (cond
12913 ((and (org-at-timestamp-p)
12914 (eq last-command 'org-time-stamp)
12915 (eq this-command 'org-time-stamp))
12916 (insert "--")
12917 (setq time (let ((this-command this-command))
12918 (org-read-date arg 'totime)))
12919 (org-insert-time-stamp time (or org-time-was-given arg)))
12920 ((org-at-timestamp-p)
12921 (setq time (let ((this-command this-command))
12922 (org-read-date arg 'totime)))
12923 (when (org-at-timestamp-p) ; just to get the match data
12924 (replace-match "")
12925 (setq org-last-changed-timestamp
12926 (org-insert-time-stamp
12927 time (or org-time-was-given arg)
12928 nil nil nil (list org-end-time-was-given))))
12929 (message "Timestamp updated"))
12931 (setq time (let ((this-command this-command))
12932 (org-read-date arg 'totime)))
12933 (org-insert-time-stamp time (or org-time-was-given arg)
12934 nil nil nil (list org-end-time-was-given))))))
12936 (defun org-time-stamp-inactive (&optional arg)
12937 "Insert an inactive time stamp.
12938 An inactive time stamp is enclosed in square brackets instead of angle
12939 brackets. It is inactive in the sense that it does not trigger agenda entries,
12940 does not link to the calendar and cannot be changed with the S-cursor keys.
12941 So these are more for recording a certain time/date."
12942 (interactive "P")
12943 (let (org-time-was-given org-end-time-was-given time)
12944 (setq time (org-read-date arg 'totime))
12945 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
12946 nil nil (list org-end-time-was-given))))
12948 (defvar org-date-ovl (org-make-overlay 1 1))
12949 (org-overlay-put org-date-ovl 'face 'org-warning)
12950 (org-detach-overlay org-date-ovl)
12952 (defvar org-ans1) ; dynamically scoped parameter
12953 (defvar org-ans2) ; dynamically scoped parameter
12955 (defvar org-plain-time-of-day-regexp) ; defined below
12956 (defun org-read-date (&optional with-time to-time from-string prompt)
12957 "Read a date and make things smooth for the user.
12958 The prompt will suggest to enter an ISO date, but you can also enter anything
12959 which will at least partially be understood by `parse-time-string'.
12960 Unrecognized parts of the date will default to the current day, month, year,
12961 hour and minute. For example,
12962 3-2-5 --> 2003-02-05
12963 feb 15 --> currentyear-02-15
12964 sep 12 9 --> 2009-09-12
12965 12:45 --> today 12:45
12966 22 sept 0:34 --> currentyear-09-22 0:34
12967 12 --> currentyear-currentmonth-12
12968 Fri --> nearest Friday (today or later)
12969 +4 --> four days from today (only if +N is the only thing given)
12970 etc.
12971 The function understands only English month and weekday abbreviations,
12972 but this can be configured with the variables `parse-time-months' and
12973 `parse-time-weekdays'.
12975 While prompting, a calendar is popped up - you can also select the
12976 date with the mouse (button 1). The calendar shows a period of three
12977 months. To scroll it to other months, use the keys `>' and `<'.
12978 If you don't like the calendar, turn it off with
12979 \(setq org-popup-calendar-for-date-prompt nil)
12981 With optional argument TO-TIME, the date will immediately be converted
12982 to an internal time.
12983 With an optional argument WITH-TIME, the prompt will suggest to also
12984 insert a time. Note that when WITH-TIME is not set, you can still
12985 enter a time, and this function will inform the calling routine about
12986 this change. The calling routine may then choose to change the format
12987 used to insert the time stamp into the buffer to include the time."
12988 (require 'parse-time)
12989 (let* ((org-time-stamp-rounding-minutes
12990 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
12991 (ct (org-current-time))
12992 (default-time
12993 ;; Default time is either today, or, when entering a range,
12994 ;; the range start.
12995 (if (save-excursion
12996 (re-search-backward
12997 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12998 (- (point) 20) t))
12999 (apply
13000 'encode-time
13001 (mapcar (lambda(x) (or x 0))
13002 (parse-time-string (match-string 1))))
13003 ct))
13004 (calendar-move-hook nil)
13005 (view-diary-entries-initially nil)
13006 (view-calendar-holidays-initially nil)
13007 (timestr (format-time-string
13008 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
13009 (prompt (concat (if prompt (concat prompt " ") "")
13010 (format "Date and/or time (default [%s]): " timestr)))
13011 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
13012 second minute hour day month year tl wday wday1 pm)
13014 (cond
13015 (from-string (setq ans from-string))
13016 (org-popup-calendar-for-date-prompt
13017 (save-excursion
13018 (save-window-excursion
13019 (calendar)
13020 (calendar-forward-day (- (time-to-days default-time)
13021 (calendar-absolute-from-gregorian
13022 (calendar-current-date))))
13023 (org-eval-in-calendar nil t)
13024 (let* ((old-map (current-local-map))
13025 (map (copy-keymap calendar-mode-map))
13026 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13027 (org-defkey map (kbd "RET") 'org-calendar-select)
13028 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13029 'org-calendar-select-mouse)
13030 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13031 'org-calendar-select-mouse)
13032 (org-defkey minibuffer-local-map [(meta shift left)]
13033 (lambda () (interactive)
13034 (org-eval-in-calendar '(calendar-backward-month 1))))
13035 (org-defkey minibuffer-local-map [(meta shift right)]
13036 (lambda () (interactive)
13037 (org-eval-in-calendar '(calendar-forward-month 1))))
13038 (org-defkey minibuffer-local-map [(shift up)]
13039 (lambda () (interactive)
13040 (org-eval-in-calendar '(calendar-backward-week 1))))
13041 (org-defkey minibuffer-local-map [(shift down)]
13042 (lambda () (interactive)
13043 (org-eval-in-calendar '(calendar-forward-week 1))))
13044 (org-defkey minibuffer-local-map [(shift left)]
13045 (lambda () (interactive)
13046 (org-eval-in-calendar '(calendar-backward-day 1))))
13047 (org-defkey minibuffer-local-map [(shift right)]
13048 (lambda () (interactive)
13049 (org-eval-in-calendar '(calendar-forward-day 1))))
13050 (org-defkey minibuffer-local-map ">"
13051 (lambda () (interactive)
13052 (org-eval-in-calendar '(scroll-calendar-left 1))))
13053 (org-defkey minibuffer-local-map "<"
13054 (lambda () (interactive)
13055 (org-eval-in-calendar '(scroll-calendar-right 1))))
13056 (unwind-protect
13057 (progn
13058 (use-local-map map)
13059 (setq org-ans0 (read-string prompt "" nil nil))
13060 ;; org-ans0: from prompt
13061 ;; org-ans1: from mouse click
13062 ;; org-ans2: from calendar motion
13063 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13064 (use-local-map old-map))))))
13065 (t ; Naked prompt only
13066 (setq ans (read-string prompt "" nil timestr))))
13067 (org-detach-overlay org-date-ovl)
13069 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
13070 (setq deltadays (string-to-number ans) ans ""))
13072 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
13073 (when (string-match
13074 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13075 (setq year (if (match-end 2)
13076 (string-to-number (match-string 2 ans))
13077 (string-to-number (format-time-string "%Y")))
13078 month (string-to-number (match-string 3 ans))
13079 day (string-to-number (match-string 4 ans)))
13080 (if (< year 100) (setq year (+ 2000 year)))
13081 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13082 t nil ans)))
13083 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13084 ;; If there is a time with am/pm, and *no* time without it, we convert
13085 ;; so that matching will be successful.
13086 ;; FIXME: make this replace twoce, so that we catch the end time.
13087 (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13088 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13089 (setq hour (string-to-number (match-string 1 ans))
13090 minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
13091 pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
13092 (if (and (= hour 12) (not pm))
13093 (setq hour 0)
13094 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13095 (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
13097 ;; Check if there is a time range
13098 (when (and (boundp 'org-end-time-was-given)
13099 (string-match org-plain-time-of-day-regexp ans)
13100 (match-end 8))
13101 (setq org-end-time-was-given (match-string 8 ans))
13102 (setq ans (concat (substring ans 0 (match-beginning 7))
13103 (substring ans (match-end 7)))))
13105 (setq tl (parse-time-string ans)
13106 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
13107 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
13108 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
13109 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
13110 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
13111 second (or (nth 0 tl) 0)
13112 wday (nth 6 tl))
13113 (setq day (+ day deltadays))
13114 (when (and wday (not (nth 3 tl)))
13115 ;; Weekday was given, but no day, so pick that day in the week
13116 ;; on or after the derived date.
13117 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13118 (unless (equal wday wday1)
13119 (setq day (+ day (% (- wday wday1 -7) 7)))))
13120 (if (and (boundp 'org-time-was-given)
13121 (nth 2 tl))
13122 (setq org-time-was-given t))
13123 (if (< year 100) (setq year (+ 2000 year)))
13124 (if to-time
13125 (encode-time second minute hour day month year)
13126 (if (or (nth 1 tl) (nth 2 tl))
13127 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
13128 (format "%04d-%02d-%02d" year month day)))))
13130 (defun org-eval-in-calendar (form &optional keepdate)
13131 "Eval FORM in the calendar window and return to current window.
13132 Also, store the cursor date in variable org-ans2."
13133 (let ((sw (selected-window)))
13134 (select-window (get-buffer-window "*Calendar*"))
13135 (eval form)
13136 (when (and (not keepdate) (calendar-cursor-to-date))
13137 (let* ((date (calendar-cursor-to-date))
13138 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13139 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13140 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13141 (select-window sw)
13142 ;; Update the prompt to show new default date
13143 (save-excursion
13144 (goto-char (point-min))
13145 (when (and org-ans2
13146 (re-search-forward "\\[[-0-9]+\\]" nil t)
13147 (get-text-property (match-end 0) 'field))
13148 (let ((inhibit-read-only t))
13149 (replace-match (concat "[" org-ans2 "]") t t)
13150 (add-text-properties (point-min) (1+ (match-end 0))
13151 (text-properties-at (1+ (point-min)))))))))
13153 (defun org-calendar-select ()
13154 "Return to `org-read-date' with the date currently selected.
13155 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13156 (interactive)
13157 (when (calendar-cursor-to-date)
13158 (let* ((date (calendar-cursor-to-date))
13159 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13160 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13161 (if (active-minibuffer-window) (exit-minibuffer))))
13163 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13164 "Insert a date stamp for the date given by the internal TIME.
13165 WITH-HM means, use the stamp format that includes the time of the day.
13166 INACTIVE means use square brackets instead of angular ones, so that the
13167 stamp will not contribute to the agenda.
13168 PRE and POST are optional strings to be inserted before and after the
13169 stamp.
13170 The command returns the inserted time stamp."
13171 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13172 stamp)
13173 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13174 (insert (or pre ""))
13175 (insert (setq stamp (format-time-string fmt time)))
13176 (when (listp extra)
13177 (setq extra (car extra))
13178 (if (and (stringp extra)
13179 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13180 (setq extra (format "-%02d:%02d"
13181 (string-to-number (match-string 1 extra))
13182 (string-to-number (match-string 2 extra))))
13183 (setq extra nil)))
13184 (when extra
13185 (backward-char 1)
13186 (insert extra)
13187 (forward-char 1))
13188 (insert (or post ""))
13189 stamp))
13191 (defun org-toggle-time-stamp-overlays ()
13192 "Toggle the use of custom time stamp formats."
13193 (interactive)
13194 (setq org-display-custom-times (not org-display-custom-times))
13195 (unless org-display-custom-times
13196 (let ((p (point-min)) (bmp (buffer-modified-p)))
13197 (while (setq p (next-single-property-change p 'display))
13198 (if (and (get-text-property p 'display)
13199 (eq (get-text-property p 'face) 'org-date))
13200 (remove-text-properties
13201 p (setq p (next-single-property-change p 'display))
13202 '(display t))))
13203 (set-buffer-modified-p bmp)))
13204 (if (featurep 'xemacs)
13205 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13206 (org-restart-font-lock)
13207 (setq org-table-may-need-update t)
13208 (if org-display-custom-times
13209 (message "Time stamps are overlayed with custom format")
13210 (message "Time stamp overlays removed")))
13212 (defun org-display-custom-time (beg end)
13213 "Overlay modified time stamp format over timestamp between BED and END."
13214 (let* ((ts (buffer-substring beg end))
13215 t1 w1 with-hm tf time str w2 (off 0))
13216 (save-match-data
13217 (setq t1 (org-parse-time-string ts t))
13218 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
13219 (setq off (- (match-end 0) (match-beginning 0)))))
13220 (setq end (- end off))
13221 (setq w1 (- end beg)
13222 with-hm (and (nth 1 t1) (nth 2 t1))
13223 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13224 time (org-fix-decoded-time t1)
13225 str (org-add-props
13226 (format-time-string
13227 (substring tf 1 -1) (apply 'encode-time time))
13228 nil 'mouse-face 'highlight)
13229 w2 (length str))
13230 (if (not (= w2 w1))
13231 (add-text-properties (1+ beg) (+ 2 beg)
13232 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13233 (if (featurep 'xemacs)
13234 (progn
13235 (put-text-property beg end 'invisible t)
13236 (put-text-property beg end 'end-glyph (make-glyph str)))
13237 (put-text-property beg end 'display str))))
13239 (defun org-translate-time (string)
13240 "Translate all timestamps in STRING to custom format.
13241 But do this only if the variable `org-display-custom-times' is set."
13242 (when org-display-custom-times
13243 (save-match-data
13244 (let* ((start 0)
13245 (re org-ts-regexp-both)
13246 t1 with-hm inactive tf time str beg end)
13247 (while (setq start (string-match re string start))
13248 (setq beg (match-beginning 0)
13249 end (match-end 0)
13250 t1 (save-match-data
13251 (org-parse-time-string (substring string beg end) t))
13252 with-hm (and (nth 1 t1) (nth 2 t1))
13253 inactive (equal (substring string beg (1+ beg)) "[")
13254 tf (funcall (if with-hm 'cdr 'car)
13255 org-time-stamp-custom-formats)
13256 time (org-fix-decoded-time t1)
13257 str (format-time-string
13258 (concat
13259 (if inactive "[" "<") (substring tf 1 -1)
13260 (if inactive "]" ">"))
13261 (apply 'encode-time time))
13262 string (replace-match str t t string)
13263 start (+ start (length str)))))))
13264 string)
13266 (defun org-fix-decoded-time (time)
13267 "Set 0 instead of nil for the first 6 elements of time.
13268 Don't touch the rest."
13269 (let ((n 0))
13270 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13272 (defun org-days-to-time (timestamp-string)
13273 "Difference between TIMESTAMP-STRING and now in days."
13274 (- (time-to-days (org-time-string-to-time timestamp-string))
13275 (time-to-days (current-time))))
13277 (defun org-deadline-close (timestamp-string &optional ndays)
13278 "Is the time in TIMESTAMP-STRING close to the current date?"
13279 (and (< (org-days-to-time timestamp-string)
13280 (or ndays org-deadline-warning-days))
13281 (not (org-entry-is-done-p))))
13283 (defun org-calendar-select-mouse (ev)
13284 "Return to `org-read-date' with the date currently selected.
13285 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13286 (interactive "e")
13287 (mouse-set-point ev)
13288 (when (calendar-cursor-to-date)
13289 (let* ((date (calendar-cursor-to-date))
13290 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13291 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13292 (if (active-minibuffer-window) (exit-minibuffer))))
13294 (defun org-check-deadlines (ndays)
13295 "Check if there are any deadlines due or past due.
13296 A deadline is considered due if it happens within `org-deadline-warning-days'
13297 days from today's date. If the deadline appears in an entry marked DONE,
13298 it is not shown. The prefix arg NDAYS can be used to test that many
13299 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13300 (interactive "P")
13301 (let* ((org-warn-days
13302 (cond
13303 ((equal ndays '(4)) 100000)
13304 (ndays (prefix-numeric-value ndays))
13305 (t org-deadline-warning-days)))
13306 (case-fold-search nil)
13307 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13308 (callback
13309 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13311 (message "%d deadlines past-due or due within %d days"
13312 (org-occur regexp nil callback)
13313 org-warn-days)))
13315 (defun org-evaluate-time-range (&optional to-buffer)
13316 "Evaluate a time range by computing the difference between start and end.
13317 Normally the result is just printed in the echo area, but with prefix arg
13318 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13319 If the time range is actually in a table, the result is inserted into the
13320 next column.
13321 For time difference computation, a year is assumed to be exactly 365
13322 days in order to avoid rounding problems."
13323 (interactive "P")
13325 (org-clock-update-time-maybe)
13326 (save-excursion
13327 (unless (org-at-date-range-p)
13328 (goto-char (point-at-bol))
13329 (re-search-forward org-tr-regexp (point-at-eol) t))
13330 (if (not (org-at-date-range-p))
13331 (error "Not at a time-stamp range, and none found in current line")))
13332 (let* ((ts1 (match-string 1))
13333 (ts2 (match-string 2))
13334 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13335 (match-end (match-end 0))
13336 (time1 (org-time-string-to-time ts1))
13337 (time2 (org-time-string-to-time ts2))
13338 (t1 (time-to-seconds time1))
13339 (t2 (time-to-seconds time2))
13340 (diff (abs (- t2 t1)))
13341 (negative (< (- t2 t1) 0))
13342 ;; (ys (floor (* 365 24 60 60)))
13343 (ds (* 24 60 60))
13344 (hs (* 60 60))
13345 (fy "%dy %dd %02d:%02d")
13346 (fy1 "%dy %dd")
13347 (fd "%dd %02d:%02d")
13348 (fd1 "%dd")
13349 (fh "%02d:%02d")
13350 y d h m align)
13351 (if havetime
13352 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13354 d (floor (/ diff ds)) diff (mod diff ds)
13355 h (floor (/ diff hs)) diff (mod diff hs)
13356 m (floor (/ diff 60)))
13357 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13359 d (floor (+ (/ diff ds) 0.5))
13360 h 0 m 0))
13361 (if (not to-buffer)
13362 (message (org-make-tdiff-string y d h m))
13363 (when (org-at-table-p)
13364 (goto-char match-end)
13365 (setq align t)
13366 (and (looking-at " *|") (goto-char (match-end 0))))
13367 (if (looking-at
13368 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13369 (replace-match ""))
13370 (if negative (insert " -"))
13371 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13372 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13373 (insert " " (format fh h m))))
13374 (if align (org-table-align))
13375 (message "Time difference inserted")))))
13377 (defun org-make-tdiff-string (y d h m)
13378 (let ((fmt "")
13379 (l nil))
13380 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13381 l (push y l)))
13382 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13383 l (push d l)))
13384 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13385 l (push h l)))
13386 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13387 l (push m l)))
13388 (apply 'format fmt (nreverse l))))
13390 (defun org-time-string-to-time (s)
13391 (apply 'encode-time (org-parse-time-string s)))
13393 (defun org-time-string-to-absolute (s &optional daynr)
13394 "Convert a time stamp to an absolute day number.
13395 If there is a specifyer for a cyclic time stamp, get the closest date to
13396 DATE."
13397 (cond
13398 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13399 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13400 daynr
13401 (+ daynr 1000)))
13402 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13403 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13404 (time-to-days (current-time))) (match-string 0 s)))
13405 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13407 (defun org-calendar-holiday ()
13408 "List of holidays, for Diary display in Org-mode."
13409 (let ((hl (check-calendar-holidays date)))
13410 (if hl (mapconcat 'identity hl "; "))))
13412 (defun org-diary-sexp-entry (sexp entry date)
13413 "Process a SEXP diary ENTRY for DATE."
13414 (let ((result (if calendar-debug-sexp
13415 (let ((stack-trace-on-error t))
13416 (eval (car (read-from-string sexp))))
13417 (condition-case nil
13418 (eval (car (read-from-string sexp)))
13419 (error
13420 (beep)
13421 (message "Bad sexp at line %d in %s: %s"
13422 (org-current-line)
13423 (buffer-file-name) sexp)
13424 (sleep-for 2))))))
13425 (cond ((stringp result) result)
13426 ((and (consp result)
13427 (stringp (cdr result))) (cdr result))
13428 (result entry)
13429 (t nil))))
13431 (defun org-diary-to-ical-string (frombuf)
13432 "FIXME"
13433 (let* ((tmpdir (if (featurep 'xemacs)
13434 (temp-directory)
13435 temporary-file-directory))
13436 (tmpfile (make-temp-name
13437 (expand-file-name "orgics" tmpdir)))
13438 buf rtn b e)
13439 (save-excursion
13440 (set-buffer frombuf)
13441 (icalendar-export-region (point-min) (point-max) tmpfile)
13442 (setq buf (find-buffer-visiting tmpfile))
13443 (set-buffer buf)
13444 (goto-char (point-min))
13445 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13446 (setq b (match-beginning 0)))
13447 (goto-char (point-max))
13448 (if (re-search-backward "^END:VEVENT" nil t)
13449 (setq e (match-end 0)))
13450 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13451 (kill-buffer buf)
13452 (kill-buffer frombuf)
13453 (delete-file tmpfile)
13454 rtn))
13456 (defun org-closest-date (start current change)
13457 "Find the date closest to CURRENT that is consistent with START and CHANGE."
13458 ;; Make the proper lists from the dates
13459 (catch 'exit
13460 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13461 dn dw sday cday n1 n2
13462 d m y y1 y2 date1 date2 nmonths nm ny m2)
13464 (setq start (org-date-to-gregorian start)
13465 current (org-date-to-gregorian current)
13466 sday (calendar-absolute-from-gregorian start)
13467 cday (calendar-absolute-from-gregorian current))
13469 (if (<= cday sday) (throw 'exit sday))
13471 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13472 (setq dn (string-to-number (match-string 1 change))
13473 dw (cdr (assoc (match-string 2 change) a1)))
13474 (error "Invalid change specifyer: %s" change))
13475 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13476 (cond
13477 ((eq dw 'day)
13478 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13479 n2 (+ n1 dn)))
13480 ((eq dw 'year)
13481 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13482 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13483 (setq date1 (list m d y1)
13484 n1 (calendar-absolute-from-gregorian date1)
13485 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13486 n2 (calendar-absolute-from-gregorian date2)))
13487 ((eq dw 'month)
13488 ;; approx number of month between the tow dates
13489 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13490 ;; How often does dn fit in there?
13491 (setq d (nth 1 start) m (car start) y (nth 2 start)
13492 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13493 m (+ m nm)
13494 ny (floor (/ m 12))
13495 y (+ y ny)
13496 m (- m (* ny 12)))
13497 (while (> m 12) (setq m (- m 12) y (1+ y)))
13498 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13499 (setq m2 (+ m dn) y2 y)
13500 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13501 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13502 (while (< n2 cday)
13503 (setq n1 n2 m m2 y y2)
13504 (setq m2 (+ m dn) y2 y)
13505 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13506 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13508 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1))))
13510 (defun org-date-to-gregorian (date)
13511 "Turn any specification of DATE into a gregorian date for the calendar."
13512 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13513 ((and (listp date) (= (length date) 3)) date)
13514 ((stringp date)
13515 (setq date (org-parse-time-string date))
13516 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13517 ((listp date)
13518 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13520 (defun org-parse-time-string (s &optional nodefault)
13521 "Parse the standard Org-mode time string.
13522 This should be a lot faster than the normal `parse-time-string'.
13523 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13524 hour and minute fields will be nil if not given."
13525 (if (string-match org-ts-regexp0 s)
13526 (list 0
13527 (if (or (match-beginning 8) (not nodefault))
13528 (string-to-number (or (match-string 8 s) "0")))
13529 (if (or (match-beginning 7) (not nodefault))
13530 (string-to-number (or (match-string 7 s) "0")))
13531 (string-to-number (match-string 4 s))
13532 (string-to-number (match-string 3 s))
13533 (string-to-number (match-string 2 s))
13534 nil nil nil)
13535 (make-list 9 0)))
13537 (defun org-timestamp-up (&optional arg)
13538 "Increase the date item at the cursor by one.
13539 If the cursor is on the year, change the year. If it is on the month or
13540 the day, change that.
13541 With prefix ARG, change by that many units."
13542 (interactive "p")
13543 (org-timestamp-change (prefix-numeric-value arg)))
13545 (defun org-timestamp-down (&optional arg)
13546 "Decrease the date item at the cursor by one.
13547 If the cursor is on the year, change the year. If it is on the month or
13548 the day, change that.
13549 With prefix ARG, change by that many units."
13550 (interactive "p")
13551 (org-timestamp-change (- (prefix-numeric-value arg))))
13553 (defun org-timestamp-up-day (&optional arg)
13554 "Increase the date in the time stamp by one day.
13555 With prefix ARG, change that many days."
13556 (interactive "p")
13557 (if (and (not (org-at-timestamp-p t))
13558 (org-on-heading-p))
13559 (org-todo 'up)
13560 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13562 (defun org-timestamp-down-day (&optional arg)
13563 "Decrease the date in the time stamp by one day.
13564 With prefix ARG, change that many days."
13565 (interactive "p")
13566 (if (and (not (org-at-timestamp-p t))
13567 (org-on-heading-p))
13568 (org-todo 'down)
13569 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13571 (defsubst org-pos-in-match-range (pos n)
13572 (and (match-beginning n)
13573 (<= (match-beginning n) pos)
13574 (>= (match-end n) pos)))
13576 (defun org-at-timestamp-p (&optional inactive-ok)
13577 "Determine if the cursor is in or at a timestamp."
13578 (interactive)
13579 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13580 (pos (point))
13581 (ans (or (looking-at tsr)
13582 (save-excursion
13583 (skip-chars-backward "^[<\n\r\t")
13584 (if (> (point) 1) (backward-char 1))
13585 (and (looking-at tsr)
13586 (> (- (match-end 0) pos) -1))))))
13587 (and (boundp 'org-ts-what)
13588 (setq org-ts-what
13589 (cond
13590 ((org-pos-in-match-range pos 2) 'year)
13591 ((org-pos-in-match-range pos 3) 'month)
13592 ((org-pos-in-match-range pos 7) 'hour)
13593 ((org-pos-in-match-range pos 8) 'minute)
13594 ((or (org-pos-in-match-range pos 4)
13595 (org-pos-in-match-range pos 5)) 'day)
13596 ((and (> pos (match-end 8)) (< pos (match-end 0)))
13597 (- pos (match-end 8)))
13598 (t 'day))))
13599 ans))
13601 (defun org-timestamp-change (n &optional what)
13602 "Change the date in the time stamp at point.
13603 The date will be changed by N times WHAT. WHAT can be `day', `month',
13604 `year', `minute', `second'. If WHAT is not given, the cursor position
13605 in the timestamp determines what will be changed."
13606 (let ((pos (point))
13607 with-hm inactive
13608 org-ts-what
13609 extra
13610 ts time time0)
13611 (if (not (org-at-timestamp-p t))
13612 (error "Not at a timestamp"))
13613 (if (and (not what) (not (eq org-ts-what 'day))
13614 org-display-custom-times
13615 (get-text-property (point) 'display)
13616 (not (get-text-property (1- (point)) 'display)))
13617 (setq org-ts-what 'day))
13618 (setq org-ts-what (or what org-ts-what)
13619 inactive (= (char-after (match-beginning 0)) ?\[)
13620 ts (match-string 0))
13621 (replace-match "")
13622 (if (string-match
13623 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( \\+[0-9]+[dwmy]\\)?\\)[]>]"
13625 (setq extra (match-string 1 ts)))
13626 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13627 (setq with-hm t))
13628 (setq time0 (org-parse-time-string ts))
13629 (setq time
13630 (apply 'encode-time
13631 (append
13632 (list (or (car time0) 0))
13633 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
13634 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
13635 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
13636 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
13637 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
13638 (nthcdr 6 time0))))
13639 (when (integerp org-ts-what)
13640 (setq extra (org-modify-ts-extra extra org-ts-what n)))
13641 (if (eq what 'calendar)
13642 (let ((cal-date
13643 (save-excursion
13644 (save-match-data
13645 (set-buffer "*Calendar*")
13646 (calendar-cursor-to-date)))))
13647 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13648 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13649 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13650 (setcar time0 (or (car time0) 0))
13651 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13652 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
13653 (setq time (apply 'encode-time time0))))
13654 (setq org-last-changed-timestamp
13655 (org-insert-time-stamp time with-hm inactive nil nil extra))
13656 (org-clock-update-time-maybe)
13657 (goto-char pos)
13658 ;; Try to recenter the calendar window, if any
13659 (if (and org-calendar-follow-timestamp-change
13660 (get-buffer-window "*Calendar*" t)
13661 (memq org-ts-what '(day month year)))
13662 (org-recenter-calendar (time-to-days time)))))
13664 (defun org-modify-ts-extra (s pos n)
13665 "FIXME"
13666 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13667 ng h m new)
13668 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13669 (cond
13670 ((or (org-pos-in-match-range pos 2)
13671 (org-pos-in-match-range pos 3))
13672 (setq m (string-to-number (match-string 3 s))
13673 h (string-to-number (match-string 2 s)))
13674 (if (org-pos-in-match-range pos 2)
13675 (setq h (+ h n))
13676 (setq m (+ m n)))
13677 (if (< m 0) (setq m (+ m 60) h (1- h)))
13678 (if (> m 59) (setq m (- m 60) h (1+ h)))
13679 (setq h (min 24 (max 0 h)))
13680 (setq ng 1 new (format "-%02d:%02d" h m)))
13681 ((org-pos-in-match-range pos 6)
13682 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13683 ((org-pos-in-match-range pos 5)
13684 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
13686 (when ng
13687 (setq s (concat
13688 (substring s 0 (match-beginning ng))
13690 (substring s (match-end ng))))))
13693 (defun org-recenter-calendar (date)
13694 "If the calendar is visible, recenter it to DATE."
13695 (let* ((win (selected-window))
13696 (cwin (get-buffer-window "*Calendar*" t))
13697 (calendar-move-hook nil))
13698 (when cwin
13699 (select-window cwin)
13700 (calendar-goto-date (if (listp date) date
13701 (calendar-gregorian-from-absolute date)))
13702 (select-window win))))
13704 (defun org-goto-calendar (&optional arg)
13705 "Go to the Emacs calendar at the current date.
13706 If there is a time stamp in the current line, go to that date.
13707 A prefix ARG can be used to force the current date."
13708 (interactive "P")
13709 (let ((tsr org-ts-regexp) diff
13710 (calendar-move-hook nil)
13711 (view-calendar-holidays-initially nil)
13712 (view-diary-entries-initially nil))
13713 (if (or (org-at-timestamp-p)
13714 (save-excursion
13715 (beginning-of-line 1)
13716 (looking-at (concat ".*" tsr))))
13717 (let ((d1 (time-to-days (current-time)))
13718 (d2 (time-to-days
13719 (org-time-string-to-time (match-string 1)))))
13720 (setq diff (- d2 d1))))
13721 (calendar)
13722 (calendar-goto-today)
13723 (if (and diff (not arg)) (calendar-forward-day diff))))
13725 (defun org-date-from-calendar ()
13726 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13727 If there is already a time stamp at the cursor position, update it."
13728 (interactive)
13729 (org-timestamp-change 0 'calendar))
13731 ;;; The clock for measuring work time.
13733 (defvar org-mode-line-string "")
13734 (put 'org-mode-line-string 'risky-local-variable t)
13736 (defvar org-mode-line-timer nil)
13737 (defvar org-clock-heading "")
13738 (defvar org-clock-start-time "")
13740 (defun org-update-mode-line ()
13741 (let* ((delta (- (time-to-seconds (current-time))
13742 (time-to-seconds org-clock-start-time)))
13743 (h (floor delta 3600))
13744 (m (floor (- delta (* 3600 h)) 60)))
13745 (setq org-mode-line-string
13746 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
13747 'help-echo "Org-mode clock is running"))
13748 (force-mode-line-update)))
13750 (defvar org-clock-marker (make-marker)
13751 "Marker recording the last clock-in.")
13752 (defvar org-clock-mode-line-entry nil
13753 "Information for the modeline about the running clock.")
13755 (defun org-clock-in ()
13756 "Start the clock on the current item.
13757 If necessary, clock-out of the currently active clock."
13758 (interactive)
13759 (org-clock-out t)
13760 (let (ts)
13761 (save-excursion
13762 (org-back-to-heading t)
13763 (if (looking-at org-todo-line-regexp)
13764 (setq org-clock-heading (match-string 3))
13765 (setq org-clock-heading "???"))
13766 (setq org-clock-heading (propertize org-clock-heading 'face nil))
13767 (beginning-of-line 2)
13768 (when (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
13769 (not (equal (match-string 1) org-clock-string)))
13770 ;; First line hast scheduling info, move one further
13771 (beginning-of-line 2)
13772 (or (bolp) (newline)))
13773 (insert "\n") (backward-char 1)
13774 (indent-relative)
13775 (insert org-clock-string " ")
13776 (setq org-clock-start-time (current-time))
13777 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
13778 (move-marker org-clock-marker (point) (buffer-base-buffer))
13779 (or global-mode-string (setq global-mode-string '("")))
13780 (or (memq 'org-mode-line-string global-mode-string)
13781 (setq global-mode-string
13782 (append global-mode-string '(org-mode-line-string))))
13783 (org-update-mode-line)
13784 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
13785 (message "Clock started at %s" ts))))
13787 (defun org-clock-out (&optional fail-quietly)
13788 "Stop the currently running clock.
13789 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
13790 (interactive)
13791 (catch 'exit
13792 (if (not (marker-buffer org-clock-marker))
13793 (if fail-quietly (throw 'exit t) (error "No active clock")))
13794 (let (ts te s h m)
13795 (save-excursion
13796 (set-buffer (marker-buffer org-clock-marker))
13797 (goto-char org-clock-marker)
13798 (beginning-of-line 1)
13799 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
13800 (equal (match-string 1) org-clock-string))
13801 (setq ts (match-string 2))
13802 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
13803 (goto-char (match-end 0))
13804 (delete-region (point) (point-at-eol))
13805 (insert "--")
13806 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
13807 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
13808 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
13809 h (floor (/ s 3600))
13810 s (- s (* 3600 h))
13811 m (floor (/ s 60))
13812 s (- s (* 60 s)))
13813 (insert " => " (format "%2d:%02d" h m))
13814 (move-marker org-clock-marker nil)
13815 (org-add-log-maybe 'clock-out)
13816 (when org-mode-line-timer
13817 (cancel-timer org-mode-line-timer)
13818 (setq org-mode-line-timer nil))
13819 (setq global-mode-string
13820 (delq 'org-mode-line-string global-mode-string))
13821 (force-mode-line-update)
13822 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
13824 (defun org-clock-cancel ()
13825 "Cancel the running clock be removing the start timestamp."
13826 (interactive)
13827 (if (not (marker-buffer org-clock-marker))
13828 (error "No active clock"))
13829 (save-excursion
13830 (set-buffer (marker-buffer org-clock-marker))
13831 (goto-char org-clock-marker)
13832 (delete-region (1- (point-at-bol)) (point-at-eol)))
13833 (message "Clock canceled"))
13835 (defvar org-clock-file-total-minutes nil
13836 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
13837 (make-variable-buffer-local 'org-clock-file-total-minutes)
13839 (defun org-clock-sum (&optional tstart tend)
13840 "Sum the times for each subtree.
13841 Puts the resulting times in minutes as a text property on each headline."
13842 (interactive)
13843 (let* ((bmp (buffer-modified-p))
13844 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
13845 org-clock-string
13846 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
13847 (lmax 30)
13848 (ltimes (make-vector lmax 0))
13849 (t1 0)
13850 (level 0)
13851 ts te dt
13852 time)
13853 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
13854 (save-excursion
13855 (goto-char (point-max))
13856 (while (re-search-backward re nil t)
13857 (cond
13858 ((match-end 2)
13859 ;; Two time stamps
13860 (setq ts (match-string 2)
13861 te (match-string 3)
13862 ts (time-to-seconds
13863 (apply 'encode-time (org-parse-time-string ts)))
13864 te (time-to-seconds
13865 (apply 'encode-time (org-parse-time-string te)))
13866 ts (if tstart (max ts tstart) ts)
13867 te (if tend (min te tend) te)
13868 dt (- te ts)
13869 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
13870 ((match-end 4)
13871 ;; A naket time
13872 (setq t1 (+ t1 (string-to-number (match-string 5))
13873 (* 60 (string-to-number (match-string 4))))))
13874 (t ;; A headline
13875 (setq level (- (match-end 1) (match-beginning 1)))
13876 (when (or (> t1 0) (> (aref ltimes level) 0))
13877 (loop for l from 0 to level do
13878 (aset ltimes l (+ (aref ltimes l) t1)))
13879 (setq t1 0 time (aref ltimes level))
13880 (loop for l from level to (1- lmax) do
13881 (aset ltimes l 0))
13882 (goto-char (match-beginning 0))
13883 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
13884 (setq org-clock-file-total-minutes (aref ltimes 0)))
13885 (set-buffer-modified-p bmp)))
13887 (defun org-clock-display (&optional total-only)
13888 "Show subtree times in the entire buffer.
13889 If TOTAL-ONLY is non-nil, only show the total time for the entire file
13890 in the echo area."
13891 (interactive)
13892 (org-remove-clock-overlays)
13893 (let (time h m p)
13894 (org-clock-sum)
13895 (unless total-only
13896 (save-excursion
13897 (goto-char (point-min))
13898 (while (setq p (next-single-property-change (point) :org-clock-minutes))
13899 (goto-char p)
13900 (when (setq time (get-text-property p :org-clock-minutes))
13901 (org-put-clock-overlay time (funcall outline-level))))
13902 (setq h (/ org-clock-file-total-minutes 60)
13903 m (- org-clock-file-total-minutes (* 60 h)))
13904 ;; Arrange to remove the overlays upon next change.
13905 (when org-remove-highlights-with-change
13906 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
13907 nil 'local))))
13908 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
13910 (defvar org-clock-overlays nil)
13911 (make-variable-buffer-local 'org-clock-overlays)
13913 (defun org-put-clock-overlay (time &optional level)
13914 "Put an overlays on the current line, displaying TIME.
13915 If LEVEL is given, prefix time with a corresponding number of stars.
13916 This creates a new overlay and stores it in `org-clock-overlays', so that it
13917 will be easy to remove."
13918 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
13919 (l (if level (org-get-legal-level level 0) 0))
13920 (off 0)
13921 ov tx)
13922 (move-to-column c)
13923 (unless (eolp) (skip-chars-backward "^ \t"))
13924 (skip-chars-backward " \t")
13925 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
13926 tx (concat (buffer-substring (1- (point)) (point))
13927 (make-string (+ off (max 0 (- c (current-column)))) ?.)
13928 (org-add-props (format "%s %2d:%02d%s"
13929 (make-string l ?*) h m
13930 (make-string (- 10 l) ?\ ))
13931 '(face secondary-selection))
13932 ""))
13933 (if (not (featurep 'xemacs))
13934 (org-overlay-put ov 'display tx)
13935 (org-overlay-put ov 'invisible t)
13936 (org-overlay-put ov 'end-glyph (make-glyph tx)))
13937 (push ov org-clock-overlays)))
13939 (defun org-remove-clock-overlays (&optional beg end noremove)
13940 "Remove the occur highlights from the buffer.
13941 BEG and END are ignored. If NOREMOVE is nil, remove this function
13942 from the `before-change-functions' in the current buffer."
13943 (interactive)
13944 (unless org-inhibit-highlight-removal
13945 (mapc 'org-delete-overlay org-clock-overlays)
13946 (setq org-clock-overlays nil)
13947 (unless noremove
13948 (remove-hook 'before-change-functions
13949 'org-remove-clock-overlays 'local))))
13951 (defun org-clock-out-if-current ()
13952 "Clock out if the current entry contains the running clock.
13953 This is used to stop the clock after a TODO entry is marked DONE."
13954 (when (and (member state org-done-keywords)
13955 (equal (marker-buffer org-clock-marker) (current-buffer))
13956 (< (point) org-clock-marker)
13957 (> (save-excursion (outline-next-heading) (point))
13958 org-clock-marker))
13959 ;; Clock out, but don't accept a logging message for this.
13960 (let ((org-log-done (if (and (listp org-log-done)
13961 (member 'clock-out org-log-done))
13962 '(done)
13963 org-log-done)))
13964 (org-clock-out))))
13966 (add-hook 'org-after-todo-state-change-hook
13967 'org-clock-out-if-current)
13969 (defun org-check-running-clock ()
13970 "Check if the current buffer contains the running clock.
13971 If yes, offer to stop it and to save the buffer with the changes."
13972 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
13973 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
13974 (buffer-name))))
13975 (org-clock-out)
13976 (when (y-or-n-p "Save changed buffer?")
13977 (save-buffer))))
13979 (defun org-clock-report ()
13980 "Create a table containing a report about clocked time.
13981 If the buffer contains lines
13982 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
13984 #+END: clocktable
13985 then the table will be inserted between these lines, replacing whatever
13986 is was there before. If these lines are not in the buffer, the table
13987 is inserted at point, surrounded by the special lines.
13988 The BEGIN line can contain parameters. Allowed are:
13989 :maxlevel The maximum level to be included in the table. Default is 3.
13990 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
13991 (interactive)
13992 (org-remove-clock-overlays)
13993 (unless (org-find-dblock "clocktable")
13994 (org-create-dblock (list :name "clocktable"
13995 :maxlevel 2 :emphasize nil)))
13996 (org-update-dblock))
13998 (defun org-clock-update-time-maybe ()
13999 "If this is a CLOCK line, update it and return t.
14000 Otherwise, return nil."
14001 (interactive)
14002 (save-excursion
14003 (beginning-of-line 1)
14004 (skip-chars-forward " \t")
14005 (when (looking-at org-clock-string)
14006 (let ((re (concat "[ \t]*" org-clock-string
14007 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
14008 "\\([ \t]*=>.*\\)?"))
14009 ts te h m s)
14010 (if (not (looking-at re))
14012 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
14013 (end-of-line 1)
14014 (setq ts (match-string 1)
14015 te (match-string 2))
14016 (setq s (- (time-to-seconds
14017 (apply 'encode-time (org-parse-time-string te)))
14018 (time-to-seconds
14019 (apply 'encode-time (org-parse-time-string ts))))
14020 h (floor (/ s 3600))
14021 s (- s (* 3600 h))
14022 m (floor (/ s 60))
14023 s (- s (* 60 s)))
14024 (insert " => " (format "%2d:%02d" h m))
14025 t)))))
14027 (defun org-clock-special-range (key &optional time as-strings)
14028 "Return two times bordering a special time range.
14029 Key is a symbol specifying the range and can be one of `today', `yesterday',
14030 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
14031 A week starts Monday 0:00 and ends Sunday 24:00.
14032 The range is determined relative to TIME. TIME defaults to the current time.
14033 The return value is a cons cell with two internal times like the ones
14034 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
14035 the returned times will be formatted strings."
14036 (let* ((tm (decode-time (or time (current-time))))
14037 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
14038 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
14039 (dow (nth 6 tm))
14040 s1 m1 h1 d1 month1 y1 diff ts te fm)
14041 (cond
14042 ((eq key 'today)
14043 (setq h 0 m 0 h1 24 m1 0))
14044 ((eq key 'yesterday)
14045 (setq d (1- d) h 0 m 0 h1 24 m1 0))
14046 ((eq key 'thisweek)
14047 (setq diff (if (= dow 0) 6 (1- dow))
14048 m 0 h 0 d (- d diff) d1 (+ 7 d)))
14049 ((eq key 'lastweek)
14050 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
14051 m 0 h 0 d (- d diff) d1 (+ 7 d)))
14052 ((eq key 'thismonth)
14053 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
14054 ((eq key 'lastmonth)
14055 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
14056 ((eq key 'thisyear)
14057 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
14058 ((eq key 'lastyear)
14059 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
14060 (t (error "No such time block %s" key)))
14061 (setq ts (encode-time s m h d month y)
14062 te (encode-time (or s1 s) (or m1 m) (or h1 h)
14063 (or d1 d) (or month1 month) (or y1 y)))
14064 (setq fm (cdr org-time-stamp-formats))
14065 (if as-strings
14066 (cons (format-time-string fm ts) (format-time-string fm te))
14067 (cons ts te))))
14069 (defun org-dblock-write:clocktable (params)
14070 "Write the standard clocktable."
14071 (let ((hlchars '((1 . "*") (2 . ?/)))
14072 (emph nil)
14073 (ins (make-marker))
14074 ipos time h m p level hlc hdl maxlevel
14075 ts te cc block)
14076 (setq maxlevel (or (plist-get params :maxlevel) 3)
14077 emph (plist-get params :emphasize)
14078 ts (plist-get params :tstart)
14079 te (plist-get params :tend)
14080 block (plist-get params :block))
14081 (when block
14082 (setq cc (org-clock-special-range block nil t)
14083 ts (car cc) te (cdr cc)))
14084 (if ts (setq ts (time-to-seconds
14085 (apply 'encode-time (org-parse-time-string ts)))))
14086 (if te (setq te (time-to-seconds
14087 (apply 'encode-time (org-parse-time-string te)))))
14088 (move-marker ins (point))
14089 (setq ipos (point))
14090 (insert-before-markers "Clock summary at ["
14091 (substring
14092 (format-time-string (cdr org-time-stamp-formats))
14093 1 -1)
14094 "]."
14095 (if block
14096 (format " Considered range is /%s/." block)
14098 "\n\n|L|Headline|Time|\n")
14099 (org-clock-sum ts te)
14100 (setq h (/ org-clock-file-total-minutes 60)
14101 m (- org-clock-file-total-minutes (* 60 h)))
14102 (insert-before-markers "|-\n|0|" "*Total file time*| "
14103 (format "*%d:%02d*" h m)
14104 "|\n")
14105 (goto-char (point-min))
14106 (while (setq p (next-single-property-change (point) :org-clock-minutes))
14107 (goto-char p)
14108 (when (setq time (get-text-property p :org-clock-minutes))
14109 (save-excursion
14110 (beginning-of-line 1)
14111 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[a-zA-Z0-9_@:]+:\\)?[ \t]*$")
14112 (setq level (- (match-end 1) (match-beginning 1)))
14113 (<= level maxlevel))
14114 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
14115 hdl (match-string 2)
14116 h (/ time 60)
14117 m (- time (* 60 h)))
14118 (goto-char ins)
14119 (if (= level 1) (insert-before-markers "|-\n"))
14120 (insert-before-markers
14121 "| " (int-to-string level) "|" hlc hdl hlc " |"
14122 (make-string (1- level) ?|)
14124 (format "%d:%02d" h m)
14126 " |\n")))))
14127 (goto-char ins)
14128 (backward-delete-char 1)
14129 (goto-char ipos)
14130 (skip-chars-forward "^|")
14131 (org-table-align)))
14133 ;; FIXME: I don't think anybody uses this, ask David
14134 (defun org-collect-clock-time-entries ()
14135 "Return an internal list with clocking information.
14136 This list has one entry for each CLOCK interval.
14137 FIXME: describe the elements."
14138 (interactive)
14139 (let ((re (concat "^[ \t]*" org-clock-string
14140 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
14141 rtn beg end next cont level title total closedp leafp
14142 clockpos titlepos h m donep)
14143 (save-excursion
14144 (org-clock-sum)
14145 (goto-char (point-min))
14146 (while (re-search-forward re nil t)
14147 (setq clockpos (match-beginning 0)
14148 beg (match-string 1) end (match-string 2)
14149 cont (match-end 0))
14150 (setq beg (apply 'encode-time (org-parse-time-string beg))
14151 end (apply 'encode-time (org-parse-time-string end)))
14152 (org-back-to-heading t)
14153 (setq donep (org-entry-is-done-p))
14154 (setq titlepos (point)
14155 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
14156 h (/ total 60) m (- total (* 60 h))
14157 total (cons h m))
14158 (looking-at "\\(\\*+\\) +\\(.*\\)")
14159 (setq level (- (match-end 1) (match-beginning 1))
14160 title (org-match-string-no-properties 2))
14161 (save-excursion (outline-next-heading) (setq next (point)))
14162 (setq closedp (re-search-forward org-closed-time-regexp next t))
14163 (goto-char next)
14164 (setq leafp (and (looking-at "^\\*+ ")
14165 (<= (- (match-end 0) (point)) level)))
14166 (push (list beg end clockpos closedp donep
14167 total title titlepos level leafp)
14168 rtn)
14169 (goto-char cont)))
14170 (nreverse rtn)))
14172 ;;;; Agenda, and Diary Integration
14174 ;;; Define the Org-agenda-mode
14176 (defvar org-agenda-mode-map (make-sparse-keymap)
14177 "Keymap for `org-agenda-mode'.")
14179 (defvar org-agenda-menu) ; defined later in this file.
14180 (defvar org-agenda-follow-mode nil)
14181 (defvar org-agenda-show-log nil)
14182 (defvar org-agenda-redo-command nil)
14183 (defvar org-agenda-mode-hook nil)
14184 (defvar org-agenda-type nil)
14185 (defvar org-agenda-force-single-file nil)
14187 (defun org-agenda-mode ()
14188 "Mode for time-sorted view on action items in Org-mode files.
14190 The following commands are available:
14192 \\{org-agenda-mode-map}"
14193 (interactive)
14194 (kill-all-local-variables)
14195 (setq org-agenda-undo-list nil
14196 org-agenda-pending-undo-list nil)
14197 (setq major-mode 'org-agenda-mode)
14198 ;; Keep global-font-lock-mode from turning on font-lock-mode
14199 (org-set-local 'font-lock-global-modes (list 'not major-mode))
14200 (setq mode-name "Org-Agenda")
14201 (use-local-map org-agenda-mode-map)
14202 (easy-menu-add org-agenda-menu)
14203 (if org-startup-truncated (setq truncate-lines t))
14204 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
14205 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
14206 ;; Make sure properties are removed when copying text
14207 (when (boundp 'buffer-substring-filters)
14208 (org-set-local 'buffer-substring-filters
14209 (cons (lambda (x)
14210 (set-text-properties 0 (length x) nil x) x)
14211 buffer-substring-filters)))
14212 (unless org-agenda-keep-modes
14213 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
14214 org-agenda-show-log nil))
14215 (easy-menu-change
14216 '("Agenda") "Agenda Files"
14217 (append
14218 (list
14219 (vector
14220 (if (get 'org-agenda-files 'org-restrict)
14221 "Restricted to single file"
14222 "Edit File List")
14223 '(org-edit-agenda-file-list)
14224 (not (get 'org-agenda-files 'org-restrict)))
14225 "--")
14226 (mapcar 'org-file-menu-entry (org-agenda-files))))
14227 (org-agenda-set-mode-name)
14228 (apply
14229 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
14230 (list 'org-agenda-mode-hook)))
14232 (substitute-key-definition 'undo 'org-agenda-undo
14233 org-agenda-mode-map global-map)
14234 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
14235 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
14236 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
14237 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
14238 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
14239 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
14240 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
14241 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
14242 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
14243 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
14244 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
14245 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
14246 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
14247 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
14248 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
14249 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
14250 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
14251 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
14252 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
14253 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
14254 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
14255 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
14256 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
14257 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
14258 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
14259 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
14261 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
14262 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
14263 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
14264 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
14265 (while l (org-defkey org-agenda-mode-map
14266 (int-to-string (pop l)) 'digit-argument)))
14268 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
14269 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
14270 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
14271 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
14272 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
14273 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
14274 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
14275 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
14276 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
14277 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
14278 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
14279 (org-defkey org-agenda-mode-map "n" 'next-line)
14280 (org-defkey org-agenda-mode-map "p" 'previous-line)
14281 (org-defkey org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
14282 (org-defkey org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
14283 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
14284 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
14285 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
14286 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
14287 (eval-after-load "calendar"
14288 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
14289 'org-calendar-goto-agenda))
14290 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
14291 (org-defkey org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
14292 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
14293 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
14294 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
14295 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
14296 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
14297 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
14298 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
14299 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
14300 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
14301 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
14302 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
14303 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
14304 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
14305 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
14306 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
14307 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
14308 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
14309 "Local keymap for agenda entries from Org-mode.")
14311 (org-defkey org-agenda-keymap
14312 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
14313 (org-defkey org-agenda-keymap
14314 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
14315 (when org-agenda-mouse-1-follows-link
14316 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
14317 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
14318 '("Agenda"
14319 ("Agenda Files")
14320 "--"
14321 ["Show" org-agenda-show t]
14322 ["Go To (other window)" org-agenda-goto t]
14323 ["Go To (this window)" org-agenda-switch-to t]
14324 ["Follow Mode" org-agenda-follow-mode
14325 :style toggle :selected org-agenda-follow-mode :active t]
14326 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
14327 "--"
14328 ["Cycle TODO" org-agenda-todo t]
14329 ["Archive subtree" org-agenda-archive t]
14330 ["Delete subtree" org-agenda-kill t]
14331 "--"
14332 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
14333 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
14334 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
14335 "--"
14336 ("Tags"
14337 ["Show all Tags" org-agenda-show-tags t]
14338 ["Set Tags" org-agenda-set-tags t])
14339 ("Date/Schedule"
14340 ["Schedule" org-agenda-schedule t]
14341 ["Set Deadline" org-agenda-deadline t]
14342 "--"
14343 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
14344 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
14345 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
14346 ("Priority"
14347 ["Set Priority" org-agenda-priority t]
14348 ["Increase Priority" org-agenda-priority-up t]
14349 ["Decrease Priority" org-agenda-priority-down t]
14350 ["Show Priority" org-agenda-show-priority t])
14351 ("Calendar/Diary"
14352 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
14353 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
14354 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
14355 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
14356 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
14357 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
14358 "--"
14359 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
14360 "--"
14361 ("View"
14362 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
14363 :style radio :selected (equal org-agenda-ndays 1)]
14364 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
14365 :style radio :selected (equal org-agenda-ndays 7)]
14366 "--"
14367 ["Show Logbook entries" org-agenda-log-mode
14368 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
14369 ["Include Diary" org-agenda-toggle-diary
14370 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
14371 ["Use Time Grid" org-agenda-toggle-time-grid
14372 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
14373 ["Write view to file" org-write-agenda t]
14374 ["Rebuild buffer" org-agenda-redo t]
14375 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
14376 "--"
14377 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
14378 "--"
14379 ["Quit" org-agenda-quit t]
14380 ["Exit and Release Buffers" org-agenda-exit t]
14383 ;;; Agenda undo
14385 (defvar org-agenda-allow-remote-undo t
14386 "Non-nil means, allow remote undo from the agenda buffer.")
14387 (defvar org-agenda-undo-list nil
14388 "List of undoable operations in the agenda since last refresh.")
14389 (defvar org-agenda-undo-has-started-in nil
14390 "Buffers that have already seen `undo-start' in the current undo sequence.")
14391 (defvar org-agenda-pending-undo-list nil
14392 "In a series of undo commands, this is the list of remaning undo items.")
14394 (defmacro org-if-unprotected (&rest body)
14395 "Execute BODY if ther is no `org-protected' text property at point."
14396 (declare (debug t))
14397 `(unless (get-text-property (point) 'org-protected)
14398 ,@body))
14400 (defmacro org-unmodified (&rest body)
14401 "Execute body without changing buffer-modified-p."
14402 `(set-buffer-modified-p
14403 (prog1 (buffer-modified-p) ,@body)))
14405 (defmacro org-with-remote-undo (_buffer &rest _body)
14406 "Execute BODY while recording undo information in two buffers."
14407 (declare (indent 1) (debug t))
14408 `(let ((_cline (org-current-line))
14409 (_cmd this-command)
14410 (_buf1 (current-buffer))
14411 (_buf2 ,_buffer)
14412 (_undo1 buffer-undo-list)
14413 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
14414 _c1 _c2)
14415 ,@_body
14416 (when org-agenda-allow-remote-undo
14417 (setq _c1 (org-verify-change-for-undo
14418 _undo1 (with-current-buffer _buf1 buffer-undo-list))
14419 _c2 (org-verify-change-for-undo
14420 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
14421 (when (or _c1 _c2)
14422 ;; make sure there are undo boundaries
14423 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
14424 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
14425 ;; remember which buffer to undo
14426 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
14427 org-agenda-undo-list)))))
14429 (defun org-agenda-undo ()
14430 "Undo a remote editing step in the agenda.
14431 This undoes changes both in the agenda buffer and in the remote buffer
14432 that have been changed along."
14433 (interactive)
14434 (or org-agenda-allow-remote-undo
14435 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
14436 (if (not (eq this-command last-command))
14437 (setq org-agenda-undo-has-started-in nil
14438 org-agenda-pending-undo-list org-agenda-undo-list))
14439 (if (not org-agenda-pending-undo-list)
14440 (error "No further undo information"))
14441 (let* ((entry (pop org-agenda-pending-undo-list))
14442 buf line cmd rembuf)
14443 (setq cmd (pop entry) line (pop entry))
14444 (setq rembuf (nth 2 entry))
14445 (org-with-remote-undo rembuf
14446 (while (bufferp (setq buf (pop entry)))
14447 (if (pop entry)
14448 (with-current-buffer buf
14449 (let ((last-undo-buffer buf)
14450 buffer-read-only)
14451 (unless (memq buf org-agenda-undo-has-started-in)
14452 (push buf org-agenda-undo-has-started-in)
14453 (make-local-variable 'pending-undo-list)
14454 (undo-start))
14455 (while (and pending-undo-list
14456 (listp pending-undo-list)
14457 (not (car pending-undo-list)))
14458 (pop pending-undo-list))
14459 (undo-more 1))))))
14460 (goto-line line)
14461 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
14463 (defun org-verify-change-for-undo (l1 l2)
14464 "Verify that a real change occurred between the undo lists L1 and L2."
14465 (while (and l1 (listp l1) (null (car l1))) (pop l1))
14466 (while (and l2 (listp l2) (null (car l2))) (pop l2))
14467 (not (eq l1 l2)))
14469 ;;; Agenda dispatch
14471 (defvar org-agenda-restrict nil)
14472 (defvar org-agenda-restrict-begin (make-marker))
14473 (defvar org-agenda-restrict-end (make-marker))
14474 (defvar org-agenda-last-dispatch-buffer nil)
14476 ;;;###autoload
14477 (defun org-agenda (arg)
14478 "Dispatch agenda commands to collect entries to the agenda buffer.
14479 Prompts for a character to select a command. Any prefix arg will be passed
14480 on to the selected command. The default selections are:
14482 a Call `org-agenda-list' to display the agenda for current day or week.
14483 t Call `org-todo-list' to display the global todo list.
14484 T Call `org-todo-list' to display the global todo list, select only
14485 entries with a specific TODO keyword (the user gets a prompt).
14486 m Call `org-tags-view' to display headlines with tags matching
14487 a condition (the user is prompted for the condition).
14488 M Like `m', but select only TODO entries, no ordinary headlines.
14489 l Create a timeline for the current buffer.
14490 e Export views to associated files.
14492 More commands can be added by configuring the variable
14493 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
14494 searches can be pre-defined in this way.
14496 If the current buffer is in Org-mode and visiting a file, you can also
14497 first press `1' to indicate that the agenda should be temporarily (until the
14498 next use of \\[org-agenda]) restricted to the current file."
14499 (interactive "P")
14500 (catch 'exit
14501 (let* ((buf (current-buffer))
14502 (bfn (buffer-file-name (buffer-base-buffer)))
14503 (restrict-ok (and bfn (org-mode-p)))
14504 (custom org-agenda-custom-commands)
14505 c entry key type match lprops)
14506 ;; Turn off restriction
14507 (put 'org-agenda-files 'org-restrict nil)
14508 (setq org-agenda-restrict nil)
14509 (move-marker org-agenda-restrict-begin nil)
14510 (move-marker org-agenda-restrict-end nil)
14511 ;; Remember where this call originated
14512 (setq org-agenda-last-dispatch-buffer (current-buffer))
14513 (save-window-excursion
14514 (delete-other-windows)
14515 (switch-to-buffer-other-window " *Agenda Commands*")
14516 (erase-buffer)
14517 (insert (eval-when-compile
14518 (let ((header
14519 "Press key for an agenda command:
14520 -------------------------------- C Configure custom agenda commands
14521 a Agenda for current week or day e Export agenda views
14522 t List of all TODO entries T Entries with special TODO kwd
14523 m Match a TAGS query M Like m, but only TODO entries
14524 L Timeline for current buffer # List stuck projects (!=configure)
14526 (start 0))
14527 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
14528 (setq start (match-end 0))
14529 (add-text-properties (match-beginning 2) (match-end 2)
14530 '(face bold) header))
14531 header)))
14532 (while (setq entry (pop custom))
14533 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
14534 (insert (format "\n%-4s%-14s: %s"
14535 (org-add-props (copy-sequence key)
14536 '(face bold))
14537 (cond
14538 ((stringp type) type)
14539 ((eq type 'agenda) "Agenda for current week or day")
14540 ((eq type 'alltodo) "List of all TODO entries")
14541 ((eq type 'stuck) "List of stuck projects")
14542 ((eq type 'todo) "TODO keyword")
14543 ((eq type 'tags) "Tags query")
14544 ((eq type 'tags-todo) "Tags (TODO)")
14545 ((eq type 'tags-tree) "Tags tree")
14546 ((eq type 'todo-tree) "TODO kwd tree")
14547 ((eq type 'occur-tree) "Occur tree")
14548 ((functionp type) (symbol-name type))
14549 (t "???"))
14550 (if (stringp match)
14551 (org-add-props match nil 'face 'org-warning)
14552 (format "set of %d commands" (length match))))))
14553 (if restrict-ok
14554 (insert "\n"
14555 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
14556 (goto-char (point-min))
14557 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
14558 (message "Press key for agenda command%s"
14559 (if restrict-ok ", or [1] or [0] to restrict" ""))
14560 (setq c (read-char-exclusive))
14561 (message "")
14562 (when (memq c '(?L ?1 ?0))
14563 (if restrict-ok
14564 (put 'org-agenda-files 'org-restrict (list bfn))
14565 (error "Cannot restrict agenda to current buffer"))
14566 (with-current-buffer " *Agenda Commands*"
14567 (goto-char (point-max))
14568 (delete-region (point-at-bol) (point))
14569 (goto-char (point-min)))
14570 (when (eq c ?0)
14571 (setq org-agenda-restrict t)
14572 (with-current-buffer buf
14573 (if (org-region-active-p)
14574 (progn
14575 (move-marker org-agenda-restrict-begin (region-beginning))
14576 (move-marker org-agenda-restrict-end (region-end)))
14577 (save-excursion
14578 (org-back-to-heading t)
14579 (move-marker org-agenda-restrict-begin (point))
14580 (move-marker org-agenda-restrict-end
14581 (progn (org-end-of-subtree t)))))))
14582 (unless (eq c ?L)
14583 (message "Press key for agenda command%s"
14584 (if restrict-ok " (restricted to current file)" ""))
14585 (setq c (read-char-exclusive)))
14586 (message "")))
14587 (require 'calendar) ; FIXME: can we avoid this for some commands?
14588 ;; For example the todo list should not need it (but does...)
14589 (cond
14590 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
14591 (if (symbolp (nth 1 entry))
14592 (progn
14593 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
14594 lprops (nth 3 entry))
14595 (cond
14596 ((eq type 'agenda)
14597 (org-let lprops '(org-agenda-list current-prefix-arg)))
14598 ((eq type 'alltodo)
14599 (org-let lprops '(org-todo-list current-prefix-arg)))
14600 ((eq type 'stuck)
14601 (org-let lprops '(org-agenda-list-stuck-projects
14602 current-prefix-arg)))
14603 ((eq type 'tags)
14604 (org-let lprops '(org-tags-view current-prefix-arg match)))
14605 ((eq type 'tags-todo)
14606 (org-let lprops '(org-tags-view '(4) match)))
14607 ((eq type 'todo)
14608 (org-let lprops '(org-todo-list match)))
14609 ((eq type 'tags-tree)
14610 (org-check-for-org-mode)
14611 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
14612 ((eq type 'todo-tree)
14613 (org-check-for-org-mode)
14614 (org-let lprops
14615 '(org-occur (concat "^" outline-regexp "[ \t]*"
14616 (regexp-quote match) "\\>"))))
14617 ((eq type 'occur-tree)
14618 (org-check-for-org-mode)
14619 (org-let lprops '(org-occur match)))
14620 ((fboundp type)
14621 (org-let lprops '(funcall type match)))
14622 (t (error "Invalid custom agenda command type %s" type))))
14623 (org-run-agenda-series (nth 1 entry) (cddr entry))))
14624 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
14625 ((equal c ?a) (call-interactively 'org-agenda-list))
14626 ((equal c ?t) (call-interactively 'org-todo-list))
14627 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
14628 ((equal c ?m) (call-interactively 'org-tags-view))
14629 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
14630 ((equal c ?e) (call-interactively 'org-store-agenda-views))
14631 ((equal c ?L)
14632 (unless restrict-ok
14633 (error "This is not an Org-mode file"))
14634 (org-call-with-arg 'org-timeline arg))
14635 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
14636 ((equal c ?!) (customize-variable 'org-stuck-projects))
14637 (t (error "Invalid key"))))))
14639 (defun org-run-agenda-series (name series)
14640 (org-prepare-agenda name)
14641 (let* ((org-agenda-multi t)
14642 (redo (list 'org-run-agenda-series name (list 'quote series)))
14643 (cmds (car series))
14644 (gprops (nth 1 series))
14645 match ;; The byte compiler incorrectly complains about this. Keep it!
14646 cmd type lprops)
14647 (while (setq cmd (pop cmds))
14648 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
14649 (cond
14650 ((eq type 'agenda)
14651 (org-let2 gprops lprops
14652 '(call-interactively 'org-agenda-list)))
14653 ((eq type 'alltodo)
14654 (org-let2 gprops lprops
14655 '(call-interactively 'org-todo-list)))
14656 ((eq type 'stuck)
14657 (org-let2 gprops lprops
14658 '(call-interactively 'org-agenda-list-stuck-projects)))
14659 ((eq type 'tags)
14660 (org-let2 gprops lprops
14661 '(org-tags-view current-prefix-arg match)))
14662 ((eq type 'tags-todo)
14663 (org-let2 gprops lprops
14664 '(org-tags-view '(4) match)))
14665 ((eq type 'todo)
14666 (org-let2 gprops lprops
14667 '(org-todo-list match)))
14668 ((fboundp type)
14669 (org-let2 gprops lprops
14670 '(funcall type match)))
14671 (t (error "Invalid type in command series"))))
14672 (widen)
14673 (setq org-agenda-redo-command redo)
14674 (goto-char (point-min)))
14675 (org-finalize-agenda))
14677 ;;;###autoload
14678 (defmacro org-batch-agenda (cmd-key &rest parameters)
14679 "Run an agenda command in batch mode and send the result to STDOUT.
14680 If CMD-KEY is a string of length 1, it is used as a key in
14681 `org-agenda-custom-commands' and triggers this command. If it is a
14682 longer string is is used as a tags/todo match string.
14683 Paramters are alternating variable names and values that will be bound
14684 before running the agenda command."
14685 (let (pars)
14686 (while parameters
14687 (push (list (pop parameters) (if parameters (pop parameters))) pars))
14688 (if (> (length cmd-key) 1)
14689 (eval (list 'let (nreverse pars)
14690 (list 'org-tags-view nil cmd-key)))
14691 (flet ((read-char-exclusive () (string-to-char cmd-key)))
14692 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
14693 (set-buffer "*Org Agenda*")
14694 (princ (org-encode-for-stdout (buffer-string)))))
14696 (defun org-encode-for-stdout (string)
14697 (if (fboundp 'encode-coding-string)
14698 (encode-coding-string string buffer-file-coding-system)
14699 string))
14701 (defvar org-agenda-info nil)
14703 ;;;###autoload
14704 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
14705 "Run an agenda command in batch mode and send the result to STDOUT.
14706 If CMD-KEY is a string of length 1, it is used as a key in
14707 `org-agenda-custom-commands' and triggers this command. If it is a
14708 longer string is is used as a tags/todo match string.
14709 Paramters are alternating variable names and values that will be bound
14710 before running the agenda command.
14712 The output gives a line for each selected agenda item. Each
14713 item is a list of comma-separated values, like this:
14715 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
14717 category The category of the item
14718 head The headline, without TODO kwd, TAGS and PRIORITY
14719 type The type of the agenda entry, can be
14720 todo selected in TODO match
14721 tagsmatch selected in tags match
14722 diary imported from diary
14723 deadline a deadline on given date
14724 scheduled scheduled on given date
14725 timestamp entry has timestamp on given date
14726 closed entry was closed on given date
14727 upcoming-deadline warning about deadline
14728 past-scheduled forwarded scheduled item
14729 block entry has date block including g. date
14730 todo The todo keyword, if any
14731 tags All tags including inherited ones, separated by colons
14732 date The relevant date, like 2007-2-14
14733 time The time, like 15:00-16:50
14734 extra Sting with extra planning info
14735 priority-l The priority letter if any was given
14736 priority-n The computed numerical priority
14737 agenda-day The day in the agenda where this is listed"
14739 (let (pars)
14740 (while parameters
14741 (push (list (pop parameters) (if parameters (pop parameters))) pars))
14742 (push (list 'org-agenda-remove-tags t) pars)
14743 (if (> (length cmd-key) 1)
14744 (eval (list 'let (nreverse pars)
14745 (list 'org-tags-view nil cmd-key)))
14746 (flet ((read-char-exclusive () (string-to-char cmd-key)))
14747 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
14748 (set-buffer "*Org Agenda*")
14749 (let* ((lines (org-split-string (buffer-string) "\n"))
14750 line)
14751 (while (setq line (pop lines))
14752 (catch 'next
14753 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
14754 (setq org-agenda-info
14755 (org-fix-agenda-info (text-properties-at 0 line)))
14756 (princ
14757 (org-encode-for-stdout
14758 (mapconcat 'org-agenda-export-csv-mapper
14759 '(org-category txt type todo tags date time-of-day extra
14760 priority-letter priority agenda-day)
14761 ",")))
14762 (princ "\n"))))))
14764 (defun org-fix-agenda-info (props)
14765 "FIXME"
14766 (let (tmp re)
14767 (when (setq tmp (plist-get props 'tags))
14768 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
14769 (when (setq tmp (plist-get props 'date))
14770 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
14771 (let ((calendar-date-display-form '(year "-" month "-" day)))
14772 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
14774 (setq tmp (calendar-date-string tmp)))
14775 (setq props (plist-put props 'date tmp)))
14776 (when (setq tmp (plist-get props 'day))
14777 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
14778 (let ((calendar-date-display-form '(year "-" month "-" day)))
14779 (setq tmp (calendar-date-string tmp)))
14780 (setq props (plist-put props 'day tmp))
14781 (setq props (plist-put props 'agenda-day tmp)))
14782 (when (setq tmp (plist-get props 'txt))
14783 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
14784 (plist-put props 'priority-letter (match-string 1 tmp))
14785 (setq tmp (replace-match "" t t tmp)))
14786 (when (and (setq re (plist-get props 'org-todo-regexp))
14787 (setq re (concat "\\`\\.*" re " ?"))
14788 (string-match re tmp))
14789 (plist-put props 'todo (match-string 1 tmp))
14790 (setq tmp (replace-match "" t t tmp)))
14791 (plist-put props 'txt tmp)))
14792 props)
14794 (defun org-agenda-export-csv-mapper (prop)
14795 (let ((res (plist-get org-agenda-info prop)))
14796 (setq res
14797 (cond
14798 ((not res) "")
14799 ((stringp res) res)
14800 (t (prin1-to-string res))))
14801 (while (string-match "," res)
14802 (setq res (replace-match ";" t t res)))
14803 (org-trim res)))
14806 ;;;###autoload
14807 (defun org-store-agenda-views (&rest parameters)
14808 (interactive)
14809 (eval (list 'org-batch-store-agenda-views)))
14811 (defvar org-agenda-buffer-name)
14813 ;; FIXME, why is this a macro?????
14814 ;;;###autoload
14815 (defmacro org-batch-store-agenda-views (&rest parameters)
14816 "Run all custom agenda commands that have a file argument."
14817 (let ((cmds org-agenda-custom-commands)
14818 (dir (default-directory))
14819 pars cmd thiscmdkey files opts)
14820 (while parameters
14821 (push (list (pop parameters) (if parameters (pop parameters))) pars))
14822 (setq pars (reverse pars))
14823 (save-window-excursion
14824 (while cmds
14825 (setq cmd (pop cmds)
14826 thiscmdkey (car cmd)
14827 opts (nth 3 cmd)
14828 files (org-last cmd))
14829 (if (stringp files) (setq files (list files)))
14830 (when files
14831 (flet ((read-char-exclusive () (string-to-char thiscmdkey)))
14832 (eval (list 'let (append org-agenda-exporter-settings opts pars)
14833 '(org-agenda nil))))
14834 (set-buffer "*Org Agenda*")
14835 (while files
14836 (eval (list 'let (append org-agenda-exporter-settings opts pars)
14837 (list 'org-write-agenda
14838 (expand-file-name (pop files) dir) t)))))
14839 (kill-buffer org-agenda-buffer-name)))))
14841 (defun org-write-agenda (file &optional nosettings)
14842 "Write the current buffer (an agenda view) as a file.
14843 Depending on the extension of the file name, plain text (.txt),
14844 HTML (.html or .htm) or Postscript (.ps) is produced.
14845 If NOSETTINGS is given, do not scope the settings of
14846 `org-agenda-exporter-settings' into the export commands. This is used when
14847 the settings have already been scoped and we do not wish to overrule other,
14848 higher priority settings."
14849 (interactive "FWrite agenda to file: ")
14850 (if (not (file-writable-p file))
14851 (error "Cannot write agenda to file %s" file))
14852 (cond
14853 ((string-match "\\.html?\\'" file) (require 'htmlize))
14854 ((string-match "\\.ps\\'" file) (require 'ps-print)))
14855 (org-let (if nosettings nil org-agenda-exporter-settings)
14856 '(save-excursion
14857 (save-window-excursion
14858 (cond
14859 ((string-match "\\.html?\\'" file)
14860 (set-buffer (htmlize-buffer (current-buffer)))
14862 (when (and org-agenda-export-html-style
14863 (string-match "<style>" org-agenda-export-html-style))
14864 ;; replace <style> section with org-agenda-export-html-style
14865 (goto-char (point-min))
14866 (kill-region (- (search-forward "<style") 6)
14867 (search-forward "</style>"))
14868 (insert org-agenda-export-html-style))
14869 (write-file file)
14870 (kill-buffer (current-buffer))
14871 (message "HTML written to %s" file))
14872 ((string-match "\\.ps\\'" file)
14873 (ps-print-buffer-with-faces file)
14874 (message "Postscript written to %s" file))
14876 (let ((bs (buffer-string)))
14877 (find-file file)
14878 (insert bs)
14879 (save-buffer 0)
14880 (kill-buffer (current-buffer))
14881 (message "Plain text written to %s" file))))))
14882 (set-buffer org-agenda-buffer-name)))
14884 (defmacro org-no-read-only (&rest body)
14885 "Inhibit read-only for BODY."
14886 `(let ((inhibit-read-only t)) ,@body))
14888 (defun org-check-for-org-mode ()
14889 "Make sure current buffer is in org-mode. Error if not."
14890 (or (org-mode-p)
14891 (error "Cannot execute org-mode agenda command on buffer in %s."
14892 major-mode)))
14894 (defun org-fit-agenda-window ()
14895 "Fit the window to the buffer size."
14896 (and (memq org-agenda-window-setup '(reorganize-frame))
14897 (fboundp 'fit-window-to-buffer)
14898 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
14899 (/ (frame-height) 2))))
14901 ;;; Agenda file list
14903 (defun org-agenda-files (&optional unrestricted)
14904 "Get the list of agenda files.
14905 Optional UNRESTRICTED means return the full list even if a restriction
14906 is currently in place."
14907 (cond
14908 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14909 ((stringp org-agenda-files) (org-read-agenda-file-list))
14910 ((listp org-agenda-files) org-agenda-files)
14911 (t (error "Invalid value of `org-agenda-files'"))))
14913 (defun org-edit-agenda-file-list ()
14914 "Edit the list of agenda files.
14915 Depending on setup, this either uses customize to edit the variable
14916 `org-agenda-files', or it visits the file that is holding the list. In the
14917 latter case, the buffer is set up in a way that saving it automatically kills
14918 the buffer and restores the previous window configuration."
14919 (interactive)
14920 (if (stringp org-agenda-files)
14921 (let ((cw (current-window-configuration)))
14922 (find-file org-agenda-files)
14923 (org-set-local 'org-window-configuration cw)
14924 (org-add-hook 'after-save-hook
14925 (lambda ()
14926 (set-window-configuration
14927 (prog1 org-window-configuration
14928 (kill-buffer (current-buffer))))
14929 (org-install-agenda-files-menu)
14930 (message "New agenda file list installed"))
14931 nil 'local)
14932 (message (substitute-command-keys
14933 "Edit list and finish with \\[save-buffer]")))
14934 (customize-variable 'org-agenda-files)))
14936 (defun org-store-new-agenda-file-list (list)
14937 "Set new value for the agenda file list and save it correcly."
14938 (if (stringp org-agenda-files)
14939 (let ((f org-agenda-files) b)
14940 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14941 (with-temp-file f
14942 (insert (mapconcat 'identity list "\n") "\n")))
14943 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
14944 (setq org-agenda-files list)
14945 (customize-save-variable 'org-agenda-files org-agenda-files))))
14947 (defun org-read-agenda-file-list ()
14948 "Read the list of agenda files from a file."
14949 (when (stringp org-agenda-files)
14950 (with-temp-buffer
14951 (insert-file-contents org-agenda-files)
14952 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14955 ;;;###autoload
14956 (defun org-cycle-agenda-files ()
14957 "Cycle through the files in `org-agenda-files'.
14958 If the current buffer visits an agenda file, find the next one in the list.
14959 If the current buffer does not, find the first agenda file."
14960 (interactive)
14961 (let* ((fs (org-agenda-files t))
14962 (files (append fs (list (car fs))))
14963 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14964 file)
14965 (unless files (error "No agenda files"))
14966 (catch 'exit
14967 (while (setq file (pop files))
14968 (if (equal (file-truename file) tcf)
14969 (when (car files)
14970 (find-file (car files))
14971 (throw 'exit t))))
14972 (find-file (car fs)))
14973 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14975 (defun org-agenda-file-to-front (&optional to-end)
14976 "Move/add the current file to the top of the agenda file list.
14977 If the file is not present in the list, it is added to the front. If it is
14978 present, it is moved there. With optional argument TO-END, add/move to the
14979 end of the list."
14980 (interactive "P")
14981 (let ((file-alist (mapcar (lambda (x)
14982 (cons (file-truename x) x))
14983 (org-agenda-files t)))
14984 (ctf (file-truename buffer-file-name))
14985 x had)
14986 (setq x (assoc ctf file-alist) had x)
14988 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14989 (if to-end
14990 (setq file-alist (append (delq x file-alist) (list x)))
14991 (setq file-alist (cons x (delq x file-alist))))
14992 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14993 (org-install-agenda-files-menu)
14994 (message "File %s to %s of agenda file list"
14995 (if had "moved" "added") (if to-end "end" "front"))))
14997 (defun org-remove-file (&optional file)
14998 "Remove current file from the list of files in variable `org-agenda-files'.
14999 These are the files which are being checked for agenda entries.
15000 Optional argument FILE means, use this file instead of the current."
15001 (interactive)
15002 (let* ((file (or file buffer-file-name))
15003 (true-file (file-truename file))
15004 (afile (abbreviate-file-name file))
15005 (files (delq nil (mapcar
15006 (lambda (x)
15007 (if (equal true-file
15008 (file-truename x))
15009 nil x))
15010 (org-agenda-files t)))))
15011 (if (not (= (length files) (length (org-agenda-files t))))
15012 (progn
15013 (org-store-new-agenda-file-list files)
15014 (org-install-agenda-files-menu)
15015 (message "Removed file: %s" afile))
15016 (message "File was not in list: %s" afile))))
15018 (defun org-file-menu-entry (file)
15019 (vector file (list 'find-file file) t))
15021 (defun org-check-agenda-file (file)
15022 "Make sure FILE exists. If not, ask user what to do."
15023 (when (not (file-exists-p file))
15024 (message "non-existent file %s. [R]emove from list or [A]bort?"
15025 (abbreviate-file-name file))
15026 (let ((r (downcase (read-char-exclusive))))
15027 (cond
15028 ((equal r ?r)
15029 (org-remove-file file)
15030 (throw 'nextfile t))
15031 (t (error "Abort"))))))
15033 ;;; Agenda prepare and finalize
15035 (defvar org-agenda-multi nil) ; dynammically scoped
15036 (defvar org-agenda-buffer-name "*Org Agenda*")
15037 (defvar org-pre-agenda-window-conf nil)
15038 (defvar org-agenda-name nil)
15039 (defun org-prepare-agenda (&optional name)
15040 (setq org-todo-keywords-for-agenda nil)
15041 (setq org-done-keywords-for-agenda nil)
15042 (if org-agenda-multi
15043 (progn
15044 (setq buffer-read-only nil)
15045 (goto-char (point-max))
15046 (unless (= (point) 1)
15047 (insert "\n" (make-string (window-width) ?=) "\n"))
15048 (narrow-to-region (point) (point-max)))
15049 (org-agenda-maybe-reset-markers 'force)
15050 (org-prepare-agenda-buffers (org-agenda-files))
15051 (setq org-todo-keywords-for-agenda
15052 (org-uniquify org-todo-keywords-for-agenda))
15053 (setq org-done-keywords-for-agenda
15054 (org-uniquify org-done-keywords-for-agenda))
15055 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
15056 (awin (get-buffer-window abuf)))
15057 (cond
15058 ((equal (current-buffer) abuf) nil)
15059 (awin (select-window awin))
15060 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
15061 ((equal org-agenda-window-setup 'current-window)
15062 (switch-to-buffer abuf))
15063 ((equal org-agenda-window-setup 'other-window)
15064 (switch-to-buffer-other-window abuf))
15065 ((equal org-agenda-window-setup 'other-frame)
15066 (switch-to-buffer-other-frame abuf))
15067 ((equal org-agenda-window-setup 'reorganize-frame)
15068 (delete-other-windows)
15069 (switch-to-buffer-other-window abuf))))
15070 (setq buffer-read-only nil)
15071 (erase-buffer)
15072 (org-agenda-mode)
15073 (and name (not org-agenda-name)
15074 (org-set-local 'org-agenda-name name)))
15075 (setq buffer-read-only nil))
15077 (defun org-finalize-agenda ()
15078 "Finishing touch for the agenda buffer, called just before displaying it."
15079 (unless org-agenda-multi
15080 (org-agenda-align-tags)
15081 (save-excursion
15082 (let ((buffer-read-only))
15083 (goto-char (point-min))
15084 (while (org-activate-bracket-links (point-max))
15085 (add-text-properties (match-beginning 0) (match-end 0)
15086 '(face org-link)))
15087 (unless org-agenda-with-colors
15088 (remove-text-properties (point-min) (point-max) '(face nil))))
15089 (run-hooks 'org-finalize-agenda-hook))))
15091 (defun org-prepare-agenda-buffers (files)
15092 "Create buffers for all agenda files, protect archived trees and comments."
15093 (interactive)
15094 (let ((pa '(:org-archived t))
15095 (pc '(:org-comment t))
15096 (pall '(:org-archived t :org-comment t))
15097 (rea (concat ":" org-archive-tag ":"))
15098 bmp file re)
15099 (save-excursion
15100 (save-restriction
15101 (while (setq file (pop files))
15102 (org-check-agenda-file file)
15103 (set-buffer (org-get-agenda-file-buffer file))
15104 (widen)
15105 (setq bmp (buffer-modified-p))
15106 (setq org-todo-keywords-for-agenda
15107 (append org-todo-keywords-for-agenda org-todo-keywords-1))
15108 (setq org-done-keywords-for-agenda
15109 (append org-done-keywords-for-agenda org-done-keywords))
15110 (save-excursion
15111 (remove-text-properties (point-min) (point-max) pall)
15112 (when org-agenda-skip-archived-trees
15113 (goto-char (point-min))
15114 (while (re-search-forward rea nil t)
15115 (if (org-on-heading-p t)
15116 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
15117 (goto-char (point-min))
15118 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
15119 (while (re-search-forward re nil t)
15120 (add-text-properties
15121 (match-beginning 0) (org-end-of-subtree t) pc)))
15122 (set-buffer-modified-p bmp))))))
15124 (defvar org-agenda-skip-function nil
15125 "Function to be called at each match during agenda construction.
15126 If this function return nil, the current match should not be skipped.
15127 Otherwise, the function must return a position from where the search
15128 should be continued.
15129 Never set this variable using `setq' or so, because then it will apply
15130 to all future agenda commands. Instead, bind it with `let' to scope
15131 it dynamically into the agenda-constructing command.")
15133 (defun org-agenda-skip ()
15134 "Throw to `:skip' in places that should be skipped.
15135 Also moves point to the end of the skipped region, so that search can
15136 continue from there."
15137 (let ((p (point-at-bol)) to)
15138 (and org-agenda-skip-archived-trees
15139 (get-text-property p :org-archived)
15140 (org-end-of-subtree t)
15141 (throw :skip t))
15142 (and (get-text-property p :org-comment)
15143 (org-end-of-subtree t)
15144 (throw :skip t))
15145 (if (equal (char-after p) ?#) (throw :skip t))
15146 (when (and (functionp org-agenda-skip-function)
15147 (setq to (save-excursion
15148 (save-match-data
15149 (funcall org-agenda-skip-function)))))
15150 (goto-char to)
15151 (throw :skip t))))
15153 (defvar org-agenda-markers nil
15154 "List of all currently active markers created by `org-agenda'.")
15155 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
15156 "Creation time of the last agenda marker.")
15158 (defun org-agenda-new-marker (&optional pos)
15159 "Return a new agenda marker.
15160 Org-mode keeps a list of these markers and resets them when they are
15161 no longer in use."
15162 (let ((m (copy-marker (or pos (point)))))
15163 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
15164 (push m org-agenda-markers)
15167 (defun org-agenda-maybe-reset-markers (&optional force)
15168 "Reset markers created by `org-agenda'. But only if they are old enough."
15169 (if (or (and force (not org-agenda-multi))
15170 (> (- (time-to-seconds (current-time))
15171 org-agenda-last-marker-time)
15173 (while org-agenda-markers
15174 (move-marker (pop org-agenda-markers) nil))))
15176 (defvar org-agenda-new-buffers nil
15177 "Buffers created to visit agenda files.")
15179 (defun org-get-agenda-file-buffer (file)
15180 "Get a buffer visiting FILE. If the buffer needs to be created, add
15181 it to the list of buffers which might be released later."
15182 (let ((buf (org-find-base-buffer-visiting file)))
15183 (if buf
15184 buf ; just return it
15185 ;; Make a new buffer and remember it
15186 (setq buf (find-file-noselect file))
15187 (if buf (push buf org-agenda-new-buffers))
15188 buf)))
15190 (defun org-release-buffers (blist)
15191 "Release all buffers in list, asking the user for confirmation when needed.
15192 When a buffer is unmodified, it is just killed. When modified, it is saved
15193 \(if the user agrees) and then killed."
15194 (let (buf file)
15195 (while (setq buf (pop blist))
15196 (setq file (buffer-file-name buf))
15197 (when (and (buffer-modified-p buf)
15198 file
15199 (y-or-n-p (format "Save file %s? " file)))
15200 (with-current-buffer buf (save-buffer)))
15201 (kill-buffer buf))))
15203 (defvar org-category-table nil)
15204 (defun org-get-category-table ()
15205 "Get the table of categories and positions in current buffer."
15206 (let (tbl)
15207 (save-excursion
15208 (save-restriction
15209 (widen)
15210 (goto-char (point-min))
15211 (while (re-search-forward "^#\\+CATEGORY:[ \t]*\\(.*\\)"
15212 nil t)
15213 (push (cons (match-beginning 1)
15214 (org-trim (match-string 1))) tbl))))
15215 tbl))
15217 (defun org-get-category (&optional pos)
15218 "Get the category applying to position POS."
15219 (if (not org-category-table)
15220 (cond
15221 ((null org-category)
15222 (setq org-category
15223 (if buffer-file-name
15224 (file-name-sans-extension
15225 (file-name-nondirectory buffer-file-name))
15226 "???")))
15227 ((symbolp org-category) (symbol-name org-category))
15228 (t org-category))
15229 (let ((tbl org-category-table)
15230 (pos (or pos (point))))
15231 (while (and tbl (> (caar tbl) pos))
15232 (pop tbl))
15233 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
15234 org-category-table))))))
15235 ;;; Agenda timeline
15237 (defun org-timeline (&optional include-all)
15238 "Show a time-sorted view of the entries in the current org file.
15239 Only entries with a time stamp of today or later will be listed. With
15240 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
15241 under the current date.
15242 If the buffer contains an active region, only check the region for
15243 dates."
15244 (interactive "P")
15245 (require 'calendar)
15246 (org-compile-prefix-format 'timeline)
15247 (org-set-sorting-strategy 'timeline)
15248 (let* ((dopast t)
15249 (dotodo include-all)
15250 (doclosed org-agenda-show-log)
15251 (entry buffer-file-name)
15252 (date (calendar-current-date))
15253 (beg (if (org-region-active-p) (region-beginning) (point-min)))
15254 (end (if (org-region-active-p) (region-end) (point-max)))
15255 (day-numbers (org-get-all-dates beg end 'no-ranges
15256 t doclosed ; always include today
15257 org-timeline-show-empty-dates))
15258 (today (time-to-days (current-time)))
15259 (past t)
15260 args
15261 s e rtn d emptyp)
15262 (setq org-agenda-redo-command
15263 (list 'progn
15264 (list 'switch-to-buffer-other-window (current-buffer))
15265 (list 'org-timeline (list 'quote include-all))))
15266 (if (not dopast)
15267 ;; Remove past dates from the list of dates.
15268 (setq day-numbers (delq nil (mapcar (lambda(x)
15269 (if (>= x today) x nil))
15270 day-numbers))))
15271 (org-prepare-agenda (concat "Timeline "
15272 (file-name-nondirectory buffer-file-name)))
15273 (if doclosed (push :closed args))
15274 (push :timestamp args)
15275 (push :sexp args)
15276 (if dotodo (push :todo args))
15277 (while (setq d (pop day-numbers))
15278 (if (and (listp d) (eq (car d) :omitted))
15279 (progn
15280 (setq s (point))
15281 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
15282 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
15283 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
15284 (if (and (>= d today)
15285 dopast
15286 past)
15287 (progn
15288 (setq past nil)
15289 (insert (make-string 79 ?-) "\n")))
15290 (setq date (calendar-gregorian-from-absolute d))
15291 (setq s (point))
15292 (setq rtn (and (not emptyp)
15293 (apply 'org-agenda-get-day-entries
15294 entry date args)))
15295 (if (or rtn (equal d today) org-timeline-show-empty-dates)
15296 (progn
15297 (insert (calendar-day-name date) " "
15298 (number-to-string (extract-calendar-day date)) " "
15299 (calendar-month-name (extract-calendar-month date)) " "
15300 (number-to-string (extract-calendar-year date)) "\n")
15301 ; FIXME: this gives a timezone problem
15302 ; (insert (format-time-string org-agenda-date-format
15303 ; (calendar-time-from-absolute d 0))
15304 ; "\n")
15305 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
15306 (put-text-property s (1- (point)) 'org-date-line t)
15307 (if (equal d today)
15308 (put-text-property s (1- (point)) 'org-today t))
15309 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
15310 (put-text-property s (1- (point)) 'day d)))))
15311 (goto-char (point-min))
15312 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
15313 (point-min)))
15314 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
15315 (org-finalize-agenda)
15316 (setq buffer-read-only t)))
15318 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
15319 "Return a list of all relevant day numbers from BEG to END buffer positions.
15320 If NO-RANGES is non-nil, include only the start and end dates of a range,
15321 not every single day in the range. If FORCE-TODAY is non-nil, make
15322 sure that TODAY is included in the list. If INACTIVE is non-nil, also
15323 inactive time stamps (those in square brackets) are included.
15324 When EMPTY is non-nil, also include days without any entries."
15325 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
15326 dates dates1 date day day1 day2 ts1 ts2)
15327 (if force-today
15328 (setq dates (list (time-to-days (current-time)))))
15329 (save-excursion
15330 (goto-char beg)
15331 (while (re-search-forward re end t)
15332 (setq day (time-to-days (org-time-string-to-time
15333 (substring (match-string 1) 0 10))))
15334 (or (memq day dates) (push day dates)))
15335 (unless no-ranges
15336 (goto-char beg)
15337 (while (re-search-forward org-tr-regexp end t)
15338 (setq ts1 (substring (match-string 1) 0 10)
15339 ts2 (substring (match-string 2) 0 10)
15340 day1 (time-to-days (org-time-string-to-time ts1))
15341 day2 (time-to-days (org-time-string-to-time ts2)))
15342 (while (< (setq day1 (1+ day1)) day2)
15343 (or (memq day1 dates) (push day1 dates)))))
15344 (setq dates (sort dates '<))
15345 (when empty
15346 (while (setq day (pop dates))
15347 (setq day2 (car dates))
15348 (push day dates1)
15349 (when (and day2 empty)
15350 (if (or (eq empty t)
15351 (and (numberp empty) (<= (- day2 day) empty)))
15352 (while (< (setq day (1+ day)) day2)
15353 (push (list day) dates1))
15354 (push (cons :omitted (- day2 day)) dates1))))
15355 (setq dates (nreverse dates1)))
15356 dates)))
15358 ;;; Agenda Daily/Weekly
15360 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
15361 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
15362 (defvar org-agenda-last-arguments nil
15363 "The arguments of the previous call to org-agenda")
15364 (defvar org-starting-day nil) ; local variable in the agenda buffer
15365 (defvar org-include-all-loc nil) ; local variable
15368 ;;;###autoload
15369 (defun org-agenda-list (&optional include-all start-day ndays)
15370 "Produce a weekly view from all files in variable `org-agenda-files'.
15371 The view will be for the current week, but from the overview buffer you
15372 will be able to go to other weeks.
15373 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
15374 also be shown, under the current date.
15375 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
15376 on the days are also shown. See the variable `org-log-done' for how
15377 to turn on logging.
15378 START-DAY defaults to TODAY, or to the most recent match for the weekday
15379 given in `org-agenda-start-on-weekday'.
15380 NDAYS defaults to `org-agenda-ndays'."
15381 (interactive "P")
15382 (setq ndays (or ndays org-agenda-ndays)
15383 start-day (or start-day org-agenda-start-day))
15384 (if org-agenda-overriding-arguments
15385 (setq include-all (car org-agenda-overriding-arguments)
15386 start-day (nth 1 org-agenda-overriding-arguments)
15387 ndays (nth 2 org-agenda-overriding-arguments)))
15388 (if (stringp start-day)
15389 ;; Convert to an absolute day number
15390 (setq start-day (time-to-days (org-read-date nil t start-day))))
15391 (setq org-agenda-last-arguments (list include-all start-day ndays))
15392 (org-compile-prefix-format 'agenda)
15393 (org-set-sorting-strategy 'agenda)
15394 (require 'calendar)
15395 (let* ((org-agenda-start-on-weekday
15396 (if (or (equal ndays 1)
15397 (and (null ndays) (equal 1 org-agenda-ndays)))
15398 nil org-agenda-start-on-weekday))
15399 (thefiles (org-agenda-files))
15400 (files thefiles)
15401 (today (time-to-days (current-time)))
15402 (sd (or start-day today))
15403 (start (if (or (null org-agenda-start-on-weekday)
15404 (< org-agenda-ndays 7))
15406 (let* ((nt (calendar-day-of-week
15407 (calendar-gregorian-from-absolute sd)))
15408 (n1 org-agenda-start-on-weekday)
15409 (d (- nt n1)))
15410 (- sd (+ (if (< d 0) 7 0) d)))))
15411 (day-numbers (list start))
15412 (inhibit-redisplay (not debug-on-error))
15413 s e rtn rtnall file date d start-pos end-pos todayp nd)
15414 (setq org-agenda-redo-command
15415 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
15416 ;; Make the list of days
15417 (setq ndays (or ndays org-agenda-ndays)
15418 nd ndays)
15419 (while (> ndays 1)
15420 (push (1+ (car day-numbers)) day-numbers)
15421 (setq ndays (1- ndays)))
15422 (setq day-numbers (nreverse day-numbers))
15423 (org-prepare-agenda "Day/Week")
15424 (org-set-local 'org-starting-day (car day-numbers))
15425 (org-set-local 'org-include-all-loc include-all)
15426 (when (and (or include-all org-agenda-include-all-todo)
15427 (member today day-numbers))
15428 (setq files thefiles
15429 rtnall nil)
15430 (while (setq file (pop files))
15431 (catch 'nextfile
15432 (org-check-agenda-file file)
15433 (setq date (calendar-gregorian-from-absolute today)
15434 rtn (org-agenda-get-day-entries
15435 file date :todo))
15436 (setq rtnall (append rtnall rtn))))
15437 (when rtnall
15438 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
15439 (add-text-properties (point-min) (1- (point))
15440 (list 'face 'org-agenda-structure))
15441 (insert (org-finalize-agenda-entries rtnall) "\n")))
15442 (setq s (point))
15443 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
15444 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
15445 'org-date-line t))
15446 (while (setq d (pop day-numbers))
15447 (setq date (calendar-gregorian-from-absolute d)
15448 s (point))
15449 (if (or (setq todayp (= d today))
15450 (and (not start-pos) (= d sd)))
15451 (setq start-pos (point))
15452 (if (and start-pos (not end-pos))
15453 (setq end-pos (point))))
15454 (setq files thefiles
15455 rtnall nil)
15456 (while (setq file (pop files))
15457 (catch 'nextfile
15458 (org-check-agenda-file file)
15459 (if org-agenda-show-log
15460 (setq rtn (org-agenda-get-day-entries
15461 file date
15462 :deadline :scheduled :timestamp :sexp :closed))
15463 (setq rtn (org-agenda-get-day-entries
15464 file date
15465 :deadline :scheduled :sexp :timestamp)))
15466 (setq rtnall (append rtnall rtn))))
15467 (if org-agenda-include-diary
15468 (progn
15469 (require 'diary-lib)
15470 (setq rtn (org-get-entries-from-diary date))
15471 (setq rtnall (append rtnall rtn))))
15472 (if (or rtnall org-agenda-show-all-dates)
15473 (progn
15474 (insert (format "%-9s %2d %s %4d\n"
15475 (calendar-day-name date)
15476 (extract-calendar-day date)
15477 (calendar-month-name (extract-calendar-month date))
15478 (extract-calendar-year date)))
15479 ; FIXME: this gives a timezone problem
15480 ; (insert (format-time-string org-agenda-date-format
15481 ; (calendar-time-from-absolute d 0)) "\n")
15482 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
15483 (put-text-property s (1- (point)) 'org-date-line t)
15484 (if todayp (put-text-property s (1- (point)) 'org-today t))
15485 (if rtnall (insert
15486 (org-finalize-agenda-entries
15487 (org-agenda-add-time-grid-maybe
15488 rtnall nd todayp))
15489 "\n"))
15490 (put-text-property s (1- (point)) 'day d))))
15491 (goto-char (point-min))
15492 (org-fit-agenda-window)
15493 (unless (and (pos-visible-in-window-p (point-min))
15494 (pos-visible-in-window-p (point-max)))
15495 (goto-char (1- (point-max)))
15496 (recenter -1)
15497 (if (not (pos-visible-in-window-p (or start-pos 1)))
15498 (progn
15499 (goto-char (or start-pos 1))
15500 (recenter 1))))
15501 (goto-char (or start-pos 1))
15502 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
15503 (org-finalize-agenda)
15504 (setq buffer-read-only t)
15505 (message "")))
15507 ;;; Agenda TODO list
15509 (defvar org-select-this-todo-keyword nil)
15510 (defvar org-last-arg nil)
15512 ;;;###autoload
15513 (defun org-todo-list (arg)
15514 "Show all TODO entries from all agenda file in a single list.
15515 The prefix arg can be used to select a specific TODO keyword and limit
15516 the list to these. When using \\[universal-argument], you will be prompted
15517 for a keyword. A numeric prefix directly selects the Nth keyword in
15518 `org-todo-keywords-1'."
15519 (interactive "P")
15520 (require 'calendar)
15521 (org-compile-prefix-format 'todo)
15522 (org-set-sorting-strategy 'todo)
15523 (org-prepare-agenda "TODO")
15524 (let* ((today (time-to-days (current-time)))
15525 (date (calendar-gregorian-from-absolute today))
15526 (kwds org-todo-keywords-for-agenda)
15527 (completion-ignore-case t)
15528 (org-select-this-todo-keyword
15529 (if (stringp arg) arg
15530 (and arg (integerp arg) (> arg 0)
15531 (nth (1- arg) kwds))))
15532 rtn rtnall files file pos)
15533 (when (equal arg '(4))
15534 (setq org-select-this-todo-keyword
15535 (completing-read "Keyword (or KWD1|K2D2|...): "
15536 (mapcar 'list kwds) nil nil)))
15537 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
15538 (org-set-local 'org-last-arg arg)
15539 ;FIXME (org-set-local 'org-todo-keywords-for-agenda kwds)
15540 (setq org-agenda-redo-command
15541 '(org-todo-list (or current-prefix-arg org-last-arg)))
15542 (setq files (org-agenda-files)
15543 rtnall nil)
15544 (while (setq file (pop files))
15545 (catch 'nextfile
15546 (org-check-agenda-file file)
15547 (setq rtn (org-agenda-get-day-entries file date :todo))
15548 (setq rtnall (append rtnall rtn))))
15549 (if org-agenda-overriding-header
15550 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
15551 nil 'face 'org-agenda-structure) "\n")
15552 (insert "Global list of TODO items of type: ")
15553 (add-text-properties (point-min) (1- (point))
15554 (list 'face 'org-agenda-structure))
15555 (setq pos (point))
15556 (insert (or org-select-this-todo-keyword "ALL") "\n")
15557 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
15558 (setq pos (point))
15559 (unless org-agenda-multi
15560 (insert "Available with `N r': (0)ALL")
15561 (let ((n 0) s)
15562 (mapc (lambda (x)
15563 (setq s (format "(%d)%s" (setq n (1+ n)) x))
15564 (if (> (+ (current-column) (string-width s) 1) (frame-width))
15565 (insert "\n "))
15566 (insert " " s))
15567 kwds))
15568 (insert "\n"))
15569 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
15570 (when rtnall
15571 (insert (org-finalize-agenda-entries rtnall) "\n"))
15572 (goto-char (point-min))
15573 (org-fit-agenda-window)
15574 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
15575 (org-finalize-agenda)
15576 (setq buffer-read-only t)))
15578 ;;; Agenda tags match
15580 ;;;###autoload
15581 (defun org-tags-view (&optional todo-only match)
15582 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
15583 The prefix arg TODO-ONLY limits the search to TODO entries."
15584 (interactive "P")
15585 (org-compile-prefix-format 'tags)
15586 (org-set-sorting-strategy 'tags)
15587 (let* ((org-tags-match-list-sublevels
15588 (if todo-only t org-tags-match-list-sublevels))
15589 (completion-ignore-case t)
15590 rtn rtnall files file pos matcher
15591 buffer)
15592 (setq matcher (org-make-tags-matcher match)
15593 match (car matcher) matcher (cdr matcher))
15594 (org-prepare-agenda (concat "TAGS " match))
15595 (setq org-agenda-redo-command
15596 (list 'org-tags-view (list 'quote todo-only)
15597 (list 'if 'current-prefix-arg nil match)))
15598 (setq files (org-agenda-files)
15599 rtnall nil)
15600 (while (setq file (pop files))
15601 (catch 'nextfile
15602 (org-check-agenda-file file)
15603 (setq buffer (if (file-exists-p file)
15604 (org-get-agenda-file-buffer file)
15605 (error "No such file %s" file)))
15606 (if (not buffer)
15607 ;; If file does not exist, merror message to agenda
15608 (setq rtn (list
15609 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
15610 rtnall (append rtnall rtn))
15611 (with-current-buffer buffer
15612 (unless (org-mode-p)
15613 (error "Agenda file %s is not in `org-mode'" file))
15614 (setq org-category-table (org-get-category-table))
15615 (save-excursion
15616 (save-restriction
15617 (if org-agenda-restrict
15618 (narrow-to-region org-agenda-restrict-begin
15619 org-agenda-restrict-end)
15620 (widen))
15621 (setq rtn (org-scan-tags 'agenda matcher todo-only))
15622 (setq rtnall (append rtnall rtn))))))))
15623 (if org-agenda-overriding-header
15624 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
15625 nil 'face 'org-agenda-structure) "\n")
15626 (insert "Headlines with TAGS match: ")
15627 (add-text-properties (point-min) (1- (point))
15628 (list 'face 'org-agenda-structure))
15629 (setq pos (point))
15630 (insert match "\n")
15631 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
15632 (setq pos (point))
15633 (unless org-agenda-multi
15634 (insert "Press `C-u r' to search again with new search string\n"))
15635 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
15636 (when rtnall
15637 (insert (org-finalize-agenda-entries rtnall) "\n"))
15638 (goto-char (point-min))
15639 (org-fit-agenda-window)
15640 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
15641 (org-finalize-agenda)
15642 (setq buffer-read-only t)))
15644 ;;; Agenda Finding stuck projects
15646 (defvar org-agenda-skip-regexp nil
15647 "Regular expression used in skipping subtrees for the agenda.
15648 This is basically a temporary global variable that can be set and then
15649 used by user-defined selections using `org-agenda-skip-function'.")
15651 (defvar org-agenda-overriding-header nil
15652 "When this is set during todo and tags searches, will replace header.")
15654 (defun org-agenda-skip-subtree-when-regexp-matches ()
15655 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
15656 If yes, it returns the end position of this tree, causing agenda commands
15657 to skip this subtree. This is a function that can be put into
15658 `org-agenda-skip-function' for the duration of a command."
15659 (save-match-data
15660 (let ((end (save-excursion (org-end-of-subtree t)))
15661 skip)
15662 (save-excursion
15663 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
15664 (and skip end))))
15666 (defun org-agenda-list-stuck-projects (&rest ignore)
15667 "Create agenda view for projects that are stuck.
15668 Stuck projects are project that have no next actions. For the definitions
15669 of what a project is and how to check if it stuck, customize the variable
15670 `org-stuck-projects'.
15671 MATCH is being ignored."
15672 (interactive)
15673 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
15674 (org-agenda-overriding-header "List of stuck projects: ")
15675 (matcher (nth 0 org-stuck-projects))
15676 (todo (nth 1 org-stuck-projects))
15677 (todo-wds (if (member "*" todo)
15678 (progn
15679 (org-prepare-agenda-buffers (org-agenda-files))
15680 (org-delete-all
15681 org-done-keywords-for-agenda
15682 (copy-sequence org-todo-keywords-for-agenda)))
15683 todo))
15684 (todo-re (concat "^\\*+[ \t]+\\("
15685 (mapconcat 'identity todo-wds "\\|")
15686 "\\)\\>"))
15687 (tags (nth 2 org-stuck-projects))
15688 (tags-re (if (member "*" tags)
15689 "^\\*+.*:[a-zA-Z0-9_@]+:[ \t]*$"
15690 (concat "^\\*+.*:\\("
15691 (mapconcat 'identity tags "\\|")
15692 "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
15693 (gen-re (nth 3 org-stuck-projects))
15694 (re-list
15695 (delq nil
15696 (list
15697 (if todo todo-re)
15698 (if tags tags-re)
15699 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
15700 gen-re)))))
15701 (setq org-agenda-skip-regexp
15702 (if re-list
15703 (mapconcat 'identity re-list "\\|")
15704 (error "No information how to identify unstuck projects")))
15705 (org-tags-view nil matcher)
15706 (with-current-buffer org-agenda-buffer-name
15707 (setq org-agenda-redo-command
15708 '(org-agenda-list-stuck-projects
15709 (or current-prefix-arg org-last-arg))))))
15711 ;;; Diary integration
15713 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
15715 (defun org-get-entries-from-diary (date)
15716 "Get the (Emacs Calendar) diary entries for DATE."
15717 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
15718 (diary-display-hook '(fancy-diary-display))
15719 (list-diary-entries-hook
15720 (cons 'org-diary-default-entry list-diary-entries-hook))
15721 (diary-file-name-prefix-function nil) ; turn this feature off
15722 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
15723 entries
15724 (org-disable-agenda-to-diary t))
15725 (save-excursion
15726 (save-window-excursion
15727 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
15728 (if (not (get-buffer fancy-diary-buffer))
15729 (setq entries nil)
15730 (with-current-buffer fancy-diary-buffer
15731 (setq buffer-read-only nil)
15732 (if (= (point-max) 1)
15733 ;; No entries
15734 (setq entries nil)
15735 ;; Omit the date and other unnecessary stuff
15736 (org-agenda-cleanup-fancy-diary)
15737 ;; Add prefix to each line and extend the text properties
15738 (if (= (point-max) 1)
15739 (setq entries nil)
15740 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
15741 (set-buffer-modified-p nil)
15742 (kill-buffer fancy-diary-buffer)))
15743 (when entries
15744 (setq entries (org-split-string entries "\n"))
15745 (setq entries
15746 (mapcar
15747 (lambda (x)
15748 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
15749 ;; Extend the text properties to the beginning of the line
15750 (org-add-props x (text-properties-at (1- (length x)) x)
15751 'type "diary" 'date date))
15752 entries)))))
15754 (defun org-agenda-cleanup-fancy-diary ()
15755 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
15756 This gets rid of the date, the underline under the date, and
15757 the dummy entry installed by `org-mode' to ensure non-empty diary for each
15758 date. It also removes lines that contain only whitespace."
15759 (goto-char (point-min))
15760 (if (looking-at ".*?:[ \t]*")
15761 (progn
15762 (replace-match "")
15763 (re-search-forward "\n=+$" nil t)
15764 (replace-match "")
15765 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
15766 (re-search-forward "\n=+$" nil t)
15767 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
15768 (goto-char (point-min))
15769 (while (re-search-forward "^ +\n" nil t)
15770 (replace-match ""))
15771 (goto-char (point-min))
15772 (if (re-search-forward "^Org-mode dummy\n?" nil t)
15773 (replace-match "")))
15775 ;; Make sure entries from the diary have the right text properties.
15776 (eval-after-load "diary-lib"
15777 '(if (boundp 'diary-modify-entry-list-string-function)
15778 ;; We can rely on the hook, nothing to do
15780 ;; Hook not avaiable, must use advice to make this work
15781 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
15782 "Make the position visible."
15783 (if (and org-disable-agenda-to-diary ;; called from org-agenda
15784 (stringp string)
15785 buffer-file-name)
15786 (setq string (org-modify-diary-entry-string string))))))
15788 (defun org-modify-diary-entry-string (string)
15789 "Add text properties to string, allowing org-mode to act on it."
15790 (org-add-props string nil
15791 'mouse-face 'highlight
15792 'keymap org-agenda-keymap
15793 'help-echo (if buffer-file-name
15794 (format "mouse-2 or RET jump to diary file %s"
15795 (abbreviate-file-name buffer-file-name))
15797 'org-agenda-diary-link t
15798 'org-marker (org-agenda-new-marker (point-at-bol))))
15800 (defun org-diary-default-entry ()
15801 "Add a dummy entry to the diary.
15802 Needed to avoid empty dates which mess up holiday display."
15803 ;; Catch the error if dealing with the new add-to-diary-alist
15804 (when org-disable-agenda-to-diary
15805 (condition-case nil
15806 (add-to-diary-list original-date "Org-mode dummy" "")
15807 (error
15808 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
15810 ;;;###autoload
15811 (defun org-diary (&rest args)
15812 "Return diary information from org-files.
15813 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
15814 It accesses org files and extracts information from those files to be
15815 listed in the diary. The function accepts arguments specifying what
15816 items should be listed. The following arguments are allowed:
15818 :timestamp List the headlines of items containing a date stamp or
15819 date range matching the selected date. Deadlines will
15820 also be listed, on the expiration day.
15822 :sexp FIXME
15824 :deadline List any deadlines past due, or due within
15825 `org-deadline-warning-days'. The listing occurs only
15826 in the diary for *today*, not at any other date. If
15827 an entry is marked DONE, it is no longer listed.
15829 :scheduled List all items which are scheduled for the given date.
15830 The diary for *today* also contains items which were
15831 scheduled earlier and are not yet marked DONE.
15833 :todo List all TODO items from the org-file. This may be a
15834 long list - so this is not turned on by default.
15835 Like deadlines, these entries only show up in the
15836 diary for *today*, not at any other date.
15838 The call in the diary file should look like this:
15840 &%%(org-diary) ~/path/to/some/orgfile.org
15842 Use a separate line for each org file to check. Or, if you omit the file name,
15843 all files listed in `org-agenda-files' will be checked automatically:
15845 &%%(org-diary)
15847 If you don't give any arguments (as in the example above), the default
15848 arguments (:deadline :scheduled :timestamp :sexp) are used.
15849 So the example above may also be written as
15851 &%%(org-diary :deadline :timestamp :sexp :scheduled)
15853 The function expects the lisp variables `entry' and `date' to be provided
15854 by the caller, because this is how the calendar works. Don't use this
15855 function from a program - use `org-agenda-get-day-entries' instead."
15856 (org-agenda-maybe-reset-markers)
15857 (org-compile-prefix-format 'agenda)
15858 (org-set-sorting-strategy 'agenda)
15859 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
15860 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
15861 (list entry)
15862 (org-agenda-files t)))
15863 file rtn results)
15864 (org-prepare-agenda-buffers files)
15865 ;; If this is called during org-agenda, don't return any entries to
15866 ;; the calendar. Org Agenda will list these entries itself.
15867 (if org-disable-agenda-to-diary (setq files nil))
15868 (while (setq file (pop files))
15869 (setq rtn (apply 'org-agenda-get-day-entries file date args))
15870 (setq results (append results rtn)))
15871 (if results
15872 (concat (org-finalize-agenda-entries results) "\n"))))
15874 ;;; Agenda entry finders
15876 (defun org-agenda-get-day-entries (file date &rest args)
15877 "Does the work for `org-diary' and `org-agenda'.
15878 FILE is the path to a file to be checked for entries. DATE is date like
15879 the one returned by `calendar-current-date'. ARGS are symbols indicating
15880 which kind of entries should be extracted. For details about these, see
15881 the documentation of `org-diary'."
15882 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
15883 (let* ((org-startup-folded nil)
15884 (org-startup-align-all-tables nil)
15885 (buffer (if (file-exists-p file)
15886 (org-get-agenda-file-buffer file)
15887 (error "No such file %s" file)))
15888 arg results rtn)
15889 (if (not buffer)
15890 ;; If file does not exist, make sure an error message ends up in diary
15891 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
15892 (with-current-buffer buffer
15893 (unless (org-mode-p)
15894 (error "Agenda file %s is not in `org-mode'" file))
15895 (setq org-category-table (org-get-category-table))
15896 (let ((case-fold-search nil))
15897 (save-excursion
15898 (save-restriction
15899 (if org-agenda-restrict
15900 (narrow-to-region org-agenda-restrict-begin
15901 org-agenda-restrict-end)
15902 (widen))
15903 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
15904 (while (setq arg (pop args))
15905 (cond
15906 ((and (eq arg :todo)
15907 (equal date (calendar-current-date)))
15908 (setq rtn (org-agenda-get-todos))
15909 (setq results (append results rtn)))
15910 ((eq arg :timestamp)
15911 (setq rtn (org-agenda-get-blocks))
15912 (setq results (append results rtn))
15913 (setq rtn (org-agenda-get-timestamps))
15914 (setq results (append results rtn)))
15915 ((eq arg :sexp)
15916 (setq rtn (org-agenda-get-sexps))
15917 (setq results (append results rtn)))
15918 ((eq arg :scheduled)
15919 (setq rtn (org-agenda-get-scheduled))
15920 (setq results (append results rtn)))
15921 ((eq arg :closed)
15922 (setq rtn (org-agenda-get-closed))
15923 (setq results (append results rtn)))
15924 ((and (eq arg :deadline)
15925 (equal date (calendar-current-date)))
15926 (setq rtn (org-agenda-get-deadlines))
15927 (setq results (append results rtn))))))))
15928 results))))
15930 (defun org-entry-is-done-p ()
15931 "Is the current entry marked DONE?"
15932 (save-excursion
15933 (and (re-search-backward "[\r\n]\\*" nil t)
15934 (looking-at org-nl-done-regexp))))
15936 (defun org-at-date-range-p (&optional inactive-ok)
15937 "Is the cursor inside a date range?"
15938 (interactive)
15939 (save-excursion
15940 (catch 'exit
15941 (let ((pos (point)))
15942 (skip-chars-backward "^[<\r\n")
15943 (skip-chars-backward "<[")
15944 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
15945 (>= (match-end 0) pos)
15946 (throw 'exit t))
15947 (skip-chars-backward "^<[\r\n")
15948 (skip-chars-backward "<[")
15949 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
15950 (>= (match-end 0) pos)
15951 (throw 'exit t)))
15952 nil)))
15954 (defun org-agenda-get-todos ()
15955 "Return the TODO information for agenda display."
15956 (let* ((props (list 'face nil
15957 'done-face 'org-done
15958 'org-not-done-regexp org-not-done-regexp
15959 'org-todo-regexp org-todo-regexp
15960 'mouse-face 'highlight
15961 'keymap org-agenda-keymap
15962 'help-echo
15963 (format "mouse-2 or RET jump to org file %s"
15964 (abbreviate-file-name buffer-file-name))))
15965 ;; FIXME: get rid of the \n at some point but watch out
15966 (regexp (concat "[\n\r]\\*+ *\\("
15967 (if org-select-this-todo-keyword
15968 (if (equal org-select-this-todo-keyword "*")
15969 org-todo-regexp
15970 (concat "\\<\\("
15971 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
15972 "\\)\\>"))
15973 org-not-done-regexp)
15974 "[^\n\r]*\\)"))
15975 marker priority category tags
15976 ee txt beg end)
15977 (goto-char (point-min))
15978 (while (re-search-forward regexp nil t)
15979 (catch :skip
15980 (save-match-data
15981 (beginning-of-line)
15982 (setq beg (point) end (progn (outline-next-heading) (point)))
15983 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
15984 (re-search-forward org-scheduled-time-regexp end t))
15985 (and org-agenda-todo-ignore-deadlines (goto-char beg)
15986 (re-search-forward org-deadline-time-regexp end t)
15987 (org-deadline-close (match-string 1))))
15988 (goto-char beg)
15989 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
15990 (throw :skip nil)))
15991 (goto-char beg)
15992 (org-agenda-skip)
15993 (goto-char (match-beginning 1))
15994 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
15995 category (org-get-category)
15996 tags (org-get-tags-at (point))
15997 txt (org-format-agenda-item "" (match-string 1) category tags)
15998 priority (1+ (org-get-priority txt)))
15999 (org-add-props txt props
16000 'org-marker marker 'org-hd-marker marker
16001 'priority priority 'org-category category
16002 'type "todo")
16003 (push txt ee)
16004 (if org-agenda-todo-list-sublevels
16005 (goto-char (match-end 1))
16006 (org-end-of-subtree 'invisible))))
16007 (nreverse ee)))
16009 (defconst org-agenda-no-heading-message
16010 "No heading for this item in buffer or region.")
16012 (defun org-agenda-get-timestamps ()
16013 "Return the date stamp information for agenda display."
16014 (let* ((props (list 'face nil
16015 'org-not-done-regexp org-not-done-regexp
16016 'org-todo-regexp org-todo-regexp
16017 'mouse-face 'highlight
16018 'keymap org-agenda-keymap
16019 'help-echo
16020 (format "mouse-2 or RET jump to org file %s"
16021 (abbreviate-file-name buffer-file-name))))
16022 ;???? (regexp (regexp-quote
16023 ; (substring
16024 ; (format-time-string
16025 ; (car org-time-stamp-formats)
16026 ; (apply 'encode-time ; DATE bound by calendar
16027 ; (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
16028 ; 0 11)))
16029 (d1 (calendar-absolute-from-gregorian date))
16030 (regexp
16031 (concat
16032 (regexp-quote
16033 (substring
16034 (format-time-string
16035 (car org-time-stamp-formats)
16036 (apply 'encode-time ; DATE bound by calendar
16037 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
16038 0 11))
16039 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
16040 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
16041 marker hdmarker deadlinep scheduledp donep tmp priority category
16042 ee txt timestr tags b0 b3 e3)
16043 (goto-char (point-min))
16044 (while (re-search-forward regexp nil t)
16045 (setq b0 (match-beginning 0)
16046 b3 (match-beginning 3) e3 (match-end 3))
16047 (catch :skip
16048 (and (org-at-date-range-p) (throw :skip nil))
16049 (org-agenda-skip)
16050 (if (and (match-end 1)
16051 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
16052 (throw :skip nil))
16053 (if (and e3
16054 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
16055 (throw :skip nil))
16056 (setq marker (org-agenda-new-marker b0)
16057 category (org-get-category b0)
16058 tmp (buffer-substring (max (point-min)
16059 (- b0 org-ds-keyword-length))
16061 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
16062 deadlinep (string-match org-deadline-regexp tmp)
16063 scheduledp (string-match org-scheduled-regexp tmp)
16064 donep (org-entry-is-done-p))
16065 (and org-agenda-skip-scheduled-if-done
16066 scheduledp donep
16067 (throw :skip t))
16068 (and org-agenda-skip-deadline-if-done
16069 deadlinep donep
16070 (throw :skip t))
16071 (if (string-match ">" timestr)
16072 ;; substring should only run to end of time stamp
16073 (setq timestr (substring timestr 0 (match-end 0))))
16074 (save-excursion
16075 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
16076 (progn
16077 (goto-char (match-end 1))
16078 (setq hdmarker (org-agenda-new-marker)
16079 tags (org-get-tags-at))
16080 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
16081 (setq txt (org-format-agenda-item
16082 (format "%s%s"
16083 (if deadlinep "Deadline: " "")
16084 (if scheduledp "Scheduled: " ""))
16085 (match-string 1) category tags timestr)))
16086 (setq txt org-agenda-no-heading-message))
16087 (setq priority (org-get-priority txt))
16088 (org-add-props txt props
16089 'org-marker marker 'org-hd-marker hdmarker)
16090 (if deadlinep
16091 (org-add-props txt nil
16092 'face (if donep 'org-done 'org-warning)
16093 'type "deadline" 'date date
16094 'undone-face 'org-warning 'done-face 'org-done
16095 'org-category category 'priority (+ 100 priority))
16096 (if scheduledp
16097 (org-add-props txt nil
16098 'face 'org-scheduled-today
16099 'type "scheduled" 'date date
16100 'undone-face 'org-scheduled-today 'done-face 'org-done
16101 'org-category category 'priority (+ 99 priority))
16102 (org-add-props txt nil 'priority priority
16103 'org-category category 'date date
16104 'type "timestamp")))
16105 (push txt ee))
16106 (outline-next-heading)))
16107 (nreverse ee)))
16109 (defun org-agenda-get-sexps ()
16110 "Return the sexp information for agenda display."
16111 (require 'diary-lib)
16112 (let* ((props (list 'face nil
16113 'mouse-face 'highlight
16114 'keymap org-agenda-keymap
16115 'help-echo
16116 (format "mouse-2 or RET jump to org file %s"
16117 (abbreviate-file-name buffer-file-name))))
16118 (regexp "^&?%%(")
16119 marker category ee txt tags entry result beg b sexp sexp-entry)
16120 (goto-char (point-min))
16121 (while (re-search-forward regexp nil t)
16122 (catch :skip
16123 (org-agenda-skip)
16124 (setq beg (match-beginning 0))
16125 (goto-char (1- (match-end 0)))
16126 (setq b (point))
16127 (forward-sexp 1)
16128 (setq sexp (buffer-substring b (point)))
16129 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
16130 (org-trim (match-string 1))
16131 ""))
16132 (setq result (org-diary-sexp-entry sexp sexp-entry date))
16133 (when result
16134 (setq marker (org-agenda-new-marker beg)
16135 category (org-get-category beg))
16137 (if (string-match "\\S-" result)
16138 (setq txt result)
16139 (setq txt "SEXP entry returned empty string"))
16141 (setq txt (org-format-agenda-item
16142 "" txt category tags 'time))
16143 (org-add-props txt props 'org-marker marker)
16144 (org-add-props txt nil
16145 'org-category category 'date date
16146 'type "sexp")
16147 (push txt ee))))
16148 (nreverse ee)))
16150 (defun org-agenda-get-closed ()
16151 "Return the logged TODO entries for agenda display."
16152 (let* ((props (list 'mouse-face 'highlight
16153 'org-not-done-regexp org-not-done-regexp
16154 'org-todo-regexp org-todo-regexp
16155 'keymap org-agenda-keymap
16156 'help-echo
16157 (format "mouse-2 or RET jump to org file %s"
16158 (abbreviate-file-name buffer-file-name))))
16159 (regexp (concat
16160 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
16161 (regexp-quote
16162 (substring
16163 (format-time-string
16164 (car org-time-stamp-formats)
16165 (apply 'encode-time ; DATE bound by calendar
16166 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
16167 1 11))))
16168 marker hdmarker priority category tags closedp
16169 ee txt timestr)
16170 (goto-char (point-min))
16171 (while (re-search-forward regexp nil t)
16172 (catch :skip
16173 (org-agenda-skip)
16174 (setq marker (org-agenda-new-marker (match-beginning 0))
16175 closedp (equal (match-string 1) org-closed-string)
16176 category (org-get-category (match-beginning 0))
16177 timestr (buffer-substring (match-beginning 0) (point-at-eol))
16178 ;; donep (org-entry-is-done-p)
16180 (if (string-match "\\]" timestr)
16181 ;; substring should only run to end of time stamp
16182 (setq timestr (substring timestr 0 (match-end 0))))
16183 (save-excursion
16184 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
16185 (progn
16186 (goto-char (match-end 1))
16187 (setq hdmarker (org-agenda-new-marker)
16188 tags (org-get-tags-at))
16189 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
16190 (setq txt (org-format-agenda-item
16191 (if closedp "Closed: " "Clocked: ")
16192 (match-string 1) category tags timestr)))
16193 (setq txt org-agenda-no-heading-message))
16194 (setq priority 100000)
16195 (org-add-props txt props
16196 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
16197 'priority priority 'org-category category
16198 'type "closed" 'date date
16199 'undone-face 'org-warning 'done-face 'org-done)
16200 (push txt ee))
16201 (outline-next-heading)))
16202 (nreverse ee)))
16204 (defun org-agenda-get-deadlines ()
16205 "Return the deadline information for agenda display."
16206 (let* ((wdays org-deadline-warning-days)
16207 (props (list 'mouse-face 'highlight
16208 'org-not-done-regexp org-not-done-regexp
16209 'org-todo-regexp org-todo-regexp
16210 'keymap org-agenda-keymap
16211 'help-echo
16212 (format "mouse-2 or RET jump to org file %s"
16213 (abbreviate-file-name buffer-file-name))))
16214 (regexp org-deadline-time-regexp)
16215 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
16216 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
16217 d2 diff pos pos1 category tags
16218 ee txt head face)
16219 (goto-char (point-min))
16220 (while (re-search-forward regexp nil t)
16221 (catch :skip
16222 (org-agenda-skip)
16223 (setq pos (1- (match-beginning 1))
16224 ;??? d2 (time-to-days
16225 ;??? (org-time-string-to-time (match-string 1)))
16226 d2 (org-time-string-to-absolute (match-string 1) d1)
16227 diff (- d2 d1))
16228 ;; When to show a deadline in the calendar:
16229 ;; If the expiration is within wdays warning time.
16230 ;; Past-due deadlines are only shown on the current date
16231 (if (and (< diff wdays) todayp (not (= diff 0)))
16232 (save-excursion
16233 (setq category (org-get-category))
16234 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
16235 (progn
16236 (goto-char (match-end 0))
16237 (setq pos1 (match-end 1))
16238 (setq tags (org-get-tags-at pos1))
16239 (setq head (buffer-substring-no-properties
16240 (point)
16241 (progn (skip-chars-forward "^\r\n")
16242 (point))))
16243 (if (string-match org-looking-at-done-regexp head)
16244 (setq txt nil)
16245 (setq txt (org-format-agenda-item
16246 (format "In %3d d.: " diff) head category tags))))
16247 (setq txt org-agenda-no-heading-message))
16248 (when txt
16249 (setq face (cond ((<= diff 0) 'org-warning)
16250 ((<= diff 5) 'org-upcoming-deadline)
16251 (t nil)))
16252 (org-add-props txt props
16253 'org-marker (org-agenda-new-marker pos)
16254 'org-hd-marker (org-agenda-new-marker pos1)
16255 'priority (+ (- 10 diff) (org-get-priority txt))
16256 'org-category category
16257 'type "upcoming-deadline" 'date d2
16258 'face face 'undone-face face 'done-face 'org-done)
16259 (push txt ee))))))
16260 ee))
16262 (defun org-agenda-get-scheduled ()
16263 "Return the scheduled information for agenda display."
16264 (let* ((props (list 'face 'org-scheduled-previously
16265 'org-not-done-regexp org-not-done-regexp
16266 'org-todo-regexp org-todo-regexp
16267 'undone-face 'org-scheduled-previously
16268 'done-face 'org-done
16269 'mouse-face 'highlight
16270 'keymap org-agenda-keymap
16271 'help-echo
16272 (format "mouse-2 or RET jump to org file %s"
16273 (abbreviate-file-name buffer-file-name))))
16274 (regexp org-scheduled-time-regexp)
16275 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
16276 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
16277 d2 diff pos pos1 category tags
16278 ee txt head)
16279 (goto-char (point-min))
16280 (while (re-search-forward regexp nil t)
16281 (catch :skip
16282 (org-agenda-skip)
16283 (setq pos (1- (match-beginning 1))
16284 d2 (org-time-string-to-absolute (match-string 1) d1)
16285 ;??? d2 (time-to-days
16286 ;??? (org-time-string-to-time (match-string 1)))
16287 diff (- d2 d1))
16288 ;; When to show a scheduled item in the calendar:
16289 ;; If it is on or past the date.
16290 (if (and (< diff 0) todayp)
16291 (save-excursion
16292 (setq category (org-get-category))
16293 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
16294 (progn
16295 (goto-char (match-end 0))
16296 (setq pos1 (match-end 1))
16297 (setq tags (org-get-tags-at))
16298 (setq head (buffer-substring-no-properties
16299 (point)
16300 (progn (skip-chars-forward "^\r\n") (point))))
16301 (if (string-match org-looking-at-done-regexp head)
16302 (setq txt nil)
16303 (setq txt (org-format-agenda-item
16304 (format "Sched.%2dx: " (- 1 diff)) head
16305 category tags))))
16306 (setq txt org-agenda-no-heading-message))
16307 (when txt
16308 (org-add-props txt props
16309 'org-marker (org-agenda-new-marker pos)
16310 'org-hd-marker (org-agenda-new-marker pos1)
16311 'type "past-scheduled" 'date d2
16312 'priority (+ (- 5 diff) (org-get-priority txt))
16313 'org-category category)
16314 (push txt ee))))))
16315 ee))
16317 (defun org-agenda-get-blocks ()
16318 "Return the date-range information for agenda display."
16319 (let* ((props (list 'face nil
16320 'org-not-done-regexp org-not-done-regexp
16321 'org-todo-regexp org-todo-regexp
16322 'mouse-face 'highlight
16323 'keymap org-agenda-keymap
16324 'help-echo
16325 (format "mouse-2 or RET jump to org file %s"
16326 (abbreviate-file-name buffer-file-name))))
16327 (regexp org-tr-regexp)
16328 (d0 (calendar-absolute-from-gregorian date))
16329 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
16330 (goto-char (point-min))
16331 (while (re-search-forward regexp nil t)
16332 (catch :skip
16333 (org-agenda-skip)
16334 (setq pos (point))
16335 (setq timestr (match-string 0)
16336 s1 (match-string 1)
16337 s2 (match-string 2)
16338 d1 (time-to-days (org-time-string-to-time s1))
16339 d2 (time-to-days (org-time-string-to-time s2)))
16340 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
16341 ;; Only allow days between the limits, because the normal
16342 ;; date stamps will catch the limits.
16343 (save-excursion
16344 (setq marker (org-agenda-new-marker (point)))
16345 (setq category (org-get-category))
16346 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
16347 (progn
16348 (setq hdmarker (org-agenda-new-marker (match-end 1)))
16349 (goto-char (match-end 1))
16350 (setq tags (org-get-tags-at))
16351 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
16352 (setq txt (org-format-agenda-item
16353 (format (if (= d1 d2) "" "(%d/%d): ")
16354 (1+ (- d0 d1)) (1+ (- d2 d1)))
16355 (match-string 1) category tags
16356 (if (= d0 d1) timestr))))
16357 (setq txt org-agenda-no-heading-message))
16358 (org-add-props txt props
16359 'org-marker marker 'org-hd-marker hdmarker
16360 'type "block" 'date date
16361 'priority (org-get-priority txt) 'org-category category)
16362 (push txt ee)))
16363 (goto-char pos)))
16364 ;; Sort the entries by expiration date.
16365 (nreverse ee)))
16367 ;;; Agenda presentation and sorting
16369 (defconst org-plain-time-of-day-regexp
16370 (concat
16371 "\\(\\<[012]?[0-9]"
16372 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
16373 "\\(--?"
16374 "\\(\\<[012]?[0-9]"
16375 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
16376 "\\)?")
16377 "Regular expression to match a plain time or time range.
16378 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
16379 groups carry important information:
16380 0 the full match
16381 1 the first time, range or not
16382 8 the second time, if it is a range.")
16384 (defconst org-stamp-time-of-day-regexp
16385 (concat
16386 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
16387 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
16388 "\\(--?"
16389 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
16390 "Regular expression to match a timestamp time or time range.
16391 After a match, the following groups carry important information:
16392 0 the full match
16393 1 date plus weekday, for backreferencing to make sure both times on same day
16394 2 the first time, range or not
16395 4 the second time, if it is a range.")
16397 (defvar org-prefix-has-time nil
16398 "A flag, set by `org-compile-prefix-format'.
16399 The flag is set if the currently compiled format contains a `%t'.")
16400 (defvar org-prefix-has-tag nil
16401 "A flag, set by `org-compile-prefix-format'.
16402 The flag is set if the currently compiled format contains a `%T'.")
16404 (defun org-format-agenda-item (extra txt &optional category tags dotime
16405 noprefix)
16406 "Format TXT to be inserted into the agenda buffer.
16407 In particular, it adds the prefix and corresponding text properties. EXTRA
16408 must be a string and replaces the `%s' specifier in the prefix format.
16409 CATEGORY (string, symbol or nil) may be used to overrule the default
16410 category taken from local variable or file name. It will replace the `%c'
16411 specifier in the format. DOTIME, when non-nil, indicates that a
16412 time-of-day should be extracted from TXT for sorting of this entry, and for
16413 the `%t' specifier in the format. When DOTIME is a string, this string is
16414 searched for a time before TXT is. NOPREFIX is a flag and indicates that
16415 only the correctly processes TXT should be returned - this is used by
16416 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
16417 (save-match-data
16418 ;; Diary entries sometimes have extra whitespace at the beginning
16419 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
16420 (let* ((category (or category
16421 org-category
16422 (if buffer-file-name
16423 (file-name-sans-extension
16424 (file-name-nondirectory buffer-file-name))
16425 "")))
16426 (tag (if tags (nth (1- (length tags)) tags) ""))
16427 time ; time and tag are needed for the eval of the prefix format
16428 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
16429 (time-of-day (and dotime (org-get-time-of-day ts)))
16430 stamp plain s0 s1 s2 rtn srp)
16431 (when (and dotime time-of-day org-prefix-has-time)
16432 ;; Extract starting and ending time and move them to prefix
16433 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
16434 (setq plain (string-match org-plain-time-of-day-regexp ts)))
16435 (setq s0 (match-string 0 ts)
16436 srp (and stamp (match-end 3))
16437 s1 (match-string (if plain 1 2) ts)
16438 s2 (match-string (if plain 8 (if srp 4 6)) ts))
16440 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
16441 ;; them, we might want to remove them there to avoid duplication.
16442 ;; The user can turn this off with a variable.
16443 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
16444 (string-match (concat (regexp-quote s0) " *") txt)
16445 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
16446 (= (match-beginning 0) 0)
16448 (setq txt (replace-match "" nil nil txt))))
16449 ;; Normalize the time(s) to 24 hour
16450 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
16451 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
16453 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" txt)
16454 ;; Tags are in the string
16455 (if (or (eq org-agenda-remove-tags t)
16456 (and org-agenda-remove-tags
16457 org-prefix-has-tag))
16458 (setq txt (replace-match "" t t txt))
16459 (setq txt (replace-match
16460 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
16461 (match-string 2 txt))
16462 t t txt))))
16464 ;; Create the final string
16465 (if noprefix
16466 (setq rtn txt)
16467 ;; Prepare the variables needed in the eval of the compiled format
16468 (setq time (cond (s2 (concat s1 "-" s2))
16469 (s1 (concat s1 "......"))
16470 (t ""))
16471 extra (or extra "")
16472 category (if (symbolp category) (symbol-name category) category))
16473 ;; Evaluate the compiled format
16474 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
16476 ;; And finally add the text properties
16477 (org-add-props rtn nil
16478 'org-category (downcase category) 'tags tags
16479 'prefix-length (- (length rtn) (length txt))
16480 'time-of-day time-of-day
16481 'txt txt
16482 'time time
16483 'extra extra
16484 'dotime dotime))))
16486 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
16487 (defvar org-agenda-sorting-strategy-selected nil)
16489 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
16490 (catch 'exit
16491 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
16492 ((and todayp (member 'today (car org-agenda-time-grid))))
16493 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
16494 ((member 'weekly (car org-agenda-time-grid)))
16495 (t (throw 'exit list)))
16496 (let* ((have (delq nil (mapcar
16497 (lambda (x) (get-text-property 1 'time-of-day x))
16498 list)))
16499 (string (nth 1 org-agenda-time-grid))
16500 (gridtimes (nth 2 org-agenda-time-grid))
16501 (req (car org-agenda-time-grid))
16502 (remove (member 'remove-match req))
16503 new time)
16504 (if (and (member 'require-timed req) (not have))
16505 ;; don't show empty grid
16506 (throw 'exit list))
16507 (while (setq time (pop gridtimes))
16508 (unless (and remove (member time have))
16509 (setq time (int-to-string time))
16510 (push (org-format-agenda-item
16511 nil string "" nil
16512 (concat (substring time 0 -2) ":" (substring time -2)))
16513 new)
16514 (put-text-property
16515 1 (length (car new)) 'face 'org-time-grid (car new))))
16516 (if (member 'time-up org-agenda-sorting-strategy-selected)
16517 (append new list)
16518 (append list new)))))
16520 (defun org-compile-prefix-format (key)
16521 "Compile the prefix format into a Lisp form that can be evaluated.
16522 The resulting form is returned and stored in the variable
16523 `org-prefix-format-compiled'."
16524 (setq org-prefix-has-time nil org-prefix-has-tag nil)
16525 (let ((s (cond
16526 ((stringp org-agenda-prefix-format)
16527 org-agenda-prefix-format)
16528 ((assq key org-agenda-prefix-format)
16529 (cdr (assq key org-agenda-prefix-format)))
16530 (t " %-12:c%?-12t% s")))
16531 (start 0)
16532 varform vars var e c f opt)
16533 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
16534 s start)
16535 (setq var (cdr (assoc (match-string 4 s)
16536 '(("c" . category) ("t" . time) ("s" . extra)
16537 ("T" . tag))))
16538 c (or (match-string 3 s) "")
16539 opt (match-beginning 1)
16540 start (1+ (match-beginning 0)))
16541 (if (equal var 'time) (setq org-prefix-has-time t))
16542 (if (equal var 'tag) (setq org-prefix-has-tag t))
16543 (setq f (concat "%" (match-string 2 s) "s"))
16544 (if opt
16545 (setq varform
16546 `(if (equal "" ,var)
16548 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
16549 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
16550 (setq s (replace-match "%s" t nil s))
16551 (push varform vars))
16552 (setq vars (nreverse vars))
16553 (setq org-prefix-format-compiled `(format ,s ,@vars))))
16555 (defun org-set-sorting-strategy (key)
16556 (if (symbolp (car org-agenda-sorting-strategy))
16557 ;; the old format
16558 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
16559 (setq org-agenda-sorting-strategy-selected
16560 (or (cdr (assq key org-agenda-sorting-strategy))
16561 (cdr (assq 'agenda org-agenda-sorting-strategy))
16562 '(time-up category-keep priority-down)))))
16564 (defun org-get-time-of-day (s &optional string mod24)
16565 "Check string S for a time of day.
16566 If found, return it as a military time number between 0 and 2400.
16567 If not found, return nil.
16568 The optional STRING argument forces conversion into a 5 character wide string
16569 HH:MM."
16570 (save-match-data
16571 (when
16573 (string-match
16574 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
16575 (string-match
16576 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
16577 (let* ((h (string-to-number (match-string 1 s)))
16578 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
16579 (ampm (if (match-end 4) (downcase (match-string 4 s))))
16580 (am-p (equal ampm "am"))
16581 (h1 (cond ((not ampm) h)
16582 ((= h 12) (if am-p 0 12))
16583 (t (+ h (if am-p 0 12)))))
16584 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
16585 (mod h1 24) h1))
16586 (t0 (+ (* 100 h2) m))
16587 (t1 (concat (if (>= h1 24) "+" " ")
16588 (if (< t0 100) "0" "")
16589 (if (< t0 10) "0" "")
16590 (int-to-string t0))))
16591 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
16593 (defun org-finalize-agenda-entries (list &optional nosort)
16594 "Sort and concatenate the agenda items."
16595 (setq list (mapcar 'org-agenda-highlight-todo list))
16596 (if nosort
16597 list
16598 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
16600 (defun org-agenda-highlight-todo (x)
16601 (let (re pl)
16602 (if (eq x 'line)
16603 (save-excursion
16604 (beginning-of-line 1)
16605 (setq re (get-text-property (point) 'org-not-done-regexp))
16606 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
16607 (and (looking-at (concat "[ \t]*\\.*" re))
16608 (add-text-properties (match-beginning 0) (match-end 0)
16609 '(face org-todo))))
16610 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
16611 pl (get-text-property 0 'prefix-length x))
16612 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
16613 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
16614 '(face org-todo) x))
16615 x)))
16617 (defsubst org-cmp-priority (a b)
16618 "Compare the priorities of string A and B."
16619 (let ((pa (or (get-text-property 1 'priority a) 0))
16620 (pb (or (get-text-property 1 'priority b) 0)))
16621 (cond ((> pa pb) +1)
16622 ((< pa pb) -1)
16623 (t nil))))
16625 (defsubst org-cmp-category (a b)
16626 "Compare the string values of categories of strings A and B."
16627 (let ((ca (or (get-text-property 1 'category a) ""))
16628 (cb (or (get-text-property 1 'category b) "")))
16629 (cond ((string-lessp ca cb) -1)
16630 ((string-lessp cb ca) +1)
16631 (t nil))))
16633 (defsubst org-cmp-tag (a b)
16634 "Compare the string values of categories of strings A and B."
16635 (let ((ta (car (last (get-text-property 1 'tags a))))
16636 (tb (car (last (get-text-property 1 'tags b)))))
16637 (cond ((not ta) +1)
16638 ((not tb) -1)
16639 ((string-lessp ta tb) -1)
16640 ((string-lessp tb ta) +1)
16641 (t nil))))
16643 (defsubst org-cmp-time (a b)
16644 "Compare the time-of-day values of strings A and B."
16645 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
16646 (ta (or (get-text-property 1 'time-of-day a) def))
16647 (tb (or (get-text-property 1 'time-of-day b) def)))
16648 (cond ((< ta tb) -1)
16649 ((< tb ta) +1)
16650 (t nil))))
16652 (defun org-entries-lessp (a b)
16653 "Predicate for sorting agenda entries."
16654 ;; The following variables will be used when the form is evaluated.
16655 ;; So even though the compiler complains, keep them.
16656 (let* ((time-up (org-cmp-time a b))
16657 (time-down (if time-up (- time-up) nil))
16658 (priority-up (org-cmp-priority a b))
16659 (priority-down (if priority-up (- priority-up) nil))
16660 (category-up (org-cmp-category a b))
16661 (category-down (if category-up (- category-up) nil))
16662 (category-keep (if category-up +1 nil))
16663 (tag-up (org-cmp-tag a b))
16664 (tag-down (if tag-up (- tag-up) nil)))
16665 (cdr (assoc
16666 (eval (cons 'or org-agenda-sorting-strategy-selected))
16667 '((-1 . t) (1 . nil) (nil . nil))))))
16669 ;;; Agenda commands
16671 (defun org-agenda-check-type (error &rest types)
16672 "Check if agenda buffer is of allowed type.
16673 If ERROR is non-nil, throw an error, otherwise just return nil."
16674 (if (memq org-agenda-type types)
16676 (if error
16677 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
16678 nil)))
16680 (defun org-agenda-quit ()
16681 "Exit agenda by removing the window or the buffer."
16682 (interactive)
16683 (let ((buf (current-buffer)))
16684 (if (not (one-window-p)) (delete-window))
16685 (kill-buffer buf)
16686 (org-agenda-maybe-reset-markers 'force))
16687 ;; Maybe restore the pre-agenda window configuration.
16688 (and org-agenda-restore-windows-after-quit
16689 (not (eq org-agenda-window-setup 'other-frame))
16690 org-pre-agenda-window-conf
16691 (set-window-configuration org-pre-agenda-window-conf)))
16693 (defun org-agenda-exit ()
16694 "Exit agenda by removing the window or the buffer.
16695 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
16696 Org-mode buffers visited directly by the user will not be touched."
16697 (interactive)
16698 (org-release-buffers org-agenda-new-buffers)
16699 (setq org-agenda-new-buffers nil)
16700 (org-agenda-quit))
16702 (defun org-save-all-org-buffers ()
16703 "Save all Org-mode buffers without user confirmation."
16704 (interactive)
16705 (message "Saving all Org-mode buffers...")
16706 (save-some-buffers t 'org-mode-p)
16707 (message "Saving all Org-mode buffers... done"))
16709 (defun org-agenda-redo ()
16710 "Rebuild Agenda.
16711 When this is the global TODO list, a prefix argument will be interpreted."
16712 (interactive)
16713 (let* ((org-agenda-keep-modes t)
16714 (line (org-current-line))
16715 (window-line (- line (org-current-line (window-start)))))
16716 (message "Rebuilding agenda buffer...")
16717 (eval org-agenda-redo-command)
16718 (setq org-agenda-undo-list nil
16719 org-agenda-pending-undo-list nil)
16720 (message "Rebuilding agenda buffer...done")
16721 (goto-line line)
16722 (recenter window-line)))
16724 (defun org-agenda-goto-today ()
16725 "Go to today."
16726 (interactive)
16727 (org-agenda-check-type t 'timeline 'agenda)
16728 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
16729 (cond
16730 (tdpos (goto-char tdpos))
16731 ((eq org-agenda-type 'agenda)
16732 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
16733 (setf (nth 1 org-agenda-overriding-arguments) nil)
16734 (org-agenda-redo)
16735 (org-agenda-find-today-or-agenda)))
16736 (t (error "Cannot find today")))))
16738 (defun org-agenda-find-today-or-agenda ()
16739 (goto-char
16740 (or (text-property-any (point-min) (point-max) 'org-today t)
16741 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
16742 (point-min))))
16744 (defun org-agenda-later (arg)
16745 "Go forward in time by `org-agenda-ndays' days.
16746 With prefix ARG, go forward that many times `org-agenda-ndays'."
16747 (interactive "p")
16748 (org-agenda-check-type t 'agenda)
16749 (let ((org-agenda-overriding-arguments
16750 (list (car org-agenda-last-arguments)
16751 (+ org-starting-day (* arg org-agenda-ndays))
16752 nil t)))
16753 (org-agenda-redo)
16754 (org-agenda-find-today-or-agenda)))
16756 (defun org-agenda-earlier (arg)
16757 "Go back in time by `org-agenda-ndays' days.
16758 With prefix ARG, go back that many times `org-agenda-ndays'."
16759 (interactive "p")
16760 (org-agenda-check-type t 'agenda)
16761 (let ((org-agenda-overriding-arguments
16762 (list (car org-agenda-last-arguments)
16763 (- org-starting-day (* arg org-agenda-ndays))
16764 nil t)))
16765 (org-agenda-redo)
16766 (org-agenda-find-today-or-agenda)))
16768 (defun org-agenda-week-view ()
16769 "Switch to weekly view for agenda."
16770 (interactive)
16771 (org-agenda-check-type t 'agenda)
16772 (if (= org-agenda-ndays 7)
16773 (error "This is already the week view"))
16774 (setq org-agenda-ndays 7)
16775 (let ((org-agenda-overriding-arguments
16776 (list (car org-agenda-last-arguments)
16777 (or (get-text-property (point) 'day)
16778 org-starting-day)
16779 nil t)))
16780 (org-agenda-redo)
16781 (org-agenda-find-today-or-agenda))
16782 (org-agenda-set-mode-name)
16783 (message "Switched to week view"))
16785 (defun org-agenda-day-view ()
16786 "Switch to daily view for agenda."
16787 (interactive)
16788 (org-agenda-check-type t 'agenda)
16789 (if (= org-agenda-ndays 1)
16790 (error "This is already the day view"))
16791 (setq org-agenda-ndays 1)
16792 (let ((org-agenda-overriding-arguments
16793 (list (car org-agenda-last-arguments)
16794 (or (get-text-property (point) 'day)
16795 org-starting-day)
16796 nil t)))
16797 (org-agenda-redo)
16798 (org-agenda-find-today-or-agenda))
16799 (org-agenda-set-mode-name)
16800 (message "Switched to day view"))
16802 ;; FIXME: this no longer works if user make date format that starts with a blank
16803 (defun org-agenda-next-date-line (&optional arg)
16804 "Jump to the next line indicating a date in agenda buffer."
16805 (interactive "p")
16806 (org-agenda-check-type t 'agenda 'timeline)
16807 (beginning-of-line 1)
16808 (if (looking-at "^\\S-") (forward-char 1))
16809 (if (not (re-search-forward "^\\S-" nil t arg))
16810 (progn
16811 (backward-char 1)
16812 (error "No next date after this line in this buffer")))
16813 (goto-char (match-beginning 0)))
16815 (defun org-agenda-previous-date-line (&optional arg)
16816 "Jump to the previous line indicating a date in agenda buffer."
16817 (interactive "p")
16818 (org-agenda-check-type t 'agenda 'timeline)
16819 (beginning-of-line 1)
16820 (if (not (re-search-backward "^\\S-" nil t arg))
16821 (error "No previous date before this line in this buffer")))
16823 ;; Initialize the highlight
16824 (defvar org-hl (org-make-overlay 1 1))
16825 (org-overlay-put org-hl 'face 'highlight)
16827 (defun org-highlight (begin end &optional buffer)
16828 "Highlight a region with overlay."
16829 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
16830 org-hl begin end (or buffer (current-buffer))))
16832 (defun org-unhighlight ()
16833 "Detach overlay INDEX."
16834 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
16836 ;; FIXME this is currently not used.
16837 (defun org-highlight-until-next-command (beg end &optional buffer)
16838 (org-highlight beg end buffer)
16839 (add-hook 'pre-command-hook 'org-unhighlight-once))
16841 (defun org-unhighlight-once ()
16842 (remove-hook 'pre-command-hook 'org-unhighlight-once)
16843 (org-unhighlight))
16845 (defun org-agenda-follow-mode ()
16846 "Toggle follow mode in an agenda buffer."
16847 (interactive)
16848 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
16849 (org-agenda-set-mode-name)
16850 (message "Follow mode is %s"
16851 (if org-agenda-follow-mode "on" "off")))
16853 (defun org-agenda-log-mode ()
16854 "Toggle log mode in an agenda buffer."
16855 (interactive)
16856 (org-agenda-check-type t 'agenda 'timeline)
16857 (setq org-agenda-show-log (not org-agenda-show-log))
16858 (org-agenda-set-mode-name)
16859 (org-agenda-redo)
16860 (message "Log mode is %s"
16861 (if org-agenda-show-log "on" "off")))
16863 (defun org-agenda-toggle-diary ()
16864 "Toggle diary inclusion in an agenda buffer."
16865 (interactive)
16866 (org-agenda-check-type t 'agenda)
16867 (setq org-agenda-include-diary (not org-agenda-include-diary))
16868 (org-agenda-redo)
16869 (org-agenda-set-mode-name)
16870 (message "Diary inclusion turned %s"
16871 (if org-agenda-include-diary "on" "off")))
16873 (defun org-agenda-toggle-time-grid ()
16874 "Toggle time grid in an agenda buffer."
16875 (interactive)
16876 (org-agenda-check-type t 'agenda)
16877 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
16878 (org-agenda-redo)
16879 (org-agenda-set-mode-name)
16880 (message "Time-grid turned %s"
16881 (if org-agenda-use-time-grid "on" "off")))
16883 (defun org-agenda-set-mode-name ()
16884 "Set the mode name to indicate all the small mode settings."
16885 (setq mode-name
16886 (concat "Org-Agenda"
16887 (if (equal org-agenda-ndays 1) " Day" "")
16888 (if (equal org-agenda-ndays 7) " Week" "")
16889 (if org-agenda-follow-mode " Follow" "")
16890 (if org-agenda-include-diary " Diary" "")
16891 (if org-agenda-use-time-grid " Grid" "")
16892 (if org-agenda-show-log " Log" "")))
16893 (force-mode-line-update))
16895 (defun org-agenda-post-command-hook ()
16896 (and (eolp) (not (bolp)) (backward-char 1))
16897 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
16898 (if (and org-agenda-follow-mode
16899 (get-text-property (point) 'org-marker))
16900 (org-agenda-show)))
16902 (defun org-agenda-show-priority ()
16903 "Show the priority of the current item.
16904 This priority is composed of the main priority given with the [#A] cookies,
16905 and by additional input from the age of a schedules or deadline entry."
16906 (interactive)
16907 (let* ((pri (get-text-property (point-at-bol) 'priority)))
16908 (message "Priority is %d" (if pri pri -1000))))
16910 (defun org-agenda-show-tags ()
16911 "Show the tags applicable to the current item."
16912 (interactive)
16913 (let* ((tags (get-text-property (point-at-bol) 'tags)))
16914 (if tags
16915 (message "Tags are :%s:"
16916 (org-no-properties (mapconcat 'identity tags ":")))
16917 (message "No tags associated with this line"))))
16919 (defun org-agenda-goto (&optional highlight)
16920 "Go to the Org-mode file which contains the item at point."
16921 (interactive)
16922 (let* ((marker (or (get-text-property (point) 'org-marker)
16923 (org-agenda-error)))
16924 (buffer (marker-buffer marker))
16925 (pos (marker-position marker)))
16926 (switch-to-buffer-other-window buffer)
16927 (widen)
16928 (goto-char pos)
16929 (when (org-mode-p)
16930 (org-show-context 'agenda)
16931 (save-excursion
16932 (and (outline-next-heading)
16933 (org-flag-heading nil)))) ; show the next heading
16934 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
16936 (defun org-agenda-kill ()
16937 "Kill the entry or subtree belonging to the current agenda entry."
16938 (interactive)
16939 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
16940 (let* ((marker (or (get-text-property (point) 'org-marker)
16941 (org-agenda-error)))
16942 (buffer (marker-buffer marker))
16943 (pos (marker-position marker))
16944 (type (get-text-property (point) 'type))
16945 dbeg dend (n 0) conf)
16946 (org-with-remote-undo buffer
16947 (with-current-buffer buffer
16948 (save-excursion
16949 (goto-char pos)
16950 (if (and (org-mode-p) (not (member type '("sexp"))))
16951 (setq dbeg (progn (org-back-to-heading t) (point))
16952 dend (org-end-of-subtree t))
16953 (setq dbeg (point-at-bol)
16954 dend (min (point-max) (1+ (point-at-eol)))))
16955 (goto-char dbeg)
16956 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
16957 (setq conf (or (eq t org-agenda-confirm-kill)
16958 (and (numberp org-agenda-confirm-kill)
16959 (> n org-agenda-confirm-kill))))
16960 (and conf
16961 (not (y-or-n-p
16962 (format "Delete entry with %d lines in buffer \"%s\"? "
16963 n (buffer-name buffer))))
16964 (error "Abort"))
16965 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
16966 (with-current-buffer buffer (delete-region dbeg dend))
16967 (message "Agenda item and source killed"))))
16969 (defun org-agenda-archive ()
16970 "Kill the entry or subtree belonging to the current agenda entry."
16971 (interactive)
16972 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
16973 (let* ((marker (or (get-text-property (point) 'org-marker)
16974 (org-agenda-error)))
16975 (buffer (marker-buffer marker))
16976 (pos (marker-position marker)))
16977 (org-with-remote-undo buffer
16978 (with-current-buffer buffer
16979 (if (org-mode-p)
16980 (save-excursion
16981 (goto-char pos)
16982 (org-remove-subtree-entries-from-agenda)
16983 (org-back-to-heading t)
16984 (org-archive-subtree))
16985 (error "Archiving works only in Org-mode files"))))))
16987 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
16988 "Remove all lines in the agenda that correspond to a given subtree.
16989 The subtree is the one in buffer BUF, starting at BEG and ending at END.
16990 If this information is not given, the function uses the tree at point."
16991 (let ((buf (or buf (current-buffer))) m p)
16992 (save-excursion
16993 (unless (and beg end)
16994 (org-back-to-heading t)
16995 (setq beg (point))
16996 (org-end-of-subtree t)
16997 (setq end (point)))
16998 (set-buffer (get-buffer org-agenda-buffer-name))
16999 (save-excursion
17000 (goto-char (point-max))
17001 (beginning-of-line 1)
17002 (while (not (bobp))
17003 (when (and (setq m (get-text-property (point) 'org-marker))
17004 (equal buf (marker-buffer m))
17005 (setq p (marker-position m))
17006 (>= p beg)
17007 (<= p end))
17008 (let (buffer-read-only)
17009 (delete-region (point-at-bol) (1+ (point-at-eol)))))
17010 (beginning-of-line 0))))))
17012 (defun org-agenda-open-link ()
17013 "Follow the link in the current line, if any."
17014 (interactive)
17015 (let ((eol (point-at-eol)))
17016 (save-excursion
17017 (if (or (re-search-forward org-bracket-link-regexp eol t)
17018 (re-search-forward org-angle-link-re eol t)
17019 (re-search-forward org-plain-link-re eol t))
17020 (call-interactively 'org-open-at-point)
17021 (error "No link in current line")))))
17023 (defun org-agenda-switch-to (&optional delete-other-windows)
17024 "Go to the Org-mode file which contains the item at point."
17025 (interactive)
17026 (let* ((marker (or (get-text-property (point) 'org-marker)
17027 (org-agenda-error)))
17028 (buffer (marker-buffer marker))
17029 (pos (marker-position marker)))
17030 (switch-to-buffer buffer)
17031 (and delete-other-windows (delete-other-windows))
17032 (widen)
17033 (goto-char pos)
17034 (when (org-mode-p)
17035 (org-show-context 'agenda)
17036 (save-excursion
17037 (and (outline-next-heading)
17038 (org-flag-heading nil)))))) ; show the next heading
17040 (defun org-agenda-goto-mouse (ev)
17041 "Go to the Org-mode file which contains the item at the mouse click."
17042 (interactive "e")
17043 (mouse-set-point ev)
17044 (org-agenda-goto))
17046 (defun org-agenda-show ()
17047 "Display the Org-mode file which contains the item at point."
17048 (interactive)
17049 (let ((win (selected-window)))
17050 (org-agenda-goto t)
17051 (select-window win)))
17053 (defun org-agenda-recenter (arg)
17054 "Display the Org-mode file which contains the item at point and recenter."
17055 (interactive "P")
17056 (let ((win (selected-window)))
17057 (org-agenda-goto t)
17058 (recenter arg)
17059 (select-window win)))
17061 (defun org-agenda-show-mouse (ev)
17062 "Display the Org-mode file which contains the item at the mouse click."
17063 (interactive "e")
17064 (mouse-set-point ev)
17065 (org-agenda-show))
17067 (defun org-agenda-check-no-diary ()
17068 "Check if the entry is a diary link and abort if yes."
17069 (if (get-text-property (point) 'org-agenda-diary-link)
17070 (org-agenda-error)))
17072 (defun org-agenda-error ()
17073 (error "Command not allowed in this line"))
17075 (defun org-agenda-tree-to-indirect-buffer ()
17076 "Show the subtree corresponding to the current entry in an indirect buffer.
17077 This calls the command `org-tree-to-indirect-buffer' from the original
17078 Org-mode buffer.
17079 With numerical prefix arg ARG, go up to this level and then take that tree.
17080 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
17081 dedicated frame)."
17082 (interactive)
17083 (org-agenda-check-no-diary)
17084 (let* ((marker (or (get-text-property (point) 'org-marker)
17085 (org-agenda-error)))
17086 (buffer (marker-buffer marker))
17087 (pos (marker-position marker)))
17088 (with-current-buffer buffer
17089 (save-excursion
17090 (goto-char pos)
17091 (call-interactively 'org-tree-to-indirect-buffer)))))
17093 (defvar org-last-heading-marker (make-marker)
17094 "Marker pointing to the headline that last changed its TODO state
17095 by a remote command from the agenda.")
17097 (defun org-agenda-todo-nextset ()
17098 "Switch TODO entry to next sequence."
17099 (interactive)
17100 (org-agenda-todo 'nextset))
17102 (defun org-agenda-todo-previousset ()
17103 "Switch TODO entry to previous sequence."
17104 (interactive)
17105 (org-agenda-todo 'previousset))
17107 (defun org-agenda-todo (&optional arg)
17108 "Cycle TODO state of line at point, also in Org-mode file.
17109 This changes the line at point, all other lines in the agenda referring to
17110 the same tree node, and the headline of the tree node in the Org-mode file."
17111 (interactive "P")
17112 (org-agenda-check-no-diary)
17113 (let* ((col (current-column))
17114 (marker (or (get-text-property (point) 'org-marker)
17115 (org-agenda-error)))
17116 (buffer (marker-buffer marker))
17117 (pos (marker-position marker))
17118 (hdmarker (get-text-property (point) 'org-hd-marker))
17119 (buffer-read-only nil)
17120 newhead)
17121 (org-with-remote-undo buffer
17122 (with-current-buffer buffer
17123 (widen)
17124 (goto-char pos)
17125 (org-show-context 'agenda)
17126 (save-excursion
17127 (and (outline-next-heading)
17128 (org-flag-heading nil))) ; show the next heading
17129 (org-todo arg)
17130 (and (bolp) (forward-char 1))
17131 (setq newhead (org-get-heading))
17132 (save-excursion
17133 (org-back-to-heading)
17134 (move-marker org-last-heading-marker (point))))
17135 (beginning-of-line 1)
17136 (save-excursion
17137 (org-agenda-change-all-lines newhead hdmarker 'fixface))
17138 (move-to-column col))))
17140 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
17141 "Change all lines in the agenda buffer which match HDMARKER.
17142 The new content of the line will be NEWHEAD (as modified by
17143 `org-format-agenda-item'). HDMARKER is checked with
17144 `equal' against all `org-hd-marker' text properties in the file.
17145 If FIXFACE is non-nil, the face of each item is modified acording to
17146 the new TODO state."
17147 (let* ((buffer-read-only nil)
17148 props m pl undone-face done-face finish new dotime cat tags)
17149 (save-excursion
17150 (goto-char (point-max))
17151 (beginning-of-line 1)
17152 (while (not finish)
17153 (setq finish (bobp))
17154 (when (and (setq m (get-text-property (point) 'org-hd-marker))
17155 (equal m hdmarker))
17156 (setq props (text-properties-at (point))
17157 dotime (get-text-property (point) 'dotime)
17158 cat (get-text-property (point) 'org-category)
17159 tags (get-text-property (point) 'tags)
17160 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
17161 pl (get-text-property (point) 'prefix-length)
17162 undone-face (get-text-property (point) 'undone-face)
17163 done-face (get-text-property (point) 'done-face))
17164 (move-to-column pl)
17165 (cond
17166 ((equal new "")
17167 (beginning-of-line 1)
17168 (and (looking-at ".*\n?") (replace-match "")))
17169 ((looking-at ".*")
17170 (replace-match new t t)
17171 (beginning-of-line 1)
17172 (add-text-properties (point-at-bol) (point-at-eol) props)
17173 (when fixface
17174 (add-text-properties
17175 (point-at-bol) (point-at-eol)
17176 (list 'face
17177 (if org-last-todo-state-is-todo
17178 undone-face done-face))))
17179 (org-agenda-highlight-todo 'line)
17180 (beginning-of-line 1))
17181 (t (error "Line update did not work"))))
17182 (beginning-of-line 0)))
17183 (org-finalize-agenda)))
17185 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
17186 ;; See the code in set-tags for the way to do this.
17187 (defun org-agenda-align-tags (&optional line)
17188 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
17189 (let ((buffer-read-only))
17190 (save-excursion
17191 (goto-char (if line (point-at-bol) (point-min)))
17192 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
17193 (if line (point-at-eol) nil) t)
17194 (delete-region (match-beginning 1) (match-end 1))
17195 (goto-char (match-beginning 1))
17196 (insert (org-add-props
17197 (make-string (max 1 (- org-agenda-align-tags-to-column
17198 (current-column))) ?\ )
17199 (text-properties-at (point))))))))
17201 (defun org-agenda-priority-up ()
17202 "Increase the priority of line at point, also in Org-mode file."
17203 (interactive)
17204 (org-agenda-priority 'up))
17206 (defun org-agenda-priority-down ()
17207 "Decrease the priority of line at point, also in Org-mode file."
17208 (interactive)
17209 (org-agenda-priority 'down))
17211 (defun org-agenda-priority (&optional force-direction)
17212 "Set the priority of line at point, also in Org-mode file.
17213 This changes the line at point, all other lines in the agenda referring to
17214 the same tree node, and the headline of the tree node in the Org-mode file."
17215 (interactive)
17216 (org-agenda-check-no-diary)
17217 (let* ((marker (or (get-text-property (point) 'org-marker)
17218 (org-agenda-error)))
17219 (buffer (marker-buffer marker))
17220 (pos (marker-position marker))
17221 (hdmarker (get-text-property (point) 'org-hd-marker))
17222 (buffer-read-only nil)
17223 newhead)
17224 (org-with-remote-undo buffer
17225 (with-current-buffer buffer
17226 (widen)
17227 (goto-char pos)
17228 (org-show-context 'agenda)
17229 (save-excursion
17230 (and (outline-next-heading)
17231 (org-flag-heading nil))) ; show the next heading
17232 (funcall 'org-priority force-direction)
17233 (end-of-line 1)
17234 (setq newhead (org-get-heading)))
17235 (org-agenda-change-all-lines newhead hdmarker)
17236 (beginning-of-line 1))))
17238 (defun org-get-tags-at (&optional pos)
17239 "Get a list of all headline tags applicable at POS.
17240 POS defaults to point. If tags are inherited, the list contains
17241 the targets in the same sequence as the headlines appear, i.e.
17242 the tags of the current headline come last."
17243 (interactive)
17244 (let (tags)
17245 (save-excursion
17246 (save-restriction
17247 (widen)
17248 (goto-char (or pos (point)))
17249 (save-match-data
17250 (org-back-to-heading t)
17251 (condition-case nil
17252 (while t
17253 (if (looking-at "[^\r\n]+?:\\([a-zA-Z0-9_@:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
17254 (setq tags (append (org-split-string
17255 (org-match-string-no-properties 1) ":")
17256 tags)))
17257 (or org-use-tag-inheritance (error ""))
17258 (org-up-heading-all 1))
17259 (error nil))))
17260 tags)))
17262 ;; FIXME: should fix the tags property of the agenda line.
17263 (defun org-agenda-set-tags ()
17264 "Set tags for the current headline."
17265 (interactive)
17266 (org-agenda-check-no-diary)
17267 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
17268 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
17269 (org-agenda-error)))
17270 (buffer (marker-buffer hdmarker))
17271 (pos (marker-position hdmarker))
17272 (buffer-read-only nil)
17273 newhead)
17274 (org-with-remote-undo buffer
17275 (with-current-buffer buffer
17276 (widen)
17277 (goto-char pos)
17278 (save-excursion
17279 (org-show-context 'agenda))
17280 (save-excursion
17281 (and (outline-next-heading)
17282 (org-flag-heading nil))) ; show the next heading
17283 (goto-char pos)
17284 (call-interactively 'org-set-tags)
17285 (end-of-line 1)
17286 (setq newhead (org-get-heading)))
17287 (org-agenda-change-all-lines newhead hdmarker)
17288 (beginning-of-line 1))))
17290 (defun org-agenda-toggle-archive-tag ()
17291 "Toggle the archive tag for the current entry."
17292 (interactive)
17293 (org-agenda-check-no-diary)
17294 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
17295 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
17296 (org-agenda-error)))
17297 (buffer (marker-buffer hdmarker))
17298 (pos (marker-position hdmarker))
17299 (buffer-read-only nil)
17300 newhead)
17301 (org-with-remote-undo buffer
17302 (with-current-buffer buffer
17303 (widen)
17304 (goto-char pos)
17305 (org-show-context 'agenda)
17306 (save-excursion
17307 (and (outline-next-heading)
17308 (org-flag-heading nil))) ; show the next heading
17309 (call-interactively 'org-toggle-archive-tag)
17310 (end-of-line 1)
17311 (setq newhead (org-get-heading)))
17312 (org-agenda-change-all-lines newhead hdmarker)
17313 (beginning-of-line 1))))
17315 (defun org-agenda-date-later (arg &optional what)
17316 "Change the date of this item to one day later."
17317 (interactive "p")
17318 (org-agenda-check-type t 'agenda 'timeline)
17319 (org-agenda-check-no-diary)
17320 (let* ((marker (or (get-text-property (point) 'org-marker)
17321 (org-agenda-error)))
17322 (buffer (marker-buffer marker))
17323 (pos (marker-position marker)))
17324 (org-with-remote-undo buffer
17325 (with-current-buffer buffer
17326 (widen)
17327 (goto-char pos)
17328 (if (not (org-at-timestamp-p))
17329 (error "Cannot find time stamp"))
17330 (org-timestamp-change arg (or what 'day)))
17331 (org-agenda-show-new-time marker org-last-changed-timestamp))
17332 (message "Time stamp changed to %s" org-last-changed-timestamp)))
17334 (defun org-agenda-date-earlier (arg &optional what)
17335 "Change the date of this item to one day earlier."
17336 (interactive "p")
17337 (org-agenda-date-later (- arg) what))
17339 (defun org-agenda-show-new-time (marker stamp)
17340 "Show new date stamp via text properties."
17341 ;; We use text properties to make this undoable
17342 (let ((buffer-read-only nil))
17343 (setq stamp (concat " => " stamp))
17344 (save-excursion
17345 (goto-char (point-max))
17346 (while (not (bobp))
17347 (when (equal marker (get-text-property (point) 'org-marker))
17348 (move-to-column (- (window-width) (length stamp)) t)
17349 (if (featurep 'xemacs)
17350 ;; Use `duplicable' property to trigger undo recording
17351 (let ((ex (make-extent nil nil))
17352 (gl (make-glyph stamp)))
17353 (set-glyph-face gl 'secondary-selection)
17354 (set-extent-properties
17355 ex (list 'invisible t 'end-glyph gl 'duplicable t))
17356 (insert-extent ex (1- (point)) (point-at-eol)))
17357 (add-text-properties
17358 (1- (point)) (point-at-eol)
17359 (list 'display (org-add-props stamp nil
17360 'face 'secondary-selection))))
17361 (beginning-of-line 1))
17362 (beginning-of-line 0)))))
17364 (defun org-agenda-date-prompt (arg)
17365 "Change the date of this item. Date is prompted for, with default today.
17366 The prefix ARG is passed to the `org-time-stamp' command and can therefore
17367 be used to request time specification in the time stamp."
17368 (interactive "P")
17369 (org-agenda-check-type t 'agenda 'timeline)
17370 (org-agenda-check-no-diary)
17371 (let* ((marker (or (get-text-property (point) 'org-marker)
17372 (org-agenda-error)))
17373 (buffer (marker-buffer marker))
17374 (pos (marker-position marker)))
17375 (org-with-remote-undo buffer
17376 (with-current-buffer buffer
17377 (widen)
17378 (goto-char pos)
17379 (if (not (org-at-timestamp-p))
17380 (error "Cannot find time stamp"))
17381 (org-time-stamp arg)
17382 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
17384 (defun org-agenda-schedule (arg)
17385 "Schedule the item at point."
17386 (interactive "P")
17387 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
17388 (org-agenda-check-no-diary)
17389 (let* ((marker (or (get-text-property (point) 'org-marker)
17390 (org-agenda-error)))
17391 (buffer (marker-buffer marker))
17392 (pos (marker-position marker))
17393 (org-insert-labeled-timestamps-at-point nil)
17395 (org-with-remote-undo buffer
17396 (with-current-buffer buffer
17397 (widen)
17398 (goto-char pos)
17399 (setq ts (org-schedule))
17400 (message "Item scheduled for %s" ts)))))
17402 (defun org-agenda-deadline (arg)
17403 "Schedule the item at point."
17404 (interactive "P")
17405 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
17406 (org-agenda-check-no-diary)
17407 (let* ((marker (or (get-text-property (point) 'org-marker)
17408 (org-agenda-error)))
17409 (buffer (marker-buffer marker))
17410 (pos (marker-position marker))
17411 (org-insert-labeled-timestamps-at-point nil)
17413 (org-with-remote-undo buffer
17414 (with-current-buffer buffer
17415 (widen)
17416 (goto-char pos)
17417 (setq ts (org-deadline))
17418 (message "Deadline for this item set to %s" ts)))))
17420 (defun org-get-heading ()
17421 "Return the heading of the current entry, without the stars."
17422 (save-excursion
17423 (org-back-to-heading t)
17424 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
17426 (defun org-agenda-clock-in (&optional arg)
17427 "Start the clock on the currently selected item."
17428 (interactive "P")
17429 (org-agenda-check-no-diary)
17430 (let* ((marker (or (get-text-property (point) 'org-marker)
17431 (org-agenda-error)))
17432 (pos (marker-position marker)))
17433 (org-with-remote-undo (marker-buffer marker)
17434 (with-current-buffer (marker-buffer marker)
17435 (widen)
17436 (goto-char pos)
17437 (org-clock-in)))))
17439 (defun org-agenda-clock-out (&optional arg)
17440 "Stop the currently running clock."
17441 (interactive "P")
17442 (unless (marker-buffer org-clock-marker)
17443 (error "No running clock"))
17444 (org-with-remote-undo (marker-buffer org-clock-marker)
17445 (org-clock-out)))
17447 (defun org-agenda-clock-cancel (&optional arg)
17448 "Cancel the currently running clock."
17449 (interactive "P")
17450 (unless (marker-buffer org-clock-marker)
17451 (error "No running clock"))
17452 (org-with-remote-undo (marker-buffer org-clock-marker)
17453 (org-clock-cancel)))
17455 (defun org-agenda-diary-entry ()
17456 "Make a diary entry, like the `i' command from the calendar.
17457 All the standard commands work: block, weekly etc."
17458 (interactive)
17459 (org-agenda-check-type t 'agenda 'timeline)
17460 (require 'diary-lib)
17461 (let* ((char (progn
17462 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
17463 (read-char-exclusive)))
17464 (cmd (cdr (assoc char
17465 '((?d . insert-diary-entry)
17466 (?w . insert-weekly-diary-entry)
17467 (?m . insert-monthly-diary-entry)
17468 (?y . insert-yearly-diary-entry)
17469 (?a . insert-anniversary-diary-entry)
17470 (?b . insert-block-diary-entry)
17471 (?c . insert-cyclic-diary-entry)))))
17472 (oldf (symbol-function 'calendar-cursor-to-date))
17473 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
17474 (point (point))
17475 (mark (or (mark t) (point))))
17476 (unless cmd
17477 (error "No command associated with <%c>" char))
17478 (unless (and (get-text-property point 'day)
17479 (or (not (equal ?b char))
17480 (get-text-property mark 'day)))
17481 (error "Don't know which date to use for diary entry"))
17482 ;; We implement this by hacking the `calendar-cursor-to-date' function
17483 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
17484 (let ((calendar-mark-ring
17485 (list (calendar-gregorian-from-absolute
17486 (or (get-text-property mark 'day)
17487 (get-text-property point 'day))))))
17488 (unwind-protect
17489 (progn
17490 (fset 'calendar-cursor-to-date
17491 (lambda (&optional error)
17492 (calendar-gregorian-from-absolute
17493 (get-text-property point 'day))))
17494 (call-interactively cmd))
17495 (fset 'calendar-cursor-to-date oldf)))))
17498 (defun org-agenda-execute-calendar-command (cmd)
17499 "Execute a calendar command from the agenda, with the date associated to
17500 the cursor position."
17501 (org-agenda-check-type t 'agenda 'timeline)
17502 (require 'diary-lib)
17503 (unless (get-text-property (point) 'day)
17504 (error "Don't know which date to use for calendar command"))
17505 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
17506 (point (point))
17507 (date (calendar-gregorian-from-absolute
17508 (get-text-property point 'day)))
17509 ;; the following 3 vars are needed in the calendar
17510 (displayed-day (extract-calendar-day date))
17511 (displayed-month (extract-calendar-month date))
17512 (displayed-year (extract-calendar-year date)))
17513 (unwind-protect
17514 (progn
17515 (fset 'calendar-cursor-to-date
17516 (lambda (&optional error)
17517 (calendar-gregorian-from-absolute
17518 (get-text-property point 'day))))
17519 (call-interactively cmd))
17520 (fset 'calendar-cursor-to-date oldf))))
17522 (defun org-agenda-phases-of-moon ()
17523 "Display the phases of the moon for the 3 months around the cursor date."
17524 (interactive)
17525 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
17527 (defun org-agenda-holidays ()
17528 "Display the holidays for the 3 months around the cursor date."
17529 (interactive)
17530 (org-agenda-execute-calendar-command 'list-calendar-holidays))
17532 (defun org-agenda-sunrise-sunset (arg)
17533 "Display sunrise and sunset for the cursor date.
17534 Latitude and longitude can be specified with the variables
17535 `calendar-latitude' and `calendar-longitude'. When called with prefix
17536 argument, latitude and longitude will be prompted for."
17537 (interactive "P")
17538 (let ((calendar-longitude (if arg nil calendar-longitude))
17539 (calendar-latitude (if arg nil calendar-latitude))
17540 (calendar-location-name
17541 (if arg "the given coordinates" calendar-location-name)))
17542 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
17544 (defun org-agenda-goto-calendar ()
17545 "Open the Emacs calendar with the date at the cursor."
17546 (interactive)
17547 (org-agenda-check-type t 'agenda 'timeline)
17548 (let* ((day (or (get-text-property (point) 'day)
17549 (error "Don't know which date to open in calendar")))
17550 (date (calendar-gregorian-from-absolute day))
17551 (calendar-move-hook nil)
17552 (view-calendar-holidays-initially nil)
17553 (view-diary-entries-initially nil))
17554 (calendar)
17555 (calendar-goto-date date)))
17557 (defun org-calendar-goto-agenda ()
17558 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
17559 This is a command that has to be installed in `calendar-mode-map'."
17560 (interactive)
17561 (org-agenda-list nil (calendar-absolute-from-gregorian
17562 (calendar-cursor-to-date))
17563 nil))
17565 (defun org-agenda-convert-date ()
17566 (interactive)
17567 (org-agenda-check-type t 'agenda 'timeline)
17568 (let ((day (get-text-property (point) 'day))
17569 date s)
17570 (unless day
17571 (error "Don't know which date to convert"))
17572 (setq date (calendar-gregorian-from-absolute day))
17573 (setq s (concat
17574 "Gregorian: " (calendar-date-string date) "\n"
17575 "ISO: " (calendar-iso-date-string date) "\n"
17576 "Day of Yr: " (calendar-day-of-year-string date) "\n"
17577 "Julian: " (calendar-julian-date-string date) "\n"
17578 "Astron. JD: " (calendar-astro-date-string date)
17579 " (Julian date number at noon UTC)\n"
17580 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
17581 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
17582 "French: " (calendar-french-date-string date) "\n"
17583 "Mayan: " (calendar-mayan-date-string date) "\n"
17584 "Coptic: " (calendar-coptic-date-string date) "\n"
17585 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
17586 "Persian: " (calendar-persian-date-string date) "\n"
17587 "Chinese: " (calendar-chinese-date-string date) "\n"))
17588 (with-output-to-temp-buffer "*Dates*"
17589 (princ s))
17590 (if (fboundp 'fit-window-to-buffer)
17591 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
17594 ;;;; Embedded LaTeX
17596 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17597 "Keymap for the minor `org-cdlatex-mode'.")
17599 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17600 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17601 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17602 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17603 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17605 (defvar org-cdlatex-texmathp-advice-is-done nil
17606 "Flag remembering if we have applied the advice to texmathp already.")
17608 (define-minor-mode org-cdlatex-mode
17609 "Toggle the minor `org-cdlatex-mode'.
17610 This mode supports entering LaTeX environment and math in LaTeX fragments
17611 in Org-mode.
17612 \\{org-cdlatex-mode-map}"
17613 nil " OCDL" nil
17614 (when org-cdlatex-mode (require 'cdlatex))
17615 (unless org-cdlatex-texmathp-advice-is-done
17616 (setq org-cdlatex-texmathp-advice-is-done t)
17617 (defadvice texmathp (around org-math-always-on activate)
17618 "Always return t in org-mode buffers.
17619 This is because we want to insert math symbols without dollars even outside
17620 the LaTeX math segments. If Orgmode thinks that point is actually inside
17621 en embedded LaTeX fragement, let texmathp do its job.
17622 \\[org-cdlatex-mode-map]"
17623 (interactive)
17624 (let (p)
17625 (cond
17626 ((not (org-mode-p)) ad-do-it)
17627 ((eq this-command 'cdlatex-math-symbol)
17628 (setq ad-return-value t
17629 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17631 (let ((p (org-inside-LaTeX-fragment-p)))
17632 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17633 (setq ad-return-value t
17634 texmathp-why '("Org-mode embedded math" . 0))
17635 (if p ad-do-it)))))))))
17637 (defun turn-on-org-cdlatex ()
17638 "Unconditionally turn on `org-cdlatex-mode'."
17639 (org-cdlatex-mode 1))
17641 (defun org-inside-LaTeX-fragment-p ()
17642 "Test if point is inside a LaTeX fragment.
17643 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17644 sequence appearing also before point.
17645 Even though the matchers for math are configurable, this function assumes
17646 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17647 delimiters are skipped when they have been removed by customization.
17648 The return value is nil, or a cons cell with the delimiter and
17649 and the position of this delimiter.
17651 This function does a reasonably good job, but can locally be fooled by
17652 for example currency specifications. For example it will assume being in
17653 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17654 fragments that are properly closed, but during editing, we have to live
17655 with the uncertainty caused by missing closing delimiters. This function
17656 looks only before point, not after."
17657 (catch 'exit
17658 (let ((pos (point))
17659 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17660 (lim (progn
17661 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17662 (point)))
17663 dd-on str (start 0) m re)
17664 (goto-char pos)
17665 (when dodollar
17666 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17667 re (nth 1 (assoc "$" org-latex-regexps)))
17668 (while (string-match re str start)
17669 (cond
17670 ((= (match-end 0) (length str))
17671 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17672 ((= (match-end 0) (- (length str) 5))
17673 (throw 'exit nil))
17674 (t (setq start (match-end 0))))))
17675 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17676 (goto-char pos)
17677 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17678 (and (match-beginning 2) (throw 'exit nil))
17679 ;; count $$
17680 (while (re-search-backward "\\$\\$" lim t)
17681 (setq dd-on (not dd-on)))
17682 (goto-char pos)
17683 (if dd-on (cons "$$" m))))))
17686 (defun org-try-cdlatex-tab ()
17687 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17688 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17689 - inside a LaTeX fragment, or
17690 - after the first word in a line, where an abbreviation expansion could
17691 insert a LaTeX environment."
17692 (when org-cdlatex-mode
17693 (cond
17694 ((save-excursion
17695 (skip-chars-backward "a-zA-Z0-9*")
17696 (skip-chars-backward " \t")
17697 (bolp))
17698 (cdlatex-tab) t)
17699 ((org-inside-LaTeX-fragment-p)
17700 (cdlatex-tab) t)
17701 (t nil))))
17703 (defun org-cdlatex-underscore-caret (&optional arg)
17704 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17705 Revert to the normal definition outside of these fragments."
17706 (interactive "P")
17707 (if (org-inside-LaTeX-fragment-p)
17708 (call-interactively 'cdlatex-sub-superscript)
17709 (let (org-cdlatex-mode)
17710 (call-interactively (key-binding (vector last-input-event))))))
17712 (defun org-cdlatex-math-modify (&optional arg)
17713 "Execute `cdlatex-math-modify' in LaTeX fragments.
17714 Revert to the normal definition outside of these fragments."
17715 (interactive "P")
17716 (if (org-inside-LaTeX-fragment-p)
17717 (call-interactively 'cdlatex-math-modify)
17718 (let (org-cdlatex-mode)
17719 (call-interactively (key-binding (vector last-input-event))))))
17721 (defvar org-latex-fragment-image-overlays nil
17722 "List of overlays carrying the images of latex fragments.")
17723 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17725 (defun org-remove-latex-fragment-image-overlays ()
17726 "Remove all overlays with LaTeX fragment images in current buffer."
17727 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
17728 (setq org-latex-fragment-image-overlays nil))
17730 (defun org-preview-latex-fragment (&optional subtree)
17731 "Preview the LaTeX fragment at point, or all locally or globally.
17732 If the cursor is in a LaTeX fragment, create the image and overlay
17733 it over the source code. If there is no fragment at point, display
17734 all fragments in the current text, from one headline to the next. With
17735 prefix SUBTREE, display all fragments in the current subtree. With a
17736 double prefix `C-u C-u', or when the cursor is before the first headline,
17737 display all fragments in the buffer.
17738 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17739 (interactive "P")
17740 (org-remove-latex-fragment-image-overlays)
17741 (save-excursion
17742 (save-restriction
17743 (let (beg end at msg)
17744 (cond
17745 ((or (equal subtree '(16))
17746 (not (save-excursion
17747 (re-search-backward (concat "^" outline-regexp) nil t))))
17748 (setq beg (point-min) end (point-max)
17749 msg "Creating images for buffer...%s"))
17750 ((equal subtree '(4))
17751 (org-back-to-heading)
17752 (setq beg (point) end (org-end-of-subtree t)
17753 msg "Creating images for subtree...%s"))
17755 (if (setq at (org-inside-LaTeX-fragment-p))
17756 (goto-char (max (point-min) (- (cdr at) 2)))
17757 (org-back-to-heading))
17758 (setq beg (point) end (progn (outline-next-heading) (point))
17759 msg (if at "Creating image...%s"
17760 "Creating images for entry...%s"))))
17761 (message msg "")
17762 (narrow-to-region beg end)
17763 (goto-char beg)
17764 (org-format-latex
17765 (concat "ltxpng/" (file-name-sans-extension
17766 (file-name-nondirectory
17767 buffer-file-name)))
17768 default-directory 'overlays msg at 'forbuffer)
17769 (message msg "done. Use `C-c C-c' to remove images.")))))
17771 (defvar org-latex-regexps
17772 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17773 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17774 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17775 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
17776 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17777 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
17778 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
17779 "Regular expressions for matching embedded LaTeX.")
17781 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
17782 "Replace LaTeX fragments with links to an image, and produce images."
17783 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17784 (let* ((prefixnodir (file-name-nondirectory prefix))
17785 (absprefix (expand-file-name prefix dir))
17786 (todir (file-name-directory absprefix))
17787 (opt org-format-latex-options)
17788 (matchers (plist-get opt :matchers))
17789 (re-list org-latex-regexps)
17790 (cnt 0) txt link beg end re e checkdir
17791 m n block linkfile movefile ov)
17792 ;; Check if there are old images files with this prefix, and remove them
17793 (when (file-directory-p todir)
17794 (mapc 'delete-file
17795 (directory-files
17796 todir 'full
17797 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
17798 ;; Check the different regular expressions
17799 (while (setq e (pop re-list))
17800 (setq m (car e) re (nth 1 e) n (nth 2 e)
17801 block (if (nth 3 e) "\n\n" ""))
17802 (when (member m matchers)
17803 (goto-char (point-min))
17804 (while (re-search-forward re nil t)
17805 (when (or (not at) (equal (cdr at) (match-beginning n)))
17806 (setq txt (match-string n)
17807 beg (match-beginning n) end (match-end n)
17808 cnt (1+ cnt)
17809 linkfile (format "%s_%04d.png" prefix cnt)
17810 movefile (format "%s_%04d.png" absprefix cnt)
17811 link (concat block "[[file:" linkfile "]]" block))
17812 (if msg (message msg cnt))
17813 (goto-char beg)
17814 (unless checkdir ; make sure the directory exists
17815 (setq checkdir t)
17816 (or (file-directory-p todir) (make-directory todir)))
17817 (org-create-formula-image
17818 txt movefile opt forbuffer)
17819 (if overlays
17820 (progn
17821 (setq ov (org-make-overlay beg end))
17822 (if (featurep 'xemacs)
17823 (progn
17824 (org-overlay-put ov 'invisible t)
17825 (org-overlay-put
17826 ov 'end-glyph
17827 (make-glyph (vector 'png :file movefile))))
17828 (org-overlay-put
17829 ov 'display
17830 (list 'image :type 'png :file movefile :ascent 'center)))
17831 (push ov org-latex-fragment-image-overlays)
17832 (goto-char end))
17833 (delete-region beg end)
17834 (insert link))))))))
17836 ;; This function borrows from Ganesh Swami's latex2png.el
17837 (defun org-create-formula-image (string tofile options buffer)
17838 (let* ((tmpdir (if (featurep 'xemacs)
17839 (temp-directory)
17840 temporary-file-directory))
17841 (texfilebase (make-temp-name
17842 (expand-file-name "orgtex" tmpdir)))
17843 (texfile (concat texfilebase ".tex"))
17844 (dvifile (concat texfilebase ".dvi"))
17845 (pngfile (concat texfilebase ".png"))
17846 (fnh (face-attribute 'default :height nil))
17847 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17848 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17849 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17850 "Black"))
17851 (bg (or (plist-get options (if buffer :background :html-background))
17852 "Transparent")))
17853 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17854 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17855 (with-temp-file texfile
17856 (insert org-format-latex-header
17857 "\n\\begin{document}\n" string "\n\\end{document}\n"))
17858 (let ((dir default-directory))
17859 (condition-case nil
17860 (progn
17861 (cd tmpdir)
17862 (call-process "latex" nil nil nil texfile))
17863 (error nil))
17864 (cd dir))
17865 (if (not (file-exists-p dvifile))
17866 (progn (message "Failed to create dvi file from %s" texfile) nil)
17867 (call-process "dvipng" nil nil nil
17868 "-E" "-fg" fg "-bg" bg
17869 "-D" dpi
17870 ;;"-x" scale "-y" scale
17871 "-T" "tight"
17872 "-o" pngfile
17873 dvifile)
17874 (if (not (file-exists-p pngfile))
17875 (progn (message "Failed to create png file from %s" texfile) nil)
17876 ;; Use the requested file name and clean up
17877 (copy-file pngfile tofile 'replace)
17878 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
17879 (delete-file (concat texfilebase e)))
17880 pngfile))))
17882 (defun org-dvipng-color (attr)
17883 "Return an rgb color specification for dvipng."
17884 (apply 'format "rgb %s %s %s"
17885 (mapcar 'org-normalize-color
17886 (color-values (face-attribute 'default attr nil)))))
17888 (defun org-normalize-color (value)
17889 "Return string to be used as color value for an RGB component."
17890 (format "%g" (/ value 65535.0)))
17892 ;;;; Exporting
17894 ;;; Variables, constants, and parameter plists
17896 (defconst org-level-max 20)
17898 (defvar org-export-html-preamble nil
17899 "Preamble, to be inserted just after <body>. Set by publishing functions.")
17900 (defvar org-export-html-postamble nil
17901 "Preamble, to be inserted just before </body>. Set by publishing functions.")
17902 (defvar org-export-html-auto-preamble t
17903 "Should default preamble be inserted? Set by publishing functions.")
17904 (defvar org-export-html-auto-postamble t
17905 "Should default postamble be inserted? Set by publishing functions.")
17906 (defvar org-current-export-file nil) ; dynamically scoped parameter
17907 (defvar org-current-export-dir nil) ; dynamically scoped parameter
17910 (defconst org-export-plist-vars
17911 '((:language . org-export-default-language)
17912 (:customtime . org-display-custom-times)
17913 (:headline-levels . org-export-headline-levels)
17914 (:section-numbers . org-export-with-section-numbers)
17915 (:table-of-contents . org-export-with-toc)
17916 (:preserve-breaks . org-export-preserve-breaks)
17917 (:archived-trees . org-export-with-archived-trees)
17918 (:emphasize . org-export-with-emphasize)
17919 (:sub-superscript . org-export-with-sub-superscripts)
17920 (:TeX-macros . org-export-with-TeX-macros)
17921 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
17922 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
17923 (:fixed-width . org-export-with-fixed-width)
17924 (:timestamps . org-export-with-timestamps)
17925 (:tables . org-export-with-tables)
17926 (:table-auto-headline . org-export-highlight-first-table-line)
17927 (:style . org-export-html-style)
17928 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
17929 (:convert-org-links . org-export-html-link-org-files-as-html)
17930 (:inline-images . org-export-html-inline-images)
17931 (:expand-quoted-html . org-export-html-expand)
17932 (:timestamp . org-export-html-with-timestamp)
17933 (:publishing-directory . org-export-publishing-directory)
17934 (:preamble . org-export-html-preamble)
17935 (:postamble . org-export-html-postamble)
17936 (:auto-preamble . org-export-html-auto-preamble)
17937 (:auto-postamble . org-export-html-auto-postamble)
17938 (:author . user-full-name)
17939 (:email . user-mail-address)))
17941 (defun org-default-export-plist ()
17942 "Return the property list with default settings for the export variables."
17943 (let ((l org-export-plist-vars) rtn e)
17944 (while (setq e (pop l))
17945 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
17946 rtn))
17948 (defun org-infile-export-plist ()
17949 "Return the property list with file-local settings for export."
17950 (save-excursion
17951 (goto-char 0)
17952 (let ((re (org-make-options-regexp
17953 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
17954 p key val text options)
17955 (while (re-search-forward re nil t)
17956 (setq key (org-match-string-no-properties 1)
17957 val (org-match-string-no-properties 2))
17958 (cond
17959 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
17960 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
17961 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
17962 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
17963 ((string-equal key "TEXT")
17964 (setq text (if text (concat text "\n" val) val)))
17965 ((string-equal key "OPTIONS") (setq options val))))
17966 (setq p (plist-put p :text text))
17967 (when options
17968 (let ((op '(("H" . :headline-levels)
17969 ("num" . :section-numbers)
17970 ("toc" . :table-of-contents)
17971 ("\\n" . :preserve-breaks)
17972 ("@" . :expand-quoted-html)
17973 (":" . :fixed-width)
17974 ("|" . :tables)
17975 ("^" . :sub-superscript)
17976 ("*" . :emphasize)
17977 ("TeX" . :TeX-macros)
17978 ("LaTeX" . :LaTeX-fragments)
17979 ("skip" . :skip-before-1st-heading)))
17981 (while (setq o (pop op))
17982 (if (string-match (concat (regexp-quote (car o))
17983 ":\\([^ \t\n\r;,.]*\\)")
17984 options)
17985 (setq p (plist-put p (cdr o)
17986 (car (read-from-string
17987 (match-string 1 options)))))))))
17988 p)))
17990 (defun org-export-directory (type plist)
17991 (let* ((val (plist-get plist :publishing-directory))
17992 (dir (if (listp val)
17993 (or (cdr (assoc type val)) ".")
17994 val)))
17995 dir))
17997 (defun org-skip-comments (lines)
17998 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
17999 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
18000 (re2 "^\\(\\*+\\)[ \t\n\r]")
18001 (case-fold-search nil)
18002 rtn line level)
18003 (while (setq line (pop lines))
18004 (cond
18005 ((and (string-match re1 line)
18006 (setq level (- (match-end 1) (match-beginning 1))))
18007 ;; Beginning of a COMMENT subtree. Skip it.
18008 (while (and (setq line (pop lines))
18009 (or (not (string-match re2 line))
18010 (> (- (match-end 1) (match-beginning 1)) level))))
18011 (setq lines (cons line lines)))
18012 ((string-match "^#" line)
18013 ;; an ordinary comment line
18015 ((and org-export-table-remove-special-lines
18016 (string-match "^[ \t]*|" line)
18017 (or (string-match "^[ \t]*| *[!_^] *|" line)
18018 (and (string-match "| *<[0-9]+> *|" line)
18019 (not (string-match "| *[^ <|]" line)))))
18020 ;; a special table line that should be removed
18022 (t (setq rtn (cons line rtn)))))
18023 (nreverse rtn)))
18025 (defun org-export (&optional arg)
18026 (interactive)
18027 (let ((help "[t] insert the export option template
18028 \[v] limit export to visible part of outline tree
18030 \[a] export as ASCII
18031 \[h] export as HTML
18032 \[H] export as HTML to temporary buffer
18033 \[b] export as HTML and browse immediately
18034 \[x] export as XOXO
18036 \[i] export current file as iCalendar file
18037 \[I] export all agenda files as iCalendar files
18038 \[c] export agenda files into combined iCalendar file
18040 \[F] publish current file
18041 \[P] publish current project
18042 \[X] publish... (project will be prompted for)
18043 \[A] publish all projects")
18044 (cmds
18045 '((?t . org-insert-export-options-template)
18046 (?v . org-export-visible)
18047 (?a . org-export-as-ascii)
18048 (?h . org-export-as-html)
18049 (?b . org-export-as-html-and-open)
18050 (?H . org-export-as-html-to-buffer)
18051 (?R . org-export-region-as-html)
18052 (?x . org-export-as-xoxo)
18053 (?i . org-export-icalendar-this-file)
18054 (?I . org-export-icalendar-all-agenda-files)
18055 (?c . org-export-icalendar-combine-agenda-files)
18056 (?F . org-publish-current-file)
18057 (?P . org-publish-current-project)
18058 (?X . org-publish)
18059 (?A . org-publish-all)))
18060 r1 r2 ass)
18061 (save-window-excursion
18062 (delete-other-windows)
18063 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
18064 (princ help))
18065 (message "Select command: ")
18066 (setq r1 (read-char-exclusive)))
18067 (setq r2 (if (< r1 27) (+ r1 96) r1))
18068 (if (setq ass (assq r2 cmds))
18069 (call-interactively (cdr ass))
18070 (error "No command associated with key %c" r1))))
18072 (defconst org-html-entities
18073 '(("nbsp")
18074 ("iexcl")
18075 ("cent")
18076 ("pound")
18077 ("curren")
18078 ("yen")
18079 ("brvbar")
18080 ("vert" . "&#124;")
18081 ("sect")
18082 ("uml")
18083 ("copy")
18084 ("ordf")
18085 ("laquo")
18086 ("not")
18087 ("shy")
18088 ("reg")
18089 ("macr")
18090 ("deg")
18091 ("plusmn")
18092 ("sup2")
18093 ("sup3")
18094 ("acute")
18095 ("micro")
18096 ("para")
18097 ("middot")
18098 ("odot"."o")
18099 ("star"."*")
18100 ("cedil")
18101 ("sup1")
18102 ("ordm")
18103 ("raquo")
18104 ("frac14")
18105 ("frac12")
18106 ("frac34")
18107 ("iquest")
18108 ("Agrave")
18109 ("Aacute")
18110 ("Acirc")
18111 ("Atilde")
18112 ("Auml")
18113 ("Aring") ("AA"."&Aring;")
18114 ("AElig")
18115 ("Ccedil")
18116 ("Egrave")
18117 ("Eacute")
18118 ("Ecirc")
18119 ("Euml")
18120 ("Igrave")
18121 ("Iacute")
18122 ("Icirc")
18123 ("Iuml")
18124 ("ETH")
18125 ("Ntilde")
18126 ("Ograve")
18127 ("Oacute")
18128 ("Ocirc")
18129 ("Otilde")
18130 ("Ouml")
18131 ("times")
18132 ("Oslash")
18133 ("Ugrave")
18134 ("Uacute")
18135 ("Ucirc")
18136 ("Uuml")
18137 ("Yacute")
18138 ("THORN")
18139 ("szlig")
18140 ("agrave")
18141 ("aacute")
18142 ("acirc")
18143 ("atilde")
18144 ("auml")
18145 ("aring")
18146 ("aelig")
18147 ("ccedil")
18148 ("egrave")
18149 ("eacute")
18150 ("ecirc")
18151 ("euml")
18152 ("igrave")
18153 ("iacute")
18154 ("icirc")
18155 ("iuml")
18156 ("eth")
18157 ("ntilde")
18158 ("ograve")
18159 ("oacute")
18160 ("ocirc")
18161 ("otilde")
18162 ("ouml")
18163 ("divide")
18164 ("oslash")
18165 ("ugrave")
18166 ("uacute")
18167 ("ucirc")
18168 ("uuml")
18169 ("yacute")
18170 ("thorn")
18171 ("yuml")
18172 ("fnof")
18173 ("Alpha")
18174 ("Beta")
18175 ("Gamma")
18176 ("Delta")
18177 ("Epsilon")
18178 ("Zeta")
18179 ("Eta")
18180 ("Theta")
18181 ("Iota")
18182 ("Kappa")
18183 ("Lambda")
18184 ("Mu")
18185 ("Nu")
18186 ("Xi")
18187 ("Omicron")
18188 ("Pi")
18189 ("Rho")
18190 ("Sigma")
18191 ("Tau")
18192 ("Upsilon")
18193 ("Phi")
18194 ("Chi")
18195 ("Psi")
18196 ("Omega")
18197 ("alpha")
18198 ("beta")
18199 ("gamma")
18200 ("delta")
18201 ("epsilon")
18202 ("varepsilon"."&epsilon;")
18203 ("zeta")
18204 ("eta")
18205 ("theta")
18206 ("iota")
18207 ("kappa")
18208 ("lambda")
18209 ("mu")
18210 ("nu")
18211 ("xi")
18212 ("omicron")
18213 ("pi")
18214 ("rho")
18215 ("sigmaf") ("varsigma"."&sigmaf;")
18216 ("sigma")
18217 ("tau")
18218 ("upsilon")
18219 ("phi")
18220 ("chi")
18221 ("psi")
18222 ("omega")
18223 ("thetasym") ("vartheta"."&thetasym;")
18224 ("upsih")
18225 ("piv")
18226 ("bull") ("bullet"."&bull;")
18227 ("hellip") ("dots"."&hellip;")
18228 ("prime")
18229 ("Prime")
18230 ("oline")
18231 ("frasl")
18232 ("weierp")
18233 ("image")
18234 ("real")
18235 ("trade")
18236 ("alefsym")
18237 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
18238 ("uarr") ("uparrow"."&uarr;")
18239 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
18240 ("darr")("downarrow"."&darr;")
18241 ("harr") ("leftrightarrow"."&harr;")
18242 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
18243 ("lArr") ("Leftarrow"."&lArr;")
18244 ("uArr") ("Uparrow"."&uArr;")
18245 ("rArr") ("Rightarrow"."&rArr;")
18246 ("dArr") ("Downarrow"."&dArr;")
18247 ("hArr") ("Leftrightarrow"."&hArr;")
18248 ("forall")
18249 ("part") ("partial"."&part;")
18250 ("exist") ("exists"."&exist;")
18251 ("empty") ("emptyset"."&empty;")
18252 ("nabla")
18253 ("isin") ("in"."&isin;")
18254 ("notin")
18255 ("ni")
18256 ("prod")
18257 ("sum")
18258 ("minus")
18259 ("lowast") ("ast"."&lowast;")
18260 ("radic")
18261 ("prop") ("proptp"."&prop;")
18262 ("infin") ("infty"."&infin;")
18263 ("ang") ("angle"."&ang;")
18264 ("and") ("vee"."&and;")
18265 ("or") ("wedge"."&or;")
18266 ("cap")
18267 ("cup")
18268 ("int")
18269 ("there4")
18270 ("sim")
18271 ("cong") ("simeq"."&cong;")
18272 ("asymp")("approx"."&asymp;")
18273 ("ne") ("neq"."&ne;")
18274 ("equiv")
18275 ("le")
18276 ("ge")
18277 ("sub") ("subset"."&sub;")
18278 ("sup") ("supset"."&sup;")
18279 ("nsub")
18280 ("sube")
18281 ("supe")
18282 ("oplus")
18283 ("otimes")
18284 ("perp")
18285 ("sdot") ("cdot"."&sdot;")
18286 ("lceil")
18287 ("rceil")
18288 ("lfloor")
18289 ("rfloor")
18290 ("lang")
18291 ("rang")
18292 ("loz") ("Diamond"."&loz;")
18293 ("spades") ("spadesuit"."&spades;")
18294 ("clubs") ("clubsuit"."&clubs;")
18295 ("hearts") ("diamondsuit"."&hearts;")
18296 ("diams") ("diamondsuit"."&diams;")
18297 ("quot")
18298 ("amp")
18299 ("lt")
18300 ("gt")
18301 ("OElig")
18302 ("oelig")
18303 ("Scaron")
18304 ("scaron")
18305 ("Yuml")
18306 ("circ")
18307 ("tilde")
18308 ("ensp")
18309 ("emsp")
18310 ("thinsp")
18311 ("zwnj")
18312 ("zwj")
18313 ("lrm")
18314 ("rlm")
18315 ("ndash")
18316 ("mdash")
18317 ("lsquo")
18318 ("rsquo")
18319 ("sbquo")
18320 ("ldquo")
18321 ("rdquo")
18322 ("bdquo")
18323 ("dagger")
18324 ("Dagger")
18325 ("permil")
18326 ("lsaquo")
18327 ("rsaquo")
18328 ("euro")
18330 ("arccos"."arccos")
18331 ("arcsin"."arcsin")
18332 ("arctan"."arctan")
18333 ("arg"."arg")
18334 ("cos"."cos")
18335 ("cosh"."cosh")
18336 ("cot"."cot")
18337 ("coth"."coth")
18338 ("csc"."csc")
18339 ("deg"."deg")
18340 ("det"."det")
18341 ("dim"."dim")
18342 ("exp"."exp")
18343 ("gcd"."gcd")
18344 ("hom"."hom")
18345 ("inf"."inf")
18346 ("ker"."ker")
18347 ("lg"."lg")
18348 ("lim"."lim")
18349 ("liminf"."liminf")
18350 ("limsup"."limsup")
18351 ("ln"."ln")
18352 ("log"."log")
18353 ("max"."max")
18354 ("min"."min")
18355 ("Pr"."Pr")
18356 ("sec"."sec")
18357 ("sin"."sin")
18358 ("sinh"."sinh")
18359 ("sup"."sup")
18360 ("tan"."tan")
18361 ("tanh"."tanh")
18363 "Entities for TeX->HTML translation.
18364 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
18365 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
18366 In that case, \"\\ent\" will be translated to \"&other;\".
18367 The list contains HTML entities for Latin-1, Greek and other symbols.
18368 It is supplemented by a number of commonly used TeX macros with appropriate
18369 translations. There is currently no way for users to extend this.")
18371 ;;; General functions for all backends
18373 (defun org-cleaned-string-for-export (string &rest parameters)
18374 "Cleanup a buffer substring so that links can be created safely."
18375 (interactive)
18376 (let* ((re-radio (and org-target-link-regexp
18377 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
18378 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
18379 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
18380 (re-archive (concat ":" org-archive-tag ":"))
18381 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
18382 (htmlp (plist-get parameters :for-html))
18383 (outline-regexp "\\*+")
18385 rtn p)
18386 (save-excursion
18387 (set-buffer (get-buffer-create " org-mode-tmp"))
18388 (erase-buffer)
18389 (insert string)
18390 ;; Remove license-to-kill stuff
18391 (while (setq p (text-property-any (point-min) (point-max)
18392 :org-license-to-kill t))
18393 (delete-region p (next-single-property-change p :org-license-to-kill)))
18395 (let ((org-inhibit-startup t)) (org-mode))
18396 (untabify (point-min) (point-max))
18398 ;; Get the correct stuff before the first headline
18399 (when (plist-get parameters :skip-before-1st-heading)
18400 (goto-char (point-min))
18401 (when (re-search-forward "^\\*+[ \t]" nil t)
18402 (delete-region (point-min) (match-beginning 0))
18403 (goto-char (point-min))
18404 (insert "\n")))
18405 (when (plist-get parameters :add-text)
18406 (goto-char (point-min))
18407 (insert (plist-get parameters :add-text) "\n"))
18409 ;; Get rid of archived trees
18410 (when (not (eq org-export-with-archived-trees t))
18411 (goto-char (point-min))
18412 (while (re-search-forward re-archive nil t)
18413 (if (not (org-on-heading-p t))
18414 (org-end-of-subtree t)
18415 (beginning-of-line 1)
18416 (setq a (if org-export-with-archived-trees
18417 (1+ (point-at-eol)) (point))
18418 b (org-end-of-subtree t))
18419 (if (> b a) (delete-region a b)))))
18421 ;; Protect stuff from HTML processing
18422 (goto-char (point-min))
18423 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
18424 (add-text-properties (match-beginning 0) (match-end 0)
18425 '(org-protected t)))
18426 (when htmlp
18427 (goto-char (point-min))
18428 (while (re-search-forward "^#\\+HTML:[ \t]*\\(.*\\)" nil t)
18429 (replace-match "\\1" t)
18430 (add-text-properties
18431 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
18432 '(org-protected t))))
18433 (goto-char (point-min))
18434 (while (re-search-forward
18435 "^#\\+BEGIN_HTML\\>.*\\(\\(\n.*\\)*?\n\\)#\\+END_HTML\\>.*\n?" nil t)
18436 (if htmlp
18437 (add-text-properties (match-beginning 1) (1+ (match-end 1))
18438 '(org-protected t))
18439 (delete-region (match-beginning 0) (match-end 0))))
18440 (goto-char (point-min))
18441 (while (re-search-forward re-quote nil t)
18442 (goto-char (match-beginning 0))
18443 (end-of-line 1)
18444 (add-text-properties (point) (org-end-of-subtree t)
18445 '(org-protected t)))
18447 ;; Find targets in comments and move them out of comments,
18448 ;; but mark them as targets that should be invisible
18449 (goto-char (point-min))
18450 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
18451 (replace-match "\\1(INVISIBLE)"))
18453 ;; Remove comments
18454 (goto-char (point-min))
18455 (while (re-search-forward "^#.*\n?" nil t)
18456 (replace-match ""))
18458 ;; Find matches for radio targets and turn them into internal links
18459 (goto-char (point-min))
18460 (when re-radio
18461 (while (re-search-forward re-radio nil t)
18462 (org-if-unprotected
18463 (replace-match "\\1[[\\2]]"))))
18465 ;; Find all links that contain a newline and put them into a single line
18466 (goto-char (point-min))
18467 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
18468 (org-if-unprotected
18469 (replace-match "\\1 \\3")
18470 (goto-char (match-beginning 0))))
18472 ;; Convert LaTeX fragments to images
18473 (when (plist-get parameters :LaTeX-fragments)
18474 (org-format-latex
18475 (concat "ltxpng/" (file-name-sans-extension
18476 (file-name-nondirectory
18477 org-current-export-file)))
18478 org-current-export-dir nil "Creating LaTeX image %s"))
18479 (message "Exporting...")
18481 ;; Normalize links: Convert angle and plain links into bracket links
18482 ;; Expand link abbreviations
18483 (goto-char (point-min))
18484 (while (re-search-forward re-plain-link nil t)
18485 (goto-char (1- (match-end 0)))
18486 (org-if-unprotected
18487 (replace-match
18488 (concat
18489 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
18490 t t)))
18491 (goto-char (point-min))
18492 (while (re-search-forward re-angle-link nil t)
18493 (goto-char (1- (match-end 0)))
18494 (org-if-unprotected
18495 (replace-match
18496 (concat
18497 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
18498 t t)))
18499 (goto-char (point-min))
18500 (while (re-search-forward org-bracket-link-regexp nil t)
18501 (org-if-unprotected
18502 (replace-match
18503 (concat "[[" (save-match-data
18504 (org-link-expand-abbrev (match-string 1)))
18506 (if (match-end 3)
18507 (match-string 2)
18508 (concat "[" (match-string 1) "]"))
18509 "]")
18510 t t)))
18512 ;; Find multiline emphasis and put them into single line
18513 (when (plist-get parameters :emph-multiline)
18514 (goto-char (point-min))
18515 (while (re-search-forward org-emph-re nil t)
18516 (if (not (= (char-after (match-beginning 3))
18517 (char-after (match-beginning 4))))
18518 (org-if-unprotected
18519 (subst-char-in-region (match-beginning 0) (match-end 0)
18520 ?\n ?\ t)
18521 (goto-char (1- (match-end 0))))
18522 (goto-char (1+ (match-beginning 0))))))
18524 (setq rtn (buffer-string)))
18525 (kill-buffer " org-mode-tmp")
18526 rtn))
18528 (defun org-export-grab-title-from-buffer ()
18529 "Get a title for the current document, from looking at the buffer."
18530 (let (buffer-read-only)
18531 (save-excursion
18532 (goto-char (point-min))
18533 (let ((end (save-excursion (outline-next-heading) (point))))
18534 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
18535 ;; Mark the line so that it will not be exported as normal text.
18536 (org-unmodified
18537 (add-text-properties (match-beginning 0) (match-end 0)
18538 (list :org-license-to-kill t)))
18539 ;; Return the title string
18540 (org-trim (match-string 0)))))))
18542 (defun org-solidify-link-text (s &optional alist)
18543 "Take link text and make a safe target out of it."
18544 (save-match-data
18545 (let* ((rtn
18546 (mapconcat
18547 'identity
18548 (org-split-string s "[ \t\r\n]+") "--"))
18549 (a (assoc rtn alist)))
18550 (or (cdr a) rtn))))
18552 ;; Variable holding the vector with section numbers
18553 (defvar org-section-numbers (make-vector org-level-max 0))
18555 (defun org-init-section-numbers ()
18556 "Initialize the vector for the section numbers."
18557 (let* ((level -1)
18558 (numbers (nreverse (org-split-string "" "\\.")))
18559 (depth (1- (length org-section-numbers)))
18560 (i depth) number-string)
18561 (while (>= i 0)
18562 (if (> i level)
18563 (aset org-section-numbers i 0)
18564 (setq number-string (or (car numbers) "0"))
18565 (if (string-match "\\`[A-Z]\\'" number-string)
18566 (aset org-section-numbers i
18567 (- (string-to-char number-string) ?A -1))
18568 (aset org-section-numbers i (string-to-number number-string)))
18569 (pop numbers))
18570 (setq i (1- i)))))
18572 (defun org-section-number (&optional level)
18573 "Return a string with the current section number.
18574 When LEVEL is non-nil, increase section numbers on that level."
18575 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
18576 (when level
18577 (when (> level -1)
18578 (aset org-section-numbers
18579 level (1+ (aref org-section-numbers level))))
18580 (setq idx (1+ level))
18581 (while (<= idx depth)
18582 (if (not (= idx 1))
18583 (aset org-section-numbers idx 0))
18584 (setq idx (1+ idx))))
18585 (setq idx 0)
18586 (while (<= idx depth)
18587 (setq n (aref org-section-numbers idx))
18588 (setq string (concat string (if (not (string= string "")) "." "")
18589 (int-to-string n)))
18590 (setq idx (1+ idx)))
18591 (save-match-data
18592 (if (string-match "\\`\\([@0]\\.\\)+" string)
18593 (setq string (replace-match "" t nil string)))
18594 (if (string-match "\\(\\.0\\)+\\'" string)
18595 (setq string (replace-match "" t nil string))))
18596 string))
18598 ;;; ASCII export
18600 (defvar org-last-level nil) ; dynamically scoped variable
18601 (defvar org-levels-open nil) ; dynamically scoped parameter
18602 (defvar org-ascii-current-indentation nil) ; For communication
18604 (defun org-export-as-ascii (arg)
18605 "Export the outline as a pretty ASCII file.
18606 If there is an active region, export only the region.
18607 The prefix ARG specifies how many levels of the outline should become
18608 underlined headlines. The default is 3."
18609 (interactive "P")
18610 (setq-default org-todo-line-regexp org-todo-line-regexp)
18611 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
18612 (org-infile-export-plist)))
18613 (custom-times org-display-custom-times)
18614 (org-ascii-current-indentation '(0 . 0))
18615 (level 0) line txt
18616 (umax nil)
18617 (umax-toc nil)
18618 (case-fold-search nil)
18619 (filename (concat (file-name-as-directory
18620 (org-export-directory :ascii opt-plist))
18621 (file-name-sans-extension
18622 (file-name-nondirectory buffer-file-name))
18623 ".txt"))
18624 (buffer (find-file-noselect filename))
18625 (org-levels-open (make-vector org-level-max nil))
18626 (odd org-odd-levels-only)
18627 (date (format-time-string "%Y/%m/%d" (current-time)))
18628 (time (format-time-string "%X" (org-current-time)))
18629 (author (plist-get opt-plist :author))
18630 (title (or (plist-get opt-plist :title)
18631 (and (not
18632 (plist-get opt-plist :skip-before-1st-heading))
18633 (org-export-grab-title-from-buffer))
18634 (file-name-sans-extension
18635 (file-name-nondirectory buffer-file-name))))
18636 (email (plist-get opt-plist :email))
18637 (language (plist-get opt-plist :language))
18638 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
18639 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
18640 (todo nil)
18641 (lang-words nil)
18642 (region
18643 (buffer-substring
18644 (if (org-region-active-p) (region-beginning) (point-min))
18645 (if (org-region-active-p) (region-end) (point-max))))
18646 (lines (org-skip-comments
18647 (org-split-string
18648 (org-cleaned-string-for-export
18649 region
18650 :skip-before-1st-heading
18651 (plist-get opt-plist :skip-before-1st-heading)
18652 :add-text (plist-get opt-plist :text))
18653 "[\r\n]")))
18654 thetoc have-headings first-heading-pos
18655 table-open table-buffer)
18657 (let (buffer-read-only)
18658 (org-unmodified
18659 (remove-text-properties (point-min) (point-max)
18660 '(:org-license-to-kill t))))
18662 (setq org-last-level 1)
18663 (org-init-section-numbers)
18665 (find-file-noselect filename)
18667 (setq lang-words (or (assoc language org-export-language-setup)
18668 (assoc "en" org-export-language-setup)))
18669 (switch-to-buffer-other-window buffer)
18670 (erase-buffer)
18671 (fundamental-mode)
18672 ;; create local variables for all options, to make sure all called
18673 ;; functions get the correct information
18674 (mapcar (lambda (x)
18675 (set (make-local-variable (cdr x))
18676 (plist-get opt-plist (car x))))
18677 org-export-plist-vars)
18678 (org-set-local 'org-odd-levels-only odd)
18679 (setq umax (if arg (prefix-numeric-value arg)
18680 org-export-headline-levels))
18681 (setq umax-toc (if (integerp org-export-with-toc)
18682 (min org-export-with-toc umax)
18683 umax))
18685 ;; File header
18686 (if title (org-insert-centered title ?=))
18687 (insert "\n")
18688 (if (or author email)
18689 (insert (concat (nth 1 lang-words) ": " (or author "")
18690 (if email (concat " <" email ">") "")
18691 "\n")))
18692 (if (and date time)
18693 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
18695 (insert "\n\n")
18697 (if org-export-with-toc
18698 (progn
18699 (push (concat (nth 3 lang-words) "\n") thetoc)
18700 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
18701 (mapcar '(lambda (line)
18702 (if (string-match org-todo-line-regexp
18703 line)
18704 ;; This is a headline
18705 (progn
18706 (setq have-headings t)
18707 (setq level (- (match-end 1) (match-beginning 1))
18708 level (org-tr-level level)
18709 txt (match-string 3 line)
18710 todo
18711 (or (and org-export-mark-todo-in-toc
18712 (match-beginning 2)
18713 (not (member (match-string 2 line)
18714 org-done-keywords)))
18715 ; TODO, not DONE
18716 (and org-export-mark-todo-in-toc
18717 (= level umax-toc)
18718 (org-search-todo-below
18719 line lines level))))
18720 (setq txt (org-html-expand-for-ascii txt))
18722 (if (and (memq org-export-with-tags '(not-in-toc nil))
18723 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
18724 (setq txt (replace-match "" t t txt)))
18725 (if (string-match quote-re0 txt)
18726 (setq txt (replace-match "" t t txt)))
18728 (if org-export-with-section-numbers
18729 (setq txt (concat (org-section-number level)
18730 " " txt)))
18731 (if (<= level umax-toc)
18732 (progn
18733 (push
18734 (concat
18735 (make-string (* (1- level) 4) ?\ )
18736 (format (if todo "%s (*)\n" "%s\n") txt))
18737 thetoc)
18738 (setq org-last-level level))
18739 ))))
18740 lines)
18741 (setq thetoc (if have-headings (nreverse thetoc) nil))))
18743 (org-init-section-numbers)
18744 (while (setq line (pop lines))
18745 ;; Remove the quoted HTML tags.
18746 (setq line (org-html-expand-for-ascii line))
18747 ;; Remove targets
18748 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
18749 (setq line (replace-match "" t t line)))
18750 ;; Replace internal links
18751 (while (string-match org-bracket-link-regexp line)
18752 (setq line (replace-match
18753 (if (match-end 3) "[\\3]" "[\\1]")
18754 t nil line)))
18755 (when custom-times
18756 (setq line (org-translate-time line)))
18757 (cond
18758 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
18759 ;; a Headline
18760 (setq first-heading-pos (or first-heading-pos (point)))
18761 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
18762 txt (match-string 2 line))
18763 (org-ascii-level-start level txt umax lines))
18765 ((and org-export-with-tables
18766 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
18767 (if (not table-open)
18768 ;; New table starts
18769 (setq table-open t table-buffer nil))
18770 ;; Accumulate lines
18771 (setq table-buffer (cons line table-buffer))
18772 (when (or (not lines)
18773 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
18774 (car lines))))
18775 (setq table-open nil
18776 table-buffer (nreverse table-buffer))
18777 (insert (mapconcat
18778 (lambda (x)
18779 (org-fix-indentation x org-ascii-current-indentation))
18780 (org-format-table-ascii table-buffer)
18781 "\n") "\n")))
18783 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
18784 (normal-mode)
18786 ;; insert the table of contents
18787 (when thetoc
18788 (goto-char (point-min))
18789 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
18790 (progn
18791 (goto-char (match-beginning 0))
18792 (replace-match ""))
18793 (goto-char first-heading-pos))
18794 (mapc 'insert thetoc)
18795 (or (looking-at "[ \t]*\n[ \t]*\n")
18796 (insert "\n\n")))
18798 (save-buffer)
18799 ;; remove display and invisible chars
18800 (let (beg end)
18801 (goto-char (point-min))
18802 (while (setq beg (next-single-property-change (point) 'display))
18803 (setq end (next-single-property-change beg 'display))
18804 (delete-region beg end)
18805 (goto-char beg)
18806 (insert "=>"))
18807 (goto-char (point-min))
18808 (while (setq beg (next-single-property-change (point) 'org-cwidth))
18809 (setq end (next-single-property-change beg 'org-cwidth))
18810 (delete-region beg end)
18811 (goto-char beg)))
18812 (goto-char (point-min))))
18814 (defun org-search-todo-below (line lines level)
18815 "Search the subtree below LINE for any TODO entries."
18816 (let ((rest (cdr (memq line lines)))
18817 (re org-todo-line-regexp)
18818 line lv todo)
18819 (catch 'exit
18820 (while (setq line (pop rest))
18821 (if (string-match re line)
18822 (progn
18823 (setq lv (- (match-end 1) (match-beginning 1))
18824 todo (and (match-beginning 2)
18825 (not (member (match-string 2 line)
18826 org-done-keywords))))
18827 ; TODO, not DONE
18828 (if (<= lv level) (throw 'exit nil))
18829 (if todo (throw 'exit t))))))))
18831 (defun org-html-expand-for-ascii (line)
18832 "Handle quoted HTML for ASCII export."
18833 (if org-export-html-expand
18834 (while (string-match "@<[^<>\n]*>" line)
18835 ;; We just remove the tags for now.
18836 (setq line (replace-match "" nil nil line))))
18837 line)
18839 (defun org-insert-centered (s &optional underline)
18840 "Insert the string S centered and underline it with character UNDERLINE."
18841 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
18842 (insert (make-string ind ?\ ) s "\n")
18843 (if underline
18844 (insert (make-string ind ?\ )
18845 (make-string (string-width s) underline)
18846 "\n"))))
18848 (defun org-ascii-level-start (level title umax &optional lines)
18849 "Insert a new level in ASCII export."
18850 (let (char (n (- level umax 1)) (ind 0))
18851 (if (> level umax)
18852 (progn
18853 (insert (make-string (* 2 n) ?\ )
18854 (char-to-string (nth (% n (length org-export-ascii-bullets))
18855 org-export-ascii-bullets))
18856 " " title "\n")
18857 ;; find the indentation of the next non-empty line
18858 (catch 'stop
18859 (while lines
18860 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
18861 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
18862 (throw 'stop (setq ind (org-get-indentation (car lines)))))
18863 (pop lines)))
18864 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
18865 (if (or (not (equal (char-before) ?\n))
18866 (not (equal (char-before (1- (point))) ?\n)))
18867 (insert "\n"))
18868 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
18869 (unless org-export-with-tags
18870 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
18871 (setq title (replace-match "" t t title))))
18872 (if org-export-with-section-numbers
18873 (setq title (concat (org-section-number level) " " title)))
18874 (insert title "\n" (make-string (string-width title) char) "\n")
18875 (setq org-ascii-current-indentation '(0 . 0)))))
18877 (defun org-export-visible (type arg)
18878 "Create a copy of the visible part of the current buffer, and export it.
18879 The copy is created in a temporary buffer and removed after use.
18880 TYPE is the final key (as a string) that also select the export command in
18881 the `C-c C-e' export dispatcher.
18882 As a special case, if the you type SPC at the prompt, the temporary
18883 org-mode file will not be removed but presented to you so that you can
18884 continue to use it. The prefix arg ARG is passed through to the exporting
18885 command."
18886 (interactive
18887 (list (progn
18888 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
18889 (read-char-exclusive))
18890 current-prefix-arg))
18891 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
18892 (error "Invalid export key"))
18893 (let* ((binding (cdr (assoc type
18894 '((?a . org-export-as-ascii)
18895 (?\C-a . org-export-as-ascii)
18896 (?b . org-export-as-html-and-open)
18897 (?\C-b . org-export-as-html-and-open)
18898 (?h . org-export-as-html)
18899 (?H . org-export-as-html-to-buffer)
18900 (?R . org-export-region-as-html)
18901 (?x . org-export-as-xoxo)))))
18902 (keepp (equal type ?\ ))
18903 (file buffer-file-name)
18904 (buffer (get-buffer-create "*Org Export Visible*"))
18905 s e)
18906 (with-current-buffer buffer (erase-buffer))
18907 (save-excursion
18908 (setq s (goto-char (point-min)))
18909 (while (not (= (point) (point-max)))
18910 (goto-char (org-find-invisible))
18911 (append-to-buffer buffer s (point))
18912 (setq s (goto-char (org-find-visible))))
18913 (goto-char (point-min))
18914 (unless keepp
18915 ;; Copy all comment lines to the end, to make sure #+ settings are
18916 ;; still available for the second export step. Kind of a hack, but
18917 ;; does do the trick.
18918 (if (looking-at "#[^\r\n]*")
18919 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
18920 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
18921 (append-to-buffer buffer (1+ (match-beginning 0))
18922 (min (point-max) (1+ (match-end 0))))))
18923 (set-buffer buffer)
18924 (let ((buffer-file-name file)
18925 (org-inhibit-startup t))
18926 (org-mode)
18927 (show-all)
18928 (unless keepp (funcall binding arg))))
18929 (if (not keepp)
18930 (kill-buffer buffer)
18931 (switch-to-buffer-other-window buffer)
18932 (goto-char (point-min)))))
18934 (defun org-find-visible ()
18935 (let ((s (point)))
18936 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18937 (get-char-property s 'invisible)))
18939 (defun org-find-invisible ()
18940 (let ((s (point)))
18941 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
18942 (not (get-char-property s 'invisible))))
18945 ;;; HTML export
18947 (defun org-get-current-options ()
18948 "Return a string with current options as keyword options.
18949 Does include HTML export options as well as TODO and CATEGORY stuff."
18950 (format
18951 "#+TITLE: %s
18952 #+AUTHOR: %s
18953 #+EMAIL: %s
18954 #+LANGUAGE: %s
18955 #+TEXT: Some descriptive text to be emitted. Several lines OK.
18956 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s skip:%s
18957 #+CATEGORY: %s
18958 #+SEQ_TODO: %s
18959 #+TYP_TODO: %s
18960 #+PRIORITIES: %c %c %c
18961 #+STARTUP: %s %s %s %s %s
18962 #+TAGS: %s
18963 #+ARCHIVE: %s
18964 #+LINK: %s
18966 (buffer-name) (user-full-name) user-mail-address org-export-default-language
18967 org-export-headline-levels
18968 org-export-with-section-numbers
18969 org-export-with-toc
18970 org-export-preserve-breaks
18971 org-export-html-expand
18972 org-export-with-fixed-width
18973 org-export-with-tables
18974 org-export-with-sub-superscripts
18975 org-export-with-emphasize
18976 org-export-with-TeX-macros
18977 org-export-with-LaTeX-fragments
18978 org-export-skip-text-before-1st-heading
18979 (file-name-nondirectory buffer-file-name)
18980 "TODO FEEDBACK VERIFY DONE"
18981 "Me Jason Marie DONE"
18982 org-highest-priority org-lowest-priority org-default-priority
18983 (cdr (assoc org-startup-folded
18984 '((nil . "showall") (t . "overview") (content . "content"))))
18985 (if org-odd-levels-only "odd" "oddeven")
18986 (if org-hide-leading-stars "hidestars" "showstars")
18987 (if org-startup-align-all-tables "align" "noalign")
18988 (cond ((eq t org-log-done) "logdone")
18989 ((not org-log-done) "nologging")
18990 ((listp org-log-done)
18991 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
18992 org-log-done " ")))
18993 (or (mapconcat (lambda (x)
18994 (cond
18995 ((equal '(:startgroup) x) "{")
18996 ((equal '(:endgroup) x) "}")
18997 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
18998 (t (car x))))
18999 (or org-tag-alist (org-get-buffer-tags)) " ") "")
19000 org-archive-location
19001 "org file:~/org/%s.org"
19004 (defun org-insert-export-options-template ()
19005 "Insert into the buffer a template with information for exporting."
19006 (interactive)
19007 (if (not (bolp)) (newline))
19008 (let ((s (org-get-current-options)))
19009 (and (string-match "#\\+CATEGORY" s)
19010 (setq s (substring s 0 (match-beginning 0))))
19011 (insert s)))
19013 (defun org-toggle-fixed-width-section (arg)
19014 "Toggle the fixed-width export.
19015 If there is no active region, the QUOTE keyword at the current headline is
19016 inserted or removed. When present, it causes the text between this headline
19017 and the next to be exported as fixed-width text, and unmodified.
19018 If there is an active region, this command adds or removes a colon as the
19019 first character of this line. If the first character of a line is a colon,
19020 this line is also exported in fixed-width font."
19021 (interactive "P")
19022 (let* ((cc 0)
19023 (regionp (org-region-active-p))
19024 (beg (if regionp (region-beginning) (point)))
19025 (end (if regionp (region-end)))
19026 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
19027 (re "[ \t]*\\(:\\)")
19028 off)
19029 (if regionp
19030 (save-excursion
19031 (goto-char beg)
19032 (setq cc (current-column))
19033 (beginning-of-line 1)
19034 (setq off (looking-at re))
19035 (while (> nlines 0)
19036 (setq nlines (1- nlines))
19037 (beginning-of-line 1)
19038 (cond
19039 (arg
19040 (move-to-column cc t)
19041 (insert ":\n")
19042 (forward-line -1))
19043 ((and off (looking-at re))
19044 (replace-match "" t t nil 1))
19045 ((not off) (move-to-column cc t) (insert ":")))
19046 (forward-line 1)))
19047 (save-excursion
19048 (org-back-to-heading)
19049 (if (looking-at (concat outline-regexp
19050 "\\( +\\<" org-quote-string "\\>\\)"))
19051 (replace-match "" t t nil 1)
19052 (if (looking-at outline-regexp)
19053 (progn
19054 (goto-char (match-end 0))
19055 (insert " " org-quote-string))))))))
19057 (defun org-export-as-html-and-open (arg)
19058 "Export the outline as HTML and immediately open it with a browser.
19059 If there is an active region, export only the region.
19060 The prefix ARG specifies how many levels of the outline should become
19061 headlines. The default is 3. Lower levels will become bulleted lists."
19062 (interactive "P")
19063 (org-export-as-html arg 'hidden)
19064 (org-open-file buffer-file-name))
19066 (defun org-export-as-html-batch ()
19067 "Call `org-export-as-html', may be used in batch processing as
19068 emacs --batch
19069 --load=$HOME/lib/emacs/org.el
19070 --eval \"(setq org-export-headline-levels 2)\"
19071 --visit=MyFile --funcall org-export-as-html-batch"
19072 (org-export-as-html org-export-headline-levels 'hidden))
19074 (defun org-export-as-html-to-buffer (arg)
19075 "Call `org-exort-as-html` with output to a temporary buffer.
19076 No file is created. The prefix ARG is passed through to `org-export-as-html'."
19077 (interactive "P")
19078 (org-export-as-html arg nil nil "*Org HTML Export*")
19079 (switch-to-buffer-other-window "*Org HTML Export*"))
19081 (defun org-replace-region-by-html (beg end)
19082 "Assume the current region has org-mode syntax, and convert it to HTML.
19083 This can be used in any buffer. For example, you could write an
19084 itemized list in org-mode syntax in an HTML buffer and then use this
19085 command to convert it."
19086 (interactive "r")
19087 (let (reg html buf)
19088 (if (org-mode-p)
19089 (setq html (org-export-region-as-html
19090 beg end t 'string))
19091 (setq reg (buffer-substring beg end)
19092 buf (get-buffer-create "*Org tmp*"))
19093 (save-excursion
19094 (set-buffer buf)
19095 (erase-buffer)
19096 (insert reg)
19097 (org-mode)
19098 (setq html (org-export-region-as-html
19099 (point-min) (point-max) t 'string)))
19100 (kill-buffer buf))
19101 (delete-region beg end)
19102 (insert html)))
19104 (defun org-export-region-as-html (beg end &optional body-only buffer)
19105 "Convert region from BEG to END in org-mode buffer to HTML.
19106 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
19107 contents, and only produce the region of converted text, useful for
19108 cut-and-paste operations.
19109 If BUFFER is a buffer or a string, use/create that buffer as a target
19110 of the converted HTML. If BUFFER is the symbol `string', return the
19111 produced HTML as a string and leave not buffer behind. For example,
19112 a Lisp program could call this function in the following way:
19114 (setq html (org-export-region-as-html beg end t 'string))
19116 When called interactively, the output buffer is selected, and shown
19117 in a window. A non-interactive call will only retunr the buffer."
19118 (interactive "r\nP")
19119 (when (interactive-p)
19120 (setq buffer "*Org HTML EXPORT*"))
19121 (let ((transient-mark-mode t) (zmacs-regions t)
19122 rtn)
19123 (goto-char end)
19124 (set-mark (point)) ;; to activate the region
19125 (goto-char beg)
19126 (setq rtn (org-export-as-html
19127 nil nil nil
19128 buffer body-only))
19129 (if (fboundp 'deactivate-mark) (deactivate-mark))
19130 (if (and (interactive-p) (bufferp rtn))
19131 (switch-to-buffer-other-window rtn)
19132 rtn)))
19134 (defun org-export-as-html (arg &optional hidden ext-plist
19135 to-buffer body-only)
19136 "Export the outline as a pretty HTML file.
19137 If there is an active region, export only the region. The prefix
19138 ARG specifies how many levels of the outline should become
19139 headlines. The default is 3. Lower levels will become bulleted
19140 lists. When HIDDEN is non-nil, don't display the HTML buffer.
19141 EXT-PLIST is a property list with external parameters overriding
19142 org-mode's default settings, but still inferior to file-local
19143 settings. When TO-BUFFER is non-nil, create a buffer with that
19144 name and export to that buffer. If TO-BUFFER is the symbol `string',
19145 don't leave any buffer behind but just return the resulting HTML as
19146 a string. When BODY-ONLY is set, don't produce the file header and footer,
19147 simply return the content of <body>...</body>, without even
19148 the body tags themselves."
19149 (interactive "P")
19151 ;; Make sure we have a file name when we need it.
19152 (when (and (not (or to-buffer body-only))
19153 (not buffer-file-name))
19154 (if (buffer-base-buffer)
19155 (org-set-local 'buffer-file-name
19156 (with-current-buffer (buffer-base-buffer)
19157 buffer-file-name))
19158 (error "Need a file name to be able to export.")))
19160 (message "Exporting...")
19161 (setq-default org-todo-line-regexp org-todo-line-regexp)
19162 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
19163 (setq-default org-done-keywords org-done-keywords)
19164 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
19165 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
19166 ext-plist
19167 (org-infile-export-plist)))
19169 (style (plist-get opt-plist :style))
19170 (link-validate (plist-get opt-plist :link-validation-function))
19171 valid thetoc have-headings first-heading-pos
19172 (odd org-odd-levels-only)
19173 (region-p (org-region-active-p))
19174 ;; The following two are dynamically scoped into other
19175 ;; routines below.
19176 (org-current-export-dir (org-export-directory :html opt-plist))
19177 (org-current-export-file buffer-file-name)
19178 (level 0) (line "") (origline "") txt todo
19179 (umax nil)
19180 (umax-toc nil)
19181 (filename (if to-buffer nil
19182 (concat (file-name-as-directory
19183 (org-export-directory :html opt-plist))
19184 (file-name-sans-extension
19185 (file-name-nondirectory buffer-file-name))
19186 ".html")))
19187 (current-dir (if buffer-file-name
19188 (file-name-directory buffer-file-name)
19189 default-directory))
19190 (buffer (if to-buffer
19191 (cond
19192 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
19193 (t (get-buffer-create to-buffer)))
19194 (find-file-noselect filename)))
19195 (org-levels-open (make-vector org-level-max nil))
19196 (date (format-time-string "%Y/%m/%d" (current-time)))
19197 (time (format-time-string "%X" (org-current-time)))
19198 (author (plist-get opt-plist :author))
19199 (title (or (plist-get opt-plist :title)
19200 (and (not
19201 (plist-get opt-plist :skip-before-1st-heading))
19202 (org-export-grab-title-from-buffer))
19203 (and buffer-file-name
19204 (file-name-sans-extension
19205 (file-name-nondirectory buffer-file-name)))
19206 "UNTITLED"))
19207 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
19208 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
19209 (inquote nil)
19210 (infixed nil)
19211 (in-local-list nil)
19212 (local-list-num nil)
19213 (local-list-indent nil)
19214 (llt org-plain-list-ordered-item-terminator)
19215 (email (plist-get opt-plist :email))
19216 (language (plist-get opt-plist :language))
19217 (lang-words nil)
19218 (target-alist nil) tg
19219 (head-count 0) cnt
19220 (start 0)
19221 (coding-system (and (boundp 'buffer-file-coding-system)
19222 buffer-file-coding-system))
19223 (coding-system-for-write (or org-export-html-coding-system
19224 coding-system))
19225 (save-buffer-coding-system (or org-export-html-coding-system
19226 coding-system))
19227 (charset (and coding-system-for-write
19228 (fboundp 'coding-system-get)
19229 (coding-system-get coding-system-for-write
19230 'mime-charset)))
19231 (region
19232 (buffer-substring
19233 (if region-p (region-beginning) (point-min))
19234 (if region-p (region-end) (point-max))))
19235 (lines
19236 (org-skip-comments (org-split-string
19237 (org-cleaned-string-for-export
19238 region
19239 :emph-multiline t
19240 :for-html t
19241 :skip-before-1st-heading
19242 (plist-get opt-plist :skip-before-1st-heading)
19243 :add-text
19244 (plist-get opt-plist :text)
19245 :LaTeX-fragments
19246 (plist-get opt-plist :LaTeX-fragments))
19247 "[\r\n]")))
19248 table-open type
19249 table-buffer table-orig-buffer
19250 ind start-is-num starter didclose
19251 rpl path desc descp desc1 desc2 link
19254 (let (buffer-read-only)
19255 (org-unmodified
19256 (remove-text-properties (point-min) (point-max)
19257 '(:org-license-to-kill t))))
19259 (message "Exporting...")
19261 (setq org-last-level 1)
19262 (org-init-section-numbers)
19264 ;; Get the language-dependent settings
19265 (setq lang-words (or (assoc language org-export-language-setup)
19266 (assoc "en" org-export-language-setup)))
19268 ;; Switch to the output buffer
19269 (set-buffer buffer)
19270 (erase-buffer)
19271 (fundamental-mode)
19272 (let ((case-fold-search nil)
19273 (org-odd-levels-only odd))
19274 ;; create local variables for all options, to make sure all called
19275 ;; functions get the correct information
19276 (mapcar (lambda (x)
19277 (set (make-local-variable (cdr x))
19278 (plist-get opt-plist (car x))))
19279 org-export-plist-vars)
19280 (setq umax (if arg (prefix-numeric-value arg)
19281 org-export-headline-levels))
19282 (setq umax-toc (if (integerp org-export-with-toc)
19283 (min org-export-with-toc umax)
19284 umax))
19285 (unless body-only
19286 ;; File header
19287 (insert (format
19288 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
19289 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
19290 <html xmlns=\"http://www.w3.org/1999/xhtml\"
19291 lang=\"%s\" xml:lang=\"%s\">
19292 <head>
19293 <title>%s</title>
19294 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
19295 <meta name=\"generator\" content=\"Org-mode\"/>
19296 <meta name=\"generated\" content=\"%s %s\"/>
19297 <meta name=\"author\" content=\"%s\"/>
19299 </head><body>
19301 language language (org-html-expand title)
19302 (or charset "iso-8859-1") date time author style))
19304 (insert (or (plist-get opt-plist :preamble) ""))
19306 (when (plist-get opt-plist :auto-preamble)
19307 (if title (insert (format org-export-html-title-format
19308 (org-html-expand title))))))
19310 (if (and org-export-with-toc (not body-only))
19311 (progn
19312 (push (format "<h%d>%s</h%d>\n"
19313 org-export-html-toplevel-hlevel
19314 (nth 3 lang-words)
19315 org-export-html-toplevel-hlevel)
19316 thetoc)
19317 (push "<ul>\n<li>" thetoc)
19318 (setq lines
19319 (mapcar '(lambda (line)
19320 (if (string-match org-todo-line-regexp line)
19321 ;; This is a headline
19322 (progn
19323 (setq have-headings t)
19324 (setq level (- (match-end 1) (match-beginning 1))
19325 level (org-tr-level level)
19326 txt (save-match-data
19327 (org-html-expand
19328 (org-export-cleanup-toc-line
19329 (match-string 3 line))))
19330 todo
19331 (or (and org-export-mark-todo-in-toc
19332 (match-beginning 2)
19333 (not (member (match-string 2 line)
19334 org-done-keywords)))
19335 ; TODO, not DONE
19336 (and org-export-mark-todo-in-toc
19337 (= level umax-toc)
19338 (org-search-todo-below
19339 line lines level))))
19340 (if (and (memq org-export-with-tags '(not-in-toc nil))
19341 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
19342 (setq txt (replace-match "" t t txt)))
19343 (if (string-match quote-re0 txt)
19344 (setq txt (replace-match "" t t txt)))
19345 (if org-export-with-section-numbers
19346 (setq txt (concat (org-section-number level)
19347 " " txt)))
19348 (if (<= level (max umax umax-toc))
19349 (setq head-count (+ head-count 1)))
19350 (if (<= level umax-toc)
19351 (progn
19352 (if (> level org-last-level)
19353 (progn
19354 (setq cnt (- level org-last-level))
19355 (while (>= (setq cnt (1- cnt)) 0)
19356 (push "\n<ul>\n<li>" thetoc))
19357 (push "\n" thetoc)))
19358 (if (< level org-last-level)
19359 (progn
19360 (setq cnt (- org-last-level level))
19361 (while (>= (setq cnt (1- cnt)) 0)
19362 (push "</li>\n</ul>" thetoc))
19363 (push "\n" thetoc)))
19364 ;; Check for targets
19365 (while (string-match org-target-regexp line)
19366 (setq tg (match-string 1 line)
19367 line (replace-match
19368 (concat "@<span class=\"target\">" tg "@</span> ")
19369 t t line))
19370 (push (cons (org-solidify-link-text tg)
19371 (format "sec-%d" head-count))
19372 target-alist))
19373 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
19374 (setq txt (replace-match "" t t txt)))
19375 (push
19376 (format
19377 (if todo
19378 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
19379 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
19380 head-count txt) thetoc)
19382 (setq org-last-level level))
19384 line)
19385 lines))
19386 (while (> org-last-level 0)
19387 (setq org-last-level (1- org-last-level))
19388 (push "</li>\n</ul>\n" thetoc))
19389 (setq thetoc (if have-headings (nreverse thetoc) nil))))
19391 (setq head-count 0)
19392 (org-init-section-numbers)
19394 (while (setq line (pop lines) origline line)
19395 (catch 'nextline
19397 ;; end of quote section?
19398 (when (and inquote (string-match "^\\*+" line))
19399 (insert "</pre>\n")
19400 (setq inquote nil))
19401 ;; inside a quote section?
19402 (when inquote
19403 (insert (org-html-protect line) "\n")
19404 (throw 'nextline nil))
19406 ;; verbatim lines
19407 (when (and org-export-with-fixed-width
19408 (string-match "^[ \t]*:\\(.*\\)" line))
19409 (when (not infixed)
19410 (setq infixed t)
19411 (insert "<pre>\n"))
19412 (insert (org-html-protect (match-string 1 line)) "\n")
19413 (when (and lines
19414 (not (string-match "^[ \t]*\\(:.*\\)"
19415 (car lines))))
19416 (setq infixed nil)
19417 (insert "</pre>\n"))
19418 (throw 'nextline nil))
19420 ;; Protected HTML
19421 (when (get-text-property 0 'org-protected line)
19422 (let (par)
19423 (when (re-search-backward
19424 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
19425 (setq par (match-string 1))
19426 (replace-match "\\2\n"))
19427 (insert line "\n")
19428 (while (and lines
19429 (get-text-property 0 'org-protected (car lines)))
19430 (insert (pop lines) "\n"))
19431 (and par (insert "<p>\n")))
19432 (throw 'nextline nil))
19434 ;; Horizontal line
19435 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
19436 (insert "\n<hr/>\n")
19437 (throw 'nextline nil))
19439 ;; make targets to anchors
19440 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
19441 (cond
19442 ((match-end 2)
19443 (setq line (replace-match
19444 (concat "@<a name=\""
19445 (org-solidify-link-text (match-string 1 line))
19446 "\">\\nbsp@</a>")
19447 t t line)))
19448 ((and org-export-with-toc (equal (string-to-char line) ?*))
19449 (setq line (replace-match
19450 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
19451 ; (concat "@<i>" (match-string 1 line) "@</i> ")
19452 t t line)))
19454 (setq line (replace-match
19455 (concat "@<a name=\""
19456 (org-solidify-link-text (match-string 1 line))
19457 "\" class=\"target\">" (match-string 1 line) "@</a> ")
19458 t t line)))))
19460 (setq line (org-html-handle-time-stamps line))
19462 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
19463 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
19464 ;; Also handle sub_superscripts and checkboxes
19465 (setq line (org-html-expand line))
19467 ;; Format the links
19468 (setq start 0)
19469 (while (string-match org-bracket-link-analytic-regexp line start)
19470 (setq start (match-beginning 0))
19471 (setq type (if (match-end 2) (match-string 2 line) "internal"))
19472 (setq path (match-string 3 line))
19473 (setq desc1 (if (match-end 5) (match-string 5 line))
19474 desc2 (if (match-end 2) (concat type ":" path) path)
19475 descp (and desc1 (not (equal desc1 desc2)))
19476 desc (or desc1 desc2))
19477 ;; Make an image out of the description if that is so wanted
19478 (when (and descp (org-file-image-p desc))
19479 (save-match-data
19480 (if (string-match "^file:" desc)
19481 (setq desc (substring desc (match-end 0)))))
19482 (setq desc (concat "<img src=\"" desc "\"/>")))
19483 ;; FIXME: do we need to unescape here somewhere?
19484 (cond
19485 ((equal type "internal")
19486 (setq rpl
19487 (concat
19488 "<a href=\"#"
19489 (org-solidify-link-text
19490 (save-match-data (org-link-unescape path)) target-alist)
19491 "\">" desc "</a>")))
19492 ((member type '("http" "https")) ; FIXME: need to test this.
19493 ;; standard URL, just check if we need to inline an image
19494 (if (and (or (eq t org-export-html-inline-images)
19495 (and org-export-html-inline-images (not descp)))
19496 (org-file-image-p path))
19497 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
19498 (setq link (concat type ":" path))
19499 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
19500 ((member type '("ftp" "mailto" "news"))
19501 ;; standard URL
19502 (setq link (concat type ":" path))
19503 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
19504 ((string= type "file")
19505 ;; FILE link
19506 (let* ((filename path)
19507 (abs-p (file-name-absolute-p filename))
19508 thefile file-is-image-p search)
19509 (save-match-data
19510 (if (string-match "::\\(.*\\)" filename)
19511 (setq search (match-string 1 filename)
19512 filename (replace-match "" t nil filename)))
19513 (setq valid
19514 (if (functionp link-validate)
19515 (funcall link-validate filename current-dir)
19517 (setq file-is-image-p (org-file-image-p filename))
19518 (setq thefile (if abs-p (expand-file-name filename) filename))
19519 (when (and org-export-html-link-org-files-as-html
19520 (string-match "\\.org$" thefile))
19521 (setq thefile (concat (substring thefile 0
19522 (match-beginning 0))
19523 ".html"))
19524 (if (and search
19525 ;; make sure this is can be used as target search
19526 (not (string-match "^[0-9]*$" search))
19527 (not (string-match "^\\*" search))
19528 (not (string-match "^/.*/$" search)))
19529 (setq thefile (concat thefile "#"
19530 (org-solidify-link-text
19531 (org-link-unescape search)))))
19532 (when (string-match "^file:" desc)
19533 (setq desc (replace-match "" t t desc))
19534 (if (string-match "\\.org$" desc)
19535 (setq desc (replace-match "" t t desc))))))
19536 (setq rpl (if (and file-is-image-p
19537 (or (eq t org-export-html-inline-images)
19538 (and org-export-html-inline-images
19539 (not descp))))
19540 (concat "<img src=\"" thefile "\"/>")
19541 (concat "<a href=\"" thefile "\">" desc "</a>")))
19542 (if (not valid) (setq rpl desc))))
19543 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
19544 (setq rpl (concat "<i>&lt;" type ":"
19545 (save-match-data (org-link-unescape path))
19546 "&gt;</i>"))))
19547 (setq line (replace-match rpl t t line)
19548 start (+ start (length rpl))))
19550 ;; TODO items
19551 (if (and (string-match org-todo-line-regexp line)
19552 (match-beginning 2))
19553 (if (member (match-string 2 line) org-done-keywords)
19554 (setq line (replace-match
19555 "<span class=\"done\">\\2</span>"
19556 t nil line 2))
19557 (setq line
19558 (concat (substring line 0 (match-beginning 2))
19559 "<span class=\"todo\">" (match-string 2 line)
19560 "</span>" (substring line (match-end 2))))))
19562 ;; Does this contain a reference to a footnote?
19563 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
19564 (let ((n (match-string 2 line)))
19565 (setq line
19566 (replace-match
19567 (format
19568 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
19569 (match-string 1 line) n n n)
19570 t t line))))
19572 (cond
19573 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
19574 ;; This is a headline
19575 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
19576 txt (match-string 2 line))
19577 (if (string-match quote-re0 txt)
19578 (setq txt (replace-match "" t t txt)))
19579 (if (<= level (max umax umax-toc))
19580 (setq head-count (+ head-count 1)))
19581 (when in-local-list
19582 ;; Close any local lists before inserting a new header line
19583 (while local-list-num
19584 (org-close-li)
19585 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
19586 (pop local-list-num))
19587 (setq local-list-indent nil
19588 in-local-list nil))
19589 (setq first-heading-pos (or first-heading-pos (point)))
19590 (org-html-level-start level txt umax
19591 (and org-export-with-toc (<= level umax))
19592 head-count)
19593 ;; QUOTES
19594 (when (string-match quote-re line)
19595 (insert "<pre>")
19596 (setq inquote t)))
19598 ((and org-export-with-tables
19599 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
19600 (if (not table-open)
19601 ;; New table starts
19602 (setq table-open t table-buffer nil table-orig-buffer nil))
19603 ;; Accumulate lines
19604 (setq table-buffer (cons line table-buffer)
19605 table-orig-buffer (cons origline table-orig-buffer))
19606 (when (or (not lines)
19607 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
19608 (car lines))))
19609 (setq table-open nil
19610 table-buffer (nreverse table-buffer)
19611 table-orig-buffer (nreverse table-orig-buffer))
19612 (org-close-par-maybe)
19613 (insert (org-format-table-html table-buffer table-orig-buffer))))
19615 ;; Normal lines
19616 (when (string-match
19617 (cond
19618 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
19619 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
19620 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
19621 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
19622 line)
19623 (setq ind (org-get-string-indentation line)
19624 start-is-num (match-beginning 4)
19625 starter (if (match-beginning 2)
19626 (substring (match-string 2 line) 0 -1))
19627 line (substring line (match-beginning 5)))
19628 (unless (string-match "[^ \t]" line)
19629 ;; empty line. Pretend indentation is large.
19630 (setq ind (if org-empty-line-terminates-plain-lists
19632 (1+ (or (car local-list-indent) 1)))))
19633 (setq didclose nil)
19634 (while (and in-local-list
19635 (or (and (= ind (car local-list-indent))
19636 (not starter))
19637 (< ind (car local-list-indent))))
19638 (setq didclose t)
19639 (org-close-li)
19640 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
19641 (pop local-list-num) (pop local-list-indent)
19642 (setq in-local-list local-list-indent))
19643 (cond
19644 ((and starter
19645 (or (not in-local-list)
19646 (> ind (car local-list-indent))))
19647 ;; Start new (level of) list
19648 (org-close-par-maybe)
19649 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
19650 (push start-is-num local-list-num)
19651 (push ind local-list-indent)
19652 (setq in-local-list t))
19653 (starter
19654 ;; continue current list
19655 (org-close-li)
19656 (insert "<li>\n"))
19657 (didclose
19658 ;; we did close a list, normal text follows: need <p>
19659 (org-open-par)))
19660 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
19661 (setq line
19662 (replace-match
19663 (if (equal (match-string 1 line) "X")
19664 "<b>[X]</b>"
19665 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
19666 t t line))))
19668 ;; Empty lines start a new paragraph. If hand-formatted lists
19669 ;; are not fully interpreted, lines starting with "-", "+", "*"
19670 ;; also start a new paragraph.
19671 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
19673 ;; Is this the start of a footnote?
19674 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
19675 (org-close-par-maybe)
19676 (let ((n (match-string 1 line)))
19677 (setq line (replace-match
19678 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line))))
19680 ;; Check if the line break needs to be conserved
19681 (cond
19682 ((string-match "\\\\\\\\[ \t]*$" line)
19683 (setq line (replace-match "<br/>" t t line)))
19684 (org-export-preserve-breaks
19685 (setq line (concat line "<br/>"))))
19687 (insert line "\n")))))
19689 ;; Properly close all local lists and other lists
19690 (when inquote (insert "</pre>\n"))
19691 (when in-local-list
19692 ;; Close any local lists before inserting a new header line
19693 (while local-list-num
19694 (org-close-li)
19695 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
19696 (pop local-list-num))
19697 (setq local-list-indent nil
19698 in-local-list nil))
19699 (org-html-level-start 1 nil umax
19700 (and org-export-with-toc (<= level umax))
19701 head-count)
19703 (unless body-only
19704 (when (plist-get opt-plist :auto-postamble)
19705 (when author
19706 (insert "<p class=\"author\"> "
19707 (nth 1 lang-words) ": " author "\n")
19708 (when email
19709 (insert "<a href=\"mailto:" email "\">&lt;"
19710 email "&gt;</a>\n"))
19711 (insert "</p>\n"))
19712 (when (and date time)
19713 (insert "<p class=\"date\"> "
19714 (nth 2 lang-words) ": "
19715 date " " time "</p>\n")))
19717 (if org-export-html-with-timestamp
19718 (insert org-export-html-html-helper-timestamp))
19719 (insert (or (plist-get opt-plist :postamble) ""))
19720 (insert "</body>\n</html>\n"))
19722 (normal-mode)
19723 (if (eq major-mode default-major-mode) (html-mode))
19725 ;; insert the table of contents
19726 (goto-char (point-min))
19727 (when thetoc
19728 (if (or (re-search-forward
19729 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
19730 (re-search-forward
19731 "\\[TABLE-OF-CONTENTS\\]" nil t))
19732 (progn
19733 (goto-char (match-beginning 0))
19734 (replace-match ""))
19735 (goto-char first-heading-pos)
19736 (when (looking-at "\\s-*</p>")
19737 (goto-char (match-end 0))
19738 (insert "\n")))
19739 (mapc 'insert thetoc))
19740 ;; remove empty paragraphs and lists
19741 (goto-char (point-min))
19742 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
19743 (replace-match ""))
19744 (goto-char (point-min))
19745 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
19746 (replace-match ""))
19747 (or to-buffer (save-buffer))
19748 (goto-char (point-min))
19749 (message "Exporting... done")
19750 (if (eq to-buffer 'string)
19751 (prog1 (buffer-substring (point-min) (point-max))
19752 (kill-buffer (current-buffer)))
19753 (current-buffer)))))
19755 (defvar org-table-colgroup-info nil) ;; FIXME: mode to a better place
19756 (defun org-format-table-ascii (lines)
19757 "Format a table for ascii export."
19758 (if (stringp lines)
19759 (setq lines (org-split-string lines "\n")))
19760 (if (not (string-match "^[ \t]*|" (car lines)))
19761 ;; Table made by table.el - test for spanning
19762 lines
19764 ;; A normal org table
19765 ;; Get rid of hlines at beginning and end
19766 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
19767 (setq lines (nreverse lines))
19768 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
19769 (setq lines (nreverse lines))
19770 (when org-export-table-remove-special-lines
19771 ;; Check if the table has a marking column. If yes remove the
19772 ;; column and the special lines
19773 (setq lines (org-table-clean-before-export lines)))
19774 ;; Get rid of the vertical lines except for grouping
19775 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
19776 rtn line vl1 start)
19777 (while (setq line (pop lines))
19778 (if (string-match org-table-hline-regexp line)
19779 (and (string-match "|\\(.*\\)|" line)
19780 (setq line (replace-match " \\1" t nil line)))
19781 (setq start 0 vl1 vl)
19782 (while (string-match "|" line start)
19783 (setq start (match-end 0))
19784 (or (pop vl1) (setq line (replace-match " " t t line)))))
19785 (push line rtn))
19786 (nreverse rtn))))
19788 (defun org-colgroup-info-to-vline-list (info)
19789 (let (vl new last rtn line)
19790 (while info
19791 (setq last new new (pop info))
19792 (if (or (memq last '(:end :startend))
19793 (memq new '(:start :startend)))
19794 (push t vl)
19795 (push nil vl)))
19796 (setq vl (cons nil (nreverse vl)))))
19799 (defun org-format-table-html (lines olines)
19800 "Find out which HTML converter to use and return the HTML code."
19801 (if (stringp lines)
19802 (setq lines (org-split-string lines "\n")))
19803 (if (string-match "^[ \t]*|" (car lines))
19804 ;; A normal org table
19805 (org-format-org-table-html lines)
19806 ;; Table made by table.el - test for spanning
19807 (let* ((hlines (delq nil (mapcar
19808 (lambda (x)
19809 (if (string-match "^[ \t]*\\+-" x) x
19810 nil))
19811 lines)))
19812 (first (car hlines))
19813 (ll (and (string-match "\\S-+" first)
19814 (match-string 0 first)))
19815 (re (concat "^[ \t]*" (regexp-quote ll)))
19816 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
19817 hlines))))
19818 (if (and (not spanning)
19819 (not org-export-prefer-native-exporter-for-tables))
19820 ;; We can use my own converter with HTML conversions
19821 (org-format-table-table-html lines)
19822 ;; Need to use the code generator in table.el, with the original text.
19823 (org-format-table-table-html-using-table-generate-source olines)))))
19825 (defun org-format-org-table-html (lines &optional splice)
19826 "Format a table into HTML."
19827 ;; Get rid of hlines at beginning and end
19828 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
19829 (setq lines (nreverse lines))
19830 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
19831 (setq lines (nreverse lines))
19832 (when org-export-table-remove-special-lines
19833 ;; Check if the table has a marking column. If yes remove the
19834 ;; column and the special lines
19835 (setq lines (org-table-clean-before-export lines)))
19837 (let ((head (and org-export-highlight-first-table-line
19838 (delq nil (mapcar
19839 (lambda (x) (string-match "^[ \t]*|-" x))
19840 (cdr lines)))))
19841 (nlines 0) fnum i
19842 tbopen line fields html gr colgropen)
19843 (if splice (setq head nil))
19844 (unless splice (push (if head "<thead>" "<tbody>") html))
19845 (setq tbopen t)
19846 (while (setq line (pop lines))
19847 (catch 'next-line
19848 (if (string-match "^[ \t]*|-" line)
19849 (progn
19850 (unless splice
19851 (push (if head "</thead>" "</tbody>") html)
19852 (if lines (push "<tbody>" html) (setq tbopen nil)))
19853 (setq head nil) ;; head ends here, first time around
19854 ;; ignore this line
19855 (throw 'next-line t)))
19856 ;; Break the line into fields
19857 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
19858 (unless fnum (setq fnum (make-vector (length fields) 0)))
19859 (setq nlines (1+ nlines) i -1)
19860 (push (concat "<tr>"
19861 (mapconcat
19862 (lambda (x)
19863 (setq i (1+ i))
19864 (if (and (< i nlines)
19865 (string-match org-table-number-regexp x))
19866 (incf (aref fnum i)))
19867 (if head
19868 (concat (car org-export-table-header-tags) x
19869 (cdr org-export-table-header-tags))
19870 (concat (car org-export-table-data-tags) x
19871 (cdr org-export-table-data-tags))))
19872 fields "")
19873 "</tr>")
19874 html)))
19875 (unless splice (if tbopen (push "</tbody>" html)))
19876 (unless splice (push "</table>\n" html))
19877 (setq html (nreverse html))
19878 (unless splice
19879 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
19880 (push (mapconcat
19881 (lambda (x)
19882 (setq gr (pop org-table-colgroup-info))
19883 (format "%s<COL align=\"%s\"></COL>%s"
19884 (if (memq gr '(:start :startend))
19885 (prog1
19886 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
19887 (setq colgropen t))
19889 (if (> (/ (float x) nlines) org-table-number-fraction)
19890 "right" "left")
19891 (if (memq gr '(:end :startend))
19892 (progn (setq colgropen nil) "</colgroup>")
19893 "")))
19894 fnum "")
19895 html)
19896 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
19897 (push org-export-html-table-tag html))
19898 (concat (mapconcat 'identity html "\n") "\n")))
19900 (defun org-table-clean-before-export (lines)
19901 "Check if the table has a marking column.
19902 If yes remove the column and the special lines."
19903 (setq org-table-colgroup-info nil)
19904 (if (memq nil
19905 (mapcar
19906 (lambda (x) (or (string-match "^[ \t]*|-" x)
19907 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
19908 lines))
19909 (progn
19910 (setq org-table-clean-did-remove-column nil)
19911 (delq nil
19912 (mapcar
19913 (lambda (x)
19914 (cond
19915 ((string-match "^[ \t]*| */ *|" x)
19916 (setq org-table-colgroup-info
19917 (mapcar (lambda (x)
19918 (cond ((member x '("<" "&lt;")) :start)
19919 ((member x '(">" "&gt;")) :end)
19920 ((member x '("<>" "&lt;&gt;")) :startend)
19921 (t nil)))
19922 (org-split-string x "[ \t]*|[ \t]*")))
19923 nil)
19924 (t x)))
19925 lines)))
19926 (setq org-table-clean-did-remove-column t)
19927 (delq nil
19928 (mapcar
19929 (lambda (x)
19930 (cond
19931 ((string-match "^[ \t]*| */ *|" x)
19932 (setq org-table-colgroup-info
19933 (mapcar (lambda (x)
19934 (cond ((member x '("<" "&lt;")) :start)
19935 ((member x '(">" "&gt;")) :end)
19936 ((member x '("<>" "&lt;&gt;")) :startend)
19937 (t nil)))
19938 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
19939 nil)
19940 ((string-match "^[ \t]*| *[!_^/] *|" x)
19941 nil) ; ignore this line
19942 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
19943 (string-match "^\\([ \t]*\\)|[^|]*|" x))
19944 ;; remove the first column
19945 (replace-match "\\1|" t nil x))
19946 (t (error "This should not happen"))))
19947 lines))))
19949 (defun org-format-table-table-html (lines)
19950 "Format a table generated by table.el into HTML.
19951 This conversion does *not* use `table-generate-source' from table.el.
19952 This has the advantage that Org-mode's HTML conversions can be used.
19953 But it has the disadvantage, that no cell- or row-spanning is allowed."
19954 (let (line field-buffer
19955 (head org-export-highlight-first-table-line)
19956 fields html empty)
19957 (setq html (concat org-export-html-table-tag "\n"))
19958 (while (setq line (pop lines))
19959 (setq empty "&nbsp;")
19960 (catch 'next-line
19961 (if (string-match "^[ \t]*\\+-" line)
19962 (progn
19963 (if field-buffer
19964 (progn
19965 (setq
19966 html
19967 (concat
19968 html
19969 "<tr>"
19970 (mapconcat
19971 (lambda (x)
19972 (if (equal x "") (setq x empty))
19973 (if head
19974 (concat (car org-export-table-header-tags) x
19975 (cdr org-export-table-header-tags))
19976 (concat (car org-export-table-data-tags) x
19977 (cdr org-export-table-data-tags))))
19978 field-buffer "\n")
19979 "</tr>\n"))
19980 (setq head nil)
19981 (setq field-buffer nil)))
19982 ;; Ignore this line
19983 (throw 'next-line t)))
19984 ;; Break the line into fields and store the fields
19985 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
19986 (if field-buffer
19987 (setq field-buffer (mapcar
19988 (lambda (x)
19989 (concat x "<br/>" (pop fields)))
19990 field-buffer))
19991 (setq field-buffer fields))))
19992 (setq html (concat html "</table>\n"))
19993 html))
19995 (defun org-format-table-table-html-using-table-generate-source (lines)
19996 "Format a table into html, using `table-generate-source' from table.el.
19997 This has the advantage that cell- or row-spanning is allowed.
19998 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
19999 (require 'table)
20000 (with-current-buffer (get-buffer-create " org-tmp1 ")
20001 (erase-buffer)
20002 (insert (mapconcat 'identity lines "\n"))
20003 (goto-char (point-min))
20004 (if (not (re-search-forward "|[^+]" nil t))
20005 (error "Error processing table"))
20006 (table-recognize-table)
20007 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
20008 (table-generate-source 'html " org-tmp2 ")
20009 (set-buffer " org-tmp2 ")
20010 (buffer-substring (point-min) (point-max))))
20012 (defun org-html-handle-time-stamps (s)
20013 "Format time stamps in string S, or remove them."
20014 (catch 'exit
20015 (let (r b)
20016 (while (string-match org-maybe-keyword-time-regexp s)
20017 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
20018 ;; never export CLOCK
20019 (throw 'exit ""))
20020 (or b (setq b (substring s 0 (match-beginning 0))))
20021 (if (not org-export-with-timestamps)
20022 (setq r (concat r (substring s 0 (match-beginning 0)))
20023 s (substring s (match-end 0)))
20024 (setq r (concat
20025 r (substring s 0 (match-beginning 0))
20026 (if (match-end 1)
20027 (format "@<span class=\"timestamp-kwd\">%s @</span>"
20028 (match-string 1 s)))
20029 (format " @<span class=\"timestamp\">%s@</span>"
20030 (substring
20031 (org-translate-time (match-string 3 s)) 1 -1)))
20032 s (substring s (match-end 0)))))
20033 ;; Line break if line started and ended with time stamp stuff
20034 (if (not r)
20036 (setq r (concat r s))
20037 (unless (string-match "\\S-" (concat b s))
20038 (setq r (concat r "@<br/>")))
20039 r))))
20041 (defun org-html-protect (s)
20042 ;; convert & to &amp;, < to &lt; and > to &gt;
20043 (let ((start 0))
20044 (while (string-match "&" s start)
20045 (setq s (replace-match "&amp;" t t s)
20046 start (1+ (match-beginning 0))))
20047 (while (string-match "<" s)
20048 (setq s (replace-match "&lt;" t t s)))
20049 (while (string-match ">" s)
20050 (setq s (replace-match "&gt;" t t s))))
20053 (defun org-export-cleanup-toc-line (s)
20054 "Remove tags and time staps from lines going into the toc."
20055 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
20056 (setq s (replace-match "" t t s)))
20057 (when org-export-remove-timestamps-from-toc
20058 (while (string-match org-maybe-keyword-time-regexp s)
20059 (setq s (replace-match "" t t s))))
20060 (while (string-match org-bracket-link-regexp s)
20061 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
20062 t t s)))
20065 (defun org-html-expand (string)
20066 "Prepare STRING for HTML export. Applies all active conversions.
20067 If there are links in the string, don't modify these."
20068 (let* (m s l res)
20069 (while (setq m (string-match org-bracket-link-regexp string))
20070 (setq s (substring string 0 m)
20071 l (match-string 0 string)
20072 string (substring string (match-end 0)))
20073 (push (org-html-do-expand s) res)
20074 (push l res))
20075 (push (org-html-do-expand string) res)
20076 (apply 'concat (nreverse res))))
20078 (defun org-html-do-expand (s)
20079 "Apply all active conversions to translate special ASCII to HTML."
20080 (setq s (org-html-protect s))
20081 (if org-export-html-expand
20082 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
20083 (setq s (replace-match "<\\1>" t nil s))))
20084 (if org-export-with-emphasize
20085 (setq s (org-export-html-convert-emphasize s)))
20086 (if org-export-with-sub-superscripts
20087 (setq s (org-export-html-convert-sub-super s)))
20088 (if org-export-with-TeX-macros
20089 (let ((start 0) wd ass)
20090 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
20091 (setq wd (match-string 1 s))
20092 (if (setq ass (assoc wd org-html-entities))
20093 (setq s (replace-match (or (cdr ass)
20094 (concat "&" (car ass) ";"))
20095 t t s))
20096 (setq start (+ start (length wd)))))))
20099 (defun org-create-multibrace-regexp (left right n)
20100 "Create a regular expression which will match a balanced sexp.
20101 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
20102 as single character strings.
20103 The regexp returned will match the entire expression including the
20104 delimiters. It will also define a single group which contains the
20105 match except for the outermost delimiters. The maximum depth of
20106 stacked delimiters is N. Escaping delimiters is not possible."
20107 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
20108 (or "\\|")
20109 (re nothing)
20110 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
20111 (while (> n 1)
20112 (setq n (1- n)
20113 re (concat re or next)
20114 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
20115 (concat left "\\(" re "\\)" right)))
20117 (defvar org-match-substring-regexp
20118 (concat
20119 "\\([^\\]\\)\\([_^]\\)\\("
20120 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
20121 "\\|"
20122 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
20123 "\\|"
20124 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
20125 "The regular expression matching a sub- or superscript.")
20127 ;(let ((s "a\\_b"))
20128 ; (and (string-match org-match-substring-regexp s)
20129 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
20131 (defun org-export-html-convert-sub-super (string)
20132 "Convert sub- and superscripts in STRING to HTML."
20133 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
20134 (while (string-match org-match-substring-regexp string s)
20135 (if (and requireb (match-end 8))
20136 (setq s (match-end 2))
20137 (setq s (match-end 1)
20138 key (if (string= (match-string 2 string) "_") "sub" "sup")
20139 c (or (match-string 8 string)
20140 (match-string 6 string)
20141 (match-string 5 string))
20142 string (replace-match
20143 (concat (match-string 1 string)
20144 "<" key ">" c "</" key ">")
20145 t t string))))
20146 (while (string-match "\\\\\\([_^]\\)" string)
20147 (setq string (replace-match (match-string 1 string) t t string)))
20148 string))
20150 (defun org-export-html-convert-emphasize (string)
20151 "Apply emphasis."
20152 (let ((s 0))
20153 (while (string-match org-emph-re string s)
20154 (if (not (equal
20155 (substring string (match-beginning 3) (1+ (match-beginning 3)))
20156 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
20157 (setq string (replace-match
20158 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
20159 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
20160 "\\5") t nil string))
20161 (setq s (1+ s))))
20162 string))
20164 (defvar org-par-open nil)
20165 (defun org-open-par ()
20166 "Insert <p>, but first close previous paragraph if any."
20167 (org-close-par-maybe)
20168 (insert "\n<p>")
20169 (setq org-par-open t))
20170 (defun org-close-par-maybe ()
20171 "Close paragraph if there is one open."
20172 (when org-par-open
20173 (insert "</p>")
20174 (setq org-par-open nil)))
20175 (defun org-close-li ()
20176 "Close <li> if necessary."
20177 (org-close-par-maybe)
20178 (insert "</li>\n"))
20180 (defvar body-only) ; dynamically scoped into this.
20181 (defun org-html-level-start (level title umax with-toc head-count)
20182 "Insert a new level in HTML export.
20183 When TITLE is nil, just close all open levels."
20184 (org-close-par-maybe)
20185 (let ((l (1+ (max level umax))))
20186 (while (<= l org-level-max)
20187 (if (aref org-levels-open (1- l))
20188 (progn
20189 (org-html-level-close l)
20190 (aset org-levels-open (1- l) nil)))
20191 (setq l (1+ l)))
20192 (when title
20193 ;; If title is nil, this means this function is called to close
20194 ;; all levels, so the rest is done only if title is given
20195 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
20196 (setq title (replace-match
20197 (if org-export-with-tags
20198 (save-match-data
20199 (concat
20200 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
20201 (mapconcat 'identity (org-split-string
20202 (match-string 1 title) ":")
20203 "&nbsp;")
20204 "</span>"))
20206 t t title)))
20207 (if (> level umax)
20208 (progn
20209 (if (aref org-levels-open (1- level))
20210 (progn
20211 (org-close-li)
20212 (insert "<li>" title "<br/>\n"))
20213 (aset org-levels-open (1- level) t)
20214 (org-close-par-maybe)
20215 (insert "<ul>\n<li>" title "<br/>\n")))
20216 (if (and org-export-with-section-numbers (not body-only))
20217 (setq title (concat (org-section-number level) " " title)))
20218 (setq level (+ level org-export-html-toplevel-hlevel -1))
20219 (if with-toc
20220 (insert (format "\n<h%d id=\"sec-%d\">%s</h%d>\n"
20221 level head-count title level))
20222 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
20223 (org-open-par)))))
20225 (defun org-html-level-close (&rest args)
20226 "Terminate one level in HTML export."
20227 (org-close-li)
20228 (insert "</ul>\n"))
20230 ;;; iCalendar export
20232 ;;;###autoload
20233 (defun org-export-icalendar-this-file ()
20234 "Export current file as an iCalendar file.
20235 The iCalendar file will be located in the same directory as the Org-mode
20236 file, but with extension `.ics'."
20237 (interactive)
20238 (org-export-icalendar nil buffer-file-name))
20240 ;;;###autoload
20241 (defun org-export-icalendar-all-agenda-files ()
20242 "Export all files in `org-agenda-files' to iCalendar .ics files.
20243 Each iCalendar file will be located in the same directory as the Org-mode
20244 file, but with extension `.ics'."
20245 (interactive)
20246 (apply 'org-export-icalendar nil (org-agenda-files t)))
20248 ;;;###autoload
20249 (defun org-export-icalendar-combine-agenda-files ()
20250 "Export all files in `org-agenda-files' to a single combined iCalendar file.
20251 The file is stored under the name `org-combined-agenda-icalendar-file'."
20252 (interactive)
20253 (apply 'org-export-icalendar t (org-agenda-files t)))
20255 (defun org-export-icalendar (combine &rest files)
20256 "Create iCalendar files for all elements of FILES.
20257 If COMBINE is non-nil, combine all calendar entries into a single large
20258 file and store it under the name `org-combined-agenda-icalendar-file'."
20259 (save-excursion
20260 (org-prepare-agenda-buffers files)
20261 (let* ((dir (org-export-directory
20262 :ical (list :publishing-directory
20263 org-export-publishing-directory)))
20264 file ical-file ical-buffer category started org-agenda-new-buffers)
20266 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
20267 (when combine
20268 (setq ical-file
20269 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
20270 org-combined-agenda-icalendar-file
20271 (expand-file-name org-combined-agenda-icalendar-file dir))
20272 ical-buffer (org-get-agenda-file-buffer ical-file))
20273 (set-buffer ical-buffer) (erase-buffer))
20274 (while (setq file (pop files))
20275 (catch 'nextfile
20276 (org-check-agenda-file file)
20277 (set-buffer (org-get-agenda-file-buffer file))
20278 (unless combine
20279 (setq ical-file (concat (file-name-as-directory dir)
20280 (file-name-sans-extension
20281 (file-name-nondirectory buffer-file-name))
20282 ".ics"))
20283 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
20284 (with-current-buffer ical-buffer (erase-buffer)))
20285 (setq category (or org-category
20286 (file-name-sans-extension
20287 (file-name-nondirectory buffer-file-name))))
20288 (if (symbolp category) (setq category (symbol-name category)))
20289 (let ((standard-output ical-buffer))
20290 (if combine
20291 (and (not started) (setq started t)
20292 (org-start-icalendar-file org-icalendar-combined-name))
20293 (org-start-icalendar-file category))
20294 (org-print-icalendar-entries combine)
20295 (when (or (and combine (not files)) (not combine))
20296 (org-finish-icalendar-file)
20297 (set-buffer ical-buffer)
20298 (save-buffer)
20299 (run-hooks 'org-after-save-iCalendar-file-hook)))))
20300 (org-release-buffers org-agenda-new-buffers))))
20302 (defvar org-after-save-iCalendar-file-hook nil
20303 "Hook run after an iCalendar file has been saved.
20304 The iCalendar buffer is still current when this hook is run.
20305 A good way to use this is to tell a desktop calenndar application to re-read
20306 the iCalendar file.")
20308 (defun org-print-icalendar-entries (&optional combine)
20309 "Print iCalendar entries for the current Org-mode file to `standard-output'.
20310 When COMBINE is non nil, add the category to each line."
20311 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
20312 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
20313 (org-category-table (org-get-category-table))
20314 (dts (org-ical-ts-to-string
20315 (format-time-string (cdr org-time-stamp-formats) (current-time))
20316 "DTSTART"))
20317 hd ts ts2 state status (inc t) pos b sexp rrule
20318 scheduledp deadlinep tmp pri category
20319 (sexp-buffer (get-buffer-create "*ical-tmp*")))
20320 (save-excursion
20321 (goto-char (point-min))
20322 (while (re-search-forward re1 nil t)
20323 (catch :skip
20324 (org-agenda-skip)
20325 (setq pos (match-beginning 0)
20326 ts (match-string 0)
20327 inc t
20328 hd (org-get-heading)
20329 category (org-get-category))
20330 (if (looking-at re2)
20331 (progn
20332 (goto-char (match-end 0))
20333 (setq ts2 (match-string 1) inc nil))
20334 (setq ts2 ts
20335 tmp (buffer-substring (max (point-min)
20336 (- pos org-ds-keyword-length))
20337 pos)
20338 deadlinep (string-match org-deadline-regexp tmp)
20339 scheduledp (string-match org-scheduled-regexp tmp)
20340 ;; donep (org-entry-is-done-p)
20342 (if (or (string-match org-tr-regexp hd)
20343 (string-match org-ts-regexp hd))
20344 (setq hd (replace-match "" t t hd)))
20345 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
20346 (setq rrule
20347 (concat "\nRRULE:FREQ="
20348 (cdr (assoc
20349 (match-string 2 ts)
20350 '(("d" . "DAILY")("w" . "WEEKLY")
20351 ("m" . "MONTHLY")("y" . "YEARLY"))))
20352 ";INTERVAL=" (match-string 1 ts)))
20353 (setq rrule ""))
20354 (if (string-match org-bracket-link-regexp hd)
20355 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
20356 (match-string 1 hd))
20357 t t hd)))
20358 (if deadlinep (setq hd (concat "DL: " hd)))
20359 (if scheduledp (setq hd (concat "S: " hd)))
20360 (if (string-match "\\`<%%" ts)
20361 (with-current-buffer sexp-buffer
20362 (insert (substring ts 1 -1) " " hd "\n"))
20363 (princ (format "BEGIN:VEVENT
20365 %s%s
20366 SUMMARY:%s
20367 CATEGORIES:%s
20368 END:VEVENT\n"
20369 (org-ical-ts-to-string ts "DTSTART")
20370 (org-ical-ts-to-string ts2 "DTEND" inc)
20371 rrule hd category)))))
20373 (when (and org-icalendar-include-sexps
20374 (condition-case nil (require 'icalendar) (error nil))
20375 (fboundp 'icalendar-export-region))
20376 ;; Get all the literal sexps
20377 (goto-char (point-min))
20378 (while (re-search-forward "^&?%%(" nil t)
20379 (catch :skip
20380 (org-agenda-skip)
20381 (setq b (match-beginning 0))
20382 (goto-char (1- (match-end 0)))
20383 (forward-sexp 1)
20384 (end-of-line 1)
20385 (setq sexp (buffer-substring b (point)))
20386 (with-current-buffer sexp-buffer
20387 (insert sexp "\n"))
20388 (princ (org-diary-to-ical-string sexp-buffer)))))
20390 (when org-icalendar-include-todo
20391 (goto-char (point-min))
20392 (while (re-search-forward org-todo-line-regexp nil t)
20393 (catch :skip
20394 (org-agenda-skip)
20395 (setq state (match-string 2))
20396 (setq status (if (member state org-done-keywords)
20397 "COMPLETED" "NEEDS-ACTION"))
20398 (when (and state
20399 (or (not (member state org-done-keywords))
20400 (eq org-icalendar-include-todo 'all))
20401 (not (member org-archive-tag (org-get-tags-at)))
20403 (setq hd (match-string 3))
20404 (if (string-match org-bracket-link-regexp hd)
20405 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
20406 (match-string 1 hd))
20407 t t hd)))
20408 (if (string-match org-priority-regexp hd)
20409 (setq pri (string-to-char (match-string 2 hd))
20410 hd (concat (substring hd 0 (match-beginning 1))
20411 (substring hd (match-end 1))))
20412 (setq pri org-default-priority))
20413 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
20414 (- org-lowest-priority org-highest-priority))))))
20416 (princ (format "BEGIN:VTODO
20418 SUMMARY:%s
20419 CATEGORIES:%s
20420 SEQUENCE:1
20421 PRIORITY:%d
20422 STATUS:%s
20423 END:VTODO\n"
20424 dts hd category pri status)))))))))
20426 (defun org-start-icalendar-file (name)
20427 "Start an iCalendar file by inserting the header."
20428 (let ((user user-full-name)
20429 (name (or name "unknown"))
20430 (timezone (cadr (current-time-zone))))
20431 (princ
20432 (format "BEGIN:VCALENDAR
20433 VERSION:2.0
20434 X-WR-CALNAME:%s
20435 PRODID:-//%s//Emacs with Org-mode//EN
20436 X-WR-TIMEZONE:%s
20437 CALSCALE:GREGORIAN\n" name user timezone))))
20439 (defun org-finish-icalendar-file ()
20440 "Finish an iCalendar file by inserting the END statement."
20441 (princ "END:VCALENDAR\n"))
20443 (defun org-ical-ts-to-string (s keyword &optional inc)
20444 "Take a time string S and convert it to iCalendar format.
20445 KEYWORD is added in front, to make a complete line like DTSTART....
20446 When INC is non-nil, increase the hour by two (if time string contains
20447 a time), or the day by one (if it does not contain a time)."
20448 (let ((t1 (org-parse-time-string s 'nodefault))
20449 t2 fmt have-time time)
20450 (if (and (car t1) (nth 1 t1) (nth 2 t1))
20451 (setq t2 t1 have-time t)
20452 (setq t2 (org-parse-time-string s)))
20453 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
20454 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
20455 (when inc
20456 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
20457 (setq time (encode-time s mi h d m y)))
20458 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
20459 (concat keyword (format-time-string fmt time))))
20461 ;;; XOXO export
20463 (defun org-export-as-xoxo-insert-into (buffer &rest output)
20464 (with-current-buffer buffer
20465 (apply 'insert output)))
20466 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
20468 (defun org-export-as-xoxo (&optional buffer)
20469 "Export the org buffer as XOXO.
20470 The XOXO buffer is named *xoxo-<source buffer name>*"
20471 (interactive (list (current-buffer)))
20472 ;; A quickie abstraction
20474 ;; Output everything as XOXO
20475 (with-current-buffer (get-buffer buffer)
20476 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
20477 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
20478 (org-infile-export-plist)))
20479 (filename (concat (file-name-as-directory
20480 (org-export-directory :xoxo opt-plist))
20481 (file-name-sans-extension
20482 (file-name-nondirectory buffer-file-name))
20483 ".html"))
20484 (out (find-file-noselect filename))
20485 (last-level 1)
20486 (hanging-li nil))
20487 ;; Check the output buffer is empty.
20488 (with-current-buffer out (erase-buffer))
20489 ;; Kick off the output
20490 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
20491 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
20492 (let* ((hd (match-string-no-properties 1))
20493 (level (length hd))
20494 (text (concat
20495 (match-string-no-properties 2)
20496 (save-excursion
20497 (goto-char (match-end 0))
20498 (let ((str ""))
20499 (catch 'loop
20500 (while 't
20501 (forward-line)
20502 (if (looking-at "^[ \t]\\(.*\\)")
20503 (setq str (concat str (match-string-no-properties 1)))
20504 (throw 'loop str)))))))))
20506 ;; Handle level rendering
20507 (cond
20508 ((> level last-level)
20509 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
20511 ((< level last-level)
20512 (dotimes (- (- last-level level) 1)
20513 (if hanging-li
20514 (org-export-as-xoxo-insert-into out "</li>\n"))
20515 (org-export-as-xoxo-insert-into out "</ol>\n"))
20516 (when hanging-li
20517 (org-export-as-xoxo-insert-into out "</li>\n")
20518 (setq hanging-li nil)))
20520 ((equal level last-level)
20521 (if hanging-li
20522 (org-export-as-xoxo-insert-into out "</li>\n")))
20525 (setq last-level level)
20527 ;; And output the new li
20528 (setq hanging-li 't)
20529 (if (equal ?+ (elt text 0))
20530 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
20531 (org-export-as-xoxo-insert-into out "<li>" text))))
20533 ;; Finally finish off the ol
20534 (dotimes (- last-level 1)
20535 (if hanging-li
20536 (org-export-as-xoxo-insert-into out "</li>\n"))
20537 (org-export-as-xoxo-insert-into out "</ol>\n"))
20539 ;; Finish the buffer off and clean it up.
20540 (switch-to-buffer-other-window out)
20541 (indent-region (point-min) (point-max) nil)
20542 (save-buffer)
20543 (goto-char (point-min))
20547 ;;;; Key bindings
20549 ;; Make `C-c C-x' a prefix key
20550 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
20552 ;; TAB key with modifiers
20553 (org-defkey org-mode-map "\C-i" 'org-cycle)
20554 (org-defkey org-mode-map [(tab)] 'org-cycle)
20555 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
20556 (org-defkey org-mode-map [(meta tab)] 'org-complete)
20557 (org-defkey org-mode-map "\M-\t" 'org-complete)
20558 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
20559 ;; The following line is necessary under Suse GNU/Linux
20560 (unless (featurep 'xemacs)
20561 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
20562 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
20563 (define-key org-mode-map (kbd "<backtab>") 'org-shifttab)
20565 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
20566 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
20567 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
20569 ;; Cursor keys with modifiers
20570 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
20571 (org-defkey org-mode-map [(meta right)] 'org-metaright)
20572 (org-defkey org-mode-map [(meta up)] 'org-metaup)
20573 (org-defkey org-mode-map [(meta down)] 'org-metadown)
20575 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
20576 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
20577 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
20578 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
20580 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
20581 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
20582 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
20583 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
20585 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
20586 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
20588 ;;; Extra keys for tty access.
20589 ;; We only set them when really needed because otherwise the
20590 ;; menus don't show the simple keys
20592 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
20593 (not window-system))
20594 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
20595 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
20596 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
20597 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
20598 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
20599 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
20600 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
20601 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
20602 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
20603 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
20604 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
20605 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
20606 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
20607 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
20608 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
20609 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
20610 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
20611 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
20612 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
20613 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
20614 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
20615 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
20617 ;; All the other keys
20619 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
20620 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
20621 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
20622 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
20623 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
20624 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
20625 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
20626 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
20627 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
20628 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
20629 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
20630 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
20631 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
20632 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
20633 (org-defkey org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
20634 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
20635 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
20636 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
20637 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
20638 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
20639 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
20640 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
20641 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
20642 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
20643 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
20644 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
20645 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
20646 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
20647 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
20648 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
20649 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
20650 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
20651 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
20652 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
20653 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
20654 (org-defkey org-mode-map "\C-c-" 'org-table-insert-hline)
20655 (org-defkey org-mode-map "\C-c^" 'org-sort)
20656 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
20657 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
20658 (org-defkey org-mode-map "\C-m" 'org-return)
20659 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
20660 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
20661 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
20662 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
20663 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
20664 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
20665 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
20666 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
20667 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
20668 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
20669 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
20670 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
20671 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
20672 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
20673 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
20674 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
20676 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
20677 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
20678 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
20679 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
20681 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
20682 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
20683 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20684 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
20685 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20686 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20687 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20688 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
20689 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20691 (when (featurep 'xemacs)
20692 (org-defkey org-mode-map 'button3 'popup-mode-menu))
20694 (defsubst org-table-p () (org-at-table-p))
20696 (defun org-self-insert-command (N)
20697 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20698 If the cursor is in a table looking at whitespace, the whitespace is
20699 overwritten, and the table is not marked as requiring realignment."
20700 (interactive "p")
20701 (if (and (org-table-p)
20702 (progn
20703 ;; check if we blank the field, and if that triggers align
20704 (and org-table-auto-blank-field
20705 (member last-command
20706 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20707 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
20708 ;; got extra space, this field does not determine column width
20709 (let (org-table-may-need-update) (org-table-blank-field))
20710 ;; no extra space, this field may determine column width
20711 (org-table-blank-field)))
20713 (eq N 1)
20714 (looking-at "[^|\n]* |"))
20715 (let (org-table-may-need-update)
20716 (goto-char (1- (match-end 0)))
20717 (delete-backward-char 1)
20718 (goto-char (match-beginning 0))
20719 (self-insert-command N))
20720 (setq org-table-may-need-update t)
20721 (self-insert-command N)))
20723 (defun org-delete-backward-char (N)
20724 "Like `delete-backward-char', insert whitespace at field end in tables.
20725 When deleting backwards, in tables this function will insert whitespace in
20726 front of the next \"|\" separator, to keep the table aligned. The table will
20727 still be marked for re-alignment if the field did fill the entire column,
20728 because, in this case the deletion might narrow the column."
20729 (interactive "p")
20730 (if (and (org-table-p)
20731 (eq N 1)
20732 (string-match "|" (buffer-substring (point-at-bol) (point)))
20733 (looking-at ".*?|"))
20734 (let ((pos (point))
20735 (noalign (looking-at "[^|\n\r]* |"))
20736 (c org-table-may-need-update))
20737 (backward-delete-char N)
20738 (skip-chars-forward "^|")
20739 (insert " ")
20740 (goto-char (1- pos))
20741 ;; noalign: if there were two spaces at the end, this field
20742 ;; does not determine the width of the column.
20743 (if noalign (setq org-table-may-need-update c)))
20744 (backward-delete-char N)))
20746 (defun org-delete-char (N)
20747 "Like `delete-char', but insert whitespace at field end in tables.
20748 When deleting characters, in tables this function will insert whitespace in
20749 front of the next \"|\" separator, to keep the table aligned. The table will
20750 still be marked for re-alignment if the field did fill the entire column,
20751 because, in this case the deletion might narrow the column."
20752 (interactive "p")
20753 (if (and (org-table-p)
20754 (not (bolp))
20755 (not (= (char-after) ?|))
20756 (eq N 1))
20757 (if (looking-at ".*?|")
20758 (let ((pos (point))
20759 (noalign (looking-at "[^|\n\r]* |"))
20760 (c org-table-may-need-update))
20761 (replace-match (concat
20762 (substring (match-string 0) 1 -1)
20763 " |"))
20764 (goto-char pos)
20765 ;; noalign: if there were two spaces at the end, this field
20766 ;; does not determine the width of the column.
20767 (if noalign (setq org-table-may-need-update c)))
20768 (delete-char N))
20769 (delete-char N)))
20771 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20772 (put 'org-self-insert-command 'delete-selection t)
20773 (put 'orgtbl-self-insert-command 'delete-selection t)
20774 (put 'org-delete-char 'delete-selection 'supersede)
20775 (put 'org-delete-backward-char 'delete-selection 'supersede)
20777 ;; Make `flyspell-mode' delay after some commands
20778 (put 'org-self-insert-command 'flyspell-delayed t)
20779 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20780 (put 'org-delete-char 'flyspell-delayed t)
20781 (put 'org-delete-backward-char 'flyspell-delayed t)
20783 ;; How to do this: Measure non-white length of current string
20784 ;; If equal to column width, we should realign.
20786 (defun org-remap (map &rest commands)
20787 "In MAP, remap the functions given in COMMANDS.
20788 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20789 (let (new old)
20790 (while commands
20791 (setq old (pop commands) new (pop commands))
20792 (if (fboundp 'command-remapping)
20793 (org-defkey map (vector 'remap old) new)
20794 (substitute-key-definition old new map global-map)))))
20796 (when (eq org-enable-table-editor 'optimized)
20797 ;; If the user wants maximum table support, we need to hijack
20798 ;; some standard editing functions
20799 (org-remap org-mode-map
20800 'self-insert-command 'org-self-insert-command
20801 'delete-char 'org-delete-char
20802 'delete-backward-char 'org-delete-backward-char)
20803 (org-defkey org-mode-map "|" 'org-force-self-insert))
20805 (defun org-shiftcursor-error ()
20806 "Throw an error because Shift-Cursor command was applied in wrong context."
20807 (error "This command is active in special context like tables, headlines or timestamps"))
20809 (defun org-shifttab (&optional arg)
20810 "Global visibility cycling or move to previous table field.
20811 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
20812 on context.
20813 See the individual commands for more information."
20814 (interactive "P")
20815 (cond
20816 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20817 (arg (message "Content view to level: ")
20818 (org-content (prefix-numeric-value arg))
20819 (setq org-cycle-global-status 'overview))
20820 (t (call-interactively 'org-global-cycle))))
20822 (defun org-shiftmetaleft ()
20823 "Promote subtree or delete table column.
20824 Calls `org-promote-subtree', `org-outdent-item',
20825 or `org-table-delete-column', depending on context.
20826 See the individual commands for more information."
20827 (interactive)
20828 (cond
20829 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20830 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
20831 ((org-at-item-p) (call-interactively 'org-outdent-item))
20832 (t (org-shiftcursor-error))))
20834 (defun org-shiftmetaright ()
20835 "Demote subtree or insert table column.
20836 Calls `org-demote-subtree', `org-indent-item',
20837 or `org-table-insert-column', depending on context.
20838 See the individual commands for more information."
20839 (interactive)
20840 (cond
20841 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20842 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
20843 ((org-at-item-p) (call-interactively 'org-indent-item))
20844 (t (org-shiftcursor-error))))
20846 (defun org-shiftmetaup (&optional arg)
20847 "Move subtree up or kill table row.
20848 Calls `org-move-subtree-up' or `org-table-kill-row' or
20849 `org-move-item-up' depending on context. See the individual commands
20850 for more information."
20851 (interactive "P")
20852 (cond
20853 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20854 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
20855 ((org-at-item-p) (call-interactively 'org-move-item-up))
20856 (t (org-shiftcursor-error))))
20857 (defun org-shiftmetadown (&optional arg)
20858 "Move subtree down or insert table row.
20859 Calls `org-move-subtree-down' or `org-table-insert-row' or
20860 `org-move-item-down', depending on context. See the individual
20861 commands for more information."
20862 (interactive "P")
20863 (cond
20864 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20865 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
20866 ((org-at-item-p) (call-interactively 'org-move-item-down))
20867 (t (org-shiftcursor-error))))
20869 (defun org-metaleft (&optional arg)
20870 "Promote heading or move table column to left.
20871 Calls `org-do-promote' or `org-table-move-column', depending on context.
20872 With no specific context, calls the Emacs default `backward-word'.
20873 See the individual commands for more information."
20874 (interactive "P")
20875 (cond
20876 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20877 ((or (org-on-heading-p) (org-region-active-p))
20878 (call-interactively 'org-do-promote))
20879 ((org-at-item-p) (call-interactively 'org-outdent-item))
20880 (t (call-interactively 'backward-word))))
20882 (defun org-metaright (&optional arg)
20883 "Demote subtree or move table column to right.
20884 Calls `org-do-demote' or `org-table-move-column', depending on context.
20885 With no specific context, calls the Emacs default `forward-word'.
20886 See the individual commands for more information."
20887 (interactive "P")
20888 (cond
20889 ((org-at-table-p) (call-interactively 'org-table-move-column))
20890 ((or (org-on-heading-p) (org-region-active-p))
20891 (call-interactively 'org-do-demote))
20892 ((org-at-item-p) (call-interactively 'org-indent-item))
20893 (t (call-interactively 'forward-word))))
20895 (defun org-metaup (&optional arg)
20896 "Move subtree up or move table row up.
20897 Calls `org-move-subtree-up' or `org-table-move-row' or
20898 `org-move-item-up', depending on context. See the individual commands
20899 for more information."
20900 (interactive "P")
20901 (cond
20902 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20903 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
20904 ((org-at-item-p) (call-interactively 'org-move-item-up))
20905 (t (org-shiftcursor-error))))
20907 (defun org-metadown (&optional arg)
20908 "Move subtree down or move table row down.
20909 Calls `org-move-subtree-down' or `org-table-move-row' or
20910 `org-move-item-down', depending on context. See the individual
20911 commands for more information."
20912 (interactive "P")
20913 (cond
20914 ((org-at-table-p) (call-interactively 'org-table-move-row))
20915 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
20916 ((org-at-item-p) (call-interactively 'org-move-item-down))
20917 (t (org-shiftcursor-error))))
20919 (defun org-shiftup (&optional arg)
20920 "Increase item in timestamp or increase priority of current headline.
20921 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20922 depending on context. See the individual commands for more information."
20923 (interactive "P")
20924 (cond
20925 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
20926 ((org-on-heading-p) (call-interactively 'org-priority-up))
20927 ((org-at-item-p) (call-interactively 'org-previous-item))
20928 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
20930 (defun org-shiftdown (&optional arg)
20931 "Decrease item in timestamp or decrease priority of current headline.
20932 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20933 depending on context. See the individual commands for more information."
20934 (interactive "P")
20935 (cond
20936 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
20937 ((org-on-heading-p) (call-interactively 'org-priority-down))
20938 (t (call-interactively 'org-next-item))))
20940 (defun org-shiftright ()
20941 "Next TODO keyword or timestamp one day later, depending on context."
20942 (interactive)
20943 (cond
20944 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20945 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
20946 (t (org-shiftcursor-error))))
20948 (defun org-shiftleft ()
20949 "Previous TODO keyword or timestamp one day earlier, depending on context."
20950 (interactive)
20951 (cond
20952 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20953 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
20954 (t (org-shiftcursor-error))))
20956 (defun org-shiftcontrolright ()
20957 "Switch to next TODO set."
20958 (interactive)
20959 (cond
20960 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
20961 (t (org-shiftcursor-error))))
20963 (defun org-shiftcontrolleft ()
20964 "Switch to previous TODO set."
20965 (interactive)
20966 (cond
20967 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
20968 (t (org-shiftcursor-error))))
20970 (defun org-ctrl-c-ret ()
20971 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20972 (interactive)
20973 (cond
20974 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20975 (t (call-interactively 'org-insert-heading))))
20977 (defun org-copy-special ()
20978 "Copy region in table or copy current subtree.
20979 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20980 See the individual commands for more information."
20981 (interactive)
20982 (call-interactively
20983 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20985 (defun org-cut-special ()
20986 "Cut region in table or cut current subtree.
20987 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20988 See the individual commands for more information."
20989 (interactive)
20990 (call-interactively
20991 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20993 (defun org-paste-special (arg)
20994 "Paste rectangular region into table, or past subtree relative to level.
20995 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20996 See the individual commands for more information."
20997 (interactive "P")
20998 (if (org-at-table-p)
20999 (org-table-paste-rectangle)
21000 (org-paste-subtree arg)))
21002 (defun org-ctrl-c-ctrl-c (&optional arg)
21003 "Set tags in headline, or update according to changed information at point.
21005 This command does many different things, depending on context:
21007 - If the cursor is in a headline, prompt for tags and insert them
21008 into the current line, aligned to `org-tags-column'. When called
21009 with prefix arg, realign all tags in the current buffer.
21011 - If the cursor is in one of the special #+KEYWORD lines, this
21012 triggers scanning the buffer for these lines and updating the
21013 information.
21015 - If the cursor is inside a table, realign the table. This command
21016 works even if the automatic table editor has been turned off.
21018 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21019 the entire table.
21021 - If the cursor is inside a table created by the table.el package,
21022 activate that table.
21024 - If the current buffer is a remember buffer, close note and file it.
21025 with a prefix argument, file it without further interaction to the default
21026 location.
21028 - If the cursor is on a <<<target>>>, update radio targets and corresponding
21029 links in this buffer.
21031 - If the cursor is on a numbered item in a plain list, renumber the
21032 ordered list."
21033 (interactive "P")
21034 (let ((org-enable-table-editor t))
21035 (cond
21036 ((or org-clock-overlays
21037 org-occur-highlights
21038 org-latex-fragment-image-overlays)
21039 (org-remove-clock-overlays)
21040 (org-remove-occur-highlights)
21041 (org-remove-latex-fragment-image-overlays)
21042 (message "Temporary highlights/overlays removed from current buffer"))
21043 ((and (local-variable-p 'org-finish-function (current-buffer))
21044 (fboundp org-finish-function))
21045 (funcall org-finish-function))
21046 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
21047 ((org-on-heading-p) (call-interactively 'org-set-tags))
21048 ((org-at-table.el-p)
21049 (require 'table)
21050 (beginning-of-line 1)
21051 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
21052 (call-interactively 'table-recognize-table))
21053 ((org-at-table-p)
21054 (org-table-maybe-eval-formula)
21055 (if arg
21056 (call-interactively 'org-table-recalculate)
21057 (org-table-maybe-recalculate-line))
21058 (call-interactively 'org-table-align))
21059 ((org-at-item-checkbox-p)
21060 (call-interactively 'org-toggle-checkbox))
21061 ((org-at-item-p)
21062 (call-interactively 'org-maybe-renumber-ordered-list))
21063 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
21064 (cond
21065 ((equal (match-string 1) "TBLFM")
21066 ;; Recalculate the table before this line
21067 (save-excursion
21068 (beginning-of-line 1)
21069 (skip-chars-backward " \r\n\t")
21070 (if (org-at-table-p)
21071 (org-call-with-arg 'org-table-recalculate t))))
21073 (call-interactively 'org-mode-restart))))
21074 (t (error "C-c C-c can do nothing useful at this location.")))))
21076 (defun org-mode-restart ()
21077 "Restart Org-mode, to scan again for special lines.
21078 Also updates the keyword regular expressions."
21079 (interactive)
21080 (let ((org-inhibit-startup t)) (org-mode))
21081 (message "Org-mode restarted to refresh keyword and special line setup"))
21083 (defun org-return ()
21084 "Goto next table row or insert a newline.
21085 Calls `org-table-next-row' or `newline', depending on context.
21086 See the individual commands for more information."
21087 (interactive)
21088 (cond
21089 ((org-at-table-p)
21090 (org-table-justify-field-maybe)
21091 (call-interactively 'org-table-next-row))
21092 (t (newline))))
21094 (defun org-meta-return (&optional arg)
21095 "Insert a new heading or wrap a region in a table.
21096 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
21097 See the individual commands for more information."
21098 (interactive "P")
21099 (cond
21100 ((org-at-table-p)
21101 (call-interactively 'org-table-wrap-region))
21102 (t (call-interactively 'org-insert-heading))))
21104 ;;; Menu entries
21106 ;; Define the Org-mode menus
21107 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21108 '("Tbl"
21109 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
21110 ["Next Field" org-cycle (org-at-table-p)]
21111 ["Previous Field" org-shifttab (org-at-table-p)]
21112 ["Next Row" org-return (org-at-table-p)]
21113 "--"
21114 ["Blank Field" org-table-blank-field (org-at-table-p)]
21115 ["Edit Field" org-table-edit-field (org-at-table-p)]
21116 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21117 "--"
21118 ("Column"
21119 ["Move Column Left" org-metaleft (org-at-table-p)]
21120 ["Move Column Right" org-metaright (org-at-table-p)]
21121 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21122 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21123 ("Row"
21124 ["Move Row Up" org-metaup (org-at-table-p)]
21125 ["Move Row Down" org-metadown (org-at-table-p)]
21126 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21127 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21128 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21129 "--"
21130 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
21131 ("Rectangle"
21132 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21133 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21134 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21135 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21136 "--"
21137 ("Calculate"
21138 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21139 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21140 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
21141 "--"
21142 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21143 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21144 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21145 "--"
21146 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21147 "--"
21148 ["Sum Column/Rectangle" org-table-sum
21149 (or (org-at-table-p) (org-region-active-p))]
21150 ["Which Column?" org-table-current-column (org-at-table-p)])
21151 ["Debug Formulas"
21152 org-table-toggle-formula-debugger
21153 :style toggle :selected org-table-formula-debug]
21154 ["Show Col/Row Numbers"
21155 org-table-toggle-coordinate-overlays
21156 :style toggle :selected org-table-overlay-coordinates]
21157 "--"
21158 ["Create" org-table-create (and (not (org-at-table-p))
21159 org-enable-table-editor)]
21160 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21161 ["Import from File" org-table-import (not (org-at-table-p))]
21162 ["Export to File" org-table-export (org-at-table-p)]
21163 "--"
21164 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
21166 (easy-menu-define org-org-menu org-mode-map "Org menu"
21167 '("Org"
21168 ("Show/Hide"
21169 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
21170 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
21171 ["Sparse Tree" org-occur t]
21172 ["Reveal Context" org-reveal t]
21173 ["Show All" show-all t]
21174 "--"
21175 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21176 "--"
21177 ["New Heading" org-insert-heading t]
21178 ("Navigate Headings"
21179 ["Up" outline-up-heading t]
21180 ["Next" outline-next-visible-heading t]
21181 ["Previous" outline-previous-visible-heading t]
21182 ["Next Same Level" outline-forward-same-level t]
21183 ["Previous Same Level" outline-backward-same-level t]
21184 "--"
21185 ["Jump" org-goto t]
21186 "--"
21187 ["C-a finds headline start"
21188 (setq org-special-ctrl-a (not org-special-ctrl-a))
21189 :style toggle :selected org-special-ctrl-a])
21190 ("Edit Structure"
21191 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
21192 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
21193 "--"
21194 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
21195 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
21196 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21197 "--"
21198 ["Promote Heading" org-metaleft (not (org-at-table-p))]
21199 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
21200 ["Demote Heading" org-metaright (not (org-at-table-p))]
21201 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
21202 "--"
21203 ["Sort Region/Children" org-sort (not (org-at-table-p))]
21204 "--"
21205 ["Convert to odd levels" org-convert-to-odd-levels t]
21206 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21207 ("Editing"
21208 ["Emphasis..." org-emphasize t])
21209 ("Archive"
21210 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
21211 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
21212 ; :active t :keys "C-u C-c C-x C-a"]
21213 ["Sparse trees open ARCHIVE trees"
21214 (setq org-sparse-tree-open-archived-trees
21215 (not org-sparse-tree-open-archived-trees))
21216 :style toggle :selected org-sparse-tree-open-archived-trees]
21217 ["Cycling opens ARCHIVE trees"
21218 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
21219 :style toggle :selected org-cycle-open-archived-trees]
21220 ["Agenda includes ARCHIVE trees"
21221 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
21222 :style toggle :selected (not org-agenda-skip-archived-trees)]
21223 "--"
21224 ["Move Subtree to Archive" org-advertized-archive-subtree t]
21225 ; ["Check and Move Children" (org-archive-subtree '(4))
21226 ; :active t :keys "C-u C-c C-x C-s"]
21228 "--"
21229 ("TODO Lists"
21230 ["TODO/DONE/-" org-todo t]
21231 ("Select keyword"
21232 ["Next keyword" org-shiftright (org-on-heading-p)]
21233 ["Previous keyword" org-shiftleft (org-on-heading-p)]
21234 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
21235 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
21236 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
21237 ["Show TODO Tree" org-show-todo-tree t]
21238 ["Global TODO list" org-todo-list t]
21239 "--"
21240 ["Set Priority" org-priority t]
21241 ["Priority Up" org-shiftup t]
21242 ["Priority Down" org-shiftdown t]
21243 "--"
21244 ;; FIXME: why is this still here????
21245 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
21246 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
21247 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
21248 ; (or (org-on-heading-p) (org-at-item-p))]
21249 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
21250 ; (or (org-on-heading-p) (org-at-item-p))]
21251 ; ["Update Statistics" org-update-checkbox-count t]
21253 ("Dates and Scheduling"
21254 ["Timestamp" org-time-stamp t]
21255 ["Timestamp (inactive)" org-time-stamp-inactive t]
21256 ("Change Date"
21257 ["1 Day Later" org-shiftright t]
21258 ["1 Day Earlier" org-shiftleft t]
21259 ["1 ... Later" org-shiftup t]
21260 ["1 ... Earlier" org-shiftdown t])
21261 ["Compute Time Range" org-evaluate-time-range t]
21262 ["Schedule Item" org-schedule t]
21263 ["Deadline" org-deadline t]
21264 "--"
21265 ["Custom time format" org-toggle-time-stamp-overlays
21266 :style radio :selected org-display-custom-times]
21267 "--"
21268 ["Goto Calendar" org-goto-calendar t]
21269 ["Date from Calendar" org-date-from-calendar t])
21270 ("Logging work"
21271 ["Clock in" org-clock-in t]
21272 ["Clock out" org-clock-out t]
21273 ["Clock cancel" org-clock-cancel t]
21274 ["Display times" org-clock-display t]
21275 ["Create clock table" org-clock-report t]
21276 "--"
21277 ["Record DONE time"
21278 (progn (setq org-log-done (not org-log-done))
21279 (message "Switching to %s will %s record a timestamp"
21280 (car org-done-keywords)
21281 (if org-log-done "automatically" "not")))
21282 :style toggle :selected org-log-done])
21283 "--"
21284 ["Agenda Command..." org-agenda t]
21285 ("File List for Agenda")
21286 ("Special views current file"
21287 ["TODO Tree" org-show-todo-tree t]
21288 ["Check Deadlines" org-check-deadlines t]
21289 ["Timeline" org-timeline t]
21290 ["Tags Tree" org-tags-sparse-tree t])
21291 "--"
21292 ("Hyperlinks"
21293 ["Store Link (Global)" org-store-link t]
21294 ["Insert Link" org-insert-link t]
21295 ["Follow Link" org-open-at-point t]
21296 "--"
21297 ["Next link" org-next-link t]
21298 ["Previous link" org-previous-link t]
21299 "--"
21300 ["Descriptive Links"
21301 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
21302 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
21303 ["Literal Links"
21304 (progn
21305 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
21306 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
21307 "--"
21308 ["Export/Publish..." org-export t]
21309 ("LaTeX"
21310 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21311 :selected org-cdlatex-mode]
21312 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21313 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21314 ["Modify math symbol" org-cdlatex-math-modify
21315 (org-inside-LaTeX-fragment-p)]
21316 ["Export LaTeX fragments as images"
21317 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
21318 :style toggle :selected org-export-with-LaTeX-fragments])
21319 "--"
21320 ("Documentation"
21321 ["Show Version" org-version t]
21322 ["Info Documentation" org-info t])
21323 ("Customize"
21324 ["Browse Org Group" org-customize t]
21325 "--"
21326 ["Expand This Menu" org-create-customize-menu
21327 (fboundp 'customize-menu-create)])
21328 "--"
21329 ["Refresh setup" org-mode-restart t]
21332 (defun org-info (&optional node)
21333 "Read documentation for Org-mode in the info system.
21334 With optional NODE, go directly to that node."
21335 (interactive)
21336 (require 'info)
21337 (Info-goto-node (format "(org)%s" (or node ""))))
21339 (defun org-install-agenda-files-menu ()
21340 (let ((bl (buffer-list)))
21341 (save-excursion
21342 (while bl
21343 (set-buffer (pop bl))
21344 (if (org-mode-p) (setq bl nil)))
21345 (when (org-mode-p)
21346 (easy-menu-change
21347 '("Org") "File List for Agenda"
21348 (append
21349 (list
21350 ["Edit File List" (org-edit-agenda-file-list) t]
21351 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21352 ["Remove Current File from List" org-remove-file t]
21353 ["Cycle through agenda files" org-cycle-agenda-files t]
21354 "--")
21355 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21357 ;;;; Documentation
21359 (defun org-customize ()
21360 "Call the customize function with org as argument."
21361 (interactive)
21362 (customize-browse 'org))
21364 (defun org-create-customize-menu ()
21365 "Create a full customization menu for Org-mode, insert it into the menu."
21366 (interactive)
21367 (if (fboundp 'customize-menu-create)
21368 (progn
21369 (easy-menu-change
21370 '("Org") "Customize"
21371 `(["Browse Org group" org-customize t]
21372 "--"
21373 ,(customize-menu-create 'org)
21374 ["Set" Custom-set t]
21375 ["Save" Custom-save t]
21376 ["Reset to Current" Custom-reset-current t]
21377 ["Reset to Saved" Custom-reset-saved t]
21378 ["Reset to Standard Settings" Custom-reset-standard t]))
21379 (message "\"Org\"-menu now contains full customization menu"))
21380 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21382 ;;;; Miscellaneous stuff
21385 ;;; Generally useful functions
21387 (defun org-context ()
21388 "Return a list of contexts of the current cursor position.
21389 If several contexts apply, all are returned.
21390 Each context entry is a list with a symbol naming the context, and
21391 two positions indicating start and end of the context. Possible
21392 contexts are:
21394 :headline anywhere in a headline
21395 :headline-stars on the leading stars in a headline
21396 :todo-keyword on a TODO keyword (including DONE) in a headline
21397 :tags on the TAGS in a headline
21398 :priority on the priority cookie in a headline
21399 :item on the first line of a plain list item
21400 :item-bullet on the bullet/number of a plain list item
21401 :checkbox on the checkbox in a plain list item
21402 :table in an org-mode table
21403 :table-special on a special filed in a table
21404 :table-table in a table.el table
21405 :link on a hyperlink
21406 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
21407 :target on a <<target>>
21408 :radio-target on a <<<radio-target>>>
21409 :latex-fragment on a LaTeX fragment
21410 :latex-preview on a LaTeX fragment with overlayed preview image
21412 This function expects the position to be visible because it uses font-lock
21413 faces as a help to recognize the following contexts: :table-special, :link,
21414 and :keyword."
21415 (let* ((f (get-text-property (point) 'face))
21416 (faces (if (listp f) f (list f)))
21417 (p (point)) clist o)
21418 ;; First the large context
21419 (cond
21420 ((org-on-heading-p t)
21421 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21422 (when (progn
21423 (beginning-of-line 1)
21424 (looking-at org-todo-line-tags-regexp))
21425 (push (org-point-in-group p 1 :headline-stars) clist)
21426 (push (org-point-in-group p 2 :todo-keyword) clist)
21427 (push (org-point-in-group p 4 :tags) clist))
21428 (goto-char p)
21429 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
21430 (if (looking-at "\\[#[A-Z0-9]\\]")
21431 (push (org-point-in-group p 0 :priority) clist)))
21433 ((org-at-item-p)
21434 (push (org-point-in-group p 2 :item-bullet) clist)
21435 (push (list :item (point-at-bol)
21436 (save-excursion (org-end-of-item) (point)))
21437 clist)
21438 (and (org-at-item-checkbox-p)
21439 (push (org-point-in-group p 0 :checkbox) clist)))
21441 ((org-at-table-p)
21442 (push (list :table (org-table-begin) (org-table-end)) clist)
21443 (if (memq 'org-formula faces)
21444 (push (list :table-special
21445 (previous-single-property-change p 'face)
21446 (next-single-property-change p 'face)) clist)))
21447 ((org-at-table-p 'any)
21448 (push (list :table-table) clist)))
21449 (goto-char p)
21451 ;; Now the small context
21452 (cond
21453 ((org-at-timestamp-p)
21454 (push (org-point-in-group p 0 :timestamp) clist))
21455 ((memq 'org-link faces)
21456 (push (list :link
21457 (previous-single-property-change p 'face)
21458 (next-single-property-change p 'face)) clist))
21459 ((memq 'org-special-keyword faces)
21460 (push (list :keyword
21461 (previous-single-property-change p 'face)
21462 (next-single-property-change p 'face)) clist))
21463 ((org-on-target-p)
21464 (push (org-point-in-group p 0 :target) clist)
21465 (goto-char (1- (match-beginning 0)))
21466 (if (looking-at org-radio-target-regexp)
21467 (push (org-point-in-group p 0 :radio-target) clist))
21468 (goto-char p))
21469 ((setq o (car (delq nil
21470 (mapcar
21471 (lambda (x)
21472 (if (memq x org-latex-fragment-image-overlays) x))
21473 (org-overlays-at (point))))))
21474 (push (list :latex-fragment
21475 (org-overlay-start o) (org-overlay-end o)) clist)
21476 (push (list :latex-preview
21477 (org-overlay-start o) (org-overlay-end o)) clist))
21478 ((org-inside-LaTeX-fragment-p)
21479 ;; FIXME: positions wrong.
21480 (push (list :latex-fragment (point) (point)) clist)))
21482 (setq clist (nreverse (delq nil clist)))
21483 clist))
21485 ;; FIXME Compare with at-regexp-p
21486 (defun org-in-regexp (re &optional nlines visually)
21487 "Check if point is inside a match of regexp.
21488 Normally only the current line is checked, but you can include NLINES extra
21489 lines both before and after point into the search.
21490 If VISUALLY is set, require that the cursor is not after the match but
21491 really on, so that the block visually is on the match."
21492 (catch 'exit
21493 (let ((pos (point))
21494 (eol (point-at-eol (+ 1 (or nlines 0))))
21495 (inc (if visually 1 0)))
21496 (save-excursion
21497 (beginning-of-line (- 1 (or nlines 0)))
21498 (while (re-search-forward re eol t)
21499 (if (and (<= (match-beginning 0) pos)
21500 (>= (+ inc (match-end 0)) pos))
21501 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21503 (defun org-at-regexp-p (regexp)
21504 "Is point inside a match of REGEXP in the current line?"
21505 (catch 'exit
21506 (save-excursion
21507 (let ((pos (point)) (end (point-at-eol)))
21508 (beginning-of-line 1)
21509 (while (re-search-forward regexp end t)
21510 (if (and (<= (match-beginning 0) pos)
21511 (>= (match-end 0) pos))
21512 (throw 'exit t)))
21513 nil))))
21515 (defun org-uniquify (list)
21516 "Remove duplicate elements from LIST."
21517 (let (res)
21518 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21519 res))
21521 (defun org-delete-all (elts list)
21522 "Remove all elements in ELTS from LIST."
21523 (while elts
21524 (setq list (delete (pop elts) list)))
21525 list)
21527 (defun org-point-in-group (point group &optional context)
21528 "Check if POINT is in match-group GROUP.
21529 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21530 match. If the match group does ot exist or point is not inside it,
21531 return nil."
21532 (and (match-beginning group)
21533 (>= point (match-beginning group))
21534 (<= point (match-end group))
21535 (if context
21536 (list context (match-beginning group) (match-end group))
21537 t)))
21539 (defun org-combine-plists (&rest plists)
21540 "Create a single property list from all plists in PLISTS.
21541 The process starts by copying the first list, and then setting properties
21542 from the other lists. Settings in the last list are the most significant
21543 ones and overrule settings in the other lists."
21544 (let ((rtn (copy-sequence (pop plists)))
21545 p v ls)
21546 (while plists
21547 (setq ls (pop plists))
21548 (while ls
21549 (setq p (pop ls) v (pop ls))
21550 (setq rtn (plist-put rtn p v))))
21551 rtn))
21553 (defun org-move-line-down (arg)
21554 "Move the current line down. With prefix argument, move it past ARG lines."
21555 (interactive "p")
21556 (let ((col (current-column))
21557 beg end pos)
21558 (beginning-of-line 1) (setq beg (point))
21559 (beginning-of-line 2) (setq end (point))
21560 (beginning-of-line (+ 1 arg))
21561 (setq pos (move-marker (make-marker) (point)))
21562 (insert (delete-and-extract-region beg end))
21563 (goto-char pos)
21564 (move-to-column col)))
21566 (defun org-move-line-up (arg)
21567 "Move the current line up. With prefix argument, move it past ARG lines."
21568 (interactive "p")
21569 (let ((col (current-column))
21570 beg end pos)
21571 (beginning-of-line 1) (setq beg (point))
21572 (beginning-of-line 2) (setq end (point))
21573 (beginning-of-line (- arg))
21574 (setq pos (move-marker (make-marker) (point)))
21575 (insert (delete-and-extract-region beg end))
21576 (goto-char pos)
21577 (move-to-column col)))
21579 (defun org-replace-escapes (string table)
21580 "Replace %-escapes in STRING with values in TABLE.
21581 TABLE is an association list with keys line \"%a\" and string values.
21582 The sequences in STRING may contain normal field width and padding information,
21583 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21584 so values can contain further %-escapes if they are define later in TABLE."
21585 (let ((case-fold-search nil)
21586 e re rpl)
21587 (while (setq e (pop table))
21588 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21589 (while (string-match re string)
21590 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21591 (cdr e)))
21592 (setq string (replace-match rpl t t string))))
21593 string))
21596 (defun org-sublist (list start end)
21597 "Return a section of LIST, from START to END.
21598 Counting starts at 1."
21599 (let (rtn (c start))
21600 (setq list (nthcdr (1- start) list))
21601 (while (and list (<= c end))
21602 (push (pop list) rtn)
21603 (setq c (1+ c)))
21604 (nreverse rtn)))
21606 (defun org-find-base-buffer-visiting (file)
21607 "Like `find-buffer-visiting' but alway return the base buffer and
21608 not an indirect buffer"
21609 (let ((buf (find-buffer-visiting file)))
21610 (or (buffer-base-buffer buf) buf)))
21612 (defun org-image-file-name-regexp ()
21613 "Return regexp matching the file names of images."
21614 (if (fboundp 'image-file-name-regexp)
21615 (image-file-name-regexp)
21616 (let ((image-file-name-extensions
21617 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21618 "xbm" "xpm" "pbm" "pgm" "ppm")))
21619 (concat "\\."
21620 (regexp-opt (nconc (mapcar 'upcase
21621 image-file-name-extensions)
21622 image-file-name-extensions)
21624 "\\'"))))
21626 (defun org-file-image-p (file)
21627 "Return non-nil if FILE is an image."
21628 (save-match-data
21629 (string-match (org-image-file-name-regexp) file)))
21631 ;;; Paragraph filling stuff.
21632 ;; We want this to be just right, so use the full arsenal.
21634 (defun org-indent-line-function ()
21635 "Indent line like previous, but further if previous was headline or item."
21636 (interactive)
21637 (let* ((pos (point))
21638 (itemp (org-at-item-p))
21639 column bpos bcol tpos tcol bullet btype bullet-type)
21640 ;; Find the previous relevant line
21641 (beginning-of-line 1)
21642 (cond
21643 ((looking-at "#") (setq column 0))
21645 (beginning-of-line 0)
21646 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
21647 (beginning-of-line 0))
21648 (cond
21649 ((looking-at "\\*+[ \t]+")
21650 (goto-char (match-end 0))
21651 (setq column (current-column)))
21652 ((org-in-item-p)
21653 (org-beginning-of-item)
21654 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
21655 (setq bpos (match-beginning 1) tpos (match-end 0)
21656 bcol (progn (goto-char bpos) (current-column))
21657 tcol (progn (goto-char tpos) (current-column))
21658 bullet (match-string 1)
21659 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
21660 (if (not itemp)
21661 (setq column tcol)
21662 (goto-char pos)
21663 (beginning-of-line 1)
21664 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
21665 (setq bullet (match-string 1)
21666 btype (if (string-match "[0-9]" bullet) "n" bullet))
21667 (setq column (if (equal btype bullet-type) bcol tcol))))
21668 (t (setq column (org-get-indentation))))))
21669 (goto-char pos)
21670 (if (<= (current-column) (current-indentation))
21671 (indent-line-to column)
21672 (save-excursion (indent-line-to column)))))
21674 (defun org-set-autofill-regexps ()
21675 (interactive)
21676 ;; In the paragraph separator we include headlines, because filling
21677 ;; text in a line directly attached to a headline would otherwise
21678 ;; fill the headline as well.
21679 (org-set-local 'comment-start-skip "^#+[ \t]*")
21680 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
21681 ;; FIXME!!!!!!! (org-set-local 'paragraph-separate "\f\\|[ ]*$")
21682 ;; The paragraph starter includes hand-formatted lists.
21683 (org-set-local 'paragraph-start
21684 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
21685 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
21686 ;; But only if the user has not turned off tables or fixed-width regions
21687 (org-set-local
21688 'auto-fill-inhibit-regexp
21689 (concat "\\*\\|#\\+"
21690 "\\|[ \t]*" org-keyword-time-regexp
21691 (if (or org-enable-table-editor org-enable-fixed-width-editor)
21692 (concat
21693 "\\|[ \t]*["
21694 (if org-enable-table-editor "|" "")
21695 (if org-enable-fixed-width-editor ":" "")
21696 "]"))))
21697 ;; We use our own fill-paragraph function, to make sure that tables
21698 ;; and fixed-width regions are not wrapped. That function will pass
21699 ;; through to `fill-paragraph' when appropriate.
21700 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21701 ; Adaptive filling: To get full control, first make sure that
21702 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
21703 (org-set-local 'adaptive-fill-regexp "\000")
21704 (org-set-local 'adaptive-fill-function
21705 'org-adaptive-fill-function))
21707 (defun org-fill-paragraph (&optional justify)
21708 "Re-align a table, pass through to fill-paragraph if no table."
21709 (let ((table-p (org-at-table-p))
21710 (table.el-p (org-at-table.el-p)))
21711 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
21712 (table.el-p t) ; skip table.el tables
21713 (table-p (org-table-align) t) ; align org-mode tables
21714 (t nil)))) ; call paragraph-fill
21716 ;; For reference, this is the default value of adaptive-fill-regexp
21717 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
21719 (defun org-adaptive-fill-function ()
21720 "Return a fill prefix for org-mode files.
21721 In particular, this makes sure hanging paragraphs for hand-formatted lists
21722 work correctly."
21723 (cond ((looking-at "#[ \t]+")
21724 (match-string 0))
21725 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
21726 (save-excursion
21727 (goto-char (match-end 0))
21728 (make-string (current-column) ?\ )))
21729 (t nil)))
21731 ;;;; Functions extending outline functionality
21733 ;; C-a should go to the beginning of a *visible* line, also in the
21734 ;; new outline.el. I guess this should be patched into Emacs?
21735 (defun org-beginning-of-line ()
21736 "Go to the beginning of the current line. If that is invisible, continue
21737 to a visible line beginning. This makes the function of C-a more intuitive."
21738 (interactive)
21739 (let ((pos (point)))
21740 (beginning-of-line 1)
21741 (if (bobp)
21743 (backward-char 1)
21744 (if (org-invisible-p)
21745 (while (and (not (bobp)) (org-invisible-p))
21746 (backward-char 1)
21747 (beginning-of-line 1))
21748 (forward-char 1)))
21749 (when (and org-special-ctrl-a (looking-at org-todo-line-regexp)
21750 (= (char-after (match-end 1)) ?\ ))
21751 (goto-char
21752 (cond ((> pos (match-beginning 3)) (match-beginning 3))
21753 ((= pos (point)) (match-beginning 3))
21754 (t (point)))))))
21756 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21758 (defun org-invisible-p ()
21759 "Check if point is at a character currently not visible."
21760 ;; Early versions of noutline don't have `outline-invisible-p'.
21761 (if (fboundp 'outline-invisible-p)
21762 (outline-invisible-p)
21763 (get-char-property (point) 'invisible)))
21765 (defun org-invisible-p2 ()
21766 "Check if point is at a character currently not visible."
21767 (save-excursion
21768 (if (and (eolp) (not (bobp))) (backward-char 1))
21769 ;; Early versions of noutline don't have `outline-invisible-p'.
21770 (if (fboundp 'outline-invisible-p)
21771 (outline-invisible-p)
21772 (get-char-property (point) 'invisible))))
21774 (defalias 'org-back-to-heading 'outline-back-to-heading)
21775 (defalias 'org-on-heading-p 'outline-on-heading-p)
21776 (defalias 'org-at-heading-p 'outline-on-heading-p)
21777 (defun org-at-heading-or-item-p ()
21778 (or (org-on-heading-p) (org-at-item-p)))
21780 (defun org-on-target-p ()
21781 (or (org-in-regexp org-radio-target-regexp)
21782 (org-in-regexp org-target-regexp)))
21784 (defun org-up-heading-all (arg)
21785 "Move to the heading line of which the present line is a subheading.
21786 This function considers both visible and invisible heading lines.
21787 With argument, move up ARG levels."
21788 (if (fboundp 'outline-up-heading-all)
21789 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21790 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21792 (defun org-goto-sibling (&optional previous)
21793 "Goto the next sibling, even if it is invisible.
21794 When PREVIOUS is set, go to the previous sibling instead. Returns t
21795 when a sibling was found. When none is found, return nil and don't
21796 move point."
21797 (let ((fun (if previous 're-search-backward 're-search-forward))
21798 (pos (point))
21799 (re (concat "^" outline-regexp))
21800 level l)
21801 (org-back-to-heading t)
21802 (setq level (funcall outline-level))
21803 (catch 'exit
21804 (or previous (forward-char 1))
21805 (while (funcall fun re nil t)
21806 (setq l (funcall outline-level))
21807 (when (< l level) (goto-char pos) (throw 'exit nil))
21808 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21809 (goto-char pos)
21810 nil)))
21812 (defun org-show-siblings ()
21813 "Show all siblings of the current headline."
21814 (save-excursion
21815 (while (org-goto-sibling) (org-flag-heading nil)))
21816 (save-excursion
21817 (while (org-goto-sibling 'previous)
21818 (org-flag-heading nil))))
21820 (defun org-show-hidden-entry ()
21821 "Show an entry where even the heading is hidden."
21822 (save-excursion
21823 (org-show-entry)))
21825 (defun org-flag-heading (flag &optional entry)
21826 "Flag the current heading. FLAG non-nil means make invisible.
21827 When ENTRY is non-nil, show the entire entry."
21828 (save-excursion
21829 (org-back-to-heading t)
21830 ;; Check if we should show the entire entry
21831 (if entry
21832 (progn
21833 (org-show-entry)
21834 (save-excursion
21835 (and (outline-next-heading)
21836 (org-flag-heading nil))))
21837 (outline-flag-region (max 1 (1- (point)))
21838 (save-excursion (outline-end-of-heading) (point))
21839 flag))))
21841 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21842 ;; This is an exact copy of the original function, but it uses
21843 ;; `org-back-to-heading', to make it work also in invisible
21844 ;; trees. And is uses an invisible-OK argument.
21845 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21846 (org-back-to-heading invisible-OK)
21847 (let ((first t)
21848 (level (funcall outline-level)))
21849 (while (and (not (eobp))
21850 (or first (> (funcall outline-level) level)))
21851 (setq first nil)
21852 (outline-next-heading))
21853 (unless to-heading
21854 (if (memq (preceding-char) '(?\n ?\^M))
21855 (progn
21856 ;; Go to end of line before heading
21857 (forward-char -1)
21858 (if (memq (preceding-char) '(?\n ?\^M))
21859 ;; leave blank line before heading
21860 (forward-char -1))))))
21861 (point))
21863 (defun org-show-subtree ()
21864 "Show everything after this heading at deeper levels."
21865 (outline-flag-region
21866 (point)
21867 (save-excursion
21868 (outline-end-of-subtree) (outline-next-heading) (point))
21869 nil))
21871 (defun org-show-entry ()
21872 "Show the body directly following this heading.
21873 Show the heading too, if it is currently invisible."
21874 (interactive)
21875 (save-excursion
21876 (org-back-to-heading t)
21877 (outline-flag-region
21878 (max 1 (1- (point)))
21879 (save-excursion
21880 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
21881 (or (match-beginning 1) (point-max)))
21882 nil)))
21884 (defun org-make-options-regexp (kwds)
21885 "Make a regular expression for keyword lines."
21886 (concat
21888 "#?[ \t]*\\+\\("
21889 (mapconcat 'regexp-quote kwds "\\|")
21890 "\\):[ \t]*"
21891 "\\(.+\\)"))
21893 ;; Make isearch reveal the necessary context
21894 (defun org-isearch-end ()
21895 "Reveal context after isearch exits."
21896 (when isearch-success ; only if search was successful
21897 (if (featurep 'xemacs)
21898 ;; Under XEmacs, the hook is run in the correct place,
21899 ;; we directly show the context.
21900 (org-show-context 'isearch)
21901 ;; In Emacs the hook runs *before* restoring the overlays.
21902 ;; So we have to use a one-time post-command-hook to do this.
21903 ;; (Emacs 22 has a special variable, see function `org-mode')
21904 (unless (and (boundp 'isearch-mode-end-hook-quit)
21905 isearch-mode-end-hook-quit)
21906 ;; Only when the isearch was not quitted.
21907 (org-add-hook 'post-command-hook 'org-isearch-post-command
21908 'append 'local)))))
21910 (defun org-isearch-post-command ()
21911 "Remove self from hook, and show context."
21912 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
21913 (org-show-context 'isearch))
21916 ;;;; Address problems with some other packages
21918 ;; Make flyspell not check words in links, to not mess up our keymap
21919 (defun org-mode-flyspell-verify ()
21920 "Don't let flyspell put overlays at active buttons."
21921 (not (get-text-property (point) 'keymap)))
21923 ;; Make `bookmark-jump' show the jump location if it was hidden.
21924 (eval-after-load "bookmark"
21925 '(if (boundp 'bookmark-after-jump-hook)
21926 ;; We can use the hook
21927 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
21928 ;; Hook not available, use advice
21929 (defadvice bookmark-jump (after org-make-visible activate)
21930 "Make the position visible."
21931 (org-bookmark-jump-unhide))))
21933 (defun org-bookmark-jump-unhide ()
21934 "Unhide the current position, to show the bookmark location."
21935 (and (org-mode-p)
21936 (or (org-invisible-p)
21937 (save-excursion (goto-char (max (point-min) (1- (point))))
21938 (org-invisible-p)))
21939 (org-show-context 'bookmark-jump)))
21941 ;; Make session.el ignore our circular variable
21942 (eval-after-load "session"
21943 '(add-to-list 'session-globals-exclude 'org-mark-ring))
21945 ;;;; Experimental code
21947 (defun org-closed-in-range ()
21948 "Sparse tree of items closed in a certain time range.
21949 Still experimental, may disappear in the furture."
21950 (interactive)
21951 ;; Get the time interval from the user.
21952 (let* ((time1 (time-to-seconds
21953 (org-read-date nil 'to-time nil "Starting date: ")))
21954 (time2 (time-to-seconds
21955 (org-read-date nil 'to-time nil "End date:")))
21956 ;; callback function
21957 (callback (lambda ()
21958 (let ((time
21959 (time-to-seconds
21960 (apply 'encode-time
21961 (org-parse-time-string
21962 (match-string 1))))))
21963 ;; check if time in interval
21964 (and (>= time time1) (<= time time2))))))
21965 ;; make tree, check each match with the callback
21966 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
21969 (defun test ()
21970 (interactive)
21971 (message "hihi: %s" (org-item-indent-positions)))
21973 ;;;; Finish up
21975 (provide 'org)
21977 (run-hooks 'org-load-hook)
21979 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
21980 ;;; org.el ends here