Release 4.72
[org-mode/org-tableheadings.git] / org.el
blob4b177c1f7d05fec400bfda1c8f3dccd2a88f2eaa
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.72
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.72"
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 S-<cursor movement>.
158 Org-mode used S-<cursor movement> for changing timestamps and priorities.
159 S-<cursor movement> is also used for example by `CUA-mode' to select text.
160 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
161 alternative bindings. Setting this variable to t will replace the following
162 keys both in Org-mode and in the Org-agenda buffer.
164 S-up -> M-p
165 S-down -> M-n
166 S-left -> M--
167 S-right -> M-+
169 If you do not like the alternative keys, take a look at the variable
170 `org-disputed-keys'.
172 This option is only relevant at load-time of Org-mode, and must be set
173 *before* org.el is loaded. Changing it requires a restart of Emacs to
174 become effective."
175 :group 'org-startup
176 :type 'boolean)
178 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
180 (defcustom org-disputed-keys
181 '(([(shift up)] . [(meta p)])
182 ([(shift down)] . [(meta n)])
183 ([(shift left)] . [(meta -)])
184 ([(shift right)] . [(meta +)])
185 ([(control shift right)] . [(meta shift +)])
186 ([(control shift left)] . [(meta shift -)]))
187 "Keys for which Org-mode and other modes compete.
188 This is an alist, cars are the default keys, second element specifies
189 the alternative to use when `org-replace-disputed-keys' is t.
191 Keys can be specified in any syntax supported by `define-key'.
192 The value of this option takes effect only at Org-mode's startup,
193 therefore you'll have to restart Emacs to apply it after changing."
194 :group 'org-startup
195 :type 'alist)
197 (defun org-key (key)
198 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
199 Or return the original if not disputed."
200 (let* ((nkey (key-description key))
201 (x (find-if (lambda (x)
202 (equal (key-description (car x)) nkey))
203 org-disputed-keys)))
204 (cond ((not x) key)
205 (org-replace-disputed-keys (cdr x))
206 (t (car x)))))
208 (defun org-defkey (keymap key def)
209 "Define a key, possibly translated, as returned by `org-key'."
210 (define-key keymap (org-key key) def))
212 (defcustom org-ellipsis nil
213 "The ellipsis to use in the Org-mode outline.
214 When nil, just use the standard three dots. When a string, use that instead,
215 and just in Org-mode (which will then use its own display table).
216 Changing this requires executing `M-x org-mode' in a buffer to become
217 effective."
218 :group 'org-startup
219 :type '(choice (const :tag "Default" nil)
220 (string :tag "String" :value "...#")))
222 (defvar org-display-table nil
223 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
225 (defgroup org-keywords nil
226 "Keywords in Org-mode."
227 :tag "Org Keywords"
228 :group 'org)
230 (defcustom org-deadline-string "DEADLINE:"
231 "String to mark deadline entries.
232 A deadline is this string, followed by a time stamp. Should be a word,
233 terminated by a colon. You can insert a schedule keyword and
234 a timestamp with \\[org-deadline].
235 Changes become only effective after restarting Emacs."
236 :group 'org-keywords
237 :type 'string)
239 (defcustom org-scheduled-string "SCHEDULED:"
240 "String to mark scheduled TODO entries.
241 A schedule is this string, followed by a time stamp. Should be a word,
242 terminated by a colon. You can insert a schedule keyword and
243 a timestamp with \\[org-schedule].
244 Changes become only effective after restarting Emacs."
245 :group 'org-keywords
246 :type 'string)
248 (defcustom org-closed-string "CLOSED:"
249 "String used as the prefix for timestamps logging closing a TODO entry."
250 :group 'org-keywords
251 :type 'string)
253 (defcustom org-clock-string "CLOCK:"
254 "String used as prefix for timestamps clocking work hours on an item."
255 :group 'org-keywords
256 :type 'string)
258 (defcustom org-comment-string "COMMENT"
259 "Entries starting with this keyword will never be exported.
260 An entry can be toggled between COMMENT and normal with
261 \\[org-toggle-comment].
262 Changes become only effective after restarting Emacs."
263 :group 'org-keywords
264 :type 'string)
266 (defcustom org-quote-string "QUOTE"
267 "Entries starting with this keyword will be exported in fixed-width font.
268 Quoting applies only to the text in the entry following the headline, and does
269 not extend beyond the next headline, even if that is lower level.
270 An entry can be toggled between QUOTE and normal with
271 \\[org-toggle-fixed-width-section]."
272 :group 'org-keywords
273 :type 'string)
275 (defvar org-repeat-re "\\<REPEAT(\\([-+ 0-9dwmy]+\\))"
276 "Regular expression for specifying repeated events.
277 After a match, group 1 contains the repeat expression.")
279 (defgroup org-structure nil
280 "Options concerning the general structure of Org-mode files."
281 :tag "Org Structure"
282 :group 'org)
284 (defgroup org-reveal-location nil
285 "Options about how to make context of a location visible."
286 :tag "Org Reveal Location"
287 :group 'org-structure)
289 (defcustom org-show-hierarchy-above '((default . t))
290 "Non-nil means, show full hierarchy when revealing a location.
291 Org-mode often shows locations in an org-mode file which might have
292 been invisible before. When this is set, the hierarchy of headings
293 above the exposed location is shown.
294 Turning this off for example for sparse trees makes them very compact.
295 Instead of t, this can also be an alist specifying this option for different
296 contexts. Valid contexts are
297 agenda when exposing an entry from the agenda
298 org-goto when using the command `org-goto' on key C-c C-j
299 occur-tree when using the command `org-occur' on key C-c /
300 tags-tree when constructing a sparse tree based on tags matches
301 link-search when exposing search matches associated with a link
302 mark-goto when exposing the jump goal of a mark
303 bookmark-jump when exposing a bookmark location
304 isearch when exiting from an incremental search
305 default default for all contexts not set explicitly"
306 :group 'org-reveal-location
307 :type '(choice
308 (const :tag "Always" t)
309 (const :tag "Never" nil)
310 (repeat :greedy t :tag "Individual contexts"
311 (cons
312 (choice :tag "Context"
313 (const agenda)
314 (const org-goto)
315 (const occur-tree)
316 (const tags-tree)
317 (const link-search)
318 (const mark-goto)
319 (const bookmark-jump)
320 (const isearch)
321 (const default))
322 (boolean)))))
324 (defcustom org-show-following-heading '((default . t))
325 "Non-nil means, show following heading when revealing a location.
326 Org-mode often shows locations in an org-mode file which might have
327 been invisible before. When this is set, the heading following the
328 match is shown.
329 Turning this off for example for sparse trees makes them very compact,
330 but makes it harder to edit the location of the match. In such a case,
331 use the command \\[org-reveal] to show more context.
332 Instead of t, this can also be an alist specifying this option for different
333 contexts. See `org-show-hierarchy-above' for valid contexts."
334 :group 'org-reveal-location
335 :type '(choice
336 (const :tag "Always" t)
337 (const :tag "Never" nil)
338 (repeat :greedy t :tag "Individual contexts"
339 (cons
340 (choice :tag "Context"
341 (const agenda)
342 (const org-goto)
343 (const occur-tree)
344 (const tags-tree)
345 (const link-search)
346 (const mark-goto)
347 (const bookmark-jump)
348 (const isearch)
349 (const default))
350 (boolean)))))
352 (defcustom org-show-siblings '((default . nil) (isearch t))
353 "Non-nil means, show all sibling heading when revealing a location.
354 Org-mode often shows locations in an org-mode file which might have
355 been invisible before. When this is set, the sibling of the current entry
356 heading are all made visible. If `org-show-hierarchy-above' is t,
357 the same happens on each level of the hierarchy above the current entry.
359 By default this is on for the isearch context, off for all other contexts.
360 Turning this off for example for sparse trees makes them very compact,
361 but makes it harder to edit the location of the match. In such a case,
362 use the command \\[org-reveal] to show more context.
363 Instead of t, this can also be an alist specifying this option for different
364 contexts. See `org-show-hierarchy-above' for valid contexts."
365 :group 'org-reveal-location
366 :type '(choice
367 (const :tag "Always" t)
368 (const :tag "Never" nil)
369 (repeat :greedy t :tag "Individual contexts"
370 (cons
371 (choice :tag "Context"
372 (const agenda)
373 (const org-goto)
374 (const occur-tree)
375 (const tags-tree)
376 (const link-search)
377 (const mark-goto)
378 (const bookmark-jump)
379 (const isearch)
380 (const default))
381 (boolean)))))
383 (defgroup org-cycle nil
384 "Options concerning visibility cycling in Org-mode."
385 :tag "Org Cycle"
386 :group 'org-structure)
388 (defcustom org-cycle-global-at-bob t
389 "Cycle globally if cursor is at beginning of buffer and not at a headline.
390 This makes it possible to do global cycling without having to use S-TAB or
391 C-u TAB. For this special case to work, the first line of the buffer
392 must not be a headline - it may be empty ot some other text. When used in
393 this way, `org-cycle-hook' is disables temporarily, to make sure the
394 cursor stays at the beginning of the buffer.
395 When this option is nil, don't do anything special at the beginning
396 of the buffer."
397 :group 'org-cycle
398 :type 'boolean)
400 (defcustom org-cycle-emulate-tab t
401 "Where should `org-cycle' emulate TAB.
402 nil Never
403 white Only in completely white lines
404 whitestart Only at the beginning of lines, before the first non-white char.
405 t Everywhere except in headlines
406 If TAB is used in a place where it does not emulate TAB, the current subtree
407 visibility is cycled."
408 :group 'org-cycle
409 :type '(choice (const :tag "Never" nil)
410 (const :tag "Only in completely white lines" white)
411 (const :tag "Before first char in a line" whitestart)
412 (const :tag "Everywhere except in headlines" t)
415 (defcustom org-cycle-separator-lines 2
416 "Number of empty lines needed to keep an empty line between collapsed trees.
417 If you leave an empty line between the end of a subtree and the following
418 headline, this empty line is hidden when the subtree is folded.
419 Org-mode will leave (exactly) one empty line visible if the number of
420 empty lines is equal or larger to the number given in this variable.
421 So the default 2 means, at least 2 empty lines after the end of a subtree
422 are needed to produce free space between a collapsed subtree and the
423 following headline.
425 Special case: when 0, never leave empty lines in collapsed view."
426 :group 'org-cycle
427 :type 'integer)
429 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
430 org-cycle-show-empty-lines
431 org-optimize-window-after-visibility-change)
432 "Hook that is run after `org-cycle' has changed the buffer visibility.
433 The function(s) in this hook must accept a single argument which indicates
434 the new state that was set by the most recent `org-cycle' command. The
435 argument is a symbol. After a global state change, it can have the values
436 `overview', `content', or `all'. After a local state change, it can have
437 the values `folded', `children', or `subtree'."
438 :group 'org-cycle
439 :type 'hook)
441 (defgroup org-edit-structure nil
442 "Options concerning structure editing in Org-mode."
443 :tag "Org Edit Structure"
444 :group 'org-structure)
446 (defcustom org-special-ctrl-a nil
447 "Non-nil means `C-a' behaves specially in headlines.
448 When set, `C-a' will bring back the cursor to the beginning of the
449 headline text, i.e. after the stars and after a possible TODO keyword.
450 When the cursor is already at that position, another `C-a' will bring
451 it to the beginning of the line."
452 :group 'org-edit-structure
453 :type 'boolean)
455 (defcustom org-odd-levels-only nil
456 "Non-nil means, skip even levels and only use odd levels for the outline.
457 This has the effect that two stars are being added/taken away in
458 promotion/demotion commands. It also influences how levels are
459 handled by the exporters.
460 Changing it requires restart of `font-lock-mode' to become effective
461 for fontification also in regions already fontified.
462 You may also set this on a per-file basis by adding one of the following
463 lines to the buffer:
465 #+STARTUP: odd
466 #+STARTUP: oddeven"
467 :group 'org-edit-structure
468 :group 'org-font-lock
469 :type 'boolean)
471 (defcustom org-adapt-indentation t
472 "Non-nil means, adapt indentation when promoting and demoting.
473 When this is set and the *entire* text in an entry is indented, the
474 indentation is increased by one space in a demotion command, and
475 decreased by one in a promotion command. If any line in the entry
476 body starts at column 0, indentation is not changed at all."
477 :group 'org-edit-structure
478 :type 'boolean)
480 (defcustom org-blank-before-new-entry '((heading . nil)
481 (plain-list-item . nil))
482 "Should `org-insert-heading' leave a blank line before new heading/item?
483 The value is an alist, with `heading' and `plain-list-item' as car,
484 and a boolean flag as cdr."
485 :group 'org-edit-structure
486 :type '(list
487 (cons (const heading) (boolean))
488 (cons (const plain-list-item) (boolean))))
490 (defcustom org-insert-heading-hook nil
491 "Hook being run after inserting a new heading."
492 :group 'org-edit-structure
493 :type 'boolean)
495 (defcustom org-enable-fixed-width-editor t
496 "Non-nil means, lines starting with \":\" are treated as fixed-width.
497 This currently only means, they are never auto-wrapped.
498 When nil, such lines will be treated like ordinary lines.
499 See also the QUOTE keyword."
500 :group 'org-edit-structure
501 :type 'boolean)
503 (defgroup org-sparse-trees nil
504 "Options concerning sparse trees in Org-mode."
505 :tag "Org Sparse Trees"
506 :group 'org-structure)
508 (defcustom org-highlight-sparse-tree-matches t
509 "Non-nil means, highlight all matches that define a sparse tree.
510 The highlights will automatically disappear the next time the buffer is
511 changed by an edit command."
512 :group 'org-sparse-trees
513 :type 'boolean)
515 (defcustom org-remove-highlights-with-change t
516 "Non-nil means, any change to the buffer will remove temporary highlights.
517 Such highlights are created by `org-occur' and `org-clock-display'.
518 When nil, `C-c C-c needs to be used to get rid of the highlights.
519 The highlights created by `org-preview-latex-fragment' always need
520 `C-c C-c' to be removed."
521 :group 'org-sparse-trees
522 :group 'org-time
523 :type 'boolean)
526 (defcustom org-occur-hook '(org-first-headline-recenter)
527 "Hook that is run after `org-occur' has constructed a sparse tree.
528 This can be used to recenter the window to show as much of the structure
529 as possible."
530 :group 'org-sparse-trees
531 :type 'hook)
533 (defgroup org-plain-lists nil
534 "Options concerning plain lists in Org-mode."
535 :tag "Org Plain lists"
536 :group 'org-structure)
538 (defcustom org-cycle-include-plain-lists nil
539 "Non-nil means, include plain lists into visibility cycling.
540 This means that during cycling, plain list items will *temporarily* be
541 interpreted as outline headlines with a level given by 1000+i where i is the
542 indentation of the bullet. In all other operations, plain list items are
543 not seen as headlines. For example, you cannot assign a TODO keyword to
544 such an item."
545 :group 'org-plain-lists
546 :type 'boolean)
548 (defcustom org-plain-list-ordered-item-terminator t
549 "The character that makes a line with leading number an ordered list item.
550 Valid values are ?. and ?\). To get both terminators, use t. While
551 ?. may look nicer, it creates the danger that a line with leading
552 number may be incorrectly interpreted as an item. ?\) therefore is
553 the safe choice."
554 :group 'org-plain-lists
555 :type '(choice (const :tag "dot like in \"2.\"" ?.)
556 (const :tag "paren like in \"2)\"" ?\))
557 (const :tab "both" t)))
559 (defcustom org-auto-renumber-ordered-lists t
560 "Non-nil means, automatically renumber ordered plain lists.
561 Renumbering happens when the sequence have been changed with
562 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
563 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
564 :group 'org-plain-lists
565 :type 'boolean)
567 (defcustom org-provide-checkbox-statistics t
568 "Non-nil means, update checkbox statistics after insert and toggle.
569 When this is set, checkbox statistics is updated each time you either insert
570 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
571 with \\[org-ctrl-c-ctrl-c\\]."
572 :group 'org-plain-lists
573 :type 'boolean)
575 (defgroup org-archive nil
576 "Options concerning archiving in Org-mode."
577 :tag "Org Archive"
578 :group 'org-structure)
580 (defcustom org-archive-tag "ARCHIVE"
581 "The tag that marks a subtree as archived.
582 An archived subtree does not open during visibility cycling, and does
583 not contribute to the agenda listings."
584 :group 'org-archive
585 :group 'org-keywords
586 :type 'string)
588 (defcustom org-agenda-skip-archived-trees t
589 "Non-nil means, the agenda will skip any items located in archived trees.
590 An archived tree is a tree marked with the tag ARCHIVE."
591 :group 'org-archive
592 :group 'org-agenda-skip
593 :type 'boolean)
595 (defcustom org-cycle-open-archived-trees nil
596 "Non-nil means, `org-cycle' will open archived trees.
597 An archived tree is a tree marked with the tag ARCHIVE.
598 When nil, archived trees will stay folded. You can still open them with
599 normal outline commands like `show-all', but not with the cycling commands."
600 :group 'org-archive
601 :group 'org-cycle
602 :type 'boolean)
604 (defcustom org-sparse-tree-open-archived-trees nil
605 "Non-nil means sparse tree construction shows matches in archived trees.
606 When nil, matches in these trees are highlighted, but the trees are kept in
607 collapsed state."
608 :group 'org-archive
609 :group 'org-sparse-trees
610 :type 'boolean)
612 (defcustom org-archive-location "%s_archive::"
613 "The location where subtrees should be archived.
614 This string consists of two parts, separated by a double-colon.
616 The first part is a file name - when omitted, archiving happens in the same
617 file. %s will be replaced by the current file name (without directory part).
618 Archiving to a different file is useful to keep archived entries from
619 contributing to the Org-mode Agenda.
621 The part after the double colon is a headline. The archived entries will be
622 filed under that headline. When omitted, the subtrees are simply filed away
623 at the end of the file, as top-level entries.
625 Here are a few examples:
626 \"%s_archive::\"
627 If the current file is Projects.org, archive in file
628 Projects.org_archive, as top-level trees. This is the default.
630 \"::* Archived Tasks\"
631 Archive in the current file, under the top-level headline
632 \"* Archived Tasks\".
634 \"~/org/archive.org::\"
635 Archive in file ~/org/archive.org (absolute path), as top-level trees.
637 \"basement::** Finished Tasks\"
638 Archive in file ./basement (relative path), as level 3 trees
639 below the level 2 heading \"** Finished Tasks\".
641 You may set this option on a per-file basis by adding to the buffer a
642 line like
644 #+ARCHIVE: basement::** Finished Tasks"
645 :group 'org-archive
646 :type 'string)
648 (defcustom org-archive-mark-done t
649 "Non-nil means, mark entries as DONE when they are moved to the archive file."
650 :group 'org-archive
651 :type 'boolean)
653 (defcustom org-archive-stamp-time t
654 "Non-nil means, add a time stamp to entries moved to an archive file.
655 The time stamp will be added directly after the TODO state keyword in the
656 first line, so it is probably best to use this in combinations with
657 `org-archive-mark-done'."
658 :group 'org-archive
659 :type 'boolean)
661 (defgroup org-table nil
662 "Options concerning tables in Org-mode."
663 :tag "Org Table"
664 :group 'org)
666 (defcustom org-enable-table-editor 'optimized
667 "Non-nil means, lines starting with \"|\" are handled by the table editor.
668 When nil, such lines will be treated like ordinary lines.
670 When equal to the symbol `optimized', the table editor will be optimized to
671 do the following:
672 - Automatic overwrite mode in front of whitespace in table fields.
673 This makes the structure of the table stay in tact as long as the edited
674 field does not exceed the column width.
675 - Minimize the number of realigns. Normally, the table is aligned each time
676 TAB or RET are pressed to move to another field. With optimization this
677 happens only if changes to a field might have changed the column width.
678 Optimization requires replacing the functions `self-insert-command',
679 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
680 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
681 very good at guessing when a re-align will be necessary, but you can always
682 force one with \\[org-ctrl-c-ctrl-c].
684 If you would like to use the optimized version in Org-mode, but the
685 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
687 This variable can be used to turn on and off the table editor during a session,
688 but in order to toggle optimization, a restart is required.
690 See also the variable `org-table-auto-blank-field'."
691 :group 'org-table
692 :type '(choice
693 (const :tag "off" nil)
694 (const :tag "on" t)
695 (const :tag "on, optimized" optimized)))
697 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
698 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
699 In the optimized version, the table editor takes over all simple keys that
700 normally just insert a character. In tables, the characters are inserted
701 in a way to minimize disturbing the table structure (i.e. in overwrite mode
702 for empty fields). Outside tables, the correct binding of the keys is
703 restored.
705 The default for this option is t if the optimized version is also used in
706 Org-mode. See the variable `org-enable-table-editor' for details. Changing
707 this variable requires a restart of Emacs to become effective."
708 :group 'org-table
709 :type 'boolean)
711 (defcustom orgtbl-radio-table-templates
712 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
713 % END RECEIVE ORGTBL %n
714 \\begin{comment}
715 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
716 | | |
717 \\end{comment}\n")
718 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
719 @c END RECEIVE ORGTBL %n
720 @ignore
721 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
722 | | |
723 @end ignore\n")
724 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
725 <!-- END RECEIVE ORGTBL %n -->
726 <!--
727 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
728 | | |
729 -->\n"))
730 "Templates for radio tables in different major modes.
731 All occurrences of %n in a template will be replaced with the name of the
732 table, obtained by prompting the user."
733 :group 'org-table
734 :type '(repeat
735 (list (symbol :tag "Major mode")
736 (string :tag "Format"))))
738 (defgroup org-table-settings nil
739 "Settings for tables in Org-mode."
740 :tag "Org Table Settings"
741 :group 'org-table)
743 (defcustom org-table-default-size "5x2"
744 "The default size for newly created tables, Columns x Rows."
745 :group 'org-table-settings
746 :type 'string)
748 (defcustom org-table-number-regexp
749 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$"
750 "Regular expression for recognizing numbers in table columns.
751 If a table column contains mostly numbers, it will be aligned to the
752 right. If not, it will be aligned to the left.
754 The default value of this option is a regular expression which allows
755 anything which looks remotely like a number as used in scientific
756 context. For example, all of the following will be considered a
757 number:
758 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
760 Other options offered by the customize interface are more restrictive."
761 :group 'org-table-settings
762 :type '(choice
763 (const :tag "Positive Integers"
764 "^[0-9]+$")
765 (const :tag "Integers"
766 "^[-+]?[0-9]+$")
767 (const :tag "Floating Point Numbers"
768 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
769 (const :tag "Floating Point Number or Integer"
770 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
771 (const :tag "Exponential, Floating point, Integer"
772 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
773 (const :tag "Very General Number-Like, including hex"
774 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$")
775 (string :tag "Regexp:")))
777 (defcustom org-table-number-fraction 0.5
778 "Fraction of numbers in a column required to make the column align right.
779 In a column all non-white fields are considered. If at least this
780 fraction of fields is matched by `org-table-number-fraction',
781 alignment to the right border applies."
782 :group 'org-table-settings
783 :type 'number)
785 (defgroup org-table-editing nil
786 "Bahavior of tables during editing in Org-mode."
787 :tag "Org Table Editing"
788 :group 'org-table)
790 (defcustom org-table-automatic-realign t
791 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
792 When nil, aligning is only done with \\[org-table-align], or after column
793 removal/insertion."
794 :group 'org-table-editing
795 :type 'boolean)
797 (defcustom org-table-auto-blank-field t
798 "Non-nil means, automatically blank table field when starting to type into it.
799 This only happens when typing immediately after a field motion
800 command (TAB, S-TAB or RET).
801 Only relevant when `org-enable-table-editor' is equal to `optimized'."
802 :group 'org-table-editing
803 :type 'boolean)
805 (defcustom org-table-tab-jumps-over-hlines t
806 "Non-nil means, tab in the last column of a table with jump over a hline.
807 If a horizontal separator line is following the current line,
808 `org-table-next-field' can either create a new row before that line, or jump
809 over the line. When this option is nil, a new line will be created before
810 this line."
811 :group 'org-table-editing
812 :type 'boolean)
814 (defcustom org-table-tab-recognizes-table.el t
815 "Non-nil means, TAB will automatically notice a table.el table.
816 When it sees such a table, it moves point into it and - if necessary -
817 calls `table-recognize-table'."
818 :group 'org-table-editing
819 :type 'boolean)
821 (defgroup org-table-calculation nil
822 "Options concerning tables in Org-mode."
823 :tag "Org Table Calculation"
824 :group 'org-table)
826 (defcustom org-table-use-standard-references t
827 "Should org-mode work with table refrences like B3 instead of @3$2?
828 Possible values are:
829 nil never use them
830 from accept as input, do not present for editing
831 t: accept as input and present for editing"
832 :group 'org-table-calculation
833 :type '(choice
834 (const :tag "Never, don't even check unser input for them" nil)
835 (const :tag "Always, both as user input, and when editing" t)
836 (const :tag "Conver user input, don't offerr during editing" 'from)))
838 (defcustom org-table-copy-increment t
839 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
840 :group 'org-table-calculation
841 :type 'boolean)
843 (defcustom org-calc-default-modes
844 '(calc-internal-prec 12
845 calc-float-format (float 5)
846 calc-angle-mode deg
847 calc-prefer-frac nil
848 calc-symbolic-mode nil
849 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
850 calc-display-working-message t
852 "List with Calc mode settings for use in calc-eval for table formulas.
853 The list must contain alternating symbols (Calc modes variables and values).
854 Don't remove any of the default settings, just change the values. Org-mode
855 relies on the variables to be present in the list."
856 :group 'org-table-calculation
857 :type 'plist)
859 (defcustom org-table-formula-evaluate-inline t
860 "Non-nil means, TAB and RET evaluate a formula in current table field.
861 If the current field starts with an equal sign, it is assumed to be a formula
862 which should be evaluated as described in the manual and in the documentation
863 string of the command `org-table-eval-formula'. This feature requires the
864 Emacs calc package.
865 When this variable is nil, formula calculation is only available through
866 the command \\[org-table-eval-formula]."
867 :group 'org-table-calculation
868 :type 'boolean)
870 (defcustom org-table-formula-use-constants t
871 "Non-nil means, interpret constants in formulas in tables.
872 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
873 by the value given in `org-table-formula-constants', or by a value obtained
874 from the `constants.el' package."
875 :group 'org-table-calculation
876 :type 'boolean)
878 ;; FIXME this is also a variable that makes Org-mode files non-portable
879 ;; Maybe I should have a #+ options for constants?
880 (defcustom org-table-formula-constants nil
881 "Alist with constant names and values, for use in table formulas.
882 The car of each element is a name of a constant, without the `$' before it.
883 The cdr is the value as a string. For example, if you'd like to use the
884 speed of light in a formula, you would configure
886 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
888 and then use it in an equation like `$1*$c'."
889 :group 'org-table-calculation
890 :type '(repeat
891 (cons (string :tag "name")
892 (string :tag "value"))))
894 (defcustom org-table-allow-automatic-line-recalculation t
895 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
896 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
897 :group 'org-table-calculation
898 :type 'boolean)
900 (defgroup org-link nil
901 "Options concerning links in Org-mode."
902 :tag "Org Link"
903 :group 'org)
905 (defvar org-link-abbrev-alist-local nil
906 "buffer-local version of `org-link-abbrev-alist', which see.
907 The value of this is taken from the #+LINK lines.")
908 (make-variable-buffer-local 'org-link-abbrev-alist-local)
910 (defcustom org-link-abbrev-alist nil
911 "Alist of link abbreviations.
912 The car of each element is a string, to be replaced at the start of a link.
913 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
914 links in Org-mode buffers can have an optional tag after a double colon, e.g.
916 [[linkkey:tag][description]]
918 If REPLACE is a string, the tag will simply be appended to create the link.
919 If the string contains \"%s\", the tag will be inserted there. REPLACE may
920 also be a function that will be called with the tag as the only argument to
921 create the link. See the manual for examples."
922 :group 'org-link
923 :type 'alist)
925 (defcustom org-descriptive-links t
926 "Non-nil means, hide link part and only show description of bracket links.
927 Bracket links are like [[link][descritpion]]. This variable sets the initial
928 state in new org-mode buffers. The setting can then be toggled on a
929 per-buffer basis from the Org->Hyperlinks menu."
930 :group 'org-link
931 :type 'boolean)
933 (defcustom org-link-file-path-type 'adaptive
934 "How the path name in file links should be stored.
935 Valid values are:
937 relative relative to the current directory, i.e. the directory of the file
938 into which the link is being inserted.
939 absolute absolute path, if possible with ~ for home directory.
940 noabbrev absolute path, no abbreviation of home directory.
941 adaptive Use relative path for files in the current directory and sub-
942 directories of it. For other files, use an absolute path."
943 :group 'org-link
944 :type '(choice
945 (const relative)
946 (const absolute)
947 (const noabbrev)
948 (const adaptive)))
950 (defcustom org-activate-links '(bracket angle plain radio tag date)
951 "Types of links that should be activated in Org-mode files.
952 This is a list of symbols, each leading to the activation of a certain link
953 type. In principle, it does not hurt to turn on most link types - there may
954 be a small gain when turning off unused link types. The types are:
956 bracket The recommended [[link][description]] or [[link]] links with hiding.
957 angular Links in angular brackes that may contain whitespace like
958 <bbdb:Carsten Dominik>.
959 plain Plain links in normal text, no whitespace, like http://google.com.
960 radio Text that is matched by a radio target, see manual for details.
961 tag Tag settings in a headline (link to tag search).
962 date Time stamps (link to calendar).
964 Changing this variable requires a restart of Emacs to become effective."
965 :group 'org-link
966 :type '(set (const :tag "Double bracket links (new style)" bracket)
967 (const :tag "Angular bracket links (old style)" angular)
968 (const :tag "plain text links" plain)
969 (const :tag "Radio target matches" radio)
970 (const :tag "Tags" tag)
971 (const :tag "Timestamps" date)))
973 (defgroup org-link-store nil
974 "Options concerning storing links in Org-mode"
975 :tag "Org Store Link"
976 :group 'org-link)
978 (defcustom org-email-link-description-format "Email %c: %.30s"
979 "Format of the description part of a link to an email or usenet message.
980 The following %-excapes will be replaced by corresponding information:
982 %F full \"From\" field
983 %f name, taken from \"From\" field, address if no name
984 %T full \"To\" field
985 %t first name in \"To\" field, address if no name
986 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
987 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
988 %s subject
989 %m message-id.
991 You may use normal field width specification between the % and the letter.
992 This is for example useful to limit the length of the subject.
994 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
995 :group 'org-link-store
996 :type 'string)
998 (defcustom org-from-is-user-regexp
999 (let (r1 r2)
1000 (when (and user-mail-address (not (string= user-mail-address "")))
1001 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1002 (when (and user-full-name (not (string= user-full-name "")))
1003 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1004 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1005 "Regexp mached against the \"From:\" header of an email or usenet message.
1006 It should match if the message is from the user him/herself."
1007 :group 'org-link-store
1008 :type 'regexp)
1010 (defcustom org-context-in-file-links t
1011 "Non-nil means, file links from `org-store-link' contain context.
1012 A search string will be added to the file name with :: as separator and
1013 used to find the context when the link is activated by the command
1014 `org-open-at-point'.
1015 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1016 negates this setting for the duration of the command."
1017 :group 'org-link-store
1018 :type 'boolean)
1020 (defcustom org-keep-stored-link-after-insertion nil
1021 "Non-nil means, keep link in list for entire session.
1023 The command `org-store-link' adds a link pointing to the current
1024 location to an internal list. These links accumulate during a session.
1025 The command `org-insert-link' can be used to insert links into any
1026 Org-mode file (offering completion for all stored links). When this
1027 option is nil, every link which has been inserted once using \\[org-insert-link]
1028 will be removed from the list, to make completing the unused links
1029 more efficient."
1030 :group 'org-link-store
1031 :type 'boolean)
1033 (defcustom org-usenet-links-prefer-google nil
1034 "Non-nil means, `org-store-link' will create web links to Google groups.
1035 When nil, Gnus will be used for such links.
1036 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1037 negates this setting for the duration of the command."
1038 :group 'org-link-store
1039 :type 'boolean)
1041 (defgroup org-link-follow nil
1042 "Options concerning following links in Org-mode"
1043 :tag "Org Follow Link"
1044 :group 'org-link)
1046 (defcustom org-tab-follows-link nil
1047 "Non-nil means, on links TAB will follow the link.
1048 Needs to be set before org.el is loaded."
1049 :group 'org-link-follow
1050 :type 'boolean)
1052 (defcustom org-return-follows-link nil
1053 "Non-nil means, on links RET will follow the link.
1054 Needs to be set before org.el is loaded."
1055 :group 'org-link-follow
1056 :type 'boolean)
1058 (defcustom org-mouse-1-follows-link t
1059 "Non-nil means, mouse-1 on a link will follow the link.
1060 A longer mouse click will still set point. Does not wortk on XEmacs.
1061 Needs to be set before org.el is loaded."
1062 :group 'org-link-follow
1063 :type 'boolean)
1065 (defcustom org-mark-ring-length 4
1066 "Number of different positions to be recorded in the ring
1067 Changing this requires a restart of Emacs to work correctly."
1068 :group 'org-link-follow
1069 :type 'interger)
1071 (defcustom org-link-frame-setup
1072 '((vm . vm-visit-folder-other-frame)
1073 (gnus . gnus-other-frame)
1074 (file . find-file-other-window))
1075 "Setup the frame configuration for following links.
1076 When following a link with Emacs, it may often be useful to display
1077 this link in another window or frame. This variable can be used to
1078 set this up for the different types of links.
1079 For VM, use any of
1080 `vm-visit-folder'
1081 `vm-visit-folder-other-frame'
1082 For Gnus, use any of
1083 `gnus'
1084 `gnus-other-frame'
1085 For FILE, use any of
1086 `find-file'
1087 `find-file-other-window'
1088 `find-file-other-frame'
1089 For the calendar, use the variable `calendar-setup'.
1090 For BBDB, it is currently only possible to display the matches in
1091 another window."
1092 :group 'org-link-follow
1093 :type '(list
1094 (cons (const vm)
1095 (choice
1096 (const vm-visit-folder)
1097 (const vm-visit-folder-other-window)
1098 (const vm-visit-folder-other-frame)))
1099 (cons (const gnus)
1100 (choice
1101 (const gnus)
1102 (const gnus-other-frame)))
1103 (cons (const file)
1104 (choice
1105 (const find-file)
1106 (const find-file-other-window)
1107 (const find-file-other-frame)))))
1109 (defcustom org-display-internal-link-with-indirect-buffer nil
1110 "Non-nil means, use indirect buffer to display infile links.
1111 Activating internal links (from one location in a file to another location
1112 in the same file) normally just jumps to the location. When the link is
1113 activated with a C-u prefix (or with mouse-3), the link is displayed in
1114 another window. When this option is set, the other window actually displays
1115 an indirect buffer clone of the current buffer, to avoid any visibility
1116 changes to the current buffer."
1117 :group 'org-link-follow
1118 :type 'boolean)
1120 (defcustom org-open-non-existing-files nil
1121 "Non-nil means, `org-open-file' will open non-existing files.
1122 When nil, an error will be generated."
1123 :group 'org-link-follow
1124 :type 'boolean)
1126 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1127 "Function and arguments to call for following mailto links.
1128 This is a list with the first element being a lisp function, and the
1129 remaining elements being arguments to the function. In string arguments,
1130 %a will be replaced by the address, and %s will be replaced by the subject
1131 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1132 :group 'org-link-follow
1133 :type '(choice
1134 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1135 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1136 (const :tag "message-mail" (message-mail "%a" "%s"))
1137 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1139 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1140 "Non-nil means, ask for confirmation before executing shell links.
1141 Shell links can be dangerous, just thing about a link
1143 [[shell:rm -rf ~/*][Google Search]]
1145 This link would show up in your Org-mode document as \"Google Search\"
1146 but really it would remove your entire home directory.
1147 Therefore I *definitely* advise against setting this variable to nil.
1148 Just change it to `y-or-n-p' of you want to confirm with a single key press
1149 rather than having to type \"yes\"."
1150 :group 'org-link-follow
1151 :type '(choice
1152 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1153 (const :tag "with y-or-n (faster)" y-or-n-p)
1154 (const :tag "no confirmation (dangerous)" nil)))
1156 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1157 "Non-nil means, ask for confirmation before executing elisp links.
1158 Elisp links can be dangerous, just think about a link
1160 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1162 This link would show up in your Org-mode document as \"Google Search\"
1163 but really it would remove your entire home directory.
1164 Therefore I *definitely* advise against setting this variable to nil.
1165 Just change it to `y-or-n-p' of you want to confirm with a single key press
1166 rather than having to type \"yes\"."
1167 :group 'org-link-follow
1168 :type '(choice
1169 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1170 (const :tag "with y-or-n (faster)" y-or-n-p)
1171 (const :tag "no confirmation (dangerous)" nil)))
1173 (defconst org-file-apps-defaults-gnu
1174 '((remote . emacs)
1175 (t . mailcap))
1176 "Default file applications on a UNIX or GNU/Linux system.
1177 See `org-file-apps'.")
1179 (defconst org-file-apps-defaults-macosx
1180 '((remote . emacs)
1181 (t . "open %s")
1182 ("ps" . "gv %s")
1183 ("ps.gz" . "gv %s")
1184 ("eps" . "gv %s")
1185 ("eps.gz" . "gv %s")
1186 ("dvi" . "xdvi %s")
1187 ("fig" . "xfig %s"))
1188 "Default file applications on a MacOS X system.
1189 The system \"open\" is known as a default, but we use X11 applications
1190 for some files for which the OS does not have a good default.
1191 See `org-file-apps'.")
1193 (defconst org-file-apps-defaults-windowsnt
1194 (list
1195 '(remote . emacs)
1196 (cons t
1197 (list (if (featurep 'xemacs)
1198 'mswindows-shell-execute
1199 'w32-shell-execute)
1200 "open" 'file)))
1201 "Default file applications on a Windows NT system.
1202 The system \"open\" is used for most files.
1203 See `org-file-apps'.")
1205 (defcustom org-file-apps
1207 ("txt" . emacs)
1208 ("tex" . emacs)
1209 ("ltx" . emacs)
1210 ("org" . emacs)
1211 ("el" . emacs)
1212 ("bib" . emacs)
1214 "External applications for opening `file:path' items in a document.
1215 Org-mode uses system defaults for different file types, but
1216 you can use this variable to set the application for a given file
1217 extension. The entries in this list are cons cells where the car identifies
1218 files and the cdr the corresponding command. Possible values for the
1219 file identifier are
1220 \"ext\" A string identifying an extension
1221 `directory' Matches a directory
1222 `remote' Matches a remote file, accessible through tramp or efs.
1223 Remote files most likely should be visited through Emacs
1224 because external applications cannot handle such paths.
1225 t Default for all remaining files
1227 Possible values for the command are:
1228 `emacs' The file will be visited by the current Emacs process.
1229 `default' Use the default application for this file type.
1230 string A command to be executed by a shell; %s will be replaced
1231 by the path to the file.
1232 sexp A Lisp form which will be evaluated. The file path will
1233 be available in the Lisp variable `file'.
1234 For more examples, see the system specific constants
1235 `org-file-apps-defaults-macosx'
1236 `org-file-apps-defaults-windowsnt'
1237 `org-file-apps-defaults-gnu'."
1238 :group 'org-link-follow
1239 :type '(repeat
1240 (cons (choice :value ""
1241 (string :tag "Extension")
1242 (const :tag "Default for unrecognized files" t)
1243 (const :tag "Remote file" remote)
1244 (const :tag "Links to a directory" directory))
1245 (choice :value ""
1246 (const :tag "Visit with Emacs" emacs)
1247 (const :tag "Use system default" default)
1248 (string :tag "Command")
1249 (sexp :tag "Lisp form")))))
1251 (defcustom org-mhe-search-all-folders nil
1252 "Non-nil means, that the search for the mh-message will be extended to
1253 all folders if the message cannot be found in the folder given in the link.
1254 Searching all folders is very efficient with one of the search engines
1255 supported by MH-E, but will be slow with pick."
1256 :group 'org-link-follow
1257 :type 'boolean)
1259 (defgroup org-remember nil
1260 "Options concerning interaction with remember.el."
1261 :tag "Org Remember"
1262 :group 'org)
1264 (defcustom org-directory "~/org"
1265 "Directory with org files.
1266 This directory will be used as default to prompt for org files.
1267 Used by the hooks for remember.el."
1268 :group 'org-remember
1269 :type 'directory)
1271 (defcustom org-default-notes-file "~/.notes"
1272 "Default target for storing notes.
1273 Used by the hooks for remember.el. This can be a string, or nil to mean
1274 the value of `remember-data-file'.
1275 You can set this on a per-template basis with the variable
1276 `org-remember-templates'."
1277 :group 'org-remember
1278 :type '(choice
1279 (const :tag "Default from remember-data-file" nil)
1280 file))
1282 (defcustom org-remember-default-headline ""
1283 "The headline that should be the default location in the notes file.
1284 When filing remember notes, the cursor will start at that position.
1285 You can set this on a per-template basis with the variable
1286 `org-remember-templates'."
1287 :group 'org-remember
1288 :type 'string)
1290 (defcustom org-remember-templates nil
1291 "Templates for the creation of remember buffers.
1292 When nil, just let remember make the buffer.
1293 When not nil, this is a list of 4-element lists. In each entry, the first
1294 element is a character, a unique key to select this template.
1295 The second element is the template. The third element is optional and can
1296 specify a destination file for remember items created with this template.
1297 The default file is given by `org-default-notes-file'. An optional third
1298 element can specify the headline in that file that should be offered
1299 first when the user is asked to file the entry. The default headline is
1300 given in the variable `org-remember-default-headline'.
1302 The template specifies the structure of the remember buffer. It should have
1303 a first line starting with a star, to act as the org-mode headline.
1304 Furthermore, the following %-escapes will be replaced with content:
1306 %^{prompt} prompt the user for a string and replace this sequence with it.
1307 %t time stamp, date only
1308 %T time stamp with date and time
1309 %u, %U like the above, but inactive time stamps
1310 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1311 You may define a prompt like %^{Please specify birthday}t
1312 %n user name (taken from `user-full-name')
1313 %a annotation, normally the link created with org-store-link
1314 %i initial content, the region when remember is called with C-u.
1315 If %i is indented, the entire inserted text will be indented
1316 as well.
1318 %? After completing the template, position cursor here.
1320 Apart from these general escapes, you can access information specific to the
1321 link type that is created. For example, calling `remember' in emails or gnus
1322 will record the author and the subject of the message, which you can access
1323 with %:author and %:subject, respectively. Here is a complete list of what
1324 is recorded for each link type.
1326 Link type | Available information
1327 -------------------+------------------------------------------------------
1328 bbdb | %:type %:name %:company
1329 vm, wl, mh, rmail | %:type %:subject %:message-id
1330 | %:from %:fromname %:fromaddress
1331 | %:to %:toname %:toaddress
1332 | %:fromto (either \"to NAME\" or \"from NAME\")
1333 gnus | %:group, for messages also all email fields
1334 w3, w3m | %:type %:url
1335 info | %:type %:file %:node
1336 calendar | %:type %:date"
1337 :group 'org-remember
1338 :get (lambda (var) ; Make sure all entries have 4 elements
1339 (mapcar (lambda (x)
1340 (cond ((= (length x) 3) (append x '("")))
1341 ((= (length x) 2) (append x '("" "")))
1342 (t x)))
1343 (default-value var)))
1344 :type '(repeat
1345 :tag "enabled"
1346 (list :value (?a "\n" nil nil)
1347 (character :tag "Selection Key")
1348 (string :tag "Template")
1349 (file :tag "Destination file (optional)")
1350 (string :tag "Destination headline (optional)"))))
1352 (defcustom org-reverse-note-order nil
1353 "Non-nil means, store new notes at the beginning of a file or entry.
1354 When nil, new notes will be filed to the end of a file or entry."
1355 :group 'org-remember
1356 :type '(choice
1357 (const :tag "Reverse always" t)
1358 (const :tag "Reverse never" nil)
1359 (repeat :tag "By file name regexp"
1360 (cons regexp boolean))))
1362 (defgroup org-todo nil
1363 "Options concerning TODO items in Org-mode."
1364 :tag "Org TODO"
1365 :group 'org)
1367 (defgroup org-progress nil
1368 "Options concerning Progress logging in Org-mode."
1369 :tag "Org Progress"
1370 :group 'org-time)
1372 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1373 "List of TODO entry keyword sequences and their interpretation.
1374 \\<org-mode-map>This is a list of sequences.
1376 Each sequence starts with a symbol, either `sequence' or `type',
1377 indicating if the keywords should be interpreted as a sequence of
1378 action steps, or as different types of TODO items. The first
1379 keywords are states requiring action - these states will select a headline
1380 for inclusion into the global TODO list Org-mode produces. If one of
1381 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1382 signify that no further action is necessary. If \"|\" is not found,
1383 the last keyword is treated as the only DONE state of the sequence.
1385 The command \\[org-todo] cycles an entry through these states, and one
1386 additional state where no keyword is present. For details about this
1387 cycling, see the manual.
1389 TODO keywords and interpretation can also be set on a per-file basis with
1390 the special #+SEQ_TODO and #+TYP_TODO lines.
1392 For backward compatibility, this variable may also be just a list
1393 of keywords - in this case the interptetation (sequence or type) will be
1394 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1395 :group 'org-todo
1396 :group 'org-keywords
1397 :type '(choice
1398 (repeat :tag "Old syntax, just keywords"
1399 (string :tag "Keyword"))
1400 (repeat :tag "New syntax"
1401 (cons
1402 (choice
1403 :tag "Interpretation"
1404 (const :tag "Sequence (cycling hits every state)" sequence)
1405 (const :tag "Type (cycling directly to DONE)" type))
1406 (repeat
1407 (string :tag "Keyword"))))))
1409 (defvar org-todo-keywords-1 nil)
1410 (make-variable-buffer-local 'org-todo-keywords-1)
1411 (defvar org-todo-keywords-for-agenda nil)
1412 (defvar org-done-keywords-for-agenda nil)
1413 (defvar org-not-done-keywords nil)
1414 (make-variable-buffer-local 'org-not-done-keywords)
1415 (defvar org-done-keywords nil)
1416 (make-variable-buffer-local 'org-done-keywords)
1417 (defvar org-todo-heads nil)
1418 (make-variable-buffer-local 'org-todo-heads)
1419 (defvar org-todo-sets nil)
1420 (make-variable-buffer-local 'org-todo-sets)
1421 (defvar org-todo-kwd-alist nil)
1422 (make-variable-buffer-local 'org-todo-kwd-alist)
1424 (defcustom org-todo-interpretation 'sequence
1425 "Controls how TODO keywords are interpreted.
1426 This variable is in principle obsolete and is only used for
1427 backward compatibility, if the interpretation of todo keywords is
1428 not given already in `org-todo-keywords'. See that variable for
1429 more information."
1430 :group 'org-todo
1431 :group 'org-keywords
1432 :type '(choice (const sequence)
1433 (const type)))
1435 (defcustom org-after-todo-state-change-hook nil
1436 "Hook which is run after the state of a TODO item was changed.
1437 The new state (a string with a TODO keyword, or nil) is available in the
1438 Lisp variable `state'."
1439 :group 'org-todo
1440 :type 'hook)
1442 (defcustom org-log-done nil
1443 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1444 When the state of an entry is changed from nothing to TODO, remove a previous
1445 closing date.
1447 This can also be a list of symbols indicating under which conditions
1448 the time stamp recording the action should be annotated with a short note.
1449 Valid members of this list are
1451 done Offer to record a note when marking entries done
1452 state Offer to record a note whenever changing the TODO state
1453 of an item. This is only relevant if TODO keywords are
1454 interpreted as sequence, see variable `org-todo-interpretation'.
1455 When `state' is set, this includes tracking `done'.
1456 clock-out Offer to record a note when clocking out of an item.
1458 A separate window will then pop up and allow you to type a note.
1459 After finishing with C-c C-c, the note will be added directly after the
1460 timestamp, as a plain list item. See also the variable
1461 `org-log-note-headings'.
1463 Logging can also be configured on a per-file basis by adding one of
1464 the following lines anywhere in the buffer:
1466 #+STARTUP: logdone
1467 #+STARTUP: nologging
1468 #+STARTUP: lognotedone
1469 #+STARTUP: lognotestate
1470 #+STARTUP: lognoteclock-out"
1471 :group 'org-todo
1472 :group 'org-progress
1473 :type '(choice
1474 (const :tag "off" nil)
1475 (const :tag "on" t)
1476 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1477 (const :tag "when item is marked DONE" done)
1478 (const :tag "when TODO state changes" state)
1479 (const :tag "when clocking out" clock-out))))
1481 (defcustom org-log-note-headings
1482 '((done . "CLOSING NOTE %t")
1483 (state . "State %-12s %t")
1484 (clock-out . ""))
1485 "Headings for notes added when clocking out or closing TODO items.
1486 The value is an alist, with the car being a sympol indicating the note
1487 context, and the cdr is the heading to be used. The heading may also be the
1488 empty string.
1489 %t in the heading will be replaced by a time stamp.
1490 %s will be replaced by the new TODO state, in double quotes.
1491 %u will be replaced by the user name.
1492 %U will be replaced by the full user name."
1493 :group 'org-todo
1494 :group 'org-progress
1495 :type '(list :greedy t
1496 (cons (const :tag "Heading when closing an item" done) string)
1497 (cons (const :tag
1498 "Heading when changing todo state (todo sequence only)"
1499 state) string)
1500 (cons (const :tag "Heading when clocking out" clock-out) string)))
1502 (defcustom org-allow-auto-repeat t
1503 "Non-nil means, find REPEAT cookies in entries and apply them.
1504 A repeat cookie looks like REPEAT(+1m) and causes deadlines and schedules
1505 to repeat themselves shifted by a certain amount of time, each time an
1506 entry is marked DONE."
1507 :group 'org-todo
1508 :group 'org-progress
1509 :type 'boolean)
1511 (defcustom org-log-repeat t
1512 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1513 When nil, no note will be taken."
1514 :group 'org-todo
1515 :group 'org-progress
1516 :type 'boolean)
1518 (defgroup org-priorities nil
1519 "Priorities in Org-mode."
1520 :tag "Org Priorities"
1521 :group 'org-todo)
1523 (defcustom org-default-priority ?B
1524 "The default priority of TODO items.
1525 This is the priority an item get if no explicit priority is given."
1526 :group 'org-priorities
1527 :type 'character)
1529 (defcustom org-lowest-priority ?C
1530 "The lowest priority of TODO items. A character like ?A, ?B etc."
1531 :group 'org-priorities
1532 :type 'character)
1534 (defgroup org-time nil
1535 "Options concerning time stamps and deadlines in Org-mode."
1536 :tag "Org Time"
1537 :group 'org)
1539 (defcustom org-insert-labeled-timestamps-at-point nil
1540 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1541 When nil, these labeled time stamps are forces into the second line of an
1542 entry, just after the headline. When scheduling from the global TODO list,
1543 the time stamp will always be forced into the second line."
1544 :group 'org-time
1545 :type 'boolean)
1547 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1548 "Formats for `format-time-string' which are used for time stamps.
1549 It is not recommended to change this constant.")
1551 (defcustom org-time-stamp-rounding-minutes 0
1552 "Number of minutes to round time stamps to upon insertion.
1553 When zero, insert the time unmodified. Useful rounding numbers
1554 should be factors of 60, so for example 5, 10, 15.
1555 When this is not zero, you can still force an exact time-stamp by using
1556 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1557 :group 'org-time
1558 :type 'integer)
1560 (defcustom org-display-custom-times nil
1561 "Non-nil means, overlay custom formats over all time stamps.
1562 The formats are defined through the variable `org-time-stamp-custom-formats'.
1563 To turn this on on a per-file basis, insert anywhere in the file:
1564 #+STARTUP: customtime"
1565 :group 'org-time
1566 :set 'set-default
1567 :type 'sexp)
1568 (make-variable-buffer-local 'org-display-custom-times)
1570 (defcustom org-time-stamp-custom-formats
1571 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1572 "Custom formats for time stamps. See `format-time-string' for the syntax.
1573 These are overlayed over the default ISO format if the variable
1574 `org-display-custom-times' is set."
1575 :group 'org-time
1576 :type 'sexp)
1578 (defun org-time-stamp-format (&optional long inactive)
1579 "Get the right format for a time string."
1580 (let ((f (if long (cdr org-time-stamp-formats)
1581 (car org-time-stamp-formats))))
1582 (if inactive
1583 (concat "[" (substring f 1 -1) "]")
1584 f)))
1586 (defcustom org-deadline-warning-days 30
1587 "No. of days before expiration during which a deadline becomes active.
1588 This variable governs the display in sparse trees and in the agenda."
1589 :group 'org-time
1590 :type 'number)
1592 (defcustom org-popup-calendar-for-date-prompt t
1593 "Non-nil means, pop up a calendar when prompting for a date.
1594 In the calendar, the date can be selected with mouse-1. However, the
1595 minibuffer will also be active, and you can simply enter the date as well.
1596 When nil, only the minibuffer will be available."
1597 :group 'org-time
1598 :type 'boolean)
1600 (defcustom org-calendar-follow-timestamp-change t
1601 "Non-nil means, make the calendar window follow timestamp changes.
1602 When a timestamp is modified and the calendar window is visible, it will be
1603 moved to the new date."
1604 :group 'org-time
1605 :type 'boolean)
1607 (defgroup org-tags nil
1608 "Options concerning tags in Org-mode."
1609 :tag "Org Tags"
1610 :group 'org)
1612 (defcustom org-tag-alist nil
1613 "List of tags allowed in Org-mode files.
1614 When this list is nil, Org-mode will base TAG input on what is already in the
1615 buffer.
1616 The value of this variable is an alist, the car may be (and should) be a
1617 character that is used to select that tag through the fast-tag-selection
1618 interface. See the manual for details."
1619 :group 'org-tags
1620 :type '(repeat
1621 (choice
1622 (cons (string :tag "Tag name")
1623 (character :tag "Access char"))
1624 (const :tag "Start radio group" (:startgroup))
1625 (const :tag "End radio group" (:endgroup)))))
1627 (defcustom org-use-fast-tag-selection 'auto
1628 "Non-nil means, use fast tag selection scheme.
1629 This is a special interface to select and deselect tags with single keys.
1630 When nil, fast selection is never used.
1631 When the symbol `auto', fast selection is used if and only if selection
1632 characters for tags have been configured, either through the variable
1633 `org-tag-alist' or through a #+TAGS line in the buffer.
1634 When t, fast selection is always used and selection keys are assigned
1635 automatically if necessary."
1636 :group 'org-tags
1637 :type '(choice
1638 (const :tag "Always" t)
1639 (const :tag "Never" nil)
1640 (const :tag "When selection characters are configured" 'auto)))
1642 (defcustom org-fast-tag-selection-single-key nil
1643 "Non-nil means, fast tag selection exits after first change.
1644 When nil, you have to press RET to exit it.
1645 During fast tag selection, you can toggle this flag with `C-c'.
1646 This variable can also have the value `expert'. In this case, the window
1647 displaying the tags menu is not even shown, until you press C-c again."
1648 :group 'org-tags
1649 :type '(choice
1650 (const :tag "No" nil)
1651 (const :tag "Yes" t)
1652 (const :tag "Expert" expert)))
1654 (defcustom org-tags-column 48
1655 "The column to which tags should be indented in a headline.
1656 If this number is positive, it specifies the column. If it is negative,
1657 it means that the tags should be flushright to that column. For example,
1658 -79 works well for a normal 80 character screen."
1659 :group 'org-tags
1660 :type 'integer)
1662 (defcustom org-auto-align-tags t
1663 "Non-nil means, realign tags after pro/demotion of TODO state change.
1664 These operations change the length of a headline and therefore shift
1665 the tags around. With this options turned on, after each such operation
1666 the tags are again aligned to `org-tags-column'."
1667 :group 'org-tags
1668 :type 'boolean)
1670 (defcustom org-use-tag-inheritance t
1671 "Non-nil means, tags in levels apply also for sublevels.
1672 When nil, only the tags directly given in a specific line apply there.
1673 If you turn off this option, you very likely want to turn on the
1674 companion option `org-tags-match-list-sublevels'."
1675 :group 'org-tags
1676 :type 'boolean)
1678 (defcustom org-tags-match-list-sublevels nil
1679 "Non-nil means list also sublevels of headlines matching tag search.
1680 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1681 the sublevels of a headline matching a tag search often also match
1682 the same search. Listing all of them can create very long lists.
1683 Setting this variable to nil causes subtrees of a match to be skipped.
1684 This option is off by default, because inheritance in on. If you turn
1685 inheritance off, you very likely want to turn this option on.
1687 As a special case, if the tag search is restricted to TODO items, the
1688 value of this variable is ignored and sublevels are always checked, to
1689 make sure all corresponding TODO items find their way into the list."
1690 :group 'org-tags
1691 :type 'boolean)
1693 (defvar org-tags-history nil
1694 "History of minibuffer reads for tags.")
1695 (defvar org-last-tags-completion-table nil
1696 "The last used completion table for tags.")
1698 (defgroup org-agenda nil
1699 "Options concerning agenda views in Org-mode."
1700 :tag "Org Agenda"
1701 :group 'org)
1703 (defvar org-category nil
1704 "Variable used by org files to set a category for agenda display.
1705 Such files should use a file variable to set it, for example
1707 # -*- mode: org; org-category: \"ELisp\"
1709 or contain a special line
1711 #+CATEGORY: ELisp
1713 If the file does not specify a category, then file's base name
1714 is used instead.")
1715 (make-variable-buffer-local 'org-category)
1717 (defcustom org-agenda-files nil
1718 "The files to be used for agenda display.
1719 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1720 \\[org-remove-file]. You can also use customize to edit the list.
1722 If the value of the variable is not a list but a single file name, then
1723 the list of agenda files is actually stored and maintained in that file, one
1724 agenda file per line."
1725 :group 'org-agenda
1726 :type '(choice
1727 (repeat :tag "List of files" file)
1728 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1731 (defcustom org-agenda-confirm-kill 1
1732 "When set, remote killing from the agenda buffer needs confirmation.
1733 When t, a confirmation is always needed. When a number N, confirmation is
1734 only needed when the text to be killed contains more than N non-white lines."
1735 :group 'org-agenda
1736 :type '(choice
1737 (const :tag "Never" nil)
1738 (const :tag "Always" t)
1739 (number :tag "When more than N lines")))
1741 (defcustom org-calendar-to-agenda-key [?c]
1742 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1743 The command `org-calendar-goto-agenda' will be bound to this key. The
1744 default is the character `c' because then `c' can be used to switch back and
1745 forth between agenda and calendar."
1746 :group 'org-agenda
1747 :type 'sexp)
1749 (defgroup org-agenda-custom-commands nil
1750 "Options concerning agenda views in Org-mode."
1751 :tag "Org Agenda Custom Commands"
1752 :group 'org-agenda)
1754 (defcustom org-agenda-custom-commands nil
1755 "Custom commands for the agenda.
1756 These commands will be offered on the splash screen displayed by the
1757 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1759 (key type match options)
1761 key The key (a single char as a string) to be associated with the command.
1762 type The command type, any of the following symbols:
1763 todo Entries with a specific TODO keyword, in all agenda files.
1764 tags Tags match in all agenda files.
1765 tags-todo Tags match in all agenda files, TODO entries only.
1766 todo-tree Sparse tree of specific TODO keyword in *current* file.
1767 tags-tree Sparse tree with all tags matches in *current* file.
1768 occur-tree Occur sparse tree for *current* file.
1769 match What to search for:
1770 - a single keyword for TODO keyword searches
1771 - a tags match expression for tags searches
1772 - a regular expression for occur searches
1773 options A list of option setttings, similar to that in a let form, so like
1774 this: ((opt1 val1) (opt2 val2) ...)
1776 You can also define a set of commands, to create a composite agenda buffer.
1777 In this case, an entry looks like this:
1779 (key desc (cmd1 cmd2 ...) general-options)
1781 where
1783 desc A description string to be displayed in the dispatcher menu.
1784 cmd An agenda command, similar to the above. However, tree commands
1785 are no allowed, but instead you can get agenda and global todo list.
1786 So valid commands for a set are:
1787 (agenda)
1788 (alltodo)
1789 (stuck)
1790 (todo \"match\" options)
1791 (tags \"match\" options )
1792 (tags-todo \"match\" options)
1794 Each command can carry a list of options, and another set of options can be
1795 given for the whole set of commands. Individual command options take
1796 precedence over the general options."
1797 :group 'org-agenda-custom-commands
1798 :type '(repeat
1799 (choice
1800 (list :tag "Single command"
1801 (string :tag "Key")
1802 (choice
1803 (const :tag "Tags search (all agenda files)" tags)
1804 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1805 (const :tag "TODO keyword search (all agenda files)" todo)
1806 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1807 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1808 (const :tag "Occur tree (current buffer)" occur-tree)
1809 (symbol :tag "Other, user-defined function"))
1810 (string :tag "Match")
1811 (repeat :tag "Local options"
1812 (list (variable :tag "Option") (sexp :tag "Value"))))
1813 (list :tag "Command series, all agenda files"
1814 (string :tag "Key")
1815 (string :tag "Description")
1816 (repeat
1817 (choice
1818 (const :tag "Agenda" (agenda))
1819 (const :tag "TODO list" (alltodo))
1820 (const :tag "Stuck projects" (stuck))
1821 (list :tag "Tags search"
1822 (const :format "" tags)
1823 (string :tag "Match")
1824 (repeat :tag "Local options"
1825 (list (variable :tag "Option")
1826 (sexp :tag "Value"))))
1828 (list :tag "Tags search, TODO entries only"
1829 (const :format "" tags-todo)
1830 (string :tag "Match")
1831 (repeat :tag "Local options"
1832 (list (variable :tag "Option")
1833 (sexp :tag "Value"))))
1835 (list :tag "TODO keyword search"
1836 (const :format "" todo)
1837 (string :tag "Match")
1838 (repeat :tag "Local options"
1839 (list (variable :tag "Option")
1840 (sexp :tag "Value"))))
1842 (list :tag "Other, user-defined function"
1843 (symbol :tag "function")
1844 (string :tag "Match")
1845 (repeat :tag "Local options"
1846 (list (variable :tag "Option")
1847 (sexp :tag "Value"))))))
1849 (repeat :tag "General options"
1850 (list (variable :tag "Option")
1851 (sexp :tag "Value")))))))
1853 (defcustom org-stuck-projects
1854 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
1855 "How to identify stuck projects.
1856 This is a list of four items:
1857 1. A tags/todo matcher string that is used to identify a project.
1858 The entire tree below a headline matched by this is considered one project.
1859 2. A list of TODO keywords identifying non-stuck projects.
1860 If the project subtree contains any headline with one of these todo
1861 keywords, the project is considered to be not stuck. If you specify
1862 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
1863 3. A list of tags identifying non-stuck projects.
1864 If the project subtree contains any headline with one of these tags,
1865 the project is considered to be not stuck. If you specify \"*\" as
1866 a tag, any tag will mark the project unstuck.
1867 4. An arbitrary regular expression matching non-stuck projects.
1869 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
1870 or `C-c a #' to produce the list."
1871 :group 'org-agenda-custom-commands
1872 :type '(list
1873 (string :tag "Tags/TODO match to identify a project")
1874 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
1875 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
1876 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
1879 (defgroup org-agenda-skip nil
1880 "Options concerning skipping parts of agenda files."
1881 :tag "Org Agenda Skip"
1882 :group 'org-agenda)
1884 (defcustom org-agenda-todo-list-sublevels t
1885 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1886 When nil, the sublevels of a TODO entry are not checked, resulting in
1887 potentially much shorter TODO lists."
1888 :group 'org-agenda-skip
1889 :group 'org-todo
1890 :type 'boolean)
1892 (defcustom org-agenda-todo-ignore-scheduled nil
1893 "Non-nil means, don't show scheduled entries in the global todo list.
1894 The idea behind this is that by scheduling it, you have already taken care
1895 of this item."
1896 :group 'org-agenda-skip
1897 :group 'org-todo
1898 :type 'boolean)
1900 (defcustom org-agenda-todo-ignore-deadlines nil
1901 "Non-nil means, don't show near deadline entries in the global todo list.
1902 Near means closer than `org-deadline-warning-days' days.
1903 The idea behind this is that such items will appear in the agenda anyway."
1904 :group 'org-agenda-skip
1905 :group 'org-todo
1906 :type 'boolean)
1908 (defcustom org-agenda-skip-scheduled-if-done nil
1909 "Non-nil means don't show scheduled items in agenda when they are done.
1910 This is relevant for the daily/weekly agenda, not for the TODO list."
1911 :group 'org-agenda-skip
1912 :type 'boolean)
1914 (defcustom org-timeline-show-empty-dates 3
1915 "Non-nil means, `org-timeline' also shows dates without an entry.
1916 When nil, only the days which actually have entries are shown.
1917 When t, all days between the first and the last date are shown.
1918 When an integer, show also empty dates, but if there is a gap of more than
1919 N days, just insert a special line indicating the size of the gap."
1920 :group 'org-agenda-skip
1921 :type '(choice
1922 (const :tag "None" nil)
1923 (const :tag "All" t)
1924 (number :tag "at most")))
1927 (defgroup org-agenda-startup nil
1928 "Options concerning initial settings in the Agenda in Org Mode."
1929 :tag "Org Agenda Startup"
1930 :group 'org-agenda)
1932 (defcustom org-finalize-agenda-hook nil
1933 "Hook run just before displaying an agenda buffer."
1934 :group 'org-agenda-startup
1935 :type 'hook)
1937 (defcustom org-agenda-mouse-1-follows-link nil
1938 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1939 A longer mouse click will still set point. Does not wortk on XEmacs.
1940 Needs to be set before org.el is loaded."
1941 :group 'org-agenda-startup
1942 :type 'boolean)
1944 (defcustom org-agenda-start-with-follow-mode nil
1945 "The initial value of follwo-mode in a newly created agenda window."
1946 :group 'org-agenda-startup
1947 :type 'boolean)
1949 (defgroup org-agenda-windows nil
1950 "Options concerning the windows used by the Agenda in Org Mode."
1951 :tag "Org Agenda Windows"
1952 :group 'org-agenda)
1954 (defcustom org-agenda-window-setup 'reorganize-frame
1955 "How the agenda buffer should be displayed.
1956 Possible values for this option are:
1958 current-window Show agenda in the current window, keeping all other windows.
1959 other-frame Use `switch-to-buffer-other-frame' to display agenda.
1960 other-window Use `switch-to-buffer-other-window' to display agenda.
1961 reorganize-frame Show only two windows on the current frame, the current
1962 window and the agenda.
1963 See also the variable `org-agenda-restore-windows-after-quit'."
1964 :group 'org-agenda-windows
1965 :type '(choice
1966 (const current-window)
1967 (const other-frame)
1968 (const other-window)
1969 (const reorganize-frame)))
1971 (defcustom org-agenda-restore-windows-after-quit nil
1972 "Non-nil means, restore window configuration open exiting agenda.
1973 Before the window configuration is changed for displaying the agenda,
1974 the current status is recorded. When the agenda is exited with
1975 `q' or `x' and this option is set, the old state is restored. If
1976 `org-agenda-window-setup' is `other-frame', the value of this
1977 option will be ignored.."
1978 :group 'org-agenda-windows
1979 :type 'boolean)
1981 (defcustom org-indirect-buffer-display 'other-window
1982 "How should indirect tree buffers be displayed?
1983 This applies to indirect buffers created with the commands
1984 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1985 Valid values are:
1986 current-window Display in the current window
1987 other-window Just display in another window.
1988 dedicated-frame Create one new frame, and re-use it each time.
1989 new-frame Make a new frame each time."
1990 :group 'org-structure
1991 :group 'org-agenda-windows
1992 :type '(choice
1993 (const :tag "In current window" current-window)
1994 (const :tag "In current frame, other window" other-window)
1995 (const :tag "Each time a new frame" new-frame)
1996 (const :tag "One dedicated frame" dedicated-frame)))
1998 (defgroup org-agenda-daily/weekly nil
1999 "Options concerning the daily/weekly agenda."
2000 :tag "Org Agenda Daily/Weekly"
2001 :group 'org-agenda)
2003 (defcustom org-agenda-ndays 7
2004 "Number of days to include in overview display.
2005 Should be 1 or 7."
2006 :group 'org-agenda-daily/weekly
2007 :type 'number)
2009 (defcustom org-agenda-start-on-weekday 1
2010 "Non-nil means, start the overview always on the specified weekday.
2011 0 denotes Sunday, 1 denotes Monday etc.
2012 When nil, always start on the current day."
2013 :group 'org-agenda-daily/weekly
2014 :type '(choice (const :tag "Today" nil)
2015 (number :tag "Weekday No.")))
2017 (defcustom org-agenda-show-all-dates t
2018 "Non-nil means, `org-agenda' shows every day in the selected range.
2019 When nil, only the days which actually have entries are shown."
2020 :group 'org-agenda-daily/weekly
2021 :type 'boolean)
2023 (defcustom org-agenda-date-format "%A %d %B %Y"
2024 "Format string for displaying dates in the agenda.
2025 Used by the daily/weekly agenda and by the timeline. This should be
2026 a format string understood by `format-time-string'.
2027 FIXME: Not used currently, because of timezone problem."
2028 :group 'org-agenda-daily/weekly
2029 :type 'string)
2031 (defcustom org-agenda-include-diary nil
2032 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2033 :group 'org-agenda-daily/weekly
2034 :type 'boolean)
2036 (defcustom org-agenda-include-all-todo nil
2037 "Set means weekly/daily agenda will always contain all TODO entries.
2038 The TODO entries will be listed at the top of the agenda, before
2039 the entries for specific days."
2040 :group 'org-agenda-daily/weekly
2041 :type 'boolean)
2043 (defgroup org-agenda-time-grid nil
2044 "Options concerning the time grid in the Org-mode Agenda."
2045 :tag "Org Agenda Time Grid"
2046 :group 'org-agenda)
2048 (defcustom org-agenda-use-time-grid t
2049 "Non-nil means, show a time grid in the agenda schedule.
2050 A time grid is a set of lines for specific times (like every two hours between
2051 8:00 and 20:00). The items scheduled for a day at specific times are
2052 sorted in between these lines.
2053 For details about when the grid will be shown, and what it will look like, see
2054 the variable `org-agenda-time-grid'."
2055 :group 'org-agenda-time-grid
2056 :type 'boolean)
2058 (defcustom org-agenda-time-grid
2059 '((daily today require-timed)
2060 "----------------"
2061 (800 1000 1200 1400 1600 1800 2000))
2063 "The settings for time grid for agenda display.
2064 This is a list of three items. The first item is again a list. It contains
2065 symbols specifying conditions when the grid should be displayed:
2067 daily if the agenda shows a single day
2068 weekly if the agenda shows an entire week
2069 today show grid on current date, independent of daily/weekly display
2070 require-timed show grid only if at least one item has a time specification
2072 The second item is a string which will be places behing the grid time.
2074 The third item is a list of integers, indicating the times that should have
2075 a grid line."
2076 :group 'org-agenda-time-grid
2077 :type
2078 '(list
2079 (set :greedy t :tag "Grid Display Options"
2080 (const :tag "Show grid in single day agenda display" daily)
2081 (const :tag "Show grid in weekly agenda display" weekly)
2082 (const :tag "Always show grid for today" today)
2083 (const :tag "Show grid only if any timed entries are present"
2084 require-timed)
2085 (const :tag "Skip grid times already present in an entry"
2086 remove-match))
2087 (string :tag "Grid String")
2088 (repeat :tag "Grid Times" (integer :tag "Time"))))
2090 (defgroup org-agenda-sorting nil
2091 "Options concerning sorting in the Org-mode Agenda."
2092 :tag "Org Agenda Sorting"
2093 :group 'org-agenda)
2095 (let ((sorting-choice
2096 '(choice
2097 (const time-up) (const time-down)
2098 (const category-keep) (const category-up) (const category-down)
2099 (const tag-down) (const tag-up)
2100 (const priority-up) (const priority-down))))
2102 (defcustom org-agenda-sorting-strategy
2103 '((agenda time-up category-keep priority-down)
2104 (todo category-keep priority-down)
2105 (tags category-keep priority-down))
2106 "Sorting structure for the agenda items of a single day.
2107 This is a list of symbols which will be used in sequence to determine
2108 if an entry should be listed before another entry. The following
2109 symbols are recognized:
2111 time-up Put entries with time-of-day indications first, early first
2112 time-down Put entries with time-of-day indications first, late first
2113 category-keep Keep the default order of categories, corresponding to the
2114 sequence in `org-agenda-files'.
2115 category-up Sort alphabetically by category, A-Z.
2116 category-down Sort alphabetically by category, Z-A.
2117 tag-up Sort alphabetically by last tag, A-Z.
2118 tag-down Sort alphabetically by last tag, Z-A.
2119 priority-up Sort numerically by priority, high priority last.
2120 priority-down Sort numerically by priority, high priority first.
2122 The different possibilities will be tried in sequence, and testing stops
2123 if one comparison returns a \"not-equal\". For example, the default
2124 '(time-up category-keep priority-down)
2125 means: Pull out all entries having a specified time of day and sort them,
2126 in order to make a time schedule for the current day the first thing in the
2127 agenda listing for the day. Of the entries without a time indication, keep
2128 the grouped in categories, don't sort the categories, but keep them in
2129 the sequence given in `org-agenda-files'. Within each category sort by
2130 priority.
2132 Leaving out `category-keep' would mean that items will be sorted across
2133 categories by priority."
2134 :group 'org-agenda-sorting
2135 :type `(choice
2136 (repeat :tag "General" ,sorting-choice)
2137 (list :tag "Individually"
2138 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2139 (repeat ,sorting-choice))
2140 (cons (const :tag "Strategy for TODO lists" todo)
2141 (repeat ,sorting-choice))
2142 (cons (const :tag "Strategy for Tags matches" tags)
2143 (repeat ,sorting-choice))))))
2145 (defcustom org-sort-agenda-notime-is-late t
2146 "Non-nil means, items without time are considered late.
2147 This is only relevant for sorting. When t, items which have no explicit
2148 time like 15:30 will be considered as 99:01, i.e. later than any items which
2149 do have a time. When nil, the default time is before 0:00. You can use this
2150 option to decide if the schedule for today should come before or after timeless
2151 agenda entries."
2152 :group 'org-agenda-sorting
2153 :type 'boolean)
2155 (defgroup org-agenda-prefix nil
2156 "Options concerning the entry prefix in the Org-mode agenda display."
2157 :tag "Org Agenda Prefix"
2158 :group 'org-agenda)
2160 (defcustom org-agenda-prefix-format
2161 '((agenda . " %-12:c%?-12t% s")
2162 (timeline . " % s")
2163 (todo . " %-12:c")
2164 (tags . " %-12:c"))
2165 "Format specifications for the prefix of items in the agenda views.
2166 An alist with four entries, for the different agenda types. The keys to the
2167 sublists are `agenda', `timeline', `todo', and `tags'. The values
2168 are format strings.
2169 This format works similar to a printf format, with the following meaning:
2171 %c the category of the item, \"Diary\" for entries from the diary, or
2172 as given by the CATEGORY keyword or derived from the file name.
2173 %T the *last* tag of the item. Last because inherited tags come
2174 first in the list.
2175 %t the time-of-day specification if one applies to the entry, in the
2176 format HH:MM
2177 %s Scheduling/Deadline information, a short string
2179 All specifiers work basically like the standard `%s' of printf, but may
2180 contain two additional characters: A question mark just after the `%' and
2181 a whitespace/punctuation character just before the final letter.
2183 If the first character after `%' is a question mark, the entire field
2184 will only be included if the corresponding value applies to the
2185 current entry. This is useful for fields which should have fixed
2186 width when present, but zero width when absent. For example,
2187 \"%?-12t\" will result in a 12 character time field if a time of the
2188 day is specified, but will completely disappear in entries which do
2189 not contain a time.
2191 If there is punctuation or whitespace character just before the final
2192 format letter, this character will be appended to the field value if
2193 the value is not empty. For example, the format \"%-12:c\" leads to
2194 \"Diary: \" if the category is \"Diary\". If the category were be
2195 empty, no additional colon would be interted.
2197 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2198 - Indent the line with two space characters
2199 - Give the category in a 12 chars wide field, padded with whitespace on
2200 the right (because of `-'). Append a colon if there is a category
2201 (because of `:').
2202 - If there is a time-of-day, put it into a 12 chars wide field. If no
2203 time, don't put in an empty field, just skip it (because of '?').
2204 - Finally, put the scheduling information and append a whitespace.
2206 As another example, if you don't want the time-of-day of entries in
2207 the prefix, you could use:
2209 (setq org-agenda-prefix-format \" %-11:c% s\")
2211 See also the variables `org-agenda-remove-times-when-in-prefix' and
2212 `org-agenda-remove-tags-when-in-prefix'."
2213 :type '(choice
2214 (string :tag "General format")
2215 (list :greedy t :tag "View dependent"
2216 (cons (const agenda) (string :tag "Format"))
2217 (cons (const timeline) (string :tag "Format"))
2218 (cons (const todo) (string :tag "Format"))
2219 (cons (const tags) (string :tag "Format"))))
2220 :group 'org-agenda-prefix)
2222 (defvar org-prefix-format-compiled nil
2223 "The compiled version of the most recently used prefix format.
2224 See the variable `org-agenda-prefix-format'.")
2226 (defcustom org-agenda-remove-times-when-in-prefix t
2227 "Non-nil means, remove duplicate time specifications in agenda items.
2228 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2229 time-of-day specification in a headline or diary entry is extracted and
2230 placed into the prefix. If this option is non-nil, the original specification
2231 \(a timestamp or -range, or just a plain time(range) specification like
2232 11:30-4pm) will be removed for agenda display. This makes the agenda less
2233 cluttered.
2234 The option can be t or nil. It may also be the symbol `beg', indicating
2235 that the time should only be removed what it is located at the beginning of
2236 the headline/diary entry."
2237 :group 'org-agenda-prefix
2238 :type '(choice
2239 (const :tag "Always" t)
2240 (const :tag "Never" nil)
2241 (const :tag "When at beginning of entry" beg)))
2243 (defcustom org-agenda-remove-tags-when-in-prefix nil
2244 "Non-nil means, remove the tags from the headline copy in the agenda.
2245 When this is the symbol `prefix', only remove tags when
2246 `org-agenda-prefix-format' contains a `%T' specifier."
2247 :group 'org-agenda-prefix
2248 :type '(choice
2249 (const :tag "Always" t)
2250 (const :tag "Never" nil)
2251 (const :tag "When prefix format contains %T" prefix)))
2253 (defcustom org-agenda-align-tags-to-column 65
2254 "Shift tags in agenda items to this column."
2255 :group 'org-agenda-prefix
2256 :type 'integer)
2258 (defgroup org-latex nil
2259 "Options for embedding LaTeX code into Org-mode"
2260 :tag "Org LaTeX"
2261 :group 'org)
2263 (defcustom org-format-latex-options
2264 '(:foreground default :background default :scale 1.0
2265 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2266 :matchers ("begin" "$" "$$" "\\(" "\\["))
2267 "Options for creating images from LaTeX fragments.
2268 This is a property list with the following properties:
2269 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2270 `default' means use the forground of the default face.
2271 :background the background color, or \"Transparent\".
2272 `default' means use the background of the default face.
2273 :scale a scaling factor for the size of the images
2274 :html-foreground, :html-background, :html-scale
2275 The same numbers for HTML export.
2276 :matchers a list indicating which matchers should be used to
2277 find LaTeX fragments. Valid members of this list are:
2278 \"begin\" find environments
2279 \"$\" find math expressions surrounded by $...$
2280 \"$$\" find math expressions surrounded by $$....$$
2281 \"\\(\" find math expressions surrounded by \\(...\\)
2282 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2283 :group 'org-latex
2284 :type 'plist)
2286 (defcustom org-format-latex-header "\\documentclass{article}
2287 \\usepackage{fullpage} % do not remove
2288 \\usepackage{amssymb}
2289 \\usepackage[usenames]{color}
2290 \\usepackage{amsmath}
2291 \\usepackage{latexsym}
2292 \\usepackage[mathscr]{eucal}
2293 \\pagestyle{empty} % do not remove"
2294 "The document header used for processing LaTeX fragments."
2295 :group 'org-latex
2296 :type 'string)
2298 (defgroup org-export nil
2299 "Options for exporting org-listings."
2300 :tag "Org Export"
2301 :group 'org)
2303 (defgroup org-export-general nil
2304 "General options for exporting Org-mode files."
2305 :tag "Org Export General"
2306 :group 'org-export)
2308 (defcustom org-export-publishing-directory "."
2309 "Path to the location where exported files should be located.
2310 This path may be relative to the directory where the Org-mode file lives.
2311 The default is to put them into the same directory as the Org-mode file.
2312 The variable may also be an alist with export types `:html', `:ascii',
2313 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2314 is relative, it is interpreted relative to the directory where the exported
2315 Org-mode files lives."
2316 :group 'org-export-general
2317 :type '(choice
2318 (directory)
2319 (repeat
2320 (cons
2321 (choice :tag "Type"
2322 (const :html) (const :ascii) (const :ical) (const :xoxo))
2323 (directory)))))
2325 (defcustom org-export-language-setup
2326 '(("en" "Author" "Date" "Table of Contents")
2327 ("cs" "Autor" "Datum" "Obsah")
2328 ("da" "Ophavsmand" "Dato" "Indhold")
2329 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2330 ("es" "Autor" "Fecha" "\xccndice")
2331 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2332 ("it" "Autore" "Data" "Indice")
2333 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2334 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2335 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2336 "Terms used in export text, translated to different languages.
2337 Use the variable `org-export-default-language' to set the language,
2338 or use the +OPTION lines for a per-file setting."
2339 :group 'org-export-general
2340 :type '(repeat
2341 (list
2342 (string :tag "HTML language tag")
2343 (string :tag "Author")
2344 (string :tag "Date")
2345 (string :tag "Table of Contents"))))
2347 (defcustom org-export-default-language "en"
2348 "The default language of HTML export, as a string.
2349 This should have an association in `org-export-language-setup'."
2350 :group 'org-export-general
2351 :type 'string)
2353 (defcustom org-export-skip-text-before-1st-heading t
2354 "Non-nil means, skip all text before the first headline when exporting.
2355 When nil, that text is exported as well."
2356 :group 'org-export-general
2357 :type 'boolean)
2359 (defcustom org-export-headline-levels 3
2360 "The last level which is still exported as a headline.
2361 Inferior levels will produce itemize lists when exported.
2362 Note that a numeric prefix argument to an exporter function overrides
2363 this setting.
2365 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2366 :group 'org-export-general
2367 :type 'number)
2369 (defcustom org-export-with-section-numbers t
2370 "Non-nil means, add section numbers to headlines when exporting.
2372 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2373 :group 'org-export-general
2374 :type 'boolean)
2376 (defcustom org-export-with-toc t
2377 "Non-nil means, create a table of contents in exported files.
2378 The TOC contains headlines with levels up to`org-export-headline-levels'.
2379 When an integer, include levels up to N in the toc, this may then be
2380 different from `org-export-headline-levels', but it will not be allowed
2381 to be larger than the number of headline levels.
2382 When nil, no table of contents is made.
2384 Headlines which contain any TODO items will be marked with \"(*)\" in
2385 ASCII export, and with red color in HTML output, if the option
2386 `org-export-mark-todo-in-toc' is set.
2388 In HTML output, the TOC will be clickable.
2390 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2391 or \"toc:3\"."
2392 :group 'org-export-general
2393 :type '(choice
2394 (const :tag "No Table of Contents" nil)
2395 (const :tag "Full Table of Contents" t)
2396 (integer :tag "TOC to level")))
2398 (defcustom org-export-mark-todo-in-toc nil
2399 "Non-nil means, mark TOC lines that contain any open TODO items."
2400 :group 'org-export-general
2401 :type 'boolean)
2403 (defcustom org-export-preserve-breaks nil
2404 "Non-nil means, preserve all line breaks when exporting.
2405 Normally, in HTML output paragraphs will be reformatted. In ASCII
2406 export, line breaks will always be preserved, regardless of this variable.
2408 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2409 :group 'org-export-general
2410 :type 'boolean)
2412 (defcustom org-export-with-archived-trees 'headline
2413 "Whether subtrees with the ARCHIVE tag should be exported.
2414 This can have three different values
2415 nil Do not export, pretend this tree is not present
2416 t Do export the entire tree
2417 headline Only export the headline, but skip the tree below it."
2418 :group 'org-export-general
2419 :group 'org-archive
2420 :type '(choice
2421 (const :tag "not at all" nil)
2422 (const :tag "headline only" 'headline)
2423 (const :tag "entirely" t)))
2425 (defcustom org-export-with-timestamps t
2426 "If nil, do not export time stamps and associated keywords."
2427 :group 'org-export-general
2428 :type 'boolean)
2430 (defcustom org-export-remove-timestamps-from-toc t
2431 "If nil, remove timestamps from the table of contents entries."
2432 :group 'org-export-general
2433 :type 'boolean)
2435 (defcustom org-export-with-tags 'not-in-toc
2436 "If nil, do not export tags, just remove them from headlines.
2437 If this is the symbol `not-in-toc', tags will be removed from table of
2438 contents entries, but still be shown in the headlines of the document."
2439 :group 'org-export-general
2440 :type '(choice
2441 (const :tag "Off" nil)
2442 (const :tag "Not in TOC" not-in-toc)
2443 (const :tag "On" t)))
2445 (defgroup org-export-translation nil
2446 "Options for translating special ascii sequences for the export backends."
2447 :tag "Org Export Translation"
2448 :group 'org-export)
2450 (defcustom org-export-with-emphasize t
2451 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2452 If the export target supports emphasizing text, the word will be
2453 typeset in bold, italic, or underlined, respectively. Works only for
2454 single words, but you can say: I *really* *mean* *this*.
2455 Not all export backends support this.
2457 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2458 :group 'org-export-translation
2459 :type 'boolean)
2461 (defcustom org-export-with-sub-superscripts t
2462 "Non-nil means, interpret \"_\" and \"^\" for export.
2463 When this option is turned on, you can use TeX-like syntax for sub- and
2464 superscripts. Several characters after \"_\" or \"^\" will be
2465 considered as a single item - so grouping with {} is normally not
2466 needed. For example, the following things will be parsed as single
2467 sub- or superscripts.
2469 10^24 or 10^tau several digits will be considered 1 item.
2470 10^-12 or 10^-tau a leading sign with digits or a word
2471 x^2-y^3 will be read as x^2 - y^3, because items are
2472 terminated by almost any nonword/nondigit char.
2473 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2475 Still, ambiguity is possible - so when in doubt use {} to enclose the
2476 sub/superscript. If you set this variable to the symbol `{}',
2477 the braces are *required* in order to trigger interpretations as
2478 sub/superscript. This can be helpful in documents that need \"_\"
2479 frequently in plain text.
2481 Not all export backends support this, but HTML does.
2483 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2484 :group 'org-export-translation
2485 :type '(choice
2486 (const :tag "Always interpret" t)
2487 (const :tag "Only with braces" {})
2488 (const :tag "Never interpret" nil)))
2490 (defcustom org-export-with-TeX-macros t
2491 "Non-nil means, interpret simple TeX-like macros when exporting.
2492 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2493 No only real TeX macros will work here, but the standard HTML entities
2494 for math can be used as macro names as well. For a list of supported
2495 names in HTML export, see the constant `org-html-entities'.
2496 Not all export backends support this.
2498 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2499 :group 'org-export-translation
2500 :group 'org-latex
2501 :type 'boolean)
2503 (defcustom org-export-with-LaTeX-fragments nil
2504 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2505 When set, the exporter will find LaTeX environments if the \\begin line is
2506 the first non-white thing on a line. It will also find the math delimiters
2507 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2508 display math.
2510 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2511 :group 'org-export-translation
2512 :group 'org-latex
2513 :type 'boolean)
2515 (defcustom org-export-with-fixed-width t
2516 "Non-nil means, lines starting with \":\" will be in fixed width font.
2517 This can be used to have pre-formatted text, fragments of code etc. For
2518 example:
2519 : ;; Some Lisp examples
2520 : (while (defc cnt)
2521 : (ding))
2522 will be looking just like this in also HTML. See also the QUOTE keyword.
2523 Not all export backends support this.
2525 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2526 :group 'org-export-translation
2527 :type 'boolean)
2529 (defcustom org-match-sexp-depth 3
2530 "Number of stacked braces for sub/superscript matching.
2531 This has to be set before loading org.el to be effective."
2532 :group 'org-export-translation
2533 :type 'integer)
2535 (defgroup org-export-tables nil
2536 "Options for exporting tables in Org-mode."
2537 :tag "Org Export Tables"
2538 :group 'org-export)
2540 (defcustom org-export-with-tables t
2541 "If non-nil, lines starting with \"|\" define a table.
2542 For example:
2544 | Name | Address | Birthday |
2545 |-------------+----------+-----------|
2546 | Arthur Dent | England | 29.2.2100 |
2548 Not all export backends support this.
2550 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2551 :group 'org-export-tables
2552 :type 'boolean)
2554 (defcustom org-export-highlight-first-table-line t
2555 "Non-nil means, highlight the first table line.
2556 In HTML export, this means use <th> instead of <td>.
2557 In tables created with table.el, this applies to the first table line.
2558 In Org-mode tables, all lines before the first horizontal separator
2559 line will be formatted with <th> tags."
2560 :group 'org-export-tables
2561 :type 'boolean)
2563 (defcustom org-export-table-remove-special-lines t
2564 "Remove special lines and marking characters in calculating tables.
2565 This removes the special marking character column from tables that are set
2566 up for spreadsheet calculations. It also removes the entire lines
2567 marked with `!', `_', or `^'. The lines with `$' are kept, because
2568 the values of constants may be useful to have."
2569 :group 'org-export-tables
2570 :type 'boolean)
2572 (defcustom org-export-prefer-native-exporter-for-tables nil
2573 "Non-nil means, always export tables created with table.el natively.
2574 Natively means, use the HTML code generator in table.el.
2575 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2576 the table does not use row- or column-spanning). This has the
2577 advantage, that the automatic HTML conversions for math symbols and
2578 sub/superscripts can be applied. Org-mode's HTML generator is also
2579 much faster."
2580 :group 'org-export-tables
2581 :type 'boolean)
2583 (defgroup org-export-ascii nil
2584 "Options specific for ASCII export of Org-mode files."
2585 :tag "Org Export ASCII"
2586 :group 'org-export)
2588 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2589 "Characters for underlining headings in ASCII export.
2590 In the given sequence, these characters will be used for level 1, 2, ..."
2591 :group 'org-export-ascii
2592 :type '(repeat character))
2594 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2595 "Bullet characters for headlines converted to lists in ASCII export.
2596 The first character is is used for the first lest level generated in this
2597 way, and so on. If there are more levels than characters given here,
2598 the list will be repeated.
2599 Note that plain lists will keep the same bullets as the have in the
2600 Org-mode file."
2601 :group 'org-export-ascii
2602 :type '(repeat character))
2604 (defgroup org-export-xml nil
2605 "Options specific for XML export of Org-mode files."
2606 :tag "Org Export XML"
2607 :group 'org-export)
2609 (defgroup org-export-html nil
2610 "Options specific for HTML export of Org-mode files."
2611 :tag "Org Export HTML"
2612 :group 'org-export)
2614 (defcustom org-export-html-style
2615 "<style type=\"text/css\">
2616 html {
2617 font-family: Times, serif;
2618 font-size: 12pt;
2620 .title { text-align: center; }
2621 .todo { color: red; }
2622 .done { color: green; }
2623 .timestamp { color: grey }
2624 .timestamp-kwd { color: CadetBlue }
2625 .tag { background-color:lightblue; font-weight:normal }
2626 .target { background-color: lavender; }
2627 pre {
2628 border: 1pt solid #AEBDCC;
2629 background-color: #F3F5F7;
2630 padding: 5pt;
2631 font-family: courier, monospace;
2633 table { border-collapse: collapse; }
2634 td, th {
2635 vertical-align: top;
2636 <!--border: 1pt solid #ADB9CC;-->
2638 </style>"
2639 "The default style specification for exported HTML files.
2640 Since there are different ways of setting style information, this variable
2641 needs to contain the full HTML structure to provide a style, including the
2642 surrounding HTML tags. The style specifications should include definitions
2643 for new classes todo, done, title, and deadline. For example, legal values
2644 would be:
2646 <style type=\"text/css\">
2647 p { font-weight: normal; color: gray; }
2648 h1 { color: black; }
2649 .title { text-align: center; }
2650 .todo, .deadline { color: red; }
2651 .done { color: green; }
2652 </style>
2654 or, if you want to keep the style in a file,
2656 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2658 As the value of this option simply gets inserted into the HTML <head> header,
2659 you can \"misuse\" it to add arbitrary text to the header."
2660 :group 'org-export-html
2661 :type 'string)
2663 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2664 "Format for typesetting the document title in HTML export."
2665 :group 'org-export-html
2666 :type 'string)
2668 (defcustom org-export-html-toplevel-hlevel 2
2669 "The <H> level for level 1 headings in HTML export."
2670 :group 'org-export-html
2671 :type 'string)
2673 (defcustom org-export-html-link-org-files-as-html t
2674 "Non-nil means, make file links to `file.org' point to `file.html'.
2675 When org-mode is exporting an org-mode file to HTML, links to
2676 non-html files are directly put into a href tag in HTML.
2677 However, links to other Org-mode files (recognized by the
2678 extension `.org.) should become links to the corresponding html
2679 file, assuming that the linked org-mode file will also be
2680 converted to HTML.
2681 When nil, the links still point to the plain `.org' file."
2682 :group 'org-export-html
2683 :type 'boolean)
2685 (defcustom org-export-html-inline-images 'maybe
2686 "Non-nil means, inline images into exported HTML pages.
2687 This is done using an <img> tag. When nil, an anchor with href is used to
2688 link to the image. If this option is `maybe', then images in links with
2689 an empty description will be inlined, while images with a description will
2690 be linked only."
2691 :group 'org-export-html
2692 :type '(choice (const :tag "Never" nil)
2693 (const :tag "Always" t)
2694 (const :tag "When there is no description" maybe)))
2696 ;; FIXME: rename
2697 (defcustom org-export-html-expand t
2698 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2699 When nil, these tags will be exported as plain text and therefore
2700 not be interpreted by a browser.
2702 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2703 :group 'org-export-html
2704 :type 'boolean)
2706 (defcustom org-export-html-table-tag
2707 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
2708 "The HTML tag that is used to start a table.
2709 This must be a <table> tag, but you may change the options like
2710 borders and spacing."
2711 :group 'org-export-html
2712 :type 'string)
2714 (defcustom org-export-table-header-tags '("<th>" . "</th>")
2715 "The opening tag for table header fields.
2716 This is customizable so that alignment options can be specified."
2717 :group 'org-export-tables
2718 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
2720 (defcustom org-export-table-data-tags '("<td>" . "</td>")
2721 "The opening tag for table data fields.
2722 This is customizable so that alignment options can be specified."
2723 :group 'org-export-tables
2724 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
2726 (defcustom org-export-html-with-timestamp nil
2727 "If non-nil, write `org-export-html-html-helper-timestamp'
2728 into the exported HTML text. Otherwise, the buffer will just be saved
2729 to a file."
2730 :group 'org-export-html
2731 :type 'boolean)
2733 (defcustom org-export-html-html-helper-timestamp
2734 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2735 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2736 :group 'org-export-html
2737 :type 'string)
2739 (defgroup org-export-icalendar nil
2740 "Options specific for iCalendar export of Org-mode files."
2741 :tag "Org Export iCalendar"
2742 :group 'org-export)
2744 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2745 "The file name for the iCalendar file covering all agenda files.
2746 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2747 The file name should be absolute."
2748 :group 'org-export-icalendar
2749 :type 'file)
2751 (defcustom org-icalendar-include-todo nil
2752 "Non-nil means, export to iCalendar files should also cover TODO items."
2753 :group 'org-export-icalendar
2754 :type '(choice
2755 (const :tag "None" nil)
2756 (const :tag "Unfinished" t)
2757 (const :tag "All" all)))
2759 (defcustom org-icalendar-combined-name "OrgMode"
2760 "Calendar name for the combined iCalendar representing all agenda files."
2761 :group 'org-export-icalendar
2762 :type 'string)
2764 (defgroup org-font-lock nil
2765 "Font-lock settings for highlighting in Org-mode."
2766 :tag "Org Font Lock"
2767 :group 'org)
2769 (defcustom org-level-color-stars-only nil
2770 "Non-nil means fontify only the stars in each headline.
2771 When nil, the entire headline is fontified.
2772 Changing it requires restart of `font-lock-mode' to become effective
2773 also in regions already fontified."
2774 :group 'org-font-lock
2775 :type 'boolean)
2777 (defcustom org-hide-leading-stars nil
2778 "Non-nil means, hide the first N-1 stars in a headline.
2779 This works by using the face `org-hide' for these stars. This
2780 face is white for a light background, and black for a dark
2781 background. You may have to customize the face `org-hide' to
2782 make this work.
2783 Changing it requires restart of `font-lock-mode' to become effective
2784 also in regions already fontified.
2785 You may also set this on a per-file basis by adding one of the following
2786 lines to the buffer:
2788 #+STARTUP: hidestars
2789 #+STARTUP: showstars"
2790 :group 'org-font-lock
2791 :type 'boolean)
2793 (defcustom org-fontify-done-headline nil
2794 "Non-nil means, change the face of a headline if it is marked DONE.
2795 Normally, only the TODO/DONE keyword indicates the state of a headline.
2796 When this is non-nil, the headline after the keyword is set to the
2797 `org-headline-done' as an additional indication."
2798 :group 'org-font-lock
2799 :type 'boolean)
2801 (defcustom org-fontify-emphasized-text t
2802 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2803 Changing this variable requires a restart of Emacs to take effect."
2804 :group 'org-font-lock
2805 :type 'boolean)
2807 (defvar org-emph-re nil
2808 "Regular expression for matching emphasis.")
2809 (defvar org-emphasis-regexp-components) ; defined just below
2810 (defvar org-emphasis-alist) ; defined just below
2811 (defun org-set-emph-re (var val)
2812 "Set variable and compute the emphasis regular expression."
2813 (set var val)
2814 (when (and (boundp 'org-emphasis-alist)
2815 (boundp 'org-emphasis-regexp-components)
2816 org-emphasis-alist org-emphasis-regexp-components)
2817 (let* ((e org-emphasis-regexp-components)
2818 (pre (car e))
2819 (post (nth 1 e))
2820 (border (nth 2 e))
2821 (body (nth 3 e))
2822 (nl (nth 4 e))
2823 (stacked (nth 5 e))
2824 (body1 (concat body "*?"))
2825 (markers (mapconcat 'car org-emphasis-alist "")))
2826 ;; make sure special characters appear at the right position in the class
2827 (if (string-match "\\^" markers)
2828 (setq markers (concat (replace-match "" t t markers) "^")))
2829 (if (string-match "-" markers)
2830 (setq markers (concat (replace-match "" t t markers) "-")))
2831 (if (> nl 0)
2832 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2833 (int-to-string nl) "\\}")))
2834 ;; Make the regexp
2835 (setq org-emph-re
2836 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2837 "\\("
2838 "\\([" markers "]\\)"
2839 "\\("
2840 "[^" border (if (and nil stacked) markers) "]"
2841 body1
2842 "[^" border (if (and nil stacked) markers) "]"
2843 "\\)"
2844 "\\3\\)"
2845 "\\([" post (if stacked markers) "]\\|$\\)")))))
2847 (defcustom org-emphasis-regexp-components
2848 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
2849 "Components used to build the reqular expression for emphasis.
2850 This is a list with 6 entries. Terminology: In an emphasis string
2851 like \" *strong word* \", we call the initial space PREMATCH, the final
2852 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2853 and \"trong wor\" is the body. The different components in this variable
2854 specify what is allowed/forbidden in each part:
2856 pre Chars allowed as prematch. Beginning of line will be allowed too.
2857 post Chars allowed as postmatch. End of line will be allowed too.
2858 border The chars *forbidden* as border characters. In addition to the
2859 characters given here, all marker characters are forbidden too.
2860 FIXME: the last statement is no longer true.
2861 body-regexp A regexp like \".\" to match a body character. Don't use
2862 non-shy groups here, and don't allow newline here.
2863 newline The maximum number of newlines allowed in an emphasis exp.
2864 stacked Non-nil means, allow stacked styles. This works only in HTML
2865 export. When this is set, all marker characters (as given in
2866 `org-emphasis-alist') will be allowed as pre/post, aiding
2867 inside-out matching.
2868 Use customize to modify this, or restart Emacs after changing it."
2869 :group 'org-font-lock
2870 :set 'org-set-emph-re
2871 :type '(list
2872 (sexp :tag "Allowed chars in pre ")
2873 (sexp :tag "Allowed chars in post ")
2874 (sexp :tag "Forbidden chars in border ")
2875 (sexp :tag "Regexp for body ")
2876 (integer :tag "number of newlines allowed")
2877 (boolean :tag "Stacking allowed ")))
2879 (defcustom org-emphasis-alist
2880 '(("*" bold "<b>" "</b>")
2881 ("/" italic "<i>" "</i>")
2882 ("_" underline "<u>" "</u>")
2883 ("=" shadow "<code>" "</code>")
2884 ("+" (:strike-through t) "<del>" "</del>")
2886 "Special syntax for emphasized text.
2887 Text starting and ending with a special character will be emphasized, for
2888 example *bold*, _underlined_ and /italic/. This variable sets the marker
2889 characters, the face to bbe used by font-lock for highlighting in Org-mode
2890 Emacs buffers, and the HTML tags to be used for this.
2891 Use customize to modify this, or restart Emacs after changing it."
2892 :group 'org-font-lock
2893 :set 'org-set-emph-re
2894 :type '(repeat
2895 (list
2896 (string :tag "Marker character")
2897 (choice
2898 (face :tag "Font-lock-face")
2899 (plist :tag "Face property list"))
2900 (string :tag "HTML start tag")
2901 (string :tag "HTML end tag"))))
2903 ;;; The faces
2905 (defgroup org-faces nil
2906 "Faces in Org-mode."
2907 :tag "Org Faces"
2908 :group 'org-font-lock)
2910 (defun org-compatible-face (specs)
2911 "Make a compatible face specification.
2912 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2913 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2914 to the top of the list. The `min-colors' attribute will be removed from
2915 any other entries, and any resulting duplicates will be removed entirely."
2916 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2917 (let (r e a)
2918 (while (setq e (pop specs))
2919 (cond
2920 ((memq (car e) '(t default)) (push e r))
2921 ((setq a (member '(min-colors 8) (car e)))
2922 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2923 (cdr e)))))
2924 ((setq a (assq 'min-colors (car e)))
2925 (setq e (cons (delq a (car e)) (cdr e)))
2926 (or (assoc (car e) r) (push e r)))
2927 (t (or (assoc (car e) r) (push e r)))))
2928 (nreverse r))
2929 specs))
2931 (defface org-hide
2932 '((((background light)) (:foreground "white"))
2933 (((background dark)) (:foreground "black")))
2934 "Face used to hide leading stars in headlines.
2935 The forground color of this face should be equal to the background
2936 color of the frame."
2937 :group 'org-faces)
2939 (defface org-level-1 ;; font-lock-function-name-face
2940 (org-compatible-face
2941 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2942 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2943 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2944 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2945 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2946 (t (:bold t))))
2947 "Face used for level 1 headlines."
2948 :group 'org-faces)
2950 (defface org-level-2 ;; font-lock-variable-name-face
2951 (org-compatible-face
2952 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2953 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2954 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2955 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2956 (t (:bold t))))
2957 "Face used for level 2 headlines."
2958 :group 'org-faces)
2960 (defface org-level-3 ;; font-lock-keyword-face
2961 (org-compatible-face
2962 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2963 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2964 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2965 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2966 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2967 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2968 (t (:bold t))))
2969 "Face used for level 3 headlines."
2970 :group 'org-faces)
2972 (defface org-level-4 ;; font-lock-comment-face
2973 (org-compatible-face
2974 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2975 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2976 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2977 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2978 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2979 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2980 (t (:bold t))))
2981 "Face used for level 4 headlines."
2982 :group 'org-faces)
2984 (defface org-level-5 ;; font-lock-type-face
2985 (org-compatible-face
2986 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2987 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2988 (((class color) (min-colors 8)) (:foreground "green"))))
2989 "Face used for level 5 headlines."
2990 :group 'org-faces)
2992 (defface org-level-6 ;; font-lock-constant-face
2993 (org-compatible-face
2994 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2995 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2996 (((class color) (min-colors 8)) (:foreground "magenta"))))
2997 "Face used for level 6 headlines."
2998 :group 'org-faces)
3000 (defface org-level-7 ;; font-lock-builtin-face
3001 (org-compatible-face
3002 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3003 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3004 (((class color) (min-colors 8)) (:foreground "blue"))))
3005 "Face used for level 7 headlines."
3006 :group 'org-faces)
3008 (defface org-level-8 ;; font-lock-string-face
3009 (org-compatible-face
3010 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3011 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3012 (((class color) (min-colors 8)) (:foreground "green"))))
3013 "Face used for level 8 headlines."
3014 :group 'org-faces)
3016 (defface org-special-keyword ;; font-lock-string-face
3017 (org-compatible-face
3018 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3019 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3020 (t (:italic t))))
3021 "Face used for special keywords."
3022 :group 'org-faces)
3024 (defface org-warning ;; font-lock-warning-face
3025 (org-compatible-face
3026 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3027 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3028 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3029 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3030 (t (:bold t))))
3031 "Face for deadlines and TODO keywords."
3032 :group 'org-faces)
3034 (defface org-archived ; similar to shadow
3035 (org-compatible-face
3036 '((((class color grayscale) (min-colors 88) (background light))
3037 (:foreground "grey50"))
3038 (((class color grayscale) (min-colors 88) (background dark))
3039 (:foreground "grey70"))
3040 (((class color) (min-colors 8) (background light))
3041 (:foreground "green"))
3042 (((class color) (min-colors 8) (background dark))
3043 (:foreground "yellow"))))
3044 "Face for headline with the ARCHIVE tag."
3045 :group 'org-faces)
3047 (defface org-link
3048 '((((class color) (background light)) (:foreground "Purple" :underline t))
3049 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3050 (t (:underline t)))
3051 "Face for links."
3052 :group 'org-faces)
3054 (defface org-date
3055 '((((class color) (background light)) (:foreground "Purple" :underline t))
3056 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3057 (t (:underline t)))
3058 "Face for links."
3059 :group 'org-faces)
3061 (defface org-tag
3062 '((t (:bold t)))
3063 "Face for tags."
3064 :group 'org-faces)
3066 (defface org-todo ;; font-lock-warning-face
3067 (org-compatible-face
3068 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3069 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3070 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3071 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3072 (t (:inverse-video t :bold t))))
3073 "Face for TODO keywords."
3074 :group 'org-faces)
3076 (defface org-done ;; font-lock-type-face
3077 (org-compatible-face
3078 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3079 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3080 (((class color) (min-colors 8)) (:foreground "green"))
3081 (t (:bold t))))
3082 "Face used for todo keywords that indicate DONE items."
3083 :group 'org-faces)
3085 (defface org-headline-done ;; font-lock-string-face
3086 (org-compatible-face
3087 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3088 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3089 (((class color) (min-colors 8) (background light)) (:bold nil))))
3090 "Face used to indicate that a headline is DONE.
3091 This face is only used if `org-fontify-done-headline' is set. If applies
3092 to the part of the headline after the DONE keyword."
3093 :group 'org-faces)
3095 (defface org-table ;; font-lock-function-name-face
3096 (org-compatible-face
3097 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3098 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3099 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3100 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3101 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3102 (((class color) (min-colors 8) (background dark)))))
3103 "Face used for tables."
3104 :group 'org-faces)
3106 (defface org-formula
3107 (org-compatible-face
3108 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3109 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3110 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3111 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3112 (t (:bold t :italic t))))
3113 "Face for formulas."
3114 :group 'org-faces)
3116 (defface org-scheduled-today
3117 (org-compatible-face
3118 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3119 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3120 (((class color) (min-colors 8)) (:foreground "green"))
3121 (t (:bold t :italic t))))
3122 "Face for items scheduled for a certain day."
3123 :group 'org-faces)
3125 (defface org-scheduled-previously
3126 (org-compatible-face
3127 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3128 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3129 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3130 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3131 (t (:bold t))))
3132 "Face for items scheduled previously, and not yet done."
3133 :group 'org-faces)
3135 (defface org-upcoming-deadline
3136 (org-compatible-face
3137 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3138 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3139 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3140 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3141 (t (:bold t))))
3142 "Face for items scheduled previously, and not yet done."
3143 :group 'org-faces)
3145 (defface org-time-grid ;; font-lock-variable-name-face
3146 (org-compatible-face
3147 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3148 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3149 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3150 "Face used for time grids."
3151 :group 'org-faces)
3153 (defconst org-level-faces
3154 '(org-level-1 org-level-2 org-level-3 org-level-4
3155 org-level-5 org-level-6 org-level-7 org-level-8
3157 (defconst org-n-levels (length org-level-faces))
3160 ;;; Variables for pre-computed regular expressions, all buffer local
3162 (defvar org-todo-regexp nil
3163 "Matches any of the TODO state keywords.")
3164 (make-variable-buffer-local 'org-todo-regexp)
3165 (defvar org-not-done-regexp nil
3166 "Matches any of the TODO state keywords except the last one.")
3167 (make-variable-buffer-local 'org-not-done-regexp)
3168 (defvar org-todo-line-regexp nil
3169 "Matches a headline and puts TODO state into group 2 if present.")
3170 (make-variable-buffer-local 'org-todo-line-regexp)
3171 (defvar org-todo-line-tags-regexp nil
3172 "Matches a headline and puts TODO state into group 2 if present.
3173 Also put tags into group 4 if tags are present.")
3174 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3175 (defvar org-nl-done-regexp nil
3176 "Matches newline followed by a headline with the DONE keyword.")
3177 (make-variable-buffer-local 'org-nl-done-regexp)
3178 (defvar org-looking-at-done-regexp nil
3179 "Matches the DONE keyword a point.")
3180 (make-variable-buffer-local 'org-looking-at-done-regexp)
3181 (defvar org-ds-keyword-length 12
3182 "Maximum length of the Deadline and SCHEDULED keywords.")
3183 (make-variable-buffer-local 'org-ds-keyword-length)
3184 (defvar org-deadline-regexp nil
3185 "Matches the DEADLINE keyword.")
3186 (make-variable-buffer-local 'org-deadline-regexp)
3187 (defvar org-deadline-time-regexp nil
3188 "Matches the DEADLINE keyword together with a time stamp.")
3189 (make-variable-buffer-local 'org-deadline-time-regexp)
3190 (defvar org-deadline-line-regexp nil
3191 "Matches the DEADLINE keyword and the rest of the line.")
3192 (make-variable-buffer-local 'org-deadline-line-regexp)
3193 (defvar org-scheduled-regexp nil
3194 "Matches the SCHEDULED keyword.")
3195 (make-variable-buffer-local 'org-scheduled-regexp)
3196 (defvar org-scheduled-time-regexp nil
3197 "Matches the SCHEDULED keyword together with a time stamp.")
3198 (make-variable-buffer-local 'org-scheduled-time-regexp)
3199 (defvar org-closed-time-regexp nil
3200 "Matches the CLOSED keyword together with a time stamp.")
3201 (make-variable-buffer-local 'org-closed-time-regexp)
3203 (defvar org-keyword-time-regexp nil
3204 "Matches any of the 4 keywords, together with the time stamp.")
3205 (make-variable-buffer-local 'org-keyword-time-regexp)
3206 (defvar org-keyword-time-not-clock-regexp nil
3207 "Matches any of the 3 keywords, together with the time stamp.")
3208 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3209 (defvar org-maybe-keyword-time-regexp nil
3210 "Matches a timestamp, possibly preceeded by a keyword.")
3211 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3213 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3214 rear-nonsticky t mouse-map t fontified t)
3215 "Properties to remove when a string without properties is wanted.")
3217 (defsubst org-match-string-no-properties (num &optional string)
3218 (if (featurep 'xemacs)
3219 (let ((s (match-string num string)))
3220 (remove-text-properties 0 (length s) org-rm-props s)
3222 (match-string-no-properties num string)))
3224 (defsubst org-no-properties (s)
3225 (remove-text-properties 0 (length s) org-rm-props s)
3228 (defsubst org-get-alist-option (option key)
3229 (cond ((eq key t) t)
3230 ((eq option t) t)
3231 ((assoc key option) (cdr (assoc key option)))
3232 (t (cdr (assq 'default option)))))
3234 (defsubst org-inhibit-invisibility ()
3235 "Modified `buffer-invisibility-spec' for Emacs 21.
3236 Some ops with invisible text do not work correctly on Emacs 21. For these
3237 we turn off invisibility temporarily. Use this in a `let' form."
3238 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3240 (defsubst org-set-local (var value)
3241 "Make VAR local in current buffer and set it to VALUE."
3242 (set (make-variable-buffer-local var) value))
3244 (defsubst org-mode-p ()
3245 "Check if the current buffer is in Org-mode."
3246 (eq major-mode 'org-mode))
3248 (defsubst org-last (list)
3249 "Return the last element of LIST."
3250 (car (last list)))
3252 (defun org-let (list &rest body)
3253 (eval (cons 'let (cons list body))))
3254 (put 'org-let 'lisp-indent-function 1)
3256 (defun org-let2 (list1 list2 &rest body)
3257 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3258 (put 'org-let2 'lisp-indent-function 2)
3259 (defconst org-startup-options
3260 '(("fold" org-startup-folded t)
3261 ("overview" org-startup-folded t)
3262 ("nofold" org-startup-folded nil)
3263 ("showall" org-startup-folded nil)
3264 ("content" org-startup-folded content)
3265 ("hidestars" org-hide-leading-stars t)
3266 ("showstars" org-hide-leading-stars nil)
3267 ("odd" org-odd-levels-only t)
3268 ("oddeven" org-odd-levels-only nil)
3269 ("align" org-startup-align-all-tables t)
3270 ("noalign" org-startup-align-all-tables nil)
3271 ("customtime" org-display-custom-times t)
3272 ("logging" org-log-done t)
3273 ("logdone" org-log-done t)
3274 ("nologging" org-log-done nil)
3275 ("lognotedone" org-log-done done push)
3276 ("lognotestate" org-log-done state push)
3277 ("lognoteclock-out" org-log-done clock-out push)
3278 ("logrepeat" org-log-repeat t)
3279 ("nologrepeat" org-log-repeat nil)
3280 ("constcgs" constants-unit-system cgs)
3281 ("constSI" constants-unit-system SI))
3282 "Variable associated with STARTUP options for org-mode.
3283 Each element is a list of three items: The startup options as written
3284 in the #+STARTUP line, the corresponding variable, and the value to
3285 set this variable to if the option is found. An optional forth element PUSH
3286 means to push this value onto the list in the variable.")
3288 (defun org-set-regexps-and-options ()
3289 "Precompute regular expressions for current buffer."
3290 (when (org-mode-p)
3291 (org-set-local 'org-todo-kwd-alist nil)
3292 (org-set-local 'org-todo-keywords-1 nil)
3293 (org-set-local 'org-done-keywords nil)
3294 (org-set-local 'org-todo-heads nil)
3295 (org-set-local 'org-todo-sets nil)
3296 (let ((re (org-make-options-regexp
3297 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
3298 "STARTUP" "ARCHIVE" "TAGS" "LINK")))
3299 (splitre "[ \t]+")
3300 kwds key value cat arch tags links hw dws tail sep kws1)
3301 (save-excursion
3302 (save-restriction
3303 (widen)
3304 (goto-char (point-min))
3305 (while (re-search-forward re nil t)
3306 (setq key (match-string 1) value (org-match-string-no-properties 2))
3307 (cond
3308 ((equal key "CATEGORY")
3309 (if (string-match "[ \t]+$" value)
3310 (setq value (replace-match "" t t value)))
3311 (setq cat (intern value)))
3312 ((equal key "SEQ_TODO")
3313 (push (cons 'sequence (org-split-string value splitre)) kwds))
3314 ((equal key "TYP_TODO")
3315 (push (cons 'type (org-split-string value splitre)) kwds))
3316 ((equal key "TAGS")
3317 (setq tags (append tags (org-split-string value splitre))))
3318 ((equal key "LINK")
3319 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3320 (push (cons (match-string 1 value)
3321 (org-trim (match-string 2 value)))
3322 links)))
3323 ((equal key "STARTUP")
3324 (let ((opts (org-split-string value splitre))
3325 l var val)
3326 (while (setq l (pop opts))
3327 (when (setq l (assoc l org-startup-options))
3328 (setq var (nth 1 l) val (nth 2 l))
3329 (if (not (nth 3 l))
3330 (set (make-local-variable var) val)
3331 (if (not (listp (symbol-value var)))
3332 (set (make-local-variable var) nil))
3333 (set (make-local-variable var) (symbol-value var))
3334 (add-to-list var val))))))
3335 ((equal key "ARCHIVE")
3336 (string-match " *$" value)
3337 (setq arch (replace-match "" t t value))
3338 (remove-text-properties 0 (length arch)
3339 '(face t fontified t) arch)))
3341 (and cat (org-set-local 'org-category cat))
3342 (and arch (org-set-local 'org-archive-location arch))
3343 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3344 ;; Process the TODO keywords
3345 (unless kwds
3346 ;; Use the global values as if they had been given locally.
3347 (setq kwds (default-value 'org-todo-keywords))
3348 (if (stringp (car kwds))
3349 (setq kwds (list (cons org-todo-interpretation
3350 (default-value 'org-todo-keywords)))))
3351 (setq kwds (reverse kwds)))
3352 (setq kwds (nreverse kwds))
3353 (let (inter kws)
3354 (while (setq kws (pop kwds))
3355 (setq inter (pop kws) sep (member "|" kws)
3356 kws1 (delete "|" (copy-sequence kws))
3357 hw (car kws1)
3358 dws (if sep (cdr sep) (last kws1))
3359 tail (list inter hw (car dws) (org-last dws)))
3360 (add-to-list 'org-todo-heads hw 'append)
3361 (push kws1 org-todo-sets)
3362 (setq org-done-keywords (append org-done-keywords dws nil))
3363 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3364 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3365 (setq org-todo-sets (nreverse org-todo-sets)
3366 org-todo-kwd-alist (nreverse org-todo-kwd-alist)))
3367 ;; Process the tags.
3368 (when tags
3369 (let (e tgs)
3370 (while (setq e (pop tags))
3371 (cond
3372 ((equal e "{") (push '(:startgroup) tgs))
3373 ((equal e "}") (push '(:endgroup) tgs))
3374 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
3375 (push (cons (match-string 1 e)
3376 (string-to-char (match-string 2 e)))
3377 tgs))
3378 (t (push (list e) tgs))))
3379 (org-set-local 'org-tag-alist nil)
3380 (while (setq e (pop tgs))
3381 (or (and (stringp (car e))
3382 (assoc (car e) org-tag-alist))
3383 (push e org-tag-alist))))))
3385 ;; Compute the regular expressions and other local variables
3386 (if (not org-done-keywords)
3387 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3388 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3389 (length org-scheduled-string)))
3390 org-not-done-keywords
3391 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3392 org-todo-regexp
3393 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3394 "\\|") "\\)\\>")
3395 org-not-done-regexp
3396 (concat "\\<\\("
3397 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3398 "\\)\\>")
3399 org-todo-line-regexp
3400 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3401 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3402 "\\)\\>\\)? *\\(.*\\)")
3403 org-nl-done-regexp
3404 (concat "[\r\n]\\*+[ \t]+"
3405 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3406 "\\)" "\\>")
3407 org-todo-line-tags-regexp
3408 (concat "^\\(\\*+\\)[ \t]*\\(?:\\("
3409 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3410 "\\)\\>\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
3411 org-looking-at-done-regexp
3412 (concat "^" "\\(?:"
3413 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3414 "\\>")
3415 org-deadline-regexp (concat "\\<" org-deadline-string)
3416 org-deadline-time-regexp
3417 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3418 org-deadline-line-regexp
3419 (concat "\\<\\(" org-deadline-string "\\).*")
3420 org-scheduled-regexp
3421 (concat "\\<" org-scheduled-string)
3422 org-scheduled-time-regexp
3423 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3424 org-closed-time-regexp
3425 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3426 org-keyword-time-regexp
3427 (concat "\\<\\(" org-scheduled-string
3428 "\\|" org-deadline-string
3429 "\\|" org-closed-string
3430 "\\|" org-clock-string "\\)"
3431 " *[[<]\\([^]>]+\\)[]>]")
3432 org-keyword-time-not-clock-regexp
3433 (concat "\\<\\(" org-scheduled-string
3434 "\\|" org-deadline-string
3435 "\\|" org-closed-string "\\)"
3436 " *[[<]\\([^]>]+\\)[]>]")
3437 org-maybe-keyword-time-regexp
3438 (concat "\\(\\<\\(" org-scheduled-string
3439 "\\|" org-deadline-string
3440 "\\|" org-closed-string
3441 "\\|" org-clock-string "\\)\\)?"
3442 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
3444 (org-set-font-lock-defaults)))
3447 ;;; Some variables ujsed in various places
3449 (defvar org-window-configuration nil
3450 "Used in various places to store a window configuration.")
3451 (defvar org-finish-function nil
3452 "Function to be called when `C-c C-c' is used.
3453 This is for getting out of special buffers like remember.")
3455 ;;; Foreign variables, to inform the compiler
3457 ;; XEmacs only
3458 (defvar outline-mode-menu-heading)
3459 (defvar outline-mode-menu-show)
3460 (defvar outline-mode-menu-hide)
3461 (defvar zmacs-regions) ; XEmacs regions
3462 ;; Emacs only
3463 (defvar mark-active)
3465 ;; Packages that org-mode interacts with
3466 (defvar calc-embedded-close-formula)
3467 (defvar calc-embedded-open-formula)
3468 (defvar font-lock-unfontify-region-function)
3469 (defvar org-goto-start-pos)
3470 (defvar vm-message-pointer)
3471 (defvar vm-folder-directory)
3472 (defvar wl-summary-buffer-elmo-folder)
3473 (defvar wl-summary-buffer-folder-name)
3474 (defvar gnus-other-frame-object)
3475 (defvar gnus-group-name)
3476 (defvar gnus-article-current)
3477 (defvar w3m-current-url)
3478 (defvar w3m-current-title)
3479 (defvar mh-progs)
3480 (defvar mh-current-folder)
3481 (defvar mh-show-folder-buffer)
3482 (defvar mh-index-folder)
3483 (defvar mh-searcher)
3484 (defvar calendar-mode-map)
3485 (defvar Info-current-file)
3486 (defvar Info-current-node)
3487 (defvar texmathp-why)
3488 (defvar remember-save-after-remembering)
3489 (defvar remember-data-file)
3490 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3491 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3492 (defvar org-latex-regexps)
3493 (defvar constants-unit-system)
3495 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3497 ;; FIXME: Occasionally check by commenting these, to make sure
3498 ;; no other functions uses these, forgetting to let-bind them.
3499 (defvar entry)
3500 (defvar state)
3501 (defvar last-state)
3502 (defvar date)
3503 (defvar description)
3506 ;; Defined somewhere in this file, but used before definition.
3507 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3508 (defvar org-agenda-undo-list)
3509 (defvar org-agenda-pending-undo-list)
3510 (defvar org-agenda-overriding-header)
3511 (defvar orgtbl-mode)
3512 (defvar org-html-entities)
3513 (defvar org-struct-menu)
3514 (defvar org-org-menu)
3515 (defvar org-tbl-menu)
3516 (defvar org-agenda-keymap)
3517 (defvar org-category-table)
3519 ;;;; Emacs/XEmacs compatibility
3521 ;; Overlay compatibility functions
3522 (defun org-make-overlay (beg end &optional buffer)
3523 (if (featurep 'xemacs)
3524 (make-extent beg end buffer)
3525 (make-overlay beg end buffer)))
3526 (defun org-delete-overlay (ovl)
3527 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3528 (defun org-detach-overlay (ovl)
3529 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3530 (defun org-move-overlay (ovl beg end &optional buffer)
3531 (if (featurep 'xemacs)
3532 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3533 (move-overlay ovl beg end buffer)))
3534 (defun org-overlay-put (ovl prop value)
3535 (if (featurep 'xemacs)
3536 (set-extent-property ovl prop value)
3537 (overlay-put ovl prop value)))
3538 (defun org-overlay-display (ovl text &optional face evap)
3539 "Make overlay OVL display TEXT with face FACE."
3540 (if (featurep 'xemacs)
3541 (let ((gl (make-glyph text)))
3542 (and face (set-glyph-face gl face))
3543 (set-extent-property ovl 'invisible t)
3544 (set-extent-property ovl 'end-glyph gl))
3545 (overlay-put ovl 'display text)
3546 (if face (overlay-put ovl 'face face))
3547 (if evap (overlay-put ovl 'evaporate t))))
3548 (defun org-overlay-before-string (ovl text &optional face evap)
3549 "Make overlay OVL display TEXT with face FACE."
3550 (if (featurep 'xemacs)
3551 (let ((gl (make-glyph text)))
3552 (and face (set-glyph-face gl face))
3553 (set-extent-property ovl 'begin-glyph gl))
3554 (if face (org-add-props text nil 'face face))
3555 (overlay-put ovl 'before-string text)
3556 (if evap (overlay-put ovl 'evaporate t))))
3557 (defun org-overlay-get (ovl prop)
3558 (if (featurep 'xemacs)
3559 (extent-property ovl prop)
3560 (overlay-get ovl prop)))
3561 (defun org-overlays-at (pos)
3562 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3563 ;; FIXME: this is currently not used
3564 (defun org-overlays-in (&optional start end)
3565 (if (featurep 'xemacs)
3566 (extent-list nil start end)
3567 (overlays-in start end)))
3568 (defun org-overlay-start (o)
3569 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3570 (defun org-overlay-end (o)
3571 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3572 ;; FIXME: this is currently not used
3573 (defun org-find-overlays (prop &optional pos delete)
3574 "Find all overlays specifying PROP at POS or point.
3575 If DELETE is non-nil, delete all those overlays."
3576 (let ((overlays (org-overlays-at (or pos (point))))
3577 ov found)
3578 (while (setq ov (pop overlays))
3579 (if (org-overlay-get ov prop)
3580 (if delete (org-delete-overlay ov) (push ov found))))
3581 found))
3583 ;; Region compatibility
3585 (defun org-add-hook (hook function &optional append local)
3586 "Add-hook, compatible with both Emacsen."
3587 (if (and local (featurep 'xemacs))
3588 (add-local-hook hook function append)
3589 (add-hook hook function append local)))
3591 (defvar org-ignore-region nil
3592 "To temporarily disable the active region.")
3594 (defun org-region-active-p ()
3595 "Is `transient-mark-mode' on and the region active?
3596 Works on both Emacs and XEmacs."
3597 (if org-ignore-region
3599 (if (featurep 'xemacs)
3600 (and zmacs-regions (region-active-p))
3601 (and transient-mark-mode mark-active))))
3603 ;; Invisibility compatibility
3605 (defun org-add-to-invisibility-spec (arg)
3606 "Add elements to `buffer-invisibility-spec'.
3607 See documentation for `buffer-invisibility-spec' for the kind of elements
3608 that can be added."
3609 (cond
3610 ((fboundp 'add-to-invisibility-spec)
3611 (add-to-invisibility-spec arg))
3612 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3613 (setq buffer-invisibility-spec (list arg)))
3615 (setq buffer-invisibility-spec
3616 (cons arg buffer-invisibility-spec)))))
3618 (defun org-remove-from-invisibility-spec (arg)
3619 "Remove elements from `buffer-invisibility-spec'."
3620 (if (fboundp 'remove-from-invisibility-spec)
3621 (remove-from-invisibility-spec arg)
3622 (if (consp buffer-invisibility-spec)
3623 (setq buffer-invisibility-spec
3624 (delete arg buffer-invisibility-spec)))))
3626 ;; FIXME: this is currently not used
3627 (defun org-in-invisibility-spec-p (arg)
3628 "Is ARG a member of `buffer-invisibility-spec'?"
3629 (if (consp buffer-invisibility-spec)
3630 (member arg buffer-invisibility-spec)
3631 nil))
3633 ;;;; Define the Org-mode
3635 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3636 (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."))
3639 ;; We use a before-change function to check if a table might need
3640 ;; an update.
3641 (defvar org-table-may-need-update t
3642 "Indicates that a table might need an update.
3643 This variable is set by `org-before-change-function'.
3644 `org-table-align' sets it back to nil.")
3645 (defvar org-mode-map)
3646 (defvar org-mode-hook nil)
3647 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3648 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3649 (defvar org-table-buffer-is-an nil)
3652 ;;;###autoload
3653 (define-derived-mode org-mode outline-mode "Org"
3654 "Outline-based notes management and organizer, alias
3655 \"Carsten's outline-mode for keeping track of everything.\"
3657 Org-mode develops organizational tasks around a NOTES file which
3658 contains information about projects as plain text. Org-mode is
3659 implemented on top of outline-mode, which is ideal to keep the content
3660 of large files well structured. It supports ToDo items, deadlines and
3661 time stamps, which magically appear in the diary listing of the Emacs
3662 calendar. Tables are easily created with a built-in table editor.
3663 Plain text URL-like links connect to websites, emails (VM), Usenet
3664 messages (Gnus), BBDB entries, and any files related to the project.
3665 For printing and sharing of notes, an Org-mode file (or a part of it)
3666 can be exported as a structured ASCII or HTML file.
3668 The following commands are available:
3670 \\{org-mode-map}"
3672 ;; Get rid of Outline menus, they are not needed
3673 ;; Need to do this here because define-derived-mode sets up
3674 ;; the keymap so late. Still, it is a waste to call this each time
3675 ;; we switch another buffer into org-mode.
3676 (if (featurep 'xemacs)
3677 (when (boundp 'outline-mode-menu-heading)
3678 ;; Assume this is Greg's port, it used easymenu
3679 (easy-menu-remove outline-mode-menu-heading)
3680 (easy-menu-remove outline-mode-menu-show)
3681 (easy-menu-remove outline-mode-menu-hide))
3682 (define-key org-mode-map [menu-bar headings] 'undefined)
3683 (define-key org-mode-map [menu-bar hide] 'undefined)
3684 (define-key org-mode-map [menu-bar show] 'undefined))
3686 (easy-menu-add org-org-menu)
3687 (easy-menu-add org-tbl-menu)
3688 (org-install-agenda-files-menu)
3689 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3690 (org-add-to-invisibility-spec '(org-cwidth))
3691 (when (featurep 'xemacs)
3692 (org-set-local 'line-move-ignore-invisible t))
3693 (setq outline-regexp "\\*+")
3694 (setq outline-level 'org-outline-level)
3695 (when (and org-ellipsis (stringp org-ellipsis)
3696 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
3697 (unless org-display-table
3698 (setq org-display-table (make-display-table)))
3699 (set-display-table-slot org-display-table
3700 4 (string-to-vector org-ellipsis))
3701 (setq buffer-display-table org-display-table))
3702 (org-set-regexps-and-options)
3703 ;; Calc embedded
3704 (org-set-local 'calc-embedded-open-mode "# ")
3705 (modify-syntax-entry ?# "<")
3706 (modify-syntax-entry ?@ "w")
3707 (if org-startup-truncated (setq truncate-lines t))
3708 (org-set-local 'font-lock-unfontify-region-function
3709 'org-unfontify-region)
3710 ;; Activate before-change-function
3711 (org-set-local 'org-table-may-need-update t)
3712 (org-add-hook 'before-change-functions 'org-before-change-function nil
3713 'local)
3714 ;; Check for running clock before killing a buffer
3715 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3716 ;; Paragraphs and auto-filling
3717 (org-set-autofill-regexps)
3718 (setq indent-line-function 'org-indent-line-function)
3719 (org-update-radio-target-regexp)
3721 ;; Comment characters
3722 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3723 (org-set-local 'comment-padding " ")
3725 ;; Make isearch reveal context
3726 (if (or (featurep 'xemacs)
3727 (not (boundp 'outline-isearch-open-invisible-function)))
3728 ;; Emacs 21 and XEmacs make use of the hook
3729 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3730 ;; Emacs 22 deals with this through a special variable
3731 (org-set-local 'outline-isearch-open-invisible-function
3732 (lambda (&rest ignore) (org-show-context 'isearch))))
3734 ;; If empty file that did not turn on org-mode automatically, make it to.
3735 (if (and org-insert-mode-line-in-empty-file
3736 (interactive-p)
3737 (= (point-min) (point-max)))
3738 (insert "# -*- mode: org -*-\n\n"))
3740 (unless org-inhibit-startup
3741 (when org-startup-align-all-tables
3742 (let ((bmp (buffer-modified-p)))
3743 (org-table-map-tables 'org-table-align)
3744 (set-buffer-modified-p bmp)))
3745 (cond
3746 ((eq org-startup-folded t)
3747 (org-cycle '(4)))
3748 ((eq org-startup-folded 'content)
3749 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3750 (org-cycle '(4)) (org-cycle '(4)))))))
3752 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3754 (defsubst org-call-with-arg (command arg)
3755 "Call COMMAND interactively, but pretend prefix are was ARG."
3756 (let ((current-prefix-arg arg)) (call-interactively command)))
3758 (defsubst org-current-line (&optional pos)
3759 (save-excursion
3760 (and pos (goto-char pos))
3761 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
3763 (defun org-current-time ()
3764 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3765 (if (> org-time-stamp-rounding-minutes 0)
3766 (let ((r org-time-stamp-rounding-minutes)
3767 (time (decode-time)))
3768 (apply 'encode-time
3769 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3770 (nthcdr 2 time))))
3771 (current-time)))
3773 (defun org-add-props (string plist &rest props)
3774 "Add text properties to entire string, from beginning to end.
3775 PLIST may be a list of properties, PROPS are individual properties and values
3776 that will be added to PLIST. Returns the string that was modified."
3777 (add-text-properties
3778 0 (length string) (if props (append plist props) plist) string)
3779 string)
3780 (put 'org-add-props 'lisp-indent-function 2)
3783 ;;;; Font-Lock stuff, including the activators
3785 (defvar org-mouse-map (make-sparse-keymap))
3786 (org-defkey org-mouse-map
3787 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3788 (org-defkey org-mouse-map
3789 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3790 (when org-mouse-1-follows-link
3791 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3792 (when org-tab-follows-link
3793 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3794 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3795 (when org-return-follows-link
3796 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3797 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3799 (require 'font-lock)
3801 (defconst org-non-link-chars "]\t\n\r<>")
3802 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3803 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3804 (defconst org-link-re-with-space
3805 (concat
3806 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3807 "\\([^" org-non-link-chars " ]"
3808 "[^" org-non-link-chars "]*"
3809 "[^" org-non-link-chars " ]\\)>?")
3810 "Matches a link with spaces, optional angular brackets around it.")
3812 (defconst org-link-re-with-space2
3813 (concat
3814 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3815 "\\([^" org-non-link-chars " ]"
3816 "[^]\t\n\r]*"
3817 "[^" org-non-link-chars " ]\\)>?")
3818 "Matches a link with spaces, optional angular brackets around it.")
3820 (defconst org-angle-link-re
3821 (concat
3822 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3823 "\\([^" org-non-link-chars " ]"
3824 "[^" org-non-link-chars "]*"
3825 "\\)>")
3826 "Matches link with angular brackets, spaces are allowed.")
3827 (defconst org-plain-link-re
3828 (concat
3829 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3830 "\\([^]\t\n\r<>,;() ]+\\)")
3831 "Matches plain link, without spaces.")
3833 (defconst org-bracket-link-regexp
3834 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3835 "Matches a link in double brackets.")
3837 (defconst org-bracket-link-analytic-regexp
3838 (concat
3839 "\\[\\["
3840 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3841 "\\([^]]+\\)"
3842 "\\]"
3843 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3844 "\\]"))
3845 ; 1: http:
3846 ; 2: http
3847 ; 3: path
3848 ; 4: [desc]
3849 ; 5: desc
3851 (defconst org-any-link-re
3852 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3853 org-angle-link-re "\\)\\|\\("
3854 org-plain-link-re "\\)")
3855 "Regular expression matching any link.")
3857 (defconst org-ts-lengths
3858 (cons (length (format-time-string (car org-time-stamp-formats)))
3859 (length (format-time-string (cdr org-time-stamp-formats))))
3860 "This holds the lengths of the two different time formats.")
3861 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3862 "Regular expression for fast time stamp matching.")
3863 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3864 "Regular expression for fast time stamp matching.")
3865 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3866 "Regular expression matching time strings for analysis.")
3867 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3868 "Regular expression matching time stamps, with groups.")
3869 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3870 "Regular expression matching time stamps (also [..]), with groups.")
3871 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3872 "Regular expression matching a time stamp range.")
3873 (defconst org-tr-regexp-both
3874 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3875 "Regular expression matching a time stamp range.")
3876 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3877 org-ts-regexp "\\)?")
3878 "Regular expression matching a time stamp or time stamp range.")
3879 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3880 org-ts-regexp-both "\\)?")
3881 "Regular expression matching a time stamp or time stamp range.
3882 The time stamps may be either active or inactive.")
3884 (defvar org-emph-face nil)
3886 (defun org-do-emphasis-faces (limit)
3887 "Run through the buffer and add overlays to links."
3888 (let (rtn)
3889 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3890 (if (not (= (char-after (match-beginning 3))
3891 (char-after (match-beginning 4))))
3892 (progn
3893 (setq rtn t)
3894 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3895 'face
3896 (nth 1 (assoc (match-string 3)
3897 org-emphasis-alist)))
3898 (add-text-properties (match-beginning 2) (match-end 2)
3899 '(font-lock-multiline t))
3900 (backward-char 1))))
3901 rtn))
3903 (defun org-activate-plain-links (limit)
3904 "Run through the buffer and add overlays to links."
3905 (if (re-search-forward org-plain-link-re limit t)
3906 (progn
3907 (add-text-properties (match-beginning 0) (match-end 0)
3908 (list 'mouse-face 'highlight
3909 'rear-nonsticky t
3910 'keymap org-mouse-map
3912 t)))
3914 (defun org-activate-angle-links (limit)
3915 "Run through the buffer and add overlays to links."
3916 (if (re-search-forward org-angle-link-re limit t)
3917 (progn
3918 (add-text-properties (match-beginning 0) (match-end 0)
3919 (list 'mouse-face 'highlight
3920 'rear-nonsticky t
3921 'keymap org-mouse-map
3923 t)))
3925 (defmacro org-maybe-intangible (props)
3926 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
3927 In emacs 21, invisible text is not avoided by the command loop, so the
3928 intangible property is needed to make sure point skips this text.
3929 In Emacs 22, this is not necessary. The intangible text property has
3930 led to problems with flyspell. These problems are fixed in flyspell.el,
3931 but we still avoid setting the property in Emacs 22 and later.
3932 We use a macro so that the test can happen at compilation time."
3933 (if (< emacs-major-version 22)
3934 `(append '(intangible t) ,props)
3935 props))
3937 (defun org-activate-bracket-links (limit)
3938 "Run through the buffer and add overlays to bracketed links."
3939 (if (re-search-forward org-bracket-link-regexp limit t)
3940 (let* ((help (concat "LINK: "
3941 (org-match-string-no-properties 1)))
3942 ;; FIXME: above we should remove the escapes.
3943 ;; but that requires another match, protecting match data,
3944 ;; a lot of overhead for font-lock.
3945 (ip (org-maybe-intangible
3946 (list 'invisible 'org-link 'rear-nonsticky t
3947 'keymap org-mouse-map 'mouse-face 'highlight
3948 'help-echo help)))
3949 (vp (list 'rear-nonsticky t
3950 'keymap org-mouse-map 'mouse-face 'highlight
3951 'help-echo help)))
3952 ;; We need to remove the invisible property here. Table narrowing
3953 ;; may have made some of this invisible.
3954 (remove-text-properties (match-beginning 0) (match-end 0)
3955 '(invisible nil))
3956 (if (match-end 3)
3957 (progn
3958 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3959 (add-text-properties (match-beginning 3) (match-end 3) vp)
3960 (add-text-properties (match-end 3) (match-end 0) ip))
3961 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3962 (add-text-properties (match-beginning 1) (match-end 1) vp)
3963 (add-text-properties (match-end 1) (match-end 0) ip))
3964 t)))
3966 (defun org-activate-dates (limit)
3967 "Run through the buffer and add overlays to dates."
3968 (if (re-search-forward org-tsr-regexp-both limit t)
3969 (progn
3970 (add-text-properties (match-beginning 0) (match-end 0)
3971 (list 'mouse-face 'highlight
3972 'rear-nonsticky t
3973 'keymap org-mouse-map))
3974 (when org-display-custom-times
3975 (if (match-end 3)
3976 (org-display-custom-time (match-beginning 3) (match-end 3)))
3977 (org-display-custom-time (match-beginning 1) (match-end 1)))
3978 t)))
3980 (defvar org-target-link-regexp nil
3981 "Regular expression matching radio targets in plain text.")
3982 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3983 "Regular expression matching a link target.")
3984 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3985 "Regular expression matching a link target.")
3987 (defun org-activate-target-links (limit)
3988 "Run through the buffer and add overlays to target matches."
3989 (when org-target-link-regexp
3990 (let ((case-fold-search t))
3991 (if (re-search-forward org-target-link-regexp limit t)
3992 (progn
3993 (add-text-properties (match-beginning 0) (match-end 0)
3994 (list 'mouse-face 'highlight
3995 'rear-nonsticky t
3996 'keymap org-mouse-map
3997 'help-echo "Radio target link"
3998 'org-linked-text t))
3999 t)))))
4001 (defun org-update-radio-target-regexp ()
4002 "Find all radio targets in this file and update the regular expression."
4003 (interactive)
4004 (when (memq 'radio org-activate-links)
4005 (setq org-target-link-regexp
4006 (org-make-target-link-regexp (org-all-targets 'radio)))
4007 (org-restart-font-lock)))
4009 (defun org-hide-wide-columns (limit)
4010 (let (s e)
4011 (setq s (text-property-any (point) (or limit (point-max))
4012 'org-cwidth t))
4013 (when s
4014 (setq e (next-single-property-change s 'org-cwidth))
4015 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4016 (goto-char e)
4017 t)))
4019 (defun org-restart-font-lock ()
4020 "Restart font-lock-mode, to force refontification."
4021 (when (and (boundp 'font-lock-mode) font-lock-mode)
4022 (font-lock-mode -1)
4023 (font-lock-mode 1)))
4025 (defun org-all-targets (&optional radio)
4026 "Return a list of all targets in this file.
4027 With optional argument RADIO, only find radio targets."
4028 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4029 rtn)
4030 (save-excursion
4031 (goto-char (point-min))
4032 (while (re-search-forward re nil t)
4033 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4034 rtn)))
4036 (defun org-make-target-link-regexp (targets)
4037 "Make regular expression matching all strings in TARGETS.
4038 The regular expression finds the targets also if there is a line break
4039 between words."
4040 (and targets
4041 (concat
4042 "\\<\\("
4043 (mapconcat
4044 (lambda (x)
4045 (while (string-match " +" x)
4046 (setq x (replace-match "\\s-+" t t x)))
4048 targets
4049 "\\|")
4050 "\\)\\>")))
4052 (defun org-activate-tags (limit)
4053 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
4054 (progn
4055 (add-text-properties (match-beginning 1) (match-end 1)
4056 (list 'mouse-face 'highlight
4057 'rear-nonsticky t
4058 'keymap org-mouse-map))
4059 t)))
4061 (defun org-outline-level ()
4062 (save-excursion
4063 (looking-at outline-regexp)
4064 (if (match-beginning 1)
4065 (+ (org-get-string-indentation (match-string 1)) 1000)
4066 (- (match-end 0) (match-beginning 0)))))
4068 (defvar org-font-lock-keywords nil)
4070 (defun org-set-font-lock-defaults ()
4071 (let* ((em org-fontify-emphasized-text)
4072 (lk org-activate-links)
4073 (org-font-lock-extra-keywords
4074 ;; Headlines
4075 (list
4076 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
4077 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4078 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4079 (1 'org-table))
4080 ;; Links
4081 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4082 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4083 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4084 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4085 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4086 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4087 '(org-hide-wide-columns (0 nil append))
4088 ;; TODO lines
4089 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
4090 '(1 'org-todo t))
4091 ;; Priorities
4092 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
4093 ;; Special keywords
4094 (list org-repeat-re '(0 'org-special-keyword t))
4095 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4096 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4097 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4098 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4099 ;; Emphasis
4100 (if em
4101 (if (featurep 'xemacs)
4102 '(org-do-emphasis-faces (0 nil append))
4103 '(org-do-emphasis-faces)))
4104 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
4105 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
4106 2 'bold prepend)
4107 (if org-provide-checkbox-statistics
4108 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4109 (0 (org-get-checkbox-statistics-face) t)))
4110 ;; COMMENT
4111 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
4112 "\\|" org-quote-string "\\)\\>")
4113 '(1 'org-special-keyword t))
4114 '("^#.*" (0 'font-lock-comment-face t))
4115 ;; DONE
4116 (if org-fontify-done-headline
4117 (list (concat "^[*]+ +\\<\\("
4118 (mapconcat 'regexp-quote org-done-keywords "\\|")
4119 "\\)\\(.*\\)")
4120 '(1 'org-done t) '(2 'org-headline-done t))
4121 (list (concat "^[*]+ +\\<\\("
4122 (mapconcat 'regexp-quote org-done-keywords "\\|")
4123 "\\)\\>")
4124 '(1 'org-done t)))
4125 ;; Table stuff
4126 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
4127 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4128 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
4129 (if org-format-transports-properties-p
4130 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4131 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4133 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4134 ;; Now set the full font-lock-keywords
4135 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4136 (org-set-local 'font-lock-defaults
4137 '(org-font-lock-keywords t nil nil backward-paragraph))
4138 (kill-local-variable 'font-lock-keywords) nil))
4140 (defvar org-m nil)
4141 (defvar org-l nil)
4142 (defvar org-f nil)
4143 (defun org-get-level-face (n)
4144 "Get the right face for match N in font-lock matching of healdines."
4145 (setq org-l (- (match-end 2) (match-beginning 1)))
4146 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4147 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
4148 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
4149 (cond
4150 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4151 ((eq n 2) org-f)
4152 (t (if org-level-color-stars-only nil org-f))))
4154 (defun org-unfontify-region (beg end &optional maybe_loudly)
4155 "Remove fontification and activation overlays from links."
4156 (font-lock-default-unfontify-region beg end)
4157 (let* ((buffer-undo-list t)
4158 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4159 (inhibit-modification-hooks t)
4160 deactivate-mark buffer-file-name buffer-file-truename)
4161 (remove-text-properties beg end
4162 '(mouse-face t keymap t org-linked-text t
4163 rear-nonsticky t
4164 invisible t intangible t))))
4166 ;;;; Visibility cycling, including org-goto and indirect buffer
4168 ;;; Cycling
4170 (defvar org-cycle-global-status nil)
4171 (make-variable-buffer-local 'org-cycle-global-status)
4172 (defvar org-cycle-subtree-status nil)
4173 (make-variable-buffer-local 'org-cycle-subtree-status)
4175 ;;;###autoload
4176 (defun org-cycle (&optional arg)
4177 "Visibility cycling for Org-mode.
4179 - When this function is called with a prefix argument, rotate the entire
4180 buffer through 3 states (global cycling)
4181 1. OVERVIEW: Show only top-level headlines.
4182 2. CONTENTS: Show all headlines of all levels, but no body text.
4183 3. SHOW ALL: Show everything.
4185 - When point is at the beginning of a headline, rotate the subtree started
4186 by this line through 3 different states (local cycling)
4187 1. FOLDED: Only the main headline is shown.
4188 2. CHILDREN: The main headline and the direct children are shown.
4189 From this state, you can move to one of the children
4190 and zoom in further.
4191 3. SUBTREE: Show the entire subtree, including body text.
4193 - When there is a numeric prefix, go up to a heading with level ARG, do
4194 a `show-subtree' and return to the previous cursor position. If ARG
4195 is negative, go up that many levels.
4197 - When point is not at the beginning of a headline, execute
4198 `indent-relative', like TAB normally does. See the option
4199 `org-cycle-emulate-tab' for details.
4201 - Special case: if point is the the beginning of the buffer and there is
4202 no headline in line 1, this function will act as if called with prefix arg."
4203 (interactive "P")
4204 (let* ((outline-regexp
4205 (if (and (org-mode-p) org-cycle-include-plain-lists)
4206 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4207 outline-regexp))
4208 (bob-special (and org-cycle-global-at-bob (bobp)
4209 (not (looking-at outline-regexp))))
4210 (org-cycle-hook
4211 (if bob-special
4212 (delq 'org-optimize-window-after-visibility-change
4213 (copy-sequence org-cycle-hook))
4214 org-cycle-hook))
4215 (pos (point)))
4217 (if (or bob-special (equal arg '(4)))
4218 ;; special case: use global cycling
4219 (setq arg t))
4221 (cond
4223 ((org-at-table-p 'any)
4224 ;; Enter the table or move to the next field in the table
4225 (or (org-table-recognize-table.el)
4226 (progn
4227 (if arg (org-table-edit-field t)
4228 (org-table-justify-field-maybe)
4229 (call-interactively 'org-table-next-field)))))
4231 ((eq arg t) ;; Global cycling
4233 (cond
4234 ((and (eq last-command this-command)
4235 (eq org-cycle-global-status 'overview))
4236 ;; We just created the overview - now do table of contents
4237 ;; This can be slow in very large buffers, so indicate action
4238 (message "CONTENTS...")
4239 (org-content)
4240 (message "CONTENTS...done")
4241 (setq org-cycle-global-status 'contents)
4242 (run-hook-with-args 'org-cycle-hook 'contents))
4244 ((and (eq last-command this-command)
4245 (eq org-cycle-global-status 'contents))
4246 ;; We just showed the table of contents - now show everything
4247 (show-all)
4248 (message "SHOW ALL")
4249 (setq org-cycle-global-status 'all)
4250 (run-hook-with-args 'org-cycle-hook 'all))
4253 ;; Default action: go to overview
4254 (org-overview)
4255 (message "OVERVIEW")
4256 (setq org-cycle-global-status 'overview)
4257 (run-hook-with-args 'org-cycle-hook 'overview))))
4259 ((integerp arg)
4260 ;; Show-subtree, ARG levels up from here.
4261 (save-excursion
4262 (org-back-to-heading)
4263 (outline-up-heading (if (< arg 0) (- arg)
4264 (- (funcall outline-level) arg)))
4265 (org-show-subtree)))
4267 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4268 ;; At a heading: rotate between three different views
4269 (org-back-to-heading)
4270 (let ((goal-column 0) eoh eol eos)
4271 ;; First, some boundaries
4272 (save-excursion
4273 (org-back-to-heading)
4274 (save-excursion
4275 (beginning-of-line 2)
4276 (while (and (not (eobp)) ;; this is like `next-line'
4277 (get-char-property (1- (point)) 'invisible))
4278 (beginning-of-line 2)) (setq eol (point)))
4279 (outline-end-of-heading) (setq eoh (point))
4280 (org-end-of-subtree t)
4281 (skip-chars-forward " \t\n")
4282 (beginning-of-line 1) ; in case this is an item
4283 (setq eos (1- (point))))
4284 ;; Find out what to do next and set `this-command'
4285 (cond
4286 ((= eos eoh)
4287 ;; Nothing is hidden behind this heading
4288 (message "EMPTY ENTRY")
4289 (setq org-cycle-subtree-status nil))
4290 ((>= eol eos)
4291 ;; Entire subtree is hidden in one line: open it
4292 (org-show-entry)
4293 (show-children)
4294 (message "CHILDREN")
4295 (setq org-cycle-subtree-status 'children)
4296 (run-hook-with-args 'org-cycle-hook 'children))
4297 ((and (eq last-command this-command)
4298 (eq org-cycle-subtree-status 'children))
4299 ;; We just showed the children, now show everything.
4300 (org-show-subtree)
4301 (message "SUBTREE")
4302 (setq org-cycle-subtree-status 'subtree)
4303 (run-hook-with-args 'org-cycle-hook 'subtree))
4305 ;; Default action: hide the subtree.
4306 (hide-subtree)
4307 (message "FOLDED")
4308 (setq org-cycle-subtree-status 'folded)
4309 (run-hook-with-args 'org-cycle-hook 'folded)))))
4311 ;; TAB emulation
4312 (buffer-read-only (org-back-to-heading))
4314 ((org-try-cdlatex-tab))
4316 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4317 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4318 (or (and (eq org-cycle-emulate-tab 'white)
4319 (= (match-end 0) (point-at-eol)))
4320 (and (eq org-cycle-emulate-tab 'whitestart)
4321 (>= (match-end 0) pos))))
4323 (eq org-cycle-emulate-tab t))
4324 (if (and (looking-at "[ \n\r\t]")
4325 (string-match "^[ \t]*$" (buffer-substring
4326 (point-at-bol) (point))))
4327 (progn
4328 (beginning-of-line 1)
4329 (and (looking-at "[ \t]+") (replace-match ""))))
4330 (indent-relative))
4332 (t (save-excursion
4333 (org-back-to-heading)
4334 (org-cycle))))))
4336 ;;;###autoload
4337 (defun org-global-cycle (&optional arg)
4338 "Cycle the global visibility. For details see `org-cycle'."
4339 (interactive "P")
4340 (let ((org-cycle-include-plain-lists
4341 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4342 (if (integerp arg)
4343 (progn
4344 (show-all)
4345 (hide-sublevels arg)
4346 (setq org-cycle-global-status 'contents))
4347 (org-cycle '(4)))))
4349 (defun org-overview ()
4350 "Switch to overview mode, shoing only top-level headlines.
4351 Really, this shows all headlines with level equal or greater than the level
4352 of the first headline in the buffer. This is important, because if the
4353 first headline is not level one, then (hide-sublevels 1) gives confusing
4354 results."
4355 (interactive)
4356 (let ((level (save-excursion
4357 (goto-char (point-min))
4358 (if (re-search-forward (concat "^" outline-regexp) nil t)
4359 (progn
4360 (goto-char (match-beginning 0))
4361 (funcall outline-level))))))
4362 (and level (hide-sublevels level))))
4364 (defun org-content (&optional arg)
4365 "Show all headlines in the buffer, like a table of contents.
4366 With numerical argument N, show content up to level N."
4367 (interactive "P")
4368 (save-excursion
4369 ;; Visit all headings and show their offspring
4370 (and (integerp arg) (org-overview))
4371 (goto-char (point-max))
4372 (catch 'exit
4373 (while (and (progn (condition-case nil
4374 (outline-previous-visible-heading 1)
4375 (error (goto-char (point-min))))
4377 (looking-at outline-regexp))
4378 (if (integerp arg)
4379 (show-children (1- arg))
4380 (show-branches))
4381 (if (bobp) (throw 'exit nil))))))
4384 (defun org-optimize-window-after-visibility-change (state)
4385 "Adjust the window after a change in outline visibility.
4386 This function is the default value of the hook `org-cycle-hook'."
4387 (when (get-buffer-window (current-buffer))
4388 (cond
4389 ((eq state 'overview) (org-first-headline-recenter 1))
4390 ((eq state 'content) nil)
4391 ((eq state 'all) nil)
4392 ((eq state 'folded) nil)
4393 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4394 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4397 (defun org-cycle-show-empty-lines (state)
4398 "Show empty lines above all visible headlines.
4399 The region to be covered depends on STATE when called through
4400 `org-cycle-hook'. Lisp program can use t for STATE to get the
4401 entire buffer covered. Note that an empty line is only shown if there
4402 are at least `org-cycle-separator-lines' empty lines before the headeline."
4403 (when (> org-cycle-separator-lines 0)
4404 (save-excursion
4405 (let* ((n org-cycle-separator-lines)
4406 (re (cond
4407 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4408 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4409 (t (let ((ns (number-to-string (- n 2))))
4410 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4411 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4412 beg end)
4413 (cond
4414 ((memq state '(overview content t))
4415 (setq beg (point-min) end (point-max)))
4416 ((memq state '(children))
4417 (setq beg (point) end (org-end-of-subtree t t))))
4418 (when beg
4419 (goto-char beg)
4420 (while (re-search-forward re end t)
4421 (if (not (get-char-property (match-end 1) 'invisible))
4422 (outline-flag-region
4423 (match-beginning 1) (match-end 1) nil))))))))
4425 (defun org-subtree-end-visible-p ()
4426 "Is the end of the current subtree visible?"
4427 (pos-visible-in-window-p
4428 (save-excursion (org-end-of-subtree t) (point))))
4430 (defun org-first-headline-recenter (&optional N)
4431 "Move cursor to the first headline and recenter the headline.
4432 Optional argument N means, put the headline into the Nth line of the window."
4433 (goto-char (point-min))
4434 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4435 (beginning-of-line)
4436 (recenter (prefix-numeric-value N))))
4438 ;;; Org-goto
4440 (defvar org-goto-window-configuration nil)
4441 (defvar org-goto-marker nil)
4442 (defvar org-goto-map (make-sparse-keymap))
4443 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4444 (while (setq cmd (pop cmds))
4445 (substitute-key-definition cmd cmd org-goto-map global-map)))
4446 (org-defkey org-goto-map "\C-m" 'org-goto-ret)
4447 (org-defkey org-goto-map [(left)] 'org-goto-left)
4448 (org-defkey org-goto-map [(right)] 'org-goto-right)
4449 (org-defkey org-goto-map [(?q)] 'org-goto-quit)
4450 (org-defkey org-goto-map [(control ?g)] 'org-goto-quit)
4451 (org-defkey org-goto-map "\C-i" 'org-cycle)
4452 (org-defkey org-goto-map [(tab)] 'org-cycle)
4453 (org-defkey org-goto-map [(down)] 'outline-next-visible-heading)
4454 (org-defkey org-goto-map [(up)] 'outline-previous-visible-heading)
4455 (org-defkey org-goto-map "n" 'outline-next-visible-heading)
4456 (org-defkey org-goto-map "p" 'outline-previous-visible-heading)
4457 (org-defkey org-goto-map "f" 'outline-forward-same-level)
4458 (org-defkey org-goto-map "b" 'outline-backward-same-level)
4459 (org-defkey org-goto-map "u" 'outline-up-heading)
4460 (org-defkey org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4461 (org-defkey org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4462 (org-defkey org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4463 (org-defkey org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4464 (org-defkey org-goto-map "\C-c\C-u" 'outline-up-heading)
4465 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4466 (while l (org-defkey org-goto-map (int-to-string (pop l)) 'digit-argument)))
4468 (defconst org-goto-help
4469 "Select a location to jump to, press RET
4470 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4472 (defun org-goto ()
4473 "Go to a different location of the document, keeping current visibility.
4475 When you want to go to a different location in a document, the fastest way
4476 is often to fold the entire buffer and then dive into the tree. This
4477 method has the disadvantage, that the previous location will be folded,
4478 which may not be what you want.
4480 This command works around this by showing a copy of the current buffer in
4481 overview mode. You can dive into the tree in that copy, to find the
4482 location you want to reach. When pressing RET, the command returns to the
4483 original buffer in which the visibility is still unchanged. It then jumps
4484 to the new location, making it and the headline hierarchy above it visible."
4485 (interactive)
4486 (let* ((org-goto-start-pos (point))
4487 (selected-point
4488 (org-get-location (current-buffer) org-goto-help)))
4489 (if selected-point
4490 (progn
4491 (org-mark-ring-push org-goto-start-pos)
4492 (goto-char selected-point)
4493 (if (or (org-invisible-p) (org-invisible-p2))
4494 (org-show-context 'org-goto)))
4495 (error "Quit"))))
4497 (defvar org-selected-point nil) ; dynamically scoped parameter
4499 (defun org-get-location (buf help)
4500 "Let the user select a location in the Org-mode buffer BUF.
4501 This function uses a recursive edit. It returns the selected position
4502 or nil."
4503 (let (org-selected-point)
4504 (save-excursion
4505 (save-window-excursion
4506 (delete-other-windows)
4507 (switch-to-buffer (get-buffer-create "*org-goto*"))
4508 (with-output-to-temp-buffer "*Help*"
4509 (princ help))
4510 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4511 (setq buffer-read-only nil)
4512 (erase-buffer)
4513 (insert-buffer-substring buf)
4514 (let ((org-startup-truncated t)
4515 (org-startup-folded t)
4516 (org-startup-align-all-tables nil))
4517 (org-mode))
4518 (setq buffer-read-only t)
4519 (if (and (boundp 'org-goto-start-pos)
4520 (integer-or-marker-p org-goto-start-pos))
4521 (let ((org-show-hierarchy-above t)
4522 (org-show-siblings t)
4523 (org-show-following-heading t))
4524 (goto-char org-goto-start-pos)
4525 (and (org-invisible-p) (org-show-context)))
4526 (goto-char (point-min)))
4527 (org-beginning-of-line)
4528 (message "Select location and press RET")
4529 ;; now we make sure that during selection, ony very few keys work
4530 ;; and that it is impossible to switch to another window.
4531 (let ((gm (current-global-map))
4532 (overriding-local-map org-goto-map))
4533 (unwind-protect
4534 (progn
4535 (use-global-map org-goto-map)
4536 (recursive-edit))
4537 (use-global-map gm)))))
4538 (kill-buffer "*org-goto*")
4539 org-selected-point))
4541 (defun org-goto-ret (&optional arg)
4542 "Finish `org-goto' by going to the new location."
4543 (interactive "P")
4544 (setq org-selected-point (point)
4545 current-prefix-arg arg)
4546 (throw 'exit nil))
4548 (defun org-goto-left ()
4549 "Finish `org-goto' by going to the new location."
4550 (interactive)
4551 (if (org-on-heading-p)
4552 (progn
4553 (beginning-of-line 1)
4554 (setq org-selected-point (point)
4555 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4556 (throw 'exit nil))
4557 (error "Not on a heading")))
4559 (defun org-goto-right ()
4560 "Finish `org-goto' by going to the new location."
4561 (interactive)
4562 (if (org-on-heading-p)
4563 (progn
4564 (outline-end-of-subtree)
4565 (or (eobp) (forward-char 1))
4566 (setq org-selected-point (point)
4567 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4568 (throw 'exit nil))
4569 (error "Not on a heading")))
4571 (defun org-goto-quit ()
4572 "Finish `org-goto' without cursor motion."
4573 (interactive)
4574 (setq org-selected-point nil)
4575 (throw 'exit nil))
4577 ;;; Indirect buffer display of subtrees
4579 (defvar org-indirect-dedicated-frame nil
4580 "This is the frame being used for indirect tree display.")
4581 (defvar org-last-indirect-buffer nil)
4583 (defun org-tree-to-indirect-buffer (&optional arg)
4584 "Create indirect buffer and narrow it to current subtree.
4585 With numerical prefix ARG, go up to this level and then take that tree.
4586 If ARG is negative, go up that many levels.
4587 Normally this command removes the indirect buffer previously made
4588 with this command. However, when called with a C-u prefix, the last buffer
4589 is kept so that you can work with several indirect buffers at the same time.
4590 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4591 requests that a new frame be made for the new buffer, so that the dedicated
4592 frame is not changed."
4593 (interactive "P")
4594 (let ((cbuf (current-buffer))
4595 (cwin (selected-window))
4596 (pos (point))
4597 beg end level heading ibuf)
4598 (save-excursion
4599 (org-back-to-heading t)
4600 (when (numberp arg)
4601 (setq level (org-outline-level))
4602 (if (< arg 0) (setq arg (+ level arg)))
4603 (while (> (setq level (org-outline-level)) arg)
4604 (outline-up-heading 1 t)))
4605 (setq beg (point)
4606 heading (org-get-heading))
4607 (org-end-of-subtree t) (setq end (point)))
4608 (if (and (not arg)
4609 (buffer-live-p org-last-indirect-buffer))
4610 (kill-buffer org-last-indirect-buffer))
4611 (setq ibuf (org-get-indirect-buffer cbuf)
4612 org-last-indirect-buffer ibuf)
4613 (cond
4614 ((or (eq org-indirect-buffer-display 'new-frame)
4615 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4616 (select-frame (make-frame))
4617 (delete-other-windows)
4618 (switch-to-buffer ibuf)
4619 (org-set-frame-title heading))
4620 ((eq org-indirect-buffer-display 'dedicated-frame)
4621 (raise-frame
4622 (select-frame (or (and org-indirect-dedicated-frame
4623 (frame-live-p org-indirect-dedicated-frame)
4624 org-indirect-dedicated-frame)
4625 (setq org-indirect-dedicated-frame (make-frame)))))
4626 (delete-other-windows)
4627 (switch-to-buffer ibuf)
4628 (org-set-frame-title (concat "Indirect: " heading)))
4629 ((eq org-indirect-buffer-display 'current-window)
4630 (switch-to-buffer ibuf))
4631 ((eq org-indirect-buffer-display 'other-window)
4632 (pop-to-buffer ibuf))
4633 (t (error "Invalid value.")))
4634 (if (featurep 'xemacs)
4635 (save-excursion (org-mode) (turn-on-font-lock)))
4636 (narrow-to-region beg end)
4637 (show-all)
4638 (goto-char pos)
4639 (and (window-live-p cwin) (select-window cwin))))
4641 (defun org-get-indirect-buffer (&optional buffer)
4642 (setq buffer (or buffer (current-buffer)))
4643 (let ((n 1) (base (buffer-name buffer)) bname)
4644 (while (buffer-live-p
4645 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4646 (setq n (1+ n)))
4647 (condition-case nil
4648 (make-indirect-buffer buffer bname 'clone)
4649 (error (make-indirect-buffer buffer bname)))))
4651 (defun org-set-frame-title (title)
4652 "Set the title of the current frame to the string TITLE."
4653 ;; FIXME: how to name a single frame in XEmacs???
4654 (unless (featurep 'xemacs)
4655 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4657 ;;;; Structure editing
4659 ;;; Inserting headlines
4661 (defun org-insert-heading (&optional force-heading)
4662 "Insert a new heading or item with same depth at point.
4663 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4664 If point is at the beginning of a headline, insert a sibling before the
4665 current headline. If point is in the middle of a headline, split the headline
4666 at that position and make the rest of the headline part of the sibling below
4667 the current headline."
4668 (interactive "P")
4669 (if (= (buffer-size) 0)
4670 (insert "\n* ")
4671 (when (or force-heading (not (org-insert-item)))
4672 (let* ((head (save-excursion
4673 (condition-case nil
4674 (progn
4675 (org-back-to-heading)
4676 (match-string 0))
4677 (error "*"))))
4678 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4679 pos)
4680 (cond
4681 ((and (org-on-heading-p) (bolp)
4682 (or (bobp)
4683 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4684 (open-line (if blank 2 1)))
4685 ((and (bolp)
4686 (or (bobp)
4687 (save-excursion
4688 (backward-char 1) (not (org-invisible-p)))))
4689 nil)
4690 (t (newline (if blank 2 1))))
4691 (insert head) (just-one-space)
4692 (setq pos (point))
4693 (end-of-line 1)
4694 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4695 (run-hooks 'org-insert-heading-hook)))))
4698 (defun org-insert-todo-heading (arg)
4699 "Insert a new heading with the same level and TODO state as current heading.
4700 If the heading has no TODO state, or if the state is DONE, use the first
4701 state (TODO by default). Also with prefix arg, force first state."
4702 (interactive "P")
4703 (when (not (org-insert-item 'checkbox))
4704 (org-insert-heading)
4705 (save-excursion
4706 (org-back-to-heading)
4707 (outline-previous-heading)
4708 (looking-at org-todo-line-regexp))
4709 (if (or arg
4710 (not (match-beginning 2))
4711 (member (match-string 2) org-done-keywords))
4712 (insert (car org-todo-keywords-1) " ")
4713 (insert (match-string 2) " "))))
4715 ;;; Promotion and Demotion
4717 (defun org-promote-subtree ()
4718 "Promote the entire subtree.
4719 See also `org-promote'."
4720 (interactive)
4721 (save-excursion
4722 (org-map-tree 'org-promote))
4723 (org-fix-position-after-promote))
4725 (defun org-demote-subtree ()
4726 "Demote the entire subtree. See `org-demote'.
4727 See also `org-promote'."
4728 (interactive)
4729 (save-excursion
4730 (org-map-tree 'org-demote))
4731 (org-fix-position-after-promote))
4734 (defun org-do-promote ()
4735 "Promote the current heading higher up the tree.
4736 If the region is active in `transient-mark-mode', promote all headings
4737 in the region."
4738 (interactive)
4739 (save-excursion
4740 (if (org-region-active-p)
4741 (org-map-region 'org-promote (region-beginning) (region-end))
4742 (org-promote)))
4743 (org-fix-position-after-promote))
4745 (defun org-do-demote ()
4746 "Demote the current heading lower down the tree.
4747 If the region is active in `transient-mark-mode', demote all headings
4748 in the region."
4749 (interactive)
4750 (save-excursion
4751 (if (org-region-active-p)
4752 (org-map-region 'org-demote (region-beginning) (region-end))
4753 (org-demote)))
4754 (org-fix-position-after-promote))
4756 (defun org-fix-position-after-promote ()
4757 "Make sure that after pro/demotion cursor position is right."
4758 (let ((pos (point)))
4759 (when (save-excursion
4760 (beginning-of-line 1)
4761 (looking-at org-todo-line-regexp)
4762 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4763 (cond ((eobp) (insert " "))
4764 ((eolp) (insert " "))
4765 ((equal (char-after) ?\ ) (forward-char 1))))))
4767 (defun org-get-legal-level (level &optional change)
4768 "Rectify a level change under the influence of `org-odd-levels-only'
4769 LEVEL is a current level, CHANGE is by how much the level should be
4770 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4771 even level numbers will become the next higher odd number."
4772 (if org-odd-levels-only
4773 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4774 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4775 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4776 (max 1 (+ level change))))
4778 (defun org-promote ()
4779 "Promote the current heading higher up the tree.
4780 If the region is active in `transient-mark-mode', promote all headings
4781 in the region."
4782 (org-back-to-heading t)
4783 (let* ((level (save-match-data (funcall outline-level)))
4784 (up-head (make-string (org-get-legal-level level -1) ?*))
4785 (diff (abs (- level (length up-head)))))
4786 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4787 (replace-match up-head nil t)
4788 ;; Fixup tag positioning
4789 (and org-auto-align-tags (org-set-tags nil t))
4790 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4792 (defun org-demote ()
4793 "Demote the current heading lower down the tree.
4794 If the region is active in `transient-mark-mode', demote all headings
4795 in the region."
4796 (org-back-to-heading t)
4797 (let* ((level (save-match-data (funcall outline-level)))
4798 (down-head (make-string (org-get-legal-level level 1) ?*))
4799 (diff (abs (- level (length down-head)))))
4800 (replace-match down-head nil t)
4801 ;; Fixup tag positioning
4802 (and org-auto-align-tags (org-set-tags nil t))
4803 (if org-adapt-indentation (org-fixup-indentation diff))))
4805 (defun org-map-tree (fun)
4806 "Call FUN for every heading underneath the current one."
4807 (org-back-to-heading)
4808 (let ((level (funcall outline-level)))
4809 (save-excursion
4810 (funcall fun)
4811 (while (and (progn
4812 (outline-next-heading)
4813 (> (funcall outline-level) level))
4814 (not (eobp)))
4815 (funcall fun)))))
4817 (defun org-map-region (fun beg end)
4818 "Call FUN for every heading between BEG and END."
4819 (let ((org-ignore-region t))
4820 (save-excursion
4821 (setq end (copy-marker end))
4822 (goto-char beg)
4823 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4824 (< (point) end))
4825 (funcall fun))
4826 (while (and (progn
4827 (outline-next-heading)
4828 (< (point) end))
4829 (not (eobp)))
4830 (funcall fun)))))
4832 (defun org-fixup-indentation (diff)
4833 "Change the indentation in the current entry by DIFF
4834 However, if any line in the current entry has no indentation, or if it
4835 would end up with no indentation after the change, nothing at all is done."
4836 (save-excursion
4837 (let ((end (save-excursion (outline-next-heading)
4838 (point-marker)))
4839 (prohibit (if (> diff 0)
4840 "^\\S-"
4841 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4842 col)
4843 (unless (save-excursion (re-search-forward prohibit end t))
4844 (while (re-search-forward "^[ \t]+" end t)
4845 (goto-char (match-end 0))
4846 (setq col (current-column))
4847 (if (< diff 0) (replace-match ""))
4848 (indent-to (+ diff col))))
4849 (move-marker end nil))))
4851 (defun org-convert-to-odd-levels ()
4852 "Convert an org-mode file with all levels allowed to one with odd levels.
4853 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4854 level 5 etc."
4855 (interactive)
4856 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4857 (let ((org-odd-levels-only nil) n)
4858 (save-excursion
4859 (goto-char (point-min))
4860 (while (re-search-forward "^\\*\\*+" nil t)
4861 (setq n (1- (length (match-string 0))))
4862 (while (>= (setq n (1- n)) 0)
4863 (org-demote))
4864 (end-of-line 1))))))
4867 (defun org-convert-to-oddeven-levels ()
4868 "Convert an org-mode file with only odd levels to one with odd and even levels.
4869 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4870 section with an even level, conversion would destroy the structure of the file. An error
4871 is signaled in this case."
4872 (interactive)
4873 (goto-char (point-min))
4874 ;; First check if there are no even levels
4875 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
4876 (org-show-context t)
4877 (error "Not all levels are odd in this file. Conversion not possible."))
4878 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4879 (let ((org-odd-levels-only nil) n)
4880 (save-excursion
4881 (goto-char (point-min))
4882 (while (re-search-forward "^\\*\\*+" nil t)
4883 (setq n (/ (length (match-string 0)) 2))
4884 (while (>= (setq n (1- n)) 0)
4885 (org-promote))
4886 (end-of-line 1))))))
4888 (defun org-tr-level (n)
4889 "Make N odd if required."
4890 (if org-odd-levels-only (1+ (/ n 2)) n))
4892 ;;; Vertical tree motion, cutting and pasting of subtrees
4894 (defun org-move-subtree-up (&optional arg)
4895 "Move the current subtree up past ARG headlines of the same level."
4896 (interactive "p")
4897 (org-move-subtree-down (- (prefix-numeric-value arg))))
4899 (defun org-move-subtree-down (&optional arg)
4900 "Move the current subtree down past ARG headlines of the same level."
4901 (interactive "p")
4902 (setq arg (prefix-numeric-value arg))
4903 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4904 'outline-get-last-sibling))
4905 (ins-point (make-marker))
4906 (cnt (abs arg))
4907 beg end txt folded)
4908 ;; Select the tree
4909 (org-back-to-heading)
4910 (setq beg (point))
4911 (save-match-data
4912 (save-excursion (outline-end-of-heading)
4913 (setq folded (org-invisible-p)))
4914 (outline-end-of-subtree))
4915 (outline-next-heading)
4916 (setq end (point))
4917 ;; Find insertion point, with error handling
4918 (goto-char beg)
4919 (while (> cnt 0)
4920 (or (and (funcall movfunc) (looking-at outline-regexp))
4921 (progn (goto-char beg)
4922 (error "Cannot move past superior level or buffer limit")))
4923 (setq cnt (1- cnt)))
4924 (if (> arg 0)
4925 ;; Moving forward - still need to move over subtree
4926 (progn (outline-end-of-subtree)
4927 (outline-next-heading)
4928 (if (not (or (looking-at (concat "^" outline-regexp))
4929 (bolp)))
4930 (newline))))
4931 (move-marker ins-point (point))
4932 (setq txt (buffer-substring beg end))
4933 (delete-region beg end)
4934 (insert txt)
4935 (or (bolp) (insert "\n"))
4936 (goto-char ins-point)
4937 (if folded (hide-subtree))
4938 (move-marker ins-point nil)))
4940 (defvar org-subtree-clip ""
4941 "Clipboard for cut and paste of subtrees.
4942 This is actually only a copy of the kill, because we use the normal kill
4943 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4945 (defvar org-subtree-clip-folded nil
4946 "Was the last copied subtree folded?
4947 This is used to fold the tree back after pasting.")
4949 (defun org-cut-subtree ()
4950 "Cut the current subtree into the clipboard.
4951 This is a short-hand for marking the subtree and then cutting it."
4952 (interactive)
4953 (org-copy-subtree 'cut))
4955 (defun org-copy-subtree (&optional cut)
4956 "Cut the current subtree into the clipboard.
4957 This is a short-hand for marking the subtree and then copying it.
4958 If CUT is non-nil, actually cut the subtree."
4959 (interactive)
4960 (let (beg end folded)
4961 (org-back-to-heading)
4962 (setq beg (point))
4963 (save-match-data
4964 (save-excursion (outline-end-of-heading)
4965 (setq folded (org-invisible-p)))
4966 (outline-end-of-subtree))
4967 (if (equal (char-after) ?\n) (forward-char 1))
4968 (setq end (point))
4969 (goto-char beg)
4970 (when (> end beg)
4971 (setq org-subtree-clip-folded folded)
4972 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4973 (setq org-subtree-clip (current-kill 0))
4974 (message "%s: Subtree with %d characters"
4975 (if cut "Cut" "Copied")
4976 (length org-subtree-clip)))))
4978 (defun org-paste-subtree (&optional level tree)
4979 "Paste the clipboard as a subtree, with modification of headline level.
4980 The entire subtree is promoted or demoted in order to match a new headline
4981 level. By default, the new level is derived from the visible headings
4982 before and after the insertion point, and taken to be the inferior headline
4983 level of the two. So if the previous visible heading is level 3 and the
4984 next is level 4 (or vice versa), level 4 will be used for insertion.
4985 This makes sure that the subtree remains an independent subtree and does
4986 not swallow low level entries.
4988 You can also force a different level, either by using a numeric prefix
4989 argument, or by inserting the heading marker by hand. For example, if the
4990 cursor is after \"*****\", then the tree will be shifted to level 5.
4992 If you want to insert the tree as is, just use \\[yank].
4994 If optional TREE is given, use this text instead of the kill ring."
4995 (interactive "P")
4996 (unless (org-kill-is-subtree-p tree)
4997 (error
4998 (substitute-command-keys
4999 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5000 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5001 (^re (concat "^\\(" outline-regexp "\\)"))
5002 (re (concat "\\(" outline-regexp "\\)"))
5003 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
5005 (old-level (if (string-match ^re txt)
5006 (- (match-end 0) (match-beginning 0))
5007 -1))
5008 (force-level (cond (level (prefix-numeric-value level))
5009 ((string-match
5010 ^re_ (buffer-substring (point-at-bol) (point)))
5011 (- (match-end 0) (match-beginning 0)))
5012 (t nil)))
5013 (previous-level (save-excursion
5014 (condition-case nil
5015 (progn
5016 (outline-previous-visible-heading 1)
5017 (if (looking-at re)
5018 (- (match-end 0) (match-beginning 0))
5020 (error 1))))
5021 (next-level (save-excursion
5022 (condition-case nil
5023 (progn
5024 (outline-next-visible-heading 1)
5025 (if (looking-at re)
5026 (- (match-end 0) (match-beginning 0))
5028 (error 1))))
5029 (new-level (or force-level (max previous-level next-level)))
5030 (shift (if (or (= old-level -1)
5031 (= new-level -1)
5032 (= old-level new-level))
5034 (- new-level old-level)))
5035 (shift1 shift)
5036 (delta (if (> shift 0) -1 1))
5037 (func (if (> shift 0) 'org-demote 'org-promote))
5038 (org-odd-levels-only nil)
5039 beg end)
5040 ;; Remove the forces level indicator
5041 (if force-level
5042 (delete-region (point-at-bol) (point)))
5043 ;; Make sure we start at the beginning of an empty line
5044 (if (not (bolp)) (insert "\n"))
5045 (if (not (looking-at "[ \t]*$"))
5046 (progn (insert "\n") (backward-char 1)))
5047 ;; Paste
5048 (setq beg (point))
5049 (if (string-match "[ \t\r\n]+\\'" txt)
5050 (setq txt (replace-match "\n" t t txt)))
5051 (insert txt)
5052 (setq end (point))
5053 (if (looking-at "[ \t\r\n]+")
5054 (replace-match "\n"))
5055 (goto-char beg)
5056 ;; Shift if necessary
5057 (if (= shift 0)
5058 (message "Pasted at level %d, without shift" new-level)
5059 (save-restriction
5060 (narrow-to-region beg end)
5061 (while (not (= shift 0))
5062 (org-map-region func (point-min) (point-max))
5063 (setq shift (+ delta shift)))
5064 (goto-char (point-min))
5065 (message "Pasted at level %d, with shift by %d levels"
5066 new-level shift1)))
5067 (if (and kill-ring
5068 (eq org-subtree-clip (current-kill 0))
5069 org-subtree-clip-folded)
5070 ;; The tree was folded before it was killed/copied
5071 (hide-subtree))))
5073 (defun org-kill-is-subtree-p (&optional txt)
5074 "Check if the current kill is an outline subtree, or a set of trees.
5075 Returns nil if kill does not start with a headline, or if the first
5076 headline level is not the largest headline level in the tree.
5077 So this will actually accept several entries of equal levels as well,
5078 which is OK for `org-paste-subtree'.
5079 If optional TXT is given, check this string instead of the current kill."
5080 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5081 (start-level (and kill
5082 (string-match (concat "\\`" outline-regexp) kill)
5083 (- (match-end 0) (match-beginning 0))))
5084 (re (concat "^" outline-regexp))
5085 (start 1))
5086 (if (not start-level)
5087 nil ;; does not even start with a heading
5088 (catch 'exit
5089 (while (setq start (string-match re kill (1+ start)))
5090 (if (< (- (match-end 0) (match-beginning 0)) start-level)
5091 (throw 'exit nil)))
5092 t))))
5094 (defun org-narrow-to-subtree ()
5095 "Narrow buffer to the current subtree."
5096 (interactive)
5097 (save-excursion
5098 (narrow-to-region
5099 (progn (org-back-to-heading) (point))
5100 (progn (org-end-of-subtree t t) (point)))))
5103 ;;; Outline Sorting
5105 (defun org-sort (with-case)
5106 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
5107 (interactive "P")
5108 (if (org-at-table-p)
5109 (org-call-with-arg 'org-table-sort-lines with-case)
5110 (org-call-with-arg 'org-sort-entries with-case)))
5112 (defun org-sort-entries (&optional with-case sorting-type)
5113 "Sort entries on a certain level of an outline tree.
5114 If there is an active region, the entries in the region are sorted.
5115 Else, if the cursor is before the first entry, sort the top-level items.
5116 Else, the children of the entry at point are sorted.
5118 Sorting can be alphabetically, numerically, and by date/time as given by
5119 the first time stamp in the entry. The command prompts for the sorting
5120 type unless it has been given to the function through the SORTING-TYPE
5121 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
5123 Comparing entries ignores case by default. However, with an optional argument
5124 WITH-CASE, the sorting considers case as well. With two prefix arguments
5125 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
5126 (interactive "P")
5127 (let ((unique (equal with-case '(16)))
5128 start beg end entries stars re re2 p nentries (nremoved 0)
5129 last txt what)
5130 ;; Find beginning and end of region to sort
5131 (cond
5132 ((org-region-active-p)
5133 ;; we will sort the region
5134 (setq end (region-end)
5135 what "region")
5136 (goto-char (region-beginning))
5137 (if (not (org-on-heading-p)) (outline-next-heading))
5138 (setq start (point)))
5139 ((or (org-on-heading-p)
5140 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5141 ;; we will sort the children of the current headline
5142 (org-back-to-heading)
5143 (setq start (point) end (org-end-of-subtree) what "children")
5144 (goto-char start)
5145 (show-subtree)
5146 (outline-next-heading))
5148 ;; we will sort the top-level entries in this file
5149 (goto-char (point-min))
5150 (or (org-on-heading-p) (outline-next-heading))
5151 (setq start (point) end (point-max) what "top-level")
5152 (goto-char start)
5153 (show-all)))
5154 (setq beg (point))
5155 (if (>= (point) end) (error "Nothing to sort"))
5156 (looking-at "\\(\\*+\\)")
5157 (setq stars (match-string 1)
5158 re (concat "^" (regexp-quote stars) " +")
5159 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5160 txt (buffer-substring beg end))
5161 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5162 (if (and (not (equal stars "*")) (string-match re2 txt))
5163 (error "Region to sort contains a level above the first entry"))
5164 ;; Make a list that can be sorted.
5165 ;; The car is the string for comparison, the cdr is the subtree
5166 (message "Sorting entries...")
5167 (setq entries
5168 (mapcar
5169 (lambda (x)
5170 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
5171 (cons (match-string 0 x) x))
5172 (org-split-string txt re)))
5174 ;; Sort the list
5175 (save-excursion
5176 (goto-char start)
5177 (setq entries (org-do-sort entries what with-case sorting-type)))
5179 ;; Delete the old stuff
5180 (goto-char beg)
5181 (kill-region beg end)
5182 (setq nentries (length entries))
5183 ;; Insert the sorted entries, and remove duplicates if this is required
5184 (while (setq p (pop entries))
5185 (if (and unique (equal last (setq last (org-trim (cdr p)))))
5186 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
5187 (insert stars " " (cdr p))))
5188 (goto-char start)
5189 (message "Sorting entries...done (%d entries%s)"
5190 nentries
5191 (if unique (format ", %d duplicates removed" nremoved) ""))))
5193 (defun org-do-sort (table what &optional with-case sorting-type)
5194 "Sort TABLE of WHAT according to SORTING-TYPE.
5195 The user will be prompted for the SORTING-TYPE if the call to this
5196 function does not specify it. WHAT is only for the prompt, to indicate
5197 what is being sorted. The sorting key will be extracted from
5198 the car of the elements of the table.
5199 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5200 (unless sorting-type
5201 (message
5202 "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
5203 what)
5204 (setq sorting-type (read-char-exclusive)))
5205 (let ((dcst (downcase sorting-type))
5206 extractfun comparefun)
5207 ;; Define the appropriate functions
5208 (cond
5209 ((= dcst ?n)
5210 (setq extractfun 'string-to-number
5211 comparefun (if (= dcst sorting-type) '< '>)))
5212 ((= dcst ?a)
5213 (setq extractfun (if with-case 'identity 'downcase)
5214 comparefun (if (= dcst sorting-type)
5215 'string<
5216 (lambda (a b) (and (not (string< a b))
5217 (not (string= a b)))))))
5218 ((= dcst ?t)
5219 (setq extractfun
5220 (lambda (x)
5221 (if (string-match org-ts-regexp x)
5222 (time-to-seconds
5223 (org-time-string-to-time (match-string 0 x)))
5225 comparefun (if (= dcst sorting-type) '< '>)))
5226 (t (error "Invalid sorting type `%c'" sorting-type)))
5228 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5229 table)
5230 (lambda (a b) (funcall comparefun (car a) (car b))))))
5232 ;;;; Plain list items, including checkboxes
5234 ;;; Plain list items
5236 (defun org-at-item-p ()
5237 "Is point in a line starting a hand-formatted item?"
5238 (let ((llt org-plain-list-ordered-item-terminator))
5239 (save-excursion
5240 (goto-char (point-at-bol))
5241 (looking-at
5242 (cond
5243 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5244 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5245 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5246 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5249 (defun org-in-item-p ()
5250 "It the cursor inside a plain list item.
5251 Does not have to be the first line."
5252 (save-excursion
5253 (condition-case nil
5254 (progn
5255 (org-beginning-of-item)
5256 (org-at-item-p)
5258 (error nil))))
5260 (defun org-insert-item (&optional checkbox)
5261 "Insert a new item at the current level.
5262 Return t when things worked, nil when we are not in an item."
5263 (when (save-excursion
5264 (condition-case nil
5265 (progn
5266 (org-beginning-of-item)
5267 (org-at-item-p)
5268 (if (org-invisible-p) (error "Invisible item"))
5270 (error nil)))
5271 (let* ((bul (match-string 0))
5272 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5273 (match-end 0)))
5274 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5275 pos)
5276 (cond
5277 ((and (org-at-item-p) (<= (point) eow))
5278 ;; before the bullet
5279 (beginning-of-line 1)
5280 (open-line (if blank 2 1)))
5281 ((<= (point) eow)
5282 (beginning-of-line 1))
5283 (t (newline (if blank 2 1))))
5284 (insert bul (if checkbox "[ ]" ""))
5285 (just-one-space)
5286 (setq pos (point))
5287 (end-of-line 1)
5288 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5289 (org-maybe-renumber-ordered-list)
5290 (and checkbox (org-update-checkbox-count-maybe))
5293 ;;; Checkboxes
5295 (defun org-at-item-checkbox-p ()
5296 "Is point at a line starting a plain-list item with a checklet?"
5297 (and (org-at-item-p)
5298 (save-excursion
5299 (goto-char (match-end 0))
5300 (skip-chars-forward " \t")
5301 (looking-at "\\[[ X]\\]"))))
5303 (defun org-toggle-checkbox (&optional arg)
5304 "Toggle the checkbox in the current line."
5305 (interactive "P")
5306 (catch 'exit
5307 (let (beg end status (firstnew 'unknown))
5308 (cond
5309 ((org-region-active-p)
5310 (setq beg (region-beginning) end (region-end)))
5311 ((org-on-heading-p)
5312 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5313 ((org-at-item-checkbox-p)
5314 (save-excursion
5315 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
5316 (throw 'exit t))
5317 (t (error "Not at a checkbox or heading, and no active region")))
5318 (save-excursion
5319 (goto-char beg)
5320 (while (< (point) end)
5321 (when (org-at-item-checkbox-p)
5322 (setq status (equal (match-string 0) "[X]"))
5323 (when (eq firstnew 'unknown)
5324 (setq firstnew (not status)))
5325 (replace-match
5326 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5327 (beginning-of-line 2)))))
5328 (org-update-checkbox-count-maybe))
5330 (defun org-update-checkbox-count-maybe ()
5331 "Update checkbox statistics unless turned off by user."
5332 (when org-provide-checkbox-statistics
5333 (org-update-checkbox-count)))
5335 (defun org-update-checkbox-count (&optional all)
5336 "Update the checkbox statistics in the current section.
5337 This will find all statistic cookies like [57%] and [6/12] and update them
5338 with the current numbers. With optional prefix argument ALL, do this for
5339 the whole buffer."
5340 (interactive "P")
5341 (save-excursion
5342 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5343 (beg (progn (outline-back-to-heading) (point)))
5344 (end (move-marker (make-marker)
5345 (progn (outline-next-heading) (point))))
5346 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5347 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
5348 b1 e1 f1 c-on c-off lim (cstat 0))
5349 (when all
5350 (goto-char (point-min))
5351 (outline-next-heading)
5352 (setq beg (point) end (point-max)))
5353 (goto-char beg)
5354 (while (re-search-forward re end t)
5355 (setq cstat (1+ cstat)
5356 b1 (match-beginning 0)
5357 e1 (match-end 0)
5358 f1 (match-beginning 1)
5359 lim (cond
5360 ((org-on-heading-p) (outline-next-heading) (point))
5361 ((org-at-item-p) (org-end-of-item) (point))
5362 (t nil))
5363 c-on 0 c-off 0)
5364 (goto-char e1)
5365 (when lim
5366 (while (re-search-forward re-box lim t)
5367 (if (equal (match-string 2) "[ ]")
5368 (setq c-off (1+ c-off))
5369 (setq c-on (1+ c-on))))
5370 (delete-region b1 e1)
5371 (goto-char b1)
5372 (insert (if f1
5373 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5374 (format "[%d/%d]" c-on (+ c-on c-off))))))
5375 (when (interactive-p)
5376 (message "Checkbox satistics updated %s (%d places)"
5377 (if all "in entire file" "in current outline entry") cstat)))))
5379 (defun org-get-checkbox-statistics-face ()
5380 "Select the face for checkbox statistics.
5381 The face will be `org-done' when all relevant boxes are checked. Otherwise
5382 it will be `org-todo'."
5383 (if (match-end 1)
5384 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5385 (if (and (> (match-end 2) (match-beginning 2))
5386 (equal (match-string 2) (match-string 3)))
5387 'org-done
5388 'org-todo)))
5390 (defun org-get-indentation (&optional line)
5391 "Get the indentation of the current line, interpreting tabs.
5392 When LINE is given, assume it represents a line and compute its indentation."
5393 (if line
5394 (if (string-match "^ *" (org-remove-tabs line))
5395 (match-end 0))
5396 (save-excursion
5397 (beginning-of-line 1)
5398 (skip-chars-forward " \t")
5399 (current-column))))
5401 (defun org-remove-tabs (s &optional width)
5402 "Replace tabulators in S with spaces.
5403 Assumes that s is a single line, starting in column 0."
5404 (setq width (or width tab-width))
5405 (while (string-match "\t" s)
5406 (setq s (replace-match
5407 (make-string
5408 (- (* width (/ (+ (match-beginning 0) width) width))
5409 (match-beginning 0)) ?\ )
5410 t t s)))
5413 (defun org-fix-indentation (line ind)
5414 "Fix indentation in LINE.
5415 IND is a cons cell with target and minimum indentation.
5416 If the current indenation in LINE is smaller than the minimum,
5417 leave it alone. If it is larger than ind, set it to the target."
5418 (let* ((l (org-remove-tabs line))
5419 (i (org-get-indentation l))
5420 (i1 (car ind)) (i2 (cdr ind)))
5421 (if (>= i i2) (setq l (substring line i2)))
5422 (if (> i1 0)
5423 (concat (make-string i1 ?\ ) l)
5424 l)))
5426 (defcustom org-empty-line-terminates-plain-lists nil
5427 "Non-nil means, an empty line ends all plain list levels.
5428 When nil, empty lines are part of the preceeding item."
5429 :group 'org-plain-lists
5430 :type 'boolean)
5432 (defun org-beginning-of-item ()
5433 "Go to the beginning of the current hand-formatted item.
5434 If the cursor is not in an item, throw an error."
5435 (interactive)
5436 (let ((pos (point))
5437 (limit (save-excursion
5438 (condition-case nil
5439 (progn
5440 (org-back-to-heading)
5441 (beginning-of-line 2) (point))
5442 (error (point-min)))))
5443 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5444 ind ind1)
5445 (if (org-at-item-p)
5446 (beginning-of-line 1)
5447 (beginning-of-line 1)
5448 (skip-chars-forward " \t")
5449 (setq ind (current-column))
5450 (if (catch 'exit
5451 (while t
5452 (beginning-of-line 0)
5453 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5455 (if (looking-at "[ \t]*$")
5456 (setq ind1 ind-empty)
5457 (skip-chars-forward " \t")
5458 (setq ind1 (current-column)))
5459 (if (< ind1 ind)
5460 (throw 'exit (org-at-item-p)))))
5462 (goto-char pos)
5463 (error "Not in an item")))))
5465 (defun org-end-of-item ()
5466 "Go to the end of the current hand-formatted item.
5467 If the cursor is not in an item, throw an error."
5468 (interactive)
5469 (let* ((pos (point))
5470 ind1
5471 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5472 (limit (save-excursion (outline-next-heading) (point)))
5473 (ind (save-excursion
5474 (org-beginning-of-item)
5475 (skip-chars-forward " \t")
5476 (current-column)))
5477 (end (catch 'exit
5478 (while t
5479 (beginning-of-line 2)
5480 (if (eobp) (throw 'exit (point)))
5481 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5482 (if (looking-at "[ \t]*$")
5483 (setq ind1 ind-empty)
5484 (skip-chars-forward " \t")
5485 (setq ind1 (current-column)))
5486 (if (<= ind1 ind)
5487 (throw 'exit (point-at-bol)))))))
5488 (if end
5489 (goto-char end)
5490 (goto-char pos)
5491 (error "Not in an item"))))
5493 (defun org-next-item ()
5494 "Move to the beginning of the next item in the current plain list.
5495 Error if not at a plain list, or if this is the last item in the list."
5496 (interactive)
5497 (let (ind ind1 (pos (point)))
5498 (org-beginning-of-item)
5499 (setq ind (org-get-indentation))
5500 (org-end-of-item)
5501 (setq ind1 (org-get-indentation))
5502 (unless (and (org-at-item-p) (= ind ind1))
5503 (goto-char pos)
5504 (error "On last item"))))
5506 (defun org-previous-item ()
5507 "Move to the beginning of the previous item in the current plain list.
5508 Error if not at a plain list, or if this is the last item in the list."
5509 (interactive)
5510 (let (beg ind (pos (point)))
5511 (org-beginning-of-item)
5512 (setq beg (point))
5513 (setq ind (org-get-indentation))
5514 (goto-char beg)
5515 (catch 'exit
5516 (while t
5517 (beginning-of-line 0)
5518 (if (looking-at "[ \t]*$")
5520 (if (<= (org-get-indentation) ind)
5521 (throw 'exit t)))))
5522 (condition-case nil
5523 (org-beginning-of-item)
5524 (error (goto-char pos)
5525 (error "On first item")))))
5527 (defun org-move-item-down ()
5528 "Move the plain list item at point down, i.e. swap with following item.
5529 Subitems (items with larger indentation) are considered part of the item,
5530 so this really moves item trees."
5531 (interactive)
5532 (let (beg end ind ind1 (pos (point)) txt)
5533 (org-beginning-of-item)
5534 (setq beg (point))
5535 (setq ind (org-get-indentation))
5536 (org-end-of-item)
5537 (setq end (point))
5538 (setq ind1 (org-get-indentation))
5539 (if (and (org-at-item-p) (= ind ind1))
5540 (progn
5541 (org-end-of-item)
5542 (setq txt (buffer-substring beg end))
5543 (save-excursion
5544 (delete-region beg end))
5545 (setq pos (point))
5546 (insert txt)
5547 (goto-char pos)
5548 (org-maybe-renumber-ordered-list))
5549 (goto-char pos)
5550 (error "Cannot move this item further down"))))
5552 (defun org-move-item-up (arg)
5553 "Move the plain list item at point up, i.e. swap with previous item.
5554 Subitems (items with larger indentation) are considered part of the item,
5555 so this really moves item trees."
5556 (interactive "p")
5557 (let (beg end ind ind1 (pos (point)) txt)
5558 (org-beginning-of-item)
5559 (setq beg (point))
5560 (setq ind (org-get-indentation))
5561 (org-end-of-item)
5562 (setq end (point))
5563 (goto-char beg)
5564 (catch 'exit
5565 (while t
5566 (beginning-of-line 0)
5567 (if (looking-at "[ \t]*$")
5568 (if org-empty-line-terminates-plain-lists
5569 (progn
5570 (goto-char pos)
5571 (error "Cannot move this item further up"))
5572 nil)
5573 (if (<= (setq ind1 (org-get-indentation)) ind)
5574 (throw 'exit t)))))
5575 (condition-case nil
5576 (org-beginning-of-item)
5577 (error (goto-char beg)
5578 (error "Cannot move this item further up")))
5579 (setq ind1 (org-get-indentation))
5580 (if (and (org-at-item-p) (= ind ind1))
5581 (progn
5582 (setq txt (buffer-substring beg end))
5583 (save-excursion
5584 (delete-region beg end))
5585 (setq pos (point))
5586 (insert txt)
5587 (goto-char pos)
5588 (org-maybe-renumber-ordered-list))
5589 (goto-char pos)
5590 (error "Cannot move this item further up"))))
5592 (defun org-maybe-renumber-ordered-list ()
5593 "Renumber the ordered list at point if setup allows it.
5594 This tests the user option `org-auto-renumber-ordered-lists' before
5595 doing the renumbering."
5596 (and org-auto-renumber-ordered-lists
5597 (org-at-item-p)
5598 (match-beginning 3)
5599 (org-renumber-ordered-list 1)))
5601 (defun org-get-string-indentation (s)
5602 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5603 (let ((n -1) (i 0) (w tab-width) c)
5604 (catch 'exit
5605 (while (< (setq n (1+ n)) (length s))
5606 (setq c (aref s n))
5607 (cond ((= c ?\ ) (setq i (1+ i)))
5608 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5609 (t (throw 'exit t)))))
5612 (defun org-renumber-ordered-list (arg)
5613 "Renumber an ordered plain list.
5614 Cursor needs to be in the first line of an item, the line that starts
5615 with something like \"1.\" or \"2)\"."
5616 (interactive "p")
5617 (unless (and (org-at-item-p)
5618 (match-beginning 3))
5619 (error "This is not an ordered list"))
5620 (let ((line (org-current-line))
5621 (col (current-column))
5622 (ind (org-get-string-indentation
5623 (buffer-substring (point-at-bol) (match-beginning 3))))
5624 ;; (term (substring (match-string 3) -1))
5625 ind1 (n (1- arg)))
5626 ;; find where this list begins
5627 (catch 'exit
5628 (while t
5629 (catch 'next
5630 (beginning-of-line 0)
5631 (if (looking-at "[ \t]*$") (throw 'next t))
5632 (skip-chars-forward " \t") (setq ind1 (current-column))
5633 (if (or (< ind1 ind)
5634 (and (= ind1 ind)
5635 (not (org-at-item-p))))
5636 (throw 'exit t)))))
5637 ;; Walk forward and replace these numbers
5638 (catch 'exit
5639 (while t
5640 (catch 'next
5641 (beginning-of-line 2)
5642 (if (eobp) (throw 'exit nil))
5643 (if (looking-at "[ \t]*$") (throw 'next nil))
5644 (skip-chars-forward " \t") (setq ind1 (current-column))
5645 (if (> ind1 ind) (throw 'next t))
5646 (if (< ind1 ind) (throw 'exit t))
5647 (if (not (org-at-item-p)) (throw 'exit nil))
5648 (if (not (match-beginning 3))
5649 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
5650 (delete-region (match-beginning 3) (1- (match-end 3)))
5651 (goto-char (match-beginning 3))
5652 (insert (format "%d" (setq n (1+ n)))))))
5653 (goto-line line)
5654 (move-to-column col)))
5656 (defvar org-last-indent-begin-marker (make-marker))
5657 (defvar org-last-indent-end-marker (make-marker))
5659 (defun org-outdent-item (arg)
5660 "Outdent a local list item."
5661 (interactive "p")
5662 (org-indent-item (- arg)))
5664 (defun org-indent-item (arg)
5665 "Indent a local list item."
5666 (interactive "p")
5667 (unless (org-at-item-p)
5668 (error "Not on an item"))
5669 (save-excursion
5670 (let (beg end ind ind1)
5671 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5672 (setq beg org-last-indent-begin-marker
5673 end org-last-indent-end-marker)
5674 (org-beginning-of-item)
5675 (setq beg (move-marker org-last-indent-begin-marker (point)))
5676 (org-end-of-item)
5677 (setq end (move-marker org-last-indent-end-marker (point))))
5678 (goto-char beg)
5679 (skip-chars-forward " \t") (setq ind (current-column))
5680 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
5681 (while (< (point) end)
5682 (beginning-of-line 1)
5683 (skip-chars-forward " \t") (setq ind1 (current-column))
5684 (delete-region (point-at-bol) (point))
5685 (indent-to-column (+ ind1 arg))
5686 (beginning-of-line 2)))))
5688 ;;;; Archiving
5690 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
5692 (defun org-archive-subtree (&optional find-done)
5693 "Move the current subtree to the archive.
5694 The archive can be a certain top-level heading in the current file, or in
5695 a different file. The tree will be moved to that location, the subtree
5696 heading be marked DONE, and the current time will be added.
5698 When called with prefix argument FIND-DONE, find whole trees without any
5699 open TODO items and archive them (after getting confirmation from the user).
5700 If the cursor is not at a headline when this comand is called, try all level
5701 1 trees. If the cursor is on a headline, only try the direct children of
5702 this heading."
5703 (interactive "P")
5704 (if find-done
5705 (org-archive-all-done)
5706 ;; Save all relevant TODO keyword-relatex variables
5708 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
5709 (tr-org-todo-keywords-1 org-todo-keywords-1)
5710 (tr-org-todo-kwd-alist org-todo-kwd-alist)
5711 (tr-org-done-keywords org-done-keywords)
5712 (tr-org-todo-regexp org-todo-regexp)
5713 (tr-org-todo-line-regexp org-todo-line-regexp)
5714 (tr-org-odd-levels-only org-odd-levels-only)
5715 (this-buffer (current-buffer))
5716 (org-archive-location org-archive-location)
5717 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
5718 file heading buffer level newfile-p)
5720 ;; Try to find a local archive location
5721 (save-excursion
5722 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
5723 (setq org-archive-location (match-string 1))))
5725 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
5726 (progn
5727 (setq file (format (match-string 1 org-archive-location)
5728 (file-name-nondirectory buffer-file-name))
5729 heading (match-string 2 org-archive-location)))
5730 (error "Invalid `org-archive-location'"))
5731 (if (> (length file) 0)
5732 (setq newfile-p (not (file-exists-p file))
5733 buffer (find-file-noselect file))
5734 (setq buffer (current-buffer)))
5735 (unless buffer
5736 (error "Cannot access file \"%s\"" file))
5737 (if (and (> (length heading) 0)
5738 (string-match "^\\*+" heading))
5739 (setq level (match-end 0))
5740 (setq heading nil level 0))
5741 (save-excursion
5742 ;; We first only copy, in case something goes wrong
5743 ;; we need to protect this-command, to avoid kill-region sets it,
5744 ;; which would lead to duplication of subtrees
5745 (let (this-command) (org-copy-subtree))
5746 (set-buffer buffer)
5747 ;; Enforce org-mode for the archive buffer
5748 (if (not (org-mode-p))
5749 ;; Force the mode for future visits.
5750 (let ((org-insert-mode-line-in-empty-file t)
5751 (org-inhibit-startup t))
5752 (call-interactively 'org-mode)))
5753 (when newfile-p
5754 (goto-char (point-max))
5755 (insert (format "\nArchived entries from file %s\n\n"
5756 (buffer-file-name this-buffer))))
5757 ;; Force the TODO keywords of the original buffer
5758 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
5759 (org-todo-keywords-1 tr-org-todo-keywords-1)
5760 (org-todo-kwd-alist tr-org-todo-kwd-alist)
5761 (org-done-keywords tr-org-done-keywords)
5762 (org-todo-regexp tr-org-todo-regexp)
5763 (org-todo-line-regexp tr-org-todo-line-regexp)
5764 (org-odd-levels-only
5765 (if (local-variable-p 'org-odd-levels-only (current-buffer))
5766 org-odd-levels-only
5767 tr-org-odd-levels-only)))
5768 (goto-char (point-min))
5769 (if heading
5770 (progn
5771 (if (re-search-forward
5772 (concat "\\(^\\|\r\\)"
5773 (regexp-quote heading) "[ \t]*\\(:[a-zA-Z0-9_@:]+:\\)?[ \t]*\\($\\|\r\\)")
5774 nil t)
5775 (goto-char (match-end 0))
5776 ;; Heading not found, just insert it at the end
5777 (goto-char (point-max))
5778 (or (bolp) (insert "\n"))
5779 (insert "\n" heading "\n")
5780 (end-of-line 0))
5781 ;; Make the subtree visible
5782 (show-subtree)
5783 (org-end-of-subtree t)
5784 (skip-chars-backward " \t\r\n")
5785 (and (looking-at "[ \t\r\n]*")
5786 (replace-match "\n\n")))
5787 ;; No specific heading, just go to end of file.
5788 (goto-char (point-max)) (insert "\n"))
5789 ;; Paste
5790 (org-paste-subtree (org-get-legal-level level 1))
5791 ;; Mark the entry as done, i.e. set to last word in org-todo-keywords-1 FIXME: not right anymore!!!!!!!
5792 (if org-archive-mark-done
5793 (let (org-log-done)
5794 (org-todo (length org-todo-keywords-1))))
5795 ;; Move cursor to right after the TODO keyword
5796 (when org-archive-stamp-time
5797 (beginning-of-line 1)
5798 (looking-at org-todo-line-regexp)
5799 (goto-char (or (match-end 2) (match-beginning 3)))
5800 (org-insert-time-stamp (org-current-time) t t "(" ")"))
5801 ;; Save the buffer, if it is not the same buffer.
5802 (if (not (eq this-buffer buffer)) (save-buffer))))
5803 ;; Here we are back in the original buffer. Everything seems to have
5804 ;; worked. So now cut the tree and finish up.
5805 (let (this-command) (org-cut-subtree))
5806 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
5807 (message "Subtree archived %s"
5808 (if (eq this-buffer buffer)
5809 (concat "under heading: " heading)
5810 (concat "in file: " (abbreviate-file-name file)))))))
5812 (defun org-archive-all-done (&optional tag)
5813 "Archive sublevels of the current tree without open TODO items.
5814 If the cursor is not on a headline, try all level 1 trees. If
5815 it is on a headline, try all direct children.
5816 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
5817 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
5818 (rea (concat ".*:" org-archive-tag ":"))
5819 (begm (make-marker))
5820 (endm (make-marker))
5821 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
5822 "Move subtree to archive (no open TODO items)? "))
5823 beg end (cntarch 0))
5824 (if (org-on-heading-p)
5825 (progn
5826 (setq re1 (concat "^" (regexp-quote
5827 (make-string
5828 (1+ (- (match-end 0) (match-beginning 0)))
5829 ?*))
5830 " "))
5831 (move-marker begm (point))
5832 (move-marker endm (org-end-of-subtree t)))
5833 (setq re1 "^* ")
5834 (move-marker begm (point-min))
5835 (move-marker endm (point-max)))
5836 (save-excursion
5837 (goto-char begm)
5838 (while (re-search-forward re1 endm t)
5839 (setq beg (match-beginning 0)
5840 end (save-excursion (org-end-of-subtree t) (point)))
5841 (goto-char beg)
5842 (if (re-search-forward re end t)
5843 (goto-char end)
5844 (goto-char beg)
5845 (if (and (or (not tag) (not (looking-at rea)))
5846 (y-or-n-p question))
5847 (progn
5848 (if tag
5849 (org-toggle-tag org-archive-tag 'on)
5850 (org-archive-subtree))
5851 (setq cntarch (1+ cntarch)))
5852 (goto-char end)))))
5853 (message "%d trees archived" cntarch)))
5855 (defun org-cycle-hide-archived-subtrees (state)
5856 "Re-hide all archived subtrees after a visibility state change."
5857 (when (and (not org-cycle-open-archived-trees)
5858 (not (memq state '(overview folded))))
5859 (save-excursion
5860 (let* ((globalp (memq state '(contents all)))
5861 (beg (if globalp (point-min) (point)))
5862 (end (if globalp (point-max) (org-end-of-subtree t))))
5863 (org-hide-archived-subtrees beg end)
5864 (goto-char beg)
5865 (if (looking-at (concat ".*:" org-archive-tag ":"))
5866 (message (substitute-command-keys
5867 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
5869 (defun org-force-cycle-archived ()
5870 "Cycle subtree even if it is archived."
5871 (interactive)
5872 (setq this-command 'org-cycle)
5873 (let ((org-cycle-open-archived-trees t))
5874 (call-interactively 'org-cycle)))
5876 (defun org-hide-archived-subtrees (beg end)
5877 "Re-hide all archived subtrees after a visibility state change."
5878 (save-excursion
5879 (let* ((re (concat ":" org-archive-tag ":")))
5880 (goto-char beg)
5881 (while (re-search-forward re end t)
5882 (and (org-on-heading-p) (hide-subtree))
5883 (org-end-of-subtree t)))))
5885 (defun org-toggle-tag (tag &optional onoff)
5886 "Toggle the tag TAG for the current line.
5887 If ONOFF is `on' or `off', don't toggle but set to this state."
5888 (unless (org-on-heading-p t) (error "Not on headling"))
5889 (let (res current)
5890 (save-excursion
5891 (beginning-of-line)
5892 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
5893 (point-at-eol) t)
5894 (progn
5895 (setq current (match-string 1))
5896 (replace-match ""))
5897 (setq current ""))
5898 (setq current (nreverse (org-split-string current ":")))
5899 (cond
5900 ((eq onoff 'on)
5901 (setq res t)
5902 (or (member tag current) (push tag current)))
5903 ((eq onoff 'off)
5904 (or (not (member tag current)) (setq current (delete tag current))))
5905 (t (if (member tag current)
5906 (setq current (delete tag current))
5907 (setq res t)
5908 (push tag current))))
5909 (end-of-line 1)
5910 (when current
5911 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
5912 (org-set-tags nil t))
5913 res))
5915 (defun org-toggle-archive-tag (&optional arg)
5916 "Toggle the archive tag for the current headline.
5917 With prefix ARG, check all children of current headline and offer tagging
5918 the children that do not contain any open TODO items."
5919 (interactive "P")
5920 (if arg
5921 (org-archive-all-done 'tag)
5922 (let (set)
5923 (save-excursion
5924 (org-back-to-heading t)
5925 (setq set (org-toggle-tag org-archive-tag))
5926 (when set (hide-subtree)))
5927 (and set (beginning-of-line 1))
5928 (message "Subtree %s" (if set "archived" "unarchived")))))
5931 ;;;; Tables
5933 ;;; The table editor
5935 ;; Watch out: Here we are talking about two different kind of tables.
5936 ;; Most of the code is for the tables created with the Org-mode table editor.
5937 ;; Sometimes, we talk about tables created and edited with the table.el
5938 ;; Emacs package. We call the former org-type tables, and the latter
5939 ;; table.el-type tables.
5941 (defun org-before-change-function (beg end)
5942 "Every change indicates that a table might need an update."
5943 (setq org-table-may-need-update t))
5945 (defconst org-table-line-regexp "^[ \t]*|"
5946 "Detects an org-type table line.")
5947 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5948 "Detects an org-type table line.")
5949 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5950 "Detects a table line marked for automatic recalculation.")
5951 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5952 "Detects a table line marked for automatic recalculation.")
5953 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5954 "Detects a table line marked for automatic recalculation.")
5955 (defconst org-table-hline-regexp "^[ \t]*|-"
5956 "Detects an org-type table hline.")
5957 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5958 "Detects a table-type table hline.")
5959 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5960 "Detects an org-type or table-type table.")
5961 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5962 "Searching from within a table (any type) this finds the first line
5963 outside the table.")
5964 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5965 "Searching from within a table (any type) this finds the first line
5966 outside the table.")
5968 (defvar org-table-last-highlighted-reference nil)
5969 (defvar org-table-formula-history nil)
5971 (defvar org-table-column-names nil
5972 "Alist with column names, derived from the `!' line.")
5973 (defvar org-table-column-name-regexp nil
5974 "Regular expression matching the current column names.")
5975 (defvar org-table-local-parameters nil
5976 "Alist with parameter names, derived from the `$' line.")
5977 (defvar org-table-named-field-locations nil
5978 "Alist with locations of named fields.")
5980 (defvar org-table-current-line-types nil
5981 "Table row types, non-nil only for the duration of a comand.")
5982 (defvar org-table-current-begin-line nil
5983 "Table begin line, non-nil only for the duration of a comand.")
5984 (defvar org-table-current-begin-pos nil
5985 "Table begin position, non-nil only for the duration of a comand.")
5986 (defvar org-table-dlines nil
5987 "Vector of data line line numbers in the current table.")
5988 (defvar org-table-hlines nil
5989 "Vector of hline line numbers in the current table.")
5991 (defconst org-table-range-regexp
5992 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
5993 ;; 1 2 3 4 5
5994 "Regular expression for matching ranges in formulas.")
5996 (defconst org-table-range-regexp2
5997 (concat
5998 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
5999 "\\.\\."
6000 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
6001 "Match a range for reference display.")
6003 (defconst org-table-translate-regexp
6004 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
6005 "Match a reference that needs translation, for reference display.")
6007 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
6009 (defun org-table-create-with-table.el ()
6010 "Use the table.el package to insert a new table.
6011 If there is already a table at point, convert between Org-mode tables
6012 and table.el tables."
6013 (interactive)
6014 (require 'table)
6015 (cond
6016 ((org-at-table.el-p)
6017 (if (y-or-n-p "Convert table to Org-mode table? ")
6018 (org-table-convert)))
6019 ((org-at-table-p)
6020 (if (y-or-n-p "Convert table to table.el table? ")
6021 (org-table-convert)))
6022 (t (call-interactively 'table-insert))))
6024 (defun org-table-create-or-convert-from-region (arg)
6025 "Convert region to table, or create an empty table.
6026 If there is an active region, convert it to a table. If there is no such
6027 region, create an empty table."
6028 (interactive "P")
6029 (if (org-region-active-p)
6030 (org-table-convert-region (region-beginning) (region-end) arg)
6031 (org-table-create arg)))
6033 (defun org-table-create (&optional size)
6034 "Query for a size and insert a table skeleton.
6035 SIZE is a string Columns x Rows like for example \"3x2\"."
6036 (interactive "P")
6037 (unless size
6038 (setq size (read-string
6039 (concat "Table size Columns x Rows [e.g. "
6040 org-table-default-size "]: ")
6041 "" nil org-table-default-size)))
6043 (let* ((pos (point))
6044 (indent (make-string (current-column) ?\ ))
6045 (split (org-split-string size " *x *"))
6046 (rows (string-to-number (nth 1 split)))
6047 (columns (string-to-number (car split)))
6048 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6049 "\n")))
6050 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6051 (point-at-bol) (point)))
6052 (beginning-of-line 1)
6053 (newline))
6054 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6055 (dotimes (i rows) (insert line))
6056 (goto-char pos)
6057 (if (> rows 1)
6058 ;; Insert a hline after the first row.
6059 (progn
6060 (end-of-line 1)
6061 (insert "\n|-")
6062 (goto-char pos)))
6063 (org-table-align)))
6065 (defun org-table-convert-region (beg0 end0 &optional nspace)
6066 "Convert region to a table.
6067 The region goes from BEG0 to END0, but these borders will be moved
6068 slightly, to make sure a beginning of line in the first line is included.
6069 When NSPACE is non-nil, it indicates the minimum number of spaces that
6070 separate columns (default: just one space)."
6071 (interactive "rP")
6072 (let* ((beg (min beg0 end0))
6073 (end (max beg0 end0))
6074 (tabsep t)
6076 (goto-char beg)
6077 (beginning-of-line 1)
6078 (setq beg (move-marker (make-marker) (point)))
6079 (goto-char end)
6080 (if (bolp) (backward-char 1) (end-of-line 1))
6081 (setq end (move-marker (make-marker) (point)))
6082 ;; Lets see if this is tab-separated material. If every nonempty line
6083 ;; contains a tab, we will assume that it is tab-separated material
6084 (if nspace
6085 (setq tabsep nil)
6086 (goto-char beg)
6087 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6088 (if nspace (setq tabsep nil))
6089 (if tabsep
6090 (setq re "^\\|\t")
6091 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6092 (max 1 (prefix-numeric-value nspace)))))
6093 (goto-char beg)
6094 (while (re-search-forward re end t)
6095 (replace-match "| " t t))
6096 (goto-char beg)
6097 (insert " ")
6098 (org-table-align)))
6100 (defun org-table-import (file arg)
6101 "Import FILE as a table.
6102 The file is assumed to be tab-separated. Such files can be produced by most
6103 spreadsheet and database applications. If no tabs (at least one per line)
6104 are found, lines will be split on whitespace into fields."
6105 (interactive "f\nP")
6106 (or (bolp) (newline))
6107 (let ((beg (point))
6108 (pm (point-max)))
6109 (insert-file-contents file)
6110 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
6112 (defun org-table-export ()
6113 "Export table as a tab-separated file.
6114 Such a file can be imported into a spreadsheet program like Excel."
6115 (interactive)
6116 (let* ((beg (org-table-begin))
6117 (end (org-table-end))
6118 (table (buffer-substring beg end))
6119 (file (read-file-name "Export table to: "))
6120 buf)
6121 (unless (or (not (file-exists-p file))
6122 (y-or-n-p (format "Overwrite file %s? " file)))
6123 (error "Abort"))
6124 (with-current-buffer (find-file-noselect file)
6125 (setq buf (current-buffer))
6126 (erase-buffer)
6127 (fundamental-mode)
6128 (insert table)
6129 (goto-char (point-min))
6130 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6131 (replace-match "" t t)
6132 (end-of-line 1))
6133 (goto-char (point-min))
6134 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6135 (replace-match "" t t)
6136 (goto-char (min (1+ (point)) (point-max))))
6137 (goto-char (point-min))
6138 (while (re-search-forward "^-[-+]*$" nil t)
6139 (replace-match "")
6140 (if (looking-at "\n")
6141 (delete-char 1)))
6142 (goto-char (point-min))
6143 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6144 (replace-match "\t" t t))
6145 (save-buffer))
6146 (kill-buffer buf)))
6148 (defvar org-table-aligned-begin-marker (make-marker)
6149 "Marker at the beginning of the table last aligned.
6150 Used to check if cursor still is in that table, to minimize realignment.")
6151 (defvar org-table-aligned-end-marker (make-marker)
6152 "Marker at the end of the table last aligned.
6153 Used to check if cursor still is in that table, to minimize realignment.")
6154 (defvar org-table-last-alignment nil
6155 "List of flags for flushright alignment, from the last re-alignment.
6156 This is being used to correctly align a single field after TAB or RET.")
6157 (defvar org-table-last-column-widths nil
6158 "List of max width of fields in each column.
6159 This is being used to correctly align a single field after TAB or RET.")
6160 (defvar org-table-overlay-coordinates nil
6161 "Overlay coordinates after each align of a table.")
6162 (make-variable-buffer-local 'org-table-overlay-coordinates)
6164 (defvar org-last-recalc-line nil)
6165 (defconst org-narrow-column-arrow "=>"
6166 "Used as display property in narrowed table columns.")
6168 (defun org-table-align ()
6169 "Align the table at point by aligning all vertical bars."
6170 (interactive)
6171 (let* (
6172 ;; Limits of table
6173 (beg (org-table-begin))
6174 (end (org-table-end))
6175 ;; Current cursor position
6176 (linepos (org-current-line))
6177 (colpos (org-table-current-column))
6178 (winstart (window-start))
6179 (winstartline (org-current-line (min winstart (1- (point-max)))))
6180 lines (new "") lengths l typenums ty fields maxfields i
6181 column
6182 (indent "") cnt frac
6183 rfmt hfmt
6184 (spaces '(1 . 1))
6185 (sp1 (car spaces))
6186 (sp2 (cdr spaces))
6187 (rfmt1 (concat
6188 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6189 (hfmt1 (concat
6190 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6191 emptystrings links dates narrow fmax f1 len c e)
6192 (untabify beg end)
6193 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
6194 ;; Check if we have links or dates
6195 (goto-char beg)
6196 (setq links (re-search-forward org-bracket-link-regexp end t))
6197 (goto-char beg)
6198 (setq dates (and org-display-custom-times
6199 (re-search-forward org-ts-regexp-both end t)))
6200 ;; Make sure the link properties are right
6201 (when links (goto-char beg) (while (org-activate-bracket-links end)))
6202 ;; Make sure the date properties are right
6203 (when dates (goto-char beg) (while (org-activate-dates end)))
6205 ;; Check if we are narrowing any columns
6206 (goto-char beg)
6207 (setq narrow (and org-format-transports-properties-p
6208 (re-search-forward "<[0-9]+>" end t)))
6209 ;; Get the rows
6210 (setq lines (org-split-string
6211 (buffer-substring beg end) "\n"))
6212 ;; Store the indentation of the first line
6213 (if (string-match "^ *" (car lines))
6214 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6215 ;; Mark the hlines by setting the corresponding element to nil
6216 ;; At the same time, we remove trailing space.
6217 (setq lines (mapcar (lambda (l)
6218 (if (string-match "^ *|-" l)
6220 (if (string-match "[ \t]+$" l)
6221 (substring l 0 (match-beginning 0))
6222 l)))
6223 lines))
6224 ;; Get the data fields by splitting the lines.
6225 (setq fields (mapcar
6226 (lambda (l)
6227 (org-split-string l " *| *"))
6228 (delq nil (copy-sequence lines))))
6229 ;; How many fields in the longest line?
6230 (condition-case nil
6231 (setq maxfields (apply 'max (mapcar 'length fields)))
6232 (error
6233 (kill-region beg end)
6234 (org-table-create org-table-default-size)
6235 (error "Empty table - created default table")))
6236 ;; A list of empty strings to fill any short rows on output
6237 (setq emptystrings (make-list maxfields ""))
6238 ;; Check for special formatting.
6239 (setq i -1)
6240 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6241 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6242 ;; Check if there is an explicit width specified
6243 (when narrow
6244 (setq c column fmax nil)
6245 (while c
6246 (setq e (pop c))
6247 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
6248 (setq fmax (string-to-number (match-string 1 e)) c nil)))
6249 ;; Find fields that are wider than fmax, and shorten them
6250 (when fmax
6251 (loop for xx in column do
6252 (when (and (stringp xx)
6253 (> (org-string-width xx) fmax))
6254 (org-add-props xx nil
6255 'help-echo
6256 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
6257 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
6258 (unless (> f1 1)
6259 (error "Cannot narrow field starting with wide link \"%s\""
6260 (match-string 0 xx)))
6261 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
6262 (add-text-properties (- f1 2) f1
6263 (list 'display org-narrow-column-arrow)
6264 xx)))))
6265 ;; Get the maximum width for each column
6266 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
6267 ;; Get the fraction of numbers, to decide about alignment of the column
6268 (setq cnt 0 frac 0.0)
6269 (loop for x in column do
6270 (if (equal x "")
6272 (setq frac ( / (+ (* frac cnt)
6273 (if (string-match org-table-number-regexp x) 1 0))
6274 (setq cnt (1+ cnt))))))
6275 (push (>= frac org-table-number-fraction) typenums))
6276 (setq lengths (nreverse lengths) typenums (nreverse typenums))
6278 ;; Store the alignment of this table, for later editing of single fields
6279 (setq org-table-last-alignment typenums
6280 org-table-last-column-widths lengths)
6282 ;; With invisible characters, `format' does not get the field width right
6283 ;; So we need to make these fields wide by hand.
6284 (when links
6285 (loop for i from 0 upto (1- maxfields) do
6286 (setq len (nth i lengths))
6287 (loop for j from 0 upto (1- (length fields)) do
6288 (setq c (nthcdr i (car (nthcdr j fields))))
6289 (if (and (stringp (car c))
6290 (string-match org-bracket-link-regexp (car c))
6291 (< (org-string-width (car c)) len))
6292 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
6294 ;; Compute the formats needed for output of the table
6295 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6296 (while (setq l (pop lengths))
6297 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6298 (setq rfmt (concat rfmt (format rfmt1 ty l))
6299 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6300 (setq rfmt (concat rfmt "\n")
6301 hfmt (concat (substring hfmt 0 -1) "|\n"))
6303 (setq new (mapconcat
6304 (lambda (l)
6305 (if l (apply 'format rfmt
6306 (append (pop fields) emptystrings))
6307 hfmt))
6308 lines ""))
6309 ;; Replace the old one
6310 (delete-region beg end)
6311 (move-marker end nil)
6312 (move-marker org-table-aligned-begin-marker (point))
6313 (insert new)
6314 (move-marker org-table-aligned-end-marker (point))
6315 (when (and orgtbl-mode (not (org-mode-p)))
6316 (goto-char org-table-aligned-begin-marker)
6317 (while (org-hide-wide-columns org-table-aligned-end-marker)))
6318 ;; Try to move to the old location
6319 (goto-line winstartline)
6320 (setq winstart (point-at-bol))
6321 (goto-line linepos)
6322 (set-window-start (selected-window) winstart 'noforce)
6323 (org-table-goto-column colpos)
6324 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
6325 (setq org-table-may-need-update nil)
6328 (defun org-string-width (s)
6329 "Compute width of string, ignoring invisible characters.
6330 This ignores character with invisibility property `org-link', and also
6331 characters with property `org-cwidth', because these will become invisible
6332 upon the next fontification round."
6333 (let (b l)
6334 (when (or (eq t buffer-invisibility-spec)
6335 (assq 'org-link buffer-invisibility-spec))
6336 (while (setq b (text-property-any 0 (length s)
6337 'invisible 'org-link s))
6338 (setq s (concat (substring s 0 b)
6339 (substring s (or (next-single-property-change
6340 b 'invisible s) (length s)))))))
6341 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
6342 (setq s (concat (substring s 0 b)
6343 (substring s (or (next-single-property-change
6344 b 'org-cwidth s) (length s))))))
6345 (setq l (string-width s) b -1)
6346 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
6347 (setq l (- l (get-text-property b 'org-dwidth-n s))))
6350 (defun org-table-begin (&optional table-type)
6351 "Find the beginning of the table and return its position.
6352 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6353 (save-excursion
6354 (if (not (re-search-backward
6355 (if table-type org-table-any-border-regexp
6356 org-table-border-regexp)
6357 nil t))
6358 (progn (goto-char (point-min)) (point))
6359 (goto-char (match-beginning 0))
6360 (beginning-of-line 2)
6361 (point))))
6363 (defun org-table-end (&optional table-type)
6364 "Find the end of the table and return its position.
6365 With argument TABLE-TYPE, go to the end of a table.el-type table."
6366 (save-excursion
6367 (if (not (re-search-forward
6368 (if table-type org-table-any-border-regexp
6369 org-table-border-regexp)
6370 nil t))
6371 (goto-char (point-max))
6372 (goto-char (match-beginning 0)))
6373 (point-marker)))
6375 (defun org-table-justify-field-maybe (&optional new)
6376 "Justify the current field, text to left, number to right.
6377 Optional argument NEW may specify text to replace the current field content."
6378 (cond
6379 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6380 ((org-at-table-hline-p))
6381 ((and (not new)
6382 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6383 (current-buffer)))
6384 (< (point) org-table-aligned-begin-marker)
6385 (>= (point) org-table-aligned-end-marker)))
6386 ;; This is not the same table, force a full re-align
6387 (setq org-table-may-need-update t))
6388 (t ;; realign the current field, based on previous full realign
6389 (let* ((pos (point)) s
6390 (col (org-table-current-column))
6391 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
6392 l f n o e)
6393 (when (> col 0)
6394 (skip-chars-backward "^|\n")
6395 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6396 (progn
6397 (setq s (match-string 1)
6398 o (match-string 0)
6399 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6400 e (not (= (match-beginning 2) (match-end 2))))
6401 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6402 l (if e "|" (setq org-table-may-need-update t) ""))
6403 n (format f s))
6404 (if new
6405 (if (<= (length new) l) ;; FIXME: length -> str-width?
6406 (setq n (format f new))
6407 (setq n (concat new "|") org-table-may-need-update t)))
6408 (or (equal n o)
6409 (let (org-table-may-need-update)
6410 (replace-match n))))
6411 (setq org-table-may-need-update t))
6412 (goto-char pos))))))
6414 (defun org-table-next-field ()
6415 "Go to the next field in the current table, creating new lines as needed.
6416 Before doing so, re-align the table if necessary."
6417 (interactive)
6418 (org-table-maybe-eval-formula)
6419 (org-table-maybe-recalculate-line)
6420 (if (and org-table-automatic-realign
6421 org-table-may-need-update)
6422 (org-table-align))
6423 (let ((end (org-table-end)))
6424 (if (org-at-table-hline-p)
6425 (end-of-line 1))
6426 (condition-case nil
6427 (progn
6428 (re-search-forward "|" end)
6429 (if (looking-at "[ \t]*$")
6430 (re-search-forward "|" end))
6431 (if (and (looking-at "-")
6432 org-table-tab-jumps-over-hlines
6433 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
6434 (goto-char (match-beginning 1)))
6435 (if (looking-at "-")
6436 (progn
6437 (beginning-of-line 0)
6438 (org-table-insert-row 'below))
6439 (if (looking-at " ") (forward-char 1))))
6440 (error
6441 (org-table-insert-row 'below)))))
6443 (defun org-table-previous-field ()
6444 "Go to the previous field in the table.
6445 Before doing so, re-align the table if necessary."
6446 (interactive)
6447 (org-table-justify-field-maybe)
6448 (org-table-maybe-recalculate-line)
6449 (if (and org-table-automatic-realign
6450 org-table-may-need-update)
6451 (org-table-align))
6452 (if (org-at-table-hline-p)
6453 (end-of-line 1))
6454 (re-search-backward "|" (org-table-begin))
6455 (re-search-backward "|" (org-table-begin))
6456 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6457 (re-search-backward "|" (org-table-begin)))
6458 (if (looking-at "| ?")
6459 (goto-char (match-end 0))))
6461 (defun org-table-next-row ()
6462 "Go to the next row (same column) in the current table.
6463 Before doing so, re-align the table if necessary."
6464 (interactive)
6465 (org-table-maybe-eval-formula)
6466 (org-table-maybe-recalculate-line)
6467 (if (or (looking-at "[ \t]*$")
6468 (save-excursion (skip-chars-backward " \t") (bolp)))
6469 (newline)
6470 (if (and org-table-automatic-realign
6471 org-table-may-need-update)
6472 (org-table-align))
6473 (let ((col (org-table-current-column)))
6474 (beginning-of-line 2)
6475 (if (or (not (org-at-table-p))
6476 (org-at-table-hline-p))
6477 (progn
6478 (beginning-of-line 0)
6479 (org-table-insert-row 'below)))
6480 (org-table-goto-column col)
6481 (skip-chars-backward "^|\n\r")
6482 (if (looking-at " ") (forward-char 1)))))
6484 (defun org-table-copy-down (n)
6485 "Copy a field down in the current column.
6486 If the field at the cursor is empty, copy into it the content of the nearest
6487 non-empty field above. With argument N, use the Nth non-empty field.
6488 If the current field is not empty, it is copied down to the next row, and
6489 the cursor is moved with it. Therefore, repeating this command causes the
6490 column to be filled row-by-row.
6491 If the variable `org-table-copy-increment' is non-nil and the field is an
6492 integer, it will be incremented while copying."
6493 (interactive "p")
6494 (let* ((colpos (org-table-current-column))
6495 (field (org-table-get-field))
6496 (non-empty (string-match "[^ \t]" field))
6497 (beg (org-table-begin))
6498 txt)
6499 (org-table-check-inside-data-field)
6500 (if non-empty
6501 (progn
6502 (setq txt (org-trim field))
6503 (org-table-next-row)
6504 (org-table-blank-field))
6505 (save-excursion
6506 (setq txt
6507 (catch 'exit
6508 (while (progn (beginning-of-line 1)
6509 (re-search-backward org-table-dataline-regexp
6510 beg t))
6511 (org-table-goto-column colpos t)
6512 (if (and (looking-at
6513 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6514 (= (setq n (1- n)) 0))
6515 (throw 'exit (match-string 1))))))))
6516 (if txt
6517 (progn
6518 (if (and org-table-copy-increment
6519 (string-match "^[0-9]+$" txt))
6520 (setq txt (format "%d" (+ (string-to-number txt) 1))))
6521 (insert txt)
6522 (org-table-maybe-recalculate-line)
6523 (org-table-align))
6524 (error "No non-empty field found"))))
6526 (defun org-table-check-inside-data-field ()
6527 "Is point inside a table data field?
6528 I.e. not on a hline or before the first or after the last column?
6529 This actually throws an error, so it aborts the current command."
6530 (if (or (not (org-at-table-p))
6531 (= (org-table-current-column) 0)
6532 (org-at-table-hline-p)
6533 (looking-at "[ \t]*$"))
6534 (error "Not in table data field")))
6536 (defvar org-table-clip nil
6537 "Clipboard for table regions.")
6539 (defun org-table-blank-field ()
6540 "Blank the current table field or active region."
6541 (interactive)
6542 (org-table-check-inside-data-field)
6543 (if (and (interactive-p) (org-region-active-p))
6544 (let (org-table-clip)
6545 (org-table-cut-region (region-beginning) (region-end)))
6546 (skip-chars-backward "^|")
6547 (backward-char 1)
6548 (if (looking-at "|[^|\n]+")
6549 (let* ((pos (match-beginning 0))
6550 (match (match-string 0))
6551 (len (org-string-width match)))
6552 (replace-match (concat "|" (make-string (1- len) ?\ )))
6553 (goto-char (+ 2 pos))
6554 (substring match 1)))))
6556 (defun org-table-get-field (&optional n replace)
6557 "Return the value of the field in column N of current row.
6558 N defaults to current field.
6559 If REPLACE is a string, replace field with this value. The return value
6560 is always the old value."
6561 (and n (org-table-goto-column n))
6562 (skip-chars-backward "^|\n")
6563 (backward-char 1)
6564 (if (looking-at "|[^|\r\n]*")
6565 (let* ((pos (match-beginning 0))
6566 (val (buffer-substring (1+ pos) (match-end 0))))
6567 (if replace
6568 (replace-match (concat "|" replace) t t))
6569 (goto-char (min (point-at-eol) (+ 2 pos)))
6570 val)
6571 (forward-char 1) ""))
6574 (defun org-table-field-info (arg)
6575 "Show info about the current field, and highlight any reference at point."
6576 (interactive "P")
6577 (org-table-get-specials)
6578 (save-excursion
6579 (let* ((pos (point))
6580 (col (org-table-current-column))
6581 (cname (car (rassoc (int-to-string col) org-table-column-names)))
6582 (name (car (rassoc (list (org-current-line) col)
6583 org-table-named-field-locations)))
6584 (eql (org-table-get-stored-formulas))
6585 (dline (org-table-current-dline))
6586 (ref (format "@%d$%d" dline col))
6587 (ref1 (org-table-convert-refs-to-an ref))
6588 (fequation (or (assoc name eql) (assoc ref eql)))
6589 (cequation (assoc (int-to-string col) eql))
6590 (eqn (or fequation cequation)))
6591 (goto-char pos)
6592 (condition-case nil
6593 (org-table-show-reference 'local)
6594 (error nil))
6595 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
6596 dline col
6597 (if cname (concat " or $" cname) "")
6598 dline col ref1
6599 (if name (concat " or $" name) "")
6600 ;; FIXME: formula info not correct if special table line
6601 (if eqn
6602 (concat ", formula: "
6603 (org-table-formula-to-user
6604 (concat
6605 (if (string-match "^[$@]"(car eqn)) "" "$")
6606 (car eqn) "=" (cdr eqn))))
6607 "")))))
6609 (defun org-table-current-column ()
6610 "Find out which column we are in.
6611 When called interactively, column is also displayed in echo area."
6612 (interactive)
6613 (if (interactive-p) (org-table-check-inside-data-field))
6614 (save-excursion
6615 (let ((cnt 0) (pos (point)))
6616 (beginning-of-line 1)
6617 (while (search-forward "|" pos t)
6618 (setq cnt (1+ cnt)))
6619 (if (interactive-p) (message "This is table column %d" cnt))
6620 cnt)))
6622 (defun org-table-current-dline ()
6623 "Find out what table data line we are in.
6624 Only datalins count for this."
6625 (interactive)
6626 (if (interactive-p) (org-table-check-inside-data-field))
6627 (save-excursion
6628 (let ((cnt 0) (pos (point)))
6629 (goto-char (org-table-begin))
6630 (while (<= (point) pos)
6631 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
6632 (beginning-of-line 2))
6633 (if (interactive-p) (message "This is table line %d" cnt))
6634 cnt)))
6636 (defun org-table-goto-column (n &optional on-delim force)
6637 "Move the cursor to the Nth column in the current table line.
6638 With optional argument ON-DELIM, stop with point before the left delimiter
6639 of the field.
6640 If there are less than N fields, just go to after the last delimiter.
6641 However, when FORCE is non-nil, create new columns if necessary."
6642 (interactive "p")
6643 (let ((pos (point-at-eol)))
6644 (beginning-of-line 1)
6645 (when (> n 0)
6646 (while (and (> (setq n (1- n)) -1)
6647 (or (search-forward "|" pos t)
6648 (and force
6649 (progn (end-of-line 1)
6650 (skip-chars-backward "^|")
6651 (insert " | "))))))
6652 ; (backward-char 2) t)))))
6653 (when (and force (not (looking-at ".*|")))
6654 (save-excursion (end-of-line 1) (insert " | ")))
6655 (if on-delim
6656 (backward-char 1)
6657 (if (looking-at " ") (forward-char 1))))))
6659 (defun org-at-table-p (&optional table-type)
6660 "Return t if the cursor is inside an org-type table.
6661 If TABLE-TYPE is non-nil, also check for table.el-type tables."
6662 (if org-enable-table-editor
6663 (save-excursion
6664 (beginning-of-line 1)
6665 (looking-at (if table-type org-table-any-line-regexp
6666 org-table-line-regexp)))
6667 nil))
6669 (defun org-at-table.el-p ()
6670 "Return t if and only if we are at a table.el table."
6671 (and (org-at-table-p 'any)
6672 (save-excursion
6673 (goto-char (org-table-begin 'any))
6674 (looking-at org-table1-hline-regexp))))
6676 (defun org-table-recognize-table.el ()
6677 "If there is a table.el table nearby, recognize it and move into it."
6678 (if org-table-tab-recognizes-table.el
6679 (if (org-at-table.el-p)
6680 (progn
6681 (beginning-of-line 1)
6682 (if (looking-at org-table-dataline-regexp)
6684 (if (looking-at org-table1-hline-regexp)
6685 (progn
6686 (beginning-of-line 2)
6687 (if (looking-at org-table-any-border-regexp)
6688 (beginning-of-line -1)))))
6689 (if (re-search-forward "|" (org-table-end t) t)
6690 (progn
6691 (require 'table)
6692 (if (table--at-cell-p (point))
6694 (message "recognizing table.el table...")
6695 (table-recognize-table)
6696 (message "recognizing table.el table...done")))
6697 (error "This should not happen..."))
6699 nil)
6700 nil))
6702 (defun org-at-table-hline-p ()
6703 "Return t if the cursor is inside a hline in a table."
6704 (if org-enable-table-editor
6705 (save-excursion
6706 (beginning-of-line 1)
6707 (looking-at org-table-hline-regexp))
6708 nil))
6710 (defun org-table-insert-column ()
6711 "Insert a new column into the table."
6712 (interactive)
6713 (if (not (org-at-table-p))
6714 (error "Not at a table"))
6715 (org-table-find-dataline)
6716 (let* ((col (max 1 (org-table-current-column)))
6717 (beg (org-table-begin))
6718 (end (org-table-end))
6719 ;; Current cursor position
6720 (linepos (org-current-line))
6721 (colpos col))
6722 (goto-char beg)
6723 (while (< (point) end)
6724 (if (org-at-table-hline-p)
6726 (org-table-goto-column col t)
6727 (insert "| "))
6728 (beginning-of-line 2))
6729 (move-marker end nil)
6730 (goto-line linepos)
6731 (org-table-goto-column colpos)
6732 (org-table-align)
6733 (org-table-fix-formulas "$" nil (1- col) 1)))
6735 (defun org-table-find-dataline ()
6736 "Find a dataline in the current table, which is needed for column commands."
6737 (if (and (org-at-table-p)
6738 (not (org-at-table-hline-p)))
6740 (let ((col (current-column))
6741 (end (org-table-end)))
6742 (move-to-column col)
6743 (while (and (< (point) end)
6744 (or (not (= (current-column) col))
6745 (org-at-table-hline-p)))
6746 (beginning-of-line 2)
6747 (move-to-column col))
6748 (if (and (org-at-table-p)
6749 (not (org-at-table-hline-p)))
6751 (error
6752 "Please position cursor in a data line for column operations")))))
6754 (defun org-table-delete-column ()
6755 "Delete a column from the table."
6756 (interactive)
6757 (if (not (org-at-table-p))
6758 (error "Not at a table"))
6759 (org-table-find-dataline)
6760 (org-table-check-inside-data-field)
6761 (let* ((col (org-table-current-column))
6762 (beg (org-table-begin))
6763 (end (org-table-end))
6764 ;; Current cursor position
6765 (linepos (org-current-line))
6766 (colpos col))
6767 (goto-char beg)
6768 (while (< (point) end)
6769 (if (org-at-table-hline-p)
6771 (org-table-goto-column col t)
6772 (and (looking-at "|[^|\n]+|")
6773 (replace-match "|")))
6774 (beginning-of-line 2))
6775 (move-marker end nil)
6776 (goto-line linepos)
6777 (org-table-goto-column colpos)
6778 (org-table-align)
6779 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
6780 col -1 col)))
6782 (defun org-table-move-column-right ()
6783 "Move column to the right."
6784 (interactive)
6785 (org-table-move-column nil))
6786 (defun org-table-move-column-left ()
6787 "Move column to the left."
6788 (interactive)
6789 (org-table-move-column 'left))
6791 (defun org-table-move-column (&optional left)
6792 "Move the current column to the right. With arg LEFT, move to the left."
6793 (interactive "P")
6794 (if (not (org-at-table-p))
6795 (error "Not at a table"))
6796 (org-table-find-dataline)
6797 (org-table-check-inside-data-field)
6798 (let* ((col (org-table-current-column))
6799 (col1 (if left (1- col) col))
6800 (beg (org-table-begin))
6801 (end (org-table-end))
6802 ;; Current cursor position
6803 (linepos (org-current-line))
6804 (colpos (if left (1- col) (1+ col))))
6805 (if (and left (= col 1))
6806 (error "Cannot move column further left"))
6807 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6808 (error "Cannot move column further right"))
6809 (goto-char beg)
6810 (while (< (point) end)
6811 (if (org-at-table-hline-p)
6813 (org-table-goto-column col1 t)
6814 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6815 (replace-match "|\\2|\\1|")))
6816 (beginning-of-line 2))
6817 (move-marker end nil)
6818 (goto-line linepos)
6819 (org-table-goto-column colpos)
6820 (org-table-align)
6821 (org-table-fix-formulas
6822 "$" (list (cons (number-to-string col) (number-to-string colpos))
6823 (cons (number-to-string colpos) (number-to-string col))))))
6825 (defun org-table-move-row-down ()
6826 "Move table row down."
6827 (interactive)
6828 (org-table-move-row nil))
6829 (defun org-table-move-row-up ()
6830 "Move table row up."
6831 (interactive)
6832 (org-table-move-row 'up))
6834 (defun org-table-move-row (&optional up)
6835 "Move the current table line down. With arg UP, move it up."
6836 (interactive "P")
6837 (let* ((col (current-column))
6838 (pos (point))
6839 (hline1p (save-excursion (beginning-of-line 1)
6840 (looking-at org-table-hline-regexp)))
6841 (dline1 (org-table-current-dline))
6842 (dline2 (+ dline1 (if up -1 1)))
6843 (tonew (if up 0 2))
6844 txt hline2p)
6845 (beginning-of-line tonew)
6846 (unless (org-at-table-p)
6847 (goto-char pos)
6848 (error "Cannot move row further"))
6849 (setq hline2p (looking-at org-table-hline-regexp))
6850 (goto-char pos)
6851 (beginning-of-line 1)
6852 (setq pos (point))
6853 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6854 (delete-region (point) (1+ (point-at-eol)))
6855 (beginning-of-line tonew)
6856 (insert txt)
6857 (beginning-of-line 0)
6858 (move-to-column col)
6859 (unless (or hline1p hline2p)
6860 (org-table-fix-formulas
6861 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
6862 (cons (number-to-string dline2) (number-to-string dline1)))))))
6864 (defun org-table-insert-row (&optional arg)
6865 "Insert a new row above the current line into the table.
6866 With prefix ARG, insert below the current line."
6867 (interactive "P")
6868 (if (not (org-at-table-p))
6869 (error "Not at a table"))
6870 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
6871 (new (org-table-clean-line line)))
6872 ;; Fix the first field if necessary
6873 (if (string-match "^[ \t]*| *[#$] *|" line)
6874 (setq new (replace-match (match-string 0 line) t t new)))
6875 (beginning-of-line (if arg 2 1))
6876 (let (org-table-may-need-update) (insert-before-markers new "\n"))
6877 (beginning-of-line 0)
6878 (re-search-forward "| ?" (point-at-eol) t)
6879 (and (or org-table-may-need-update org-table-overlay-coordinates)
6880 (org-table-align))
6881 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
6883 (defun org-table-insert-hline (&optional above)
6884 "Insert a horizontal-line below the current line into the table.
6885 With prefix ABOVE, insert above the current line."
6886 (interactive "P")
6887 (if (not (org-at-table-p))
6888 (error "Not at a table"))
6889 (let ((line (org-table-clean-line
6890 (buffer-substring (point-at-bol) (point-at-eol))))
6891 (col (current-column)))
6892 (while (string-match "|\\( +\\)|" line)
6893 (setq line (replace-match
6894 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
6895 ?-) "|") t t line)))
6896 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
6897 (beginning-of-line (if above 1 2))
6898 (insert line "\n")
6899 (beginning-of-line (if above 1 -1))
6900 (move-to-column col)
6901 (and org-table-overlay-coordinates (org-table-align))))
6903 (defun org-table-hline-and-move (&optional same-column)
6904 "Insert a hline and move to the row below that line."
6905 (interactive "P")
6906 (let ((col (org-table-current-column)))
6907 (org-table-maybe-eval-formula)
6908 (org-table-maybe-recalculate-line)
6909 (org-table-insert-hline)
6910 (end-of-line 2)
6911 (if (looking-at "\n[ \t]*|-")
6912 (progn (insert "\n|") (org-table-align))
6913 (org-table-next-field))
6914 (if same-column (org-table-goto-column col))))
6916 (defun org-table-clean-line (s)
6917 "Convert a table line S into a string with only \"|\" and space.
6918 In particular, this does handle wide and invisible characters."
6919 (if (string-match "^[ \t]*|-" s)
6920 ;; It's a hline, just map the characters
6921 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
6922 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
6923 (setq s (replace-match
6924 (concat "|" (make-string (org-string-width (match-string 1 s))
6925 ?\ ) "|")
6926 t t s)))
6929 (defun org-table-kill-row ()
6930 "Delete the current row or horizontal line from the table."
6931 (interactive)
6932 (if (not (org-at-table-p))
6933 (error "Not at a table"))
6934 (let ((col (current-column))
6935 (dline (org-table-current-dline)))
6936 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6937 (if (not (org-at-table-p)) (beginning-of-line 0))
6938 (move-to-column col)
6939 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
6940 dline -1 dline)))
6943 (defun org-table-sort-lines (with-case &optional sorting-type)
6944 "Sort table lines according to the column at point.
6946 The position of point indicates the column to be used for
6947 sorting, and the range of lines is the range between the nearest
6948 horizontal separator lines, or the entire table of no such lines
6949 exist. If point is before the first column, you will be prompted
6950 for the sorting column. If there is an active region, the mark
6951 specifies the first line and the sorting column, while point
6952 should be in the last line to be included into the sorting.
6954 The command then prompts for the sorting type which can be
6955 alphabetically, numerically, or by time (as given in a time stamp
6956 in the field). Sorting in reverse order is also possible.
6958 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
6960 If SORTING-TYPE is specified when this function is called from a Lisp
6961 program, no prompting will take place. SORTING-TYPE must be a character,
6962 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
6963 should be done in reverse order."
6964 (interactive "P")
6965 (let* ((thisline (org-current-line))
6966 (thiscol (org-table-current-column))
6967 beg end bcol ecol tend tbeg column lns pos)
6968 (when (equal thiscol 0)
6969 (if (interactive-p)
6970 (setq thiscol
6971 (string-to-number
6972 (read-string "Use column N for sorting: ")))
6973 (setq thiscol 1))
6974 (org-table-goto-column thiscol))
6975 (org-table-check-inside-data-field)
6976 (if (org-region-active-p)
6977 (progn
6978 (setq beg (region-beginning) end (region-end))
6979 (goto-char beg)
6980 (setq column (org-table-current-column)
6981 beg (point-at-bol))
6982 (goto-char end)
6983 (setq end (point-at-bol 2)))
6984 (setq column (org-table-current-column)
6985 pos (point)
6986 tbeg (org-table-begin)
6987 tend (org-table-end))
6988 (if (re-search-backward org-table-hline-regexp tbeg t)
6989 (setq beg (point-at-bol 2))
6990 (goto-char tbeg)
6991 (setq beg (point-at-bol 1)))
6992 (goto-char pos)
6993 (if (re-search-forward org-table-hline-regexp tend t)
6994 (setq beg (point-at-bol 0))
6995 (goto-char tend)
6996 (setq end (point-at-bol))))
6997 (setq beg (move-marker (make-marker) beg)
6998 end (move-marker (make-marker) end))
6999 (untabify beg end)
7000 (goto-char beg)
7001 (org-table-goto-column column)
7002 (skip-chars-backward "^|")
7003 (setq bcol (current-column))
7004 (org-table-goto-column (1+ column))
7005 (skip-chars-backward "^|")
7006 (setq ecol (1- (current-column)))
7007 (org-table-goto-column column)
7008 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
7009 (org-split-string (buffer-substring beg end) "\n")))
7010 (setq lns (org-do-sort lns "Table" with-case sorting-type))
7011 (delete-region beg end)
7012 (move-marker beg nil)
7013 (move-marker end nil)
7014 (insert (mapconcat 'cdr lns "\n") "\n")
7015 (goto-line thisline)
7016 (org-table-goto-column thiscol)
7017 (message "%d lines sorted, based on column %d" (length lns) column)))
7019 (defun org-table-cut-region (beg end)
7020 "Copy region in table to the clipboard and blank all relevant fields."
7021 (interactive "r")
7022 (org-table-copy-region beg end 'cut))
7024 (defun org-table-copy-region (beg end &optional cut)
7025 "Copy rectangular region in table to clipboard.
7026 A special clipboard is used which can only be accessed
7027 with `org-table-paste-rectangle'."
7028 (interactive "rP")
7029 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
7030 region cols
7031 (rpl (if cut " " nil)))
7032 (goto-char beg)
7033 (org-table-check-inside-data-field)
7034 (setq l01 (org-current-line)
7035 c01 (org-table-current-column))
7036 (goto-char end)
7037 (org-table-check-inside-data-field)
7038 (setq l02 (org-current-line)
7039 c02 (org-table-current-column))
7040 (setq l1 (min l01 l02) l2 (max l01 l02)
7041 c1 (min c01 c02) c2 (max c01 c02))
7042 (catch 'exit
7043 (while t
7044 (catch 'nextline
7045 (if (> l1 l2) (throw 'exit t))
7046 (goto-line l1)
7047 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
7048 (setq cols nil ic1 c1 ic2 c2)
7049 (while (< ic1 (1+ ic2))
7050 (push (org-table-get-field ic1 rpl) cols)
7051 (setq ic1 (1+ ic1)))
7052 (push (nreverse cols) region)
7053 (setq l1 (1+ l1)))))
7054 (setq org-table-clip (nreverse region))
7055 (if cut (org-table-align))
7056 org-table-clip))
7058 (defun org-table-paste-rectangle ()
7059 "Paste a rectangular region into a table.
7060 The upper right corner ends up in the current field. All involved fields
7061 will be overwritten. If the rectangle does not fit into the present table,
7062 the table is enlarged as needed. The process ignores horizontal separator
7063 lines."
7064 (interactive)
7065 (unless (and org-table-clip (listp org-table-clip))
7066 (error "First cut/copy a region to paste!"))
7067 (org-table-check-inside-data-field)
7068 (let* ((clip org-table-clip)
7069 (line (org-current-line))
7070 (col (org-table-current-column))
7071 (org-enable-table-editor t)
7072 (org-table-automatic-realign nil)
7073 c cols field)
7074 (while (setq cols (pop clip))
7075 (while (org-at-table-hline-p) (beginning-of-line 2))
7076 (if (not (org-at-table-p))
7077 (progn (end-of-line 0) (org-table-next-field)))
7078 (setq c col)
7079 (while (setq field (pop cols))
7080 (org-table-goto-column c nil 'force)
7081 (org-table-get-field nil field)
7082 (setq c (1+ c)))
7083 (beginning-of-line 2))
7084 (goto-line line)
7085 (org-table-goto-column col)
7086 (org-table-align)))
7088 (defun org-table-convert ()
7089 "Convert from `org-mode' table to table.el and back.
7090 Obviously, this only works within limits. When an Org-mode table is
7091 converted to table.el, all horizontal separator lines get lost, because
7092 table.el uses these as cell boundaries and has no notion of horizontal lines.
7093 A table.el table can be converted to an Org-mode table only if it does not
7094 do row or column spanning. Multiline cells will become multiple cells.
7095 Beware, Org-mode does not test if the table can be successfully converted - it
7096 blindly applies a recipe that works for simple tables."
7097 (interactive)
7098 (require 'table)
7099 (if (org-at-table.el-p)
7100 ;; convert to Org-mode table
7101 (let ((beg (move-marker (make-marker) (org-table-begin t)))
7102 (end (move-marker (make-marker) (org-table-end t))))
7103 (table-unrecognize-region beg end)
7104 (goto-char beg)
7105 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
7106 (replace-match ""))
7107 (goto-char beg))
7108 (if (org-at-table-p)
7109 ;; convert to table.el table
7110 (let ((beg (move-marker (make-marker) (org-table-begin)))
7111 (end (move-marker (make-marker) (org-table-end))))
7112 ;; first, get rid of all horizontal lines
7113 (goto-char beg)
7114 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
7115 (replace-match ""))
7116 ;; insert a hline before first
7117 (goto-char beg)
7118 (org-table-insert-hline 'above)
7119 (beginning-of-line -1)
7120 ;; insert a hline after each line
7121 (while (progn (beginning-of-line 3) (< (point) end))
7122 (org-table-insert-hline))
7123 (goto-char beg)
7124 (setq end (move-marker end (org-table-end)))
7125 ;; replace "+" at beginning and ending of hlines
7126 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
7127 (replace-match "\\1+-"))
7128 (goto-char beg)
7129 (while (re-search-forward "-|[ \t]*$" end t)
7130 (replace-match "-+"))
7131 (goto-char beg)))))
7133 (defun org-table-wrap-region (arg)
7134 "Wrap several fields in a column like a paragraph.
7135 This is useful if you'd like to spread the contents of a field over several
7136 lines, in order to keep the table compact.
7138 If there is an active region, and both point and mark are in the same column,
7139 the text in the column is wrapped to minimum width for the given number of
7140 lines. Generally, this makes the table more compact. A prefix ARG may be
7141 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
7142 formats the selected text to two lines. If the region was longer than two
7143 lines, the remaining lines remain empty. A negative prefix argument reduces
7144 the current number of lines by that amount. The wrapped text is pasted back
7145 into the table. If you formatted it to more lines than it was before, fields
7146 further down in the table get overwritten - so you might need to make space in
7147 the table first.
7149 If there is no region, the current field is split at the cursor position and
7150 the text fragment to the right of the cursor is prepended to the field one
7151 line down.
7153 If there is no region, but you specify a prefix ARG, the current field gets
7154 blank, and the content is appended to the field above."
7155 (interactive "P")
7156 (org-table-check-inside-data-field)
7157 (if (org-region-active-p)
7158 ;; There is a region: fill as a paragraph
7159 (let* ((beg (region-beginning))
7160 (cline (save-excursion (goto-char beg) (org-current-line)))
7161 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
7162 nlines)
7163 (org-table-cut-region (region-beginning) (region-end))
7164 (if (> (length (car org-table-clip)) 1)
7165 (error "Region must be limited to single column"))
7166 (setq nlines (if arg
7167 (if (< arg 1)
7168 (+ (length org-table-clip) arg)
7169 arg)
7170 (length org-table-clip)))
7171 (setq org-table-clip
7172 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
7173 nil nlines)))
7174 (goto-line cline)
7175 (org-table-goto-column ccol)
7176 (org-table-paste-rectangle))
7177 ;; No region, split the current field at point
7178 (if arg
7179 ;; combine with field above
7180 (let ((s (org-table-blank-field))
7181 (col (org-table-current-column)))
7182 (beginning-of-line 0)
7183 (while (org-at-table-hline-p) (beginning-of-line 0))
7184 (org-table-goto-column col)
7185 (skip-chars-forward "^|")
7186 (skip-chars-backward " ")
7187 (insert " " (org-trim s))
7188 (org-table-align))
7189 ;; split field
7190 (when (looking-at "\\([^|]+\\)+|")
7191 (let ((s (match-string 1)))
7192 (replace-match " |")
7193 (goto-char (match-beginning 0))
7194 (org-table-next-row)
7195 (insert (org-trim s) " ")
7196 (org-table-align))))))
7198 (defvar org-field-marker nil)
7200 (defun org-table-edit-field (arg)
7201 "Edit table field in a different window.
7202 This is mainly useful for fields that contain hidden parts.
7203 When called with a \\[universal-argument] prefix, just make the full field visible so that
7204 it can be edited in place."
7205 (interactive "P")
7206 (if arg
7207 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
7208 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
7209 (remove-text-properties b e '(org-cwidth t invisible t
7210 display t intangible t))
7211 (if (and (boundp 'font-lock-mode) font-lock-mode)
7212 (font-lock-fontify-block)))
7213 (let ((pos (move-marker (make-marker) (point)))
7214 (field (org-table-get-field))
7215 (cw (current-window-configuration))
7217 (switch-to-buffer-other-window "*Org tmp*")
7218 (erase-buffer)
7219 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
7220 (let ((org-inhibit-startup t)) (org-mode))
7221 (goto-char (setq p (point-max)))
7222 (insert (org-trim field))
7223 (remove-text-properties p (point-max)
7224 '(invisible t org-cwidth t display t
7225 intangible t))
7226 (goto-char p)
7227 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
7228 (org-set-local 'org-window-configuration cw)
7229 (org-set-local 'org-field-marker pos)
7230 (message "Edit and finish with C-c C-c"))))
7232 (defun org-table-finish-edit-field ()
7233 "Finish editing a table data field.
7234 Remove all newline characters, insert the result into the table, realign
7235 the table and kill the editing buffer."
7236 (let ((pos org-field-marker)
7237 (cw org-window-configuration)
7238 (cb (current-buffer))
7239 text)
7240 (goto-char (point-min))
7241 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
7242 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
7243 (replace-match " "))
7244 (setq text (org-trim (buffer-string)))
7245 (set-window-configuration cw)
7246 (kill-buffer cb)
7247 (select-window (get-buffer-window (marker-buffer pos)))
7248 (goto-char pos)
7249 (move-marker pos nil)
7250 (org-table-check-inside-data-field)
7251 (org-table-get-field nil text)
7252 (org-table-align)
7253 (message "New field value inserted")))
7255 (defun org-trim (s)
7256 "Remove whitespace at beginning and end of string."
7257 (if (string-match "^[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
7258 (if (string-match "[ \t\n\r]+$" s) (setq s (replace-match "" t t s)))
7261 (defun org-wrap (string &optional width lines)
7262 "Wrap string to either a number of lines, or a width in characters.
7263 If WIDTH is non-nil, the string is wrapped to that width, however many lines
7264 that costs. If there is a word longer than WIDTH, the text is actually
7265 wrapped to the length of that word.
7266 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
7267 many lines, whatever width that takes.
7268 The return value is a list of lines, without newlines at the end."
7269 (let* ((words (org-split-string string "[ \t\n]+"))
7270 (maxword (apply 'max (mapcar 'org-string-width words)))
7271 w ll)
7272 (cond (width
7273 (org-do-wrap words (max maxword width)))
7274 (lines
7275 (setq w maxword)
7276 (setq ll (org-do-wrap words maxword))
7277 (if (<= (length ll) lines)
7279 (setq ll words)
7280 (while (> (length ll) lines)
7281 (setq w (1+ w))
7282 (setq ll (org-do-wrap words w)))
7283 ll))
7284 (t (error "Cannot wrap this")))))
7287 (defun org-do-wrap (words width)
7288 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
7289 (let (lines line)
7290 (while words
7291 (setq line (pop words))
7292 (while (and words (< (+ (length line) (length (car words))) width))
7293 (setq line (concat line " " (pop words))))
7294 (setq lines (push line lines)))
7295 (nreverse lines)))
7297 (defun org-split-string (string &optional separators)
7298 "Splits STRING into substrings at SEPARATORS.
7299 No empty strings are returned if there are matches at the beginning
7300 and end of string."
7301 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
7302 (start 0)
7303 notfirst
7304 (list nil))
7305 (while (and (string-match rexp string
7306 (if (and notfirst
7307 (= start (match-beginning 0))
7308 (< start (length string)))
7309 (1+ start) start))
7310 (< (match-beginning 0) (length string)))
7311 (setq notfirst t)
7312 (or (eq (match-beginning 0) 0)
7313 (and (eq (match-beginning 0) (match-end 0))
7314 (eq (match-beginning 0) start))
7315 (setq list
7316 (cons (substring string start (match-beginning 0))
7317 list)))
7318 (setq start (match-end 0)))
7319 (or (eq start (length string))
7320 (setq list
7321 (cons (substring string start)
7322 list)))
7323 (nreverse list)))
7325 (defun org-table-map-tables (function)
7326 "Apply FUNCTION to the start of all tables in the buffer."
7327 (save-excursion
7328 (save-restriction
7329 (widen)
7330 (goto-char (point-min))
7331 (while (re-search-forward org-table-any-line-regexp nil t)
7332 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
7333 (beginning-of-line 1)
7334 (if (looking-at org-table-line-regexp)
7335 (save-excursion (funcall function)))
7336 (re-search-forward org-table-any-border-regexp nil 1))))
7337 (message "Mapping tables: done"))
7339 (defvar org-timecnt) ; dynamically scoped parameter
7341 (defun org-table-sum (&optional beg end nlast)
7342 "Sum numbers in region of current table column.
7343 The result will be displayed in the echo area, and will be available
7344 as kill to be inserted with \\[yank].
7346 If there is an active region, it is interpreted as a rectangle and all
7347 numbers in that rectangle will be summed. If there is no active
7348 region and point is located in a table column, sum all numbers in that
7349 column.
7351 If at least one number looks like a time HH:MM or HH:MM:SS, all other
7352 numbers are assumed to be times as well (in decimal hours) and the
7353 numbers are added as such.
7355 If NLAST is a number, only the NLAST fields will actually be summed."
7356 (interactive)
7357 (save-excursion
7358 (let (col (org-timecnt 0) diff h m s org-table-clip)
7359 (cond
7360 ((and beg end)) ; beg and end given explicitly
7361 ((org-region-active-p)
7362 (setq beg (region-beginning) end (region-end)))
7364 (setq col (org-table-current-column))
7365 (goto-char (org-table-begin))
7366 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
7367 (error "No table data"))
7368 (org-table-goto-column col)
7369 (setq beg (point))
7370 (goto-char (org-table-end))
7371 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
7372 (error "No table data"))
7373 (org-table-goto-column col)
7374 (setq end (point))))
7375 (let* ((items (apply 'append (org-table-copy-region beg end)))
7376 (items1 (cond ((not nlast) items)
7377 ((>= nlast (length items)) items)
7378 (t (setq items (reverse items))
7379 (setcdr (nthcdr (1- nlast) items) nil)
7380 (nreverse items))))
7381 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
7382 items1)))
7383 (res (apply '+ numbers))
7384 (sres (if (= org-timecnt 0)
7385 (format "%g" res)
7386 (setq diff (* 3600 res)
7387 h (floor (/ diff 3600)) diff (mod diff 3600)
7388 m (floor (/ diff 60)) diff (mod diff 60)
7389 s diff)
7390 (format "%d:%02d:%02d" h m s))))
7391 (kill-new sres)
7392 (if (interactive-p)
7393 (message "%s"
7394 (substitute-command-keys
7395 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
7396 (length numbers) sres))))
7397 sres))))
7399 (defun org-table-get-number-for-summing (s)
7400 (let (n)
7401 (if (string-match "^ *|? *" s)
7402 (setq s (replace-match "" nil nil s)))
7403 (if (string-match " *|? *$" s)
7404 (setq s (replace-match "" nil nil s)))
7405 (setq n (string-to-number s))
7406 (cond
7407 ((and (string-match "0" s)
7408 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
7409 ((string-match "\\`[ \t]+\\'" s) nil)
7410 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
7411 (let ((h (string-to-number (or (match-string 1 s) "0")))
7412 (m (string-to-number (or (match-string 2 s) "0")))
7413 (s (string-to-number (or (match-string 4 s) "0"))))
7414 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
7415 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
7416 ((equal n 0) nil)
7417 (t n))))
7419 (defun org-table-current-field-formula (&optional key noerror)
7420 "Return the formula active for the current field.
7421 Assumes that specials are in place.
7422 If KEY is given, return the key to this formula.
7423 Otherwise return the formula preceeded with \"=\" or \":=\"."
7424 (let* ((name (car (rassoc (list (org-current-line)
7425 (org-table-current-column))
7426 org-table-named-field-locations)))
7427 (col (org-table-current-column))
7428 (scol (int-to-string col))
7429 (ref (format "@%d$%d" (org-table-current-dline) col))
7430 (stored-list (org-table-get-stored-formulas noerror))
7431 (ass (or (assoc name stored-list)
7432 (assoc ref stored-list)
7433 (assoc scol stored-list))))
7434 (if key
7435 (car ass)
7436 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
7437 (cdr ass))))))
7439 (defun org-table-get-formula (&optional equation named)
7440 "Read a formula from the minibuffer, offer stored formula as default.
7441 When NAMED is non-nil, look for a named equation."
7442 (let* ((stored-list (org-table-get-stored-formulas))
7443 (name (car (rassoc (list (org-current-line)
7444 (org-table-current-column))
7445 org-table-named-field-locations)))
7446 (ref (format "@%d$%d" (org-table-current-dline)
7447 (org-table-current-column)))
7448 (refass (assoc ref stored-list))
7449 (scol (if named
7450 (if name name ref)
7451 (int-to-string (org-table-current-column))))
7452 (dummy (and (or name refass) (not named)
7453 (not (y-or-n-p "Replace field formula with column formula? " ))
7454 (error "Abort")))
7455 (name (or name ref))
7456 (org-table-may-need-update nil)
7457 (stored (cdr (assoc scol stored-list)))
7458 (eq (cond
7459 ((and stored equation (string-match "^ *=? *$" equation))
7460 stored)
7461 ((stringp equation)
7462 equation)
7463 (t (org-table-formula-from-user
7464 (read-string
7465 (org-table-formula-to-user
7466 (format "%s formula %s%s="
7467 (if named "Field" "Column")
7468 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
7469 scol))
7470 (if stored (org-table-formula-to-user stored) "")
7471 'org-table-formula-history
7472 )))))
7473 mustsave)
7474 (when (not (string-match "\\S-" eq))
7475 ;; remove formula
7476 (setq stored-list (delq (assoc scol stored-list) stored-list))
7477 (org-table-store-formulas stored-list)
7478 (error "Formula removed"))
7479 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7480 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7481 (if (and name (not named))
7482 ;; We set the column equation, delete the named one.
7483 (setq stored-list (delq (assoc name stored-list) stored-list)
7484 mustsave t))
7485 (if stored
7486 (setcdr (assoc scol stored-list) eq)
7487 (setq stored-list (cons (cons scol eq) stored-list)))
7488 (if (or mustsave (not (equal stored eq)))
7489 (org-table-store-formulas stored-list))
7490 eq))
7492 (defun org-table-store-formulas (alist)
7493 "Store the list of formulas below the current table."
7494 (setq alist (sort alist 'org-table-formula-less-p))
7495 (save-excursion
7496 (goto-char (org-table-end))
7497 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
7498 (progn
7499 ;; don't overwrite TBLFM, we might use text properties to store stuff
7500 (goto-char (match-beginning 2))
7501 (delete-region (match-beginning 2) (match-end 0)))
7502 (insert "#+TBLFM:"))
7503 (insert " "
7504 (mapconcat (lambda (x)
7505 (concat
7506 (if (equal (string-to-char (car x)) ?@) "" "$")
7507 (car x) "=" (cdr x)))
7508 alist "::")
7509 "\n")))
7511 (defsubst org-table-formula-make-cmp-string (a)
7512 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
7513 (concat
7514 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
7515 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
7516 (if (match-end 5) (concat "@@" (match-string 5 a))))))
7518 (defun org-table-formula-less-p (a b)
7519 "Compare two formulas for sorting."
7520 (let ((as (org-table-formula-make-cmp-string (car a)))
7521 (bs (org-table-formula-make-cmp-string (car b))))
7522 (and as bs (string< as bs))))
7524 (defun org-table-get-stored-formulas (&optional noerror)
7525 "Return an alist with the stored formulas directly after current table."
7526 (interactive)
7527 (let (scol eq eq-alist strings string seen)
7528 (save-excursion
7529 (goto-char (org-table-end))
7530 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7531 (setq strings (org-split-string (match-string 2) " *:: *"))
7532 (while (setq string (pop strings))
7533 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
7534 (setq scol (if (match-end 2)
7535 (match-string 2 string)
7536 (match-string 1 string))
7537 eq (match-string 3 string)
7538 eq-alist (cons (cons scol eq) eq-alist))
7539 (if (member scol seen)
7540 (if noerror
7541 (progn
7542 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7543 (ding)
7544 (sit-for 2))
7545 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
7546 (push scol seen))))))
7547 (nreverse eq-alist)))
7549 (defun org-table-fix-formulas (key replace &optional limit delta remove)
7550 "Modify the equations after the table structure has been edited.
7551 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
7552 For all numbers larger than LIMIT, shift them by DELTA."
7553 (save-excursion
7554 (goto-char (org-table-end))
7555 (when (looking-at "#\\+TBLFM:")
7556 (let ((re (concat key "\\([0-9]+\\)"))
7557 (re2
7558 (when remove
7559 (if (equal key "$")
7560 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
7561 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
7562 s n a)
7563 (when remove
7564 (while (re-search-forward re2 (point-at-eol) t)
7565 (replace-match "")))
7566 (while (re-search-forward re (point-at-eol) t)
7567 (setq s (match-string 1) n (string-to-number s))
7568 (cond
7569 ((setq a (assoc s replace))
7570 (replace-match (concat key (cdr a)) t t))
7571 ((and limit (> n limit))
7572 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
7574 (defun org-table-get-specials ()
7575 "Get the column names and local parameters for this table."
7576 (save-excursion
7577 (let ((beg (org-table-begin)) (end (org-table-end))
7578 names name fields fields1 field cnt
7579 c v l line col types dlines hlines)
7580 (setq org-table-column-names nil
7581 org-table-local-parameters nil
7582 org-table-named-field-locations nil
7583 org-table-current-begin-line nil
7584 org-table-current-begin-pos nil
7585 org-table-current-line-types nil)
7586 (goto-char beg)
7587 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7588 (setq names (org-split-string (match-string 1) " *| *")
7589 cnt 1)
7590 (while (setq name (pop names))
7591 (setq cnt (1+ cnt))
7592 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7593 (push (cons name (int-to-string cnt)) org-table-column-names))))
7594 (setq org-table-column-names (nreverse org-table-column-names))
7595 (setq org-table-column-name-regexp
7596 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7597 (goto-char beg)
7598 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7599 (setq fields (org-split-string (match-string 1) " *| *"))
7600 (while (setq field (pop fields))
7601 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7602 (push (cons (match-string 1 field) (match-string 2 field))
7603 org-table-local-parameters))))
7604 (goto-char beg)
7605 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7606 (setq c (match-string 1)
7607 fields (org-split-string (match-string 2) " *| *"))
7608 (save-excursion
7609 (beginning-of-line (if (equal c "_") 2 0))
7610 (setq line (org-current-line) col 1)
7611 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7612 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7613 (while (and fields1 (setq field (pop fields)))
7614 (setq v (pop fields1) col (1+ col))
7615 (when (and (stringp field) (stringp v)
7616 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7617 (push (cons field v) org-table-local-parameters)
7618 (push (list field line col) org-table-named-field-locations))))
7619 ;; Analyse the line types
7620 (goto-char beg)
7621 (setq org-table-current-begin-line (org-current-line)
7622 org-table-current-begin-pos (point)
7623 l org-table-current-begin-line)
7624 (while (looking-at "[ \t]*|\\(-\\)?")
7625 (push (if (match-end 1) 'hline 'dline) types)
7626 (if (match-end 1) (push l hlines) (push l dlines))
7627 (beginning-of-line 2)
7628 (setq l (1+ l)))
7629 (setq org-table-current-line-types (apply 'vector (nreverse types))
7630 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
7631 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
7633 (defun org-table-maybe-eval-formula ()
7634 "Check if the current field starts with \"=\" or \":=\".
7635 If yes, store the formula and apply it."
7636 ;; We already know we are in a table. Get field will only return a formula
7637 ;; when appropriate. It might return a separator line, but no problem.
7638 (when org-table-formula-evaluate-inline
7639 (let* ((field (org-trim (or (org-table-get-field) "")))
7640 named eq)
7641 (when (string-match "^:?=\\(.*\\)" field)
7642 (setq named (equal (string-to-char field) ?:)
7643 eq (match-string 1 field))
7644 (if (or (fboundp 'calc-eval)
7645 (equal (substring eq 0 (min 2 (length eq))) "'("))
7646 (org-table-eval-formula (if named '(4) nil)
7647 (org-table-formula-from-user eq))
7648 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
7650 (defvar org-recalc-commands nil
7651 "List of commands triggering the recalculation of a line.
7652 Will be filled automatically during use.")
7654 (defvar org-recalc-marks
7655 '((" " . "Unmarked: no special line, no automatic recalculation")
7656 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7657 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7658 ("!" . "Column name definition line. Reference in formula as $name.")
7659 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7660 ("_" . "Names for values in row below this one.")
7661 ("^" . "Names for values in row above this one.")))
7663 (defun org-table-rotate-recalc-marks (&optional newchar)
7664 "Rotate the recalculation mark in the first column.
7665 If in any row, the first field is not consistent with a mark,
7666 insert a new column for the markers.
7667 When there is an active region, change all the lines in the region,
7668 after prompting for the marking character.
7669 After each change, a message will be displayed indicating the meaning
7670 of the new mark."
7671 (interactive)
7672 (unless (org-at-table-p) (error "Not at a table"))
7673 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7674 (beg (org-table-begin))
7675 (end (org-table-end))
7676 (l (org-current-line))
7677 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7678 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7679 (have-col
7680 (save-excursion
7681 (goto-char beg)
7682 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7683 (col (org-table-current-column))
7684 (forcenew (car (assoc newchar org-recalc-marks)))
7685 epos new)
7686 (when l1
7687 (message "Change region to what mark? Type # * ! $ or SPC: ")
7688 (setq newchar (char-to-string (read-char-exclusive))
7689 forcenew (car (assoc newchar org-recalc-marks))))
7690 (if (and newchar (not forcenew))
7691 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7692 newchar))
7693 (if l1 (goto-line l1))
7694 (save-excursion
7695 (beginning-of-line 1)
7696 (unless (looking-at org-table-dataline-regexp)
7697 (error "Not at a table data line")))
7698 (unless have-col
7699 (org-table-goto-column 1)
7700 (org-table-insert-column)
7701 (org-table-goto-column (1+ col)))
7702 (setq epos (point-at-eol))
7703 (save-excursion
7704 (beginning-of-line 1)
7705 (org-table-get-field
7706 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7707 (concat " "
7708 (setq new (or forcenew
7709 (cadr (member (match-string 1) marks))))
7710 " ")
7711 " # ")))
7712 (if (and l1 l2)
7713 (progn
7714 (goto-line l1)
7715 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7716 (and (looking-at org-table-dataline-regexp)
7717 (org-table-get-field 1 (concat " " new " "))))
7718 (goto-line l1)))
7719 (if (not (= epos (point-at-eol))) (org-table-align))
7720 (goto-line l)
7721 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7723 (defun org-table-maybe-recalculate-line ()
7724 "Recompute the current line if marked for it, and if we haven't just done it."
7725 (interactive)
7726 (and org-table-allow-automatic-line-recalculation
7727 (not (and (memq last-command org-recalc-commands)
7728 (equal org-last-recalc-line (org-current-line))))
7729 (save-excursion (beginning-of-line 1)
7730 (looking-at org-table-auto-recalculate-regexp))
7731 (org-table-recalculate) t))
7733 (defvar org-table-formula-debug nil
7734 "Non-nil means, debug table formulas.
7735 When nil, simply write \"#ERROR\" in corrupted fields.")
7736 (make-variable-buffer-local 'org-table-formula-debug)
7738 (defvar modes)
7739 (defsubst org-set-calc-mode (var &optional value)
7740 (if (stringp var)
7741 (setq var (assoc var '(("D" calc-angle-mode deg)
7742 ("R" calc-angle-mode rad)
7743 ("F" calc-prefer-frac t)
7744 ("S" calc-symbolic-mode t)))
7745 value (nth 2 var) var (nth 1 var)))
7746 (if (memq var modes)
7747 (setcar (cdr (memq var modes)) value)
7748 (cons var (cons value modes)))
7749 modes)
7751 (defun org-table-eval-formula (&optional arg equation
7752 suppress-align suppress-const
7753 suppress-store suppress-analysis)
7754 "Replace the table field value at the cursor by the result of a calculation.
7756 This function makes use of Dave Gillespie's Calc package, in my view the
7757 most exciting program ever written for GNU Emacs. So you need to have Calc
7758 installed in order to use this function.
7760 In a table, this command replaces the value in the current field with the
7761 result of a formula. It also installs the formula as the \"current\" column
7762 formula, by storing it in a special line below the table. When called
7763 with a `C-u' prefix, the current field must ba a named field, and the
7764 formula is installed as valid in only this specific field.
7766 When called with two `C-u' prefixes, insert the active equation
7767 for the field back into the current field, so that it can be
7768 edited there. This is useful in order to use \\[org-table-show-reference]
7769 to check the referenced fields.
7771 When called, the command first prompts for a formula, which is read in
7772 the minibuffer. Previously entered formulas are available through the
7773 history list, and the last used formula is offered as a default.
7774 These stored formulas are adapted correctly when moving, inserting, or
7775 deleting columns with the corresponding commands.
7777 The formula can be any algebraic expression understood by the Calc package.
7778 For details, see the Org-mode manual.
7780 This function can also be called from Lisp programs and offers
7781 additional arguments: EQUATION can be the formula to apply. If this
7782 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7783 used to speed-up recursive calls by by-passing unnecessary aligns.
7784 SUPPRESS-CONST suppresses the interpretation of constants in the
7785 formula, assuming that this has been done already outside the function.
7786 SUPPRESS-STORE means the formula should not be stored, either because
7787 it is already stored, or because it is a modified equation that should
7788 not overwrite the stored one."
7789 (interactive "P")
7790 (org-table-check-inside-data-field)
7791 (or suppress-analysis (org-table-get-specials))
7792 (if (equal arg '(16))
7793 (let ((eq (org-table-current-field-formula)))
7794 (or eq (error "No equation active for current field"))
7795 (org-table-get-field nil eq)
7796 (org-table-align)
7797 (setq org-table-may-need-update t))
7798 (let* (fields
7799 (ndown (if (integerp arg) arg 1))
7800 (org-table-automatic-realign nil)
7801 (case-fold-search nil)
7802 (down (> ndown 1))
7803 (formula (if (and equation suppress-store)
7804 equation
7805 (org-table-get-formula equation (equal arg '(4)))))
7806 (n0 (org-table-current-column))
7807 (modes (copy-sequence org-calc-default-modes))
7808 (numbers nil) ; was a variable, now fixed default
7809 (keep-empty nil)
7810 n form form0 bw fmt x ev orig c lispp)
7811 ;; Parse the format string. Since we have a lot of modes, this is
7812 ;; a lot of work. However, I think calc still uses most of the time.
7813 (if (string-match ";" formula)
7814 (let ((tmp (org-split-string formula ";")))
7815 (setq formula (car tmp)
7816 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7817 (nth 1 tmp)))
7818 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
7819 (setq c (string-to-char (match-string 1 fmt))
7820 n (string-to-number (match-string 2 fmt)))
7821 (if (= c ?p)
7822 (setq modes (org-set-calc-mode 'calc-internal-prec n))
7823 (setq modes (org-set-calc-mode
7824 'calc-float-format
7825 (list (cdr (assoc c '((?n . float) (?f . fix)
7826 (?s . sci) (?e . eng))))
7827 n))))
7828 (setq fmt (replace-match "" t t fmt)))
7829 (if (string-match "[NT]" fmt)
7830 (setq numbers (equal (match-string 0 fmt) "N")
7831 fmt (replace-match "" t t fmt)))
7832 (if (string-match "E" fmt)
7833 (setq keep-empty t
7834 fmt (replace-match "" t t fmt)))
7835 (while (string-match "[DRFS]" fmt)
7836 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7837 (setq fmt (replace-match "" t t fmt)))
7838 (unless (string-match "\\S-" fmt)
7839 (setq fmt nil))))
7840 (if (and (not suppress-const) org-table-formula-use-constants)
7841 (setq formula (org-table-formula-substitute-names formula)))
7842 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7843 (while (> ndown 0)
7844 (setq fields (org-split-string
7845 (org-no-properties
7846 (buffer-substring (point-at-bol) (point-at-eol)))
7847 " *| *"))
7848 (if numbers
7849 (setq fields (mapcar
7850 (lambda (x) (number-to-string (string-to-number x)))
7851 fields)))
7852 (setq ndown (1- ndown))
7853 (setq form (copy-sequence formula)
7854 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
7855 ;; Check for old vertical references
7856 (setq form (org-rewrite-old-row-references form))
7857 ;; Insert complex ranges
7858 (while (string-match org-table-range-regexp form)
7859 (setq form
7860 (replace-match
7861 (save-match-data
7862 (org-table-make-reference
7863 (org-table-get-range (match-string 0 form) nil n0)
7864 keep-empty numbers lispp))
7865 t t form)))
7866 ;; Insert simple ranges
7867 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
7868 (setq form
7869 (replace-match
7870 (save-match-data
7871 (org-table-make-reference
7872 (org-sublist
7873 fields (string-to-number (match-string 1 form))
7874 (string-to-number (match-string 2 form)))
7875 keep-empty numbers lispp))
7876 t t form)))
7877 (setq form0 form)
7878 ;; Insert the references to fields in same row
7879 (while (string-match "\\$\\([0-9]+\\)" form)
7880 (setq n (string-to-number (match-string 1 form))
7881 x (nth (1- (if (= n 0) n0 n)) fields))
7882 (unless x (error "Invalid field specifier \"%s\""
7883 (match-string 0 form)))
7884 (setq form (replace-match
7885 (save-match-data
7886 (org-table-make-reference x nil numbers lispp))
7887 t t form)))
7889 (if lispp
7890 (setq ev (condition-case nil
7891 (eval (eval (read form)))
7892 (error "#ERROR"))
7893 ev (if (numberp ev) (number-to-string ev) ev))
7894 (or (fboundp 'calc-eval)
7895 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
7896 (setq ev (calc-eval (cons form modes)
7897 (if numbers 'num))))
7899 (when org-table-formula-debug
7900 (with-output-to-temp-buffer "*Substitution History*"
7901 (princ (format "Substitution history of formula
7902 Orig: %s
7903 $xyz-> %s
7904 @r$c-> %s
7905 $1-> %s\n" orig formula form0 form))
7906 (if (listp ev)
7907 (princ (format " %s^\nError: %s"
7908 (make-string (car ev) ?\-) (nth 1 ev)))
7909 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7910 ev (or fmt "NONE")
7911 (if fmt (format fmt (string-to-number ev)) ev)))))
7912 (setq bw (get-buffer-window "*Substitution History*"))
7913 (shrink-window-if-larger-than-buffer bw)
7914 (unless (and (interactive-p) (not ndown))
7915 (unless (let (inhibit-redisplay)
7916 (y-or-n-p "Debugging Formula. Continue to next? "))
7917 (org-table-align)
7918 (error "Abort"))
7919 (delete-window bw)
7920 (message "")))
7921 (if (listp ev) (setq fmt nil ev "#ERROR"))
7922 (org-table-justify-field-maybe
7923 (if fmt (format fmt (string-to-number ev)) ev))
7924 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7925 (call-interactively 'org-return)
7926 (setq ndown 0)))
7927 (and down (org-table-maybe-recalculate-line))
7928 (or suppress-align (and org-table-may-need-update
7929 (org-table-align))))))
7931 (defun org-table-get-range (desc &optional tbeg col highlight)
7932 "Get a calc vector from a column, accorting to descriptor DESC.
7933 Optional arguments TBEG and COL can give the beginning of the table and
7934 the current column, to avoid unnecessary parsing.
7935 HIGHLIGHT means, just highlight the range."
7936 (if (not (equal (string-to-char desc) ?@))
7937 (setq desc (concat "@" desc)))
7938 (save-excursion
7939 (or tbeg (setq tbeg (org-table-begin)))
7940 (or col (setq col (org-table-current-column)))
7941 (let ((thisline (org-current-line))
7942 beg end c1 c2 r1 r2 rangep tmp)
7943 (unless (string-match org-table-range-regexp desc)
7944 (error "Invalid table range specifier `%s'" desc))
7945 (setq rangep (match-end 3)
7946 r1 (and (match-end 1) (match-string 1 desc))
7947 r2 (and (match-end 4) (match-string 4 desc))
7948 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
7949 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
7951 (and c1 (setq c1 (+ (string-to-number c1)
7952 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
7953 (and c2 (setq c2 (+ (string-to-number c2)
7954 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
7955 (if (equal r1 "") (setq r1 nil))
7956 (if (equal r2 "") (setq r2 nil))
7957 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
7958 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
7959 ; (setq r2 (or r2 r1) c2 (or c2 c1))
7960 (if (not r1) (setq r1 thisline))
7961 (if (not r2) (setq r2 thisline))
7962 (if (not c1) (setq c1 col))
7963 (if (not c2) (setq c2 col))
7964 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
7965 ;; just one field
7966 (progn
7967 (goto-line r1)
7968 (while (not (looking-at org-table-dataline-regexp))
7969 (beginning-of-line 2))
7970 (prog1 (org-table-get-field c1)
7971 (if highlight (org-table-highlight-rectangle (point) (point)))))
7972 ;; A range, return a vector
7973 ;; First sort the numbers to get a regular ractangle
7974 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
7975 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
7976 (goto-line r1)
7977 (while (not (looking-at org-table-dataline-regexp))
7978 (beginning-of-line 2))
7979 (org-table-goto-column c1)
7980 (setq beg (point))
7981 (goto-line r2)
7982 (while (not (looking-at org-table-dataline-regexp))
7983 (beginning-of-line 0))
7984 (org-table-goto-column c2)
7985 (setq end (point))
7986 (if highlight
7987 (org-table-highlight-rectangle
7988 beg (progn (skip-chars-forward "^|\n") (point))))
7989 ;; return string representation of calc vector
7990 (apply 'append (org-table-copy-region beg end))))))
7992 (defun org-table-get-descriptor-line (desc &optional cline bline table)
7993 "Analyze descriptor DESC and retrieve the corresponding line number.
7994 The cursor is currently in line CLINE, the table begins in line BLINE,
7995 and TABLE is a vector with line types."
7996 (if (string-match "^[0-9]+$" desc)
7997 (aref org-table-dlines (string-to-number desc))
7998 (setq cline (or cline (org-current-line))
7999 bline (or bline org-table-current-begin-line)
8000 table (or table org-table-current-line-types))
8001 (if (or
8002 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
8003 ;; 1 2 3 4 5 6
8004 (and (not (match-end 3)) (not (match-end 6)))
8005 (and (match-end 3) (match-end 6) (not (match-end 5))))
8006 (error "invalid row descriptor `%s'" desc))
8007 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
8008 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
8009 (odir (and (match-end 5) (match-string 5 desc)))
8010 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
8011 (i (- cline bline))
8012 (rel (and (match-end 6)
8013 (or (and (match-end 1) (not (match-end 3)))
8014 (match-end 5)))))
8015 (if (and hn (not hdir))
8016 (progn
8017 (setq i 0 hdir "+")
8018 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
8019 (if (and (not hn) on (not odir))
8020 (error "should never happen");;(aref org-table-dlines on) FIXME
8021 (if (and hn (> hn 0))
8022 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
8023 (if on
8024 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
8025 (+ bline i)))))
8027 (defun org-find-row-type (table i type backwards relative n)
8028 (let ((l (length table)))
8029 (while (> n 0)
8030 (while (and (setq i (+ i (if backwards -1 1)))
8031 (>= i 0) (< i l)
8032 (not (eq (aref table i) type))
8033 (if (and relative (eq (aref table i) 'hline))
8034 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
8035 t)))
8036 (setq n (1- n)))
8037 (if (or (< i 0) (>= i l))
8038 (error "Row descriptior leads outside table")
8039 i)))
8041 (defun org-rewrite-old-row-references (s)
8042 (if (string-match "&[-+0-9I]" s)
8043 (error "Formula contains old &row reference, please rewrite using @-syntax")
8046 (defun org-table-make-reference (elements keep-empty numbers lispp)
8047 "Convert list ELEMENTS to something appropriate to insert into formula.
8048 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
8049 NUMBERS indicates that everything should be converted to numbers.
8050 LISPP means to return something appropriate for a Lisp list."
8051 (if (stringp elements) ; just a single val
8052 (if lispp
8053 (prin1-to-string (if numbers (string-to-number elements) elements))
8054 (if (equal elements "") (setq elements "0"))
8055 (if numbers (number-to-string (string-to-number elements)) elements))
8056 (unless keep-empty
8057 (setq elements
8058 (delq nil
8059 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
8060 elements))))
8061 (setq elements (or elements '("0")))
8062 (if lispp
8063 (mapconcat 'prin1-to-string
8064 (if numbers (mapcar 'string-to-number elements) elements)
8065 " ")
8066 (concat "[" (mapconcat
8067 (lambda (x)
8068 (if numbers (number-to-string (string-to-number x)) x))
8069 elements
8070 ",") "]"))))
8072 (defun org-table-recalculate (&optional all noalign)
8073 "Recalculate the current table line by applying all stored formulas.
8074 With prefix arg ALL, do this for all lines in the table."
8075 (interactive "P")
8076 (or (memq this-command org-recalc-commands)
8077 (setq org-recalc-commands (cons this-command org-recalc-commands)))
8078 (unless (org-at-table-p) (error "Not at a table"))
8079 (if (equal all '(16))
8080 (org-table-iterate)
8081 (org-table-get-specials)
8082 (let* ((eqlist (sort (org-table-get-stored-formulas)
8083 (lambda (a b) (string< (car a) (car b)))))
8084 (inhibit-redisplay (not debug-on-error))
8085 (line-re org-table-dataline-regexp)
8086 (thisline (org-current-line))
8087 (thiscol (org-table-current-column))
8088 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
8089 ;; Insert constants in all formulas
8090 (setq eqlist
8091 (mapcar (lambda (x)
8092 (setcdr x (org-table-formula-substitute-names (cdr x)))
8094 eqlist))
8095 ;; Split the equation list
8096 (while (setq eq (pop eqlist))
8097 (if (<= (string-to-char (car eq)) ?9)
8098 (push eq eqlnum)
8099 (push eq eqlname)))
8100 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
8101 (if all
8102 (progn
8103 (setq end (move-marker (make-marker) (1+ (org-table-end))))
8104 (goto-char (setq beg (org-table-begin)))
8105 (if (re-search-forward org-table-calculate-mark-regexp end t)
8106 ;; This is a table with marked lines, compute selected lines
8107 (setq line-re org-table-recalculate-regexp)
8108 ;; Move forward to the first non-header line
8109 (if (and (re-search-forward org-table-dataline-regexp end t)
8110 (re-search-forward org-table-hline-regexp end t)
8111 (re-search-forward org-table-dataline-regexp end t))
8112 (setq beg (match-beginning 0))
8113 nil))) ;; just leave beg where it is
8114 (setq beg (point-at-bol)
8115 end (move-marker (make-marker) (1+ (point-at-eol)))))
8116 (goto-char beg)
8117 (and all (message "Re-applying formulas to full table..."))
8118 (while (re-search-forward line-re end t)
8119 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
8120 ;; Unprotected line, recalculate
8121 (and all (message "Re-applying formulas to full table...(line %d)"
8122 (setq cnt (1+ cnt))))
8123 (setq org-last-recalc-line (org-current-line))
8124 (setq eql eqlnum)
8125 (while (setq entry (pop eql))
8126 (goto-line org-last-recalc-line)
8127 (org-table-goto-column (string-to-number (car entry)) nil 'force)
8128 (org-table-eval-formula nil (cdr entry)
8129 'noalign 'nocst 'nostore 'noanalysis))))
8130 (goto-line thisline)
8131 (org-table-goto-column thiscol)
8132 (or noalign (and org-table-may-need-update (org-table-align))
8133 (and all (message "Re-applying formulas to %d lines...done" cnt)))
8134 ;; Now do the named fields
8135 (while (setq eq (pop eqlname))
8136 (setq name (car eq)
8137 a (assoc name org-table-named-field-locations))
8138 (and (not a)
8139 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
8140 (setq a
8141 (list
8142 name
8143 (aref org-table-dlines
8144 (string-to-number (match-string 1 name)))
8145 (string-to-number (match-string 2 name)))))
8146 (when (and a (or all (equal (nth 1 a) thisline)))
8147 (message "Re-applying formula to field: %s" name)
8148 (goto-line (nth 1 a))
8149 (org-table-goto-column (nth 2 a))
8150 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
8151 'nostore 'noanalysis)))
8152 ;; back to initial position
8153 (message "Re-applying formulas...done")
8154 (goto-line thisline)
8155 (org-table-goto-column thiscol)
8156 (or noalign (and org-table-may-need-update (org-table-align))
8157 (and all (message "Re-applying formulas...done"))))))
8159 (defun org-table-iterate (&optional arg)
8160 "Recalculate the table until it does not change anymore."
8161 (interactive "P")
8162 (let ((imax (if arg (prefix-numeric-value arg) 10))
8163 (i 0)
8164 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
8165 thistbl)
8166 (catch 'exit
8167 (while (< i imax)
8168 (setq i (1+ i))
8169 (org-table-recalculate 'all)
8170 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
8171 (if (not (string= lasttbl thistbl))
8172 (setq lasttbl thistbl)
8173 (if (> i 1)
8174 (message "Convergence after %d iterations" i)
8175 (message "Table was already stable"))
8176 (throw 'exit t)))
8177 (error "No convergence after %d iterations" i))))
8179 (defun org-table-formula-substitute-names (f)
8180 "Replace $const with values in string F."
8181 (let ((start 0) a (f1 f))
8182 ;; First, check for column names
8183 (while (setq start (string-match org-table-column-name-regexp f start))
8184 (setq start (1+ start))
8185 (setq a (assoc (match-string 1 f) org-table-column-names))
8186 (setq f (replace-match (concat "$" (cdr a)) t t f)))
8187 ;; Parameters and constants
8188 (setq start 0)
8189 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
8190 (setq start (1+ start))
8191 (if (setq a (save-match-data
8192 (org-table-get-constant (match-string 1 f))))
8193 (setq f (replace-match (concat "(" a ")") t t f))))
8194 (if org-table-formula-debug
8195 (put-text-property 0 (length f) :orig-formula f1 f))
8198 (defun org-table-get-constant (const)
8199 "Find the value for a parameter or constant in a formula.
8200 Parameters get priority."
8201 (or (cdr (assoc const org-table-local-parameters))
8202 (cdr (assoc const org-table-formula-constants))
8203 (and (fboundp 'constants-get) (constants-get const))
8204 "#UNDEFINED_NAME"))
8206 (defvar org-table-fedit-map (make-sparse-keymap))
8207 (org-defkey org-table-fedit-map "\C-x\C-s" 'org-table-fedit-finish)
8208 (org-defkey org-table-fedit-map "\C-c\C-s" 'org-table-fedit-finish)
8209 (org-defkey org-table-fedit-map "\C-c\C-c" 'org-table-fedit-finish)
8210 (org-defkey org-table-fedit-map "\C-c\C-q" 'org-table-fedit-abort)
8211 (org-defkey org-table-fedit-map "\C-c?" 'org-table-show-reference)
8212 (org-defkey org-table-fedit-map [(meta shift up)] 'org-table-fedit-line-up)
8213 (org-defkey org-table-fedit-map [(meta shift down)] 'org-table-fedit-line-down)
8214 (org-defkey org-table-fedit-map [(shift up)] 'org-table-fedit-ref-up)
8215 (org-defkey org-table-fedit-map [(shift down)] 'org-table-fedit-ref-down)
8216 (org-defkey org-table-fedit-map [(shift left)] 'org-table-fedit-ref-left)
8217 (org-defkey org-table-fedit-map [(shift right)] 'org-table-fedit-ref-right)
8218 (org-defkey org-table-fedit-map [(meta up)] 'org-table-fedit-scroll-down)
8219 (org-defkey org-table-fedit-map [(meta down)] 'org-table-fedit-scroll)
8220 (org-defkey org-table-fedit-map [(meta tab)] 'lisp-complete-symbol)
8221 (org-defkey org-table-fedit-map "\M-\C-i" 'lisp-complete-symbol)
8222 (org-defkey org-table-fedit-map [(tab)] 'org-table-fedit-lisp-indent)
8223 (org-defkey org-table-fedit-map "\C-i" 'org-table-fedit-lisp-indent)
8224 (org-defkey org-table-fedit-map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
8225 (org-defkey org-table-fedit-map "\C-c}" 'org-table-fedit-toggle-coordinates)
8227 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
8228 '("Edit-Formulas"
8229 ["Finish and Install" org-table-fedit-finish t]
8230 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
8231 ["Abort" org-table-fedit-abort t]
8232 "--"
8233 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
8234 ["Complete Lisp Symbol" lisp-complete-symbol t]
8235 "--"
8236 "Shift Reference at Point"
8237 ["Up" org-table-fedit-ref-up t]
8238 ["Down" org-table-fedit-ref-down t]
8239 ["Left" org-table-fedit-ref-left t]
8240 ["Right" org-table-fedit-ref-right t]
8242 "Change Test Row for Column Formulas"
8243 ["Up" org-table-fedit-line-up t]
8244 ["Down" org-table-fedit-line-down t]
8245 "--"
8246 ["Scroll Table Window" org-table-fedit-scroll t]
8247 ["Scroll Table Window down" org-table-fedit-scroll-down t]
8248 ["Show Table Grid" org-table-fedit-toggle-coordinates
8249 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
8250 org-table-overlay-coordinates)]
8251 "--"
8252 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
8253 :style toggle :selected org-table-buffer-is-an]))
8255 (defvar org-pos)
8257 (defun org-table-edit-formulas ()
8258 "Edit the formulas of the current table in a separate buffer."
8259 (interactive)
8260 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
8261 (beginning-of-line 0))
8262 (unless (org-at-table-p) (error "Not at a table"))
8263 (org-table-get-specials)
8264 (let ((key (org-table-current-field-formula 'key 'noerror))
8265 (eql (sort (org-table-get-stored-formulas 'noerror)
8266 'org-table-formula-less-p))
8267 (pos (move-marker (make-marker) (point)))
8268 (startline 1)
8269 (wc (current-window-configuration))
8270 (titles '((column . "# Column Formulas\n")
8271 (field . "# Field Formulas\n")
8272 (named . "# Named Field Formulas\n")))
8273 entry s type title)
8274 (switch-to-buffer-other-window "*Edit Formulas*")
8275 (erase-buffer)
8276 ;; Keep global-font-lock-mode from turning on font-lock-mode
8277 (let ((font-lock-global-modes '(not fundamental-mode)))
8278 (fundamental-mode))
8279 (org-set-local 'font-lock-global-modes (list 'not major-mode))
8280 (org-set-local 'org-pos pos)
8281 (org-set-local 'org-window-configuration wc)
8282 (use-local-map org-table-fedit-map)
8283 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
8284 (easy-menu-add org-table-fedit-menu)
8285 (setq startline (org-current-line))
8286 (while (setq entry (pop eql))
8287 (setq type (cond
8288 ((equal (string-to-char (car entry)) ?@) 'field)
8289 ((string-match "^[0-9]" (car entry)) 'column)
8290 (t 'named)))
8291 (when (setq title (assq type titles))
8292 (or (bobp) (insert "\n"))
8293 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
8294 (setq titles (delq title titles)))
8295 (if (equal key (car entry)) (setq startline (org-current-line)))
8296 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
8297 (car entry) " = " (cdr entry) "\n"))
8298 (remove-text-properties 0 (length s) '(face nil) s)
8299 (insert s))
8300 (if (eq org-table-use-standard-references t)
8301 (org-table-fedit-toggle-ref-type))
8302 (goto-line startline)
8303 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
8305 (defun org-table-fedit-post-command ()
8306 (when (not (memq this-command '(lisp-complete-symbol)))
8307 (let ((win (selected-window)))
8308 (save-excursion
8309 (condition-case nil
8310 (org-table-show-reference)
8311 (error nil))
8312 (select-window win)))))
8314 (defun org-table-formula-to-user (s)
8315 "Convert a formula from internal to user representation."
8316 (if (eq org-table-use-standard-references t)
8317 (org-table-convert-refs-to-an s)
8320 (defun org-table-formula-from-user (s)
8321 "Convert a formula from user to internal representation."
8322 (if org-table-use-standard-references
8323 (org-table-convert-refs-to-rc s)
8326 (defun org-table-convert-refs-to-rc (s)
8327 "Convert spreadsheet references from AB7 to @7$28.
8328 Works for single references, but also for entire formulas and even the
8329 full TBLFM line."
8330 (let ((start 0))
8331 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
8332 (if (match-end 3)
8333 ;; format match, just advance
8334 (setq start (match-end 0))
8335 (setq start (match-beginning 0)
8336 s (replace-match
8337 (if (equal (match-string 2 s) "&")
8338 (format "$%d" (org-letters-to-number (match-string 1 s)))
8339 (format "@%d$%d"
8340 (string-to-number (match-string 2 s))
8341 (org-letters-to-number (match-string 1 s))))
8342 t t s))))
8345 (defun org-table-convert-refs-to-an (s)
8346 "Convert spreadsheet references from to @7$28 to AB7.
8347 Works for single references, but also for entire formulas and even the
8348 full TBLFM line."
8349 (while (string-match "@\\([0-9]+\\)$\\([0-9]+\\)" s)
8350 (setq s (replace-match
8351 (format "%s%d"
8352 (org-number-to-letters
8353 (string-to-number (match-string 2 s)))
8354 (string-to-number (match-string 1 s)))
8355 t t s)))
8356 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
8357 (setq s (replace-match (concat "\\1"
8358 (org-number-to-letters
8359 (string-to-number (match-string 2 s))) "&")
8360 t nil s)))
8363 (defun org-letters-to-number (s)
8364 "Convert a base 26 number represented by letters into an integer.
8365 For example: AB -> 28."
8366 (let ((n 0))
8367 (setq s (upcase s))
8368 (while (> (length s) 0)
8369 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
8370 s (substring s 1)))
8373 (defun org-number-to-letters (n)
8374 "Convert an integer into a base 26 number represented by letters.
8375 For example: 28 -> AB."
8376 (let ((s ""))
8377 (while (> n 0)
8378 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
8379 n (/ (1- n) 26)))
8382 (defun org-table-fedit-convert-buffer (function)
8383 "Convert all references in this buffer, using FUNTION."
8384 (let ((line (org-current-line)))
8385 (goto-char (point-min))
8386 (while (not (eobp))
8387 (insert (funcall function (buffer-substring (point) (point-at-eol))))
8388 (delete-region (point) (point-at-eol))
8389 (or (eobp) (forward-char 1)))
8390 (goto-line line)))
8392 (defun org-table-fedit-toggle-ref-type ()
8393 "Convert all references in the buffer from B3 to @3$2 and back."
8394 (interactive)
8395 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
8396 (org-table-fedit-convert-buffer
8397 (if org-table-buffer-is-an
8398 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
8399 (message "Reference type switched to %s"
8400 (if org-table-buffer-is-an "A1 etc" "@row$column")))
8402 (defun org-table-fedit-ref-up ()
8403 "Shift the reference at point one row/hline up."
8404 (interactive)
8405 (org-table-fedit-shift-reference 'up))
8406 (defun org-table-fedit-ref-down ()
8407 "Shift the reference at point one row/hline down."
8408 (interactive)
8409 (org-table-fedit-shift-reference 'down))
8410 (defun org-table-fedit-ref-left ()
8411 "Shift the reference at point one field to the left."
8412 (interactive)
8413 (org-table-fedit-shift-reference 'left))
8414 (defun org-table-fedit-ref-right ()
8415 "Shift the reference at point one field to the right."
8416 (interactive)
8417 (org-table-fedit-shift-reference 'right))
8419 (defun org-table-fedit-shift-reference (dir)
8420 (cond
8421 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
8422 (if (memq dir '(left right))
8423 (org-rematch-and-replace 1 (eq dir 'left))
8424 (error "Cannot shift reference in this direction")))
8425 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
8426 ;; A B3-like reference
8427 (if (memq dir '(up down))
8428 (org-rematch-and-replace 2 (eq dir 'up))
8429 (org-rematch-and-replace 1 (eq dir 'left))))
8430 ((org-at-regexp-p
8431 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
8432 ;; An internal reference
8433 (if (memq dir '(up down))
8434 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
8435 (org-rematch-and-replace 5 (eq dir 'left))))))
8437 (defun org-rematch-and-replace (n &optional decr hline)
8438 "Re-match the group N, and replace it with the shifted refrence."
8439 (or (match-end n) (error "Cannot shift reference in this direction"))
8440 (goto-char (match-beginning n))
8441 (and (looking-at (regexp-quote (match-string n)))
8442 (replace-match (org-shift-refpart (match-string 0) decr hline)
8443 t t)))
8445 (defun org-shift-refpart (ref &optional decr hline)
8446 "Shift a refrence part REF.
8447 If DECR is set, decrease the references row/column, else increase.
8448 If HLINE is set, this may be a hline reference, it certainly is not
8449 a translation reference."
8450 (save-match-data
8451 (let* ((sign (string-match "^[-+]" ref)) n)
8453 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
8454 (cond
8455 ((and hline (string-match "^I+" ref))
8456 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
8457 (setq n (+ n (if decr -1 1)))
8458 (if (= n 0) (setq n (+ n (if decr -1 1))))
8459 (if sign
8460 (setq sign (if (< n 0) "-" "+") n (abs n))
8461 (setq n (max 1 n)))
8462 (concat sign (make-string n ?I)))
8464 ((string-match "^[0-9]+" ref)
8465 (setq n (string-to-number (concat sign ref)))
8466 (setq n (+ n (if decr -1 1)))
8467 (if sign
8468 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
8469 (number-to-string (max 1 n))))
8471 ((string-match "^[a-zA-Z]+" ref)
8472 (org-number-to-letters
8473 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
8475 (t (error "Cannot shift reference"))))))
8477 (defun org-table-fedit-toggle-coordinates ()
8478 "Toggle the display of coordinates in the refrenced table."
8479 (interactive)
8480 (let ((pos (marker-position org-pos)))
8481 (with-current-buffer (marker-buffer org-pos)
8482 (save-excursion
8483 (goto-char pos)
8484 (org-table-toggle-coordinate-overlays)))))
8486 (defun org-table-fedit-finish (&optional arg)
8487 "Parse the buffer for formula definitions and install them.
8488 With prefix ARG, apply the new formulas to the table."
8489 (interactive "P")
8490 (org-table-remove-rectangle-highlight)
8491 (if org-table-use-standard-references
8492 (progn
8493 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
8494 (setq org-table-buffer-is-an nil)))
8495 (let ((pos org-pos) eql var form)
8496 (goto-char (point-min))
8497 (while (re-search-forward
8498 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
8499 nil t)
8500 (setq var (if (match-end 2) (match-string 2) (match-string 1))
8501 form (match-string 3))
8502 (setq form (org-trim form))
8503 (when (not (equal form ""))
8504 (while (string-match "[ \t]*\n[ \t]*" form)
8505 (setq form (replace-match " " t t form)))
8506 (when (assoc var eql)
8507 (error "Double formulas for %s" var))
8508 (push (cons var form) eql)))
8509 (setq org-pos nil)
8510 (set-window-configuration org-window-configuration)
8511 (select-window (get-buffer-window (marker-buffer pos)))
8512 (goto-char pos)
8513 (unless (org-at-table-p)
8514 (error "Lost table position - cannot install formulae"))
8515 (org-table-store-formulas eql)
8516 (move-marker pos nil)
8517 (kill-buffer "*Edit Formulas*")
8518 (if arg
8519 (org-table-recalculate 'all)
8520 (message "New formulas installed - press C-u C-c C-c to apply."))))
8522 (defun org-table-fedit-abort ()
8523 "Abort editing formulas, without installing the changes."
8524 (interactive)
8525 (org-table-remove-rectangle-highlight)
8526 (let ((pos org-pos))
8527 (set-window-configuration org-window-configuration)
8528 (select-window (get-buffer-window (marker-buffer pos)))
8529 (goto-char pos)
8530 (move-marker pos nil)
8531 (message "Formula editing aborted without installing changes")))
8533 (defun org-table-fedit-lisp-indent ()
8534 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
8535 (interactive)
8536 (let ((pos (point)) beg end ind)
8537 (beginning-of-line 1)
8538 (cond
8539 ((looking-at "[ \t]")
8540 (goto-char pos)
8541 (call-interactively 'lisp-indent-line))
8542 ((looking-at "[$@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
8543 ((not (fboundp 'pp-buffer))
8544 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
8545 ((looking-at "[$@0-9a-zA-Z]+ *= *'(")
8546 (goto-char (- (match-end 0) 2))
8547 (setq beg (point))
8548 (setq ind (make-string (current-column) ?\ ))
8549 (condition-case nil (forward-sexp 1)
8550 (error
8551 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
8552 (setq end (point))
8553 (save-restriction
8554 (narrow-to-region beg end)
8555 (if (eq last-command this-command)
8556 (progn
8557 (goto-char (point-min))
8558 (setq this-command nil)
8559 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
8560 (replace-match " ")))
8561 (pp-buffer)
8562 (untabify (point-min) (point-max))
8563 (goto-char (1+ (point-min)))
8564 (while (re-search-forward "^." nil t)
8565 (beginning-of-line 1)
8566 (insert ind))
8567 (goto-char (point-max))
8568 (backward-delete-char 1)))
8569 (goto-char beg))
8570 (t nil))))
8572 (defvar org-show-positions nil)
8574 (defun org-table-show-reference (&optional local)
8575 "Show the location/value of the $ expression at point."
8576 (interactive)
8577 (org-table-remove-rectangle-highlight)
8578 (catch 'exit
8579 (let ((pos (if local (point) org-pos))
8580 (face2 'highlight)
8581 (org-inhibit-highlight-removal t)
8582 (win (selected-window))
8583 (org-show-positions nil)
8584 var name e what match dest)
8585 (if local (org-table-get-specials))
8586 (setq what (cond
8587 ((or (org-at-regexp-p org-table-range-regexp2)
8588 (org-at-regexp-p org-table-translate-regexp)
8589 (org-at-regexp-p org-table-range-regexp))
8590 (setq match
8591 (save-match-data
8592 (org-table-convert-refs-to-rc (match-string 0))))
8593 'range)
8594 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
8595 ((org-at-regexp-p "\\$[0-9]+") 'column)
8596 ((not local) nil)
8597 (t (error "No reference at point")))
8598 match (and what (or match (match-string 0))))
8599 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
8600 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
8601 'secondary-selection))
8602 (org-add-hook 'before-change-functions
8603 'org-table-remove-rectangle-highlight)
8604 (if (eq what 'name) (setq var (substring match 1)))
8605 (when (eq what 'range)
8606 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
8607 (setq match (org-table-formula-substitute-names match)))
8608 (unless local
8609 (save-excursion
8610 (end-of-line 1)
8611 (re-search-backward "^\\S-" nil t)
8612 (beginning-of-line 1)
8613 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
8614 (setq dest
8615 (save-match-data
8616 (org-table-convert-refs-to-rc (match-string 1))))
8617 (org-table-add-rectangle-overlay
8618 (match-beginning 1) (match-end 1) face2))))
8619 (if (and (markerp pos) (marker-buffer pos))
8620 (if (get-buffer-window (marker-buffer pos))
8621 (select-window (get-buffer-window (marker-buffer pos)))
8622 (switch-to-buffer-other-window (get-buffer-window
8623 (marker-buffer pos)))))
8624 (goto-char pos)
8625 (org-table-force-dataline)
8626 (when dest
8627 (setq name (substring dest 1))
8628 (cond
8629 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
8630 (setq e (assoc name org-table-named-field-locations))
8631 (goto-line (nth 1 e))
8632 (org-table-goto-column (nth 2 e)))
8633 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
8634 (let ((l (string-to-number (match-string 1 dest)))
8635 (c (string-to-number (match-string 2 dest))))
8636 (goto-line (aref org-table-dlines l))
8637 (org-table-goto-column c)))
8638 (t (org-table-goto-column (string-to-number name))))
8639 (move-marker pos (point))
8640 (org-table-highlight-rectangle nil nil face2))
8641 (cond
8642 ((equal dest match))
8643 ((not match))
8644 ((eq what 'range)
8645 (condition-case nil
8646 (save-excursion
8647 (org-table-get-range match nil nil 'highlight))
8648 (error nil)))
8649 ((setq e (assoc var org-table-named-field-locations))
8650 (goto-line (nth 1 e))
8651 (org-table-goto-column (nth 2 e))
8652 (org-table-highlight-rectangle (point) (point))
8653 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
8654 ((setq e (assoc var org-table-column-names))
8655 (org-table-goto-column (string-to-number (cdr e)))
8656 (org-table-highlight-rectangle (point) (point))
8657 (goto-char (org-table-begin))
8658 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
8659 (org-table-end) t)
8660 (progn
8661 (goto-char (match-beginning 1))
8662 (org-table-highlight-rectangle)
8663 (message "Named column (column %s)" (cdr e)))
8664 (error "Column name not found")))
8665 ((eq what 'column)
8666 ;; column number
8667 (org-table-goto-column (string-to-number (substring match 1)))
8668 (org-table-highlight-rectangle (point) (point))
8669 (message "Column %s" (substring match 1)))
8670 ((setq e (assoc var org-table-local-parameters))
8671 (goto-char (org-table-begin))
8672 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
8673 (progn
8674 (goto-char (match-beginning 1))
8675 (org-table-highlight-rectangle)
8676 (message "Local parameter."))
8677 (error "Parameter not found")))
8679 (cond
8680 ((not var) (error "No reference at point"))
8681 ((setq e (assoc var org-table-formula-constants))
8682 (message "Constant: $%s=%s in `org-table-formula-constants'."
8683 var (cdr e)))
8684 ((setq e (and (fboundp 'constants-get) (constants-get var)))
8685 (message "Constant: $%s=%s, from `constants.el'%s."
8686 var e (format " (%s units)" constants-unit-system)))
8687 (t (error "Undefined name $%s" var)))))
8688 (goto-char pos)
8689 (when (and org-show-positions
8690 (not (memq this-command '(org-table-fedit-scroll
8691 org-table-fedit-scroll-down))))
8692 (push pos org-show-positions)
8693 (push org-table-current-begin-pos org-show-positions)
8694 (let ((min (apply 'min org-show-positions))
8695 (max (apply 'max org-show-positions)))
8696 (goto-char min) (recenter 0)
8697 (goto-char max)
8698 (or (pos-visible-in-window-p max) (recenter -1))))
8699 (select-window win))))
8701 (defun org-table-force-dataline ()
8702 "Make sure the cursor is in a dataline in a table."
8703 (unless (save-excursion
8704 (beginning-of-line 1)
8705 (looking-at org-table-dataline-regexp))
8706 (let* ((re org-table-dataline-regexp)
8707 (p1 (save-excursion (re-search-forward re nil 'move)))
8708 (p2 (save-excursion (re-search-backward re nil 'move))))
8709 (cond ((and p1 p2)
8710 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
8711 p1 p2)))
8712 ((or p1 p2) (goto-char (or p1 p2)))
8713 (t (error "No table dataline around here"))))))
8715 (defun org-table-fedit-line-up ()
8716 "Move cursor one line up in the window showing the table."
8717 (interactive)
8718 (org-table-fedit-move 'previous-line))
8720 (defun org-table-fedit-line-down ()
8721 "Move cursor one line down in the window showing the table."
8722 (interactive)
8723 (org-table-fedit-move 'next-line))
8725 (defun org-table-fedit-move (command)
8726 "Move the cursor in the window shoinw the table.
8727 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
8728 (let ((org-table-allow-automatic-line-recalculation nil)
8729 (pos org-pos) (win (selected-window)) p)
8730 (select-window (get-buffer-window (marker-buffer org-pos)))
8731 (setq p (point))
8732 (call-interactively command)
8733 (while (and (org-at-table-p)
8734 (org-at-table-hline-p))
8735 (call-interactively command))
8736 (or (org-at-table-p) (goto-char p))
8737 (move-marker pos (point))
8738 (select-window win)))
8740 (defun org-table-fedit-scroll (N)
8741 (interactive "p")
8742 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
8743 (scroll-other-window N)))
8745 (defun org-table-fedit-scroll-down (N)
8746 (interactive "p")
8747 (org-table-fedit-scroll (- N)))
8749 (defvar org-table-rectangle-overlays nil)
8751 (defun org-table-add-rectangle-overlay (beg end &optional face)
8752 "Add a new overlay."
8753 (let ((ov (org-make-overlay beg end)))
8754 (org-overlay-put ov 'face (or face 'secondary-selection))
8755 (push ov org-table-rectangle-overlays)))
8757 (defun org-table-highlight-rectangle (&optional beg end face)
8758 "Highlight rectangular region in a table."
8759 (setq beg (or beg (point)) end (or end (point)))
8760 (let ((b (min beg end))
8761 (e (max beg end))
8762 l1 c1 l2 c2 tmp)
8763 (and (boundp 'org-show-positions)
8764 (setq org-show-positions (cons b (cons e org-show-positions))))
8765 (goto-char (min beg end))
8766 (setq l1 (org-current-line)
8767 c1 (org-table-current-column))
8768 (goto-char (max beg end))
8769 (setq l2 (org-current-line)
8770 c2 (org-table-current-column))
8771 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
8772 (goto-line l1)
8773 (beginning-of-line 1)
8774 (loop for line from l1 to l2 do
8775 (when (looking-at org-table-dataline-regexp)
8776 (org-table-goto-column c1)
8777 (skip-chars-backward "^|\n") (setq beg (point))
8778 (org-table-goto-column c2)
8779 (skip-chars-forward "^|\n") (setq end (point))
8780 (org-table-add-rectangle-overlay beg end face))
8781 (beginning-of-line 2))
8782 (goto-char b))
8783 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
8785 (defun org-table-remove-rectangle-highlight (&rest ignore)
8786 "Remove the rectangle overlays."
8787 (unless org-inhibit-highlight-removal
8788 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
8789 (mapc 'org-delete-overlay org-table-rectangle-overlays)
8790 (setq org-table-rectangle-overlays nil)))
8792 (defvar org-table-coordinate-overlays nil
8793 "Collects the cooordinate grid overlays, so that they can be removed.")
8794 (make-variable-buffer-local 'org-table-coordinate-overlays)
8796 (defun org-table-overlay-coordinates ()
8797 "Add overlays to the table at point, to show row/column coordinates."
8798 (interactive)
8799 (mapc 'org-delete-overlay org-table-coordinate-overlays)
8800 (setq org-table-coordinate-overlays nil)
8801 (save-excursion
8802 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
8803 (goto-char (org-table-begin))
8804 (while (org-at-table-p)
8805 (setq eol (point-at-eol))
8806 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
8807 (push ov org-table-coordinate-overlays)
8808 (setq hline (looking-at org-table-hline-regexp))
8809 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
8810 (format "%4d" (setq id (1+ id)))))
8811 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
8812 (when hline
8813 (setq ic 0)
8814 (while (re-search-forward "[+|]\\(-+\\)" eol t)
8815 (setq beg (1+ (match-beginning 0))
8816 ic (1+ ic)
8817 s1 (concat "$" (int-to-string ic))
8818 s2 (org-number-to-letters ic)
8819 str (if org-table-use-standard-references s2 s1))
8820 (setq ov (org-make-overlay beg (+ beg (length str))))
8821 (push ov org-table-coordinate-overlays)
8822 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
8823 (beginning-of-line 2)))))
8825 (defun org-table-toggle-coordinate-overlays ()
8826 "Toggle the display of Row/Column numbers in tables."
8827 (interactive)
8828 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
8829 (message "Row/Column number display turned %s"
8830 (if org-table-overlay-coordinates "on" "off"))
8831 (if (and (org-at-table-p) org-table-overlay-coordinates)
8832 (org-table-align))
8833 (unless org-table-overlay-coordinates
8834 (mapc 'org-delete-overlay org-table-coordinate-overlays)
8835 (setq org-table-coordinate-overlays nil)))
8837 (defun org-table-toggle-formula-debugger ()
8838 "Toggle the formula debugger in tables."
8839 (interactive)
8840 (setq org-table-formula-debug (not org-table-formula-debug))
8841 (message "Formula debugging has been turned %s"
8842 (if org-table-formula-debug "on" "off")))
8844 ;;; The orgtbl minor mode
8846 ;; Define a minor mode which can be used in other modes in order to
8847 ;; integrate the org-mode table editor.
8849 ;; This is really a hack, because the org-mode table editor uses several
8850 ;; keys which normally belong to the major mode, for example the TAB and
8851 ;; RET keys. Here is how it works: The minor mode defines all the keys
8852 ;; necessary to operate the table editor, but wraps the commands into a
8853 ;; function which tests if the cursor is currently inside a table. If that
8854 ;; is the case, the table editor command is executed. However, when any of
8855 ;; those keys is used outside a table, the function uses `key-binding' to
8856 ;; look up if the key has an associated command in another currently active
8857 ;; keymap (minor modes, major mode, global), and executes that command.
8858 ;; There might be problems if any of the keys used by the table editor is
8859 ;; otherwise used as a prefix key.
8861 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8862 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8863 ;; addresses this by checking explicitly for both bindings.
8865 ;; The optimized version (see variable `orgtbl-optimized') takes over
8866 ;; all keys which are bound to `self-insert-command' in the *global map*.
8867 ;; Some modes bind other commands to simple characters, for example
8868 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
8869 ;; active, this binding is ignored inside tables and replaced with a
8870 ;; modified self-insert.
8872 (defvar orgtbl-mode nil
8873 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
8874 table editor in arbitrary modes.")
8875 (make-variable-buffer-local 'orgtbl-mode)
8877 (defvar orgtbl-mode-map (make-keymap)
8878 "Keymap for `orgtbl-mode'.")
8880 ;;;###autoload
8881 (defun turn-on-orgtbl ()
8882 "Unconditionally turn on `orgtbl-mode'."
8883 (orgtbl-mode 1))
8885 (defvar org-old-auto-fill-inhibit-regexp nil
8886 "Local variable used by `orgtbl-mode'")
8888 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
8889 "Matches a line belonging to an orgtbl.")
8891 (defconst orgtbl-extra-font-lock-keywords
8892 (list (list (concat "^" orgtbl-line-start-regexp ".*")
8893 0 (quote 'org-table) 'prepend))
8894 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
8896 ;;;###autoload
8897 (defun orgtbl-mode (&optional arg)
8898 "The `org-mode' table editor as a minor mode for use in other modes."
8899 (interactive)
8900 (if (org-mode-p)
8901 ;; Exit without error, in case some hook functions calls this
8902 ;; by accident in org-mode.
8903 (message "Orgtbl-mode is not useful in org-mode, command ignored")
8904 (setq orgtbl-mode
8905 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
8906 (if orgtbl-mode
8907 (progn
8908 (and (orgtbl-setup) (defun orgtbl-setup () nil))
8909 ;; Make sure we are first in minor-mode-map-alist
8910 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
8911 (and c (setq minor-mode-map-alist
8912 (cons c (delq c minor-mode-map-alist)))))
8913 (org-set-local (quote org-table-may-need-update) t)
8914 (org-add-hook 'before-change-functions 'org-before-change-function
8915 nil 'local)
8916 (org-set-local 'org-old-auto-fill-inhibit-regexp
8917 auto-fill-inhibit-regexp)
8918 (org-set-local 'auto-fill-inhibit-regexp
8919 (if auto-fill-inhibit-regexp
8920 (concat orgtbl-line-start-regexp "\\|"
8921 auto-fill-inhibit-regexp)
8922 orgtbl-line-start-regexp))
8923 (org-add-to-invisibility-spec '(org-cwidth))
8924 (when (fboundp 'font-lock-add-keywords)
8925 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
8926 (org-restart-font-lock))
8927 (easy-menu-add orgtbl-mode-menu)
8928 (run-hooks 'orgtbl-mode-hook))
8929 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
8930 (org-cleanup-narrow-column-properties)
8931 (org-remove-from-invisibility-spec '(org-cwidth))
8932 (remove-hook 'before-change-functions 'org-before-change-function t)
8933 (when (fboundp 'font-lock-remove-keywords)
8934 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
8935 (org-restart-font-lock))
8936 (easy-menu-remove orgtbl-mode-menu)
8937 (force-mode-line-update 'all))))
8939 (defun org-cleanup-narrow-column-properties ()
8940 "Remove all properties related to narrow-column invisibility."
8941 (let ((s 1))
8942 (while (setq s (text-property-any s (point-max)
8943 'display org-narrow-column-arrow))
8944 (remove-text-properties s (1+ s) '(display t)))
8945 (setq s 1)
8946 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
8947 (remove-text-properties s (1+ s) '(org-cwidth t)))
8948 (setq s 1)
8949 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
8950 (remove-text-properties s (1+ s) '(invisible t)))))
8952 ;; Install it as a minor mode.
8953 (put 'orgtbl-mode :included t)
8954 (put 'orgtbl-mode :menu-tag "Org Table Mode")
8955 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
8957 (defun orgtbl-make-binding (fun n &rest keys)
8958 "Create a function for binding in the table minor mode.
8959 FUN is the command to call inside a table. N is used to create a unique
8960 command name. KEYS are keys that should be checked in for a command
8961 to execute outside of tables."
8962 (eval
8963 (list 'defun
8964 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
8965 '(arg)
8966 (concat "In tables, run `" (symbol-name fun) "'.\n"
8967 "Outside of tables, run the binding of `"
8968 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8969 "'.")
8970 '(interactive "p")
8971 (list 'if
8972 '(org-at-table-p)
8973 (list 'call-interactively (list 'quote fun))
8974 (list 'let '(orgtbl-mode)
8975 (list 'call-interactively
8976 (append '(or)
8977 (mapcar (lambda (k)
8978 (list 'key-binding k))
8979 keys)
8980 '('orgtbl-error))))))))
8982 (defun orgtbl-error ()
8983 "Error when there is no default binding for a table key."
8984 (interactive)
8985 (error "This key is has no function outside tables"))
8987 (defun orgtbl-setup ()
8988 "Setup orgtbl keymaps."
8989 (let ((nfunc 0)
8990 (bindings
8991 (list
8992 '([(meta shift left)] org-table-delete-column)
8993 '([(meta left)] org-table-move-column-left)
8994 '([(meta right)] org-table-move-column-right)
8995 '([(meta shift right)] org-table-insert-column)
8996 '([(meta shift up)] org-table-kill-row)
8997 '([(meta shift down)] org-table-insert-row)
8998 '([(meta up)] org-table-move-row-up)
8999 '([(meta down)] org-table-move-row-down)
9000 '("\C-c\C-w" org-table-cut-region)
9001 '("\C-c\M-w" org-table-copy-region)
9002 '("\C-c\C-y" org-table-paste-rectangle)
9003 '("\C-c-" org-table-insert-hline)
9004 '("\C-c}" org-table-toggle-coordinate-overlays)
9005 '("\C-c{" org-table-toggle-formula-debugger)
9006 '("\C-m" org-table-next-row)
9007 '([(shift return)] org-table-copy-down)
9008 '("\C-c\C-q" org-table-wrap-region)
9009 '("\C-c?" org-table-field-info)
9010 '("\C-c " org-table-blank-field)
9011 '("\C-c+" org-table-sum)
9012 '("\C-c=" org-table-eval-formula)
9013 '("\C-c'" org-table-edit-formulas)
9014 '("\C-c`" org-table-edit-field)
9015 '("\C-c*" org-table-recalculate)
9016 '("\C-c|" org-table-create-or-convert-from-region)
9017 '("\C-c^" org-table-sort-lines)
9018 '([(control ?#)] org-table-rotate-recalc-marks)))
9019 elt key fun cmd)
9020 (while (setq elt (pop bindings))
9021 (setq nfunc (1+ nfunc))
9022 (setq key (org-key (car elt))
9023 fun (nth 1 elt)
9024 cmd (orgtbl-make-binding fun nfunc key))
9025 (org-defkey orgtbl-mode-map key cmd))
9027 ;; Special treatment needed for TAB and RET
9028 (org-defkey orgtbl-mode-map [(return)]
9029 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9030 (org-defkey orgtbl-mode-map "\C-m"
9031 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9033 (org-defkey orgtbl-mode-map [(tab)]
9034 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9035 (org-defkey orgtbl-mode-map "\C-i"
9036 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
9038 (org-defkey orgtbl-mode-map [(shift tab)]
9039 (orgtbl-make-binding 'org-table-previous-field 104
9040 [(shift tab)] [(tab)] "\C-i"))
9042 (org-defkey orgtbl-mode-map "\M-\C-m"
9043 (orgtbl-make-binding 'org-table-wrap-region 105
9044 "\M-\C-m" [(meta return)]))
9045 (org-defkey orgtbl-mode-map [(meta return)]
9046 (orgtbl-make-binding 'org-table-wrap-region 106
9047 [(meta return)] "\M-\C-m"))
9049 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
9050 (when orgtbl-optimized
9051 ;; If the user wants maximum table support, we need to hijack
9052 ;; some standard editing functions
9053 (org-remap orgtbl-mode-map
9054 'self-insert-command 'orgtbl-self-insert-command
9055 'delete-char 'org-delete-char
9056 'delete-backward-char 'org-delete-backward-char)
9057 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
9058 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9059 '("OrgTbl"
9060 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9061 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9062 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9063 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9064 "--"
9065 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9066 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
9067 ["Copy Field from Above"
9068 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9069 "--"
9070 ("Column"
9071 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9072 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9073 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9074 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9075 ("Row"
9076 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9077 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9078 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9079 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9080 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9081 "--"
9082 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9083 ("Rectangle"
9084 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9085 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9086 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9087 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9088 "--"
9089 ("Radio tables"
9090 ["Insert table template" orgtbl-insert-radio-table
9091 (assq major-mode orgtbl-radio-table-templates)]
9092 ["Comment/uncomment table" orgtbl-toggle-comment t])
9093 "--"
9094 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9095 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9096 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9097 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9098 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9099 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
9100 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9101 ["Sum Column/Rectangle" org-table-sum
9102 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9103 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9104 ["Debug Formulas"
9105 org-table-toggle-formula-debugger :active (org-at-table-p)
9106 :keys "C-c {"
9107 :style toggle :selected org-table-formula-debug]
9108 ["Show Col/Row Numbers"
9109 org-table-toggle-coordinate-overlays :active (org-at-table-p)
9110 :keys "C-c }"
9111 :style toggle :selected org-table-overlay-coordinates]
9115 (defun orgtbl-ctrl-c-ctrl-c (arg)
9116 "If the cursor is inside a table, realign the table.
9117 It it is a table to be sent away to a receiver, do it.
9118 With prefix arg, also recompute table."
9119 (interactive "P")
9120 (let ((pos (point)) action)
9121 (save-excursion
9122 (beginning-of-line 1)
9123 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
9124 ((looking-at "[ \t]*|") pos)
9125 ((looking-at "#\\+TBLFM:") 'recalc))))
9126 (cond
9127 ((integerp action)
9128 (goto-char action)
9129 (org-table-maybe-eval-formula)
9130 (if arg
9131 (call-interactively 'org-table-recalculate)
9132 (org-table-maybe-recalculate-line))
9133 (call-interactively 'org-table-align)
9134 (orgtbl-send-table 'maybe))
9135 ((eq action 'recalc)
9136 (save-excursion
9137 (beginning-of-line 1)
9138 (skip-chars-backward " \r\n\t")
9139 (if (org-at-table-p)
9140 (org-call-with-arg 'org-table-recalculate t))))
9141 (t (let (orgtbl-mode)
9142 (call-interactively (key-binding "\C-c\C-c")))))))
9144 (defun orgtbl-tab (arg)
9145 "Justification and field motion for `orgtbl-mode'."
9146 (interactive "P")
9147 (if arg (org-table-edit-field t)
9148 (org-table-justify-field-maybe)
9149 (org-table-next-field)))
9151 (defun orgtbl-ret ()
9152 "Justification and field motion for `orgtbl-mode'."
9153 (interactive)
9154 (org-table-justify-field-maybe)
9155 (org-table-next-row))
9157 (defun orgtbl-self-insert-command (N)
9158 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9159 If the cursor is in a table looking at whitespace, the whitespace is
9160 overwritten, and the table is not marked as requiring realignment."
9161 (interactive "p")
9162 (if (and (org-at-table-p)
9164 (and org-table-auto-blank-field
9165 (member last-command
9166 '(orgtbl-hijacker-command-100
9167 orgtbl-hijacker-command-101
9168 orgtbl-hijacker-command-102
9169 orgtbl-hijacker-command-103
9170 orgtbl-hijacker-command-104
9171 orgtbl-hijacker-command-105))
9172 (org-table-blank-field))
9174 (eq N 1)
9175 (looking-at "[^|\n]* +|"))
9176 (let (org-table-may-need-update)
9177 (goto-char (1- (match-end 0)))
9178 (delete-backward-char 1)
9179 (goto-char (match-beginning 0))
9180 (self-insert-command N))
9181 (setq org-table-may-need-update t)
9182 (let (orgtbl-mode)
9183 (call-interactively (key-binding (vector last-input-event))))))
9185 (defun org-force-self-insert (N)
9186 "Needed to enforce self-insert under remapping."
9187 (interactive "p")
9188 (self-insert-command N))
9190 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
9191 "Regula expression matching exponentials as produced by calc.")
9193 (defvar org-table-clean-did-remove-column-1 nil)
9195 (defun orgtbl-send-table (&optional maybe)
9196 "Send a tranformed version of this table to the receiver position.
9197 With argument MAYBE, fail quietly if no transformation is defined for
9198 this table."
9199 (interactive)
9200 (catch 'exit
9201 (unless (org-at-table-p) (error "Not at a table"))
9202 ;; when non-interactive, we assume align has just happened.
9203 (when (interactive-p) (org-table-align))
9204 (save-excursion
9205 (goto-char (org-table-begin))
9206 (beginning-of-line 0)
9207 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
9208 (if maybe
9209 (throw 'exit nil)
9210 (error "Don't know how to transform this table."))))
9211 (let* ((name (match-string 1))
9213 (transform (intern (match-string 2)))
9214 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
9215 (skip (plist-get params :skip))
9216 (skipcols (plist-get params :skipcols))
9217 (txt (buffer-substring-no-properties
9218 (org-table-begin) (org-table-end)))
9219 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
9220 (lines (org-table-clean-before-export lines))
9221 (i0 (if org-table-clean-did-remove-column-1 2 1))
9222 (table (mapcar
9223 (lambda (x)
9224 (if (string-match org-table-hline-regexp x)
9225 'hline
9226 (org-remove-by-index
9227 (org-split-string (org-trim x) "\\s-*|\\s-*")
9228 skipcols i0)))
9229 lines))
9230 (fun (if (= i0 2) 'cdr 'identity))
9231 (org-table-last-alignment
9232 (org-remove-by-index (funcall fun org-table-last-alignment)
9233 skipcols i0))
9234 (org-table-last-column-widths
9235 (org-remove-by-index (funcall fun org-table-last-column-widths)
9236 skipcols i0)))
9238 (unless (fboundp transform)
9239 (error "No such transformation function %s" transform))
9240 (setq txt (funcall transform table params))
9241 ;; Find the insertion place
9242 (save-excursion
9243 (goto-char (point-min))
9244 (unless (re-search-forward
9245 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
9246 (error "Don't know where to insert translated table"))
9247 (goto-char (match-beginning 0))
9248 (beginning-of-line 2)
9249 (setq beg (point))
9250 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
9251 (error "Cannot find end of insertion region"))
9252 (beginning-of-line 1)
9253 (delete-region beg (point))
9254 (goto-char beg)
9255 (insert txt "\n"))
9256 (message "Table converted and installed at receiver location"))))
9258 (defun org-remove-by-index (list indices &optional i0)
9259 "Remove the elements in LIST with indices in INDICES.
9260 First element has index 0, or I0 if given."
9261 (if (not indices)
9262 list
9263 (if (integerp indices) (setq indices (list indices)))
9264 (setq i0 (1- (or i0 0)))
9265 (delq :rm (mapcar (lambda (x)
9266 (setq i0 (1+ i0))
9267 (if (memq i0 indices) :rm x))
9268 list))))
9270 (defun orgtbl-toggle-comment ()
9271 "Comment or uncomment the orgtbl at point."
9272 (interactive)
9273 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
9274 (re2 (concat "^" orgtbl-line-start-regexp))
9275 (commented (save-excursion (beginning-of-line 1)
9276 (cond ((looking-at re1) t)
9277 ((looking-at re2) nil)
9278 (t (error "Not at an org table")))))
9279 (re (if commented re1 re2))
9280 beg end)
9281 (save-excursion
9282 (beginning-of-line 1)
9283 (while (looking-at re) (beginning-of-line 0))
9284 (beginning-of-line 2)
9285 (setq beg (point))
9286 (while (looking-at re) (beginning-of-line 2))
9287 (setq end (point)))
9288 (comment-region beg end (if commented '(4) nil))))
9290 (defun orgtbl-insert-radio-table ()
9291 "Insert a radio table template appropriate for this major mode."
9292 (interactive)
9293 (let* ((e (assq major-mode orgtbl-radio-table-templates))
9294 (txt (nth 1 e))
9295 name pos)
9296 (unless e (error "No radio table setup defined for %s" major-mode))
9297 (setq name (read-string "Table name: "))
9298 (while (string-match "%n" txt)
9299 (setq txt (replace-match name t t txt)))
9300 (or (bolp) (insert "\n"))
9301 (setq pos (point))
9302 (insert txt)
9303 (goto-char pos)))
9305 (defun org-get-param (params header i sym &optional hsym)
9306 "Get parameter value for symbol SYM.
9307 If this is a header line, actually get the value for the symbol with an
9308 additional \"h\" inserted after the colon.
9309 If the value is a protperty list, get the element for the current column.
9310 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
9311 (let ((val (plist-get params sym)))
9312 (and hsym header (setq val (or (plist-get params hsym) val)))
9313 (if (consp val) (plist-get val i) val)))
9315 (defun orgtbl-to-generic (table params)
9316 "Convert the orgtbl-mode TABLE to some other format.
9317 This generic routine can be used for many standard cases.
9318 TABLE is a list, each entry either the symbol `hline' for a horizontal
9319 separator line, or a list of fields for that line.
9320 PARAMS is a property list of parameters that can influence the conversion.
9321 For the generic converter, some parameters are obligatory: You need to
9322 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
9323 :splice, you must have :tstart and :tend.
9325 Valid parameters are
9327 :tstart String to start the table. Ignored when :splice is t.
9328 :tend String to end the table. Ignored when :splice is t.
9330 :splice When set to t, return only table body lines, don't wrap
9331 them into :tstart and :tend. Default is nil.
9333 :hline String to be inserted on horizontal separation lines.
9334 May be nil to ignore hlines.
9336 :lstart String to start a new table line.
9337 :lend String to end a table line
9338 :sep Separator between two fields
9339 :lfmt Format for entire line, with enough %s to capture all fields.
9340 If this is present, :lstart, :lend, and :sep are ignored.
9341 :fmt A format to be used to wrap the field, should contain
9342 %s for the original field value. For example, to wrap
9343 everything in dollars, you could use :fmt \"$%s$\".
9344 This may also be a property list with column numbers and
9345 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
9347 :hlstart :hlend :hlsep :hlfmt :hfmt
9348 Same as above, specific for the header lines in the table.
9349 All lines before the first hline are treated as header.
9350 If any of these is not present, the data line value is used.
9352 :efmt Use this format to print numbers with exponentials.
9353 The format should have %s twice for inserting mantissa
9354 and exponent, for example \"%s\\\\times10^{%s}\". This
9355 may also be a property list with column numbers and
9356 formats. :fmt will still be applied after :efmt.
9358 In addition to this, the parameters :skip and :skipcols are always handled
9359 directly by `orgtbl-send-table'. See manual."
9360 (interactive)
9361 (let* ((p params)
9362 (splicep (plist-get p :splice))
9363 (hline (plist-get p :hline))
9364 rtn line i fm efm lfmt h)
9366 ;; Do we have a header?
9367 (if (and (not splicep) (listp (car table)) (memq 'hline table))
9368 (setq h t))
9370 ;; Put header
9371 (unless splicep
9372 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
9374 ;; Now loop over all lines
9375 (while (setq line (pop table))
9376 (if (eq line 'hline)
9377 ;; A horizontal separator line
9378 (progn (if hline (push hline rtn))
9379 (setq h nil)) ; no longer in header
9380 ;; A normal line. Convert the fields, push line onto the result list
9381 (setq i 0)
9382 (setq line
9383 (mapcar
9384 (lambda (f)
9385 (setq i (1+ i)
9386 fm (org-get-param p h i :fmt :hfmt)
9387 efm (org-get-param p h i :efmt))
9388 (if (and efm (string-match orgtbl-exp-regexp f))
9389 (setq f (format
9390 efm (match-string 1 f) (match-string 2 f))))
9391 (if fm (setq f (format fm f)))
9393 line))
9394 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
9395 (push (apply 'format lfmt line) rtn)
9396 (push (concat
9397 (org-get-param p h i :lstart :hlstart)
9398 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
9399 (org-get-param p h i :lend :hlend))
9400 rtn))))
9402 (unless splicep
9403 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
9405 (mapconcat 'identity (nreverse rtn) "\n")))
9407 (defun orgtbl-to-latex (table params)
9408 "Convert the orgtbl-mode TABLE to LaTeX.
9409 TABLE is a list, each entry either the symbol `hline' for a horizontal
9410 separator line, or a list of fields for that line.
9411 PARAMS is a property list of parameters that can influence the conversion.
9412 Supports all parameters from `orgtbl-to-generic'. Most important for
9413 LaTeX are:
9415 :splice When set to t, return only table body lines, don't wrap
9416 them into a tabular environment. Default is nil.
9418 :fmt A format to be used to wrap the field, should contain %s for the
9419 original field value. For example, to wrap everything in dollars,
9420 use :fmt \"$%s$\". This may also be a property list with column
9421 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
9423 :efmt Format for transforming numbers with exponentials. The format
9424 should have %s twice for inserting mantissa and exponent, for
9425 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
9426 This may also be a property list with column numbers and formats.
9428 The general parameters :skip and :skipcols have already been applied when
9429 this function is called."
9430 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
9431 org-table-last-alignment ""))
9432 (params2
9433 (list
9434 :tstart (concat "\\begin{tabular}{" alignment "}")
9435 :tend "\\end{tabular}"
9436 :lstart "" :lend " \\\\" :sep " & "
9437 :efmt "%s\\,(%s)" :hline "\\hline")))
9438 (orgtbl-to-generic table (org-combine-plists params2 params))))
9440 (defun orgtbl-to-html (table params)
9441 "Convert the orgtbl-mode TABLE to LaTeX.
9442 TABLE is a list, each entry either the symbol `hline' for a horizontal
9443 separator line, or a list of fields for that line.
9444 PARAMS is a property list of parameters that can influence the conversion.
9445 Currently this function recognizes the following parameters:
9447 :splice When set to t, return only table body lines, don't wrap
9448 them into a <table> environment. Default is nil.
9450 The general parameters :skip and :skipcols have already been applied when
9451 this function is called. The function does *not* use `orgtbl-to-generic',
9452 so you cannot specify parameters for it."
9453 (let* ((splicep (plist-get params :splice))
9454 html)
9455 ;; Just call the formatter we already have
9456 ;; We need to make text lines for it, so put the fields back together.
9457 (setq html (org-format-org-table-html
9458 (mapcar
9459 (lambda (x)
9460 (if (eq x 'hline)
9461 "|----+----|"
9462 (concat "| " (mapconcat 'identity x " | ") " |")))
9463 table)
9464 splicep))
9465 (if (string-match "\n+\\'" html)
9466 (setq html (replace-match "" t t html)))
9467 html))
9469 (defun orgtbl-to-texinfo (table params)
9470 "Convert the orgtbl-mode TABLE to TeXInfo.
9471 TABLE is a list, each entry either the symbol `hline' for a horizontal
9472 separator line, or a list of fields for that line.
9473 PARAMS is a property list of parameters that can influence the conversion.
9474 Supports all parameters from `orgtbl-to-generic'. Most important for
9475 TeXInfo are:
9477 :splice nil/t When set to t, return only table body lines, don't wrap
9478 them into a multitable environment. Default is nil.
9480 :fmt fmt A format to be used to wrap the field, should contain
9481 %s for the original field value. For example, to wrap
9482 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
9483 This may also be a property list with column numbers and
9484 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
9486 :cf \"f1 f2..\" The column fractions for the table. Bye default these
9487 are computed automatically from the width of the columns
9488 under org-mode.
9490 The general parameters :skip and :skipcols have already been applied when
9491 this function is called."
9492 (let* ((total (float (apply '+ org-table-last-column-widths)))
9493 (colfrac (or (plist-get params :cf)
9494 (mapconcat
9495 (lambda (x) (format "%.3f" (/ (float x) total)))
9496 org-table-last-column-widths " ")))
9497 (params2
9498 (list
9499 :tstart (concat "@multitable @columnfractions " colfrac)
9500 :tend "@end multitable"
9501 :lstart "@item " :lend "" :sep " @tab "
9502 :hlstart "@headitem ")))
9503 (orgtbl-to-generic table (org-combine-plists params2 params))))
9505 ;;;; Link Stuff
9507 ;;; Link abbreviations
9509 (defun org-link-expand-abbrev (link)
9510 "Apply replacements as defined in `org-link-abbrev-alist."
9511 (if (string-match "^\\([a-zA-Z]+\\)\\(::?\\(.*\\)\\)?$" link)
9512 (let* ((key (match-string 1 link))
9513 (as (or (assoc key org-link-abbrev-alist-local)
9514 (assoc key org-link-abbrev-alist)))
9515 (tag (and (match-end 2) (match-string 3 link)))
9516 rpl)
9517 (if (not as)
9518 link
9519 (setq rpl (cdr as))
9520 (cond
9521 ((symbolp rpl) (funcall rpl tag))
9522 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9523 (t (concat rpl tag)))))
9524 link))
9526 ;;; Storing and inserting links
9528 (defvar org-insert-link-history nil
9529 "Minibuffer history for links inserted with `org-insert-link'.")
9531 (defvar org-stored-links nil
9532 "Contains the links stored with `org-store-link'.")
9534 (defvar org-store-link-plist nil
9535 "Plist with info about the most recently link created with `org-store-link'.")
9537 ;;;###autoload
9538 (defun org-store-link (arg)
9539 "\\<org-mode-map>Store an org-link to the current location.
9540 This link can later be inserted into an org-buffer with
9541 \\[org-insert-link].
9542 For some link types, a prefix arg is interpreted:
9543 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9544 For file links, arg negates `org-context-in-file-links'."
9545 (interactive "P")
9546 (setq org-store-link-plist nil) ; reset
9547 (let (link cpltxt desc description search txt)
9548 (cond
9550 ((eq major-mode 'bbdb-mode)
9551 (let ((name (bbdb-record-name (bbdb-current-record)))
9552 (company (bbdb-record-company (bbdb-current-record))))
9553 (setq cpltxt (concat "bbdb:" (or name company))
9554 link (org-make-link cpltxt))
9555 (org-store-link-props :type "bbdb" :name name :company company)))
9557 ((eq major-mode 'Info-mode)
9558 (setq link (org-make-link "info:"
9559 (file-name-nondirectory Info-current-file)
9560 ":" Info-current-node))
9561 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9562 ":" Info-current-node))
9563 (org-store-link-props :type "info" :file Info-current-file
9564 :node Info-current-node))
9566 ((eq major-mode 'calendar-mode)
9567 (let ((cd (calendar-cursor-to-date)))
9568 (setq link
9569 (format-time-string
9570 (car org-time-stamp-formats)
9571 (apply 'encode-time
9572 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9573 nil nil nil))))
9574 (org-store-link-props :type "calendar" :date cd)))
9576 ((or (eq major-mode 'vm-summary-mode)
9577 (eq major-mode 'vm-presentation-mode))
9578 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9579 (vm-follow-summary-cursor)
9580 (save-excursion
9581 (vm-select-folder-buffer)
9582 (let* ((message (car vm-message-pointer))
9583 (folder buffer-file-name)
9584 (subject (vm-su-subject message))
9585 (to (vm-get-header-contents message "To"))
9586 (from (vm-get-header-contents message "From"))
9587 (message-id (vm-su-message-id message)))
9588 (org-store-link-props :type "vm" :from from :to to :subject subject
9589 :message-id message-id)
9590 (setq message-id (org-remove-angle-brackets message-id))
9591 (setq folder (abbreviate-file-name folder))
9592 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9593 folder)
9594 (setq folder (replace-match "" t t folder)))
9595 (setq cpltxt (org-email-link-description))
9596 (setq link (org-make-link "vm:" folder "#" message-id)))))
9598 ((eq major-mode 'wl-summary-mode)
9599 (let* ((msgnum (wl-summary-message-number))
9600 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9601 msgnum 'message-id))
9602 (wl-message-entity
9603 (if (fboundp 'elmo-message-entity)
9604 (elmo-message-entity
9605 wl-summary-buffer-elmo-folder msgnum)
9606 (elmo-msgdb-overview-get-entity
9607 msgnum (wl-summary-buffer-msgdb))))
9608 (from (wl-summary-line-from))
9609 (to (car (elmo-message-entity-field wl-message-entity 'to)))
9610 (subject (let (wl-thr-indent-string wl-parent-message-entity)
9611 (wl-summary-line-subject))))
9612 (org-store-link-props :type "wl" :from from :to to
9613 :subject subject :message-id message-id)
9614 (setq message-id (org-remove-angle-brackets message-id))
9615 (setq cpltxt (org-email-link-description))
9616 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9617 "#" message-id))))
9619 ((or (equal major-mode 'mh-folder-mode)
9620 (equal major-mode 'mh-show-mode))
9621 (let ((from (org-mhe-get-header "From:"))
9622 (to (org-mhe-get-header "To:"))
9623 (message-id (org-mhe-get-header "Message-Id:"))
9624 (subject (org-mhe-get-header "Subject:")))
9625 (org-store-link-props :type "mh" :from from :to to
9626 :subject subject :message-id message-id)
9627 (setq cpltxt (org-email-link-description))
9628 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9629 (org-remove-angle-brackets message-id)))))
9631 ((eq major-mode 'rmail-mode)
9632 (save-excursion
9633 (save-restriction
9634 (rmail-narrow-to-non-pruned-header)
9635 (let ((folder buffer-file-name)
9636 (message-id (mail-fetch-field "message-id"))
9637 (from (mail-fetch-field "from"))
9638 (to (mail-fetch-field "to"))
9639 (subject (mail-fetch-field "subject")))
9640 (org-store-link-props
9641 :type "rmail" :from from :to to
9642 :subject subject :message-id message-id)
9643 (setq message-id (org-remove-angle-brackets message-id))
9644 (setq cpltxt (org-email-link-description))
9645 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9647 ((eq major-mode 'gnus-group-mode)
9648 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9649 (gnus-group-group-name)) ; version
9650 ((fboundp 'gnus-group-name)
9651 (gnus-group-name))
9652 (t "???"))))
9653 (unless group (error "Not on a group"))
9654 (org-store-link-props :type "gnus" :group group)
9655 (setq cpltxt (concat
9656 (if (org-xor arg org-usenet-links-prefer-google)
9657 "http://groups.google.com/groups?group="
9658 "gnus:")
9659 group)
9660 link (org-make-link cpltxt))))
9662 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9663 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9664 (let* ((group gnus-newsgroup-name)
9665 (article (gnus-summary-article-number))
9666 (header (gnus-summary-article-header article))
9667 (from (mail-header-from header))
9668 (message-id (mail-header-id header))
9669 (date (mail-header-date header))
9670 (subject (gnus-summary-subject-string)))
9671 (org-store-link-props :type "gnus" :from from :subject subject
9672 :message-id message-id :group group)
9673 (setq cpltxt (org-email-link-description))
9674 (if (org-xor arg org-usenet-links-prefer-google)
9675 (setq link
9676 (concat
9677 cpltxt "\n "
9678 (format "http://groups.google.com/groups?as_umsgid=%s"
9679 (org-fixup-message-id-for-http message-id))))
9680 (setq link (org-make-link "gnus:" group
9681 "#" (number-to-string article))))))
9683 ((eq major-mode 'w3-mode)
9684 (setq cpltxt (url-view-url t)
9685 link (org-make-link cpltxt))
9686 (org-store-link-props :type "w3" :url (url-view-url t)))
9688 ((eq major-mode 'w3m-mode)
9689 (setq cpltxt (or w3m-current-title w3m-current-url)
9690 link (org-make-link w3m-current-url))
9691 (org-store-link-props :type "w3m" :url (url-view-url t)))
9693 ((setq search (run-hook-with-args-until-success
9694 'org-create-file-search-functions))
9695 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9696 "::" search))
9697 (setq cpltxt (or description link)))
9699 ((eq major-mode 'image-mode)
9700 (setq cpltxt (concat "file:"
9701 (abbreviate-file-name buffer-file-name))
9702 link (org-make-link cpltxt))
9703 (org-store-link-props :type "image" :file buffer-file-name))
9705 ((eq major-mode 'dired-mode)
9706 ;; link to the file in the current line
9707 (setq cpltxt (concat "file:"
9708 (abbreviate-file-name
9709 (expand-file-name
9710 (dired-get-filename nil t))))
9711 link (org-make-link cpltxt)))
9713 ((and buffer-file-name (org-mode-p))
9714 ;; Just link to current headline
9715 (setq cpltxt (concat "file:"
9716 (abbreviate-file-name buffer-file-name)))
9717 ;; Add a context search string
9718 (when (org-xor org-context-in-file-links arg)
9719 ;; Check if we are on a target
9720 (if (org-in-regexp "<<\\(.*?\\)>>")
9721 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9722 (setq txt (cond
9723 ((org-on-heading-p) nil)
9724 ((org-region-active-p)
9725 (buffer-substring (region-beginning) (region-end)))
9726 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9727 (when (or (null txt) (string-match "\\S-" txt))
9728 (setq cpltxt
9729 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9730 desc "NONE"))))
9731 (if (string-match "::\\'" cpltxt)
9732 (setq cpltxt (substring cpltxt 0 -2)))
9733 (setq link (org-make-link cpltxt)))
9735 (buffer-file-name
9736 ;; Just link to this file here.
9737 (setq cpltxt (concat "file:"
9738 (abbreviate-file-name buffer-file-name)))
9739 ;; Add a context string
9740 (when (org-xor org-context-in-file-links arg)
9741 (setq txt (if (org-region-active-p)
9742 (buffer-substring (region-beginning) (region-end))
9743 (buffer-substring (point-at-bol) (point-at-eol))))
9744 ;; Only use search option if there is some text.
9745 (when (string-match "\\S-" txt)
9746 (setq cpltxt
9747 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9748 desc "NONE")))
9749 (setq link (org-make-link cpltxt)))
9751 ((interactive-p)
9752 (error "Cannot link to a buffer which is not visiting a file"))
9754 (t (setq link nil)))
9756 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9757 (setq link (or link cpltxt)
9758 desc (or desc cpltxt))
9759 (if (equal desc "NONE") (setq desc nil))
9761 (if (and (interactive-p) link)
9762 (progn
9763 (setq org-stored-links
9764 (cons (list cpltxt link desc) org-stored-links))
9765 (message "Stored: %s" (or cpltxt link)))
9766 (org-make-link-string link desc))))
9768 (defun org-store-link-props (&rest plist)
9769 "Store link properties, extract names and addresses."
9770 (let (x adr)
9771 (when (setq x (plist-get plist :from))
9772 (setq adr (mail-extract-address-components x))
9773 (plist-put plist :fromname (car adr))
9774 (plist-put plist :fromaddress (nth 1 adr)))
9775 (when (setq x (plist-get plist :to))
9776 (setq adr (mail-extract-address-components x))
9777 (plist-put plist :toname (car adr))
9778 (plist-put plist :toaddress (nth 1 adr))))
9779 (let ((from (plist-get plist :from))
9780 (to (plist-get plist :to)))
9781 (when (and from to org-from-is-user-regexp)
9782 (plist-put plist :fromto
9783 (if (string-match org-from-is-user-regexp from)
9784 (concat "to %t")
9785 (concat "from %f")))))
9786 (setq org-store-link-plist plist))
9788 (defun org-email-link-description (&optional fmt)
9789 "Return the description part of an email link.
9790 This takes information from `org-store-link-plist' and formats it
9791 according to FMT (default from `org-email-link-description-format')."
9792 (setq fmt (or fmt org-email-link-description-format))
9793 (let* ((p org-store-link-plist)
9794 (to (plist-get p :toaddress))
9795 (from (plist-get p :fromaddress))
9796 (table
9797 (list
9798 (cons "%c" (plist-get p :fromto))
9799 (cons "%F" (plist-get p :from))
9800 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9801 (cons "%T" (plist-get p :to))
9802 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9803 (cons "%s" (plist-get p :subject))
9804 (cons "%m" (plist-get p :message-id)))))
9805 (when (string-match "%c" fmt)
9806 ;; Check if the user wrote this message
9807 (if (and org-from-is-user-regexp from to
9808 (save-match-data (string-match org-from-is-user-regexp from)))
9809 (setq fmt (replace-match "to %t" t t fmt))
9810 (setq fmt (replace-match "from %f" t t fmt))))
9811 (org-replace-escapes fmt table)))
9813 (defun org-make-org-heading-search-string (&optional string heading)
9814 "Make search string for STRING or current headline."
9815 (interactive)
9816 (let ((s (or string (org-get-heading))))
9817 (unless (and string (not heading))
9818 ;; We are using a headline, clean up garbage in there.
9819 (if (string-match org-todo-regexp s)
9820 (setq s (replace-match "" t t s)))
9821 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
9822 (setq s (replace-match "" t t s)))
9823 (setq s (org-trim s))
9824 (if (string-match (concat "^\\(" org-quote-string "\\|"
9825 org-comment-string "\\)") s)
9826 (setq s (replace-match "" t t s)))
9827 (while (string-match org-ts-regexp s)
9828 (setq s (replace-match "" t t s))))
9829 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
9830 (setq s (replace-match " " t t s)))
9831 (or string (setq s (concat "*" s))) ; Add * for headlines
9832 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9834 (defun org-make-link (&rest strings)
9835 "Concatenate STRINGS, format resulting string with `org-link-format'."
9836 (apply 'concat strings))
9838 (defun org-make-link-string (link &optional description)
9839 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9840 (when (stringp description)
9841 ;; Remove brackets from the description, they are fatal.
9842 (while (string-match "\\[\\|\\]" description)
9843 (setq description (replace-match "" t t description))))
9844 (when (equal (org-link-escape link) description)
9845 ;; No description needed, it is identical
9846 (setq description nil))
9847 (when (and (not description)
9848 (not (equal link (org-link-escape link))))
9849 (setq description link))
9850 (concat "[[" (org-link-escape link) "]"
9851 (if description (concat "[" description "]") "")
9852 "]"))
9854 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
9855 "Association list of escapes for some characters problematic in links.")
9857 (defun org-link-escape (text)
9858 "Escape charaters in TEXT that are problematic for links."
9859 (when text
9860 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
9861 org-link-escape-chars "\\|")))
9862 (while (string-match re text)
9863 (setq text
9864 (replace-match
9865 (cdr (assoc (match-string 0 text) org-link-escape-chars))
9866 t t text)))
9867 text)))
9869 (defun org-link-unescape (text)
9870 "Reverse the action of `org-link-escape'."
9871 (when text
9872 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
9873 org-link-escape-chars "\\|")))
9874 (while (string-match re text)
9875 (setq text
9876 (replace-match
9877 (car (rassoc (match-string 0 text) org-link-escape-chars))
9878 t t text)))
9879 text)))
9881 (defun org-xor (a b)
9882 "Exclusive or."
9883 (if a (not b) b))
9885 (defun org-get-header (header)
9886 "Find a header field in the current buffer."
9887 (save-excursion
9888 (goto-char (point-min))
9889 (let ((case-fold-search t) s)
9890 (cond
9891 ((eq header 'from)
9892 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
9893 (setq s (match-string 1)))
9894 (while (string-match "\"" s)
9895 (setq s (replace-match "" t t s)))
9896 (if (string-match "[<(].*" s)
9897 (setq s (replace-match "" t t s))))
9898 ((eq header 'message-id)
9899 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
9900 (setq s (match-string 1))))
9901 ((eq header 'subject)
9902 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
9903 (setq s (match-string 1)))))
9904 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
9905 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
9906 s)))
9909 (defun org-fixup-message-id-for-http (s)
9910 "Replace special characters in a message id, so it can be used in an http query."
9911 (while (string-match "<" s)
9912 (setq s (replace-match "%3C" t t s)))
9913 (while (string-match ">" s)
9914 (setq s (replace-match "%3E" t t s)))
9915 (while (string-match "@" s)
9916 (setq s (replace-match "%40" t t s)))
9919 (defun org-insert-link (&optional complete-file)
9920 "Insert a link. At the prompt, enter the link.
9922 Completion can be used to select a link previously stored with
9923 `org-store-link'. When the empty string is entered (i.e. if you just
9924 press RET at the prompt), the link defaults to the most recently
9925 stored link. As SPC triggers completion in the minibuffer, you need to
9926 use M-SPC or C-q SPC to force the insertion of a space character.
9928 You will also be prompted for a description, and if one is given, it will
9929 be displayed in the buffer instead of the link.
9931 If there is already a link at point, this command will allow you to edit link
9932 and description parts.
9934 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
9935 selected using completion. The path to the file will be relative to
9936 the current directory if the file is in the current directory or a
9937 subdirectory. Otherwise, the link will be the absolute path as
9938 completed in the minibuffer (i.e. normally ~/path/to/file).
9940 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
9941 is in the current directory or below.
9942 With three \\[universal-argument] prefixes, negate the meaning of
9943 `org-keep-stored-link-after-insertion'."
9944 (interactive "P")
9945 (let ((region (if (org-region-active-p)
9946 (prog1 (buffer-substring (region-beginning) (region-end))
9947 (delete-region (region-beginning) (region-end)))))
9948 tmphist ; byte-compile incorrectly complains about this
9949 link desc entry remove file)
9950 (cond
9951 ((org-in-regexp org-bracket-link-regexp 1)
9952 ;; We do have a link at point, and we are going to edit it.
9953 (setq remove (list (match-beginning 0) (match-end 0)))
9954 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9955 (setq link (read-string "Link: "
9956 (org-link-unescape
9957 (org-match-string-no-properties 1)))))
9958 ((or (org-in-regexp org-angle-link-re)
9959 (org-in-regexp org-plain-link-re))
9960 ;; Convert to bracket link
9961 (setq remove (list (match-beginning 0) (match-end 0))
9962 link (read-string "Link: "
9963 (org-remove-angle-brackets (match-string 0)))))
9964 ((equal complete-file '(4))
9965 ;; Completing read for file names.
9966 (setq file (read-file-name "File: "))
9967 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9968 (pwd1 (file-name-as-directory (abbreviate-file-name
9969 (expand-file-name ".")))))
9970 (cond
9971 ((equal complete-file '(16))
9972 (setq link (org-make-link
9973 "file:"
9974 (abbreviate-file-name (expand-file-name file)))))
9975 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9976 (setq link (org-make-link "file:" (match-string 1 file))))
9977 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9978 (expand-file-name file))
9979 (setq link (org-make-link
9980 "file:" (match-string 1 (expand-file-name file)))))
9981 (t (setq link (org-make-link "file:" file))))))
9983 ;; Read link, with completion for stored links.
9984 ;; Fake a link history
9985 (setq tmphist (append (mapcar 'car org-stored-links)
9986 org-insert-link-history))
9987 (setq link (org-completing-read
9988 "Link: " org-stored-links nil nil nil
9989 'tmphist
9990 (or (car (car org-stored-links)))))
9991 (setq entry (assoc link org-stored-links))
9992 (or entry (push link org-insert-link-history))
9993 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9994 (not org-keep-stored-link-after-insertion))
9995 (setq org-stored-links (delq (assoc link org-stored-links)
9996 org-stored-links)))
9997 (setq link (if entry (nth 1 entry) link)
9998 desc (or region desc (nth 2 entry)))))
10000 (if (string-match org-plain-link-re link)
10001 ;; URL-like link, normalize the use of angular brackets.
10002 (setq link (org-make-link (org-remove-angle-brackets link))))
10004 ;; Check if we are linking to the current file with a search option
10005 ;; If yes, simplify the link by using only the search option.
10006 (when (and buffer-file-name
10007 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
10008 (let* ((path (match-string 1 link))
10009 (case-fold-search nil)
10010 (search (match-string 2 link)))
10011 (save-match-data
10012 (if (equal (file-truename buffer-file-name) (file-truename path))
10013 ;; We are linking to this same file, with a search option
10014 (setq link search)))))
10016 ;; Check if we can/should use a relative path. If yes, simplify the link
10017 (when (string-match "\\<file:\\(.*\\)" link)
10018 (let* ((path (match-string 1 link))
10019 (case-fold-search nil))
10020 (cond
10021 ((eq org-link-file-path-type 'absolute)
10022 (setq path (abbreviate-file-name (expand-file-name path))))
10023 ((eq org-link-file-path-type 'noabbrev)
10024 (setq path (expand-file-name path)))
10025 ((eq org-link-file-path-type 'relative)
10026 (setq path (file-relative-name path)))
10028 (save-match-data
10029 (if (string-match (concat "^" (regexp-quote
10030 (file-name-as-directory
10031 (expand-file-name "."))))
10032 (expand-file-name path))
10033 ;; We are linking a file with relative path name.
10034 (setq path (substring (expand-file-name path)
10035 (match-end 0)))))))
10036 (setq link (concat "file:" path))))
10038 (setq desc (read-string "Description: " desc))
10039 (unless (string-match "\\S-" desc) (setq desc nil))
10040 (if remove (apply 'delete-region remove))
10041 (insert (org-make-link-string link desc))))
10043 (defun org-completing-read (&rest args)
10044 (let ((minibuffer-local-completion-map
10045 (copy-keymap minibuffer-local-completion-map)))
10046 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10047 (apply 'completing-read args)))
10049 ;;; Opening/following a link
10050 (defvar org-link-search-failed nil)
10052 (defun org-next-link ()
10053 "Move forward to the next link.
10054 If the link is in hidden text, expose it."
10055 (interactive)
10056 (when (and org-link-search-failed (eq this-command last-command))
10057 (goto-char (point-min))
10058 (message "Link search wrapped back to beginning of buffer"))
10059 (setq org-link-search-failed nil)
10060 (let* ((pos (point))
10061 (ct (org-context))
10062 (a (assoc :link ct)))
10063 (if a (goto-char (nth 2 a)))
10064 (if (re-search-forward org-any-link-re nil t)
10065 (progn
10066 (goto-char (match-beginning 0))
10067 (if (org-invisible-p) (org-show-context)))
10068 (goto-char pos)
10069 (setq org-link-search-failed t)
10070 (error "No further link found"))))
10072 (defun org-previous-link ()
10073 "Move backward to the previous link.
10074 If the link is in hidden text, expose it."
10075 (interactive)
10076 (when (and org-link-search-failed (eq this-command last-command))
10077 (goto-char (point-max))
10078 (message "Link search wrapped back to end of buffer"))
10079 (setq org-link-search-failed nil)
10080 (let* ((pos (point))
10081 (ct (org-context))
10082 (a (assoc :link ct)))
10083 (if a (goto-char (nth 1 a)))
10084 (if (re-search-backward org-any-link-re nil t)
10085 (progn
10086 (goto-char (match-beginning 0))
10087 (if (org-invisible-p) (org-show-context)))
10088 (goto-char pos)
10089 (setq org-link-search-failed t)
10090 (error "No further link found"))))
10092 (defun org-find-file-at-mouse (ev)
10093 "Open file link or URL at mouse."
10094 (interactive "e")
10095 (mouse-set-point ev)
10096 (org-open-at-point 'in-emacs))
10098 (defun org-open-at-mouse (ev)
10099 "Open file link or URL at mouse."
10100 (interactive "e")
10101 (mouse-set-point ev)
10102 (org-open-at-point))
10104 (defvar org-window-config-before-follow-link nil
10105 "The window configuration before following a link.
10106 This is saved in case the need arises to restore it.")
10108 (defvar org-open-link-marker (make-marker)
10109 "Marker pointing to the location where `org-open-at-point; was called.")
10111 (defun org-open-at-point (&optional in-emacs)
10112 "Open link at or after point.
10113 If there is no link at point, this function will search forward up to
10114 the end of the current subtree.
10115 Normally, files will be opened by an appropriate application. If the
10116 optional argument IN-EMACS is non-nil, Emacs will visit the file."
10117 (interactive "P")
10118 (move-marker org-open-link-marker (point))
10119 (setq org-window-config-before-follow-link (current-window-configuration))
10120 (org-remove-occur-highlights nil nil t)
10121 (if (org-at-timestamp-p t)
10122 (org-follow-timestamp-link)
10123 (let (type path link line search (pos (point)))
10124 (catch 'match
10125 (save-excursion
10126 (skip-chars-forward "^]\n\r")
10127 (when (org-in-regexp org-bracket-link-regexp)
10128 (setq link (org-link-unescape (org-match-string-no-properties 1)))
10129 (while (string-match " *\n *" link)
10130 (setq link (replace-match " " t t link)))
10131 (setq link (org-link-expand-abbrev link))
10132 (if (string-match org-link-re-with-space2 link)
10133 (setq type (match-string 1 link) path (match-string 2 link))
10134 (setq type "thisfile" path link))
10135 (throw 'match t)))
10137 (when (get-text-property (point) 'org-linked-text)
10138 (setq type "thisfile"
10139 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10140 (1+ (point)) (point))
10141 path (buffer-substring
10142 (previous-single-property-change pos 'org-linked-text)
10143 (next-single-property-change pos 'org-linked-text)))
10144 (throw 'match t))
10146 (save-excursion
10147 (when (or (org-in-regexp org-angle-link-re)
10148 (org-in-regexp org-plain-link-re))
10149 (setq type (match-string 1) path (match-string 2))
10150 (throw 'match t)))
10151 (save-excursion
10152 (when (org-in-regexp "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
10153 (setq type "tags"
10154 path (match-string 1))
10155 (while (string-match ":" path)
10156 (setq path (replace-match "+" t t path)))
10157 (throw 'match t))))
10158 (unless path
10159 (error "No link found"))
10160 ;; Remove any trailing spaces in path
10161 (if (string-match " +\\'" path)
10162 (setq path (replace-match "" t t path)))
10164 (cond
10166 ((equal type "mailto")
10167 (let ((cmd (car org-link-mailto-program))
10168 (args (cdr org-link-mailto-program)) args1
10169 (address path) (subject "") a)
10170 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10171 (setq address (match-string 1 path)
10172 subject (org-link-escape (match-string 2 path))))
10173 (while args
10174 (cond
10175 ((not (stringp (car args))) (push (pop args) args1))
10176 (t (setq a (pop args))
10177 (if (string-match "%a" a)
10178 (setq a (replace-match address t t a)))
10179 (if (string-match "%s" a)
10180 (setq a (replace-match subject t t a)))
10181 (push a args1))))
10182 (apply cmd (nreverse args1))))
10184 ((member type '("http" "https" "ftp" "news"))
10185 (browse-url (concat type ":" path)))
10187 ((string= type "tags")
10188 (org-tags-view in-emacs path))
10189 ((string= type "thisfile")
10190 (if in-emacs
10191 (switch-to-buffer-other-window
10192 (org-get-buffer-for-internal-link (current-buffer)))
10193 (org-mark-ring-push))
10194 (org-link-search
10195 path
10196 (cond ((equal in-emacs '(4)) 'occur)
10197 ((equal in-emacs '(16)) 'org-occur)
10198 (t nil))
10199 pos))
10201 ((string= type "file")
10202 (if (string-match "::\\([0-9]+\\)\\'" path)
10203 (setq line (string-to-number (match-string 1 path))
10204 path (substring path 0 (match-beginning 0)))
10205 (if (string-match "::\\(.+\\)\\'" path)
10206 (setq search (match-string 1 path)
10207 path (substring path 0 (match-beginning 0)))))
10208 (org-open-file path in-emacs line search))
10210 ((string= type "news")
10211 (org-follow-gnus-link path))
10213 ((string= type "bbdb")
10214 (org-follow-bbdb-link path))
10216 ((string= type "info")
10217 (org-follow-info-link path))
10219 ((string= type "gnus")
10220 (let (group article)
10221 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10222 (error "Error in Gnus link"))
10223 (setq group (match-string 1 path)
10224 article (match-string 3 path))
10225 (org-follow-gnus-link group article)))
10227 ((string= type "vm")
10228 (let (folder article)
10229 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10230 (error "Error in VM link"))
10231 (setq folder (match-string 1 path)
10232 article (match-string 3 path))
10233 ;; in-emacs is the prefix arg, will be interpreted as read-only
10234 (org-follow-vm-link folder article in-emacs)))
10236 ((string= type "wl")
10237 (let (folder article)
10238 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10239 (error "Error in Wanderlust link"))
10240 (setq folder (match-string 1 path)
10241 article (match-string 3 path))
10242 (org-follow-wl-link folder article)))
10244 ((string= type "mhe")
10245 (let (folder article)
10246 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10247 (error "Error in MHE link"))
10248 (setq folder (match-string 1 path)
10249 article (match-string 3 path))
10250 (org-follow-mhe-link folder article)))
10252 ((string= type "rmail")
10253 (let (folder article)
10254 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
10255 (error "Error in RMAIL link"))
10256 (setq folder (match-string 1 path)
10257 article (match-string 3 path))
10258 (org-follow-rmail-link folder article)))
10260 ((string= type "shell")
10261 (let ((cmd path))
10262 ;; FIXME: the following is only for backward compatibility
10263 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
10264 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
10265 (if (or (not org-confirm-shell-link-function)
10266 (funcall org-confirm-shell-link-function
10267 (format "Execute \"%s\" in shell? "
10268 (org-add-props cmd nil
10269 'face 'org-warning))))
10270 (progn
10271 (message "Executing %s" cmd)
10272 (shell-command cmd))
10273 (error "Abort"))))
10275 ((string= type "elisp")
10276 (let ((cmd path))
10277 (if (or (not org-confirm-elisp-link-function)
10278 (funcall org-confirm-elisp-link-function
10279 (format "Execute \"%s\" as elisp? "
10280 (org-add-props cmd nil
10281 'face 'org-warning))))
10282 (message "%s => %s" cmd (eval (read cmd)))
10283 (error "Abort"))))
10286 (browse-url-at-point)))))
10287 (move-marker org-open-link-marker nil))
10290 ;;; File search
10292 (defvar org-create-file-search-functions nil
10293 "List of functions to construct the right search string for a file link.
10294 These functions are called in turn with point at the location to
10295 which the link should point.
10297 A function in the hook should first test if it would like to
10298 handle this file type, for example by checking the major-mode or
10299 the file extension. If it decides not to handle this file, it
10300 should just return nil to give other functions a chance. If it
10301 does handle the file, it must return the search string to be used
10302 when following the link. The search string will be part of the
10303 file link, given after a double colon, and `org-open-at-point'
10304 will automatically search for it. If special measures must be
10305 taken to make the search successful, another function should be
10306 added to the companion hook `org-execute-file-search-functions',
10307 which see.
10309 A function in this hook may also use `setq' to set the variable
10310 `description' to provide a suggestion for the descriptive text to
10311 be used for this link when it gets inserted into an Org-mode
10312 buffer with \\[org-insert-link].")
10314 (defvar org-execute-file-search-functions nil
10315 "List of functions to execute a file search triggered by a link.
10317 Functions added to this hook must accept a single argument, the
10318 search string that was part of the file link, the part after the
10319 double colon. The function must first check if it would like to
10320 handle this search, for example by checking the major-mode or the
10321 file extension. If it decides not to handle this search, it
10322 should just return nil to give other functions a chance. If it
10323 does handle the search, it must return a non-nil value to keep
10324 other functions from trying.
10326 Each function can access the current prefix argument through the
10327 variable `current-prefix-argument'. Note that a single prefix is
10328 used to force opening a link in Emacs, so it may be good to only
10329 use a numeric or double prefix to guide the search function.
10331 In case this is needed, a function in this hook can also restore
10332 the window configuration before `org-open-at-point' was called using:
10334 (set-window-configuration org-window-config-before-follow-link)")
10336 (defun org-link-search (s &optional type avoid-pos)
10337 "Search for a link search option.
10338 If S is surrounded by forward slashes, it is interpreted as a
10339 regular expression. In org-mode files, this will create an `org-occur'
10340 sparse tree. In ordinary files, `occur' will be used to list matches.
10341 If the current buffer is in `dired-mode', grep will be used to search
10342 in all files. If AVOID-POS is given, ignore matches near that position."
10343 (let ((case-fold-search t)
10344 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10345 (pos (point))
10346 (pre "") (post "")
10347 words re0 re1 re2 re3 re4 re5 re2a reall)
10348 (cond
10349 ;; First check if there are any special
10350 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10351 ;; Now try the builtin stuff
10352 ((save-excursion
10353 (goto-char (point-min))
10354 (and
10355 (re-search-forward
10356 (concat "<<" (regexp-quote s0) ">>") nil t)
10357 (setq pos (match-beginning 0))))
10358 ;; There is an exact target for this
10359 (goto-char pos))
10360 ((string-match "^/\\(.*\\)/$" s)
10361 ;; A regular expression
10362 (cond
10363 ((org-mode-p)
10364 (org-occur (match-string 1 s)))
10365 ;;((eq major-mode 'dired-mode)
10366 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10367 (t (org-do-occur (match-string 1 s)))))
10369 ;; A normal search string
10370 (when (equal (string-to-char s) ?*)
10371 ;; Anchor on headlines, post may include tags.
10372 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
10373 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
10374 s (substring s 1)))
10375 (remove-text-properties
10376 0 (length s)
10377 '(face nil mouse-face nil keymap nil fontified nil) s)
10378 ;; Make a series of regular expressions to find a match
10379 (setq words (org-split-string s "[ \n\r\t]+")
10380 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10381 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
10382 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10383 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10384 re1 (concat pre re2 post)
10385 re3 (concat pre re4 post)
10386 re5 (concat pre ".*" re4)
10387 re2 (concat pre re2)
10388 re2a (concat pre re2a)
10389 re4 (concat pre re4)
10390 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10391 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10392 re5 "\\)"
10394 (cond
10395 ((eq type 'org-occur) (org-occur reall))
10396 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10397 (t (goto-char (point-min))
10398 (if (or (org-search-not-self 1 re0 nil t)
10399 (org-search-not-self 1 re1 nil t)
10400 (org-search-not-self 1 re2 nil t)
10401 (org-search-not-self 1 re2a nil t)
10402 (org-search-not-self 1 re3 nil t)
10403 (org-search-not-self 1 re4 nil t)
10404 (org-search-not-self 1 re5 nil t)
10406 (goto-char (match-beginning 1))
10407 (goto-char pos)
10408 (error "No match")))))
10410 ;; Normal string-search
10411 (goto-char (point-min))
10412 (if (search-forward s nil t)
10413 (goto-char (match-beginning 0))
10414 (error "No match"))))
10415 (and (org-mode-p) (org-show-context 'link-search))))
10417 (defun org-search-not-self (group &rest args)
10418 "Execute `re-search-forward', but only accept matches that do not
10419 enclose the position of `org-open-link-marker'."
10420 (let ((m org-open-link-marker))
10421 (catch 'exit
10422 (while (apply 're-search-forward args)
10423 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10424 (goto-char (match-end group))
10425 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10426 (> (match-beginning 0) (marker-position m))
10427 (< (match-end 0) (marker-position m)))
10428 (save-match-data
10429 (or (not (org-in-regexp
10430 org-bracket-link-analytic-regexp 1))
10431 (not (match-end 4)) ; no description
10432 (and (<= (match-beginning 4) (point))
10433 (>= (match-end 4) (point))))))
10434 (throw 'exit (point))))))))
10436 (defun org-get-buffer-for-internal-link (buffer)
10437 "Return a buffer to be used for displaying the link target of internal links."
10438 (cond
10439 ((not org-display-internal-link-with-indirect-buffer)
10440 buffer)
10441 ((string-match "(Clone)$" (buffer-name buffer))
10442 (message "Buffer is already a clone, not making another one")
10443 ;; we also do not modify visibility in this case
10444 buffer)
10445 (t ; make a new indirect buffer for displaying the link
10446 (let* ((bn (buffer-name buffer))
10447 (ibn (concat bn "(Clone)"))
10448 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10449 (with-current-buffer ib (org-overview))
10450 ib))))
10452 (defun org-do-occur (regexp &optional cleanup)
10453 "Call the Emacs command `occur'.
10454 If CLEANUP is non-nil, remove the printout of the regular expression
10455 in the *Occur* buffer. This is useful if the regex is long and not useful
10456 to read."
10457 (occur regexp)
10458 (when cleanup
10459 (let ((cwin (selected-window)) win beg end)
10460 (when (setq win (get-buffer-window "*Occur*"))
10461 (select-window win))
10462 (goto-char (point-min))
10463 (when (re-search-forward "match[a-z]+" nil t)
10464 (setq beg (match-end 0))
10465 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10466 (setq end (1- (match-beginning 0)))))
10467 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
10468 (goto-char (point-min))
10469 (select-window cwin))))
10471 ;;; The mark ring for links jumps
10473 (defvar org-mark-ring nil
10474 "Mark ring for positions before jumps in Org-mode.")
10475 (defvar org-mark-ring-last-goto nil
10476 "Last position in the mark ring used to go back.")
10477 ;; Fill and close the ring
10478 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10479 (loop for i from 1 to org-mark-ring-length do
10480 (push (make-marker) org-mark-ring))
10481 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10482 org-mark-ring)
10484 (defun org-mark-ring-push (&optional pos buffer)
10485 "Put the current position or POS into the mark ring and rotate it."
10486 (interactive)
10487 (setq pos (or pos (point)))
10488 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10489 (move-marker (car org-mark-ring)
10490 (or pos (point))
10491 (or buffer (current-buffer)))
10492 (message
10493 (substitute-command-keys
10494 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10496 (defun org-mark-ring-goto (&optional n)
10497 "Jump to the previous position in the mark ring.
10498 With prefix arg N, jump back that many stored positions. When
10499 called several times in succession, walk through the entire ring.
10500 Org-mode commands jumping to a different position in the current file,
10501 or to another Org-mode file, automatically push the old position
10502 onto the ring."
10503 (interactive "p")
10504 (let (p m)
10505 (if (eq last-command this-command)
10506 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10507 (setq p org-mark-ring))
10508 (setq org-mark-ring-last-goto p)
10509 (setq m (car p))
10510 (switch-to-buffer (marker-buffer m))
10511 (goto-char m)
10512 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10514 (defun org-remove-angle-brackets (s)
10515 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10516 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10518 (defun org-add-angle-brackets (s)
10519 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10520 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10523 ;;; Following specific links
10525 (defun org-follow-timestamp-link ()
10526 (cond
10527 ((org-at-date-range-p t)
10528 (let ((org-agenda-start-on-weekday)
10529 (t1 (match-string 1))
10530 (t2 (match-string 2)))
10531 (setq t1 (time-to-days (org-time-string-to-time t1))
10532 t2 (time-to-days (org-time-string-to-time t2)))
10533 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10534 ((org-at-timestamp-p t)
10535 (org-agenda-list nil (time-to-days (org-time-string-to-time
10536 (substring (match-string 1) 0 10)))
10538 (t (error "This should not happen"))))
10541 (defun org-follow-bbdb-link (name)
10542 "Follow a BBDB link to NAME."
10543 (require 'bbdb)
10544 (let ((inhibit-redisplay (not debug-on-error))
10545 (bbdb-electric-p nil))
10546 (catch 'exit
10547 ;; Exact match on name
10548 (bbdb-name (concat "\\`" name "\\'") nil)
10549 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10550 ;; Exact match on name
10551 (bbdb-company (concat "\\`" name "\\'") nil)
10552 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10553 ;; Partial match on name
10554 (bbdb-name name nil)
10555 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10556 ;; Partial match on company
10557 (bbdb-company name nil)
10558 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
10559 ;; General match including network address and notes
10560 (bbdb name nil)
10561 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
10562 (delete-window (get-buffer-window "*BBDB*"))
10563 (error "No matching BBDB record")))))
10565 (defun org-follow-info-link (name)
10566 "Follow an info file & node link to NAME."
10567 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
10568 (string-match "\\(.*\\)" name))
10569 (progn
10570 (require 'info)
10571 (if (match-string 2 name) ; If there isn't a node, choose "Top"
10572 (Info-find-node (match-string 1 name) (match-string 2 name))
10573 (Info-find-node (match-string 1 name) "Top")))
10574 (message (concat "Could not open: " name))))
10576 (defun org-follow-gnus-link (&optional group article)
10577 "Follow a Gnus link to GROUP and ARTICLE."
10578 (require 'gnus)
10579 (funcall (cdr (assq 'gnus org-link-frame-setup)))
10580 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
10581 (cond ((and group article)
10582 (gnus-group-read-group 0 nil group)
10583 (gnus-summary-goto-article (string-to-number article) nil t))
10584 (group (gnus-group-jump-to-group group))))
10586 (defun org-follow-vm-link (&optional folder article readonly)
10587 "Follow a VM link to FOLDER and ARTICLE."
10588 (require 'vm)
10589 (setq article (org-add-angle-brackets article))
10590 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
10591 ;; ange-ftp or efs or tramp access
10592 (let ((user (or (match-string 1 folder) (user-login-name)))
10593 (host (match-string 2 folder))
10594 (file (match-string 3 folder)))
10595 (cond
10596 ((featurep 'tramp)
10597 ;; use tramp to access the file
10598 (if (featurep 'xemacs)
10599 (setq folder (format "[%s@%s]%s" user host file))
10600 (setq folder (format "/%s@%s:%s" user host file))))
10602 ;; use ange-ftp or efs
10603 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
10604 (setq folder (format "/%s@%s:%s" user host file))))))
10605 (when folder
10606 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
10607 (sit-for 0.1)
10608 (when article
10609 (vm-select-folder-buffer)
10610 (widen)
10611 (let ((case-fold-search t))
10612 (goto-char (point-min))
10613 (if (not (re-search-forward
10614 (concat "^" "message-id: *" (regexp-quote article))))
10615 (error "Could not find the specified message in this folder"))
10616 (vm-isearch-update)
10617 (vm-isearch-narrow)
10618 (vm-beginning-of-message)
10619 (vm-summarize)))))
10621 (defun org-follow-wl-link (folder article)
10622 "Follow a Wanderlust link to FOLDER and ARTICLE."
10623 (if (and (string= folder "%")
10624 article
10625 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
10626 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
10627 ;; Thus, we recompose folder and article ids.
10628 (setq folder (format "%s#%s" folder (match-string 1 article))
10629 article (match-string 3 article)))
10630 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
10631 (error "No such folder: %s" folder))
10632 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
10633 (and article
10634 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
10635 (wl-summary-redisplay)))
10637 (defun org-follow-rmail-link (folder article)
10638 "Follow an RMAIL link to FOLDER and ARTICLE."
10639 (setq article (org-add-angle-brackets article))
10640 (let (message-number)
10641 (save-excursion
10642 (save-window-excursion
10643 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10644 (setq message-number
10645 (save-restriction
10646 (widen)
10647 (goto-char (point-max))
10648 (if (re-search-backward
10649 (concat "^Message-ID:\\s-+" (regexp-quote
10650 (or article "")))
10651 nil t)
10652 (rmail-what-message))))))
10653 (if message-number
10654 (progn
10655 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
10656 (rmail-show-message message-number)
10657 message-number)
10658 (error "Message not found"))))
10660 ;;; mh-e integration based on planner-mode
10661 (defun org-mhe-get-message-real-folder ()
10662 "Return the name of the current message real folder, so if you use
10663 sequences, it will now work."
10664 (save-excursion
10665 (let* ((folder
10666 (if (equal major-mode 'mh-folder-mode)
10667 mh-current-folder
10668 ;; Refer to the show buffer
10669 mh-show-folder-buffer))
10670 (end-index
10671 (if (boundp 'mh-index-folder)
10672 (min (length mh-index-folder) (length folder))))
10674 ;; a simple test on mh-index-data does not work, because
10675 ;; mh-index-data is always nil in a show buffer.
10676 (if (and (boundp 'mh-index-folder)
10677 (string= mh-index-folder (substring folder 0 end-index)))
10678 (if (equal major-mode 'mh-show-mode)
10679 (save-window-excursion
10680 (when (buffer-live-p (get-buffer folder))
10681 (progn
10682 (pop-to-buffer folder)
10683 (org-mhe-get-message-folder-from-index)
10686 (org-mhe-get-message-folder-from-index)
10688 folder
10692 (defun org-mhe-get-message-folder-from-index ()
10693 "Returns the name of the message folder in a index folder buffer."
10694 (save-excursion
10695 (mh-index-previous-folder)
10696 (re-search-forward "^\\(+.*\\)$" nil t)
10697 (message (match-string 1))))
10699 (defun org-mhe-get-message-folder ()
10700 "Return the name of the current message folder. Be careful if you
10701 use sequences."
10702 (save-excursion
10703 (if (equal major-mode 'mh-folder-mode)
10704 mh-current-folder
10705 ;; Refer to the show buffer
10706 mh-show-folder-buffer)))
10708 (defun org-mhe-get-message-num ()
10709 "Return the number of the current message. Be careful if you
10710 use sequences."
10711 (save-excursion
10712 (if (equal major-mode 'mh-folder-mode)
10713 (mh-get-msg-num nil)
10714 ;; Refer to the show buffer
10715 (mh-show-buffer-message-number))))
10717 (defun org-mhe-get-header (header)
10718 "Return a header of the message in folder mode. This will create a
10719 show buffer for the corresponding message. If you have a more clever
10720 idea..."
10721 (let* ((folder (org-mhe-get-message-folder))
10722 (num (org-mhe-get-message-num))
10723 (buffer (get-buffer-create (concat "show-" folder)))
10724 (header-field))
10725 (with-current-buffer buffer
10726 (mh-display-msg num folder)
10727 (if (equal major-mode 'mh-folder-mode)
10728 (mh-header-display)
10729 (mh-show-header-display))
10730 (set-buffer buffer)
10731 (setq header-field (mh-get-header-field header))
10732 (if (equal major-mode 'mh-folder-mode)
10733 (mh-show)
10734 (mh-show-show))
10735 header-field)))
10737 (defun org-follow-mhe-link (folder article)
10738 "Follow an MHE link to FOLDER and ARTICLE.
10739 If ARTICLE is nil FOLDER is shown. If the configuration variable
10740 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
10741 ARTICLE is searched in all folders. Indexed searches (swish++,
10742 namazu, and others supported by MH-E) will always search in all
10743 folders."
10744 (require 'mh-e)
10745 (require 'mh-search)
10746 (require 'mh-utils)
10747 (mh-find-path)
10748 (if (not article)
10749 (mh-visit-folder (mh-normalize-folder-name folder))
10750 (setq article (org-add-angle-brackets article))
10751 (mh-search-choose)
10752 (if (equal mh-searcher 'pick)
10753 (progn
10754 (mh-search folder (list "--message-id" article))
10755 (when (and org-mhe-search-all-folders
10756 (not (org-mhe-get-message-real-folder)))
10757 (kill-this-buffer)
10758 (mh-search "+" (list "--message-id" article))))
10759 (mh-search "+" article))
10760 (if (org-mhe-get-message-real-folder)
10761 (mh-show-msg 1)
10762 (kill-this-buffer)
10763 (error "Message not found"))))
10765 ;;; BibTeX links
10767 ;; Use the custom search meachnism to construct and use search strings for
10768 ;; file links to BibTeX database entries.
10770 (defun org-create-file-search-in-bibtex ()
10771 "Create the search string and description for a BibTeX database entry."
10772 (when (eq major-mode 'bibtex-mode)
10773 ;; yes, we want to construct this search string.
10774 ;; Make a good description for this entry, using names, year and the title
10775 ;; Put it into the `description' variable which is dynamically scoped.
10776 (let ((bibtex-autokey-names 1)
10777 (bibtex-autokey-names-stretch 1)
10778 (bibtex-autokey-name-case-convert-function 'identity)
10779 (bibtex-autokey-name-separator " & ")
10780 (bibtex-autokey-additional-names " et al.")
10781 (bibtex-autokey-year-length 4)
10782 (bibtex-autokey-name-year-separator " ")
10783 (bibtex-autokey-titlewords 3)
10784 (bibtex-autokey-titleword-separator " ")
10785 (bibtex-autokey-titleword-case-convert-function 'identity)
10786 (bibtex-autokey-titleword-length 'infty)
10787 (bibtex-autokey-year-title-separator ": "))
10788 (setq description (bibtex-generate-autokey)))
10789 ;; Now parse the entry, get the key and return it.
10790 (save-excursion
10791 (bibtex-beginning-of-entry)
10792 (cdr (assoc "=key=" (bibtex-parse-entry))))))
10794 (defun org-execute-file-search-in-bibtex (s)
10795 "Find the link search string S as a key for a database entry."
10796 (when (eq major-mode 'bibtex-mode)
10797 ;; Yes, we want to do the search in this file.
10798 ;; We construct a regexp that searches for "@entrytype{" followed by the key
10799 (goto-char (point-min))
10800 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
10801 (regexp-quote s) "[ \t\n]*,") nil t)
10802 (goto-char (match-beginning 0)))
10803 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
10804 ;; Use double prefix to indicate that any web link should be browsed
10805 (let ((b (current-buffer)) (p (point)))
10806 ;; Restore the window configuration because we just use the web link
10807 (set-window-configuration org-window-config-before-follow-link)
10808 (save-excursion (set-buffer b) (goto-char p)
10809 (bibtex-url)))
10810 (recenter 0)) ; Move entry start to beginning of window
10811 ;; return t to indicate that the search is done.
10814 ;; Finally add the functions to the right hooks.
10815 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
10816 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
10818 ;; end of Bibtex link setup
10820 ;;; Following file links
10822 (defun org-open-file (path &optional in-emacs line search)
10823 "Open the file at PATH.
10824 First, this expands any special file name abbreviations. Then the
10825 configuration variable `org-file-apps' is checked if it contains an
10826 entry for this file type, and if yes, the corresponding command is launched.
10827 If no application is found, Emacs simply visits the file.
10828 With optional argument IN-EMACS, Emacs will visit the file.
10829 Optional LINE specifies a line to go to, optional SEARCH a string to
10830 search for. If LINE or SEARCH is given, the file will always be
10831 opened in Emacs.
10832 If the file does not exist, an error is thrown."
10833 (setq in-emacs (or in-emacs line search))
10834 (let* ((file (if (equal path "")
10835 buffer-file-name
10836 (substitute-in-file-name (expand-file-name path))))
10837 (apps (append org-file-apps (org-default-apps)))
10838 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10839 (dirp (if remp nil (file-directory-p file)))
10840 (dfile (downcase file))
10841 (old-buffer (current-buffer))
10842 (old-pos (point))
10843 (old-mode major-mode)
10844 ext cmd)
10845 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10846 (setq ext (match-string 1 dfile))
10847 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10848 (setq ext (match-string 1 dfile))))
10849 (if in-emacs
10850 (setq cmd 'emacs)
10851 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10852 (and dirp (cdr (assoc 'directory apps)))
10853 (cdr (assoc ext apps))
10854 (cdr (assoc t apps)))))
10855 (when (eq cmd 'mailcap)
10856 (require 'mailcap)
10857 (mailcap-parse-mailcaps)
10858 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10859 (command (mailcap-mime-info mime-type)))
10860 (if (stringp command)
10861 (setq cmd command)
10862 (setq cmd 'emacs))))
10863 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10864 (not (file-exists-p file))
10865 (not org-open-non-existing-files))
10866 (error "No such file: %s" file))
10867 (cond
10868 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10869 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10870 (if (string-match "['\"]%s['\"]" cmd)
10871 (setq cmd (replace-match "%s" t t cmd)))
10872 (setq cmd (format cmd (shell-quote-argument file)))
10873 (save-window-excursion
10874 (shell-command (concat cmd " &"))))
10875 ((or (stringp cmd)
10876 (eq cmd 'emacs))
10877 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10878 (if line (goto-line line)
10879 (if search (org-link-search search))))
10880 ((consp cmd)
10881 (eval cmd))
10882 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10883 (and (org-mode-p) (eq old-mode 'org-mode)
10884 (or (not (equal old-buffer (current-buffer)))
10885 (not (equal old-pos (point))))
10886 (org-mark-ring-push old-pos old-buffer))))
10888 (defun org-default-apps ()
10889 "Return the default applications for this operating system."
10890 (cond
10891 ((eq system-type 'darwin)
10892 org-file-apps-defaults-macosx)
10893 ((eq system-type 'windows-nt)
10894 org-file-apps-defaults-windowsnt)
10895 (t org-file-apps-defaults-gnu)))
10897 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10898 (defun org-file-remote-p (file)
10899 "Test whether FILE specifies a location on a remote system.
10900 Return non-nil if the location is indeed remote.
10902 For example, the filename \"/user@host:/foo\" specifies a location
10903 on the system \"/user@host:\"."
10904 (cond ((fboundp 'file-remote-p)
10905 (file-remote-p file))
10906 ((fboundp 'tramp-handle-file-remote-p)
10907 (tramp-handle-file-remote-p file))
10908 ((and (boundp 'ange-ftp-name-format)
10909 (string-match (car ange-ftp-name-format) file))
10911 (t nil)))
10914 ;;;; Hooks for remember.el
10916 ;;;###autoload
10917 (defun org-remember-annotation ()
10918 "Return a link to the current location as an annotation for remember.el.
10919 If you are using Org-mode files as target for data storage with
10920 remember.el, then the annotations should include a link compatible with the
10921 conventions in Org-mode. This function returns such a link."
10922 (org-store-link nil))
10924 (defconst org-remember-help
10925 "Select a destination location for the note.
10926 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10927 RET at beg-of-buf -> Append to file as level 2 headline
10928 RET on headline -> Store as sublevel entry to current headline
10929 <left>/<right> -> before/after current headline, same headings level")
10931 ;;;###autoload
10932 (defun org-remember-apply-template (&optional use-char skip-interactive)
10933 "Initialize *remember* buffer with template, invoke `org-mode'.
10934 This function should be placed into `remember-mode-hook' and in fact requires
10935 to be run from that hook to fucntion properly."
10936 (if org-remember-templates
10938 (let* ((char (or use-char
10939 (if (= (length org-remember-templates) 1)
10940 (caar org-remember-templates)
10941 (message "Select template: %s"
10942 (mapconcat
10943 (lambda (x) (char-to-string (car x)))
10944 org-remember-templates " "))
10945 (read-char-exclusive))))
10946 (entry (cdr (assoc char org-remember-templates)))
10947 (tpl (car entry))
10948 (plist-p (if org-store-link-plist t nil))
10949 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
10950 (string-match "\\S-" (nth 1 entry)))
10951 (nth 1 entry)
10952 org-default-notes-file))
10953 (headline (nth 2 entry))
10954 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10955 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10956 (v-u (concat "[" (substring v-t 1 -1) "]"))
10957 (v-U (concat "[" (substring v-T 1 -1) "]"))
10958 (v-i initial) ; defined in `remember-mode'
10959 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
10960 (v-n user-full-name)
10961 (org-startup-folded nil)
10962 org-time-was-given x prompt char time)
10963 (setq org-store-link-plist
10964 (append (list :annotation v-a :initial v-i)))
10965 (unless tpl (setq tpl "") (message "No template") (ding))
10966 (erase-buffer)
10967 (insert (substitute-command-keys
10968 (format
10969 "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
10970 ## Target file \"%s\", headline \"%s\"
10971 ## To switch templates, use `\\[org-remember]'.\n\n"
10972 (abbreviate-file-name (or file org-default-notes-file))
10973 (or headline ""))))
10974 (insert tpl) (goto-char (point-min))
10975 ;; Simple %-escapes
10976 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
10977 (when (and initial (equal (match-string 0) "%i"))
10978 (save-match-data
10979 (let* ((lead (buffer-substring
10980 (point-at-bol) (match-beginning 0))))
10981 (setq v-i (mapconcat 'identity
10982 (org-split-string initial "\n")
10983 (concat "\n" lead))))))
10984 (replace-match
10985 (or (eval (intern (concat "v-" (match-string 1)))) "")
10986 t t))
10987 ;; From the property list
10988 (when plist-p
10989 (goto-char (point-min))
10990 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
10991 (and (setq x (plist-get org-store-link-plist
10992 (intern (match-string 1))))
10993 (replace-match x t t))))
10994 ;; Turn on org-mode in the remember buffer, set local variables
10995 (org-mode)
10996 (org-set-local 'org-finish-function 'remember-buffer)
10997 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10998 (org-set-local 'org-default-notes-file file))
10999 (if (and headline (stringp headline) (string-match "\\S-" headline))
11000 (org-set-local 'org-remember-default-headline headline))
11001 ;; Interactive template entries
11002 (goto-char (point-min))
11003 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([uUtT]\\)?" nil t)
11004 (setq char (if (match-end 3) (match-string 3))
11005 prompt (if (match-end 2) (match-string 2)))
11006 (goto-char (match-beginning 0))
11007 (replace-match "")
11008 (if char
11009 (progn
11010 (setq org-time-was-given (equal (upcase char) char))
11011 (setq time (org-read-date (equal (upcase char) "U") t nil
11012 prompt))
11013 (org-insert-time-stamp time org-time-was-given
11014 (member char '("u" "U"))))
11015 (insert (read-string
11016 (if prompt (concat prompt ": ") "Enter string")))))
11017 (goto-char (point-min))
11018 (if (re-search-forward "%\\?" nil t)
11019 (replace-match "")
11020 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
11021 (org-mode)
11022 (org-set-local 'org-finish-function 'remember-buffer)))
11024 ;;;###autoload
11025 (defun org-remember ()
11026 "Call `remember'. If this is already a remember buffer, re-apply template.
11027 If there is an active region, make sure remember uses it as initial content
11028 of the remember buffer."
11029 (interactive)
11030 (if (eq org-finish-function 'remember-buffer)
11031 (progn
11032 (when (< (length org-remember-templates) 2)
11033 (error "No other template available"))
11034 (erase-buffer)
11035 (let ((annotation (plist-get org-store-link-plist :annotation))
11036 (initial (plist-get org-store-link-plist :initial)))
11037 (org-remember-apply-template))
11038 (message "Press C-c C-c to remember data"))
11039 (if (org-region-active-p)
11040 (remember (buffer-substring (point) (mark)))
11041 (call-interactively 'remember))))
11043 ;;;###autoload
11044 (defun org-remember-handler ()
11045 "Store stuff from remember.el into an org file.
11046 First prompts for an org file. If the user just presses return, the value
11047 of `org-default-notes-file' is used.
11048 Then the command offers the headings tree of the selected file in order to
11049 file the text at a specific location.
11050 You can either immediately press RET to get the note appended to the
11051 file, or you can use vertical cursor motion and visibility cycling (TAB) to
11052 find a better place. Then press RET or <left> or <right> in insert the note.
11054 Key Cursor position Note gets inserted
11055 -----------------------------------------------------------------------------
11056 RET buffer-start as level 2 heading at end of file
11057 RET on headline as sublevel of the heading at cursor
11058 RET no heading at cursor position, level taken from context.
11059 Or use prefix arg to specify level manually.
11060 <left> on headline as same level, before current heading
11061 <right> on headline as same level, after current heading
11063 So the fastest way to store the note is to press RET RET to append it to
11064 the default file. This way your current train of thought is not
11065 interrupted, in accordance with the principles of remember.el. But with
11066 little extra effort, you can push it directly to the correct location.
11068 Before being stored away, the function ensures that the text has a
11069 headline, i.e. a first line that starts with a \"*\". If not, a headline
11070 is constructed from the current date and some additional data.
11072 If the variable `org-adapt-indentation' is non-nil, the entire text is
11073 also indented so that it starts in the same column as the headline
11074 \(i.e. after the stars).
11076 See also the variable `org-reverse-note-order'."
11077 (goto-char (point-min))
11078 (while (looking-at "^[ \t]*\n\\|^##.*\n")
11079 (replace-match ""))
11080 (catch 'quit
11081 (let* ((txt (buffer-substring (point-min) (point-max)))
11082 (fastp (equal current-prefix-arg '(4)))
11083 (file (if fastp org-default-notes-file (org-get-org-file)))
11084 (heading org-remember-default-headline)
11085 (visiting (org-find-base-buffer-visiting file))
11086 (org-startup-folded nil)
11087 (org-startup-align-all-tables nil)
11088 (org-goto-start-pos 1)
11089 spos level indent reversed)
11090 (setq current-prefix-arg nil)
11091 ;; Modify text so that it becomes a nice subtree which can be inserted
11092 ;; into an org tree.
11093 (let* ((lines (split-string txt "\n"))
11094 first)
11095 (setq first (car lines) lines (cdr lines))
11096 (if (string-match "^\\*+" first)
11097 ;; Is already a headline
11098 (setq indent nil)
11099 ;; We need to add a headline: Use time and first buffer line
11100 (setq lines (cons first lines)
11101 first (concat "* " (current-time-string)
11102 " (" (remember-buffer-desc) ")")
11103 indent " "))
11104 (if (and org-adapt-indentation indent)
11105 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
11106 (setq txt (concat first "\n"
11107 (mapconcat 'identity lines "\n"))))
11108 ;; Find the file
11109 (if (not visiting) (find-file-noselect file))
11110 (with-current-buffer (or visiting (get-file-buffer file))
11111 (save-excursion (and (goto-char (point-min))
11112 (not (re-search-forward "^\\* " nil t))
11113 (insert "\n* Notes\n")))
11114 (setq reversed (org-notes-order-reversed-p))
11115 (save-excursion
11116 (save-restriction
11117 (widen)
11119 ;; Find the default location
11120 (when (and heading (stringp heading) (string-match "\\S-" heading))
11121 (goto-char (point-min))
11122 (if (re-search-forward
11123 (concat "^\\*+[ \t]+" (regexp-quote heading)
11124 "\\([ \t]+:[@a-zA-Z0-9_:]*\\)?[ \t]*$")
11125 nil t)
11126 (setq org-goto-start-pos (match-beginning 0))))
11128 ;; Ask the User for a location
11129 (setq spos (if fastp
11130 org-goto-start-pos
11131 (org-get-location (current-buffer) org-remember-help)))
11132 (if (not spos) (throw 'quit nil)) ; return nil to show we did
11133 ; not handle this note
11134 (goto-char spos)
11135 (cond ((and (bobp) (not reversed))
11136 ;; Put it at the end, one level below level 1
11137 (save-restriction
11138 (widen)
11139 (goto-char (point-max))
11140 (if (not (bolp)) (newline))
11141 (org-paste-subtree (org-get-legal-level 1 1) txt)))
11142 ((and (bobp) reversed)
11143 ;; Put it at the start, as level 1
11144 (save-restriction
11145 (widen)
11146 (goto-char (point-min))
11147 (re-search-forward "^\\*" nil t)
11148 (beginning-of-line 1)
11149 (org-paste-subtree 1 txt)))
11150 ((and (org-on-heading-p nil) (not current-prefix-arg))
11151 ;; Put it below this entry, at the beg/end of the subtree
11152 (org-back-to-heading t)
11153 (setq level (funcall outline-level))
11154 (if reversed
11155 (outline-end-of-heading)
11156 (org-end-of-subtree t))
11157 (if (not (bolp)) (newline))
11158 (beginning-of-line 1)
11159 (org-paste-subtree (org-get-legal-level level 1) txt))
11161 ;; Put it right there, with automatic level determined by
11162 ;; org-paste-subtree or from prefix arg
11163 (org-paste-subtree
11164 (if (numberp current-prefix-arg) current-prefix-arg)
11165 txt)))
11166 (when remember-save-after-remembering
11167 (save-buffer)
11168 (if (not visiting) (kill-buffer (current-buffer)))))))))
11169 t) ;; return t to indicate that we took care of this note.
11171 (defun org-get-org-file ()
11172 "Read a filename, with default directory `org-directory'."
11173 (let ((default (or org-default-notes-file remember-data-file)))
11174 (read-file-name (format "File name [%s]: " default)
11175 (file-name-as-directory org-directory)
11176 default)))
11178 (defun org-notes-order-reversed-p ()
11179 "Check if the current file should receive notes in reversed order."
11180 (cond
11181 ((not org-reverse-note-order) nil)
11182 ((eq t org-reverse-note-order) t)
11183 ((not (listp org-reverse-note-order)) nil)
11184 (t (catch 'exit
11185 (let ((all org-reverse-note-order)
11186 entry)
11187 (while (setq entry (pop all))
11188 (if (string-match (car entry) buffer-file-name)
11189 (throw 'exit (cdr entry))))
11190 nil)))))
11192 ;;;; Dynamic blocks
11194 (defun org-find-dblock (name)
11195 "Find the first dynamic block with name NAME in the buffer.
11196 If not found, stay at current position and return nil."
11197 (let (pos)
11198 (save-excursion
11199 (goto-char (point-min))
11200 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
11201 nil t)
11202 (match-beginning 0))))
11203 (if pos (goto-char pos))
11204 pos))
11206 (defconst org-dblock-start-re
11207 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11208 "Matches the startline of a dynamic block, with parameters.")
11210 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
11211 "Matches the end of a dyhamic block.")
11213 (defun org-create-dblock (plist)
11214 "Create a dynamic block section, with parameters taken from PLIST.
11215 PLIST must containe a :name entry which is used as name of the block."
11216 (unless (bolp) (newline))
11217 (let ((name (plist-get plist :name)))
11218 (insert "#+BEGIN: " name)
11219 (while plist
11220 (if (eq (car plist) :name)
11221 (setq plist (cddr plist))
11222 (insert " " (prin1-to-string (pop plist)))))
11223 (insert "\n\n#+END:\n")
11224 (beginning-of-line -2)))
11226 (defun org-prepare-dblock ()
11227 "Prepare dynamic block for refresh.
11228 This empties the block, puts the cursor at the insert position and returns
11229 the property list including an extra property :name with the block name."
11230 (unless (looking-at org-dblock-start-re)
11231 (error "Not at a dynamic block"))
11232 (let* ((begdel (1+ (match-end 0)))
11233 (name (match-string 1))
11234 (params (append (list :name name)
11235 (read (concat "(" (match-string 3) ")")))))
11236 (unless (re-search-forward org-dblock-end-re nil t)
11237 (error "Dynamic block not terminated"))
11238 (delete-region begdel (match-beginning 0))
11239 (goto-char begdel)
11240 (open-line 1)
11241 params))
11243 (defun org-map-dblocks (&optional command)
11244 "Apply COMMAND to all dynamic blocks in the current buffer.
11245 If COMMAND is not given, use `org-update-dblock'."
11246 (let ((cmd (or command 'org-update-dblock))
11247 pos)
11248 (save-excursion
11249 (goto-char (point-min))
11250 (while (re-search-forward org-dblock-start-re nil t)
11251 (goto-char (setq pos (match-beginning 0)))
11252 (condition-case nil
11253 (funcall cmd)
11254 (error (message "Error during update of dynamic block")))
11255 (goto-char pos)
11256 (unless (re-search-forward org-dblock-end-re nil t)
11257 (error "Dynamic block not terminated"))))))
11259 (defun org-dblock-update (&optional arg)
11260 "User command for updating dynamic blocks.
11261 Update the dynamic block at point. With prefix ARG, update all dynamic
11262 blocks in the buffer."
11263 (interactive "P")
11264 (if arg
11265 (org-update-all-dblocks)
11266 (or (looking-at org-dblock-start-re)
11267 (org-beginning-of-dblock))
11268 (org-update-dblock)))
11270 (defun org-update-dblock ()
11271 "Update the dynamic block at point
11272 This means to empty the block, parse for parameters and then call
11273 the correct writing function."
11274 (let* ((pos (point))
11275 (params (org-prepare-dblock))
11276 (name (plist-get params :name))
11277 (cmd (intern (concat "org-dblock-write:" name))))
11278 (funcall cmd params)
11279 (goto-char pos)))
11281 (defun org-beginning-of-dblock ()
11282 "Find the beginning of the dynamic block at point.
11283 Error if there is no scuh block at point."
11284 (let ((pos (point))
11285 beg)
11286 (end-of-line 1)
11287 (if (and (re-search-backward org-dblock-start-re nil t)
11288 (setq beg (match-beginning 0))
11289 (re-search-forward org-dblock-end-re nil t)
11290 (> (match-end 0) pos))
11291 (goto-char beg)
11292 (goto-char pos)
11293 (error "Not in a dynamic block"))))
11295 (defun org-update-all-dblocks ()
11296 "Update all dynamic blocks in the buffer.
11297 This function can be used in a hook."
11298 (when (org-mode-p)
11299 (org-map-dblocks 'org-update-dblock)))
11302 ;;;; Completion
11304 (defun org-complete (&optional arg)
11305 "Perform completion on word at point.
11306 At the beginning of a headline, this completes TODO keywords as given in
11307 `org-todo-keywords'.
11308 If the current word is preceded by a backslash, completes the TeX symbols
11309 that are supported for HTML support.
11310 If the current word is preceded by \"#+\", completes special words for
11311 setting file options.
11312 In the line after \"#+STARTUP:, complete valid keywords.\"
11313 At all other locations, this simply calls `ispell-complete-word'."
11314 (interactive "P")
11315 (catch 'exit
11316 (let* ((end (point))
11317 (beg1 (save-excursion
11318 (skip-chars-backward "a-zA-Z_@0-9")
11319 (point)))
11320 (beg (save-excursion
11321 (skip-chars-backward "a-zA-Z0-9_:$")
11322 (point)))
11323 (confirm (lambda (x) (stringp (car x))))
11324 (searchhead (equal (char-before beg) ?*))
11325 (tag (equal (char-before beg1) ?:))
11326 (texp (equal (char-before beg) ?\\))
11327 (link (equal (char-before beg) ?\[))
11328 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
11329 beg)
11330 "#+"))
11331 (startup (string-match "^#\\+STARTUP:.*"
11332 (buffer-substring (point-at-bol) (point))))
11333 (completion-ignore-case opt)
11334 (type nil)
11335 (tbl nil)
11336 (table (cond
11337 (opt
11338 (setq type :opt)
11339 (mapcar (lambda (x)
11340 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
11341 (cons (match-string 2 x) (match-string 1 x)))
11342 (org-split-string (org-get-current-options) "\n")))
11343 (startup
11344 (setq type :startup)
11345 org-startup-options)
11346 (link (append org-link-abbrev-alist-local
11347 org-link-abbrev-alist))
11348 (texp
11349 (setq type :tex)
11350 org-html-entities)
11351 ((string-match "\\`\\*+[ \t]*\\'"
11352 (buffer-substring (point-at-bol) beg))
11353 (setq type :todo)
11354 (mapcar 'list org-todo-keywords-1))
11355 (searchhead
11356 (setq type :searchhead)
11357 (save-excursion
11358 (goto-char (point-min))
11359 (while (re-search-forward org-todo-line-regexp nil t)
11360 (push (list
11361 (org-make-org-heading-search-string
11362 (match-string 3) t))
11363 tbl)))
11364 tbl)
11365 (tag (setq type :tag beg beg1)
11366 (or org-tag-alist (org-get-buffer-tags)))
11367 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
11368 (pattern (buffer-substring-no-properties beg end))
11369 (completion (try-completion pattern table confirm)))
11370 (cond ((eq completion t)
11371 (if (equal type :opt)
11372 (insert (substring (cdr (assoc (upcase pattern) table))
11373 (length pattern)))
11374 (if (equal type :tag) (insert ":"))))
11375 ((null completion)
11376 (message "Can't find completion for \"%s\"" pattern)
11377 (ding))
11378 ((not (string= pattern completion))
11379 (delete-region beg end)
11380 (if (string-match " +$" completion)
11381 (setq completion (replace-match "" t t completion)))
11382 (insert completion)
11383 (if (get-buffer-window "*Completions*")
11384 (delete-window (get-buffer-window "*Completions*")))
11385 (if (assoc completion table)
11386 (if (eq type :todo) (insert " ")
11387 (if (eq type :tag) (insert ":"))))
11388 (if (and (equal type :opt) (assoc completion table))
11389 (message "%s" (substitute-command-keys
11390 "Press \\[org-complete] again to insert example settings"))))
11392 (message "Making completion list...")
11393 (let ((list (sort (all-completions pattern table confirm)
11394 'string<)))
11395 (with-output-to-temp-buffer "*Completions*"
11396 (condition-case nil
11397 ;; Protection needed for XEmacs and emacs 21
11398 (display-completion-list list pattern)
11399 (error (display-completion-list list)))))
11400 (message "Making completion list...%s" "done"))))))
11402 ;;;; TODO, DEADLINE, Comments
11404 (defun org-toggle-comment ()
11405 "Change the COMMENT state of an entry."
11406 (interactive)
11407 (save-excursion
11408 (org-back-to-heading)
11409 (if (looking-at (concat outline-regexp
11410 "\\( +\\<" org-comment-string "\\>\\)"))
11411 (replace-match "" t t nil 1)
11412 (if (looking-at outline-regexp)
11413 (progn
11414 (goto-char (match-end 0))
11415 (insert " " org-comment-string))))))
11417 (defvar org-last-todo-state-is-todo nil
11418 "This is non-nil when the last TODO state change led to a TODO state.
11419 If the last change removed the TODO tag or switched to DONE, then
11420 this is nil.")
11422 (defun org-todo (&optional arg)
11423 "Change the TODO state of an item.
11424 The state of an item is given by a keyword at the start of the heading,
11425 like
11426 *** TODO Write paper
11427 *** DONE Call mom
11429 The different keywords are specified in the variable `org-todo-keywords'.
11430 By default the available states are \"TODO\" and \"DONE\".
11431 So for this example: when the item starts with TODO, it is changed to DONE.
11432 When it starts with DONE, the DONE is removed. And when neither TODO nor
11433 DONE are present, add TODO at the beginning of the heading.
11435 With C-u prefix arg, use completion to determine the new state.
11436 With numeric prefix arg, switch to that state.
11438 For calling through lisp, arg is also interpreted in the following way:
11439 'none -> empty state
11440 \"\"(empty string) -> switch to empty state
11441 'done -> switch to DONE
11442 'nextset -> switch to the next set of keywords
11443 'previousset -> switch to the previous set of keywords
11444 \"WAITING\" -> switch to the specified keyword, but only if it
11445 really is a member of `org-todo-keywords'."
11446 (interactive "P")
11447 (save-excursion
11448 (org-back-to-heading)
11449 (if (looking-at outline-regexp) (goto-char (match-end 0)))
11450 (or (looking-at (concat " +" org-todo-regexp " *"))
11451 (looking-at " *"))
11452 (let* ((this (match-string 1))
11453 (head (org-get-todo-sequence-head this))
11454 (ass (assoc head org-todo-kwd-alist))
11455 (interpret (nth 1 ass))
11456 (done-word (nth 3 ass))
11457 (final-done-word (nth 4 ass))
11458 (last-state (or this ""))
11459 (completion-ignore-case t)
11460 (member (member this org-todo-keywords-1))
11461 (tail (cdr member))
11462 (state (cond
11463 ((equal arg '(4))
11464 ;; Read a state with completion
11465 (completing-read "State: " (mapcar (lambda(x) (list x))
11466 org-todo-keywords-1)
11467 nil t))
11468 ((eq arg 'right)
11469 (if this
11470 (if tail (car tail) nil)
11471 (car org-todo-keywords-1)))
11472 ((eq arg 'left)
11473 (if (equal member org-todo-keywords-1)
11475 (if this
11476 (nth (- (length org-todo-keywords-1) (length tail) 2)
11477 org-todo-keywords-1)
11478 (org-last org-todo-keywords-1))))
11479 (arg
11480 ;; user or caller requests a specific state
11481 (cond
11482 ((equal arg "") nil)
11483 ((eq arg 'none) nil)
11484 ((eq arg 'done) (or done-word (car org-done-keywords)))
11485 ((eq arg 'nextset)
11486 (or (car (cdr (member head org-todo-heads)))
11487 (car org-todo-heads)))
11488 ((eq arg 'previousset)
11489 (let ((org-todo-heads (reverse org-todo-heads)))
11490 (or (car (cdr (member head org-todo-heads)))
11491 (car org-todo-heads))))
11492 ((car (member arg org-todo-keywords-1)))
11493 ((nth (1- (prefix-numeric-value arg))
11494 org-todo-keywords-1))))
11495 ((null member) (or head (car org-todo-keywords-1)))
11496 ((equal this final-done-word) nil) ;; -> make empty
11497 ((null tail) nil) ;; -> first entry
11498 ((eq interpret 'sequence)
11499 (car tail))
11500 ((memq interpret '(type priority))
11501 (if (eq this-command last-command)
11502 (car tail)
11503 (if (> (length tail) 0)
11504 (or done-word (car org-done-keywords))
11505 nil)))
11506 (t nil)))
11507 (next (if state (concat " " state " ") " "))
11508 dostates)
11509 (replace-match next t t)
11510 (when (memq arg '(nextset previousset))
11511 (message "Keyword set: %s"
11512 (mapconcat 'identity (assoc state org-todo-sets) " ")))
11513 (setq org-last-todo-state-is-todo
11514 (not (member state org-done-keywords)))
11515 (when (and org-log-done (not (memq arg '(nextset previousset))))
11516 (setq dostates (and (eq interpret 'sequence)
11517 (listp org-log-done) (memq 'state org-log-done)))
11518 (cond
11519 ((and state (not this))
11520 (org-add-planning-info nil nil 'closed)
11521 (and dostates (org-add-log-maybe 'state state 'findpos)))
11522 ((and state dostates)
11523 (org-add-log-maybe 'state state 'findpos))
11524 ((member state org-done-keywords)
11525 ;; Planning info calls the note-setting command.
11526 (org-add-planning-info 'closed (org-current-time)
11527 (if (org-get-repeat) nil 'scheduled))
11528 (org-add-log-maybe 'done state 'findpos))))
11529 ;; Fixup tag positioning
11530 (and org-auto-align-tags (org-set-tags nil t))
11531 (run-hooks 'org-after-todo-state-change-hook)
11532 (and (member state org-done-keywords) (org-auto-repeat-maybe))
11533 (if (and arg (not (member state org-done-keywords)))
11534 (setq head (org-get-todo-sequence-head state)))
11535 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
11536 ;; Fixup cursor location if close to the keyword
11537 (if (and (outline-on-heading-p)
11538 (not (bolp))
11539 (save-excursion (beginning-of-line 1)
11540 (looking-at org-todo-line-regexp))
11541 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11542 (progn
11543 (goto-char (or (match-end 2) (match-end 1)))
11544 (just-one-space))))
11546 (defun org-get-todo-sequence-head (kwd)
11547 "Return the head of the TODO sequence to which KWD belongs.
11548 If KWD is not set, check if there is a text property remembering the
11549 right sequence."
11550 (let (p)
11551 (cond
11552 ((not kwd)
11553 (or (get-text-property (point-at-bol) 'org-todo-head)
11554 (progn
11555 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
11556 nil (point-at-eol)))
11557 (get-text-property p 'org-todo-head))))
11558 ((not (member kwd org-todo-keywords-1))
11559 (car org-todo-keywords-1))
11560 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
11562 (defun org-get-repeat ()
11563 "Return the REPEAT statement of this entry."
11564 (save-match-data
11565 (save-excursion
11566 (org-back-to-heading t)
11567 (if (re-search-forward
11568 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
11569 (match-string 1)))))
11571 (defvar org-last-changed-timestamp)
11572 (defvar org-log-post-message)
11573 (defun org-auto-repeat-maybe ()
11574 "Check if the current headline contains a REPEAT key.
11575 If yes, set TODO state back to what it was and change any SCHEDULED
11576 or DEADLINE times the new date.
11577 This function should be run in the `org-after-todo-state-change-hook'."
11578 ;; last-state is dynamically scoped into this function
11579 (let* ((repeat (org-get-repeat))
11580 (aa (assoc last-state org-todo-kwd-alist))
11581 (interpret (nth 1 aa))
11582 (head (nth 2 aa))
11583 (done-word (nth 3 aa))
11584 (whata '(("d" . day) ("m" . month) ("y" . year)))
11585 (msg "Entry repeats: ")
11586 (org-log-done)
11587 re type n what start)
11588 (when repeat
11589 (org-todo (if (eq interpret 'type) last-state head))
11590 (when (and org-log-repeat
11591 (not (memq 'org-add-log-note
11592 (default-value 'post-command-hook))))
11593 ;; Make sure a note is taken
11594 (let ((org-log-done '(done)))
11595 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
11596 'findpos)))
11597 (org-back-to-heading t)
11598 (org-add-planning-info nil nil 'closed)
11599 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11600 org-deadline-time-regexp "\\)"))
11601 (while (re-search-forward
11602 re (save-excursion (outline-next-heading) (point)) t)
11603 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
11604 start 0)
11605 (while (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" repeat start)
11606 (setq start (match-end 0)
11607 n (string-to-number (match-string 1 repeat))
11608 what (match-string 2 repeat))
11609 (if (equal what "w") (setq n (* n 7) what "d"))
11610 (org-timestamp-change n (cdr (assoc what whata))))
11611 (setq msg (concat msg type org-last-changed-timestamp " ")))
11612 (setq org-log-post-message msg)
11613 (message msg))))
11615 (defun org-show-todo-tree (arg)
11616 "Make a compact tree which shows all headlines marked with TODO.
11617 The tree will show the lines where the regexp matches, and all higher
11618 headlines above the match.
11619 With \\[universal-argument] prefix, also show the DONE entries.
11620 With a numeric prefix N, construct a sparse tree for the Nth element
11621 of `org-todo-keywords-1'."
11622 (interactive "P")
11623 (let ((case-fold-search nil)
11624 (kwd-re
11625 (cond ((null arg) org-not-done-regexp)
11626 ((equal arg '(4))
11627 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
11628 (mapcar 'list org-todo-keywords-1))))
11629 (concat "\\("
11630 (mapconcat 'identity (org-split-string kwd "|") "\\|")
11631 "\\)\\>")))
11632 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
11633 (regexp-quote (nth (1- (prefix-numeric-value arg))
11634 org-todo-keywords-1)))
11635 (t (error "Invalid prefix argument: %s" arg)))))
11636 (message "%d TODO entries found"
11637 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
11639 (defun org-deadline ()
11640 "Insert the DEADLINE: string to make a deadline.
11641 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11642 to modify it to the correct date."
11643 (interactive)
11644 (org-add-planning-info 'deadline nil 'closed))
11646 (defun org-schedule ()
11647 "Insert the SCHEDULED: string to schedule a TODO item.
11648 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
11649 to modify it to the correct date."
11650 (interactive)
11651 (org-add-planning-info 'scheduled nil 'closed))
11653 (defun org-add-planning-info (what &optional time &rest remove)
11654 "Insert new timestamp with keyword in the line directly after the headline.
11655 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11656 If non is given, the user is prompted for a date.
11657 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11658 be removed."
11659 (interactive)
11660 (let (org-time-was-given)
11661 (when what (setq time (or time (org-read-date nil 'to-time))))
11662 (when (and org-insert-labeled-timestamps-at-point
11663 (member what '(scheduled deadline)))
11664 (insert
11665 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11666 (org-insert-time-stamp time org-time-was-given)
11667 (setq what nil))
11668 (save-excursion
11669 (save-restriction
11670 (let (col list elt ts buffer-invisibility-spec)
11671 (org-back-to-heading t)
11672 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11673 (goto-char (match-end 1))
11674 (setq col (current-column))
11675 (goto-char (1+ (match-end 0)))
11676 (if (and (not (looking-at outline-regexp))
11677 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11678 "[^\r\n]*"))
11679 (not (equal (match-string 1) org-clock-string)))
11680 (narrow-to-region (match-beginning 0) (match-end 0))
11681 (insert "\n")
11682 (backward-char 1)
11683 (narrow-to-region (point) (point))
11684 (indent-to-column col))
11685 ;; Check if we have to remove something.
11686 (setq list (cons what remove))
11687 (while list
11688 (setq elt (pop list))
11689 (goto-char (point-min))
11690 (when (or (and (eq elt 'scheduled)
11691 (re-search-forward org-scheduled-time-regexp nil t))
11692 (and (eq elt 'deadline)
11693 (re-search-forward org-deadline-time-regexp nil t))
11694 (and (eq elt 'closed)
11695 (re-search-forward org-closed-time-regexp nil t)))
11696 (replace-match "")
11697 (if (looking-at "--+<[^>]+>") (replace-match ""))
11698 (if (looking-at " +") (replace-match ""))))
11699 (goto-char (point-max))
11700 (when what
11701 (insert
11702 (if (not (equal (char-before) ?\ )) " " "")
11703 (cond ((eq what 'scheduled) org-scheduled-string)
11704 ((eq what 'deadline) org-deadline-string)
11705 ((eq what 'closed) org-closed-string))
11706 " ")
11707 (org-insert-time-stamp time
11708 (or org-time-was-given (eq what 'closed))
11709 (eq what 'closed))
11710 (end-of-line 1))
11711 (goto-char (point-min))
11712 (widen)
11713 (if (looking-at "[ \t]+\r?\n")
11714 (replace-match ""))
11715 ts)))))
11717 (defvar org-log-note-marker (make-marker))
11718 (defvar org-log-note-purpose nil)
11719 (defvar org-log-note-state nil)
11720 (defvar org-log-note-window-configuration nil)
11721 (defvar org-log-note-return-to (make-marker))
11722 (defvar org-log-post-message nil
11723 "Message to be displayed after a log note has been stored.
11724 The auto-repeater uses this.")
11726 (defun org-add-log-maybe (&optional purpose state findpos)
11727 (save-excursion
11728 (when (and (listp org-log-done)
11729 (memq purpose org-log-done))
11730 (when findpos
11731 (org-back-to-heading t)
11732 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11733 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11734 "[^\r\n]*\\)?"))
11735 (goto-char (match-end 0)))
11736 (move-marker org-log-note-marker (point))
11737 (setq org-log-note-purpose purpose)
11738 (setq org-log-note-state state)
11739 (add-hook 'post-command-hook 'org-add-log-note 'append))))
11741 (defun org-add-log-note (&optional purpose)
11742 "Pop up a window for taking a note, and add this note later at point."
11743 (remove-hook 'post-command-hook 'org-add-log-note)
11744 (setq org-log-note-window-configuration (current-window-configuration))
11745 (delete-other-windows)
11746 (move-marker org-log-note-return-to (point))
11747 (switch-to-buffer (marker-buffer org-log-note-marker))
11748 (goto-char org-log-note-marker)
11749 (switch-to-buffer-other-window "*Org Note*")
11750 (erase-buffer)
11751 (let ((org-inhibit-startup t)) (org-mode))
11752 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
11753 (cond
11754 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11755 ((eq org-log-note-purpose 'done) "closed todo item")
11756 ((eq org-log-note-purpose 'state) "state change")
11757 (t (error "This should not happen")))))
11758 (org-set-local 'org-finish-function 'org-store-log-note))
11760 (defun org-store-log-note ()
11761 "Finish taking a log note, and insert it to where it belongs."
11762 (let ((txt (buffer-string))
11763 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11764 lines ind)
11765 (kill-buffer (current-buffer))
11766 (if (string-match "^#.*\n[ \t\n]*" txt)
11767 (setq txt (replace-match "" t t txt)))
11768 (if (string-match "\\s-+\\'" txt)
11769 (setq txt (replace-match "" t t txt)))
11770 (setq lines (org-split-string txt "\n"))
11771 (when (and note (string-match "\\S-" note))
11772 (setq note
11773 (org-replace-escapes
11774 note
11775 (list (cons "%u" (user-login-name))
11776 (cons "%U" user-full-name)
11777 (cons "%t" (format-time-string
11778 (org-time-stamp-format 'long 'inactive)
11779 (current-time)))
11780 (cons "%s" (if org-log-note-state
11781 (concat "\"" org-log-note-state "\"")
11782 "")))))
11783 (if lines (setq note (concat note " \\\\")))
11784 (push note lines))
11785 (save-excursion
11786 (set-buffer (marker-buffer org-log-note-marker))
11787 (save-excursion
11788 (goto-char org-log-note-marker)
11789 (move-marker org-log-note-marker nil)
11790 (end-of-line 1)
11791 (if (not (bolp)) (insert "\n")) (indent-relative nil)
11792 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
11793 (insert " - " (pop lines))
11794 (while lines
11795 (insert "\n" ind (pop lines))))))
11796 (set-window-configuration org-log-note-window-configuration)
11797 (with-current-buffer (marker-buffer org-log-note-return-to)
11798 (goto-char org-log-note-return-to))
11799 (move-marker org-log-note-return-to nil)
11800 (and org-log-post-message (message org-log-post-message)))
11802 (defvar org-occur-highlights nil)
11803 (make-variable-buffer-local 'org-occur-highlights)
11805 (defun org-occur (regexp &optional keep-previous callback)
11806 "Make a compact tree which shows all matches of REGEXP.
11807 The tree will show the lines where the regexp matches, and all higher
11808 headlines above the match. It will also show the heading after the match,
11809 to make sure editing the matching entry is easy.
11810 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11811 call to `org-occur' will be kept, to allow stacking of calls to this
11812 command.
11813 If CALLBACK is non-nil, it is a function which is called to confirm
11814 that the match should indeed be shown."
11815 (interactive "sRegexp: \nP")
11816 (or keep-previous (org-remove-occur-highlights nil nil t))
11817 (let ((cnt 0))
11818 (save-excursion
11819 (goto-char (point-min))
11820 (if (or (not keep-previous) ; do not want to keep
11821 (not org-occur-highlights)) ; no previous matches
11822 ;; hide everything
11823 (org-overview))
11824 (while (re-search-forward regexp nil t)
11825 (when (or (not callback)
11826 (save-match-data (funcall callback)))
11827 (setq cnt (1+ cnt))
11828 (org-highlight-new-match (match-beginning 0) (match-end 0))
11829 (org-show-context 'occur-tree))))
11830 (when org-remove-highlights-with-change
11831 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11832 nil 'local))
11833 (unless org-sparse-tree-open-archived-trees
11834 (org-hide-archived-subtrees (point-min) (point-max)))
11835 (run-hooks 'org-occur-hook)
11836 (if (interactive-p)
11837 (message "%d match(es) for regexp %s" cnt regexp))
11838 cnt))
11840 (defun org-show-context (&optional key)
11841 "Make sure point and context and visible.
11842 How much context is shown depends upon the variables
11843 `org-show-hierarchy-above', `org-show-following-heading'. and
11844 `org-show-siblings'."
11845 (let ((heading-p (org-on-heading-p t))
11846 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11847 (following-p (org-get-alist-option org-show-following-heading key))
11848 (siblings-p (org-get-alist-option org-show-siblings key)))
11849 (catch 'exit
11850 ;; Show heading or entry text
11851 (if heading-p
11852 (org-flag-heading nil) ; only show the heading
11853 (and (or (org-invisible-p) (org-invisible-p2))
11854 (org-show-hidden-entry))) ; show entire entry
11855 (when following-p
11856 ;; Show next sibling, or heading below text
11857 (save-excursion
11858 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11859 (org-flag-heading nil))))
11860 (when siblings-p (org-show-siblings))
11861 (when hierarchy-p
11862 ;; show all higher headings, possibly with siblings
11863 (save-excursion
11864 (while (and (condition-case nil
11865 (progn (org-up-heading-all 1) t)
11866 (error nil))
11867 (not (bobp)))
11868 (org-flag-heading nil)
11869 (when siblings-p (org-show-siblings))))))))
11871 (defun org-reveal (&optional siblings)
11872 "Show current entry, hierarchy above it, and the following headline.
11873 This can be used to show a consistent set of context around locations
11874 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11875 not t for the search context.
11877 With optional argument SIBLINGS, on each level of the hierarchy all
11878 siblings are shown. This repairs the tree structure to what it would
11879 look like when opened with hierarchical calls to `org-cycle'."
11880 (interactive "P")
11881 (let ((org-show-hierarchy-above t)
11882 (org-show-following-heading t)
11883 (org-show-siblings (if siblings t org-show-siblings)))
11884 (org-show-context nil)))
11886 (defun org-highlight-new-match (beg end)
11887 "Highlight from BEG to END and mark the highlight is an occur headline."
11888 (let ((ov (org-make-overlay beg end)))
11889 (org-overlay-put ov 'face 'secondary-selection)
11890 (push ov org-occur-highlights)))
11892 (defun org-remove-occur-highlights (&optional beg end noremove)
11893 "Remove the occur highlights from the buffer.
11894 BEG and END are ignored. If NOREMOVE is nil, remove this function
11895 from the `before-change-functions' in the current buffer."
11896 (interactive)
11897 (unless org-inhibit-highlight-removal
11898 (mapc 'org-delete-overlay org-occur-highlights)
11899 (setq org-occur-highlights nil)
11900 (unless noremove
11901 (remove-hook 'before-change-functions
11902 'org-remove-occur-highlights 'local))))
11904 ;;;; Priorities
11906 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
11907 "Regular expression matching the priority indicator.")
11909 (defvar org-remove-priority-next-time nil)
11911 (defun org-priority-up ()
11912 "Increase the priority of the current item."
11913 (interactive)
11914 (org-priority 'up))
11916 (defun org-priority-down ()
11917 "Decrease the priority of the current item."
11918 (interactive)
11919 (org-priority 'down))
11921 (defun org-priority (&optional action)
11922 "Change the priority of an item by ARG.
11923 ACTION can be set, up, or down."
11924 (interactive)
11925 (setq action (or action 'set))
11926 (let (current new news have remove)
11927 (save-excursion
11928 (org-back-to-heading)
11929 (if (looking-at org-priority-regexp)
11930 (setq current (string-to-char (match-string 2))
11931 have t)
11932 (setq current org-default-priority))
11933 (cond
11934 ((eq action 'set)
11935 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
11936 (setq new (read-char-exclusive))
11937 (cond ((equal new ?\ ) (setq remove t))
11938 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
11939 (error "Priority must be between `%c' and `%c'"
11940 ?A org-lowest-priority))))
11941 ((eq action 'up)
11942 (setq new (1- current)))
11943 ((eq action 'down)
11944 (setq new (1+ current)))
11945 (t (error "Invalid action")))
11946 (setq new (min (max ?A (upcase new)) org-lowest-priority))
11947 (setq news (format "%c" new))
11948 (if have
11949 (if remove
11950 (replace-match "" t t nil 1)
11951 (replace-match news t t nil 2))
11952 (if remove
11953 (error "No priority cookie found in line")
11954 (looking-at org-todo-line-regexp)
11955 (if (match-end 2)
11956 (progn
11957 (goto-char (match-end 2))
11958 (insert " [#" news "]"))
11959 (goto-char (match-beginning 3))
11960 (insert "[#" news "] ")))))
11961 (if remove
11962 (message "Priority removed")
11963 (message "Priority of current item set to %s" news))))
11966 (defun org-get-priority (s)
11967 "Find priority cookie and return priority."
11968 (save-match-data
11969 (if (not (string-match org-priority-regexp s))
11970 (* 1000 (- org-lowest-priority org-default-priority))
11971 (* 1000 (- org-lowest-priority
11972 (string-to-char (match-string 2 s)))))))
11974 ;;;; Tags
11976 (defun org-scan-tags (action matcher &optional todo-only)
11977 "Scan headline tags with inheritance and produce output ACTION.
11978 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
11979 evaluated, testing if a given set of tags qualifies a headline for
11980 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
11981 are included in the output."
11982 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
11983 (mapconcat 'regexp-quote
11984 (nreverse (cdr (reverse org-todo-keywords-1)))
11985 "\\|")
11986 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*$"))
11987 (props (list 'face nil
11988 'done-face 'org-done
11989 'undone-face nil
11990 'mouse-face 'highlight
11991 'org-not-done-regexp org-not-done-regexp
11992 'keymap org-agenda-keymap
11993 'help-echo
11994 (format "mouse-2 or RET jump to org file %s"
11995 (abbreviate-file-name buffer-file-name))))
11996 (case-fold-search nil)
11997 lspos
11998 tags tags-list tags-alist (llast 0) rtn level category i txt
11999 todo marker entry priority)
12000 (save-excursion
12001 (goto-char (point-min))
12002 (when (eq action 'sparse-tree) (org-overview))
12003 (while (re-search-forward re nil t)
12004 (catch :skip
12005 (setq todo (if (match-end 1) (match-string 2))
12006 tags (if (match-end 4) (match-string 4)))
12007 (goto-char (setq lspos (1+ (match-beginning 0))))
12008 (setq level (funcall outline-level)
12009 category (org-get-category))
12010 (setq i llast llast level)
12011 ;; remove tag lists from same and sublevels
12012 (while (>= i level)
12013 (when (setq entry (assoc i tags-alist))
12014 (setq tags-alist (delete entry tags-alist)))
12015 (setq i (1- i)))
12016 ;; add the nex tags
12017 (when tags
12018 (setq tags (mapcar 'downcase (org-split-string tags ":"))
12019 tags-alist
12020 (cons (cons level tags) tags-alist)))
12021 ;; compile tags for current headline
12022 (setq tags-list
12023 (if org-use-tag-inheritance
12024 (apply 'append (mapcar 'cdr tags-alist))
12025 tags))
12026 (when (and (or (not todo-only) todo)
12027 (eval matcher)
12028 (or (not org-agenda-skip-archived-trees)
12029 (not (member org-archive-tag tags-list))))
12030 (and (eq action 'agenda) (org-agenda-skip))
12031 ;; list this headline
12032 (if (eq action 'sparse-tree)
12033 (progn
12034 (org-show-context 'tags-tree))
12035 (setq txt (org-format-agenda-item
12037 (concat
12038 (if org-tags-match-list-sublevels
12039 (make-string (1- level) ?.) "")
12040 (org-get-heading))
12041 category tags-list)
12042 priority (org-get-priority txt))
12043 (goto-char lspos)
12044 (setq marker (org-agenda-new-marker))
12045 (org-add-props txt props
12046 'org-marker marker 'org-hd-marker marker 'org-category category
12047 'priority priority)
12048 (push txt rtn))
12049 ;; if we are to skip sublevels, jump to end of subtree
12050 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
12051 (when (and (eq action 'sparse-tree)
12052 (not org-sparse-tree-open-archived-trees))
12053 (org-hide-archived-subtrees (point-min) (point-max)))
12054 (nreverse rtn)))
12056 (defvar todo-only) ;; dynamically scoped
12058 (defun org-tags-sparse-tree (&optional todo-only match)
12059 "Create a sparse tree according to tags string MATCH.
12060 MATCH can contain positive and negative selection of tags, like
12061 \"+WORK+URGENT-WITHBOSS\".
12062 If optional argument TODO_ONLY is non-nil, only select lines that are
12063 also TODO lines."
12064 (interactive "P")
12065 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12067 (defun org-make-tags-matcher (match)
12068 "Create the TAGS//TODO matcher form for the selection string MATCH."
12069 ;; todo-only is scoped dynamically into this function, and the function
12070 ;; may change it it the matcher asksk for it.
12071 (unless match
12072 ;; Get a new match request, with completion
12073 (setq org-last-tags-completion-table
12074 (or org-tag-alist
12075 org-last-tags-completion-table))
12076 (setq match (completing-read
12077 "Match: " 'org-tags-completion-function nil nil nil
12078 'org-tags-history)))
12080 ;; Parse the string and create a lisp form
12081 (let ((match0 match)
12082 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|[A-Za-z_@0-9]+\\)")
12083 minus tag mm
12084 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
12085 orterms term orlist re-p level-p)
12086 (if (string-match "/+" match)
12087 ;; match contains also a todo-matching request
12088 (progn
12089 (setq tagsmatch (substring match 0 (match-beginning 0))
12090 todomatch (substring match (match-end 0)))
12091 (if (string-match "^!" todomatch)
12092 (setq todo-only t todomatch (substring todomatch 1)))
12093 (if (string-match "^\\s-*$" todomatch)
12094 (setq todomatch nil)))
12095 ;; only matching tags
12096 (setq tagsmatch match todomatch nil))
12098 ;; Make the tags matcher
12099 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
12100 (setq tagsmatcher t)
12101 (setq orterms (org-split-string tagsmatch "|") orlist nil)
12102 (while (setq term (pop orterms))
12103 (while (and (equal (substring term -1) "\\") orterms)
12104 (setq term (concat term "|" (pop orterms)))) ; repair bad split
12105 (while (string-match re term)
12106 (setq minus (and (match-end 1)
12107 (equal (match-string 1 term) "-"))
12108 tag (match-string 2 term)
12109 re-p (equal (string-to-char tag) ?{)
12110 level-p (match-end 3)
12111 mm (cond
12112 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
12113 (level-p `(= level ,(string-to-number
12114 (match-string 3 term))))
12115 (t `(member ,(downcase tag) tags-list)))
12116 mm (if minus (list 'not mm) mm)
12117 term (substring term (match-end 0)))
12118 (push mm tagsmatcher))
12119 (push (if (> (length tagsmatcher) 1)
12120 (cons 'and tagsmatcher)
12121 (car tagsmatcher))
12122 orlist)
12123 (setq tagsmatcher nil))
12124 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist))))
12126 ;; Make the todo matcher
12127 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
12128 (setq todomatcher t)
12129 (setq orterms (org-split-string todomatch "|") orlist nil)
12130 (while (setq term (pop orterms))
12131 (while (string-match re term)
12132 (setq minus (and (match-end 1)
12133 (equal (match-string 1 term) "-"))
12134 kwd (match-string 2 term)
12135 re-p (equal (string-to-char kwd) ?{)
12136 term (substring term (match-end 0))
12137 mm (if re-p
12138 `(string-match ,(substring kwd 1 -1) todo)
12139 (list 'equal 'todo kwd))
12140 mm (if minus (list 'not mm) mm))
12141 (push mm todomatcher))
12142 (push (if (> (length todomatcher) 1)
12143 (cons 'and todomatcher)
12144 (car todomatcher))
12145 orlist)
12146 (setq todomatcher nil))
12147 (setq todomatcher (if (> (length orlist) 1)
12148 (cons 'or orlist) (car orlist))))
12150 ;; Return the string and lisp forms of the matcher
12151 (setq matcher (if todomatcher
12152 (list 'and tagsmatcher todomatcher)
12153 tagsmatcher))
12154 (cons match0 matcher)))
12156 (defun org-match-any-p (re list)
12157 "Does re match any element of list?"
12158 (setq list (mapcar (lambda (x) (string-match re x)) list))
12159 (delq nil list))
12161 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
12162 (defvar org-tags-overlay (org-make-overlay 1 1))
12163 (org-detach-overlay org-tags-overlay)
12165 (defun org-set-tags (&optional arg just-align)
12166 "Set the tags for the current headline.
12167 With prefix ARG, realign all tags in headings in the current buffer."
12168 (interactive "P")
12169 (let* ((re (concat "^" outline-regexp))
12170 (current (org-get-tags))
12171 table current-tags inherited-tags ; computed below when needed
12172 tags p0 c0 c1 rpl)
12173 (if arg
12174 (save-excursion
12175 (goto-char (point-min))
12176 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12177 (while (re-search-forward re nil t)
12178 (org-set-tags nil t)
12179 (end-of-line 1)))
12180 (message "All tags realigned to column %d" org-tags-column))
12181 (if just-align
12182 (setq tags current)
12183 ;; Get a new set of tags from the user
12184 (save-excursion
12185 (setq table (or org-tag-alist (org-get-buffer-tags))
12186 org-last-tags-completion-table table
12187 current-tags (org-split-string current ":")
12188 inherited-tags (nreverse
12189 (nthcdr (length current-tags)
12190 (nreverse (org-get-tags-at))))
12191 tags
12192 (if (or (eq t org-use-fast-tag-selection)
12193 (and org-use-fast-tag-selection
12194 (delq nil (mapcar 'cdr table))))
12195 (org-fast-tag-selection current-tags inherited-tags table)
12196 (let ((org-add-colon-after-tag-completion t))
12197 (org-trim
12198 (completing-read "Tags: " 'org-tags-completion-function
12199 nil nil current 'org-tags-history))))))
12200 (while (string-match "[-+&]+" tags)
12201 ;; No boolean logic, just a list
12202 (setq tags (replace-match ":" t t tags))))
12204 (if (string-match "\\`[\t ]*\\'" tags)
12205 (setq tags "")
12206 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12207 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12209 ;; Insert new tags at the correct column
12210 (beginning-of-line 1)
12211 (if (re-search-forward
12212 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12213 (point-at-eol) t)
12214 (progn
12215 (if (equal tags "")
12216 (setq rpl "")
12217 (goto-char (match-beginning 0))
12218 (setq c0 (current-column) p0 (point)
12219 c1 (max (1+ c0) (if (> org-tags-column 0)
12220 org-tags-column
12221 (- (- org-tags-column) (length tags))))
12222 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12223 (replace-match rpl t t)
12224 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
12225 tags)
12226 (error "Tags alignment failed")))))
12228 (defun org-tags-completion-function (string predicate &optional flag)
12229 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12230 (confirm (lambda (x) (stringp (car x)))))
12231 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12232 (setq s1 (match-string 1 string)
12233 s2 (match-string 2 string))
12234 (setq s1 "" s2 string))
12235 (cond
12236 ((eq flag nil)
12237 ;; try completion
12238 (setq rtn (try-completion s2 ctable confirm))
12239 (if (stringp rtn)
12240 (concat s1 s2 (substring rtn (length s2))
12241 (if (and org-add-colon-after-tag-completion
12242 (assoc rtn ctable))
12243 ":" "")))
12245 ((eq flag t)
12246 ;; all-completions
12247 (all-completions s2 ctable confirm)
12249 ((eq flag 'lambda)
12250 ;; exact match?
12251 (assoc s2 ctable)))
12254 (defun org-fast-tag-insert (kwd tags face &optional end)
12255 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
12256 (insert (format "%-12s" (concat kwd ":"))
12257 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12258 (or end "")))
12260 (defun org-fast-tag-show-exit (flag)
12261 (save-excursion
12262 (goto-line 3)
12263 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12264 (replace-match ""))
12265 (when flag
12266 (end-of-line 1)
12267 (move-to-column (- (window-width) 19) t)
12268 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12270 (defun org-set-current-tags-overlay (current prefix)
12271 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12272 (if (featurep 'xemacs)
12273 (org-overlay-display org-tags-overlay (concat prefix s)
12274 'secondary-selection)
12275 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12276 (org-overlay-display org-tags-overlay (concat prefix s)))))
12278 (defun org-fast-tag-selection (current inherited table)
12279 "Fast tag selection with single keys.
12280 CURRENT is the current list of tags in the headline, INHERITED is the
12281 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12282 possibly with grouping information.
12283 If the keys are nil, a-z are automatically assigned.
12284 Returns the new tags string, or nil to not change the current settings."
12285 (let* ((maxlen (apply 'max (mapcar
12286 (lambda (x)
12287 (if (stringp (car x)) (string-width (car x)) 0))
12288 table)))
12289 (buf (current-buffer))
12290 (expert (eq org-fast-tag-selection-single-key 'expert))
12291 (buffer-tags nil)
12292 (fwidth (+ maxlen 3 1 3))
12293 (ncol (/ (- (window-width) 4) fwidth))
12294 (i-face 'org-done)
12295 (c-face 'org-todo)
12296 tg cnt e c char c1 c2 ntable tbl rtn
12297 ov-start ov-end ov-prefix
12298 (exit-after-next org-fast-tag-selection-single-key)
12299 groups ingroup)
12300 (save-excursion
12301 (beginning-of-line 1)
12302 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
12303 (setq ov-start (match-beginning 1)
12304 ov-end (match-end 1)
12305 ov-prefix "")
12306 (setq ov-start (1- (point-at-eol))
12307 ov-end (1+ ov-start))
12308 (skip-chars-forward "^\n\r")
12309 (setq ov-prefix
12310 (concat
12311 (buffer-substring (1- (point)) (point))
12312 (if (> (current-column) org-tags-column)
12314 (make-string (- org-tags-column (current-column)) ?\ ))))))
12315 (org-move-overlay org-tags-overlay ov-start ov-end)
12316 (save-window-excursion
12317 (if expert
12318 (set-buffer (get-buffer-create " *Org tags*"))
12319 (delete-other-windows)
12320 (split-window-vertically)
12321 (switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12322 (erase-buffer)
12323 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12324 (org-fast-tag-insert "Current" current c-face "\n\n")
12325 (org-fast-tag-show-exit exit-after-next)
12326 (org-set-current-tags-overlay current ov-prefix)
12327 (setq tbl table char ?a cnt 0)
12328 (while (setq e (pop tbl))
12329 (cond
12330 ((equal e '(:startgroup))
12331 (push '() groups) (setq ingroup t)
12332 (when (not (= cnt 0))
12333 (setq cnt 0)
12334 (insert "\n"))
12335 (insert "{ "))
12336 ((equal e '(:endgroup))
12337 (setq ingroup nil cnt 0)
12338 (insert "}\n"))
12340 (setq tg (car e) c2 nil)
12341 (if (cdr e)
12342 (setq c (cdr e))
12343 ;; automatically assign a character.
12344 (setq c1 (string-to-char
12345 (downcase (substring
12346 tg (if (= (string-to-char tg) ?@) 1 0)))))
12347 (if (or (rassoc c1 ntable) (rassoc c1 table))
12348 (while (or (rassoc char ntable) (rassoc char table))
12349 (setq char (1+ char)))
12350 (setq c2 c1))
12351 (setq c (or c2 char)))
12352 (if ingroup (push tg (car groups)))
12353 (setq tg (org-add-props tg nil 'face
12354 (cond
12355 ((member tg current) c-face)
12356 ((member tg inherited) i-face)
12357 (t nil))))
12358 (if (and (= cnt 0) (not ingroup)) (insert " "))
12359 (insert "[" c "] " tg (make-string
12360 (- fwidth 4 (length tg)) ?\ ))
12361 (push (cons tg c) ntable)
12362 (when (= (setq cnt (1+ cnt)) ncol)
12363 (insert "\n")
12364 (if ingroup (insert " "))
12365 (setq cnt 0)))))
12366 (setq ntable (nreverse ntable))
12367 (insert "\n")
12368 (goto-char (point-min))
12369 (if (and (not expert) (fboundp 'fit-window-to-buffer))
12370 (fit-window-to-buffer))
12371 (setq rtn
12372 (catch 'exit
12373 (while t
12374 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
12375 (if groups " [!] no groups" " [!]groups")
12376 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12377 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12378 (cond
12379 ((= c ?\r) (throw 'exit t))
12380 ((= c ?!)
12381 (setq groups (not groups))
12382 (goto-char (point-min))
12383 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12384 ((= c ?\C-c)
12385 (if (not expert)
12386 (org-fast-tag-show-exit
12387 (setq exit-after-next (not exit-after-next)))
12388 (setq expert nil)
12389 (delete-other-windows)
12390 (split-window-vertically)
12391 (switch-to-buffer-other-window " *Org tags*")
12392 (and (fboundp 'fit-window-to-buffer)
12393 (fit-window-to-buffer))))
12394 ((or (= c ?\C-g)
12395 (and (= c ?q) (not (rassoc c ntable))))
12396 (org-detach-overlay org-tags-overlay)
12397 (setq quit-flag t))
12398 ((= c ?\ )
12399 (setq current nil)
12400 (if exit-after-next (setq exit-after-next 'now)))
12401 ((= c ?\t)
12402 (condition-case nil
12403 (setq tg (completing-read
12404 "Tag: "
12405 (or buffer-tags
12406 (with-current-buffer buf
12407 (org-get-buffer-tags)))))
12408 (quit (setq tg "")))
12409 (when (string-match "\\S-" tg)
12410 (add-to-list 'buffer-tags (list tg))
12411 (if (member tg current)
12412 (setq current (delete tg current))
12413 (push tg current)))
12414 (if exit-after-next (setq exit-after-next 'now)))
12415 ((setq e (rassoc c ntable) tg (car e))
12416 (if (member tg current)
12417 (setq current (delete tg current))
12418 (loop for g in groups do
12419 (if (member tg g)
12420 (mapcar (lambda (x)
12421 (setq current (delete x current)))
12422 g)))
12423 (push tg current))
12424 (if exit-after-next (setq exit-after-next 'now))))
12426 ;; Create a sorted list
12427 (setq current
12428 (sort current
12429 (lambda (a b)
12430 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12431 (if (eq exit-after-next 'now) (throw 'exit t))
12432 (goto-char (point-min))
12433 (beginning-of-line 2)
12434 (delete-region (point) (point-at-eol))
12435 (org-fast-tag-insert "Current" current c-face)
12436 (org-set-current-tags-overlay current ov-prefix)
12437 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
12438 (setq tg (match-string 1))
12439 (add-text-properties (match-beginning 1) (match-end 1)
12440 (list 'face
12441 (cond
12442 ((member tg current) c-face)
12443 ((member tg inherited) i-face)
12444 (t nil)))))
12445 (goto-char (point-min)))))
12446 (org-detach-overlay org-tags-overlay)
12447 (if rtn
12448 (mapconcat 'identity current ":")
12449 nil))))
12451 (defun org-get-tags ()
12452 "Get the TAGS string in the current headline."
12453 (unless (org-on-heading-p t)
12454 (error "Not on a heading"))
12455 (save-excursion
12456 (beginning-of-line 1)
12457 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
12458 (org-match-string-no-properties 1)
12459 "")))
12461 (defun org-get-buffer-tags ()
12462 "Get a table of all tags used in the buffer, for completion."
12463 (let (tags)
12464 (save-excursion
12465 (goto-char (point-min))
12466 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
12467 (mapc (lambda (x) (add-to-list 'tags x))
12468 (org-split-string (org-match-string-no-properties 1) ":"))))
12469 (mapcar 'list tags)))
12471 ;;;; Timestamps
12473 (defvar org-last-changed-timestamp nil)
12474 (defvar org-time-was-given) ; dynamically scoped parameter
12475 (defvar org-ts-what) ; dynamically scoped parameter
12477 (defun org-time-stamp (arg)
12478 "Prompt for a date/time and insert a time stamp.
12479 If the user specifies a time like HH:MM, or if this command is called
12480 with a prefix argument, the time stamp will contain date and time.
12481 Otherwise, only the date will be included. All parts of a date not
12482 specified by the user will be filled in from the current date/time.
12483 So if you press just return without typing anything, the time stamp
12484 will represent the current date/time. If there is already a timestamp
12485 at the cursor, it will be modified."
12486 (interactive "P")
12487 (let (org-time-was-given time)
12488 (cond
12489 ((and (org-at-timestamp-p)
12490 (eq last-command 'org-time-stamp)
12491 (eq this-command 'org-time-stamp))
12492 (insert "--")
12493 (setq time (let ((this-command this-command))
12494 (org-read-date arg 'totime)))
12495 (org-insert-time-stamp time (or org-time-was-given arg)))
12496 ((org-at-timestamp-p)
12497 (setq time (let ((this-command this-command))
12498 (org-read-date arg 'totime)))
12499 (when (org-at-timestamp-p) ; just to get the match data
12500 (replace-match "")
12501 (setq org-last-changed-timestamp
12502 (org-insert-time-stamp time (or org-time-was-given arg))))
12503 (message "Timestamp updated"))
12505 (setq time (let ((this-command this-command))
12506 (org-read-date arg 'totime)))
12507 (org-insert-time-stamp time (or org-time-was-given arg))))))
12509 (defun org-time-stamp-inactive (&optional arg)
12510 "Insert an inactive time stamp.
12511 An inactive time stamp is enclosed in square brackets instead of angle
12512 brackets. It is inactive in the sense that it does not trigger agenda entries,
12513 does not link to the calendar and cannot be changed with the S-cursor keys.
12514 So these are more for recording a certain time/date."
12515 (interactive "P")
12516 (let (org-time-was-given time)
12517 (setq time (org-read-date arg 'totime))
12518 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive)))
12520 (defvar org-date-ovl (org-make-overlay 1 1))
12521 (org-overlay-put org-date-ovl 'face 'org-warning)
12522 (org-detach-overlay org-date-ovl)
12524 (defvar org-ans1) ; dynamically scoped parameter
12525 (defvar org-ans2) ; dynamically scoped parameter
12527 (defun org-read-date (&optional with-time to-time from-string prompt)
12528 "Read a date and make things smooth for the user.
12529 The prompt will suggest to enter an ISO date, but you can also enter anything
12530 which will at least partially be understood by `parse-time-string'.
12531 Unrecognized parts of the date will default to the current day, month, year,
12532 hour and minute. For example,
12533 3-2-5 --> 2003-02-05
12534 feb 15 --> currentyear-02-15
12535 sep 12 9 --> 2009-09-12
12536 12:45 --> today 12:45
12537 22 sept 0:34 --> currentyear-09-22 0:34
12538 12 --> currentyear-currentmonth-12
12539 Fri --> nearest Friday (today or later)
12540 +4 --> four days from today (only if +N is the only thing given)
12541 etc.
12542 The function understands only English month and weekday abbreviations,
12543 but this can be configured with the variables `parse-time-months' and
12544 `parse-time-weekdays'.
12546 While prompting, a calendar is popped up - you can also select the
12547 date with the mouse (button 1). The calendar shows a period of three
12548 months. To scroll it to other months, use the keys `>' and `<'.
12549 If you don't like the calendar, turn it off with
12550 \(setq org-popup-calendar-for-date-prompt nil)
12552 With optional argument TO-TIME, the date will immediately be converted
12553 to an internal time.
12554 With an optional argument WITH-TIME, the prompt will suggest to also
12555 insert a time. Note that when WITH-TIME is not set, you can still
12556 enter a time, and this function will inform the calling routine about
12557 this change. The calling routine may then choose to change the format
12558 used to insert the time stamp into the buffer to include the time."
12559 (require 'parse-time)
12560 (let* ((org-time-stamp-rounding-minutes
12561 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
12562 (ct (org-current-time))
12563 (default-time
12564 ;; Default time is either today, or, when entering a range,
12565 ;; the range start.
12566 (if (save-excursion
12567 (re-search-backward
12568 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12569 (- (point) 20) t))
12570 (apply
12571 'encode-time
12572 (mapcar (lambda(x) (or x 0))
12573 (parse-time-string (match-string 1))))
12574 ct))
12575 (calendar-move-hook nil)
12576 (view-diary-entries-initially nil)
12577 (view-calendar-holidays-initially nil)
12578 (timestr (format-time-string
12579 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
12580 (prompt (concat (if prompt (concat prompt " ") "")
12581 (format "Date and/or time (default [%s]): " timestr)))
12582 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
12583 second minute hour day month year tl wday wday1 pm)
12585 (cond
12586 (from-string (setq ans from-string))
12587 (org-popup-calendar-for-date-prompt
12588 (save-excursion
12589 (save-window-excursion
12590 (calendar)
12591 (calendar-forward-day (- (time-to-days default-time)
12592 (calendar-absolute-from-gregorian
12593 (calendar-current-date))))
12594 (org-eval-in-calendar nil t)
12595 (let* ((old-map (current-local-map))
12596 (map (copy-keymap calendar-mode-map))
12597 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12598 (org-defkey map (kbd "RET") 'org-calendar-select)
12599 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12600 'org-calendar-select-mouse)
12601 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12602 'org-calendar-select-mouse)
12603 (org-defkey minibuffer-local-map [(meta shift left)]
12604 (lambda () (interactive)
12605 (org-eval-in-calendar '(calendar-backward-month 1))))
12606 (org-defkey minibuffer-local-map [(meta shift right)]
12607 (lambda () (interactive)
12608 (org-eval-in-calendar '(calendar-forward-month 1))))
12609 (org-defkey minibuffer-local-map [(shift up)]
12610 (lambda () (interactive)
12611 (org-eval-in-calendar '(calendar-backward-week 1))))
12612 (org-defkey minibuffer-local-map [(shift down)]
12613 (lambda () (interactive)
12614 (org-eval-in-calendar '(calendar-forward-week 1))))
12615 (org-defkey minibuffer-local-map [(shift left)]
12616 (lambda () (interactive)
12617 (org-eval-in-calendar '(calendar-backward-day 1))))
12618 (org-defkey minibuffer-local-map [(shift right)]
12619 (lambda () (interactive)
12620 (org-eval-in-calendar '(calendar-forward-day 1))))
12621 (org-defkey minibuffer-local-map ">"
12622 (lambda () (interactive)
12623 (org-eval-in-calendar '(scroll-calendar-left 1))))
12624 (org-defkey minibuffer-local-map "<"
12625 (lambda () (interactive)
12626 (org-eval-in-calendar '(scroll-calendar-right 1))))
12627 (unwind-protect
12628 (progn
12629 (use-local-map map)
12630 (setq org-ans0 (read-string prompt "" nil nil))
12631 ;; org-ans0: from prompt
12632 ;; org-ans1: from mouse click
12633 ;; org-ans2: from calendar motion
12634 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12635 (use-local-map old-map))))))
12636 (t ; Naked prompt only
12637 (setq ans (read-string prompt "" nil timestr))))
12638 (org-detach-overlay org-date-ovl)
12640 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
12641 (setq deltadays (string-to-number ans) ans ""))
12643 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12644 (when (string-match
12645 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12646 (setq year (if (match-end 2)
12647 (string-to-number (match-string 2 ans))
12648 (string-to-number (format-time-string "%Y")))
12649 month (string-to-number (match-string 3 ans))
12650 day (string-to-number (match-string 4 ans)))
12651 (if (< year 100) (setq year (+ 2000 year)))
12652 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12653 t nil ans)))
12654 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12655 ;; If there is a time with am/pm, and *no* time without it, we convert
12656 ;; convert so that matching will be successful.
12657 (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12658 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12659 (setq hour (string-to-number (match-string 1 ans))
12660 minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
12661 pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
12662 (if (and (= hour 12) (not pm))
12663 (setq hour 0)
12664 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12665 (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
12667 (setq tl (parse-time-string ans)
12668 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
12669 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
12670 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
12671 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
12672 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
12673 second (or (nth 0 tl) 0)
12674 wday (nth 6 tl))
12675 (setq day (+ day deltadays))
12676 (when (and wday (not (nth 3 tl)))
12677 ;; Weekday was given, but no day, so pick that day in the week
12678 ;; on or after the derived date.
12679 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12680 (unless (equal wday wday1)
12681 (setq day (+ day (% (- wday wday1 -7) 7)))))
12682 (if (and (boundp 'org-time-was-given)
12683 (nth 2 tl))
12684 (setq org-time-was-given t))
12685 (if (< year 100) (setq year (+ 2000 year)))
12686 (if to-time
12687 (encode-time second minute hour day month year)
12688 (if (or (nth 1 tl) (nth 2 tl))
12689 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
12690 (format "%04d-%02d-%02d" year month day)))))
12692 (defun org-eval-in-calendar (form &optional keepdate)
12693 "Eval FORM in the calendar window and return to current window.
12694 Also, store the cursor date in variable org-ans2."
12695 (let ((sw (selected-window)))
12696 (select-window (get-buffer-window "*Calendar*"))
12697 (eval form)
12698 (when (and (not keepdate) (calendar-cursor-to-date))
12699 (let* ((date (calendar-cursor-to-date))
12700 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12701 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12702 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12703 (select-window sw)
12704 ;; Update the prompt to show new default date
12705 (save-excursion
12706 (goto-char (point-min))
12707 (when (and org-ans2
12708 (re-search-forward "\\[[-0-9]+\\]" nil t)
12709 (get-text-property (match-end 0) 'field))
12710 (let ((inhibit-read-only t))
12711 (replace-match (concat "[" org-ans2 "]") t t)
12712 (add-text-properties (point-min) (1+ (match-end 0))
12713 (text-properties-at (1+ (point-min)))))))))
12715 (defun org-calendar-select ()
12716 "Return to `org-read-date' with the date currently selected.
12717 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12718 (interactive)
12719 (when (calendar-cursor-to-date)
12720 (let* ((date (calendar-cursor-to-date))
12721 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12722 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12723 (if (active-minibuffer-window) (exit-minibuffer))))
12725 (defun org-insert-time-stamp (time &optional with-hm inactive pre post)
12726 "Insert a date stamp for the date given by the internal TIME.
12727 WITH-HM means, use the stamp format that includes the time of the day.
12728 INACTIVE means use square brackets instead of angular ones, so that the
12729 stamp will not contribute to the agenda.
12730 PRE and POST are optional strings to be inserted before and after the
12731 stamp.
12732 The command returns the inserted time stamp."
12733 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12734 stamp)
12735 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12736 (insert (or pre ""))
12737 (insert (setq stamp (format-time-string fmt time)))
12738 (insert (or post ""))
12739 stamp))
12741 (defun org-toggle-time-stamp-overlays ()
12742 "Toggle the use of custom time stamp formats."
12743 (interactive)
12744 (setq org-display-custom-times (not org-display-custom-times))
12745 (unless org-display-custom-times
12746 (let ((p (point-min)) (bmp (buffer-modified-p)))
12747 (while (setq p (next-single-property-change p 'display))
12748 (if (and (get-text-property p 'display)
12749 (eq (get-text-property p 'face) 'org-date))
12750 (remove-text-properties
12751 p (setq p (next-single-property-change p 'display))
12752 '(display t))))
12753 (set-buffer-modified-p bmp)))
12754 (if (featurep 'xemacs)
12755 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12756 (org-restart-font-lock)
12757 (setq org-table-may-need-update t)
12758 (if org-display-custom-times
12759 (message "Time stamps are overlayed with custom format")
12760 (message "Time stamp overlays removed")))
12762 (defun org-display-custom-time (beg end)
12763 "Overlay modified time stamp format over timestamp between BED and END."
12764 (let* ((t1 (save-match-data
12765 (org-parse-time-string (buffer-substring beg end) t)))
12766 (w1 (- end beg))
12767 (with-hm (and (nth 1 t1) (nth 2 t1)))
12768 (tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats))
12769 (time (org-fix-decoded-time t1))
12770 (str (org-add-props
12771 (format-time-string
12772 (substring tf 1 -1) (apply 'encode-time time))
12773 nil 'mouse-face 'highlight))
12774 (w2 (length str)))
12775 (if (not (= w2 w1))
12776 (add-text-properties (1+ beg) (+ 2 beg)
12777 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12778 (if (featurep 'xemacs)
12779 (progn
12780 (put-text-property beg end 'invisible t)
12781 (put-text-property beg end 'end-glyph (make-glyph str)))
12782 (put-text-property beg end 'display str))))
12784 (defun org-translate-time (string)
12785 "Translate all timestamps in STRING to custom format.
12786 But do this only if the variable `org-display-custom-times' is set."
12787 (when org-display-custom-times
12788 (save-match-data
12789 (let* ((start 0)
12790 (re org-ts-regexp-both)
12791 t1 with-hm inactive tf time str beg end)
12792 (while (setq start (string-match re string start))
12793 (setq beg (match-beginning 0)
12794 end (match-end 0)
12795 t1 (save-match-data
12796 (org-parse-time-string (substring string beg end) t))
12797 with-hm (and (nth 1 t1) (nth 2 t1))
12798 inactive (equal (substring string beg (1+ beg)) "[")
12799 tf (funcall (if with-hm 'cdr 'car)
12800 org-time-stamp-custom-formats)
12801 time (org-fix-decoded-time t1)
12802 str (format-time-string
12803 (concat
12804 (if inactive "[" "<") (substring tf 1 -1)
12805 (if inactive "]" ">"))
12806 (apply 'encode-time time))
12807 string (replace-match str t t string)
12808 start (+ start (length str)))))))
12809 string)
12811 (defun org-fix-decoded-time (time)
12812 "Set 0 instead of nil for the first 6 elements of time.
12813 Don't touch the rest."
12814 (let ((n 0))
12815 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12817 (defun org-days-to-time (timestamp-string)
12818 "Difference between TIMESTAMP-STRING and now in days."
12819 (- (time-to-days (org-time-string-to-time timestamp-string))
12820 (time-to-days (current-time))))
12822 (defun org-deadline-close (timestamp-string &optional ndays)
12823 "Is the time in TIMESTAMP-STRING close to the current date?"
12824 (and (< (org-days-to-time timestamp-string)
12825 (or ndays org-deadline-warning-days))
12826 (not (org-entry-is-done-p))))
12828 (defun org-calendar-select-mouse (ev)
12829 "Return to `org-read-date' with the date currently selected.
12830 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12831 (interactive "e")
12832 (mouse-set-point ev)
12833 (when (calendar-cursor-to-date)
12834 (let* ((date (calendar-cursor-to-date))
12835 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12836 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12837 (if (active-minibuffer-window) (exit-minibuffer))))
12839 (defun org-check-deadlines (ndays)
12840 "Check if there are any deadlines due or past due.
12841 A deadline is considered due if it happens within `org-deadline-warning-days'
12842 days from today's date. If the deadline appears in an entry marked DONE,
12843 it is not shown. The prefix arg NDAYS can be used to test that many
12844 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12845 (interactive "P")
12846 (let* ((org-warn-days
12847 (cond
12848 ((equal ndays '(4)) 100000)
12849 (ndays (prefix-numeric-value ndays))
12850 (t org-deadline-warning-days)))
12851 (case-fold-search nil)
12852 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12853 (callback
12854 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12856 (message "%d deadlines past-due or due within %d days"
12857 (org-occur regexp nil callback)
12858 org-warn-days)))
12860 (defun org-evaluate-time-range (&optional to-buffer)
12861 "Evaluate a time range by computing the difference between start and end.
12862 Normally the result is just printed in the echo area, but with prefix arg
12863 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12864 If the time range is actually in a table, the result is inserted into the
12865 next column.
12866 For time difference computation, a year is assumed to be exactly 365
12867 days in order to avoid rounding problems."
12868 (interactive "P")
12870 (org-clock-update-time-maybe)
12871 (save-excursion
12872 (unless (org-at-date-range-p)
12873 (goto-char (point-at-bol))
12874 (re-search-forward org-tr-regexp (point-at-eol) t))
12875 (if (not (org-at-date-range-p))
12876 (error "Not at a time-stamp range, and none found in current line")))
12877 (let* ((ts1 (match-string 1))
12878 (ts2 (match-string 2))
12879 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12880 (match-end (match-end 0))
12881 (time1 (org-time-string-to-time ts1))
12882 (time2 (org-time-string-to-time ts2))
12883 (t1 (time-to-seconds time1))
12884 (t2 (time-to-seconds time2))
12885 (diff (abs (- t2 t1)))
12886 (negative (< (- t2 t1) 0))
12887 ;; (ys (floor (* 365 24 60 60)))
12888 (ds (* 24 60 60))
12889 (hs (* 60 60))
12890 (fy "%dy %dd %02d:%02d")
12891 (fy1 "%dy %dd")
12892 (fd "%dd %02d:%02d")
12893 (fd1 "%dd")
12894 (fh "%02d:%02d")
12895 y d h m align)
12896 (if havetime
12897 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12899 d (floor (/ diff ds)) diff (mod diff ds)
12900 h (floor (/ diff hs)) diff (mod diff hs)
12901 m (floor (/ diff 60)))
12902 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12904 d (floor (+ (/ diff ds) 0.5))
12905 h 0 m 0))
12906 (if (not to-buffer)
12907 (message (org-make-tdiff-string y d h m))
12908 (when (org-at-table-p)
12909 (goto-char match-end)
12910 (setq align t)
12911 (and (looking-at " *|") (goto-char (match-end 0))))
12912 (if (looking-at
12913 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12914 (replace-match ""))
12915 (if negative (insert " -"))
12916 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12917 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12918 (insert " " (format fh h m))))
12919 (if align (org-table-align))
12920 (message "Time difference inserted")))))
12922 (defun org-make-tdiff-string (y d h m)
12923 (let ((fmt "")
12924 (l nil))
12925 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12926 l (push y l)))
12927 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12928 l (push d l)))
12929 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12930 l (push h l)))
12931 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12932 l (push m l)))
12933 (apply 'format fmt (nreverse l))))
12935 (defun org-time-string-to-time (s)
12936 (apply 'encode-time (org-parse-time-string s)))
12938 (defun org-parse-time-string (s &optional nodefault)
12939 "Parse the standard Org-mode time string.
12940 This should be a lot faster than the normal `parse-time-string'.
12941 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12942 hour and minute fields will be nil if not given."
12943 (if (string-match org-ts-regexp1 s)
12944 (list 0
12945 (if (or (match-beginning 8) (not nodefault))
12946 (string-to-number (or (match-string 8 s) "0")))
12947 (if (or (match-beginning 7) (not nodefault))
12948 (string-to-number (or (match-string 7 s) "0")))
12949 (string-to-number (match-string 4 s))
12950 (string-to-number (match-string 3 s))
12951 (string-to-number (match-string 2 s))
12952 nil nil nil)
12953 (make-list 9 0)))
12955 (defun org-timestamp-up (&optional arg)
12956 "Increase the date item at the cursor by one.
12957 If the cursor is on the year, change the year. If it is on the month or
12958 the day, change that.
12959 With prefix ARG, change by that many units."
12960 (interactive "p")
12961 (org-timestamp-change (prefix-numeric-value arg)))
12963 (defun org-timestamp-down (&optional arg)
12964 "Decrease the date item at the cursor by one.
12965 If the cursor is on the year, change the year. If it is on the month or
12966 the day, change that.
12967 With prefix ARG, change by that many units."
12968 (interactive "p")
12969 (org-timestamp-change (- (prefix-numeric-value arg))))
12971 (defun org-timestamp-up-day (&optional arg)
12972 "Increase the date in the time stamp by one day.
12973 With prefix ARG, change that many days."
12974 (interactive "p")
12975 (if (and (not (org-at-timestamp-p t))
12976 (org-on-heading-p))
12977 (org-todo 'up)
12978 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12980 (defun org-timestamp-down-day (&optional arg)
12981 "Decrease the date in the time stamp by one day.
12982 With prefix ARG, change that many days."
12983 (interactive "p")
12984 (if (and (not (org-at-timestamp-p t))
12985 (org-on-heading-p))
12986 (org-todo 'down)
12987 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12989 (defsubst org-pos-in-match-range (pos n)
12990 (and (match-beginning n)
12991 (<= (match-beginning n) pos)
12992 (>= (match-end n) pos)))
12994 (defun org-at-timestamp-p (&optional inactive-ok)
12995 "Determine if the cursor is in or at a timestamp."
12996 (interactive)
12997 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12998 (pos (point))
12999 (ans (or (looking-at tsr)
13000 (save-excursion
13001 (skip-chars-backward "^[<\n\r\t")
13002 (if (> (point) 1) (backward-char 1))
13003 (and (looking-at tsr)
13004 (> (- (match-end 0) pos) -1))))))
13005 (and (boundp 'org-ts-what)
13006 (setq org-ts-what
13007 (cond
13008 ((org-pos-in-match-range pos 2) 'year)
13009 ((org-pos-in-match-range pos 3) 'month)
13010 ((org-pos-in-match-range pos 7) 'hour)
13011 ((org-pos-in-match-range pos 8) 'minute)
13012 ((or (org-pos-in-match-range pos 4)
13013 (org-pos-in-match-range pos 5)) 'day)
13014 (t 'day))))
13015 ans))
13017 (defun org-timestamp-change (n &optional what)
13018 "Change the date in the time stamp at point.
13019 The date will be changed by N times WHAT. WHAT can be `day', `month',
13020 `year', `minute', `second'. If WHAT is not given, the cursor position
13021 in the timestamp determines what will be changed."
13022 (let ((pos (point))
13023 with-hm inactive
13024 org-ts-what
13025 ts time time0)
13026 (if (not (org-at-timestamp-p t))
13027 (error "Not at a timestamp"))
13028 (if (and (not what) (not (eq org-ts-what 'day))
13029 org-display-custom-times
13030 (get-text-property (point) 'display)
13031 (not (get-text-property (1- (point)) 'display)))
13032 (setq org-ts-what 'day))
13033 (setq org-ts-what (or what org-ts-what)
13034 with-hm (<= (abs (- (cdr org-ts-lengths)
13035 (- (match-end 0) (match-beginning 0))))
13037 inactive (= (char-after (match-beginning 0)) ?\[)
13038 ts (match-string 0))
13039 (replace-match "")
13040 (setq time0 (org-parse-time-string ts))
13041 (setq time
13042 (apply 'encode-time
13043 (append
13044 (list (or (car time0) 0))
13045 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
13046 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
13047 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
13048 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
13049 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
13050 (nthcdr 6 time0))))
13051 (if (eq what 'calendar)
13052 (let ((cal-date
13053 (save-excursion
13054 (save-match-data
13055 (set-buffer "*Calendar*")
13056 (calendar-cursor-to-date)))))
13057 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13058 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13059 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13060 (setcar time0 (or (car time0) 0))
13061 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13062 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
13063 (setq time (apply 'encode-time time0))))
13064 (setq org-last-changed-timestamp
13065 (org-insert-time-stamp time with-hm inactive))
13066 (org-clock-update-time-maybe)
13067 (goto-char pos)
13068 ;; Try to recenter the calendar window, if any
13069 (if (and org-calendar-follow-timestamp-change
13070 (get-buffer-window "*Calendar*" t)
13071 (memq org-ts-what '(day month year)))
13072 (org-recenter-calendar (time-to-days time)))))
13074 (defun org-recenter-calendar (date)
13075 "If the calendar is visible, recenter it to DATE."
13076 (let* ((win (selected-window))
13077 (cwin (get-buffer-window "*Calendar*" t))
13078 (calendar-move-hook nil))
13079 (when cwin
13080 (select-window cwin)
13081 (calendar-goto-date (if (listp date) date
13082 (calendar-gregorian-from-absolute date)))
13083 (select-window win))))
13085 (defun org-goto-calendar (&optional arg)
13086 "Go to the Emacs calendar at the current date.
13087 If there is a time stamp in the current line, go to that date.
13088 A prefix ARG can be used to force the current date."
13089 (interactive "P")
13090 (let ((tsr org-ts-regexp) diff
13091 (calendar-move-hook nil)
13092 (view-calendar-holidays-initially nil)
13093 (view-diary-entries-initially nil))
13094 (if (or (org-at-timestamp-p)
13095 (save-excursion
13096 (beginning-of-line 1)
13097 (looking-at (concat ".*" tsr))))
13098 (let ((d1 (time-to-days (current-time)))
13099 (d2 (time-to-days
13100 (org-time-string-to-time (match-string 1)))))
13101 (setq diff (- d2 d1))))
13102 (calendar)
13103 (calendar-goto-today)
13104 (if (and diff (not arg)) (calendar-forward-day diff))))
13106 (defun org-date-from-calendar ()
13107 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13108 If there is already a time stamp at the cursor position, update it."
13109 (interactive)
13110 (org-timestamp-change 0 'calendar))
13112 ;;; The clock for measuring work time.
13114 (defvar org-mode-line-string "")
13115 (put 'org-mode-line-string 'risky-local-variable t)
13117 (defvar org-mode-line-timer nil)
13118 (defvar org-clock-heading "")
13119 (defvar org-clock-start-time "")
13121 (defun org-update-mode-line ()
13122 (let* ((now (current-time))
13123 (delta (- (time-to-seconds (current-time)) (time-to-seconds org-clock-start-time)))
13124 (h (floor delta 3600))
13125 (m (floor (- delta (* 3600 h)) 60)))
13126 (setq org-mode-line-string
13127 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
13128 'help-echo "Org-mode clock is running"))
13129 (force-mode-line-update)))
13131 (defvar org-clock-marker (make-marker)
13132 "Marker recording the last clock-in.")
13133 (defvar org-clock-mode-line-entry nil
13134 "Information for the modeline about the running clock.")
13136 (defun org-clock-in ()
13137 "Start the clock on the current item.
13138 If necessary, clock-out of the currently active clock."
13139 (interactive)
13140 (org-clock-out t)
13141 (let (ts)
13142 (save-excursion
13143 (org-back-to-heading t)
13144 (if (looking-at org-todo-line-regexp)
13145 (setq org-clock-heading (match-string 3))
13146 (setq org-clock-heading "???"))
13147 (setq org-clock-heading (propertize org-clock-heading 'face nil))
13148 (beginning-of-line 2)
13149 (when (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
13150 (not (equal (match-string 1) org-clock-string)))
13151 ;; First line hast scheduling info, move one further
13152 (beginning-of-line 2)
13153 (or (bolp) (newline)))
13154 (insert "\n") (backward-char 1)
13155 (indent-relative)
13156 (insert org-clock-string " ")
13157 (setq org-clock-start-time (current-time))
13158 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
13159 (move-marker org-clock-marker (point) (buffer-base-buffer))
13160 (or global-mode-string (setq global-mode-string '("")))
13161 (or (memq 'org-mode-line-string global-mode-string)
13162 (setq global-mode-string
13163 (append global-mode-string '(org-mode-line-string))))
13164 (org-update-mode-line)
13165 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
13166 (message "Clock started at %s" ts))))
13168 (defun org-clock-out (&optional fail-quietly)
13169 "Stop the currently running clock.
13170 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
13171 (interactive)
13172 (catch 'exit
13173 (if (not (marker-buffer org-clock-marker))
13174 (if fail-quietly (throw 'exit t) (error "No active clock")))
13175 (let (ts te s h m)
13176 (save-excursion
13177 (set-buffer (marker-buffer org-clock-marker))
13178 (goto-char org-clock-marker)
13179 (beginning-of-line 1)
13180 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
13181 (equal (match-string 1) org-clock-string))
13182 (setq ts (match-string 2))
13183 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
13184 (goto-char org-clock-marker)
13185 (insert "--")
13186 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
13187 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
13188 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
13189 h (floor (/ s 3600))
13190 s (- s (* 3600 h))
13191 m (floor (/ s 60))
13192 s (- s (* 60 s)))
13193 (insert " => " (format "%2d:%02d" h m))
13194 (move-marker org-clock-marker nil)
13195 (org-add-log-maybe 'clock-out)
13196 (when org-mode-line-timer
13197 (cancel-timer org-mode-line-timer)
13198 (setq org-mode-line-timer nil))
13199 (setq global-mode-string
13200 (delq 'org-mode-line-string global-mode-string))
13201 (force-mode-line-update)
13202 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
13204 (defun org-clock-cancel ()
13205 "Cancel the running clock be removing the start timestamp."
13206 (interactive)
13207 (if (not (marker-buffer org-clock-marker))
13208 (error "No active clock"))
13209 (save-excursion
13210 (set-buffer (marker-buffer org-clock-marker))
13211 (goto-char org-clock-marker)
13212 (delete-region (1- (point-at-bol)) (point-at-eol)))
13213 (message "Clock canceled"))
13215 (defvar org-clock-file-total-minutes nil
13216 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
13217 (make-variable-buffer-local 'org-clock-file-total-minutes)
13219 (defun org-clock-sum (&optional tstart tend)
13220 "Sum the times for each subtree.
13221 Puts the resulting times in minutes as a text property on each headline."
13222 (interactive)
13223 (let* ((bmp (buffer-modified-p))
13224 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
13225 org-clock-string
13226 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
13227 (lmax 30)
13228 (ltimes (make-vector lmax 0))
13229 (t1 0)
13230 (level 0)
13231 ts te dt
13232 time)
13233 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
13234 (save-excursion
13235 (goto-char (point-max))
13236 (while (re-search-backward re nil t)
13237 (if (match-end 2)
13238 ;; A time
13239 (setq ts (match-string 2)
13240 te (match-string 3)
13241 ts (time-to-seconds
13242 (apply 'encode-time (org-parse-time-string ts)))
13243 te (time-to-seconds
13244 (apply 'encode-time (org-parse-time-string te)))
13245 ts (if tstart (max ts tstart) ts)
13246 te (if tend (min te tend) te)
13247 dt (- te ts)
13248 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
13249 ;; A headline
13250 (setq level (- (match-end 1) (match-beginning 1)))
13251 (when (or (> t1 0) (> (aref ltimes level) 0))
13252 (loop for l from 0 to level do
13253 (aset ltimes l (+ (aref ltimes l) t1)))
13254 (setq t1 0 time (aref ltimes level))
13255 (loop for l from level to (1- lmax) do
13256 (aset ltimes l 0))
13257 (goto-char (match-beginning 0))
13258 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
13259 (setq org-clock-file-total-minutes (aref ltimes 0)))
13260 (set-buffer-modified-p bmp)))
13262 (defun org-clock-display (&optional total-only)
13263 "Show subtree times in the entire buffer.
13264 If TOTAL-ONLY is non-nil, only show the total time for the entire file
13265 in the echo area."
13266 (interactive)
13267 (org-remove-clock-overlays)
13268 (let (time h m p)
13269 (org-clock-sum)
13270 (unless total-only
13271 (save-excursion
13272 (goto-char (point-min))
13273 (while (setq p (next-single-property-change (point) :org-clock-minutes))
13274 (goto-char p)
13275 (when (setq time (get-text-property p :org-clock-minutes))
13276 (org-put-clock-overlay time (funcall outline-level))))
13277 (setq h (/ org-clock-file-total-minutes 60)
13278 m (- org-clock-file-total-minutes (* 60 h)))
13279 ;; Arrange to remove the overlays upon next change.
13280 (when org-remove-highlights-with-change
13281 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
13282 nil 'local))))
13283 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
13285 (defvar org-clock-overlays nil)
13286 (make-variable-buffer-local 'org-clock-overlays)
13288 (defun org-put-clock-overlay (time &optional level)
13289 "Put an overlays on the current line, displaying TIME.
13290 If LEVEL is given, prefix time with a corresponding number of stars.
13291 This creates a new overlay and stores it in `org-clock-overlays', so that it
13292 will be easy to remove."
13293 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
13294 (l (if level (org-get-legal-level level 0) 0))
13295 (off 0)
13296 ov tx)
13297 (move-to-column c)
13298 (unless (eolp) (skip-chars-backward "^ \t"))
13299 (skip-chars-backward " \t")
13300 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
13301 tx (concat (buffer-substring (1- (point)) (point))
13302 (make-string (+ off (max 0 (- c (current-column)))) ?.)
13303 (org-add-props (format "%s %2d:%02d%s"
13304 (make-string l ?*) h m
13305 (make-string (- 10 l) ?\ ))
13306 '(face secondary-selection))
13307 ""))
13308 (if (not (featurep 'xemacs))
13309 (org-overlay-put ov 'display tx)
13310 (org-overlay-put ov 'invisible t)
13311 (org-overlay-put ov 'end-glyph (make-glyph tx)))
13312 (push ov org-clock-overlays)))
13314 (defun org-remove-clock-overlays (&optional beg end noremove)
13315 "Remove the occur highlights from the buffer.
13316 BEG and END are ignored. If NOREMOVE is nil, remove this function
13317 from the `before-change-functions' in the current buffer."
13318 (interactive)
13319 (unless org-inhibit-highlight-removal
13320 (mapc 'org-delete-overlay org-clock-overlays)
13321 (setq org-clock-overlays nil)
13322 (unless noremove
13323 (remove-hook 'before-change-functions
13324 'org-remove-clock-overlays 'local))))
13326 (defun org-clock-out-if-current ()
13327 "Clock out if the current entry contains the running clock.
13328 This is used to stop the clock after a TODO entry is marked DONE."
13329 (when (and (member state org-done-keywords)
13330 (equal (marker-buffer org-clock-marker) (current-buffer))
13331 (< (point) org-clock-marker)
13332 (> (save-excursion (outline-next-heading) (point))
13333 org-clock-marker))
13334 ;; Clock out, but don't accept a logging message for this.
13335 (let ((org-log-done (if (and (listp org-log-done)
13336 (member 'clock-out org-log-done))
13337 '(done)
13338 org-log-done)))
13339 (org-clock-out))))
13341 (add-hook 'org-after-todo-state-change-hook
13342 'org-clock-out-if-current)
13344 (defun org-check-running-clock ()
13345 "Check if the current buffer contains the running clock.
13346 If yes, offer to stop it and to save the buffer with the changes."
13347 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
13348 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
13349 (buffer-name))))
13350 (org-clock-out)
13351 (when (y-or-n-p "Save changed buffer?")
13352 (save-buffer))))
13354 (defun org-clock-report ()
13355 "Create a table containing a report about clocked time.
13356 If the buffer contains lines
13357 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
13359 #+END: clocktable
13360 then the table will be inserted between these lines, replacing whatever
13361 is was there before. If these lines are not in the buffer, the table
13362 is inserted at point, surrounded by the special lines.
13363 The BEGIN line can contain parameters. Allowed are:
13364 :maxlevel The maximum level to be included in the table. Default is 3.
13365 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
13366 (interactive)
13367 (org-remove-clock-overlays)
13368 (unless (org-find-dblock "clocktable")
13369 (org-create-dblock (list :name "clocktable"
13370 :maxlevel 2 :emphasize nil)))
13371 (org-update-dblock))
13373 (defun org-clock-update-time-maybe ()
13374 "If this is a CLOCK line, update it and return t.
13375 Otherwise, return nil."
13376 (interactive)
13377 (save-excursion
13378 (beginning-of-line 1)
13379 (skip-chars-forward " \t")
13380 (when (looking-at org-clock-string)
13381 (let ((re (concat "[ \t]*" org-clock-string
13382 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
13383 "\\([ \t]*=>.*\\)?"))
13384 ts te h m s)
13385 (if (not (looking-at re))
13387 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
13388 (end-of-line 1)
13389 (setq ts (match-string 1)
13390 te (match-string 2))
13391 (setq s (- (time-to-seconds
13392 (apply 'encode-time (org-parse-time-string te)))
13393 (time-to-seconds
13394 (apply 'encode-time (org-parse-time-string ts))))
13395 h (floor (/ s 3600))
13396 s (- s (* 3600 h))
13397 m (floor (/ s 60))
13398 s (- s (* 60 s)))
13399 (insert " => " (format "%2d:%02d" h m))
13400 t)))))
13402 (defun org-clock-special-range (key &optional time as-strings)
13403 "Return two times bordering a special time range.
13404 Key is a symbol specifying the range and can be one of `today', `yesterday',
13405 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
13406 A week starts Monday 0:00 and ends Sunday 24:00.
13407 The range is determined relative to TIME. TIME defaults to the current time.
13408 The return value is a cons cell with two internal times like the ones
13409 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
13410 the returned times will be formatted strings."
13411 (let* ((tm (decode-time (or time (current-time))))
13412 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
13413 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
13414 (dow (nth 6 tm))
13415 s1 m1 h1 d1 month1 y1 diff ts te fm)
13416 (cond
13417 ((eq key 'today)
13418 (setq h 0 m 0 h1 24 m1 0))
13419 ((eq key 'yesterday)
13420 (setq d (1- d) h 0 m 0 h1 24 m1 0))
13421 ((eq key 'thisweek)
13422 (setq diff (if (= dow 0) 6 (1- dow))
13423 m 0 h 0 d (- d diff) d1 (+ 7 d)))
13424 ((eq key 'lastweek)
13425 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
13426 m 0 h 0 d (- d diff) d1 (+ 7 d)))
13427 ((eq key 'thismonth)
13428 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
13429 ((eq key 'lastmonth)
13430 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
13431 ((eq key 'thisyear)
13432 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
13433 ((eq key 'lastyear)
13434 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
13435 (t (error "No such time block %s" key)))
13436 (setq ts (encode-time s m h d month y)
13437 te (encode-time (or s1 s) (or m1 m) (or h1 h)
13438 (or d1 d) (or month1 month) (or y1 y)))
13439 (setq fm (cdr org-time-stamp-formats))
13440 (if as-strings
13441 (cons (format-time-string fm ts) (format-time-string fm te))
13442 (cons ts te))))
13444 (defun org-dblock-write:clocktable (params)
13445 "Write the standard clocktable."
13446 (let ((hlchars '((1 . "*") (2 . ?/)))
13447 (emph nil)
13448 (ins (make-marker))
13449 ipos time h m p level hlc hdl maxlevel
13450 ts te cc block)
13451 (setq maxlevel (or (plist-get params :maxlevel) 3)
13452 emph (plist-get params :emphasize)
13453 ts (plist-get params :tstart)
13454 te (plist-get params :tend)
13455 block (plist-get params :block))
13456 (when block
13457 (setq cc (org-clock-special-range block nil t)
13458 ts (car cc) te (cdr cc)))
13459 (if ts (setq ts (time-to-seconds
13460 (apply 'encode-time (org-parse-time-string ts)))))
13461 (if te (setq te (time-to-seconds
13462 (apply 'encode-time (org-parse-time-string te)))))
13463 (move-marker ins (point))
13464 (setq ipos (point))
13465 (insert-before-markers "Clock summary at ["
13466 (substring
13467 (format-time-string (cdr org-time-stamp-formats))
13468 1 -1)
13469 "]."
13470 (if block
13471 (format " Considered range is /%s/." block)
13473 "\n\n|L|Headline|Time|\n")
13474 (org-clock-sum ts te)
13475 (setq h (/ org-clock-file-total-minutes 60)
13476 m (- org-clock-file-total-minutes (* 60 h)))
13477 (insert-before-markers "|-\n|0|" "*Total file time*| "
13478 (format "*%d:%02d*" h m)
13479 "|\n")
13480 (goto-char (point-min))
13481 (while (setq p (next-single-property-change (point) :org-clock-minutes))
13482 (goto-char p)
13483 (when (setq time (get-text-property p :org-clock-minutes))
13484 (save-excursion
13485 (beginning-of-line 1)
13486 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
13487 (setq level (- (match-end 1) (match-beginning 1)))
13488 (<= level maxlevel))
13489 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
13490 hdl (match-string 2)
13491 h (/ time 60)
13492 m (- time (* 60 h)))
13493 (goto-char ins)
13494 (if (= level 1) (insert-before-markers "|-\n"))
13495 (insert-before-markers
13496 "| " (int-to-string level) "|" hlc hdl hlc " |"
13497 (make-string (1- level) ?|)
13499 (format "%d:%02d" h m)
13501 " |\n")))))
13502 (goto-char ins)
13503 (backward-delete-char 1)
13504 (goto-char ipos)
13505 (skip-chars-forward "^|")
13506 (org-table-align)))
13508 ;; FIXME: I don't think anybody uses this, ask David
13509 (defun org-collect-clock-time-entries ()
13510 "Return an internal list with clocking information.
13511 This list has one entry for each CLOCK interval.
13512 FIXME: describe the elements."
13513 (interactive)
13514 (let ((re (concat "^[ \t]*" org-clock-string
13515 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
13516 rtn beg end next cont level title total closedp leafp
13517 clockpos titlepos h m donep)
13518 (save-excursion
13519 (org-clock-sum)
13520 (goto-char (point-min))
13521 (while (re-search-forward re nil t)
13522 (setq clockpos (match-beginning 0)
13523 beg (match-string 1) end (match-string 2)
13524 cont (match-end 0))
13525 (setq beg (apply 'encode-time (org-parse-time-string beg))
13526 end (apply 'encode-time (org-parse-time-string end)))
13527 (org-back-to-heading t)
13528 (setq donep (org-entry-is-done-p))
13529 (setq titlepos (point)
13530 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
13531 h (/ total 60) m (- total (* 60 h))
13532 total (cons h m))
13533 (looking-at "\\(\\*+\\) +\\(.*\\)")
13534 (setq level (- (match-end 1) (match-beginning 1))
13535 title (org-match-string-no-properties 2))
13536 (save-excursion (outline-next-heading) (setq next (point)))
13537 (setq closedp (re-search-forward org-closed-time-regexp next t))
13538 (goto-char next)
13539 (setq leafp (and (looking-at "^\\*+ ")
13540 (<= (- (match-end 0) (point)) level)))
13541 (push (list beg end clockpos closedp donep
13542 total title titlepos level leafp)
13543 rtn)
13544 (goto-char cont)))
13545 (nreverse rtn)))
13547 ;;;; Agenda, and Diary Integration
13549 ;;; Define the Org-agenda-mode
13551 (defvar org-agenda-mode-map (make-sparse-keymap)
13552 "Keymap for `org-agenda-mode'.")
13554 (defvar org-agenda-menu) ; defined later in this file.
13555 (defvar org-agenda-follow-mode nil)
13556 (defvar org-agenda-show-log nil)
13557 (defvar org-agenda-redo-command nil)
13558 (defvar org-agenda-mode-hook nil)
13559 (defvar org-agenda-type nil)
13560 (defvar org-agenda-force-single-file nil)
13562 (defun org-agenda-mode ()
13563 "Mode for time-sorted view on action items in Org-mode files.
13565 The following commands are available:
13567 \\{org-agenda-mode-map}"
13568 (interactive)
13569 (kill-all-local-variables)
13570 (setq org-agenda-undo-list nil
13571 org-agenda-pending-undo-list nil)
13572 (setq major-mode 'org-agenda-mode)
13573 ;; Keep global-font-lock-mode from turning on font-lock-mode
13574 (org-set-local 'font-lock-global-modes (list 'not major-mode))
13575 (setq mode-name "Org-Agenda")
13576 (use-local-map org-agenda-mode-map)
13577 (easy-menu-add org-agenda-menu)
13578 (if org-startup-truncated (setq truncate-lines t))
13579 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
13580 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
13581 ;; Make sure properties are removed when copying text
13582 (when (boundp 'buffer-substring-filters)
13583 (org-set-local 'buffer-substring-filters
13584 (cons (lambda (x)
13585 (set-text-properties 0 (length x) nil x) x)
13586 buffer-substring-filters)))
13587 (unless org-agenda-keep-modes
13588 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
13589 org-agenda-show-log nil))
13590 (easy-menu-change
13591 '("Agenda") "Agenda Files"
13592 (append
13593 (list
13594 (vector
13595 (if (get 'org-agenda-files 'org-restrict)
13596 "Restricted to single file"
13597 "Edit File List")
13598 '(org-edit-agenda-file-list)
13599 (not (get 'org-agenda-files 'org-restrict)))
13600 "--")
13601 (mapcar 'org-file-menu-entry (org-agenda-files))))
13602 (org-agenda-set-mode-name)
13603 (apply
13604 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
13605 (list 'org-agenda-mode-hook)))
13607 (substitute-key-definition 'undo 'org-agenda-undo
13608 org-agenda-mode-map global-map)
13609 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
13610 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
13611 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
13612 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
13613 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
13614 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
13615 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
13616 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
13617 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
13618 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
13619 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
13620 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
13621 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
13622 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
13623 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
13624 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
13625 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
13626 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
13627 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
13628 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
13629 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
13630 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
13631 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
13632 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-earlier)
13633 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
13634 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
13636 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
13637 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
13638 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
13639 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
13640 (while l (org-defkey org-agenda-mode-map
13641 (int-to-string (pop l)) 'digit-argument)))
13643 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
13644 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
13645 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
13646 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
13647 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
13648 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
13649 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
13650 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
13651 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
13652 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
13653 (org-defkey org-agenda-mode-map "n" 'next-line)
13654 (org-defkey org-agenda-mode-map "p" 'previous-line)
13655 (org-defkey org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
13656 (org-defkey org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
13657 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
13658 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
13659 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
13660 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
13661 (eval-after-load "calendar"
13662 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
13663 'org-calendar-goto-agenda))
13664 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
13665 (org-defkey org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
13666 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
13667 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
13668 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
13669 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
13670 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
13671 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
13672 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
13673 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
13674 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
13675 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-priority-up)
13676 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
13677 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
13678 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
13679 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
13680 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
13681 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
13682 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
13683 "Local keymap for agenda entries from Org-mode.")
13685 (org-defkey org-agenda-keymap
13686 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
13687 (org-defkey org-agenda-keymap
13688 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
13689 (when org-agenda-mouse-1-follows-link
13690 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
13691 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
13692 '("Agenda"
13693 ("Agenda Files")
13694 "--"
13695 ["Show" org-agenda-show t]
13696 ["Go To (other window)" org-agenda-goto t]
13697 ["Go To (this window)" org-agenda-switch-to t]
13698 ["Follow Mode" org-agenda-follow-mode
13699 :style toggle :selected org-agenda-follow-mode :active t]
13700 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
13701 "--"
13702 ["Cycle TODO" org-agenda-todo t]
13703 ["Archive subtree" org-agenda-archive t]
13704 ["Delete subtree" org-agenda-kill t]
13705 "--"
13706 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
13707 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
13708 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
13709 "--"
13710 ("Tags"
13711 ["Show all Tags" org-agenda-show-tags t]
13712 ["Set Tags" org-agenda-set-tags t])
13713 ("Date/Schedule"
13714 ["Schedule" org-agenda-schedule t]
13715 ["Set Deadline" org-agenda-deadline t]
13716 "--"
13717 ["Change date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
13718 ["Change date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
13719 ["Change date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
13720 ("Priority"
13721 ["Set Priority" org-agenda-priority t]
13722 ["Increase Priority" org-agenda-priority-up t]
13723 ["Decrease Priority" org-agenda-priority-down t]
13724 ["Show Priority" org-agenda-show-priority t])
13725 ("Calendar/Diary"
13726 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
13727 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
13728 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
13729 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
13730 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
13731 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
13732 "--"
13733 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
13734 "--"
13735 ("View"
13736 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
13737 :style radio :selected (equal org-agenda-ndays 1)]
13738 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
13739 :style radio :selected (equal org-agenda-ndays 7)]
13740 "--"
13741 ["Show Logbook entries" org-agenda-log-mode
13742 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
13743 ["Include Diary" org-agenda-toggle-diary
13744 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
13745 ["Use Time Grid" org-agenda-toggle-time-grid
13746 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
13747 ["Rebuild buffer" org-agenda-redo t]
13748 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
13749 "--"
13750 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
13751 "--"
13752 ["Quit" org-agenda-quit t]
13753 ["Exit and Release Buffers" org-agenda-exit t]
13756 ;;; Agenda undo
13758 (defvar org-agenda-allow-remote-undo t
13759 "Non-nil means, allow remote undo from the agenda buffer.")
13760 (defvar org-agenda-undo-list nil
13761 "List of undoable operations in the agenda since last refresh.")
13762 (defvar org-agenda-undo-has-started-in nil
13763 "Buffers that have already seen `undo-start' in the current undo sequence.")
13764 (defvar org-agenda-pending-undo-list nil
13765 "In a series of undo commands, this is the list of remaning undo items.")
13767 (defmacro org-if-unprotected (&rest body)
13768 "Execute BODY if ther is no `org-protected' text property at point."
13769 (declare (debug t))
13770 `(unless (get-text-property (point) 'org-protected)
13771 ,@body))
13773 (defmacro org-unmodified (&rest body)
13774 "Execute body without changing buffer-modified-p."
13775 `(set-buffer-modified-p
13776 (prog1 (buffer-modified-p) ,@body)))
13778 (defmacro org-with-remote-undo (_buffer &rest _body)
13779 "Execute BODY while recording undo information in two buffers."
13780 (declare (indent 1) (debug t))
13781 `(let ((_cline (org-current-line))
13782 (_cmd this-command)
13783 (_buf1 (current-buffer))
13784 (_buf2 ,_buffer)
13785 (_undo1 buffer-undo-list)
13786 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
13787 _c1 _c2)
13788 ,@_body
13789 (when org-agenda-allow-remote-undo
13790 (setq _c1 (org-verify-change-for-undo
13791 _undo1 (with-current-buffer _buf1 buffer-undo-list))
13792 _c2 (org-verify-change-for-undo
13793 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
13794 (when (or _c1 _c2)
13795 ;; make sure there are undo boundaries
13796 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
13797 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
13798 ;; remember which buffer to undo
13799 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
13800 org-agenda-undo-list)))))
13802 (defun org-agenda-undo ()
13803 "Undo a remote editing step in the agenda.
13804 This undoes changes both in the agenda buffer and in the remote buffer
13805 that have been changed along."
13806 (interactive)
13807 (or org-agenda-allow-remote-undo
13808 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
13809 (if (not (eq this-command last-command))
13810 (setq org-agenda-undo-has-started-in nil
13811 org-agenda-pending-undo-list org-agenda-undo-list))
13812 (if (not org-agenda-pending-undo-list)
13813 (error "No further undo information"))
13814 (let* ((entry (pop org-agenda-pending-undo-list))
13815 buf line cmd rembuf)
13816 (setq cmd (pop entry) line (pop entry))
13817 (setq rembuf (nth 2 entry))
13818 (org-with-remote-undo rembuf
13819 (while (bufferp (setq buf (pop entry)))
13820 (if (pop entry)
13821 (with-current-buffer buf
13822 (let ((last-undo-buffer buf)
13823 buffer-read-only)
13824 (unless (memq buf org-agenda-undo-has-started-in)
13825 (push buf org-agenda-undo-has-started-in)
13826 (make-local-variable 'pending-undo-list)
13827 (undo-start))
13828 (while (and pending-undo-list
13829 (listp pending-undo-list)
13830 (not (car pending-undo-list)))
13831 (pop pending-undo-list))
13832 (undo-more 1))))))
13833 (goto-line line)
13834 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
13836 (defun org-verify-change-for-undo (l1 l2)
13837 "Verify that a real change occurred between the undo lists L1 and L2."
13838 (while (and l1 (listp l1) (null (car l1))) (pop l1))
13839 (while (and l2 (listp l2) (null (car l2))) (pop l2))
13840 (not (eq l1 l2)))
13842 ;;; Agenda dispatch
13844 (defvar org-agenda-restrict nil)
13845 (defvar org-agenda-restrict-begin (make-marker))
13846 (defvar org-agenda-restrict-end (make-marker))
13847 (defvar org-agenda-last-dispatch-buffer nil)
13849 ;;;###autoload
13850 (defun org-agenda (arg)
13851 "Dispatch agenda commands to collect entries to the agenda buffer.
13852 Prompts for a character to select a command. Any prefix arg will be passed
13853 on to the selected command. The default selections are:
13855 a Call `org-agenda-list' to display the agenda for current day or week.
13856 t Call `org-todo-list' to display the global todo list.
13857 T Call `org-todo-list' to display the global todo list, select only
13858 entries with a specific TODO keyword (the user gets a prompt).
13859 m Call `org-tags-view' to display headlines with tags matching
13860 a condition (the user is prompted for the condition).
13861 M Like `m', but select only TODO entries, no ordinary headlines.
13862 l Create a timeeline for the current buffer.
13864 More commands can be added by configuring the variable
13865 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
13866 searches can be pre-defined in this way.
13868 If the current buffer is in Org-mode and visiting a file, you can also
13869 first press `1' to indicate that the agenda should be temporarily (until the
13870 next use of \\[org-agenda]) restricted to the current file."
13871 (interactive "P")
13872 (catch 'exit
13873 (let* ((buf (current-buffer))
13874 (bfn (buffer-file-name (buffer-base-buffer)))
13875 (restrict-ok (and bfn (org-mode-p)))
13876 (custom org-agenda-custom-commands)
13877 c entry key type match lprops)
13878 ;; Turn off restriction
13879 (put 'org-agenda-files 'org-restrict nil)
13880 (setq org-agenda-restrict nil)
13881 (move-marker org-agenda-restrict-begin nil)
13882 (move-marker org-agenda-restrict-end nil)
13883 ;; Remember where this call originated
13884 (setq org-agenda-last-dispatch-buffer (current-buffer))
13885 (save-window-excursion
13886 (delete-other-windows)
13887 (switch-to-buffer-other-window " *Agenda Commands*")
13888 (erase-buffer)
13889 (insert (eval-when-compile
13890 (let ((header
13891 "Press key for an agenda command:
13892 -------------------------------- C Configure custom agenda commands
13893 a Agenda for current week or day
13894 t List of all TODO entries T Entries with special TODO kwd
13895 m Match a TAGS query M Like m, but only TODO entries
13896 L Timeline for current buffer # List stuck projects (!=configure)
13898 (start 0))
13899 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
13900 (setq start (match-end 0))
13901 (add-text-properties (match-beginning 2) (match-end 2)
13902 '(face bold) header))
13903 header)))
13904 (while (setq entry (pop custom))
13905 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
13906 (insert (format "\n%-4s%-14s: %s"
13907 (org-add-props (copy-sequence key)
13908 '(face bold))
13909 (cond
13910 ((stringp type) type)
13911 ((eq type 'todo) "TODO keyword")
13912 ((eq type 'tags) "Tags query")
13913 ((eq type 'tags-todo) "Tags (TODO)")
13914 ((eq type 'tags-tree) "Tags tree")
13915 ((eq type 'todo-tree) "TODO kwd tree")
13916 ((eq type 'occur-tree) "Occur tree")
13917 ((functionp type) (symbol-name type))
13918 (t "???"))
13919 (if (stringp match)
13920 (org-add-props match nil 'face 'org-warning)
13921 (format "set of %d commands" (length match))))))
13922 (if restrict-ok
13923 (insert "\n"
13924 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
13925 (goto-char (point-min))
13926 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
13927 (message "Press key for agenda command%s"
13928 (if restrict-ok ", or [1] or [0] to restrict" ""))
13929 (setq c (read-char-exclusive))
13930 (message "")
13931 (when (memq c '(?L ?1 ?0))
13932 (if restrict-ok
13933 (put 'org-agenda-files 'org-restrict (list bfn))
13934 (error "Cannot restrict agenda to current buffer"))
13935 (with-current-buffer " *Agenda Commands*"
13936 (goto-char (point-max))
13937 (delete-region (point-at-bol) (point))
13938 (goto-char (point-min)))
13939 (when (eq c ?0)
13940 (setq org-agenda-restrict t)
13941 (with-current-buffer buf
13942 (if (org-region-active-p)
13943 (progn
13944 (move-marker org-agenda-restrict-begin (region-beginning))
13945 (move-marker org-agenda-restrict-end (region-end)))
13946 (save-excursion
13947 (org-back-to-heading t)
13948 (move-marker org-agenda-restrict-begin (point))
13949 (move-marker org-agenda-restrict-end
13950 (progn (org-end-of-subtree t)))))))
13951 (unless (eq c ?L)
13952 (message "Press key for agenda command%s"
13953 (if restrict-ok " (restricted to current file)" ""))
13954 (setq c (read-char-exclusive)))
13955 (message "")))
13956 (require 'calendar) ; FIXME: can we avoid this for some commands?
13957 ;; For example the todo list should not need it (but does...)
13958 (cond
13959 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
13960 (if (symbolp (nth 1 entry))
13961 (progn
13962 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
13963 lprops (nth 3 entry))
13964 (cond
13965 ((eq type 'tags)
13966 (org-let lprops '(org-tags-view current-prefix-arg match)))
13967 ((eq type 'tags-todo)
13968 (org-let lprops '(org-tags-view '(4) match)))
13969 ((eq type 'todo)
13970 (org-let lprops '(org-todo-list match)))
13971 ((eq type 'tags-tree)
13972 (org-check-for-org-mode)
13973 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
13974 ((eq type 'todo-tree)
13975 (org-check-for-org-mode)
13976 (org-let lprops
13977 '(org-occur (concat "^" outline-regexp "[ \t]*"
13978 (regexp-quote match) "\\>"))))
13979 ((eq type 'occur-tree)
13980 (org-check-for-org-mode)
13981 (org-let lprops '(org-occur match)))
13982 ((fboundp type)
13983 (org-let lprops '(funcall type match)))
13984 (t (error "Invalid custom agenda command type %s" type))))
13985 (org-run-agenda-series (cddr entry))))
13986 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
13987 ((equal c ?a) (call-interactively 'org-agenda-list))
13988 ((equal c ?t) (call-interactively 'org-todo-list))
13989 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
13990 ((equal c ?m) (call-interactively 'org-tags-view))
13991 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
13992 ((equal c ?L)
13993 (unless restrict-ok
13994 (error "This is not an Org-mode file"))
13995 (org-call-with-arg 'org-timeline arg))
13996 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
13997 ((equal c ?!) (customize-variable 'org-stuck-projects))
13998 (t (error "Invalid key"))))))
14000 (defun org-run-agenda-series (series)
14001 (org-prepare-agenda)
14002 (let* ((org-agenda-multi t)
14003 (redo (list 'org-run-agenda-series (list 'quote series)))
14004 (cmds (car series))
14005 (gprops (nth 1 series))
14006 match ;; The byte compiler incorrectly complains about this. Keep it!
14007 cmd type lprops)
14008 (while (setq cmd (pop cmds))
14009 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
14010 (cond
14011 ((eq type 'agenda)
14012 (call-interactively 'org-agenda-list))
14013 ((eq type 'alltodo)
14014 (call-interactively 'org-todo-list))
14015 ((eq type 'stuck)
14016 (call-interactively 'org-agenda-list-stuck-projects))
14017 ((eq type 'tags)
14018 (org-let2 gprops lprops
14019 '(org-tags-view current-prefix-arg match)))
14020 ((eq type 'tags-todo)
14021 (org-let2 gprops lprops
14022 '(org-tags-view '(4) match)))
14023 ((eq type 'todo)
14024 (org-let2 gprops lprops
14025 '(org-todo-list match)))
14026 ((fboundp type)
14027 (org-let2 gprops lprops
14028 '(funcall type match)))
14029 (t (error "Invalid type in command series"))))
14030 (widen)
14031 (setq org-agenda-redo-command redo)
14032 (goto-char (point-min)))
14033 (org-finalize-agenda))
14035 ;;;###autoload
14036 (defmacro org-batch-agenda (cmd-key &rest parameters)
14037 "Run an agenda command in batch mode, send result to STDOUT.
14038 CMD-KEY is a string that is also a key in `org-agenda-custom-commands'.
14039 Paramters are alternating variable names and values that will be bound
14040 before running the agenda command."
14041 (let (pars)
14042 (while parameters
14043 (push (list (pop parameters) (if parameters (pop parameters))) pars))
14044 (flet ((read-char-exclusive () (string-to-char cmd-key)))
14045 (eval (list 'let (nreverse pars) '(org-agenda nil))))
14046 (set-buffer "*Org Agenda*")
14047 (princ (buffer-string))))
14049 (defmacro org-no-read-only (&rest body)
14050 "Inhibit read-only for BODY."
14051 `(let ((inhibit-read-only t)) ,@body))
14053 (defun org-check-for-org-mode ()
14054 "Make sure current buffer is in org-mode. Error if not."
14055 (or (org-mode-p)
14056 (error "Cannot execute org-mode agenda command on buffer in %s."
14057 major-mode)))
14059 (defun org-fit-agenda-window ()
14060 "Fit the window to the buffer size."
14061 (and (memq org-agenda-window-setup '(reorganize-frame))
14062 (fboundp 'fit-window-to-buffer)
14063 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
14064 (/ (frame-height) 2))))
14066 ;;; Agenda file list
14068 (defun org-agenda-files (&optional unrestricted)
14069 "Get the list of agenda files.
14070 Optional UNRESTRICTED means return the full list even if a restriction
14071 is currently in place."
14072 (cond
14073 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14074 ((stringp org-agenda-files) (org-read-agenda-file-list))
14075 ((listp org-agenda-files) org-agenda-files)
14076 (t (error "Invalid value of `org-agenda-files'"))))
14078 (defun org-edit-agenda-file-list ()
14079 "Edit the list of agenda files.
14080 Depending on setup, this either uses customize to edit the variable
14081 `org-agenda-files', or it visits the file that is holding the list. In the
14082 latter case, the buffer is set up in a way that saving it automatically kills
14083 the buffer and restores the previous window configuration."
14084 (interactive)
14085 (if (stringp org-agenda-files)
14086 (let ((cw (current-window-configuration)))
14087 (find-file org-agenda-files)
14088 (org-set-local 'org-window-configuration cw)
14089 (org-add-hook 'after-save-hook
14090 (lambda ()
14091 (set-window-configuration
14092 (prog1 org-window-configuration
14093 (kill-buffer (current-buffer))))
14094 (org-install-agenda-files-menu)
14095 (message "New agenda file list installed"))
14096 nil 'local)
14097 (message (substitute-command-keys
14098 "Edit list and finish with \\[save-buffer]")))
14099 (customize-variable 'org-agenda-files)))
14101 (defun org-store-new-agenda-file-list (list)
14102 "Set new value for the agenda file list and save it correcly."
14103 (if (stringp org-agenda-files)
14104 (let ((f org-agenda-files) b)
14105 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
14106 (with-temp-file f
14107 (insert (mapconcat 'identity list "\n") "\n")))
14108 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
14109 (setq org-agenda-files list)
14110 (customize-save-variable 'org-agenda-files org-agenda-files))))
14112 (defun org-read-agenda-file-list ()
14113 "Read the list of agenda files from a file."
14114 (when (stringp org-agenda-files)
14115 (with-temp-buffer
14116 (insert-file-contents org-agenda-files)
14117 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
14120 ;;;###autoload
14121 (defun org-cycle-agenda-files ()
14122 "Cycle through the files in `org-agenda-files'.
14123 If the current buffer visits an agenda file, find the next one in the list.
14124 If the current buffer does not, find the first agenda file."
14125 (interactive)
14126 (let* ((fs (org-agenda-files t))
14127 (files (append fs (list (car fs))))
14128 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14129 file)
14130 (unless files (error "No agenda files"))
14131 (catch 'exit
14132 (while (setq file (pop files))
14133 (if (equal (file-truename file) tcf)
14134 (when (car files)
14135 (find-file (car files))
14136 (throw 'exit t))))
14137 (find-file (car fs)))
14138 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14140 (defun org-agenda-file-to-front (&optional to-end)
14141 "Move/add the current file to the top of the agenda file list.
14142 If the file is not present in the list, it is added to the front. If it is
14143 present, it is moved there. With optional argument TO-END, add/move to the
14144 end of the list."
14145 (interactive "P")
14146 (let ((file-alist (mapcar (lambda (x)
14147 (cons (file-truename x) x))
14148 (org-agenda-files t)))
14149 (ctf (file-truename buffer-file-name))
14150 x had)
14151 (setq x (assoc ctf file-alist) had x)
14153 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14154 (if to-end
14155 (setq file-alist (append (delq x file-alist) (list x)))
14156 (setq file-alist (cons x (delq x file-alist))))
14157 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14158 (org-install-agenda-files-menu)
14159 (message "File %s to %s of agenda file list"
14160 (if had "moved" "added") (if to-end "end" "front"))))
14162 (defun org-remove-file (&optional file)
14163 "Remove current file from the list of files in variable `org-agenda-files'.
14164 These are the files which are being checked for agenda entries.
14165 Optional argument FILE means, use this file instead of the current."
14166 (interactive)
14167 (let* ((file (or file buffer-file-name))
14168 (true-file (file-truename file))
14169 (afile (abbreviate-file-name file))
14170 (files (delq nil (mapcar
14171 (lambda (x)
14172 (if (equal true-file
14173 (file-truename x))
14174 nil x))
14175 (org-agenda-files t)))))
14176 (if (not (= (length files) (length (org-agenda-files t))))
14177 (progn
14178 (org-store-new-agenda-file-list files)
14179 (org-install-agenda-files-menu)
14180 (message "Removed file: %s" afile))
14181 (message "File was not in list: %s" afile))))
14183 (defun org-file-menu-entry (file)
14184 (vector file (list 'find-file file) t))
14186 (defun org-check-agenda-file (file)
14187 "Make sure FILE exists. If not, ask user what to do."
14188 (when (not (file-exists-p file))
14189 (message "non-existent file %s. [R]emove from list or [A]bort?"
14190 (abbreviate-file-name file))
14191 (let ((r (downcase (read-char-exclusive))))
14192 (cond
14193 ((equal r ?r)
14194 (org-remove-file file)
14195 (throw 'nextfile t))
14196 (t (error "Abort"))))))
14198 ;;; Agenda prepare and finalize
14200 (defvar org-agenda-multi nil) ; dynammically scoped
14201 (defvar org-agenda-buffer-name "*Org Agenda*")
14202 (defvar org-pre-agenda-window-conf nil)
14203 (defun org-prepare-agenda ()
14204 (setq org-todo-keywords-for-agenda nil)
14205 (setq org-done-keywords-for-agenda nil)
14206 (if org-agenda-multi
14207 (progn
14208 (setq buffer-read-only nil)
14209 (goto-char (point-max))
14210 (unless (= (point) 1)
14211 (insert "\n" (make-string (window-width) ?=) "\n"))
14212 (narrow-to-region (point) (point-max)))
14213 (org-agenda-maybe-reset-markers 'force)
14214 (org-prepare-agenda-buffers (org-agenda-files))
14215 (setq org-todo-keywords-for-agenda
14216 (org-uniquify org-todo-keywords-for-agenda))
14217 (setq org-done-keywords-for-agenda
14218 (org-uniquify org-done-keywords-for-agenda))
14219 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
14220 (awin (get-buffer-window abuf)))
14221 (cond
14222 ((equal (current-buffer) abuf) nil)
14223 (awin (select-window awin))
14224 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
14225 ((equal org-agenda-window-setup 'current-window)
14226 (switch-to-buffer abuf))
14227 ((equal org-agenda-window-setup 'other-window)
14228 (switch-to-buffer-other-window abuf))
14229 ((equal org-agenda-window-setup 'other-frame)
14230 (switch-to-buffer-other-frame abuf))
14231 ((equal org-agenda-window-setup 'reorganize-frame)
14232 (delete-other-windows)
14233 (switch-to-buffer-other-window abuf))))
14234 (setq buffer-read-only nil)
14235 (erase-buffer)
14236 (org-agenda-mode))
14237 (setq buffer-read-only nil))
14239 (defun org-finalize-agenda ()
14240 "Finishing touch for the agenda buffer, called just before displaying it."
14241 (unless org-agenda-multi
14242 (org-agenda-align-tags)
14243 (save-excursion
14244 (let ((buffer-read-only))
14245 (goto-char (point-min))
14246 (while (org-activate-bracket-links (point-max))
14247 (add-text-properties (match-beginning 0) (match-end 0)
14248 '(face org-link))))
14249 (run-hooks 'org-finalize-agenda-hook))))
14251 (defun org-prepare-agenda-buffers (files)
14252 "Create buffers for all agenda files, protect archived trees and comments."
14253 (interactive)
14254 (let ((pa '(:org-archived t))
14255 (pc '(:org-comment t))
14256 (pall '(:org-archived t :org-comment t))
14257 (rea (concat ":" org-archive-tag ":"))
14258 bmp file re)
14259 (save-excursion
14260 (save-restriction
14261 (while (setq file (pop files))
14262 (org-check-agenda-file file)
14263 (set-buffer (org-get-agenda-file-buffer file))
14264 (widen)
14265 (setq bmp (buffer-modified-p))
14266 (setq org-todo-keywords-for-agenda
14267 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14268 (setq org-done-keywords-for-agenda
14269 (append org-done-keywords-for-agenda org-done-keywords))
14270 (save-excursion
14271 (remove-text-properties (point-min) (point-max) pall)
14272 (when org-agenda-skip-archived-trees
14273 (goto-char (point-min))
14274 (while (re-search-forward rea nil t)
14275 (if (org-on-heading-p t)
14276 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14277 (goto-char (point-min))
14278 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14279 (while (re-search-forward re nil t)
14280 (add-text-properties
14281 (match-beginning 0) (org-end-of-subtree t) pc)))
14282 (set-buffer-modified-p bmp))))))
14284 (defvar org-agenda-skip-function nil
14285 "Function to be called at each match during agenda construction.
14286 If this function return nil, the current match should not be skipped.
14287 Otherwise, the function must return a position from where the search
14288 should be continued.
14289 Never set this variable using `setq' or so, because then it will apply
14290 to all future agenda commands. Instead, bind it with `let' to scope
14291 it dynamically into the agenda-constructing command.")
14293 (defun org-agenda-skip ()
14294 "Throw to `:skip' in places that should be skipped.
14295 Also moves point to the end of the skipped region, so that search can
14296 continue from there."
14297 (let ((p (point-at-bol)) to)
14298 (and org-agenda-skip-archived-trees
14299 (get-text-property p :org-archived)
14300 (org-end-of-subtree t)
14301 (throw :skip t))
14302 (and (get-text-property p :org-comment)
14303 (org-end-of-subtree t)
14304 (throw :skip t))
14305 (if (equal (char-after p) ?#) (throw :skip t))
14306 (when (and (functionp org-agenda-skip-function)
14307 (setq to (save-excursion
14308 (save-match-data
14309 (funcall org-agenda-skip-function)))))
14310 (goto-char to)
14311 (throw :skip t))))
14313 (defvar org-agenda-markers nil
14314 "List of all currently active markers created by `org-agenda'.")
14315 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
14316 "Creation time of the last agenda marker.")
14318 (defun org-agenda-new-marker (&optional pos)
14319 "Return a new agenda marker.
14320 Org-mode keeps a list of these markers and resets them when they are
14321 no longer in use."
14322 (let ((m (copy-marker (or pos (point)))))
14323 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
14324 (push m org-agenda-markers)
14327 (defun org-agenda-maybe-reset-markers (&optional force)
14328 "Reset markers created by `org-agenda'. But only if they are old enough."
14329 (if (or (and force (not org-agenda-multi))
14330 (> (- (time-to-seconds (current-time))
14331 org-agenda-last-marker-time)
14333 (while org-agenda-markers
14334 (move-marker (pop org-agenda-markers) nil))))
14336 (defvar org-agenda-new-buffers nil
14337 "Buffers created to visit agenda files.")
14339 (defun org-get-agenda-file-buffer (file)
14340 "Get a buffer visiting FILE. If the buffer needs to be created, add
14341 it to the list of buffers which might be released later."
14342 (let ((buf (org-find-base-buffer-visiting file)))
14343 (if buf
14344 buf ; just return it
14345 ;; Make a new buffer and remember it
14346 (setq buf (find-file-noselect file))
14347 (if buf (push buf org-agenda-new-buffers))
14348 buf)))
14350 (defun org-release-buffers (blist)
14351 "Release all buffers in list, asking the user for confirmation when needed.
14352 When a buffer is unmodified, it is just killed. When modified, it is saved
14353 \(if the user agrees) and then killed."
14354 (let (buf file)
14355 (while (setq buf (pop blist))
14356 (setq file (buffer-file-name buf))
14357 (when (and (buffer-modified-p buf)
14358 file
14359 (y-or-n-p (format "Save file %s? " file)))
14360 (with-current-buffer buf (save-buffer)))
14361 (kill-buffer buf))))
14363 (defvar org-category-table nil)
14364 (defun org-get-category-table ()
14365 "Get the table of categories and positions in current buffer."
14366 (let (tbl)
14367 (save-excursion
14368 (save-restriction
14369 (widen)
14370 (goto-char (point-min))
14371 (while (re-search-forward "^#\\+CATEGORY:[ \t]*\\(.*\\)"
14372 nil t)
14373 (push (cons (match-beginning 1)
14374 (org-trim (match-string 1))) tbl))))
14375 tbl))
14377 (defun org-get-category (&optional pos)
14378 "Get the category applying to position POS."
14379 (if (not org-category-table)
14380 (cond
14381 ((null org-category)
14382 (setq org-category
14383 (if buffer-file-name
14384 (file-name-sans-extension
14385 (file-name-nondirectory buffer-file-name))
14386 "???")))
14387 ((symbolp org-category) (symbol-name org-category))
14388 (t org-category))
14389 (let ((tbl org-category-table)
14390 (pos (or pos (point))))
14391 (while (and tbl (> (caar tbl) pos))
14392 (pop tbl))
14393 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
14394 org-category-table))))))
14395 ;;; Agenda timeline
14397 (defun org-timeline (&optional include-all)
14398 "Show a time-sorted view of the entries in the current org file.
14399 Only entries with a time stamp of today or later will be listed. With
14400 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
14401 under the current date.
14402 If the buffer contains an active region, only check the region for
14403 dates."
14404 (interactive "P")
14405 (require 'calendar)
14406 (org-compile-prefix-format 'timeline)
14407 (org-set-sorting-strategy 'timeline)
14408 (let* ((dopast t)
14409 (dotodo include-all)
14410 (doclosed org-agenda-show-log)
14411 (entry buffer-file-name)
14412 (date (calendar-current-date))
14413 (beg (if (org-region-active-p) (region-beginning) (point-min)))
14414 (end (if (org-region-active-p) (region-end) (point-max)))
14415 (day-numbers (org-get-all-dates beg end 'no-ranges
14416 t doclosed ; always include today
14417 org-timeline-show-empty-dates))
14418 (today (time-to-days (current-time)))
14419 (past t)
14420 args
14421 s e rtn d emptyp)
14422 (setq org-agenda-redo-command
14423 (list 'progn
14424 (list 'switch-to-buffer-other-window (current-buffer))
14425 (list 'org-timeline (list 'quote include-all))))
14426 (if (not dopast)
14427 ;; Remove past dates from the list of dates.
14428 (setq day-numbers (delq nil (mapcar (lambda(x)
14429 (if (>= x today) x nil))
14430 day-numbers))))
14431 (org-prepare-agenda)
14432 (if doclosed (push :closed args))
14433 (push :timestamp args)
14434 (if dotodo (push :todo args))
14435 (while (setq d (pop day-numbers))
14436 (if (and (listp d) (eq (car d) :omitted))
14437 (progn
14438 (setq s (point))
14439 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
14440 (put-text-property s (1- (point)) 'face 'org-level-3))
14441 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
14442 (if (and (>= d today)
14443 dopast
14444 past)
14445 (progn
14446 (setq past nil)
14447 (insert (make-string 79 ?-) "\n")))
14448 (setq date (calendar-gregorian-from-absolute d))
14449 (setq s (point))
14450 (setq rtn (and (not emptyp)
14451 (apply 'org-agenda-get-day-entries
14452 entry date args)))
14453 (if (or rtn (equal d today) org-timeline-show-empty-dates)
14454 (progn
14455 (insert (calendar-day-name date) " "
14456 (number-to-string (extract-calendar-day date)) " "
14457 (calendar-month-name (extract-calendar-month date)) " "
14458 (number-to-string (extract-calendar-year date)) "\n")
14459 ; FIXME: this gives a timezone problem
14460 ; (insert (format-time-string org-agenda-date-format
14461 ; (calendar-time-from-absolute d 0))
14462 ; "\n")
14463 (put-text-property s (1- (point)) 'face 'org-level-3)
14464 (put-text-property s (1- (point)) 'org-date-line t)
14465 (if (equal d today)
14466 (put-text-property s (1- (point)) 'org-today t))
14467 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
14468 (put-text-property s (1- (point)) 'day d)))))
14469 (goto-char (point-min))
14470 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
14471 (point-min)))
14472 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
14473 (org-finalize-agenda)
14474 (setq buffer-read-only t)))
14476 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
14477 "Return a list of all relevant day numbers from BEG to END buffer positions.
14478 If NO-RANGES is non-nil, include only the start and end dates of a range,
14479 not every single day in the range. If FORCE-TODAY is non-nil, make
14480 sure that TODAY is included in the list. If INACTIVE is non-nil, also
14481 inactive time stamps (those in square brackets) are included.
14482 When EMPTY is non-nil, also include days without any entries."
14483 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
14484 dates dates1 date day day1 day2 ts1 ts2)
14485 (if force-today
14486 (setq dates (list (time-to-days (current-time)))))
14487 (save-excursion
14488 (goto-char beg)
14489 (while (re-search-forward re end t)
14490 (setq day (time-to-days (org-time-string-to-time
14491 (substring (match-string 1) 0 10))))
14492 (or (memq day dates) (push day dates)))
14493 (unless no-ranges
14494 (goto-char beg)
14495 (while (re-search-forward org-tr-regexp end t)
14496 (setq ts1 (substring (match-string 1) 0 10)
14497 ts2 (substring (match-string 2) 0 10)
14498 day1 (time-to-days (org-time-string-to-time ts1))
14499 day2 (time-to-days (org-time-string-to-time ts2)))
14500 (while (< (setq day1 (1+ day1)) day2)
14501 (or (memq day1 dates) (push day1 dates)))))
14502 (setq dates (sort dates '<))
14503 (when empty
14504 (while (setq day (pop dates))
14505 (setq day2 (car dates))
14506 (push day dates1)
14507 (when (and day2 empty)
14508 (if (or (eq empty t)
14509 (and (numberp empty) (<= (- day2 day) empty)))
14510 (while (< (setq day (1+ day)) day2)
14511 (push (list day) dates1))
14512 (push (cons :omitted (- day2 day)) dates1))))
14513 (setq dates (nreverse dates1)))
14514 dates)))
14516 ;;; Agenda Daily/Weekly
14518 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
14519 (defvar org-agenda-last-arguments nil
14520 "The arguments of the previous call to org-agenda")
14521 (defvar org-starting-day nil) ; local variable in the agenda buffer
14522 (defvar org-include-all-loc nil) ; local variable
14525 ;;;###autoload
14526 (defun org-agenda-list (&optional include-all start-day ndays)
14527 "Produce a weekly view from all files in variable `org-agenda-files'.
14528 The view will be for the current week, but from the overview buffer you
14529 will be able to go to other weeks.
14530 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
14531 also be shown, under the current date.
14532 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
14533 on the days are also shown. See the variable `org-log-done' for how
14534 to turn on logging.
14535 START-DAY defaults to TODAY, or to the most recent match for the weekday
14536 given in `org-agenda-start-on-weekday'.
14537 NDAYS defaults to `org-agenda-ndays'."
14538 (interactive "P")
14539 (if org-agenda-overriding-arguments
14540 (setq include-all (car org-agenda-overriding-arguments)
14541 start-day (nth 1 org-agenda-overriding-arguments)
14542 ndays (nth 2 org-agenda-overriding-arguments)))
14543 (setq org-agenda-last-arguments (list include-all start-day ndays))
14544 (org-compile-prefix-format 'agenda)
14545 (org-set-sorting-strategy 'agenda)
14546 (require 'calendar)
14547 (let* ((org-agenda-start-on-weekday
14548 (if (or (equal ndays 1)
14549 (and (null ndays) (equal 1 org-agenda-ndays)))
14550 nil org-agenda-start-on-weekday))
14551 (thefiles (org-agenda-files))
14552 (files thefiles)
14553 (today (time-to-days (current-time)))
14554 (sd (or start-day today))
14555 (start (if (or (null org-agenda-start-on-weekday)
14556 (< org-agenda-ndays 7))
14558 (let* ((nt (calendar-day-of-week
14559 (calendar-gregorian-from-absolute sd)))
14560 (n1 org-agenda-start-on-weekday)
14561 (d (- nt n1)))
14562 (- sd (+ (if (< d 0) 7 0) d)))))
14563 (day-numbers (list start))
14564 (inhibit-redisplay (not debug-on-error))
14565 s e rtn rtnall file date d start-pos end-pos todayp nd)
14566 (setq org-agenda-redo-command
14567 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
14568 ;; Make the list of days
14569 (setq ndays (or ndays org-agenda-ndays)
14570 nd ndays)
14571 (while (> ndays 1)
14572 (push (1+ (car day-numbers)) day-numbers)
14573 (setq ndays (1- ndays)))
14574 (setq day-numbers (nreverse day-numbers))
14575 (org-prepare-agenda)
14576 (org-set-local 'org-starting-day (car day-numbers))
14577 (org-set-local 'org-include-all-loc include-all)
14578 (when (and (or include-all org-agenda-include-all-todo)
14579 (member today day-numbers))
14580 (setq files thefiles
14581 rtnall nil)
14582 (while (setq file (pop files))
14583 (catch 'nextfile
14584 (org-check-agenda-file file)
14585 (setq date (calendar-gregorian-from-absolute today)
14586 rtn (org-agenda-get-day-entries
14587 file date :todo))
14588 (setq rtnall (append rtnall rtn))))
14589 (when rtnall
14590 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
14591 (add-text-properties (point-min) (1- (point))
14592 (list 'face 'org-level-3))
14593 (insert (org-finalize-agenda-entries rtnall) "\n")))
14594 (setq s (point))
14595 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
14596 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
14597 (while (setq d (pop day-numbers))
14598 (setq date (calendar-gregorian-from-absolute d)
14599 s (point))
14600 (if (or (setq todayp (= d today))
14601 (and (not start-pos) (= d sd)))
14602 (setq start-pos (point))
14603 (if (and start-pos (not end-pos))
14604 (setq end-pos (point))))
14605 (setq files thefiles
14606 rtnall nil)
14607 (while (setq file (pop files))
14608 (catch 'nextfile
14609 (org-check-agenda-file file)
14610 (if org-agenda-show-log
14611 (setq rtn (org-agenda-get-day-entries
14612 file date
14613 :deadline :scheduled :timestamp :closed))
14614 (setq rtn (org-agenda-get-day-entries
14615 file date
14616 :deadline :scheduled :timestamp)))
14617 (setq rtnall (append rtnall rtn))))
14618 (if org-agenda-include-diary
14619 (progn
14620 (require 'diary-lib)
14621 (setq rtn (org-get-entries-from-diary date))
14622 (setq rtnall (append rtnall rtn))))
14623 (if (or rtnall org-agenda-show-all-dates)
14624 (progn
14625 (insert (format "%-9s %2d %s %4d\n"
14626 (calendar-day-name date)
14627 (extract-calendar-day date)
14628 (calendar-month-name (extract-calendar-month date))
14629 (extract-calendar-year date)))
14630 ; FIXME: this gives a timezone problem
14631 ; (insert (format-time-string org-agenda-date-format
14632 ; (calendar-time-from-absolute d 0)) "\n")
14633 (put-text-property s (1- (point)) 'face 'org-level-3)
14634 (put-text-property s (1- (point)) 'org-date-line t)
14635 (if todayp (put-text-property s (1- (point)) 'org-today t))
14636 (if rtnall (insert
14637 (org-finalize-agenda-entries
14638 (org-agenda-add-time-grid-maybe
14639 rtnall nd todayp))
14640 "\n"))
14641 (put-text-property s (1- (point)) 'day d))))
14642 (goto-char (point-min))
14643 (org-fit-agenda-window)
14644 (unless (and (pos-visible-in-window-p (point-min))
14645 (pos-visible-in-window-p (point-max)))
14646 (goto-char (1- (point-max)))
14647 (recenter -1)
14648 (if (not (pos-visible-in-window-p (or start-pos 1)))
14649 (progn
14650 (goto-char (or start-pos 1))
14651 (recenter 1))))
14652 (goto-char (or start-pos 1))
14653 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
14654 (org-finalize-agenda)
14655 (setq buffer-read-only t)
14656 (message "")))
14658 ;;; Agenda TODO list
14660 (defvar org-select-this-todo-keyword nil)
14661 (defvar org-last-arg nil)
14663 ;;;###autoload
14664 (defun org-todo-list (arg)
14665 "Show all TODO entries from all agenda file in a single list.
14666 The prefix arg can be used to select a specific TODO keyword and limit
14667 the list to these. When using \\[universal-argument], you will be prompted
14668 for a keyword. A numeric prefix directly selects the Nth keyword in
14669 `org-todo-keywords-1'."
14670 (interactive "P")
14671 (require 'calendar)
14672 (org-compile-prefix-format 'todo)
14673 (org-set-sorting-strategy 'todo)
14674 (org-prepare-agenda)
14675 (let* ((today (time-to-days (current-time)))
14676 (date (calendar-gregorian-from-absolute today))
14677 (kwds org-todo-keywords-for-agenda)
14678 (completion-ignore-case t)
14679 (org-select-this-todo-keyword
14680 (if (stringp arg) arg
14681 (and arg (integerp arg) (> arg 0)
14682 (nth (1- arg) kwds))))
14683 rtn rtnall files file pos)
14684 (when (equal arg '(4))
14685 (setq org-select-this-todo-keyword
14686 (completing-read "Keyword (or KWD1|K2D2|...): "
14687 (mapcar 'list kwds) nil nil)))
14688 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
14689 (org-set-local 'org-last-arg arg)
14690 ;FIXME (org-set-local 'org-todo-keywords-for-agenda kwds)
14691 (setq org-agenda-redo-command
14692 '(org-todo-list (or current-prefix-arg org-last-arg)))
14693 (setq files (org-agenda-files)
14694 rtnall nil)
14695 (while (setq file (pop files))
14696 (catch 'nextfile
14697 (org-check-agenda-file file)
14698 (setq rtn (org-agenda-get-day-entries file date :todo))
14699 (setq rtnall (append rtnall rtn))))
14700 (if org-agenda-overriding-header
14701 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
14702 nil 'face 'org-level-3) "\n")
14703 (insert "Global list of TODO items of type: ")
14704 (add-text-properties (point-min) (1- (point))
14705 (list 'face 'org-level-3))
14706 (setq pos (point))
14707 (insert (or org-select-this-todo-keyword "ALL") "\n")
14708 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14709 (setq pos (point))
14710 (unless org-agenda-multi
14711 (insert "Available with `N r': (0)ALL")
14712 (let ((n 0) s)
14713 (mapc (lambda (x)
14714 (setq s (format "(%d)%s" (setq n (1+ n)) x))
14715 (if (> (+ (current-column) (string-width s) 1) (frame-width))
14716 (insert "\n "))
14717 (insert " " s))
14718 kwds))
14719 (insert "\n"))
14720 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14721 (when rtnall
14722 (insert (org-finalize-agenda-entries rtnall) "\n"))
14723 (goto-char (point-min))
14724 (org-fit-agenda-window)
14725 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
14726 (org-finalize-agenda)
14727 (setq buffer-read-only t)))
14729 ;;; Agenda tags match
14731 ;;;###autoload
14732 (defun org-tags-view (&optional todo-only match)
14733 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
14734 The prefix arg TODO-ONLY limits the search to TODO entries."
14735 (interactive "P")
14736 (org-compile-prefix-format 'tags)
14737 (org-set-sorting-strategy 'tags)
14738 (let* ((org-tags-match-list-sublevels
14739 (if todo-only t org-tags-match-list-sublevels))
14740 (completion-ignore-case t)
14741 rtn rtnall files file pos matcher
14742 buffer)
14743 (setq matcher (org-make-tags-matcher match)
14744 match (car matcher) matcher (cdr matcher))
14745 (org-prepare-agenda)
14746 (setq org-agenda-redo-command
14747 (list 'org-tags-view (list 'quote todo-only)
14748 (list 'if 'current-prefix-arg nil match)))
14749 (setq files (org-agenda-files)
14750 rtnall nil)
14751 (while (setq file (pop files))
14752 (catch 'nextfile
14753 (org-check-agenda-file file)
14754 (setq buffer (if (file-exists-p file)
14755 (org-get-agenda-file-buffer file)
14756 (error "No such file %s" file)))
14757 (if (not buffer)
14758 ;; If file does not exist, merror message to agenda
14759 (setq rtn (list
14760 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
14761 rtnall (append rtnall rtn))
14762 (with-current-buffer buffer
14763 (unless (org-mode-p)
14764 (error "Agenda file %s is not in `org-mode'" file))
14765 (setq org-category-table (org-get-category-table))
14766 (save-excursion
14767 (save-restriction
14768 (if org-agenda-restrict
14769 (narrow-to-region org-agenda-restrict-begin
14770 org-agenda-restrict-end)
14771 (widen))
14772 (setq rtn (org-scan-tags 'agenda matcher todo-only))
14773 (setq rtnall (append rtnall rtn))))))))
14774 (if org-agenda-overriding-header
14775 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
14776 nil 'face 'org-level-3) "\n")
14777 (insert "Headlines with TAGS match: ")
14778 (add-text-properties (point-min) (1- (point))
14779 (list 'face 'org-level-3))
14780 (setq pos (point))
14781 (insert match "\n")
14782 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
14783 (setq pos (point))
14784 (unless org-agenda-multi
14785 (insert "Press `C-u r' to search again with new search string\n"))
14786 (add-text-properties pos (1- (point)) (list 'face 'org-level-3)))
14787 (when rtnall
14788 (insert (org-finalize-agenda-entries rtnall) "\n"))
14789 (goto-char (point-min))
14790 (org-fit-agenda-window)
14791 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
14792 (org-finalize-agenda)
14793 (setq buffer-read-only t)))
14795 ;;; Agenda Finding stuck projects
14797 (defvar org-agenda-skip-regexp nil
14798 "Regular expression used in skipping subtrees for the agenda.
14799 This is basically a temporary global variable that can be set and then
14800 used by user-defined selections using `org-agenda-skip-function'.")
14802 (defvar org-agenda-overriding-header nil
14803 "When this is set during todo and tags searches, will replace header.")
14805 (defun org-agenda-skip-subtree-when-regexp-matches ()
14806 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
14807 If yes, it returns the end position of this tree, causing agenda commands
14808 to skip this subtree. This is a function that can be put into
14809 `org-agenda-skip-function' for the duration of a command."
14810 (save-match-data
14811 (let ((end (save-excursion (org-end-of-subtree t)))
14812 skip)
14813 (save-excursion
14814 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
14815 (and skip end))))
14817 (defun org-agenda-list-stuck-projects (&rest ignore)
14818 "Create agenda view for projects that are stuck.
14819 Stuck projects are project that have no next actions. For the definitions
14820 of what a project is and how to check if it stuck, customize the variable
14821 `org-stuck-projects'.
14822 MATCH is being ignored."
14823 (interactive)
14824 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
14825 (org-agenda-overriding-header "List of stuck projects: ")
14826 (matcher (nth 0 org-stuck-projects))
14827 (todo (nth 1 org-stuck-projects))
14828 (todo-wds (if (member "*" todo)
14829 (progn
14830 (org-prepare-agenda-buffers (org-agenda-files))
14831 (org-delete-all
14832 org-done-keywords-for-agenda
14833 (copy-sequence org-todo-keywords-for-agenda)))
14834 todo))
14835 (todo-re (concat "^\\*+[ \t]+\\("
14836 (mapconcat 'identity todo-wds "\\|")
14837 "\\)\\>"))
14838 (tags (nth 2 org-stuck-projects))
14839 (tags-re (if (member "*" tags)
14840 "^\\*+.*:[a-zA-Z0-9_@]+:[ \t]*$"
14841 (concat "^\\*+.*:\\("
14842 (mapconcat 'identity tags "\\|")
14843 "\\):[a-zA-Z0-9_@:]*[ \t]*$")))
14844 (gen-re (nth 3 org-stuck-projects))
14845 (re-list
14846 (delq nil
14847 (list
14848 (if todo todo-re)
14849 (if tags tags-re)
14850 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
14851 gen-re)))))
14852 (setq org-agenda-skip-regexp
14853 (if re-list
14854 (mapconcat 'identity re-list "\\|")
14855 (error "No information how to identify unstuck projects")))
14856 (org-tags-view nil matcher)
14857 (with-current-buffer org-agenda-buffer-name
14858 (setq org-agenda-redo-command
14859 '(org-agenda-list-stuck-projects
14860 (or current-prefix-arg org-last-arg))))))
14862 ;;; Diary integration
14864 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
14866 (defun org-get-entries-from-diary (date)
14867 "Get the (Emacs Calendar) diary entries for DATE."
14868 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
14869 (diary-display-hook '(fancy-diary-display))
14870 (list-diary-entries-hook
14871 (cons 'org-diary-default-entry list-diary-entries-hook))
14872 (diary-file-name-prefix-function nil) ; turn this feature off
14873 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
14874 entries
14875 (org-disable-agenda-to-diary t))
14876 (save-excursion
14877 (save-window-excursion
14878 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
14879 (if (not (get-buffer fancy-diary-buffer))
14880 (setq entries nil)
14881 (with-current-buffer fancy-diary-buffer
14882 (setq buffer-read-only nil)
14883 (if (= (point-max) 1)
14884 ;; No entries
14885 (setq entries nil)
14886 ;; Omit the date and other unnecessary stuff
14887 (org-agenda-cleanup-fancy-diary)
14888 ;; Add prefix to each line and extend the text properties
14889 (if (= (point-max) 1)
14890 (setq entries nil)
14891 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
14892 (set-buffer-modified-p nil)
14893 (kill-buffer fancy-diary-buffer)))
14894 (when entries
14895 (setq entries (org-split-string entries "\n"))
14896 (setq entries
14897 (mapcar
14898 (lambda (x)
14899 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
14900 ;; Extend the text properties to the beginning of the line
14901 (org-add-props x (text-properties-at (1- (length x)) x)))
14902 entries)))))
14904 (defun org-agenda-cleanup-fancy-diary ()
14905 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
14906 This gets rid of the date, the underline under the date, and
14907 the dummy entry installed by `org-mode' to ensure non-empty diary for each
14908 date. It also removes lines that contain only whitespace."
14909 (goto-char (point-min))
14910 (if (looking-at ".*?:[ \t]*")
14911 (progn
14912 (replace-match "")
14913 (re-search-forward "\n=+$" nil t)
14914 (replace-match "")
14915 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
14916 (re-search-forward "\n=+$" nil t)
14917 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
14918 (goto-char (point-min))
14919 (while (re-search-forward "^ +\n" nil t)
14920 (replace-match ""))
14921 (goto-char (point-min))
14922 (if (re-search-forward "^Org-mode dummy\n?" nil t)
14923 (replace-match "")))
14925 ;; Make sure entries from the diary have the right text properties.
14926 (eval-after-load "diary-lib"
14927 '(if (boundp 'diary-modify-entry-list-string-function)
14928 ;; We can rely on the hook, nothing to do
14930 ;; Hook not avaiable, must use advice to make this work
14931 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
14932 "Make the position visible."
14933 (if (and org-disable-agenda-to-diary ;; called from org-agenda
14934 (stringp string)
14935 buffer-file-name)
14936 (setq string (org-modify-diary-entry-string string))))))
14938 (defun org-modify-diary-entry-string (string)
14939 "Add text properties to string, allowing org-mode to act on it."
14940 (org-add-props string nil
14941 'mouse-face 'highlight
14942 'keymap org-agenda-keymap
14943 'help-echo (format "mouse-2 or RET jump to diary file %s"
14944 (abbreviate-file-name buffer-file-name))
14945 'org-agenda-diary-link t
14946 'org-marker (org-agenda-new-marker (point-at-bol))))
14948 (defun org-diary-default-entry ()
14949 "Add a dummy entry to the diary.
14950 Needed to avoid empty dates which mess up holiday display."
14951 ;; Catch the error if dealing with the new add-to-diary-alist
14952 (when org-disable-agenda-to-diary
14953 (condition-case nil
14954 (add-to-diary-list original-date "Org-mode dummy" "")
14955 (error
14956 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
14958 ;;;###autoload
14959 (defun org-diary (&rest args)
14960 "Return diary information from org-files.
14961 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
14962 It accesses org files and extracts information from those files to be
14963 listed in the diary. The function accepts arguments specifying what
14964 items should be listed. The following arguments are allowed:
14966 :timestamp List the headlines of items containing a date stamp or
14967 date range matching the selected date. Deadlines will
14968 also be listed, on the expiration day.
14970 :deadline List any deadlines past due, or due within
14971 `org-deadline-warning-days'. The listing occurs only
14972 in the diary for *today*, not at any other date. If
14973 an entry is marked DONE, it is no longer listed.
14975 :scheduled List all items which are scheduled for the given date.
14976 The diary for *today* also contains items which were
14977 scheduled earlier and are not yet marked DONE.
14979 :todo List all TODO items from the org-file. This may be a
14980 long list - so this is not turned on by default.
14981 Like deadlines, these entries only show up in the
14982 diary for *today*, not at any other date.
14984 The call in the diary file should look like this:
14986 &%%(org-diary) ~/path/to/some/orgfile.org
14988 Use a separate line for each org file to check. Or, if you omit the file name,
14989 all files listed in `org-agenda-files' will be checked automatically:
14991 &%%(org-diary)
14993 If you don't give any arguments (as in the example above), the default
14994 arguments (:deadline :scheduled :timestamp) are used. So the example above may
14995 also be written as
14997 &%%(org-diary :deadline :timestamp :scheduled)
14999 The function expects the lisp variables `entry' and `date' to be provided
15000 by the caller, because this is how the calendar works. Don't use this
15001 function from a program - use `org-agenda-get-day-entries' instead."
15002 (org-agenda-maybe-reset-markers)
15003 (org-compile-prefix-format 'agenda)
15004 (org-set-sorting-strategy 'agenda)
15005 (setq args (or args '(:deadline :scheduled :timestamp)))
15006 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
15007 (list entry)
15008 (org-agenda-files t)))
15009 file rtn results)
15010 ;; If this is called during org-agenda, don't return any entries to
15011 ;; the calendar. Org Agenda will list these entries itself.
15012 (if org-disable-agenda-to-diary (setq files nil))
15013 (while (setq file (pop files))
15014 (setq rtn (apply 'org-agenda-get-day-entries file date args))
15015 (setq results (append results rtn)))
15016 (if results
15017 (concat (org-finalize-agenda-entries results) "\n"))))
15019 ;;; Agenda entry finders
15021 (defun org-agenda-get-day-entries (file date &rest args)
15022 "Does the work for `org-diary' and `org-agenda'.
15023 FILE is the path to a file to be checked for entries. DATE is date like
15024 the one returned by `calendar-current-date'. ARGS are symbols indicating
15025 which kind of entries should be extracted. For details about these, see
15026 the documentation of `org-diary'."
15027 (setq args (or args '(:deadline :scheduled :timestamp)))
15028 (let* ((org-startup-folded nil)
15029 (org-startup-align-all-tables nil)
15030 (buffer (if (file-exists-p file)
15031 (org-get-agenda-file-buffer file)
15032 (error "No such file %s" file)))
15033 arg results rtn)
15034 (if (not buffer)
15035 ;; If file does not exist, make sure an error message ends up in diary
15036 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
15037 (with-current-buffer buffer
15038 (unless (org-mode-p)
15039 (error "Agenda file %s is not in `org-mode'" file))
15040 (setq org-category-table (org-get-category-table))
15041 (let ((case-fold-search nil))
15042 (save-excursion
15043 (save-restriction
15044 (if org-agenda-restrict
15045 (narrow-to-region org-agenda-restrict-begin
15046 org-agenda-restrict-end)
15047 (widen))
15048 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
15049 (while (setq arg (pop args))
15050 (cond
15051 ((and (eq arg :todo)
15052 (equal date (calendar-current-date)))
15053 (setq rtn (org-agenda-get-todos))
15054 (setq results (append results rtn)))
15055 ((eq arg :timestamp)
15056 (setq rtn (org-agenda-get-blocks))
15057 (setq results (append results rtn))
15058 (setq rtn (org-agenda-get-timestamps))
15059 (setq results (append results rtn)))
15060 ((eq arg :scheduled)
15061 (setq rtn (org-agenda-get-scheduled))
15062 (setq results (append results rtn)))
15063 ((eq arg :closed)
15064 (setq rtn (org-agenda-get-closed))
15065 (setq results (append results rtn)))
15066 ((and (eq arg :deadline)
15067 (equal date (calendar-current-date)))
15068 (setq rtn (org-agenda-get-deadlines))
15069 (setq results (append results rtn))))))))
15070 results))))
15072 (defun org-entry-is-done-p ()
15073 "Is the current entry marked DONE?"
15074 (save-excursion
15075 (and (re-search-backward "[\r\n]\\*" nil t)
15076 (looking-at org-nl-done-regexp))))
15078 (defun org-at-date-range-p (&optional inactive-ok)
15079 "Is the cursor inside a date range?"
15080 (interactive)
15081 (save-excursion
15082 (catch 'exit
15083 (let ((pos (point)))
15084 (skip-chars-backward "^[<\r\n")
15085 (skip-chars-backward "<[")
15086 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
15087 (>= (match-end 0) pos)
15088 (throw 'exit t))
15089 (skip-chars-backward "^<[\r\n")
15090 (skip-chars-backward "<[")
15091 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
15092 (>= (match-end 0) pos)
15093 (throw 'exit t)))
15094 nil)))
15096 (defun org-agenda-get-todos ()
15097 "Return the TODO information for agenda display."
15098 (let* ((props (list 'face nil
15099 'done-face 'org-done
15100 'org-not-done-regexp org-not-done-regexp
15101 'mouse-face 'highlight
15102 'keymap org-agenda-keymap
15103 'help-echo
15104 (format "mouse-2 or RET jump to org file %s"
15105 (abbreviate-file-name buffer-file-name))))
15106 ;; FIXME: get rid of the \n at some point but watch out
15107 (regexp (concat "[\n\r]\\*+ *\\("
15108 (if org-select-this-todo-keyword
15109 (concat "\\<\\("
15110 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
15111 "\\)\\>")
15112 org-not-done-regexp)
15113 "[^\n\r]*\\)"))
15114 marker priority category tags
15115 ee txt beg end)
15116 (goto-char (point-min))
15117 (while (re-search-forward regexp nil t)
15118 (catch :skip
15119 (save-match-data
15120 (beginning-of-line)
15121 (setq beg (point) end (progn (outline-next-heading) (point)))
15122 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
15123 (re-search-forward org-scheduled-time-regexp end t))
15124 (and org-agenda-todo-ignore-deadlines (goto-char beg)
15125 (re-search-forward org-deadline-time-regexp end t)
15126 (org-deadline-close (match-string 1))))
15127 (goto-char beg)
15128 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
15129 (throw :skip nil)))
15130 (goto-char beg)
15131 (org-agenda-skip)
15132 (goto-char (match-beginning 1))
15133 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
15134 category (org-get-category)
15135 tags (org-get-tags-at (point))
15136 txt (org-format-agenda-item "" (match-string 1) category tags)
15137 priority (1+ (org-get-priority txt)))
15138 (org-add-props txt props
15139 'org-marker marker 'org-hd-marker marker
15140 'priority priority 'org-category category)
15141 (push txt ee)
15142 (if org-agenda-todo-list-sublevels
15143 (goto-char (match-end 1))
15144 (org-end-of-subtree 'invisible))))
15145 (nreverse ee)))
15147 (defconst org-agenda-no-heading-message
15148 "No heading for this item in buffer or region.")
15150 (defun org-agenda-get-timestamps ()
15151 "Return the date stamp information for agenda display."
15152 (let* ((props (list 'face nil
15153 'org-not-done-regexp org-not-done-regexp
15154 'mouse-face 'highlight
15155 'keymap org-agenda-keymap
15156 'help-echo
15157 (format "mouse-2 or RET jump to org file %s"
15158 (abbreviate-file-name buffer-file-name))))
15159 (regexp (regexp-quote
15160 (substring
15161 (format-time-string
15162 (car org-time-stamp-formats)
15163 (apply 'encode-time ; DATE bound by calendar
15164 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
15165 0 11)))
15166 marker hdmarker deadlinep scheduledp donep tmp priority category
15167 ee txt timestr tags)
15168 (goto-char (point-min))
15169 (while (re-search-forward regexp nil t)
15170 (catch :skip
15171 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
15172 (org-agenda-skip)
15173 (setq marker (org-agenda-new-marker (match-beginning 0))
15174 category (org-get-category (match-beginning 0))
15175 tmp (buffer-substring (max (point-min)
15176 (- (match-beginning 0)
15177 org-ds-keyword-length))
15178 (match-beginning 0))
15179 timestr (buffer-substring (match-beginning 0) (point-at-eol))
15180 deadlinep (string-match org-deadline-regexp tmp)
15181 scheduledp (string-match org-scheduled-regexp tmp)
15182 donep (org-entry-is-done-p))
15183 (and org-agenda-skip-scheduled-if-done
15184 scheduledp donep
15185 (throw :skip t))
15186 (if (string-match ">" timestr)
15187 ;; substring should only run to end of time stamp
15188 (setq timestr (substring timestr 0 (match-end 0))))
15189 (save-excursion
15190 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
15191 (progn
15192 (goto-char (match-end 1))
15193 (setq hdmarker (org-agenda-new-marker)
15194 tags (org-get-tags-at))
15195 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
15196 (setq txt (org-format-agenda-item
15197 (format "%s%s"
15198 (if deadlinep "Deadline: " "")
15199 (if scheduledp "Scheduled: " ""))
15200 (match-string 1) category tags timestr)))
15201 (setq txt org-agenda-no-heading-message))
15202 (setq priority (org-get-priority txt))
15203 (org-add-props txt props
15204 'org-marker marker 'org-hd-marker hdmarker)
15205 (if deadlinep
15206 (org-add-props txt nil
15207 'face (if donep 'org-done 'org-warning)
15208 'undone-face 'org-warning 'done-face 'org-done
15209 'org-category category 'priority (+ 100 priority))
15210 (if scheduledp
15211 (org-add-props txt nil
15212 'face 'org-scheduled-today
15213 'undone-face 'org-scheduled-today 'done-face 'org-done
15214 'org-category category 'priority (+ 99 priority))
15215 (org-add-props txt nil 'priority priority 'org-category category)))
15216 (push txt ee))
15217 (outline-next-heading)))
15218 (nreverse ee)))
15220 (defun org-agenda-get-closed ()
15221 "Return the logged TODO entries for agenda display."
15222 (let* ((props (list 'mouse-face 'highlight
15223 'org-not-done-regexp org-not-done-regexp
15224 'keymap org-agenda-keymap
15225 'help-echo
15226 (format "mouse-2 or RET jump to org file %s"
15227 (abbreviate-file-name buffer-file-name))))
15228 (regexp (concat
15229 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
15230 (regexp-quote
15231 (substring
15232 (format-time-string
15233 (car org-time-stamp-formats)
15234 (apply 'encode-time ; DATE bound by calendar
15235 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
15236 1 11))))
15237 marker hdmarker priority category tags closedp
15238 ee txt timestr)
15239 (goto-char (point-min))
15240 (while (re-search-forward regexp nil t)
15241 (catch :skip
15242 (org-agenda-skip)
15243 (setq marker (org-agenda-new-marker (match-beginning 0))
15244 closedp (equal (match-string 1) org-closed-string)
15245 category (org-get-category (match-beginning 0))
15246 timestr (buffer-substring (match-beginning 0) (point-at-eol))
15247 ;; donep (org-entry-is-done-p)
15249 (if (string-match "\\]" timestr)
15250 ;; substring should only run to end of time stamp
15251 (setq timestr (substring timestr 0 (match-end 0))))
15252 (save-excursion
15253 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
15254 (progn
15255 (goto-char (match-end 1))
15256 (setq hdmarker (org-agenda-new-marker)
15257 tags (org-get-tags-at))
15258 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
15259 (setq txt (org-format-agenda-item
15260 (if closedp "Closed: " "Clocked: ")
15261 (match-string 1) category tags timestr)))
15262 (setq txt org-agenda-no-heading-message))
15263 (setq priority 100000)
15264 (org-add-props txt props
15265 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
15266 'priority priority 'org-category category
15267 'undone-face 'org-warning 'done-face 'org-done)
15268 (push txt ee))
15269 (outline-next-heading)))
15270 (nreverse ee)))
15272 (defun org-agenda-get-deadlines ()
15273 "Return the deadline information for agenda display."
15274 (let* ((wdays org-deadline-warning-days)
15275 (props (list 'mouse-face 'highlight
15276 'org-not-done-regexp org-not-done-regexp
15277 'keymap org-agenda-keymap
15278 'help-echo
15279 (format "mouse-2 or RET jump to org file %s"
15280 (abbreviate-file-name buffer-file-name))))
15281 (regexp org-deadline-time-regexp)
15282 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
15283 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
15284 d2 diff pos pos1 category tags
15285 ee txt head face)
15286 (goto-char (point-min))
15287 (while (re-search-forward regexp nil t)
15288 (catch :skip
15289 (org-agenda-skip)
15290 (setq pos (1- (match-beginning 1))
15291 d2 (time-to-days
15292 (org-time-string-to-time (match-string 1)))
15293 diff (- d2 d1))
15294 ;; When to show a deadline in the calendar:
15295 ;; If the expiration is within wdays warning time.
15296 ;; Past-due deadlines are only shown on the current date
15297 (if (and (< diff wdays) todayp (not (= diff 0)))
15298 (save-excursion
15299 (setq category (org-get-category))
15300 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
15301 (progn
15302 (goto-char (match-end 0))
15303 (setq pos1 (match-end 1))
15304 (setq tags (org-get-tags-at pos1))
15305 (setq head (buffer-substring-no-properties
15306 (point)
15307 (progn (skip-chars-forward "^\r\n")
15308 (point))))
15309 (if (string-match org-looking-at-done-regexp head)
15310 (setq txt nil)
15311 (setq txt (org-format-agenda-item
15312 (format "In %3d d.: " diff) head category tags))))
15313 (setq txt org-agenda-no-heading-message))
15314 (when txt
15315 (setq face (cond ((<= diff 0) 'org-warning)
15316 ((<= diff 5) 'org-upcoming-deadline)
15317 (t nil)))
15318 (org-add-props txt props
15319 'org-marker (org-agenda-new-marker pos)
15320 'org-hd-marker (org-agenda-new-marker pos1)
15321 'priority (+ (- 10 diff) (org-get-priority txt))
15322 'org-category category
15323 'face face 'undone-face face 'done-face 'org-done)
15324 (push txt ee))))))
15325 ee))
15327 (defun org-agenda-get-scheduled ()
15328 "Return the scheduled information for agenda display."
15329 (let* ((props (list 'face 'org-scheduled-previously
15330 'org-not-done-regexp org-not-done-regexp
15331 'undone-face 'org-scheduled-previously
15332 'done-face 'org-done
15333 'mouse-face 'highlight
15334 'keymap org-agenda-keymap
15335 'help-echo
15336 (format "mouse-2 or RET jump to org file %s"
15337 (abbreviate-file-name buffer-file-name))))
15338 (regexp org-scheduled-time-regexp)
15339 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
15340 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
15341 d2 diff pos pos1 category tags
15342 ee txt head)
15343 (goto-char (point-min))
15344 (while (re-search-forward regexp nil t)
15345 (catch :skip
15346 (org-agenda-skip)
15347 (setq pos (1- (match-beginning 1))
15348 d2 (time-to-days
15349 (org-time-string-to-time (match-string 1)))
15350 diff (- d2 d1))
15351 ;; When to show a scheduled item in the calendar:
15352 ;; If it is on or past the date.
15353 (if (and (< diff 0) todayp)
15354 (save-excursion
15355 (setq category (org-get-category))
15356 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
15357 (progn
15358 (goto-char (match-end 0))
15359 (setq pos1 (match-end 1))
15360 (setq tags (org-get-tags-at))
15361 (setq head (buffer-substring-no-properties
15362 (point)
15363 (progn (skip-chars-forward "^\r\n") (point))))
15364 (if (string-match org-looking-at-done-regexp head)
15365 (setq txt nil)
15366 (setq txt (org-format-agenda-item
15367 (format "Sched.%2dx: " (- 1 diff)) head
15368 category tags))))
15369 (setq txt org-agenda-no-heading-message))
15370 (when txt
15371 (org-add-props txt props
15372 'org-marker (org-agenda-new-marker pos)
15373 'org-hd-marker (org-agenda-new-marker pos1)
15374 'priority (+ (- 5 diff) (org-get-priority txt))
15375 'org-category category)
15376 (push txt ee))))))
15377 ee))
15379 (defun org-agenda-get-blocks ()
15380 "Return the date-range information for agenda display."
15381 (let* ((props (list 'face nil
15382 'org-not-done-regexp org-not-done-regexp
15383 'mouse-face 'highlight
15384 'keymap org-agenda-keymap
15385 'help-echo
15386 (format "mouse-2 or RET jump to org file %s"
15387 (abbreviate-file-name buffer-file-name))))
15388 (regexp org-tr-regexp)
15389 (d0 (calendar-absolute-from-gregorian date))
15390 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
15391 (goto-char (point-min))
15392 (while (re-search-forward regexp nil t)
15393 (catch :skip
15394 (org-agenda-skip)
15395 (setq pos (point))
15396 (setq timestr (match-string 0)
15397 s1 (match-string 1)
15398 s2 (match-string 2)
15399 d1 (time-to-days (org-time-string-to-time s1))
15400 d2 (time-to-days (org-time-string-to-time s2)))
15401 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
15402 ;; Only allow days between the limits, because the normal
15403 ;; date stamps will catch the limits.
15404 (save-excursion
15405 (setq marker (org-agenda-new-marker (point)))
15406 (setq category (org-get-category))
15407 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
15408 (progn
15409 (setq hdmarker (org-agenda-new-marker (match-end 1)))
15410 (goto-char (match-end 1))
15411 (setq tags (org-get-tags-at))
15412 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
15413 (setq txt (org-format-agenda-item
15414 (format (if (= d1 d2) "" "(%d/%d): ")
15415 (1+ (- d0 d1)) (1+ (- d2 d1)))
15416 (match-string 1) category tags
15417 (if (= d0 d1) timestr))))
15418 (setq txt org-agenda-no-heading-message))
15419 (org-add-props txt props
15420 'org-marker marker 'org-hd-marker hdmarker
15421 'priority (org-get-priority txt) 'org-category category)
15422 (push txt ee)))
15423 (goto-char pos)))
15424 ;; Sort the entries by expiration date.
15425 (nreverse ee)))
15427 ;;; Agenda presentation and sorting
15429 ;; FIXME: should I allow spaces around the dash?
15430 (defconst org-plain-time-of-day-regexp
15431 (concat
15432 "\\(\\<[012]?[0-9]"
15433 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
15434 "\\(--?"
15435 "\\(\\<[012]?[0-9]"
15436 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
15437 "\\)?")
15438 "Regular expression to match a plain time or time range.
15439 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
15440 groups carry important information:
15441 0 the full match
15442 1 the first time, range or not
15443 8 the second time, if it is a range.")
15445 (defconst org-stamp-time-of-day-regexp
15446 (concat
15447 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
15448 "\\([012][0-9]:[0-5][0-9]\\)>"
15449 "\\(--?"
15450 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
15451 "Regular expression to match a timestamp time or time range.
15452 After a match, the following groups carry important information:
15453 0 the full match
15454 1 date plus weekday, for backreferencing to make sure both times on same day
15455 2 the first time, range or not
15456 4 the second time, if it is a range.")
15458 (defvar org-prefix-has-time nil
15459 "A flag, set by `org-compile-prefix-format'.
15460 The flag is set if the currently compiled format contains a `%t'.")
15461 (defvar org-prefix-has-tag nil
15462 "A flag, set by `org-compile-prefix-format'.
15463 The flag is set if the currently compiled format contains a `%T'.")
15465 (defun org-format-agenda-item (extra txt &optional category tags dotime
15466 noprefix)
15467 "Format TXT to be inserted into the agenda buffer.
15468 In particular, it adds the prefix and corresponding text properties. EXTRA
15469 must be a string and replaces the `%s' specifier in the prefix format.
15470 CATEGORY (string, symbol or nil) may be used to overrule the default
15471 category taken from local variable or file name. It will replace the `%c'
15472 specifier in the format. DOTIME, when non-nil, indicates that a
15473 time-of-day should be extracted from TXT for sorting of this entry, and for
15474 the `%t' specifier in the format. When DOTIME is a string, this string is
15475 searched for a time before TXT is. NOPREFIX is a flag and indicates that
15476 only the correctly processes TXT should be returned - this is used by
15477 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
15478 (save-match-data
15479 ;; Diary entries sometimes have extra whitespace at the beginning
15480 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
15481 (let* ((category (or category
15482 org-category
15483 (if buffer-file-name
15484 (file-name-sans-extension
15485 (file-name-nondirectory buffer-file-name))
15486 "")))
15487 (tag (if tags (nth (1- (length tags)) tags) ""))
15488 time ; time and tag are needed for the eval of the prefix format
15489 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
15490 (time-of-day (and dotime (org-get-time-of-day ts)))
15491 stamp plain s0 s1 s2 rtn)
15492 (when (and dotime time-of-day org-prefix-has-time)
15493 ;; Extract starting and ending time and move them to prefix
15494 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
15495 (setq plain (string-match org-plain-time-of-day-regexp ts)))
15496 (setq s0 (match-string 0 ts)
15497 s1 (match-string (if plain 1 2) ts)
15498 s2 (match-string (if plain 8 4) ts))
15500 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
15501 ;; them, we might want to remove them there to avoid duplication.
15502 ;; The user can turn this off with a variable.
15503 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
15504 (string-match (concat (regexp-quote s0) " *") txt)
15505 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
15506 (= (match-beginning 0) 0)
15508 (setq txt (replace-match "" nil nil txt))))
15509 ;; Normalize the time(s) to 24 hour
15510 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
15511 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
15513 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
15514 ;; Tags are in the string
15515 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
15516 (and org-agenda-remove-tags-when-in-prefix
15517 org-prefix-has-tag))
15518 (setq txt (replace-match "" t t txt))
15519 (setq txt (replace-match
15520 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
15521 (match-string 2 txt))
15522 t t txt))))
15524 ;; Create the final string
15525 (if noprefix
15526 (setq rtn txt)
15527 ;; Prepare the variables needed in the eval of the compiled format
15528 (setq time (cond (s2 (concat s1 "-" s2))
15529 (s1 (concat s1 "......"))
15530 (t ""))
15531 extra (or extra "")
15532 category (if (symbolp category) (symbol-name category) category))
15533 ;; Evaluate the compiled format
15534 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
15536 ;; And finally add the text properties
15537 (org-add-props rtn nil
15538 'org-category (downcase category) 'tags tags
15539 'prefix-length (- (length rtn) (length txt))
15540 'time-of-day time-of-day
15541 'dotime dotime))))
15543 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
15544 (defvar org-agenda-sorting-strategy-selected nil)
15546 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
15547 (catch 'exit
15548 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
15549 ((and todayp (member 'today (car org-agenda-time-grid))))
15550 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
15551 ((member 'weekly (car org-agenda-time-grid)))
15552 (t (throw 'exit list)))
15553 (let* ((have (delq nil (mapcar
15554 (lambda (x) (get-text-property 1 'time-of-day x))
15555 list)))
15556 (string (nth 1 org-agenda-time-grid))
15557 (gridtimes (nth 2 org-agenda-time-grid))
15558 (req (car org-agenda-time-grid))
15559 (remove (member 'remove-match req))
15560 new time)
15561 (if (and (member 'require-timed req) (not have))
15562 ;; don't show empty grid
15563 (throw 'exit list))
15564 (while (setq time (pop gridtimes))
15565 (unless (and remove (member time have))
15566 (setq time (int-to-string time))
15567 (push (org-format-agenda-item
15568 nil string "" nil
15569 (concat (substring time 0 -2) ":" (substring time -2)))
15570 new)
15571 (put-text-property
15572 1 (length (car new)) 'face 'org-time-grid (car new))))
15573 (if (member 'time-up org-agenda-sorting-strategy-selected)
15574 (append new list)
15575 (append list new)))))
15577 (defun org-compile-prefix-format (key)
15578 "Compile the prefix format into a Lisp form that can be evaluated.
15579 The resulting form is returned and stored in the variable
15580 `org-prefix-format-compiled'."
15581 (setq org-prefix-has-time nil org-prefix-has-tag nil)
15582 (let ((s (cond
15583 ((stringp org-agenda-prefix-format)
15584 org-agenda-prefix-format)
15585 ((assq key org-agenda-prefix-format)
15586 (cdr (assq key org-agenda-prefix-format)))
15587 (t " %-12:c%?-12t% s")))
15588 (start 0)
15589 varform vars var e c f opt)
15590 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
15591 s start)
15592 (setq var (cdr (assoc (match-string 4 s)
15593 '(("c" . category) ("t" . time) ("s" . extra)
15594 ("T" . tag))))
15595 c (or (match-string 3 s) "")
15596 opt (match-beginning 1)
15597 start (1+ (match-beginning 0)))
15598 (if (equal var 'time) (setq org-prefix-has-time t))
15599 (if (equal var 'tag) (setq org-prefix-has-tag t))
15600 (setq f (concat "%" (match-string 2 s) "s"))
15601 (if opt
15602 (setq varform
15603 `(if (equal "" ,var)
15605 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
15606 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
15607 (setq s (replace-match "%s" t nil s))
15608 (push varform vars))
15609 (setq vars (nreverse vars))
15610 (setq org-prefix-format-compiled `(format ,s ,@vars))))
15612 (defun org-set-sorting-strategy (key)
15613 (if (symbolp (car org-agenda-sorting-strategy))
15614 ;; the old format
15615 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
15616 (setq org-agenda-sorting-strategy-selected
15617 (or (cdr (assq key org-agenda-sorting-strategy))
15618 (cdr (assq 'agenda org-agenda-sorting-strategy))
15619 '(time-up category-keep priority-down)))))
15621 (defun org-get-time-of-day (s &optional string mod24)
15622 "Check string S for a time of day.
15623 If found, return it as a military time number between 0 and 2400.
15624 If not found, return nil.
15625 The optional STRING argument forces conversion into a 5 character wide string
15626 HH:MM."
15627 (save-match-data
15628 (when
15630 (string-match
15631 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
15632 (string-match
15633 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
15634 (let* ((h (string-to-number (match-string 1 s)))
15635 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
15636 (ampm (if (match-end 4) (downcase (match-string 4 s))))
15637 (am-p (equal ampm "am"))
15638 (h1 (cond ((not ampm) h)
15639 ((= h 12) (if am-p 0 12))
15640 (t (+ h (if am-p 0 12)))))
15641 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
15642 (mod h1 24) h1))
15643 (t0 (+ (* 100 h2) m))
15644 (t1 (concat (if (>= h1 24) "+" " ")
15645 (if (< t0 100) "0" "")
15646 (if (< t0 10) "0" "")
15647 (int-to-string t0))))
15648 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
15650 (defun org-finalize-agenda-entries (list &optional nosort)
15651 "Sort and concatenate the agenda items."
15652 (setq list (mapcar 'org-agenda-highlight-todo list))
15653 (if nosort
15654 list
15655 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
15657 (defun org-agenda-highlight-todo (x)
15658 (let (re pl)
15659 (if (eq x 'line)
15660 (save-excursion
15661 (beginning-of-line 1)
15662 (setq re (get-text-property (point) 'org-not-done-regexp))
15663 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
15664 (and (looking-at (concat "[ \t]*\\.*" re))
15665 (add-text-properties (match-beginning 0) (match-end 0)
15666 '(face org-todo))))
15667 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
15668 pl (get-text-property 0 'prefix-length x))
15669 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
15670 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
15671 '(face org-todo) x))
15672 x)))
15674 (defsubst org-cmp-priority (a b)
15675 "Compare the priorities of string A and B."
15676 (let ((pa (or (get-text-property 1 'priority a) 0))
15677 (pb (or (get-text-property 1 'priority b) 0)))
15678 (cond ((> pa pb) +1)
15679 ((< pa pb) -1)
15680 (t nil))))
15682 (defsubst org-cmp-category (a b)
15683 "Compare the string values of categories of strings A and B."
15684 (let ((ca (or (get-text-property 1 'category a) ""))
15685 (cb (or (get-text-property 1 'category b) "")))
15686 (cond ((string-lessp ca cb) -1)
15687 ((string-lessp cb ca) +1)
15688 (t nil))))
15690 (defsubst org-cmp-tag (a b)
15691 "Compare the string values of categories of strings A and B."
15692 (let ((ta (car (last (get-text-property 1 'tags a))))
15693 (tb (car (last (get-text-property 1 'tags b)))))
15694 (cond ((not ta) +1)
15695 ((not tb) -1)
15696 ((string-lessp ta tb) -1)
15697 ((string-lessp tb ta) +1)
15698 (t nil))))
15700 (defsubst org-cmp-time (a b)
15701 "Compare the time-of-day values of strings A and B."
15702 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
15703 (ta (or (get-text-property 1 'time-of-day a) def))
15704 (tb (or (get-text-property 1 'time-of-day b) def)))
15705 (cond ((< ta tb) -1)
15706 ((< tb ta) +1)
15707 (t nil))))
15709 (defun org-entries-lessp (a b)
15710 "Predicate for sorting agenda entries."
15711 ;; The following variables will be used when the form is evaluated.
15712 ;; So even though the compiler complains, keep them.
15713 (let* ((time-up (org-cmp-time a b))
15714 (time-down (if time-up (- time-up) nil))
15715 (priority-up (org-cmp-priority a b))
15716 (priority-down (if priority-up (- priority-up) nil))
15717 (category-up (org-cmp-category a b))
15718 (category-down (if category-up (- category-up) nil))
15719 (category-keep (if category-up +1 nil))
15720 (tag-up (org-cmp-tag a b))
15721 (tag-down (if tag-up (- tag-up) nil)))
15722 (cdr (assoc
15723 (eval (cons 'or org-agenda-sorting-strategy-selected))
15724 '((-1 . t) (1 . nil) (nil . nil))))))
15726 ;;; Agenda commands
15728 (defun org-agenda-check-type (error &rest types)
15729 "Check if agenda buffer is of allowed type.
15730 If ERROR is non-nil, throw an error, otherwise just return nil."
15731 (if (memq org-agenda-type types)
15733 (if error
15734 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
15735 nil)))
15737 (defun org-agenda-quit ()
15738 "Exit agenda by removing the window or the buffer."
15739 (interactive)
15740 (let ((buf (current-buffer)))
15741 (if (not (one-window-p)) (delete-window))
15742 (kill-buffer buf)
15743 (org-agenda-maybe-reset-markers 'force))
15744 ;; Maybe restore the pre-agenda window configuration.
15745 (and org-agenda-restore-windows-after-quit
15746 (not (eq org-agenda-window-setup 'other-frame))
15747 org-pre-agenda-window-conf
15748 (set-window-configuration org-pre-agenda-window-conf)))
15750 (defun org-agenda-exit ()
15751 "Exit agenda by removing the window or the buffer.
15752 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
15753 Org-mode buffers visited directly by the user will not be touched."
15754 (interactive)
15755 (org-release-buffers org-agenda-new-buffers)
15756 (setq org-agenda-new-buffers nil)
15757 (org-agenda-quit))
15759 (defun org-save-all-org-buffers ()
15760 "Save all Org-mode buffers without user confirmation."
15761 (interactive)
15762 (message "Saving all Org-mode buffers...")
15763 (save-some-buffers t 'org-mode-p)
15764 (message "Saving all Org-mode buffers... done"))
15766 (defun org-agenda-redo ()
15767 "Rebuild Agenda.
15768 When this is the global TODO list, a prefix argument will be interpreted."
15769 (interactive)
15770 (let* ((org-agenda-keep-modes t)
15771 (line (org-current-line))
15772 (window-line (- line (org-current-line (window-start)))))
15773 (message "Rebuilding agenda buffer...")
15774 (eval org-agenda-redo-command)
15775 (setq org-agenda-undo-list nil
15776 org-agenda-pending-undo-list nil)
15777 (message "Rebuilding agenda buffer...done")
15778 (goto-line line)
15779 (recenter window-line)))
15781 (defun org-agenda-goto-today ()
15782 "Go to today."
15783 (interactive)
15784 (org-agenda-check-type t 'timeline 'agenda)
15785 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
15786 (cond
15787 (tdpos (goto-char tdpos))
15788 ((eq org-agenda-type 'agenda)
15789 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
15790 (setf (nth 1 org-agenda-overriding-arguments) nil)
15791 (org-agenda-redo)
15792 (org-agenda-find-today-or-agenda)))
15793 (t (error "Cannot find today")))))
15795 (defun org-agenda-find-today-or-agenda ()
15796 (goto-char
15797 (or (text-property-any (point-min) (point-max) 'org-today t)
15798 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
15799 (point-min))))
15801 (defun org-agenda-later (arg)
15802 "Go forward in time by `org-agenda-ndays' days.
15803 With prefix ARG, go forward that many times `org-agenda-ndays'."
15804 (interactive "p")
15805 (org-agenda-check-type t 'agenda)
15806 (let ((org-agenda-overriding-arguments
15807 (list (car org-agenda-last-arguments)
15808 (+ org-starting-day (* arg org-agenda-ndays))
15809 nil t)))
15810 (org-agenda-redo)
15811 (org-agenda-find-today-or-agenda)))
15813 (defun org-agenda-earlier (arg)
15814 "Go back in time by `org-agenda-ndays' days.
15815 With prefix ARG, go back that many times `org-agenda-ndays'."
15816 (interactive "p")
15817 (org-agenda-check-type t 'agenda)
15818 (let ((org-agenda-overriding-arguments
15819 (list (car org-agenda-last-arguments)
15820 (- org-starting-day (* arg org-agenda-ndays))
15821 nil t)))
15822 (org-agenda-redo)
15823 (org-agenda-find-today-or-agenda)))
15825 (defun org-agenda-week-view ()
15826 "Switch to weekly view for agenda."
15827 (interactive)
15828 (org-agenda-check-type t 'agenda)
15829 (if (= org-agenda-ndays 7)
15830 (error "This is already the week view"))
15831 (setq org-agenda-ndays 7)
15832 (let ((org-agenda-overriding-arguments
15833 (list (car org-agenda-last-arguments)
15834 (or (get-text-property (point) 'day)
15835 org-starting-day)
15836 nil t)))
15837 (org-agenda-redo)
15838 (org-agenda-find-today-or-agenda))
15839 (org-agenda-set-mode-name)
15840 (message "Switched to week view"))
15842 (defun org-agenda-day-view ()
15843 "Switch to daily view for agenda."
15844 (interactive)
15845 (org-agenda-check-type t 'agenda)
15846 (if (= org-agenda-ndays 1)
15847 (error "This is already the day view"))
15848 (setq org-agenda-ndays 1)
15849 (let ((org-agenda-overriding-arguments
15850 (list (car org-agenda-last-arguments)
15851 (or (get-text-property (point) 'day)
15852 org-starting-day)
15853 nil t)))
15854 (org-agenda-redo)
15855 (org-agenda-find-today-or-agenda))
15856 (org-agenda-set-mode-name)
15857 (message "Switched to day view"))
15859 ;; FIXME: this no longer works if user make date format that starts with a blank
15860 (defun org-agenda-next-date-line (&optional arg)
15861 "Jump to the next line indicating a date in agenda buffer."
15862 (interactive "p")
15863 (org-agenda-check-type t 'agenda 'timeline)
15864 (beginning-of-line 1)
15865 (if (looking-at "^\\S-") (forward-char 1))
15866 (if (not (re-search-forward "^\\S-" nil t arg))
15867 (progn
15868 (backward-char 1)
15869 (error "No next date after this line in this buffer")))
15870 (goto-char (match-beginning 0)))
15872 (defun org-agenda-previous-date-line (&optional arg)
15873 "Jump to the previous line indicating a date in agenda buffer."
15874 (interactive "p")
15875 (org-agenda-check-type t 'agenda 'timeline)
15876 (beginning-of-line 1)
15877 (if (not (re-search-backward "^\\S-" nil t arg))
15878 (error "No previous date before this line in this buffer")))
15880 ;; Initialize the highlight
15881 (defvar org-hl (org-make-overlay 1 1))
15882 (org-overlay-put org-hl 'face 'highlight)
15884 (defun org-highlight (begin end &optional buffer)
15885 "Highlight a region with overlay."
15886 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
15887 org-hl begin end (or buffer (current-buffer))))
15889 (defun org-unhighlight ()
15890 "Detach overlay INDEX."
15891 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
15893 ;; FIXME this is currently not used.
15894 (defun org-highlight-until-next-command (beg end &optional buffer)
15895 (org-highlight beg end buffer)
15896 (add-hook 'pre-command-hook 'org-unhighlight-once))
15898 (defun org-unhighlight-once ()
15899 (remove-hook 'pre-command-hook 'org-unhighlight-once)
15900 (org-unhighlight))
15902 (defun org-agenda-follow-mode ()
15903 "Toggle follow mode in an agenda buffer."
15904 (interactive)
15905 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
15906 (org-agenda-set-mode-name)
15907 (message "Follow mode is %s"
15908 (if org-agenda-follow-mode "on" "off")))
15910 (defun org-agenda-log-mode ()
15911 "Toggle log mode in an agenda buffer."
15912 (interactive)
15913 (org-agenda-check-type t 'agenda 'timeline)
15914 (setq org-agenda-show-log (not org-agenda-show-log))
15915 (org-agenda-set-mode-name)
15916 (org-agenda-redo)
15917 (message "Log mode is %s"
15918 (if org-agenda-show-log "on" "off")))
15920 (defun org-agenda-toggle-diary ()
15921 "Toggle diary inclusion in an agenda buffer."
15922 (interactive)
15923 (org-agenda-check-type t 'agenda)
15924 (setq org-agenda-include-diary (not org-agenda-include-diary))
15925 (org-agenda-redo)
15926 (org-agenda-set-mode-name)
15927 (message "Diary inclusion turned %s"
15928 (if org-agenda-include-diary "on" "off")))
15930 (defun org-agenda-toggle-time-grid ()
15931 "Toggle time grid in an agenda buffer."
15932 (interactive)
15933 (org-agenda-check-type t 'agenda)
15934 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
15935 (org-agenda-redo)
15936 (org-agenda-set-mode-name)
15937 (message "Time-grid turned %s"
15938 (if org-agenda-use-time-grid "on" "off")))
15940 (defun org-agenda-set-mode-name ()
15941 "Set the mode name to indicate all the small mode settings."
15942 (setq mode-name
15943 (concat "Org-Agenda"
15944 (if (equal org-agenda-ndays 1) " Day" "")
15945 (if (equal org-agenda-ndays 7) " Week" "")
15946 (if org-agenda-follow-mode " Follow" "")
15947 (if org-agenda-include-diary " Diary" "")
15948 (if org-agenda-use-time-grid " Grid" "")
15949 (if org-agenda-show-log " Log" "")))
15950 (force-mode-line-update))
15952 (defun org-agenda-post-command-hook ()
15953 (and (eolp) (not (bolp)) (backward-char 1))
15954 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
15955 (if (and org-agenda-follow-mode
15956 (get-text-property (point) 'org-marker))
15957 (org-agenda-show)))
15959 (defun org-agenda-show-priority ()
15960 "Show the priority of the current item.
15961 This priority is composed of the main priority given with the [#A] cookies,
15962 and by additional input from the age of a schedules or deadline entry."
15963 (interactive)
15964 (let* ((pri (get-text-property (point-at-bol) 'priority)))
15965 (message "Priority is %d" (if pri pri -1000))))
15967 (defun org-agenda-show-tags ()
15968 "Show the tags applicable to the current item."
15969 (interactive)
15970 (let* ((tags (get-text-property (point-at-bol) 'tags)))
15971 (if tags
15972 (message "Tags are :%s:"
15973 (org-no-properties (mapconcat 'identity tags ":")))
15974 (message "No tags associated with this line"))))
15976 (defun org-agenda-goto (&optional highlight)
15977 "Go to the Org-mode file which contains the item at point."
15978 (interactive)
15979 (let* ((marker (or (get-text-property (point) 'org-marker)
15980 (org-agenda-error)))
15981 (buffer (marker-buffer marker))
15982 (pos (marker-position marker)))
15983 (switch-to-buffer-other-window buffer)
15984 (widen)
15985 (goto-char pos)
15986 (when (org-mode-p)
15987 (org-show-context 'agenda)
15988 (save-excursion
15989 (and (outline-next-heading)
15990 (org-flag-heading nil)))) ; show the next heading
15991 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
15993 (defun org-agenda-kill ()
15994 "Kill the entry or subtree belonging to the current agenda entry."
15995 (interactive)
15996 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
15997 (let* ((marker (or (get-text-property (point) 'org-marker)
15998 (org-agenda-error)))
15999 (buffer (marker-buffer marker))
16000 (pos (marker-position marker))
16001 dbeg dend (n 0) conf)
16002 (org-with-remote-undo buffer
16003 (with-current-buffer buffer
16004 (save-excursion
16005 (goto-char pos)
16006 (if (org-mode-p)
16007 (setq dbeg (progn (org-back-to-heading t) (point))
16008 dend (org-end-of-subtree t))
16009 (setq dbeg (point-at-bol)
16010 dend (min (point-max) (1+ (point-at-eol)))))
16011 (goto-char dbeg)
16012 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
16013 (setq conf (or (eq t org-agenda-confirm-kill)
16014 (and (numberp org-agenda-confirm-kill)
16015 (> n org-agenda-confirm-kill))))
16016 (and conf
16017 (not (y-or-n-p
16018 (format "Delete entry with %d lines in buffer \"%s\"? "
16019 n (buffer-name buffer))))
16020 (error "Abort"))
16021 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
16022 (with-current-buffer buffer (delete-region dbeg dend))
16023 (message "Agenda item and source killed"))))
16025 (defun org-agenda-archive ()
16026 "Kill the entry or subtree belonging to the current agenda entry."
16027 (interactive)
16028 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
16029 (let* ((marker (or (get-text-property (point) 'org-marker)
16030 (org-agenda-error)))
16031 (buffer (marker-buffer marker))
16032 (pos (marker-position marker)))
16033 (org-with-remote-undo buffer
16034 (with-current-buffer buffer
16035 (if (org-mode-p)
16036 (save-excursion
16037 (goto-char pos)
16038 (org-remove-subtree-entries-from-agenda)
16039 (org-back-to-heading t)
16040 (org-archive-subtree))
16041 (error "Archiving works only in Org-mode files"))))))
16043 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
16044 "Remove all lines in the agenda that correspond to a given subtree.
16045 The subtree is the one in buffer BUF, starting at BEG and ending at END.
16046 If this information is not given, the function uses the tree at point."
16047 (let ((buf (or buf (current-buffer))) m p)
16048 (save-excursion
16049 (unless (and beg end)
16050 (org-back-to-heading t)
16051 (setq beg (point))
16052 (org-end-of-subtree t)
16053 (setq end (point)))
16054 (set-buffer (get-buffer org-agenda-buffer-name))
16055 (save-excursion
16056 (goto-char (point-max))
16057 (beginning-of-line 1)
16058 (while (not (bobp))
16059 (when (and (setq m (get-text-property (point) 'org-marker))
16060 (equal buf (marker-buffer m))
16061 (setq p (marker-position m))
16062 (>= p beg)
16063 (<= p end))
16064 (let (buffer-read-only)
16065 (delete-region (point-at-bol) (1+ (point-at-eol)))))
16066 (beginning-of-line 0))))))
16068 (defun org-agenda-open-link ()
16069 "Follow the link in the current line, if any."
16070 (interactive)
16071 (let ((eol (point-at-eol)))
16072 (save-excursion
16073 (if (or (re-search-forward org-bracket-link-regexp eol t)
16074 (re-search-forward org-angle-link-re eol t)
16075 (re-search-forward org-plain-link-re eol t))
16076 (call-interactively 'org-open-at-point)
16077 (error "No link in current line")))))
16079 (defun org-agenda-switch-to (&optional delete-other-windows)
16080 "Go to the Org-mode file which contains the item at point."
16081 (interactive)
16082 (let* ((marker (or (get-text-property (point) 'org-marker)
16083 (org-agenda-error)))
16084 (buffer (marker-buffer marker))
16085 (pos (marker-position marker)))
16086 (switch-to-buffer buffer)
16087 (and delete-other-windows (delete-other-windows))
16088 (widen)
16089 (goto-char pos)
16090 (when (org-mode-p)
16091 (org-show-context 'agenda)
16092 (save-excursion
16093 (and (outline-next-heading)
16094 (org-flag-heading nil)))))) ; show the next heading
16096 (defun org-agenda-goto-mouse (ev)
16097 "Go to the Org-mode file which contains the item at the mouse click."
16098 (interactive "e")
16099 (mouse-set-point ev)
16100 (org-agenda-goto))
16102 (defun org-agenda-show ()
16103 "Display the Org-mode file which contains the item at point."
16104 (interactive)
16105 (let ((win (selected-window)))
16106 (org-agenda-goto t)
16107 (select-window win)))
16109 (defun org-agenda-recenter (arg)
16110 "Display the Org-mode file which contains the item at point and recenter."
16111 (interactive "P")
16112 (let ((win (selected-window)))
16113 (org-agenda-goto t)
16114 (recenter arg)
16115 (select-window win)))
16117 (defun org-agenda-show-mouse (ev)
16118 "Display the Org-mode file which contains the item at the mouse click."
16119 (interactive "e")
16120 (mouse-set-point ev)
16121 (org-agenda-show))
16123 (defun org-agenda-check-no-diary ()
16124 "Check if the entry is a diary link and abort if yes."
16125 (if (get-text-property (point) 'org-agenda-diary-link)
16126 (org-agenda-error)))
16128 (defun org-agenda-error ()
16129 (error "Command not allowed in this line"))
16131 (defun org-agenda-tree-to-indirect-buffer ()
16132 "Show the subtree corresponding to the current entry in an indirect buffer.
16133 This calls the command `org-tree-to-indirect-buffer' from the original
16134 Org-mode buffer.
16135 With numerical prefix arg ARG, go up to this level and then take that tree.
16136 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
16137 dedicated frame)."
16138 (interactive)
16139 (org-agenda-check-no-diary)
16140 (let* ((marker (or (get-text-property (point) 'org-marker)
16141 (org-agenda-error)))
16142 (buffer (marker-buffer marker))
16143 (pos (marker-position marker)))
16144 (with-current-buffer buffer
16145 (save-excursion
16146 (goto-char pos)
16147 (call-interactively 'org-tree-to-indirect-buffer)))))
16149 (defvar org-last-heading-marker (make-marker)
16150 "Marker pointing to the headline that last changed its TODO state
16151 by a remote command from the agenda.")
16153 (defun org-agenda-todo-nextset ()
16154 "Switch TODO entry to next sequence."
16155 (interactive)
16156 (org-agenda-todo 'nextset))
16158 (defun org-agenda-todo-previousset ()
16159 "Switch TODO entry to previous sequence."
16160 (interactive)
16161 (org-agenda-todo 'previousset))
16163 (defun org-agenda-todo (&optional arg)
16164 "Cycle TODO state of line at point, also in Org-mode file.
16165 This changes the line at point, all other lines in the agenda referring to
16166 the same tree node, and the headline of the tree node in the Org-mode file."
16167 (interactive "P")
16168 (org-agenda-check-no-diary)
16169 (let* ((col (current-column))
16170 (marker (or (get-text-property (point) 'org-marker)
16171 (org-agenda-error)))
16172 (buffer (marker-buffer marker))
16173 (pos (marker-position marker))
16174 (hdmarker (get-text-property (point) 'org-hd-marker))
16175 (buffer-read-only nil)
16176 newhead)
16177 (org-with-remote-undo buffer
16178 (with-current-buffer buffer
16179 (widen)
16180 (goto-char pos)
16181 (org-show-context 'agenda)
16182 (save-excursion
16183 (and (outline-next-heading)
16184 (org-flag-heading nil))) ; show the next heading
16185 (org-todo arg)
16186 (and (bolp) (forward-char 1))
16187 (setq newhead (org-get-heading))
16188 (save-excursion
16189 (org-back-to-heading)
16190 (move-marker org-last-heading-marker (point))))
16191 (beginning-of-line 1)
16192 (save-excursion
16193 (org-agenda-change-all-lines newhead hdmarker 'fixface))
16194 (move-to-column col))))
16196 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
16197 "Change all lines in the agenda buffer which match HDMARKER.
16198 The new content of the line will be NEWHEAD (as modified by
16199 `org-format-agenda-item'). HDMARKER is checked with
16200 `equal' against all `org-hd-marker' text properties in the file.
16201 If FIXFACE is non-nil, the face of each item is modified acording to
16202 the new TODO state."
16203 (let* ((buffer-read-only nil)
16204 props m pl undone-face done-face finish new dotime cat tags)
16205 (save-excursion
16206 (goto-char (point-max))
16207 (beginning-of-line 1)
16208 (while (not finish)
16209 (setq finish (bobp))
16210 (when (and (setq m (get-text-property (point) 'org-hd-marker))
16211 (equal m hdmarker))
16212 (setq props (text-properties-at (point))
16213 dotime (get-text-property (point) 'dotime)
16214 cat (get-text-property (point) 'org-category)
16215 tags (get-text-property (point) 'tags)
16216 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
16217 pl (get-text-property (point) 'prefix-length)
16218 undone-face (get-text-property (point) 'undone-face)
16219 done-face (get-text-property (point) 'done-face))
16220 (move-to-column pl)
16221 (cond
16222 ((equal new "")
16223 (beginning-of-line 1)
16224 (and (looking-at ".*\n?") (replace-match "")))
16225 ((looking-at ".*")
16226 (replace-match new t t)
16227 (beginning-of-line 1)
16228 (add-text-properties (point-at-bol) (point-at-eol) props)
16229 (when fixface
16230 (add-text-properties
16231 (point-at-bol) (point-at-eol)
16232 (list 'face
16233 (if org-last-todo-state-is-todo
16234 undone-face done-face))))
16235 (org-agenda-highlight-todo 'line)
16236 (beginning-of-line 1))
16237 (t (error "Line update did not work"))))
16238 (beginning-of-line 0)))
16239 (org-finalize-agenda)))
16241 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
16242 ;; See the code in set-tags for the way to do this.
16243 (defun org-agenda-align-tags (&optional line)
16244 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
16245 (let ((buffer-read-only))
16246 (save-excursion
16247 (goto-char (if line (point-at-bol) (point-min)))
16248 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
16249 (if line (point-at-eol) nil) t)
16250 (delete-region (match-beginning 1) (match-end 1))
16251 (goto-char (match-beginning 1))
16252 (insert (org-add-props
16253 (make-string (max 1 (- org-agenda-align-tags-to-column
16254 (current-column))) ?\ )
16255 (text-properties-at (point))))))))
16257 (defun org-agenda-priority-up ()
16258 "Increase the priority of line at point, also in Org-mode file."
16259 (interactive)
16260 (org-agenda-priority 'up))
16262 (defun org-agenda-priority-down ()
16263 "Decrease the priority of line at point, also in Org-mode file."
16264 (interactive)
16265 (org-agenda-priority 'down))
16267 (defun org-agenda-priority (&optional force-direction)
16268 "Set the priority of line at point, also in Org-mode file.
16269 This changes the line at point, all other lines in the agenda referring to
16270 the same tree node, and the headline of the tree node in the Org-mode file."
16271 (interactive)
16272 (org-agenda-check-no-diary)
16273 (let* ((marker (or (get-text-property (point) 'org-marker)
16274 (org-agenda-error)))
16275 (buffer (marker-buffer marker))
16276 (pos (marker-position marker))
16277 (hdmarker (get-text-property (point) 'org-hd-marker))
16278 (buffer-read-only nil)
16279 newhead)
16280 (org-with-remote-undo buffer
16281 (with-current-buffer buffer
16282 (widen)
16283 (goto-char pos)
16284 (org-show-context 'agenda)
16285 (save-excursion
16286 (and (outline-next-heading)
16287 (org-flag-heading nil))) ; show the next heading
16288 (funcall 'org-priority force-direction)
16289 (end-of-line 1)
16290 (setq newhead (org-get-heading)))
16291 (org-agenda-change-all-lines newhead hdmarker)
16292 (beginning-of-line 1))))
16294 (defun org-get-tags-at (&optional pos)
16295 "Get a list of all headline tags applicable at POS.
16296 POS defaults to point. If tags are inherited, the list contains
16297 the targets in the same sequence as the headlines appear, i.e.
16298 the tags of the current headline come last."
16299 (interactive)
16300 (let (tags)
16301 (save-excursion
16302 (save-restriction
16303 (widen)
16304 (goto-char (or pos (point)))
16305 (save-match-data
16306 (org-back-to-heading t)
16307 (condition-case nil
16308 (while t
16309 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
16310 (setq tags (append (org-split-string
16311 (org-match-string-no-properties 1) ":")
16312 tags)))
16313 (or org-use-tag-inheritance (error ""))
16314 (org-up-heading-all 1))
16315 (error nil))))
16316 tags)))
16318 ;; FIXME: should fix the tags property of the agenda line.
16319 (defun org-agenda-set-tags ()
16320 "Set tags for the current headline."
16321 (interactive)
16322 (org-agenda-check-no-diary)
16323 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
16324 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
16325 (org-agenda-error)))
16326 (buffer (marker-buffer hdmarker))
16327 (pos (marker-position hdmarker))
16328 (buffer-read-only nil)
16329 newhead)
16330 (org-with-remote-undo buffer
16331 (with-current-buffer buffer
16332 (widen)
16333 (goto-char pos)
16334 (save-excursion
16335 (org-show-context 'agenda))
16336 (save-excursion
16337 (and (outline-next-heading)
16338 (org-flag-heading nil))) ; show the next heading
16339 (goto-char pos)
16340 (call-interactively 'org-set-tags)
16341 (end-of-line 1)
16342 (setq newhead (org-get-heading)))
16343 (org-agenda-change-all-lines newhead hdmarker)
16344 (beginning-of-line 1))))
16346 (defun org-agenda-toggle-archive-tag ()
16347 "Toggle the archive tag for the current entry."
16348 (interactive)
16349 (org-agenda-check-no-diary)
16350 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
16351 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
16352 (org-agenda-error)))
16353 (buffer (marker-buffer hdmarker))
16354 (pos (marker-position hdmarker))
16355 (buffer-read-only nil)
16356 newhead)
16357 (org-with-remote-undo buffer
16358 (with-current-buffer buffer
16359 (widen)
16360 (goto-char pos)
16361 (org-show-context 'agenda)
16362 (save-excursion
16363 (and (outline-next-heading)
16364 (org-flag-heading nil))) ; show the next heading
16365 (call-interactively 'org-toggle-archive-tag)
16366 (end-of-line 1)
16367 (setq newhead (org-get-heading)))
16368 (org-agenda-change-all-lines newhead hdmarker)
16369 (beginning-of-line 1))))
16371 (defun org-agenda-date-later (arg &optional what)
16372 "Change the date of this item to one day later."
16373 (interactive "p")
16374 (org-agenda-check-type t 'agenda 'timeline)
16375 (org-agenda-check-no-diary)
16376 (let* ((marker (or (get-text-property (point) 'org-marker)
16377 (org-agenda-error)))
16378 (buffer (marker-buffer marker))
16379 (pos (marker-position marker)))
16380 (org-with-remote-undo buffer
16381 (with-current-buffer buffer
16382 (widen)
16383 (goto-char pos)
16384 (if (not (org-at-timestamp-p))
16385 (error "Cannot find time stamp"))
16386 (org-timestamp-change arg (or what 'day)))
16387 (org-agenda-show-new-time marker org-last-changed-timestamp))
16388 (message "Time stamp changed to %s" org-last-changed-timestamp)))
16390 (defun org-agenda-date-earlier (arg &optional what)
16391 "Change the date of this item to one day earlier."
16392 (interactive "p")
16393 (org-agenda-date-later (- arg) what))
16395 (defun org-agenda-show-new-time (marker stamp)
16396 "Show new date stamp via text properties."
16397 ;; We use text properties to make this undoable
16398 (let ((buffer-read-only nil))
16399 (setq stamp (concat " => " stamp))
16400 (save-excursion
16401 (goto-char (point-max))
16402 (while (not (bobp))
16403 (when (equal marker (get-text-property (point) 'org-marker))
16404 (move-to-column (- (window-width) (length stamp)) t)
16405 (if (featurep 'xemacs)
16406 ;; Use `duplicable' property to trigger undo recording
16407 (let ((ex (make-extent nil nil))
16408 (gl (make-glyph stamp)))
16409 (set-glyph-face gl 'secondary-selection)
16410 (set-extent-properties
16411 ex (list 'invisible t 'end-glyph gl 'duplicable t))
16412 (insert-extent ex (1- (point)) (point-at-eol)))
16413 (add-text-properties
16414 (1- (point)) (point-at-eol)
16415 (list 'display (org-add-props stamp nil
16416 'face 'secondary-selection))))
16417 (beginning-of-line 1))
16418 (beginning-of-line 0)))))
16420 (defun org-agenda-date-prompt (arg)
16421 "Change the date of this item. Date is prompted for, with default today.
16422 The prefix ARG is passed to the `org-time-stamp' command and can therefore
16423 be used to request time specification in the time stamp."
16424 (interactive "P")
16425 (org-agenda-check-type t 'agenda 'timeline)
16426 (org-agenda-check-no-diary)
16427 (let* ((marker (or (get-text-property (point) 'org-marker)
16428 (org-agenda-error)))
16429 (buffer (marker-buffer marker))
16430 (pos (marker-position marker)))
16431 (org-with-remote-undo buffer
16432 (with-current-buffer buffer
16433 (widen)
16434 (goto-char pos)
16435 (if (not (org-at-timestamp-p))
16436 (error "Cannot find time stamp"))
16437 (org-time-stamp arg)
16438 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
16440 (defun org-agenda-schedule (arg)
16441 "Schedule the item at point."
16442 (interactive "P")
16443 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
16444 (org-agenda-check-no-diary)
16445 (let* ((marker (or (get-text-property (point) 'org-marker)
16446 (org-agenda-error)))
16447 (buffer (marker-buffer marker))
16448 (pos (marker-position marker))
16449 (org-insert-labeled-timestamps-at-point nil)
16451 (org-with-remote-undo buffer
16452 (with-current-buffer buffer
16453 (widen)
16454 (goto-char pos)
16455 (setq ts (org-schedule))
16456 (message "Item scheduled for %s" ts)))))
16458 (defun org-agenda-deadline (arg)
16459 "Schedule the item at point."
16460 (interactive "P")
16461 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
16462 (org-agenda-check-no-diary)
16463 (let* ((marker (or (get-text-property (point) 'org-marker)
16464 (org-agenda-error)))
16465 (buffer (marker-buffer marker))
16466 (pos (marker-position marker))
16467 (org-insert-labeled-timestamps-at-point nil)
16469 (org-with-remote-undo buffer
16470 (with-current-buffer buffer
16471 (widen)
16472 (goto-char pos)
16473 (setq ts (org-deadline))
16474 (message "Deadline for this item set to %s" ts)))))
16476 (defun org-get-heading ()
16477 "Return the heading of the current entry, without the stars."
16478 (save-excursion
16479 (org-back-to-heading t)
16480 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
16482 (defun org-agenda-clock-in (&optional arg)
16483 "Start the clock on the currently selected item."
16484 (interactive "P")
16485 (org-agenda-check-no-diary)
16486 (let* ((marker (or (get-text-property (point) 'org-marker)
16487 (org-agenda-error)))
16488 (pos (marker-position marker)))
16489 (org-with-remote-undo (marker-buffer marker)
16490 (with-current-buffer (marker-buffer marker)
16491 (widen)
16492 (goto-char pos)
16493 (org-clock-in)))))
16495 (defun org-agenda-clock-out (&optional arg)
16496 "Stop the currently running clock."
16497 (interactive "P")
16498 (unless (marker-buffer org-clock-marker)
16499 (error "No running clock"))
16500 (org-with-remote-undo (marker-buffer org-clock-marker)
16501 (org-clock-out)))
16503 (defun org-agenda-clock-cancel (&optional arg)
16504 "Cancel the currently running clock."
16505 (interactive "P")
16506 (unless (marker-buffer org-clock-marker)
16507 (error "No running clock"))
16508 (org-with-remote-undo (marker-buffer org-clock-marker)
16509 (org-clock-cancel)))
16511 (defun org-agenda-diary-entry ()
16512 "Make a diary entry, like the `i' command from the calendar.
16513 All the standard commands work: block, weekly etc."
16514 (interactive)
16515 (org-agenda-check-type t 'agenda 'timeline)
16516 (require 'diary-lib)
16517 (let* ((char (progn
16518 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
16519 (read-char-exclusive)))
16520 (cmd (cdr (assoc char
16521 '((?d . insert-diary-entry)
16522 (?w . insert-weekly-diary-entry)
16523 (?m . insert-monthly-diary-entry)
16524 (?y . insert-yearly-diary-entry)
16525 (?a . insert-anniversary-diary-entry)
16526 (?b . insert-block-diary-entry)
16527 (?c . insert-cyclic-diary-entry)))))
16528 (oldf (symbol-function 'calendar-cursor-to-date))
16529 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
16530 (point (point))
16531 (mark (or (mark t) (point))))
16532 (unless cmd
16533 (error "No command associated with <%c>" char))
16534 (unless (and (get-text-property point 'day)
16535 (or (not (equal ?b char))
16536 (get-text-property mark 'day)))
16537 (error "Don't know which date to use for diary entry"))
16538 ;; We implement this by hacking the `calendar-cursor-to-date' function
16539 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
16540 (let ((calendar-mark-ring
16541 (list (calendar-gregorian-from-absolute
16542 (or (get-text-property mark 'day)
16543 (get-text-property point 'day))))))
16544 (unwind-protect
16545 (progn
16546 (fset 'calendar-cursor-to-date
16547 (lambda (&optional error)
16548 (calendar-gregorian-from-absolute
16549 (get-text-property point 'day))))
16550 (call-interactively cmd))
16551 (fset 'calendar-cursor-to-date oldf)))))
16554 (defun org-agenda-execute-calendar-command (cmd)
16555 "Execute a calendar command from the agenda, with the date associated to
16556 the cursor position."
16557 (org-agenda-check-type t 'agenda 'timeline)
16558 (require 'diary-lib)
16559 (unless (get-text-property (point) 'day)
16560 (error "Don't know which date to use for calendar command"))
16561 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
16562 (point (point))
16563 (date (calendar-gregorian-from-absolute
16564 (get-text-property point 'day)))
16565 ;; the following 3 vars are needed in the calendar
16566 (displayed-day (extract-calendar-day date))
16567 (displayed-month (extract-calendar-month date))
16568 (displayed-year (extract-calendar-year date)))
16569 (unwind-protect
16570 (progn
16571 (fset 'calendar-cursor-to-date
16572 (lambda (&optional error)
16573 (calendar-gregorian-from-absolute
16574 (get-text-property point 'day))))
16575 (call-interactively cmd))
16576 (fset 'calendar-cursor-to-date oldf))))
16578 (defun org-agenda-phases-of-moon ()
16579 "Display the phases of the moon for the 3 months around the cursor date."
16580 (interactive)
16581 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
16583 (defun org-agenda-holidays ()
16584 "Display the holidays for the 3 months around the cursor date."
16585 (interactive)
16586 (org-agenda-execute-calendar-command 'list-calendar-holidays))
16588 (defun org-agenda-sunrise-sunset (arg)
16589 "Display sunrise and sunset for the cursor date.
16590 Latitude and longitude can be specified with the variables
16591 `calendar-latitude' and `calendar-longitude'. When called with prefix
16592 argument, latitude and longitude will be prompted for."
16593 (interactive "P")
16594 (let ((calendar-longitude (if arg nil calendar-longitude))
16595 (calendar-latitude (if arg nil calendar-latitude))
16596 (calendar-location-name
16597 (if arg "the given coordinates" calendar-location-name)))
16598 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
16600 (defun org-agenda-goto-calendar ()
16601 "Open the Emacs calendar with the date at the cursor."
16602 (interactive)
16603 (org-agenda-check-type t 'agenda 'timeline)
16604 (let* ((day (or (get-text-property (point) 'day)
16605 (error "Don't know which date to open in calendar")))
16606 (date (calendar-gregorian-from-absolute day))
16607 (calendar-move-hook nil)
16608 (view-calendar-holidays-initially nil)
16609 (view-diary-entries-initially nil))
16610 (calendar)
16611 (calendar-goto-date date)))
16613 (defun org-calendar-goto-agenda ()
16614 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
16615 This is a command that has to be installed in `calendar-mode-map'."
16616 (interactive)
16617 (org-agenda-list nil (calendar-absolute-from-gregorian
16618 (calendar-cursor-to-date))
16619 nil))
16621 (defun org-agenda-convert-date ()
16622 (interactive)
16623 (org-agenda-check-type t 'agenda 'timeline)
16624 (let ((day (get-text-property (point) 'day))
16625 date s)
16626 (unless day
16627 (error "Don't know which date to convert"))
16628 (setq date (calendar-gregorian-from-absolute day))
16629 (setq s (concat
16630 "Gregorian: " (calendar-date-string date) "\n"
16631 "ISO: " (calendar-iso-date-string date) "\n"
16632 "Day of Yr: " (calendar-day-of-year-string date) "\n"
16633 "Julian: " (calendar-julian-date-string date) "\n"
16634 "Astron. JD: " (calendar-astro-date-string date)
16635 " (Julian date number at noon UTC)\n"
16636 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
16637 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
16638 "French: " (calendar-french-date-string date) "\n"
16639 "Mayan: " (calendar-mayan-date-string date) "\n"
16640 "Coptic: " (calendar-coptic-date-string date) "\n"
16641 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
16642 "Persian: " (calendar-persian-date-string date) "\n"
16643 "Chinese: " (calendar-chinese-date-string date) "\n"))
16644 (with-output-to-temp-buffer "*Dates*"
16645 (princ s))
16646 (if (fboundp 'fit-window-to-buffer)
16647 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
16650 ;;;; Embedded LaTeX
16652 (defvar org-cdlatex-mode-map (make-sparse-keymap)
16653 "Keymap for the minor `org-cdlatex-mode'.")
16655 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
16656 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
16657 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
16658 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
16659 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
16661 (defvar org-cdlatex-texmathp-advice-is-done nil
16662 "Flag remembering if we have applied the advice to texmathp already.")
16664 (define-minor-mode org-cdlatex-mode
16665 "Toggle the minor `org-cdlatex-mode'.
16666 This mode supports entering LaTeX environment and math in LaTeX fragments
16667 in Org-mode.
16668 \\{org-cdlatex-mode-map}"
16669 nil " OCDL" nil
16670 (when org-cdlatex-mode (require 'cdlatex))
16671 (unless org-cdlatex-texmathp-advice-is-done
16672 (setq org-cdlatex-texmathp-advice-is-done t)
16673 (defadvice texmathp (around org-math-always-on activate)
16674 "Always return t in org-mode buffers.
16675 This is because we want to insert math symbols without dollars even outside
16676 the LaTeX math segments. If Orgmode thinks that point is actually inside
16677 en embedded LaTeX fragement, let texmathp do its job.
16678 \\[org-cdlatex-mode-map]"
16679 (interactive)
16680 (let (p)
16681 (cond
16682 ((not (org-mode-p)) ad-do-it)
16683 ((eq this-command 'cdlatex-math-symbol)
16684 (setq ad-return-value t
16685 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
16687 (let ((p (org-inside-LaTeX-fragment-p)))
16688 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
16689 (setq ad-return-value t
16690 texmathp-why '("Org-mode embedded math" . 0))
16691 (if p ad-do-it)))))))))
16693 (defun turn-on-org-cdlatex ()
16694 "Unconditionally turn on `org-cdlatex-mode'."
16695 (org-cdlatex-mode 1))
16697 (defun org-inside-LaTeX-fragment-p ()
16698 "Test if point is inside a LaTeX fragment.
16699 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
16700 sequence appearing also before point.
16701 Even though the matchers for math are configurable, this function assumes
16702 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
16703 delimiters are skipped when they have been removed by customization.
16704 The return value is nil, or a cons cell with the delimiter and
16705 and the position of this delimiter.
16707 This function does a reasonably good job, but can locally be fooled by
16708 for example currency specifications. For example it will assume being in
16709 inline math after \"$22.34\". The LaTeX fragment formatter will only format
16710 fragments that are properly closed, but during editing, we have to live
16711 with the uncertainty caused by missing closing delimiters. This function
16712 looks only before point, not after."
16713 (catch 'exit
16714 (let ((pos (point))
16715 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
16716 (lim (progn
16717 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
16718 (point)))
16719 dd-on str (start 0) m re)
16720 (goto-char pos)
16721 (when dodollar
16722 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
16723 re (nth 1 (assoc "$" org-latex-regexps)))
16724 (while (string-match re str start)
16725 (cond
16726 ((= (match-end 0) (length str))
16727 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
16728 ((= (match-end 0) (- (length str) 5))
16729 (throw 'exit nil))
16730 (t (setq start (match-end 0))))))
16731 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
16732 (goto-char pos)
16733 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
16734 (and (match-beginning 2) (throw 'exit nil))
16735 ;; count $$
16736 (while (re-search-backward "\\$\\$" lim t)
16737 (setq dd-on (not dd-on)))
16738 (goto-char pos)
16739 (if dd-on (cons "$$" m))))))
16742 (defun org-try-cdlatex-tab ()
16743 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
16744 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
16745 - inside a LaTeX fragment, or
16746 - after the first word in a line, where an abbreviation expansion could
16747 insert a LaTeX environment."
16748 (when org-cdlatex-mode
16749 (cond
16750 ((save-excursion
16751 (skip-chars-backward "a-zA-Z0-9*")
16752 (skip-chars-backward " \t")
16753 (bolp))
16754 (cdlatex-tab) t)
16755 ((org-inside-LaTeX-fragment-p)
16756 (cdlatex-tab) t)
16757 (t nil))))
16759 (defun org-cdlatex-underscore-caret (&optional arg)
16760 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
16761 Revert to the normal definition outside of these fragments."
16762 (interactive "P")
16763 (if (org-inside-LaTeX-fragment-p)
16764 (call-interactively 'cdlatex-sub-superscript)
16765 (let (org-cdlatex-mode)
16766 (call-interactively (key-binding (vector last-input-event))))))
16768 (defun org-cdlatex-math-modify (&optional arg)
16769 "Execute `cdlatex-math-modify' in LaTeX fragments.
16770 Revert to the normal definition outside of these fragments."
16771 (interactive "P")
16772 (if (org-inside-LaTeX-fragment-p)
16773 (call-interactively 'cdlatex-math-modify)
16774 (let (org-cdlatex-mode)
16775 (call-interactively (key-binding (vector last-input-event))))))
16777 (defvar org-latex-fragment-image-overlays nil
16778 "List of overlays carrying the images of latex fragments.")
16779 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
16781 (defun org-remove-latex-fragment-image-overlays ()
16782 "Remove all overlays with LaTeX fragment images in current buffer."
16783 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
16784 (setq org-latex-fragment-image-overlays nil))
16786 (defun org-preview-latex-fragment (&optional subtree)
16787 "Preview the LaTeX fragment at point, or all locally or globally.
16788 If the cursor is in a LaTeX fragment, create the image and overlay
16789 it over the source code. If there is no fragment at point, display
16790 all fragments in the current text, from one headline to the next. With
16791 prefix SUBTREE, display all fragments in the current subtree. With a
16792 double prefix `C-u C-u', or when the cursor is before the first headline,
16793 display all fragments in the buffer.
16794 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
16795 (interactive "P")
16796 (org-remove-latex-fragment-image-overlays)
16797 (save-excursion
16798 (save-restriction
16799 (let (beg end at msg)
16800 (cond
16801 ((or (equal subtree '(16))
16802 (not (save-excursion
16803 (re-search-backward (concat "^" outline-regexp) nil t))))
16804 (setq beg (point-min) end (point-max)
16805 msg "Creating images for buffer...%s"))
16806 ((equal subtree '(4))
16807 (org-back-to-heading)
16808 (setq beg (point) end (org-end-of-subtree t)
16809 msg "Creating images for subtree...%s"))
16811 (if (setq at (org-inside-LaTeX-fragment-p))
16812 (goto-char (max (point-min) (- (cdr at) 2)))
16813 (org-back-to-heading))
16814 (setq beg (point) end (progn (outline-next-heading) (point))
16815 msg (if at "Creating image...%s"
16816 "Creating images for entry...%s"))))
16817 (message msg "")
16818 (narrow-to-region beg end)
16819 (goto-char beg)
16820 (org-format-latex
16821 (concat "ltxpng/" (file-name-sans-extension
16822 (file-name-nondirectory
16823 buffer-file-name)))
16824 default-directory 'overlays msg at 'forbuffer)
16825 (message msg "done. Use `C-c C-c' to remove images.")))))
16827 (defvar org-latex-regexps
16828 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
16829 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
16830 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
16831 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
16832 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
16833 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
16834 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
16835 "Regular expressions for matching embedded LaTeX.")
16837 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
16838 "Replace LaTeX fragments with links to an image, and produce images."
16839 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
16840 (let* ((prefixnodir (file-name-nondirectory prefix))
16841 (absprefix (expand-file-name prefix dir))
16842 (todir (file-name-directory absprefix))
16843 (opt org-format-latex-options)
16844 (matchers (plist-get opt :matchers))
16845 (re-list org-latex-regexps)
16846 (cnt 0) txt link beg end re e checkdir
16847 m n block linkfile movefile ov)
16848 ;; Check if there are old images files with this prefix, and remove them
16849 (when (file-directory-p todir)
16850 (mapc 'delete-file
16851 (directory-files
16852 todir 'full
16853 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
16854 ;; Check the different regular expressions
16855 (while (setq e (pop re-list))
16856 (setq m (car e) re (nth 1 e) n (nth 2 e)
16857 block (if (nth 3 e) "\n\n" ""))
16858 (when (member m matchers)
16859 (goto-char (point-min))
16860 (while (re-search-forward re nil t)
16861 (when (or (not at) (equal (cdr at) (match-beginning n)))
16862 (setq txt (match-string n)
16863 beg (match-beginning n) end (match-end n)
16864 cnt (1+ cnt)
16865 linkfile (format "%s_%04d.png" prefix cnt)
16866 movefile (format "%s_%04d.png" absprefix cnt)
16867 link (concat block "[[file:" linkfile "]]" block))
16868 (if msg (message msg cnt))
16869 (goto-char beg)
16870 (unless checkdir ; make sure the directory exists
16871 (setq checkdir t)
16872 (or (file-directory-p todir) (make-directory todir)))
16873 (org-create-formula-image
16874 txt movefile opt forbuffer)
16875 (if overlays
16876 (progn
16877 (setq ov (org-make-overlay beg end))
16878 (if (featurep 'xemacs)
16879 (progn
16880 (org-overlay-put ov 'invisible t)
16881 (org-overlay-put
16882 ov 'end-glyph
16883 (make-glyph (vector 'png :file movefile))))
16884 (org-overlay-put
16885 ov 'display
16886 (list 'image :type 'png :file movefile :ascent 'center)))
16887 (push ov org-latex-fragment-image-overlays)
16888 (goto-char end))
16889 (delete-region beg end)
16890 (insert link))))))))
16892 ;; This function borrows from Ganesh Swami's latex2png.el
16893 (defun org-create-formula-image (string tofile options buffer)
16894 (let* ((tmpdir (if (featurep 'xemacs)
16895 (temp-directory)
16896 temporary-file-directory))
16897 (texfilebase (make-temp-name
16898 (expand-file-name "orgtex" tmpdir)))
16899 (texfile (concat texfilebase ".tex"))
16900 (dvifile (concat texfilebase ".dvi"))
16901 (pngfile (concat texfilebase ".png"))
16902 (fnh (face-attribute 'default :height nil 'inherit))
16903 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
16904 (dpi (number-to-string (floor (* 0.9 (if buffer fnh 140.)))))
16905 (fg (or (plist-get options (if buffer :foreground :html-foreground))
16906 "Black"))
16907 (bg (or (plist-get options (if buffer :background :html-background))
16908 "Transparent")))
16909 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
16910 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
16911 (with-temp-file texfile
16912 (insert org-format-latex-header
16913 "\n\\begin{document}\n" string "\n\\end{document}\n"))
16914 (let ((dir default-directory))
16915 (condition-case nil
16916 (progn
16917 (cd tmpdir)
16918 (call-process "latex" nil nil nil texfile))
16919 (error nil))
16920 (cd dir))
16921 (if (not (file-exists-p dvifile))
16922 (progn (message "Failed to create dvi file from %s" texfile) nil)
16923 (call-process "dvipng" nil nil nil
16924 "-E" "-fg" fg "-bg" bg
16925 "-D" dpi
16926 ;;"-x" scale "-y" scale
16927 "-T" "tight"
16928 "-o" pngfile
16929 dvifile)
16930 (if (not (file-exists-p pngfile))
16931 (progn (message "Failed to create png file from %s" texfile) nil)
16932 ;; Use the requested file name and clean up
16933 (copy-file pngfile tofile 'replace)
16934 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
16935 (delete-file (concat texfilebase e)))
16936 pngfile))))
16938 (defun org-dvipng-color (attr)
16939 "Return an rgb color specification for dvipng."
16940 (apply 'format "rgb %s %s %s"
16941 (mapcar 'org-normalize-color
16942 (color-values (face-attribute 'default attr nil 'inherit)))))
16944 (face-attribute 'default :height nil)
16946 (defun org-normalize-color (value)
16947 "Return string to be used as color value for an RGB component."
16948 (format "%g" (/ value 65535.0)))
16950 ;;;; Exporting
16952 ;;; Variables, constants, and parameter plists
16954 (defconst org-level-max 20)
16956 (defvar org-export-html-preamble nil
16957 "Preamble, to be inserted just after <body>. Set by publishing functions.")
16958 (defvar org-export-html-postamble nil
16959 "Preamble, to be inserted just before </body>. Set by publishing functions.")
16960 (defvar org-export-html-auto-preamble t
16961 "Should default preamble be inserted? Set by publishing functions.")
16962 (defvar org-export-html-auto-postamble t
16963 "Should default postamble be inserted? Set by publishing functions.")
16964 (defvar org-current-export-file nil) ; dynamically scoped parameter
16965 (defvar org-current-export-dir nil) ; dynamically scoped parameter
16968 (defconst org-export-plist-vars
16969 '((:language . org-export-default-language)
16970 (:customtime . org-display-custom-times)
16971 (:headline-levels . org-export-headline-levels)
16972 (:section-numbers . org-export-with-section-numbers)
16973 (:table-of-contents . org-export-with-toc)
16974 (:archived-trees . org-export-with-archived-trees)
16975 (:emphasize . org-export-with-emphasize)
16976 (:sub-superscript . org-export-with-sub-superscripts)
16977 (:TeX-macros . org-export-with-TeX-macros)
16978 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
16979 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
16980 (:fixed-width . org-export-with-fixed-width)
16981 (:timestamps . org-export-with-timestamps)
16982 (:tables . org-export-with-tables)
16983 (:table-auto-headline . org-export-highlight-first-table-line)
16984 (:style . org-export-html-style)
16985 (:convert-org-links . org-export-html-link-org-files-as-html)
16986 (:inline-images . org-export-html-inline-images)
16987 (:expand-quoted-html . org-export-html-expand)
16988 (:timestamp . org-export-html-with-timestamp)
16989 (:publishing-directory . org-export-publishing-directory)
16990 (:preamble . org-export-html-preamble)
16991 (:postamble . org-export-html-postamble)
16992 (:auto-preamble . org-export-html-auto-preamble)
16993 (:auto-postamble . org-export-html-auto-postamble)
16994 (:author . user-full-name)
16995 (:email . user-mail-address)))
16997 (defun org-default-export-plist ()
16998 "Return the property list with default settings for the export variables."
16999 (let ((l org-export-plist-vars) rtn e)
17000 (while (setq e (pop l))
17001 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
17002 rtn))
17004 (defun org-infile-export-plist ()
17005 "Return the property list with file-local settings for export."
17006 (save-excursion
17007 (goto-char 0)
17008 (let ((re (org-make-options-regexp
17009 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
17010 p key val text options)
17011 (while (re-search-forward re nil t)
17012 (setq key (org-match-string-no-properties 1)
17013 val (org-match-string-no-properties 2))
17014 (cond
17015 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
17016 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
17017 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
17018 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
17019 ((string-equal key "TEXT")
17020 (setq text (if text (concat text "\n" val) val)))
17021 ((string-equal key "OPTIONS") (setq options val))))
17022 (setq p (plist-put p :text text))
17023 (when options
17024 (let ((op '(("H" . :headline-levels)
17025 ("num" . :section-numbers)
17026 ("toc" . :table-of-contents)
17027 ("\\n" . :preserve-breaks)
17028 ("@" . :expand-quoted-html)
17029 (":" . :fixed-width)
17030 ("|" . :tables)
17031 ("^" . :sub-superscript)
17032 ("*" . :emphasize)
17033 ("TeX" . :TeX-macros)
17034 ("LaTeX" . :LaTeX-fragments)
17035 ("skip" . :skip-before-1st-heading)))
17037 (while (setq o (pop op))
17038 (if (string-match (concat (regexp-quote (car o))
17039 ":\\([^ \t\n\r;,.]*\\)")
17040 options)
17041 (setq p (plist-put p (cdr o)
17042 (car (read-from-string
17043 (match-string 1 options)))))))))
17044 p)))
17046 (defun org-export-directory (type plist)
17047 (let* ((val (plist-get plist :publishing-directory))
17048 (dir (if (listp val)
17049 (or (cdr (assoc type val)) ".")
17050 val)))
17051 dir))
17053 (defun org-skip-comments (lines)
17054 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
17055 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
17056 (re2 "^\\(\\*+\\)[ \t\n\r]")
17057 (case-fold-search nil)
17058 rtn line level)
17059 (while (setq line (pop lines))
17060 (cond
17061 ((and (string-match re1 line)
17062 (setq level (- (match-end 1) (match-beginning 1))))
17063 ;; Beginning of a COMMENT subtree. Skip it.
17064 (while (and (setq line (pop lines))
17065 (or (not (string-match re2 line))
17066 (> (- (match-end 1) (match-beginning 1)) level))))
17067 (setq lines (cons line lines)))
17068 ((string-match "^#" line)
17069 ;; an ordinary comment line
17071 ((and org-export-table-remove-special-lines
17072 (string-match "^[ \t]*|" line)
17073 (or (string-match "^[ \t]*| *[!_^] *|" line)
17074 (and (string-match "| *<[0-9]+> *|" line)
17075 (not (string-match "| *[^ <|]" line)))))
17076 ;; a special table line that should be removed
17078 (t (setq rtn (cons line rtn)))))
17079 (nreverse rtn)))
17081 (defun org-export (&optional arg)
17082 (interactive)
17083 (let ((help "[t] insert the export option template
17084 \[v] limit export to visible part of outline tree
17086 \[a] export as ASCII
17087 \[h] export as HTML
17088 \[H] export as HTML to temporary buffer
17089 \[b] export as HTML and browse immediately
17090 \[x] export as XOXO
17092 \[i] export current file as iCalendar file
17093 \[I] export all agenda files as iCalendar files
17094 \[c] export agenda files into combined iCalendar file
17096 \[F] publish current file
17097 \[P] publish current project
17098 \[X] publish... (project will be prompted for)
17099 \[A] publish all projects")
17100 (cmds
17101 '((?t . org-insert-export-options-template)
17102 (?v . org-export-visible)
17103 (?a . org-export-as-ascii)
17104 (?h . org-export-as-html)
17105 (?b . org-export-as-html-and-open)
17106 (?H . org-export-as-html-to-buffer)
17107 (?x . org-export-as-xoxo)
17108 (?i . org-export-icalendar-this-file)
17109 (?I . org-export-icalendar-all-agenda-files)
17110 (?c . org-export-icalendar-combine-agenda-files)
17111 (?F . org-publish-current-file)
17112 (?P . org-publish-current-project)
17113 (?X . org-publish)
17114 (?A . org-publish-all)))
17115 r1 r2 ass)
17116 (save-window-excursion
17117 (delete-other-windows)
17118 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
17119 (princ help))
17120 (message "Select command: ")
17121 (setq r1 (read-char-exclusive)))
17122 (setq r2 (if (< r1 27) (+ r1 96) r1))
17123 (if (setq ass (assq r2 cmds))
17124 (call-interactively (cdr ass))
17125 (error "No command associated with key %c" r1))))
17127 (defconst org-html-entities
17128 '(("nbsp")
17129 ("iexcl")
17130 ("cent")
17131 ("pound")
17132 ("curren")
17133 ("yen")
17134 ("brvbar")
17135 ("vert" . "&#124;")
17136 ("sect")
17137 ("uml")
17138 ("copy")
17139 ("ordf")
17140 ("laquo")
17141 ("not")
17142 ("shy")
17143 ("reg")
17144 ("macr")
17145 ("deg")
17146 ("plusmn")
17147 ("sup2")
17148 ("sup3")
17149 ("acute")
17150 ("micro")
17151 ("para")
17152 ("middot")
17153 ("odot"."o")
17154 ("star"."*")
17155 ("cedil")
17156 ("sup1")
17157 ("ordm")
17158 ("raquo")
17159 ("frac14")
17160 ("frac12")
17161 ("frac34")
17162 ("iquest")
17163 ("Agrave")
17164 ("Aacute")
17165 ("Acirc")
17166 ("Atilde")
17167 ("Auml")
17168 ("Aring") ("AA"."&Aring;")
17169 ("AElig")
17170 ("Ccedil")
17171 ("Egrave")
17172 ("Eacute")
17173 ("Ecirc")
17174 ("Euml")
17175 ("Igrave")
17176 ("Iacute")
17177 ("Icirc")
17178 ("Iuml")
17179 ("ETH")
17180 ("Ntilde")
17181 ("Ograve")
17182 ("Oacute")
17183 ("Ocirc")
17184 ("Otilde")
17185 ("Ouml")
17186 ("times")
17187 ("Oslash")
17188 ("Ugrave")
17189 ("Uacute")
17190 ("Ucirc")
17191 ("Uuml")
17192 ("Yacute")
17193 ("THORN")
17194 ("szlig")
17195 ("agrave")
17196 ("aacute")
17197 ("acirc")
17198 ("atilde")
17199 ("auml")
17200 ("aring")
17201 ("aelig")
17202 ("ccedil")
17203 ("egrave")
17204 ("eacute")
17205 ("ecirc")
17206 ("euml")
17207 ("igrave")
17208 ("iacute")
17209 ("icirc")
17210 ("iuml")
17211 ("eth")
17212 ("ntilde")
17213 ("ograve")
17214 ("oacute")
17215 ("ocirc")
17216 ("otilde")
17217 ("ouml")
17218 ("divide")
17219 ("oslash")
17220 ("ugrave")
17221 ("uacute")
17222 ("ucirc")
17223 ("uuml")
17224 ("yacute")
17225 ("thorn")
17226 ("yuml")
17227 ("fnof")
17228 ("Alpha")
17229 ("Beta")
17230 ("Gamma")
17231 ("Delta")
17232 ("Epsilon")
17233 ("Zeta")
17234 ("Eta")
17235 ("Theta")
17236 ("Iota")
17237 ("Kappa")
17238 ("Lambda")
17239 ("Mu")
17240 ("Nu")
17241 ("Xi")
17242 ("Omicron")
17243 ("Pi")
17244 ("Rho")
17245 ("Sigma")
17246 ("Tau")
17247 ("Upsilon")
17248 ("Phi")
17249 ("Chi")
17250 ("Psi")
17251 ("Omega")
17252 ("alpha")
17253 ("beta")
17254 ("gamma")
17255 ("delta")
17256 ("epsilon")
17257 ("varepsilon"."&epsilon;")
17258 ("zeta")
17259 ("eta")
17260 ("theta")
17261 ("iota")
17262 ("kappa")
17263 ("lambda")
17264 ("mu")
17265 ("nu")
17266 ("xi")
17267 ("omicron")
17268 ("pi")
17269 ("rho")
17270 ("sigmaf") ("varsigma"."&sigmaf;")
17271 ("sigma")
17272 ("tau")
17273 ("upsilon")
17274 ("phi")
17275 ("chi")
17276 ("psi")
17277 ("omega")
17278 ("thetasym") ("vartheta"."&thetasym;")
17279 ("upsih")
17280 ("piv")
17281 ("bull") ("bullet"."&bull;")
17282 ("hellip") ("dots"."&hellip;")
17283 ("prime")
17284 ("Prime")
17285 ("oline")
17286 ("frasl")
17287 ("weierp")
17288 ("image")
17289 ("real")
17290 ("trade")
17291 ("alefsym")
17292 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
17293 ("uarr") ("uparrow"."&uarr;")
17294 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
17295 ("darr")("downarrow"."&darr;")
17296 ("harr") ("leftrightarrow"."&harr;")
17297 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
17298 ("lArr") ("Leftarrow"."&lArr;")
17299 ("uArr") ("Uparrow"."&uArr;")
17300 ("rArr") ("Rightarrow"."&rArr;")
17301 ("dArr") ("Downarrow"."&dArr;")
17302 ("hArr") ("Leftrightarrow"."&hArr;")
17303 ("forall")
17304 ("part") ("partial"."&part;")
17305 ("exist") ("exists"."&exist;")
17306 ("empty") ("emptyset"."&empty;")
17307 ("nabla")
17308 ("isin") ("in"."&isin;")
17309 ("notin")
17310 ("ni")
17311 ("prod")
17312 ("sum")
17313 ("minus")
17314 ("lowast") ("ast"."&lowast;")
17315 ("radic")
17316 ("prop") ("proptp"."&prop;")
17317 ("infin") ("infty"."&infin;")
17318 ("ang") ("angle"."&ang;")
17319 ("and") ("vee"."&and;")
17320 ("or") ("wedge"."&or;")
17321 ("cap")
17322 ("cup")
17323 ("int")
17324 ("there4")
17325 ("sim")
17326 ("cong") ("simeq"."&cong;")
17327 ("asymp")("approx"."&asymp;")
17328 ("ne") ("neq"."&ne;")
17329 ("equiv")
17330 ("le")
17331 ("ge")
17332 ("sub") ("subset"."&sub;")
17333 ("sup") ("supset"."&sup;")
17334 ("nsub")
17335 ("sube")
17336 ("supe")
17337 ("oplus")
17338 ("otimes")
17339 ("perp")
17340 ("sdot") ("cdot"."&sdot;")
17341 ("lceil")
17342 ("rceil")
17343 ("lfloor")
17344 ("rfloor")
17345 ("lang")
17346 ("rang")
17347 ("loz") ("Diamond"."&loz;")
17348 ("spades") ("spadesuit"."&spades;")
17349 ("clubs") ("clubsuit"."&clubs;")
17350 ("hearts") ("diamondsuit"."&hearts;")
17351 ("diams") ("diamondsuit"."&diams;")
17352 ("quot")
17353 ("amp")
17354 ("lt")
17355 ("gt")
17356 ("OElig")
17357 ("oelig")
17358 ("Scaron")
17359 ("scaron")
17360 ("Yuml")
17361 ("circ")
17362 ("tilde")
17363 ("ensp")
17364 ("emsp")
17365 ("thinsp")
17366 ("zwnj")
17367 ("zwj")
17368 ("lrm")
17369 ("rlm")
17370 ("ndash")
17371 ("mdash")
17372 ("lsquo")
17373 ("rsquo")
17374 ("sbquo")
17375 ("ldquo")
17376 ("rdquo")
17377 ("bdquo")
17378 ("dagger")
17379 ("Dagger")
17380 ("permil")
17381 ("lsaquo")
17382 ("rsaquo")
17383 ("euro")
17385 ("arccos"."arccos")
17386 ("arcsin"."arcsin")
17387 ("arctan"."arctan")
17388 ("arg"."arg")
17389 ("cos"."cos")
17390 ("cosh"."cosh")
17391 ("cot"."cot")
17392 ("coth"."coth")
17393 ("csc"."csc")
17394 ("deg"."deg")
17395 ("det"."det")
17396 ("dim"."dim")
17397 ("exp"."exp")
17398 ("gcd"."gcd")
17399 ("hom"."hom")
17400 ("inf"."inf")
17401 ("ker"."ker")
17402 ("lg"."lg")
17403 ("lim"."lim")
17404 ("liminf"."liminf")
17405 ("limsup"."limsup")
17406 ("ln"."ln")
17407 ("log"."log")
17408 ("max"."max")
17409 ("min"."min")
17410 ("Pr"."Pr")
17411 ("sec"."sec")
17412 ("sin"."sin")
17413 ("sinh"."sinh")
17414 ("sup"."sup")
17415 ("tan"."tan")
17416 ("tanh"."tanh")
17418 "Entities for TeX->HTML translation.
17419 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
17420 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
17421 In that case, \"\\ent\" will be translated to \"&other;\".
17422 The list contains HTML entities for Latin-1, Greek and other symbols.
17423 It is supplemented by a number of commonly used TeX macros with appropriate
17424 translations. There is currently no way for users to extend this.")
17426 ;;; General functions for all backends
17428 (defun org-cleaned-string-for-export (string &rest parameters)
17429 "Cleanup a buffer substring so that links can be created safely."
17430 (interactive)
17431 (let* ((re-radio (and org-target-link-regexp
17432 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
17433 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
17434 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
17435 (re-archive (concat ":" org-archive-tag ":"))
17436 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
17437 (htmlp (plist-get parameters :for-html))
17438 (outline-regexp "\\*+")
17439 rtn p)
17440 (save-excursion
17441 (set-buffer (get-buffer-create " org-mode-tmp"))
17442 (erase-buffer)
17443 (insert string)
17444 ;; Remove license-to-kill stuff
17445 (while (setq p (text-property-any (point-min) (point-max)
17446 :org-license-to-kill t))
17447 (delete-region p (next-single-property-change p :org-license-to-kill)))
17449 (let ((org-inhibit-startup t)) (org-mode))
17450 (untabify (point-min) (point-max))
17452 ;; Get the correct stuff before the first headline
17453 (when (plist-get parameters :skip-before-1st-heading)
17454 (goto-char (point-min))
17455 (when (re-search-forward "^\\*+[ \t]" nil t)
17456 (delete-region (point-min) (match-beginning 0))
17457 (goto-char (point-min))
17458 (insert "\n")))
17459 (when (plist-get parameters :add-text)
17460 (goto-char (point-min))
17461 (insert (plist-get parameters :add-text) "\n"))
17463 ;; Get rid of archived trees
17464 (when (not (eq org-export-with-archived-trees t))
17465 (goto-char (point-min))
17466 (while (re-search-forward re-archive nil t)
17467 (if (not (org-on-heading-p t))
17468 (org-end-of-subtree t)
17469 (beginning-of-line 1)
17470 (delete-region
17471 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
17472 (org-end-of-subtree t)))))
17474 ;; Protect stuff from HTML processing
17475 (goto-char (point-min))
17476 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
17477 (add-text-properties (match-beginning 0) (match-end 0)
17478 '(org-protected t)))
17479 (when htmlp
17480 (goto-char (point-min))
17481 (while (re-search-forward "^#\\+HTML:[ \t]*\\(.*\\)" nil t)
17482 (replace-match "\\1" t)
17483 (add-text-properties
17484 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
17485 '(org-protected t))))
17486 (goto-char (point-min))
17487 (while (re-search-forward
17488 "^#\\+BEGIN_HTML\\>.*\\(\\(\n.*\\)*?\n\\)#\\+END_HTML\\>.*\n?" nil t)
17489 (if htmlp
17490 (add-text-properties (match-beginning 1) (1+ (match-end 1))
17491 '(org-protected t))
17492 (delete-region (match-beginning 0) (match-end 0))))
17493 (goto-char (point-min))
17494 (while (re-search-forward re-quote nil t)
17495 (goto-char (match-beginning 0))
17496 (end-of-line 1)
17497 (add-text-properties (point) (org-end-of-subtree t)
17498 '(org-protected t)))
17500 ;; Find targets in comments and move them out of comments,
17501 ;; but mark them as targets that should be invisible
17502 (goto-char (point-min))
17503 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
17504 (replace-match "\\1(INVISIBLE)"))
17506 ;; Remove comments
17507 (goto-char (point-min))
17508 (while (re-search-forward "^#.*\n?" nil t)
17509 (replace-match ""))
17511 ;; Find matches for radio targets and turn them into internal links
17512 (goto-char (point-min))
17513 (when re-radio
17514 (while (re-search-forward re-radio nil t)
17515 (org-if-unprotected
17516 (replace-match "\\1[[\\2]]"))))
17518 ;; Find all links that contain a newline and put them into a single line
17519 (goto-char (point-min))
17520 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
17521 (org-if-unprotected
17522 (replace-match "\\1 \\3")
17523 (goto-char (match-beginning 0))))
17525 ;; Convert LaTeX fragments to images
17526 (when (plist-get parameters :LaTeX-fragments)
17527 (org-format-latex
17528 (concat "ltxpng/" (file-name-sans-extension
17529 (file-name-nondirectory
17530 org-current-export-file)))
17531 org-current-export-dir nil "Creating LaTeX image %s"))
17532 (message "Exporting...")
17534 ;; Normalize links: Convert angle and plain links into bracket links
17535 ;; Expand link abbreviations
17536 (goto-char (point-min))
17537 (while (re-search-forward re-plain-link nil t)
17538 (goto-char (1- (match-end 0)))
17539 (org-if-unprotected
17540 (replace-match
17541 (concat
17542 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
17543 t t)))
17544 (goto-char (point-min))
17545 (while (re-search-forward re-angle-link nil t)
17546 (goto-char (1- (match-end 0)))
17547 (org-if-unprotected
17548 (replace-match
17549 (concat
17550 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
17551 t t)))
17552 (goto-char (point-min))
17553 (while (re-search-forward org-bracket-link-regexp nil t)
17554 (org-if-unprotected
17555 (replace-match
17556 (concat "[[" (save-match-data
17557 (org-link-expand-abbrev (match-string 1)))
17559 (if (match-end 3)
17560 (match-string 2)
17561 (concat "[" (match-string 1) "]"))
17562 "]")
17563 t t)))
17565 ;; Find multiline emphasis and put them into single line
17566 (when (plist-get parameters :emph-multiline)
17567 (goto-char (point-min))
17568 (while (re-search-forward org-emph-re nil t)
17569 (if (not (= (char-after (match-beginning 3))
17570 (char-after (match-beginning 4))))
17571 (org-if-unprotected
17572 (subst-char-in-region (match-beginning 0) (match-end 0)
17573 ?\n ?\ t)
17574 (goto-char (1- (match-end 0))))
17575 (goto-char (1+ (match-beginning 0))))))
17577 (setq rtn (buffer-string)))
17578 (kill-buffer " org-mode-tmp")
17579 rtn))
17581 (defun org-export-grab-title-from-buffer ()
17582 "Get a title for the current document, from looking at the buffer."
17583 (let (buffer-read-only)
17584 (save-excursion
17585 (goto-char (point-min))
17586 (let ((end (save-excursion (outline-next-heading) (point))))
17587 (when (re-search-forward "^[ \t]*[^# \t\r\n].*\n" end t)
17588 ;; Mark the line so that it will not be exported as normal text.
17589 (org-unmodified
17590 (add-text-properties (match-beginning 0) (match-end 0)
17591 (list :org-license-to-kill t)))
17592 ;; Return the title string
17593 (org-trim (match-string 0)))))))
17595 (defun org-solidify-link-text (s &optional alist)
17596 "Take link text and make a safe target out of it."
17597 (save-match-data
17598 (let* ((rtn
17599 (mapconcat
17600 'identity
17601 (org-split-string s "[ \t\r\n]+") "--"))
17602 (a (assoc rtn alist)))
17603 (or (cdr a) rtn))))
17605 ;; Variable holding the vector with section numbers
17606 (defvar org-section-numbers (make-vector org-level-max 0))
17608 (defun org-init-section-numbers ()
17609 "Initialize the vector for the section numbers."
17610 (let* ((level -1)
17611 (numbers (nreverse (org-split-string "" "\\.")))
17612 (depth (1- (length org-section-numbers)))
17613 (i depth) number-string)
17614 (while (>= i 0)
17615 (if (> i level)
17616 (aset org-section-numbers i 0)
17617 (setq number-string (or (car numbers) "0"))
17618 (if (string-match "\\`[A-Z]\\'" number-string)
17619 (aset org-section-numbers i
17620 (- (string-to-char number-string) ?A -1))
17621 (aset org-section-numbers i (string-to-number number-string)))
17622 (pop numbers))
17623 (setq i (1- i)))))
17625 (defun org-section-number (&optional level)
17626 "Return a string with the current section number.
17627 When LEVEL is non-nil, increase section numbers on that level."
17628 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
17629 (when level
17630 (when (> level -1)
17631 (aset org-section-numbers
17632 level (1+ (aref org-section-numbers level))))
17633 (setq idx (1+ level))
17634 (while (<= idx depth)
17635 (if (not (= idx 1))
17636 (aset org-section-numbers idx 0))
17637 (setq idx (1+ idx))))
17638 (setq idx 0)
17639 (while (<= idx depth)
17640 (setq n (aref org-section-numbers idx))
17641 (setq string (concat string (if (not (string= string "")) "." "")
17642 (int-to-string n)))
17643 (setq idx (1+ idx)))
17644 (save-match-data
17645 (if (string-match "\\`\\([@0]\\.\\)+" string)
17646 (setq string (replace-match "" t nil string)))
17647 (if (string-match "\\(\\.0\\)+\\'" string)
17648 (setq string (replace-match "" t nil string))))
17649 string))
17651 ;;; ASCII export
17653 (defvar org-last-level nil) ; dynamically scoped variable
17654 (defvar org-levels-open nil) ; dynamically scoped parameter
17655 (defvar org-ascii-current-indentation nil) ; For communication
17657 (defun org-export-as-ascii (arg)
17658 "Export the outline as a pretty ASCII file.
17659 If there is an active region, export only the region.
17660 The prefix ARG specifies how many levels of the outline should become
17661 underlined headlines. The default is 3."
17662 (interactive "P")
17663 (setq-default org-todo-line-regexp org-todo-line-regexp)
17664 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
17665 (org-infile-export-plist)))
17666 (custom-times org-display-custom-times)
17667 (org-ascii-current-indentation '(0 . 0))
17668 (level 0) line txt
17669 (umax nil)
17670 (umax-toc nil)
17671 (case-fold-search nil)
17672 (filename (concat (file-name-as-directory
17673 (org-export-directory :ascii opt-plist))
17674 (file-name-sans-extension
17675 (file-name-nondirectory buffer-file-name))
17676 ".txt"))
17677 (buffer (find-file-noselect filename))
17678 (org-levels-open (make-vector org-level-max nil))
17679 (odd org-odd-levels-only)
17680 (date (format-time-string "%Y/%m/%d" (current-time)))
17681 (time (format-time-string "%X" (org-current-time)))
17682 (author (plist-get opt-plist :author))
17683 (title (or (plist-get opt-plist :title)
17684 (and (not
17685 (plist-get opt-plist :skip-before-1st-heading))
17686 (org-export-grab-title-from-buffer))
17687 (file-name-sans-extension
17688 (file-name-nondirectory buffer-file-name))))
17689 (email (plist-get opt-plist :email))
17690 (language (plist-get opt-plist :language))
17691 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
17692 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
17693 (todo nil)
17694 (lang-words nil)
17695 (region
17696 (buffer-substring
17697 (if (org-region-active-p) (region-beginning) (point-min))
17698 (if (org-region-active-p) (region-end) (point-max))))
17699 (lines (org-skip-comments
17700 (org-split-string
17701 (org-cleaned-string-for-export
17702 region
17703 :skip-before-1st-heading
17704 (plist-get opt-plist :skip-before-1st-heading)
17705 :add-text (plist-get opt-plist :text))
17706 "[\r\n]")))
17707 thetoc have-headings first-heading-pos)
17709 (let (buffer-read-only)
17710 (org-unmodified
17711 (remove-text-properties (point-min) (point-max)
17712 '(:org-license-to-kill t))))
17714 (setq org-last-level 1)
17715 (org-init-section-numbers)
17717 (find-file-noselect filename)
17719 (setq lang-words (or (assoc language org-export-language-setup)
17720 (assoc "en" org-export-language-setup)))
17721 (switch-to-buffer-other-window buffer)
17722 (erase-buffer)
17723 (fundamental-mode)
17724 ;; create local variables for all options, to make sure all called
17725 ;; functions get the correct information
17726 (mapcar (lambda (x)
17727 (set (make-local-variable (cdr x))
17728 (plist-get opt-plist (car x))))
17729 org-export-plist-vars)
17730 (org-set-local 'org-odd-levels-only odd)
17731 (setq umax (if arg (prefix-numeric-value arg)
17732 org-export-headline-levels))
17733 (setq umax-toc (if (integerp org-export-with-toc)
17734 (min org-export-with-toc umax)
17735 umax))
17737 ;; File header
17738 (if title (org-insert-centered title ?=))
17739 (insert "\n")
17740 (if (or author email)
17741 (insert (concat (nth 1 lang-words) ": " (or author "")
17742 (if email (concat " <" email ">") "")
17743 "\n")))
17744 (if (and date time)
17745 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
17747 (insert "\n\n")
17749 (if org-export-with-toc
17750 (progn
17751 (push (concat (nth 3 lang-words) "\n") thetoc)
17752 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
17753 (mapcar '(lambda (line)
17754 (if (string-match org-todo-line-regexp
17755 line)
17756 ;; This is a headline
17757 (progn
17758 (setq have-headings t)
17759 (setq level (- (match-end 1) (match-beginning 1))
17760 level (org-tr-level level)
17761 txt (match-string 3 line)
17762 todo
17763 (or (and org-export-mark-todo-in-toc
17764 (match-beginning 2)
17765 (not (member (match-string 2 line)
17766 org-done-keywords)))
17767 ; TODO, not DONE
17768 (and org-export-mark-todo-in-toc
17769 (= level umax-toc)
17770 (org-search-todo-below
17771 line lines level))))
17772 (setq txt (org-html-expand-for-ascii txt))
17774 (if (and (memq org-export-with-tags '(not-in-toc nil))
17775 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
17776 (setq txt (replace-match "" t t txt)))
17777 (if (string-match quote-re0 txt)
17778 (setq txt (replace-match "" t t txt)))
17780 (if org-export-with-section-numbers
17781 (setq txt (concat (org-section-number level)
17782 " " txt)))
17783 (if (<= level umax-toc)
17784 (progn
17785 (push
17786 (concat
17787 (make-string (* (1- level) 4) ?\ )
17788 (format (if todo "%s (*)\n" "%s\n") txt))
17789 thetoc)
17790 (setq org-last-level level))
17791 ))))
17792 lines)
17793 (setq thetoc (if have-headings (nreverse thetoc) nil))))
17795 (org-init-section-numbers)
17796 (while (setq line (pop lines))
17797 ;; Remove the quoted HTML tags.
17798 (setq line (org-html-expand-for-ascii line))
17799 ;; Remove targets
17800 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
17801 (setq line (replace-match "" t t line)))
17802 ;; Replace internal links
17803 (while (string-match org-bracket-link-regexp line)
17804 (setq line (replace-match
17805 (if (match-end 3) "[\\3]" "[\\1]")
17806 t nil line)))
17807 (when custom-times
17808 (setq line (org-translate-time line)))
17809 (cond
17810 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
17811 ;; a Headline
17812 (setq first-heading-pos (or first-heading-pos (point)))
17813 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
17814 txt (match-string 2 line))
17815 (org-ascii-level-start level txt umax lines))
17817 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
17818 (normal-mode)
17820 ;; insert the table of contents
17821 (when thetoc
17822 (goto-char (point-min))
17823 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
17824 (progn
17825 (goto-char (match-beginning 0))
17826 (replace-match ""))
17827 (goto-char first-heading-pos))
17828 (mapc 'insert thetoc)
17829 (or (looking-at "[ \t]*\n[ \t]*\n")
17830 (insert "\n\n")))
17832 (save-buffer)
17833 ;; remove display and invisible chars
17834 (let (beg end)
17835 (goto-char (point-min))
17836 (while (setq beg (next-single-property-change (point) 'display))
17837 (setq end (next-single-property-change beg 'display))
17838 (delete-region beg end)
17839 (goto-char beg)
17840 (insert "=>"))
17841 (goto-char (point-min))
17842 (while (setq beg (next-single-property-change (point) 'org-cwidth))
17843 (setq end (next-single-property-change beg 'org-cwidth))
17844 (delete-region beg end)
17845 (goto-char beg)))
17846 (goto-char (point-min))))
17848 (defun org-search-todo-below (line lines level)
17849 "Search the subtree below LINE for any TODO entries."
17850 (let ((rest (cdr (memq line lines)))
17851 (re org-todo-line-regexp)
17852 line lv todo)
17853 (catch 'exit
17854 (while (setq line (pop rest))
17855 (if (string-match re line)
17856 (progn
17857 (setq lv (- (match-end 1) (match-beginning 1))
17858 todo (and (match-beginning 2)
17859 (not (member (match-string 2 line)
17860 org-done-keywords))))
17861 ; TODO, not DONE
17862 (if (<= lv level) (throw 'exit nil))
17863 (if todo (throw 'exit t))))))))
17865 (defun org-html-expand-for-ascii (line)
17866 "Handle quoted HTML for ASCII export."
17867 (if org-export-html-expand
17868 (while (string-match "@<[^<>\n]*>" line)
17869 ;; We just remove the tags for now.
17870 (setq line (replace-match "" nil nil line))))
17871 line)
17873 (defun org-insert-centered (s &optional underline)
17874 "Insert the string S centered and underline it with character UNDERLINE."
17875 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
17876 (insert (make-string ind ?\ ) s "\n")
17877 (if underline
17878 (insert (make-string ind ?\ )
17879 (make-string (string-width s) underline)
17880 "\n"))))
17882 (defun org-ascii-level-start (level title umax &optional lines)
17883 "Insert a new level in ASCII export."
17884 (let (char (n (- level umax 1)) (ind 0))
17885 (if (> level umax)
17886 (progn
17887 (insert (make-string (* 2 n) ?\ )
17888 (char-to-string (nth (% n (length org-export-ascii-bullets))
17889 org-export-ascii-bullets))
17890 " " title "\n")
17891 ;; find the indentation of the next non-empty line
17892 (catch 'stop
17893 (while lines
17894 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
17895 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
17896 (throw 'stop (setq ind (org-get-indentation (car lines)))))
17897 (pop lines)))
17898 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
17899 (if (or (not (equal (char-before) ?\n))
17900 (not (equal (char-before (1- (point))) ?\n)))
17901 (insert "\n"))
17902 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
17903 (unless org-export-with-tags
17904 (if (string-match "[ \t]+\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
17905 (setq title (replace-match "" t t title))))
17906 (if org-export-with-section-numbers
17907 (setq title (concat (org-section-number level) " " title)))
17908 (insert title "\n" (make-string (string-width title) char) "\n")
17909 (setq org-ascii-current-indentation '(0 . 0)))))
17911 (defun org-export-visible (type arg)
17912 "Create a copy of the visible part of the current buffer, and export it.
17913 The copy is created in a temporary buffer and removed after use.
17914 TYPE is the final key (as a string) that also select the export command in
17915 the `C-c C-e' export dispatcher.
17916 As a special case, if the you type SPC at the prompt, the temporary
17917 org-mode file will not be removed but presented to you so that you can
17918 continue to use it. The prefix arg ARG is passed through to the exporting
17919 command."
17920 (interactive
17921 (list (progn
17922 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H]uffer with HTML [x]OXO [ ]keep buffer")
17923 (read-char-exclusive))
17924 current-prefix-arg))
17925 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
17926 (error "Invalid export key"))
17927 (let* ((binding (cdr (assoc type
17928 '((?a . org-export-as-ascii)
17929 (?\C-a . org-export-as-ascii)
17930 (?b . org-export-as-html-and-open)
17931 (?\C-b . org-export-as-html-and-open)
17932 (?h . org-export-as-html)
17933 (?H . org-export-as-html-to-buffer)
17934 (?x . org-export-as-xoxo)))))
17935 (keepp (equal type ?\ ))
17936 (file buffer-file-name)
17937 (buffer (get-buffer-create "*Org Export Visible*"))
17938 s e)
17939 (with-current-buffer buffer (erase-buffer))
17940 (save-excursion
17941 (setq s (goto-char (point-min)))
17942 (while (not (= (point) (point-max)))
17943 (goto-char (org-find-invisible))
17944 (append-to-buffer buffer s (point))
17945 (setq s (goto-char (org-find-visible))))
17946 (goto-char (point-min))
17947 (unless keepp
17948 ;; Copy all comment lines to the end, to make sure #+ settings are
17949 ;; still available for the second export step. Kind of a hack, but
17950 ;; does do the trick.
17951 (if (looking-at "#[^\r\n]*")
17952 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
17953 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
17954 (append-to-buffer buffer (1+ (match-beginning 0))
17955 (min (point-max) (1+ (match-end 0))))))
17956 (set-buffer buffer)
17957 (let ((buffer-file-name file)
17958 (org-inhibit-startup t))
17959 (org-mode)
17960 (show-all)
17961 (unless keepp (funcall binding arg))))
17962 (if (not keepp)
17963 (kill-buffer buffer)
17964 (switch-to-buffer-other-window buffer)
17965 (goto-char (point-min)))))
17967 (defun org-find-visible ()
17968 (let ((s (point)))
17969 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17970 (get-char-property s 'invisible)))
17972 (defun org-find-invisible ()
17973 (let ((s (point)))
17974 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
17975 (not (get-char-property s 'invisible))))
17978 ;;; HTML export
17980 (defun org-get-current-options ()
17981 "Return a string with current options as keyword options.
17982 Does include HTML export options as well as TODO and CATEGORY stuff."
17983 (format
17984 "#+TITLE: %s
17985 #+AUTHOR: %s
17986 #+EMAIL: %s
17987 #+LANGUAGE: %s
17988 #+TEXT: Some descriptive text to be emitted. Several lines OK.
17989 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s skip:%s
17990 #+CATEGORY: %s
17991 #+SEQ_TODO: %s
17992 #+TYP_TODO: %s
17993 #+STARTUP: %s %s %s %s %s
17994 #+TAGS: %s
17995 #+ARCHIVE: %s
17996 #+LINK: %s
17998 (buffer-name) (user-full-name) user-mail-address org-export-default-language
17999 org-export-headline-levels
18000 org-export-with-section-numbers
18001 org-export-with-toc
18002 org-export-preserve-breaks
18003 org-export-html-expand
18004 org-export-with-fixed-width
18005 org-export-with-tables
18006 org-export-with-sub-superscripts
18007 org-export-with-emphasize
18008 org-export-with-TeX-macros
18009 org-export-with-LaTeX-fragments
18010 org-export-skip-text-before-1st-heading
18011 (file-name-nondirectory buffer-file-name)
18012 "TODO FEEDBACK VERIFY DONE"
18013 "Me Jason Marie DONE"
18014 (cdr (assoc org-startup-folded
18015 '((nil . "showall") (t . "overview") (content . "content"))))
18016 (if org-odd-levels-only "odd" "oddeven")
18017 (if org-hide-leading-stars "hidestars" "showstars")
18018 (if org-startup-align-all-tables "align" "noalign")
18019 (cond ((eq t org-log-done) "logdone")
18020 ((not org-log-done) "nologging")
18021 ((listp org-log-done)
18022 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
18023 org-log-done " ")))
18024 (or (mapconcat (lambda (x)
18025 (cond
18026 ((equal '(:startgroup) x) "{")
18027 ((equal '(:endgroup) x) "}")
18028 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
18029 (t (car x))))
18030 (or org-tag-alist (org-get-buffer-tags)) " ") "")
18031 org-archive-location
18032 "org file:~/org/%s.org"
18035 (defun org-insert-export-options-template ()
18036 "Insert into the buffer a template with information for exporting."
18037 (interactive)
18038 (if (not (bolp)) (newline))
18039 (let ((s (org-get-current-options)))
18040 (and (string-match "#\\+CATEGORY" s)
18041 (setq s (substring s 0 (match-beginning 0))))
18042 (insert s)))
18044 (defun org-toggle-fixed-width-section (arg)
18045 "Toggle the fixed-width export.
18046 If there is no active region, the QUOTE keyword at the current headline is
18047 inserted or removed. When present, it causes the text between this headline
18048 and the next to be exported as fixed-width text, and unmodified.
18049 If there is an active region, this command adds or removes a colon as the
18050 first character of this line. If the first character of a line is a colon,
18051 this line is also exported in fixed-width font."
18052 (interactive "P")
18053 (let* ((cc 0)
18054 (regionp (org-region-active-p))
18055 (beg (if regionp (region-beginning) (point)))
18056 (end (if regionp (region-end)))
18057 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
18058 (re "[ \t]*\\(:\\)")
18059 off)
18060 (if regionp
18061 (save-excursion
18062 (goto-char beg)
18063 (setq cc (current-column))
18064 (beginning-of-line 1)
18065 (setq off (looking-at re))
18066 (while (> nlines 0)
18067 (setq nlines (1- nlines))
18068 (beginning-of-line 1)
18069 (cond
18070 (arg
18071 (move-to-column cc t)
18072 (insert ":\n")
18073 (forward-line -1))
18074 ((and off (looking-at re))
18075 (replace-match "" t t nil 1))
18076 ((not off) (move-to-column cc t) (insert ":")))
18077 (forward-line 1)))
18078 (save-excursion
18079 (org-back-to-heading)
18080 (if (looking-at (concat outline-regexp
18081 "\\( +\\<" org-quote-string "\\>\\)"))
18082 (replace-match "" t t nil 1)
18083 (if (looking-at outline-regexp)
18084 (progn
18085 (goto-char (match-end 0))
18086 (insert " " org-quote-string))))))))
18088 (defun org-export-as-html-and-open (arg)
18089 "Export the outline as HTML and immediately open it with a browser.
18090 If there is an active region, export only the region.
18091 The prefix ARG specifies how many levels of the outline should become
18092 headlines. The default is 3. Lower levels will become bulleted lists."
18093 (interactive "P")
18094 (org-export-as-html arg 'hidden)
18095 (org-open-file buffer-file-name))
18097 (defun org-export-as-html-batch ()
18098 "Call `org-export-as-html', may be used in batch processing as
18099 emacs --batch
18100 --load=$HOME/lib/emacs/org.el
18101 --eval \"(setq org-export-headline-levels 2)\"
18102 --visit=MyFile --funcall org-export-as-html-batch"
18103 (org-export-as-html org-export-headline-levels 'hidden))
18105 (defun org-export-as-html-to-buffer (arg)
18106 "Call `org-exort-as-html` with output to a temporary buffer.
18107 No file is created. The prefix ARG is passed through to `org-export-as-html'."
18108 (interactive "P")
18109 (org-export-as-html arg nil nil t)
18110 (switch-to-buffer-other-window "*Org HTML Export*"))
18112 (defun org-export-as-html (arg &optional hidden ext-plist temp-buffer-only)
18113 "Export the outline as a pretty HTML file.
18114 If there is an active region, export only the region. The prefix
18115 ARG specifies how many levels of the outline should become
18116 headlines. The default is 3. Lower levels will become bulleted
18117 lists. When HIDDEN is non-nil, don't display the HTML buffer.
18118 EXT-PLIST is a property list with external parameters overriding
18119 org-mode's default settings, but still inferior to file-local
18120 settings. Wehn TEMP-BUFFER-ONLY is non-nil, export to a buffer not
18121 associated with a file."
18122 (interactive "P")
18123 (message "Exporting...")
18124 (setq-default org-todo-line-regexp org-todo-line-regexp)
18125 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
18126 (setq-default org-done-keywords org-done-keywords)
18127 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
18128 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
18129 ext-plist
18130 (org-infile-export-plist)))
18132 (style (plist-get opt-plist :style))
18133 (link-validate (plist-get opt-plist :link-validation-function))
18134 valid thetoc have-headings first-heading-pos
18135 (odd org-odd-levels-only)
18136 (region-p (org-region-active-p))
18137 (region
18138 (buffer-substring
18139 (if region-p (region-beginning) (point-min))
18140 (if region-p (region-end) (point-max))))
18141 ;; The following two are dynamically scoped into other
18142 ;; routines below.
18143 (org-current-export-dir (org-export-directory :html opt-plist))
18144 (org-current-export-file buffer-file-name)
18145 (level 0) (line "") (origline "") txt todo
18146 (umax nil)
18147 (umax-toc nil)
18148 (filename (concat (file-name-as-directory
18149 (org-export-directory :html opt-plist))
18150 (file-name-sans-extension
18151 (file-name-nondirectory buffer-file-name))
18152 ".html"))
18153 (current-dir (file-name-directory buffer-file-name))
18154 (buffer (if temp-buffer-only
18155 (get-buffer-create "*Org HTML Export*")
18156 (find-file-noselect filename)))
18157 (org-levels-open (make-vector org-level-max nil))
18158 (date (format-time-string "%Y/%m/%d" (current-time)))
18159 (time (format-time-string "%X" (org-current-time)))
18160 (author (plist-get opt-plist :author))
18161 (title (or (plist-get opt-plist :title)
18162 (and (not
18163 (plist-get opt-plist :skip-before-1st-heading))
18164 (org-export-grab-title-from-buffer))
18165 (file-name-sans-extension
18166 (file-name-nondirectory buffer-file-name))))
18167 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
18168 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
18169 (inquote nil)
18170 (infixed nil)
18171 (in-local-list nil)
18172 (local-list-num nil)
18173 (local-list-indent nil)
18174 (llt org-plain-list-ordered-item-terminator)
18175 (email (plist-get opt-plist :email))
18176 (language (plist-get opt-plist :language))
18177 (lang-words nil)
18178 (target-alist nil) tg
18179 (head-count 0) cnt
18180 (start 0)
18181 (coding-system (and (boundp 'buffer-file-coding-system)
18182 buffer-file-coding-system))
18183 (coding-system-for-write coding-system)
18184 (save-buffer-coding-system coding-system)
18185 (charset (and coding-system
18186 (fboundp 'coding-system-get)
18187 (coding-system-get coding-system 'mime-charset)))
18188 (lines
18189 (org-skip-comments (org-split-string
18190 (org-cleaned-string-for-export
18191 region
18192 :emph-multiline t
18193 :for-html t
18194 :skip-before-1st-heading
18195 (plist-get opt-plist :skip-before-1st-heading)
18196 :add-text
18197 (plist-get opt-plist :text)
18198 :LaTeX-fragments
18199 (plist-get opt-plist :LaTeX-fragments))
18200 "[\r\n]")))
18201 table-open type
18202 table-buffer table-orig-buffer
18203 ind start-is-num starter didclose
18204 rpl path desc descp desc1 desc2 link
18207 (let (buffer-read-only)
18208 (org-unmodified
18209 (remove-text-properties (point-min) (point-max)
18210 '(:org-license-to-kill t))))
18212 (message "Exporting...")
18214 (setq org-last-level 1)
18215 (org-init-section-numbers)
18217 ;; Get the language-dependent settings
18218 (setq lang-words (or (assoc language org-export-language-setup)
18219 (assoc "en" org-export-language-setup)))
18221 ;; Switch to the output buffer
18222 (if (or hidden t)
18223 (set-buffer buffer)
18224 (switch-to-buffer-other-window buffer))
18225 (erase-buffer)
18226 (fundamental-mode)
18227 (let ((case-fold-search nil)
18228 (org-odd-levels-only odd))
18229 ;; create local variables for all options, to make sure all called
18230 ;; functions get the correct information
18231 (mapcar (lambda (x)
18232 (set (make-local-variable (cdr x))
18233 (plist-get opt-plist (car x))))
18234 org-export-plist-vars)
18235 (setq umax (if arg (prefix-numeric-value arg)
18236 org-export-headline-levels))
18237 (setq umax-toc (if (integerp org-export-with-toc)
18238 (min org-export-with-toc umax)
18239 umax))
18240 ;; File header
18241 (insert (format
18242 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
18243 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
18244 <html xmlns=\"http://www.w3.org/1999/xhtml\"
18245 lang=\"%s\" xml:lang=\"%s\">
18246 <head>
18247 <title>%s</title>
18248 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
18249 <meta name=\"generator\" content=\"Org-mode\"/>
18250 <meta name=\"generated\" content=\"%s %s\"/>
18251 <meta name=\"author\" content=\"%s\"/>
18253 </head><body>
18255 language language (org-html-expand title) (or charset "iso-8859-1")
18256 date time author style))
18259 (insert (or (plist-get opt-plist :preamble) ""))
18261 (when (plist-get opt-plist :auto-preamble)
18262 (if title (insert (format org-export-html-title-format
18263 (org-html-expand title)))))
18265 (if org-export-with-toc
18266 (progn
18267 (push (format "<h%d>%s</h%d>\n"
18268 org-export-html-toplevel-hlevel
18269 (nth 3 lang-words)
18270 org-export-html-toplevel-hlevel)
18271 thetoc)
18272 (push "<ul>\n<li>" thetoc)
18273 (setq lines
18274 (mapcar '(lambda (line)
18275 (if (string-match org-todo-line-regexp line)
18276 ;; This is a headline
18277 (progn
18278 (setq have-headings t)
18279 (setq level (- (match-end 1) (match-beginning 1))
18280 level (org-tr-level level)
18281 txt (save-match-data
18282 (org-html-expand
18283 (org-export-cleanup-toc-line
18284 (match-string 3 line))))
18285 todo
18286 (or (and org-export-mark-todo-in-toc
18287 (match-beginning 2)
18288 (not (member (match-string 2 line)
18289 org-done-keywords)))
18290 ; TODO, not DONE
18291 (and org-export-mark-todo-in-toc
18292 (= level umax-toc)
18293 (org-search-todo-below
18294 line lines level))))
18295 (if (and (memq org-export-with-tags '(not-in-toc nil))
18296 (string-match "[ \t]+:[a-zA-Z0-9_@:]+:[ \t]*$" txt))
18297 (setq txt (replace-match "" t t txt)))
18298 (if (string-match quote-re0 txt)
18299 (setq txt (replace-match "" t t txt)))
18300 (if org-export-with-section-numbers
18301 (setq txt (concat (org-section-number level)
18302 " " txt)))
18303 (if (<= level umax-toc)
18304 (progn
18305 (setq head-count (+ head-count 1))
18306 (if (> level org-last-level)
18307 (progn
18308 (setq cnt (- level org-last-level))
18309 (while (>= (setq cnt (1- cnt)) 0)
18310 (push "\n<ul>\n<li>" thetoc))
18311 (push "\n" thetoc)))
18312 (if (< level org-last-level)
18313 (progn
18314 (setq cnt (- org-last-level level))
18315 (while (>= (setq cnt (1- cnt)) 0)
18316 (push "</li>\n</ul>" thetoc))
18317 (push "\n" thetoc)))
18318 ;; Check for targets
18319 (while (string-match org-target-regexp line)
18320 (setq tg (match-string 1 line)
18321 line (replace-match
18322 (concat "@<span class=\"target\">" tg "@</span> ")
18323 t t line))
18324 (push (cons (org-solidify-link-text tg)
18325 (format "sec-%d" head-count))
18326 target-alist))
18327 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
18328 (setq txt (replace-match "" t t txt)))
18329 (push
18330 (format
18331 (if todo
18332 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
18333 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
18334 head-count txt) thetoc)
18336 (setq org-last-level level))
18338 line)
18339 lines))
18340 (while (> org-last-level 0)
18341 (setq org-last-level (1- org-last-level))
18342 (push "</li>\n</ul>\n" thetoc))
18343 (setq thetoc (if have-headings (nreverse thetoc) nil))))
18344 (setq head-count 0)
18345 (org-init-section-numbers)
18347 (while (setq line (pop lines) origline line)
18348 (catch 'nextline
18350 ;; end of quote section?
18351 (when (and inquote (string-match "^\\*+" line))
18352 (insert "</pre>\n")
18353 (setq inquote nil))
18354 ;; inside a quote section?
18355 (when inquote
18356 (insert (org-html-protect line) "\n")
18357 (throw 'nextline nil))
18359 ;; verbatim lines
18360 (when (and org-export-with-fixed-width
18361 (string-match "^[ \t]*:\\(.*\\)" line))
18362 (when (not infixed)
18363 (setq infixed t)
18364 (insert "<pre>\n"))
18365 (insert (org-html-protect (match-string 1 line)) "\n")
18366 (when (and lines
18367 (not (string-match "^[ \t]*\\(:.*\\)"
18368 (car lines))))
18369 (setq infixed nil)
18370 (insert "</pre>\n"))
18371 (throw 'nextline nil))
18373 ;; Protected HTML
18374 (when (get-text-property 0 'org-protected line)
18375 (let (par)
18376 (when (re-search-backward
18377 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
18378 (setq par (match-string 1))
18379 (replace-match "\\2\n"))
18380 (insert line "\n")
18381 (while (and lines
18382 (get-text-property 0 'org-protected (car lines)))
18383 (insert (pop lines) "\n"))
18384 (and par (insert "<p>\n")))
18385 (throw 'nextline nil))
18387 ;; Horizontal line
18388 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
18389 (insert "\n<hr/>\n")
18390 (throw 'nextline nil))
18392 ;; make targets to anchors
18393 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
18394 (cond
18395 ((match-end 2)
18396 (setq line (replace-match
18397 (concat "@<a name=\""
18398 (org-solidify-link-text (match-string 1 line))
18399 "\">\\nbsp@</a>")
18400 t t line)))
18401 ((and org-export-with-toc (equal (string-to-char line) ?*))
18402 (setq line (replace-match
18403 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
18404 ; (concat "@<i>" (match-string 1 line) "@</i> ")
18405 t t line)))
18407 (setq line (replace-match
18408 (concat "@<a name=\""
18409 (org-solidify-link-text (match-string 1 line))
18410 "\" class=\"target\">" (match-string 1 line) "@</a> ")
18411 t t line)))))
18413 (setq line (org-html-handle-time-stamps line))
18415 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
18416 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
18417 ;; Also handle sub_superscripts and checkboxes
18418 (setq line (org-html-expand line))
18420 ;; Format the links
18421 (setq start 0)
18422 (while (string-match org-bracket-link-analytic-regexp line start)
18423 (setq start (match-beginning 0))
18424 (setq type (if (match-end 2) (match-string 2 line) "internal"))
18425 (setq path (match-string 3 line))
18426 (setq desc1 (if (match-end 5) (match-string 5 line))
18427 desc2 (if (match-end 2) (concat type ":" path) path)
18428 descp (and desc1 (not (equal desc1 desc2)))
18429 desc (or desc1 desc2))
18430 ;; Make an image out of the description if that is so wanted
18431 (when (and descp (org-file-image-p desc))
18432 (save-match-data
18433 (if (string-match "^file:" desc)
18434 (setq desc (substring desc (match-end 0)))))
18435 (setq desc (concat "<img src=\"" desc "\"/>")))
18436 ;; FIXME: do we need to unescape here somewhere?
18437 (cond
18438 ((equal type "internal")
18439 (setq rpl
18440 (concat
18441 "<a href=\"#"
18442 (org-solidify-link-text path target-alist)
18443 "\">" desc "</a>")))
18444 ((member type '("http" "https")) ; FIXME: need to test this.
18445 ;; standard URL, just check if we need to inline an image
18446 (if (and (or (eq t org-export-html-inline-images)
18447 (and org-export-html-inline-images (not descp)))
18448 (org-file-image-p path))
18449 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
18450 (setq link (concat type ":" path))
18451 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
18452 ((member type '("ftp" "mailto" "news"))
18453 ;; standard URL
18454 (setq link (concat type ":" path))
18455 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
18456 ((string= type "file")
18457 ;; FILE link
18458 (let* ((filename path)
18459 (abs-p (file-name-absolute-p filename))
18460 thefile file-is-image-p search)
18461 (save-match-data
18462 (if (string-match "::\\(.*\\)" filename)
18463 (setq search (match-string 1 filename)
18464 filename (replace-match "" t nil filename)))
18465 (setq valid
18466 (if (functionp link-validate)
18467 (funcall link-validate filename current-dir)
18469 (setq file-is-image-p (org-file-image-p filename))
18470 (setq thefile (if abs-p (expand-file-name filename) filename))
18471 (when (and org-export-html-link-org-files-as-html
18472 (string-match "\\.org$" thefile))
18473 (setq thefile (concat (substring thefile 0
18474 (match-beginning 0))
18475 ".html"))
18476 (if (and search
18477 ;; make sure this is can be used as target search
18478 (not (string-match "^[0-9]*$" search))
18479 (not (string-match "^\\*" search))
18480 (not (string-match "^/.*/$" search)))
18481 (setq thefile (concat thefile "#"
18482 (org-solidify-link-text
18483 (org-link-unescape search)))))
18484 (when (string-match "^file:" desc)
18485 (setq desc (replace-match "" t t desc))
18486 (if (string-match "\\.org$" desc)
18487 (setq desc (replace-match "" t t desc))))))
18488 (setq rpl (if (and file-is-image-p
18489 (or (eq t org-export-html-inline-images)
18490 (and org-export-html-inline-images
18491 (not descp))))
18492 (concat "<img src=\"" thefile "\"/>")
18493 (concat "<a href=\"" thefile "\">" desc "</a>")))
18494 (if (not valid) (setq rpl desc))))
18495 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
18496 (setq rpl (concat "<i>&lt;" type ":"
18497 (save-match-data (org-link-unescape path))
18498 "&gt;</i>"))))
18499 (setq line (replace-match rpl t t line)
18500 start (+ start (length rpl))))
18501 ;; TODO items
18502 (if (and (string-match org-todo-line-regexp line)
18503 (match-beginning 2))
18504 (if (member (match-string 2 line) org-done-keywords)
18505 (setq line (replace-match
18506 "<span class=\"done\">\\2</span>"
18507 t nil line 2))
18508 (setq line (replace-match "<span class=\"todo\">\\2</span>"
18509 t nil line 2))))
18511 (cond
18512 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
18513 ;; This is a headline
18514 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
18515 txt (match-string 2 line))
18516 (if (string-match quote-re0 txt)
18517 (setq txt (replace-match "" t t txt)))
18518 (if (<= level umax) (setq head-count (+ head-count 1)))
18519 (when in-local-list
18520 ;; Close any local lists before inserting a new header line
18521 (while local-list-num
18522 (org-close-li)
18523 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
18524 (pop local-list-num))
18525 (setq local-list-indent nil
18526 in-local-list nil))
18527 (setq first-heading-pos (or first-heading-pos (point)))
18528 (org-html-level-start level txt umax
18529 (and org-export-with-toc (<= level umax))
18530 head-count)
18531 ;; QUOTES
18532 (when (string-match quote-re line)
18533 (insert "<pre>")
18534 (setq inquote t)))
18536 ((and org-export-with-tables
18537 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
18538 (if (not table-open)
18539 ;; New table starts
18540 (setq table-open t table-buffer nil table-orig-buffer nil))
18541 ;; Accumulate lines
18542 (setq table-buffer (cons line table-buffer)
18543 table-orig-buffer (cons origline table-orig-buffer))
18544 (when (or (not lines)
18545 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
18546 (car lines))))
18547 (setq table-open nil
18548 table-buffer (nreverse table-buffer)
18549 table-orig-buffer (nreverse table-orig-buffer))
18550 (org-close-par-maybe)
18551 (insert (org-format-table-html table-buffer table-orig-buffer))))
18553 ;; Normal lines
18554 (when (string-match
18555 (cond
18556 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
18557 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
18558 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
18559 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
18560 line)
18561 (setq ind (org-get-string-indentation line)
18562 start-is-num (match-beginning 4)
18563 starter (if (match-beginning 2)
18564 (substring (match-string 2 line) 0 -1))
18565 line (substring line (match-beginning 5)))
18566 (unless (string-match "[^ \t]" line)
18567 ;; empty line. Pretend indentation is large.
18568 (setq ind (if org-empty-line-terminates-plain-lists
18570 (1+ (or (car local-list-indent) 1)))))
18571 (setq didclose nil)
18572 (while (and in-local-list
18573 (or (and (= ind (car local-list-indent))
18574 (not starter))
18575 (< ind (car local-list-indent))))
18576 (setq didclose t)
18577 (org-close-li)
18578 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
18579 (pop local-list-num) (pop local-list-indent)
18580 (setq in-local-list local-list-indent))
18581 (cond
18582 ((and starter
18583 (or (not in-local-list)
18584 (> ind (car local-list-indent))))
18585 ;; Start new (level of) list
18586 (org-close-par-maybe)
18587 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
18588 (push start-is-num local-list-num)
18589 (push ind local-list-indent)
18590 (setq in-local-list t))
18591 (starter
18592 ;; continue current list
18593 (org-close-li)
18594 (insert "<li>\n"))
18595 (didclose
18596 ;; we did close a list, normal text follows: need <p>
18597 (org-open-par)))
18598 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
18599 (setq line
18600 (replace-match
18601 (if (equal (match-string 1 line) "X")
18602 "<b>[X]</b>"
18603 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
18604 t t line))))
18606 ;; Empty lines start a new paragraph. If hand-formatted lists
18607 ;; are not fully interpreted, lines starting with "-", "+", "*"
18608 ;; also start a new paragraph.
18609 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
18611 ;; Check if the line break needs to be conserved
18612 (cond
18613 ((string-match "\\\\\\\\[ \t]*$" line)
18614 (setq line (replace-match "<br/>" t t line)))
18615 (org-export-preserve-breaks
18616 (setq line (concat line "<br/>"))))
18618 (insert line "\n")))))
18620 ;; Properly close all local lists and other lists
18621 (when inquote (insert "</pre>\n"))
18622 (when in-local-list
18623 ;; Close any local lists before inserting a new header line
18624 (while local-list-num
18625 (org-close-li)
18626 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
18627 (pop local-list-num))
18628 (setq local-list-indent nil
18629 in-local-list nil))
18630 (org-html-level-start 1 nil umax
18631 (and org-export-with-toc (<= level umax))
18632 head-count)
18634 (when (plist-get opt-plist :auto-postamble)
18635 (when author
18636 (insert "<p class=\"author\"> "
18637 (nth 1 lang-words) ": " author "\n")
18638 (when email
18639 (insert "<a href=\"mailto:" email "\">&lt;"
18640 email "&gt;</a>\n"))
18641 (insert "</p>\n"))
18642 (when (and date time)
18643 (insert "<p class=\"date\"> "
18644 (nth 2 lang-words) ": "
18645 date " " time "</p>\n")))
18647 (if org-export-html-with-timestamp
18648 (insert org-export-html-html-helper-timestamp))
18649 (insert (or (plist-get opt-plist :postamble) ""))
18650 (insert "</body>\n</html>\n")
18651 (normal-mode)
18652 ;; insert the table of contents
18653 (goto-char (point-min))
18654 (when thetoc
18655 (if (or (re-search-forward
18656 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
18657 (re-search-forward
18658 "\\[TABLE-OF-CONTENTS\\]" nil t))
18659 (progn
18660 (goto-char (match-beginning 0))
18661 (replace-match ""))
18662 (goto-char first-heading-pos)
18663 (when (looking-at "\\s-*</p>")
18664 (goto-char (match-end 0))
18665 (insert "\n")))
18666 (mapc 'insert thetoc))
18667 ;; remove empty paragraphs and lists
18668 (goto-char (point-min))
18669 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
18670 (replace-match ""))
18671 (goto-char (point-min))
18672 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
18673 (replace-match ""))
18674 (or temp-buffer-only (save-buffer))
18675 (goto-char (point-min))
18676 (message "Exporting... done"))))
18678 (defun org-format-table-html (lines olines)
18679 "Find out which HTML converter to use and return the HTML code."
18680 (if (string-match "^[ \t]*|" (car lines))
18681 ;; A normal org table
18682 (org-format-org-table-html lines)
18683 ;; Table made by table.el - test for spanning
18684 (let* ((hlines (delq nil (mapcar
18685 (lambda (x)
18686 (if (string-match "^[ \t]*\\+-" x) x
18687 nil))
18688 lines)))
18689 (first (car hlines))
18690 (ll (and (string-match "\\S-+" first)
18691 (match-string 0 first)))
18692 (re (concat "^[ \t]*" (regexp-quote ll)))
18693 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
18694 hlines))))
18695 (if (and (not spanning)
18696 (not org-export-prefer-native-exporter-for-tables))
18697 ;; We can use my own converter with HTML conversions
18698 (org-format-table-table-html lines)
18699 ;; Need to use the code generator in table.el, with the original text.
18700 (org-format-table-table-html-using-table-generate-source olines)))))
18702 (defun org-format-org-table-html (lines &optional splice)
18703 "Format a table into HTML."
18704 ;; Get rid of hlines at beginning and end
18705 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
18706 (setq lines (nreverse lines))
18707 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
18708 (setq lines (nreverse lines))
18709 (when org-export-table-remove-special-lines
18710 ;; Check if the table has a marking column. If yes remove the
18711 ;; column and the special lines
18712 (setq lines (org-table-clean-before-export lines)))
18714 (let ((head (and org-export-highlight-first-table-line
18715 (delq nil (mapcar
18716 (lambda (x) (string-match "^[ \t]*|-" x))
18717 (cdr lines)))))
18718 (nlines 0) fnum i
18719 tbopen line fields html)
18720 (if splice (setq head nil))
18721 (unless splice (push (if head "<thead>" "<tbody>") html))
18722 (setq tbopen t)
18723 (while (setq line (pop lines))
18724 (catch 'next-line
18725 (if (string-match "^[ \t]*|-" line)
18726 (progn
18727 (unless splice
18728 (push (if head "</thead>" "</tbody>") html)
18729 (if lines (push "<tbody>" html) (setq tbopen nil)))
18730 (setq head nil) ;; head ends here, first time around
18731 ;; ignore this line
18732 (throw 'next-line t)))
18733 ;; Break the line into fields
18734 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
18735 (unless fnum (setq fnum (make-vector (length fields) 0)))
18736 (setq nlines (1+ nlines) i -1)
18737 (push (concat "<tr>"
18738 (mapconcat
18739 (lambda (x)
18740 (setq i (1+ i))
18741 (if (and (< i nlines)
18742 (string-match org-table-number-regexp x))
18743 (incf (aref fnum i)))
18744 (if head
18745 (concat (car org-export-table-header-tags) x
18746 (cdr org-export-table-header-tags))
18747 (concat (car org-export-table-data-tags) x
18748 (cdr org-export-table-data-tags))))
18749 fields "")
18750 "</tr>")
18751 html)))
18752 (unless splice (if tbopen (push "</tbody>" html)))
18753 (unless splice (push "</table>\n" html))
18754 (setq html (nreverse html))
18755 (unless splice
18756 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
18757 (push (mapconcat
18758 (lambda (x)
18759 (format "<COL align=\"%s\">"
18760 (if (> (/ (float x) nlines) org-table-number-fraction)
18761 "right" "left")))
18762 fnum "")
18763 html)
18764 (push org-export-html-table-tag html))
18765 (concat (mapconcat 'identity html "\n") "\n")))
18767 (defun org-table-clean-before-export (lines)
18768 "Check if the table has a marking column.
18769 If yes remove the column and the special lines."
18770 (if (memq nil
18771 (mapcar
18772 (lambda (x) (or (string-match "^[ \t]*|-" x)
18773 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
18774 lines))
18775 (progn
18776 (setq org-table-clean-did-remove-column-1 nil)
18777 lines)
18778 (setq org-table-clean-did-remove-column-1 t)
18779 (delq nil
18780 (mapcar
18781 (lambda (x) (if (string-match "^[ \t]*| *[!_^/] *|" x)
18782 nil ; ignore this line
18783 (and (or (string-match "^[ \t]*|-+\\+" x)
18784 (string-match "^[ \t]*|[^|]*|" x))
18785 (replace-match "|" t t x))))
18786 lines))))
18788 (defun org-format-table-table-html (lines)
18789 "Format a table generated by table.el into HTML.
18790 This conversion does *not* use `table-generate-source' from table.el.
18791 This has the advantage that Org-mode's HTML conversions can be used.
18792 But it has the disadvantage, that no cell- or row-spanning is allowed."
18793 (let (line field-buffer
18794 (head org-export-highlight-first-table-line)
18795 fields html empty)
18796 (setq html (concat org-export-html-table-tag "\n"))
18797 (while (setq line (pop lines))
18798 (setq empty "&nbsp;")
18799 (catch 'next-line
18800 (if (string-match "^[ \t]*\\+-" line)
18801 (progn
18802 (if field-buffer
18803 (progn
18804 (setq
18805 html
18806 (concat
18807 html
18808 "<tr>"
18809 (mapconcat
18810 (lambda (x)
18811 (if (equal x "") (setq x empty))
18812 (if head
18813 (concat (car org-export-table-header-tags) x
18814 (cdr org-export-table-header-tags))
18815 (concat (car org-export-table-data-tags) x
18816 (cdr org-export-table-data-tags))))
18817 field-buffer "\n")
18818 "</tr>\n"))
18819 (setq head nil)
18820 (setq field-buffer nil)))
18821 ;; Ignore this line
18822 (throw 'next-line t)))
18823 ;; Break the line into fields and store the fields
18824 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
18825 (if field-buffer
18826 (setq field-buffer (mapcar
18827 (lambda (x)
18828 (concat x "<br/>" (pop fields)))
18829 field-buffer))
18830 (setq field-buffer fields))))
18831 (setq html (concat html "</table>\n"))
18832 html))
18834 (defun org-format-table-table-html-using-table-generate-source (lines)
18835 "Format a table into html, using `table-generate-source' from table.el.
18836 This has the advantage that cell- or row-spanning is allowed.
18837 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
18838 (require 'table)
18839 (with-current-buffer (get-buffer-create " org-tmp1 ")
18840 (erase-buffer)
18841 (insert (mapconcat 'identity lines "\n"))
18842 (goto-char (point-min))
18843 (if (not (re-search-forward "|[^+]" nil t))
18844 (error "Error processing table"))
18845 (table-recognize-table)
18846 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
18847 (table-generate-source 'html " org-tmp2 ")
18848 (set-buffer " org-tmp2 ")
18849 (buffer-substring (point-min) (point-max))))
18851 (defun org-html-handle-time-stamps (s)
18852 "Format time stamps in string S, or remove them."
18853 (catch 'exit
18854 (let (r b)
18855 (while (string-match org-maybe-keyword-time-regexp s)
18856 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
18857 ;; never export CLOCK
18858 (throw 'exit ""))
18859 (or b (setq b (substring s 0 (match-beginning 0))))
18860 (if (not org-export-with-timestamps)
18861 (setq r (concat r (substring s 0 (match-beginning 0)))
18862 s (substring s (match-end 0)))
18863 (setq r (concat
18864 r (substring s 0 (match-beginning 0))
18865 (if (match-end 1)
18866 (format "@<span class=\"timestamp-kwd\">%s @</span>"
18867 (match-string 1 s)))
18868 (format " @<span class=\"timestamp\">%s@</span>"
18869 (substring
18870 (org-translate-time (match-string 3 s)) 1 -1)))
18871 s (substring s (match-end 0)))))
18872 ;; Line break if line started and ended with time stamp stuff
18873 (if (not r)
18875 (setq r (concat r s))
18876 (unless (string-match "\\S-" (concat b s))
18877 (setq r (concat r "@<br/>")))
18878 r))))
18880 (defun org-html-protect (s)
18881 ;; convert & to &amp;, < to &lt; and > to &gt;
18882 (let ((start 0))
18883 (while (string-match "&" s start)
18884 (setq s (replace-match "&amp;" t t s)
18885 start (1+ (match-beginning 0))))
18886 (while (string-match "<" s)
18887 (setq s (replace-match "&lt;" t t s)))
18888 (while (string-match ">" s)
18889 (setq s (replace-match "&gt;" t t s))))
18892 (defun org-export-cleanup-toc-line (s)
18893 "Remove tags and time staps from lines going into the toc."
18894 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
18895 (setq s (replace-match "" t t s)))
18896 (when org-export-remove-timestamps-from-toc
18897 (while (string-match org-maybe-keyword-time-regexp s)
18898 (setq s (replace-match "" t t s))))
18901 (defun org-html-expand (string)
18902 "Prepare STRING for HTML export. Applies all active conversions.
18903 If there are links in the string, don't modify these."
18904 (let* (m s l res)
18905 (while (setq m (string-match org-bracket-link-regexp string))
18906 (setq s (substring string 0 m)
18907 l (match-string 0 string)
18908 string (substring string (match-end 0)))
18909 (push (org-html-do-expand s) res)
18910 (push l res))
18911 (push (org-html-do-expand string) res)
18912 (apply 'concat (nreverse res))))
18914 (defun org-html-do-expand (s)
18915 "Apply all active conversions to translate special ASCII to HTML."
18916 (setq s (org-html-protect s))
18917 (if org-export-html-expand
18918 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
18919 (setq s (replace-match "<\\1>" t nil s))))
18920 (if org-export-with-emphasize
18921 (setq s (org-export-html-convert-emphasize s)))
18922 (if org-export-with-sub-superscripts
18923 (setq s (org-export-html-convert-sub-super s)))
18924 (if org-export-with-TeX-macros
18925 (let ((start 0) wd ass)
18926 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
18927 (setq wd (match-string 1 s))
18928 (if (setq ass (assoc wd org-html-entities))
18929 (setq s (replace-match (or (cdr ass)
18930 (concat "&" (car ass) ";"))
18931 t t s))
18932 (setq start (+ start (length wd)))))))
18935 (defun org-create-multibrace-regexp (left right n)
18936 "Create a regular expression which will match a balanced sexp.
18937 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
18938 as single character strings.
18939 The regexp returned will match the entire expression including the
18940 delimiters. It will also define a single group which contains the
18941 match except for the outermost delimiters. The maximum depth of
18942 stacked delimiters is N. Escaping delimiters is not possible."
18943 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
18944 (or "\\|")
18945 (re nothing)
18946 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
18947 (while (> n 1)
18948 (setq n (1- n)
18949 re (concat re or next)
18950 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
18951 (concat left "\\(" re "\\)" right)))
18953 (defvar org-match-substring-regexp
18954 (concat
18955 "\\([^\\]\\)\\([_^]\\)\\("
18956 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
18957 "\\|"
18958 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
18959 "\\|"
18960 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
18961 "The regular expression matching a sub- or superscript.")
18963 ;(let ((s "a\\_b"))
18964 ; (and (string-match org-match-substring-regexp s)
18965 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
18967 (defun org-export-html-convert-sub-super (string)
18968 "Convert sub- and superscripts in STRING to HTML."
18969 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
18970 (while (string-match org-match-substring-regexp string s)
18971 (if (and requireb (match-end 8))
18972 (setq s (match-end 2))
18973 (setq s (match-end 1)
18974 key (if (string= (match-string 2 string) "_") "sub" "sup")
18975 c (or (match-string 8 string)
18976 (match-string 6 string)
18977 (match-string 5 string))
18978 string (replace-match
18979 (concat (match-string 1 string)
18980 "<" key ">" c "</" key ">")
18981 t t string))))
18982 (while (string-match "\\\\\\([_^]\\)" string)
18983 (setq string (replace-match (match-string 1 string) t t string)))
18984 string))
18986 ;; FIXME: what if the if does not match???????
18987 (defun org-export-html-convert-emphasize (string)
18988 "Apply emphasis."
18989 (let ((s 0))
18990 (while (string-match org-emph-re string s)
18991 (if (not (equal
18992 (substring string (match-beginning 3) (1+ (match-beginning 3)))
18993 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
18994 (setq string (replace-match
18995 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
18996 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
18997 "\\5") t nil string))
18998 (setq s (1+ s))))
18999 string))
19001 (defvar org-par-open nil)
19002 (defun org-open-par ()
19003 "Insert <p>, but first close previous paragraph if any."
19004 (org-close-par-maybe)
19005 (insert "\n<p>")
19006 (setq org-par-open t))
19007 (defun org-close-par-maybe ()
19008 "Close paragraph if there is one open."
19009 (when org-par-open
19010 (insert "</p>")
19011 (setq org-par-open nil)))
19012 (defun org-close-li ()
19013 "Close <li> if necessary."
19014 (org-close-par-maybe)
19015 (insert "</li>\n"))
19017 (defun org-html-level-start (level title umax with-toc head-count)
19018 "Insert a new level in HTML export.
19019 When TITLE is nil, just close all open levels."
19020 (org-close-par-maybe)
19021 (let ((l (1+ (max level umax))))
19022 (while (<= l org-level-max)
19023 (if (aref org-levels-open (1- l))
19024 (progn
19025 (org-html-level-close l)
19026 (aset org-levels-open (1- l) nil)))
19027 (setq l (1+ l)))
19028 (when title
19029 ;; If title is nil, this means this function is called to close
19030 ;; all levels, so the rest is done only if title is given
19031 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
19032 (setq title (replace-match
19033 (if org-export-with-tags
19034 (save-match-data
19035 (concat
19036 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
19037 (mapconcat 'identity (org-split-string
19038 (match-string 1 title) ":")
19039 "&nbsp;")
19040 "</span>"))
19042 t t title)))
19043 (if (> level umax)
19044 (progn
19045 (if (aref org-levels-open (1- level))
19046 (progn
19047 (org-close-li)
19048 (insert "<li>" title "<br/>\n"))
19049 (aset org-levels-open (1- level) t)
19050 (org-close-par-maybe)
19051 (insert "<ul>\n<li>" title "<br/>\n")))
19052 (if org-export-with-section-numbers
19053 (setq title (concat (org-section-number level) " " title)))
19054 (setq level (+ level org-export-html-toplevel-hlevel -1))
19055 (if with-toc
19056 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
19057 level head-count title level))
19058 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
19059 (org-open-par)))))
19061 (defun org-html-level-close (&rest args)
19062 "Terminate one level in HTML export."
19063 (org-close-li)
19064 (insert "</ul>\n"))
19066 ;;; iCalendar export
19068 ;;;###autoload
19069 (defun org-export-icalendar-this-file ()
19070 "Export current file as an iCalendar file.
19071 The iCalendar file will be located in the same directory as the Org-mode
19072 file, but with extension `.ics'."
19073 (interactive)
19074 (org-export-icalendar nil buffer-file-name))
19076 ;;;###autoload
19077 (defun org-export-icalendar-all-agenda-files ()
19078 "Export all files in `org-agenda-files' to iCalendar .ics files.
19079 Each iCalendar file will be located in the same directory as the Org-mode
19080 file, but with extension `.ics'."
19081 (interactive)
19082 (apply 'org-export-icalendar nil (org-agenda-files t)))
19084 ;;;###autoload
19085 (defun org-export-icalendar-combine-agenda-files ()
19086 "Export all files in `org-agenda-files' to a single combined iCalendar file.
19087 The file is stored under the name `org-combined-agenda-icalendar-file'."
19088 (interactive)
19089 (apply 'org-export-icalendar t (org-agenda-files t)))
19091 (defun org-export-icalendar (combine &rest files)
19092 "Create iCalendar files for all elements of FILES.
19093 If COMBINE is non-nil, combine all calendar entries into a single large
19094 file and store it under the name `org-combined-agenda-icalendar-file'."
19095 (save-excursion
19096 (let* ((dir (org-export-directory
19097 :ical (list :publishing-directory
19098 org-export-publishing-directory)))
19099 file ical-file ical-buffer category started org-agenda-new-buffers)
19101 (when combine
19102 (setq ical-file
19103 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
19104 org-combined-agenda-icalendar-file
19105 (expand-file-name org-combined-agenda-icalendar-file dir))
19106 ical-buffer (org-get-agenda-file-buffer ical-file))
19107 (set-buffer ical-buffer) (erase-buffer))
19108 (while (setq file (pop files))
19109 (catch 'nextfile
19110 (org-check-agenda-file file)
19111 (set-buffer (org-get-agenda-file-buffer file))
19112 (unless combine
19113 (setq ical-file (concat (file-name-as-directory dir)
19114 (file-name-sans-extension
19115 (file-name-nondirectory buffer-file-name))
19116 ".ics"))
19117 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
19118 (with-current-buffer ical-buffer (erase-buffer)))
19119 (setq category (or org-category
19120 (file-name-sans-extension
19121 (file-name-nondirectory buffer-file-name))))
19122 (if (symbolp category) (setq category (symbol-name category)))
19123 (let ((standard-output ical-buffer))
19124 (if combine
19125 (and (not started) (setq started t)
19126 (org-start-icalendar-file org-icalendar-combined-name))
19127 (org-start-icalendar-file category))
19128 (org-print-icalendar-entries combine)
19129 (when (or (and combine (not files)) (not combine))
19130 (org-finish-icalendar-file)
19131 (set-buffer ical-buffer)
19132 (save-buffer)
19133 (run-hooks 'org-after-save-iCalendar-file-hook)))))
19134 (org-release-buffers org-agenda-new-buffers))))
19136 (defvar org-after-save-iCalendar-file-hook nil
19137 "Hook run after an iCalendar file has been saved.
19138 The iCalendar buffer is still current when this hook is run.
19139 A good way to use this is to tell a desktop calenndar application to re-read
19140 the iCalendar file.")
19142 (defun org-print-icalendar-entries (&optional combine)
19143 "Print iCalendar entries for the current Org-mode file to `standard-output'.
19144 When COMBINE is non nil, add the category to each line."
19145 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
19146 (org-category-table (org-get-category-table))
19147 (dts (org-ical-ts-to-string
19148 (format-time-string (cdr org-time-stamp-formats) (current-time))
19149 "DTSTART"))
19150 hd ts ts2 state status (inc t) pos
19151 scheduledp deadlinep tmp pri category)
19152 (save-excursion
19153 (goto-char (point-min))
19154 (while (re-search-forward org-ts-regexp nil t)
19155 (setq pos (match-beginning 0)
19156 ts (match-string 0)
19157 inc t
19158 hd (org-get-heading)
19159 category (org-get-category))
19160 (if (looking-at re2)
19161 (progn
19162 (goto-char (match-end 0))
19163 (setq ts2 (match-string 1) inc nil))
19164 (setq ts2 ts
19165 tmp (buffer-substring (max (point-min)
19166 (- pos org-ds-keyword-length))
19167 pos)
19168 deadlinep (string-match org-deadline-regexp tmp)
19169 scheduledp (string-match org-scheduled-regexp tmp)
19170 ;; donep (org-entry-is-done-p)
19172 (if (or (string-match org-tr-regexp hd)
19173 (string-match org-ts-regexp hd))
19174 (setq hd (replace-match "" t t hd)))
19175 (if (string-match org-bracket-link-regexp hd)
19176 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
19177 (match-string 1 hd))
19178 t t hd)))
19179 (if deadlinep (setq hd (concat "DL: " hd)))
19180 (if scheduledp (setq hd (concat "S: " hd)))
19181 (princ (format "BEGIN:VEVENT
19184 SUMMARY:%s
19185 CATEGORIES:%s
19186 END:VEVENT\n"
19187 (org-ical-ts-to-string ts "DTSTART")
19188 (org-ical-ts-to-string ts2 "DTEND" inc)
19189 hd category)))
19190 (when org-icalendar-include-todo
19191 (goto-char (point-min))
19192 (while (re-search-forward org-todo-line-regexp nil t)
19193 (setq state (match-string 2))
19194 (setq status (if (member state org-done-keywords)
19195 "COMPLETED" "NEEDS-ACTION"))
19196 (when (and state
19197 (or (not (member state org-done-keywords))
19198 (eq org-icalendar-include-todo 'all))
19199 (not (member org-archive-tag (org-get-tags-at)))
19201 (setq hd (match-string 3))
19202 (if (string-match org-bracket-link-regexp hd)
19203 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
19204 (match-string 1 hd))
19205 t t hd)))
19206 (if (string-match org-priority-regexp hd)
19207 (setq pri (string-to-char (match-string 2 hd))
19208 hd (concat (substring hd 0 (match-beginning 1))
19209 (substring hd (match-end 1))))
19210 (setq pri org-default-priority))
19211 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
19212 (- org-lowest-priority ?A))))))
19214 (princ (format "BEGIN:VTODO
19216 SUMMARY:%s
19217 CATEGORIES:%s
19218 SEQUENCE:1
19219 PRIORITY:%d
19220 STATUS:%s
19221 END:VTODO\n"
19222 dts hd category pri status))))))))
19224 (defun org-start-icalendar-file (name)
19225 "Start an iCalendar file by inserting the header."
19226 (let ((user user-full-name)
19227 (name (or name "unknown"))
19228 (timezone (cadr (current-time-zone))))
19229 (princ
19230 (format "BEGIN:VCALENDAR
19231 VERSION:2.0
19232 X-WR-CALNAME:%s
19233 PRODID:-//%s//Emacs with Org-mode//EN
19234 X-WR-TIMEZONE:%s
19235 CALSCALE:GREGORIAN\n" name user timezone))))
19237 (defun org-finish-icalendar-file ()
19238 "Finish an iCalendar file by inserting the END statement."
19239 (princ "END:VCALENDAR\n"))
19241 (defun org-ical-ts-to-string (s keyword &optional inc)
19242 "Take a time string S and convert it to iCalendar format.
19243 KEYWORD is added in front, to make a complete line like DTSTART....
19244 When INC is non-nil, increase the hour by two (if time string contains
19245 a time), or the day by one (if it does not contain a time)."
19246 (let ((t1 (org-parse-time-string s 'nodefault))
19247 t2 fmt have-time time)
19248 (if (and (car t1) (nth 1 t1) (nth 2 t1))
19249 (setq t2 t1 have-time t)
19250 (setq t2 (org-parse-time-string s)))
19251 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
19252 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
19253 (when inc
19254 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
19255 (setq time (encode-time s mi h d m y)))
19256 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
19257 (concat keyword (format-time-string fmt time))))
19259 ;;; XOXO export
19261 (defun org-export-as-xoxo-insert-into (buffer &rest output)
19262 (with-current-buffer buffer
19263 (apply 'insert output)))
19264 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
19266 (defun org-export-as-xoxo (&optional buffer)
19267 "Export the org buffer as XOXO.
19268 The XOXO buffer is named *xoxo-<source buffer name>*"
19269 (interactive (list (current-buffer)))
19270 ;; A quickie abstraction
19272 ;; Output everything as XOXO
19273 (with-current-buffer (get-buffer buffer)
19274 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
19275 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
19276 (org-infile-export-plist)))
19277 (filename (concat (file-name-as-directory
19278 (org-export-directory :xoxo opt-plist))
19279 (file-name-sans-extension
19280 (file-name-nondirectory buffer-file-name))
19281 ".html"))
19282 (out (find-file-noselect filename))
19283 (last-level 1)
19284 (hanging-li nil))
19285 ;; Check the output buffer is empty.
19286 (with-current-buffer out (erase-buffer))
19287 ;; Kick off the output
19288 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
19289 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
19290 (let* ((hd (match-string-no-properties 1))
19291 (level (length hd))
19292 (text (concat
19293 (match-string-no-properties 2)
19294 (save-excursion
19295 (goto-char (match-end 0))
19296 (let ((str ""))
19297 (catch 'loop
19298 (while 't
19299 (forward-line)
19300 (if (looking-at "^[ \t]\\(.*\\)")
19301 (setq str (concat str (match-string-no-properties 1)))
19302 (throw 'loop str)))))))))
19304 ;; Handle level rendering
19305 (cond
19306 ((> level last-level)
19307 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
19309 ((< level last-level)
19310 (dotimes (- (- last-level level) 1)
19311 (if hanging-li
19312 (org-export-as-xoxo-insert-into out "</li>\n"))
19313 (org-export-as-xoxo-insert-into out "</ol>\n"))
19314 (when hanging-li
19315 (org-export-as-xoxo-insert-into out "</li>\n")
19316 (setq hanging-li nil)))
19318 ((equal level last-level)
19319 (if hanging-li
19320 (org-export-as-xoxo-insert-into out "</li>\n")))
19323 (setq last-level level)
19325 ;; And output the new li
19326 (setq hanging-li 't)
19327 (if (equal ?+ (elt text 0))
19328 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
19329 (org-export-as-xoxo-insert-into out "<li>" text))))
19331 ;; Finally finish off the ol
19332 (dotimes (- last-level 1)
19333 (if hanging-li
19334 (org-export-as-xoxo-insert-into out "</li>\n"))
19335 (org-export-as-xoxo-insert-into out "</ol>\n"))
19337 ;; Finish the buffer off and clean it up.
19338 (switch-to-buffer-other-window out)
19339 (indent-region (point-min) (point-max) nil)
19340 (save-buffer)
19341 (goto-char (point-min))
19345 ;;;; Key bindings
19347 ;; Make `C-c C-x' a prefix key
19348 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19350 ;; TAB key with modifiers
19351 (org-defkey org-mode-map "\C-i" 'org-cycle)
19352 (org-defkey org-mode-map [(tab)] 'org-cycle)
19353 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19354 (org-defkey org-mode-map [(meta tab)] 'org-complete)
19355 (org-defkey org-mode-map "\M-\t" 'org-complete)
19356 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
19357 ;; The following line is necessary under Suse GNU/Linux
19358 (unless (featurep 'xemacs)
19359 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19360 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19362 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19363 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19364 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19366 ;; Cursor keys with modifiers
19367 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19368 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19369 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19370 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19372 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19373 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19374 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19375 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19377 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19378 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19379 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19380 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19382 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19383 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19385 ;;; Extra keys for tty access.
19386 ;; We only set them when really needed because otherwise the
19387 ;; menus don't show the simple keys
19389 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19390 (not window-system))
19391 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19392 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19393 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19394 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19395 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19396 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19397 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19398 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19399 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19400 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19401 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19402 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19403 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19404 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19405 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19406 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19407 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19408 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19409 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19410 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19411 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19412 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
19414 ;; All the other keys
19416 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19417 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19418 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
19419 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19420 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19421 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
19422 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19423 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19424 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19425 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19426 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19427 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19428 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
19429 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
19430 (org-defkey org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
19431 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
19432 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19433 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19434 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19435 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19436 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19437 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19438 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19439 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19440 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
19441 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19442 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19443 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19444 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19445 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19446 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19447 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19448 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19449 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19450 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19451 (org-defkey org-mode-map "\C-c-" 'org-table-insert-hline)
19452 (org-defkey org-mode-map "\C-c^" 'org-sort)
19453 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19454 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
19455 (org-defkey org-mode-map "\C-m" 'org-return)
19456 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19457 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19458 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19459 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19460 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
19461 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19462 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19463 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
19464 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19465 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19466 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
19467 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19468 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19469 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
19470 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19472 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
19473 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19474 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19475 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19477 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19478 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19479 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19480 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
19481 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19482 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19483 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19484 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19485 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19487 (when (featurep 'xemacs)
19488 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19490 (defsubst org-table-p () (org-at-table-p))
19492 (defun org-self-insert-command (N)
19493 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19494 If the cursor is in a table looking at whitespace, the whitespace is
19495 overwritten, and the table is not marked as requiring realignment."
19496 (interactive "p")
19497 (if (and (org-table-p)
19498 (progn
19499 ;; check if we blank the field, and if that triggers align
19500 (and org-table-auto-blank-field
19501 (member last-command
19502 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19503 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19504 ;; got extra space, this field does not determine column width
19505 (let (org-table-may-need-update) (org-table-blank-field))
19506 ;; no extra space, this field may determine column width
19507 (org-table-blank-field)))
19509 (eq N 1)
19510 (looking-at "[^|\n]* |"))
19511 (let (org-table-may-need-update)
19512 (goto-char (1- (match-end 0)))
19513 (delete-backward-char 1)
19514 (goto-char (match-beginning 0))
19515 (self-insert-command N))
19516 (setq org-table-may-need-update t)
19517 (self-insert-command N)))
19519 (defun org-delete-backward-char (N)
19520 "Like `delete-backward-char', insert whitespace at field end in tables.
19521 When deleting backwards, in tables this function will insert whitespace in
19522 front of the next \"|\" separator, to keep the table aligned. The table will
19523 still be marked for re-alignment if the field did fill the entire column,
19524 because, in this case the deletion might narrow the column."
19525 (interactive "p")
19526 (if (and (org-table-p)
19527 (eq N 1)
19528 (string-match "|" (buffer-substring (point-at-bol) (point)))
19529 (looking-at ".*?|"))
19530 (let ((pos (point))
19531 (noalign (looking-at "[^|\n\r]* |"))
19532 (c org-table-may-need-update))
19533 (backward-delete-char N)
19534 (skip-chars-forward "^|")
19535 (insert " ")
19536 (goto-char (1- pos))
19537 ;; noalign: if there were two spaces at the end, this field
19538 ;; does not determine the width of the column.
19539 (if noalign (setq org-table-may-need-update c)))
19540 (backward-delete-char N)))
19542 (defun org-delete-char (N)
19543 "Like `delete-char', but insert whitespace at field end in tables.
19544 When deleting characters, in tables this function will insert whitespace in
19545 front of the next \"|\" separator, to keep the table aligned. The table will
19546 still be marked for re-alignment if the field did fill the entire column,
19547 because, in this case the deletion might narrow the column."
19548 (interactive "p")
19549 (if (and (org-table-p)
19550 (not (bolp))
19551 (not (= (char-after) ?|))
19552 (eq N 1))
19553 (if (looking-at ".*?|")
19554 (let ((pos (point))
19555 (noalign (looking-at "[^|\n\r]* |"))
19556 (c org-table-may-need-update))
19557 (replace-match (concat
19558 (substring (match-string 0) 1 -1)
19559 " |"))
19560 (goto-char pos)
19561 ;; noalign: if there were two spaces at the end, this field
19562 ;; does not determine the width of the column.
19563 (if noalign (setq org-table-may-need-update c)))
19564 (delete-char N))
19565 (delete-char N)))
19567 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19568 (put 'org-self-insert-command 'delete-selection t)
19569 (put 'orgtbl-self-insert-command 'delete-selection t)
19570 (put 'org-delete-char 'delete-selection 'supersede)
19571 (put 'org-delete-backward-char 'delete-selection 'supersede)
19573 ;; Make `flyspell-mode' delay after some commands
19574 (put 'org-self-insert-command 'flyspell-delayed t)
19575 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19576 (put 'org-delete-char 'flyspell-delayed t)
19577 (put 'org-delete-backward-char 'flyspell-delayed t)
19579 ;; How to do this: Measure non-white length of current string
19580 ;; If equal to column width, we should realign.
19582 (defun org-remap (map &rest commands)
19583 "In MAP, remap the functions given in COMMANDS.
19584 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19585 (let (new old)
19586 (while commands
19587 (setq old (pop commands) new (pop commands))
19588 (if (fboundp 'command-remapping)
19589 (org-defkey map (vector 'remap old) new)
19590 (substitute-key-definition old new map global-map)))))
19592 (when (eq org-enable-table-editor 'optimized)
19593 ;; If the user wants maximum table support, we need to hijack
19594 ;; some standard editing functions
19595 (org-remap org-mode-map
19596 'self-insert-command 'org-self-insert-command
19597 'delete-char 'org-delete-char
19598 'delete-backward-char 'org-delete-backward-char)
19599 (org-defkey org-mode-map "|" 'org-force-self-insert))
19601 (defun org-shiftcursor-error ()
19602 "Throw an error because Shift-Cursor command was applied in wrong context."
19603 (error "This command is active in special context like tables, headlines or timestamps"))
19605 (defun org-shifttab (&optional arg)
19606 "Global visibility cycling or move to previous table field.
19607 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19608 on context.
19609 See the individual commands for more information."
19610 (interactive "P")
19611 (cond
19612 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19613 (arg (message "Content view to level: ")
19614 (org-content (prefix-numeric-value arg))
19615 (setq org-cycle-global-status 'overview))
19616 (t (call-interactively 'org-global-cycle))))
19618 (defun org-shiftmetaleft ()
19619 "Promote subtree or delete table column.
19620 Calls `org-promote-subtree', `org-outdent-item',
19621 or `org-table-delete-column', depending on context.
19622 See the individual commands for more information."
19623 (interactive)
19624 (cond
19625 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19626 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
19627 ((org-at-item-p) (call-interactively 'org-outdent-item))
19628 (t (org-shiftcursor-error))))
19630 (defun org-shiftmetaright ()
19631 "Demote subtree or insert table column.
19632 Calls `org-demote-subtree', `org-indent-item',
19633 or `org-table-insert-column', depending on context.
19634 See the individual commands for more information."
19635 (interactive)
19636 (cond
19637 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19638 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
19639 ((org-at-item-p) (call-interactively 'org-indent-item))
19640 (t (org-shiftcursor-error))))
19642 (defun org-shiftmetaup (&optional arg)
19643 "Move subtree up or kill table row.
19644 Calls `org-move-subtree-up' or `org-table-kill-row' or
19645 `org-move-item-up' depending on context. See the individual commands
19646 for more information."
19647 (interactive "P")
19648 (cond
19649 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19650 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
19651 ((org-at-item-p) (call-interactively 'org-move-item-up))
19652 (t (org-shiftcursor-error))))
19653 (defun org-shiftmetadown (&optional arg)
19654 "Move subtree down or insert table row.
19655 Calls `org-move-subtree-down' or `org-table-insert-row' or
19656 `org-move-item-down', depending on context. See the individual
19657 commands for more information."
19658 (interactive "P")
19659 (cond
19660 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19661 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
19662 ((org-at-item-p) (call-interactively 'org-move-item-down))
19663 (t (org-shiftcursor-error))))
19665 (defun org-metaleft (&optional arg)
19666 "Promote heading or move table column to left.
19667 Calls `org-do-promote' or `org-table-move-column', depending on context.
19668 With no specific context, calls the Emacs default `backward-word'.
19669 See the individual commands for more information."
19670 (interactive "P")
19671 (cond
19672 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19673 ((or (org-on-heading-p) (org-region-active-p))
19674 (call-interactively 'org-do-promote))
19675 ((org-at-item-p) (call-interactively 'org-outdent-item))
19676 (t (call-interactively 'backward-word))))
19678 (defun org-metaright (&optional arg)
19679 "Demote subtree or move table column to right.
19680 Calls `org-do-demote' or `org-table-move-column', depending on context.
19681 With no specific context, calls the Emacs default `forward-word'.
19682 See the individual commands for more information."
19683 (interactive "P")
19684 (cond
19685 ((org-at-table-p) (call-interactively 'org-table-move-column))
19686 ((or (org-on-heading-p) (org-region-active-p))
19687 (call-interactively 'org-do-demote))
19688 ((org-at-item-p) (call-interactively 'org-indent-item))
19689 (t (call-interactively 'forward-word))))
19691 (defun org-metaup (&optional arg)
19692 "Move subtree up or move table row up.
19693 Calls `org-move-subtree-up' or `org-table-move-row' or
19694 `org-move-item-up', depending on context. See the individual commands
19695 for more information."
19696 (interactive "P")
19697 (cond
19698 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19699 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
19700 ((org-at-item-p) (call-interactively 'org-move-item-up))
19701 (t (org-shiftcursor-error))))
19703 (defun org-metadown (&optional arg)
19704 "Move subtree down or move table row down.
19705 Calls `org-move-subtree-down' or `org-table-move-row' or
19706 `org-move-item-down', depending on context. See the individual
19707 commands for more information."
19708 (interactive "P")
19709 (cond
19710 ((org-at-table-p) (call-interactively 'org-table-move-row))
19711 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
19712 ((org-at-item-p) (call-interactively 'org-move-item-down))
19713 (t (org-shiftcursor-error))))
19715 (defun org-shiftup (&optional arg)
19716 "Increase item in timestamp or increase priority of current headline.
19717 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19718 depending on context. See the individual commands for more information."
19719 (interactive "P")
19720 (cond
19721 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
19722 ((org-on-heading-p) (call-interactively 'org-priority-up))
19723 ((org-at-item-p) (call-interactively 'org-previous-item))
19724 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
19726 (defun org-shiftdown (&optional arg)
19727 "Decrease item in timestamp or decrease priority of current headline.
19728 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19729 depending on context. See the individual commands for more information."
19730 (interactive "P")
19731 (cond
19732 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
19733 ((org-on-heading-p) (call-interactively 'org-priority-down))
19734 (t (call-interactively 'org-next-item))))
19736 (defun org-shiftright ()
19737 "Next TODO keyword or timestamp one day later, depending on context."
19738 (interactive)
19739 (cond
19740 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19741 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
19742 (t (org-shiftcursor-error))))
19744 (defun org-shiftleft ()
19745 "Previous TODO keyword or timestamp one day earlier, depending on context."
19746 (interactive)
19747 (cond
19748 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19749 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
19750 (t (org-shiftcursor-error))))
19752 (defun org-shiftcontrolright ()
19753 "Switch to next TODO set."
19754 (interactive)
19755 (cond
19756 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
19757 (t (org-shiftcursor-error))))
19759 (defun org-shiftcontrolleft ()
19760 "Switch to previous TODO set."
19761 (interactive)
19762 (cond
19763 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
19764 (t (org-shiftcursor-error))))
19766 (defun org-ctrl-c-ret ()
19767 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19768 (interactive)
19769 (cond
19770 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19771 (t (call-interactively 'org-insert-heading))))
19773 (defun org-copy-special ()
19774 "Copy region in table or copy current subtree.
19775 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19776 See the individual commands for more information."
19777 (interactive)
19778 (call-interactively
19779 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19781 (defun org-cut-special ()
19782 "Cut region in table or cut current subtree.
19783 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19784 See the individual commands for more information."
19785 (interactive)
19786 (call-interactively
19787 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19789 (defun org-paste-special (arg)
19790 "Paste rectangular region into table, or past subtree relative to level.
19791 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19792 See the individual commands for more information."
19793 (interactive "P")
19794 (if (org-at-table-p)
19795 (org-table-paste-rectangle)
19796 (org-paste-subtree arg)))
19798 (defun org-ctrl-c-ctrl-c (&optional arg)
19799 "Set tags in headline, or update according to changed information at point.
19801 This command does many different things, depending on context:
19803 - If the cursor is in a headline, prompt for tags and insert them
19804 into the current line, aligned to `org-tags-column'. When called
19805 with prefix arg, realign all tags in the current buffer.
19807 - If the cursor is in one of the special #+KEYWORD lines, this
19808 triggers scanning the buffer for these lines and updating the
19809 information.
19811 - If the cursor is inside a table, realign the table. This command
19812 works even if the automatic table editor has been turned off.
19814 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19815 the entire table.
19817 - If the cursor is inside a table created by the table.el package,
19818 activate that table.
19820 - If the current buffer is a remember buffer, close note and file it.
19821 with a prefix argument, file it without further interaction to the default
19822 location.
19824 - If the cursor is on a <<<target>>>, update radio targets and corresponding
19825 links in this buffer.
19827 - If the cursor is on a numbered item in a plain list, renumber the
19828 ordered list."
19829 (interactive "P")
19830 (let ((org-enable-table-editor t))
19831 (cond
19832 ((or org-clock-overlays
19833 org-occur-highlights
19834 org-latex-fragment-image-overlays)
19835 (org-remove-clock-overlays)
19836 (org-remove-occur-highlights)
19837 (org-remove-latex-fragment-image-overlays)
19838 (message "Temporary highlights/overlays removed from current buffer"))
19839 ((and (local-variable-p 'org-finish-function (current-buffer))
19840 (fboundp org-finish-function))
19841 (funcall org-finish-function))
19842 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
19843 ((org-on-heading-p) (call-interactively 'org-set-tags))
19844 ((org-at-table.el-p)
19845 (require 'table)
19846 (beginning-of-line 1)
19847 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
19848 (call-interactively 'table-recognize-table))
19849 ((org-at-table-p)
19850 (org-table-maybe-eval-formula)
19851 (if arg
19852 (call-interactively 'org-table-recalculate)
19853 (org-table-maybe-recalculate-line))
19854 (call-interactively 'org-table-align))
19855 ((org-at-item-checkbox-p)
19856 (call-interactively 'org-toggle-checkbox))
19857 ((org-at-item-p)
19858 (call-interactively 'org-renumber-ordered-list))
19859 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
19860 (cond
19861 ((equal (match-string 1) "TBLFM")
19862 ;; Recalculate the table before this line
19863 (save-excursion
19864 (beginning-of-line 1)
19865 (skip-chars-backward " \r\n\t")
19866 (if (org-at-table-p)
19867 (org-call-with-arg 'org-table-recalculate t))))
19869 (call-interactively 'org-mode-restart))))
19870 (t (error "C-c C-c can do nothing useful at this location.")))))
19872 (defun org-mode-restart ()
19873 "Restart Org-mode, to scan again for special lines.
19874 Also updates the keyword regular expressions."
19875 (interactive)
19876 (let ((org-inhibit-startup t)) (org-mode))
19877 (message "Org-mode restarted to refresh keyword and special line setup"))
19879 (defun org-return ()
19880 "Goto next table row or insert a newline.
19881 Calls `org-table-next-row' or `newline', depending on context.
19882 See the individual commands for more information."
19883 (interactive)
19884 (cond
19885 ((org-at-table-p)
19886 (org-table-justify-field-maybe)
19887 (call-interactively 'org-table-next-row))
19888 (t (newline))))
19890 (defun org-meta-return (&optional arg)
19891 "Insert a new heading or wrap a region in a table.
19892 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19893 See the individual commands for more information."
19894 (interactive "P")
19895 (cond
19896 ((org-at-table-p)
19897 (call-interactively 'org-table-wrap-region))
19898 (t (call-interactively 'org-insert-heading))))
19900 ;;; Menu entries
19902 ;; Define the Org-mode menus
19903 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19904 '("Tbl"
19905 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
19906 ["Next Field" org-cycle (org-at-table-p)]
19907 ["Previous Field" org-shifttab (org-at-table-p)]
19908 ["Next Row" org-return (org-at-table-p)]
19909 "--"
19910 ["Blank Field" org-table-blank-field (org-at-table-p)]
19911 ["Edit Field" org-table-edit-field (org-at-table-p)]
19912 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19913 "--"
19914 ("Column"
19915 ["Move Column Left" org-metaleft (org-at-table-p)]
19916 ["Move Column Right" org-metaright (org-at-table-p)]
19917 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19918 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19919 ("Row"
19920 ["Move Row Up" org-metaup (org-at-table-p)]
19921 ["Move Row Down" org-metadown (org-at-table-p)]
19922 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19923 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19924 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19925 "--"
19926 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
19927 ("Rectangle"
19928 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19929 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19930 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19931 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19932 "--"
19933 ("Calculate"
19934 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19935 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19936 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
19937 "--"
19938 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19939 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19940 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19941 "--"
19942 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19943 "--"
19944 ["Sum Column/Rectangle" org-table-sum
19945 (or (org-at-table-p) (org-region-active-p))]
19946 ["Which Column?" org-table-current-column (org-at-table-p)])
19947 ["Debug Formulas"
19948 org-table-toggle-formula-debugger
19949 :style toggle :selected org-table-formula-debug]
19950 ["Show Col/Row Numbers"
19951 org-table-toggle-coordinate-overlays
19952 :style toggle :selected org-table-overlay-coordinates]
19953 "--"
19954 ["Create" org-table-create (and (not (org-at-table-p))
19955 org-enable-table-editor)]
19956 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19957 ["Import from File" org-table-import (not (org-at-table-p))]
19958 ["Export to File" org-table-export (org-at-table-p)]
19959 "--"
19960 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19962 (easy-menu-define org-org-menu org-mode-map "Org menu"
19963 '("Org"
19964 ("Show/Hide"
19965 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
19966 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
19967 ["Sparse Tree" org-occur t]
19968 ["Reveal Context" org-reveal t]
19969 ["Show All" show-all t]
19970 "--"
19971 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19972 "--"
19973 ["New Heading" org-insert-heading t]
19974 ("Navigate Headings"
19975 ["Up" outline-up-heading t]
19976 ["Next" outline-next-visible-heading t]
19977 ["Previous" outline-previous-visible-heading t]
19978 ["Next Same Level" outline-forward-same-level t]
19979 ["Previous Same Level" outline-backward-same-level t]
19980 "--"
19981 ["Jump" org-goto t])
19982 ("Edit Structure"
19983 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19984 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19985 "--"
19986 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19987 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19988 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19989 "--"
19990 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19991 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19992 ["Demote Heading" org-metaright (not (org-at-table-p))]
19993 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19994 "--"
19995 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19996 "--"
19997 ["Convert to odd levels" org-convert-to-odd-levels t]
19998 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19999 ("Archive"
20000 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
20001 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
20002 ; :active t :keys "C-u C-c C-x C-a"]
20003 ["Sparse trees open ARCHIVE trees"
20004 (setq org-sparse-tree-open-archived-trees
20005 (not org-sparse-tree-open-archived-trees))
20006 :style toggle :selected org-sparse-tree-open-archived-trees]
20007 ["Cycling opens ARCHIVE trees"
20008 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
20009 :style toggle :selected org-cycle-open-archived-trees]
20010 ["Agenda includes ARCHIVE trees"
20011 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
20012 :style toggle :selected (not org-agenda-skip-archived-trees)]
20013 "--"
20014 ["Move Subtree to Archive" org-advertized-archive-subtree t]
20015 ; ["Check and Move Children" (org-archive-subtree '(4))
20016 ; :active t :keys "C-u C-c C-x C-s"]
20018 "--"
20019 ("TODO Lists"
20020 ["TODO/DONE/-" org-todo t]
20021 ("Select keyword"
20022 ["Next keyword" org-shiftright (org-on-heading-p)]
20023 ["Previous keyword" org-shiftleft (org-on-heading-p)]
20024 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
20025 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
20026 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
20027 ["Show TODO Tree" org-show-todo-tree t]
20028 ["Global TODO list" org-todo-list t]
20029 "--"
20030 ["Set Priority" org-priority t]
20031 ["Priority Up" org-shiftup t]
20032 ["Priority Down" org-shiftdown t]
20033 "--"
20034 ;; FIXME: why is this still here????
20035 ; ["Insert Checkbox" org-insert-todo-heading (org-in-item-p)]
20036 ; ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
20037 ; ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
20038 ; (or (org-on-heading-p) (org-at-item-p))]
20039 ; ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
20040 ; (or (org-on-heading-p) (org-at-item-p))]
20041 ; ["Update Statistics" org-update-checkbox-count t]
20043 ("Dates and Scheduling"
20044 ["Timestamp" org-time-stamp t]
20045 ["Timestamp (inactive)" org-time-stamp-inactive t]
20046 ("Change Date"
20047 ["1 Day Later" org-shiftright t]
20048 ["1 Day Earlier" org-shiftleft t]
20049 ["1 ... Later" org-shiftup t]
20050 ["1 ... Earlier" org-shiftdown t])
20051 ["Compute Time Range" org-evaluate-time-range t]
20052 ["Schedule Item" org-schedule t]
20053 ["Deadline" org-deadline t]
20054 "--"
20055 ["Custom time format" org-toggle-time-stamp-overlays
20056 :style radio :selected org-display-custom-times]
20057 "--"
20058 ["Goto Calendar" org-goto-calendar t]
20059 ["Date from Calendar" org-date-from-calendar t])
20060 ("Logging work"
20061 ["Clock in" org-clock-in t]
20062 ["Clock out" org-clock-out t]
20063 ["Clock cancel" org-clock-cancel t]
20064 ["Display times" org-clock-display t]
20065 ["Create clock table" org-clock-report t]
20066 "--"
20067 ["Record DONE time"
20068 (progn (setq org-log-done (not org-log-done))
20069 (message "Switching to %s will %s record a timestamp"
20070 (car org-done-keywords)
20071 (if org-log-done "automatically" "not")))
20072 :style toggle :selected org-log-done])
20073 "--"
20074 ["Agenda Command..." org-agenda t]
20075 ("File List for Agenda")
20076 ("Special views current file"
20077 ["TODO Tree" org-show-todo-tree t]
20078 ["Check Deadlines" org-check-deadlines t]
20079 ["Timeline" org-timeline t]
20080 ["Tags Tree" org-tags-sparse-tree t])
20081 "--"
20082 ("Hyperlinks"
20083 ["Store Link (Global)" org-store-link t]
20084 ["Insert Link" org-insert-link t]
20085 ["Follow Link" org-open-at-point t]
20086 "--"
20087 ["Next link" org-next-link t]
20088 ["Previous link" org-previous-link t]
20089 "--"
20090 ["Descriptive Links"
20091 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
20092 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
20093 ["Literal Links"
20094 (progn
20095 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
20096 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
20097 "--"
20098 ["Export/Publish..." org-export t]
20099 ("LaTeX"
20100 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20101 :selected org-cdlatex-mode]
20102 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20103 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20104 ["Modify math symbol" org-cdlatex-math-modify
20105 (org-inside-LaTeX-fragment-p)]
20106 ["Export LaTeX fragments as images"
20107 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
20108 :style toggle :selected org-export-with-LaTeX-fragments])
20109 "--"
20110 ("Documentation"
20111 ["Show Version" org-version t]
20112 ["Info Documentation" org-info t])
20113 ("Customize"
20114 ["Browse Org Group" org-customize t]
20115 "--"
20116 ["Expand This Menu" org-create-customize-menu
20117 (fboundp 'customize-menu-create)])
20118 "--"
20119 ["Refresh setup" org-mode-restart t]
20122 (defun org-info (&optional node)
20123 "Read documentation for Org-mode in the info system.
20124 With optional NODE, go directly to that node."
20125 (interactive)
20126 (require 'info)
20127 (Info-goto-node (format "(org)%s" (or node ""))))
20129 (defun org-install-agenda-files-menu ()
20130 (let ((bl (buffer-list)))
20131 (save-excursion
20132 (while bl
20133 (set-buffer (pop bl))
20134 (if (org-mode-p) (setq bl nil)))
20135 (when (org-mode-p)
20136 (easy-menu-change
20137 '("Org") "File List for Agenda"
20138 (append
20139 (list
20140 ["Edit File List" (org-edit-agenda-file-list) t]
20141 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20142 ["Remove Current File from List" org-remove-file t]
20143 ["Cycle through agenda files" org-cycle-agenda-files t]
20144 "--")
20145 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20147 ;;;; Documentation
20149 (defun org-customize ()
20150 "Call the customize function with org as argument."
20151 (interactive)
20152 (customize-browse 'org))
20154 (defun org-create-customize-menu ()
20155 "Create a full customization menu for Org-mode, insert it into the menu."
20156 (interactive)
20157 (if (fboundp 'customize-menu-create)
20158 (progn
20159 (easy-menu-change
20160 '("Org") "Customize"
20161 `(["Browse Org group" org-customize t]
20162 "--"
20163 ,(customize-menu-create 'org)
20164 ["Set" Custom-set t]
20165 ["Save" Custom-save t]
20166 ["Reset to Current" Custom-reset-current t]
20167 ["Reset to Saved" Custom-reset-saved t]
20168 ["Reset to Standard Settings" Custom-reset-standard t]))
20169 (message "\"Org\"-menu now contains full customization menu"))
20170 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20172 ;;;; Miscellaneous stuff
20175 ;;; Generally useful functions
20177 (defun org-context ()
20178 "Return a list of contexts of the current cursor position.
20179 If several contexts apply, all are returned.
20180 Each context entry is a list with a symbol naming the context, and
20181 two positions indicating start and end of the context. Possible
20182 contexts are:
20184 :headline anywhere in a headline
20185 :headline-stars on the leading stars in a headline
20186 :todo-keyword on a TODO keyword (including DONE) in a headline
20187 :tags on the TAGS in a headline
20188 :priority on the priority cookie in a headline
20189 :item on the first line of a plain list item
20190 :item-bullet on the bullet/number of a plain list item
20191 :checkbox on the checkbox in a plain list item
20192 :table in an org-mode table
20193 :table-special on a special filed in a table
20194 :table-table in a table.el table
20195 :link on a hyperlink
20196 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
20197 :target on a <<target>>
20198 :radio-target on a <<<radio-target>>>
20199 :latex-fragment on a LaTeX fragment
20200 :latex-preview on a LaTeX fragment with overlayed preview image
20202 This function expects the position to be visible because it uses font-lock
20203 faces as a help to recognize the following contexts: :table-special, :link,
20204 and :keyword."
20205 (let* ((f (get-text-property (point) 'face))
20206 (faces (if (listp f) f (list f)))
20207 (p (point)) clist o)
20208 ;; First the large context
20209 (cond
20210 ((org-on-heading-p t)
20211 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20212 (when (progn
20213 (beginning-of-line 1)
20214 (looking-at org-todo-line-tags-regexp))
20215 (push (org-point-in-group p 1 :headline-stars) clist)
20216 (push (org-point-in-group p 2 :todo-keyword) clist)
20217 (push (org-point-in-group p 4 :tags) clist))
20218 (goto-char p)
20219 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
20220 (if (looking-at "\\[#[A-Z]\\]")
20221 (push (org-point-in-group p 0 :priority) clist)))
20223 ((org-at-item-p)
20224 (push (org-point-in-group p 2 :item-bullet) clist)
20225 (push (list :item (point-at-bol)
20226 (save-excursion (org-end-of-item) (point)))
20227 clist)
20228 (and (org-at-item-checkbox-p)
20229 (push (org-point-in-group p 0 :checkbox) clist)))
20231 ((org-at-table-p)
20232 (push (list :table (org-table-begin) (org-table-end)) clist)
20233 (if (memq 'org-formula faces)
20234 (push (list :table-special
20235 (previous-single-property-change p 'face)
20236 (next-single-property-change p 'face)) clist)))
20237 ((org-at-table-p 'any)
20238 (push (list :table-table) clist)))
20239 (goto-char p)
20241 ;; Now the small context
20242 (cond
20243 ((org-at-timestamp-p)
20244 (push (org-point-in-group p 0 :timestamp) clist))
20245 ((memq 'org-link faces)
20246 (push (list :link
20247 (previous-single-property-change p 'face)
20248 (next-single-property-change p 'face)) clist))
20249 ((memq 'org-special-keyword faces)
20250 (push (list :keyword
20251 (previous-single-property-change p 'face)
20252 (next-single-property-change p 'face)) clist))
20253 ((org-on-target-p)
20254 (push (org-point-in-group p 0 :target) clist)
20255 (goto-char (1- (match-beginning 0)))
20256 (if (looking-at org-radio-target-regexp)
20257 (push (org-point-in-group p 0 :radio-target) clist))
20258 (goto-char p))
20259 ((setq o (car (delq nil
20260 (mapcar
20261 (lambda (x)
20262 (if (memq x org-latex-fragment-image-overlays) x))
20263 (org-overlays-at (point))))))
20264 (push (list :latex-fragment
20265 (org-overlay-start o) (org-overlay-end o)) clist)
20266 (push (list :latex-preview
20267 (org-overlay-start o) (org-overlay-end o)) clist))
20268 ((org-inside-LaTeX-fragment-p)
20269 ;; FIXME: positions wrong.
20270 (push (list :latex-fragment (point) (point)) clist)))
20272 (setq clist (nreverse (delq nil clist)))
20273 clist))
20275 ;; FIXME Compare with at-regexp-p
20276 (defun org-in-regexp (re &optional nlines visually)
20277 "Check if point is inside a match of regexp.
20278 Normally only the current line is checked, but you can include NLINES extra
20279 lines both before and after point into the search.
20280 If VISUALLY is set, require that the cursor is not after the match but
20281 really on, so that the block visually is on the match."
20282 (catch 'exit
20283 (let ((pos (point))
20284 (eol (point-at-eol (+ 1 (or nlines 0))))
20285 (inc (if visually 1 0)))
20286 (save-excursion
20287 (beginning-of-line (- 1 (or nlines 0)))
20288 (while (re-search-forward re eol t)
20289 (if (and (<= (match-beginning 0) pos)
20290 (>= (+ inc (match-end 0)) pos))
20291 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20293 (defun org-at-regexp-p (regexp)
20294 "Is point inside a match of REGEXP in the current line?"
20295 (catch 'exit
20296 (save-excursion
20297 (let ((pos (point)) (end (point-at-eol)))
20298 (beginning-of-line 1)
20299 (while (re-search-forward regexp end t)
20300 (if (and (<= (match-beginning 0) pos)
20301 (>= (match-end 0) pos))
20302 (throw 'exit t)))
20303 nil))))
20305 (defun org-uniquify (list)
20306 "Remove duplicate elements from LIST."
20307 (let (res)
20308 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20309 res))
20311 (defun org-delete-all (elts list)
20312 "Remove all elements in ELTS from LIST."
20313 (while elts
20314 (setq list (delete (pop elts) list)))
20315 list)
20317 (defun org-point-in-group (point group &optional context)
20318 "Check if POINT is in match-group GROUP.
20319 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20320 match. If the match group does ot exist or point is not inside it,
20321 return nil."
20322 (and (match-beginning group)
20323 (>= point (match-beginning group))
20324 (<= point (match-end group))
20325 (if context
20326 (list context (match-beginning group) (match-end group))
20327 t)))
20329 (defun org-combine-plists (&rest plists)
20330 "Create a single property list from all plists in PLISTS.
20331 The process starts by copying the first list, and then setting properties
20332 from the other lists. Settings in the last list are the most significant
20333 ones and overrule settings in the other lists."
20334 (let ((rtn (copy-sequence (pop plists)))
20335 p v ls)
20336 (while plists
20337 (setq ls (pop plists))
20338 (while ls
20339 (setq p (pop ls) v (pop ls))
20340 (setq rtn (plist-put rtn p v))))
20341 rtn))
20343 (defun org-move-line-down (arg)
20344 "Move the current line down. With prefix argument, move it past ARG lines."
20345 (interactive "p")
20346 (let ((col (current-column))
20347 beg end pos)
20348 (beginning-of-line 1) (setq beg (point))
20349 (beginning-of-line 2) (setq end (point))
20350 (beginning-of-line (+ 1 arg))
20351 (setq pos (move-marker (make-marker) (point)))
20352 (insert (delete-and-extract-region beg end))
20353 (goto-char pos)
20354 (move-to-column col)))
20356 (defun org-move-line-up (arg)
20357 "Move the current line up. With prefix argument, move it past ARG lines."
20358 (interactive "p")
20359 (let ((col (current-column))
20360 beg end pos)
20361 (beginning-of-line 1) (setq beg (point))
20362 (beginning-of-line 2) (setq end (point))
20363 (beginning-of-line (- arg))
20364 (setq pos (move-marker (make-marker) (point)))
20365 (insert (delete-and-extract-region beg end))
20366 (goto-char pos)
20367 (move-to-column col)))
20369 (defun org-replace-escapes (string table)
20370 "Replace %-escapes in STRING with values in TABLE.
20371 TABLE is an association list with keys line \"%a\" and string values.
20372 The sequences in STRING may contain normal field width and padding information,
20373 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20374 so values can contain further %-escapes if they are define later in TABLE."
20375 (let ((case-fold-search nil)
20376 e re rpl)
20377 (while (setq e (pop table))
20378 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20379 (while (string-match re string)
20380 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20381 (cdr e)))
20382 (setq string (replace-match rpl t t string))))
20383 string))
20386 (defun org-sublist (list start end)
20387 "Return a section of LIST, from START to END.
20388 Counting starts at 1."
20389 (let (rtn (c start))
20390 (setq list (nthcdr (1- start) list))
20391 (while (and list (<= c end))
20392 (push (pop list) rtn)
20393 (setq c (1+ c)))
20394 (nreverse rtn)))
20396 (defun org-find-base-buffer-visiting (file)
20397 "Like `find-buffer-visiting' but alway return the base buffer and
20398 not an indirect buffer"
20399 (let ((buf (find-buffer-visiting file)))
20400 (or (buffer-base-buffer buf) buf)))
20402 (defun org-image-file-name-regexp ()
20403 "Return regexp matching the file names of images."
20404 (if (fboundp 'image-file-name-regexp)
20405 (image-file-name-regexp)
20406 (let ((image-file-name-extensions
20407 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20408 "xbm" "xpm" "pbm" "pgm" "ppm")))
20409 (concat "\\."
20410 (regexp-opt (nconc (mapcar 'upcase
20411 image-file-name-extensions)
20412 image-file-name-extensions)
20414 "\\'"))))
20416 (defun org-file-image-p (file)
20417 "Return non-nil if FILE is an image."
20418 (save-match-data
20419 (string-match (org-image-file-name-regexp) file)))
20421 ;;; Paragraph filling stuff.
20422 ;; We want this to be just right, so use the full arsenal.
20424 (defun org-indent-line-function ()
20425 "Indent line like previous, but further if previous was headline or item."
20426 (interactive)
20427 (let ((column (save-excursion
20428 (beginning-of-line)
20429 (if (looking-at "#") 0
20430 (skip-chars-backward "\n \t")
20431 (beginning-of-line)
20432 (if (or (looking-at "\\*+[ \t]+")
20433 (looking-at "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)"))
20434 (progn (goto-char (match-end 0)) (current-column))
20435 (current-indentation))))))
20436 (if (<= (current-column) (current-indentation))
20437 (indent-line-to column)
20438 (save-excursion (indent-line-to column)))))
20440 (defun org-set-autofill-regexps ()
20441 (interactive)
20442 ;; In the paragraph separator we include headlines, because filling
20443 ;; text in a line directly attached to a headline would otherwise
20444 ;; fill the headline as well.
20445 (org-set-local 'comment-start-skip "^#+[ \t]*")
20446 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
20447 ;; FIXME!!!!!!! (org-set-local 'paragraph-separate "\f\\|[ ]*$")
20448 ;; The paragraph starter includes hand-formatted lists.
20449 (org-set-local 'paragraph-start
20450 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
20451 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
20452 ;; But only if the user has not turned off tables or fixed-width regions
20453 (org-set-local
20454 'auto-fill-inhibit-regexp
20455 (concat "\\*\\|#\\+"
20456 "\\|[ \t]*" org-keyword-time-regexp
20457 (if (or org-enable-table-editor org-enable-fixed-width-editor)
20458 (concat
20459 "\\|[ \t]*["
20460 (if org-enable-table-editor "|" "")
20461 (if org-enable-fixed-width-editor ":" "")
20462 "]"))))
20463 ;; We use our own fill-paragraph function, to make sure that tables
20464 ;; and fixed-width regions are not wrapped. That function will pass
20465 ;; through to `fill-paragraph' when appropriate.
20466 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
20467 ; Adaptive filling: To get full control, first make sure that
20468 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
20469 (org-set-local 'adaptive-fill-regexp "\000")
20470 (org-set-local 'adaptive-fill-function
20471 'org-adaptive-fill-function))
20473 (defun org-fill-paragraph (&optional justify)
20474 "Re-align a table, pass through to fill-paragraph if no table."
20475 (let ((table-p (org-at-table-p))
20476 (table.el-p (org-at-table.el-p)))
20477 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
20478 (table.el-p t) ; skip table.el tables
20479 (table-p (org-table-align) t) ; align org-mode tables
20480 (t nil)))) ; call paragraph-fill
20482 ;; For reference, this is the default value of adaptive-fill-regexp
20483 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
20485 (defun org-adaptive-fill-function ()
20486 "Return a fill prefix for org-mode files.
20487 In particular, this makes sure hanging paragraphs for hand-formatted lists
20488 work correctly."
20489 (cond ((looking-at "#[ \t]+")
20490 (match-string 0))
20491 ((looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
20492 (make-string (- (match-end 0) (match-beginning 0)) ?\ ))
20493 (t nil)))
20495 ;;;; Functions extending outline functionality
20497 ;; C-a should go to the beginning of a *visible* line, also in the
20498 ;; new outline.el. I guess this should be patched into Emacs?
20499 (defun org-beginning-of-line ()
20500 "Go to the beginning of the current line. If that is invisible, continue
20501 to a visible line beginning. This makes the function of C-a more intuitive."
20502 (interactive)
20503 (let ((pos (point)))
20504 (beginning-of-line 1)
20505 (if (bobp)
20507 (backward-char 1)
20508 (if (org-invisible-p)
20509 (while (and (not (bobp)) (org-invisible-p))
20510 (backward-char 1)
20511 (beginning-of-line 1))
20512 (forward-char 1)))
20513 (when (and org-special-ctrl-a (looking-at org-todo-line-regexp)
20514 (= (char-after (match-end 1)) ?\ ))
20515 (goto-char
20516 (cond ((> pos (match-beginning 3)) (match-beginning 3))
20517 ((= pos (point)) (match-beginning 3))
20518 (t (point)))))))
20520 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
20522 (defun org-invisible-p ()
20523 "Check if point is at a character currently not visible."
20524 ;; Early versions of noutline don't have `outline-invisible-p'.
20525 (if (fboundp 'outline-invisible-p)
20526 (outline-invisible-p)
20527 (get-char-property (point) 'invisible)))
20529 (defun org-invisible-p2 ()
20530 "Check if point is at a character currently not visible."
20531 (save-excursion
20532 (if (and (eolp) (not (bobp))) (backward-char 1))
20533 ;; Early versions of noutline don't have `outline-invisible-p'.
20534 (if (fboundp 'outline-invisible-p)
20535 (outline-invisible-p)
20536 (get-char-property (point) 'invisible))))
20538 (defalias 'org-back-to-heading 'outline-back-to-heading)
20539 (defalias 'org-on-heading-p 'outline-on-heading-p)
20540 (defalias 'org-at-heading-p 'outline-on-heading-p)
20541 (defun org-at-heading-or-item-p ()
20542 (or (org-on-heading-p) (org-at-item-p)))
20544 (defun org-on-target-p ()
20545 (or (org-in-regexp org-radio-target-regexp)
20546 (org-in-regexp org-target-regexp)))
20548 (defun org-up-heading-all (arg)
20549 "Move to the heading line of which the present line is a subheading.
20550 This function considers both visible and invisible heading lines.
20551 With argument, move up ARG levels."
20552 (if (fboundp 'outline-up-heading-all)
20553 (outline-up-heading-all arg) ; emacs 21 version of outline.el
20554 (outline-up-heading arg t))) ; emacs 22 version of outline.el
20556 (defun org-goto-sibling (&optional previous)
20557 "Goto the next sibling, even if it is invisible.
20558 When PREVIOUS is set, go to the previous sibling instead. Returns t
20559 when a sibling was found. When none is found, return nil and don't
20560 move point."
20561 (let ((fun (if previous 're-search-backward 're-search-forward))
20562 (pos (point))
20563 (re (concat "^" outline-regexp))
20564 level l)
20565 (org-back-to-heading t)
20566 (setq level (funcall outline-level))
20567 (catch 'exit
20568 (or previous (forward-char 1))
20569 (while (funcall fun re nil t)
20570 (setq l (funcall outline-level))
20571 (when (< l level) (goto-char pos) (throw 'exit nil))
20572 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
20573 (goto-char pos)
20574 nil)))
20576 (defun org-show-siblings ()
20577 "Show all siblings of the current headline."
20578 (save-excursion
20579 (while (org-goto-sibling) (org-flag-heading nil)))
20580 (save-excursion
20581 (while (org-goto-sibling 'previous)
20582 (org-flag-heading nil))))
20584 (defun org-show-hidden-entry ()
20585 "Show an entry where even the heading is hidden."
20586 (save-excursion
20587 (org-show-entry)))
20589 (defun org-flag-heading (flag &optional entry)
20590 "Flag the current heading. FLAG non-nil means make invisible.
20591 When ENTRY is non-nil, show the entire entry."
20592 (save-excursion
20593 (org-back-to-heading t)
20594 ;; Check if we should show the entire entry
20595 (if entry
20596 (progn
20597 (org-show-entry)
20598 (save-excursion
20599 (and (outline-next-heading)
20600 (org-flag-heading nil))))
20601 (outline-flag-region (max 1 (1- (point)))
20602 (save-excursion (outline-end-of-heading) (point))
20603 flag))))
20605 (defun org-end-of-subtree (&optional invisible-OK to-heading)
20606 ;; This is an exact copy of the original function, but it uses
20607 ;; `org-back-to-heading', to make it work also in invisible
20608 ;; trees. And is uses an invisible-OK argument.
20609 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
20610 (org-back-to-heading invisible-OK)
20611 (let ((first t)
20612 (level (funcall outline-level)))
20613 (while (and (not (eobp))
20614 (or first (> (funcall outline-level) level)))
20615 (setq first nil)
20616 (outline-next-heading))
20617 (unless to-heading
20618 (if (memq (preceding-char) '(?\n ?\^M))
20619 (progn
20620 ;; Go to end of line before heading
20621 (forward-char -1)
20622 (if (memq (preceding-char) '(?\n ?\^M))
20623 ;; leave blank line before heading
20624 (forward-char -1))))))
20625 (point))
20627 (defun org-show-subtree ()
20628 "Show everything after this heading at deeper levels."
20629 (outline-flag-region
20630 (point)
20631 (save-excursion
20632 (outline-end-of-subtree) (outline-next-heading) (point))
20633 nil))
20635 (defun org-show-entry ()
20636 "Show the body directly following this heading.
20637 Show the heading too, if it is currently invisible."
20638 (interactive)
20639 (save-excursion
20640 (org-back-to-heading t)
20641 (outline-flag-region
20642 (max 1 (1- (point)))
20643 (save-excursion
20644 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
20645 (or (match-beginning 1) (point-max)))
20646 nil)))
20648 (defun org-make-options-regexp (kwds)
20649 "Make a regular expression for keyword lines."
20650 (concat
20652 "#?[ \t]*\\+\\("
20653 (mapconcat 'regexp-quote kwds "\\|")
20654 "\\):[ \t]*"
20655 "\\(.+\\)"))
20657 ;; Make isearch reveal the necessary context
20658 (defun org-isearch-end ()
20659 "Reveal context after isearch exits."
20660 (when isearch-success ; only if search was successful
20661 (if (featurep 'xemacs)
20662 ;; Under XEmacs, the hook is run in the correct place,
20663 ;; we directly show the context.
20664 (org-show-context 'isearch)
20665 ;; In Emacs the hook runs *before* restoring the overlays.
20666 ;; So we have to use a one-time post-command-hook to do this.
20667 ;; (Emacs 22 has a special variable, see function `org-mode')
20668 (unless (and (boundp 'isearch-mode-end-hook-quit)
20669 isearch-mode-end-hook-quit)
20670 ;; Only when the isearch was not quitted.
20671 (org-add-hook 'post-command-hook 'org-isearch-post-command
20672 'append 'local)))))
20674 (defun org-isearch-post-command ()
20675 "Remove self from hook, and show context."
20676 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
20677 (org-show-context 'isearch))
20680 ;;;; Address problems with some other packages
20682 ;; Make flyspell not check words in links, to not mess up our keymap
20683 (defun org-mode-flyspell-verify ()
20684 "Don't let flyspell put overlays at active buttons."
20685 (not (get-text-property (point) 'keymap)))
20687 ;; Make `bookmark-jump' show the jump location if it was hidden.
20688 (eval-after-load "bookmark"
20689 '(if (boundp 'bookmark-after-jump-hook)
20690 ;; We can use the hook
20691 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
20692 ;; Hook not available, use advice
20693 (defadvice bookmark-jump (after org-make-visible activate)
20694 "Make the position visible."
20695 (org-bookmark-jump-unhide))))
20697 (defun org-bookmark-jump-unhide ()
20698 "Unhide the current position, to show the bookmark location."
20699 (and (org-mode-p)
20700 (or (org-invisible-p)
20701 (save-excursion (goto-char (max (point-min) (1- (point))))
20702 (org-invisible-p)))
20703 (org-show-context 'bookmark-jump)))
20705 ;; Make session.el ignore our circular variable
20706 (eval-after-load "session"
20707 '(add-to-list 'session-globals-exclude 'org-mark-ring))
20709 ;;;; Experimental code
20712 ;;;; Finish up
20714 (provide 'org)
20716 (run-hooks 'org-load-hook)
20718 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
20719 ;;; org.el ends here